# HG changeset patch # User goeckslab # Date 1662657813 0 # Node ID 9f60ef2d586e89483545eee9b0f5b424ab6acf88 planemo upload for repository https://github.com/goeckslab/tools-mti/tree/main/tools/vitessce commit 9b2dc921e692af8045773013d9f87d4d790e2ea1 diff -r 000000000000 -r 9f60ef2d586e gate_finder.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/gate_finder.py Thu Sep 08 17:23:33 2022 +0000 @@ -0,0 +1,156 @@ +import argparse +import json +import warnings +from pathlib import Path + +import numpy as np +import pandas as pd +from anndata import read_h5ad +from sklearn.mixture import GaussianMixture +from sklearn.preprocessing import MinMaxScaler +from vitessce import ( + AnnDataWrapper, + Component as cm, + MultiImageWrapper, + OmeTiffWrapper, + VitessceConfig, +) + + +# Generate binarized phenotype for a gate +def get_gate_phenotype(g, d): + dd = d.copy() + dd = np.where(dd < g, 0, dd) + np.warnings.filterwarnings('ignore') + dd = np.where(dd >= g, 1, dd) + return dd + + +def get_gmm_phenotype(data): + low = np.percentile(data, 0.01) + high = np.percentile(data, 99.99) + data = np.clip(data, low, high) + + sum = np.sum(data) + median = np.median(data) + data_med = data / sum * median + + data_log = np.log1p(data_med) + data_log = data_log.reshape(-1, 1) + + scaler = MinMaxScaler(feature_range=(0, 1)) + data_norm = scaler.fit_transform(data_log) + + gmm = GaussianMixture(n_components=2) + gmm.fit(data_norm) + gate = np.mean(gmm.means_) + + return get_gate_phenotype(gate, np.ravel(data_norm)) + + +def main(inputs, output, image, anndata, masks=None): + """ + Parameter + --------- + inputs : str + File path to galaxy tool parameter. + output : str + Output folder for saving web content. + image : str + File path to the OME Tiff image. + anndata : str + File path to anndata containing phenotyping info. + masks : str + File path to the image masks. + """ + warnings.simplefilter('ignore') + + with open(inputs, 'r') as param_handler: + params = json.load(param_handler) + + marker = params['marker'].strip() + from_gate = params['from_gate'] + to_gate = params['to_gate'] + increment = params['increment'] + x_coordinate = params['x_coordinate'].strip() or 'X_centroid' + y_coordinate = params['y_coordinate'].strip() or 'Y_centroid' + + adata = read_h5ad(anndata) + + # If no raw data is available make a copy + if adata.raw is None: + adata.raw = adata + + # Copy of the raw data if it exisits + if adata.raw is not None: + adata.X = adata.raw.X + + data = pd.DataFrame( + adata.X, + columns=adata.var.index, + index=adata.obs.index + ) + marker_values = data[[marker]].values + marker_values_log = np.log1p(marker_values) + + # Identify the list of increments + gate_names = [] + for num in np.arange(from_gate, to_gate, increment): + num = round(num, 3) + key = marker + '--' + str(num) + adata.obs[key] = get_gate_phenotype(num, marker_values_log) + gate_names.append(key) + + adata.obs['GMM_auto'] = get_gmm_phenotype(marker_values) + gate_names.append('GMM_auto') + + adata.obsm['XY_coordinate'] = adata.obs[[x_coordinate, y_coordinate]].values + + vc = VitessceConfig(name=None, description=None) + dataset = vc.add_dataset() + image_wrappers = [OmeTiffWrapper(img_path=image, name='OMETIFF')] + if masks: + image_wrappers.append( + OmeTiffWrapper(img_path=masks, name='MASKS', is_bitmask=True) + ) + dataset.add_object(MultiImageWrapper(image_wrappers)) + + dataset.add_object( + AnnDataWrapper( + adata, + spatial_centroid_obsm='XY_coordinate', + cell_set_obs=gate_names, + cell_set_obs_names=[obj[0].upper() + obj[1:] for obj in gate_names], + expression_matrix="X" + ) + ) + spatial = vc.add_view(dataset, cm.SPATIAL) + cellsets = vc.add_view(dataset, cm.CELL_SETS) + status = vc.add_view(dataset, cm.STATUS) + lc = vc.add_view(dataset, cm.LAYER_CONTROLLER) + genes = vc.add_view(dataset, cm.GENES) + cell_set_sizes = vc.add_view(dataset, cm.CELL_SET_SIZES) + cell_set_expression = vc.add_view(dataset, cm.CELL_SET_EXPRESSION) + + vc.layout( + (status / genes / cell_set_expression) + | (cellsets / cell_set_sizes / lc) + | (spatial) + ) + config_dict = vc.export(to='files', base_url='http://localhost', out_dir=output) + + with open(Path(output).joinpath('config.json'), 'w') as f: + json.dump(config_dict, f, indent=4) + + +if __name__ == '__main__': + aparser = argparse.ArgumentParser() + aparser.add_argument("-i", "--inputs", dest="inputs", required=True) + aparser.add_argument("-e", "--output", dest="output", required=True) + aparser.add_argument("-g", "--image", dest="image", required=True) + aparser.add_argument("-a", "--anndata", dest="anndata", required=True) + aparser.add_argument("-m", "--masks", dest="masks", required=False) + + args = aparser.parse_args() + + main(args.inputs, args.output, args.image, args.anndata, args.masks) diff -r 000000000000 -r 9f60ef2d586e index.html --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/index.html Thu Sep 08 17:23:33 2022 +0000 @@ -0,0 +1,39 @@ + + + + + + Vitessce + + + + +
+
+
+
+

Vitessce is loading...

+
+
+
+
+
+
+
+
+ + + + + + \ No newline at end of file diff -r 000000000000 -r 9f60ef2d586e main_macros.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main_macros.xml Thu Sep 08 17:23:33 2022 +0000 @@ -0,0 +1,84 @@ + + 1.0.4 + 0 + 20.01 + + + + quay.io/goeckslab/vitessce:@TOOL_VERSION@ + + + + + + + + + + + + showinf -nopix -nometa -noflat \$image' && + echo "\$info\n" && + masks_info=\$(showinf -nopix -nometa -noflat '$masks') && + echo '>showinf -nopix -nometa -noflat \$masks' && + echo "\$masks_info\n" && + masks_n_resolutions=\$(echo "\$masks_info" | grep '^\s*Resolutions\s*=' -m1 | cut -d'=' -f2 | xargs) && + if [ -z \$masks_n_resolutions ]; then + n_resolutions=\$(echo "\$info" | grep '^\s*Resolutions\s*=' -m1 | cut -d'=' -f2 | xargs) && + pyramid_scale=1 && + if [ -z "\$n_resolutions" ]; then + echo "Warning: Failded to retrieve the number of pyramid resolutions. Set pyramid resolutions to 4 and scale to 2!"; + n_resolutions=4; + pyramid_scale=2; + else + echo "Found the number of pyramid resolutions: \$n_resolutions"; + if [ "\$n_resolutions" -gt 1 ]; then + sizeX0=\$(echo "\$info" | grep '^\s*sizeX\[0\]\s*=' -m1 | cut -d'=' -f2 | xargs) ; + sizeX1=\$(echo "\$info" | grep '^\s*sizeX\[1\]\s*=' -m1 | cut -d'=' -f2 | xargs) ; + if [ "\$sizeX0" -gt 0 ] && [ "\$sizeX1" -gt 0 ]; then + pyramid_scale=\$(((\$sizeX0 + \$sizeX1 / 2 ) / \$sizeX1)); + echo "Calculate pyramid scale: \$sizeX0 / \$sizeX1 ~= \$pyramid_scale."; + else + pyramid_scale=2; + echo "Warning: Failed to calculate the pyramid scale; set it to 2!"; + fi; + fi; + fi; + tile_info=\$(showinf -nopix -nometa -noflat '${output.files_path}/A/0/image01.ome.tiff' | grep '^\s*Tile\ssize\s*=' -m1); + tile_x=\$(echo "\$tile_info" | cut -d' ' -f4); + tile_y=\$(echo "\$tile_info" | cut -d' ' -f6); + convert_cmd="bfconvert -pyramid-resolutions \$n_resolutions -pyramid-scale \$pyramid_scale -noflat -tilex \$tile_x -tiley \$tile_y '$masks' '${output.files_path}/A/0/masks01.ome.tiff'"; + echo "\n>\$convert_cmd"; + eval \$convert_cmd; + masks_info_new=\$(showinf -nopix -nometa -noflat '${output.files_path}/A/0/masks01.ome.tiff'); + echo "\n>showinf -nopix -nometa -noflat '${output.files_path}/A/0/masks01.ome.tiff'"; + echo "\$masks_info_new\n"; + else + ln -sf '$masks' '${output.files_path}/A/0/masks01.ome.tiff'; + fi && + #end if + python '$__tool_directory__/@TOOL_ID@.py' + --inputs '$inputs' + --output '${output.files_path}' + --image '${output.files_path}/A/0/image01.ome.tiff' + #if $masks + --masks '${output.files_path}/A/0/masks01.ome.tiff' + #end if + #if $do_phenotyping.phenotyping_choice + --anndata '$anndata' + #end if + && + cp -R '$__tool_directory__/static' '${output.files_path}' && + cp '$__tool_directory__/index.html' '$output'; + + ]]> + + + + diff -r 000000000000 -r 9f60ef2d586e static/css/2.f290e260.chunk.css --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/static/css/2.f290e260.chunk.css Thu Sep 08 17:23:33 2022 +0000 @@ -0,0 +1,2 @@ +.react-grid-layout{position:relative;transition:height .2s ease}.react-grid-item{transition:all .2s ease;transition-property:left,top}.react-grid-item.cssTransforms{transition-property:transform}.react-grid-item.resizing{z-index:1;will-change:width,height}.react-grid-item.react-draggable-dragging{transition:none;z-index:3;will-change:transform}.react-grid-item.dropping{visibility:hidden}.react-grid-item.react-grid-placeholder{background:red;opacity:.2;transition-duration:.1s;z-index:2;-webkit-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.react-grid-item>.react-resizable-handle{position:absolute;width:20px;height:20px;bottom:0;right:0;cursor:se-resize}.react-grid-item>.react-resizable-handle:after{content:"";position:absolute;right:3px;bottom:3px;width:5px;height:5px;border-right:2px solid rgba(0,0,0,.4);border-bottom:2px solid rgba(0,0,0,.4)}.react-resizable-hide>.react-resizable-handle{display:none}.react-resizable{position:relative}.react-resizable-handle{position:absolute;width:20px;height:20px;background-repeat:no-repeat;background-origin:content-box;box-sizing:border-box;background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHN0eWxlPSJiYWNrZ3JvdW5kLWNvbG9yOiNmZmZmZmYwMCIgd2lkdGg9IjYiIGhlaWdodD0iNiI+PHBhdGggZD0iTTYgNkgwVjQuMmg0LjJWMEg2djZ6IiBvcGFjaXR5PSIuMzAyIi8+PC9zdmc+");background-position:100% 100%;padding:0 3px 3px 0}.react-resizable-handle-sw{bottom:0;left:0;cursor:sw-resize;transform:rotate(90deg)}.react-resizable-handle-se{bottom:0;right:0;cursor:se-resize}.react-resizable-handle-nw{top:0;left:0;cursor:nw-resize;transform:rotate(180deg)}.react-resizable-handle-ne{top:0;right:0;cursor:ne-resize;transform:rotate(270deg)}.react-resizable-handle-e,.react-resizable-handle-w{top:50%;margin-top:-10px;cursor:ew-resize}.react-resizable-handle-w{left:0;transform:rotate(135deg)}.react-resizable-handle-e{right:0;transform:rotate(315deg)}.react-resizable-handle-n,.react-resizable-handle-s{left:50%;margin-left:-10px;cursor:ns-resize}.react-resizable-handle-n{top:0;transform:rotate(225deg)}.react-resizable-handle-s{bottom:0;transform:rotate(45deg)} +/*# sourceMappingURL=2.f290e260.chunk.css.map */ \ No newline at end of file diff -r 000000000000 -r 9f60ef2d586e static/css/2.f290e260.chunk.css.map --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/static/css/2.f290e260.chunk.css.map Thu Sep 08 17:23:33 2022 +0000 @@ -0,0 +1,1 @@ +{"version":3,"sources":["styles.css"],"names":[],"mappings":"AAAA,mBACE,iBAAkB,CAClB,0BACF,CACA,iBACE,uBAA0B,CAC1B,4BACF,CACA,+BACE,6BACF,CACA,0BACE,SAAU,CACV,wBACF,CAEA,0CACE,eAAgB,CAChB,SAAU,CACV,qBACF,CAEA,0BACE,iBACF,CAEA,wCACE,cAAe,CACf,UAAY,CACZ,uBAA0B,CAC1B,SAAU,CACV,wBAAyB,CAEzB,oBAAqB,CACrB,mBAAoB,CACpB,gBACF,CAEA,yCACE,iBAAkB,CAClB,UAAW,CACX,WAAY,CACZ,QAAS,CACT,OAAQ,CACR,gBACF,CAEA,+CACE,UAAW,CACX,iBAAkB,CAClB,SAAU,CACV,UAAW,CACX,SAAU,CACV,UAAW,CACX,qCAA0C,CAC1C,sCACF,CAEA,8CACE,YACF,CA5DA,iBACE,iBACF,CACA,wBACE,iBAAkB,CAClB,UAAW,CACX,WAAY,CACZ,2BAA4B,CAC5B,6BAA8B,CAC9B,qBAAsB,CACtB,0PAAuY,CACvY,6BAAiC,CACjC,mBACF,CACA,2BACE,QAAS,CACT,MAAO,CACP,gBAAiB,CACjB,uBACF,CACA,2BACE,QAAS,CACT,OAAQ,CACR,gBACF,CACA,2BACE,KAAM,CACN,MAAO,CACP,gBAAiB,CACjB,wBACF,CACA,2BACE,KAAM,CACN,OAAQ,CACR,gBAAiB,CACjB,wBACF,CACA,oDAEE,OAAQ,CACR,gBAAiB,CACjB,gBACF,CACA,0BACE,MAAO,CACP,wBACF,CACA,0BACE,OAAQ,CACR,wBACF,CACA,oDAEE,QAAS,CACT,iBAAkB,CAClB,gBACF,CACA,0BACE,KAAM,CACN,wBACF,CACA,0BACE,QAAS,CACT,uBACF","file":"2.f290e260.chunk.css","sourcesContent":[".react-resizable {\n position: relative;\n}\n.react-resizable-handle {\n position: absolute;\n width: 20px;\n height: 20px;\n background-repeat: no-repeat;\n background-origin: content-box;\n box-sizing: border-box;\n background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2IDYiIHN0eWxlPSJiYWNrZ3JvdW5kLWNvbG9yOiNmZmZmZmYwMCIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSI2cHgiIGhlaWdodD0iNnB4Ij48ZyBvcGFjaXR5PSIwLjMwMiI+PHBhdGggZD0iTSA2IDYgTCAwIDYgTCAwIDQuMiBMIDQgNC4yIEwgNC4yIDQuMiBMIDQuMiAwIEwgNiAwIEwgNiA2IEwgNiA2IFoiIGZpbGw9IiMwMDAwMDAiLz48L2c+PC9zdmc+');\n background-position: bottom right;\n padding: 0 3px 3px 0;\n}\n.react-resizable-handle-sw {\n bottom: 0;\n left: 0;\n cursor: sw-resize;\n transform: rotate(90deg);\n}\n.react-resizable-handle-se {\n bottom: 0;\n right: 0;\n cursor: se-resize;\n}\n.react-resizable-handle-nw {\n top: 0;\n left: 0;\n cursor: nw-resize;\n transform: rotate(180deg);\n}\n.react-resizable-handle-ne {\n top: 0;\n right: 0;\n cursor: ne-resize;\n transform: rotate(270deg);\n}\n.react-resizable-handle-w,\n.react-resizable-handle-e {\n top: 50%;\n margin-top: -10px;\n cursor: ew-resize;\n}\n.react-resizable-handle-w {\n left: 0;\n transform: rotate(135deg);\n}\n.react-resizable-handle-e {\n right: 0;\n transform: rotate(315deg);\n}\n.react-resizable-handle-n,\n.react-resizable-handle-s {\n left: 50%;\n margin-left: -10px;\n cursor: ns-resize;\n}\n.react-resizable-handle-n {\n top: 0;\n transform: rotate(225deg);\n}\n.react-resizable-handle-s {\n bottom: 0;\n transform: rotate(45deg);\n}"]} \ No newline at end of file diff -r 000000000000 -r 9f60ef2d586e static/css/main.a53cc462.chunk.css --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/static/css/main.a53cc462.chunk.css Thu Sep 08 17:23:33 2022 +0000 @@ -0,0 +1,2 @@ +.react-draggable-transparent-selection .react-grid-item{-webkit-user-select:none!important;-moz-user-select:none!important;-o-user-select:none!important;-ms-user-select:none!important;user-select:none!important}body{margin:0;text-align:left}.container-fluid{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto;box-sizing:border-box}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-2OwvL{position:fixed;background-color:hsla(0,0%,100%,.95);border:1px solid rgba(0,0,0,.1);border-radius:3px;font-size:12px;cursor:default;padding:3px;box-shadow:0 0 3px 0 rgba(0,0,0,.1),0 1px 5px 0 rgba(0,0,0,.05)}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-dark-2PO31{color:#ccc;background-color:rgba(68,68,68,.97)}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-icon-I4kiw{display:inline-block;margin-right:3px;vertical-align:middle}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-icon-I4kiw>svg{width:30px;height:20px}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-item-1HeVv{padding:2px;white-space:nowrap;border-radius:2px;transition:background .15s ease,color .15s ease}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-item-1HeVv:hover{background:#337ab7;color:#fff}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-hr-3yapb{margin-top:5px;margin-bottom:5px;border:0;border-top:1px solid rgba(0,0,0,.1)}.vitessce-container .higlass-wrapper .ContextMenu-module_play-icon-R4pIO{width:12px;height:12px;position:absolute;right:5px}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-span-8EUfZ{margin-right:20px;vertical-align:middle;display:inline-block;line-height:normal;white-space:nowrap}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-thumbnail-2vHLD{margin-right:10px;border:1px solid #888}.vitessce-container .higlass-wrapper .ContextMenu-module_context-menu-thumbnail-inline-1iOcg{display:inline-block;margin-right:10px;vertical-align:middle}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-2zDf3,.vitessce-container .higlass-wrapper .TrackControl-module_track-control-vertical-2McB_{position:absolute;z-index:1;display:flex;background:hsla(0,0%,100%,.75);right:2px;top:2px;border-radius:2.5px;box-shadow:0 0 0 1px rgba(0,0,0,.05),0 0 3px 0 rgba(0,0,0,.1);opacity:0;transition:opacity .15s ease,background .15s ease,box-shadow .15s ease}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-dark-fP2uZ,.vitessce-container .higlass-wrapper .TrackControl-module_track-control-dark-fP2uZ .TrackControl-module_track-control-active-2JD9i{background:rgba(40,40,40,.85)}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-vertical-2McB_{flex-direction:column-reverse}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-left-zHd9W{left:2px;right:auto}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-active-2JD9i,.vitessce-container .higlass-wrapper .TrackControl-module_track-control-vertical-active-1QCKn{opacity:1;z-index:1}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-active-2JD9i:hover,.vitessce-container .higlass-wrapper .TrackControl-module_track-control-vertical-active-1QCKn:hover{background:#fff;box-shadow:0 0 0 1px rgba(0,0,0,.1),0 0 3px 0 rgba(0,0,0,.2)}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-dark-fP2uZ.TrackControl-module_track-control-active-2JD9i:hover{background:rgba(34,34,34,.95)}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-padding-right-2p6Lp{right:80px}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-button-2fdIb{width:20px;height:20px;padding:4px;cursor:pointer;opacity:.66;transition:background .15s ease,color .15s ease,opacity .15s ease}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-button-2fdIb:hover{color:#fff;background:#337ab7;opacity:1}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-button-2fdIb:first-child{border-radius:2.5px 0 0 2.5px}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-button-2fdIb:last-child{border-radius:0 2.5px 2.5px 0}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-dark-fP2uZ .TrackControl-module_track-control-button-2fdIb{color:#ccc}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-dark-fP2uZ .TrackControl-module_track-control-button-2fdIb:hover{color:#fff;background:#337ab7;opacity:1}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-button-vertical-1s22z:first-child{border-radius:0 0 2.5px 2.5px}.vitessce-container .higlass-wrapper .TrackControl-module_track-control-button-vertical-1s22z:last-child{border-radius:2.5px 2.5px 0 0}.vitessce-container .higlass-wrapper .CenterTrack-module_center-track-3ptRW{position:relative;background:transparent}.vitessce-container .higlass-wrapper .CenterTrack-module_center-track-container-2ELhp{position:absolute;z-index:1}.vitessce-container .higlass-wrapper .Track-module_track-range-selection-1yrDf{position:absolute;z-index:-1;opacity:0;transition:opacity .15s ease}.vitessce-container .higlass-wrapper .Track-module_track-range-selection-active-1oljJ{z-index:1;opacity:1}.vitessce-container .higlass-wrapper .Track-module_track-range-selection-group-inactive-YNRM4{display:none}.vitessce-container .higlass-wrapper .Track-module_track-range-selection-group-brush-selection-2VYDl{outline:2px solid rgba(0,0,0,.33);fill:#000;fill-opacity:.1}.vitessce-container .higlass-wrapper .DragListeningDiv-module_drag-listening-div-active-3wpRk{z-index:10;box-shadow:inset 0 0 3px 0 red}.vitessce-container .higlass-wrapper .GalleryTracks-module_gallery-tracks-3tsUO{position:relative;top:0;left:0;width:100%;height:100%}.vitessce-container .higlass-wrapper .GalleryTracks-module_gallery-track-eGKoq{position:absolute;box-sizing:border-box;top:0;right:0;bottom:0;left:0}.vitessce-container .higlass-wrapper .GalleryTracks-module_gallery-invisible-track-1hMJp,.vitessce-container .higlass-wrapper .GalleryTracks-module_gallery-sub-track-z1HEh{position:absolute}.vitessce-container .higlass-wrapper .TiledPlot-module_tiled-plot-uFHiB{position:relative;flex:1 1;overflow:hidden}.vitessce-container .higlass-wrapper .TiledPlot-module_horizontalList-1c1P8{display:flex;width:600px;height:300px;white-space:nowrap}.vitessce-container .higlass-wrapper .TiledPlot-module_list-24zgV{width:400px;height:600px;overflow:hidden;-webkit-overflow-scrolling:touch}.vitessce-container .higlass-wrapper .TiledPlot-module_stylizedList-Mt4JL{position:relative;z-index:0;background-color:#f3f3f3;outline:none}.vitessce-container .higlass-wrapper .TiledPlot-module_stylizedItem-2bQBK{position:relative;display:flex;align-items:center;width:100%;background-color:transparent;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;color:#333;font-weight:400}.vitessce-container .higlass-wrapper .TiledPlot-module_stylizedHelper-3IVEu{box-shadow:0 5px 5px -5px rgba(0,0,0,.2),0 -5px 5px -5px rgba(0,0,0,.2);background-color:hsla(0,0%,100%,.8);cursor:row-resize}.vitessce-container .higlass-wrapper .TiledPlot-module_stylizedHelper-3IVEu.TiledPlot-module_horizontalItem-2-ZjU{cursor:col-resize}.vitessce-container .higlass-wrapper .TiledPlot-module_horizontalItem-2-ZjU{display:flex;flex-shrink:0;align-items:center;justify-content:center}.vitessce-container .higlass-wrapper .TiledPlot-module_resizable-track-2oLT9{width:100%;height:100%}.vitessce-container .higlass-wrapper path.TiledPlot-module_domain-qYw6K{stroke-width:0px}.vitessce-container .higlass-wrapper .TrackRenderer-module_track-renderer-3TM7n{position:relative}.vitessce-container .higlass-wrapper .TrackRenderer-module_track-renderer-element-2i16D,.vitessce-container .higlass-wrapper .TrackRenderer-module_track-renderer-events-3tVM2{position:absolute;top:0;right:0;bottom:0;left:0;z-index:-1}.vitessce-container .higlass-wrapper .TrackRenderer-module_track-renderer-events-3tVM2{z-index:1}.vitessce-container .higlass-wrapper .Button-module_button-3YXsQ{display:flex;align-items:center;box-sizing:border-box;padding:.5em;color:#000;font-size:1em;line-height:1em;border:0;border-radius:2.5px;background:#fff;box-shadow:0 0 0 1px #ccc;transition:transform .15s ease,box-shadow .15s ease,background .15s ease;-webkit-appearance:none}.vitessce-container .higlass-wrapper .Button-module_button-3YXsQ:hover{background:#f2f2f2;box-shadow:0 0 0 1px #ccc}.vitessce-container .higlass-wrapper .Button-module_button-3YXsQ:focus{box-shadow:0 0 0 2px #0089ff}.vitessce-container .higlass-wrapper .Button-module_button-3YXsQ:active{transform:scale(.9)}.vitessce-container .higlass-wrapper .Button-module_button-3YXsQ:active,.vitessce-container .higlass-wrapper .Button-module_button-3YXsQ:focus,.vitessce-container .higlass-wrapper .Button-module_button-3YXsQ:hover{cursor:pointer;outline:none}.vitessce-container .higlass-wrapper .Button-module_button-shortcut-1zMAn{padding:.1em 5px;color:#999;font-size:.8em;transition:color .15s ease}.vitessce-container .higlass-wrapper .Cross-module_cross-3WYME{position:relative;width:1em;height:1em}.vitessce-container .higlass-wrapper .Cross-module_cross-3WYME:after,.vitessce-container .higlass-wrapper .Cross-module_cross-3WYME:before{content:"";display:block;position:absolute;top:50%;left:0;width:1em;height:1px;background:#000;transform-origin:center}.vitessce-container .higlass-wrapper .Cross-module_cross-3WYME:before{transform:translateY(-50%) rotate(45deg)}.vitessce-container .higlass-wrapper .Cross-module_cross-3WYME:after{transform:translateY(-50%) rotate(-45deg)}.vitessce-container .higlass-wrapper .Modal-module_modal-background-3vDy1{position:absolute;z-index:1000;top:0;right:0;bottom:0;left:0;background:rgba(0,0,0,.666);-webkit-animation:Modal-module_fade-in-3Nm-O .2s ease 1;animation:Modal-module_fade-in-3Nm-O .2s ease 1;transition:opacity .2s ease}.vitessce-container .higlass-wrapper .Modal-module_modal-hide-3huBg{opacity:0}.vitessce-container .higlass-wrapper .Modal-module_modal-wrap-1HWNn{position:absolute;top:20px;right:20px;bottom:20px;left:20px}.vitessce-container .higlass-wrapper .Modal-module_modal-window-1XZAq{position:relative;width:100%;max-width:640px;max-height:100%;margin-left:auto;margin-right:auto;color:#000;border-radius:5px;background:#fff;-webkit-animation:Modal-module_fade-scale-in-11Dkx .2s ease 1;animation:Modal-module_fade-scale-in-11Dkx .2s ease 1}.vitessce-container .higlass-wrapper .Modal-module_modal-window-max-height-CZYCl{height:100%}.vitessce-container .higlass-wrapper .Modal-module_modal-content-2xb_x{padding:10px}@-webkit-keyframes Modal-module_fade-in-3Nm-O{0%{opacity:0}to{opacity:1}}@keyframes Modal-module_fade-in-3Nm-O{0%{opacity:0}to{opacity:1}}@-webkit-keyframes Modal-module_fade-scale-in-11Dkx{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes Modal-module_fade-scale-in-11Dkx{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}.vitessce-container .higlass-wrapper .Dialog-module_dialog-header-2mk2M{position:relative;z-index:2;display:flex;justify-content:space-between;margin:0 -10px 10px;padding:0 10px 10px;border-bottom:1px solid #ccc}.vitessce-container .higlass-wrapper .Dialog-module_dialog-header-2mk2M h3{margin:0;padding:0;font-size:20px;line-height:1em}.vitessce-container .higlass-wrapper .Dialog-module_dialog-header-2mk2M button{font-size:10px}.vitessce-container .higlass-wrapper .Dialog-module_dialog-main-max-height-1EAb2{position:absolute;z-index:1;top:40px;right:0;bottom:50px;left:0;padding:10px;overflow:auto}.vitessce-container .higlass-wrapper .Dialog-module_dialog-footer-1BnEv,.vitessce-container .higlass-wrapper .Dialog-module_dialog-footer-max-height-KjDek{display:flex;justify-content:space-between;margin:10px -10px 0;padding:10px 10px 0;border-top:1px solid #ccc}.vitessce-container .higlass-wrapper .Dialog-module_dialog-footer-1BnEv button,.vitessce-container .higlass-wrapper .Dialog-module_dialog-footer-max-height-KjDek button{font-size:14px}.vitessce-container .higlass-wrapper .Dialog-module_dialog-footer-max-height-KjDek{position:absolute;z-index:2;left:10px;right:10px;bottom:10px}.vitessce-container .higlass-wrapper .tileset-finder-label{font-weight:700}.vitessce-container .higlass-wrapper .tileset-finder-search-box{margin-left:10px}.vitessce-container .higlass-wrapper .tileset-finder-search-bar{display:flex;margin-left:5px;justify-content:space-between;align-items:center}.vitessce-container .higlass-wrapper .tileset-finder-checkbox-tree{margin:5px;padding:3px;border:1px solid #aaa;border-radius:5px}.vitessce-container .higlass-wrapper .react-checkbox-tree{display:flex;flex-direction:row;font-size:14px}.vitessce-container .higlass-wrapper .react-checkbox-tree>ol{flex:1 1 auto}.vitessce-container .higlass-wrapper .react-checkbox-tree ol{margin:0;padding-left:0;list-style-type:none}.vitessce-container .higlass-wrapper .react-checkbox-tree ol ol{padding-left:24px}.vitessce-container .higlass-wrapper .react-checkbox-tree button{line-height:normal;color:inherit}.vitessce-container .higlass-wrapper .react-checkbox-tree button:focus{outline:none}.vitessce-container .higlass-wrapper .react-checkbox-tree button:disabled{cursor:not-allowed}.vitessce-container .higlass-wrapper .react-checkbox-tree .rct-bare-label{cursor:default}.vitessce-container .higlass-wrapper .react-checkbox-tree label{margin-bottom:0;cursor:pointer;font-weight:400}.vitessce-container .higlass-wrapper .react-checkbox-tree label:hover{background:rgba(51,51,204,.1)}.vitessce-container .higlass-wrapper .react-checkbox-tree label:active{background:rgba(51,51,204,.15)}.vitessce-container .higlass-wrapper .react-checkbox-tree:not(.rct-native-display) input{display:none}.vitessce-container .higlass-wrapper .react-checkbox-tree.rct-native-display input{margin:0 5px}.vitessce-container .higlass-wrapper .react-checkbox-tree .rct-icon{font-family:FontAwesome;font-style:normal}.vitessce-container .higlass-wrapper .rct-disabled>.rct-text>label{opacity:.75;cursor:not-allowed}.vitessce-container .higlass-wrapper .rct-disabled>.rct-text>label:active,.vitessce-container .higlass-wrapper .rct-disabled>.rct-text>label:hover{background:transparent}.vitessce-container .higlass-wrapper .rct-text{display:flex;align-items:center}.vitessce-container .higlass-wrapper .rct-options{flex:0 0 auto;margin-left:.5rem;text-align:right}.vitessce-container .higlass-wrapper .rct-option{opacity:.75;border:0;background:none;cursor:pointer;padding:0 4px;font-size:18px}.vitessce-container .higlass-wrapper .rct-option:hover{opacity:1}.vitessce-container .higlass-wrapper .rct-option+.rct-option{margin-left:2px}.vitessce-container .higlass-wrapper .rct-checkbox,.vitessce-container .higlass-wrapper .rct-collapse,.vitessce-container .higlass-wrapper .rct-node-icon{padding:0 5px}.vitessce-container .higlass-wrapper .rct-checkbox *,.vitessce-container .higlass-wrapper .rct-collapse *,.vitessce-container .higlass-wrapper .rct-node-icon *{display:inline-block;margin:0;width:14px}.vitessce-container .higlass-wrapper .rct-collapse{border:0;background:none;line-height:normal;color:inherit;font-size:12px}.vitessce-container .higlass-wrapper .rct-collapse.rct-collapse-btn{cursor:pointer}.vitessce-container .higlass-wrapper .rct-collapse>.rct-icon-expand-close{opacity:.5}.vitessce-container .higlass-wrapper .rct-collapse>.rct-icon-expand-close:hover{opacity:1}.vitessce-container .higlass-wrapper .rct-native-display .rct-checkbox{display:none}.vitessce-container .higlass-wrapper .rct-node-clickable{cursor:pointer}.vitessce-container .higlass-wrapper .rct-node-clickable:hover{background:rgba(51,51,204,.1)}.vitessce-container .higlass-wrapper .rct-node-clickable:focus{outline:0;background:rgba(51,51,204,.2)}.vitessce-container .higlass-wrapper .rct-node-icon{color:#33c}.vitessce-container .higlass-wrapper .rct-title{padding:0 5px}.vitessce-container .higlass-wrapper .rct-icon-expand-close:before{content:""}.vitessce-container .higlass-wrapper .rct-icon-expand-open:before{content:""}.vitessce-container .higlass-wrapper .rct-icon-uncheck:before{content:""}.vitessce-container .higlass-wrapper .rct-icon-check:before{content:""}.vitessce-container .higlass-wrapper .rct-icon-half-check:before{opacity:.5;content:""}.vitessce-container .higlass-wrapper .rct-icon-leaf:before{content:""}.vitessce-container .higlass-wrapper .rct-icon-parent-open:before{content:""}.vitessce-container .higlass-wrapper .rct-icon-parent-close:before{content:""}.vitessce-container .higlass-wrapper .rct-icon-expand-all:before{content:""}.vitessce-container .higlass-wrapper .rct-icon-collapse-all:before{content:""}.vitessce-container .higlass-wrapper .plot-type-selected{background-color:rgba(0,0,255,.3)}.vitessce-container .higlass-wrapper .plot-type-container{overflow-y:scroll;padding:3px;max-height:15vh}.vitessce-container .higlass-wrapper .plot-type-container,.vitessce-container .higlass-wrapper .plot-type-container-empty{margin:5px;border:1px solid #aaa;border-radius:5px}.vitessce-container .higlass-wrapper .plot-type-container-empty{padding:3px 8px;background-color:#e8e8e8}.vitessce-container .higlass-wrapper .plot-type-item{cursor:pointer}.vitessce-container .higlass-wrapper .plot-type-item:not(.plot-type-selected):hover{background-color:rgba(51,51,204,.1)}.vitessce-container .higlass-wrapper .track-thumbnail{width:30px;height:20px;display:inline-block;margin-right:10;vertical-align:middle}.vitessce-container .higlass-wrapper .track-thumbnail>svg{width:20px;height:20px}.vitessce-container .higlass-wrapper .AddTrackDialog-module_collapse-toggle-icon-1Of5_:before{font-family:Glyphicons Halflings;content:"";float:left;padding-right:3px}.vitessce-container .higlass-wrapper .AddTrackDialog-module_collapse-toggle-icon-1Of5_.AddTrackDialog-module_collapsed-1ifB1:before{content:""}.vitessce-container .higlass-wrapper .AddTrackDialog-module_modal-title-1Atka{font-family:Roboto;font-weight:700}.vitessce-container .higlass-wrapper .AddTrackDialog-module_modal-container-14d_4{position:relative}.vitessce-container .higlass-wrapper .AddTrackDialog-module_modal-container-14d_4 .AddTrackDialog-module_modal-backdrop-ZrVQg,.vitessce-container .higlass-wrapper .AddTrackDialog-module_modal-container-14d_4 .AddTrackDialog-module_modal-bZqLI{position:absolute}.vitessce-container .higlass-wrapper .AddTrackDialog-module_modal-dialog-3bKDk{position:relative;display:table;overflow-y:auto;overflow-x:auto;width:600px;min-width:300px;margin:auto}.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-right-handle-o7UYG,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-right-handle-oUk0R{border-right:solid #000;border-top:solid #000}.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-left-handle-FO7d4,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-left-handle-R5Zui{border-left:solid #000;border-top:solid #000}.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP{position:absolute;opacity:0;transition:transform .15s ease,opacity .15s ease}.vitessce-container .higlass-wrapper .DraggableDiv-module_draggable-div-2eWml{background-color:transparent;box-sizing:border-box}.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-grabber-2mVDE{width:10px;height:4px;border-top:1px solid #000;border-bottom:1px solid #000;margin:4px 7px}.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-grabber-1mtC0{width:4px;height:10px;border-left:1px solid #000;border-right:1px solid #000;margin:7px 4px}.vitessce-container .higlass-wrapper .DraggableDiv-module_draggable-div-2eWml:hover .DraggableDiv-module_bottom-draggable-handle-3olLp,.vitessce-container .higlass-wrapper .DraggableDiv-module_draggable-div-2eWml:hover .DraggableDiv-module_left-draggable-handle-2gpow,.vitessce-container .higlass-wrapper .DraggableDiv-module_draggable-div-2eWml:hover .DraggableDiv-module_right-draggable-handle-2Sriq,.vitessce-container .higlass-wrapper .DraggableDiv-module_draggable-div-2eWml:hover .DraggableDiv-module_top-draggable-handle-3W5bP{opacity:.5;background:hsla(0,0%,100%,.75);box-shadow:0 0 3px 1px hsla(0,0%,100%,.75);border-radius:3px}.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:active,.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:hover,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:active,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:hover,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:active,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:hover,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:active,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:hover{opacity:1!important;transform:scale(2)}.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:active .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:active .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:active .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:active .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:hover .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:hover .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:hover .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp:hover .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:active .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:active .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:active .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:active .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:hover .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:hover .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:hover .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow:hover .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:active .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:active .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:active .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:active .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:hover .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:hover .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:hover .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq:hover .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:active .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:active .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:active .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:active .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:hover .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:hover .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:hover .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP:hover .DraggableDiv-module_top-draggable-handle-grabber-2mVDE{box-shadow:0 0 3px 1px #0089ff;background:#0089ff}.vitessce-container .higlass-wrapper .DraggableDiv-module_bottom-draggable-handle-3olLp,.vitessce-container .higlass-wrapper .DraggableDiv-module_top-draggable-handle-3W5bP{height:12px;cursor:row-resize}.vitessce-container .higlass-wrapper .DraggableDiv-module_left-draggable-handle-2gpow,.vitessce-container .higlass-wrapper .DraggableDiv-module_right-draggable-handle-2Sriq{width:12px;cursor:col-resize}.vitessce-container .higlass-wrapper .HorizontalTiledPlot-module_horizontal-tiled-plot-3EK65,.vitessce-container .higlass-wrapper .VerticalTiledPlot-module_vertical-tiled-plot-R3sb7{position:relative}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-focus-23by2,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-SYccr{position:relative;display:flex;align-items:stretch;height:100%;margin-bottom:0;font-size:13.71429px;transition:box-shadow .15s ease,font-size .15s ease}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-focus-23by2{box-shadow:0 0 0 1px #337ab7,0 0 3px 1px #337ab7}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-1_0ZU{position:relative;box-sizing:border-box;width:100%;height:100%;padding:3px;color:#666;font-size:inherit;line-height:24px;border:0;border-radius:3px 0 0 3px;background:transparent}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-1_0ZU:focus{outline:none;color:#000}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-dark-EML2e .GenomePositionSearchBox-module_genome-position-search-bar-1_0ZU:focus{color:#e5e5e5}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk{display:block;height:100%;padding:0 8px!important;color:#999;border:0!important;border-radius:0!important;background:transparent;transition:background .15s ease,color .15s ease}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ:active,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ:focus,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ:hover,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk:active,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk:focus,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk:hover{color:#fff;background:#337ab7}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-icon-14AEk,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z{display:flex;align-items:center;transition:color .15s ease}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-icon-14AEk:first-child,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z:first-child{margin-left:6px;margin-right:2px}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-icon-14AEk span,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z span{display:block;margin-top:-2px}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z{color:#337ab7}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-bar-suggestions-SrIoU{position:fixed;border-radius:3px;box-shadow:0 0 3px 0 rgba(0,0,0,.1),0 1px 5px 0 rgba(0,0,0,.05);background-color:hsla(0,0%,100%,.95);border:1px solid rgba(0,0,0,.1);padding:2px 0;font-size:90%;overflow:auto;max-height:50%}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_btn-2bTUd{display:inline-block;margin-bottom:0;font-size:13.71429px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_btn-sm-2Ltms{font-size:12px;line-height:1.5;border-radius:3px}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_btn-default-2pap4{color:#666;background-color:#fff;border-color:#ccc}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_btn-default-2pap4:hover{color:#000;background:#ccc}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_btn-default-2pap4:active,.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_btn-default-2pap4:focus{color:#fff;border-color:#000;background:#000}.vitessce-container .higlass-wrapper .GenomePositionSearchBox-module_genome-position-search-SYccr .GenomePositionSearchBox-module_btn-2bTUd{border-radius:0 3px 3px 0}.vitessce-container .higlass-wrapper .ExportLinkDialog-module_export-link-dialog-wrapper-ldYlL{display:flex}.vitessce-container .higlass-wrapper .ExportLinkDialog-module_export-link-dialog-wrapper-ldYlL input{flex-grow:1}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-table-RHODc{border-collapse:collapse;margin:5px;color:#666}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-table-dark-_B9fu{color:#ccc}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-other-lIGbb{outline:none}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-top-center-2Dw4e{min-width:80px;min-height:20px;text-align:center;outline:none;border-top:1px solid #999;border-left:1px solid #999;border-right:1px solid #999;border-radius:2px 2px 0 0}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-top-center-2Dw4e:hover{color:#fff;background-color:#337ab7}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-middle-left-2ycaN{min-width:40px;text-align:center;outline:none;border-top:1px solid #999;border-left:1px solid #999;border-bottom:1px solid #999;border-radius:2px 0 0 2px}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-middle-left-2ycaN:hover{background-color:#337ab7;color:#fff}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-middle-right-Qqjnn{min-width:40px;text-align:center;outline:none;border-top:1px solid #999;border-right:1px solid #999;border-bottom:1px solid #999;border-radius:0 2px 2px 0}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-middle-right-Qqjnn:hover{background-color:#337ab7;color:#fff}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-middle-middle-2YFZd{text-align:center;outline:none;border:1px solid #999}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-middle-middle-2YFZd:hover{background-color:#337ab7;color:#fff}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-bottom-middle-3ityE{min-height:20px;text-align:center;outline:none;border-left:1px solid #999;border-right:1px solid #999;border-bottom:1px solid #999;border-radius:0 0 2px 2px}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-bottom-middle-3ityE:hover{background-color:#337ab7;color:#fff}.vitessce-container .higlass-wrapper .AddTrackPositionMenu-module_add-track-position-span-2hbwE{margin:5px}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-3XnZx,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-focus-3akkN,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-squeazed-GHIVd{position:relative;display:flex;justify-content:space-between;height:24px;margin-top:4px;margin-bottom:4px;color:#999;font-size:12px;line-height:24px;vertical-align:middle;border:0;border-radius:3px;background:#e5e5e5;transition:height .15s ease,margin .15s ease}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-dark-97tZt{background:#222}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-focus-3akkN{height:32px;margin-top:0;margin-bottom:0}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-id-3YURk{padding-left:3px}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-id-3YURk:before{content:"ID:";font-weight:700;padding-right:5px}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-left-Qj9Sm{display:flex;flex-grow:1}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-grabber-3jrIz,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z{display:flex;align-items:center;justify-content:center;width:24px;height:100%;cursor:move;border-radius:3px 0 0 3px;transition:background .15s ease}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-grabber-3jrIz:hover,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z:hover{background:#999}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-grabber-3jrIz:hover div,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z:hover div{background:#fff}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-grabber-3jrIz div,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z div{width:1px;height:50%;margin:1px;background:#999;transition:background .15s ease}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-dark-97tZt .ViewHeader-module_multitrack-header-grabber-3jrIz div{background:#666}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z{width:19.2px}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-search-1X_3_{position:relative;flex-grow:1;height:100%;margin-right:12px}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-search-1X_3_:after{position:absolute;top:3px;bottom:3px;right:-12px;display:block;content:"";width:1px;margin:0 6px;background:#ccc}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-dark-97tZt .ViewHeader-module_multitrack-header-search-1X_3_:after{background:#666}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-3XnZx>nav,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-nav-list-2nvcu{display:flex}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-16QKZ,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-squeazed-25lkF{width:24px;height:100%;padding:6px;transition:background .15s ease,color .15s ease}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-16QKZ:active,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-16QKZ:focus,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-16QKZ:hover,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-squeazed-25lkF:active,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-squeazed-25lkF:focus,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-squeazed-25lkF:hover{color:#fff;background:#337ab7}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-16QKZ:last-child,.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-squeazed-25lkF:last-child{border-radius:0 3px 3px 0}.vitessce-container .higlass-wrapper .ViewHeader-module_mouse-tool-selection-1pg2m{color:#fff;border-radius:3px 0 0 3px;background:#337ab7}.vitessce-container .higlass-wrapper .ViewHeader-module_multitrack-header-icon-squeazed-25lkF{width:20px 5;padding-left:3px;padding-right:3px}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-editor-header-2nTtX{margin:-10px -10px 0;padding:10px;display:flex;justify-content:space-between;background:#f2f2f2}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-editor-header-2nTtX button{display:flex;align-items:center;font-size:14px;background:#f2f2f2}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-editor-header-2nTtX button:hover{background:#e5e5e5}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-editor-header-2nTtX button:hover span{color:#666}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-editor-2HAFN{position:absolute;top:50px;right:0;bottom:0;left:0;margin:1px 0 0;padding:0;overflow:auto;font-size:12.5px;height:calc(100% - 80px)}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-1mYmL{position:absolute;right:0;bottom:0;left:0;margin:1px 0 0;padding:0;min-height:30px;background:#f2f2f2;transition:height .15s ease}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-header-3EbEM{background:#f2f2f2;border-top:1px solid #ccc;border-bottom:1px solid #ccc;padding-left:10px;height:30px;display:flex;align-items:center;cursor:pointer;position:sticky;position:-webkit-sticky;top:0}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-msg-2-CJZ{background:#f2f2f2;overflow:auto;height:calc(100% - 30px)}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-msg-2-CJZ td,.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-msg-2-CJZ tr{outline:none;vertical-align:top}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-msg-2-CJZ .ViewConfigEditor-module_title-3nLH_{font-weight:700;padding-left:8px;padding-top:8px;width:100px}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-msg-2-CJZ .ViewConfigEditor-module_Warning-_sgiB{color:orange}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-msg-2-CJZ .ViewConfigEditor-module_Success-nclFo{color:green}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-msg-2-CJZ .ViewConfigEditor-module_Error-3enaC{color:red}.vitessce-container .higlass-wrapper .ViewConfigEditor-module_view-config-log-msg-2-CJZ pre{background:#fff;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word}.vitessce-container .higlass-wrapper .HiGlass-module_higlass-1NHR2{position:relative}.vitessce-container .higlass-wrapper .HiGlass-module_higlass-dark-theme-2visd{background:#000}.vitessce-container .higlass-wrapper .HiGlass-module_higlass-container-overflow-zNXnY,.vitessce-container .higlass-wrapper .HiGlass-module_higlass-scroll-container-overflow-2FS0w,.vitessce-container .higlass-wrapper .HiGlass-module_higlass-scroll-container-scroll-2lAU4{position:absolute;top:0;right:0;bottom:0;left:0}.vitessce-container .higlass-wrapper .HiGlass-module_higlass-scroll-container-overflow-2FS0w{overflow:hidden}.vitessce-container .higlass-wrapper .HiGlass-module_higlass-scroll-container-scroll-2lAU4{overflow-x:hidden;overflow-y:auto}.vitessce-container .higlass-wrapper .HiGlass-module_higlass-canvas-_mP9r{position:absolute;width:100%;height:100%}.vitessce-container .higlass-wrapper .HiGlass-module_higlass-drawing-surface-3aQQo{position:relative}.vitessce-container .higlass-wrapper .HiGlass-module_higlass-svg-JJZbf{position:absolute;width:100%;height:100%;left:0;top:0;pointer-events:none}.vitessce-container .higlass-wrapper .HiGlass-module_tiled-area-22H1L{display:flex;flex-direction:column}.vitessce-container .higlass-wrapper .HiGlass-module_track-mouseover-menu-1AoaP{position:fixed;z-index:1;margin:17px 0 0 9px;padding:0 .25rem;max-width:50vw;word-wrap:break-word;font-size:.8em;pointer-events:none;background:#fff;border-radius:.25rem;box-shadow:0 0 0 1px rgba(0,0,0,.1),0 0 3px 0 rgba(0,0,0,.075),0 0 7px 0 rgba(0,0,0,.05)}.vitessce-container .higlass-wrapper .higlass .react-grid-layout{position:relative;transition:height .2s ease}.vitessce-container .higlass-wrapper .higlass .react-grid-item{transition:all .2s ease;transition-property:left,top}.vitessce-container .higlass-wrapper .higlass .react-grid-item.cssTransforms{transition-property:transform}.vitessce-container .higlass-wrapper .higlass .react-grid-item.resizing{z-index:1;will-change:width,height}.vitessce-container .higlass-wrapper .higlass .react-grid-item.react-draggable-dragging{transition:none;z-index:3;will-change:transform}.vitessce-container .higlass-wrapper .higlass .react-grid-item.react-grid-placeholder{background:red;opacity:.2;transition-duration:.1s;z-index:2;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.vitessce-container .higlass-wrapper .higlass .react-grid-item>.react-resizable-handle{position:absolute;width:20px;height:20px;bottom:0;right:0;cursor:se-resize}.vitessce-container .higlass-wrapper .higlass .react-grid-item>.react-resizable-handle:after{content:"";position:absolute;right:3px;bottom:3px;width:5px;height:5px;border-right:2px solid rgba(0,0,0,.4);border-bottom:2px solid rgba(0,0,0,.4)}.vitessce-container .higlass-wrapper .higlass .react-resizable{position:relative}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle{position:absolute;width:20px;height:20px;background-repeat:no-repeat;background-origin:content-box;box-sizing:border-box;background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHN0eWxlPSJiYWNrZ3JvdW5kLWNvbG9yOiNmZmZmZmYwMCIgd2lkdGg9IjYiIGhlaWdodD0iNiI+PHBhdGggZD0iTTYgNkgwVjQuMmg0LjJWMEg2djZ6IiBvcGFjaXR5PSIuMzAyIi8+PC9zdmc+");background-position:100% 100%;padding:0 3px 3px 0}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-sw{bottom:0;left:0;cursor:sw-resize;transform:rotate(90deg)}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-se{bottom:0;right:0;cursor:se-resize}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-nw{top:0;left:0;cursor:nw-resize;transform:rotate(180deg)}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-ne{top:0;right:0;cursor:ne-resize;transform:rotate(270deg)}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-e,.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-w{top:50%;margin-top:-10px;cursor:ew-resize}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-w{left:0;transform:rotate(135deg)}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-e{right:0;transform:rotate(315deg)}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-n,.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-s{left:50%;margin-left:-10px;cursor:ns-resize}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-n{top:0;transform:rotate(225deg)}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle-s{bottom:0;transform:rotate(45deg)}.vitessce-container .higlass-wrapper .higlass code[class*=language-],.vitessce-container .higlass-wrapper .higlass pre[class*=language-]{color:#393a34;font-family:Consolas,Bitstream Vera Sans Mono,Courier New,Courier,monospace;direction:ltr;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;font-size:.95em;line-height:1.2em;-moz-tab-size:4;tab-size:4;-webkit-hyphens:none;-ms-hyphens:none;hyphens:none}.vitessce-container .higlass-wrapper .higlass code[class*=language-]::selection,.vitessce-container .higlass-wrapper .higlass code[class*=language-] ::selection,.vitessce-container .higlass-wrapper .higlass pre[class*=language-]::selection,.vitessce-container .higlass-wrapper .higlass pre[class*=language-] ::selection{background:#b3d4fc}.vitessce-container .higlass-wrapper .higlass pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto;border:1px solid #ddd;background-color:#fff}.vitessce-container .higlass-wrapper .higlass :not(pre)>code[class*=language-]{padding:1px .2em;background:#f8f8f8;border:1px solid #ddd}.vitessce-container .higlass-wrapper .higlass .token.cdata,.vitessce-container .higlass-wrapper .higlass .token.comment,.vitessce-container .higlass-wrapper .higlass .token.doctype,.vitessce-container .higlass-wrapper .higlass .token.prolog{color:#998;font-style:italic}.vitessce-container .higlass-wrapper .higlass .token.namespace{opacity:.7}.vitessce-container .higlass-wrapper .higlass .token.attr-value,.vitessce-container .higlass-wrapper .higlass .token.string{color:#e3116c}.vitessce-container .higlass-wrapper .higlass .token.operator,.vitessce-container .higlass-wrapper .higlass .token.punctuation{color:#393a34}.vitessce-container .higlass-wrapper .higlass .token.boolean,.vitessce-container .higlass-wrapper .higlass .token.constant,.vitessce-container .higlass-wrapper .higlass .token.entity,.vitessce-container .higlass-wrapper .higlass .token.inserted,.vitessce-container .higlass-wrapper .higlass .token.number,.vitessce-container .higlass-wrapper .higlass .token.property,.vitessce-container .higlass-wrapper .higlass .token.regex,.vitessce-container .higlass-wrapper .higlass .token.symbol,.vitessce-container .higlass-wrapper .higlass .token.url,.vitessce-container .higlass-wrapper .higlass .token.variable{color:#36acaa}.vitessce-container .higlass-wrapper .higlass .language-autohotkey .token.selector,.vitessce-container .higlass-wrapper .higlass .token.atrule,.vitessce-container .higlass-wrapper .higlass .token.attr-name,.vitessce-container .higlass-wrapper .higlass .token.keyword{color:#00a4db}.vitessce-container .higlass-wrapper .higlass .language-autohotkey .token.tag,.vitessce-container .higlass-wrapper .higlass .token.deleted,.vitessce-container .higlass-wrapper .higlass .token.function{color:#9a050f}.vitessce-container .higlass-wrapper .higlass .language-autohotkey .token.keyword,.vitessce-container .higlass-wrapper .higlass .token.selector,.vitessce-container .higlass-wrapper .higlass .token.tag{color:#00009f}.vitessce-container .higlass-wrapper .higlass .token.bold,.vitessce-container .higlass-wrapper .higlass .token.function,.vitessce-container .higlass-wrapper .higlass .token.important{font-weight:700}.vitessce-container .higlass-wrapper .higlass .token.italic{font-style:italic}.vitessce-container .higlass-wrapper .higlass *{box-sizing:border-box}.vitessce-container .higlass-wrapper .higlass .react-resizable-handle{z-index:1}.vitessce-container .higlass-wrapper table.table-track-options{border-collapse:collapse;margin-left:auto;margin-right:auto}.vitessce-container .higlass-wrapper td.td-track-options{border:1px solid #fff;outline:none;padding:3px;position:relative;font-family:Roboto,sans-serif;font-size:14px;color:#666}.vitessce-container .higlass-wrapper .cell-label{position:absolute;left:0;top:0;margin-left:5px;color:#777}.vitessce-container .higlass-wrapper .modal-dialog{position:relative;display:table;overflow-y:auto;overflow-x:auto;width:auto;min-width:300px;margin:auto}.vitessce-container{position:relative}.vitessce-container *,.vitessce-container :after,.vitessce-container :before{box-sizing:border-box}.vitessce-container div{-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:rgba(0,0,0,0);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;text-align:left}.vitessce-container article,.vitessce-container aside,.vitessce-container figcaption,.vitessce-container figure,.vitessce-container footer,.vitessce-container header,.vitessce-container hgroup,.vitessce-container main,.vitessce-container nav,.vitessce-container section{display:block}.vitessce-container h1,.vitessce-container h2,.vitessce-container h3,.vitessce-container h4,.vitessce-container h5,.vitessce-container h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2}.vitessce-container p{margin-top:0;margin-bottom:1rem}.vitessce-container dl,.vitessce-container ol,.vitessce-container ul{margin-top:0;margin-bottom:0}.vitessce-container b,.vitessce-container strong{font-weight:bolder}.vitessce-container small{font-size:80%}.vitessce-container a{color:#007bff;text-decoration:none;background-color:transparent}.vitessce-container a:hover{color:#0056b3;text-decoration:underline}.vitessce-container a:not([href]),.vitessce-container a:not([href]):hover{color:inherit;text-decoration:none}.vitessce-container img{vertical-align:middle;border-style:none}.vitessce-container svg{overflow:hidden}.vitessce-container table{border-collapse:collapse}.vitessce-container th{text-align:inherit}.vitessce-container button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}.vitessce-container button,.vitessce-container input,.vitessce-container optgroup,.vitessce-container select,.vitessce-container textarea{font-family:inherit;font-size:inherit;line-height:inherit}.vitessce-container button,.vitessce-container input{overflow:visible}.vitessce-container button,.vitessce-container select{text-transform:none}.vitessce-container select{word-wrap:normal}.vitessce-container [type=button],.vitessce-container [type=reset],.vitessce-container [type=submit],.vitessce-container button{-webkit-appearance:button}.vitessce-container [type=button]:not(:disabled),.vitessce-container [type=reset]:not(:disabled),.vitessce-container [type=submit]:not(:disabled),.vitessce-container button:not(:disabled){cursor:pointer}.vitessce-container [type=button]::-moz-focus-inner,.vitessce-container [type=reset]::-moz-focus-inner,.vitessce-container [type=submit]::-moz-focus-inner,.vitessce-container button::-moz-focus-inner{padding:0;border-style:none}.vitessce-container input[type=checkbox],.vitessce-container input[type=radio]{box-sizing:border-box;padding:0}.vitessce-container [hidden]{display:none!important}.vitessce-container h1{font-size:2.5rem}.vitessce-container h2{font-size:2rem}.vitessce-container h3{font-size:1.75rem}.vitessce-container h4{font-size:1.5rem}.vitessce-container h5{font-size:1.25rem}.vitessce-container h6{font-size:1rem}.vitessce-container .container-fluid{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.vitessce-container .row{display:flex;flex-wrap:wrap;margin-right:-15px;margin-left:-15px}.vitessce-container .col{flex-basis:0;flex-grow:1;max-width:100%;position:relative;width:100%;padding-right:15px;padding-left:15px}.vitessce-container .d-flex{display:flex!important}.vitessce-container .card>.list-group:first-child .list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.vitessce-container .card>.list-group:last-child .list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.vitessce-container .card-header+.list-group .list-group-item:first-child{border-top:0}.vitessce-container .card-body{flex:1 1 auto;min-height:1px;padding:.75rem}.vitessce-container .list-group{display:flex;flex-direction:column;padding-left:0;margin-bottom:0}.vitessce-container .list-group-item-action{width:100%;color:#495057;text-align:inherit}.vitessce-container .list-group-item-action:focus,.vitessce-container .list-group-item-action:hover{z-index:1;text-decoration:none}.vitessce-container .list-group-item{position:relative;display:block;padding:.75rem 1.25rem;border:1px solid rgba(0,0,0,.125)}.vitessce-container .list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.vitessce-container .list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.vitessce-container .list-group-item.disabled,.vitessce-container .list-group-item:disabled{color:#6c757d;pointer-events:none;background-color:#fff}.vitessce-container .list-group-item.active{z-index:2;color:#fff;background-color:#007bff;border-color:#007bff}.vitessce-container .list-group-item+.list-group-item{border-top-width:0}.vitessce-container .list-group-item+.list-group-item.active{margin-top:-1px;border-top-width:1px}.vitessce-container .flex-column{flex-direction:column!important}.vitessce-container .align-items-start{align-items:flex-start!important}.vitessce-container .input-group{position:relative;display:flex;flex-wrap:wrap;align-items:stretch;width:100%}.vitessce-container .input-group>.form-control,.vitessce-container .input-group>.form-control-plaintext{position:relative;flex:1 1;min-width:0;margin-bottom:0}.vitessce-container .input-group>.custom-file+.form-control,.vitessce-container .input-group>.custom-select+.form-control,.vitessce-container .input-group>.form-control+.form-control,.vitessce-container .input-group>.form-control-plaintext+.form-control{margin-left:-1px}.vitessce-container .input-group>.form-control:focus{z-index:3}.vitessce-container .input-group>.form-control:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.vitessce-container .input-group>.form-control:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.vitessce-container .input-group-append,.vitessce-container .input-group-prepend{display:flex}.vitessce-container .input-group-append .btn,.vitessce-container .input-group-prepend .btn{position:relative;z-index:2}.vitessce-container .input-group-append .btn:focus,.vitessce-container .input-group-prepend .btn:focus{z-index:3}.vitessce-container .input-group-append .btn+.btn,.vitessce-container .input-group-prepend .btn+.btn{margin-left:-1px}.vitessce-container .input-group-prepend{margin-right:-1px}.vitessce-container .input-group-append{margin-left:-1px}.vitessce-container .input-group-lg>.form-control:not(textarea){height:calc(1.5em + 1rem + 2px)}.vitessce-container .input-group-lg>.form-control,.vitessce-container .input-group-lg>.input-group-append>.btn,.vitessce-container .input-group-lg>.input-group-prepend>.btn{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.vitessce-container .input-group-sm>.form-control:not(textarea){height:calc(1.5em + .5rem + 2px)}.vitessce-container .input-group-sm>.form-control,.vitessce-container .input-group-sm>.input-group-append>.btn,.vitessce-container .input-group-sm>.input-group-prepend>.btn{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.vitessce-container .input-group>.input-group-append:last-child>.btn:not(:last-child):not(.dropdown-toggle),.vitessce-container .input-group>.input-group-append:not(:last-child)>.btn,.vitessce-container .input-group>.input-group-prepend>.btn{border-top-right-radius:0;border-bottom-right-radius:0}.vitessce-container .input-group>.input-group-append>.btn,.vitessce-container .input-group>.input-group-prepend:first-child>.btn:not(:first-child),.vitessce-container .input-group>.input-group-prepend:not(:first-child)>.btn{border-top-left-radius:0;border-bottom-left-radius:0}.vitessce-container .mt-auto,.vitessce-container .my-auto{margin-top:auto!important}.vitessce-container .mb-auto,.vitessce-container .my-auto{margin-bottom:auto!important}.vitessce-container .mt-0,.vitessce-container .my-0{margin-top:0!important}.vitessce-container .mb-0,.vitessce-container .my-0{margin-bottom:0!important}.vitessce-container .mt-1,.vitessce-container .my-1{margin-top:.25rem!important}.vitessce-container .mb-1,.vitessce-container .my-1{margin-bottom:.25rem!important}.vitessce-container .mt-2,.vitessce-container .my-2{margin-top:.5rem!important}.vitessce-container .mb-2,.vitessce-container .my-2{margin-bottom:.5rem!important}.vitessce-container .mt-3,.vitessce-container .my-3{margin-top:1rem!important}.vitessce-container .mb-3,.vitessce-container .my-3{margin-bottom:1rem!important}.vitessce-container .ml-auto,.vitessce-container .mx-auto{margin-left:auto!important}.vitessce-container .mr-auto,.vitessce-container .mx-auto{margin-right:auto!important}.vitessce-container .ml-0,.vitessce-container .mx-0{margin-left:0!important}.vitessce-container .mr-0,.vitessce-container .mx-0{margin-right:0!important}.vitessce-container .ml-1,.vitessce-container .mx-1{margin-left:.25rem!important}.vitessce-container .mr-1,.vitessce-container .mx-1{margin-right:.25rem!important}.vitessce-container .ml-2,.vitessce-container .mx-2{margin-left:.5rem!important}.vitessce-container .mr-2,.vitessce-container .mx-2{margin-right:.5rem!important}.vitessce-container .ml-3,.vitessce-container .mx-3{margin-left:1rem!important}.vitessce-container .mr-3,.vitessce-container .mx-3{margin-right:1rem!important}.vitessce-container .pt-0,.vitessce-container .py-0{padding-top:0!important}.vitessce-container .pb-0,.vitessce-container .py-0{padding-bottom:0!important}.vitessce-container .pt-1,.vitessce-container .py-1{padding-top:.25rem!important}.vitessce-container .pb-1,.vitessce-container .py-1{padding-bottom:.25rem!important}.vitessce-container .pt-2,.vitessce-container .py-2{padding-top:.5rem!important}.vitessce-container .pb-2,.vitessce-container .py-2{padding-bottom:.5rem!important}.vitessce-container .pt-3,.vitessce-container .py-3{padding-top:1rem!important}.vitessce-container .pb-3,.vitessce-container .py-3{padding-bottom:1rem!important}.vitessce-container .pl-0,.vitessce-container .px-0{padding-left:0!important}.vitessce-container .pr-0,.vitessce-container .px-0{padding-right:0!important}.vitessce-container .pl-1,.vitessce-container .px-1{padding-left:.25rem!important}.vitessce-container .pr-1,.vitessce-container .px-1{padding-right:.25rem!important}.vitessce-container .pr-2,.vitessce-container .px-2{padding-right:.5rem!important}.vitessce-container .pl-3,.vitessce-container .px-3{padding-left:1rem!important}.vitessce-container .pr-3,.vitessce-container .px-3{padding-right:1rem!important}.vitessce-container .form-control{display:block;width:100%;height:calc(1.5em + .75rem + 2px);padding:.375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;background-color:#fff;background-clip:padding-box;border:1px solid #ced4da;border-radius:.25rem;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media(prefers-reduced-motion:reduce){.vitessce-container .form-control{transition:none}}.vitessce-container .form-control::-ms-expand{background-color:transparent;border:0}.vitessce-container .form-control:-moz-focusring{color:transparent;text-shadow:0 0 0 #495057}.vitessce-container .form-control:focus{color:#495057;background-color:#fff;border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.vitessce-container .form-control::-webkit-input-placeholder{color:#6c757d;opacity:1}.vitessce-container .form-control:-ms-input-placeholder{color:#6c757d;opacity:1}.vitessce-container .form-control::-ms-input-placeholder{color:#6c757d;opacity:1}.vitessce-container .form-control::placeholder{color:#6c757d;opacity:1}.vitessce-container .form-control:disabled,.vitessce-container .form-control[readonly]{background-color:#e9ecef;opacity:1}.vitessce-container select.form-control:focus::-ms-value{color:#495057;background-color:#fff}.vitessce-container .btn .badge{position:relative;top:-1px}.vitessce-container .btn{display:inline-block;font-weight:400;color:#212529;text-align:center;vertical-align:middle;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:transparent;border:1px solid transparent;padding:.375rem .75rem;font-size:1rem;line-height:1.5;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media(prefers-reduced-motion:reduce){.vitessce-container .btn{transition:none}}.vitessce-container .btn:hover{color:#212529;text-decoration:none}.vitessce-container .btn.focus,.vitessce-container .btn:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.vitessce-container .btn.disabled,.vitessce-container .btn:disabled{opacity:.65}.vitessce-container .btn-outline-secondary{color:#6c757d;border-color:#6c757d}.vitessce-container .btn-outline-secondary:hover{color:#fff;background-color:#6c757d;border-color:#6c757d}.vitessce-container .btn-outline-secondary.focus,.vitessce-container .btn-outline-secondary:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.vitessce-container .btn-outline-secondary.disabled,.vitessce-container .btn-outline-secondary:disabled{color:#6c757d;background-color:transparent}.vitessce-container .btn-outline-secondary:not(:disabled):not(.disabled).active,.vitessce-container .btn-outline-secondary:not(:disabled):not(.disabled):active,.vitessce-container .show>.btn-outline-secondary.dropdown-toggle{color:#fff;background-color:#6c757d;border-color:#6c757d}.vitessce-container .btn-outline-secondary:not(:disabled):not(.disabled).active:focus,.vitessce-container .btn-outline-secondary:not(:disabled):not(.disabled):active:focus,.vitessce-container .show>.btn-outline-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.vitessce-container .modal-open{overflow:hidden}.vitessce-container .modal-open .modal{overflow-x:hidden;overflow-y:auto}.vitessce-container .modal{position:absolute;top:0;left:0;z-index:1050;width:100%;height:100%;overflow:hidden;outline:0}.vitessce-container .modal-dialog{position:relative;width:auto;margin:.5rem;pointer-events:none}.vitessce-container .modal.fade .modal-dialog{transition:transform .3s ease-out;transform:translateY(-50px)}@media(prefers-reduced-motion:reduce){.vitessce-container .modal.fade .modal-dialog{transition:none}}.vitessce-container .modal.show .modal-dialog{transform:none}.vitessce-container .modal.modal-static .modal-dialog{transform:scale(1.02)}.vitessce-container .modal-dialog-scrollable{display:flex;max-height:calc(100% - 1rem)}.vitessce-container .modal-dialog-scrollable .modal-content{max-height:calc(100vh - 1rem);overflow:hidden}.vitessce-container .modal-dialog-scrollable .modal-footer,.vitessce-container .modal-dialog-scrollable .modal-header{flex-shrink:0}.vitessce-container .modal-dialog-scrollable .modal-body{overflow-y:auto}.vitessce-container .modal-dialog-centered{display:flex;align-items:center;min-height:calc(100% - 1rem)}.vitessce-container .modal-dialog-centered:before{display:block;height:calc(100vh - 1rem);content:""}.vitessce-container .modal-dialog-centered.modal-dialog-scrollable{flex-direction:column;justify-content:center;height:100%}.vitessce-container .modal-dialog-centered.modal-dialog-scrollable .modal-content{max-height:none}.vitessce-container .modal-dialog-centered.modal-dialog-scrollable:before{content:none}.vitessce-container .modal-content{position:relative;display:flex;flex-direction:column;width:100%;pointer-events:auto;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem;outline:0}.vitessce-container .modal-backdrop{position:absolute;top:0;left:0;z-index:1040;width:100%;height:100%;background-color:#000}.vitessce-container .modal-backdrop.fade{opacity:0}.vitessce-container .modal-backdrop.show{opacity:.5}.vitessce-container .modal-header{display:flex;align-items:flex-start;justify-content:space-between;padding:1rem;border-bottom:1px solid #dee2e6;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.vitessce-container .modal-header .close{padding:1rem;margin:-1rem -1rem -1rem auto}.vitessce-container .modal-title{margin-bottom:0;line-height:1.5}.vitessce-container .modal-body{position:relative;flex:1 1 auto;padding:1rem}.vitessce-container .modal-footer{display:flex;flex-wrap:wrap;align-items:center;justify-content:flex-end;padding:.75rem;border-top:1px solid #dee2e6;border-bottom-right-radius:calc(.3rem - 1px);border-bottom-left-radius:calc(.3rem - 1px)}.vitessce-container .modal-footer>*{margin:.25rem}.vitessce-container .modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media(min-width:576px){.vitessce-container .modal-dialog{max-width:500px;margin:1.75rem auto}.vitessce-container .modal-dialog-scrollable{max-height:calc(100% - 3.5rem)}.vitessce-container .modal-dialog-scrollable .modal-content{max-height:calc(100vh - 3.5rem)}.vitessce-container .modal-dialog-centered{min-height:calc(100% - 3.5rem)}.vitessce-container .modal-dialog-centered:before{height:calc(100vh - 3.5rem)}.vitessce-container .modal-sm{max-width:300px}}@media(min-width:992px){.vitessce-container .modal-lg,.vitessce-container .modal-xl{max-width:800px}}@media(min-width:1200px){.vitessce-container .modal-xl{max-width:1140px}}.vitessce-container .card{position:relative;display:flex;flex-direction:column;min-width:0;word-wrap:break-word;background-clip:border-box;border-radius:.25rem}.vitessce-container .alert{position:relative;padding:.75rem 1.25rem;margin-bottom:1rem;border:1px solid transparent;border-radius:.25rem}.vitessce-container .alert-warning{color:#856404;background-color:#fff3cd;border-color:#ffeeba}.vitessce-container .justify-content-between{justify-content:space-between!important}.vitessce-container .align-items-baseline{align-items:baseline!important}.vitessce-container .pl-2,.vitessce-container .px-2{padding-left:.5rem!important}.vitessce-container .align-items-end{align-items:flex-end!important}.vitessce-container.vitessce-theme-dark.welcome-container{overflow:visible}.vitessce-container.vitessce-theme-dark.welcome-container .react-grid-layout,.vitessce-container.vitessce-theme-dark.welcome-container .warning-layout{position:relative}.vitessce-container.vitessce-theme-dark.welcome-container .row>div>.card{margin:1rem 0}.vitessce-container.vitessce-theme-dark .welcome-beta-header{background-color:#93e5c3;padding:1rem}.vitessce-container.vitessce-theme-dark .welcome-beta-header p{margin:0;color:#222}.vitessce-container.vitessce-theme-dark .welcome-beta-header p a{color:#000;text-decoration:underline;font-weight:600}.vitessce-container.vitessce-theme-dark .react-grid-layout,.vitessce-container.vitessce-theme-dark .warning-layout{background-color:#333;height:auto;position:absolute;width:100%}.vitessce-container.vitessce-theme-dark .warning-layout{height:100vh}.vitessce-container.vitessce-theme-dark .warning-layout .card{margin-left:.5rem}.vitessce-container.vitessce-theme-dark .loading-indicator-backdrop{position:absolute;top:0;left:0;z-index:1040;width:100%;height:100%;border-radius:.25rem;background-color:rgba(0,0,0,.5)}.vitessce-container.vitessce-theme-dark .loading-indicator-backdrop .loading-indicator-container{display:grid;place-items:center;position:absolute;width:100%;height:100%}.vitessce-container.vitessce-theme-dark .react-grid-item{flex-direction:column!important;display:flex!important;padding-right:10px}.vitessce-container.vitessce-theme-dark .d-flex{flex-shrink:0}.vitessce-container.vitessce-theme-dark .title{color:#d3d3d3;overflow-x:hidden;display:flex;flex-direction:row;flex-shrink:0}.vitessce-container.vitessce-theme-dark .title .title-left{flex-shrink:1;text-overflow:ellipsis;white-space:nowrap}.vitessce-container.vitessce-theme-dark .title .title-info{width:100%;text-overflow:ellipsis;white-space:nowrap;overflow:hidden;font-size:80%;opacity:.8;padding:0 .25rem;justify-content:center;line-height:25px;flex-shrink:1;text-align:right}.vitessce-container.vitessce-theme-dark .title .title-buttons{display:flex;flex-direction:row;flex-grow:1;flex-shrink:0;justify-content:right}.vitessce-container.vitessce-theme-dark .title .title-buttons div{display:inline-block}.vitessce-container.vitessce-theme-dark .card{border:1px solid rgba(0,0,0,.125)}.vitessce-container.vitessce-theme-dark .bg-black{background-color:#000;color:#fff}.vitessce-container.vitessce-theme-dark .bg-black a{color:#fff}.vitessce-container.vitessce-theme-dark .bg-primary{background-color:#222;color:#d3d3d3}.vitessce-container.vitessce-theme-dark .bg-primary a{color:#9bb7d6}.vitessce-container.vitessce-theme-dark .bg-secondary{background-color:#000;color:#d3d3d3}.vitessce-container.vitessce-theme-dark .scroll{overflow-y:auto}.vitessce-container.vitessce-theme-dark .description details,.vitessce-container.vitessce-theme-dark .description p,.vitessce-container.vitessce-theme-dark .description table,.vitessce-container.vitessce-theme-dark .details{font-size:80%;opacity:.8}.vitessce-container.vitessce-theme-dark .description details{margin-bottom:6px}.vitessce-container.vitessce-theme-dark .description summary{border-bottom:1px solid #3c3c3c;cursor:pointer}.vitessce-container.vitessce-theme-dark .description .metadata-container{padding-left:14px}.vitessce-container.vitessce-theme-dark .description .metadata-container table{width:100%}.vitessce-container.vitessce-theme-dark .description .metadata-container table td,.vitessce-container.vitessce-theme-dark .description .metadata-container table th{outline:none;padding:2px;max-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;width:50%}.vitessce-container.vitessce-theme-dark .description .metadata-container table tr:nth-child(2n){background-color:#2f2f2f}.vitessce-container.vitessce-theme-dark .coll-full,.vitessce-container.vitessce-theme-dark .welcome-col-left,.vitessce-container.vitessce-theme-dark .welcome-col-right{position:relative;width:100%;padding-right:15px;padding-left:15px}.vitessce-container.vitessce-theme-dark .col-full{flex:0 0 100%;max-width:100%}.vitessce-container.vitessce-theme-dark .welcome-col-left{flex:0 0 50%;max-width:50%}.vitessce-container.vitessce-theme-dark .welcome-col-left .list-group-item{background-color:#000}.vitessce-container.vitessce-theme-dark .welcome-col-left .input-group input{background-color:#d3d3d3}.vitessce-container.vitessce-theme-dark .welcome-col-left a{color:#fff}.vitessce-container.vitessce-theme-dark .welcome-col-right{flex:0 0 50%;max-width:50%}.vitessce-container.vitessce-theme-dark .welcome-col-right .info-paragraph{margin-bottom:0!important}.vitessce-container.vitessce-theme-dark .welcome-col-right .info-section-text{margin-top:.5rem}.vitessce-container.vitessce-theme-dark .welcome-col-right a{color:#fff}.vitessce-container.vitessce-theme-dark .btn.icon{padding:0;height:2em;width:2em;background-color:#fff}.vitessce-container.vitessce-theme-dark .btn.icon>svg{vertical-align:middle}.vitessce-container.vitessce-theme-dark .roll-up{height:2em;overflow:hidden;background-color:#fff}.vitessce-container.vitessce-theme-dark .roll-up:hover{-webkit-animation-name:roll-up;animation-name:roll-up;-webkit-animation-duration:.5s;animation-duration:.5s;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards}@-webkit-keyframes roll-up{0%{height:2em}to{height:100%}}.vitessce-container.vitessce-theme-dark .tool{position:absolute;display:inline;z-index:1000;opacity:.65;color:#000}.vitessce-container.vitessce-theme-dark .tool:hover{opacity:.9}.vitessce-container.vitessce-theme-dark .radio{-webkit-appearance:none;-moz-appearance:none;appearance:none;display:inline-block;width:1em;height:1em;padding:6px!important;background-clip:content-box;border:2px solid #d3d3d3;background-color:#d3d3d3;border-radius:50%}.vitessce-container.vitessce-theme-dark .radio:checked{background-clip:unset}.vitessce-container.vitessce-theme-dark .layer-controller-container>div:first-child{margin-top:0!important}.vitessce-container.vitessce-theme-dark .channel-container{width:100%;display:flex;position:relative}.vitessce-container.vitessce-theme-dark .channel-set-color{display:flex;position:relative;top:5px;width:16px;height:16px;margin-right:24px;cursor:pointer;outline:medium none currentColor;border-radius:3px;box-shadow:inset 0 0 0 1px rgba(0,0,0,.15)}.vitessce-container.vitessce-theme-dark .channel-checked{display:flex;position:relative;margin-right:10px}.vitessce-container.vitessce-theme-dark .add-image-layer{color:#c6c6c6;border:1px dashed #c6c6c6}.vitessce-container.vitessce-theme-dark pre{color:#d3d3d3}.vitessce-container.vitessce-theme-dark .cell-emphasis-crosshair{z-index:50;position:absolute;pointer-events:none;box-sizing:border-box;background-color:#d3d3d3}.vitessce-container.vitessce-theme-dark .help-tooltip.rc-tooltip{z-index:1060;display:block;max-width:250px;visibility:visible;box-sizing:border-box;margin:0;padding:0;color:rgba(0,0,0,.65);font-size:14px;list-style:none;position:absolute}.vitessce-container.vitessce-theme-dark .help-tooltip.rc-tooltip-hidden{display:none}.vitessce-container.vitessce-theme-dark .help-tooltip.rc-tooltip .rc-tooltip-inner{border-radius:2px;box-shadow:0 3px 6px -4px hsla(0,0%,39.2%,.12),0 6px 16px 0 hsla(0,0%,39.2%,.08),0 9px 28px 8px hsla(0,0%,39.2%,.05)}.vitessce-container.vitessce-theme-dark .help-tooltip.rc-tooltip-placement-top{padding-top:8px}.vitessce-container.vitessce-theme-dark .help-tooltip.rc-tooltip-placement-right{padding-left:8px}.vitessce-container.vitessce-theme-dark .help-tooltip.rc-tooltip-placement-bottom{padding-top:8px}.vitessce-container.vitessce-theme-dark .help-tooltip.rc-tooltip-placement-left{padding-right:8px}.vitessce-container.vitessce-theme-dark .help-tooltip.rc-tooltip .rc-tooltip-inner{font-size:10px;min-width:30px;padding:6px 8px;color:#fff;text-align:left;text-decoration:none;word-wrap:break-word;background-color:rgba(0,0,0,.9)}.vitessce-container.vitessce-theme-dark .help-tooltip.rc-tooltip .rc-tooltip-arrow{display:none}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip{top:0;left:0;z-index:1030;font-weight:400;white-space:normal;text-align:left;cursor:auto;-webkit-user-select:text;-moz-user-select:text;-ms-user-select:text;user-select:text;box-sizing:border-box;margin:0;padding:0;color:rgba(0,0,0,.65);font-size:14px;list-style:none;position:absolute}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip:after{position:absolute;background:hsla(0,0%,100%,.01);content:""}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip-hidden{display:none}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner{border-radius:2px;box-shadow:0 3px 6px -4px hsla(0,0%,39.2%,.12),0 6px 16px 0 hsla(0,0%,39.2%,.08),0 9px 28px 8px hsla(0,0%,39.2%,.05)}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip-placement-top{padding-bottom:10px}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip-placement-right{padding-left:10px}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip-placement-bottom{padding-top:10px}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip-placement-left{padding-right:10px}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-content{padding:0}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner{box-sizing:border-box;background-color:#fff;background-clip:padding-box}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list{list-style-type:none;padding:0;margin-bottom:0}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list dl,.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list ol,.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list ul{margin-top:0;margin-bottom:1rem}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list li button{border:0;padding:4px 16px;cursor:pointer;width:100%;background-color:transparent;border-radius:2px}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list li button span.small{font-size:11px}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list li button:hover{background-color:#ededed}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list li:not(:last-child){border-bottom:1px solid grey}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list button{-webkit-appearance:button;text-transform:none;overflow:visible;margin:0;font-family:inherit;font-size:14px;line-height:inherit;border-radius:0}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner .popover-menu-color+.popover-menu-list{border-top:1px solid grey}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .popover-menu-color.twitter-picker{box-shadow:none!important;margin:0 auto}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .popover-menu-color.twitter-picker>div:nth-child(3){padding:6px!important;transform:translate(2px)}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .popover-menu-color.twitter-picker>div>div:first-of-type{font-size:12px;width:20px!important}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .popover-menu-color.twitter-picker input{width:60px!important;font-size:12px}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .popover-menu-color.twitter-picker>div>span>div{width:18px!important;height:18px!important}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-inner-content{padding:12px 16px;color:rgba(0,0,0,.65)}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip .rc-tooltip-arrow{position:absolute;display:block;width:8px;height:8px;background:transparent;border-style:solid;border-width:4px;transform:rotate(45deg)}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip.rc-tooltip-placement-top>.rc-tooltip-content>.rc-tooltip-arrow{bottom:6px;border-color:transparent #fff #fff transparent;box-shadow:3px 3px 7px rgba(0,0,0,.07);left:50%;transform:translateX(-50%) rotate(45deg)}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip.rc-tooltip-placement-right>.rc-tooltip-content>.rc-tooltip-arrow{left:6px;border-color:transparent transparent #fff #fff;box-shadow:-3px 3px 7px rgba(0,0,0,.07);top:50%;transform:translateY(-50%) rotate(45deg)}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip.rc-tooltip-placement-bottom>.rc-tooltip-content>.rc-tooltip-arrow{top:6px;border-color:#fff transparent transparent #fff;box-shadow:-2px -2px 5px rgba(0,0,0,.06);left:50%;transform:translateX(-50%) rotate(45deg)}.vitessce-container.vitessce-theme-dark .popover.rc-tooltip.rc-tooltip-placement-left>.rc-tooltip-content>.rc-tooltip-arrow{right:6px;border-color:#fff #fff transparent transparent;box-shadow:3px -3px 7px rgba(0,0,0,.07);top:50%;transform:translateY(-50%) rotate(45deg)}.vitessce-container.vitessce-theme-dark .sets-manager{position:relative;width:100%;display:block;height:auto}.vitessce-container.vitessce-theme-dark .sets-manager .set-operation-buttons{background-color:#d3d3d3;border-radius:4px;padding:2px;display:inline-block;position:absolute;bottom:1.75rem;right:.25rem;box-shadow:-2px -2px 5px rgba(0,0,0,.06)}.vitessce-container.vitessce-theme-dark .sets-manager .set-operation-buttons button{border:0;background-color:transparent;color:#626262}.vitessce-container.vitessce-theme-dark .sets-manager .set-operation-buttons button[disabled]{pointer-events:none}.vitessce-container.vitessce-theme-dark .sets-manager .set-operation-buttons button[disabled] svg{fill:silver}.vitessce-container.vitessce-theme-dark .sets-manager .set-operation-buttons button svg{fill:#555;vertical-align:top;height:20px;margin-top:1px}.vitessce-container.vitessce-theme-dark .sets-manager .set-operation-buttons button:hover,.vitessce-container.vitessce-theme-dark .sets-manager .set-operation-buttons button:hover path{color:#2f2f2f;fill:#2f2f2f}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree{position:relative;top:0;left:0;width:100%;height:auto;display:block;padding-right:17px;box-sizing:content-box}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .plus-button{border:0;background-color:transparent;color:#e0e0e0;padding:0;font-size:18px;margin-bottom:2rem}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree{padding-left:0;margin:0;border:1px solid transparent}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .node-menu-icon{fill:grey;cursor:pointer;height:14px;position:relative;vertical-align:top;width:32px;top:5.5px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .node-menu-icon:hover{fill:#9a9a9a}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .node-size-label{font-size:12px;color:#adadad}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .level-buttons-container{height:20px;width:100%;position:relative;padding-left:4px;left:0}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .level-buttons-container .level-buttons input.level-radio-button{cursor:pointer;-webkit-appearance:none;-moz-appearance:none;appearance:none;width:12px;height:12px;padding:5px;background-clip:content-box;border:2px solid #ededed;background-color:#ededed;border-radius:6px;position:relative;top:3px;left:0;float:left;margin-right:10px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .level-buttons-container .level-buttons input.level-radio-button.checked,.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .level-buttons-container .level-buttons input.level-radio-button:checked{background-clip:unset}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .level-0-treenode>.rc-tree-switcher i svg path{fill:#e0e0e0}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-focused:not(.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-active-focused){border-color:#0ff}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode{margin:0;padding:0;line-height:24px;white-space:nowrap;list-style:none;outline:0}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button,.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input{padding:0;margin:0}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button{height:24px;line-height:24px;border:1px solid transparent;color:#e0e0e0;background:transparent;background-color:transparent;vertical-align:top;font-size:14px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input{display:block;height:26px;box-sizing:border-box}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input .title-input{font-size:14px;height:24px;line-height:24px;width:calc(100% - 60px);margin-right:10px;background-color:#d3d3d3;color:#000;border-radius:4px;outline:none;padding:4px 0 4px 4px;border:1px solid #d3d3d3}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input .title-input:focus{border:1px solid #9bb7d6}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input .title-save-button{background-color:#555;border:1px solid #555;color:#d3d3d3;border-radius:3px;width:50px;height:24px;line-height:20px;font-size:13px;vertical-align:top;margin:0;padding:0}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input .title-save-button:hover{background-color:#626262;border:1px solid #626262}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .draggable{color:#333;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none;-khtml-user-drag:element;-webkit-user-drag:element;border:2px solid transparent}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode.drag-over>.draggable{color:#fff;background-color:#316ac5;border:2px solid #316ac5;opacity:.8}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode.drag-over-gap-top>.draggable{border-top:2px solid #00f}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode.drag-over-gap-bottom>.draggable{border-bottom:2px solid #00f}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode.filter-node>.rc-tree-node-content-wrapper{color:#a60000!important;font-weight:700!important}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode ul{margin:0;padding-left:35px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .rc-tree-node-content-wrapper{width:calc(100% - 20px);display:inline-block;margin:0;padding:0;text-decoration:none;vertical-align:top;cursor:pointer;position:relative}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .rc-tree-node-content-wrapper>span{position:relative;width:100%;display:inline-block}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .rc-tree-node-content-wrapper>span .title-button{position:relative;max-width:calc(100% - 45px);overflow:hidden;text-overflow:ellipsis}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .rc-tree-node-content-wrapper>span .node-menu-icon{position:relative;left:0}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox,.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-switcher{display:inline-block;margin-top:4px;margin-right:6px;vertical-align:middle;background-color:transparent;background-repeat:no-repeat;background-attachment:scroll;border:0;outline:none;cursor:pointer}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-switcher svg{width:15px;height:15px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-switcher.rc-tree-switcher-noop{cursor:auto}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-switcher.rc-tree-switcher_close{transform:rotate(-90deg)}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox{width:13px;height:13px;border:2px solid grey;border-radius:3px;position:relative;left:0;margin:0 10px 0 3px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox-checked{background-color:grey}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox-indeterminate{background-position:-14px -28px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox-disabled{background-position:0 -56px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox.rc-tree-checkbox-checked.rc-tree-checkbox-disabled{background-position:-14px -56px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox.rc-tree-checkbox-indeterminate.rc-tree-checkbox-disabled{position:relative;background:#ccc;border-radius:3px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox.rc-tree-checkbox-indeterminate.rc-tree-checkbox-disabled:after{position:absolute;top:5px;left:3px;width:5px;height:0;border:2px solid #fff;border-top:0;border-left:0;transform:scale(1);content:" "}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree:not(.rc-tree-show-line) .rc-tree-treenode .rc-tree-switcher-noop{background:none}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree.rc-tree-show-line .rc-tree-treenode:not(:last-child)>.rc-tree-switcher-noop{background-position:-56px -18px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree.rc-tree-show-line .rc-tree-treenode:last-child>.rc-tree-switcher-noop{background-position:-56px -36px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-child-tree{display:none}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-child-tree-open{display:block}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-treenode-disabled>a,.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-treenode-disabled>a span,.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-treenode-disabled>span:not(.rc-tree-switcher){color:#767676;cursor:not-allowed}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-treenode-active{background:rgba(0,0,0,.1)}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-node-selected{background-color:#ffe6b0;border:1px solid #ffb951;opacity:.8}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-icon__open{margin-right:2px;vertical-align:top;background-position:-110px -16px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-icon__close{margin-right:2px;vertical-align:top;background-position:-110px 0}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-icon__docu{margin-right:2px;vertical-align:top;background-position:-110px -32px}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-icon__customize{margin-right:2px;vertical-align:top}.vitessce-container.vitessce-theme-dark .sets-manager .sets-manager-tree .rc-tree-indent-unit{display:inline-block;padding-left:18px}.vitessce-container.vitessce-theme-dark .vitessce-tooltip .ant-tooltip-content .ant-tooltip-inner{font-size:12px;background-color:rgba(0,0,0,.95)}.vitessce-container.vitessce-theme-dark .selectable-table{flex:1 1 auto;outline:none}.vitessce-container.vitessce-theme-dark .selectable-table .table-row{display:flex;flex-direction:row;border-bottom:1px solid #444}.vitessce-container.vitessce-theme-dark .selectable-table .table-item{cursor:pointer}.vitessce-container.vitessce-theme-dark .selectable-table .table-item:not(.row-checked):hover{background-color:#2b2b2b}.vitessce-container.vitessce-theme-dark .selectable-table .table-item.row-checked{background-color:#444}.vitessce-container.vitessce-theme-dark .selectable-table .table-item .hidden-input-column{display:none}.vitessce-container.vitessce-theme-dark .selectable-table .table-item .table-cell{padding:0 4px}.vitessce-container.vitessce-theme-dark .selectable-table .table-item .input-container{width:1em}.vitessce-container.vitessce-theme-dark .selectable-table .table-item .input-container label{display:block;margin:0;cursor:pointer}.vitessce-container.vitessce-theme-dark .selectable-table .table-item .input-container input{cursor:pointer}.vitessce-container.vitessce-theme-dark .selectable-table .table-item .input-container input.checkbox,.vitessce-container.vitessce-theme-dark .selectable-table .table-item .input-container input.radio{-webkit-appearance:none;-moz-appearance:none;appearance:none;display:inline-block;width:1em;height:1em;margin:.3em .5em 0;padding:6px!important;background-clip:content-box;border:2px solid #d3d3d3;background-color:#d3d3d3}.vitessce-container.vitessce-theme-dark .selectable-table .table-item .input-container input.checkbox:checked,.vitessce-container.vitessce-theme-dark .selectable-table .table-item .input-container input.radio:checked{background-clip:unset}.vitessce-container.vitessce-theme-dark .selectable-table .table-item .input-container input.radio{border-radius:50%}.vitessce-container.vitessce-theme-dark .selectable-table .table-item .input-container input.checkbox{border-radius:2px}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper{height:calc(100% - 20px)}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper .card-body{width:inherit;height:inherit;padding:5px;background-color:#000}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper .card-body .higlass-lazy-wrapper{width:inherit;height:inherit}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper .card-body .higlass-wrapper-parent{display:block;position:relative;box-sizing:border-box;font-size:12px;color:#333;overflow:hidden}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper{width:inherit;height:inherit;position:relative;display:block;text-align:left;box-sizing:border-box}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass{width:100%;height:100%}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass .react-grid-layout{background-color:transparent!important}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass nav{display:flex}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass input{font-size:12px}.vitessce-container.vitessce-theme-dark .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass .btn{color:#999;font-size:12px}.vitessce-container.vitessce-theme-dark .vega-container{display:flex;flex:1 1 auto;overflow:hidden}.vitessce-container.vitessce-theme-dark .heatmap{width:100%;left:0;position:absolute;padding-right:inherit;padding-left:inherit}.vitessce-container.vitessce-theme-dark .heatmap-container{position:absolute;top:1.25rem;left:1.25rem;width:calc(100% - 2.5rem);height:calc(100% - 2.5rem)}.vitessce-container.vitessce-theme-dark .search-bar{margin-bottom:.25rem;border:0;padding:2px;border-radius:2px}.vitessce-container.vitessce-theme-light.welcome-container{overflow:visible}.vitessce-container.vitessce-theme-light.welcome-container .react-grid-layout,.vitessce-container.vitessce-theme-light.welcome-container .warning-layout{position:relative}.vitessce-container.vitessce-theme-light.welcome-container .row>div>.card{margin:1rem 0}.vitessce-container.vitessce-theme-light .welcome-beta-header{background-color:#93e5c3;padding:1rem}.vitessce-container.vitessce-theme-light .welcome-beta-header p{margin:0;color:#222}.vitessce-container.vitessce-theme-light .welcome-beta-header p a{color:#000;text-decoration:underline;font-weight:600}.vitessce-container.vitessce-theme-light .react-grid-layout,.vitessce-container.vitessce-theme-light .warning-layout{background-color:#fff;height:auto;position:absolute;width:100%}.vitessce-container.vitessce-theme-light .warning-layout{height:100vh}.vitessce-container.vitessce-theme-light .warning-layout .card{margin-left:.5rem}.vitessce-container.vitessce-theme-light .loading-indicator-backdrop{position:absolute;top:0;left:0;z-index:1040;width:100%;height:100%;border-radius:.25rem;background-color:rgba(0,0,0,.5)}.vitessce-container.vitessce-theme-light .loading-indicator-backdrop .loading-indicator-container{display:grid;place-items:center;position:absolute;width:100%;height:100%}.vitessce-container.vitessce-theme-light .react-grid-item{flex-direction:column!important;display:flex!important;padding-right:10px}.vitessce-container.vitessce-theme-light .d-flex{flex-shrink:0}.vitessce-container.vitessce-theme-light .title{color:#333;overflow-x:hidden;display:flex;flex-direction:row;flex-shrink:0}.vitessce-container.vitessce-theme-light .title .title-left{flex-shrink:1;text-overflow:ellipsis;white-space:nowrap}.vitessce-container.vitessce-theme-light .title .title-info{width:100%;text-overflow:ellipsis;white-space:nowrap;overflow:hidden;font-size:80%;opacity:.8;padding:0 .25rem;justify-content:center;line-height:25px;flex-shrink:1;text-align:right}.vitessce-container.vitessce-theme-light .title .title-buttons{display:flex;flex-direction:row;flex-grow:1;flex-shrink:0;justify-content:right}.vitessce-container.vitessce-theme-light .title .title-buttons div{display:inline-block}.vitessce-container.vitessce-theme-light .card{border:1px solid hsla(0,0%,94.5%,.125)}.vitessce-container.vitessce-theme-light .bg-black{background-color:#000;color:#fff}.vitessce-container.vitessce-theme-light .bg-black a{color:#fff}.vitessce-container.vitessce-theme-light .bg-primary{background-color:#f1f1f1;color:#333}.vitessce-container.vitessce-theme-light .bg-primary a{color:#0074d9}.vitessce-container.vitessce-theme-light .bg-secondary{background-color:#f1f1f1;color:#222}.vitessce-container.vitessce-theme-light .scroll{overflow-y:auto}.vitessce-container.vitessce-theme-light .description details,.vitessce-container.vitessce-theme-light .description p,.vitessce-container.vitessce-theme-light .description table,.vitessce-container.vitessce-theme-light .details{font-size:80%;opacity:.8}.vitessce-container.vitessce-theme-light .description details{margin-bottom:6px}.vitessce-container.vitessce-theme-light .description summary{border-bottom:1px solid #fff;cursor:pointer}.vitessce-container.vitessce-theme-light .description .metadata-container{padding-left:14px}.vitessce-container.vitessce-theme-light .description .metadata-container table{width:100%}.vitessce-container.vitessce-theme-light .description .metadata-container table td,.vitessce-container.vitessce-theme-light .description .metadata-container table th{outline:none;padding:2px;max-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;width:50%}.vitessce-container.vitessce-theme-light .description .metadata-container table tr:nth-child(2n){background-color:#fefefe}.vitessce-container.vitessce-theme-light .coll-full,.vitessce-container.vitessce-theme-light .welcome-col-left,.vitessce-container.vitessce-theme-light .welcome-col-right{position:relative;width:100%;padding-right:15px;padding-left:15px}.vitessce-container.vitessce-theme-light .col-full{flex:0 0 100%;max-width:100%}.vitessce-container.vitessce-theme-light .welcome-col-left{flex:0 0 50%;max-width:50%}.vitessce-container.vitessce-theme-light .welcome-col-left .input-group input,.vitessce-container.vitessce-theme-light .welcome-col-left .list-group-item{background-color:#fff}.vitessce-container.vitessce-theme-light .welcome-col-left a{color:#fff}.vitessce-container.vitessce-theme-light .welcome-col-right{flex:0 0 50%;max-width:50%}.vitessce-container.vitessce-theme-light .welcome-col-right .info-paragraph{margin-bottom:0!important}.vitessce-container.vitessce-theme-light .welcome-col-right .info-section-text{margin-top:.5rem}.vitessce-container.vitessce-theme-light .welcome-col-right a{color:#fff}.vitessce-container.vitessce-theme-light .btn.icon{padding:0;height:2em;width:2em;background-color:#fff}.vitessce-container.vitessce-theme-light .btn.icon>svg{vertical-align:middle}.vitessce-container.vitessce-theme-light .roll-up{height:2em;overflow:hidden;background-color:#fff}.vitessce-container.vitessce-theme-light .roll-up:hover{-webkit-animation-name:roll-up;animation-name:roll-up;-webkit-animation-duration:.5s;animation-duration:.5s;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards}@keyframes roll-up{0%{height:2em}to{height:100%}}.vitessce-container.vitessce-theme-light .tool{position:absolute;display:inline;z-index:1000;opacity:.65;color:#000}.vitessce-container.vitessce-theme-light .tool:hover{opacity:.9}.vitessce-container.vitessce-theme-light .radio{-webkit-appearance:none;-moz-appearance:none;appearance:none;display:inline-block;width:1em;height:1em;padding:6px!important;background-clip:content-box;border:2px solid #d3d3d3;background-color:#d3d3d3;border-radius:50%}.vitessce-container.vitessce-theme-light .radio:checked{background-clip:unset}.vitessce-container.vitessce-theme-light .layer-controller-container>div:first-child{margin-top:0!important}.vitessce-container.vitessce-theme-light .channel-container{width:100%;display:flex;position:relative}.vitessce-container.vitessce-theme-light .channel-set-color{display:flex;position:relative;top:5px;width:16px;height:16px;margin-right:24px;cursor:pointer;outline:medium none currentColor;border-radius:3px;box-shadow:inset 0 0 0 1px rgba(0,0,0,.15)}.vitessce-container.vitessce-theme-light .channel-checked{display:flex;position:relative;margin-right:10px}.vitessce-container.vitessce-theme-light .add-image-layer{color:#262626;border:1px dashed #262626}.vitessce-container.vitessce-theme-light pre{color:#333}.vitessce-container.vitessce-theme-light .cell-emphasis-crosshair{z-index:50;position:absolute;pointer-events:none;box-sizing:border-box;background-color:#222}.vitessce-container.vitessce-theme-light .help-tooltip.rc-tooltip{z-index:1060;display:block;max-width:250px;visibility:visible;box-sizing:border-box;margin:0;padding:0;color:rgba(0,0,0,.65);font-size:14px;list-style:none;position:absolute}.vitessce-container.vitessce-theme-light .help-tooltip.rc-tooltip-hidden{display:none}.vitessce-container.vitessce-theme-light .help-tooltip.rc-tooltip .rc-tooltip-inner{border-radius:2px;box-shadow:0 3px 6px -4px hsla(0,0%,39.2%,.12),0 6px 16px 0 hsla(0,0%,39.2%,.08),0 9px 28px 8px hsla(0,0%,39.2%,.05)}.vitessce-container.vitessce-theme-light .help-tooltip.rc-tooltip-placement-top{padding-top:8px}.vitessce-container.vitessce-theme-light .help-tooltip.rc-tooltip-placement-right{padding-left:8px}.vitessce-container.vitessce-theme-light .help-tooltip.rc-tooltip-placement-bottom{padding-top:8px}.vitessce-container.vitessce-theme-light .help-tooltip.rc-tooltip-placement-left{padding-right:8px}.vitessce-container.vitessce-theme-light .help-tooltip.rc-tooltip .rc-tooltip-inner{font-size:10px;min-width:30px;padding:6px 8px;color:#fff;text-align:left;text-decoration:none;word-wrap:break-word;background-color:rgba(0,0,0,.9)}.vitessce-container.vitessce-theme-light .help-tooltip.rc-tooltip .rc-tooltip-arrow{display:none}.vitessce-container.vitessce-theme-light .popover.rc-tooltip{top:0;left:0;z-index:1030;font-weight:400;white-space:normal;text-align:left;cursor:auto;-webkit-user-select:text;-moz-user-select:text;-ms-user-select:text;user-select:text;box-sizing:border-box;margin:0;padding:0;color:rgba(0,0,0,.65);font-size:14px;list-style:none;position:absolute}.vitessce-container.vitessce-theme-light .popover.rc-tooltip:after{position:absolute;background:hsla(0,0%,100%,.01);content:""}.vitessce-container.vitessce-theme-light .popover.rc-tooltip-hidden{display:none}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner{border-radius:2px;box-shadow:0 3px 6px -4px hsla(0,0%,39.2%,.12),0 6px 16px 0 hsla(0,0%,39.2%,.08),0 9px 28px 8px hsla(0,0%,39.2%,.05)}.vitessce-container.vitessce-theme-light .popover.rc-tooltip-placement-top{padding-bottom:10px}.vitessce-container.vitessce-theme-light .popover.rc-tooltip-placement-right{padding-left:10px}.vitessce-container.vitessce-theme-light .popover.rc-tooltip-placement-bottom{padding-top:10px}.vitessce-container.vitessce-theme-light .popover.rc-tooltip-placement-left{padding-right:10px}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-content{padding:0}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner{box-sizing:border-box;background-color:#fff;background-clip:padding-box}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list{list-style-type:none;padding:0;margin-bottom:0}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list dl,.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list ol,.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list ul{margin-top:0;margin-bottom:1rem}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list li button{border:0;padding:4px 16px;cursor:pointer;width:100%;background-color:transparent;border-radius:2px}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list li button span.small{font-size:11px}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list li button:hover{background-color:#ededed}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list li:not(:last-child){border-bottom:1px solid grey}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-list button{-webkit-appearance:button;text-transform:none;overflow:visible;margin:0;font-family:inherit;font-size:14px;line-height:inherit;border-radius:0}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner .popover-menu-color+.popover-menu-list{border-top:1px solid grey}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .popover-menu-color.twitter-picker{box-shadow:none!important;margin:0 auto}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .popover-menu-color.twitter-picker>div:nth-child(3){padding:6px!important;transform:translate(2px)}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .popover-menu-color.twitter-picker>div>div:first-of-type{font-size:12px;width:20px!important}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .popover-menu-color.twitter-picker input{width:60px!important;font-size:12px}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .popover-menu-color.twitter-picker>div>span>div{width:18px!important;height:18px!important}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-inner-content{padding:12px 16px;color:rgba(0,0,0,.65)}.vitessce-container.vitessce-theme-light .popover.rc-tooltip .rc-tooltip-arrow{position:absolute;display:block;width:8px;height:8px;background:transparent;border-style:solid;border-width:4px;transform:rotate(45deg)}.vitessce-container.vitessce-theme-light .popover.rc-tooltip.rc-tooltip-placement-top>.rc-tooltip-content>.rc-tooltip-arrow{bottom:6px;border-color:transparent #fff #fff transparent;box-shadow:3px 3px 7px rgba(0,0,0,.07);left:50%;transform:translateX(-50%) rotate(45deg)}.vitessce-container.vitessce-theme-light .popover.rc-tooltip.rc-tooltip-placement-right>.rc-tooltip-content>.rc-tooltip-arrow{left:6px;border-color:transparent transparent #fff #fff;box-shadow:-3px 3px 7px rgba(0,0,0,.07);top:50%;transform:translateY(-50%) rotate(45deg)}.vitessce-container.vitessce-theme-light .popover.rc-tooltip.rc-tooltip-placement-bottom>.rc-tooltip-content>.rc-tooltip-arrow{top:6px;border-color:#fff transparent transparent #fff;box-shadow:-2px -2px 5px rgba(0,0,0,.06);left:50%;transform:translateX(-50%) rotate(45deg)}.vitessce-container.vitessce-theme-light .popover.rc-tooltip.rc-tooltip-placement-left>.rc-tooltip-content>.rc-tooltip-arrow{right:6px;border-color:#fff #fff transparent transparent;box-shadow:3px -3px 7px rgba(0,0,0,.07);top:50%;transform:translateY(-50%) rotate(45deg)}.vitessce-container.vitessce-theme-light .sets-manager{position:relative;width:100%;display:block;height:auto}.vitessce-container.vitessce-theme-light .sets-manager .set-operation-buttons{background-color:#d3d3d3;border-radius:4px;padding:2px;display:inline-block;position:absolute;bottom:1.75rem;right:.25rem;box-shadow:-2px -2px 5px rgba(0,0,0,.06)}.vitessce-container.vitessce-theme-light .sets-manager .set-operation-buttons button{border:0;background-color:transparent;color:#626262}.vitessce-container.vitessce-theme-light .sets-manager .set-operation-buttons button[disabled]{pointer-events:none}.vitessce-container.vitessce-theme-light .sets-manager .set-operation-buttons button[disabled] svg{fill:silver}.vitessce-container.vitessce-theme-light .sets-manager .set-operation-buttons button svg{fill:#555;vertical-align:top;height:20px;margin-top:1px}.vitessce-container.vitessce-theme-light .sets-manager .set-operation-buttons button:hover,.vitessce-container.vitessce-theme-light .sets-manager .set-operation-buttons button:hover path{color:#2f2f2f;fill:#2f2f2f}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree{position:relative;top:0;left:0;width:100%;height:auto;display:block;padding-right:17px;box-sizing:content-box}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .plus-button{border:0;background-color:transparent;color:#404040;padding:0;font-size:18px;margin-bottom:2rem}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree{padding-left:0;margin:0;border:1px solid transparent}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .node-menu-icon{fill:grey;cursor:pointer;height:14px;position:relative;vertical-align:top;width:32px;top:5.5px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .node-menu-icon:hover{fill:#9a9a9a}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .node-size-label{font-size:12px;color:#0d0d0d}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .level-buttons-container{height:20px;width:100%;position:relative;padding-left:4px;left:0}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .level-buttons-container .level-buttons input.level-radio-button{cursor:pointer;-webkit-appearance:none;-moz-appearance:none;appearance:none;width:12px;height:12px;padding:5px;background-clip:content-box;border:2px solid #4d4d4d;background-color:#4d4d4d;border-radius:6px;position:relative;top:3px;left:0;float:left;margin-right:10px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .level-buttons-container .level-buttons input.level-radio-button.checked,.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .level-buttons-container .level-buttons input.level-radio-button:checked{background-clip:unset}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .level-0-treenode>.rc-tree-switcher i svg path{fill:#404040}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-focused:not(.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-active-focused){border-color:#0ff}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode{margin:0;padding:0;line-height:24px;white-space:nowrap;list-style:none;outline:0}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button,.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input{padding:0;margin:0}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button{height:24px;line-height:24px;border:1px solid transparent;color:#404040;background:transparent;background-color:transparent;vertical-align:top;font-size:14px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input{display:block;height:26px;box-sizing:border-box}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input .title-input{font-size:14px;height:24px;line-height:24px;width:calc(100% - 60px);margin-right:10px;background-color:#d3d3d3;color:#000;border-radius:4px;outline:none;padding:4px 0 4px 4px;border:1px solid #d3d3d3}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input .title-input:focus{border:1px solid #0074d9}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input .title-save-button{background-color:#555;border:1px solid #555;color:#d3d3d3;border-radius:3px;width:50px;height:24px;line-height:20px;font-size:13px;vertical-align:top;margin:0;padding:0}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .title-button-with-input .title-save-button:hover{background-color:#626262;border:1px solid #626262}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .draggable{color:#333;-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;user-select:none;-khtml-user-drag:element;-webkit-user-drag:element;border:2px solid transparent}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode.drag-over>.draggable{color:#fff;background-color:#316ac5;border:2px solid #316ac5;opacity:.8}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode.drag-over-gap-top>.draggable{border-top:2px solid #00f}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode.drag-over-gap-bottom>.draggable{border-bottom:2px solid #00f}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode.filter-node>.rc-tree-node-content-wrapper{color:#a60000!important;font-weight:700!important}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode ul{margin:0;padding-left:35px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .rc-tree-node-content-wrapper{width:calc(100% - 20px);display:inline-block;margin:0;padding:0;text-decoration:none;vertical-align:top;cursor:pointer;position:relative}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .rc-tree-node-content-wrapper>span{position:relative;width:100%;display:inline-block}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .rc-tree-node-content-wrapper>span .title-button{position:relative;max-width:calc(100% - 45px);overflow:hidden;text-overflow:ellipsis}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode .rc-tree-node-content-wrapper>span .node-menu-icon{position:relative;left:0}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox,.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-switcher{display:inline-block;margin-top:4px;margin-right:6px;vertical-align:middle;background-color:transparent;background-repeat:no-repeat;background-attachment:scroll;border:0;outline:none;cursor:pointer}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-switcher svg{width:15px;height:15px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-switcher.rc-tree-switcher-noop{cursor:auto}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-switcher.rc-tree-switcher_close{transform:rotate(-90deg)}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox{width:13px;height:13px;border:2px solid grey;border-radius:3px;position:relative;left:0;margin:0 10px 0 3px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox-checked{background-color:grey}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox-indeterminate{background-position:-14px -28px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox-disabled{background-position:0 -56px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox.rc-tree-checkbox-checked.rc-tree-checkbox-disabled{background-position:-14px -56px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox.rc-tree-checkbox-indeterminate.rc-tree-checkbox-disabled{position:relative;background:#ccc;border-radius:3px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree .rc-tree-treenode span.rc-tree-checkbox.rc-tree-checkbox-indeterminate.rc-tree-checkbox-disabled:after{position:absolute;top:5px;left:3px;width:5px;height:0;border:2px solid #fff;border-top:0;border-left:0;transform:scale(1);content:" "}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree:not(.rc-tree-show-line) .rc-tree-treenode .rc-tree-switcher-noop{background:none}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree.rc-tree-show-line .rc-tree-treenode:not(:last-child)>.rc-tree-switcher-noop{background-position:-56px -18px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree.rc-tree-show-line .rc-tree-treenode:last-child>.rc-tree-switcher-noop{background-position:-56px -36px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-child-tree{display:none}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-child-tree-open{display:block}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-treenode-disabled>a,.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-treenode-disabled>a span,.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-treenode-disabled>span:not(.rc-tree-switcher){color:#767676;cursor:not-allowed}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-treenode-active{background:rgba(0,0,0,.1)}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-node-selected{background-color:#ffe6b0;border:1px solid #ffb951;opacity:.8}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-icon__open{margin-right:2px;vertical-align:top;background-position:-110px -16px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-icon__close{margin-right:2px;vertical-align:top;background-position:-110px 0}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-icon__docu{margin-right:2px;vertical-align:top;background-position:-110px -32px}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-icon__customize{margin-right:2px;vertical-align:top}.vitessce-container.vitessce-theme-light .sets-manager .sets-manager-tree .rc-tree-indent-unit{display:inline-block;padding-left:18px}.vitessce-container.vitessce-theme-light .vitessce-tooltip .ant-tooltip-content .ant-tooltip-inner{font-size:12px;background-color:rgba(0,0,0,.95)}.vitessce-container.vitessce-theme-light .selectable-table{flex:1 1 auto;outline:none}.vitessce-container.vitessce-theme-light .selectable-table .table-row{display:flex;flex-direction:row;border-bottom:1px solid silver}.vitessce-container.vitessce-theme-light .selectable-table .table-item{cursor:pointer}.vitessce-container.vitessce-theme-light .selectable-table .table-item:not(.row-checked):hover{background-color:#dadada}.vitessce-container.vitessce-theme-light .selectable-table .table-item.row-checked{background-color:silver}.vitessce-container.vitessce-theme-light .selectable-table .table-item .hidden-input-column{display:none}.vitessce-container.vitessce-theme-light .selectable-table .table-item .table-cell{padding:0 4px}.vitessce-container.vitessce-theme-light .selectable-table .table-item .input-container{width:1em}.vitessce-container.vitessce-theme-light .selectable-table .table-item .input-container label{display:block;margin:0;cursor:pointer}.vitessce-container.vitessce-theme-light .selectable-table .table-item .input-container input{cursor:pointer}.vitessce-container.vitessce-theme-light .selectable-table .table-item .input-container input.checkbox,.vitessce-container.vitessce-theme-light .selectable-table .table-item .input-container input.radio{-webkit-appearance:none;-moz-appearance:none;appearance:none;display:inline-block;width:1em;height:1em;margin:.3em .5em 0;padding:6px!important;background-clip:content-box;border:2px solid #d3d3d3;background-color:#d3d3d3}.vitessce-container.vitessce-theme-light .selectable-table .table-item .input-container input.checkbox:checked,.vitessce-container.vitessce-theme-light .selectable-table .table-item .input-container input.radio:checked{background-clip:unset}.vitessce-container.vitessce-theme-light .selectable-table .table-item .input-container input.radio{border-radius:50%}.vitessce-container.vitessce-theme-light .selectable-table .table-item .input-container input.checkbox{border-radius:2px}.vitessce-container.vitessce-theme-light .higlass-title-wrapper{height:calc(100% - 20px)}.vitessce-container.vitessce-theme-light .higlass-title-wrapper .card-body{width:inherit;height:inherit;padding:5px;background-color:#f1f1f1}.vitessce-container.vitessce-theme-light .higlass-title-wrapper .card-body .higlass-lazy-wrapper{width:inherit;height:inherit}.vitessce-container.vitessce-theme-light .higlass-title-wrapper .card-body .higlass-wrapper-parent{display:block;position:relative;box-sizing:border-box;font-size:12px;color:#333;overflow:hidden}.vitessce-container.vitessce-theme-light .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper{width:inherit;height:inherit;position:relative;display:block;text-align:left;box-sizing:border-box}.vitessce-container.vitessce-theme-light .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass{width:100%;height:100%}.vitessce-container.vitessce-theme-light .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass .react-grid-layout{background-color:transparent!important}.vitessce-container.vitessce-theme-light .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass nav{display:flex}.vitessce-container.vitessce-theme-light .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass input{font-size:12px}.vitessce-container.vitessce-theme-light .higlass-title-wrapper .card-body .higlass-wrapper-parent .higlass-wrapper .higlass .btn{color:#999;font-size:12px}.vitessce-container.vitessce-theme-light .vega-container{display:flex;flex:1 1 auto;overflow:hidden}.vitessce-container.vitessce-theme-light .heatmap{width:100%;left:0;position:absolute;padding-right:inherit;padding-left:inherit}.vitessce-container.vitessce-theme-light .heatmap-container{position:absolute;top:1.25rem;left:1.25rem;width:calc(100% - 2.5rem);height:calc(100% - 2.5rem)}.vitessce-container.vitessce-theme-light .search-bar{margin-bottom:.25rem;border:0;padding:2px;border-radius:2px} +/*# sourceMappingURL=main.a53cc462.chunk.css.map */ \ No newline at end of file diff -r 000000000000 -r 9f60ef2d586e static/css/main.a53cc462.chunk.css.map --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/static/css/main.a53cc462.chunk.css.map Thu Sep 08 17:23:33 2022 +0000 @@ -0,0 +1,1 @@ +{"version":3,"sources":["index.scss","_app.scss","../../node_modules/higlass/dist/hglib.css","_bootstrap-minimal.scss","_controls.scss","_channels.scss","_error.scss","_plot-tooltips.scss","_help-tooltips.scss","_sets-manager.scss","_selectable-table.scss","_higlass.scss","_vega.scss","_heatmap.scss","_genes.scss"],"names":[],"mappings":"AAAA,wDC6OA,kCAKE,CACA,+BACA,CAAA,6BACA,CAAA,8BAAA,CAAA,0BACA,CAAA,KAIF,QACI,CAAA,eACA,CAAA,iBAGJ,UACI,CAAA,kBACA,CAAA,iBACA,CAAA,iBACA,CAAA,gBACA,CAAA,qBACA,CAAA,4ECrQJ,cAAA,CAAA,oCAAA,CAAA,+BAAA,CAAA,iBAAA,CAAA,cAAA,CAAA,cAAA,CAAA,WAAA,CAAA,+DAAA,CAAA,iFAAA,UAAA,CAAA,mCAAA,CAAA,iFAAA,oBAAA,CAAA,gBAAA,CAAA,qBAAA,CAAA,qFAAA,UAAA,CAAA,WAAA,CAAA,iFAAA,WAAA,CAAA,kBAAA,CAAA,iBAAA,CAAA,+CAAA,CAAA,uFAAA,kBAAA,CAAA,UAAA,CAAA,+EAAA,cAAA,CAAA,iBAAA,CAAA,QAAA,CAAA,mCAAA,CAAA,yEAAA,UAAA,CAAA,WAAA,CAAA,iBAAA,CAAA,SAAA,CAAA,iFAAA,iBAAA,CAAA,qBAAA,CAAA,oBAAA,CAAA,kBAAA,CAAA,kBAAA,CAAA,sFAAA,iBAAA,CAAA,qBAAA,CAAA,6FAAA,oBAAA,CAAA,iBAAA,CAAA,qBAAA,CAAA,qKAAA,iBAAA,CAAA,SAAA,CAAA,YAAA,CAAA,8BAAA,CAAA,SAAA,CAAA,OAA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+FAEF,gBACE,CAAA,kBACA,CAAA,4BACA,CAAA,8FAEF,gBACE,CAAA,kBACA,CAAA,gCACA,CAAA,mGAEF,gBACE,CAAA,kBACA,CAAA,+FAEF,oBACE,CAAA,iBACA,CAAA,mGASZ,cACE,CAAA,gCACA,CAAA,2DClaJ,aACI,CAAA,YACA,CAAA,sEACA,YACI,CAAA,kBACA,CAAA,8BACA,CAAA,uEAEJ,cACI,CAAA,+FACA,wBAIQ,CAAA,mFAGR,uBACI,CAAA,4FAEJ,YACI,CAAA,mFAEJ,aACI,CAAA,wFAEJ,SACI,CAAA,8FACA,aACI,CAAA,QACA,CAAA,cACA,CAAA,8FAEJ,cACI,CAAA,2MACA,uBACI,CAAA,oBACA,CAAA,eACA,CAAA,oBAEA,CAAA,SACA,CAAA,UACA,CAAA,kBACA,CAAA,qBACA,CAAA,2BAEA,CAAA,wBACA,CAAA,wBACA,CAAA,2NAEA,qBACI,CAAA,oGAGR,iBACI,CAAA,uGAEJ,iBACI,CAAA,gECrDpB,wBACI,CAAA,2EACA,aACE,CAAA,cACA,CAAA,WACA,CAAA,wBACA,CAAA,iGACA,aACE,CAAA,cACA,CAAA,mGAEF,aACE,CAAA,iBACA,CAAA,qBACA,CAAA,cACA,CAAA,UACA,CAAA,eACA,CAAA,oHACA,aACE,CAAA,cACA,CAAA,iBACA,CAAA,aACA,CAAA,eACA,CAAA,qBACA,CAAA,6HACA,UACE,CAAA,WACA,CAAA,gJACA,sCACE,CAAA,iIAEF,YACE,CAAA,mIAEF,cACE,CAAA,kIAEF,UACE,CAAA,cACA,CAAA,yDC9Cd,YACI,CAAA,aACA,CAAA,eACA,CAAA,kDCCJ,UACE,CAAA,MACA,CAAA,iBACA,CAAA,qBACA,CAAA,oBACA,CAAA,4DAGF,iBACI,CAAA,WACA,CAAA,YACA,CAAA,yBACA,CAAA,0BACA,CAAA,qDCjBJ,oBACE,CAAA,QACA,CAAA,WACA,CAAA,iBACA","file":"main.a53cc462.chunk.css","sourcesContent":["@import 'colors';\n\n@import 'app';\n@import 'bootstrap-minimal';\n@import 'channels';\n@import 'controls';\n@import 'error';\n@import 'plot-tooltips';\n@import 'help-tooltips';\n@import 'sets-manager';\n@import 'selectable-table';\n@import 'higlass';\n@import 'vega';\n@import 'heatmap';\n@import 'genes';\n\n@mixin vitessce-themable($theme-name, $theme-colors) {\n @include app($theme-name, $theme-colors);\n @include controls($theme-name, $theme-colors);\n @include channels($theme-name, $theme-colors);\n @include error($theme-name, $theme-colors);\n @include plot-tooltips($theme-name, $theme-colors);\n @include help-tooltips($theme-name, $theme-colors);\n @include popover($theme-name, $theme-colors);\n @include sets-manager($theme-name, $theme-colors);\n @include selectable-table($theme-name, $theme-colors);\n @include higlass($theme-name, $theme-colors);\n @include vega($theme-name, $theme-colors);\n @include heatmap($theme-name, $theme-colors);\n @include genes($theme-name, $theme-colors);\n}\n\n.vitessce-container {\n @include bootstrap-minimal;\n position: relative; // So please-wait can be positioned absolutely.\n \n &.vitessce-theme-dark {\n @include vitessce-themable(\"dark\", $colors-dark);\n }\n &.vitessce-theme-light {\n @include vitessce-themable(\"light\", $colors-light);\n }\n}","@import 'colors';\n\n@mixin app($theme-name, $theme-colors) {\n\n &.welcome-container {\n overflow: visible;\n .react-grid-layout, .warning-layout {\n position: relative;\n }\n .row > div > .card {\n margin: 1rem 0;\n }\n }\n\n .welcome-beta-header {\n background-color: #93e5c3;\n padding: 1rem;\n p {\n margin: 0;\n color: #222222;\n a {\n color: #000;\n text-decoration: underline;\n font-weight: 600;\n }\n }\n }\n\n .react-grid-layout, .warning-layout {\n background-color: map-get($theme-colors, \"grid-layout-background\");\n height: auto;\n position: absolute;\n width: 100%;\n }\n\n .warning-layout {\n height: 100vh;\n .card {\n margin-left: 0.5rem;\n }\n }\n\n .loading-indicator-backdrop {\n position: absolute;\n top: 0;\n left: 0;\n z-index: 1040;\n width: 100%;\n height: 100%;\n border-radius: 0.25rem;\n background-color: rgba(0, 0, 0, 0.5);\n\n .loading-indicator-container {\n display: grid;\n place-items: center;\n position: absolute;\n width: 100%;\n height: 100%;\n }\n }\n \n\n /* Flex grid items */\n .react-grid-item {\n /* emulate bootstrap .flex-column: */\n -webkit-box-orient: vertical!important;\n -webkit-box-direction: normal!important;\n -ms-flex-direction: column!important;\n flex-direction: column!important;\n\n /* emulate bootstrap .d-flex: */\n display: -webkit-box!important;\n display: -ms-flexbox!important;\n display: flex!important;\n\n /* So the resize handle position looks correct: */\n padding-right: 10px;\n }\n\n /* Fix grid title rendering on Safari 12.0.\n Inspired by https://stackoverflow.com/questions/32689686/overlapping-css-flexbox-items-in-safari */\n .d-flex {\n flex-shrink: 0;\n }\n\n /* Tool styles */\n .title {\n color: map-get($theme-colors, \"primary-foreground\");\n overflow-x: hidden;\n display: flex;\n flex-direction: row;\n flex-shrink: 0;\n .title-left {\n flex-shrink: 1;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .title-info {\n width: 100%;\n text-overflow: ellipsis;\n white-space: nowrap;\n overflow: hidden;\n font-size: 80%;\n opacity: .8;\n padding: 0 0.25rem;\n justify-content: center;\n line-height: 25px;\n flex-shrink: 1;\n text-align: right;\n }\n .title-buttons {\n display: flex;\n flex-direction: row;\n flex-grow: 1;\n flex-shrink: 0;\n justify-content: right;\n div {\n display: inline-block;\n }\n }\n \n }\n\n .card {\n border: 1px solid map-get($theme-colors, \"card-border\");\n }\n\n .bg-black {\n background-color: map-get($global-colors, \"black\");\n color: map-get($global-colors, \"white\");\n a {\n color: map-get($global-colors, \"white\");\n }\n }\n\n .bg-primary {\n background-color: map-get($theme-colors, \"primary-background\");\n color: map-get($theme-colors, \"primary-foreground\");\n a {\n color: map-get($theme-colors, \"primary-foreground-active\");\n }\n }\n\n .bg-secondary {\n background-color: map-get($theme-colors, \"secondary-background\");\n color: map-get($theme-colors, \"secondary-foreground\");\n }\n\n .scroll {\n overflow-y: auto;\n }\n\n .details {\n font-size: 80%;\n opacity: 0.8;\n }\n\n .description {\n p, details, table {\n font-size: 80%;\n opacity: 0.8;\n }\n details {\n margin-bottom: 6px;\n }\n summary {\n border-bottom: 1px solid lighten(map-get($theme-colors, \"primary-background\"), 10%);\n cursor: pointer;\n }\n .metadata-container {\n padding-left: 14px;\n table {\n width: 100%;\n td, th {\n outline: none;\n padding: 2px 2px;\n max-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n width: 50%;\n }\n tr:nth-child(even) {\n background-color: lighten(map-get($theme-colors, \"primary-background\"), 5%);\n }\n }\n }\n }\n\n .coll-full, .welcome-col-left, .welcome-col-right {\n position: relative;\n width: 100%;\n padding-right: 15px;\n padding-left: 15px;\n }\n\n .col-full {\n -ms-flex: 0 0 100%;\n flex: 0 0 100%;\n max-width: 100%;\n }\n\n .welcome-col-left {\n -ms-flex: 0 0 50%;\n flex: 0 0 50%;\n max-width: 50%;\n\n .list-group-item {\n background-color: map-get($theme-colors, \"primary-background-highlight\");\n }\n\n .input-group input {\n background-color: map-get($theme-colors, \"primary-background-input\");\n }\n a {\n color: #ffffff;\n }\n }\n \n\n .welcome-col-right {\n -ms-flex: 0 0 50%;\n flex: 0 0 50%;\n max-width: 50%;\n .info-paragraph {\n margin-bottom: 0 !important;\n }\n .info-section-text {\n margin-top: 0.5rem\n }\n a {\n color: #ffffff;\n }\n }\n \n}\n\n.react-draggable-transparent-selection .react-grid-item {\n /* These styles prevent text selection during resize drag interactions.\n The react-draggable-transparent-selection class is added to the body \n element during resizing and removed after resizing has finished.\n Not part of mixin because acts outside of .vitessce-container. */\n -webkit-user-select: none !important;\n -khtml-user-select: none !important;\n -moz-user-select: none !important;\n -o-user-select: none !important;\n user-select: none !important;\n}\n\n\nbody {\n margin: 0;\n text-align: left;\n}\n\n.container-fluid {\n width: 100%;\n padding-right: 15px;\n padding-left: 15px;\n margin-right: auto;\n margin-left: auto;\n box-sizing: border-box;\n}",".ContextMenu-module_context-menu-2OwvL{position:fixed;background-color:hsla(0,0%,100%,.95);border:1px solid rgba(0,0,0,.1);border-radius:3px;font-size:12px;cursor:default;padding:3px;-webkit-box-shadow:0 0 3px 0 rgba(0,0,0,.1),0 1px 5px 0 rgba(0,0,0,.05);box-shadow:0 0 3px 0 rgba(0,0,0,.1),0 1px 5px 0 rgba(0,0,0,.05)}.ContextMenu-module_context-menu-dark-2PO31{color:#ccc;background-color:rgba(68,68,68,.97)}.ContextMenu-module_context-menu-icon-I4kiw{display:inline-block;margin-right:3px;vertical-align:middle}.ContextMenu-module_context-menu-icon-I4kiw>svg{width:30px;height:20px}.ContextMenu-module_context-menu-item-1HeVv{padding:2px;white-space:nowrap;border-radius:2px;-webkit-transition:background .15s ease,color .15s ease;-o-transition:background .15s ease,color .15s ease;transition:background .15s ease,color .15s ease}.ContextMenu-module_context-menu-item-1HeVv:hover{background:#337ab7;color:#fff}.ContextMenu-module_context-menu-hr-3yapb{margin-top:5px;margin-bottom:5px;border:0;border-top:1px solid rgba(0,0,0,.1)}.ContextMenu-module_play-icon-R4pIO{width:12px;height:12px;position:absolute;right:5px}.ContextMenu-module_context-menu-span-8EUfZ{margin-right:20px;vertical-align:middle;display:inline-block;line-height:normal;white-space:nowrap}.ContextMenu-module_context-menu-thumbnail-2vHLD{margin-right:10px;border:1px solid #888}.ContextMenu-module_context-menu-thumbnail-inline-1iOcg{display:inline-block;margin-right:10px;vertical-align:middle}.TrackControl-module_track-control-2zDf3,.TrackControl-module_track-control-vertical-2McB_{position:absolute;z-index:1;display:-ms-flexbox;display:flex;background:hsla(0,0%,100%,.75);right:2px;top:2px;border-radius:2.5px;-webkit-box-shadow:0 0 0 1px rgba(0,0,0,.05),0 0 3px 0 rgba(0,0,0,.1);box-shadow:0 0 0 1px rgba(0,0,0,.05),0 0 3px 0 rgba(0,0,0,.1);opacity:0;-webkit-transition:opacity .15s ease,background .15s ease,-webkit-box-shadow .15s ease;transition:opacity .15s ease,background .15s ease,-webkit-box-shadow .15s ease;-o-transition:opacity .15s ease,background .15s ease,box-shadow .15s ease;transition:opacity .15s ease,background .15s ease,box-shadow .15s ease;transition:opacity .15s ease,background .15s ease,box-shadow .15s ease,-webkit-box-shadow .15s ease}.TrackControl-module_track-control-dark-fP2uZ,.TrackControl-module_track-control-dark-fP2uZ .TrackControl-module_track-control-active-2JD9i{background:rgba(40,40,40,.85)}.TrackControl-module_track-control-vertical-2McB_{-ms-flex-direction:column-reverse;flex-direction:column-reverse}.TrackControl-module_track-control-left-zHd9W{left:2px;right:auto}.TrackControl-module_track-control-active-2JD9i,.TrackControl-module_track-control-vertical-active-1QCKn{opacity:1;z-index:1}.TrackControl-module_track-control-active-2JD9i:hover,.TrackControl-module_track-control-vertical-active-1QCKn:hover{background:#fff;-webkit-box-shadow:0 0 0 1px rgba(0,0,0,.1),0 0 3px 0 rgba(0,0,0,.2);box-shadow:0 0 0 1px rgba(0,0,0,.1),0 0 3px 0 rgba(0,0,0,.2)}.TrackControl-module_track-control-dark-fP2uZ.TrackControl-module_track-control-active-2JD9i:hover{background:rgba(34,34,34,.95)}.TrackControl-module_track-control-padding-right-2p6Lp{right:80px}.TrackControl-module_track-control-button-2fdIb{width:20px;height:20px;padding:4px;cursor:pointer;opacity:.66;-webkit-transition:background .15s ease,color .15s ease,opacity .15s ease;-o-transition:background .15s ease,color .15s ease,opacity .15s ease;transition:background .15s ease,color .15s ease,opacity .15s ease}.TrackControl-module_track-control-button-2fdIb:hover{color:#fff;background:#337ab7;opacity:1}.TrackControl-module_track-control-button-2fdIb:first-child{border-radius:2.5px 0 0 2.5px}.TrackControl-module_track-control-button-2fdIb:last-child{border-radius:0 2.5px 2.5px 0}.TrackControl-module_track-control-dark-fP2uZ .TrackControl-module_track-control-button-2fdIb{color:#ccc}.TrackControl-module_track-control-dark-fP2uZ .TrackControl-module_track-control-button-2fdIb:hover{color:#fff;background:#337ab7;opacity:1}.TrackControl-module_track-control-button-vertical-1s22z:first-child{border-radius:0 0 2.5px 2.5px}.TrackControl-module_track-control-button-vertical-1s22z:last-child{border-radius:2.5px 2.5px 0 0}.CenterTrack-module_center-track-3ptRW{position:relative;background:transparent}.CenterTrack-module_center-track-container-2ELhp{position:absolute;z-index:1}.Track-module_track-range-selection-1yrDf{position:absolute;z-index:-1;opacity:0;-webkit-transition:opacity .15s ease;-o-transition:opacity .15s ease;transition:opacity .15s ease}.Track-module_track-range-selection-active-1oljJ{z-index:1;opacity:1}.Track-module_track-range-selection-group-inactive-YNRM4{display:none}.Track-module_track-range-selection-group-brush-selection-2VYDl{outline:2px solid rgba(0,0,0,.33);fill:#000;fill-opacity:.1}.DragListeningDiv-module_drag-listening-div-active-3wpRk{z-index:10;-webkit-box-shadow:inset 0 0 3px 0 red;box-shadow:inset 0 0 3px 0 red}.GalleryTracks-module_gallery-tracks-3tsUO{position:relative;top:0;left:0;width:100%;height:100%}.GalleryTracks-module_gallery-track-eGKoq{position:absolute;-webkit-box-sizing:border-box;box-sizing:border-box;top:0;right:0;bottom:0;left:0}.GalleryTracks-module_gallery-invisible-track-1hMJp,.GalleryTracks-module_gallery-sub-track-z1HEh{position:absolute}.TiledPlot-module_tiled-plot-uFHiB{position:relative;-ms-flex:1 1;flex:1 1;overflow:hidden}.TiledPlot-module_horizontalList-1c1P8{display:-ms-flexbox;display:flex;width:600px;height:300px;white-space:nowrap}.TiledPlot-module_list-24zgV{width:400px;height:600px;overflow:hidden;-webkit-overflow-scrolling:touch}.TiledPlot-module_stylizedList-Mt4JL{position:relative;z-index:0;background-color:#f3f3f3;outline:none}.TiledPlot-module_stylizedItem-2bQBK{position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;width:100%;background-color:transparent;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;color:#333;font-weight:400}.TiledPlot-module_stylizedHelper-3IVEu{-webkit-box-shadow:0 5px 5px -5px rgba(0,0,0,.2),0 -5px 5px -5px rgba(0,0,0,.2);box-shadow:0 5px 5px -5px rgba(0,0,0,.2),0 -5px 5px -5px rgba(0,0,0,.2);background-color:hsla(0,0%,100%,.8);cursor:row-resize}.TiledPlot-module_stylizedHelper-3IVEu.TiledPlot-module_horizontalItem-2-ZjU{cursor:col-resize}.TiledPlot-module_horizontalItem-2-ZjU{display:-ms-flexbox;display:flex;-ms-flex-negative:0;flex-shrink:0;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.TiledPlot-module_resizable-track-2oLT9{width:100%;height:100%}path.TiledPlot-module_domain-qYw6K{stroke-width:0px}.TrackRenderer-module_track-renderer-3TM7n{position:relative}.TrackRenderer-module_track-renderer-element-2i16D,.TrackRenderer-module_track-renderer-events-3tVM2{position:absolute;top:0;right:0;bottom:0;left:0;z-index:-1}.TrackRenderer-module_track-renderer-events-3tVM2{z-index:1}.Button-module_button-3YXsQ{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-webkit-box-sizing:border-box;box-sizing:border-box;padding:.5em;color:#000;font-size:1em;line-height:1em;border:0;border-radius:2.5px;background:#fff;-webkit-box-shadow:0 0 0 1px #ccc;box-shadow:0 0 0 1px #ccc;-webkit-transition:background .15s ease,-webkit-transform .15s ease,-webkit-box-shadow .15s ease;transition:background .15s ease,-webkit-transform .15s ease,-webkit-box-shadow .15s ease;-o-transition:transform .15s ease,box-shadow .15s ease,background .15s ease;transition:transform .15s ease,box-shadow .15s ease,background .15s ease;transition:transform .15s ease,box-shadow .15s ease,background .15s ease,-webkit-transform .15s ease,-webkit-box-shadow .15s ease;-webkit-appearance:none}.Button-module_button-3YXsQ:hover{background:#f2f2f2;-webkit-box-shadow:0 0 0 1px #ccc;box-shadow:0 0 0 1px #ccc}.Button-module_button-3YXsQ:focus{-webkit-box-shadow:0 0 0 2px #0089ff;box-shadow:0 0 0 2px #0089ff}.Button-module_button-3YXsQ:active{-webkit-transform:scale(.9);-ms-transform:scale(.9);transform:scale(.9)}.Button-module_button-3YXsQ:active,.Button-module_button-3YXsQ:focus,.Button-module_button-3YXsQ:hover{cursor:pointer;outline:none}.Button-module_button-shortcut-1zMAn{padding:.1em 5px;color:#999;font-size:.8em;-webkit-transition:color .15s ease;-o-transition:color .15s ease;transition:color .15s ease}.Cross-module_cross-3WYME{position:relative;width:1em;height:1em}.Cross-module_cross-3WYME:after,.Cross-module_cross-3WYME:before{content:\"\";display:block;position:absolute;top:50%;left:0;width:1em;height:1px;background:#000;-webkit-transform-origin:center;-ms-transform-origin:center;transform-origin:center}.Cross-module_cross-3WYME:before{-webkit-transform:translateY(-50%) rotate(45deg);-ms-transform:translateY(-50%) rotate(45deg);transform:translateY(-50%) rotate(45deg)}.Cross-module_cross-3WYME:after{-webkit-transform:translateY(-50%) rotate(-45deg);-ms-transform:translateY(-50%) rotate(-45deg);transform:translateY(-50%) rotate(-45deg)}.Modal-module_modal-background-3vDy1{position:absolute;z-index:1000;top:0;right:0;bottom:0;left:0;background:rgba(0,0,0,.666);-webkit-animation:Modal-module_fade-in-3Nm-O .2s ease 1;animation:Modal-module_fade-in-3Nm-O .2s ease 1;-webkit-transition:opacity .2s ease;-o-transition:opacity .2s ease;transition:opacity .2s ease}.Modal-module_modal-hide-3huBg{opacity:0}.Modal-module_modal-wrap-1HWNn{position:absolute;top:20px;right:20px;bottom:20px;left:20px}.Modal-module_modal-window-1XZAq{position:relative;width:100%;max-width:640px;max-height:100%;margin-left:auto;margin-right:auto;color:#000;border-radius:5px;background:#fff;-webkit-animation:Modal-module_fade-scale-in-11Dkx .2s ease 1;animation:Modal-module_fade-scale-in-11Dkx .2s ease 1}.Modal-module_modal-window-max-height-CZYCl{height:100%}.Modal-module_modal-content-2xb_x{padding:10px}@-webkit-keyframes Modal-module_fade-in-3Nm-O{0%{opacity:0}to{opacity:1}}@keyframes Modal-module_fade-in-3Nm-O{0%{opacity:0}to{opacity:1}}@-webkit-keyframes Modal-module_fade-scale-in-11Dkx{0%{opacity:0;-webkit-transform:scale(.5);transform:scale(.5)}to{opacity:1;-webkit-transform:scale(1);transform:scale(1)}}@keyframes Modal-module_fade-scale-in-11Dkx{0%{opacity:0;-webkit-transform:scale(.5);transform:scale(.5)}to{opacity:1;-webkit-transform:scale(1);transform:scale(1)}}.Dialog-module_dialog-header-2mk2M{position:relative;z-index:2;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;margin:0 -10px 10px;padding:0 10px 10px;border-bottom:1px solid #ccc}.Dialog-module_dialog-header-2mk2M h3{margin:0;padding:0;font-size:20px;line-height:1em}.Dialog-module_dialog-header-2mk2M button{font-size:10px}.Dialog-module_dialog-main-max-height-1EAb2{position:absolute;z-index:1;top:40px;right:0;bottom:50px;left:0;padding:10px;overflow:auto}.Dialog-module_dialog-footer-1BnEv,.Dialog-module_dialog-footer-max-height-KjDek{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;margin:10px -10px 0;padding:10px 10px 0;border-top:1px solid #ccc}.Dialog-module_dialog-footer-1BnEv button,.Dialog-module_dialog-footer-max-height-KjDek button{font-size:14px}.Dialog-module_dialog-footer-max-height-KjDek{position:absolute;z-index:2;left:10px;right:10px;bottom:10px}.tileset-finder-label{font-weight:700}.tileset-finder-search-box{margin-left:10px}.tileset-finder-search-bar{display:-ms-flexbox;display:flex;margin-left:5px;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-align:center;align-items:center}.tileset-finder-checkbox-tree{margin:5px;padding:3px;border:1px solid #aaa;border-radius:5px}.react-checkbox-tree{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;font-size:14px}.react-checkbox-tree>ol{-ms-flex:1 1 auto;flex:1 1 auto}.react-checkbox-tree ol{margin:0;padding-left:0;list-style-type:none}.react-checkbox-tree ol ol{padding-left:24px}.react-checkbox-tree button{line-height:normal;color:inherit}.react-checkbox-tree button:focus{outline:none}.react-checkbox-tree button:disabled{cursor:not-allowed}.react-checkbox-tree .rct-bare-label{cursor:default}.react-checkbox-tree label{margin-bottom:0;cursor:pointer;font-weight:400}.react-checkbox-tree label:hover{background:rgba(51,51,204,.1)}.react-checkbox-tree label:active{background:rgba(51,51,204,.15)}.react-checkbox-tree:not(.rct-native-display) input{display:none}.react-checkbox-tree.rct-native-display input{margin:0 5px}.react-checkbox-tree .rct-icon{font-family:FontAwesome;font-style:normal}.rct-disabled>.rct-text>label{opacity:.75;cursor:not-allowed}.rct-disabled>.rct-text>label:active,.rct-disabled>.rct-text>label:hover{background:transparent}.rct-text{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.rct-options{-ms-flex:0 0 auto;flex:0 0 auto;margin-left:.5rem;text-align:right}.rct-option{opacity:.75;border:0;background:none;cursor:pointer;padding:0 4px;font-size:18px}.rct-option:hover{opacity:1}.rct-option+.rct-option{margin-left:2px}.rct-checkbox,.rct-collapse,.rct-node-icon{padding:0 5px}.rct-checkbox *,.rct-collapse *,.rct-node-icon *{display:inline-block;margin:0;width:14px}.rct-collapse{border:0;background:none;line-height:normal;color:inherit;font-size:12px}.rct-collapse.rct-collapse-btn{cursor:pointer}.rct-collapse>.rct-icon-expand-close{opacity:.5}.rct-collapse>.rct-icon-expand-close:hover{opacity:1}.rct-native-display .rct-checkbox{display:none}.rct-node-clickable{cursor:pointer}.rct-node-clickable:hover{background:rgba(51,51,204,.1)}.rct-node-clickable:focus{outline:0;background:rgba(51,51,204,.2)}.rct-node-icon{color:#33c}.rct-title{padding:0 5px}.rct-icon-expand-close:before{content:\"\\f054\"}.rct-icon-expand-open:before{content:\"\\f078\"}.rct-icon-uncheck:before{content:\"\\f096\"}.rct-icon-check:before{content:\"\\f046\"}.rct-icon-half-check:before{opacity:.5;content:\"\\f046\"}.rct-icon-leaf:before{content:\"\\f016\"}.rct-icon-parent-open:before{content:\"\\f115\"}.rct-icon-parent-close:before{content:\"\\f114\"}.rct-icon-expand-all:before{content:\"\\f0fe\"}.rct-icon-collapse-all:before{content:\"\\f146\"}.plot-type-selected{background-color:rgba(0,0,255,.3)}.plot-type-container{overflow-y:scroll;padding:3px;max-height:15vh}.plot-type-container,.plot-type-container-empty{margin:5px;border:1px solid #aaa;border-radius:5px}.plot-type-container-empty{padding:3px 8px;background-color:#e8e8e8}.plot-type-item{cursor:pointer}.plot-type-item:not(.plot-type-selected):hover{background-color:rgba(51,51,204,.1)}.track-thumbnail{width:30px;height:20px;display:inline-block;margin-right:10;vertical-align:middle}.track-thumbnail>svg{width:20px;height:20px}.AddTrackDialog-module_collapse-toggle-icon-1Of5_:before{font-family:Glyphicons Halflings;content:\"\\E159\";float:left;padding-right:3px}.AddTrackDialog-module_collapse-toggle-icon-1Of5_.AddTrackDialog-module_collapsed-1ifB1:before{content:\"\\E158\"}.AddTrackDialog-module_modal-title-1Atka{font-family:Roboto;font-weight:700}.AddTrackDialog-module_modal-container-14d_4{position:relative}.AddTrackDialog-module_modal-container-14d_4 .AddTrackDialog-module_modal-backdrop-ZrVQg,.AddTrackDialog-module_modal-container-14d_4 .AddTrackDialog-module_modal-bZqLI{position:absolute}.AddTrackDialog-module_modal-dialog-3bKDk{position:relative;display:table;overflow-y:auto;overflow-x:auto;width:600px;min-width:300px;margin:auto}.DraggableDiv-module_bottom-right-handle-o7UYG,.DraggableDiv-module_top-right-handle-oUk0R{border-right:solid #000;border-top:solid #000}.DraggableDiv-module_bottom-left-handle-FO7d4,.DraggableDiv-module_top-left-handle-R5Zui{border-left:solid #000;border-top:solid #000}.DraggableDiv-module_bottom-draggable-handle-3olLp,.DraggableDiv-module_left-draggable-handle-2gpow,.DraggableDiv-module_right-draggable-handle-2Sriq,.DraggableDiv-module_top-draggable-handle-3W5bP{position:absolute;opacity:0;-webkit-transition:opacity .15s ease,-webkit-transform .15s ease;transition:opacity .15s ease,-webkit-transform .15s ease;-o-transition:transform .15s ease,opacity .15s ease;transition:transform .15s ease,opacity .15s ease;transition:transform .15s ease,opacity .15s ease,-webkit-transform .15s ease}.DraggableDiv-module_draggable-div-2eWml{background-color:transparent;-webkit-box-sizing:border-box;box-sizing:border-box}.DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_top-draggable-handle-grabber-2mVDE{width:10px;height:4px;border-top:1px solid #000;border-bottom:1px solid #000}.DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_top-draggable-handle-grabber-2mVDE{margin:4px 7px}.DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_right-draggable-handle-grabber-1mtC0{width:4px;height:10px;border-left:1px solid #000;border-right:1px solid #000}.DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_right-draggable-handle-grabber-1mtC0{margin:7px 4px}.DraggableDiv-module_draggable-div-2eWml:hover .DraggableDiv-module_bottom-draggable-handle-3olLp,.DraggableDiv-module_draggable-div-2eWml:hover .DraggableDiv-module_left-draggable-handle-2gpow,.DraggableDiv-module_draggable-div-2eWml:hover .DraggableDiv-module_right-draggable-handle-2Sriq,.DraggableDiv-module_draggable-div-2eWml:hover .DraggableDiv-module_top-draggable-handle-3W5bP{opacity:.5;background:hsla(0,0%,100%,.75);-webkit-box-shadow:0 0 3px 1px hsla(0,0%,100%,.75);box-shadow:0 0 3px 1px hsla(0,0%,100%,.75);border-radius:3px}.DraggableDiv-module_bottom-draggable-handle-3olLp:active,.DraggableDiv-module_bottom-draggable-handle-3olLp:hover,.DraggableDiv-module_left-draggable-handle-2gpow:active,.DraggableDiv-module_left-draggable-handle-2gpow:hover,.DraggableDiv-module_right-draggable-handle-2Sriq:active,.DraggableDiv-module_right-draggable-handle-2Sriq:hover,.DraggableDiv-module_top-draggable-handle-3W5bP:active,.DraggableDiv-module_top-draggable-handle-3W5bP:hover{opacity:1!important;-webkit-transform:scale(2);-ms-transform:scale(2);transform:scale(2)}.DraggableDiv-module_bottom-draggable-handle-3olLp:active .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_bottom-draggable-handle-3olLp:active .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_bottom-draggable-handle-3olLp:active .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.DraggableDiv-module_bottom-draggable-handle-3olLp:active .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.DraggableDiv-module_bottom-draggable-handle-3olLp:hover .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_bottom-draggable-handle-3olLp:hover .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_bottom-draggable-handle-3olLp:hover .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.DraggableDiv-module_bottom-draggable-handle-3olLp:hover .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.DraggableDiv-module_left-draggable-handle-2gpow:active .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_left-draggable-handle-2gpow:active .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_left-draggable-handle-2gpow:active .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.DraggableDiv-module_left-draggable-handle-2gpow:active .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.DraggableDiv-module_left-draggable-handle-2gpow:hover .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_left-draggable-handle-2gpow:hover .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_left-draggable-handle-2gpow:hover .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.DraggableDiv-module_left-draggable-handle-2gpow:hover .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.DraggableDiv-module_right-draggable-handle-2Sriq:active .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_right-draggable-handle-2Sriq:active .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_right-draggable-handle-2Sriq:active .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.DraggableDiv-module_right-draggable-handle-2Sriq:active .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.DraggableDiv-module_right-draggable-handle-2Sriq:hover .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_right-draggable-handle-2Sriq:hover .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_right-draggable-handle-2Sriq:hover .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.DraggableDiv-module_right-draggable-handle-2Sriq:hover .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.DraggableDiv-module_top-draggable-handle-3W5bP:active .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_top-draggable-handle-3W5bP:active .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_top-draggable-handle-3W5bP:active .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.DraggableDiv-module_top-draggable-handle-3W5bP:active .DraggableDiv-module_top-draggable-handle-grabber-2mVDE,.DraggableDiv-module_top-draggable-handle-3W5bP:hover .DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k,.DraggableDiv-module_top-draggable-handle-3W5bP:hover .DraggableDiv-module_left-draggable-handle-grabber-1Pqhc,.DraggableDiv-module_top-draggable-handle-3W5bP:hover .DraggableDiv-module_right-draggable-handle-grabber-1mtC0,.DraggableDiv-module_top-draggable-handle-3W5bP:hover .DraggableDiv-module_top-draggable-handle-grabber-2mVDE{-webkit-box-shadow:0 0 3px 1px #0089ff;box-shadow:0 0 3px 1px #0089ff;background:#0089ff}.DraggableDiv-module_bottom-draggable-handle-3olLp,.DraggableDiv-module_top-draggable-handle-3W5bP{height:12px;cursor:row-resize}.DraggableDiv-module_left-draggable-handle-2gpow,.DraggableDiv-module_right-draggable-handle-2Sriq{width:12px;cursor:col-resize}.HorizontalTiledPlot-module_horizontal-tiled-plot-3EK65,.VerticalTiledPlot-module_vertical-tiled-plot-R3sb7{position:relative}.GenomePositionSearchBox-module_genome-position-search-focus-23by2,.GenomePositionSearchBox-module_genome-position-search-SYccr{position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:stretch;align-items:stretch;height:100%;margin-bottom:0;font-size:13.71429px;-webkit-transition:font-size .15s ease,-webkit-box-shadow .15s ease;transition:font-size .15s ease,-webkit-box-shadow .15s ease;-o-transition:box-shadow .15s ease,font-size .15s ease;transition:box-shadow .15s ease,font-size .15s ease;transition:box-shadow .15s ease,font-size .15s ease,-webkit-box-shadow .15s ease}.GenomePositionSearchBox-module_genome-position-search-focus-23by2{-webkit-box-shadow:0 0 0 1px #337ab7,0 0 3px 1px #337ab7;box-shadow:0 0 0 1px #337ab7,0 0 3px 1px #337ab7}.GenomePositionSearchBox-module_genome-position-search-bar-1_0ZU{position:relative;-webkit-box-sizing:border-box;box-sizing:border-box;width:100%;height:100%;padding:3px;color:#666;font-size:inherit;line-height:24px;border:0;border-radius:3px 0 0 3px;background:transparent}.GenomePositionSearchBox-module_genome-position-search-bar-1_0ZU:focus{outline:none;color:#000}.GenomePositionSearchBox-module_genome-position-search-dark-EML2e .GenomePositionSearchBox-module_genome-position-search-bar-1_0ZU:focus{color:#e5e5e5}.GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ,.GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk{display:block;height:100%;padding:0 8px!important;color:#999;border:0!important;border-radius:0!important;background:transparent;-webkit-transition:background .15s ease,color .15s ease;-o-transition:background .15s ease,color .15s ease;transition:background .15s ease,color .15s ease}.GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ:active,.GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ:focus,.GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ:hover,.GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk,.GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk:active,.GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk:focus,.GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk:hover{color:#fff;background:#337ab7}.GenomePositionSearchBox-module_genome-position-search-bar-icon-14AEk,.GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-webkit-transition:color .15s ease;-o-transition:color .15s ease;transition:color .15s ease}.GenomePositionSearchBox-module_genome-position-search-bar-icon-14AEk:first-child,.GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z:first-child{margin-left:6px;margin-right:2px}.GenomePositionSearchBox-module_genome-position-search-bar-icon-14AEk span,.GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z span{display:block;margin-top:-2px}.GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z{color:#337ab7}.GenomePositionSearchBox-module_genome-position-search-bar-suggestions-SrIoU{position:fixed;border-radius:3px;-webkit-box-shadow:0 0 3px 0 rgba(0,0,0,.1),0 1px 5px 0 rgba(0,0,0,.05);box-shadow:0 0 3px 0 rgba(0,0,0,.1),0 1px 5px 0 rgba(0,0,0,.05);background-color:hsla(0,0%,100%,.95);border:1px solid rgba(0,0,0,.1);padding:2px 0;font-size:90%;overflow:auto;max-height:50%}.GenomePositionSearchBox-module_btn-2bTUd{display:inline-block;margin-bottom:0;font-size:13.71429px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.GenomePositionSearchBox-module_btn-sm-2Ltms{font-size:12px;line-height:1.5;border-radius:3px}.GenomePositionSearchBox-module_btn-default-2pap4{color:#666;background-color:#fff;border-color:#ccc}.GenomePositionSearchBox-module_btn-default-2pap4:hover{color:#000;background:#ccc}.GenomePositionSearchBox-module_btn-default-2pap4:active,.GenomePositionSearchBox-module_btn-default-2pap4:focus{color:#fff;border-color:#000;background:#000}.GenomePositionSearchBox-module_genome-position-search-SYccr .GenomePositionSearchBox-module_btn-2bTUd{border-radius:0 3px 3px 0}.ExportLinkDialog-module_export-link-dialog-wrapper-ldYlL{display:-ms-flexbox;display:flex}.ExportLinkDialog-module_export-link-dialog-wrapper-ldYlL input{-ms-flex-positive:1;flex-grow:1}.AddTrackPositionMenu-module_add-track-position-table-RHODc{border-collapse:collapse;margin:5px;color:#666}.AddTrackPositionMenu-module_add-track-position-table-dark-_B9fu{color:#ccc}.AddTrackPositionMenu-module_add-track-position-other-lIGbb{outline:none}.AddTrackPositionMenu-module_add-track-position-top-center-2Dw4e{min-width:80px;min-height:20px;text-align:center;outline:none;border-top:1px solid #999;border-left:1px solid #999;border-right:1px solid #999;border-radius:2px 2px 0 0}.AddTrackPositionMenu-module_add-track-position-top-center-2Dw4e:hover{color:#fff;background-color:#337ab7}.AddTrackPositionMenu-module_add-track-position-middle-left-2ycaN{min-width:40px;text-align:center;outline:none;border-top:1px solid #999;border-left:1px solid #999;border-bottom:1px solid #999;border-radius:2px 0 0 2px}.AddTrackPositionMenu-module_add-track-position-middle-left-2ycaN:hover{background-color:#337ab7;color:#fff}.AddTrackPositionMenu-module_add-track-position-middle-right-Qqjnn{min-width:40px;text-align:center;outline:none;border-top:1px solid #999;border-right:1px solid #999;border-bottom:1px solid #999;border-radius:0 2px 2px 0}.AddTrackPositionMenu-module_add-track-position-middle-right-Qqjnn:hover{background-color:#337ab7;color:#fff}.AddTrackPositionMenu-module_add-track-position-middle-middle-2YFZd{text-align:center;outline:none;border:1px solid #999}.AddTrackPositionMenu-module_add-track-position-middle-middle-2YFZd:hover{background-color:#337ab7;color:#fff}.AddTrackPositionMenu-module_add-track-position-bottom-middle-3ityE{min-height:20px;text-align:center;outline:none;border-left:1px solid #999;border-right:1px solid #999;border-bottom:1px solid #999;border-radius:0 0 2px 2px}.AddTrackPositionMenu-module_add-track-position-bottom-middle-3ityE:hover{background-color:#337ab7;color:#fff}.AddTrackPositionMenu-module_add-track-position-span-2hbwE{margin:5px}.ViewHeader-module_multitrack-header-3XnZx,.ViewHeader-module_multitrack-header-focus-3akkN,.ViewHeader-module_multitrack-header-squeazed-GHIVd{position:relative;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;height:24px;margin-top:4px;margin-bottom:4px;color:#999;font-size:12px;line-height:24px;vertical-align:middle;border:0;border-radius:3px;background:#e5e5e5;-webkit-transition:height .15s ease,margin .15s ease;-o-transition:height .15s ease,margin .15s ease;transition:height .15s ease,margin .15s ease}.ViewHeader-module_multitrack-header-dark-97tZt{background:#222}.ViewHeader-module_multitrack-header-focus-3akkN{height:32px;margin-top:0;margin-bottom:0}.ViewHeader-module_multitrack-header-id-3YURk{padding-left:3px}.ViewHeader-module_multitrack-header-id-3YURk:before{content:\"ID:\";font-weight:700;padding-right:5px}.ViewHeader-module_multitrack-header-left-Qj9Sm{display:-ms-flexbox;display:flex;-ms-flex-positive:1;flex-grow:1}.ViewHeader-module_multitrack-header-grabber-3jrIz,.ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:24px;height:100%;cursor:move;border-radius:3px 0 0 3px;-webkit-transition:background .15s ease;-o-transition:background .15s ease;transition:background .15s ease}.ViewHeader-module_multitrack-header-grabber-3jrIz:hover,.ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z:hover{background:#999}.ViewHeader-module_multitrack-header-grabber-3jrIz:hover div,.ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z:hover div{background:#fff}.ViewHeader-module_multitrack-header-grabber-3jrIz div,.ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z div{width:1px;height:50%;margin:1px;background:#999;-webkit-transition:background .15s ease;-o-transition:background .15s ease;transition:background .15s ease}.ViewHeader-module_multitrack-header-dark-97tZt .ViewHeader-module_multitrack-header-grabber-3jrIz div{background:#666}.ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z{width:19.2px}.ViewHeader-module_multitrack-header-search-1X_3_{position:relative;-ms-flex-positive:1;flex-grow:1;height:100%;margin-right:12px}.ViewHeader-module_multitrack-header-search-1X_3_:after{position:absolute;top:3px;bottom:3px;right:-12px;display:block;content:\"\";width:1px;margin:0 6px;background:#ccc}.ViewHeader-module_multitrack-header-dark-97tZt .ViewHeader-module_multitrack-header-search-1X_3_:after{background:#666}.ViewHeader-module_multitrack-header-3XnZx>nav,.ViewHeader-module_multitrack-header-nav-list-2nvcu{display:-ms-flexbox;display:flex}.ViewHeader-module_multitrack-header-icon-16QKZ,.ViewHeader-module_multitrack-header-icon-squeazed-25lkF{width:24px;height:100%;padding:6px;-webkit-transition:background .15s ease,color .15s ease;-o-transition:background .15s ease,color .15s ease;transition:background .15s ease,color .15s ease}.ViewHeader-module_multitrack-header-icon-16QKZ:active,.ViewHeader-module_multitrack-header-icon-16QKZ:focus,.ViewHeader-module_multitrack-header-icon-16QKZ:hover,.ViewHeader-module_multitrack-header-icon-squeazed-25lkF:active,.ViewHeader-module_multitrack-header-icon-squeazed-25lkF:focus,.ViewHeader-module_multitrack-header-icon-squeazed-25lkF:hover{color:#fff;background:#337ab7}.ViewHeader-module_multitrack-header-icon-16QKZ:last-child,.ViewHeader-module_multitrack-header-icon-squeazed-25lkF:last-child{border-radius:0 3px 3px 0}.ViewHeader-module_mouse-tool-selection-1pg2m{color:#fff;border-radius:3px 0 0 3px;background:#337ab7}.ViewHeader-module_multitrack-header-icon-squeazed-25lkF{width:20px 5;padding-left:3px;padding-right:3px}.ViewConfigEditor-module_view-config-editor-header-2nTtX{margin:-10px -10px 0;padding:10px;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;background:#f2f2f2}.ViewConfigEditor-module_view-config-editor-header-2nTtX button{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;font-size:14px;background:#f2f2f2}.ViewConfigEditor-module_view-config-editor-header-2nTtX button:hover{background:#e5e5e5}.ViewConfigEditor-module_view-config-editor-header-2nTtX button:hover span{color:#666}.ViewConfigEditor-module_view-config-editor-2HAFN{position:absolute;top:50px;right:0;bottom:0;left:0;margin:1px 0 0;padding:0;overflow:auto;font-size:12.5px;height:calc(100% - 80px)}.ViewConfigEditor-module_view-config-log-1mYmL{position:absolute;right:0;bottom:0;left:0;margin:1px 0 0;padding:0;min-height:30px;background:#f2f2f2;-webkit-transition:height .15s ease;-o-transition:height .15s ease;transition:height .15s ease}.ViewConfigEditor-module_view-config-log-header-3EbEM{background:#f2f2f2;border-top:1px solid #ccc;border-bottom:1px solid #ccc;padding-left:10px;height:30px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;cursor:pointer;position:sticky;position:-webkit-sticky;top:0}.ViewConfigEditor-module_view-config-log-msg-2-CJZ{background:#f2f2f2;overflow:auto;height:calc(100% - 30px)}.ViewConfigEditor-module_view-config-log-msg-2-CJZ td,.ViewConfigEditor-module_view-config-log-msg-2-CJZ tr{outline:none;vertical-align:top}.ViewConfigEditor-module_view-config-log-msg-2-CJZ .ViewConfigEditor-module_title-3nLH_{font-weight:700;padding-left:8px;padding-top:8px;width:100px}.ViewConfigEditor-module_view-config-log-msg-2-CJZ .ViewConfigEditor-module_Warning-_sgiB{color:orange}.ViewConfigEditor-module_view-config-log-msg-2-CJZ .ViewConfigEditor-module_Success-nclFo{color:green}.ViewConfigEditor-module_view-config-log-msg-2-CJZ .ViewConfigEditor-module_Error-3enaC{color:red}.ViewConfigEditor-module_view-config-log-msg-2-CJZ pre{background:#fff;white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word}.HiGlass-module_higlass-1NHR2{position:relative}.HiGlass-module_higlass-dark-theme-2visd{background:#000}.HiGlass-module_higlass-container-overflow-zNXnY,.HiGlass-module_higlass-scroll-container-overflow-2FS0w,.HiGlass-module_higlass-scroll-container-scroll-2lAU4{position:absolute;top:0;right:0;bottom:0;left:0}.HiGlass-module_higlass-scroll-container-overflow-2FS0w{overflow:hidden}.HiGlass-module_higlass-scroll-container-scroll-2lAU4{overflow-x:hidden;overflow-y:auto}.HiGlass-module_higlass-canvas-_mP9r{position:absolute;width:100%;height:100%}.HiGlass-module_higlass-drawing-surface-3aQQo{position:relative}.HiGlass-module_higlass-svg-JJZbf{position:absolute;width:100%;height:100%;left:0;top:0;pointer-events:none}.HiGlass-module_tiled-area-22H1L{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.HiGlass-module_track-mouseover-menu-1AoaP{position:fixed;z-index:1;margin:17px 0 0 9px;padding:0 .25rem;max-width:50vw;word-wrap:break-word;font-size:.8em;pointer-events:none;background:#fff;border-radius:.25rem;-webkit-box-shadow:0 0 0 1px rgba(0,0,0,.1),0 0 3px 0 rgba(0,0,0,.075),0 0 7px 0 rgba(0,0,0,.05);box-shadow:0 0 0 1px rgba(0,0,0,.1),0 0 3px 0 rgba(0,0,0,.075),0 0 7px 0 rgba(0,0,0,.05)}.higlass .react-grid-layout{position:relative;-webkit-transition:height .2s ease;-o-transition:height .2s ease;transition:height .2s ease}.higlass .react-grid-item{-webkit-transition:all .2s ease;-o-transition:all .2s ease;transition:all .2s ease;-webkit-transition-property:left,top;-o-transition-property:left,top;transition-property:left,top}.higlass .react-grid-item.cssTransforms{-webkit-transition-property:-webkit-transform;transition-property:-webkit-transform;-o-transition-property:transform;transition-property:transform;transition-property:transform,-webkit-transform}.higlass .react-grid-item.resizing{z-index:1;will-change:width,height}.higlass .react-grid-item.react-draggable-dragging{-webkit-transition:none;-o-transition:none;transition:none;z-index:3;will-change:transform}.higlass .react-grid-item.react-grid-placeholder{background:red;opacity:.2;-webkit-transition-duration:.1s;-o-transition-duration:.1s;transition-duration:.1s;z-index:2;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.higlass .react-grid-item>.react-resizable-handle{position:absolute;width:20px;height:20px;bottom:0;right:0;cursor:se-resize}.higlass .react-grid-item>.react-resizable-handle:after{content:\"\";position:absolute;right:3px;bottom:3px;width:5px;height:5px;border-right:2px solid rgba(0,0,0,.4);border-bottom:2px solid rgba(0,0,0,.4)}.higlass .react-resizable{position:relative}.higlass .react-resizable-handle{position:absolute;width:20px;height:20px;background-repeat:no-repeat;background-origin:content-box;-webkit-box-sizing:border-box;box-sizing:border-box;background-image:url(\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHN0eWxlPSJiYWNrZ3JvdW5kLWNvbG9yOiNmZmZmZmYwMCIgd2lkdGg9IjYiIGhlaWdodD0iNiI+PHBhdGggZD0iTTYgNkgwVjQuMmg0LjJWMEg2djZ6IiBvcGFjaXR5PSIuMzAyIi8+PC9zdmc+\");background-position:100% 100%;padding:0 3px 3px 0}.higlass .react-resizable-handle-sw{bottom:0;left:0;cursor:sw-resize;-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.higlass .react-resizable-handle-se{bottom:0;right:0;cursor:se-resize}.higlass .react-resizable-handle-nw{top:0;left:0;cursor:nw-resize;-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.higlass .react-resizable-handle-ne{top:0;right:0;cursor:ne-resize;-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.higlass .react-resizable-handle-e,.higlass .react-resizable-handle-w{top:50%;margin-top:-10px;cursor:ew-resize}.higlass .react-resizable-handle-w{left:0;-webkit-transform:rotate(135deg);-ms-transform:rotate(135deg);transform:rotate(135deg)}.higlass .react-resizable-handle-e{right:0;-webkit-transform:rotate(315deg);-ms-transform:rotate(315deg);transform:rotate(315deg)}.higlass .react-resizable-handle-n,.higlass .react-resizable-handle-s{left:50%;margin-left:-10px;cursor:ns-resize}.higlass .react-resizable-handle-n{top:0;-webkit-transform:rotate(225deg);-ms-transform:rotate(225deg);transform:rotate(225deg)}.higlass .react-resizable-handle-s{bottom:0;-webkit-transform:rotate(45deg);-ms-transform:rotate(45deg);transform:rotate(45deg)}.higlass code[class*=language-],.higlass pre[class*=language-]{color:#393a34;font-family:Consolas,Bitstream Vera Sans Mono,Courier New,Courier,monospace;direction:ltr;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;font-size:.95em;line-height:1.2em;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-ms-hyphens:none;hyphens:none}.higlass code[class*=language-]::-moz-selection,.higlass code[class*=language-] ::-moz-selection,.higlass pre[class*=language-]::-moz-selection,.higlass pre[class*=language-] ::-moz-selection{background:#b3d4fc}.higlass code[class*=language-]::selection,.higlass code[class*=language-] ::selection,.higlass pre[class*=language-]::selection,.higlass pre[class*=language-] ::selection{background:#b3d4fc}.higlass pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto;border:1px solid #ddd;background-color:#fff}.higlass :not(pre)>code[class*=language-]{padding:1px .2em;background:#f8f8f8;border:1px solid #ddd}.higlass .token.cdata,.higlass .token.comment,.higlass .token.doctype,.higlass .token.prolog{color:#998;font-style:italic}.higlass .token.namespace{opacity:.7}.higlass .token.attr-value,.higlass .token.string{color:#e3116c}.higlass .token.operator,.higlass .token.punctuation{color:#393a34}.higlass .token.boolean,.higlass .token.constant,.higlass .token.entity,.higlass .token.inserted,.higlass .token.number,.higlass .token.property,.higlass .token.regex,.higlass .token.symbol,.higlass .token.url,.higlass .token.variable{color:#36acaa}.higlass .language-autohotkey .token.selector,.higlass .token.atrule,.higlass .token.attr-name,.higlass .token.keyword{color:#00a4db}.higlass .language-autohotkey .token.tag,.higlass .token.deleted,.higlass .token.function{color:#9a050f}.higlass .language-autohotkey .token.keyword,.higlass .token.selector,.higlass .token.tag{color:#00009f}.higlass .token.bold,.higlass .token.function,.higlass .token.important{font-weight:700}.higlass .token.italic{font-style:italic}.higlass *{-webkit-box-sizing:border-box;box-sizing:border-box}.higlass .react-resizable-handle{z-index:1}table.table-track-options{border-collapse:collapse;margin-left:auto;margin-right:auto}td.td-track-options{border:1px solid #fff;outline:none;padding:3px;position:relative;font-family:Roboto,sans-serif;font-size:14px;color:#666}.cell-label{position:absolute;left:0;top:0;margin-left:5px;color:#777}.modal-dialog{position:relative;display:table;overflow-y:auto;overflow-x:auto;width:auto;min-width:300px;margin:auto}","@mixin bootstrap-minimal {\n /* This contains only those Bootstrap (v4)\n styles that are required by Vitessce. */\n\n *,\n *::before,\n *::after {\n box-sizing: border-box;\n }\n\n div {\n -webkit-text-size-adjust: 100%;\n -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, \"Noto Sans\", sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\";\n font-size: 1rem;\n font-weight: 400;\n line-height: 1.5;\n text-align: left;\n }\n\n article, aside, figcaption, figure, footer, header, hgroup, main, nav, section {\n display: block;\n }\n\n\n\n h1, h2, h3, h4, h5, h6 {\n margin-top: 0;\n margin-bottom: 0.5rem;\n\n font-weight: 500;\n line-height: 1.2;\n }\n\n p {\n margin-top: 0;\n margin-bottom: 1rem;\n }\n\n ol,\n ul,\n dl {\n margin-top: 0;\n margin-bottom: 0;\n }\n\n\n b,\n strong {\n font-weight: bolder;\n }\n\n small {\n font-size: 80%;\n }\n\n\n a {\n color: #007bff;\n text-decoration: none;\n background-color: transparent;\n }\n\n a:hover {\n color: #0056b3;\n text-decoration: underline;\n }\n\n a:not([href]) {\n color: inherit;\n text-decoration: none;\n }\n\n a:not([href]):hover {\n color: inherit;\n text-decoration: none;\n }\n\n img {\n vertical-align: middle;\n border-style: none;\n }\n\n svg {\n overflow: hidden;\n }\n\n table {\n border-collapse: collapse;\n }\n\n\n th {\n text-align: inherit;\n }\n\n button:focus {\n outline: 1px dotted;\n outline: 5px auto -webkit-focus-ring-color;\n }\n\n input,\n button,\n select,\n optgroup,\n textarea {\n font-family: inherit;\n font-size: inherit;\n line-height: inherit;\n }\n\n button,\n input {\n overflow: visible;\n }\n\n button,\n select {\n text-transform: none;\n }\n\n select {\n word-wrap: normal;\n }\n\n button,\n [type=\"button\"],\n [type=\"reset\"],\n [type=\"submit\"] {\n -webkit-appearance: button;\n }\n\n button:not(:disabled),\n [type=\"button\"]:not(:disabled),\n [type=\"reset\"]:not(:disabled),\n [type=\"submit\"]:not(:disabled) {\n cursor: pointer;\n }\n\n button::-moz-focus-inner,\n [type=\"button\"]::-moz-focus-inner,\n [type=\"reset\"]::-moz-focus-inner,\n [type=\"submit\"]::-moz-focus-inner {\n padding: 0;\n border-style: none;\n }\n\n\n input[type=\"radio\"],\n input[type=\"checkbox\"] {\n box-sizing: border-box;\n padding: 0;\n }\n\n\n [hidden] {\n display: none !important;\n }\n\n h1 {\n font-size: 2.5rem;\n }\n\n h2 {\n font-size: 2rem;\n }\n\n h3 {\n font-size: 1.75rem;\n }\n\n h4 {\n font-size: 1.5rem;\n }\n\n h5 {\n font-size: 1.25rem;\n }\n\n h6 {\n font-size: 1rem;\n }\n\n .container-fluid {\n width: 100%;\n padding-right: 15px;\n padding-left: 15px;\n margin-right: auto;\n margin-left: auto;\n }\n\n .row {\n display: -ms-flexbox;\n display: flex;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n margin-right: -15px;\n margin-left: -15px;\n }\n\n .col {\n -ms-flex-preferred-size: 0;\n flex-basis: 0;\n -ms-flex-positive: 1;\n flex-grow: 1;\n max-width: 100%;\n\n position: relative;\n width: 100%;\n padding-right: 15px;\n padding-left: 15px;\n }\n\n .d-flex {\n display: -ms-flexbox !important;\n display: flex !important;\n }\n\n .card > .list-group:first-child .list-group-item:first-child {\n border-top-left-radius: 0.25rem;\n border-top-right-radius: 0.25rem;\n }\n\n .card > .list-group:last-child .list-group-item:last-child {\n border-bottom-right-radius: 0.25rem;\n border-bottom-left-radius: 0.25rem;\n }\n\n .card-header + .list-group .list-group-item:first-child {\n border-top: 0;\n }\n\n .card-body {\n -ms-flex: 1 1 auto;\n flex: 1 1 auto;\n min-height: 1px;\n padding: 0.75rem;\n }\n\n .list-group {\n display: -ms-flexbox;\n display: flex;\n -ms-flex-direction: column;\n flex-direction: column;\n padding-left: 0;\n margin-bottom: 0;\n }\n\n .list-group-item-action {\n width: 100%;\n color: #495057;\n text-align: inherit;\n }\n\n .list-group-item-action:hover, .list-group-item-action:focus {\n z-index: 1;\n text-decoration: none;\n }\n\n .list-group-item {\n position: relative;\n display: block;\n padding: 0.75rem 1.25rem;\n border: 1px solid rgba(0, 0, 0, 0.125);\n }\n\n .list-group-item:first-child {\n border-top-left-radius: 0.25rem;\n border-top-right-radius: 0.25rem;\n }\n\n .list-group-item:last-child {\n border-bottom-right-radius: 0.25rem;\n border-bottom-left-radius: 0.25rem;\n }\n\n .list-group-item.disabled, .list-group-item:disabled {\n color: #6c757d;\n pointer-events: none;\n background-color: #fff;\n }\n\n .list-group-item.active {\n z-index: 2;\n color: #fff;\n background-color: #007bff;\n border-color: #007bff;\n }\n\n .list-group-item + .list-group-item {\n border-top-width: 0;\n }\n\n .list-group-item + .list-group-item.active {\n margin-top: -1px;\n border-top-width: 1px;\n }\n\n .flex-column {\n -ms-flex-direction: column !important;\n flex-direction: column !important;\n }\n\n .align-items-start {\n -ms-flex-align: start !important;\n align-items: flex-start !important;\n }\n\n\n .input-group {\n position: relative;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n -ms-flex-align: stretch;\n align-items: stretch;\n width: 100%;\n }\n\n .input-group > .form-control,\n .input-group > .form-control-plaintext {\n position: relative;\n -ms-flex: 1 1 0%;\n flex: 1 1 0%;\n min-width: 0;\n margin-bottom: 0;\n }\n\n .input-group > .form-control + .form-control,\n .input-group > .form-control-plaintext + .form-control,\n .input-group > .custom-select + .form-control,\n .input-group > .custom-file + .form-control {\n margin-left: -1px;\n }\n\n .input-group > .form-control:focus {\n z-index: 3;\n }\n\n .input-group > .form-control:not(:last-child) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n }\n\n .input-group > .form-control:not(:first-child) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n }\n\n\n .input-group-prepend,\n .input-group-append {\n display: -ms-flexbox;\n display: flex;\n }\n\n .input-group-prepend .btn,\n .input-group-append .btn {\n position: relative;\n z-index: 2;\n }\n\n .input-group-prepend .btn:focus,\n .input-group-append .btn:focus {\n z-index: 3;\n }\n\n .input-group-prepend .btn + .btn,\n .input-group-append .btn + .btn {\n margin-left: -1px;\n }\n\n .input-group-prepend {\n margin-right: -1px;\n }\n\n .input-group-append {\n margin-left: -1px;\n }\n\n .input-group-lg > .form-control:not(textarea) {\n height: calc(1.5em + 1rem + 2px);\n }\n\n .input-group-lg > .form-control,\n .input-group-lg > .input-group-prepend > .btn,\n .input-group-lg > .input-group-append > .btn {\n padding: 0.5rem 1rem;\n font-size: 1.25rem;\n line-height: 1.5;\n border-radius: 0.3rem;\n }\n\n .input-group-sm > .form-control:not(textarea) {\n height: calc(1.5em + 0.5rem + 2px);\n }\n\n .input-group-sm > .form-control,\n .input-group-sm > .input-group-prepend > .btn,\n .input-group-sm > .input-group-append > .btn {\n padding: 0.25rem 0.5rem;\n font-size: 0.875rem;\n line-height: 1.5;\n border-radius: 0.2rem;\n }\n\n\n .input-group > .input-group-prepend > .btn,\n .input-group > .input-group-append:not(:last-child) > .btn,\n .input-group > .input-group-append:last-child > .btn:not(:last-child):not(.dropdown-toggle) {\n border-top-right-radius: 0;\n border-bottom-right-radius: 0;\n }\n\n .input-group > .input-group-append > .btn,\n .input-group > .input-group-prepend:not(:first-child) > .btn,\n .input-group > .input-group-prepend:first-child > .btn:not(:first-child) {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n }\n\n /* Margin Y */\n .my-auto, .mt-auto {\n margin-top: auto !important;\n }\n\n .my-auto, .mb-auto {\n margin-bottom: auto !important;\n }\n\n .my-0, .mt-0 {\n margin-top: 0 !important;\n }\n\n .my-0, .mb-0 {\n margin-bottom: 0 !important;\n }\n\n .my-1, .mt-1 {\n margin-top: 0.25rem !important;\n }\n\n .my-1, .mb-1 {\n margin-bottom: 0.25rem !important;\n }\n\n .my-2, .mt-2 {\n margin-top: 0.5rem !important;\n }\n\n .my-2, .mb-2 {\n margin-bottom: 0.5rem !important;\n }\n\n .my-3, .mt-3 {\n margin-top: 1rem !important;\n }\n\n .my-3, .mb-3 {\n margin-bottom: 1rem !important;\n }\n\n /* Margin X */\n .mx-auto, .ml-auto {\n margin-left: auto !important;\n }\n\n .mx-auto, .mr-auto {\n margin-right: auto !important;\n }\n\n .mx-0, .ml-0 {\n margin-left: 0 !important;\n }\n\n .mx-0, .mr-0 {\n margin-right: 0 !important;\n }\n\n .mx-1, .ml-1 {\n margin-left: 0.25rem !important;\n }\n\n .mx-1, .mr-1 {\n margin-right: 0.25rem !important;\n }\n\n .mx-2, .ml-2 {\n margin-left: 0.5rem !important;\n }\n\n .mx-2, .mr-2 {\n margin-right: 0.5rem !important;\n }\n\n .mx-3, .ml-3 {\n margin-left: 1rem !important;\n }\n\n .mx-3, .mr-3 {\n margin-right: 1rem !important;\n }\n\n /* Padding Y */\n .py-0, .pt-0 {\n padding-top: 0 !important;\n }\n\n .py-0, .pb-0 {\n padding-bottom: 0 !important;\n }\n\n .py-1, .pt-1 {\n padding-top: 0.25rem !important;\n }\n\n .py-1, .pb-1 {\n padding-bottom: 0.25rem !important;\n }\n\n .py-2, .pt-2 {\n padding-top: 0.5rem !important;\n }\n\n .py-2, .pb-2 {\n padding-bottom: 0.5rem !important;\n }\n\n .py-3, .pt-3 {\n padding-top: 1rem !important;\n }\n\n .py-3, .pb-3 {\n padding-bottom: 1rem !important;\n }\n\n /* Padding X */\n .px-0, .pl-0 {\n padding-left: 0 !important;\n }\n\n .px-0, .pr-0 {\n padding-right: 0 !important;\n }\n\n .px-1, .pl-1 {\n padding-left: 0.25rem !important;\n }\n\n .px-1, .pr-1 {\n padding-right: 0.25rem !important;\n }\n\n .px-2, .pl-2 {\n padding-left: 0.5rem !important;\n }\n\n .px-2, .pr-2 {\n padding-right: 0.5rem !important;\n }\n\n .px-3, .pl-3 {\n padding-left: 1rem !important;\n }\n\n .px-3, .pr-3 {\n padding-right: 1rem !important;\n }\n\n\n .form-control {\n display: block;\n width: 100%;\n height: calc(1.5em + 0.75rem + 2px);\n padding: 0.375rem 0.75rem;\n font-size: 1rem;\n font-weight: 400;\n line-height: 1.5;\n color: #495057;\n background-color: #fff;\n background-clip: padding-box;\n border: 1px solid #ced4da;\n border-radius: 0.25rem;\n transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;\n }\n\n @media (prefers-reduced-motion: reduce) {\n .form-control {\n transition: none;\n }\n }\n\n .form-control::-ms-expand {\n background-color: transparent;\n border: 0;\n }\n\n .form-control:-moz-focusring {\n color: transparent;\n text-shadow: 0 0 0 #495057;\n }\n\n .form-control:focus {\n color: #495057;\n background-color: #fff;\n border-color: #80bdff;\n outline: 0;\n box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);\n }\n\n .form-control::-webkit-input-placeholder {\n color: #6c757d;\n opacity: 1;\n }\n\n .form-control::-moz-placeholder {\n color: #6c757d;\n opacity: 1;\n }\n\n .form-control:-ms-input-placeholder {\n color: #6c757d;\n opacity: 1;\n }\n\n .form-control::-ms-input-placeholder {\n color: #6c757d;\n opacity: 1;\n }\n\n .form-control::placeholder {\n color: #6c757d;\n opacity: 1;\n }\n\n .form-control:disabled, .form-control[readonly] {\n background-color: #e9ecef;\n opacity: 1;\n }\n\n select.form-control:focus::-ms-value {\n color: #495057;\n background-color: #fff;\n }\n\n .btn .badge {\n position: relative;\n top: -1px;\n }\n\n .btn {\n display: inline-block;\n font-weight: 400;\n color: #212529;\n text-align: center;\n vertical-align: middle;\n cursor: pointer;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n background-color: transparent;\n border: 1px solid transparent;\n padding: 0.375rem 0.75rem;\n font-size: 1rem;\n line-height: 1.5;\n border-radius: 0.25rem;\n transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;\n }\n\n @media (prefers-reduced-motion: reduce) {\n .btn {\n transition: none;\n }\n }\n\n\n .btn:hover {\n color: #212529;\n text-decoration: none;\n }\n\n .btn:focus, .btn.focus {\n outline: 0;\n box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);\n }\n\n .btn.disabled, .btn:disabled {\n opacity: 0.65;\n }\n\n\n .btn-outline-secondary {\n color: #6c757d;\n border-color: #6c757d;\n }\n\n .btn-outline-secondary:hover {\n color: #fff;\n background-color: #6c757d;\n border-color: #6c757d;\n }\n\n .btn-outline-secondary:focus, .btn-outline-secondary.focus {\n box-shadow: 0 0 0 0.2rem rgba(108, 117, 125, 0.5);\n }\n\n .btn-outline-secondary.disabled, .btn-outline-secondary:disabled {\n color: #6c757d;\n background-color: transparent;\n }\n\n .btn-outline-secondary:not(:disabled):not(.disabled):active, .btn-outline-secondary:not(:disabled):not(.disabled).active,\n .show > .btn-outline-secondary.dropdown-toggle {\n color: #fff;\n background-color: #6c757d;\n border-color: #6c757d;\n }\n\n .btn-outline-secondary:not(:disabled):not(.disabled):active:focus, .btn-outline-secondary:not(:disabled):not(.disabled).active:focus,\n .show > .btn-outline-secondary.dropdown-toggle:focus {\n box-shadow: 0 0 0 0.2rem rgba(108, 117, 125, 0.5);\n }\n\n\n .modal-open {\n overflow: hidden;\n }\n\n .modal-open .modal {\n overflow-x: hidden;\n overflow-y: auto;\n }\n\n .modal {\n position: absolute;\n top: 0;\n left: 0;\n z-index: 1050;\n width: 100%;\n height: 100%;\n overflow: hidden;\n outline: 0;\n }\n\n .modal-dialog {\n position: relative;\n width: auto;\n margin: 0.5rem;\n pointer-events: none;\n }\n\n .modal.fade .modal-dialog {\n transition: -webkit-transform 0.3s ease-out;\n transition: transform 0.3s ease-out;\n transition: transform 0.3s ease-out, -webkit-transform 0.3s ease-out;\n -webkit-transform: translate(0, -50px);\n transform: translate(0, -50px);\n }\n\n @media (prefers-reduced-motion: reduce) {\n .modal.fade .modal-dialog {\n transition: none;\n }\n }\n\n .modal.show .modal-dialog {\n -webkit-transform: none;\n transform: none;\n }\n\n .modal.modal-static .modal-dialog {\n -webkit-transform: scale(1.02);\n transform: scale(1.02);\n }\n\n .modal-dialog-scrollable {\n display: -ms-flexbox;\n display: flex;\n max-height: calc(100% - 1rem);\n }\n\n .modal-dialog-scrollable .modal-content {\n max-height: calc(100vh - 1rem);\n overflow: hidden;\n }\n\n .modal-dialog-scrollable .modal-header,\n .modal-dialog-scrollable .modal-footer {\n -ms-flex-negative: 0;\n flex-shrink: 0;\n }\n\n .modal-dialog-scrollable .modal-body {\n overflow-y: auto;\n }\n\n .modal-dialog-centered {\n display: -ms-flexbox;\n display: flex;\n -ms-flex-align: center;\n align-items: center;\n min-height: calc(100% - 1rem);\n }\n\n .modal-dialog-centered::before {\n display: block;\n height: calc(100vh - 1rem);\n content: \"\";\n }\n\n .modal-dialog-centered.modal-dialog-scrollable {\n -ms-flex-direction: column;\n flex-direction: column;\n -ms-flex-pack: center;\n justify-content: center;\n height: 100%;\n }\n\n .modal-dialog-centered.modal-dialog-scrollable .modal-content {\n max-height: none;\n }\n\n .modal-dialog-centered.modal-dialog-scrollable::before {\n content: none;\n }\n\n .modal-content {\n position: relative;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-direction: column;\n flex-direction: column;\n width: 100%;\n pointer-events: auto;\n background-color: #fff;\n background-clip: padding-box;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 0.3rem;\n outline: 0;\n }\n\n .modal-backdrop {\n position: absolute;\n top: 0;\n left: 0;\n z-index: 1040;\n width: 100%;\n height: 100%;\n background-color: #000;\n }\n\n .modal-backdrop.fade {\n opacity: 0;\n }\n\n .modal-backdrop.show {\n opacity: 0.5;\n }\n\n .modal-header {\n display: -ms-flexbox;\n display: flex;\n -ms-flex-align: start;\n align-items: flex-start;\n -ms-flex-pack: justify;\n justify-content: space-between;\n padding: 1rem 1rem;\n border-bottom: 1px solid #dee2e6;\n border-top-left-radius: calc(0.3rem - 1px);\n border-top-right-radius: calc(0.3rem - 1px);\n }\n\n .modal-header .close {\n padding: 1rem 1rem;\n margin: -1rem -1rem -1rem auto;\n }\n\n .modal-title {\n margin-bottom: 0;\n line-height: 1.5;\n }\n\n .modal-body {\n position: relative;\n -ms-flex: 1 1 auto;\n flex: 1 1 auto;\n padding: 1rem;\n }\n\n .modal-footer {\n display: -ms-flexbox;\n display: flex;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n -ms-flex-align: center;\n align-items: center;\n -ms-flex-pack: end;\n justify-content: flex-end;\n padding: 0.75rem;\n border-top: 1px solid #dee2e6;\n border-bottom-right-radius: calc(0.3rem - 1px);\n border-bottom-left-radius: calc(0.3rem - 1px);\n }\n\n .modal-footer > * {\n margin: 0.25rem;\n }\n\n .modal-scrollbar-measure {\n position: absolute;\n top: -9999px;\n width: 50px;\n height: 50px;\n overflow: scroll;\n }\n\n @media (min-width: 576px) {\n .modal-dialog {\n max-width: 500px;\n margin: 1.75rem auto;\n }\n .modal-dialog-scrollable {\n max-height: calc(100% - 3.5rem);\n }\n .modal-dialog-scrollable .modal-content {\n max-height: calc(100vh - 3.5rem);\n }\n .modal-dialog-centered {\n min-height: calc(100% - 3.5rem);\n }\n .modal-dialog-centered::before {\n height: calc(100vh - 3.5rem);\n }\n .modal-sm {\n max-width: 300px;\n }\n }\n\n @media (min-width: 992px) {\n .modal-lg,\n .modal-xl {\n max-width: 800px;\n }\n }\n\n @media (min-width: 1200px) {\n .modal-xl {\n max-width: 1140px;\n }\n }\n\n\n\n\n .card {\n position: relative;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-direction: column;\n flex-direction: column;\n min-width: 0;\n word-wrap: break-word;\n background-clip: border-box;\n border-radius: 0.25rem;\n }\n\n\n .alert {\n position: relative;\n padding: 0.75rem 1.25rem;\n margin-bottom: 1rem;\n border: 1px solid transparent;\n border-radius: 0.25rem;\n }\n\n\n .alert-warning {\n color: #856404;\n background-color: #fff3cd;\n border-color: #ffeeba;\n }\n\n\n .justify-content-between {\n -ms-flex-pack: justify !important;\n justify-content: space-between !important;\n }\n\n .align-items-baseline {\n -ms-flex-align: baseline !important;\n align-items: baseline !important;\n }\n\n .pl-2,\n .px-2 {\n padding-left: 0.5rem !important;\n }\n\n .align-items-end {\n -ms-flex-align: end !important;\n align-items: flex-end !important;\n }\n}\n","/* Spatial and t-SNE controls */\n@mixin controls($theme-name, $theme-colors) {\n .btn.icon {\n padding: 0;\n height: 2em;\n width: 2em;\n background-color: white;\n > svg {\n vertical-align: middle;\n }\n }\n .roll-up {\n height: 2em; /* Matches .btn.icon */\n overflow: hidden;\n background-color: white;\n &:hover {\n animation-name: roll-up;\n animation-duration: 0.5s;\n animation-fill-mode: forwards;\n }\n }\n @keyframes roll-up {\n 0% { height: 2em; }\n 100% { height: 100%; }\n }\n .tool {\n position: absolute;\n display: inline;\n z-index: 1000;\n opacity: .65;\n color: black;\n &:hover {\n opacity: .90;\n }\n }\n\n .radio {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n /* create custom radiobutton appearance */\n display: inline-block;\n width: 1em;\n height: 1em;\n padding: 6px !important; /* TODO: Only need \"important\" to override Bootstrap. */\n /* background-color only for content */\n background-clip: content-box;\n border: 2px solid lightgrey;\n background-color: lightgrey;\n border-radius: 50%;\n\n &:checked {\n background-clip: unset;\n }\n }\n}\n","\n@mixin channels($theme-name, $theme-colors) {\n $box-size: 16px;\n\n .layer-controller-container {\n & > div:first-child {\n margin-top: 0 !important;\n }\n }\n\n .channel-container {\n width: 100%;\n display: flex;\n position: relative;\n }\n\n .channel-set-color {\n display: flex;\n position: relative;\n top: 5px;\n width: $box-size;\n height: $box-size;\n margin-right: 24px;\n cursor: pointer;\n outline: currentColor none medium;\n border-radius: 3px;\n box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 0px 1px inset;\n }\n\n .channel-checked {\n display: flex;\n position: relative;\n margin-right: 10px;\n }\n\n .add-image-layer {\n color: darken(map-get($theme-colors, \"primary-foreground\"), 5%);\n border: 1px dashed darken(map-get($theme-colors, \"primary-foreground\"), 5%);\n }\n\n}\n","\n/* In error message */\n@mixin error($theme-name, $theme-colors) {\n pre {\n color: map-get($theme-colors, \"primary-foreground\");\n }\n}\n","/* Tooltips for plot hover events. */\n@mixin plot-tooltips($theme-name, $theme-colors) {\n .cell-emphasis-crosshair {\n z-index: 50;\n position: absolute;\n pointer-events: none;\n box-sizing: border-box;\n background-color: map-get($theme-colors, \"secondary-foreground\");\n }\n\n}\n","\n/*\n Tooltips and popovers for showing help info to the user.\n Some styles here (for .rc-tooltip and descendants) have been adapted from the ant-design tooltip and popover styles:\n https://github.com/ant-design/ant-design/blob/34c2fad6368cce0d3e1959613d092274f567582a/components/tooltip/style/index.less\n https://github.com/ant-design/ant-design/blob/34c2fad6368cce0d3e1959613d092274f567582a/components/popover/style/index.less\n */\n@mixin help-tooltip-popover-common($theme-name, $theme-colors) {\n\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n color: rgba(0, 0, 0, 0.65);\n font-size: 14px;\n list-style: none;\n position: absolute;\n\n &-hidden {\n display: none;\n }\n\n .rc-tooltip-inner {\n border-radius: 2px;\n -webkit-box-shadow: 0 3px 6px -4px rgba(100, 100, 100, 0.12), 0 6px 16px 0 rgba(100, 100, 100, 0.08), 0 9px 28px 8px rgba(100, 100, 100, 0.05);\n box-shadow: 0 3px 6px -4px rgba(100, 100, 100, 0.12), 0 6px 16px 0 rgba(100, 100, 100, 0.08), 0 9px 28px 8px rgba(100, 100, 100, 0.05);\n }\n \n}\n\n@mixin help-tooltips($theme-name, $theme-colors) {\n .help-tooltip {\n &.rc-tooltip {\n z-index: 1060;\n display: block;\n max-width: 250px;\n visibility: visible;\n\n @include help-tooltip-popover-common($theme-name, $theme-colors);\n\n &-placement-top {\n padding-top: 8px;\n }\n &-placement-right {\n padding-left: 8px;\n }\n &-placement-bottom {\n padding-top: 8px;\n }\n &-placement-left {\n padding-right: 8px;\n }\n .rc-tooltip-inner {\n font-size: 10px;\n min-width: 30px;\n padding: 6px 8px;\n color: #fff;\n text-align: left;\n text-decoration: none;\n word-wrap: break-word;\n background-color: rgba(0, 0, 0, 0.9);\n \n }\n .rc-tooltip-arrow {\n display: none;\n }\n }\n }\n}\n\n@mixin popover($theme-name, $theme-colors) {\n\n .popover {\n &.rc-tooltip {\n top: 0;\n left: 0;\n z-index: 1030;\n font-weight: normal;\n white-space: normal;\n text-align: left;\n cursor: auto;\n -webkit-user-select: text;\n -moz-user-select: text;\n -ms-user-select: text;\n user-select: text;\n\n &::after {\n position: absolute;\n background: rgba(255, 255, 255, 0.01);\n content: '';\n }\n\n @include help-tooltip-popover-common($theme-name, $theme-colors);\n\n &-placement-top {\n padding-bottom: 10px;\n }\n &-placement-right {\n padding-left: 10px;\n }\n &-placement-bottom {\n padding-top: 10px;\n }\n &-placement-left {\n padding-right: 10px;\n }\n\n .rc-tooltip-content {\n padding: 0;\n }\n\n .rc-tooltip-inner {\n box-sizing: border-box;\n background-color: map-get($global-colors, \"white\");\n background-clip: padding-box;\n\n .popover-menu-list {\n list-style-type: none;\n padding: 0;\n margin-bottom: 0;\n dl, ol, ul {\n margin-top: 0;\n margin-bottom: 1rem;\n }\n\n li {\n button {\n border: 0;\n padding: 4px 16px;\n cursor: pointer;\n width: 100%;\n background-color: transparent;\n border-radius: 2px;\n\n span.small {\n font-size: 11px;\n }\n\n &:hover {\n background-color: lighten(map-get($global-colors, \"gray-light\"), 10%);\n }\n }\n &:not(:last-child) {\n border-bottom: 1px solid map-get($global-colors, \"gray-mid\");\n }\n }\n\n button {\n -webkit-appearance: button;\n text-transform: none;\n overflow: visible;\n margin: 0;\n font-family: inherit;\n font-size: 14px;\n line-height: inherit;\n border-radius: 0;\n }\n }\n\n .popover-menu-color + .popover-menu-list {\n border-top: 1px solid map-get($global-colors, \"gray-mid\");\n }\n }\n\n .popover-menu-color.twitter-picker {\n box-shadow: none !important;\n margin: 0 auto;\n /* Sets margins around color picker and centers */\n > div:nth-child(3) {\n padding: 6px !important;\n transform: translate(2px, 0);\n }\n > div > div:nth-of-type(1) {\n font-size: 12px;\n width: 20px !important;\n }\n input {\n width: 60px !important;\n font-size: 12px;\n }\n /* Sets smaller color squares */\n > div > span > div {\n width: 18px !important;\n height: 18px !important;\n }\n }\n\n .rc-tooltip-inner-content {\n padding: 12px 16px;\n color: rgba(0, 0, 0, 0.65);\n }\n\n .rc-tooltip-arrow {\n position: absolute;\n display: block;\n width: 8px;\n height: 8px;\n background: transparent;\n border-style: solid;\n border-width: 4px;\n -webkit-transform: rotate(45deg);\n transform: rotate(45deg);\n }\n\n &.rc-tooltip-placement-top > .rc-tooltip-content > .rc-tooltip-arrow {\n bottom: 6px;\n border-top-color: transparent;\n border-right-color: #fff;\n border-bottom-color: #fff;\n border-left-color: transparent;\n -webkit-box-shadow: 3px 3px 7px rgba(0, 0, 0, 0.07);\n box-shadow: 3px 3px 7px rgba(0, 0, 0, 0.07);\n left: 50%;\n -webkit-transform: translateX(-50%) rotate(45deg);\n transform: translateX(-50%) rotate(45deg);\n }\n\n\n &.rc-tooltip-placement-right > .rc-tooltip-content > .rc-tooltip-arrow {\n left: 6px;\n border-top-color: transparent;\n border-right-color: transparent;\n border-bottom-color: #fff;\n border-left-color: #fff;\n -webkit-box-shadow: -3px 3px 7px rgba(0, 0, 0, 0.07);\n box-shadow: -3px 3px 7px rgba(0, 0, 0, 0.07);\n top: 50%;\n -webkit-transform: translateY(-50%) rotate(45deg);\n transform: translateY(-50%) rotate(45deg);\n }\n\n\n &.rc-tooltip-placement-bottom > .rc-tooltip-content > .rc-tooltip-arrow {\n top: 6px;\n border-top-color: #fff;\n border-right-color: transparent;\n border-bottom-color: transparent;\n border-left-color: #fff;\n -webkit-box-shadow: -2px -2px 5px rgba(0, 0, 0, 0.06);\n box-shadow: -2px -2px 5px rgba(0, 0, 0, 0.06);\n left: 50%;\n -webkit-transform: translateX(-50%) rotate(45deg);\n transform: translateX(-50%) rotate(45deg);\n }\n \n &.rc-tooltip-placement-left > .rc-tooltip-content > .rc-tooltip-arrow {\n right: 6px;\n border-top-color: #fff;\n border-right-color: #fff;\n border-bottom-color: transparent;\n border-left-color: transparent;\n -webkit-box-shadow: 3px -3px 7px rgba(0, 0, 0, 0.07);\n box-shadow: 3px -3px 7px rgba(0, 0, 0, 0.07);\n top: 50%;\n -webkit-transform: translateY(-50%) rotate(45deg);\n transform: translateY(-50%) rotate(45deg);\n }\n }\n }\n}","@import 'colors';\n\n/*\n Some styles here (for .rc-tree and descendants) have been adapted from the ant-design tree styles:\n https://github.com/ant-design/ant-design/blob/34c2fad6368cce0d3e1959613d092274f567582a/components/tree/style/index.less\n */\n@mixin sets-manager($theme-name, $theme-colors) {\n\n $node-height: 32 !default;\n .sets-manager {\n position: relative;\n width: 100%;\n display: block;\n height: auto;\n .set-operation-buttons {\n background-color: map-get($global-colors, \"gray-light\");\n border-radius: 4px;\n padding: 2px;\n display: inline-block;\n position: absolute;\n bottom: 1.75rem;\n right: 0.25rem;\n -webkit-box-shadow: -2px -2px 5px rgba(0, 0, 0, 0.06);\n box-shadow: -2px -2px 5px rgba(0, 0, 0, 0.06);\n button {\n border: 0;\n background-color: transparent;\n color: lighten(map-get($global-colors, \"gray-dark\"), 5%);\n\n &[disabled] {\n pointer-events: none;\n svg {\n fill: silver;\n }\n }\n \n svg {\n fill: map-get($global-colors, \"gray-dark\");\n vertical-align: top;\n height: 20px;\n margin-top: 1px;\n }\n\n &:hover, &:hover path {\n color: darken(map-get($global-colors, \"gray-dark\"), 15%);\n fill: darken(map-get($global-colors, \"gray-dark\"), 15%);\n }\n }\n }\n \n .sets-manager-tree {\n position: relative;\n top: 0;\n left: 0;\n width: 100%;\n height: auto;\n display: block;\n padding-right: 17px; /* Increase/decrease this value for cross-browser compatibility */\n box-sizing: content-box; /* So the width will be 100% + 17px */\n \n .plus-button {\n border: 0;\n background-color: transparent;\n color: lighten(map-get($theme-colors, \"primary-foreground\"), 5%);\n padding: 0;\n font-size: 18px;\n margin-bottom: 2rem;\n }\n \n .rc-tree {\n padding-left: 0;\n margin: 0;\n border: 1px solid transparent;\n\n .node-menu-icon {\n fill: map-get($global-colors, \"gray-mid\");\n cursor: pointer;\n height: 14px;\n position: relative;\n vertical-align: top;\n width: #{$node-height}px;\n top: 5.5px;\n\n &:hover {\n fill: lighten(map-get($global-colors, \"gray-mid\"), 10%);\n }\n }\n .node-size-label {\n font-size: 12px;\n color: darken(map-get($theme-colors, \"primary-foreground\"), 15%);\n }\n\n .level-buttons-container {\n height: 20px;\n width: 100%;\n position: relative;\n padding-left: 4px;\n left: 0;\n\n .level-buttons {\n\n input.level-radio-button {\n cursor: pointer;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n /* create custom radiobutton appearance */\n width: 12px;\n height: 12px;\n padding: 5px;\n /* background-color only for content */\n background-clip: content-box;\n border: 2px solid lighten(map-get($theme-colors, \"primary-foreground\"), 10%);\n background-color: lighten(map-get($theme-colors, \"primary-foreground\"), 10%);\n border-radius: 6px;\n position: relative;\n top: 3px;\n left: 0px;\n float: left;\n margin-right: 10px;\n\n &:checked, &.checked {\n background-clip: unset;\n }\n }\n }\n }\n\n .level-0-treenode > .rc-tree-switcher i svg {\n path {\n fill: lighten(map-get($theme-colors, \"primary-foreground\"), 5%);\n }\n }\n\n &-focused:not(&-active-focused) {\n border-color: cyan;\n }\n \n .rc-tree-treenode {\n margin: 0;\n padding: 0;\n line-height: #{$node-height - 8}px;\n white-space: nowrap;\n list-style: none;\n outline: 0;\n\n .title-button, .title-button-with-input {\n padding: 0;\n margin: 0;\n }\n\n .title-button {\n height: #{$node-height - 8}px;\n line-height: #{$node-height - 8}px;\n border: 1px solid transparent;\n color: lighten(map-get($theme-colors, \"primary-foreground\"), 5%);\n background: transparent;\n background-color: transparent;\n vertical-align: top;\n font-size: 14px;\n }\n\n .title-button-with-input {\n display: block;\n height: #{$node-height - 6}px;\n box-sizing: border-box;\n .title-input {\n font-size: 14px;\n height: #{$node-height - 8}px;\n line-height: #{$node-height - 8}px;\n width: calc(100% - 60px);\n margin-right: 10px;\n background-color: map-get($global-colors, \"gray-light\");\n color: map-get($global-colors, \"black\");\n border-radius: 4px;\n outline: none;\n padding: 4px 0px 4px 4px;\n border: 1px solid map-get($global-colors, \"gray-light\");\n &:focus {\n border: 1px solid map-get($theme-colors, \"primary-foreground-active\");\n }\n }\n \n .title-save-button {\n background-color: map-get($global-colors, \"gray-dark\");\n border: 1px solid map-get($global-colors, \"gray-dark\");\n color: map-get($global-colors, \"gray-light\");\n border-radius: 3px;\n width: 50px;\n height: #{$node-height - 8}px;\n line-height: 20px;\n font-size: 13px;\n vertical-align: top;\n margin: 0;\n padding: 0;\n \n &:hover {\n background-color: lighten(map-get($global-colors, \"gray-dark\"), 5%);\n border: 1px solid lighten(map-get($global-colors, \"gray-dark\"), 5%);\n }\n }\n }\n\n .draggable {\n color: #333;\n -moz-user-select: none;\n -khtml-user-select: none;\n -webkit-user-select: none;\n user-select: none;\n /* Required to make elements draggable in old WebKit */\n -khtml-user-drag: element;\n -webkit-user-drag: element;\n border: 2px transparent solid;\n }\n &.drag-over {\n > .draggable {\n color: white;\n background-color: #316ac5;\n border: 2px #316ac5 solid;\n opacity: 0.8;\n }\n }\n &.drag-over-gap-top {\n > .draggable {\n border-top: 2px blue solid;\n }\n }\n &.drag-over-gap-bottom {\n > .draggable {\n border-bottom: 2px blue solid;\n }\n }\n &.filter-node {\n > .rc-tree-node-content-wrapper {\n color: #a60000 !important;\n font-weight: bold !important;\n }\n }\n ul {\n margin: 0;\n padding-left: 35px;\n }\n .rc-tree-node-content-wrapper {\n width: calc(100% - 20px);\n display: inline-block;\n margin: 0;\n padding: 0;\n text-decoration: none;\n vertical-align: top;\n cursor: pointer;\n position: relative;\n & > span {\n position: relative;\n width: 100%;\n display: inline-block;\n\n .title-button {\n position: relative;\n /* To accomodate the checkbox and node menu button. */\n max-width: calc(100% - 45px);\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .node-menu-icon {\n position: relative;\n left: 0;\n }\n }\n }\n span {\n &.rc-tree-switcher,\n &.rc-tree-checkbox {\n display: inline-block;\n margin-top: 4px;\n margin-right: 6px;\n vertical-align: middle;\n background-color: transparent;\n \n background-repeat: no-repeat;\n background-attachment: scroll;\n border: 0 none;\n outline: none;\n cursor: pointer;\n \n }\n\n &.rc-tree-switcher {\n svg {\n width: 15px;\n height: 15px;\n }\n &.rc-tree-switcher-noop {\n cursor: auto;\n }\n\n &.rc-tree-switcher_close {\n -webkit-transform: rotate(-90deg);\n -ms-transform: rotate(-90deg);\n transform: rotate(-90deg);\n }\n }\n &.rc-tree-checkbox {\n width: 13px;\n height: 13px;\n margin: 0 3px;\n border: 2px solid map-get($global-colors, \"gray-mid\");\n border-radius: 3px;\n position: relative;\n left: 0;\n margin-right: 10px;\n &-checked {\n background-color: map-get($global-colors, \"gray-mid\");\n }\n &-indeterminate {\n background-position: -14px -28px;\n }\n &-disabled {\n background-position: 0 -56px;\n }\n &.rc-tree-checkbox-checked.rc-tree-checkbox-disabled {\n background-position: -14px -56px;\n }\n &.rc-tree-checkbox-indeterminate.rc-tree-checkbox-disabled {\n position: relative;\n background: #ccc;\n border-radius: 3px;\n &::after {\n position: absolute;\n top: 5px;\n left: 3px;\n width: 5px;\n height: 0;\n border: 2px solid #fff;\n border-top: 0;\n border-left: 0;\n -webkit-transform: scale(1);\n transform: scale(1);\n content: ' ';\n }\n }\n }\n }\n }\n &:not(.rc-tree-show-line) {\n .rc-tree-treenode {\n .rc-tree-switcher-noop {\n background: none;\n }\n }\n }\n &.rc-tree-show-line {\n .rc-tree-treenode:not(:last-child) {\n > .rc-tree-switcher-noop {\n background-position: -56px -18px;\n }\n }\n .rc-tree-treenode:last-child {\n > .rc-tree-switcher-noop {\n background-position: -56px -36px;\n }\n }\n }\n &-child-tree {\n display: none;\n &-open {\n display: block;\n }\n }\n &-treenode-disabled {\n > span:not(.rc-tree-switcher),\n > a,\n > a span {\n color: #767676;\n cursor: not-allowed;\n }\n }\n &-treenode-active {\n background: rgba(0, 0, 0, 0.1);\n \n // .rc-tree-node-content-wrapper {\n // background: rgba(0, 0, 0, 0.1);\n // }\n }\n &-node-selected {\n background-color: #ffe6b0;\n border: 1px #ffb951 solid;\n opacity: 0.8;\n }\n &-icon__open {\n margin-right: 2px;\n vertical-align: top;\n background-position: -110px -16px;\n }\n &-icon__close {\n margin-right: 2px;\n vertical-align: top;\n background-position: -110px 0;\n }\n &-icon__docu {\n margin-right: 2px;\n vertical-align: top;\n background-position: -110px -32px;\n }\n &-icon__customize {\n margin-right: 2px;\n vertical-align: top;\n }\n &-indent-unit {\n display: inline-block;\n padding-left: 18px;\n }\n }\n\n \n }\n }\n\n .vitessce-tooltip {\n .ant-tooltip-content .ant-tooltip-inner {\n font-size: 12px;\n background-color: rgba(0, 0, 0, 0.95);\n }\n }\n\n}","@import 'colors';\n\n@mixin selectable-table($theme-name, $theme-colors) {\n .selectable-table {\n flex: 1 1 auto;\n outline : none;\n .table-row {\n display: flex;\n flex-direction: row;\n border-bottom: 1px solid map-get($theme-colors, \"secondary-background-dim\");\n }\n .table-item {\n cursor: pointer;\n &:not(.row-checked):hover {\n @if $theme-name == dark {\n background-color: darken(map-get($theme-colors, \"secondary-background-dim\"), 10%);\n } @else {\n background-color: lighten(map-get($theme-colors, \"secondary-background-dim\"), 10%);\n }\n }\n &.row-checked {\n background-color: map-get($theme-colors, \"secondary-background-dim\");\n }\n .hidden-input-column {\n display: none;\n }\n .table-cell {\n padding: 0 4px;\n }\n .input-container {\n width: 1em;\n label {\n display: block;\n margin: 0;\n cursor: pointer;\n }\n input {\n cursor: pointer;\n &.radio, &.checkbox {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n /* create custom radiobutton appearance */\n display: inline-block;\n width: 1em;\n height: 1em;\n margin: 0.3em 0.5em 0.0em 0.5em;\n padding: 6px !important; /* TODO: Only need \"important\" to override Bootstrap. */\n /* background-color only for content */\n background-clip: content-box;\n border: 2px solid map-get($global-colors, \"gray-light\");\n background-color: map-get($global-colors, \"gray-light\");\n \n &:checked {\n background-clip: unset;\n }\n }\n &.radio {\n border-radius: 50%;\n }\n &.checkbox {\n border-radius: 2px;\n }\n }\n }\n } \n }\n}\n ","\n.vitessce-container .higlass-wrapper {\n // https://sass-lang.com/documentation/at-rules/import#nesting\n // https://sass-lang.com/documentation/at-rules/import#importing-css\n @import \"../../node_modules/higlass/dist/hglib\";\n}\n@mixin higlass($theme-name, $theme-colors) {\n\n .higlass-title-wrapper {\n height: calc(100% - 20px);\n .card-body {\n width: inherit;\n height: inherit;\n padding: 5px;\n background-color: map-get($theme-colors, \"secondary-background\");\n .higlass-lazy-wrapper {\n width: inherit;\n height: inherit;\n }\n .higlass-wrapper-parent {\n display: block;\n position: relative;\n box-sizing: border-box;\n font-size: 12px;\n color: #333;\n overflow: hidden;\n .higlass-wrapper {\n width: inherit;\n height: inherit;\n position: relative;\n display: block;\n text-align: left;\n box-sizing: border-box;\n .higlass {\n width: 100%;\n height: 100%;\n .react-grid-layout {\n background-color: transparent !important;\n }\n nav {\n display: flex;\n }\n input {\n font-size: 12px;\n }\n .btn {\n color: #999;\n font-size: 12px;\n }\n }\n }\n }\n }\n }\n \n}\n","@mixin vega($theme-name, $theme-colors) {\n .vega-container {\n display: flex;\n flex: 1 1 auto;\n overflow: hidden;\n }\n}","/*\nSee https://github.com/vitessce/vitessce/issues/368 for why this css needs to exist and https://github.com/vitessce/vitessce/pull/607 for a longer explanation.\nThe absolute positioning gives us the control we need to force the canvas elements to \"fill\" the container - this was not happening in Safari with the bootstrap css.\n*/\n@mixin heatmap($theme-name, $theme-colors) {\n .heatmap {\n width: 100%;\n left: 0;\n position: absolute;\n padding-right: inherit;\n padding-left: inherit;\n }\n\n .heatmap-container {\n position: absolute;\n top: 1.25rem; // Corresponds to the padding on .vitessce-container .card-body\n left: 1.25rem; // Corresponds to the padding on .vitessce-container .card-body\n width: calc(100% - 2.5rem);\n height: calc(100% - 2.5rem);\n }\n}","@mixin genes($theme-name, $theme-colors) {\n .search-bar {\n margin-bottom: .25rem;\n border: 0;\n padding: 2px;\n border-radius: 2px;\n }\n}\n"]} \ No newline at end of file diff -r 000000000000 -r 9f60ef2d586e static/js/2.eb2fd6ea.chunk.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/static/js/2.eb2fd6ea.chunk.js Thu Sep 08 17:23:33 2022 +0000 @@ -0,0 +1,3 @@ +/*! For license information please see 2.eb2fd6ea.chunk.js.LICENSE.txt */ +(this.webpackJsonpvitessce=this.webpackJsonpvitessce||[]).push([[2],[function(e,t,A){"use strict";e.exports=A(750)},function(e,t,A){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";function n(e,t,A){return t in e?Object.defineProperty(e,t,{value:A,enumerable:!0,configurable:!0,writable:!0}):e[t]=A,e}A.d(t,"a",(function(){return n}))},function(e,t,A){e.exports=A(853)},function(e,t,A){"use strict";function n(e,t){for(var A=0;At&&c(),a=t=A+1):"]"===n&&(a||g("Access path missing open bracket: "+e),a>0&&c(),a=0,t=A+1):A>t?c():t=A+1}return a&&g("Access path missing closing bracket: "+e),o&&g("Access path missing closing quote: "+e),A>t&&(A++,c()),r}function u(e,t,A){var r=c(e);return e=1===r.length?r[0]:e,n((A&&A.get||o)(r),[e],t||e)}var l=u("id"),I=n((function(e){return e}),[],"identity"),C=n((function(){return 0}),[],"zero"),h=n((function(){return 1}),[],"one"),f=n((function(){return!0}),[],"true"),d=n((function(){return!1}),[],"false");function B(e,t,A){var n=[t].concat([].slice.call(A));console[e].apply(console,n)}var p=0,E=1,Q=2,y=3,v=4;function m(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:B,n=e||p;return{level:function(e){return arguments.length?(n=+e,this):n},error:function(){return n>=E&&A(t||"error","ERROR",arguments),this},warn:function(){return n>=Q&&A(t||"warn","WARN",arguments),this},info:function(){return n>=y&&A(t||"log","INFO",arguments),this},debug:function(){return n>=v&&A(t||"log","DEBUG",arguments),this}}}var b=Array.isArray;function w(e){return e===Object(e)}var S=function(e){return"__proto__"!==e};function F(){for(var e=arguments.length,t=new Array(e),A=0;A=A-t?[t,A]:[r=Math.min(Math.max(r,t),A-n),r+n]}function z(e){return"function"===typeof e}function $(e,t,A){A=A||{},t=X(t)||[];var r=[],o=[],a={},s=A.comparator||te;return X(e).forEach((function(e,n){null!=e&&(r.push("descending"===t[n]?-1:1),o.push(e=z(e)?e:u(e,null,A)),(i(e)||[]).forEach((function(e){return a[e]=1})))})),0===o.length?null:n(s(o,r),Object.keys(a))}var ee=function(e,t){return(et||null==t)&&null!=e?1:(t=t instanceof Date?+t:t,(e=e instanceof Date?+e:e)!==e&&t===t?-1:t!==t&&e===e?1:0)},te=function(e,t){return 1===e.length?Ae(e[0],t[0]):ne(e,t,e.length)},Ae=function(e,t){return function(A,n){return ee(e(A),e(n))*t}},ne=function(e,t,A){return t.push(0),function(n,r){for(var i,o=0,a=-1;0===o&&++ai&&(i=n))}else{for(n=t(e[o]);oi&&(i=n))}return[r,i]}function se(e,t){var A,n,r,i,o,a=e.length,s=-1;if(null==t){for(;++s=n){A=r=n;break}if(s===a)return[-1,-1];for(i=o=s;++sn&&(A=n,i=s),r=n){A=r=n;break}if(s===a)return[-1,-1];for(i=o=s;++sn&&(A=n,i=s),ro&&(r=i,i=o,o=r),n=void 0===n||n,((A=void 0===A||A)?i<=e:ie&&(A=t,t={},n=1),t[r]=i};return r(),{clear:r,has:function(e){return ce(t,e)||ce(A,e)},get:function(e){return ce(t,e)?t[e]:ce(A,e)?i(e,A[e]):void 0},set:function(e,A){return ce(t,e)?t[e]=A:i(e,A)}}}function be(e,t,A,n){var r=t.length,i=A.length;if(!i)return t;if(!r)return A;for(var o=n||new t.constructor(r+i),a=0,s=0,g=0;a0?A[s++]:t[a++];for(;a=0;)A+=e;return A}function Se(e,t,A,n){var r=A||" ",i=e+"",o=t-i.length;return o<=0?i:"left"===n?we(r,o)+i:"center"===n?we(r,~~(o/2))+i+we(r,Math.ceil(o/2)):i+we(r,o)}function Fe(e){return e&&G(e)-e[0]||0}function Re(e){return b(e)?"["+e.map(Re)+"]":w(e)||Qe(e)?JSON.stringify(e).replace("\u2028","\\u2028").replace("\u2029","\\u2029"):e}function De(e){return null==e||""===e?null:!(!e||"false"===e||"0"===e)&&!!e}var Ge=function(e){return pe(e)||de(e)?e:Date.parse(e)};function ke(e,t){return t=t||Ge,null==e||""===e?null:t(e)}function xe(e){return null==e||""===e?null:e+""}function Ne(e){for(var t={},A=e.length,n=0;n=e.length?{done:!0}:{done:!1,value:e[t++]}},e:function(e){throw e},f:A}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,i,o=!0,a=!1;return{s:function(){r=e[Symbol.iterator]()},n:function(){var e=r.next();return o=e.done,e},e:function(e){a=!0,i=e},f:function(){try{o||null==r.return||r.return()}finally{if(a)throw i}}}}},function(e,t,A){"use strict";A.d(t,"a",(function(){return i}));var n=A(2);function r(e,t){var A=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),A.push.apply(A,n)}return A}function i(e){for(var t=1;t2&&void 0!==arguments[2])||arguments[2],n=g(e),r=e.drawingBufferWidth,i=e.drawingBufferHeight;return l(t,n,r,i,A)}function u(e){var t="undefined"===typeof window?1:window.devicePixelRatio||1;return Number.isFinite(e)?e<=0?1:e:e?t:1}function l(e,t,A,n,r){var i,o=I(e[0],t,A),a=C(e[1],t,n,r),s=I(e[0]+1,t,A),g=s===A-1?s:s-1;return s=C(e[1]+1,t,n,r),r?(i=a,a=s=0===s?s:s+1):i=s===n-1?s:s-1,{x:o,y:a,width:Math.max(g-o+1,1),height:Math.max(i-a+1,1)}}function I(e,t,A){return Math.min(Math.round(e*t),A-1)}function C(e,t,A,n){return n?Math.max(0,A-1-Math.round(e*t)):Math.min(Math.round(e*t),A-1)}var h=Object(a.isBrowser)(),f=h&&"undefined"!==typeof document,d={webgl2:!0,webgl1:!0,throwOnError:!0,manageState:!0,canvas:null,debug:!1,width:800,height:600};function B(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(s.a)(h,"createGLContext only available in the browser.\nCreate your own headless context or use 'createHeadlessContext' from @luma.gl/test-utils");var t,A=e=Object.assign({},d,e),n=A.width,r=A.height;function i(t){if(e.throwOnError)throw new Error(t);return console.error(t),null}e.onError=i;var o=e,a=o.canvas,g=y({canvas:a,width:n,height:r,onError:i});return(t=Q(g,e))?(v(t=p(t,e)),t):null}function p(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e||e._instrumented)return e;e._version=e._version||m(e),e.luma=e.luma||{},e.luma.canvasSizeInfo=e.luma.canvasSizeInfo||{};var A=t=Object.assign({},d,t),r=A.manageState,i=A.debug;return r&&Object(o.c)(e,{copyState:!1,log:function(){for(var e=arguments.length,t=new Array(e),A=0;A1&&void 0!==arguments[1]?arguments[1]:{};if(e.canvas){var A=u(t.useDevicePixels);b(e,A,t)}else{var n=e.getExtension("STACKGL_resize_drawingbuffer");n&&"width"in t&&"height"in t&&n.resize(t.width,t.height)}}function Q(e,t){var A=t.onError,n=null,r=function(e){return n=e.statusMessage||n};e.addEventListener("webglcontextcreationerror",r,!1);var i=t.webgl1,o=void 0===i||i,a=t.webgl2,s=void 0===a||a,g=null;return s&&(g=(g=g||e.getContext("webgl2",t))||e.getContext("experimental-webgl2",t)),o&&(g=(g=g||e.getContext("webgl",t))||e.getContext("experimental-webgl",t)),e.removeEventListener("webglcontextcreationerror",r,!1),g?(t.onContextLost&&e.addEventListener("webglcontextlost",t.onContextLost,!1),t.onContextRestored&&e.addEventListener("webglcontextrestored",t.onContextRestored,!1),g):A("Failed to create ".concat(s&&!o?"WebGL2":"WebGL"," context: ").concat(n||"Unknown error"))}function y(e){var t,A=e.canvas,n=e.width,r=void 0===n?800:n,i=e.height,o=void 0===i?600:i,a=e.onError;"string"===typeof A?(f&&"complete"===document.readyState||a("createGLContext called on canvas '".concat(A,"' before page was loaded")),t=document.getElementById(A)):A?t=A:((t=document.createElement("canvas")).id="lumagl-canvas",t.style.width=Number.isFinite(r)?"".concat(r,"px"):"100%",t.style.height=Number.isFinite(o)?"".concat(o,"px"):"100%",document.body.insertBefore(t,document.body.firstChild));return t}function v(e){var t=Object(r.e)(e)?"WebGL2":"WebGL1",A=function(e){var t=e.getParameter(7936),A=e.getParameter(7937),n=e.getExtension("WEBGL_debug_renderer_info");return{vendor:n&&e.getParameter(n.UNMASKED_VENDOR_WEBGL||7936)||t,renderer:n&&e.getParameter(n.UNMASKED_RENDERER_WEBGL||7937)||A,vendorMasked:t,rendererMasked:A,version:e.getParameter(7938),shadingLanguageVersion:e.getParameter(35724)}}(e),i=A?"(".concat(A.vendor,",").concat(A.renderer,")"):"",o=e.debug?" debug":"";n.info(1,"".concat(t).concat(o," context ").concat(i))()}function m(e){return"undefined"!==typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext?2:1}function b(e,t,A){var r="width"in A?A.width:e.canvas.clientWidth,i="height"in A?A.height:e.canvas.clientHeight;r&&i||(n.log(1,"Canvas clientWidth/clientHeight is 0")(),t=1,r=e.canvas.width||1,i=e.canvas.height||1),e.luma=e.luma||{},e.luma.canvasSizeInfo=e.luma.canvasSizeInfo||{};var o=e.luma.canvasSizeInfo;if(o.clientWidth!==r||o.clientHeight!==i||o.devicePixelRatio!==t){var a=t,s=Math.floor(r*a),g=Math.floor(i*a);e.canvas.width=s,e.canvas.height=g,e.drawingBufferWidth===s&&e.drawingBufferHeight===g||(n.warn("Device pixel ratio clamped")(),a=Math.min(e.drawingBufferWidth/r,e.drawingBufferHeight/i),e.canvas.width=Math.floor(r*a),e.canvas.height=Math.floor(i*a)),Object.assign(e.luma.canvasSizeInfo,{clientWidth:r,clientHeight:i,devicePixelRatio:t})}}A.d(t,"k",(function(){return n})),A.d(t,"i",(function(){return r.d})),A.d(t,"j",(function(){return r.e})),A.d(t,"g",(function(){return r.c})),A.d(t,"b",(function(){return r.b})),A.d(t,"a",(function(){return r.a})),A.d(t,"f",(function(){return i.a})),A.d(t,"n",(function(){return i.c})),A.d(t,"l",(function(){return i.b})),A.d(t,"o",(function(){return i.d})),A.d(t,"c",(function(){return B})),A.d(t,"m",(function(){return E})),A.d(t,"h",(function(){return p})),A.d(t,"e",(function(){return g})),A.d(t,"d",(function(){return c}))},function(e,t,A){"use strict";function n(e){var t,A,r="";if("string"===typeof e||"number"===typeof e)r+=e;else if("object"===typeof e)if(Array.isArray(e))for(t=0;t=0||Object.prototype.propertyIsEnumerable.call(e,A)&&(i[A]=e[A])}return i}},function(e,t,A){"use strict";A.r(t),t.default={DEPTH_BUFFER_BIT:256,STENCIL_BUFFER_BIT:1024,COLOR_BUFFER_BIT:16384,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,ZERO:0,ONE:1,SRC_COLOR:768,ONE_MINUS_SRC_COLOR:769,SRC_ALPHA:770,ONE_MINUS_SRC_ALPHA:771,DST_ALPHA:772,ONE_MINUS_DST_ALPHA:773,DST_COLOR:774,ONE_MINUS_DST_COLOR:775,SRC_ALPHA_SATURATE:776,CONSTANT_COLOR:32769,ONE_MINUS_CONSTANT_COLOR:32770,CONSTANT_ALPHA:32771,ONE_MINUS_CONSTANT_ALPHA:32772,FUNC_ADD:32774,FUNC_SUBTRACT:32778,FUNC_REVERSE_SUBTRACT:32779,BLEND_EQUATION:32777,BLEND_EQUATION_RGB:32777,BLEND_EQUATION_ALPHA:34877,BLEND_DST_RGB:32968,BLEND_SRC_RGB:32969,BLEND_DST_ALPHA:32970,BLEND_SRC_ALPHA:32971,BLEND_COLOR:32773,ARRAY_BUFFER_BINDING:34964,ELEMENT_ARRAY_BUFFER_BINDING:34965,LINE_WIDTH:2849,ALIASED_POINT_SIZE_RANGE:33901,ALIASED_LINE_WIDTH_RANGE:33902,CULL_FACE_MODE:2885,FRONT_FACE:2886,DEPTH_RANGE:2928,DEPTH_WRITEMASK:2930,DEPTH_CLEAR_VALUE:2931,DEPTH_FUNC:2932,STENCIL_CLEAR_VALUE:2961,STENCIL_FUNC:2962,STENCIL_FAIL:2964,STENCIL_PASS_DEPTH_FAIL:2965,STENCIL_PASS_DEPTH_PASS:2966,STENCIL_REF:2967,STENCIL_VALUE_MASK:2963,STENCIL_WRITEMASK:2968,STENCIL_BACK_FUNC:34816,STENCIL_BACK_FAIL:34817,STENCIL_BACK_PASS_DEPTH_FAIL:34818,STENCIL_BACK_PASS_DEPTH_PASS:34819,STENCIL_BACK_REF:36003,STENCIL_BACK_VALUE_MASK:36004,STENCIL_BACK_WRITEMASK:36005,VIEWPORT:2978,SCISSOR_BOX:3088,COLOR_CLEAR_VALUE:3106,COLOR_WRITEMASK:3107,UNPACK_ALIGNMENT:3317,PACK_ALIGNMENT:3333,MAX_TEXTURE_SIZE:3379,MAX_VIEWPORT_DIMS:3386,SUBPIXEL_BITS:3408,RED_BITS:3410,GREEN_BITS:3411,BLUE_BITS:3412,ALPHA_BITS:3413,DEPTH_BITS:3414,STENCIL_BITS:3415,POLYGON_OFFSET_UNITS:10752,POLYGON_OFFSET_FACTOR:32824,TEXTURE_BINDING_2D:32873,SAMPLE_BUFFERS:32936,SAMPLES:32937,SAMPLE_COVERAGE_VALUE:32938,SAMPLE_COVERAGE_INVERT:32939,COMPRESSED_TEXTURE_FORMATS:34467,VENDOR:7936,RENDERER:7937,VERSION:7938,IMPLEMENTATION_COLOR_READ_TYPE:35738,IMPLEMENTATION_COLOR_READ_FORMAT:35739,BROWSER_DEFAULT_WEBGL:37444,STATIC_DRAW:35044,STREAM_DRAW:35040,DYNAMIC_DRAW:35048,ARRAY_BUFFER:34962,ELEMENT_ARRAY_BUFFER:34963,BUFFER_SIZE:34660,BUFFER_USAGE:34661,CURRENT_VERTEX_ATTRIB:34342,VERTEX_ATTRIB_ARRAY_ENABLED:34338,VERTEX_ATTRIB_ARRAY_SIZE:34339,VERTEX_ATTRIB_ARRAY_STRIDE:34340,VERTEX_ATTRIB_ARRAY_TYPE:34341,VERTEX_ATTRIB_ARRAY_NORMALIZED:34922,VERTEX_ATTRIB_ARRAY_POINTER:34373,VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:34975,CULL_FACE:2884,FRONT:1028,BACK:1029,FRONT_AND_BACK:1032,BLEND:3042,DEPTH_TEST:2929,DITHER:3024,POLYGON_OFFSET_FILL:32823,SAMPLE_ALPHA_TO_COVERAGE:32926,SAMPLE_COVERAGE:32928,SCISSOR_TEST:3089,STENCIL_TEST:2960,NO_ERROR:0,INVALID_ENUM:1280,INVALID_VALUE:1281,INVALID_OPERATION:1282,OUT_OF_MEMORY:1285,CONTEXT_LOST_WEBGL:37442,CW:2304,CCW:2305,DONT_CARE:4352,FASTEST:4353,NICEST:4354,GENERATE_MIPMAP_HINT:33170,BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,DOUBLE:5130,DEPTH_COMPONENT:6402,ALPHA:6406,RGB:6407,RGBA:6408,LUMINANCE:6409,LUMINANCE_ALPHA:6410,UNSIGNED_SHORT_4_4_4_4:32819,UNSIGNED_SHORT_5_5_5_1:32820,UNSIGNED_SHORT_5_6_5:33635,FRAGMENT_SHADER:35632,VERTEX_SHADER:35633,COMPILE_STATUS:35713,DELETE_STATUS:35712,LINK_STATUS:35714,VALIDATE_STATUS:35715,ATTACHED_SHADERS:35717,ACTIVE_ATTRIBUTES:35721,ACTIVE_UNIFORMS:35718,MAX_VERTEX_ATTRIBS:34921,MAX_VERTEX_UNIFORM_VECTORS:36347,MAX_VARYING_VECTORS:36348,MAX_COMBINED_TEXTURE_IMAGE_UNITS:35661,MAX_VERTEX_TEXTURE_IMAGE_UNITS:35660,MAX_TEXTURE_IMAGE_UNITS:34930,MAX_FRAGMENT_UNIFORM_VECTORS:36349,SHADER_TYPE:35663,SHADING_LANGUAGE_VERSION:35724,CURRENT_PROGRAM:35725,NEVER:512,ALWAYS:519,LESS:513,EQUAL:514,LEQUAL:515,GREATER:516,GEQUAL:518,NOTEQUAL:517,KEEP:7680,REPLACE:7681,INCR:7682,DECR:7683,INVERT:5386,INCR_WRAP:34055,DECR_WRAP:34056,NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987,TEXTURE_MAG_FILTER:10240,TEXTURE_MIN_FILTER:10241,TEXTURE_WRAP_S:10242,TEXTURE_WRAP_T:10243,TEXTURE_2D:3553,TEXTURE:5890,TEXTURE_CUBE_MAP:34067,TEXTURE_BINDING_CUBE_MAP:34068,TEXTURE_CUBE_MAP_POSITIVE_X:34069,TEXTURE_CUBE_MAP_NEGATIVE_X:34070,TEXTURE_CUBE_MAP_POSITIVE_Y:34071,TEXTURE_CUBE_MAP_NEGATIVE_Y:34072,TEXTURE_CUBE_MAP_POSITIVE_Z:34073,TEXTURE_CUBE_MAP_NEGATIVE_Z:34074,MAX_CUBE_MAP_TEXTURE_SIZE:34076,TEXTURE0:33984,ACTIVE_TEXTURE:34016,REPEAT:10497,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,TEXTURE_WIDTH:4096,TEXTURE_HEIGHT:4097,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,INT_VEC2:35667,INT_VEC3:35668,INT_VEC4:35669,BOOL:35670,BOOL_VEC2:35671,BOOL_VEC3:35672,BOOL_VEC4:35673,FLOAT_MAT2:35674,FLOAT_MAT3:35675,FLOAT_MAT4:35676,SAMPLER_2D:35678,SAMPLER_CUBE:35680,LOW_FLOAT:36336,MEDIUM_FLOAT:36337,HIGH_FLOAT:36338,LOW_INT:36339,MEDIUM_INT:36340,HIGH_INT:36341,FRAMEBUFFER:36160,RENDERBUFFER:36161,RGBA4:32854,RGB5_A1:32855,RGB565:36194,DEPTH_COMPONENT16:33189,STENCIL_INDEX:6401,STENCIL_INDEX8:36168,DEPTH_STENCIL:34041,RENDERBUFFER_WIDTH:36162,RENDERBUFFER_HEIGHT:36163,RENDERBUFFER_INTERNAL_FORMAT:36164,RENDERBUFFER_RED_SIZE:36176,RENDERBUFFER_GREEN_SIZE:36177,RENDERBUFFER_BLUE_SIZE:36178,RENDERBUFFER_ALPHA_SIZE:36179,RENDERBUFFER_DEPTH_SIZE:36180,RENDERBUFFER_STENCIL_SIZE:36181,FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:36048,FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:36049,FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:36050,FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:36051,COLOR_ATTACHMENT0:36064,DEPTH_ATTACHMENT:36096,STENCIL_ATTACHMENT:36128,DEPTH_STENCIL_ATTACHMENT:33306,NONE:0,FRAMEBUFFER_COMPLETE:36053,FRAMEBUFFER_INCOMPLETE_ATTACHMENT:36054,FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:36055,FRAMEBUFFER_INCOMPLETE_DIMENSIONS:36057,FRAMEBUFFER_UNSUPPORTED:36061,FRAMEBUFFER_BINDING:36006,RENDERBUFFER_BINDING:36007,READ_FRAMEBUFFER:36008,DRAW_FRAMEBUFFER:36009,MAX_RENDERBUFFER_SIZE:34024,INVALID_FRAMEBUFFER_OPERATION:1286,UNPACK_FLIP_Y_WEBGL:37440,UNPACK_PREMULTIPLY_ALPHA_WEBGL:37441,UNPACK_COLORSPACE_CONVERSION_WEBGL:37443,READ_BUFFER:3074,UNPACK_ROW_LENGTH:3314,UNPACK_SKIP_ROWS:3315,UNPACK_SKIP_PIXELS:3316,PACK_ROW_LENGTH:3330,PACK_SKIP_ROWS:3331,PACK_SKIP_PIXELS:3332,TEXTURE_BINDING_3D:32874,UNPACK_SKIP_IMAGES:32877,UNPACK_IMAGE_HEIGHT:32878,MAX_3D_TEXTURE_SIZE:32883,MAX_ELEMENTS_VERTICES:33e3,MAX_ELEMENTS_INDICES:33001,MAX_TEXTURE_LOD_BIAS:34045,MAX_FRAGMENT_UNIFORM_COMPONENTS:35657,MAX_VERTEX_UNIFORM_COMPONENTS:35658,MAX_ARRAY_TEXTURE_LAYERS:35071,MIN_PROGRAM_TEXEL_OFFSET:35076,MAX_PROGRAM_TEXEL_OFFSET:35077,MAX_VARYING_COMPONENTS:35659,FRAGMENT_SHADER_DERIVATIVE_HINT:35723,RASTERIZER_DISCARD:35977,VERTEX_ARRAY_BINDING:34229,MAX_VERTEX_OUTPUT_COMPONENTS:37154,MAX_FRAGMENT_INPUT_COMPONENTS:37157,MAX_SERVER_WAIT_TIMEOUT:37137,MAX_ELEMENT_INDEX:36203,RED:6403,RGB8:32849,RGBA8:32856,RGB10_A2:32857,TEXTURE_3D:32879,TEXTURE_WRAP_R:32882,TEXTURE_MIN_LOD:33082,TEXTURE_MAX_LOD:33083,TEXTURE_BASE_LEVEL:33084,TEXTURE_MAX_LEVEL:33085,TEXTURE_COMPARE_MODE:34892,TEXTURE_COMPARE_FUNC:34893,SRGB:35904,SRGB8:35905,SRGB8_ALPHA8:35907,COMPARE_REF_TO_TEXTURE:34894,RGBA32F:34836,RGB32F:34837,RGBA16F:34842,RGB16F:34843,TEXTURE_2D_ARRAY:35866,TEXTURE_BINDING_2D_ARRAY:35869,R11F_G11F_B10F:35898,RGB9_E5:35901,RGBA32UI:36208,RGB32UI:36209,RGBA16UI:36214,RGB16UI:36215,RGBA8UI:36220,RGB8UI:36221,RGBA32I:36226,RGB32I:36227,RGBA16I:36232,RGB16I:36233,RGBA8I:36238,RGB8I:36239,RED_INTEGER:36244,RGB_INTEGER:36248,RGBA_INTEGER:36249,R8:33321,RG8:33323,R16F:33325,R32F:33326,RG16F:33327,RG32F:33328,R8I:33329,R8UI:33330,R16I:33331,R16UI:33332,R32I:33333,R32UI:33334,RG8I:33335,RG8UI:33336,RG16I:33337,RG16UI:33338,RG32I:33339,RG32UI:33340,R8_SNORM:36756,RG8_SNORM:36757,RGB8_SNORM:36758,RGBA8_SNORM:36759,RGB10_A2UI:36975,TEXTURE_IMMUTABLE_FORMAT:37167,TEXTURE_IMMUTABLE_LEVELS:33503,UNSIGNED_INT_2_10_10_10_REV:33640,UNSIGNED_INT_10F_11F_11F_REV:35899,UNSIGNED_INT_5_9_9_9_REV:35902,FLOAT_32_UNSIGNED_INT_24_8_REV:36269,UNSIGNED_INT_24_8:34042,HALF_FLOAT:5131,RG:33319,RG_INTEGER:33320,INT_2_10_10_10_REV:36255,CURRENT_QUERY:34917,QUERY_RESULT:34918,QUERY_RESULT_AVAILABLE:34919,ANY_SAMPLES_PASSED:35887,ANY_SAMPLES_PASSED_CONSERVATIVE:36202,MAX_DRAW_BUFFERS:34852,DRAW_BUFFER0:34853,DRAW_BUFFER1:34854,DRAW_BUFFER2:34855,DRAW_BUFFER3:34856,DRAW_BUFFER4:34857,DRAW_BUFFER5:34858,DRAW_BUFFER6:34859,DRAW_BUFFER7:34860,DRAW_BUFFER8:34861,DRAW_BUFFER9:34862,DRAW_BUFFER10:34863,DRAW_BUFFER11:34864,DRAW_BUFFER12:34865,DRAW_BUFFER13:34866,DRAW_BUFFER14:34867,DRAW_BUFFER15:34868,MAX_COLOR_ATTACHMENTS:36063,COLOR_ATTACHMENT1:36065,COLOR_ATTACHMENT2:36066,COLOR_ATTACHMENT3:36067,COLOR_ATTACHMENT4:36068,COLOR_ATTACHMENT5:36069,COLOR_ATTACHMENT6:36070,COLOR_ATTACHMENT7:36071,COLOR_ATTACHMENT8:36072,COLOR_ATTACHMENT9:36073,COLOR_ATTACHMENT10:36074,COLOR_ATTACHMENT11:36075,COLOR_ATTACHMENT12:36076,COLOR_ATTACHMENT13:36077,COLOR_ATTACHMENT14:36078,COLOR_ATTACHMENT15:36079,SAMPLER_3D:35679,SAMPLER_2D_SHADOW:35682,SAMPLER_2D_ARRAY:36289,SAMPLER_2D_ARRAY_SHADOW:36292,SAMPLER_CUBE_SHADOW:36293,INT_SAMPLER_2D:36298,INT_SAMPLER_3D:36299,INT_SAMPLER_CUBE:36300,INT_SAMPLER_2D_ARRAY:36303,UNSIGNED_INT_SAMPLER_2D:36306,UNSIGNED_INT_SAMPLER_3D:36307,UNSIGNED_INT_SAMPLER_CUBE:36308,UNSIGNED_INT_SAMPLER_2D_ARRAY:36311,MAX_SAMPLES:36183,SAMPLER_BINDING:35097,PIXEL_PACK_BUFFER:35051,PIXEL_UNPACK_BUFFER:35052,PIXEL_PACK_BUFFER_BINDING:35053,PIXEL_UNPACK_BUFFER_BINDING:35055,COPY_READ_BUFFER:36662,COPY_WRITE_BUFFER:36663,COPY_READ_BUFFER_BINDING:36662,COPY_WRITE_BUFFER_BINDING:36663,FLOAT_MAT2x3:35685,FLOAT_MAT2x4:35686,FLOAT_MAT3x2:35687,FLOAT_MAT3x4:35688,FLOAT_MAT4x2:35689,FLOAT_MAT4x3:35690,UNSIGNED_INT_VEC2:36294,UNSIGNED_INT_VEC3:36295,UNSIGNED_INT_VEC4:36296,UNSIGNED_NORMALIZED:35863,SIGNED_NORMALIZED:36764,VERTEX_ATTRIB_ARRAY_INTEGER:35069,VERTEX_ATTRIB_ARRAY_DIVISOR:35070,TRANSFORM_FEEDBACK_BUFFER_MODE:35967,MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:35968,TRANSFORM_FEEDBACK_VARYINGS:35971,TRANSFORM_FEEDBACK_BUFFER_START:35972,TRANSFORM_FEEDBACK_BUFFER_SIZE:35973,TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:35976,MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:35978,MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:35979,INTERLEAVED_ATTRIBS:35980,SEPARATE_ATTRIBS:35981,TRANSFORM_FEEDBACK_BUFFER:35982,TRANSFORM_FEEDBACK_BUFFER_BINDING:35983,TRANSFORM_FEEDBACK:36386,TRANSFORM_FEEDBACK_PAUSED:36387,TRANSFORM_FEEDBACK_ACTIVE:36388,TRANSFORM_FEEDBACK_BINDING:36389,FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING:33296,FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE:33297,FRAMEBUFFER_ATTACHMENT_RED_SIZE:33298,FRAMEBUFFER_ATTACHMENT_GREEN_SIZE:33299,FRAMEBUFFER_ATTACHMENT_BLUE_SIZE:33300,FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE:33301,FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE:33302,FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE:33303,FRAMEBUFFER_DEFAULT:33304,DEPTH24_STENCIL8:35056,DRAW_FRAMEBUFFER_BINDING:36006,READ_FRAMEBUFFER_BINDING:36010,RENDERBUFFER_SAMPLES:36011,FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER:36052,FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:36182,UNIFORM_BUFFER:35345,UNIFORM_BUFFER_BINDING:35368,UNIFORM_BUFFER_START:35369,UNIFORM_BUFFER_SIZE:35370,MAX_VERTEX_UNIFORM_BLOCKS:35371,MAX_FRAGMENT_UNIFORM_BLOCKS:35373,MAX_COMBINED_UNIFORM_BLOCKS:35374,MAX_UNIFORM_BUFFER_BINDINGS:35375,MAX_UNIFORM_BLOCK_SIZE:35376,MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:35377,MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:35379,UNIFORM_BUFFER_OFFSET_ALIGNMENT:35380,ACTIVE_UNIFORM_BLOCKS:35382,UNIFORM_TYPE:35383,UNIFORM_SIZE:35384,UNIFORM_BLOCK_INDEX:35386,UNIFORM_OFFSET:35387,UNIFORM_ARRAY_STRIDE:35388,UNIFORM_MATRIX_STRIDE:35389,UNIFORM_IS_ROW_MAJOR:35390,UNIFORM_BLOCK_BINDING:35391,UNIFORM_BLOCK_DATA_SIZE:35392,UNIFORM_BLOCK_ACTIVE_UNIFORMS:35394,UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES:35395,UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER:35396,UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER:35398,OBJECT_TYPE:37138,SYNC_CONDITION:37139,SYNC_STATUS:37140,SYNC_FLAGS:37141,SYNC_FENCE:37142,SYNC_GPU_COMMANDS_COMPLETE:37143,UNSIGNALED:37144,SIGNALED:37145,ALREADY_SIGNALED:37146,TIMEOUT_EXPIRED:37147,CONDITION_SATISFIED:37148,WAIT_FAILED:37149,SYNC_FLUSH_COMMANDS_BIT:1,COLOR:6144,DEPTH:6145,STENCIL:6146,MIN:32775,MAX:32776,DEPTH_COMPONENT24:33190,STREAM_READ:35041,STREAM_COPY:35042,STATIC_READ:35045,STATIC_COPY:35046,DYNAMIC_READ:35049,DYNAMIC_COPY:35050,DEPTH_COMPONENT32F:36012,DEPTH32F_STENCIL8:36013,INVALID_INDEX:4294967295,TIMEOUT_IGNORED:-1,MAX_CLIENT_WAIT_TIMEOUT_WEBGL:37447,VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE:35070,UNMASKED_VENDOR_WEBGL:37445,UNMASKED_RENDERER_WEBGL:37446,MAX_TEXTURE_MAX_ANISOTROPY_EXT:34047,TEXTURE_MAX_ANISOTROPY_EXT:34046,COMPRESSED_RGB_S3TC_DXT1_EXT:33776,COMPRESSED_RGBA_S3TC_DXT1_EXT:33777,COMPRESSED_RGBA_S3TC_DXT3_EXT:33778,COMPRESSED_RGBA_S3TC_DXT5_EXT:33779,COMPRESSED_R11_EAC:37488,COMPRESSED_SIGNED_R11_EAC:37489,COMPRESSED_RG11_EAC:37490,COMPRESSED_SIGNED_RG11_EAC:37491,COMPRESSED_RGB8_ETC2:37492,COMPRESSED_RGBA8_ETC2_EAC:37493,COMPRESSED_SRGB8_ETC2:37494,COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:37495,COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:37496,COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:37497,COMPRESSED_RGB_PVRTC_4BPPV1_IMG:35840,COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:35842,COMPRESSED_RGB_PVRTC_2BPPV1_IMG:35841,COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:35843,COMPRESSED_RGB_ETC1_WEBGL:36196,COMPRESSED_RGB_ATC_WEBGL:35986,COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL:35986,COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL:34798,UNSIGNED_INT_24_8_WEBGL:34042,HALF_FLOAT_OES:36193,RGBA32F_EXT:34836,RGB32F_EXT:34837,FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT:33297,UNSIGNED_NORMALIZED_EXT:35863,MIN_EXT:32775,MAX_EXT:32776,SRGB_EXT:35904,SRGB_ALPHA_EXT:35906,SRGB8_ALPHA8_EXT:35907,FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT:33296,FRAGMENT_SHADER_DERIVATIVE_HINT_OES:35723,COLOR_ATTACHMENT0_WEBGL:36064,COLOR_ATTACHMENT1_WEBGL:36065,COLOR_ATTACHMENT2_WEBGL:36066,COLOR_ATTACHMENT3_WEBGL:36067,COLOR_ATTACHMENT4_WEBGL:36068,COLOR_ATTACHMENT5_WEBGL:36069,COLOR_ATTACHMENT6_WEBGL:36070,COLOR_ATTACHMENT7_WEBGL:36071,COLOR_ATTACHMENT8_WEBGL:36072,COLOR_ATTACHMENT9_WEBGL:36073,COLOR_ATTACHMENT10_WEBGL:36074,COLOR_ATTACHMENT11_WEBGL:36075,COLOR_ATTACHMENT12_WEBGL:36076,COLOR_ATTACHMENT13_WEBGL:36077,COLOR_ATTACHMENT14_WEBGL:36078,COLOR_ATTACHMENT15_WEBGL:36079,DRAW_BUFFER0_WEBGL:34853,DRAW_BUFFER1_WEBGL:34854,DRAW_BUFFER2_WEBGL:34855,DRAW_BUFFER3_WEBGL:34856,DRAW_BUFFER4_WEBGL:34857,DRAW_BUFFER5_WEBGL:34858,DRAW_BUFFER6_WEBGL:34859,DRAW_BUFFER7_WEBGL:34860,DRAW_BUFFER8_WEBGL:34861,DRAW_BUFFER9_WEBGL:34862,DRAW_BUFFER10_WEBGL:34863,DRAW_BUFFER11_WEBGL:34864,DRAW_BUFFER12_WEBGL:34865,DRAW_BUFFER13_WEBGL:34866,DRAW_BUFFER14_WEBGL:34867,DRAW_BUFFER15_WEBGL:34868,MAX_COLOR_ATTACHMENTS_WEBGL:36063,MAX_DRAW_BUFFERS_WEBGL:34852,VERTEX_ARRAY_BINDING_OES:34229,QUERY_COUNTER_BITS_EXT:34916,CURRENT_QUERY_EXT:34917,QUERY_RESULT_EXT:34918,QUERY_RESULT_AVAILABLE_EXT:34919,TIME_ELAPSED_EXT:35007,TIMESTAMP_EXT:36392,GPU_DISJOINT_EXT:36795}},function(e,t,A){"use strict";A.r(t);var n=A(156);A.d(t,"Vector2",(function(){return n.g})),A.d(t,"Vector3",(function(){return n.h})),A.d(t,"Vector4",(function(){return n.i})),A.d(t,"Matrix3",(function(){return n.b})),A.d(t,"Matrix4",(function(){return n.c})),A.d(t,"Quaternion",(function(){return n.e})),A.d(t,"config",(function(){return n.u})),A.d(t,"configure",(function(){return n.v})),A.d(t,"formatValue",(function(){return n.A})),A.d(t,"isArray",(function(){return n.B})),A.d(t,"clone",(function(){return n.t})),A.d(t,"equals",(function(){return n.y})),A.d(t,"exactEquals",(function(){return n.z})),A.d(t,"toRadians",(function(){return n.H})),A.d(t,"toDegrees",(function(){return n.G})),A.d(t,"radians",(function(){return n.D})),A.d(t,"degrees",(function(){return n.x})),A.d(t,"sin",(function(){return n.E})),A.d(t,"cos",(function(){return n.w})),A.d(t,"tan",(function(){return n.F})),A.d(t,"asin",(function(){return n.o})),A.d(t,"acos",(function(){return n.n})),A.d(t,"atan",(function(){return n.q})),A.d(t,"clamp",(function(){return n.s})),A.d(t,"lerp",(function(){return n.C})),A.d(t,"withEpsilon",(function(){return n.I})),A.d(t,"checkNumber",(function(){return n.r})),A.d(t,"_MathUtils",(function(){return n.k})),A.d(t,"SphericalCoordinates",(function(){return n.f})),A.d(t,"Pose",(function(){return n.d})),A.d(t,"Euler",(function(){return n.a})),A.d(t,"assert",(function(){return n.p})),A.d(t,"_SphericalCoordinates",(function(){return n.m})),A.d(t,"_Pose",(function(){return n.l})),A.d(t,"_Euler",(function(){return n.j}))},function(e,t,A){"use strict";function n(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";function n(e,t,A){return t in e?Object.defineProperty(e,t,{value:A,enumerable:!0,configurable:!0,writable:!0}):e[t]=A,e}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";function n(e,t){if(!e)throw new Error(t||"luma.gl: assertion failed.")}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";A.d(t,"p",(function(){return r})),A.d(t,"e",(function(){return i})),A.d(t,"a",(function(){return o})),A.d(t,"g",(function(){return a})),A.d(t,"o",(function(){return s})),A.d(t,"n",(function(){return g})),A.d(t,"j",(function(){return c})),A.d(t,"k",(function(){return u})),A.d(t,"l",(function(){return l})),A.d(t,"m",(function(){return I})),A.d(t,"d",(function(){return C})),A.d(t,"b",(function(){return h})),A.d(t,"c",(function(){return f})),A.d(t,"i",(function(){return d})),A.d(t,"h",(function(){return B})),A.d(t,"f",(function(){return p}));var n=A(31);function r(e,t){if(e===t){var A=t[1],n=t[2],r=t[3],i=t[6],o=t[7],a=t[11];e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=A,e[6]=t[9],e[7]=t[13],e[8]=n,e[9]=i,e[11]=t[14],e[12]=r,e[13]=o,e[14]=a}else e[0]=t[0],e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=t[1],e[5]=t[5],e[6]=t[9],e[7]=t[13],e[8]=t[2],e[9]=t[6],e[10]=t[10],e[11]=t[14],e[12]=t[3],e[13]=t[7],e[14]=t[11],e[15]=t[15];return e}function i(e,t){var A=t[0],n=t[1],r=t[2],i=t[3],o=t[4],a=t[5],s=t[6],g=t[7],c=t[8],u=t[9],l=t[10],I=t[11],C=t[12],h=t[13],f=t[14],d=t[15],B=A*a-n*o,p=A*s-r*o,E=A*g-i*o,Q=n*s-r*a,y=n*g-i*a,v=r*g-i*s,m=c*h-u*C,b=c*f-l*C,w=c*d-I*C,S=u*f-l*h,F=u*d-I*h,R=l*d-I*f,D=B*R-p*F+E*S+Q*w-y*b+v*m;return D?(D=1/D,e[0]=(a*R-s*F+g*S)*D,e[1]=(r*F-n*R-i*S)*D,e[2]=(h*v-f*y+d*Q)*D,e[3]=(l*y-u*v-I*Q)*D,e[4]=(s*w-o*R-g*b)*D,e[5]=(A*R-r*w+i*b)*D,e[6]=(f*E-C*v-d*p)*D,e[7]=(c*v-l*E+I*p)*D,e[8]=(o*F-a*w+g*m)*D,e[9]=(n*w-A*F-i*m)*D,e[10]=(C*y-h*E+d*B)*D,e[11]=(u*E-c*y-I*B)*D,e[12]=(a*b-o*S-s*m)*D,e[13]=(A*S-n*b+r*m)*D,e[14]=(h*p-C*Q-f*B)*D,e[15]=(c*Q-u*p+l*B)*D,e):null}function o(e){var t=e[0],A=e[1],n=e[2],r=e[3],i=e[4],o=e[5],a=e[6],s=e[7],g=e[8],c=e[9],u=e[10],l=e[11],I=e[12],C=e[13],h=e[14],f=e[15];return(t*o-A*i)*(u*f-l*h)-(t*a-n*i)*(c*f-l*C)+(t*s-r*i)*(c*h-u*C)+(A*a-n*o)*(g*f-l*I)-(A*s-r*o)*(g*h-u*I)+(n*s-r*a)*(g*C-c*I)}function a(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],s=t[5],g=t[6],c=t[7],u=t[8],l=t[9],I=t[10],C=t[11],h=t[12],f=t[13],d=t[14],B=t[15],p=A[0],E=A[1],Q=A[2],y=A[3];return e[0]=p*n+E*a+Q*u+y*h,e[1]=p*r+E*s+Q*l+y*f,e[2]=p*i+E*g+Q*I+y*d,e[3]=p*o+E*c+Q*C+y*B,p=A[4],E=A[5],Q=A[6],y=A[7],e[4]=p*n+E*a+Q*u+y*h,e[5]=p*r+E*s+Q*l+y*f,e[6]=p*i+E*g+Q*I+y*d,e[7]=p*o+E*c+Q*C+y*B,p=A[8],E=A[9],Q=A[10],y=A[11],e[8]=p*n+E*a+Q*u+y*h,e[9]=p*r+E*s+Q*l+y*f,e[10]=p*i+E*g+Q*I+y*d,e[11]=p*o+E*c+Q*C+y*B,p=A[12],E=A[13],Q=A[14],y=A[15],e[12]=p*n+E*a+Q*u+y*h,e[13]=p*r+E*s+Q*l+y*f,e[14]=p*i+E*g+Q*I+y*d,e[15]=p*o+E*c+Q*C+y*B,e}function s(e,t,A){var n,r,i,o,a,s,g,c,u,l,I,C,h=A[0],f=A[1],d=A[2];return t===e?(e[12]=t[0]*h+t[4]*f+t[8]*d+t[12],e[13]=t[1]*h+t[5]*f+t[9]*d+t[13],e[14]=t[2]*h+t[6]*f+t[10]*d+t[14],e[15]=t[3]*h+t[7]*f+t[11]*d+t[15]):(n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],s=t[5],g=t[6],c=t[7],u=t[8],l=t[9],I=t[10],C=t[11],e[0]=n,e[1]=r,e[2]=i,e[3]=o,e[4]=a,e[5]=s,e[6]=g,e[7]=c,e[8]=u,e[9]=l,e[10]=I,e[11]=C,e[12]=n*h+a*f+u*d+t[12],e[13]=r*h+s*f+l*d+t[13],e[14]=i*h+g*f+I*d+t[14],e[15]=o*h+c*f+C*d+t[15]),e}function g(e,t,A){var n=A[0],r=A[1],i=A[2];return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*i,e[9]=t[9]*i,e[10]=t[10]*i,e[11]=t[11]*i,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function c(e,t,A,r){var i,o,a,s,g,c,u,l,I,C,h,f,d,B,p,E,Q,y,v,m,b,w,S,F,R=r[0],D=r[1],G=r[2],k=Math.hypot(R,D,G);return k1&&void 0!==arguments[1]?arguments[1]:{};return function(A){var i=t.defaultTheme,a=t.withTheme,l=void 0!==a&&a,I=t.name,C=Object(r.a)(t,["defaultTheme","withTheme","name"]);var h=I,f=Object(g.a)(e,Object(n.a)({defaultTheme:i,Component:A,name:I||A.displayName,classNamePrefix:h},C)),d=o.a.forwardRef((function(e,t){e.classes;var a,s=e.innerRef,g=Object(r.a)(e,["classes","innerRef"]),C=f(Object(n.a)({},A.defaultProps,e)),h=g;return("string"===typeof I||l)&&(a=Object(u.a)()||i,I&&(h=Object(c.a)({theme:a,name:I,props:g})),l&&!h.theme&&(h.theme=a)),o.a.createElement(A,Object(n.a)({ref:s||t,classes:C},h))}));return s()(d,A),d}},I=A(205);t.a=function(e,t){return l(e,Object(n.a)({defaultTheme:I.a},t))}},function(e,t,A){"use strict";A.d(t,"b",(function(){return r})),A.d(t,"g",(function(){return i})),A.d(t,"e",(function(){return o})),A.d(t,"i",(function(){return a})),A.d(t,"d",(function(){return s})),A.d(t,"c",(function(){return g})),A.d(t,"h",(function(){return c})),A.d(t,"p",(function(){return u})),A.d(t,"o",(function(){return l})),A.d(t,"q",(function(){return I})),A.d(t,"j",(function(){return C})),A.d(t,"k",(function(){return h})),A.d(t,"l",(function(){return f})),A.d(t,"a",(function(){return d})),A.d(t,"n",(function(){return B})),A.d(t,"f",(function(){return p})),A.d(t,"m",(function(){return E}));var n=A(31);function r(){var e=new n.a(3);return n.a!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e}function i(e){var t=e[0],A=e[1],n=e[2];return Math.hypot(t,A,n)}function o(e,t,A){var r=new n.a(3);return r[0]=e,r[1]=t,r[2]=A,r}function a(e,t){var A=t[0],n=t[1],r=t[2],i=A*A+n*n+r*r;return i>0&&(i=1/Math.sqrt(i)),e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e}function s(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function g(e,t,A){var n=t[0],r=t[1],i=t[2],o=A[0],a=A[1],s=A[2];return e[0]=r*s-i*a,e[1]=i*o-n*s,e[2]=n*a-r*o,e}function c(e,t,A,n){var r=t[0],i=t[1],o=t[2];return e[0]=r+n*(A[0]-r),e[1]=i+n*(A[1]-i),e[2]=o+n*(A[2]-o),e}function u(e,t,A){var n=t[0],r=t[1],i=t[2],o=A[3]*n+A[7]*r+A[11]*i+A[15];return o=o||1,e[0]=(A[0]*n+A[4]*r+A[8]*i+A[12])/o,e[1]=(A[1]*n+A[5]*r+A[9]*i+A[13])/o,e[2]=(A[2]*n+A[6]*r+A[10]*i+A[14])/o,e}function l(e,t,A){var n=t[0],r=t[1],i=t[2];return e[0]=n*A[0]+r*A[3]+i*A[6],e[1]=n*A[1]+r*A[4]+i*A[7],e[2]=n*A[2]+r*A[5]+i*A[8],e}function I(e,t,A){var n=A[0],r=A[1],i=A[2],o=A[3],a=t[0],s=t[1],g=t[2],c=r*g-i*s,u=i*a-n*g,l=n*s-r*a,I=r*l-i*u,C=i*c-n*l,h=n*u-r*c,f=2*o;return c*=f,u*=f,l*=f,I*=2,C*=2,h*=2,e[0]=a+c+I,e[1]=s+u+C,e[2]=g+l+h,e}function C(e,t,A,n){var r=[],i=[];return r[0]=t[0]-A[0],r[1]=t[1]-A[1],r[2]=t[2]-A[2],i[0]=r[0],i[1]=r[1]*Math.cos(n)-r[2]*Math.sin(n),i[2]=r[1]*Math.sin(n)+r[2]*Math.cos(n),e[0]=i[0]+A[0],e[1]=i[1]+A[1],e[2]=i[2]+A[2],e}function h(e,t,A,n){var r=[],i=[];return r[0]=t[0]-A[0],r[1]=t[1]-A[1],r[2]=t[2]-A[2],i[0]=r[2]*Math.sin(n)+r[0]*Math.cos(n),i[1]=r[1],i[2]=r[2]*Math.cos(n)-r[0]*Math.sin(n),e[0]=i[0]+A[0],e[1]=i[1]+A[1],e[2]=i[2]+A[2],e}function f(e,t,A,n){var r=[],i=[];return r[0]=t[0]-A[0],r[1]=t[1]-A[1],r[2]=t[2]-A[2],i[0]=r[0]*Math.cos(n)-r[1]*Math.sin(n),i[1]=r[0]*Math.sin(n)+r[1]*Math.cos(n),i[2]=r[2],e[0]=i[0]+A[0],e[1]=i[1]+A[1],e[2]=i[2]+A[2],e}function d(e,t){var A=e[0],n=e[1],r=e[2],i=t[0],o=t[1],a=t[2],g=Math.sqrt(A*A+n*n+r*r)*Math.sqrt(i*i+o*o+a*a),c=g&&s(e,t)/g;return Math.acos(Math.min(Math.max(c,-1),1))}var B=function(e,t,A){return e[0]=t[0]-A[0],e[1]=t[1]-A[1],e[2]=t[2]-A[2],e},p=i,E=function(e){var t=e[0],A=e[1],n=e[2];return t*t+A*A+n*n};!function(){var e=r()}()},function(e,t,A){"use strict";A.d(t,"b",(function(){return n})),A.d(t,"a",(function(){return r})),A.d(t,"c",(function(){return i}));var n=1e-6,r="undefined"!==typeof Float32Array?Float32Array:Array,i=Math.random;Math.PI;Math.hypot||(Math.hypot=function(){for(var e=0,t=arguments.length;t--;)e+=arguments[t]*arguments[t];return Math.sqrt(e)})},function(e,t,A){"use strict";A.d(t,"b",(function(){return n})),A.d(t,"a",(function(){return r})),A.d(t,"c",(function(){return i}));var n=1e-6,r="undefined"!==typeof Float32Array?Float32Array:Array,i=Math.random;Math.PI;Math.hypot||(Math.hypot=function(){for(var e=0,t=arguments.length;t--;)e+=arguments[t]*arguments[t];return Math.sqrt(e)})},function(e,t,A){"use strict";A.d(t,"f",(function(){return s})),A.d(t,"g",(function(){return g})),A.d(t,"l",(function(){return u})),A.d(t,"m",(function(){return l})),A.d(t,"e",(function(){return I})),A.d(t,"s",(function(){return h})),A.d(t,"r",(function(){return f})),A.d(t,"o",(function(){return d})),A.d(t,"i",(function(){return B})),A.d(t,"p",(function(){return p})),A.d(t,"h",(function(){return E})),A.d(t,"q",(function(){return Q})),A.d(t,"b",(function(){return y})),A.d(t,"a",(function(){return v})),A.d(t,"c",(function(){return m})),A.d(t,"d",(function(){return b})),A.d(t,"n",(function(){return w})),A.d(t,"j",(function(){return S})),A.d(t,"k",(function(){return F})),A.d(t,"t",(function(){return R}));var n=A(91),r=A(11),i=A(97),o=1/Math.PI*180,a=1/180*Math.PI,s={};function g(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e)Object(i.a)(t in s),s[t]=e[t];return s}function c(e){return Math.round(e/s.EPSILON)*s.EPSILON}function u(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.precision,n=void 0===A?s.precision||4:A;return e=c(e),"".concat(parseFloat(e.toPrecision(n)))}function l(e){return Array.isArray(e)||ArrayBuffer.isView(e)&&!(e instanceof DataView)}function I(e){return e.clone?e.clone():Object(n.a)(Array,Object(r.a)(e))}function C(e,t,A){if(l(e)){A=A||((r=e).clone?r.clone():new Array(r.length));for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:"";if(n.f.debug&&!r(e,t))throw new Error("math.gl: ".concat(A," some fields set to invalid numbers'"));return e}var a={};function s(e,t){a[e]||(a[e]=!0,console.warn("".concat(e," has been removed in version ").concat(t,", see upgrade guide for more information")))}},function(e,t,A){"use strict";A.d(t,"f",(function(){return s})),A.d(t,"p",(function(){return g})),A.d(t,"j",(function(){return c})),A.d(t,"k",(function(){return u})),A.d(t,"l",(function(){return l})),A.d(t,"m",(function(){return I})),A.d(t,"b",(function(){return C})),A.d(t,"q",(function(){return h})),A.d(t,"g",(function(){return f})),A.d(t,"c",(function(){return d})),A.d(t,"e",(function(){return B})),A.d(t,"a",(function(){return p})),A.d(t,"o",(function(){return E})),A.d(t,"d",(function(){return Q})),A.d(t,"i",(function(){return y})),A.d(t,"h",(function(){return v})),A.d(t,"r",(function(){return m})),A.d(t,"n",(function(){return w}));var n=A(31),r=A(58),i=A(29),o=A(56);function a(){var e=new n.a(4);return n.a!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e[3]=1,e}function s(e){return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e}function g(e,t,A){A*=.5;var n=Math.sin(A);return e[0]=n*t[0],e[1]=n*t[1],e[2]=n*t[2],e[3]=Math.cos(A),e}function c(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3],a=A[0],s=A[1],g=A[2],c=A[3];return e[0]=n*c+o*a+r*g-i*s,e[1]=r*c+o*s+i*a-n*g,e[2]=i*c+o*g+n*s-r*a,e[3]=o*c-n*a-r*s-i*g,e}function u(e,t,A){A*=.5;var n=t[0],r=t[1],i=t[2],o=t[3],a=Math.sin(A),s=Math.cos(A);return e[0]=n*s+o*a,e[1]=r*s+i*a,e[2]=i*s-r*a,e[3]=o*s-n*a,e}function l(e,t,A){A*=.5;var n=t[0],r=t[1],i=t[2],o=t[3],a=Math.sin(A),s=Math.cos(A);return e[0]=n*s-i*a,e[1]=r*s+o*a,e[2]=i*s+n*a,e[3]=o*s-r*a,e}function I(e,t,A){A*=.5;var n=t[0],r=t[1],i=t[2],o=t[3],a=Math.sin(A),s=Math.cos(A);return e[0]=n*s+r*a,e[1]=r*s-n*a,e[2]=i*s+o*a,e[3]=o*s-i*a,e}function C(e,t){var A=t[0],n=t[1],r=t[2];return e[0]=A,e[1]=n,e[2]=r,e[3]=Math.sqrt(Math.abs(1-A*A-n*n-r*r)),e}function h(e,t,A,r){var i,o,a,s,g,c=t[0],u=t[1],l=t[2],I=t[3],C=A[0],h=A[1],f=A[2],d=A[3];return(o=c*C+u*h+l*f+I*d)<0&&(o=-o,C=-C,h=-h,f=-f,d=-d),1-o>n.b?(i=Math.acos(o),a=Math.sin(i),s=Math.sin((1-r)*i)/a,g=Math.sin(r*i)/a):(s=1-r,g=r),e[0]=s*c+g*C,e[1]=s*u+g*h,e[2]=s*l+g*f,e[3]=s*I+g*d,e}function f(e,t){var A=t[0],n=t[1],r=t[2],i=t[3],o=A*A+n*n+r*r+i*i,a=o?1/o:0;return e[0]=-A*a,e[1]=-n*a,e[2]=-r*a,e[3]=i*a,e}function d(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=t[3],e}function B(e,t){var A,n=t[0]+t[4]+t[8];if(n>0)A=Math.sqrt(n+1),e[3]=.5*A,A=.5/A,e[0]=(t[5]-t[7])*A,e[1]=(t[6]-t[2])*A,e[2]=(t[1]-t[3])*A;else{var r=0;t[4]>t[0]&&(r=1),t[8]>t[3*r+r]&&(r=2);var i=(r+1)%3,o=(r+2)%3;A=Math.sqrt(t[3*r+r]-t[3*i+i]-t[3*o+o]+1),e[r]=.5*A,A=.5/A,e[3]=(t[3*i+o]-t[3*o+i])*A,e[i]=(t[3*i+r]+t[3*r+i])*A,e[o]=(t[3*o+r]+t[3*r+o])*A}return e}o.b,o.g,o.c,o.l;var p=o.a,E=o.k,Q=o.d,y=o.i,v=o.h,m=o.m,b=o.j,w=(o.f,o.e,function(){var e=i.b(),t=i.e(1,0,0),A=i.e(0,1,0);return function(n,r,o){var a=i.d(r,o);return a<-.999999?(i.c(e,t,r),i.f(e)<1e-6&&i.c(e,A,r),i.i(e,e),g(n,e,Math.PI),n):a>.999999?(n[0]=0,n[1]=0,n[2]=0,n[3]=1,n):(i.c(e,r,o),n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=1+a,b(n,n))}}());(function(){var e=a(),t=a()})(),function(){var e=r.a()}()},function(e,t,A){"use strict";A.r(t);var n=A(36),r=A(318),i=A(383),o=A(222),a=A(7),s=A(1),g=A(4),c=A(324),u=[255,255,255],l=[0,0,1],I=[0,0,1],C=0,h=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(s.a)(this,e);var A=t.color,n=void 0===A?u:A,r=t.intensity,i=void 0===r?1:r,o=t.position,g=void 0===o?I:o;this.id=t.id||"point-".concat(C++),this.color=n,this.intensity=i,this.type="point",this.position=g,this.attenuation=f(t),this.projectedLight=Object(a.a)({},this)}return Object(g.a)(e,[{key:"getProjectedLight",value:function(e){var t=e.layer,A=this.projectedLight,r=t.context.viewport,i=t.props,o=i.coordinateSystem,a=i.coordinateOrigin,s=Object(c.b)(this.position,{viewport:r,coordinateSystem:o,coordinateOrigin:a,fromCoordinateSystem:r.isGeospatial?n.a.LNGLAT:n.a.CARTESIAN,fromCoordinateOrigin:[0,0,0]});return A.color=this.color,A.intensity=this.intensity,A.position=s,A}}]),e}();function f(e){return"attenuation"in e?e.attenuation:"intensity"in e?[0,0,e.intensity]:l}var d=A(9),B=A(10),p=A(274),E=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(){return Object(s.a)(this,A),t.apply(this,arguments)}return Object(g.a)(A,[{key:"getProjectedLight",value:function(e){var t=e.layer,A=this.projectedLight,n=t.context.viewport,r=t.props,i=r.coordinateSystem,o=r.coordinateOrigin,a=r.modelMatrix,s=Object(p.b)({viewport:n,modelMatrix:a,coordinateSystem:i,coordinateOrigin:o}).project_uCameraPosition;return A.color=this.color,A.intensity=this.intensity,A.position=s,A}}]),A}(h),Q=A(8),y=A(83),v=Math.PI/180,m=23.4397*v;function b(e,t,A){var n=v*-A,r=v*t,i=function(e){return function(e){return e/864e5-.5+2440588}(e)-2451545}(e),o=function(e){var t=function(e){var t=e,A=v*(1.9148*Math.sin(t)+.02*Math.sin(2*t)+3e-4*Math.sin(3*t));return t+A+102.9372*v+Math.PI}((A=e,v*(357.5291+.98560028*A)));var A;return{declination:F(t,0),rightAscension:S(t,0)}}(i),a=function(e,t){return v*(280.147+360.9856235*e)-t}(i,n)-o.rightAscension;return{azimuth:R(a,r,o.declination),altitude:D(a,r,o.declination)}}function w(e,t,A){var n=b(e,t,A),r=n.azimuth,i=n.altitude;return[Math.sin(r)*Math.cos(i),Math.cos(r)*Math.cos(i),-Math.sin(i)]}function S(e,t){var A=e;return Math.atan2(Math.sin(A)*Math.cos(m)-Math.tan(t)*Math.sin(m),Math.cos(A))}function F(e,t){var A=e;return Math.asin(Math.sin(t)*Math.cos(m)+Math.cos(t)*Math.sin(m)*Math.sin(A))}function R(e,t,A){var n=e,r=t,i=A;return Math.atan2(Math.sin(n),Math.cos(n)*Math.sin(r)-Math.tan(i)*Math.cos(r))}function D(e,t,A){var n=e,r=t,i=A;return Math.asin(Math.sin(r)*Math.sin(i)+Math.cos(r)*Math.cos(i)*Math.cos(n))}var G=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){var n,r=e.timestamp,i=Object(y.a)(e,["timestamp"]);return Object(s.a)(this,A),(n=t.call(this,i)).timestamp=r,n}return Object(g.a)(A,[{key:"getProjectedLight",value:function(e){var t=e.layer.context.viewport;if(t.resolution>0){var A=w(this.timestamp,0,0),n=Object(Q.a)(A,3),r=n[0],i=n[1],o=n[2];this.direction=[r,-o,i]}else{var a=t.latitude,s=t.longitude;this.direction=w(this.timestamp,a,s)}return this}}]),A}(o.a),k=A(6),x=A(198),N=A(1257),U=A(18),_=A(428),M=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){var n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object(s.a)(this,A),n=t.call(this,e,r);var i=r.module,o=r.fs,a=r.id;return n.model=new N.a(e,{id:a,fs:o,modules:[i]}),n}return Object(g.a)(A,[{key:"render",value:function(e){var t=this,A=this.gl;Object(U.n)(A,{viewport:[0,0,A.drawingBufferWidth,A.drawingBufferHeight]}),Object(U.o)(A,{framebuffer:e.outputBuffer,clearColor:[0,0,0,0]},(function(){return t._renderPass(A,e)}))}},{key:"delete",value:function(){this.model.delete(),this.model=null}},{key:"_renderPass",value:function(e,t){var A=t.inputBuffer;t.outputBuffer;Object(_.a)(e,{color:!0}),this.model.draw({moduleSettings:this.props.moduleSettings,uniforms:{texture:A,texSize:[A.width,A.height]},parameters:{depthWrite:!1,depthTest:!1}})}}]),A}(A(410).a),O=A(531),L=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){var n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object(s.a)(this,A),(n=t.call(this,r)).id="".concat(e.name,"-pass"),Object(O.b)(e),n.module=e,n}return Object(g.a)(A,[{key:"postRender",value:function(e,t){this.passes||(this.passes=function(e,t,A,n){if(t.filter||t.sampler){var r=H(t);return[new M(e,{id:A,module:t,fs:r,moduleSettings:n})]}return(t.passes||[]).map((function(r,i){var o=H(t,r),a="".concat(A,"-").concat(i);return new M(e,{id:a,module:t,fs:o,moduleSettings:n})}))}(e,this.module,this.id,this.props));for(var A=t.target,n=t.inputBuffer,r=t.swapBuffer,i=0;i1&&void 0!==arguments[1]?arguments[1]:e;if(t.filter){var A="string"===typeof t.filter?t.filter:"".concat(e.name,"_filterColor");return T(A)}if(t.sampler){var n="string"===typeof t.sampler?t.sampler:"".concat(e.name,"_sampleColor");return Z(n)}return null}var Y=A(199),J=A(644),j=A(390),P=A(385),V=A(384),K=A(511),W=A(392),X=A(96),q=A(263),z=A(23),$=A(29),ee=A(56),te=Math.PI/180,Ae=180/Math.PI;function ne(){var e=Math.PI/180*256;return{unitsPerMeter:[256/6370972,256/6370972,256/6370972],unitsPerMeter2:[0,0,0],metersPerUnit:[24886.609375,24886.609375,24886.609375],unitsPerDegree:[e,e,256/6370972],unitsPerDegree2:[0,0,0],degreesPerUnit:[1/e,1/e,24886.609375]}}var re=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(s.a)(this,A);var r=n.latitude,i=void 0===r?0:r,o=n.longitude,g=void 0===o?0:o,c=n.zoom,u=void 0===c?11:c,l=n.nearZMultiplier,I=void 0===l?.1:l,C=n.farZMultiplier,h=void 0===C?2:C,f=n.resolution,d=void 0===f?10:f,B=n.width,p=n.height,E=n.altitude,Q=void 0===E?1.5:E;B=B||1,p=p||1,Q=Math.max(.75,Q);var y=(new z.Matrix4).lookAt({eye:[0,-Q,0],up:[0,0,1]}),v=Math.pow(2,u);y.rotateX(i*te),y.rotateZ(-g*te),y.scale(v/p);var m=Math.atan(.5/Q),b=512*v/p;return(e=t.call(this,Object(a.a)({},n,{width:B,height:p,viewMatrix:y,longitude:g,latitude:i,zoom:u,fovyRadians:2*m,aspect:B/p,focalDistance:Q,near:I,far:Math.min(2,1/b+1)*Q*h}))).resolution=d,e.distanceScales=ne(),e}return Object(g.a)(A,[{key:"getDistanceScales",value:function(){return this.distanceScales}},{key:"getBounds",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={targetZ:e.z||0},A=this.unproject([0,this.height/2],t),n=this.unproject([this.width/2,0],t),r=this.unproject([this.width,this.height/2],t),i=this.unproject([this.width/2,this.height],t);return r[0]this.longitude&&(A[0]-=360),[Math.min(A[0],r[0],n[0],i[0]),Math.min(A[1],r[1],n[1],i[1]),Math.max(A[0],r[0],n[0],i[0]),Math.max(A[1],r[1],n[1],i[1])]}},{key:"unproject",value:function(e){var t,A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=A.topLeft,r=void 0===n||n,i=A.targetZ,o=Object(Q.a)(e,3),a=o[0],s=o[1],g=o[2],c=r?s:this.height-s,u=this.pixelUnprojectionMatrix;if(Number.isFinite(g))t=ie(u,[a,c,g,1]);else{var l=ie(u,[a,c,-1,1]),I=ie(u,[a,c,1,1]),C=256*((i||0)/6370972+1),h=$.m($.n([],l,I)),f=$.m(l),d=$.m(I),B=(4*f*d-Math.pow(h-f-d,2))/16,p=4*B/h,E=Math.sqrt(f-p),y=Math.sqrt(Math.max(0,C*C-p)),v=(E-y)/Math.sqrt(h);t=$.h([],l,I,v)}var m=this.unprojectPosition(t),b=Object(Q.a)(m,3),w=b[0],S=b[1],F=b[2];return Number.isFinite(g)?[w,S,F]:Number.isFinite(i)?[w,S,i]:[w,S]}},{key:"projectPosition",value:function(e){var t=Object(Q.a)(e,3),A=t[0],n=t[1],r=t[2],i=void 0===r?0:r,o=A*te,a=n*te,s=Math.cos(a),g=256*(i/6370972+1);return[Math.sin(o)*s*g,-Math.cos(o)*s*g,Math.sin(a)*g]}},{key:"unprojectPosition",value:function(e){var t=Object(Q.a)(e,3),A=t[0],n=t[1],r=t[2],i=$.f(e),o=Math.asin(r/i);return[Math.atan2(A,-n)*Ae,o*Ae,6370972*(i/256-1)]}},{key:"projectFlat",value:function(e){return e}},{key:"unprojectFlat",value:function(e){return e}},{key:"panByPosition",value:function(e,t){var A=this.unproject(t);return{longitude:e[0]-A[0]+this.longitude,latitude:e[1]-A[1]+this.latitude}}},{key:"projectionMode",get:function(){return n.c.GLOBE}}]),A}(X.a);function ie(e,t){var A=ee.n([],t,e);return ee.k(A,A,1/A[3]),A}var oe=A(576),ae=A(223),se=A(575),ge=A(655),ce=A(276),ue=A(134),le=A(381),Ie=A(42),Ce=A(133),he=A(275),fe=A(84),de={position:[0,0,0],pitch:0,bearing:0,maxPitch:90,minPitch:-90},Be=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){var n,r=e.width,i=e.height,o=e.position,a=void 0===o?de.position:o,g=e.bearing,c=void 0===g?de.bearing:g,u=e.pitch,l=void 0===u?de.pitch:u,I=e.longitude,C=e.latitude,h=e.maxPitch,f=void 0===h?de.maxPitch:h,d=e.minPitch,B=void 0===d?de.minPitch:d,p=e.startRotatePos,E=e.startBearing,Q=e.startPitch,y=e.startZoomPosition,v=e.startZoom;return Object(s.a)(this,A),(n=t.call(this,{width:r,height:i,position:a,bearing:c,pitch:l,longitude:I,latitude:C,maxPitch:f,minPitch:B}))._state={startRotatePos:p,startBearing:E,startPitch:Q,startZoomPosition:y,startZoom:v},n}return Object(g.a)(A,[{key:"getDirection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=new z._SphericalCoordinates({bearing:this._viewportProps.bearing,pitch:e?90:90+this._viewportProps.pitch}),A=t.toVector3().normalize();return A}},{key:"panStart",value:function(){return this}},{key:"pan",value:function(){return this}},{key:"panEnd",value:function(){return this}},{key:"rotateStart",value:function(e){var t=e.pos;return this._getUpdatedState({startRotatePos:t,startBearing:this._viewportProps.bearing,startPitch:this._viewportProps.pitch})}},{key:"rotate",value:function(e){var t,A=e.pos,n=e.deltaAngleX,r=void 0===n?0:n,i=e.deltaAngleY,o=void 0===i?0:i,a=this._state,s=a.startRotatePos,g=a.startBearing,c=a.startPitch,u=this._viewportProps,l=u.width,I=u.height;if(!s||!Number.isFinite(g)||!Number.isFinite(c))return this;A?t={bearing:g-180*((A[0]-s[0])/l),pitch:c-90*((A[1]-s[1])/I)}:t={bearing:g-r,pitch:c-o};return this._getUpdatedState(t)}},{key:"rotateEnd",value:function(){return this._getUpdatedState({startRotatePos:null,startBearing:null,startPitch:null})}},{key:"zoomStart",value:function(){return this._getUpdatedState({startZoomPosition:this._viewportProps.position,startZoom:this._viewportProps.zoom})}},{key:"zoom",value:function(e){var t=e.scale,A=this._state.startZoomPosition;A||(A=this._viewportProps.position);var n=this.getDirection();return this._move(n,20*Math.log2(t),A)}},{key:"zoomEnd",value:function(){return this._getUpdatedState({startZoomPosition:null,startZoom:null})}},{key:"moveLeft",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=this.getDirection(!0);return this._move(t.rotateZ({radians:Math.PI/2}),e)}},{key:"moveRight",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=this.getDirection(!0);return this._move(t.rotateZ({radians:-Math.PI/2}),e)}},{key:"moveUp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=this.getDirection(!0);return this._move(t,e)}},{key:"moveDown",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=this.getDirection(!0);return this._move(t.negate(),e)}},{key:"rotateLeft",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15;return this._getUpdatedState({bearing:this._viewportProps.bearing-e})}},{key:"rotateRight",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15;return this._getUpdatedState({bearing:this._viewportProps.bearing+e})}},{key:"rotateUp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this._getUpdatedState({pitch:this._viewportProps.pitch+e})}},{key:"rotateDown",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this._getUpdatedState({pitch:this._viewportProps.pitch-e})}},{key:"zoomIn",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2;return this.zoom({scale:e})}},{key:"zoomOut",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2;return this.zoom({scale:1/e})}},{key:"shortestPathFrom",value:function(e){var t=e.getViewportProps(),A=Object(a.a)({},this._viewportProps),n=A.bearing,r=A.longitude;return Math.abs(n-t.bearing)>180&&(A.bearing=n<0?n+360:n-360),Math.abs(r-t.longitude)>180&&(A.longitude=r<0?r+360:r-360),A}},{key:"_move",value:function(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this._viewportProps.position,n=e.scale(t);return this._getUpdatedState({position:new z.Vector3(A).add(n)})}},{key:"_getUpdatedState",value:function(e){return new A(Object(a.a)({},this._viewportProps,{},this._state,{},e))}},{key:"_applyConstraints",value:function(e){var t=e.pitch,A=e.maxPitch,n=e.minPitch,r=e.longitude,i=e.bearing;return e.pitch=Object(z.clamp)(t,n,A),(r<-180||r>180)&&(e.longitude=Object(fe.e)(r+180,360)-180),(i<-180||i>180)&&(e.bearing=Object(fe.e)(i+180,360)-180),e}}]),A}(he.a),pe=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){return Object(s.a)(this,A),t.call(this,Be,e)}return Object(g.a)(A,[{key:"linearTransitionProps",get:function(){return["position","pitch","bearing"]}}]),A}(Ce.a);var Ee=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){Object(s.a)(this,A);var n=e.modelMatrix,r=void 0===n?null:n,i=e.bearing,o=void 0===i?0:i,g=e.pitch,c=void 0===g?0:g,u=e.up,l=void 0===u?[0,0,1]:u,I=function(e){var t=e.bearing,A=e.pitch;return new z._SphericalCoordinates({bearing:t,pitch:A}).toVector3().normalize()}({bearing:o,pitch:-90===c?1e-4:90+c}),C=r?r.transformDirection(I):I,h=Object(Ie.j)(e),f=Math.pow(2,h),d=(new z.Matrix4).lookAt({eye:[0,0,0],center:C,up:l}).scale(f);return t.call(this,Object(a.a)({},e,{zoom:h,viewMatrix:d}))}return A}(X.a),Qe=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){return Object(s.a)(this,A),t.call(this,Object(a.a)({},e,{type:Ee}))}return Object(g.a)(A,[{key:"controller",get:function(){return this._getControllerProps({type:pe})}}]),A}(ue.a);Qe.displayName="FirstPersonView";var ye=A(582),ve=A(581),me=A(16),be=A(17),we=A(266),Se=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(){return Object(s.a)(this,A),t.apply(this,arguments)}return Object(g.a)(A,[{key:"_applyConstraints",value:function(e){var t=e.maxZoom,A=e.minZoom,n=e.zoom;e.zoom=Object(z.clamp)(n,A,t);var r=e.longitude,i=e.latitude;return(r<-180||r>180)&&(e.longitude=Object(fe.e)(r+180,360)-180),e.latitude=Object(z.clamp)(i,-89,89),e}}]),A}(we.a),Fe=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){return Object(s.a)(this,A),e.dragMode=e.dragMode||"pan",t.call(this,Se,e)}return Object(g.a)(A,[{key:"setProps",value:function(e){Object(be.a)(Object(me.a)(A.prototype),"setProps",this).call(this,e),this.dragRotate=!1,this.touchRotate=!1}},{key:"linearTransitionProps",get:function(){return["longitude","latitude","zoom"]}}]),A}(Ce.a),Re=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){return Object(s.a)(this,A),t.call(this,Object(a.a)({},e,{type:re}))}return Object(g.a)(A,[{key:"controller",get:function(){return this._getControllerProps({type:Fe})}}]),A}(ue.a);Re.displayName="GlobeView";var De=A(264),Ge=A(380),ke=A(579),xe=A(315),Ne=A(265),Ue=A(316),_e=["bearing","pitch"],Me={speed:1.2,curve:1.414},Oe=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object(s.a)(this,A),(e=t.call(this,{compare:["longitude","latitude","zoom","bearing","pitch"],extract:["width","height","longitude","latitude","zoom","bearing","pitch"],required:["width","height","latitude","longitude","zoom"]})).props=Object(a.a)({},Me,{},n),e}return Object(g.a)(A,[{key:"interpolateProps",value:function(e,t,A){var n,r=Object(Ie.e)(e,t,A,this.props),i=Object(k.a)(_e);try{for(i.s();!(n=i.n()).done;){var o=n.value;r[o]=Object(z.lerp)(e[o]||0,t[o]||0,A)}}catch(a){i.e(a)}finally{i.f()}return r}},{key:"getDuration",value:function(e,t){var A=t.transitionDuration;return"auto"===A&&(A=Object(Ie.i)(e,t,this.props)),A}}]),A}(Ne.a),Le=A(41),Te=A(116),Ze=A(577),He=A(147),Ye=A(379),Je=A(173),je=A(378),Pe=A(313);A.d(t,"COORDINATE_SYSTEM",(function(){return n.a})),A.d(t,"UNIT",(function(){return n.d})),A.d(t,"LightingEffect",(function(){return r.a})),A.d(t,"AmbientLight",(function(){return i.a})),A.d(t,"DirectionalLight",(function(){return o.a})),A.d(t,"PointLight",(function(){return h})),A.d(t,"_CameraLight",(function(){return E})),A.d(t,"_SunLight",(function(){return G})),A.d(t,"PostProcessEffect",(function(){return L})),A.d(t,"_LayersPass",(function(){return Y.a})),A.d(t,"Deck",(function(){return J.a})),A.d(t,"LayerManager",(function(){return j.a})),A.d(t,"AttributeManager",(function(){return P.a})),A.d(t,"Layer",(function(){return V.a})),A.d(t,"CompositeLayer",(function(){return K.a})),A.d(t,"DeckRenderer",(function(){return W.a})),A.d(t,"Viewport",(function(){return X.a})),A.d(t,"WebMercatorViewport",(function(){return q.a})),A.d(t,"_GlobeViewport",(function(){return re})),A.d(t,"picking",(function(){return oe.a})),A.d(t,"project",(function(){return ae.a})),A.d(t,"project32",(function(){return se.a})),A.d(t,"gouraudLighting",(function(){return ge.a})),A.d(t,"phongLighting",(function(){return ge.b})),A.d(t,"shadow",(function(){return ce.a})),A.d(t,"View",(function(){return ue.a})),A.d(t,"MapView",(function(){return le.a})),A.d(t,"FirstPersonView",(function(){return Qe})),A.d(t,"OrbitView",(function(){return ye.a})),A.d(t,"OrthographicView",(function(){return ve.a})),A.d(t,"_GlobeView",(function(){return Re})),A.d(t,"Controller",(function(){return Ce.a})),A.d(t,"MapController",(function(){return we.b})),A.d(t,"_GlobeController",(function(){return Fe})),A.d(t,"FirstPersonController",(function(){return pe})),A.d(t,"OrbitController",(function(){return De.b})),A.d(t,"OrthographicController",(function(){return Ge.a})),A.d(t,"Effect",(function(){return x.a})),A.d(t,"LayerExtension",(function(){return ke.a})),A.d(t,"TRANSITION_EVENTS",(function(){return xe.a})),A.d(t,"TransitionInterpolator",(function(){return Ne.a})),A.d(t,"LinearInterpolator",(function(){return Ue.a})),A.d(t,"FlyToInterpolator",(function(){return Oe})),A.d(t,"log",(function(){return Le.a})),A.d(t,"createIterable",(function(){return Te.a})),A.d(t,"fp64LowPart",(function(){return fe.b})),A.d(t,"Tesselator",(function(){return Ze.a})),A.d(t,"_fillArray",(function(){return He.a})),A.d(t,"_flatten",(function(){return He.b})),A.d(t,"_count",(function(){return Ye.a})),A.d(t,"_memoize",(function(){return Je.a})),A.d(t,"_mergeShaders",(function(){return je.a})),A.d(t,"_compareProps",(function(){return Pe.a}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return r})),A.d(t,"c",(function(){return i})),A.d(t,"d",(function(){return o})),A.d(t,"b",(function(){return a}));var n=A(41),r={DEFAULT:-1,LNGLAT:1,METER_OFFSETS:2,LNGLAT_OFFSETS:3,CARTESIAN:0};Object.defineProperty(r,"IDENTITY",{get:function(){return n.a.deprecated("COORDINATE_SYSTEM.IDENTITY","COORDINATE_SYSTEM.CARTESIAN")()||0}});var i={WEB_MERCATOR:1,GLOBE:2,WEB_MERCATOR_AUTO_OFFSET:4,IDENTITY:0},o={common:0,meters:1,pixels:2},a={click:{handler:"onClick"},panstart:{handler:"onDragStart"},panmove:{handler:"onDrag"},panend:{handler:"onDragEnd"}}},,function(e,t,A){var n=A(444);e.exports=function(e,t){return n(e,t)}},function(e,t,A){"use strict";!function e(){if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE){0;try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}}(),e.exports=A(749)},function(e,t,A){"use strict";A.d(t,"a",(function(){return r}));var n=A(717);function r(e){if("string"!==typeof e)throw new Error(Object(n.a)(7));return e.charAt(0).toUpperCase()+e.slice(1)}},function(e,t,A){"use strict";var n=A(1163);t.a=new n.a({id:"deck"})},function(e,t,A){"use strict";var n=A(11),r=A(8),i=A(1),o=A(4),a=1e-6,s="undefined"!==typeof Float32Array?Float32Array:Array;Math.random;Math.PI;Math.hypot||(Math.hypot=function(){for(var e=0,t=arguments.length;t--;)e+=arguments[t]*arguments[t];return Math.sqrt(e)});!function(){var e=function(){var e=new s(4);return s!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0,e[3]=0),e}()}();function g(e,t){var A,n,r,i=function(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3];return e[0]=A[0]*n+A[4]*r+A[8]*i+A[12]*o,e[1]=A[1]*n+A[5]*r+A[9]*i+A[13]*o,e[2]=A[2]*n+A[6]*r+A[10]*i+A[14]*o,e[3]=A[3]*n+A[7]*r+A[11]*i+A[15]*o,e}([],t,e);return A=i,n=i,r=1/i[3],A[0]=n[0]*r,A[1]=n[1]*r,A[2]=n[2]*r,A[3]=n[3]*r,i}function c(e,t){var A=e%t;return A<0?t+A:A}function u(e,t,A){return A*t+(1-A)*e}var l=Math.log2||function(e){return Math.log(e)*Math.LOG2E};function I(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],s=t[5],g=t[6],c=t[7],u=t[8],l=t[9],I=t[10],C=t[11],h=t[12],f=t[13],d=t[14],B=t[15],p=A[0],E=A[1],Q=A[2],y=A[3];return e[0]=p*n+E*a+Q*u+y*h,e[1]=p*r+E*s+Q*l+y*f,e[2]=p*i+E*g+Q*I+y*d,e[3]=p*o+E*c+Q*C+y*B,p=A[4],E=A[5],Q=A[6],y=A[7],e[4]=p*n+E*a+Q*u+y*h,e[5]=p*r+E*s+Q*l+y*f,e[6]=p*i+E*g+Q*I+y*d,e[7]=p*o+E*c+Q*C+y*B,p=A[8],E=A[9],Q=A[10],y=A[11],e[8]=p*n+E*a+Q*u+y*h,e[9]=p*r+E*s+Q*l+y*f,e[10]=p*i+E*g+Q*I+y*d,e[11]=p*o+E*c+Q*C+y*B,p=A[12],E=A[13],Q=A[14],y=A[15],e[12]=p*n+E*a+Q*u+y*h,e[13]=p*r+E*s+Q*l+y*f,e[14]=p*i+E*g+Q*I+y*d,e[15]=p*o+E*c+Q*C+y*B,e}function C(e,t,A){var n,r,i,o,a,s,g,c,u,l,I,C,h=A[0],f=A[1],d=A[2];return t===e?(e[12]=t[0]*h+t[4]*f+t[8]*d+t[12],e[13]=t[1]*h+t[5]*f+t[9]*d+t[13],e[14]=t[2]*h+t[6]*f+t[10]*d+t[14],e[15]=t[3]*h+t[7]*f+t[11]*d+t[15]):(n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],s=t[5],g=t[6],c=t[7],u=t[8],l=t[9],I=t[10],C=t[11],e[0]=n,e[1]=r,e[2]=i,e[3]=o,e[4]=a,e[5]=s,e[6]=g,e[7]=c,e[8]=u,e[9]=l,e[10]=I,e[11]=C,e[12]=n*h+a*f+u*d+t[12],e[13]=r*h+s*f+l*d+t[13],e[14]=i*h+g*f+I*d+t[14],e[15]=o*h+c*f+C*d+t[15]),e}function h(e,t,A){var n=A[0],r=A[1],i=A[2];return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*i,e[9]=t[9]*i,e[10]=t[10]*i,e[11]=t[11]*i,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function f(e,t){var A=e[0],n=e[1],r=e[2],i=e[3],o=e[4],s=e[5],g=e[6],c=e[7],u=e[8],l=e[9],I=e[10],C=e[11],h=e[12],f=e[13],d=e[14],B=e[15],p=t[0],E=t[1],Q=t[2],y=t[3],v=t[4],m=t[5],b=t[6],w=t[7],S=t[8],F=t[9],R=t[10],D=t[11],G=t[12],k=t[13],x=t[14],N=t[15];return Math.abs(A-p)<=a*Math.max(1,Math.abs(A),Math.abs(p))&&Math.abs(n-E)<=a*Math.max(1,Math.abs(n),Math.abs(E))&&Math.abs(r-Q)<=a*Math.max(1,Math.abs(r),Math.abs(Q))&&Math.abs(i-y)<=a*Math.max(1,Math.abs(i),Math.abs(y))&&Math.abs(o-v)<=a*Math.max(1,Math.abs(o),Math.abs(v))&&Math.abs(s-m)<=a*Math.max(1,Math.abs(s),Math.abs(m))&&Math.abs(g-b)<=a*Math.max(1,Math.abs(g),Math.abs(b))&&Math.abs(c-w)<=a*Math.max(1,Math.abs(c),Math.abs(w))&&Math.abs(u-S)<=a*Math.max(1,Math.abs(u),Math.abs(S))&&Math.abs(l-F)<=a*Math.max(1,Math.abs(l),Math.abs(F))&&Math.abs(I-R)<=a*Math.max(1,Math.abs(I),Math.abs(R))&&Math.abs(C-D)<=a*Math.max(1,Math.abs(C),Math.abs(D))&&Math.abs(h-G)<=a*Math.max(1,Math.abs(h),Math.abs(G))&&Math.abs(f-k)<=a*Math.max(1,Math.abs(f),Math.abs(k))&&Math.abs(d-x)<=a*Math.max(1,Math.abs(d),Math.abs(x))&&Math.abs(B-N)<=a*Math.max(1,Math.abs(B),Math.abs(N))}function d(e,t,A){return e[0]=t[0]+A[0],e[1]=t[1]+A[1],e}function B(e,t,A){return e[0]=t[0]*A,e[1]=t[1]*A,e}function p(e){var t=e[0],A=e[1];return Math.hypot(t,A)}function E(e,t,A,n){var r=t[0],i=t[1];return e[0]=r+n*(A[0]-r),e[1]=i+n*(A[1]-i),e}var Q=function(e,t,A){return e[0]=t[0]-A[0],e[1]=t[1]-A[1],e};!function(){var e=function(){var e=new s(2);return s!=Float32Array&&(e[0]=0,e[1]=0),e}()}();function y(e,t,A){return e[0]=t[0]+A[0],e[1]=t[1]+A[1],e[2]=t[2]+A[2],e}var v=function(e,t,A){return e[0]=t[0]*A[0],e[1]=t[1]*A[1],e[2]=t[2]*A[2],e};!function(){var e=function(){var e=new s(3);return s!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e}()}();function m(e,t){if(!e)throw new Error(t||"@math.gl/web-mercator: assertion failed.")}var b=Math.PI,w=b/4,S=b/180,F=180/b;function R(e){return Math.pow(2,e)}function D(e){return l(e)}function G(e){var t=Object(r.a)(e,2),A=t[0],n=t[1];m(Number.isFinite(A)),m(Number.isFinite(n)&&n>=-90&&n<=90,"invalid latitude");var i=n*S;return[512*(A*S+b)/(2*b),512*(b+Math.log(Math.tan(w+.5*i)))/(2*b)]}function k(e){var t=Object(r.a)(e,2),A=t[0],n=t[1],i=A/512*(2*b)-b,o=2*(Math.atan(Math.exp(n/512*(2*b)-b))-w);return[i*F,o*F]}function x(e){var t=e.latitude;return m(Number.isFinite(t)),D(4003e4*Math.cos(t*S))-9}function N(e){var t=e.latitude,A=e.longitude,n=e.highPrecision,r=void 0!==n&&n;m(Number.isFinite(t)&&Number.isFinite(A));var i={},o=Math.cos(t*S),a=512/360/o,s=512/4003e4/o;if(i.unitsPerMeter=[s,s,s],i.metersPerUnit=[1/s,1/s,1/s],i.unitsPerDegree=[512/360,a,s],i.degreesPerUnit=[.703125,1/a,1/s],r){var g=S*Math.tan(t*S)/o,c=512/360*g/2,u=512/4003e4*g,l=u/a*s;i.unitsPerDegree2=[0,c,u],i.unitsPerMeter2=[l,0,l]}return i}function U(e,t){var A=Object(r.a)(e,3),n=A[0],i=A[1],o=A[2],a=Object(r.a)(t,3),s=a[0],g=a[1],c=a[2],u=N({longitude:n,latitude:i,highPrecision:!0}),l=u.unitsPerMeter,I=u.unitsPerMeter2,C=G(e);C[0]+=s*(l[0]+I[0]*g),C[1]+=g*(l[1]+I[1]*g);var h=k(C),f=(o||0)+(c||0);return Number.isFinite(o)||Number.isFinite(c)?[h[0],h[1],f]:h}function _(e){var t,A,n=e.height,r=e.pitch,i=e.bearing,o=e.altitude,a=e.scale,s=e.center,g=void 0===s?null:s,c=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return C(c,c,[0,0,-o]),function(e,t,A){var n=Math.sin(A),r=Math.cos(A),i=t[4],o=t[5],a=t[6],s=t[7],g=t[8],c=t[9],u=t[10],l=t[11];t!==e&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[4]=i*r+g*n,e[5]=o*r+c*n,e[6]=a*r+u*n,e[7]=s*r+l*n,e[8]=g*r-i*n,e[9]=c*r-o*n,e[10]=u*r-a*n,e[11]=l*r-s*n}(c,c,-r*S),function(e,t,A){var n=Math.sin(A),r=Math.cos(A),i=t[0],o=t[1],a=t[2],s=t[3],g=t[4],c=t[5],u=t[6],l=t[7];t!==e&&(e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=i*r+g*n,e[1]=o*r+c*n,e[2]=a*r+u*n,e[3]=s*r+l*n,e[4]=g*r-i*n,e[5]=c*r-o*n,e[6]=u*r-a*n,e[7]=l*r-s*n}(c,c,i*S),h(c,c,[a/=n,a,a]),g&&C(c,c,((t=[])[0]=-(A=g)[0],t[1]=-A[1],t[2]=-A[2],t)),c}function M(e){var t=e.width,A=e.height,n=e.fovy,r=void 0===n?L(1.5):n,i=e.altitude,o=e.pitch,a=void 0===o?0:o,s=e.nearZMultiplier,g=void 0===s?1:s,c=e.farZMultiplier,u=void 0===c?1:c;void 0!==i&&(r=L(i));var l=.5*r*S,I=T(r),C=a*S,h=Math.sin(l)*I/Math.sin(Math.min(Math.max(Math.PI/2-C-l,.01),Math.PI-.01));return{fov:2*l,aspect:t/A,focalDistance:I,near:g,far:(Math.sin(C)*h+I)*u}}function O(e){var t=e.width,A=e.height,n=e.pitch,r=M({width:t,height:A,altitude:e.altitude,fovy:e.fovy,pitch:n,nearZMultiplier:e.nearZMultiplier,farZMultiplier:e.farZMultiplier});return function(e,t,A,n,r){var i,o=1/Math.tan(t/2);return e[0]=o/A,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=o,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,null!=r&&r!==1/0?(i=1/(n-r),e[10]=(r+n)*i,e[14]=2*r*n*i):(e[10]=-1,e[14]=-2*n),e}([],r.fov,r.aspect,r.near,r.far)}function L(e){return 2*Math.atan(.5/e)*F}function T(e){return.5/Math.tan(.5*e*S)}function Z(e,t){var A=Object(r.a)(e,3),n=A[0],i=A[1],o=A[2],a=void 0===o?0:o;return m(Number.isFinite(n)&&Number.isFinite(i)&&Number.isFinite(a)),g(t,[n,i,a,1])}function H(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=Object(r.a)(e,3),i=n[0],o=n[1],a=n[2];if(m(Number.isFinite(i)&&Number.isFinite(o),"invalid pixel coordinate"),Number.isFinite(a)){var s=g(t,[i,o,a,1]);return s}var c=g(t,[i,o,0,1]),u=g(t,[i,o,1,1]),l=c[2],I=u[2],C=l===I?0:((A||0)-l)/(I-l);return E([],c,u,C)}function Y(e){var t=e.width,A=e.height,n=e.bounds,i=e.minExtent,o=void 0===i?0:i,a=e.maxZoom,s=void 0===a?24:a,g=e.padding,c=void 0===g?0:g,u=e.offset,I=void 0===u?[0,0]:u,C=Object(r.a)(n,2),h=Object(r.a)(C[0],2),f=h[0],d=h[1],B=Object(r.a)(C[1],2),p=B[0],E=B[1];if(Number.isFinite(c)){c={top:c,bottom:c,left:c,right:c}}else m(Number.isFinite(c.top)&&Number.isFinite(c.bottom)&&Number.isFinite(c.left)&&Number.isFinite(c.right));var Q=new V({width:t,height:A,longitude:0,latitude:0,zoom:0}),y=Q.project([f,E]),v=Q.project([p,d]),b=[Math.max(Math.abs(v[0]-y[0]),o),Math.max(Math.abs(v[1]-y[1]),o)],w=[t-c.left-c.right-2*Math.abs(I[0]),A-c.top-c.bottom-2*Math.abs(I[1])];m(w[0]>0&&w[1]>0);var S=w[0]/b[0],F=w[1]/b[1],R=(c.right-c.left)/2/S,D=(c.bottom-c.top)/2/F,G=[(v[0]+y[0])/2+R,(v[1]+y[1])/2+D],k=Q.unproject(G),x=Math.min(s,Q.zoom+l(Math.abs(Math.min(S,F))));return m(Number.isFinite(x)),{longitude:k[0],latitude:k[1],zoom:x}}var J=Math.PI/180;function j(e){var t,A,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=e.width,i=e.height,o=e.unproject,a={targetZ:n},s=o([0,i],a),g=o([r,i],a),c=e.fovy?.5*e.fovy*J:Math.atan(.5/e.altitude),u=(90-e.pitch)*J;return c>u-.01?(t=P(e,0,n),A=P(e,r,n)):(t=o([0,0],a),A=o([r,0],a)),[s,g,A,t]}function P(e,t,A){var n=e.pixelUnprojectionMatrix,r=g(n,[t,0,1,1]),i=g(n,[t,e.height,1,1]),o=k(E([],r,i,(A*e.distanceScales.unitsPerMeter[2]-r[2])/(i[2]-r[2])));return o[2]=A,o}var V=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{width:1,height:1},A=t.width,n=t.height,r=t.latitude,o=void 0===r?0:r,a=t.longitude,s=void 0===a?0:a,g=t.zoom,c=void 0===g?0:g,u=t.pitch,l=void 0===u?0:u,I=t.bearing,C=void 0===I?0:I,h=t.altitude,f=void 0===h?null:h,d=t.fovy,B=void 0===d?null:d,p=t.position,E=void 0===p?null:p,Q=t.nearZMultiplier,m=void 0===Q?.02:Q,b=t.farZMultiplier,w=void 0===b?1.01:b;Object(i.a)(this,e),A=A||1,n=n||1,null===B&&null===f?B=L(f=1.5):null===B?B=L(f):null===f&&(f=T(B));var S=R(c);f=Math.max(.75,f);var F=N({longitude:s,latitude:o}),D=G([s,o]);D[2]=0,E&&y(D,D,v([],E,F.unitsPerMeter)),this.projectionMatrix=O({width:A,height:n,pitch:l,fovy:B,nearZMultiplier:m,farZMultiplier:w}),this.viewMatrix=_({height:n,scale:S,center:D,pitch:l,bearing:C,altitude:f}),this.width=A,this.height=n,this.scale=S,this.latitude=o,this.longitude=s,this.zoom=c,this.pitch=l,this.bearing=C,this.altitude=f,this.fovy=B,this.center=D,this.meterOffset=E||[0,0,0],this.distanceScales=F,this._initMatrices(),this.equals=this.equals.bind(this),this.project=this.project.bind(this),this.unproject=this.unproject.bind(this),this.projectPosition=this.projectPosition.bind(this),this.unprojectPosition=this.unprojectPosition.bind(this),Object.freeze(this)}return Object(o.a)(e,[{key:"_initMatrices",value:function(){var e=this.width,t=this.height,A=this.projectionMatrix,n=this.viewMatrix,r=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];I(r,r,A),I(r,r,n),this.viewProjectionMatrix=r;var i=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];h(i,i,[e/2,-t/2,1]),C(i,i,[1,-1,0]),I(i,i,r);var o=function(e,t){var A=t[0],n=t[1],r=t[2],i=t[3],o=t[4],a=t[5],s=t[6],g=t[7],c=t[8],u=t[9],l=t[10],I=t[11],C=t[12],h=t[13],f=t[14],d=t[15],B=A*a-n*o,p=A*s-r*o,E=A*g-i*o,Q=n*s-r*a,y=n*g-i*a,v=r*g-i*s,m=c*h-u*C,b=c*f-l*C,w=c*d-I*C,S=u*f-l*h,F=u*d-I*h,R=l*d-I*f,D=B*R-p*F+E*S+Q*w-y*b+v*m;return D?(D=1/D,e[0]=(a*R-s*F+g*S)*D,e[1]=(r*F-n*R-i*S)*D,e[2]=(h*v-f*y+d*Q)*D,e[3]=(l*y-u*v-I*Q)*D,e[4]=(s*w-o*R-g*b)*D,e[5]=(A*R-r*w+i*b)*D,e[6]=(f*E-C*v-d*p)*D,e[7]=(c*v-l*E+I*p)*D,e[8]=(o*F-a*w+g*m)*D,e[9]=(n*w-A*F-i*m)*D,e[10]=(C*y-h*E+d*B)*D,e[11]=(u*E-c*y-I*B)*D,e[12]=(a*b-o*S-s*m)*D,e[13]=(A*S-n*b+r*m)*D,e[14]=(h*p-C*Q-f*B)*D,e[15]=(c*Q-u*p+l*B)*D,e):null}([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],i);if(!o)throw new Error("Pixel project matrix not invertible");this.pixelProjectionMatrix=i,this.pixelUnprojectionMatrix=o}},{key:"equals",value:function(t){return t instanceof e&&(t.width===this.width&&t.height===this.height&&f(t.projectionMatrix,this.projectionMatrix)&&f(t.viewMatrix,this.viewMatrix))}},{key:"project",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.topLeft,n=void 0===A||A,i=this.projectPosition(e),o=Z(i,this.pixelProjectionMatrix),a=Object(r.a)(o,2),s=a[0],g=a[1],c=n?g:this.height-g;return 2===e.length?[s,c]:[s,c,o[2]]}},{key:"unproject",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.topLeft,n=void 0===A||A,i=t.targetZ,o=void 0===i?void 0:i,a=Object(r.a)(e,3),s=a[0],g=a[1],c=a[2],u=n?g:this.height-g,l=o&&o*this.distanceScales.unitsPerMeter[2],I=H([s,u,c],this.pixelUnprojectionMatrix,l),C=this.unprojectPosition(I),h=Object(r.a)(C,3),f=h[0],d=h[1],B=h[2];return Number.isFinite(c)?[f,d,B]:Number.isFinite(o)?[f,d,o]:[f,d]}},{key:"projectPosition",value:function(e){var t=G(e),A=Object(r.a)(t,2);return[A[0],A[1],(e[2]||0)*this.distanceScales.unitsPerMeter[2]]}},{key:"unprojectPosition",value:function(e){var t=k(e),A=Object(r.a)(t,2);return[A[0],A[1],(e[2]||0)*this.distanceScales.metersPerUnit[2]]}},{key:"projectFlat",value:function(e){return G(e)}},{key:"unprojectFlat",value:function(e){return k(e)}},{key:"getMapCenterByLngLatPosition",value:function(e){var t,A,n=e.lngLat,r=H(e.pos,this.pixelUnprojectionMatrix),i=d([],G(n),((t=[])[0]=-(A=r)[0],t[1]=-A[1],t));return k(d([],this.center,i))}},{key:"getLocationAtPoint",value:function(e){var t=e.lngLat,A=e.pos;return this.getMapCenterByLngLatPosition({lngLat:t,pos:A})}},{key:"fitBounds",value:function(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.width,r=this.height,i=Y(Object.assign({width:n,height:r,bounds:t},A)),o=i.longitude,a=i.latitude,s=i.zoom;return new e({width:n,height:r,longitude:o,latitude:a,zoom:s})}},{key:"getBounds",value:function(e){var t=this.getBoundingRegion(e),A=Math.min.apply(Math,Object(n.a)(t.map((function(e){return e[0]})))),r=Math.max.apply(Math,Object(n.a)(t.map((function(e){return e[0]}))));return[[A,Math.min.apply(Math,Object(n.a)(t.map((function(e){return e[1]}))))],[r,Math.max.apply(Math,Object(n.a)(t.map((function(e){return e[1]}))))]]}},{key:"getBoundingRegion",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return j(this,e.z||0)}}]),e}();function K(e){var t=e.width,A=e.height,n=e.longitude,r=e.latitude,i=e.zoom,o=e.pitch,a=void 0===o?0:o,s=e.bearing,g=void 0===s?0:s;(n<-180||n>180)&&(n=c(n+180,360)-180),(g<-180||g>180)&&(g=c(g+180,360)-180);var u=l(A/512);if(i<=u)i=u,r=0;else{var I=A/2/Math.pow(2,i),C=k([0,I])[1];if(rh&&(r=h)}}return{width:t,height:A,longitude:n,latitude:r,zoom:i,pitch:a,bearing:g}}var W=A(6),X=["longitude","latitude","zoom"],q={curve:1.414,speed:1.2};function z(e,t,A){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},r={},i=ee(e,t,n),o=i.startZoom,a=i.startCenterXY,s=i.uDelta,g=i.w0,c=i.u1,l=i.S,I=i.rho,C=i.rho2,h=i.r0;if(c<.01){var f,p=Object(W.a)(X);try{for(p.s();!(f=p.n()).done;){var E=f.value,Q=e[E],y=t[E];r[E]=u(Q,y,A)}}catch(G){p.e(G)}finally{p.f()}return r}var v=A*l,m=Math.cosh(h)/Math.cosh(h+I*v),b=g*((Math.cosh(h)*Math.tanh(h+I*v)-Math.sinh(h))/C)/c,w=1/m,S=o+D(w),F=B([],s,b);d(F,F,a);var R=k(F);return r.longitude=R[0],r.latitude=R[1],r.zoom=S,r}function $(e,t){var A,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n=Object.assign({},q,n),i=r.screenSpeed,o=r.speed,a=r.maxDuration,s=ee(e,t,n),g=s.S,c=s.rho,u=1e3*g;return A=Number.isFinite(i)?u/(i/c):u/o,Number.isFinite(a)&&A>a?0:A}function ee(e,t,A){var n=(A=Object.assign({},q,A)).curve,r=e.zoom,i=[e.longitude,e.latitude],o=R(r),a=t.zoom,s=[t.longitude,t.latitude],g=R(a-r),c=G(i),u=G(s),l=Q([],u,c),I=Math.max(e.width,e.height),C=I/g,h=p(l)*o,f=Math.max(h,.01),d=n*n,B=(C*C-I*I+d*d*f*f)/(2*I*d*f),E=(C*C-I*I-d*d*f*f)/(2*C*d*f),y=Math.log(Math.sqrt(B*B+1)-B),v=Math.log(Math.sqrt(E*E+1)-E);return{startZoom:r,startCenterXY:c,uDelta:l,w0:I,u1:h,S:(v-y)/n,rho:n,rho2:d,r0:y,r1:v}}A.d(t,"a",(function(){return V})),A.d(t,"g",(function(){return j})),A.d(t,"d",(function(){return Y})),A.d(t,"o",(function(){return K})),A.d(t,"e",(function(){return z})),A.d(t,"i",(function(){return $})),A.d(t,"n",(function(){return G})),A.d(t,"r",(function(){return k})),A.d(t,"s",(function(){return Z})),A.d(t,"p",(function(){return H})),A.d(t,"t",(function(){return R})),A.d(t,"q",(function(){return D})),A.d(t,"c",(function(){return L})),A.d(t,"f",(function(){return T})),A.d(t,"j",(function(){return x})),A.d(t,"h",(function(){return N})),A.d(t,"b",(function(){return U})),A.d(t,"m",(function(){return _})),A.d(t,"k",(function(){return O})),A.d(t,"l",(function(){return M}))},function(e,t,A){"use strict";A.r(t);var n=A(18),r=A(330),i=A(427),o=A(718),a=A(80),s=A(1288),g=A(161),c=A(238),u=A(232),l=A(664),I=A(428),C=A(530),h=A(663),f=A(665),d=A(1246),B=A(1293),p=A(422),E=A(1289),Q=A(528),y=A(1247),v=A(135),m=A(1257),b=A(7),w=A(1),S=A(9),F=A(10),R=A(108),D={x:[2,0,1],y:[0,1,2],z:[1,2,0]},G=function(e){Object(S.a)(A,e);var t=Object(F.a)(A);function A(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(w.a)(this,A);var n=e.id,r=void 0===n?Object(R.c)("truncated-code-geometry"):n,i=k(e),o=i.indices,a=i.attributes;return t.call(this,Object(b.a)({},e,{id:r,indices:o,attributes:Object(b.a)({},a,{},e.attributes)}))}return A}(v.a);function k(e){for(var t=e.bottomRadius,A=void 0===t?0:t,n=e.topRadius,r=void 0===n?0:n,i=e.height,o=void 0===i?1:i,a=e.nradial,s=void 0===a?10:a,g=e.nvertical,c=void 0===g?10:g,u=e.verticalAxis,l=void 0===u?"y":u,I=e.topCap,C=void 0!==I&&I,h=e.bottomCap,f=void 0!==h&&h,d=(C?2:0)+(f?2:0),B=(s+1)*(c+1+d),p=Math.atan2(A-r,o),E=Math.sin,Q=Math.cos,y=Math.PI,v=Q(p),m=E(p),b=C?-2:0,w=c+(f?2:0),S=s+1,F=new Uint16Array(s*(c+d)*6),R=D[l],G=new Float32Array(3*B),k=new Float32Array(3*B),x=new Float32Array(2*B),N=0,U=0,_=b;_<=w;_++){var M=_/c,O=o*M,L=void 0;_<0?(O=0,M=1,L=A):_>c?(O=o,M=1,L=r):L=A+_/c*(r-A),-2!==_&&_!==c+2||(L=0,M=0),O-=o/2;for(var T=0;Tc?0:Z*v,k[N+R[1]]=_<0?-1:_>c?1:m,k[N+R[2]]=_<0||_>c?0:H*v,x[U+0]=T/s,x[U+1]=M,U+=2,N+=3}}for(var Y=0;Y0&&void 0!==arguments[0]?arguments[0]:{};Object(w.a)(this,A);var n=e.id,r=void 0===n?Object(R.c)("cone-geometry"):n,i=e.radius,o=void 0===i?1:i,a=e.cap,s=void 0===a||a;return t.call(this,Object(b.a)({},e,{id:r,topRadius:0,topCap:Boolean(s),bottomCap:Boolean(s),bottomRadius:o}))}return A}(G),N=A(1256),U=function(e){Object(S.a)(A,e);var t=Object(F.a)(A);function A(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(w.a)(this,A);var n=e.id,r=void 0===n?Object(R.c)("cylinder-geometry"):n,i=e.radius,o=void 0===i?1:i;return t.call(this,Object(b.a)({},e,{id:r,bottomRadius:o,topRadius:o}))}return A}(G),_=A(221),M=[-1,0,0,0,1,0,0,0,-1,0,0,1,0,-1,0,1,0,0],O=[3,4,5,3,5,1,3,1,0,3,0,4,4,0,2,4,2,5,2,0,1,5,2,1],L=function(e){Object(S.a)(A,e);var t=Object(F.a)(A);function A(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(w.a)(this,A);var n=e.id,r=void 0===n?Object(R.c)("ico-sphere-geometry"):n,i=T(e),o=i.indices,a=i.attributes;return t.call(this,Object(b.a)({},e,{id:r,indices:o,attributes:Object(b.a)({},a,{},e.attributes)}))}return A}(v.a);function T(e){var t=e.iterations,A=void 0===t?0:t,n=Math.PI,r=2*n,i=[].concat(M),o=[].concat(O);i.push(),o.push();for(var a=function(){var e={};return function(t,A){var n=(t*=3)>(A*=3)?t:A,r="".concat(t=0;f-=3){var d=o[f+0],B=o[f+1],p=o[f+2],E=3*d,Q=3*B,y=3*p,v=2*d,m=2*B,b=2*p,w=i[E+0],S=i[E+1],F=i[E+2],R=Math.acos(F/Math.sqrt(w*w+S*S+F*F))/n,D=1-(Math.atan2(S,w)+n)/r,G=i[Q+0],k=i[Q+1],x=i[Q+2],N=Math.acos(x/Math.sqrt(G*G+k*k+x*x))/n,U=1-(Math.atan2(k,G)+n)/r,L=i[y+0],T=i[y+1],Z=i[y+2],H=Math.acos(Z/Math.sqrt(L*L+T*T+Z*Z))/n,Y=1-(Math.atan2(T,L)+n)/r,J=[L-G,T-k,Z-x],j=[w-G,S-k,F-x],P=new _.a(J).cross(j).normalize(),V=void 0;(0===D||0===U||0===Y)&&(0===D||D>.5)&&(0===U||U>.5)&&(0===Y||Y>.5)&&(i.push(i[E+0],i[E+1],i[E+2]),V=i.length/3-1,o.push(V),h[2*V+0]=1,h[2*V+1]=R,C[3*V+0]=P.x,C[3*V+1]=P.y,C[3*V+2]=P.z,i.push(i[Q+0],i[Q+1],i[Q+2]),V=i.length/3-1,o.push(V),h[2*V+0]=1,h[2*V+1]=N,C[3*V+0]=P.x,C[3*V+1]=P.y,C[3*V+2]=P.z,i.push(i[y+0],i[y+1],i[y+2]),V=i.length/3-1,o.push(V),h[2*V+0]=1,h[2*V+1]=H,C[3*V+0]=P.x,C[3*V+1]=P.y,C[3*V+2]=P.z),C[E+0]=C[Q+0]=C[y+0]=P.x,C[E+1]=C[Q+1]=C[y+1]=P.y,C[E+2]=C[Q+2]=C[y+2]=P.z,h[v+0]=D,h[v+1]=R,h[m+0]=U,h[m+1]=N,h[b+0]=Y,h[b+1]=H}return{indices:{size:1,value:new Uint16Array(o)},attributes:{POSITION:{size:3,value:new Float32Array(i)},NORMAL:{size:3,value:new Float32Array(C)},TEXCOORD_0:{size:2,value:new Float32Array(h)}}}}var Z=function(e){Object(S.a)(A,e);var t=Object(F.a)(A);function A(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(w.a)(this,A);var n=e.id,r=void 0===n?Object(R.c)("plane-geometry"):n,i=H(e),o=i.indices,a=i.attributes;return t.call(this,Object(b.a)({},e,{id:r,indices:o,attributes:Object(b.a)({},a,{},e.attributes)}))}return A}(v.a);function H(e){var t=e.type,A=void 0===t?"x,y":t,n=e.offset,r=void 0===n?0:n,i=e.flipCull,o=void 0!==i&&i,a=e.unpack,s=void 0!==a&&a,g=A.split(","),c=e["".concat(g[0],"len")]||1,u=e["".concat(g[1],"len")]||1,l=e["n".concat(g[0])]||1,I=e["n".concat(g[1])]||1,C=(l+1)*(I+1),h=new Float32Array(3*C),f=new Float32Array(3*C),d=new Float32Array(2*C);o&&(c=-c);for(var B=0,p=0,E=0;E<=I;E++)for(var Q=0;Q<=l;Q++){var y=Q/l,v=E/I;switch(d[B+0]=o?1-y:y,d[B+1]=v,A){case"x,y":h[p+0]=c*y-.5*c,h[p+1]=u*v-.5*u,h[p+2]=r,f[p+0]=0,f[p+1]=0,f[p+2]=o?1:-1;break;case"x,z":h[p+0]=c*y-.5*c,h[p+1]=r,h[p+2]=u*v-.5*u,f[p+0]=0,f[p+1]=o?1:-1,f[p+2]=0;break;case"y,z":h[p+0]=r,h[p+1]=c*y-.5*c,h[p+2]=u*v-.5*u,f[p+0]=o?1:-1,f[p+1]=0,f[p+2]=0;break;default:throw new Error("PlaneGeometry: unknown type")}B+=2,p+=3}for(var m=l+1,b=new Uint16Array(l*I*6),w=0;w0&&void 0!==arguments[0]?arguments[0]:{};Object(w.a)(this,A);var n=e.id,r=void 0===n?Object(R.c)("sphere-geometry"):n,i=J(e),o=i.indices,a=i.attributes;return t.call(this,Object(b.a)({},e,{id:r,indices:o,attributes:Object(b.a)({},a,{},e.attributes)}))}return A}(v.a);function J(e){var t=e.nlat,A=void 0===t?10:t,n=e.nlong,r=void 0===n?10:n,i=e.radius,o=void 0===i?1:i,a=Math.PI-0,s=2*Math.PI-0,g=(A+1)*(r+1);if("number"===typeof o){var c=o;o=function(e,t,A,n,r){return c}}for(var u=new Float32Array(3*g),l=new Float32Array(3*g),I=new Float32Array(2*g),C=new(g>65535?Uint32Array:Uint16Array)(A*r*6),h=0;h<=A;h++)for(var f=0;f<=r;f++){var d=f/r,B=h/A,p=f+h*(r+1),E=2*p,Q=3*p,y=s*d,v=a*B,m=Math.sin(y),b=Math.cos(y),w=Math.sin(v),S=b*w,F=Math.cos(v),R=m*w,D=o(S,F,R,d,B);u[Q+0]=D*S,u[Q+1]=D*F,u[Q+2]=D*R,l[Q+0]=S,l[Q+1]=F,l[Q+2]=R,I[E+0]=d,I[E+1]=1-B}for(var G=r+1,k=0;k1&&void 0!==arguments[1]?arguments[1]:[],A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=Math.fround(e),r=e-n;return t[A]=n,t[A+1]=r,t}function K(e){return e-Math.fround(e)}function W(e){for(var t=new Float32Array(32),A=0;A<4;++A)for(var n=0;n<4;++n){var r=4*A+n;V(e[4*n+A],t,2*r)}return t}var X={ONE:1};var q={name:"fp64",vs:"const vec2 E_FP64 = vec2(2.7182817459106445e+00, 8.254840366817007e-08);\nconst vec2 LOG2_FP64 = vec2(0.6931471824645996e+00, -1.9046542121259336e-09);\nconst vec2 PI_FP64 = vec2(3.1415927410125732, -8.742278012618954e-8);\nconst vec2 TWO_PI_FP64 = vec2(6.2831854820251465, -1.7484556025237907e-7);\nconst vec2 PI_2_FP64 = vec2(1.5707963705062866, -4.371139006309477e-8);\nconst vec2 PI_4_FP64 = vec2(0.7853981852531433, -2.1855695031547384e-8);\nconst vec2 PI_16_FP64 = vec2(0.19634954631328583, -5.463923757886846e-9);\nconst vec2 PI_16_2_FP64 = vec2(0.39269909262657166, -1.0927847515773692e-8);\nconst vec2 PI_16_3_FP64 = vec2(0.5890486240386963, -1.4906100798128818e-9);\nconst vec2 PI_180_FP64 = vec2(0.01745329238474369, 1.3519960498364902e-10);\n\nconst vec2 SIN_TABLE_0_FP64 = vec2(0.19509032368659973, -1.6704714833615242e-9);\nconst vec2 SIN_TABLE_1_FP64 = vec2(0.3826834261417389, 6.22335089017767e-9);\nconst vec2 SIN_TABLE_2_FP64 = vec2(0.5555702447891235, -1.1769521357507529e-8);\nconst vec2 SIN_TABLE_3_FP64 = vec2(0.7071067690849304, 1.2101617041793133e-8);\n\nconst vec2 COS_TABLE_0_FP64 = vec2(0.9807852506637573, 2.9739473106360492e-8);\nconst vec2 COS_TABLE_1_FP64 = vec2(0.9238795042037964, 2.8307490351764386e-8);\nconst vec2 COS_TABLE_2_FP64 = vec2(0.8314695954322815, 1.6870263741530778e-8);\nconst vec2 COS_TABLE_3_FP64 = vec2(0.7071067690849304, 1.2101617152815436e-8);\n\nconst vec2 INVERSE_FACTORIAL_3_FP64 = vec2(1.666666716337204e-01, -4.967053879312289e-09);\nconst vec2 INVERSE_FACTORIAL_4_FP64 = vec2(4.16666679084301e-02, -1.2417634698280722e-09);\nconst vec2 INVERSE_FACTORIAL_5_FP64 = vec2(8.333333767950535e-03, -4.34617203337595e-10);\nconst vec2 INVERSE_FACTORIAL_6_FP64 = vec2(1.3888889225199819e-03, -3.3631094437103215e-11);\nconst vec2 INVERSE_FACTORIAL_7_FP64 = vec2(1.9841270113829523e-04, -2.725596874933456e-12);\nconst vec2 INVERSE_FACTORIAL_8_FP64 = vec2(2.4801587642286904e-05, -3.406996025904184e-13);\nconst vec2 INVERSE_FACTORIAL_9_FP64 = vec2(2.75573188446287533e-06, 3.7935713937038186e-14);\nconst vec2 INVERSE_FACTORIAL_10_FP64 = vec2(2.755731998149713e-07, -7.575112367869873e-15);\n\nfloat nint(float d) {\n if (d == floor(d)) return d;\n return floor(d + 0.5);\n}\n\nvec2 nint_fp64(vec2 a) {\n float hi = nint(a.x);\n float lo;\n vec2 tmp;\n if (hi == a.x) {\n lo = nint(a.y);\n tmp = quickTwoSum(hi, lo);\n } else {\n lo = 0.0;\n if (abs(hi - a.x) == 0.5 && a.y < 0.0) {\n hi -= 1.0;\n }\n tmp = vec2(hi, lo);\n }\n return tmp;\n}\n\nvec2 exp_fp64(vec2 a) {\n\n const int k_power = 4;\n const float k = 16.0;\n\n const float inv_k = 1.0 / k;\n\n if (a.x <= -88.0) return vec2(0.0, 0.0);\n if (a.x >= 88.0) return vec2(1.0 / 0.0, 1.0 / 0.0);\n if (a.x == 0.0 && a.y == 0.0) return vec2(1.0, 0.0);\n if (a.x == 1.0 && a.y == 0.0) return E_FP64;\n\n float m = floor(a.x / LOG2_FP64.x + 0.5);\n vec2 r = sub_fp64(a, mul_fp64(LOG2_FP64, vec2(m, 0.0))) * inv_k;\n vec2 s, t, p;\n\n p = mul_fp64(r, r);\n s = sum_fp64(r, p * 0.5);\n p = mul_fp64(p, r);\n t = mul_fp64(p, INVERSE_FACTORIAL_3_FP64);\n\n s = sum_fp64(s, t);\n p = mul_fp64(p, r);\n t = mul_fp64(p, INVERSE_FACTORIAL_4_FP64);\n\n s = sum_fp64(s, t);\n p = mul_fp64(p, r);\n t = mul_fp64(p, INVERSE_FACTORIAL_5_FP64);\n\n\n\n\n\n\n s = sum_fp64(s, t);\n for (int i = 0; i < k_power; i++) {\n s = sum_fp64(s * 2.0, mul_fp64(s, s));\n }\n\n#if defined(NVIDIA_FP64_WORKAROUND) || defined(INTEL_FP64_WORKAROUND)\n s = sum_fp64(s, vec2(ONE, 0.0));\n#else\n s = sum_fp64(s, vec2(1.0, 0.0));\n#endif\n\n return s * pow(2.0, m);\n}\n\nvec2 log_fp64(vec2 a)\n{\n if (a.x == 1.0 && a.y == 0.0) return vec2(0.0, 0.0);\n if (a.x <= 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0);\n vec2 x = vec2(log(a.x), 0.0);\n vec2 s;\n#if defined(NVIDIA_FP64_WORKAROUND) || defined(INTEL_FP64_WORKAROUND)\n s = vec2(ONE, 0.0);\n#else\n s = vec2(1.0, 0.0);\n#endif\n\n x = sub_fp64(sum_fp64(x, mul_fp64(a, exp_fp64(-x))), s);\n return x;\n}\n\nvec2 sin_taylor_fp64(vec2 a) {\n vec2 r, s, t, x;\n\n if (a.x == 0.0 && a.y == 0.0) {\n return vec2(0.0, 0.0);\n }\n\n x = -mul_fp64(a, a);\n s = a;\n r = a;\n\n r = mul_fp64(r, x);\n t = mul_fp64(r, INVERSE_FACTORIAL_3_FP64);\n s = sum_fp64(s, t);\n\n r = mul_fp64(r, x);\n t = mul_fp64(r, INVERSE_FACTORIAL_5_FP64);\n s = sum_fp64(s, t);\n\n\n\n\n\n\n return s;\n}\n\nvec2 cos_taylor_fp64(vec2 a) {\n vec2 r, s, t, x;\n\n if (a.x == 0.0 && a.y == 0.0) {\n return vec2(1.0, 0.0);\n }\n\n x = -mul_fp64(a, a);\n r = x;\n s = sum_fp64(vec2(1.0, 0.0), r * 0.5);\n\n r = mul_fp64(r, x);\n t = mul_fp64(r, INVERSE_FACTORIAL_4_FP64);\n s = sum_fp64(s, t);\n\n r = mul_fp64(r, x);\n t = mul_fp64(r, INVERSE_FACTORIAL_6_FP64);\n s = sum_fp64(s, t);\n\n\n\n\n\n\n return s;\n}\n\nvoid sincos_taylor_fp64(vec2 a, out vec2 sin_t, out vec2 cos_t) {\n if (a.x == 0.0 && a.y == 0.0) {\n sin_t = vec2(0.0, 0.0);\n cos_t = vec2(1.0, 0.0);\n }\n\n sin_t = sin_taylor_fp64(a);\n cos_t = sqrt_fp64(sub_fp64(vec2(1.0, 0.0), mul_fp64(sin_t, sin_t)));\n}\n\nvec2 sin_fp64(vec2 a) {\n if (a.x == 0.0 && a.y == 0.0) {\n return vec2(0.0, 0.0);\n }\n vec2 z = nint_fp64(div_fp64(a, TWO_PI_FP64));\n vec2 r = sub_fp64(a, mul_fp64(TWO_PI_FP64, z));\n\n vec2 t;\n float q = floor(r.x / PI_2_FP64.x + 0.5);\n int j = int(q);\n\n if (j < -2 || j > 2) {\n return vec2(0.0 / 0.0, 0.0 / 0.0);\n }\n\n t = sub_fp64(r, mul_fp64(PI_2_FP64, vec2(q, 0.0)));\n\n q = floor(t.x / PI_16_FP64.x + 0.5);\n int k = int(q);\n\n if (k == 0) {\n if (j == 0) {\n return sin_taylor_fp64(t);\n } else if (j == 1) {\n return cos_taylor_fp64(t);\n } else if (j == -1) {\n return -cos_taylor_fp64(t);\n } else {\n return -sin_taylor_fp64(t);\n }\n }\n\n int abs_k = int(abs(float(k)));\n\n if (abs_k > 4) {\n return vec2(0.0 / 0.0, 0.0 / 0.0);\n } else {\n t = sub_fp64(t, mul_fp64(PI_16_FP64, vec2(q, 0.0)));\n }\n\n vec2 u = vec2(0.0, 0.0);\n vec2 v = vec2(0.0, 0.0);\n\n#if defined(NVIDIA_FP64_WORKAROUND) || defined(INTEL_FP64_WORKAROUND)\n if (abs(float(abs_k) - 1.0) < 0.5) {\n u = COS_TABLE_0_FP64;\n v = SIN_TABLE_0_FP64;\n } else if (abs(float(abs_k) - 2.0) < 0.5) {\n u = COS_TABLE_1_FP64;\n v = SIN_TABLE_1_FP64;\n } else if (abs(float(abs_k) - 3.0) < 0.5) {\n u = COS_TABLE_2_FP64;\n v = SIN_TABLE_2_FP64;\n } else if (abs(float(abs_k) - 4.0) < 0.5) {\n u = COS_TABLE_3_FP64;\n v = SIN_TABLE_3_FP64;\n }\n#else\n if (abs_k == 1) {\n u = COS_TABLE_0_FP64;\n v = SIN_TABLE_0_FP64;\n } else if (abs_k == 2) {\n u = COS_TABLE_1_FP64;\n v = SIN_TABLE_1_FP64;\n } else if (abs_k == 3) {\n u = COS_TABLE_2_FP64;\n v = SIN_TABLE_2_FP64;\n } else if (abs_k == 4) {\n u = COS_TABLE_3_FP64;\n v = SIN_TABLE_3_FP64;\n }\n#endif\n\n vec2 sin_t, cos_t;\n sincos_taylor_fp64(t, sin_t, cos_t);\n\n\n\n vec2 result = vec2(0.0, 0.0);\n if (j == 0) {\n if (k > 0) {\n result = sum_fp64(mul_fp64(u, sin_t), mul_fp64(v, cos_t));\n } else {\n result = sub_fp64(mul_fp64(u, sin_t), mul_fp64(v, cos_t));\n }\n } else if (j == 1) {\n if (k > 0) {\n result = sub_fp64(mul_fp64(u, cos_t), mul_fp64(v, sin_t));\n } else {\n result = sum_fp64(mul_fp64(u, cos_t), mul_fp64(v, sin_t));\n }\n } else if (j == -1) {\n if (k > 0) {\n result = sub_fp64(mul_fp64(v, sin_t), mul_fp64(u, cos_t));\n } else {\n result = -sum_fp64(mul_fp64(v, sin_t), mul_fp64(u, cos_t));\n }\n } else {\n if (k > 0) {\n result = -sum_fp64(mul_fp64(u, sin_t), mul_fp64(v, cos_t));\n } else {\n result = sub_fp64(mul_fp64(v, cos_t), mul_fp64(u, sin_t));\n }\n }\n\n return result;\n}\n\nvec2 cos_fp64(vec2 a) {\n if (a.x == 0.0 && a.y == 0.0) {\n return vec2(1.0, 0.0);\n }\n vec2 z = nint_fp64(div_fp64(a, TWO_PI_FP64));\n vec2 r = sub_fp64(a, mul_fp64(TWO_PI_FP64, z));\n\n vec2 t;\n float q = floor(r.x / PI_2_FP64.x + 0.5);\n int j = int(q);\n\n if (j < -2 || j > 2) {\n return vec2(0.0 / 0.0, 0.0 / 0.0);\n }\n\n t = sub_fp64(r, mul_fp64(PI_2_FP64, vec2(q, 0.0)));\n\n q = floor(t.x / PI_16_FP64.x + 0.5);\n int k = int(q);\n\n if (k == 0) {\n if (j == 0) {\n return cos_taylor_fp64(t);\n } else if (j == 1) {\n return -sin_taylor_fp64(t);\n } else if (j == -1) {\n return sin_taylor_fp64(t);\n } else {\n return -cos_taylor_fp64(t);\n }\n }\n\n int abs_k = int(abs(float(k)));\n\n if (abs_k > 4) {\n return vec2(0.0 / 0.0, 0.0 / 0.0);\n } else {\n t = sub_fp64(t, mul_fp64(PI_16_FP64, vec2(q, 0.0)));\n }\n\n vec2 u = vec2(0.0, 0.0);\n vec2 v = vec2(0.0, 0.0);\n\n#if defined(NVIDIA_FP64_WORKAROUND) || defined(INTEL_FP64_WORKAROUND)\n if (abs(float(abs_k) - 1.0) < 0.5) {\n u = COS_TABLE_0_FP64;\n v = SIN_TABLE_0_FP64;\n } else if (abs(float(abs_k) - 2.0) < 0.5) {\n u = COS_TABLE_1_FP64;\n v = SIN_TABLE_1_FP64;\n } else if (abs(float(abs_k) - 3.0) < 0.5) {\n u = COS_TABLE_2_FP64;\n v = SIN_TABLE_2_FP64;\n } else if (abs(float(abs_k) - 4.0) < 0.5) {\n u = COS_TABLE_3_FP64;\n v = SIN_TABLE_3_FP64;\n }\n#else\n if (abs_k == 1) {\n u = COS_TABLE_0_FP64;\n v = SIN_TABLE_0_FP64;\n } else if (abs_k == 2) {\n u = COS_TABLE_1_FP64;\n v = SIN_TABLE_1_FP64;\n } else if (abs_k == 3) {\n u = COS_TABLE_2_FP64;\n v = SIN_TABLE_2_FP64;\n } else if (abs_k == 4) {\n u = COS_TABLE_3_FP64;\n v = SIN_TABLE_3_FP64;\n }\n#endif\n\n vec2 sin_t, cos_t;\n sincos_taylor_fp64(t, sin_t, cos_t);\n\n vec2 result = vec2(0.0, 0.0);\n if (j == 0) {\n if (k > 0) {\n result = sub_fp64(mul_fp64(u, cos_t), mul_fp64(v, sin_t));\n } else {\n result = sum_fp64(mul_fp64(u, cos_t), mul_fp64(v, sin_t));\n }\n } else if (j == 1) {\n if (k > 0) {\n result = -sum_fp64(mul_fp64(u, sin_t), mul_fp64(v, cos_t));\n } else {\n result = sub_fp64(mul_fp64(v, cos_t), mul_fp64(u, sin_t));\n }\n } else if (j == -1) {\n if (k > 0) {\n result = sum_fp64(mul_fp64(u, sin_t), mul_fp64(v, cos_t));\n } else {\n result = sub_fp64(mul_fp64(u, sin_t), mul_fp64(v, cos_t));\n }\n } else {\n if (k > 0) {\n result = sub_fp64(mul_fp64(v, sin_t), mul_fp64(u, cos_t));\n } else {\n result = -sum_fp64(mul_fp64(u, cos_t), mul_fp64(v, sin_t));\n }\n }\n\n return result;\n}\n\nvec2 tan_fp64(vec2 a) {\n vec2 sin_a;\n vec2 cos_a;\n\n if (a.x == 0.0 && a.y == 0.0) {\n return vec2(0.0, 0.0);\n }\n vec2 z = nint_fp64(div_fp64(a, TWO_PI_FP64));\n vec2 r = sub_fp64(a, mul_fp64(TWO_PI_FP64, z));\n\n vec2 t;\n float q = floor(r.x / PI_2_FP64.x + 0.5);\n int j = int(q);\n\n\n if (j < -2 || j > 2) {\n return vec2(0.0 / 0.0, 0.0 / 0.0);\n }\n\n t = sub_fp64(r, mul_fp64(PI_2_FP64, vec2(q, 0.0)));\n\n q = floor(t.x / PI_16_FP64.x + 0.5);\n int k = int(q);\n int abs_k = int(abs(float(k)));\n\n if (abs_k > 4) {\n return vec2(0.0 / 0.0, 0.0 / 0.0);\n } else {\n t = sub_fp64(t, mul_fp64(PI_16_FP64, vec2(q, 0.0)));\n }\n\n\n vec2 u = vec2(0.0, 0.0);\n vec2 v = vec2(0.0, 0.0);\n\n vec2 sin_t, cos_t;\n vec2 s, c;\n sincos_taylor_fp64(t, sin_t, cos_t);\n\n if (k == 0) {\n s = sin_t;\n c = cos_t;\n } else {\n#if defined(NVIDIA_FP64_WORKAROUND) || defined(INTEL_FP64_WORKAROUND)\n if (abs(float(abs_k) - 1.0) < 0.5) {\n u = COS_TABLE_0_FP64;\n v = SIN_TABLE_0_FP64;\n } else if (abs(float(abs_k) - 2.0) < 0.5) {\n u = COS_TABLE_1_FP64;\n v = SIN_TABLE_1_FP64;\n } else if (abs(float(abs_k) - 3.0) < 0.5) {\n u = COS_TABLE_2_FP64;\n v = SIN_TABLE_2_FP64;\n } else if (abs(float(abs_k) - 4.0) < 0.5) {\n u = COS_TABLE_3_FP64;\n v = SIN_TABLE_3_FP64;\n }\n#else\n if (abs_k == 1) {\n u = COS_TABLE_0_FP64;\n v = SIN_TABLE_0_FP64;\n } else if (abs_k == 2) {\n u = COS_TABLE_1_FP64;\n v = SIN_TABLE_1_FP64;\n } else if (abs_k == 3) {\n u = COS_TABLE_2_FP64;\n v = SIN_TABLE_2_FP64;\n } else if (abs_k == 4) {\n u = COS_TABLE_3_FP64;\n v = SIN_TABLE_3_FP64;\n }\n#endif\n if (k > 0) {\n s = sum_fp64(mul_fp64(u, sin_t), mul_fp64(v, cos_t));\n c = sub_fp64(mul_fp64(u, cos_t), mul_fp64(v, sin_t));\n } else {\n s = sub_fp64(mul_fp64(u, sin_t), mul_fp64(v, cos_t));\n c = sum_fp64(mul_fp64(u, cos_t), mul_fp64(v, sin_t));\n }\n }\n\n if (j == 0) {\n sin_a = s;\n cos_a = c;\n } else if (j == 1) {\n sin_a = c;\n cos_a = -s;\n } else if (j == -1) {\n sin_a = -c;\n cos_a = s;\n } else {\n sin_a = -s;\n cos_a = -c;\n }\n return div_fp64(sin_a, cos_a);\n}\n\nvec2 radians_fp64(vec2 degree) {\n return mul_fp64(degree, PI_180_FP64);\n}\n\nvec2 mix_fp64(vec2 a, vec2 b, float x) {\n vec2 range = sub_fp64(b, a);\n return sum_fp64(a, mul_fp64(range, vec2(x, 0.0)));\n}\n\nvoid vec2_sum_fp64(vec2 a[2], vec2 b[2], out vec2 out_val[2]) {\n out_val[0] = sum_fp64(a[0], b[0]);\n out_val[1] = sum_fp64(a[1], b[1]);\n}\n\nvoid vec2_sub_fp64(vec2 a[2], vec2 b[2], out vec2 out_val[2]) {\n out_val[0] = sub_fp64(a[0], b[0]);\n out_val[1] = sub_fp64(a[1], b[1]);\n}\n\nvoid vec2_mul_fp64(vec2 a[2], vec2 b[2], out vec2 out_val[2]) {\n out_val[0] = mul_fp64(a[0], b[0]);\n out_val[1] = mul_fp64(a[1], b[1]);\n}\n\nvoid vec2_div_fp64(vec2 a[2], vec2 b[2], out vec2 out_val[2]) {\n out_val[0] = div_fp64(a[0], b[0]);\n out_val[1] = div_fp64(a[1], b[1]);\n}\n\nvoid vec2_mix_fp64(vec2 x[2], vec2 y[2], float a, out vec2 out_val[2]) {\n vec2 range[2];\n vec2_sub_fp64(y, x, range);\n vec2 portion[2];\n portion[0] = range[0] * a;\n portion[1] = range[1] * a;\n vec2_sum_fp64(x, portion, out_val);\n}\n\nvec2 vec2_length_fp64(vec2 x[2]) {\n return sqrt_fp64(sum_fp64(mul_fp64(x[0], x[0]), mul_fp64(x[1], x[1])));\n}\n\nvoid vec2_normalize_fp64(vec2 x[2], out vec2 out_val[2]) {\n vec2 length = vec2_length_fp64(x);\n vec2 length_vec2[2];\n length_vec2[0] = length;\n length_vec2[1] = length;\n\n vec2_div_fp64(x, length_vec2, out_val);\n}\n\nvec2 vec2_distance_fp64(vec2 x[2], vec2 y[2]) {\n vec2 diff[2];\n vec2_sub_fp64(x, y, diff);\n return vec2_length_fp64(diff);\n}\n\nvec2 vec2_dot_fp64(vec2 a[2], vec2 b[2]) {\n vec2 v[2];\n\n v[0] = mul_fp64(a[0], b[0]);\n v[1] = mul_fp64(a[1], b[1]);\n\n return sum_fp64(v[0], v[1]);\n}\nvoid vec3_sub_fp64(vec2 a[3], vec2 b[3], out vec2 out_val[3]) {\n for (int i = 0; i < 3; i++) {\n out_val[i] = sum_fp64(a[i], b[i]);\n }\n}\n\nvoid vec3_sum_fp64(vec2 a[3], vec2 b[3], out vec2 out_val[3]) {\n for (int i = 0; i < 3; i++) {\n out_val[i] = sum_fp64(a[i], b[i]);\n }\n}\n\nvec2 vec3_length_fp64(vec2 x[3]) {\n return sqrt_fp64(sum_fp64(sum_fp64(mul_fp64(x[0], x[0]), mul_fp64(x[1], x[1])),\n mul_fp64(x[2], x[2])));\n}\n\nvec2 vec3_distance_fp64(vec2 x[3], vec2 y[3]) {\n vec2 diff[3];\n vec3_sub_fp64(x, y, diff);\n return vec3_length_fp64(diff);\n}\nvoid vec4_fp64(vec4 a, out vec2 out_val[4]) {\n out_val[0].x = a[0];\n out_val[0].y = 0.0;\n\n out_val[1].x = a[1];\n out_val[1].y = 0.0;\n\n out_val[2].x = a[2];\n out_val[2].y = 0.0;\n\n out_val[3].x = a[3];\n out_val[3].y = 0.0;\n}\n\nvoid vec4_scalar_mul_fp64(vec2 a[4], vec2 b, out vec2 out_val[4]) {\n out_val[0] = mul_fp64(a[0], b);\n out_val[1] = mul_fp64(a[1], b);\n out_val[2] = mul_fp64(a[2], b);\n out_val[3] = mul_fp64(a[3], b);\n}\n\nvoid vec4_sum_fp64(vec2 a[4], vec2 b[4], out vec2 out_val[4]) {\n for (int i = 0; i < 4; i++) {\n out_val[i] = sum_fp64(a[i], b[i]);\n }\n}\n\nvoid vec4_dot_fp64(vec2 a[4], vec2 b[4], out vec2 out_val) {\n vec2 v[4];\n\n v[0] = mul_fp64(a[0], b[0]);\n v[1] = mul_fp64(a[1], b[1]);\n v[2] = mul_fp64(a[2], b[2]);\n v[3] = mul_fp64(a[3], b[3]);\n\n out_val = sum_fp64(sum_fp64(v[0], v[1]), sum_fp64(v[2], v[3]));\n}\n\nvoid mat4_vec4_mul_fp64(vec2 b[16], vec2 a[4], out vec2 out_val[4]) {\n vec2 tmp[4];\n\n for (int i = 0; i < 4; i++)\n {\n for (int j = 0; j < 4; j++)\n {\n tmp[j] = b[j + i * 4];\n }\n vec4_dot_fp64(a, tmp, out_val[i]);\n }\n}\n",fs:null,dependencies:[{name:"fp64-arithmetic",vs:"uniform float ONE;\nvec2 split(float a) {\n const float SPLIT = 4097.0;\n float t = a * SPLIT;\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float a_hi = t * ONE - (t - a);\n float a_lo = a * ONE - a_hi;\n#else\n float a_hi = t - (t - a);\n float a_lo = a - a_hi;\n#endif\n return vec2(a_hi, a_lo);\n}\nvec2 split2(vec2 a) {\n vec2 b = split(a.x);\n b.y += a.y;\n return b;\n}\nvec2 quickTwoSum(float a, float b) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float sum = (a + b) * ONE;\n float err = b - (sum - a) * ONE;\n#else\n float sum = a + b;\n float err = b - (sum - a);\n#endif\n return vec2(sum, err);\n}\nvec2 twoSum(float a, float b) {\n float s = (a + b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * ONE - a) * ONE;\n float err = (a - (s - v) * ONE) * ONE * ONE * ONE + (b - v);\n#else\n float v = s - a;\n float err = (a - (s - v)) + (b - v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSub(float a, float b) {\n float s = (a - b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * ONE - a) * ONE;\n float err = (a - (s - v) * ONE) * ONE * ONE * ONE - (b + v);\n#else\n float v = s - a;\n float err = (a - (s - v)) - (b + v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSqr(float a) {\n float prod = a * a;\n vec2 a_fp64 = split(a);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err = ((a_fp64.x * a_fp64.x - prod) * ONE + 2.0 * a_fp64.x *\n a_fp64.y * ONE * ONE) + a_fp64.y * a_fp64.y * ONE * ONE * ONE;\n#else\n float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y;\n#endif\n return vec2(prod, err);\n}\n\nvec2 twoProd(float a, float b) {\n float prod = a * b;\n vec2 a_fp64 = split(a);\n vec2 b_fp64 = split(b);\n float err = ((a_fp64.x * b_fp64.x - prod) + a_fp64.x * b_fp64.y +\n a_fp64.y * b_fp64.x) + a_fp64.y * b_fp64.y;\n return vec2(prod, err);\n}\n\nvec2 sum_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSum(a.x, b.x);\n t = twoSum(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 sub_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSub(a.x, b.x);\n t = twoSub(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 mul_fp64(vec2 a, vec2 b) {\n vec2 prod = twoProd(a.x, b.x);\n prod.y += a.x * b.y;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n prod.y += a.y * b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\nvec2 div_fp64(vec2 a, vec2 b) {\n float xn = 1.0 / b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n vec2 yn = mul_fp64(a, vec2(xn, 0));\n#else\n vec2 yn = a * xn;\n#endif\n float diff = (sub_fp64(a, mul_fp64(b, yn))).x;\n vec2 prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nvec2 sqrt_fp64(vec2 a) {\n if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0);\n if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0);\n\n float x = 1.0 / sqrt(a.x);\n float yn = a.x * x;\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n vec2 yn_sqr = twoSqr(yn) * ONE;\n#else\n vec2 yn_sqr = twoSqr(yn);\n#endif\n float diff = sub_fp64(a, yn_sqr).x;\n vec2 prod = twoProd(x * 0.5, diff);\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2(yn, 0.0), prod);\n#endif\n}\n",fs:null,getUniforms:function(){return X},fp64ify:V,fp64LowPart:K,fp64ifyMatrix4:W}],fp64ify:V,fp64LowPart:K,fp64ifyMatrix4:W},z=A(286),$=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],ee={modelMatrix:$,viewMatrix:$,projectionMatrix:$,cameraPositionWorld:[0,0,0]};var te="varying vec4 project_vPositionWorld;\nvarying vec3 project_vNormalWorld;\n\nvec4 project_getPosition_World() {\n return project_vPositionWorld;\n}\n\nvec3 project_getNormal_World() {\n return project_vNormalWorld;\n}\n",Ae={name:"project",getUniforms:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ee,t=(arguments.length>1&&void 0!==arguments[1]&&arguments[1],{});return void 0!==e.modelMatrix&&(t.modelMatrix=e.modelMatrix),void 0!==e.viewMatrix&&(t.viewMatrix=e.viewMatrix),void 0!==e.projectionMatrix&&(t.projectionMatrix=e.projectionMatrix),void 0!==e.cameraPositionWorld&&(t.cameraPositionWorld=e.cameraPositionWorld),void 0===e.projectionMatrix&&void 0===e.viewMatrix||(t.viewProjectionMatrix=new z.a(e.projectionMatrix).multiplyRight(e.viewMatrix)),t},vs:"".concat(te,"\nuniform mat4 modelMatrix;\nuniform mat4 viewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewProjectionMatrix;\nuniform vec3 cameraPositionWorld;\n\nstruct World {\n vec3 position;\n vec3 normal;\n};\n\nWorld world;\n\nvoid project_setPosition(vec4 position) {\n project_vPositionWorld = position;\n}\n\nvoid project_setNormal(vec3 normal) {\n project_vNormalWorld = normal;\n}\n\nvoid project_setPositionAndNormal_World(vec3 position, vec3 normal) {\n world.position = position;\n world.normal = normal;\n}\n\nvoid project_setPositionAndNormal_Model(vec3 position, vec3 normal) {\n world.position = (modelMatrix * vec4(position, 1.)).xyz;\n world.normal = mat3(modelMatrix) * normal;\n}\n\nvec4 project_model_to_clipspace(vec4 position) {\n return viewProjectionMatrix * modelMatrix * position;\n}\n\nvec4 project_model_to_clipspace(vec3 position) {\n return viewProjectionMatrix * modelMatrix * vec4(position, 1.);\n}\n\nvec4 project_world_to_clipspace(vec3 position) {\n return viewProjectionMatrix * vec4(position, 1.);\n}\n\nvec4 project_view_to_clipspace(vec3 position) {\n return projectionMatrix * vec4(position, 1.);\n}\n\nvec4 project_to_clipspace(vec3 position) {\n return viewProjectionMatrix * vec4(position, 1.);\n}\n"),fs:"\n".concat(te)},ne={lightDirection:new Float32Array([1,1,2])};var re={name:"dirlight",vs:null,fs:"uniform vec3 dirlight_uLightDirection;\nvec4 dirlight_filterColor(vec4 color) {\n vec3 normal = project_getNormal_World();\n float d = abs(dot(normalize(normal), normalize(dirlight_uLightDirection)));\n return vec4(color.rgb * d, color.a);\n}\n",getUniforms:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ne,t={};return e.lightDirection&&(t.dirlight_uLightDirection=e.lightDirection),t},dependencies:[Ae]},ie=A(1158),oe=A(655),ae=A(1295),se=A(26);A.d(t,"createGLContext",(function(){return n.c})),A.d(t,"instrumentGLContext",(function(){return n.h})),A.d(t,"isWebGL",(function(){return n.i})),A.d(t,"isWebGL2",(function(){return n.j})),A.d(t,"getParameters",(function(){return n.f})),A.d(t,"setParameters",(function(){return n.n})),A.d(t,"withParameters",(function(){return n.o})),A.d(t,"resetParameters",(function(){return n.l})),A.d(t,"cssToDeviceRatio",(function(){return n.e})),A.d(t,"cssToDevicePixels",(function(){return n.d})),A.d(t,"lumaStats",(function(){return r.a})),A.d(t,"FEATURES",(function(){return i.a})),A.d(t,"hasFeature",(function(){return o.b})),A.d(t,"hasFeatures",(function(){return o.c})),A.d(t,"Buffer",(function(){return a.a})),A.d(t,"Program",(function(){return s.a})),A.d(t,"Framebuffer",(function(){return g.a})),A.d(t,"Renderbuffer",(function(){return c.a})),A.d(t,"Texture2D",(function(){return u.a})),A.d(t,"TextureCube",(function(){return l.a})),A.d(t,"clear",(function(){return I.a})),A.d(t,"readPixelsToArray",(function(){return C.c})),A.d(t,"readPixelsToBuffer",(function(){return C.d})),A.d(t,"cloneTextureFrom",(function(){return h.a})),A.d(t,"copyToTexture",(function(){return C.b})),A.d(t,"Texture3D",(function(){return f.a})),A.d(t,"TransformFeedback",(function(){return d.a})),A.d(t,"AnimationLoop",(function(){return B.a})),A.d(t,"Model",(function(){return p.a})),A.d(t,"Transform",(function(){return E.a})),A.d(t,"ProgramManager",(function(){return Q.a})),A.d(t,"Timeline",(function(){return y.a})),A.d(t,"Geometry",(function(){return v.a})),A.d(t,"ClipSpace",(function(){return m.a})),A.d(t,"ConeGeometry",(function(){return x})),A.d(t,"CubeGeometry",(function(){return N.a})),A.d(t,"CylinderGeometry",(function(){return U})),A.d(t,"IcoSphereGeometry",(function(){return L})),A.d(t,"PlaneGeometry",(function(){return Z})),A.d(t,"SphereGeometry",(function(){return Y})),A.d(t,"TruncatedConeGeometry",(function(){return G})),A.d(t,"normalizeShaderModule",(function(){return j.b})),A.d(t,"fp32",(function(){return P.a})),A.d(t,"fp64",(function(){return q})),A.d(t,"project",(function(){return Ae})),A.d(t,"dirlight",(function(){return re})),A.d(t,"picking",(function(){return ie.a})),A.d(t,"gouraudLighting",(function(){return oe.a})),A.d(t,"phongLighting",(function(){return oe.b})),A.d(t,"pbr",(function(){return ae.a})),A.d(t,"log",(function(){return n.k})),A.d(t,"assert",(function(){return se.a})),A.d(t,"uid",(function(){return R.c}))},,function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,A){"use strict";var n=A(2),r=A(5),i=new Date,o=new Date;function a(e,t,A,n){function r(t){return e(t=0===arguments.length?new Date:new Date(+t)),t}return r.floor=function(t){return e(t=new Date(+t)),t},r.ceil=function(A){return e(A=new Date(A-1)),t(A,1),e(A),A},r.round=function(e){var t=r(e),A=r.ceil(e);return e-t0))return a;do{a.push(o=new Date(+A)),t(A,i),e(A)}while(o=t)for(;e(t),!A(t);)t.setTime(t-1)}),(function(e,n){if(e>=e)if(n<0)for(;++n<=0;)for(;t(e,-1),!A(e););else for(;--n>=0;)for(;t(e,1),!A(e););}))},A&&(r.count=function(t,n){return i.setTime(+t),o.setTime(+n),e(i),e(o),Math.floor(A(i,o))},r.every=function(e){return e=Math.floor(e),isFinite(e)&&e>0?e>1?r.filter(n?function(t){return n(t)%e===0}:function(t){return r.count(0,t)%e===0}):r:null}),r}var s=a((function(e){return e.setHours(0,0,0,0)}),(function(e,t){return e.setDate(e.getDate()+t)}),(function(e,t){return(t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5}),(function(e){return e.getDate()-1})),g=s;s.range;function c(e){return a((function(t){t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)}),(function(e,t){e.setDate(e.getDate()+7*t)}),(function(e,t){return(t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/6048e5}))}var u=c(0),l=c(1),I=c(2),C=c(3),h=c(4),f=c(5),d=c(6),B=(u.range,l.range,I.range,C.range,h.range,f.range,d.range,a((function(e){e.setUTCHours(0,0,0,0)}),(function(e,t){e.setUTCDate(e.getUTCDate()+t)}),(function(e,t){return(t-e)/864e5}),(function(e){return e.getUTCDate()-1}))),p=B;B.range;function E(e){return a((function(t){t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)}),(function(e,t){e.setUTCDate(e.getUTCDate()+7*t)}),(function(e,t){return(t-e)/6048e5}))}var Q=E(0),y=E(1),v=E(2),m=E(3),b=E(4),w=E(5),S=E(6),F=(Q.range,y.range,v.range,m.range,b.range,w.range,S.range,a((function(e){e.setMonth(0,1),e.setHours(0,0,0,0)}),(function(e,t){e.setFullYear(e.getFullYear()+t)}),(function(e,t){return t.getFullYear()-e.getFullYear()}),(function(e){return e.getFullYear()})));F.every=function(e){return isFinite(e=Math.floor(e))&&e>0?a((function(t){t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,A){t.setFullYear(t.getFullYear()+A*e)})):null};var R=F,D=(F.range,a((function(e){e.setDate(1),e.setHours(0,0,0,0)}),(function(e,t){e.setMonth(e.getMonth()+t)}),(function(e,t){return t.getMonth()-e.getMonth()+12*(t.getFullYear()-e.getFullYear())}),(function(e){return e.getMonth()}))),G=D,k=(D.range,a((function(e){e.setTime(e-e.getMilliseconds()-1e3*e.getSeconds()-6e4*e.getMinutes())}),(function(e,t){e.setTime(+e+36e5*t)}),(function(e,t){return(t-e)/36e5}),(function(e){return e.getHours()}))),x=k,N=(k.range,a((function(e){e.setTime(e-e.getMilliseconds()-1e3*e.getSeconds())}),(function(e,t){e.setTime(+e+6e4*t)}),(function(e,t){return(t-e)/6e4}),(function(e){return e.getMinutes()}))),U=N,_=(N.range,a((function(e){e.setTime(e-e.getMilliseconds())}),(function(e,t){e.setTime(+e+1e3*t)}),(function(e,t){return(t-e)/1e3}),(function(e){return e.getUTCSeconds()}))),M=_,O=(_.range,a((function(){}),(function(e,t){e.setTime(+e+t)}),(function(e,t){return t-e})));O.every=function(e){return e=Math.floor(e),isFinite(e)&&e>0?e>1?a((function(t){t.setTime(Math.floor(t/e)*e)}),(function(t,A){t.setTime(+t+A*e)}),(function(t,A){return(A-t)/e})):O:null};var L=O,T=(O.range,a((function(e){e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)}),(function(e,t){e.setUTCFullYear(e.getUTCFullYear()+t)}),(function(e,t){return t.getUTCFullYear()-e.getUTCFullYear()}),(function(e){return e.getUTCFullYear()})));T.every=function(e){return isFinite(e=Math.floor(e))&&e>0?a((function(t){t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,A){t.setUTCFullYear(t.getUTCFullYear()+A*e)})):null};var Z=T,H=(T.range,a((function(e){e.setUTCDate(1),e.setUTCHours(0,0,0,0)}),(function(e,t){e.setUTCMonth(e.getUTCMonth()+t)}),(function(e,t){return t.getUTCMonth()-e.getUTCMonth()+12*(t.getUTCFullYear()-e.getUTCFullYear())}),(function(e){return e.getUTCMonth()}))),Y=H,J=(H.range,a((function(e){e.setUTCMinutes(0,0,0)}),(function(e,t){e.setTime(+e+36e5*t)}),(function(e,t){return(t-e)/36e5}),(function(e){return e.getUTCHours()}))),j=J,P=(J.range,a((function(e){e.setUTCSeconds(0,0)}),(function(e,t){e.setTime(+e+6e4*t)}),(function(e,t){return(t-e)/6e4}),(function(e){return e.getUTCMinutes()}))),V=P,K=(P.range,function(e){var t=e,A=e;function n(e,t,n,r){for(null==n&&(n=0),null==r&&(r=e.length);n>>1;A(e[i],t)<0?n=i+1:r=i}return n}return 1===e.length&&(t=function(t,A){return e(t)-A},A=function(e){return function(t,A){return(n=e(t))<(r=A)?-1:n>r?1:n>=r?0:NaN;var n,r}}(e)),{left:n,center:function(e,A,r,i){null==r&&(r=0),null==i&&(i=e.length);var o=n(e,A,r,i-1);return o>r&&t(e[o-1],A)>-t(e[o],A)?o-1:o},right:function(e,t,n,r){for(null==n&&(n=0),null==r&&(r=e.length);n>>1;A(e[i],t)>0?r=i:n=i+1}return n}}});var W,X,q,z,$,ee,te,Ae=Math.sqrt(50),ne=Math.sqrt(10),re=Math.sqrt(2);function ie(e,t,A){var n=Math.abs(t-e)/Math.max(0,A),r=Math.pow(10,Math.floor(Math.log(n)/Math.LN10)),i=n/r;return i>=Ae?r*=10:i>=ne?r*=5:i>=re&&(r*=2),t1&&Object(r.o)("Incompatible time units: ".concat(e)),t.sort((function(e,t){return Be[e]-Be[t]})),t}var Ee=(W={},Object(n.a)(W,oe,"%Y "),Object(n.a)(W,ae,"Q%q "),Object(n.a)(W,se,"%b "),Object(n.a)(W,ce,"%d "),Object(n.a)(W,ge,"W%U "),Object(n.a)(W,ue,"%a "),Object(n.a)(W,le,"%j "),Object(n.a)(W,Ie,"%H:00"),Object(n.a)(W,Ce,"00:%M"),Object(n.a)(W,he,":%S"),Object(n.a)(W,fe,".%L"),Object(n.a)(W,"".concat(oe,"-").concat(se),"%Y-%m "),Object(n.a)(W,"".concat(oe,"-").concat(se,"-").concat(ce),"%Y-%m-%d "),Object(n.a)(W,"".concat(Ie,"-").concat(Ce),"%H:%M"),W);function Qe(e,t){var A,n,i=Object(r.p)({},Ee,t),o=pe(e),a=o.length,s="",g=0;for(g=0;gg;--A)if(null!=i[n=o.slice(g,A).join("-")]){s+=i[n],g=A;break}return s.trim()}var ye=new Date;function ve(e){return ye.setFullYear(e),ye.setMonth(0),ye.setDate(1),ye.setHours(0,0,0,0),ye}function me(e){return we(new Date(e))}function be(e){return Se(new Date(e))}function we(e){return g.count(ve(e.getFullYear())-1,e)}function Se(e){return u.count(ve(e.getFullYear())-1,e)}function Fe(e){return ve(e).getDay()}function Re(e,t,A,n,r,i,o){if(0<=e&&e<100){var a=new Date(-1,t,A,n,r,i,o);return a.setFullYear(e),a}return new Date(e,t,A,n,r,i,o)}function De(e){return ke(new Date(e))}function Ge(e){return xe(new Date(e))}function ke(e){var t=Date.UTC(e.getUTCFullYear(),0,1);return p.count(t-1,e)}function xe(e){var t=Date.UTC(e.getUTCFullYear(),0,1);return Q.count(t-1,e)}function Ne(e){return ye.setTime(Date.UTC(e,0,1)),ye.getUTCDay()}function Ue(e,t,A,n,r,i,o){if(0<=e&&e<100){var a=new Date(Date.UTC(-1,t,A,n,r,i,o));return a.setUTCFullYear(A.y),a}return new Date(Date.UTC(e,t,A,n,r,i,o))}function _e(e,t,A,n,i){var o=t||1,a=Object(r.W)(e),s=function(e,t,r){return function(e,t,A,n){var r=A<=1?e:n?function(t,r){return n+A*Math.floor((e(t,r)-n)/A)}:function(t,n){return A*Math.floor(e(t,n)/A)};return t?function(e,A){return t(r(e,A),A)}:r}(A[r=r||e],n[r],e===a&&o,t)},g=new Date,c=Object(r.fb)(e),u=c[oe]?s(oe):Object(r.m)(2012),l=c[se]?s(se):c[ae]?s(ae):r.mb,I=c[ge]&&c[ue]?s(ue,1,ge+ue):c[ge]?s(ge,1):c[ue]?s(ue,1):c[ce]?s(ce,1):c[le]?s(le,1):r.Q,C=c[Ie]?s(Ie):r.mb,h=c[Ce]?s(Ce):r.mb,f=c[he]?s(he):r.mb,d=c[fe]?s(fe):r.mb;return function(e){g.setTime(+e);var t=u(g);return i(t,l(g),I(g,t),C(g),h(g),f(g),d(g))}}function Me(e,t,A){return t+7*e-(A+6)%7}var Oe=(X={},Object(n.a)(X,oe,(function(e){return e.getFullYear()})),Object(n.a)(X,ae,(function(e){return Math.floor(e.getMonth()/3)})),Object(n.a)(X,se,(function(e){return e.getMonth()})),Object(n.a)(X,ce,(function(e){return e.getDate()})),Object(n.a)(X,Ie,(function(e){return e.getHours()})),Object(n.a)(X,Ce,(function(e){return e.getMinutes()})),Object(n.a)(X,he,(function(e){return e.getSeconds()})),Object(n.a)(X,fe,(function(e){return e.getMilliseconds()})),Object(n.a)(X,le,(function(e){return we(e)})),Object(n.a)(X,ge,(function(e){return Se(e)})),Object(n.a)(X,ge+ue,(function(e,t){return Me(Se(e),e.getDay(),Fe(t))})),Object(n.a)(X,ue,(function(e,t){return Me(1,e.getDay(),Fe(t))})),X),Le=(q={},Object(n.a)(q,ae,(function(e){return 3*e})),Object(n.a)(q,ge,(function(e,t){return Me(e,0,Fe(t))})),q);function Te(e,t){return _e(e,t||1,Oe,Le,Re)}var Ze=(z={},Object(n.a)(z,oe,(function(e){return e.getUTCFullYear()})),Object(n.a)(z,ae,(function(e){return Math.floor(e.getUTCMonth()/3)})),Object(n.a)(z,se,(function(e){return e.getUTCMonth()})),Object(n.a)(z,ce,(function(e){return e.getUTCDate()})),Object(n.a)(z,Ie,(function(e){return e.getUTCHours()})),Object(n.a)(z,Ce,(function(e){return e.getUTCMinutes()})),Object(n.a)(z,he,(function(e){return e.getUTCSeconds()})),Object(n.a)(z,fe,(function(e){return e.getUTCMilliseconds()})),Object(n.a)(z,le,(function(e){return ke(e)})),Object(n.a)(z,ge,(function(e){return xe(e)})),Object(n.a)(z,ue,(function(e,t){return Me(1,e.getUTCDay(),Ne(t))})),Object(n.a)(z,ge+ue,(function(e,t){return Me(xe(e),e.getUTCDay(),Ne(t))})),z),He=($={},Object(n.a)($,ae,(function(e){return 3*e})),Object(n.a)($,ge,(function(e,t){return Me(e,0,Ne(t))})),$);function Ye(e,t){return _e(e,t||1,Ze,He,Ue)}var Je=(ee={},Object(n.a)(ee,oe,R),Object(n.a)(ee,ae,G.every(3)),Object(n.a)(ee,se,G),Object(n.a)(ee,ge,u),Object(n.a)(ee,ce,g),Object(n.a)(ee,ue,g),Object(n.a)(ee,le,g),Object(n.a)(ee,Ie,x),Object(n.a)(ee,Ce,U),Object(n.a)(ee,he,M),Object(n.a)(ee,fe,L),ee),je=(te={},Object(n.a)(te,oe,Z),Object(n.a)(te,ae,Y.every(3)),Object(n.a)(te,se,Y),Object(n.a)(te,ge,Q),Object(n.a)(te,ce,p),Object(n.a)(te,ue,p),Object(n.a)(te,le,p),Object(n.a)(te,Ie,j),Object(n.a)(te,Ce,V),Object(n.a)(te,he,M),Object(n.a)(te,fe,L),te);function Pe(e){return Je[e]}function Ve(e){return je[e]}function Ke(e,t,A){return e?e.offset(t,A):void 0}function We(e,t,A){return Ke(Pe(e),t,A)}function Xe(e,t,A){return Ke(Ve(e),t,A)}function qe(e,t,A,n){return e?e.range(t,A,n):void 0}function ze(e,t,A,n){return qe(Pe(e),t,A,n)}function $e(e,t,A,n){return qe(Ve(e),t,A,n)}var et=[oe,se,ce,Ie,Ce,he,fe],tt=et.slice(0,-1),At=tt.slice(0,-1),nt=At.slice(0,-1),rt=nt.slice(0,-1),it=[oe,se],ot=[oe],at=[[tt,1,1e3],[tt,5,5e3],[tt,15,15e3],[tt,30,3e4],[At,1,6e4],[At,5,3e5],[At,15,9e5],[At,30,18e5],[nt,1,36e5],[nt,3,108e5],[nt,6,216e5],[nt,12,432e5],[rt,1,864e5],[[oe,ge],1,6048e5],[it,1,2592e6],[it,3,7776e6],[ot,1,31536e6]];function st(e){var t,A,n=e.extent,i=e.maxbins||40,o=Math.abs(Object(r.Z)(n))/i,a=K((function(e){return e[2]})).right(at,o);return a===at.length?(t=ot,A=ie(n[0]/31536e6,n[1]/31536e6,i)):a?(t=(a=at[o/at[a-1][2]1&&void 0!==arguments[1]?arguments[1]:void 0,A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(void 0===e)throw new x(e,t,A,"The first argument must not be undefined");if("string"===typeof e&&":"!==e||"string"===typeof t&&":"!==t)throw new x(e,t,A,'Arguments can only be integers, ":" or null');return void 0===t&&(t=e,e=null),{start:":"===e?null:e,stop:":"===t?null:t,step:A,_slice:!0}}function O(e,t){var A,n,r;r=null===e.step?1:e.step,null===e.start?A=r<0?Number.MAX_SAFE_INTEGER:0:(A=e.start)<0&&(A+=t),null===e.stop?n=r<0?-Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER:(n=e.stop)<0&&(n+=t);var i=function(e,t,A,n){if(e<0?(e+=n)<0&&(e=A<0?-1:0):e>=n&&(e=A<0?n-1:n),t<0?(t+=n)<0&&(t=A<0?-1:0):t>=n&&(t=A<0?n-1:n),A<0){if(t2&&void 0!==arguments[2]&&arguments[2];e=H(e,t);for(var n=0;n1)throw new RangeError("an index can only have a single ellipsis ('...')");if(1===n){var i=A,o=e.length-(i+1),a=e.length-1;if(a>=t.length)e=e.filter((function(e){return"..."!==e}));else{var s=t.length-a,g=e.slice(0,i).concat(new Array(s).fill(null));o>0&&(g=g.concat(e.slice(e.length-o))),e=g}}if(e.lengtht.length)throw new G(e,t)}(e,t),e}function Y(e,t){if(e<0&&(e=t+e),e>=t||e<0)throw new k("index out of bounds for dimension with length ".concat(t));return e}function J(e){if(!Array.isArray(e))return!1;var t,A=Object(u.a)(e);try{for(A.s();!(t=A.n()).done;){if("number"!==typeof t.value)return!1}}catch(n){A.e(n)}finally{A.f()}return!0}function j(e){return null!==e&&!0===e._slice}function P(e){return j(e)&&(null===e.step||1===e.step)}function V(e){e=L(e);for(var t=0;t=n.length)){a.next=11;break}return a.abrupt("return");case 11:a.next=16;break;case 13:return a.next=15,r.map((function(e){return e.value}));case 15:i=0;case 16:r[i]=n[i].next();case 17:a.next=6;break;case 19:case"end":return a.stop()}}),B)}var W=function(){function e(t,A){Object(l.a)(this,e),t=Z(t,A.shape),this.dimIndexers=[];for(var n=A.shape,r=0;r0&&(a+=this.step-u),g=Math.ceil((r-this.start)/this.step)):(a=this.start-r,g=0),s=this.stop>i?o:this.stop-r,l=M(a,s,this.step),I=Math.ceil((s-a)/this.step),C=M(g,g+I),e.next=17,{dimChunkIndex:n,dimChunkSelection:l,dimOutSelection:C};case 17:n++,e.next=3;break;case 20:case"end":return e.stop()}}),e,this)}))}]),e}(),z="undefined"!==typeof e&&e.versions&&e.versions.node;function $(e){if(null===e)return"";for(e instanceof String&&(e=e.valueOf()),e=e.replace(/\\/g,"/");e.length>0&&"/"===e[0];)e=e.slice(1);for(;e.length>0&&"/"===e[e.length-1];)e=e.slice(0,e.length-1);var t,A=(e=e.replace(/\/\/+/g,"/")).split("/"),n=Object(u.a)(A);try{for(n.s();!(t=n.n()).done;){var r=t.value;if("."===r||".."===r)throw Error("path containing '.' or '..' segment not allowed")}}catch(i){n.e(i)}finally{n.f()}return e}function ee(e){return"number"===typeof e&&(e=[e]),e.map((function(e){return Math.floor(e)}))}function te(e,t){if(null===e||!0===e)throw new Error("Chunk guessing is not supported yet");return!1===e?t:("number"===typeof e&&(e=[e]),e.length1&&void 0!==i[1]?i[1]:null),n=le(A),r=n+".zarray",e.abrupt("return",t.containsItem(r));case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ce(e){return ue.apply(this,arguments)}function ue(){return(ue=Object(d.a)(c.a.mark((function e(t){var A,n,r,i=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=$(A=i.length>1&&void 0!==i[1]?i[1]:null),n=le(A),r=n+".zgroup",e.abrupt("return",t.containsItem(r));case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function le(e){return e.length>0?e+"/":""}function Ie(e,t,A,n){return Ce.apply(this,arguments)}function Ce(){return(Ce=Object(d.a)(c.a.mark((function e(t,A,n,r){var i,o,a,s,g;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==A.length){e.next=2;break}return e.abrupt("return");case 2:i=A.split("/"),o="",a=Object(u.a)(i.slice(0,i.length-1)),e.prev=5,a.s();case 7:if((s=a.n()).done){e.next=25;break}return g=s.value,o+=g,e.next=12,se(t,o);case 12:if(!e.sent){e.next=17;break}return e.next=15,he(t,o,r);case 15:e.next=22;break;case 17:return e.next=19,ce(t,o);case 19:if(e.sent){e.next=22;break}return e.next=22,he(t,o);case 22:o+="/";case 23:e.next=7;break;case 25:e.next=30;break;case 27:e.prev=27,e.t0=e.catch(5),a.e(e.t0);case 30:return e.prev=30,a.f(),e.finish(30);case 33:case"end":return e.stop()}}),e,null,[[5,27,30,33]])})))).apply(this,arguments)}function he(e){return fe.apply(this,arguments)}function fe(){return(fe=Object(d.a)(c.a.mark((function e(t){var A,n,r,i,o=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(A=o.length>1&&void 0!==o[1]?o[1]:null,n=o.length>2&&void 0!==o[2]&&o[2],A=$(A),!n){e.next=7;break}throw Error("Group overwriting not implemented yet :(");case 7:return e.next=9,se(t,A);case 9:if(!e.sent){e.next=13;break}throw new b(A);case 13:return e.next=15,ce(t,A);case 15:if(!e.sent){e.next=17;break}throw new w(A);case 17:return r={zarr_format:2},i=le(A)+".zgroup",e.next=21,t.setItem(i,JSON.stringify(r));case 21:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function de(e){return Be.apply(this,arguments)}function Be(){return(Be=Object(d.a)(c.a.mark((function e(t){var A,n,r,i=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=i.length>1&&void 0!==i[1]?i[1]:null,n=i.length>2&&void 0!==i[2]?i[2]:null,r=i.length>3&&void 0!==i[3]&&i[3],A=$(A),e.next=6,Ie(t,A,n,r);case 6:return e.next=8,he(t,A,r);case 8:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function pe(e,t,A,n,r,i,o,a,s,g,c,u){return Ee.apply(this,arguments)}function Ee(){return(Ee=Object(d.a)(c.a.mark((function e(t,A,n,r,i,o,a,s,g,u,l,I){var C,h,f;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!g){e.next=4;break}throw Error("Array overwriting not implemented yet :(");case 4:return e.next=6,se(t,i);case 6:if(!e.sent){e.next=10;break}throw new b(i);case 10:return e.next=12,ce(t,i);case 12:if(!e.sent){e.next=14;break}throw new w(i);case 14:if(r=r,A=ee(A),n=te(n,A),s=Ae(s),a=a,!(null!==l&&l.length>0)){e.next=21;break}throw Error("Filters are not supported yet");case 21:return C=a,"number"===typeof a&&(Number.isNaN(a)&&(C="NaN"),Number.POSITIVE_INFINITY===a&&(C="Infinity"),Number.NEGATIVE_INFINITY===a&&(C="-Infinity")),h={zarr_format:2,shape:A,chunks:n,dtype:r,fill_value:C,order:s,compressor:o,filters:l=null},I&&(h.dimension_separator=I),f=le(i)+".zarray",e.next=29,t.setItem(f,JSON.stringify(h));case 29:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Qe(e,t,A,n){return ye.apply(this,arguments)}function ye(){return(ye=Object(d.a)(c.a.mark((function e(t,A,n,r){var i,o,a,s,g,u,l,I,C=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=C.length>4&&void 0!==C[4]?C[4]:null,o=C.length>5&&void 0!==C[5]?C[5]:null,a=C.length>6&&void 0!==C[6]?C[6]:null,s=C.length>7&&void 0!==C[7]?C[7]:"C",g=C.length>8&&void 0!==C[8]&&C[8],u=C.length>9&&void 0!==C[9]?C[9]:null,l=C.length>10&&void 0!==C[10]?C[10]:null,I=C.length>11?C[11]:void 0,i=$(i),e.next=11,Ie(t,i,u,g);case 11:return e.next=13,pe(t,A,n,r,i,o,a,s,g,u,l,I);case 13:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ve(e){if("string"!==typeof e){if(z&&n.isBuffer(e))return JSON.parse(e.toString());if(e instanceof ArrayBuffer){var t=new TextDecoder,A=new Uint8Array(e);return JSON.parse(t.decode(A))}return e}return JSON.parse(e)}var me=function(){function e(t,A,n){var r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];Object(l.a)(this,e),this.store=t,this.key=A,this.readOnly=n,this.cache=r,this.cachedValue=null}return Object(s.a)(e,[{key:"asObject",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.cache||null===this.cachedValue){e.next=2;break}return e.abrupt("return",this.cachedValue);case 2:return e.next=4,this.getNoSync();case 4:return t=e.sent,this.cache&&(this.cachedValue=t),e.abrupt("return",t);case 7:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"getNoSync",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.store.getItem(this.key);case 3:return t=e.sent,e.abrupt("return",ve(t));case 7:return e.prev=7,e.t0=e.catch(0),e.abrupt("return",{});case 10:case"end":return e.stop()}}),e,this,[[0,7]])})));return function(){return e.apply(this,arguments)}}()},{key:"setNoSync",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getNoSync();case 2:return(n=e.sent)[t]=A,e.next=6,this.putNoSync(n);case 6:return e.abrupt("return",!0);case 7:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"putNoSync",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.store.setItem(this.key,JSON.stringify(t));case 2:this.cache&&(this.cachedValue=t);case 3:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"delNoSync",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getNoSync();case 2:return delete(A=e.sent)[t],e.next=6,this.putNoSync(A);case 6:return e.abrupt("return",!0);case 7:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"put",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.readOnly){e.next=2;break}throw new R("attributes are read-only");case 2:return e.abrupt("return",this.putNoSync(t));case 3:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"setItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.readOnly){e.next=2;break}throw new R("attributes are read-only");case 2:return e.abrupt("return",this.setNoSync(t,A));case 3:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"getItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.asObject();case 2:return e.t0=t,e.abrupt("return",e.sent[e.t0]);case 4:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"deleteItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.readOnly){e.next=2;break}throw new R("attributes are read-only");case 2:return e.abrupt("return",this.delNoSync(t));case 3:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"containsItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.asObject();case 2:return e.t0=t,e.t1=e.sent[e.t0],e.t2=void 0,e.abrupt("return",e.t1!==e.t2);case 6:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"proxy",value:function(){return v(this)}}]),e}(),be={"|b":Int8Array,"|B":Uint8Array,"|u1":Uint8Array,"|i1":Int8Array,"b":Int8Array,">B":Uint8Array,">u1":Uint8Array,">i1":Int8Array,">u2":Uint16Array,">i2":Int16Array,">u4":Uint32Array,">i4":Int32Array,">f4":Float32Array,">f8":Float64Array};function we(e){var t=be[e];if(!t)throw Error("Dtype not recognized or not supported in zarr.js, got ".concat(e,"."));return t}function Se(e){if(e instanceof Uint8Array)return"|u1";if(e instanceof Int8Array)return"|i1";if(e instanceof Uint16Array)return"0&&"number"===typeof I[0]){var h=t[0].constructor;I=h.from(I)}return I}(e,t,i),a]}function De(e,t,A,n){var r=T(Z(n,A,!0),A),i=Object(o.a)(r,2),a=i[0];i[1];ke(e,t,A,a)}function Ge(e,t,A,n,r){var i=T(Z(r,A,!1),A),a=Object(o.a)(i,2),s=a[0],g=a[1];if(JSON.stringify(g)!==JSON.stringify(n))throw new U("Shape mismatch in target and source NestedArray: ".concat(g," and ").concat(n));!function e(t,A,n,r){var i=r[0];if("number"===typeof A)return void ke(t,A,n,r.map((function(e){return"number"===typeof e?[e,e+1,1,1]:e})));if("number"===typeof i)return void e(t[i],A,n.slice(1),r.slice(1));var a=Object(o.a)(i,4),s=a[0],g=(a[1],a[2]),c=a[3];if(1===n.length){if(1===g)t.set(A,s);else for(var u=0;u3&&void 0!==arguments[3]?arguments[3]:0;if(1===n.length)return new A(t.slice(r,r+n[0]*A.BYTES_PER_ELEMENT));var i=new Array(n[0]);if(2===n.length){for(var o=0;o0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1?arguments[1]:void 0;null===e&&(e=[M(null)]),"number"===typeof t?0===this.shape.length?this.data[0]=t:De(this.data,t,this.shape,e):Ge(this.data,t.data,this.shape,t.shape,e)}},{key:"flatten",value:function(){return 1===this.shape.length?this.data:xe(this.data,this.shape,we(this.dtype))}}],[{key:"arange",value:function(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"=0;r--)A[r]=n,n*=e[r];return A}(A)),this.shape=A,this.dtype=r,this.strides=i,o&&1!==A.length&&(t=t.buffer),0===this.shape.length)this.data=new(we(r))(1);else if(z&&n.isBuffer(t)||t instanceof ArrayBuffer||null===t||t.toString().startsWith("[object ArrayBuffer]")){var a=A.reduce((function(e,t){return e*t}),1);null===t&&(t=new ArrayBuffer(a*parseInt(r[r.length-1],10)));var s=t.byteLength/parseInt(r[r.length-1],10);if(a!==s)throw new Error("Buffer has ".concat(s," of dtype ").concat(r,", shape is too large or small ").concat(A," (flat=").concat(a,")"));var g=we(r);this.data=new g(t)}else this.data=t}return Object(s.a)(e,[{key:"set",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,A=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;null===t&&(t=[M(null)]),"number"===typeof A?0===this.shape.length?this.data[0]=A:_e(this.data,this.strides,this.shape,t,A):A instanceof e&&n?Oe(this.data,this.strides,this.shape,t,A.data,A.strides,A.shape,n):Me(this.data,this.strides,this.shape,t,A.data,A.strides,A.shape)}}]),e}();var Te=function(e){var t={exports:{}};return e(t,t.exports),t.exports}((function(e){var t=Object.prototype.hasOwnProperty,A="~";function n(){}function r(e,t,A){this.fn=e,this.context=t,this.once=A||!1}function i(e,t,n,i,o){if("function"!==typeof n)throw new TypeError("The listener must be a function");var a=new r(n,i||e,o),s=A?A+t:t;return e._events[s]?e._events[s].fn?e._events[s]=[e._events[s],a]:e._events[s].push(a):(e._events[s]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(A=!1)),a.prototype.eventNames=function(){var e,n,r=[];if(0===this._eventsCount)return r;for(n in e=this._events)t.call(e,n)&&r.push(A?n.slice(1):n);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},a.prototype.listeners=function(e){var t=A?A+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var r=0,i=n.length,o=new Array(i);r0;){var i=r/2|0,o=n+i;A(e[o],t)<=0?(n=++o,r-=i+1):r=i}return n},Ke=Object.defineProperty({default:Ve},"__esModule",{value:!0}),We=function(){function e(){Object(l.a)(this,e),this._queue=[]}return Object(s.a)(e,[{key:"enqueue",value:function(e,t){var A={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)this._queue.push(A);else{var n=Ke.default(this._queue,A,(function(e,t){return t.priority-e.priority}));this._queue.splice(n,0,A)}}},{key:"dequeue",value:function(){var e=this._queue.shift();return e&&e.run}},{key:"size",get:function(){return this._queue.length}}]),e}(),Xe=Object.defineProperty({default:We},"__esModule",{value:!0}),qe=function(){},ze=new Ye.default.TimeoutError,$e=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e){var n;if(Object(l.a)(this,A),(n=t.call(this))._intervalCount=0,n._intervalEnd=0,n._pendingCount=0,n._resolveEmpty=qe,n._resolveIdle=qe,!("number"===typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Xe.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError("Expected `intervalCap` to be a number from 1 and up, got `".concat(e.intervalCap,"` (").concat(typeof e.intervalCap,")"));if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError("Expected `interval` to be a finite number >= 0, got `".concat(e.interval,"` (").concat(typeof e.interval,")"));return n._carryoverConcurrencyCount=e.carryoverConcurrencyCount,n._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,n._intervalCap=e.intervalCap,n._interval=e.interval,n._queue=new e.queueClass,n._queueClass=e.queueClass,n.concurrency=e.concurrency,n._timeout=e.timeout,n._throwOnTimeout=!0===e.throwOnTimeout,n._isPaused=!1===e.autoStart,n}return Object(s.a)(A,[{key:"_next",value:function(){this._pendingCount--,this._tryToStartAnother()}},{key:"_resolvePromises",value:function(){this._resolveEmpty(),this._resolveEmpty=qe,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=qe)}},{key:"_onResumeInterval",value:function(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}},{key:"_isIntervalPaused",value:function(){var e=this,t=Date.now();if(void 0===this._intervalId){var A=this._intervalEnd-t;if(!(A<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout((function(){e._onResumeInterval()}),A)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}},{key:"_tryToStartAnother",value:function(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){var e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother)return this.emit("active"),this._queue.dequeue()(),e&&this._initializeIntervalIfNeeded(),!0}return!1}},{key:"_initializeIntervalIfNeeded",value:function(){var e=this;this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((function(){e._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}},{key:"_onInterval",value:function(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}},{key:"_processQueue",value:function(){for(;this._tryToStartAnother(););}},{key:"add",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A,n=this,r=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=r.length>1&&void 0!==r[1]?r[1]:{},e.abrupt("return",new Promise((function(e,r){var i=function(){var i=Object(d.a)(c.a.mark((function i(){var o;return c.a.wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return n._pendingCount++,n._intervalCount++,i.prev=2,o=void 0===n._timeout&&void 0===A.timeout?t():Ye.default(Promise.resolve(t()),void 0===A.timeout?n._timeout:A.timeout,(function(){(void 0===A.throwOnTimeout?n._throwOnTimeout:A.throwOnTimeout)&&r(ze)})),i.t0=e,i.next=7,o;case 7:i.t1=i.sent,(0,i.t0)(i.t1),i.next=14;break;case 11:i.prev=11,i.t2=i.catch(2),r(i.t2);case 14:n._next();case 15:case"end":return i.stop()}}),i,null,[[2,11]])})));return function(){return i.apply(this,arguments)}}();n._queue.enqueue(i,A),n._tryToStartAnother()})));case 2:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()},{key:"addAll",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",Promise.all(t.map(function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",n.add(t,A));case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}())));case 1:case"end":return e.stop()}}),e)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"start",value:function(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}},{key:"pause",value:function(){this._isPaused=!0}},{key:"clear",value:function(){this._queue=new this._queueClass}},{key:"onEmpty",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==this._queue.size){e.next=2;break}return e.abrupt("return");case 2:return e.abrupt("return",new Promise((function(e){var A=t._resolveEmpty;t._resolveEmpty=function(){A(),e()}})));case 3:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"onIdle",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==this._pendingCount||0!==this._queue.size){e.next=2;break}return e.abrupt("return");case 2:return e.abrupt("return",new Promise((function(e){var A=t._resolveIdle;t._resolveIdle=function(){A(),e()}})));case 3:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"_doesIntervalAllowAnother",get:function(){return this._isIntervalIgnored||this._intervalCount=1))throw new TypeError("Expected `concurrency` to be a number from 1 and up, got `".concat(e,"` (").concat(typeof e,")"));this._concurrency=e,this._processQueue()}},{key:"size",get:function(){return this._queue.size}},{key:"pending",get:function(){return this._pendingCount}},{key:"isPaused",get:function(){return this._isPaused}},{key:"timeout",set:function(e){this._timeout=e},get:function(){return this._timeout}}]),A}(Te),et=function(){function e(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],a=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];Object(l.a)(this,e),this.store=t,this._chunkStore=i,this.path=$(A),this.keyPrefix=le(this.path),this.readOnly=r,this.cacheMetadata=o,this.cacheAttrs=a,this.meta=n,null!==this.meta.compressor?this.compressor=Q(this.meta.compressor):this.compressor=null;var s=this.keyPrefix+".zattrs";this.attrs=new me(this.store,s,this.readOnly,a)}return Object(s.a)(e,[{key:"reloadMetadata",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t,A;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.keyPrefix+".zarray",A=this.store.getItem(t),e.t0=ve,e.next=5,A;case 5:return e.t1=e.sent,this.meta=(0,e.t0)(e.t1),e.abrupt("return",this.meta);case 8:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"refreshMetadata",value:function(){var e=Object(d.a)(c.a.mark((function e(){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.cacheMetadata){e.next=3;break}return e.next=3,this.reloadMetadata();case 3:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"get",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.getBasicSelection(e,!1,t)}},{key:"getRaw",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.getBasicSelection(e,!0,t)}},{key:"getBasicSelection",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A,n,r,i,o,a=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(A=a.length>1&&void 0!==a[1]&&a[1],n=a.length>2&&void 0!==a[2]?a[2]:{},r=n.concurrencyLimit,i=void 0===r?10:r,o=n.progressCallback,this.cacheMetadata){e.next=5;break}return e.next=5,this.reloadMetadata();case 5:if(this.shape!==[]){e.next=9;break}throw new Error("Shape [] indexing is not supported yet");case 9:return e.abrupt("return",this.getBasicSelectionND(t,A,i,o));case 10:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"getBasicSelectionND",value:function(e,t,A,n){var r=new W(e,this);return this.getSelection(r,t,A,n)}},{key:"getSelection",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n,r){var i,o,a,s,g,l,I,C,h,f,B,p,E=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=this.dtype,o=t.shape,a=t.shape.reduce((function(e,t){return e*t}),1),!A||a!==this.chunkSize){e.next=12;break}if(s=t.iter(),!1!==(g=s.next()).done||!0!==s.next().done){e.next=12;break}return l=g.value,e.next=10,this.decodeDirectToRawArray(l,o,a);case 10:return I=e.sent,e.abrupt("return",I);case 12:if(C=A?new Le(null,o,i):new Ne(null,o,i),0!==a){e.next=15;break}return e.abrupt("return",C);case 15:if(h=new $e({concurrency:n}),r)!function(){var e,A=0,n=0,i=Object(u.a)(t.iter());try{for(i.s();!(e=i.n()).done;){e.value;n+=1}}catch(g){i.e(g)}finally{i.f()}r({progress:0,queueSize:n});var o,a=Object(u.a)(t.iter());try{var s=function(){var e=o.value;Object(d.a)(c.a.mark((function i(){return c.a.wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,h.add((function(){return E.chunkGetItem(e.chunkCoords,e.chunkSelection,C,e.outSelection,t.dropAxes)}));case 2:r({progress:A+=1,queueSize:n});case 4:case"end":return i.stop()}}),i)})))()};for(a.s();!(o=a.n()).done;)s()}catch(g){a.e(g)}finally{a.f()}}();else{f=Object(u.a)(t.iter());try{for(p=function(){var e=B.value;h.add((function(){return E.chunkGetItem(e.chunkCoords,e.chunkSelection,C,e.outSelection,t.dropAxes)}))},f.s();!(B=f.n()).done;)p()}catch(Q){f.e(Q)}finally{f.f()}}return e.next=19,h.onIdle();case 19:if(0!==C.shape.length){e.next=21;break}return e.abrupt("return",C.data[0]);case 21:return e.abrupt("return",C);case 22:case"end":return e.stop()}}),e,this)})));return function(t,A,n,r){return e.apply(this,arguments)}}()},{key:"chunkGetItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n,r,i){var o,a,s,g,u;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length===this._chunkDataShape.length){e.next=2;break}throw new U("Inconsistent shapes: chunkCoordsLength: ".concat(t.length,", cDataShapeLength: ").concat(this.chunkDataShape.length));case 2:return o=this.chunkKey(t),e.prev=3,e.next=6,this.chunkStore.getItem(o);case 6:return a=e.sent,e.next=9,this.decodeChunk(a);case 9:if(s=e.sent,!(n instanceof Ne)){e.next=21;break}if(!V(r)||!ne(A,this.chunks)||this.meta.filters){e.next=14;break}return n.set(r,this.toNestedArray(s)),e.abrupt("return");case 14:if(g=this.toNestedArray(s),u=g.get(A),null===i){e.next=18;break}throw new Error("Drop axes is not supported yet");case 18:n.set(r,u),e.next=22;break;case 21:n.set(r,this.chunkBufferToRawArray(s),A);case 22:e.next=31;break;case 24:if(e.prev=24,e.t0=e.catch(3),!m(e.t0)){e.next=30;break}null!==this.fillValue&&n.set(r,this.fillValue),e.next=31;break;case 30:throw e.t0;case 31:case"end":return e.stop()}}),e,this,[[3,24]])})));return function(t,A,n,r,i){return e.apply(this,arguments)}}()},{key:"getRawChunk",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n,r,i,o,a,s;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length===this.shape.length){e.next=2;break}throw new Error("Chunk coordinates ".concat(t.join(".")," do not correspond to shape ").concat(this.shape,"."));case 2:for(e.prev=2,n=0;n")&&oe(this.toTypedArray(A.buffer)),e.abrupt("return",A.buffer);case 9:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"chunkBufferToRawArray",value:function(e){return new Le(e,this.chunks,this.dtype)}},{key:"decodeDirectToRawArray",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n){var r,i,o,a;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.chunkCoords,i=this.chunkKey(r),e.prev=2,e.next=5,this.chunkStore.getItem(i);case 5:return o=e.sent,e.t0=Le,e.next=9,this.decodeChunk(o);case 9:return e.t1=e.sent,e.t2=A,e.t3=this.dtype,e.abrupt("return",new e.t0(e.t1,e.t2,e.t3));case 15:if(e.prev=15,e.t4=e.catch(2),!m(e.t4)){e.next=22;break}return a=new(we(this.dtype))(n),e.abrupt("return",new Le(a.fill(this.fillValue),A));case 22:throw e.t4;case 23:case"end":return e.stop()}}),e,this,[[2,15]])})));return function(t,A,n){return e.apply(this,arguments)}}()},{key:"set",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t,A,n,r=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=r.length>0&&void 0!==r[0]?r[0]:null,A=r.length>1?r[1]:void 0,n=r.length>2&&void 0!==r[2]?r[2]:{},e.next=5,this.setBasicSelection(t,A,n);case 5:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"setBasicSelection",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n,r,i,o,a=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=a.length>2&&void 0!==a[2]?a[2]:{},r=n.concurrencyLimit,i=void 0===r?10:r,o=n.progressCallback,!this.readOnly){e.next=3;break}throw new R("Object is read only");case 3:if(this.cacheMetadata){e.next=6;break}return e.next=6,this.reloadMetadata();case 6:if(this.shape!==[]){e.next=10;break}throw new Error("Shape [] indexing is not supported yet");case 10:return e.next=12,this.setBasicSelectionND(t,A,i,o);case 12:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"setBasicSelectionND",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n,r){var i;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=new W(t,this),e.next=3,this.setSelection(i,A,n,r);case 3:case"end":return e.stop()}}),e,this)})));return function(t,A,n,r){return e.apply(this,arguments)}}()},{key:"getChunkValue",value:function(e,t,A,n){var r;if(n===[])r=A;else if("number"===typeof A)r=A;else if(r=A.get(e.outSelection),null!==t.dropAxes)throw new Error("Handling drop axes not supported yet");return r}},{key:"setSelection",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n,r){var i,o,a,s,g,l=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((i=t.shape)!==[]){e.next=5;break}e.next=15;break;case 5:if("number"!==typeof A){e.next=9;break}e.next=15;break;case 9:if(!(A instanceof Ne)){e.next=14;break}if(re(A.shape,i)){e.next=12;break}throw new U("Shape mismatch in source NestedArray and set selection: ".concat(A.shape," and ").concat(i));case 12:e.next=15;break;case 14:throw new Error("Unknown data type for setting :(");case 15:if(o=new $e({concurrency:n}),r)!function(){var e,n=0,a=Object(u.a)(t.iter());try{for(a.s();!(e=a.n()).done;){e.value;n+=1}}catch(h){a.e(h)}finally{a.f()}var s=0;r({progress:0,queueSize:n});var g,I=Object(u.a)(t.iter());try{var C=function(){var e=g.value,a=l.getChunkValue(e,t,A,i);Object(d.a)(c.a.mark((function t(){return c.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,o.add((function(){return l.chunkSetItem(e.chunkCoords,e.chunkSelection,a)}));case 2:r({progress:s+=1,queueSize:n});case 4:case"end":return t.stop()}}),t)})))()};for(I.s();!(g=I.n()).done;)C()}catch(h){I.e(h)}finally{I.f()}}();else{a=Object(u.a)(t.iter());try{for(g=function(){var e=s.value,n=l.getChunkValue(e,t,A,i);o.add((function(){return l.chunkSetItem(e.chunkCoords,e.chunkSelection,n)}))},a.s();!(s=a.n()).done;)g()}catch(I){a.e(I)}finally{a.f()}}return e.next=19,o.onIdle();case 19:case"end":return e.stop()}}),e)})));return function(t,A,n,r){return e.apply(this,arguments)}}()},{key:"chunkSetItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n){var r,i,o,a,s,g,u,l,I;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=this.chunkKey(t),i=null,o=we(this.dtype),a=this.chunkSize,!ne(A,this.chunks)){e.next=8;break}"number"===typeof n?(i=new o(a)).fill(n):i=n.flatten(),e.next=29;break;case 8:return e.prev=8,e.next=11,this.chunkStore.getItem(r);case 11:return g=e.sent,e.next=14,this.decodeChunk(g);case 14:u=e.sent,s=this.toTypedArray(u),e.next=26;break;case 18:if(e.prev=18,e.t0=e.catch(8),!m(e.t0)){e.next=25;break}s=new o(a),null!==this.fillValue&&s.fill(this.fillValue),e.next=26;break;case 25:throw e.t0;case 26:(l=new Ne(s,this.chunks,this.dtype)).set(A,n),i=l.flatten();case 29:return e.next=31,this.encodeChunk(i);case 31:I=e.sent,this.chunkStore.setItem(r,I);case 33:case"end":return e.stop()}}),e,this,[[8,18]])})));return function(t,A,n){return e.apply(this,arguments)}}()},{key:"encodeChunk",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A,n;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.dtype.includes(">")&&(t=ae(t)),null===this.compressor){e.next=9;break}return A=new Uint8Array(t.buffer),e.next=5,this.compressor;case 5:return e.next=7,e.sent.encode(A);case 7:return n=e.sent,e.abrupt("return",n.buffer);case 9:return e.abrupt("return",t.buffer);case 10:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"chunkStore",get:function(){return this._chunkStore?this._chunkStore:this.store}},{key:"name",get:function(){return this.path.length>0?"/"!==this.path[0]?"/"+this.path:this.path:null}},{key:"basename",get:function(){var e=this.name;if(null===e)return null;var t=e.split("/");return t[t.length-1]}},{key:"shape",get:function(){return this.meta.shape}},{key:"chunks",get:function(){return this.meta.chunks}},{key:"chunkSize",get:function(){return this.chunks.reduce((function(e,t){return e*t}),1)}},{key:"dtype",get:function(){return this.meta.dtype}},{key:"fillValue",get:function(){var e=this.meta.fill_value;return"NaN"===e?NaN:"Infinity"===e?1/0:"-Infinity"===e?-1/0:this.meta.fill_value}},{key:"nDims",get:function(){return this.meta.shape.length}},{key:"size",get:function(){return this.meta.shape.reduce((function(e,t){return e*t}),1)}},{key:"length",get:function(){return this.shape[0]}},{key:"_chunkDataShape",get:function(){if(this.shape===[])return[1];for(var e=[],t=0;t1&&void 0!==g[1]?g[1]:null,r=g.length>2&&void 0!==g[2]&&g[2],i=g.length>3&&void 0!==g[3]?g[3]:null,o=!(g.length>4&&void 0!==g[4])||g[4],a=!(g.length>5&&void 0!==g[5])||g[5],t.next=7,this.loadMetadataForConstructor(A,n);case 7:return s=t.sent,t.abrupt("return",new e(A,n,s,r,i,o,a));case 9:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}()},{key:"loadMetadataForConstructor",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n,r;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,A=$(A),n=le(A),e.next=5,t.getItem(n+".zarray");case 5:return r=e.sent,e.abrupt("return",ve(r));case 9:return e.prev=9,e.t0=e.catch(0),e.next=13,ce(t,A);case 13:if(!e.sent){e.next=15;break}throw new w(null!==A&&void 0!==A?A:"");case 15:throw new Error("Failed to load metadata for ZarrArray:"+e.t0.toString());case 16:case"end":return e.stop()}}),e,null,[[0,9]])})));return function(t,A){return e.apply(this,arguments)}}()}]),e}(),tt=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(l.a)(this,e),this.root=t}return Object(s.a)(e,[{key:"proxy",value:function(){return v(this)}},{key:"getParent",value:function(e){var t,A=this.root,n=e.split("/"),r=Object(u.a)(n.slice(0,n.length-1));try{for(r.s();!(t=r.n()).done;){if(!(A=A[t.value]))throw Error(e)}}catch(i){r.e(i)}finally{r.f()}return[A,n[n.length-1]]}},{key:"requireParent",value:function(e){var t,A=this.root,n=e.split("/"),r=Object(u.a)(n.slice(0,n.length-1));try{for(r.s();!(t=r.n()).done;){var i=t.value;void 0===A[i]&&(A[i]={}),A=A[i]}}catch(o){r.e(o)}finally{r.f()}return[A,n[n.length-1]]}},{key:"getItem",value:function(e){var t=this.getParent(e),A=Object(o.a)(t,2),n=A[0][A[1]];if(void 0===n)throw new D(e);return n}},{key:"setItem",value:function(e,t){var A=this.requireParent(e),n=Object(o.a)(A,2);return n[0][n[1]]=t,!0}},{key:"deleteItem",value:function(e){var t=this.getParent(e),A=Object(o.a)(t,2);return delete A[0][A[1]]}},{key:"containsItem",value:function(e){try{return void 0!==this.getItem(e)}catch(t){return!1}}},{key:"keys",value:function(){throw new Error("Method not implemented.")}}]),e}();!function(e){e.HEAD="HEAD",e.GET="GET",e.PUT="PUT"}(Pe||(Pe={}));var At=[Pe.HEAD,Pe.GET,Pe.PUT],nt=function(){function e(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object(l.a)(this,e),this.url=t;var n=A.fetchOptions,r=void 0===n?{}:n,i=A.supportedMethods,o=void 0===i?At:i;this.fetchOptions=r,this.supportedMethods=new Set(o)}return Object(s.a)(e,[{key:"keys",value:function(){throw new Error("Method not implemented.")}},{key:"getItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var i,o;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=ie(this.url,t),e.next=3,fetch(i,Object(r.a)({},this.fetchOptions,{},A));case 3:if(404!==(o=e.sent).status){e.next=8;break}throw new D(t);case 8:if(200===o.status){e.next=10;break}throw new _(String(o.status));case 10:if(!z){e.next=18;break}return e.t0=n,e.next=14,o.arrayBuffer();case 14:return e.t1=e.sent,e.abrupt("return",e.t0.from.call(e.t0,e.t1));case 18:return e.abrupt("return",o.arrayBuffer());case 19:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"setItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n,i;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.supportedMethods.has(Pe.PUT)){e.next=2;break}throw new Error("HTTP PUT no a supported method for store.");case 2:return n=ie(this.url,t),"string"===typeof A&&(A=(new TextEncoder).encode(A).buffer),e.next=6,fetch(n,Object(r.a)({},this.fetchOptions,{method:Pe.PUT,body:A}));case 6:return i=e.sent,e.abrupt("return","2"===i.status.toString()[0]);case 8:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"deleteItem",value:function(e){throw new Error("Method not implemented.")}},{key:"containsItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A,n,i;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=ie(this.url,t),n=this.supportedMethods.has(Pe.HEAD)?Pe.HEAD:Pe.GET,e.next=4,fetch(A,Object(r.a)({},this.fetchOptions,{method:n}));case 4:return i=e.sent,e.abrupt("return",200===i.status);case 6:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()}]),e}();function rt(e){return it.apply(this,arguments)}function it(){return(it=Object(d.a)(c.a.mark((function e(t){var A,n,r,i,o,a,s,g,u,l,I,C,h,f,d,B,p,E,Q,y,v,m,b,w,S;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=t.shape,n=t.chunks,r=void 0===n||n,i=t.dtype,o=void 0===i?"1&&void 0!==n[1]?n[1]:{}).fillValue=null,e.abrupt("return",rt(Object(r.a)({shape:t},A)));case 3:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function st(e){return gt.apply(this,arguments)}function gt(){return(gt=Object(d.a)(c.a.mark((function e(t){var A,n=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(A=n.length>1&&void 0!==n[1]?n[1]:{}).fillValue=0,e.abrupt("return",rt(Object(r.a)({shape:t},A)));case 3:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ct(e){return ut.apply(this,arguments)}function ut(){return(ut=Object(d.a)(c.a.mark((function e(t){var A,n=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(A=n.length>1&&void 0!==n[1]?n[1]:{}).fillValue=1,e.abrupt("return",rt(Object(r.a)({shape:t},A)));case 3:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function lt(e,t){return It.apply(this,arguments)}function It(){return(It=Object(d.a)(c.a.mark((function e(t,A){var n,i=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(n=i.length>2&&void 0!==i[2]?i[2]:{}).fillValue=A,e.abrupt("return",rt(Object(r.a)({shape:t},n)));case 3:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Ct(e){return ht.apply(this,arguments)}function ht(){return(ht=Object(d.a)(c.a.mark((function e(t){var A,n,i,o,a=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=a.length>1&&void 0!==a[1]?a[1]:{},n=null,t instanceof Ne?(n=t.shape,A.dtype=void 0===A.dtype?t.dtype:A.dtype):n=t.byteLength,i=void 0!==A.readOnly&&A.readOnly,A.readOnly=!1,e.next=7,rt(Object(r.a)({shape:n},A));case 7:return o=e.sent,e.next=10,o.set(null,t);case 10:return o.readOnly=i,e.abrupt("return",o);case 12:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ft(){return dt.apply(this,arguments)}function dt(){return(dt=Object(d.a)(c.a.mark((function e(){var t,A,n,r,i,o,a,s,g,u,l,I,C,h,f,d,B,p,E,Q,y,v,m,F,R,D,G,k=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=k.length>0&&void 0!==k[0]?k[0]:{},A=t.shape,n=t.mode,r=void 0===n?"a":n,i=t.chunks,o=void 0===i||i,a=t.dtype,s=void 0===a?"1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=!(arguments.length>5&&void 0!==arguments[5])||arguments[5];Object(l.a)(this,e),this.store=t,this._chunkStore=i,this.path=$(A),this.keyPrefix=le(this.path),this.readOnly=r,this.meta=n;var a=this.keyPrefix+".zattrs";this.attrs=new me(this.store,a,this.readOnly,o)}return Object(s.a)(e,[{key:"itemPath",value:function(e){var t="string"===typeof e&&e.length>0&&"/"===e[0],A=$(e);return!t&&this.path.length>0?this.keyPrefix+A:A}},{key:"createGroup",value:function(){var t=Object(d.a)(c.a.mark((function t(A){var n,r,i=arguments;return c.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=i.length>1&&void 0!==i[1]&&i[1],!this.readOnly){t.next=3;break}throw new R("group is read only");case 3:return r=this.itemPath(A),t.next=6,de(this.store,r,this._chunkStore,n);case 6:return t.abrupt("return",e.create(this.store,r,this.readOnly,this._chunkStore,this.attrs.cache));case 7:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}()},{key:"requireGroup",value:function(){var t=Object(d.a)(c.a.mark((function t(A){var n,r,i=arguments;return c.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=i.length>1&&void 0!==i[1]&&i[1],!this.readOnly){t.next=3;break}throw new R("group is read only");case 3:return r=this.itemPath(A),t.next=6,ce(this.store,r);case 6:if(t.sent){t.next=9;break}return t.next=9,de(this.store,r,this._chunkStore,n);case 9:return t.abrupt("return",e.create(this.store,r,this.readOnly,this._chunkStore,this.attrs.cache));case 10:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}()},{key:"getOptsForArrayCreation",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=this.itemPath(e);return t.path=A,void 0===t.cacheAttrs&&(t.cacheAttrs=this.attrs.cache),t.store=this.store,t.chunkStore=this.chunkStore,t}},{key:"array",value:function(e,t,A,n){if(this.readOnly)throw new R("group is read only");return(A=this.getOptsForArrayCreation(e,A)).overwrite=void 0===n?A.overwrite:n,Ct(t,A)}},{key:"empty",value:function(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(this.readOnly)throw new R("group is read only");return ot(t,A=this.getOptsForArrayCreation(e,A))}},{key:"zeros",value:function(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(this.readOnly)throw new R("group is read only");return st(t,A=this.getOptsForArrayCreation(e,A))}},{key:"ones",value:function(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(this.readOnly)throw new R("group is read only");return ct(t,A=this.getOptsForArrayCreation(e,A))}},{key:"full",value:function(e,t,A){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(this.readOnly)throw new R("group is read only");return lt(t,A,n=this.getOptsForArrayCreation(e,n))}},{key:"createDataset",value:function(e,t,A,n){if(this.readOnly)throw new R("group is read only");var i;if(n=this.getOptsForArrayCreation(e,n),void 0===A){if(void 0===t)throw new U("Shape must be set if no data is passed to CreateDataset");i=rt(Object(r.a)({shape:t},n))}else i=Ct(A,n);return i}},{key:"getItem",value:function(){var t=Object(d.a)(c.a.mark((function t(A){var n;return c.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=this.itemPath(A),t.next=3,se(this.store,n);case 3:if(!t.sent){t.next=7;break}return t.abrupt("return",et.create(this.store,n,this.readOnly,this.chunkStore,void 0,this.attrs.cache));case 7:return t.next=9,ce(this.store,n);case 9:if(!t.sent){t.next=11;break}return t.abrupt("return",e.create(this.store,n,this.readOnly,this._chunkStore,this.attrs.cache));case 11:throw new D(A);case 12:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}()},{key:"setItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.array(t,A,{},!0);case 2:return e.abrupt("return",!0);case 3:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"deleteItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.readOnly){e.next=2;break}throw new R("group is read only");case 2:throw new Error("Method not implemented.");case 3:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"containsItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=this.itemPath(t),e.next=3,se(this.store,A);case 3:if(e.t0=e.sent,e.t0){e.next=6;break}e.t0=ce(this.store,A);case 6:return e.abrupt("return",e.t0);case 7:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"proxy",value:function(){return v(this)}},{key:"name",get:function(){return this.path.length>0?"/"!==this.path[0]?"/"+this.path:this.path:"/"}},{key:"basename",get:function(){var e=this.name.split("/");return e[e.length-1]}},{key:"chunkStore",get:function(){return this._chunkStore?this._chunkStore:this.store}}],[{key:"create",value:function(){var t=Object(d.a)(c.a.mark((function t(A){var n,r,i,o,a,s=arguments;return c.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=s.length>1&&void 0!==s[1]?s[1]:null,r=s.length>2&&void 0!==s[2]&&s[2],i=s.length>3&&void 0!==s[3]?s[3]:null,o=!(s.length>4&&void 0!==s[4])||s[4],t.next=6,this.loadMetadataForConstructor(A,n);case 6:return a=t.sent,t.abrupt("return",new e(A,n,a,r,i,o));case 8:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}()},{key:"loadMetadataForConstructor",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n,r;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=$(A),n=le(A),e.prev=2,e.next=5,t.getItem(n+".zgroup");case 5:return r=e.sent,e.abrupt("return",ve(r));case 9:return e.prev=9,e.t0=e.catch(2),e.next=13,se(t,A);case 13:if(!e.sent){e.next=15;break}throw new b(A);case 15:throw new F(A);case 16:case"end":return e.stop()}}),e,null,[[2,9]])})));return function(t,A){return e.apply(this,arguments)}}()}]),e}();function Et(e){return Qt.apply(this,arguments)}function Qt(){return(Qt=Object(d.a)(c.a.mark((function e(t){var A,n,r,i,o,a=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(A=a.length>1&&void 0!==a[1]?a[1]:null,n=a.length>2&&void 0!==a[2]?a[2]:"a",r=a.length>3?a[3]:void 0,i=!(a.length>4&&void 0!==a[4])||a[4],t=Bt(t),void 0!==r&&(r=Bt(t)),A=$(A),"r"!==n&&"r+"!==n){e.next=18;break}return e.next=10,ce(t,A);case 10:if(e.sent){e.next=16;break}return e.next=13,se(t,A);case 13:if(!e.sent){e.next=15;break}throw new b(A);case 15:throw new F(A);case 16:e.next=53;break;case 18:if("w"!==n){e.next=23;break}return e.next=21,de(t,A,r,!0);case 21:e.next=53;break;case 23:if("a"!==n){e.next=35;break}return e.next=26,ce(t,A);case 26:if(e.sent){e.next=33;break}return e.next=29,se(t,A);case 29:if(!e.sent){e.next=31;break}throw new b(A);case 31:return e.next=33,de(t,A,r);case 33:e.next=53;break;case 35:if("w-"!==n&&"x"!==n){e.next=52;break}return e.next=38,se(t,A);case 38:if(!e.sent){e.next=42;break}throw new b(A);case 42:return e.next=44,ce(t,A);case 44:if(!e.sent){e.next=48;break}throw new w(A);case 48:return e.next=50,de(t,A,r);case 50:e.next=53;break;case 52:throw new U("Invalid mode argument: ".concat(n));case 53:return o="r"===n,e.abrupt("return",pt.create(t,A,o,r,i));case 55:case"end":return e.stop()}}),e)})))).apply(this,arguments)}}).call(this,A(90),A(188).Buffer)},function(e,t,A){"use strict";(function(e,n){A.d(t,"a",(function(){return qe})),A.d(t,"b",(function(){return E})),A.d(t,"c",(function(){return ze})),A.d(t,"d",(function(){return _}));var r=A(7),i=A(73),o=A(8),a=A(11),s=A(4),g=A(3),c=A.n(g),u=A(6),l=A(1),I=A(24),C=A(9),h=A(10),f=A(54),d=A(12),B=c.a.mark(V),p=new Map;function E(e,t){p.set(e,t)}function Q(e){return y.apply(this,arguments)}function y(){return(y=Object(d.a)(c.a.mark((function e(t){var A;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(p.has(t.id)){e.next=2;break}throw new Error("Compression codec ".concat(t.id," is not supported by Zarr.js yet."));case 2:return e.next=4,p.get(t.id)();case 4:return A=e.sent,e.abrupt("return",A.fromConfig(t));case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function v(e){return new Proxy(e,{set:function(e,t,A,n){return e.setItem(t,A)},get:function(e,t,A){return e.getItem(t)},deleteProperty:function(e,t){return e.deleteItem(t)},has:function(e,t){return e.containsItem(t)}})}function m(e){return"object"===typeof(t=e)&&null!==t&&"__zarr__"in t&&"KeyError"===e.__zarr__;var t}var b=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e){var n;return Object(l.a)(this,A),(n=t.call(this,"path ".concat(e," contains an array"))).__zarr__="ContainsArrayError",Object.setPrototypeOf(Object(I.a)(n),A.prototype),n}return A}(Object(f.a)(Error)),w=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e){var n;return Object(l.a)(this,A),(n=t.call(this,"path ".concat(e," contains a group"))).__zarr__="ContainsGroupError",Object.setPrototypeOf(Object(I.a)(n),A.prototype),n}return A}(Object(f.a)(Error)),S=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e){var n;return Object(l.a)(this,A),(n=t.call(this,"array not found at path ".concat(e))).__zarr__="ArrayNotFoundError",Object.setPrototypeOf(Object(I.a)(n),A.prototype),n}return A}(Object(f.a)(Error)),F=(Error,Error,function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e){var n;return Object(l.a)(this,A),(n=t.call(this,e)).__zarr__="PermissionError",Object.setPrototypeOf(Object(I.a)(n),A.prototype),n}return A}(Object(f.a)(Error))),R=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e){var n;return Object(l.a)(this,A),(n=t.call(this,"key ".concat(e," not present"))).__zarr__="KeyError",Object.setPrototypeOf(Object(I.a)(n),A.prototype),n}return A}(Object(f.a)(Error)),D=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e,n){var r;return Object(l.a)(this,A),(r=t.call(this,"too many indices for array; expected ".concat(n.length,", got ").concat(e.length))).__zarr__="TooManyIndicesError",Object.setPrototypeOf(Object(I.a)(r),A.prototype),r}return A}(Object(f.a)(RangeError)),G=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e){var n;return Object(l.a)(this,A),(n=t.call(this,e)).__zarr__="BoundsCheckError",Object.setPrototypeOf(Object(I.a)(n),A.prototype),n}return A}(Object(f.a)(RangeError)),k=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e,n,r,i){var o;return Object(l.a)(this,A),(o=t.call(this,"slice arguments slice(".concat(e,", ").concat(n,", ").concat(r,") invalid: ").concat(i))).__zarr__="InvalidSliceError",Object.setPrototypeOf(Object(I.a)(o),A.prototype),o}return A}(Object(f.a)(RangeError)),x=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(){var e;return Object(l.a)(this,A),(e=t.call(this,"Negative step size is not supported when indexing.")).__zarr__="NegativeStepError",Object.setPrototypeOf(Object(I.a)(e),A.prototype),e}return A}(Object(f.a)(Error)),N=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e){var n;return Object(l.a)(this,A),(n=t.call(this,e)).__zarr__="ValueError",Object.setPrototypeOf(Object(I.a)(n),A.prototype),n}return A}(Object(f.a)(Error)),U=function(e){Object(C.a)(A,e);var t=Object(h.a)(A);function A(e){var n;return Object(l.a)(this,A),(n=t.call(this,e)).__zarr__="HTTPError",Object.setPrototypeOf(Object(I.a)(n),A.prototype),n}return A}(Object(f.a)(Error));function _(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(void 0===e)throw new k(e,t,A,"The first argument must not be undefined");if("string"===typeof e&&":"!==e||"string"===typeof t&&":"!==t)throw new k(e,t,A,'Arguments can only be integers, ":" or null');return void 0===t&&(t=e,e=null),{start:":"===e?null:e,stop:":"===t?null:t,step:A,_slice:!0}}function M(e,t){var A,n,r;r=null===e.step?1:e.step,null===e.start?A=r<0?Number.MAX_SAFE_INTEGER:0:(A=e.start)<0&&(A+=t),null===e.stop?n=r<0?-Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER:(n=e.stop)<0&&(n+=t);var i=function(e,t,A,n){if(e<0?(e+=n)<0&&(e=A<0?-1:0):e>=n&&(e=A<0?n-1:n),t<0?(t+=n)<0&&(t=A<0?-1:0):t>=n&&(t=A<0?n-1:n),A<0){if(t2&&void 0!==arguments[2]&&arguments[2];e=Z(e,t);for(var n=0;n1)throw new RangeError("an index can only have a single ellipsis ('...')");if(1===n){var i=A,o=e.length-(i+1),a=e.length-1;if(a>=t.length)e=e.filter((function(e){return"..."!==e}));else{var s=t.length-a,g=e.slice(0,i).concat(new Array(s).fill(null));o>0&&(g=g.concat(e.slice(e.length-o))),e=g}}if(e.lengtht.length)throw new D(e,t)}(e,t),e}function H(e,t){if(e<0&&(e=t+e),e>=t||e<0)throw new G("index out of bounds for dimension with length ".concat(t));return e}function Y(e){if(!Array.isArray(e))return!1;var t,A=Object(u.a)(e);try{for(A.s();!(t=A.n()).done;){if("number"!==typeof t.value)return!1}}catch(n){A.e(n)}finally{A.f()}return!0}function J(e){return null!==e&&!0===e._slice}function j(e){return J(e)&&(null===e.step||1===e.step)}function P(e){e=O(e);for(var t=0;t=n.length)){a.next=11;break}return a.abrupt("return");case 11:a.next=16;break;case 13:return a.next=15,r.map((function(e){return e.value}));case 15:i=0;case 16:r[i]=n[i].next();case 17:a.next=6;break;case 19:case"end":return a.stop()}}),B)}var K=function(){function e(t,A){Object(l.a)(this,e),t=T(t,A.shape),this.dimIndexers=[];for(var n=A.shape,r=0;r0&&(a+=this.step-u),g=Math.ceil((r-this.start)/this.step)):(a=this.start-r,g=0),s=this.stop>i?o:this.stop-r,l=_(a,s,this.step),I=Math.ceil((s-a)/this.step),C=_(g,g+I),e.next=17,{dimChunkIndex:n,dimChunkSelection:l,dimOutSelection:C};case 17:n++,e.next=3;break;case 20:case"end":return e.stop()}}),e,this)}))}]),e}(),q="undefined"!==typeof e&&e.versions&&e.versions.node;function z(e){if(null===e)return"";for(e instanceof String&&(e=e.valueOf()),e=e.replace(/\\/g,"/");e.length>0&&"/"===e[0];)e=e.slice(1);for(;e.length>0&&"/"===e[e.length-1];)e=e.slice(0,e.length-1);var t,A=(e=e.replace(/\/\/+/g,"/")).split("/"),n=Object(u.a)(A);try{for(n.s();!(t=n.n()).done;){var r=t.value;if("."===r||".."===r)throw Error("path containing '.' or '..' segment not allowed")}}catch(i){n.e(i)}finally{n.f()}return e}function $(e){return"number"===typeof e&&(e=[e]),e.map((function(e){return Math.floor(e)}))}function ee(e,t){if(null===e||!0===e)throw new Error("Chunk guessing is not supported yet");return!1===e?t:("number"===typeof e&&(e=[e]),e.length1&&void 0!==i[1]?i[1]:null),n=ue(A),r=n+".zarray",e.abrupt("return",t.containsItem(r));case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ge(e){return ce.apply(this,arguments)}function ce(){return(ce=Object(d.a)(c.a.mark((function e(t){var A,n,r,i=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=z(A=i.length>1&&void 0!==i[1]?i[1]:null),n=ue(A),r=n+".zgroup",e.abrupt("return",t.containsItem(r));case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ue(e){return e.length>0?e+"/":""}function le(e,t,A,n){return Ie.apply(this,arguments)}function Ie(){return(Ie=Object(d.a)(c.a.mark((function e(t,A,n,r){var i,o,a,s,g;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==A.length){e.next=2;break}return e.abrupt("return");case 2:i=A.split("/"),o="",a=Object(u.a)(i.slice(0,i.length-1)),e.prev=5,a.s();case 7:if((s=a.n()).done){e.next=25;break}return g=s.value,o+=g,e.next=12,ae(t,o);case 12:if(!e.sent){e.next=17;break}return e.next=15,Ce(t,o,r);case 15:e.next=22;break;case 17:return e.next=19,ge(t,o);case 19:if(e.sent){e.next=22;break}return e.next=22,Ce(t,o);case 22:o+="/";case 23:e.next=7;break;case 25:e.next=30;break;case 27:e.prev=27,e.t0=e.catch(5),a.e(e.t0);case 30:return e.prev=30,a.f(),e.finish(30);case 33:case"end":return e.stop()}}),e,null,[[5,27,30,33]])})))).apply(this,arguments)}function Ce(e){return he.apply(this,arguments)}function he(){return(he=Object(d.a)(c.a.mark((function e(t){var A,n,r,i,o=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(A=o.length>1&&void 0!==o[1]?o[1]:null,n=o.length>2&&void 0!==o[2]&&o[2],A=z(A),!n){e.next=7;break}throw Error("Group overwriting not implemented yet :(");case 7:return e.next=9,ae(t,A);case 9:if(!e.sent){e.next=13;break}throw new b(A);case 13:return e.next=15,ge(t,A);case 15:if(!e.sent){e.next=17;break}throw new w(A);case 17:return r={zarr_format:2},i=ue(A)+".zgroup",e.next=21,t.setItem(i,JSON.stringify(r));case 21:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function fe(e,t,A,n,r,i,o,a,s,g,c){return de.apply(this,arguments)}function de(){return(de=Object(d.a)(c.a.mark((function e(t,A,n,r,i,o,a,s,g,u,l){var I,C,h;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!g){e.next=4;break}throw Error("Array overwriting not implemented yet :(");case 4:return e.next=6,ae(t,i);case 6:if(!e.sent){e.next=10;break}throw new b(i);case 10:return e.next=12,ge(t,i);case 12:if(!e.sent){e.next=14;break}throw new w(i);case 14:if(r=r,A=$(A),n=ee(n,A),s=te(s),a=a,!(null!==l&&l.length>0)){e.next=21;break}throw Error("Filters are not supported yet");case 21:return I=a,"number"===typeof a&&(Number.isNaN(a)&&(I="NaN"),Number.POSITIVE_INFINITY===a&&(I="Infinity"),Number.NEGATIVE_INFINITY===a&&(I="-Infinity")),C={zarr_format:2,shape:A,chunks:n,dtype:r,fill_value:I,order:s,compressor:o,filters:l=null},h=ue(i)+".zarray",e.next=28,t.setItem(h,JSON.stringify(C));case 28:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Be(e,t,A,n){return pe.apply(this,arguments)}function pe(){return(pe=Object(d.a)(c.a.mark((function e(t,A,n,r){var i,o,a,s,g,u,l,I=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=I.length>4&&void 0!==I[4]?I[4]:null,o=I.length>5&&void 0!==I[5]?I[5]:null,a=I.length>6&&void 0!==I[6]?I[6]:null,s=I.length>7&&void 0!==I[7]?I[7]:"C",g=I.length>8&&void 0!==I[8]&&I[8],u=I.length>9&&void 0!==I[9]?I[9]:null,l=I.length>10&&void 0!==I[10]?I[10]:null,i=z(i),e.next=10,le(t,i,u,g);case 10:return e.next=12,fe(t,A,n,r,i,o,a,s,g,u,l);case 12:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Ee(e){if("string"!==typeof e){if(q&&n.isBuffer(e))return JSON.parse(e.toString());if(e instanceof ArrayBuffer){var t=new TextDecoder,A=new Uint8Array(e);return JSON.parse(t.decode(A))}return e}return JSON.parse(e)}var Qe=function(){function e(t,A,n){var r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];Object(l.a)(this,e),this.store=t,this.key=A,this.readOnly=n,this.cache=r,this.cachedValue=null}return Object(s.a)(e,[{key:"asObject",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.cache||null===this.cachedValue){e.next=2;break}return e.abrupt("return",this.cachedValue);case 2:return e.next=4,this.getNoSync();case 4:return t=e.sent,this.cache&&(this.cachedValue=t),e.abrupt("return",t);case 7:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"getNoSync",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.store.getItem(this.key);case 3:return t=e.sent,e.abrupt("return",Ee(t));case 7:return e.prev=7,e.t0=e.catch(0),e.abrupt("return",{});case 10:case"end":return e.stop()}}),e,this,[[0,7]])})));return function(){return e.apply(this,arguments)}}()},{key:"setNoSync",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getNoSync();case 2:return(n=e.sent)[t]=A,e.next=6,this.putNoSync(n);case 6:return e.abrupt("return",!0);case 7:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"putNoSync",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.store.setItem(this.key,JSON.stringify(t));case 2:this.cache&&(this.cachedValue=t);case 3:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"delNoSync",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getNoSync();case 2:return delete(A=e.sent)[t],e.next=6,this.putNoSync(A);case 6:return e.abrupt("return",!0);case 7:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"put",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.readOnly){e.next=2;break}throw new F("attributes are read-only");case 2:return e.abrupt("return",this.putNoSync(t));case 3:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"setItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.readOnly){e.next=2;break}throw new F("attributes are read-only");case 2:return e.abrupt("return",this.setNoSync(t,A));case 3:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"getItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.asObject();case 2:return e.t0=t,e.abrupt("return",e.sent[e.t0]);case 4:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"deleteItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.readOnly){e.next=2;break}throw new F("attributes are read-only");case 2:return e.abrupt("return",this.delNoSync(t));case 3:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"containsItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.asObject();case 2:return e.t0=t,e.t1=e.sent[e.t0],e.t2=void 0,e.abrupt("return",e.t1!==e.t2);case 6:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"proxy",value:function(){return v(this)}}]),e}(),ye={"|b":Int8Array,"|B":Uint8Array,"|u1":Uint8Array,"|i1":Int8Array,"b":Int8Array,">B":Uint8Array,">u1":Uint8Array,">i1":Int8Array,">u2":Uint16Array,">i2":Int16Array,">u4":Uint32Array,">i4":Int32Array,">f4":Float32Array,">f8":Float64Array};function ve(e){if(e instanceof Uint8Array)return"|u1";if(e instanceof Int8Array)return"|i1";if(e instanceof Uint16Array)return"0&&"number"===typeof I[0]){var h=t[0].constructor;I=h.from(I)}return I}(e,t,i),a]}function we(e,t,A,n){var r=L(T(n,A,!0),A),i=Object(o.a)(r,2),a=i[0];i[1];Fe(e,t,A,a)}function Se(e,t,A,n,r){var i=L(T(r,A,!1),A),a=Object(o.a)(i,2),s=a[0],g=a[1];if(JSON.stringify(g)!==JSON.stringify(n))throw new N("Shape mismatch in target and source NestedArray: ".concat(g," and ").concat(n));!function e(t,A,n,r){var i=r[0];if("number"===typeof A)return void Fe(t,A,n,r.map((function(e){return"number"===typeof e?[e,e+1,1,1]:e})));if("number"===typeof i)return void e(t[i],A,n.slice(1),r.slice(1));var a=Object(o.a)(i,4),s=a[0],g=(a[1],a[2]),c=a[3];if(1===n.length){if(1===g)t.set(A,s);else for(var u=0;u3&&void 0!==arguments[3]?arguments[3]:0;if(1===n.length)return new A(t.slice(r,r+n[0]*A.BYTES_PER_ELEMENT));var i=new Array(n[0]);if(2===n.length){for(var o=0;o0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1?arguments[1]:void 0;null===e&&(e=[_(null)]),"number"===typeof t?0===this.shape.length?this.data[0]=t:we(this.data,t,this.shape,e):Se(this.data,t.data,this.shape,t.shape,e)}},{key:"flatten",value:function(){return 1===this.shape.length?this.data:Re(this.data,this.shape,ye[this.dtype])}}],[{key:"arange",value:function(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"=0;r--)A[r]=n,n*=e[r];return A}(A)),this.shape=A,this.dtype=r,this.strides=i,o&&1!==A.length&&(t=t.buffer),0===this.shape.length)this.data=new ye[r](1);else if(q&&n.isBuffer(t)||t instanceof ArrayBuffer||null===t||t.toString().startsWith("[object ArrayBuffer]")){var a=A.reduce((function(e,t){return e*t}),1);null===t&&(t=new ArrayBuffer(a*parseInt(r[r.length-1],10)));var s=t.byteLength/parseInt(r[r.length-1],10);if(a!==s)throw new Error("Buffer has ".concat(s," of dtype ").concat(r,", shape is too large or small ").concat(A," (flat=").concat(a,")"));var g=ye[r];this.data=new g(t)}else this.data=t}return Object(s.a)(e,[{key:"set",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,A=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;null===t&&(t=[_(null)]),"number"===typeof A?0===this.shape.length?this.data[0]=A:ke(this.data,this.strides,this.shape,t,A):A instanceof e&&n?Ne(this.data,this.strides,this.shape,t,A.data,A.strides,A.shape,n):xe(this.data,this.strides,this.shape,t,A.data,A.strides,A.shape)}}]),e}();function _e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Me(e,t){return e(t={exports:{}},t.exports),t.exports}var Oe=Me((function(e){var t=Object.prototype.hasOwnProperty,A="~";function n(){}function r(e,t,A){this.fn=e,this.context=t,this.once=A||!1}function i(e,t,n,i,o){if("function"!==typeof n)throw new TypeError("The listener must be a function");var a=new r(n,i||e,o),s=A?A+t:t;return e._events[s]?e._events[s].fn?e._events[s]=[e._events[s],a]:e._events[s].push(a):(e._events[s]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(A=!1)),a.prototype.eventNames=function(){var e,n,r=[];if(0===this._eventsCount)return r;for(n in e=this._events)t.call(e,n)&&r.push(A?n.slice(1):n);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},a.prototype.listeners=function(e){var t=A?A+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var r=0,i=n.length,o=new Array(i);r0;){var i=r/2|0,o=n+i;A(e[o],t)<=0?(n=++o,r-=i+1):r=i}return n}}));_e(Je);var je=Me((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var A=function(){function e(){Object(l.a)(this,e),this._queue=[]}return Object(s.a)(e,[{key:"enqueue",value:function(e,t){var A={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)this._queue.push(A);else{var n=Je.default(this._queue,A,(function(e,t){return t.priority-e.priority}));this._queue.splice(n,0,A)}}},{key:"dequeue",value:function(){var e=this._queue.shift();return e&&e.run}},{key:"size",get:function(){return this._queue.length}}]),e}();t.default=A}));_e(je);var Pe,Ve=_e(Me((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var A=function(){},n=new Ze.default.TimeoutError,r=function(e){Object(C.a)(r,e);var t=Object(h.a)(r);function r(e){var n;if(Object(l.a)(this,r),(n=t.call(this))._intervalCount=0,n._intervalEnd=0,n._pendingCount=0,n._resolveEmpty=A,n._resolveIdle=A,!("number"===typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:je.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError("Expected `intervalCap` to be a number from 1 and up, got `".concat(e.intervalCap,"` (").concat(typeof e.intervalCap,")"));if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError("Expected `interval` to be a finite number >= 0, got `".concat(e.interval,"` (").concat(typeof e.interval,")"));return n._carryoverConcurrencyCount=e.carryoverConcurrencyCount,n._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,n._intervalCap=e.intervalCap,n._interval=e.interval,n._queue=new e.queueClass,n._queueClass=e.queueClass,n.concurrency=e.concurrency,n._timeout=e.timeout,n._throwOnTimeout=!0===e.throwOnTimeout,n._isPaused=!1===e.autoStart,n}return Object(s.a)(r,[{key:"_next",value:function(){this._pendingCount--,this._tryToStartAnother()}},{key:"_resolvePromises",value:function(){this._resolveEmpty(),this._resolveEmpty=A,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=A)}},{key:"_onResumeInterval",value:function(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}},{key:"_isIntervalPaused",value:function(){var e=this,t=Date.now();if(void 0===this._intervalId){var A=this._intervalEnd-t;if(!(A<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout((function(){e._onResumeInterval()}),A)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}},{key:"_tryToStartAnother",value:function(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){var e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother)return this.emit("active"),this._queue.dequeue()(),e&&this._initializeIntervalIfNeeded(),!0}return!1}},{key:"_initializeIntervalIfNeeded",value:function(){var e=this;this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((function(){e._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}},{key:"_onInterval",value:function(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}},{key:"_processQueue",value:function(){for(;this._tryToStartAnother(););}},{key:"add",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A,r=this,i=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=i.length>1&&void 0!==i[1]?i[1]:{},e.abrupt("return",new Promise((function(e,i){var o=function(){var o=Object(d.a)(c.a.mark((function o(){var a;return c.a.wrap((function(o){for(;;)switch(o.prev=o.next){case 0:return r._pendingCount++,r._intervalCount++,o.prev=2,a=void 0===r._timeout&&void 0===A.timeout?t():Ze.default(Promise.resolve(t()),void 0===A.timeout?r._timeout:A.timeout,(function(){(void 0===A.throwOnTimeout?r._throwOnTimeout:A.throwOnTimeout)&&i(n)})),o.t0=e,o.next=7,a;case 7:o.t1=o.sent,(0,o.t0)(o.t1),o.next=14;break;case 11:o.prev=11,o.t2=o.catch(2),i(o.t2);case 14:r._next();case 15:case"end":return o.stop()}}),o,null,[[2,11]])})));return function(){return o.apply(this,arguments)}}();r._queue.enqueue(o,A),r._tryToStartAnother()})));case 2:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()},{key:"addAll",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",Promise.all(t.map(function(){var e=Object(d.a)(c.a.mark((function e(t){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",n.add(t,A));case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}())));case 1:case"end":return e.stop()}}),e)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"start",value:function(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}},{key:"pause",value:function(){this._isPaused=!0}},{key:"clear",value:function(){this._queue=new this._queueClass}},{key:"onEmpty",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==this._queue.size){e.next=2;break}return e.abrupt("return");case 2:return e.abrupt("return",new Promise((function(e){var A=t._resolveEmpty;t._resolveEmpty=function(){A(),e()}})));case 3:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"onIdle",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==this._pendingCount||0!==this._queue.size){e.next=2;break}return e.abrupt("return");case 2:return e.abrupt("return",new Promise((function(e){var A=t._resolveIdle;t._resolveIdle=function(){A(),e()}})));case 3:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"_doesIntervalAllowAnother",get:function(){return this._isIntervalIgnored||this._intervalCount=1))throw new TypeError("Expected `concurrency` to be a number from 1 and up, got `".concat(e,"` (").concat(typeof e,")"));this._concurrency=e,this._processQueue()}},{key:"size",get:function(){return this._queue.size}},{key:"pending",get:function(){return this._pendingCount}},{key:"isPaused",get:function(){return this._isPaused}},{key:"timeout",set:function(e){this._timeout=e},get:function(){return this._timeout}}]),r}(Oe);t.default=r}))),Ke=function(){function e(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=arguments.length>2?arguments[2]:void 0,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],a=!(arguments.length>6&&void 0!==arguments[6])||arguments[6];Object(l.a)(this,e),this.store=t,this._chunkStore=i,this.path=z(A),this.keyPrefix=ue(this.path),this.readOnly=r,this.cacheMetadata=o,this.cacheAttrs=a,this.meta=n,null!==this.meta.compressor?this.compressor=Q(this.meta.compressor):this.compressor=null;var s=this.keyPrefix+".zattrs";this.attrs=new Qe(this.store,s,this.readOnly,a)}return Object(s.a)(e,[{key:"reloadMetadata",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t,A;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.keyPrefix+".zarray",A=this.store.getItem(t),e.t0=Ee,e.next=5,A;case 5:return e.t1=e.sent,this.meta=(0,e.t0)(e.t1),e.abrupt("return",this.meta);case 8:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"refreshMetadata",value:function(){var e=Object(d.a)(c.a.mark((function e(){return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.cacheMetadata){e.next=3;break}return e.next=3,this.reloadMetadata();case 3:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"get",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.getBasicSelection(e,!1,t)}},{key:"getRaw",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.getBasicSelection(e,!0,t)}},{key:"getBasicSelection",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A,n,r,i,o,a=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(A=a.length>1&&void 0!==a[1]&&a[1],n=a.length>2&&void 0!==a[2]?a[2]:{},r=n.concurrencyLimit,i=void 0===r?10:r,o=n.progressCallback,this.cacheMetadata){e.next=5;break}return e.next=5,this.reloadMetadata();case 5:if(this.shape!==[]){e.next=9;break}throw new Error("Shape [] indexing is not supported yet");case 9:return e.abrupt("return",this.getBasicSelectionND(t,A,i,o));case 10:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"getBasicSelectionND",value:function(e,t,A,n){var r=new K(e,this);return this.getSelection(r,t,A,n)}},{key:"getSelection",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n,r){var i,o,a,s,g,l,I,C,h,f,B,p,E=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=this.dtype,o=t.shape,a=t.shape.reduce((function(e,t){return e*t}),1),!A||a!==this.chunkSize){e.next=12;break}if(s=t.iter(),!1!==(g=s.next()).done||!0!==s.next().done){e.next=12;break}return l=g.value,e.next=10,this.decodeDirectToRawArray(l,o,a);case 10:return I=e.sent,e.abrupt("return",I);case 12:if(C=A?new Ue(null,o,i):new De(null,o,i),0!==a){e.next=15;break}return e.abrupt("return",C);case 15:if(h=new Ve({concurrency:n}),r)!function(){var e,A=0,n=0,i=Object(u.a)(t.iter());try{for(i.s();!(e=i.n()).done;){e.value;n+=1}}catch(g){i.e(g)}finally{i.f()}r({progress:0,queueSize:n});var o,a=Object(u.a)(t.iter());try{var s=function(){var e=o.value;Object(d.a)(c.a.mark((function i(){return c.a.wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return i.next=2,h.add((function(){return E.chunkGetItem(e.chunkCoords,e.chunkSelection,C,e.outSelection,t.dropAxes)}));case 2:r({progress:A+=1,queueSize:n});case 4:case"end":return i.stop()}}),i)})))()};for(a.s();!(o=a.n()).done;)s()}catch(g){a.e(g)}finally{a.f()}}();else{f=Object(u.a)(t.iter());try{for(p=function(){var e=B.value;h.add((function(){return E.chunkGetItem(e.chunkCoords,e.chunkSelection,C,e.outSelection,t.dropAxes)}))},f.s();!(B=f.n()).done;)p()}catch(Q){f.e(Q)}finally{f.f()}}return e.next=19,h.onIdle();case 19:if(0!==C.shape.length){e.next=21;break}return e.abrupt("return",C.data[0]);case 21:return e.abrupt("return",C);case 22:case"end":return e.stop()}}),e,this)})));return function(t,A,n,r){return e.apply(this,arguments)}}()},{key:"chunkGetItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n,r,i){var o,a,s,g,u;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length===this._chunkDataShape.length){e.next=2;break}throw new N("Inconsistent shapes: chunkCoordsLength: ".concat(t.length,", cDataShapeLength: ").concat(this.chunkDataShape.length));case 2:return o=this.chunkKey(t),e.prev=3,e.next=6,this.chunkStore.getItem(o);case 6:return a=e.sent,e.next=9,this.decodeChunk(a);case 9:if(s=e.sent,!(n instanceof De)){e.next=21;break}if(!P(r)||!Ae(A,this.chunks)||this.meta.filters){e.next=14;break}return n.set(r,this.toNestedArray(s)),e.abrupt("return");case 14:if(g=this.toNestedArray(s),u=g.get(A),null===i){e.next=18;break}throw new Error("Drop axes is not supported yet");case 18:n.set(r,u),e.next=22;break;case 21:n.set(r,this.chunkBufferToRawArray(s),A);case 22:e.next=31;break;case 24:if(e.prev=24,e.t0=e.catch(3),!m(e.t0)){e.next=30;break}null!==this.fillValue&&n.set(r,this.fillValue),e.next=31;break;case 30:throw e.t0;case 31:case"end":return e.stop()}}),e,this,[[3,24]])})));return function(t,A,n,r,i){return e.apply(this,arguments)}}()},{key:"getRawChunk",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n,r,i,o,a,s;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length===this.shape.length){e.next=2;break}throw new Error("Chunk coordinates ".concat(t.join(".")," do not correspond to shape ").concat(this.shape,"."));case 2:for(e.prev=2,n=0;n")&&ie(this.toTypedArray(A.buffer)),e.abrupt("return",A.buffer);case 9:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"chunkBufferToRawArray",value:function(e){return new Ue(e,this.chunks,this.dtype)}},{key:"decodeDirectToRawArray",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n){var r,i,o,a;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.chunkCoords,i=this.chunkKey(r),e.prev=2,e.next=5,this.chunkStore.getItem(i);case 5:return o=e.sent,e.t0=Ue,e.next=9,this.decodeChunk(o);case 9:return e.t1=e.sent,e.t2=A,e.t3=this.dtype,e.abrupt("return",new e.t0(e.t1,e.t2,e.t3));case 15:if(e.prev=15,e.t4=e.catch(2),!m(e.t4)){e.next=22;break}return a=new ye[this.dtype](n),e.abrupt("return",new Ue(a.fill(this.fillValue),A));case 22:throw e.t4;case 23:case"end":return e.stop()}}),e,this,[[2,15]])})));return function(t,A,n){return e.apply(this,arguments)}}()},{key:"set",value:function(){var e=Object(d.a)(c.a.mark((function e(){var t,A,n,r=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=r.length>0&&void 0!==r[0]?r[0]:null,A=r.length>1?r[1]:void 0,n=r.length>2&&void 0!==r[2]?r[2]:{},e.next=5,this.setBasicSelection(t,A,n);case 5:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"setBasicSelection",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n,r,i,o,a=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=a.length>2&&void 0!==a[2]?a[2]:{},r=n.concurrencyLimit,i=void 0===r?10:r,o=n.progressCallback,!this.readOnly){e.next=3;break}throw new F("Object is read only");case 3:if(this.cacheMetadata){e.next=6;break}return e.next=6,this.reloadMetadata();case 6:if(this.shape!==[]){e.next=10;break}throw new Error("Shape [] indexing is not supported yet");case 10:return e.next=12,this.setBasicSelectionND(t,A,i,o);case 12:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"setBasicSelectionND",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n,r){var i;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=new K(t,this),e.next=3,this.setSelection(i,A,n,r);case 3:case"end":return e.stop()}}),e,this)})));return function(t,A,n,r){return e.apply(this,arguments)}}()},{key:"getChunkValue",value:function(e,t,A,n){var r;if(n===[])r=A;else if("number"===typeof A)r=A;else if(r=A.get(e.outSelection),null!==t.dropAxes)throw new Error("Handling drop axes not supported yet");return r}},{key:"setSelection",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n,r){var i,o,a,s,g,l=this;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((i=t.shape)!==[]){e.next=5;break}e.next=15;break;case 5:if("number"!==typeof A){e.next=9;break}e.next=15;break;case 9:if(!(A instanceof De)){e.next=14;break}if(ne(A.shape,i)){e.next=12;break}throw new N("Shape mismatch in source NestedArray and set selection: ".concat(A.shape," and ").concat(i));case 12:e.next=15;break;case 14:throw new Error("Unknown data type for setting :(");case 15:if(o=new Ve({concurrency:n}),r)!function(){var e,n=0,a=Object(u.a)(t.iter());try{for(a.s();!(e=a.n()).done;){e.value;n+=1}}catch(h){a.e(h)}finally{a.f()}var s=0;r({progress:0,queueSize:n});var g,I=Object(u.a)(t.iter());try{var C=function(){var e=g.value,a=l.getChunkValue(e,t,A,i);Object(d.a)(c.a.mark((function t(){return c.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,o.add((function(){return l.chunkSetItem(e.chunkCoords,e.chunkSelection,a)}));case 2:r({progress:s+=1,queueSize:n});case 4:case"end":return t.stop()}}),t)})))()};for(I.s();!(g=I.n()).done;)C()}catch(h){I.e(h)}finally{I.f()}}();else{a=Object(u.a)(t.iter());try{for(g=function(){var e=s.value,n=l.getChunkValue(e,t,A,i);o.add((function(){return l.chunkSetItem(e.chunkCoords,e.chunkSelection,n)}))},a.s();!(s=a.n()).done;)g()}catch(I){a.e(I)}finally{a.f()}}return e.next=19,o.onIdle();case 19:case"end":return e.stop()}}),e)})));return function(t,A,n,r){return e.apply(this,arguments)}}()},{key:"chunkSetItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A,n){var r,i,o,a,s,g,u,l,I;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=this.chunkKey(t),i=null,o=ye[this.dtype],a=this.chunkSize,!Ae(A,this.chunks)){e.next=8;break}"number"===typeof n?(i=new o(a)).fill(n):i=n.flatten(),e.next=29;break;case 8:return e.prev=8,e.next=11,this.chunkStore.getItem(r);case 11:return g=e.sent,e.next=14,this.decodeChunk(g);case 14:u=e.sent,s=this.toTypedArray(u),e.next=26;break;case 18:if(e.prev=18,e.t0=e.catch(8),!m(e.t0)){e.next=25;break}s=new o(a),null!==this.fillValue&&s.fill(this.fillValue),e.next=26;break;case 25:throw e.t0;case 26:(l=new De(s,this.chunks,this.dtype)).set(A,n),i=l.flatten();case 29:return e.next=31,this.encodeChunk(i);case 31:I=e.sent,this.chunkStore.setItem(r,I);case 33:case"end":return e.stop()}}),e,this,[[8,18]])})));return function(t,A,n){return e.apply(this,arguments)}}()},{key:"encodeChunk",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A,n;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.dtype.includes(">")&&(t=oe(t)),null===this.compressor){e.next=9;break}return A=new Uint8Array(t.buffer),e.next=5,this.compressor;case 5:return e.next=7,e.sent.encode(A);case 7:return n=e.sent,e.abrupt("return",n.buffer);case 9:return e.abrupt("return",t.buffer);case 10:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"chunkStore",get:function(){return this._chunkStore?this._chunkStore:this.store}},{key:"name",get:function(){return this.path.length>0?"/"!==this.path[0]?"/"+this.path:this.path:null}},{key:"basename",get:function(){var e=this.name;if(null===e)return null;var t=e.split("/");return t[t.length-1]}},{key:"shape",get:function(){return this.meta.shape}},{key:"chunks",get:function(){return this.meta.chunks}},{key:"chunkSize",get:function(){return this.chunks.reduce((function(e,t){return e*t}),1)}},{key:"dtype",get:function(){return this.meta.dtype}},{key:"fillValue",get:function(){var e=this.meta.fill_value;return"NaN"===e?NaN:"Infinity"===e?1/0:"-Infinity"===e?-1/0:this.meta.fill_value}},{key:"nDims",get:function(){return this.meta.shape.length}},{key:"size",get:function(){return this.meta.shape.reduce((function(e,t){return e*t}),1)}},{key:"length",get:function(){return this.shape[0]}},{key:"_chunkDataShape",get:function(){if(this.shape===[])return[1];for(var e=[],t=0;t1&&void 0!==g[1]?g[1]:null,r=g.length>2&&void 0!==g[2]&&g[2],i=g.length>3&&void 0!==g[3]?g[3]:null,o=!(g.length>4&&void 0!==g[4])||g[4],a=!(g.length>5&&void 0!==g[5])||g[5],t.next=7,this.loadMetadataForConstructor(A,n);case 7:return s=t.sent,t.abrupt("return",new e(A,n,s,r,i,o,a));case 9:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}()},{key:"loadMetadataForConstructor",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n,r;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,A=z(A),n=ue(A),e.next=5,t.getItem(n+".zarray");case 5:return r=e.sent,e.abrupt("return",Ee(r));case 9:return e.prev=9,e.t0=e.catch(0),e.next=13,ge(t,A);case 13:if(!e.sent){e.next=15;break}throw new w(null!==A&&void 0!==A?A:"");case 15:throw new Error("Failed to load metadata for ZarrArray:"+e.t0.toString());case 16:case"end":return e.stop()}}),e,null,[[0,9]])})));return function(t,A){return e.apply(this,arguments)}}()}]),e}(),We=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(l.a)(this,e),this.root=t}return Object(s.a)(e,[{key:"proxy",value:function(){return v(this)}},{key:"getParent",value:function(e){var t,A=this.root,n=e.split("/"),r=Object(u.a)(n.slice(0,n.length-1));try{for(r.s();!(t=r.n()).done;){if(!(A=A[t.value]))throw Error(e)}}catch(i){r.e(i)}finally{r.f()}return[A,n[n.length-1]]}},{key:"requireParent",value:function(e){var t,A=this.root,n=e.split("/"),r=Object(u.a)(n.slice(0,n.length-1));try{for(r.s();!(t=r.n()).done;){var i=t.value;void 0===A[i]&&(A[i]={}),A=A[i]}}catch(o){r.e(o)}finally{r.f()}return[A,n[n.length-1]]}},{key:"getItem",value:function(e){var t=this.getParent(e),A=Object(o.a)(t,2),n=A[0][A[1]];if(void 0===n)throw new R(e);return n}},{key:"setItem",value:function(e,t){var A=this.requireParent(e),n=Object(o.a)(A,2);return n[0][n[1]]=t,!0}},{key:"deleteItem",value:function(e){var t=this.getParent(e),A=Object(o.a)(t,2);return delete A[0][A[1]]}},{key:"containsItem",value:function(e){try{return void 0!==this.getItem(e)}catch(t){return!1}}},{key:"keys",value:function(){throw new Error("Method not implemented.")}}]),e}();!function(e){e.HEAD="HEAD",e.GET="GET",e.PUT="PUT"}(Pe||(Pe={}));var Xe=[Pe.HEAD,Pe.GET,Pe.PUT],qe=function(){function e(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object(l.a)(this,e),this.url=t;var n=A.fetchOptions,r=void 0===n?{}:n,i=A.supportedMethods,o=void 0===i?Xe:i;this.fetchOptions=r,this.supportedMethods=new Set(o)}return Object(s.a)(e,[{key:"keys",value:function(){throw new Error("Method not implemented.")}},{key:"getItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var i,o;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=re(this.url,t),e.next=3,fetch(i,Object(r.a)({},this.fetchOptions,{},A));case 3:if(404!==(o=e.sent).status){e.next=8;break}throw new R(t);case 8:if(200===o.status){e.next=10;break}throw new U(String(o.status));case 10:if(!q){e.next=18;break}return e.t0=n,e.next=14,o.arrayBuffer();case 14:return e.t1=e.sent,e.abrupt("return",e.t0.from.call(e.t0,e.t1));case 18:return e.abrupt("return",o.arrayBuffer());case 19:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"setItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t,A){var n,i;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.supportedMethods.has(Pe.PUT)){e.next=2;break}throw new Error("HTTP PUT no a supported method for store.");case 2:return n=re(this.url,t),"string"===typeof A&&(A=(new TextEncoder).encode(A).buffer),e.next=6,fetch(n,Object(r.a)({},this.fetchOptions,{method:Pe.PUT,body:A}));case 6:return i=e.sent,e.abrupt("return","2"===i.status.toString()[0]);case 8:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"deleteItem",value:function(e){throw new Error("Method not implemented.")}},{key:"containsItem",value:function(){var e=Object(d.a)(c.a.mark((function e(t){var A,n,i;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=re(this.url,t),n=this.supportedMethods.has(Pe.HEAD)?Pe.HEAD:Pe.GET,e.next=4,fetch(A,Object(r.a)({},this.fetchOptions,{method:n}));case 4:return i=e.sent,e.abrupt("return",200===i.status);case 6:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()}]),e}();function ze(){return $e.apply(this,arguments)}function $e(){return($e=Object(d.a)(c.a.mark((function e(){var t,A,n,r,i,o,a,s,g,u,l,I,C,h,f,d,B,p,E,Q,y,v,m,F,R,D,G=arguments;return c.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=G.length>0&&void 0!==G[0]?G[0]:{},A=t.shape,n=t.mode,r=void 0===n?"a":n,i=t.chunks,o=void 0===i||i,a=t.dtype,s=void 0===a?"1?t-1:0),o=1;o=0&&A.splice(n,1),A}function C(e,t){var A=e.slice();return-1===A.indexOf(t)&&A.push(t),A}function h(e){return e.split("-")}function f(e,t){return e+"-"+t}function d(e){return e&&e.type&&e.type.isTreeNode}function B(e){return Object(a.a)(e).filter(d)}function p(e){var t=e.props||{},A=t.disabled,n=t.disableCheckbox;return!(!A&&!n)}function E(e,t){!function A(n,r,o){var a=n?n.props.children:e,s=n?f(o.pos,r):0,g=B(a);if(n){var c={node:n,index:r,pos:s,key:n.key||s,parentPos:o.node?o.pos:null};t(c)}i.Children.forEach(g,(function(e,t){A(e,t,{node:n,pos:s})}))}(null)}function Q(e,t){var A=Object(a.a)(e).map(t);return 1===A.length?A[0]:A}function y(e,t){var A=t.props,n=A.eventKey,r=A.pos,i=[];return E(e,(function(e){var t=e.key;i.push(t)})),i.push(n||r),i}function v(e,t){var A=e.clientY,n=t.selectHandle.getBoundingClientRect(),r=n.top,i=n.bottom,o=n.height,a=Math.max(.25*o,2);return A<=r+a?-1:A>=i-a?1:0}function m(e,t){if(e)return t.multiple?e.slice():e.length?[e[0]]:e}function b(e){return e?e.map((function(e){return String(e)})):e}var w=function(e){return e};function S(e,t){if(!e)return[];var A=(t||{}).processProps,n=void 0===A?w:A;return(Array.isArray(e)?e:[e]).map((function(e){var A=e.children,i=r()(e,["children"]),a=S(A,t);return o.a.createElement(c.a,n(i),a)}))}function F(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.initWrapper,n=t.processEntity,r=t.onProcessFinished,i={},o={},a={posEntities:i,keyEntities:o};return A&&(a=A(a)||a),E(e,(function(e){var t=e.node,A=e.index,r=e.pos,s=e.key,g=e.parentPos,c={node:t,index:A,key:s,pos:r};i[r]=c,o[s]=c,c.parent=i[g],c.parent&&(c.parent.children=c.parent.children||[],c.parent.children.push(c)),n&&n(c,a)})),r&&r(a),a}function R(e){if(!e)return null;var t=void 0;if(Array.isArray(e))t={checkedKeys:e,halfCheckedKeys:void 0};else{if("object"!==typeof e)return g()(!1,"`checkedKeys` is not an array or an object"),null;t={checkedKeys:e.checked||void 0,halfCheckedKeys:e.halfChecked||void 0}}return t.checkedKeys=b(t.checkedKeys),t.halfCheckedKeys=b(t.halfCheckedKeys),t}function D(e,t,A){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},r={},i={};function o(e){if(r[e]!==t){var n=A[e];if(n){var a=n.children,s=n.parent;if(!p(n.node)){var g=!0,c=!1;(a||[]).filter((function(e){return!p(e.node)})).forEach((function(e){var t=e.key,A=r[t],n=i[t];(A||n)&&(c=!0),A||(g=!1)})),r[e]=!!t&&g,i[e]=c,s&&o(s.key)}}}}function a(e){if(r[e]!==t){var n=A[e];if(n){var i=n.children;p(n.node)||(r[e]=t,(i||[]).forEach((function(e){a(e.key)})))}}}function s(e){var n=A[e];if(n){var i=n.children,s=n.parent,c=n.node;r[e]=t,p(c)||((i||[]).filter((function(e){return!p(e.node)})).forEach((function(e){a(e.key)})),s&&o(s.key))}else g()(!1,"'"+e+"' does not exist in the tree.")}(n.checkedKeys||[]).forEach((function(e){r[e]=!0})),(n.halfCheckedKeys||[]).forEach((function(e){i[e]=!0})),(e||[]).forEach((function(e){s(e)}));var c=[],u=[];return Object.keys(r).forEach((function(e){r[e]&&c.push(e)})),Object.keys(i).forEach((function(e){!r[e]&&i[e]&&u.push(e)})),{checkedKeys:c,halfCheckedKeys:u}}function G(e,t){var A={};return(e||[]).forEach((function(e){!function e(n){if(!A[n]){var r=t[n];if(r){A[n]=!0;var i=r.parent;p(r.node)||i&&e(i.key)}}}(e)})),Object.keys(A)}function k(e){return Object.keys(e).reduce((function(t,A){return"data-"!==A.substr(0,5)&&"aria-"!==A.substr(0,5)||(t[A]=e[A]),t}),{})}},function(e,t,A){"use strict";var n=A(6),r=A(24),i=A(3),o=A.n(i),a=A(12),s=A(8),g=A(2),c=A(83),u=A(1),l=A(4),I=A(16),C=A(17),h=A(9),f=A(10),d=A(7),B=A(11),p=A(36),E=A(575),Q=A(576),y=A(384),v=A(511),m=A(579),b=A(581),w=A(133),S=(A(582),A(23)),F=A(22),R=A(224),D=A(18),G=A(422),k=A(135),x=A(232),N=A(665),U=A(528),_=A(718),M=A(427),O=A(648),L=A(580),T=A(649),Z=A(386);function H(e,t,A,n,r){!function e(t,A,n,r,i){for(;r>n;){if(r-n>600){var o=r-n+1,a=A-n+1,s=Math.log(o),g=.5*Math.exp(2*s/3),c=.5*Math.sqrt(s*g*(o-g)/o)*(a-o/2<0?-1:1),u=Math.max(n,Math.floor(A-a*g/o+c)),l=Math.min(r,Math.floor(A+(o-a)*g/o+c));e(t,A,u,l,i)}var I=t[A],C=n,h=r;for(Y(t,n,A),i(t[r],I)>0&&Y(t,n,r);C0;)h--}0===i(t[n],I)?Y(t,n,h):(h++,Y(t,h,r)),h<=A&&(n=h+1),A<=h&&(r=h-1)}}(e,t,A||0,n||e.length-1,r||J)}function Y(e,t,A){var n=e[t];e[t]=e[A],e[A]=n}function J(e,t){return et?1:0}var j=A(81),P=A(0),V=A(1290),K=A(146),W=A.n(K),X=A(292),q=A(54);function z(e){return e instanceof DataView}for(var $=new ArrayBuffer(4),ee=new Float32Array($),te=new Uint32Array($),Ae=new Uint32Array(512),ne=new Uint32Array(512),re=0;re<256;++re){var ie=re-127;ie<-27?(Ae[0|re]=0,Ae[256|re]=32768,ne[0|re]=24,ne[256|re]=24):ie<-14?(Ae[0|re]=1024>>-ie-14,Ae[256|re]=1024>>-ie-14|32768,ne[0|re]=-ie-1,ne[256|re]=-ie-1):ie<=15?(Ae[0|re]=ie+15<<10,Ae[256|re]=ie+15<<10|32768,ne[0|re]=13,ne[256|re]=13):ie<128?(Ae[0|re]=31744,Ae[256|re]=64512,ne[0|re]=24,ne[256|re]=24):(Ae[0|re]=31744,Ae[256|re]=64512,ne[0|re]=13,ne[256|re]=13)}var oe=new Uint32Array(2048),ae=new Uint32Array(64),se=new Uint32Array(64);oe[0]=0;for(var ge=1;ge<1024;++ge){for(var ce=ge<<13,ue=0;0===(8388608&ce);)ue-=8388608,ce<<=1;ce&=-8388609,ue+=947912704,oe[ge]=ce|ue}for(var le=1024;le<2048;++le)oe[le]=939524096+(le-1024<<13);ae[0]=0;for(var Ie=1;Ie<31;++Ie)ae[Ie]=Ie<<23;ae[31]=1199570944,ae[32]=2147483648;for(var Ce=33;Ce<63;++Ce)ae[Ce]=2147483648+(Ce-32<<23);ae[63]=3347054592,se[0]=0;for(var he=1;he<64;++he)se[he]=32===he?0:1024;function fe(e){var t=e>>10;return te[0]=oe[se[t]+(1023&e)]+ae[t],ee[0]}function de(e,t){if(!z(e))throw new TypeError("First argument to getFloat16 function must be a DataView");for(var A=arguments.length,n=new Array(A>2?A-2:0),r=2;r".charCodeAt(0),a="-".charCodeAt(0),s="/".charCodeAt(0),g="!".charCodeAt(0),c="'".charCodeAt(0),u='"'.charCodeAt(0),l="[".charCodeAt(0),I="]".charCodeAt(0);function C(t){for(var c=[];e[A];)if(e.charCodeAt(A)==i){if(e.charCodeAt(A+1)===s){var u=A+2;if(A=e.indexOf(">",A),-1==e.substring(u,A).indexOf(t)){var C=e.substring(0,A).split("\n");throw new Error("Unexpected close tag\nLine: "+(C.length-1)+"\nColumn: "+(C[C.length-1].length+1)+"\nChar: "+e[A])}return A+1&&(A+=1),c}if(e.charCodeAt(A+1)===g){if(e.charCodeAt(A+2)==a){for(var f=A;-1!==A&&(e.charCodeAt(A)!==o||e.charCodeAt(A-1)!=a||e.charCodeAt(A-2)!=a||-1==A);)A=e.indexOf(">",A+1);-1===A&&(A=e.length),n&&c.push(e.substring(f,A+1))}else{if(e.charCodeAt(A+2)===l&&e.charCodeAt(A+8)===l&&"cdata"===e.substr(A+3,5).toLowerCase()){var d=e.indexOf("]]>",A);-1==d?(c.push(e.substr(A+9)),A=e.length):(c.push(e.substring(A+9,d)),A=d+3);continue}var E=A+1;A+=2;for(var Q=!1;(e.charCodeAt(A)!==o||!0===Q)&&e[A];)e.charCodeAt(A)===l?Q=!0:!0===Q&&e.charCodeAt(A)===I&&(Q=!1),A++;c.push(e.substring(E,A))}A++;continue}var y=p();c.push(y),"?"===y.tagName[0]&&(c.push.apply(c,Object(B.a)(y.children)),y.children=[])}else{var v=h();if(r)v.length>0&&c.push(v);else{var m=v.trim();m.length>0&&c.push(m)}A++}return c}function h(){var t=A;return-2===(A=e.indexOf("<",A)-1)&&(A=e.length),e.slice(t,A+1)}function f(){for(var t=A;-1==="\r\n\t>/= ".indexOf(e[A])&&e[A];)A++;return e.slice(t,A)}var d=t.noChildNodes||["img","br","input","meta","link","hr"];function p(){A++;for(var t=f(),n={},r=[];e.charCodeAt(A)!==o&&e[A];){var i=e.charCodeAt(A);if(i>64&&i<91||i>96&&i<123){for(var a=f(),g=e.charCodeAt(A);g&&g!==c&&g!==u&&!(g>64&&g<91||g>96&&g<123)&&g!==o;)A++,g=e.charCodeAt(A);if(g===c||g===u){var l=E();if(-1===A)return{tagName:t,attributes:n,children:r}}else l=null,A--;n[a]=l}A++}if(e.charCodeAt(A-1)!==s)if("script"==t){var I=A+1;A=e.indexOf("<\/script>",A),r=[e.slice(I,A)],A+=9}else if("style"==t){I=A+1;A=e.indexOf("",A),r=[e.slice(I,A)],A+=8}else-1===d.indexOf(t)?(A++,r=C(t)):A++;else A++;return{tagName:t,attributes:n,children:r}}function E(){var t=e[A],n=A+1;return A=e.indexOf(t,n),e.slice(n,A)}function Q(){var A=new RegExp("\\s"+t.attrName+"\\s*=['\"]"+t.attrValue+"['\"]").exec(e);return A?A.index:-1}var y=null;if(void 0!==t.attrValue){t.attrName=t.attrName||"id";for(y=[];-1!==(A=Q());)-1!==(A=e.lastIndexOf("<",A))&&y.push(p()),e=e.substr(A),A=0}else y=t.parseNode?p():C("");return t.filter&&(y=function e(t,A){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",i=[];return t.forEach((function(t,o){if("object"===typeof t&&A(t,o,n,r)&&i.push(t),t.children){var a=e(t.children,A,n+1,(r?r+".":"")+o+"."+t.tagName);i=i.concat(a)}})),i}(y,t.filter)),t.simplify?function e(t){var A={};if(!t.length)return"";if(1===t.length&&"string"==typeof t[0])return t[0];for(var n in t.forEach((function(t){if("object"===typeof t){A[t.tagName]||(A[t.tagName]=[]);var n=e(t.children);A[t.tagName].push(n),Object.keys(t.attributes).length&&"string"!==typeof n&&(n._attributes=t.attributes)}})),A)1==A[n].length&&(A[n]=A[n][0]);return A}(Array.isArray(y)?y:[y]):(t.setPos&&(y.pos=A),y)}var pe={315:"Artist",258:"BitsPerSample",265:"CellLength",264:"CellWidth",320:"ColorMap",259:"Compression",33432:"Copyright",306:"DateTime",338:"ExtraSamples",266:"FillOrder",289:"FreeByteCounts",288:"FreeOffsets",291:"GrayResponseCurve",290:"GrayResponseUnit",316:"HostComputer",270:"ImageDescription",257:"ImageLength",256:"ImageWidth",271:"Make",281:"MaxSampleValue",280:"MinSampleValue",272:"Model",254:"NewSubfileType",274:"Orientation",262:"PhotometricInterpretation",284:"PlanarConfiguration",296:"ResolutionUnit",278:"RowsPerStrip",277:"SamplesPerPixel",305:"Software",279:"StripByteCounts",273:"StripOffsets",255:"SubfileType",263:"Threshholding",282:"XResolution",283:"YResolution",326:"BadFaxLines",327:"CleanFaxData",343:"ClipPath",328:"ConsecutiveBadFaxLines",433:"Decode",434:"DefaultImageColor",269:"DocumentName",336:"DotRange",321:"HalftoneHints",346:"Indexed",347:"JPEGTables",285:"PageName",297:"PageNumber",317:"Predictor",319:"PrimaryChromaticities",532:"ReferenceBlackWhite",339:"SampleFormat",340:"SMinSampleValue",341:"SMaxSampleValue",559:"StripRowCounts",330:"SubIFDs",292:"T4Options",293:"T6Options",325:"TileByteCounts",323:"TileLength",324:"TileOffsets",322:"TileWidth",301:"TransferFunction",318:"WhitePoint",344:"XClipPathUnits",286:"XPosition",529:"YCbCrCoefficients",531:"YCbCrPositioning",530:"YCbCrSubSampling",345:"YClipPathUnits",287:"YPosition",37378:"ApertureValue",40961:"ColorSpace",36868:"DateTimeDigitized",36867:"DateTimeOriginal",34665:"Exif IFD",36864:"ExifVersion",33434:"ExposureTime",41728:"FileSource",37385:"Flash",40960:"FlashpixVersion",33437:"FNumber",42016:"ImageUniqueID",37384:"LightSource",37500:"MakerNote",37377:"ShutterSpeedValue",37510:"UserComment",33723:"IPTC",34675:"ICC Profile",700:"XMP",42112:"GDAL_METADATA",42113:"GDAL_NODATA",34377:"Photoshop",33550:"ModelPixelScale",33922:"ModelTiepoint",34264:"ModelTransformation",34735:"GeoKeyDirectory",34736:"GeoDoubleParams",34737:"GeoAsciiParams",50674:"LercParameters"},Ee={};for(var Qe in pe)pe.hasOwnProperty(Qe)&&(Ee[pe[Qe]]=parseInt(Qe,10));var ye=[Ee.BitsPerSample,Ee.ExtraSamples,Ee.SampleFormat,Ee.StripByteCounts,Ee.StripOffsets,Ee.StripRowCounts,Ee.TileByteCounts,Ee.TileOffsets,Ee.SubIFDs],ve={1:"BYTE",2:"ASCII",3:"SHORT",4:"LONG",5:"RATIONAL",6:"SBYTE",7:"UNDEFINED",8:"SSHORT",9:"SLONG",10:"SRATIONAL",11:"FLOAT",12:"DOUBLE",13:"IFD",16:"LONG8",17:"SLONG8",18:"IFD8"},me={};for(var be in ve)ve.hasOwnProperty(be)&&(me[ve[be]]=parseInt(be,10));var we=0,Se=1,Fe=2,Re=3,De=5,Ge=6,ke=8,xe=0,Ne=1,Ue=0,_e=1,Me={1024:"GTModelTypeGeoKey",1025:"GTRasterTypeGeoKey",1026:"GTCitationGeoKey",2048:"GeographicTypeGeoKey",2049:"GeogCitationGeoKey",2050:"GeogGeodeticDatumGeoKey",2051:"GeogPrimeMeridianGeoKey",2052:"GeogLinearUnitsGeoKey",2053:"GeogLinearUnitSizeGeoKey",2054:"GeogAngularUnitsGeoKey",2055:"GeogAngularUnitSizeGeoKey",2056:"GeogEllipsoidGeoKey",2057:"GeogSemiMajorAxisGeoKey",2058:"GeogSemiMinorAxisGeoKey",2059:"GeogInvFlatteningGeoKey",2060:"GeogAzimuthUnitsGeoKey",2061:"GeogPrimeMeridianLongGeoKey",2062:"GeogTOWGS84GeoKey",3072:"ProjectedCSTypeGeoKey",3073:"PCSCitationGeoKey",3074:"ProjectionGeoKey",3075:"ProjCoordTransGeoKey",3076:"ProjLinearUnitsGeoKey",3077:"ProjLinearUnitSizeGeoKey",3078:"ProjStdParallel1GeoKey",3079:"ProjStdParallel2GeoKey",3080:"ProjNatOriginLongGeoKey",3081:"ProjNatOriginLatGeoKey",3082:"ProjFalseEastingGeoKey",3083:"ProjFalseNorthingGeoKey",3084:"ProjFalseOriginLongGeoKey",3085:"ProjFalseOriginLatGeoKey",3086:"ProjFalseOriginEastingGeoKey",3087:"ProjFalseOriginNorthingGeoKey",3088:"ProjCenterLongGeoKey",3089:"ProjCenterLatGeoKey",3090:"ProjCenterEastingGeoKey",3091:"ProjCenterNorthingGeoKey",3092:"ProjScaleAtNatOriginGeoKey",3093:"ProjScaleAtCenterGeoKey",3094:"ProjAzimuthAngleGeoKey",3095:"ProjStraightVertPoleLongGeoKey",3096:"ProjRectifiedGridAngleGeoKey",4096:"VerticalCSTypeGeoKey",4097:"VerticalCitationGeoKey",4098:"VerticalDatumGeoKey",4099:"VerticalUnitsGeoKey"},Oe={};for(var Le in Me)Me.hasOwnProperty(Le)&&(Oe[Me[Le]]=parseInt(Le,10));function Te(e,t){for(var A,n=e.width,r=e.height,i=new Uint8Array(n*r*3),o=0,a=0;o>24)/500+o,s=o-(e[r+2]<<24>>24)/200,g=void 0,c=void 0,u=void 0;c=-.9689*(a=.95047*(a*a*a>.008856?a*a*a:(a-16/116)/7.787))+1.8758*(o=1*(o*o*o>.008856?o*o*o:(o-16/116)/7.787))+.0415*(s=1.08883*(s*s*s>.008856?s*s*s:(s-16/116)/7.787)),u=.0557*a+-.204*o+1.057*s,g=(g=3.2406*a+-1.5372*o+-.4986*s)>.0031308?1.055*Math.pow(g,1/2.4)-.055:12.92*g,c=c>.0031308?1.055*Math.pow(c,1/2.4)-.055:12.92*c,u=u>.0031308?1.055*Math.pow(u,1/2.4)-.055:12.92*u,n[i]=255*Math.max(0,Math.min(1,g)),n[i+1]=255*Math.max(0,Math.min(1,c)),n[i+2]=255*Math.max(0,Math.min(1,u))}return n}function Pe(e,t){var A=e.length-t,n=0;do{for(var r=t;r>0;r--)e[n+t]+=e[n],n++;A-=t}while(A>0)}function Ve(e,t,A){for(var n=0,r=e.length,i=r/A;r>t;){for(var o=t;o>0;--o)e[n+t]+=e[n],++n;r-=t}for(var a=e.slice(),s=0;s=e.byteLength);++g){var c=void 0;if(2===t){switch(r[0]){case 8:c=new Uint8Array(e,g*s*A*a,s*A*a);break;case 16:c=new Uint16Array(e,g*s*A*a,s*A*a/2);break;case 32:c=new Uint32Array(e,g*s*A*a,s*A*a/4);break;default:throw new Error("Predictor 2 not allowed with ".concat(r[0]," bits per sample."))}Pe(c,s)}else 3===t&&Ve(c=new Uint8Array(e,g*s*A*a,s*A*a),s,a)}return e}var We,Xe=function(){function e(){Object(u.a)(this,e)}return Object(l.a)(e,[{key:"decode",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A){var n,r,i,a,s;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.decodeBlock(A);case 2:if(n=e.sent,1===(r=t.Predictor||1)){e.next=9;break}return i=!t.StripOffsets,a=i?t.TileWidth:t.ImageWidth,s=i?t.TileLength:t.RowsPerStrip||t.ImageLength,e.abrupt("return",Ke(n,r,a,s,t.BitsPerSample,t.PlanarConfiguration));case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()}]),e}(),qe=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"decodeBlock",value:function(e){return e}}]),A}(Xe),ze=null;function $e(){return null!==ze&&ze.buffer===We.memory.buffer||(ze=new Uint8Array(We.memory.buffer)),ze}var et=0,tt=null;function At(){return null!==tt&&tt.buffer===We.memory.buffer||(tt=new Int32Array(We.memory.buffer)),tt}function nt(e){return rt.apply(this,arguments)}function rt(){return(rt=Object(a.a)(o.a.mark((function e(t){var A,n,r;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return void 0===t&&(t="".replace(/\.js$/,"_bg.wasm")),("string"==typeof t||"function"==typeof Request&&t instanceof Request||"function"==typeof URL&&t instanceof URL)&&(t=fetch(t)),e.t0=function(){var e=Object(a.a)(o.a.mark((function e(t,A){var n,r;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!("function"==typeof Response&&t instanceof Response)){e.next=19;break}if("function"!=typeof WebAssembly.instantiateStreaming){e.next=13;break}return e.prev=2,e.next=5,WebAssembly.instantiateStreaming(t,A);case 5:return e.abrupt("return",e.sent);case 8:if(e.prev=8,e.t0=e.catch(2),"application/wasm"!=t.headers.get("Content-Type")){e.next=12;break}throw e.t0;case 12:console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e.t0);case 13:return e.next=15,t.arrayBuffer();case 15:return n=e.sent,e.next=18,WebAssembly.instantiate(n,A);case 18:return e.abrupt("return",e.sent);case 19:return e.next=21,WebAssembly.instantiate(t,A);case 21:return r=e.sent,e.abrupt("return",r instanceof WebAssembly.Instance?{instance:r,module:t}:r);case 23:case"end":return e.stop()}}),e,null,[[2,8]])})));return function(t,A){return e.apply(this,arguments)}}(),e.next=5,t;case 5:return e.t1=e.sent,e.t2={},e.next=9,(0,e.t0)(e.t1,e.t2);case 9:return A=e.sent,n=A.instance,r=A.module,e.abrupt("return",(We=n.exports,nt.__wbindgen_wasm_module=r,We));case 13:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var it=Object.freeze({__proto__:null,decompress:function(e,t){try{var A=We.__wbindgen_add_to_stack_pointer(-16),n=function(e,t){var A=t(1*e.length);return $e().set(e,A/1),et=e.length,A}(e,We.__wbindgen_malloc),r=et;We.decompress(A,n,r,t);var i=At()[A/4+0],o=At()[A/4+1],a=(s=i,g=o,$e().subarray(s/1,s/1+g)).slice();return We.__wbindgen_free(i,1*o),a}finally{We.__wbindgen_add_to_stack_pointer(16)}var s,g},default:nt}),ot=[62,0,0,0,63,52,53,54,55,56,57,58,59,60,61,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];function at(e){return ot[e-43]}var st,gt=function(e){for(var t,A=e.endsWith("==")?2:e.endsWith("=")?1:0,n=e.length,r=new Uint8Array(n/4*3),i=0,o=0;i>16,r[o+1]=t>>8&255,r[o+2]=255&t;return r.subarray(0,r.length-A)}("AGFzbQEAAAABWQ5gAn9/AX9gA39/fwF/YAJ/fwBgAX8AYAN/f38AYAF/AX9gBH9/f38AYAR/f39/AX9gBn9/f39/fwBgAX8BfmAAAGAFf39/f38AYAV/f39/fwF/YAJ+fwF/A21sBQgICwMBAgUMAQABAAIABQACAgYGDQYDAgACAAAEBAQCAgYGAAYBBgIHAwQDBAQDAwADBQMDBAQEBAQCAgAHAAQAAgMBAgcFBAIDAQUCAgIDAgIDAwcCAQAABAIACgAAAQAFAgADBQkJCQMCBAUBcAErKwUDAQARBgkBfwFBgIDAAAsHXwUGbWVtb3J5AgAKZGVjb21wcmVzcwAnH19fd2JpbmRnZW5fYWRkX3RvX3N0YWNrX3BvaW50ZXIAYhFfX3diaW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AgBCkDEDcCBAsgACACNgIAIARBQGskAAuuAgEIfyMAQTBrIgEkAEGAICECIAFBGGoQLyABKAIcIQQgASgCGCEFIAFBEGoQMiABKAIUIQYgASgCECEHIAFBCGpBgCBBARBAIAFBgCA2AiggASABKAIMIgg2AiQgASABKAIIIgM2AiAgCEGBIE8EQCABQSBqQYAgEEUgASgCICEDIAEoAighAgsgAEEAOwBHIABBADsBOCAAIAM2AiggACAFNgIQIABBCDoARiAAQQA6AAsgAEIANwMAIABBMGpCADcDACAAQSxqIAI2AgAgAEEkakEANgIAIABBIGogBjYCACAAQRxqIAc2AgAgAEEYakEANgIAIABBFGogBDYCACAAQQk6AAogAEGAAjsBQiAAQYECOwFEIABBggI7AUAgAEH/AzsBCCABQTBqJAALxwICBX8BfiMAQRBrIgMkACAALQALIQIgA0IANwMIIAEoAgAhBQJAAkAgAAJ/IAEoAgQiBEHAACACayIGQfgBcUEDdiICSQRAIARBCU8NAiADQQhqIAUgBBBLGiABQQA2AgQgAUGIg8AANgIAIARBA3QMAQsgBkH/AXFByABPDQIgA0EIaiAFIAIQSxogASAEIAJrNgIEIAEgAiAFajYCACAGQfgBcQsgAC0ACyIBajoACyAAIAApAwAgAykDCCIHQjiGIAdCKIZCgICAgICAwP8Ag4QgB0IYhkKAgICAgOA/gyAHQgiGQoCAgIDwH4OEhCAHQgiIQoCAgPgPgyAHQhiIQoCA/AeDhCAHQiiIQoD+A4MgB0I4iISEhCABQT9xrYiENwMAIANBEGokAA8LIARBCEHYhcAAEDcACyACQQhByIXAABA3AAuqAgEDfyMAQYABayIEJAACQAJAAn8CQCABKAIAIgNBEHFFBEAgACgCACECIANBIHENASACrSABEBUMAgsgACgCACECQQAhAANAIAAgBGpB/wBqIAJBD3EiA0EwciADQdcAaiADQQpJGzoAACAAQX9qIQAgAkEEdiICDQALIABBgAFqIgJBgQFPDQIgAUGkjsAAQQIgACAEakGAAWpBACAAaxAIDAELQQAhAANAIAAgBGpB/wBqIAJBD3EiA0EwciADQTd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EMAAtBgIABQQIQYwALIAAgATYCACAAQYAgNgIEC4YBAQF/IwBBQGoiASQAIAFBKzYCDCABQYCBwAA2AgggAUGsgcAANgIUIAEgADYCECABQSxqQQI2AgAgAUE8akEhNgIAIAFCAjcCHCABQayMwAA2AhggAUEdNgI0IAEgAUEwajYCKCABIAFBEGo2AjggASABQQhqNgIwIAFBGGpB8IDAABBRAAtxAQN/IwBBIGsiAiQAAkAgACABEBkNACABQRxqKAIAIQMgASgCGCACQRxqQQA2AgAgAkHwi8AANgIYIAJCATcCDCACQfSLwAA2AgggAyACQQhqEAkNACAAQQRqIAEQGSACQSBqJAAPCyACQSBqJABBAQswAQF/AkACQEGAwABBAhBZIgENAQwAC0GAwABBAhBjAAsgACABNgIAIABBgCA2AgQLewECfwJAAkAgACgCBCIBBEAgACgCDCICIAFPDQEgACgCACIBIAJqIAEtAAA6AAAgAEEANgIIIAAgACgCDEEBajYCDCAAKAIERQ0CIAAoAgAtAAAPC0EAQQBBiIbAABA2AAsgAiABQZiGwAAQNgALQQBBAEGohsAAEDYAC2gBAn8gACAALQBGIgFBAWoiAjoACiAAQQEgAUEPcXRBAmoiATsBQCAAQX8gAkEPcXRBf3M7AQggAEEYaigCACABQf//A3EiAU8EQCAAIAE2AhgLIABBJGooAgAgAU8EQCAAIAE2AiQLC1ABAX8gAEEUaigCACIBRSABQQJ0RXJFBEAgACgCEBAECyAAQSBqKAIAIgFFIAFBAXRFckUEQCAAKAIcEAQLIABBLGooAgAEQCAAKAIoEAQLC2wBAX8jAEEwayIDJAAgAyABNgIEIAMgADYCACADQRxqQQI2AgAgA0EsakEcNgIAIANCAjcCDCADQYCNwAA2AgggA0EcNgIkIAMgA0EgajYCGCADIAM2AiggAyADQQRqNgIgIANBCGogAhBRAAtsAQF/IwBBMGsiAyQAIAMgATYCBCADIAA2AgAgA0EcakECNgIAIANBLGpBHDYCACADQgI3AgwgA0HMkcAANgIIIANBHDYCJCADIANBIGo2AhggAyADQQRqNgIoIAMgAzYCICADQQhqIAIQUQALbAEBfyMAQTBrIgMkACADIAE2AgQgAyAANgIAIANBHGpBAjYCACADQSxqQRw2AgAgA0ICNwIMIANBgJLAADYCCCADQRw2AiQgAyADQSBqNgIYIAMgA0EEajYCKCADIAM2AiAgA0EIaiACEFEAC2wBAX8jAEEwayIDJAAgAyABNgIEIAMgADYCACADQRxqQQI2AgAgA0EsakEcNgIAIANCAjcCDCADQayRwAA2AgggA0EcNgIkIAMgA0EgajYCGCADIANBBGo2AiggAyADNgIgIANBCGogAhBRAAtcAQF/IwBBEGsiAyQAAkAgACgCBCABayACTwRAIANBADYCAAwBCyADIAAgASACEBYgAygCAEEBRw0AIANBCGooAgAiAARAIAMoAgQgABBjAAsQXQALIANBEGokAAtaAQF/IwBBEGsiAiQAAkAgACgCBCABa0EBTwRAIAJBADYCAAwBCyACIAAgARAeIAIoAgBBAUcNACACQQhqKAIAIgAEQCACKAIEIAAQYwALEF0ACyACQRBqJAALWgEBfyMAQRBrIgIkAAJAIAAoAgQgAWtBAU8EQCACQQA2AgAMAQsgAiAAIAEQHSACKAIAQQFHDQAgAkEIaigCACIABEAgAigCBCAAEGMACxBdAAsgAkEQaiQAC1kBAX8jAEEgayICJAAgAiAAKAIANgIEIAJBGGogAUEQaikCADcDACACQRBqIAFBCGopAgA3AwAgAiABKQIANwMIIAJBBGpB2InAACACQQhqEAkgAkEgaiQAC0YAAkBBCCACSQRAAn9BCCACSQRAIAIgAxAQDAELIAMQAAsiAg0BQQAPCyAAIAMQCg8LIAIgACADIAEgASADSxsQSyAAEAQLWQEBfyMAQSBrIgIkACACIAAoAgA2AgQgAkEYaiABQRBqKQIANwMAIAJBEGogAUEIaikCADcDACACIAEpAgA3AwggAkEEakHwj8AAIAJBCGoQCSACQSBqJAALWQACQAJAAkAgAUF/SgRAAkAgAgRAIAENAQwECyABRQ0DIAFBARBZIgINBAwCCyABEEciAkUNAQwDCxBdAAsgAUEBEGMAC0EBIQILIAAgATYCBCAAIAI2AgALVgEBfyMAQS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AAsgAAsxAQF/IAEoAgQiAgRAIAAgAjYCBCAAQQhqQQE2AgAgACABKAIANgIADwsgAEEANgIACzEBAX8gACABKAIEIAEoAggiAksEfyABIAIQRSABKAIIBSACCzYCBCAAIAEoAgA2AgALKAEBfyAAKAIIIgIgAU8EQCAAKAIAGiAAIAE2AggPCyAAIAEgAmsQKAssAQF/IwBBEGsiASQAIAFBCGogAEEIaigCADYCACABIAApAgA3AwAgARAsAAs0AQF/IwBBEGsiAiQAIAIgATYCDCACIAA2AgggAkG8jMAANgIEIAJB8IvAADYCACACEEoACyEAIAEEQANAIABBADoAACAAQQFqIQAgAUF/aiIBDQALCwsgAQF/AkAgACgCACIBRQ0AIABBBGooAgBFDQAgARAECwsgAQF/AkAgACgCBCIBRQ0AIABBCGooAgBFDQAgARAECwsMACAAIAEgAiADED4LCwAgAQRAIAAQBAsLEgAgACgCACABIAEgAmoQH0EACxQAIAAoAgAgASAAKAIEKAIMEQAACxkAAn9BCCABSQRAIAEgABAQDAELIAAQAAsLEAAgACACNgIEIAAgATYCAAsTACAAQaCLwAA2AgQgACABNgIACxAAIAEgACgCACAAKAIEEAULEQBBzIvAAEERQeCLwAAQSAALDgAgACgCABoDQAwACwALCwAgADUCACABEBULDQAgACgCACABIAIQCwsLACAAMQAAIAEQFQsLACAAIwBqJAAjAAsZACAAIAFB+KbAACgCACIAQQ4gABsRAgAACw0AIAFBxJDAAEECEAULCQAgAEEAOgBHCwcAIAAtAEcLDQBC9Pme5u6jqvn+AAsNAEL3uO76qszV7uUACwwAQunQotvMouq7RgsDAAELAwABCwvfJgEAQYCAwAAL1SYvVXNlcnMvZm04MTMvLnJ1c3R1cC90b29sY2hhaW5zL3N0YWJsZS14ODZfNjQtYXBwbGUtZGFyd2luL2xpYi9ydXN0bGliL3NyYy9ydXN0L2xpYnJhcnkvY29yZS9zcmMvYWxsb2MvbGF5b3V0LnJzAAAQAHAAAAALAQAAOQAAAGNhbGxlZCBgUmVzdWx0Ojp1bndyYXAoKWAg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Nlc3NlZC1ieQMFcnVzdGMdMS40OS4wIChlMTg4NGE4ZTMgMjAyMC0xMi0yOSkGd2FscnVzBjAuMTguMAx3YXNtLWJpbmRnZW4SMC4yLjcwIChiNjM1NWMyNzAp");function ct(e,t){return ut.apply(this,arguments)}function ut(){return(ut=Object(a.a)(o.a.mark((function e(t,A){var n;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=st,e.t0){e.next=5;break}return e.next=4,Object(a.a)(o.a.mark((function e(){return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,nt(gt);case 2:return e.abrupt("return",it);case 3:case"end":return e.stop()}}),e)})))();case 4:st=e.sent;case 5:if(0!==(n=st.decompress(t,A)).length){e.next=8;break}throw Error("Failed to decode with LZW decoder.");case 8:return e.abrupt("return",n);case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var lt=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(e){var n;Object(u.a)(this,A),n=t.call(this);var r=e.TileWidth||e.ImageWidth,i=e.TileLength||e.ImageLength,o=e.BitsPerSample[0]/8;return n.maxUncompressedSize=r*i*o,n}return Object(l.a)(A,[{key:"decodeBlock",value:function(){var e=Object(a.a)(o.a.mark((function e(t){var A,n;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=new Uint8Array(t),e.next=3,ct(A,this.maxUncompressedSize);case 3:return n=e.sent,e.abrupt("return",n.buffer);case 5:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()}]),A}(Xe),It=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]);function Ct(e,t){for(var A=0,n=[],r=16;r>0&&!e[r-1];)--r;n.push({children:[],index:0});for(var i,o=n[0],a=0;a0;)o=n.pop();for(o.index++,n.push(o);n.length<=a;)n.push(i={children:[],index:0}),o.children[o.index]=i.children,o=i;A++}a+10)return C--,I>>C&1;if(255===(I=e[l++])){var t=e[l++];if(t)throw new Error("unexpected marker: ".concat((I<<8|t).toString(16)))}return C=7,I>>>7}function f(e){for(var t,A=e;null!==(t=h());){if("number"===typeof(A=A[t]))return A;if("object"!==typeof A)throw new Error("invalid huffman sequence")}return null}function d(e){for(var t=e,A=0;t>0;){var n=h();if(null===n)return;A=A<<1|n,--t}return A}function B(e){var t=d(e);return t>=1<0)p--;else for(var A=i,n=o;A<=n;){var r=f(e.huffmanTableAC),a=15&r,g=r>>4;if(0===a){if(g<15){p=d(g)+(1<>4,0===u)r<15?(p=d(r)+(1<>4;if(0===o){if(a<15)break;r+=16}else{t[It[r+=a]]=B(o),r++}}};var G,k,x=0;k=1===D?n[0].blocksPerLine*n[0].blocksPerColumn:g*A.mcusPerColumn;for(var N=r||k;x=65488&&G<=65495))break;l+=2}return l-u}function ft(e,t){var A=[],n=t.blocksPerLine,r=t.blocksPerColumn,i=n<<3,o=new Int32Array(64),a=new Uint8Array(64);function s(e,A,n){var r,i,o,a,s,g,c,u,l,I,C=t.quantizationTable,h=n;for(I=0;I<64;I++)h[I]=e[I]*C[I];for(I=0;I<8;++I){var f=8*I;0!==h[1+f]||0!==h[2+f]||0!==h[3+f]||0!==h[4+f]||0!==h[5+f]||0!==h[6+f]||0!==h[7+f]?(r=5793*h[0+f]+128>>8,i=5793*h[4+f]+128>>8,o=h[2+f],a=h[6+f],s=2896*(h[1+f]-h[7+f])+128>>8,u=2896*(h[1+f]+h[7+f])+128>>8,g=h[3+f]<<4,l=r-i+1>>1,r=r+i+1>>1,i=l,l=3784*o+1567*a+128>>8,o=1567*o-3784*a+128>>8,a=l,l=s-(c=h[5+f]<<4)+1>>1,s=s+c+1>>1,c=l,l=u+g+1>>1,g=u-g+1>>1,u=l,l=r-a+1>>1,r=r+a+1>>1,a=l,l=i-o+1>>1,i=i+o+1>>1,o=l,l=2276*s+3406*u+2048>>12,s=3406*s-2276*u+2048>>12,u=l,l=799*g+4017*c+2048>>12,g=4017*g-799*c+2048>>12,c=l,h[0+f]=r+u,h[7+f]=r-u,h[1+f]=i+c,h[6+f]=i-c,h[2+f]=o+g,h[5+f]=o-g,h[3+f]=a+s,h[4+f]=a-s):(l=5793*h[0+f]+512>>10,h[0+f]=l,h[1+f]=l,h[2+f]=l,h[3+f]=l,h[4+f]=l,h[5+f]=l,h[6+f]=l,h[7+f]=l)}for(I=0;I<8;++I){var d=I;0!==h[8+d]||0!==h[16+d]||0!==h[24+d]||0!==h[32+d]||0!==h[40+d]||0!==h[48+d]||0!==h[56+d]?(r=5793*h[0+d]+2048>>12,i=5793*h[32+d]+2048>>12,o=h[16+d],a=h[48+d],s=2896*(h[8+d]-h[56+d])+2048>>12,u=2896*(h[8+d]+h[56+d])+2048>>12,g=h[24+d],l=r-i+1>>1,r=r+i+1>>1,i=l,l=3784*o+1567*a+2048>>12,o=1567*o-3784*a+2048>>12,a=l,l=s-(c=h[40+d])+1>>1,s=s+c+1>>1,c=l,l=u+g+1>>1,g=u-g+1>>1,u=l,l=r-a+1>>1,r=r+a+1>>1,a=l,l=i-o+1>>1,i=i+o+1>>1,o=l,l=2276*s+3406*u+2048>>12,s=3406*s-2276*u+2048>>12,u=l,l=799*g+4017*c+2048>>12,g=4017*g-799*c+2048>>12,c=l,h[0+d]=r+u,h[56+d]=r-u,h[8+d]=i+c,h[48+d]=i-c,h[16+d]=o+g,h[40+d]=o-g,h[24+d]=a+s,h[32+d]=a-s):(l=5793*n[I+0]+8192>>14,h[0+d]=l,h[8+d]=l,h[16+d]=l,h[24+d]=l,h[32+d]=l,h[40+d]=l,h[48+d]=l,h[56+d]=l)}for(I=0;I<64;++I){var B=128+(h[I]+8>>4);A[I]=B<0?0:B>255?255:B}}for(var g=0;g>4===0)for(var c=0;c<64;c++){g[It[c]]=e[t++]}else{if(s>>4!==1)throw new Error("DQT: invalid table spec");for(var u=0;u<64;u++){g[It[u]]=A()}}this.quantizationTables[15&s]=g}break;case 65472:case 65473:case 65474:A();for(var l={extended:65473===i,progressive:65474===i,precision:e[t++],scanLines:A(),samplesPerLine:A(),components:{},componentsOrder:[]},I=e[t++],C=void 0,h=0;h>4,d=15&e[t+1],B=e[t+2];l.componentsOrder.push(C),l.components[C]={h:f,v:d,quantizationIdx:B},t+=3}r(l),this.frames.push(l);break;case 65476:for(var p=A(),E=2;E>4===0?this.huffmanTablesDC[15&Q]=Ct(y,b):this.huffmanTablesAC[15&Q]=Ct(y,b)}break;case 65501:A(),this.resetInterval=A();break;case 65498:A();for(var S=e[t++],F=[],R=this.frames[0],D=0;D>4],G.huffmanTableAC=this.huffmanTablesAC[15&k],F.push(G)}var x=e[t++],N=e[t++],U=e[t++],_=ht(e,t,R,F,this.resetInterval,x,N,U>>4,15&U);t+=_;break;case 65535:255!==e[t]&&t--;break;default:if(255===e[t-3]&&e[t-2]>=192&&e[t-2]<=254){t-=3;break}throw new Error("unknown JPEG marker ".concat(i.toString(16)))}i=A()}}},{key:"getResult",value:function(){var e=this.frames;if(0===this.frames.length)throw new Error("no frames were decoded");this.frames.length>1&&console.warn("more than one frame is not supported");for(var t=0;t=0;)e[t]=0}var Et=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Qt=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),yt=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),vt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),mt=new Array(576);pt(mt);var bt=new Array(60);pt(bt);var wt=new Array(512);pt(wt);var St=new Array(256);pt(St);var Ft=new Array(29);pt(Ft);var Rt,Dt,Gt,kt=new Array(30);function xt(e,t,A,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=A,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}function Nt(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}pt(kt);var Ut=function(e){return e<256?wt[e]:wt[256+(e>>>7)]},_t=function(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},Mt=function(e,t,A){e.bi_valid>16-A?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=A-16):(e.bi_buf|=t<>>=1,A<<=1}while(--t>0);return A>>>1},Tt=function(e,t,A){var n,r,i=new Array(16),o=0;for(n=1;n<=15;n++)i[n]=o=o+A[n-1]<<1;for(r=0;r<=t;r++){var a=e[2*r+1];0!==a&&(e[2*r]=Lt(i[a]++,a))}},Zt=function(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0},Ht=function(e){e.bi_valid>8?_t(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},Yt=function(e,t,A,n){var r=2*t,i=2*A;return e[r]>1;A>=1;A--)Jt(e,i,A);r=s;do{A=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Jt(e,i,1),n=e.heap[1],e.heap[--e.heap_max]=A,e.heap[--e.heap_max]=n,i[2*r]=i[2*A]+i[2*n],e.depth[r]=(e.depth[A]>=e.depth[n]?e.depth[A]:e.depth[n])+1,i[2*A+1]=i[2*n+1]=r,e.heap[1]=r++,Jt(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var A,n,r,i,o,a,s=t.dyn_tree,g=t.max_code,c=t.stat_desc.static_tree,u=t.stat_desc.has_stree,l=t.stat_desc.extra_bits,I=t.stat_desc.extra_base,C=t.stat_desc.max_length,h=0;for(i=0;i<=15;i++)e.bl_count[i]=0;for(s[2*e.heap[e.heap_max]+1]=0,A=e.heap_max+1;A<573;A++)(i=s[2*s[2*(n=e.heap[A])+1]+1]+1)>C&&(i=C,h++),s[2*n+1]=i,n>g||(e.bl_count[i]++,o=0,n>=I&&(o=l[n-I]),a=s[2*n],e.opt_len+=a*(i+o),u&&(e.static_len+=a*(c[2*n+1]+o)));if(0!==h){do{for(i=C-1;0===e.bl_count[i];)i--;e.bl_count[i]--,e.bl_count[i+1]+=2,e.bl_count[C]--,h-=2}while(h>0);for(i=C;0!==i;i--)for(n=e.bl_count[i];0!==n;)(r=e.heap[--A])>g||(s[2*r+1]!==i&&(e.opt_len+=(i-s[2*r+1])*s[2*r],s[2*r+1]=i),n--)}}(e,t),Tt(i,g,e.bl_count)},Vt=function(e,t,A){var n,r,i=-1,o=t[1],a=0,s=7,g=4;for(0===o&&(s=138,g=3),t[2*(A+1)+1]=65535,n=0;n<=A;n++)r=o,o=t[2*(n+1)+1],++a>=7;n<30;n++)for(kt[n]=r<<7,e=0;e<1<0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,A=4093624447;for(t=0;t<=31;t++,A>>>=1)if(1&A&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),Pt(e,e.l_desc),Pt(e,e.d_desc),o=function(e){var t;for(Vt(e,e.dyn_ltree,e.l_desc.max_code),Vt(e,e.dyn_dtree,e.d_desc.max_code),Pt(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*vt[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(i=e.static_len+3+7>>>3)<=r&&(r=i)):r=i=A+5,A+4<=r&&-1!==t?Xt(e,t,A,n):4===e.strategy||i===r?(Mt(e,2+(n?1:0),3),jt(e,mt,bt)):(Mt(e,4+(n?1:0),3),function(e,t,A,n){var r;for(Mt(e,t-257,5),Mt(e,A-1,5),Mt(e,n-4,4),r=0;r>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&A,e.last_lit++,0===t?e.dyn_ltree[2*A]++:(e.matches++,t--,e.dyn_ltree[2*(St[A]+256+1)]++,e.dyn_dtree[2*Ut(t)]++),e.last_lit===e.lit_bufsize-1},_tr_align:function(e){Mt(e,2,3),Ot(e,256,mt),function(e){16===e.bi_valid?(_t(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},zt=function(e,t,A,n){for(var r=65535&e|0,i=e>>>16&65535|0,o=0;0!==A;){A-=o=A>2e3?2e3:A;do{i=i+(r=r+t[n++]|0)|0}while(--o);r%=65521,i%=65521}return r|i<<16|0},$t=new Uint32Array(function(){for(var e,t=[],A=0;A<256;A++){e=A;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[A]=e}return t}()),eA=function(e,t,A,n){var r=$t,i=n+A;e^=-1;for(var o=n;o>>8^r[255&(e^t[o])];return-1^e},tA={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},AA={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},nA=qt._tr_init,rA=qt._tr_stored_block,iA=qt._tr_flush_block,oA=qt._tr_tally,aA=qt._tr_align,sA=AA.Z_NO_FLUSH,gA=AA.Z_PARTIAL_FLUSH,cA=AA.Z_FULL_FLUSH,uA=AA.Z_FINISH,lA=AA.Z_BLOCK,IA=AA.Z_OK,CA=AA.Z_STREAM_END,hA=AA.Z_STREAM_ERROR,fA=AA.Z_DATA_ERROR,dA=AA.Z_BUF_ERROR,BA=AA.Z_DEFAULT_COMPRESSION,pA=AA.Z_FILTERED,EA=AA.Z_HUFFMAN_ONLY,QA=AA.Z_RLE,yA=AA.Z_FIXED,vA=AA.Z_DEFAULT_STRATEGY,mA=AA.Z_UNKNOWN,bA=AA.Z_DEFLATED,wA=function(e,t){return e.msg=tA[t],t},SA=function(e){return(e<<1)-(e>4?9:0)},FA=function(e){for(var t=e.length;--t>=0;)e[t]=0},RA=function(e,t,A){return(t<e.avail_out&&(A=e.avail_out),0!==A&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+A),e.next_out),e.next_out+=A,t.pending_out+=A,e.total_out+=A,e.avail_out-=A,t.pending-=A,0===t.pending&&(t.pending_out=0))},GA=function(e,t){iA(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,DA(e.strm)},kA=function(e,t){e.pending_buf[e.pending++]=t},xA=function(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},NA=function(e,t,A,n){var r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),A),1===e.state.wrap?e.adler=zt(e.adler,t,r,A):2===e.state.wrap&&(e.adler=eA(e.adler,t,r,A)),e.next_in+=r,e.total_in+=r,r)},UA=function(e,t){var A,n,r=e.max_chain_length,i=e.strstart,o=e.prev_length,a=e.nice_match,s=e.strstart>e.w_size-262?e.strstart-(e.w_size-262):0,g=e.window,c=e.w_mask,u=e.prev,l=e.strstart+258,I=g[i+o-1],C=g[i+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(g[(A=t)+o]===C&&g[A+o-1]===I&&g[A]===g[i]&&g[++A]===g[i+1]){i+=2,A++;do{}while(g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&io){if(e.match_start=t,o=n,n>=a)break;I=g[i+o-1],C=g[i+o]}}}while((t=u[t&c])>s&&0!==--r);return o<=e.lookahead?o:e.lookahead},_A=function(e){var t,A,n,r,i,o=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=o+(o-262)){e.window.set(e.window.subarray(o,o+o),0),e.match_start-=o,e.strstart-=o,e.block_start-=o,t=A=e.hash_size;do{n=e.head[--t],e.head[t]=n>=o?n-o:0}while(--A);t=A=o;do{n=e.prev[--t],e.prev[t]=n>=o?n-o:0}while(--A);r+=o}if(0===e.strm.avail_in)break;if(A=NA(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=A,e.lookahead+e.insert>=3)for(i=e.strstart-e.insert,e.ins_h=e.window[i],e.ins_h=RA(e,e.ins_h,e.window[i+1]);e.insert&&(e.ins_h=RA(e,e.ins_h,e.window[i+3-1]),e.prev[i&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=i,i++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<262&&0!==e.strm.avail_in)},MA=function(e,t){for(var A,n;;){if(e.lookahead<262){if(_A(e),e.lookahead<262&&t===sA)return 1;if(0===e.lookahead)break}if(A=0,e.lookahead>=3&&(e.ins_h=RA(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==A&&e.strstart-A<=e.w_size-262&&(e.match_length=UA(e,A)),e.match_length>=3)if(n=oA(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=RA(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=RA(e,e.ins_h,e.window[e.strstart+1]);else n=oA(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(GA(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===uA?(GA(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(GA(e,!1),0===e.strm.avail_out)?1:2},OA=function(e,t){for(var A,n,r;;){if(e.lookahead<262){if(_A(e),e.lookahead<262&&t===sA)return 1;if(0===e.lookahead)break}if(A=0,e.lookahead>=3&&(e.ins_h=RA(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==A&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=oA(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=RA(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(GA(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((n=oA(e,0,e.window[e.strstart-1]))&&GA(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=oA(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===uA?(GA(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(GA(e,!1),0===e.strm.avail_out)?1:2};function LA(e,t,A,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=A,this.max_chain=n,this.func=r}var TA=[new LA(0,0,0,0,(function(e,t){var A=65535;for(A>e.pending_buf_size-5&&(A=e.pending_buf_size-5);;){if(e.lookahead<=1){if(_A(e),0===e.lookahead&&t===sA)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+A;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,GA(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-262&&(GA(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===uA?(GA(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(GA(e,!1),e.strm.avail_out),1)})),new LA(4,4,8,4,MA),new LA(4,5,16,8,MA),new LA(4,6,32,32,MA),new LA(4,4,16,16,OA),new LA(8,16,32,32,OA),new LA(8,16,128,128,OA),new LA(8,32,128,256,OA),new LA(32,128,258,1024,OA),new LA(32,258,258,4096,OA)];function ZA(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=bA,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),FA(this.dyn_ltree),FA(this.dyn_dtree),FA(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),FA(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),FA(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var HA=function(e){if(!e||!e.state)return wA(e,hA);e.total_in=e.total_out=0,e.data_type=mA;var t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:113,e.adler=2===t.wrap?0:1,t.last_flush=sA,nA(t),IA},YA=function(e){var t,A=HA(e);return A===IA&&((t=e.state).window_size=2*t.w_size,FA(t.head),t.max_lazy_match=TA[t.level].max_lazy,t.good_match=TA[t.level].good_length,t.nice_match=TA[t.level].nice_length,t.max_chain_length=TA[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),A},JA=function(e,t,A,n,r,i){if(!e)return hA;var o=1;if(t===BA&&(t=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),r<1||r>9||A!==bA||n<8||n>15||t<0||t>9||i<0||i>yA)return wA(e,hA);8===n&&(n=9);var a=new ZA;return e.state=a,a.strm=e,a.wrap=o,a.gzhead=null,a.w_bits=n,a.w_size=1<lA||t<0)return e?wA(e,hA):hA;var r=e.state;if(!e.output||!e.input&&0!==e.avail_in||666===r.status&&t!==uA)return wA(e,0===e.avail_out?dA:hA);r.strm=e;var i=r.last_flush;if(r.last_flush=t,42===r.status)if(2===r.wrap)e.adler=0,kA(r,31),kA(r,139),kA(r,8),r.gzhead?(kA(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),kA(r,255&r.gzhead.time),kA(r,r.gzhead.time>>8&255),kA(r,r.gzhead.time>>16&255),kA(r,r.gzhead.time>>24&255),kA(r,9===r.level?2:r.strategy>=EA||r.level<2?4:0),kA(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(kA(r,255&r.gzhead.extra.length),kA(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=eA(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69):(kA(r,0),kA(r,0),kA(r,0),kA(r,0),kA(r,0),kA(r,9===r.level?2:r.strategy>=EA||r.level<2?4:0),kA(r,3),r.status=113);else{var o=bA+(r.w_bits-8<<4)<<8;o|=(r.strategy>=EA||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(o|=32),o+=31-o%31,r.status=113,xA(r,o),0!==r.strstart&&(xA(r,e.adler>>>16),xA(r,65535&e.adler)),e.adler=1}if(69===r.status)if(r.gzhead.extra){for(A=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>A&&(e.adler=eA(e.adler,r.pending_buf,r.pending-A,A)),DA(e),A=r.pending,r.pending!==r.pending_buf_size));)kA(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>A&&(e.adler=eA(e.adler,r.pending_buf,r.pending-A,A)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=73)}else r.status=73;if(73===r.status)if(r.gzhead.name){A=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>A&&(e.adler=eA(e.adler,r.pending_buf,r.pending-A,A)),DA(e),A=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindexA&&(e.adler=eA(e.adler,r.pending_buf,r.pending-A,A)),0===n&&(r.gzindex=0,r.status=91)}else r.status=91;if(91===r.status)if(r.gzhead.comment){A=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>A&&(e.adler=eA(e.adler,r.pending_buf,r.pending-A,A)),DA(e),A=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindexA&&(e.adler=eA(e.adler,r.pending_buf,r.pending-A,A)),0===n&&(r.status=103)}else r.status=103;if(103===r.status&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&DA(e),r.pending+2<=r.pending_buf_size&&(kA(r,255&e.adler),kA(r,e.adler>>8&255),e.adler=0,r.status=113)):r.status=113),0!==r.pending){if(DA(e),0===e.avail_out)return r.last_flush=-1,IA}else if(0===e.avail_in&&SA(t)<=SA(i)&&t!==uA)return wA(e,dA);if(666===r.status&&0!==e.avail_in)return wA(e,dA);if(0!==e.avail_in||0!==r.lookahead||t!==sA&&666!==r.status){var a=r.strategy===EA?function(e,t){for(var A;;){if(0===e.lookahead&&(_A(e),0===e.lookahead)){if(t===sA)return 1;break}if(e.match_length=0,A=oA(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,A&&(GA(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===uA?(GA(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(GA(e,!1),0===e.strm.avail_out)?1:2}(r,t):r.strategy===QA?function(e,t){for(var A,n,r,i,o=e.window;;){if(e.lookahead<=258){if(_A(e),e.lookahead<=258&&t===sA)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(n=o[r=e.strstart-1])===o[++r]&&n===o[++r]&&n===o[++r]){i=e.strstart+258;do{}while(n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(A=oA(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(A=oA(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),A&&(GA(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===uA?(GA(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(GA(e,!1),0===e.strm.avail_out)?1:2}(r,t):TA[r.level].func(r,t);if(3!==a&&4!==a||(r.status=666),1===a||3===a)return 0===e.avail_out&&(r.last_flush=-1),IA;if(2===a&&(t===gA?aA(r):t!==lA&&(rA(r,0,0,!1),t===cA&&(FA(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),DA(e),0===e.avail_out))return r.last_flush=-1,IA}return t!==uA?IA:r.wrap<=0?CA:(2===r.wrap?(kA(r,255&e.adler),kA(r,e.adler>>8&255),kA(r,e.adler>>16&255),kA(r,e.adler>>24&255),kA(r,255&e.total_in),kA(r,e.total_in>>8&255),kA(r,e.total_in>>16&255),kA(r,e.total_in>>24&255)):(xA(r,e.adler>>>16),xA(r,65535&e.adler)),DA(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?IA:CA)},deflateEnd:function(e){if(!e||!e.state)return hA;var t=e.state.status;return 42!==t&&69!==t&&73!==t&&91!==t&&103!==t&&113!==t&&666!==t?wA(e,hA):(e.state=null,113===t?wA(e,fA):IA)},deflateSetDictionary:function(e,t){var A=t.length;if(!e||!e.state)return hA;var n=e.state,r=n.wrap;if(2===r||1===r&&42!==n.status||n.lookahead)return hA;if(1===r&&(e.adler=zt(e.adler,t,A,0)),n.wrap=0,A>=n.w_size){0===r&&(FA(n.head),n.strstart=0,n.block_start=0,n.insert=0);var i=new Uint8Array(n.w_size);i.set(t.subarray(A-n.w_size,A),0),t=i,A=n.w_size}var o=e.avail_in,a=e.next_in,s=e.input;for(e.avail_in=A,e.next_in=0,e.input=t,_A(n);n.lookahead>=3;){var g=n.strstart,c=n.lookahead-2;do{n.ins_h=RA(n,n.ins_h,n.window[g+3-1]),n.prev[g&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=g,g++}while(--c);n.strstart=g,n.lookahead=2,_A(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=a,e.input=s,e.avail_in=o,n.wrap=r,IA},deflateInfo:"pako deflate (from Nodeca project)"},PA=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},VA=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var A=t.shift();if(A){if("object"!==typeof A)throw new TypeError(A+"must be non-object");for(var n in A)PA(A,n)&&(e[n]=A[n])}}return e},KA=function(e){for(var t=0,A=0,n=e.length;A=252?6:qA>=248?5:qA>=240?4:qA>=224?3:qA>=192?2:1;XA[254]=XA[254]=1;var zA=function(e){if("function"===typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);var t,A,n,r,i,o=e.length,a=0;for(r=0;r>>6,t[i++]=128|63&A):A<65536?(t[i++]=224|A>>>12,t[i++]=128|A>>>6&63,t[i++]=128|63&A):(t[i++]=240|A>>>18,t[i++]=128|A>>>12&63,t[i++]=128|A>>>6&63,t[i++]=128|63&A);return t},$A=function(e,t){var A,n,r=t||e.length;if("function"===typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));var i=new Array(2*r);for(n=0,A=0;A4)i[n++]=65533,A+=a-1;else{for(o&=2===a?31:3===a?15:7;a>1&&A1?i[n++]=65533:o<65536?i[n++]=o:(o-=65536,i[n++]=55296|o>>10&1023,i[n++]=56320|1023&o)}}}return function(e,t){if(t<65534&&e.subarray&&WA)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));for(var A="",n=0;ne.length&&(t=e.length);for(var A=t-1;A>=0&&128===(192&e[A]);)A--;return A<0||0===A?t:A+XA[e[A]]>t?A:t};var tn=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},An=Object.prototype.toString,nn=AA.Z_NO_FLUSH,rn=AA.Z_SYNC_FLUSH,on=AA.Z_FULL_FLUSH,an=AA.Z_FINISH,sn=AA.Z_OK,gn=AA.Z_STREAM_END,cn=AA.Z_DEFAULT_COMPRESSION,un=AA.Z_DEFAULT_STRATEGY,ln=AA.Z_DEFLATED;function In(e){this.options=VA({level:cn,method:ln,chunkSize:16384,windowBits:15,memLevel:8,strategy:un},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new tn,this.strm.avail_out=0;var A=jA.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(A!==sn)throw new Error(tA[A]);if(t.header&&jA.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(n="string"===typeof t.dictionary?zA(t.dictionary):"[object ArrayBuffer]"===An.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(A=jA.deflateSetDictionary(this.strm,n))!==sn)throw new Error(tA[A]);this._dict_set=!0}}In.prototype.push=function(e,t){var A,n,r=this.strm,i=this.options.chunkSize;if(this.ended)return!1;for(n=t===~~t?t:!0===t?an:nn,"string"===typeof e?r.input=zA(e):"[object ArrayBuffer]"===An.call(e)?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;;)if(0===r.avail_out&&(r.output=new Uint8Array(i),r.next_out=0,r.avail_out=i),(n===rn||n===on)&&r.avail_out<=6)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else{if((A=jA.deflate(r,n))===gn)return r.next_out>0&&this.onData(r.output.subarray(0,r.next_out)),A=jA.deflateEnd(this.strm),this.onEnd(A),this.ended=!0,A===sn;if(0!==r.avail_out){if(n>0&&r.next_out>0)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else if(0===r.avail_in)break}else this.onData(r.output)}return!0},In.prototype.onData=function(e){this.chunks.push(e)},In.prototype.onEnd=function(e){e===sn&&(this.result=KA(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Cn=function(e,t){var A,n,r,i,o,a,s,g,c,u,l,I,C,h,f,d,B,p,E,Q,y,v,m,b,w=e.state;A=e.next_in,m=e.input,n=A+(e.avail_in-5),r=e.next_out,b=e.output,i=r-(t-e.avail_out),o=r+(e.avail_out-257),a=w.dmax,s=w.wsize,g=w.whave,c=w.wnext,u=w.window,l=w.hold,I=w.bits,C=w.lencode,h=w.distcode,f=(1<>>=p=B>>>24,I-=p,0===(p=B>>>16&255))b[r++]=65535&B;else{if(!(16&p)){if(0===(64&p)){B=C[(65535&B)+(l&(1<>>=p,I-=p),I<15&&(l+=m[A++]<>>=p=B>>>24,I-=p,!(16&(p=B>>>16&255))){if(0===(64&p)){B=h[(65535&B)+(l&(1<a){e.msg="invalid distance too far back",w.mode=30;break e}if(l>>>=p,I-=p,Q>(p=r-i)){if((p=Q-p)>g&&w.sane){e.msg="invalid distance too far back",w.mode=30;break e}if(y=0,v=u,0===c){if(y+=s-p,p2;)b[r++]=v[y++],b[r++]=v[y++],b[r++]=v[y++],E-=3;E&&(b[r++]=v[y++],E>1&&(b[r++]=v[y++]))}else{y=r-Q;do{b[r++]=b[y++],b[r++]=b[y++],b[r++]=b[y++],E-=3}while(E>2);E&&(b[r++]=b[y++],E>1&&(b[r++]=b[y++]))}break}}break}}while(A>3,l&=(1<<(I-=E<<3))-1,e.next_in=A,e.next_out=r,e.avail_in=A=1&&0===D[Q];Q--);if(y>Q&&(y=Q),0===Q)return r[i++]=20971520,r[i++]=20971520,a.bits=1,0;for(E=1;E0&&(0===e||1!==Q))return-1;for(G[1]=0,B=1;B<15;B++)G[B+1]=G[B]+D[B];for(p=0;p852||2===e&&w>592)return 1;for(;;){C=B-m,o[p]I?(h=k[x+o[p]],f=F[R+o[p]]):(h=96,f=0),s=1<>m)+(g-=s)]=C<<24|h<<16|f|0}while(0!==g);for(s=1<>=1;if(0!==s?(S&=s-1,S+=s):S=0,p++,0===--D[B]){if(B===Q)break;B=t[A+o[p]]}if(B>y&&(S&u)!==c){for(0===m&&(m=y),l+=E,b=1<<(v=B-m);v+m852||2===e&&w>592)return 1;r[c=S&u]=y<<24|v<<16|l-i|0}}return 0!==S&&(r[l+S]=B-m<<24|64<<16|0),a.bits=y,0},En=AA.Z_FINISH,Qn=AA.Z_BLOCK,yn=AA.Z_TREES,vn=AA.Z_OK,mn=AA.Z_STREAM_END,bn=AA.Z_NEED_DICT,wn=AA.Z_STREAM_ERROR,Sn=AA.Z_DATA_ERROR,Fn=AA.Z_MEM_ERROR,Rn=AA.Z_BUF_ERROR,Dn=AA.Z_DEFLATED,Gn=function(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)};function kn(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var xn,Nn,Un=function(e){if(!e||!e.state)return wn;var t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,vn},_n=function(e){if(!e||!e.state)return wn;var t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Un(e)},Mn=function(e,t){var A;if(!e||!e.state)return wn;var n=e.state;return t<0?(A=0,t=-t):(A=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?wn:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=A,n.wbits=t,_n(e))},On=function(e,t){if(!e)return wn;var A=new kn;e.state=A,A.window=null;var n=Mn(e,t);return n!==vn&&(e.state=null),n},Ln=!0,Tn=function(e){if(Ln){xn=new Int32Array(512),Nn=new Int32Array(32);for(var t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(pn(1,e.lens,0,288,xn,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;pn(2,e.lens,0,32,Nn,0,e.work,{bits:5}),Ln=!1}e.lencode=xn,e.lenbits=9,e.distcode=Nn,e.distbits=5},Zn=function(e,t,A,n){var r,i=e.state;return null===i.window&&(i.wsize=1<=i.wsize?(i.window.set(t.subarray(A-i.wsize,A),0),i.wnext=0,i.whave=i.wsize):((r=i.wsize-i.wnext)>n&&(r=n),i.window.set(t.subarray(A-n,A-n+r),i.wnext),(n-=r)?(i.window.set(t.subarray(A-n,A),0),i.wnext=n,i.whave=i.wsize):(i.wnext+=r,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,A.check=eA(A.check,S,2,0),g=0,c=0,A.mode=2;break}if(A.flags=0,A.head&&(A.head.done=!1),!(1&A.wrap)||(((255&g)<<8)+(g>>8))%31){e.msg="incorrect header check",A.mode=30;break}if((15&g)!==Dn){e.msg="unknown compression method",A.mode=30;break}if(c-=4,y=8+(15&(g>>>=4)),0===A.wbits)A.wbits=y;else if(y>A.wbits){e.msg="invalid window size",A.mode=30;break}A.dmax=1<>8&1),512&A.flags&&(S[0]=255&g,S[1]=g>>>8&255,A.check=eA(A.check,S,2,0)),g=0,c=0,A.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,g+=n[i++]<>>8&255,S[2]=g>>>16&255,S[3]=g>>>24&255,A.check=eA(A.check,S,4,0)),g=0,c=0,A.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,g+=n[i++]<>8),512&A.flags&&(S[0]=255&g,S[1]=g>>>8&255,A.check=eA(A.check,S,2,0)),g=0,c=0,A.mode=5;case 5:if(1024&A.flags){for(;c<16;){if(0===a)break e;a--,g+=n[i++]<>>8&255,A.check=eA(A.check,S,2,0)),g=0,c=0}else A.head&&(A.head.extra=null);A.mode=6;case 6:if(1024&A.flags&&((I=A.length)>a&&(I=a),I&&(A.head&&(y=A.head.extra_len-A.length,A.head.extra||(A.head.extra=new Uint8Array(A.head.extra_len)),A.head.extra.set(n.subarray(i,i+I),y)),512&A.flags&&(A.check=eA(A.check,n,I,i)),a-=I,i+=I,A.length-=I),A.length))break e;A.length=0,A.mode=7;case 7:if(2048&A.flags){if(0===a)break e;I=0;do{y=n[i+I++],A.head&&y&&A.length<65536&&(A.head.name+=String.fromCharCode(y))}while(y&&I>9&1,A.head.done=!0),e.adler=A.check=0,A.mode=12;break;case 10:for(;c<32;){if(0===a)break e;a--,g+=n[i++]<>>=7&c,c-=7&c,A.mode=27;break}for(;c<3;){if(0===a)break e;a--,g+=n[i++]<>>=1)){case 0:A.mode=14;break;case 1:if(Tn(A),A.mode=20,t===yn){g>>>=2,c-=2;break e}break;case 2:A.mode=17;break;case 3:e.msg="invalid block type",A.mode=30}g>>>=2,c-=2;break;case 14:for(g>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,g+=n[i++]<>>16^65535)){e.msg="invalid stored block lengths",A.mode=30;break}if(A.length=65535&g,g=0,c=0,A.mode=15,t===yn)break e;case 15:A.mode=16;case 16:if(I=A.length){if(I>a&&(I=a),I>s&&(I=s),0===I)break e;r.set(n.subarray(i,i+I),o),a-=I,i+=I,s-=I,o+=I,A.length-=I;break}A.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,g+=n[i++]<>>=5,c-=5,A.ndist=1+(31&g),g>>>=5,c-=5,A.ncode=4+(15&g),g>>>=4,c-=4,A.nlen>286||A.ndist>30){e.msg="too many length or distance symbols",A.mode=30;break}A.have=0,A.mode=18;case 18:for(;A.have>>=3,c-=3}for(;A.have<19;)A.lens[F[A.have++]]=0;if(A.lencode=A.lendyn,A.lenbits=7,m={bits:A.lenbits},v=pn(0,A.lens,0,19,A.lencode,0,A.work,m),A.lenbits=m.bits,v){e.msg="invalid code lengths set",A.mode=30;break}A.have=0,A.mode=19;case 19:for(;A.have>>16&255,B=65535&w,!((f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>>=f,c-=f,A.lens[A.have++]=B;else{if(16===B){for(b=f+2;c>>=f,c-=f,0===A.have){e.msg="invalid bit length repeat",A.mode=30;break}y=A.lens[A.have-1],I=3+(3&g),g>>>=2,c-=2}else if(17===B){for(b=f+3;c>>=f)),g>>>=3,c-=3}else{for(b=f+7;c>>=f)),g>>>=7,c-=7}if(A.have+I>A.nlen+A.ndist){e.msg="invalid bit length repeat",A.mode=30;break}for(;I--;)A.lens[A.have++]=y}}if(30===A.mode)break;if(0===A.lens[256]){e.msg="invalid code -- missing end-of-block",A.mode=30;break}if(A.lenbits=9,m={bits:A.lenbits},v=pn(1,A.lens,0,A.nlen,A.lencode,0,A.work,m),A.lenbits=m.bits,v){e.msg="invalid literal/lengths set",A.mode=30;break}if(A.distbits=6,A.distcode=A.distdyn,m={bits:A.distbits},v=pn(2,A.lens,A.nlen,A.ndist,A.distcode,0,A.work,m),A.distbits=m.bits,v){e.msg="invalid distances set",A.mode=30;break}if(A.mode=20,t===yn)break e;case 20:A.mode=21;case 21:if(a>=6&&s>=258){e.next_out=o,e.avail_out=s,e.next_in=i,e.avail_in=a,A.hold=g,A.bits=c,Cn(e,l),o=e.next_out,r=e.output,s=e.avail_out,i=e.next_in,n=e.input,a=e.avail_in,g=A.hold,c=A.bits,12===A.mode&&(A.back=-1);break}for(A.back=0;d=(w=A.lencode[g&(1<>>16&255,B=65535&w,!((f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>p)])>>>16&255,B=65535&w,!(p+(f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>>=p,c-=p,A.back+=p}if(g>>>=f,c-=f,A.back+=f,A.length=B,0===d){A.mode=26;break}if(32&d){A.back=-1,A.mode=12;break}if(64&d){e.msg="invalid literal/length code",A.mode=30;break}A.extra=15&d,A.mode=22;case 22:if(A.extra){for(b=A.extra;c>>=A.extra,c-=A.extra,A.back+=A.extra}A.was=A.length,A.mode=23;case 23:for(;d=(w=A.distcode[g&(1<>>16&255,B=65535&w,!((f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>p)])>>>16&255,B=65535&w,!(p+(f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>>=p,c-=p,A.back+=p}if(g>>>=f,c-=f,A.back+=f,64&d){e.msg="invalid distance code",A.mode=30;break}A.offset=B,A.extra=15&d,A.mode=24;case 24:if(A.extra){for(b=A.extra;c>>=A.extra,c-=A.extra,A.back+=A.extra}if(A.offset>A.dmax){e.msg="invalid distance too far back",A.mode=30;break}A.mode=25;case 25:if(0===s)break e;if(I=l-s,A.offset>I){if((I=A.offset-I)>A.whave&&A.sane){e.msg="invalid distance too far back",A.mode=30;break}I>A.wnext?(I-=A.wnext,C=A.wsize-I):C=A.wnext-I,I>A.length&&(I=A.length),h=A.window}else h=r,C=o-A.offset,I=A.length;I>s&&(I=s),s-=I,A.length-=I;do{r[o++]=h[C++]}while(--I);0===A.length&&(A.mode=21);break;case 26:if(0===s)break e;r[o++]=A.length,s--,A.mode=21;break;case 27:if(A.wrap){for(;c<32;){if(0===a)break e;a--,g|=n[i++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0===(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new tn,this.strm.avail_out=0;var A=Hn.inflateInit2(this.strm,t.windowBits);if(A!==Vn)throw new Error(tA[A]);if(this.header=new Yn,Hn.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"===typeof t.dictionary?t.dictionary=zA(t.dictionary):"[object ArrayBuffer]"===Jn.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(A=Hn.inflateSetDictionary(this.strm,t.dictionary))!==Vn))throw new Error(tA[A])}function er(e,t){var A=new $n(t);if(A.push(e),A.err)throw A.msg||tA[A.err];return A.result}$n.prototype.push=function(e,t){var A,n,r,i=this.strm,o=this.options.chunkSize,a=this.options.dictionary;if(this.ended)return!1;for(n=t===~~t?t:!0===t?Pn:jn,"[object ArrayBuffer]"===Jn.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(o),i.next_out=0,i.avail_out=o),(A=Hn.inflate(i,n))===Wn&&a&&((A=Hn.inflateSetDictionary(i,a))===Vn?A=Hn.inflate(i,n):A===qn&&(A=Wn));i.avail_in>0&&A===Kn&&i.state.wrap>0&&0!==e[i.next_in];)Hn.inflateReset(i),A=Hn.inflate(i,n);switch(A){case Xn:case qn:case Wn:case zn:return this.onEnd(A),this.ended=!0,!1}if(r=i.avail_out,i.next_out&&(0===i.avail_out||A===Kn))if("string"===this.options.to){var s=en(i.output,i.next_out),g=i.next_out-s,c=$A(i.output,s);i.next_out=g,i.avail_out=o-g,g&&i.output.set(i.output.subarray(s,s+g),0),this.onData(c)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(A!==Vn||0!==r){if(A===Kn)return A=Hn.inflateEnd(this.strm),this.onEnd(A),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},$n.prototype.onData=function(e){this.chunks.push(e)},$n.prototype.onEnd=function(e){e===Vn&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=KA(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var tr={Inflate:$n,inflate:er,inflateRaw:function(e,t){return(t=t||{}).raw=!0,er(e,t)},ungzip:er,constants:AA},Ar=tr.inflate,nr=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"decodeBlock",value:function(e){return Ar(new Uint8Array(e)).buffer}}]),A}(Xe),rr=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"decodeBlock",value:function(e){for(var t=new DataView(e),A=[],n=0;n3&&void 0!==arguments[3]?arguments[3]:1;return new(Object.getPrototypeOf(e).constructor)(t*A*n)}function cr(e,t,A,n,r){var i=t/n,o=A/r;return e.map((function(e){for(var a=gr(e,n,r),s=0;s5&&void 0!==arguments[5]?arguments[5]:"nearest";switch(i.toLowerCase()){case"nearest":return cr(e,t,A,n,r);case"bilinear":case"linear":return lr(e,t,A,n,r);default:throw new Error("Unsupported resampling method: '".concat(i,"'"))}}function Cr(e,t,A,n,r,i){for(var o=t/n,a=A/r,s=gr(e,n,r,i),g=0;g6&&void 0!==arguments[6]?arguments[6]:"nearest";switch(o.toLowerCase()){case"nearest":return Cr(e,t,A,n,r,i);case"bilinear":case"linear":return hr(e,t,A,n,r,i);default:throw new Error("Unsupported resampling method: '".concat(o,"'"))}}function dr(e,t,A){for(var n=0,r=t;r>8-r-E&c;else if(E+r<=16)g[B]=a.getUint16(p)>>16-r-E&c;else if(E+r<=24){var Q=a.getUint16(p)<<8|a.getUint8(p+2);g[B]=Q>>24-r-E&c}else g[B]=a.getUint32(p)>>32-r-E&c}}return g.buffer}var Qr=function(){function e(t,A,n,r,i,o){Object(u.a)(this,e),this.fileDirectory=t,this.geoKeys=A,this.dataView=n,this.littleEndian=r,this.tiles=i?{}:null,this.isTiled=!t.StripOffsets;var a=t.PlanarConfiguration;if(this.planarConfiguration="undefined"===typeof a?1:a,1!==this.planarConfiguration&&2!==this.planarConfiguration)throw new Error("Invalid planar configuration.");this.source=o}return Object(l.a)(e,[{key:"getFileDirectory",value:function(){return this.fileDirectory}},{key:"getGeoKeys",value:function(){return this.geoKeys}},{key:"getWidth",value:function(){return this.fileDirectory.ImageWidth}},{key:"getHeight",value:function(){return this.fileDirectory.ImageLength}},{key:"getSamplesPerPixel",value:function(){return"undefined"!==typeof this.fileDirectory.SamplesPerPixel?this.fileDirectory.SamplesPerPixel:1}},{key:"getTileWidth",value:function(){return this.isTiled?this.fileDirectory.TileWidth:this.getWidth()}},{key:"getTileHeight",value:function(){return this.isTiled?this.fileDirectory.TileLength:"undefined"!==typeof this.fileDirectory.RowsPerStrip?Math.min(this.fileDirectory.RowsPerStrip,this.getHeight()):this.getHeight()}},{key:"getBlockWidth",value:function(){return this.getTileWidth()}},{key:"getBlockHeight",value:function(e){return this.isTiled||(e+1)*this.getTileHeight()<=this.getHeight()?this.getTileHeight():this.getHeight()-e*this.getTileHeight()}},{key:"getBytesPerPixel",value:function(){for(var e=0,t=0;t=this.fileDirectory.BitsPerSample.length)throw new RangeError("Sample index ".concat(e," is out of range."));return Math.ceil(this.fileDirectory.BitsPerSample[e]/8)}},{key:"getReaderForSample",value:function(e){var t=this.fileDirectory.SampleFormat?this.fileDirectory.SampleFormat[e]:1,A=this.fileDirectory.BitsPerSample[e];switch(t){case 1:if(A<=8)return DataView.prototype.getUint8;if(A<=16)return DataView.prototype.getUint16;if(A<=32)return DataView.prototype.getUint32;break;case 2:if(A<=8)return DataView.prototype.getInt8;if(A<=16)return DataView.prototype.getInt16;if(A<=32)return DataView.prototype.getInt32;break;case 3:switch(A){case 16:return function(e,t){return de(this,e,t)};case 32:return DataView.prototype.getFloat32;case 64:return DataView.prototype.getFloat64}}throw Error("Unsupported data format/bitsPerSample")}},{key:"getSampleFormat",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return this.fileDirectory.SampleFormat?this.fileDirectory.SampleFormat[e]:1}},{key:"getBitsPerSample",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return this.fileDirectory.BitsPerSample[e]}},{key:"getArrayForSample",value:function(e,t){return Br(this.getSampleFormat(e),this.getBitsPerSample(e),t)}},{key:"getTileOrStrip",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A,n,r,i){var s,g,c,u,l,I,C,h,f=this;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return s=Math.ceil(this.getWidth()/this.getTileWidth()),g=Math.ceil(this.getHeight()/this.getTileHeight()),u=this.tiles,1===this.planarConfiguration?c=A*s+t:2===this.planarConfiguration&&(c=n*s*g+A*s+t),this.isTiled?(l=this.fileDirectory.TileOffsets[c],I=this.fileDirectory.TileByteCounts[c]):(l=this.fileDirectory.StripOffsets[c],I=this.fileDirectory.StripByteCounts[c]),e.next=7,this.source.fetch([{offset:l,length:I}],i);case 7:return C=e.sent[0],null!==u&&u[c]?h=u[c]:(h=Object(a.a)(o.a.mark((function e(){var t,n,i;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,r.decode(f.fileDirectory,C);case 2:return t=e.sent,n=f.getSampleFormat(),i=f.getBitsPerSample(),pr(n,i)&&(t=Er(t,n,f.planarConfiguration,f.getSamplesPerPixel(),i,f.getTileWidth(),f.getBlockHeight(A))),e.abrupt("return",t);case 7:case"end":return e.stop()}}),e)})))(),null!==u&&(u[c]=h)),e.t0=t,e.t1=A,e.t2=n,e.next=14,h;case 14:return e.t3=e.sent,e.abrupt("return",{x:e.t0,y:e.t1,sample:e.t2,data:e.t3});case 16:case"end":return e.stop()}}),e,this)})));return function(t,A,n,r,i){return e.apply(this,arguments)}}()},{key:"_readRaster",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A,n,r,i,a,s,g,c){var u,l,I,C,h,f,d,B,p,E,Q,y,v,m,b,w,S,F,R=this;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(u=this.getTileWidth(),l=this.getTileHeight(),I=Math.max(Math.floor(t[0]/u),0),C=Math.min(Math.ceil(t[2]/u),Math.ceil(this.getWidth()/this.getTileWidth())),h=Math.max(Math.floor(t[1]/l),0),f=Math.min(Math.ceil(t[3]/l),Math.ceil(this.getHeight()/this.getTileHeight())),d=t[2]-t[0],B=this.getBytesPerPixel(),p=[],E=[],Q=0;Q0&&void 0!==F[0]?F[0]:{},A=t.window,n=t.samples,r=void 0===n?[]:n,i=t.interleave,a=t.pool,s=void 0===a?null:a,g=t.width,c=t.height,u=t.resampleMethod,l=t.fillValue,I=t.signal,!((C=A||[0,0,this.getWidth(),this.getHeight()])[0]>C[2]||C[1]>C[3])){e.next=4;break}throw new Error("Invalid subsets");case 4:if(h=C[2]-C[0],f=C[3]-C[1],d=h*f,B=this.getSamplesPerPixel(),r&&r.length){e.next=12;break}for(p=0;p=B)){e.next=16;break}return e.abrupt("return",Promise.reject(new RangeError("Invalid sample index '".concat(r[E],"'."))));case 16:++E,e.next=13;break;case 19:if(i)y=this.fileDirectory.SampleFormat?Math.max.apply(null,this.fileDirectory.SampleFormat):1,v=Math.max.apply(null,this.fileDirectory.BitsPerSample),Q=Br(y,v,d*r.length),l&&Q.fill(l);else for(Q=[],m=0;m0&&void 0!==y[0]?y[0]:{},A=t.window,n=t.pool,r=void 0===n?null:n,i=t.width,a=t.height,s=t.resampleMethod,g=t.enableAlpha,c=void 0!==g&&g,u=t.signal,!((l=A||[0,0,this.getWidth(),this.getHeight()])[0]>l[2]||l[1]>l[3])){e.next=4;break}throw new Error("Invalid subsets");case 4:if((I=this.fileDirectory.PhotometricInterpretation)!==Fe){e.next=9;break}if(C=[0,1,2],this.fileDirectory.ExtraSamples!==xe&&c)for(C=[],h=0;h0&&void 0!==arguments[0]?arguments[0]:null,t={};if(!this.fileDirectory.GDAL_METADATA)return null;var A=this.fileDirectory.GDAL_METADATA,n=Be(A.substring(0,A.length-1));if(!n[0].tagName)throw new Error("Failed to parse GDAL metadata XML.");var r=n[0];if("GDALMetadata"!==r.tagName)throw new Error("Unexpected GDAL metadata XML tag.");var i=r.children.filter((function(e){return"Item"===e.tagName}));null!==e&&(i=i.filter((function(t){return Number(t.attributes.sample)===e})));for(var o=0;o0&&void 0!==arguments[0]?arguments[0]:null,t=this.fileDirectory.ModelPixelScale,A=this.fileDirectory.ModelTransformation;if(t)return[t[0],-t[1],t[2]];if(A)return[A[0],A[5],A[10]];if(e){var n=e.getResolution(),r=Object(s.a)(n,3),i=r[0],o=r[1],a=r[2];return[i*e.getWidth()/this.getWidth(),o*e.getHeight()/this.getHeight(),a*e.getWidth()/this.getWidth()]}throw new Error("The image does not have an affine transformation.")}},{key:"pixelIsArea",value:function(){return 1===this.geoKeys.GTRasterTypeGeoKey}},{key:"getBoundingBox",value:function(){var e=this.getOrigin(),t=this.getResolution(),A=e[0],n=e[1],r=A+t[0]*this.getWidth(),i=n+t[1]*this.getHeight();return[Math.min(A,r),Math.min(n,i),Math.max(A,r),Math.max(n,i)]}}]),e}(),yr=function(){function e(t){Object(u.a)(this,e),this._dataView=new DataView(t)}return Object(l.a)(e,[{key:"getUint64",value:function(e,t){var A,n=this.getUint32(e,t),r=this.getUint32(e+4,t);if(t){if(A=n+Math.pow(2,32)*r,!Number.isSafeInteger(A))throw new Error("".concat(A," exceeds MAX_SAFE_INTEGER. Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues"));return A}if(A=Math.pow(2,32)*n+r,!Number.isSafeInteger(A))throw new Error("".concat(A," exceeds MAX_SAFE_INTEGER. Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues"));return A}},{key:"getInt64",value:function(e,t){for(var A=0,n=(128&this._dataView.getUint8(e+(t?7:0)))>0,r=!0,i=0;i<8;i++){var o=this._dataView.getUint8(e+(t?i:7-i));n&&(r?0!==o&&(o=255&~(o-1),r=!1):o=255&~o),A+=o*Math.pow(256,i)}return n&&(A=-A),A}},{key:"getUint8",value:function(e,t){return this._dataView.getUint8(e,t)}},{key:"getInt8",value:function(e,t){return this._dataView.getInt8(e,t)}},{key:"getUint16",value:function(e,t){return this._dataView.getUint16(e,t)}},{key:"getInt16",value:function(e,t){return this._dataView.getInt16(e,t)}},{key:"getUint32",value:function(e,t){return this._dataView.getUint32(e,t)}},{key:"getInt32",value:function(e,t){return this._dataView.getInt32(e,t)}},{key:"getFloat16",value:function(e,t){return de(this._dataView,t)}},{key:"getFloat32",value:function(e,t){return this._dataView.getFloat32(e,t)}},{key:"getFloat64",value:function(e,t){return this._dataView.getFloat64(e,t)}},{key:"buffer",get:function(){return this._dataView.buffer}}]),e}(),vr=function(){function e(t,A,n,r){Object(u.a)(this,e),this._dataView=new DataView(t),this._sliceOffset=A,this._littleEndian=n,this._bigTiff=r}return Object(l.a)(e,[{key:"covers",value:function(e,t){return this.sliceOffset<=e&&this.sliceTop>=e+t}},{key:"readUint8",value:function(e){return this._dataView.getUint8(e-this._sliceOffset,this._littleEndian)}},{key:"readInt8",value:function(e){return this._dataView.getInt8(e-this._sliceOffset,this._littleEndian)}},{key:"readUint16",value:function(e){return this._dataView.getUint16(e-this._sliceOffset,this._littleEndian)}},{key:"readInt16",value:function(e){return this._dataView.getInt16(e-this._sliceOffset,this._littleEndian)}},{key:"readUint32",value:function(e){return this._dataView.getUint32(e-this._sliceOffset,this._littleEndian)}},{key:"readInt32",value:function(e){return this._dataView.getInt32(e-this._sliceOffset,this._littleEndian)}},{key:"readFloat32",value:function(e){return this._dataView.getFloat32(e-this._sliceOffset,this._littleEndian)}},{key:"readFloat64",value:function(e){return this._dataView.getFloat64(e-this._sliceOffset,this._littleEndian)}},{key:"readUint64",value:function(e){var t,A=this.readUint32(e),n=this.readUint32(e+4);if(this._littleEndian){if(t=A+Math.pow(2,32)*n,!Number.isSafeInteger(t))throw new Error("".concat(t," exceeds MAX_SAFE_INTEGER. Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues"));return t}if(t=Math.pow(2,32)*A+n,!Number.isSafeInteger(t))throw new Error("".concat(t," exceeds MAX_SAFE_INTEGER. Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues"));return t}},{key:"readInt64",value:function(e){for(var t=0,A=(128&this._dataView.getUint8(e+(this._littleEndian?7:0)))>0,n=!0,r=0;r<8;r++){var i=this._dataView.getUint8(e+(this._littleEndian?r:7-r));A&&(n?0!==i&&(i=255&~(i-1),n=!1):i=255&~i),t+=i*Math.pow(256,r)}return A&&(t=-t),t}},{key:"readOffset",value:function(e){return this._bigTiff?this.readUint64(e):this.readUint32(e)}},{key:"sliceOffset",get:function(){return this._sliceOffset}},{key:"sliceTop",get:function(){return this._sliceOffset+this.buffer.byteLength}},{key:"littleEndian",get:function(){return this._littleEndian}},{key:"bigTiff",get:function(){return this._bigTiff}},{key:"buffer",get:function(){return this._dataView.buffer}}]),e}(),mr=A(73);function br(e){if("undefined"!==typeof Object.fromEntries)return Object.fromEntries(e);var t,A={},r=Object(n.a)(e);try{for(r.s();!(t=r.n()).done;){var i=Object(s.a)(t.value,2),o=i[0],a=i[1];A[o.toLowerCase()]=a}}catch(g){r.e(g)}finally{r.f()}return A}function wr(e){return br(e.split("\r\n").map((function(e){var t=e.split(":").map((function(e){return e.trim()}));return t[0]=t[0].toLowerCase(),t})))}function Sr(e){var t=e.split(";").map((function(e){return e.trim()})),A=Object(mr.a)(t);return{type:A[0],params:br(A.slice(1).map((function(e){return e.split("=")})))}}function Fr(e){var t,A,n;if(e){var r=e.match(/bytes (\d+)-(\d+)\/(\d+)/),i=Object(s.a)(r,4);t=i[1],A=i[2],n=i[3],t=parseInt(t,10),A=parseInt(A,10),n=parseInt(n,10)}return{start:t,end:A,total:n}}function Rr(e,t){for(var A=null,n=new TextDecoder("ascii"),r=[],i="--".concat(t),o="".concat(i,"--"),a=0;a<10;++a){n.decode(new Uint8Array(e,a,i.length))===i&&(A=a)}if(null===A)throw new Error("Could not find initial boundary");for(;A2&&void 0!==arguments[2]?arguments[2]:null;Object(u.a)(this,e),this.offset=t,this.length=A,this.data=n}return Object(l.a)(e,[{key:"top",get:function(){return this.offset+this.length}}]),e}(),Ur=function e(t,A,n){Object(u.a)(this,e),this.offset=t,this.length=A,this.blockIds=n},_r=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(e){var n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=r.blockSize,o=void 0===i?65536:i,a=r.cacheSize,s=void 0===a?100:a;return Object(u.a)(this,A),(n=t.call(this)).source=e,n.blockSize=o,n.blockCache=new kr.a({max:s}),n.blockRequests=new Map,n.blockIdsToFetch=new Set,n.abortedBlockIds=new Set,n}return Object(l.a)(A,[{key:"fetch",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A){var r,i,a,s,g,c,u,l,I,C,h,f,d,B,p,E,Q,y,v,m,b,w,S,F,R,D,G=this;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=[],i=[],a=[],s=Object(n.a)(t);try{for(s.s();!(g=s.n()).done;)for(c=g.value,u=c.offset,l=c.length,I=u+l,null!==(C=this.fileSize)&&(I=Math.min(I,C)),h=Math.floor(u/this.blockSize)*this.blockSize,f=h;f0&&A)||A.aborted){e.next=40;break}this.fetchBlocks(null),m=Object(n.a)(v),e.prev=20,m.s();case 22:if((b=m.n()).done){e.next=30;break}if(w=b.value,S=this.blockRequests.get(w)){e.next=27;break}throw new Error("Block ".concat(w," is not in the block requests"));case 27:y.push(S);case 28:e.next=22;break;case 30:e.next=35;break;case 32:e.prev=32,e.t0=e.catch(20),m.e(e.t0);case 35:return e.prev=35,m.f(),e.finish(35);case 38:return e.next=40,Promise.allSettled(Array.from(y.values()));case 40:if(!A||!A.aborted){e.next=42;break}throw new xr.a("Request was aborted");case 42:if(F=a.map((function(e){return G.blockCache.get(e)})),!(R=F.filter((function(e){return!e}))).length){e.next=46;break}throw new xr.b(R,"Request failed");case 46:return D=new Map(Object(xr.i)(a,F)),e.abrupt("return",this.readSliceData(t,D));case 48:case"end":return e.stop()}}),e,this,[[20,32,35,38]])})));return function(t,A){return e.apply(this,arguments)}}()},{key:"fetchBlocks",value:function(e){var t=this;this.blockIdsToFetch.size>0&&function(){for(var A=t.groupBlocks(t.blockIdsToFetch),r=t.source.fetch(A,e),i=function(i){var s,g=A[i],c=Object(n.a)(g.blockIds);try{var u=function(){var A=s.value;t.blockRequests.set(A,Object(a.a)(o.a.mark((function n(){var a,s,g,c,u,l;return o.a.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.prev=0,n.next=3,r;case 3:n.t0=i,a=n.sent[n.t0],s=A*t.blockSize,g=s-a.offset,c=Math.min(g+t.blockSize,a.data.byteLength),u=a.data.slice(g,c),l=new Nr(s,u.byteLength,u,A),t.blockCache.set(A,l),t.abortedBlockIds.delete(A),n.next=23;break;case 14:if(n.prev=14,n.t1=n.catch(0),"AbortError"!==n.t1.name){n.next=22;break}n.t1.signal=e,t.blockCache.del(A),t.abortedBlockIds.add(A),n.next=23;break;case 22:throw n.t1;case 23:return n.prev=23,t.blockRequests.delete(A),n.finish(23);case 26:case"end":return n.stop()}}),n,null,[[0,14,23,26]])})))())};for(c.s();!(s=c.n()).done;)u()}catch(l){c.e(l)}finally{c.f()}},s=0;s0&&(l=c),I=g.top-n<0?g.length-u:n-g.offset-u;var C=new Uint8Array(g.data,u,I);a.set(C,l)}return o}))}},{key:"fileSize",get:function(){return this.source.fileSize}}]),A}(Dr.a),Mr=A(181),Or=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(e){var n;return Object(u.a)(this,A),(n=t.call(this)).response=e,n}return Object(l.a)(A,[{key:"getHeader",value:function(e){return this.response.headers.get(e)}},{key:"getData",value:function(){var e=Object(a.a)(o.a.mark((function e(){var t;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.response.arrayBuffer){e.next=6;break}return e.next=3,this.response.arrayBuffer();case 3:e.t0=e.sent,e.next=9;break;case 6:return e.next=8,this.response.buffer();case 8:e.t0=e.sent.buffer;case 9:return t=e.t0,e.abrupt("return",t);case 11:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"status",get:function(){return this.response.status}}]),A}(Mr.b),Lr=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(e,n){var r;return Object(u.a)(this,A),(r=t.call(this,e)).credentials=n,r}return Object(l.a)(A,[{key:"request",value:function(){var e=Object(a.a)(o.a.mark((function e(){var t,A,n,r,i,a=arguments;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=a.length>0&&void 0!==a[0]?a[0]:{},A=t.headers,n=t.credentials,r=t.signal,e.next=3,fetch(this.url,{headers:A,credentials:n,signal:r});case 3:return i=e.sent,e.abrupt("return",new Or(i));case 5:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()}]),A}(Mr.a),Tr=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(e,n){var r;return Object(u.a)(this,A),(r=t.call(this)).xhr=e,r.data=n,r}return Object(l.a)(A,[{key:"getHeader",value:function(e){return this.xhr.getResponseHeader(e)}},{key:"getData",value:function(){var e=Object(a.a)(o.a.mark((function e(){return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.data);case 1:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"status",get:function(){return this.xhr.status}}]),A}(Mr.b),Zr=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"constructRequest",value:function(e,t){var A=this;return new Promise((function(n,r){var i=new XMLHttpRequest;i.open("GET",A.url),i.responseType="arraybuffer";for(var o=0,a=Object.entries(e);o0&&void 0!==i[0]?i[0]:{},A=t.headers,n=t.signal,e.next=3,this.constructRequest(A,n);case 3:return r=e.sent,e.abrupt("return",r);case 5:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()}]),A}(Mr.a),Hr=A(671),Yr=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(e,n,r,i){var o;return Object(u.a)(this,A),(o=t.call(this)).client=e,o.headers=n,o.maxRanges=r,o.allowFullFile=i,o._fileSize=null,o}return Object(l.a)(A,[{key:"fetch",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A){var n=this;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(this.maxRanges>=t.length)){e.next=4;break}return e.abrupt("return",this.fetchSlices(t,A));case 4:this.maxRanges>0&&t.length;case 5:return e.next=7,Promise.all(t.map((function(e){return n.fetchSlice(e,A)})));case 7:return e.abrupt("return",e.sent);case 8:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"fetchSlices",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A){var n,r,i,a,s,g,c,u,l,I,C,h,f,B=this;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.client.request({headers:Object(d.a)({},this.headers,{Range:"bytes=".concat(t.map((function(e){var t=e.offset,A=e.length;return"".concat(t,"-").concat(t+A)})).join(","))}),signal:A});case 2:if((n=e.sent).ok){e.next=7;break}throw new Error("Error fetching data.");case 7:if(206!==n.status){e.next=32;break}if(r=Sr(n.getHeader("content-type")),i=r.type,a=r.params,"multipart/byteranges"!==i){e.next=18;break}return e.t0=Rr,e.next=13,n.getData();case 13:return e.t1=e.sent,e.t2=a.boundary,s=(0,e.t0)(e.t1,e.t2),this._fileSize=s[0].fileSize||null,e.abrupt("return",s);case 18:return e.next=20,n.getData();case 20:if(g=e.sent,c=Fr(n.getHeader("content-range")),u=c.start,l=c.end,I=c.total,this._fileSize=I||null,C=[{data:g,offset:u,length:l-u}],!(t.length>1)){e.next=29;break}return e.next=27,Promise.all(t.slice(1).map((function(e){return B.fetchSlice(e,A)})));case 27:return h=e.sent,e.abrupt("return",C.concat(h));case 29:return e.abrupt("return",C);case 32:if(this.allowFullFile){e.next=34;break}throw new Error("Server responded with full file");case 34:return e.next=36,n.getData();case 36:return f=e.sent,this._fileSize=f.byteLength,e.abrupt("return",[{data:f,offset:0,length:f.byteLength}]);case 39:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"fetchSlice",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A){var n,r,i,a,s,g,c;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.offset,r=t.length,e.next=3,this.client.request({headers:Object(d.a)({},this.headers,{Range:"bytes=".concat(n,"-").concat(n+r)}),signal:A});case 3:if((i=e.sent).ok){e.next=8;break}throw new Error("Error fetching data.");case 8:if(206!==i.status){e.next=17;break}return e.next=11,i.getData();case 11:return a=e.sent,s=Fr(i.getHeader("content-range")),g=s.total,this._fileSize=g||null,e.abrupt("return",{data:a,offset:n,length:r});case 17:if(this.allowFullFile){e.next=19;break}throw new Error("Server responded with full file");case 19:return e.next=21,i.getData();case 21:return c=e.sent,this._fileSize=c.byteLength,e.abrupt("return",{data:c,offset:0,length:c.byteLength});case 24:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"fileSize",get:function(){return this._fileSize}}]),A}(Dr.a);function Jr(e,t){var A=t.blockSize,n=t.cacheSize;return null===A?e:new _r(e,{blockSize:A,cacheSize:n})}function jr(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.headers,n=void 0===A?{}:A,r=t.credentials,i=t.maxRanges,o=void 0===i?0:i,a=t.allowFullFile,s=void 0!==a&&a,g=Object(c.a)(t,["headers","credentials","maxRanges","allowFullFile"]),u=new Lr(e,r),l=new Yr(u,n,o,s);return Jr(l,g)}function Pr(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.headers,n=void 0===A?{}:A,r=t.maxRanges,i=void 0===r?0:r,o=t.allowFullFile,a=void 0!==o&&o,s=Object(c.a)(t,["headers","maxRanges","allowFullFile"]),g=new Zr(e),u=new Yr(g,n,i,a);return Jr(u,s)}function Vr(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.headers,n=void 0===A?{}:A,r=t.maxRanges,i=void 0===r?0:r,o=t.allowFullFile,a=void 0!==o&&o,s=Object(c.a)(t,["headers","maxRanges","allowFullFile"]),g=new Hr.a(e),u=new Yr(g,n,i,a);return Jr(u,s)}function Kr(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.forceXHR,n=void 0!==A&&A,r=Object(c.a)(t,["forceXHR"]);return"function"!==typeof fetch||n?"undefined"!==typeof XMLHttpRequest?Pr(e,r):Vr(e,r):jr(e,r)}Dr.a;var Wr=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(e){var n;return Object(u.a)(this,A),(n=t.call(this)).file=e,n}return Object(l.a)(A,[{key:"fetchSlice",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A){var n=this;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",new Promise((function(e,r){var i=n.file.slice(t.offset,t.offset+t.length),o=new FileReader;o.onload=function(t){return e(t.target.result)},o.onerror=r,o.onabort=r,o.readAsArrayBuffer(i),A&&A.addEventListener("abort",(function(){return o.abort()}))})));case 1:case"end":return e.stop()}}),e)})));return function(t,A){return e.apply(this,arguments)}}()}]),A}(Dr.a);function Xr(e){return new Wr(e)}A(675);var qr=Object(xr.f)(pe),zr=Object(xr.f)(Me),$r={};Object(xr.c)($r,qr),Object(xr.c)($r,zr);Object(xr.f)(ve);var ei={nextZero:function(e,t){for(var A=t;0!==e[A];)A++;return A},readUshort:function(e,t){return e[t]<<8|e[t+1]},readShort:function(e,t){var A=ei.ui8;return A[0]=e[t+1],A[1]=e[t+0],ei.i16[0]},readInt:function(e,t){var A=ei.ui8;return A[0]=e[t+3],A[1]=e[t+2],A[2]=e[t+1],A[3]=e[t+0],ei.i32[0]},readUint:function(e,t){var A=ei.ui8;return A[0]=e[t+3],A[1]=e[t+2],A[2]=e[t+1],A[3]=e[t+0],ei.ui32[0]},readASCII:function(e,t,A){return A.map((function(A){return String.fromCharCode(e[t+A])})).join("")},readFloat:function(e,t){var A=ei.ui8;return Object(xr.g)(4,(function(n){A[n]=e[t+3-n]})),ei.fl32[0]},readDouble:function(e,t){var A=ei.ui8;return Object(xr.g)(8,(function(n){A[n]=e[t+7-n]})),ei.fl64[0]},writeUshort:function(e,t,A){e[t]=A>>8&255,e[t+1]=255&A},writeUint:function(e,t,A){e[t]=A>>24&255,e[t+1]=A>>16&255,e[t+2]=A>>8&255,e[t+3]=A>>0&255},writeASCII:function(e,t,A){Object(xr.g)(A.length,(function(n){e[t+n]=A.charCodeAt(n)}))},ui8:new Uint8Array(8)};ei.fl64=new Float64Array(ei.ui8.buffer),ei.writeDouble=function(e,t,A){ei.fl64[0]=A,Object(xr.g)(8,(function(A){e[t+A]=ei.ui8[7-A]}))};function ti(e){switch(e){case me.BYTE:case me.ASCII:case me.SBYTE:case me.UNDEFINED:return 1;case me.SHORT:case me.SSHORT:return 2;case me.LONG:case me.SLONG:case me.FLOAT:case me.IFD:return 4;case me.RATIONAL:case me.SRATIONAL:case me.DOUBLE:case me.LONG8:case me.SLONG8:case me.IFD8:return 8;default:throw new RangeError("Invalid field type: ".concat(e))}}function Ai(e){var t=e.GeoKeyDirectory;if(!t)return null;for(var A={},n=4;n<=4*t[3];n+=4){var r=Me[t[n]],i=t[n+1]?pe[t[n+1]]:null,o=t[n+2],a=t[n+3],s=null;if(i){if("undefined"===typeof(s=e[i])||null===s)throw new Error("Could not get value of geoKey '".concat(r,"'."));"string"===typeof s?s=s.substring(a,a+o-1):s.subarray&&(s=s.subarray(a,a+o),1===o&&(s=s[0]))}else s=a;A[r]=s}return A}function ni(e,t,A,n){var r=null,i=null,o=ti(t);switch(t){case me.BYTE:case me.ASCII:case me.UNDEFINED:r=new Uint8Array(A),i=e.readUint8;break;case me.SBYTE:r=new Int8Array(A),i=e.readInt8;break;case me.SHORT:r=new Uint16Array(A),i=e.readUint16;break;case me.SSHORT:r=new Int16Array(A),i=e.readInt16;break;case me.LONG:case me.IFD:r=new Uint32Array(A),i=e.readUint32;break;case me.SLONG:r=new Int32Array(A),i=e.readInt32;break;case me.LONG8:case me.IFD8:r=new Array(A),i=e.readUint64;break;case me.SLONG8:r=new Array(A),i=e.readInt64;break;case me.RATIONAL:r=new Uint32Array(2*A),i=e.readUint32;break;case me.SRATIONAL:r=new Int32Array(2*A),i=e.readInt32;break;case me.FLOAT:r=new Float32Array(A),i=e.readFloat32;break;case me.DOUBLE:r=new Float64Array(A),i=e.readFloat64;break;default:throw new RangeError("Invalid field type: ".concat(t))}if(t!==me.RATIONAL&&t!==me.SRATIONAL)for(var a=0;a0&&void 0!==Y[0]?Y[0]:{},A=t.window,n=t.width,r=t.height,i=t.resX,a=t.resY,g=t.bbox,e.next=5,this.getImage();case 5:return c=e.sent,u=c,e.next=9,this.getImageCount();case 9:if(l=e.sent,I=c.getBoundingBox(),!A||!g){e.next=13;break}throw new Error('Both "bbox" and "window" passed.');case 13:if(!n&&!r){e.next=24;break}if(A&&(C=c.getOrigin(),h=Object(s.a)(C,2),f=h[0],B=h[1],p=c.getResolution(),E=Object(s.a)(p,2),Q=E[0],y=E[1],g=[f+A[0]*Q,B+A[1]*y,f+A[2]*Q,B+A[3]*y]),v=g||I,!n){e.next=20;break}if(!i){e.next=19;break}throw new Error("Both width and resX passed");case 19:i=(v[2]-v[0])/n;case 20:if(!r){e.next=24;break}if(!a){e.next=23;break}throw new Error("Both width and resY passed");case 23:a=(v[3]-v[1])/r;case 24:if(!i&&!a){e.next=48;break}m=[],b=0;case 27:if(!(bk||a&&a>x)){e.next=45;break}return e.abrupt("break",48);case 45:++D,e.next=38;break;case 48:return N=A,g&&(U=c.getOrigin(),_=Object(s.a)(U,2),M=_[0],O=_[1],L=u.getResolution(c),T=Object(s.a)(L,2),Z=T[0],H=T[1],N=[Math.round((g[0]-M)/Z),Math.round((g[1]-O)/H),Math.round((g[2]-M)/Z),Math.round((g[3]-O)/H)],N=[Math.min(N[0],N[2]),Math.min(N[1],N[3]),Math.max(N[0],N[2]),Math.max(N[1],N[3])]),e.abrupt("return",u.readRasters(Object(d.a)({},t,{window:N})));case 51:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()}]),e}(),ai=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(e,n,r,i){var o,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};return Object(u.a)(this,A),(o=t.call(this)).source=e,o.littleEndian=n,o.bigTiff=r,o.firstIFDOffset=i,o.cache=a.cache||!1,o.ifdRequests=[],o.ghostValues=null,o}return Object(l.a)(A,[{key:"getSlice",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A){var n;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.bigTiff?4048:1024,e.t0=vr,e.next=4,this.source.fetch([{offset:t,length:"undefined"!==typeof A?A:n}]);case 4:return e.t1=e.sent[0],e.t2=t,e.t3=this.littleEndian,e.t4=this.bigTiff,e.abrupt("return",new e.t0(e.t1,e.t2,e.t3,e.t4));case 9:case"end":return e.stop()}}),e,this)})));return function(t,A){return e.apply(this,arguments)}}()},{key:"parseFileDirectoryAt",value:function(){var e=Object(a.a)(o.a.mark((function e(t){var A,n,r,i,a,s,g,c,u,l,I,C,h,f,d,B,p,E,Q,y;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=this.bigTiff?20:12,n=this.bigTiff?8:2,e.next=4,this.getSlice(t);case 4:if(r=e.sent,i=this.bigTiff?r.readUint64(t):r.readUint16(t),a=i*A+(this.bigTiff?16:6),r.covers(t,a)){e.next=11;break}return e.next=10,this.getSlice(t,a);case 10:r=e.sent;case 11:s={},g=t+(this.bigTiff?8:2),c=0;case 14:if(!(c0&&void 0!==n[0]?n[0]:0,e.next=3,this.requestIFD(t);case 3:return A=e.sent,e.abrupt("return",new Qr(A.fileDirectory,A.geoKeyDirectory,this.dataView,this.littleEndian,this.cache,this.source));case 5:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"getImageCount",value:function(){var e=Object(a.a)(o.a.mark((function e(){var t,A;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=0,A=!0;case 2:if(!A){e.next=18;break}return e.prev=3,e.next=6,this.requestIFD(t);case 6:++t,e.next=16;break;case 9:if(e.prev=9,e.t0=e.catch(3),!(e.t0 instanceof ii)){e.next=15;break}A=!1,e.next=16;break;case 15:throw e.t0;case 16:e.next=2;break;case 18:return e.abrupt("return",t);case 19:case"end":return e.stop()}}),e,this,[[3,9]])})));return function(){return e.apply(this,arguments)}}()},{key:"getGhostValues",value:function(){var e=Object(a.a)(o.a.mark((function e(){var t,A,n,r,i,a,g,c,u=this;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=this.bigTiff?16:8,!this.ghostValues){e.next=3;break}return e.abrupt("return",this.ghostValues);case 3:return n=(A="GDAL_STRUCTURAL_METADATA_SIZE=").length+100,e.next=7,this.getSlice(t,n);case 7:if(r=e.sent,A!==ni(r,me.ASCII,A.length,t)){e.next=19;break}if(i=ni(r,me.ASCII,n,t),a=i.split("\n")[0],!((g=Number(a.split("=")[1].split(" ")[0])+a.length)>n)){e.next=16;break}return e.next=15,this.getSlice(t,g);case 15:r=e.sent;case 16:c=ni(r,me.ASCII,g,t),this.ghostValues={},c.split("\n").filter((function(e){return e.length>0})).map((function(e){return e.split("=")})).forEach((function(e){var t=Object(s.a)(e,2),A=t[0],n=t[1];u.ghostValues[A]=n}));case 19:return e.abrupt("return",this.ghostValues);case 20:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()},{key:"close",value:function(){return"function"===typeof this.source.close&&this.source.close()}}],[{key:"fromSource",value:function(){var e=Object(a.a)(o.a.mark((function e(t,n,r){var i,a,s,g,c,u,l;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.fetch([{offset:0,length:1024}],r);case 2:if(i=e.sent[0],a=new yr(i),18761!==(s=a.getUint16(0,0))){e.next=9;break}g=!0,e.next=14;break;case 9:if(19789!==s){e.next=13;break}g=!1,e.next=14;break;case 13:throw new TypeError("Invalid byte order value.");case 14:if(42!==(c=a.getUint16(2,g))){e.next=19;break}u=!1,e.next=27;break;case 19:if(43!==c){e.next=26;break}if(u=!0,8===a.getUint16(4,g)){e.next=24;break}throw new Error("Unsupported offset byte-size.");case 24:e.next=27;break;case 26:throw new TypeError("Invalid magic number.");case 27:return l=u?a.getUint64(8,g):a.getUint32(4,g),e.abrupt("return",new A(t,g,u,l,n));case 29:case"end":return e.stop()}}),e)})));return function(t,A,n){return e.apply(this,arguments)}}()}]),A}(oi);function si(e){return gi.apply(this,arguments)}function gi(){return(gi=Object(a.a)(o.a.mark((function e(t){var A,n,r=arguments;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=r.length>1&&void 0!==r[1]?r[1]:{},n=r.length>2?r[2]:void 0,e.abrupt("return",ai.fromSource(Kr(t,A),n));case 3:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ci(e,t){return ui.apply(this,arguments)}function ui(){return(ui=Object(a.a)(o.a.mark((function e(t,A){return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",ai.fromSource(Xr(t),A));case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var li,Ii,Ci,hi,fi=A(661),di=A.n(fi),Bi=A(71);A.d(t,"a",(function(){return oo})),A.d(t,"b",(function(){return no})),A.d(t,"c",(function(){return mi})),A.d(t,"d",(function(){return so})),A.d(t,"e",(function(){return vi})),A.d(t,"f",(function(){return co})),A.d(t,"g",(function(){return pi})),A.d(t,"h",(function(){return fo})),A.d(t,"i",(function(){return Fo})),A.d(t,"j",(function(){return Ni})),A.d(t,"k",(function(){return Aa})),A.d(t,"l",(function(){return Li})),A.d(t,"m",(function(){return ho})),A.d(t,"n",(function(){return Xo})),A.d(t,"o",(function(){return ia}));var pi,Ei,Qi={name:"channel-intensity-module",defines:{SAMPLER_TYPE:"usampler2D",COLORMAP_FUNCTION:""},fs:"#define GLSLIFY 1\nfloat apply_contrast_limits(float intensity,vec2 contrastLimits){return max(0.,(intensity-contrastLimits[0])/max(0.0005,(contrastLimits[1]-contrastLimits[0])));}"},yi=[0,0,0],vi=6,mi={Uint8:{format:F.default.R8UI,dataFormat:F.default.RED_INTEGER,type:F.default.UNSIGNED_BYTE,max:Math.pow(2,8)-1,sampler:"usampler2D"},Uint16:{format:F.default.R16UI,dataFormat:F.default.RED_INTEGER,type:F.default.UNSIGNED_SHORT,max:Math.pow(2,16)-1,sampler:"usampler2D"},Uint32:{format:F.default.R32UI,dataFormat:F.default.RED_INTEGER,type:F.default.UNSIGNED_INT,max:Math.pow(2,32)-1,sampler:"usampler2D"},Float32:{format:F.default.R32F,dataFormat:F.default.RED,type:F.default.FLOAT,max:3.4*Math.pow(10,38),sampler:"sampler2D"},Int8:{format:F.default.R8I,dataFormat:F.default.RED_INTEGER,type:F.default.BYTE,max:Math.pow(2,7)-1,sampler:"isampler2D"},Int16:{format:F.default.R16I,dataFormat:F.default.RED_INTEGER,type:F.default.SHORT,max:Math.pow(2,15)-1,sampler:"isampler2D"},Int32:{format:F.default.R32I,dataFormat:F.default.RED_INTEGER,type:F.default.INT,max:Math.pow(2,31)-1,sampler:"isampler2D"},Float64:{format:F.default.R32F,dataFormat:F.default.RED,type:F.default.FLOAT,max:3.4*Math.pow(10,38),sampler:"sampler2D",cast:function(e){return new Float32Array(e)}}},bi=["jet","hsv","hot","cool","spring","summer","autumn","winter","bone","copper","greys","yignbu","greens","yiorrd","bluered","rdbu","picnic","rainbow","portland","blackbody","earth","electric","alpha","viridis","inferno","magma","plasma","warm","rainbow-soft","bathymetry","cdom","chlorophyll","density","freesurface-blue","freesurface-red","oxygen","par","phase","salinity","temperature","turbidity","velocity-blue","velocity-green","cubehelix"];function wi(e,t,A){for(var n=0;n0&&e.data&&(e.data.forEach((function(n,r){A["channel".concat(r)]=t.dataToTexture(n,e.width,e.height)}),this),this.setState({textures:A}))}},{key:"dataToTexture",value:function(e,t,A){var n,r,i,o=this.props.interpolation,a=ki(this.props.dtype,this.context.gl,o);return new x.a(this.context.gl,{width:t,height:A,data:null!==(n=null===(r=a.cast)||void 0===r?void 0:r.call(a,e))&&void 0!==n?n:e,mipmaps:!1,parameters:(i={},Object(g.a)(i,F.default.TEXTURE_MIN_FILTER,a.filter),Object(g.a)(i,F.default.TEXTURE_MAG_FILTER,a.filter),Object(g.a)(i,F.default.TEXTURE_WRAP_S,F.default.CLAMP_TO_EDGE),Object(g.a)(i,F.default.TEXTURE_WRAP_T,F.default.CLAMP_TO_EDGE),i),format:a.format,dataFormat:a.dataFormat,type:a.type})}}]),A}(y.a);Ni.layerName="XRLayer",Ni.defaultProps=xi;var Ui={WhiteIsZero:0,BlackIsZero:1,RGB:2,Palette:3,TransparencyMask:4,CMYK:5,YCbCr:6,CIELab:8,ICCLab:9},_i=Object(d.a)({},O.a.defaultProps,{pickable:{type:"boolean",value:!0,compare:!0},coordinateSystem:p.a.CARTESIAN}),Mi=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"_getModel",value:function(e){var t=this.props,A=function(e,t){var A=t?"true":"false",n="vec3(".concat((t||[0,0,0]).map((function(e){return String(e/255)})).join(","),")");switch(e){case Ui.RGB:return"color[3] = (".concat(A," && (color.rgb == ").concat(n,")) ? 0.0 : color.a;");case Ui.WhiteIsZero:return" float value = 1.0 - (color.r / 256.0);\n color = vec4(value, value, value, (".concat(A," && vec3(value, value, value) == ").concat(n,") ? 0.0 : color.a);\n ");case Ui.BlackIsZero:return" float value = (color.r / 256.0);\n color = vec4(value, value, value, (".concat(A," && vec3(value, value, value) == ").concat(n,") ? 0.0 : color.a);\n ");case Ui.YCbCr:return" float y = color[0];\n float cb = color[1];\n float cr = color[2];\n color[0] = (y + (1.40200 * (cr - .5)));\n color[1] = (y - (0.34414 * (cb - .5)) - (0.71414 * (cr - .5)));\n color[2] = (y + (1.77200 * (cb - .5)));\n color[3] = (".concat(A," && distance(color.rgb, ").concat(n,") < 0.01) ? 0.0 : color.a;\n ");default:return console.error("Unsupported photometric interpretation or none provided. No transformation will be done to image data"),""}}(t.photometricInterpretation,t.transparentColorInHook);return e?new G.a(e,Object(d.a)({},this.getShaders(),{id:this.props.id,geometry:new k.a({drawMode:F.default.TRIANGLES,vertexCount:6}),isInstanced:!1,inject:{"fs:DECKGL_FILTER_COLOR":A}})):null}}]),A}(O.a),Oi=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"initializeState",value:function(e){var t=this.context.gl;t.pixelStorei(F.default.UNPACK_ALIGNMENT,1),t.pixelStorei(F.default.PACK_ALIGNMENT,1),Object(C.a)(Object(I.a)(A.prototype),"initializeState",this).call(this,e)}},{key:"renderLayers",value:function(){var e=this.props,t=e.photometricInterpretation,A=e.transparentColor,n=function(e){switch(e){case Ui.RGB:return[0,0,0,0];case Ui.WhiteIsZero:return[255,255,255,0];case Ui.BlackIsZero:return[0,0,0,0];case Ui.YCbCr:return[16,128,128,0];default:return console.error("Unsupported photometric interpretation or none provided. No transformation will be done to image data"),[0,0,0,0]}}(t);return new Mi(this.props,{transparentColor:n,transparentColorInHook:A,id:"".concat(this.props.id,"-wrapped")})}}]),A}(v.a);function Li(e){for(var t=e.length,A=1/0,n=-1/0,r=0;t--;)e[t]n&&(n=e[t]),r+=e[t];var i=r/e.length;t=e.length;for(var o=0;t--;)o+=Math.pow(e[t]-i,2);var a=Math.pow(o/e.length,.5),s=Math.floor(e.length/2),g=Math.floor(e.length/4),c=3*Math.floor(e.length/4);H(e,s);var u=e[s];H(e,g,0,s);var l=e[g];H(e,c,s,e.length-1);var I=e[c],C=e.filter((function(e){return e>0})),h=Math.floor(.9995*C.length),f=Math.floor(5e-4*C.length);return H(C,h),H(C,f,0,h),{mean:i,sd:a,q1:l,q3:I,median:u,domain:[A,n],contrastLimits:[C[f]||0,C[h]||0]}}function Ti(e){return Array.isArray(e)?e:[e]}function Zi(e){if(!Number.isInteger(e))throw Error("Not an integer.");var t=new ArrayBuffer(4);new DataView(t).setInt32(0,e,!1);var A=new Uint8Array(t);return Array.from(A)}function Hi(e){var t=e[e.length-1];return 3===t||4===t}function Yi(e){return e.toLowerCase().split("").reverse()}function Ji(e){var t=new Map(e.map((function(e,t){return[e,t]})));if(t.size!==e.length)throw Error("Labels must be unique, found duplicated label.");return function(e){var A=t.get(e);if(void 0===A)throw Error("Invalid dimension.");return A}}function ji(e){var t=Hi(e.shape),A=e.shape.slice(t?-3:-2),n=Object(s.a)(A,2);return{height:n[0],width:n[1]}}function Pi(e){return Math.pow(2,Math.floor(Math.log2(e)))}Oi.layerName="BitmapLayer",Oi.PHOTOMETRIC_INTERPRETATIONS=Ui,Oi.defaultProps=Object(d.a)({},_i,{image:{type:"object",value:{},compare:!0},transparentColor:{type:"array",value:[0,0,0],compare:!0},photometricInterpretation:{type:"number",value:2,compare:!0}}),Mi.defaultProps=_i,Mi.layerName="BitmapLayerWrapper";var Vi={pickable:{type:"boolean",value:!0,compare:!0},coordinateSystem:p.a.CARTESIAN,contrastLimits:{type:"array",value:[],compare:!0},channelsVisible:{type:"array",value:[],compare:!0},renderSubLayers:{type:"function",value:function(e){var t=e.tile,A=t.bbox,n=A.left,r=A.top,i=A.right,o=A.bottom,a=t.x,s=t.y,g=t.z,c=e.data,u=e.id,l=e.loader,I=e.maxZoom;if([n,o,i,r].some((function(e){return e<0}))||!c)return null;var C=l[0],h=ji(C),f=h.height,d=h.width,B=[n,c.height=(1.-lensBorderRadius);}float get_use_color_float(vec2 vTexCoord,int channelIndex){bool isFragInLensBounds=frag_in_lens_bounds(vTexCoord);bool inLensAndUseLens=lensEnabled&&isFragInLensBounds;return float(int((inLensAndUseLens&&channelIndex==lensSelection)||(!inLensAndUseLens)));}void mutate_color(inout vec3 rgb,float intensity0,float intensity1,float intensity2,float intensity3,float intensity4,float intensity5,vec2 vTexCoord){float useColorValue=0.;useColorValue=get_use_color_float(vTexCoord,0);rgb+=max(0.,min(1.,intensity0))*max(vec3(colors[0]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,1);rgb+=max(0.,min(1.,intensity1))*max(vec3(colors[1]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,2);rgb+=max(0.,min(1.,intensity2))*max(vec3(colors[2]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,3);rgb+=max(0.,min(1.,intensity3))*max(vec3(colors[3]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,4);rgb+=max(0.,min(1.,intensity4))*max(vec3(colors[4]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,5);rgb+=max(0.,min(1.,intensity5))*max(vec3(colors[5]),(1.-useColorValue)*vec3(1.,1.,1.));}",inject:{"fs:DECKGL_MUTATE_COLOR":"\n vec3 rgb = rgba.rgb;\n mutate_color(rgb, intensity0, intensity1, intensity2, intensity3, intensity4, intensity5, vTexCoord);\n rgba = vec4(rgb, 1.);\n ","fs:#main-end":"\n bool isFragOnLensBounds = frag_on_lens_bounds(vTexCoord);\n gl_FragColor = (lensEnabled && isFragOnLensBounds) ? vec4(lensBorderColor, 1.) : gl_FragColor;\n "}},Xi=[[0,0,255],[0,255,0],[255,0,255],[255,255,0],[255,128,0],[0,255,255],[255,255,255],[255,0,0]];function qi(e){if(e>Xi.length)throw new Error("Too many colors");return Xi.slice(0,e)}function zi(e){var t=e.colors,A=e.channelsVisible,n=t.map((function(e,t){return A[t]?e.map((function(e){return e/255})):yi})),r=vi-n.length;return wi(n,yi,r).reduce((function(e,t){return e.concat(t)}),[])}var $i={lensEnabled:{type:"boolean",value:!1,compare:!0},lensSelection:{type:"number",value:0,compare:!0},lensRadius:{type:"number",value:100,compare:!0},lensBorderColor:{type:"array",value:[255,255,255],compare:!0},lensBorderRadius:{type:"number",value:.02,compare:!0},colors:{type:"array",value:null,compare:!0}},eo=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"getShaders",value:function(){return Object(d.a)({},Object(C.a)(Object(I.a)(A.prototype),"getShaders",this).call(this),{modules:[Wi]})}},{key:"initializeState",value:function(){var e=this,t=this.getCurrentLayer();if(!t.isComposite){var A=function(){var A=t.props.viewportId,n=e.props.lensRadius,r=void 0===n?$i.lensRadius.value:n;if(A){var i=t.context.mousePosition,o=t.context.deck.viewManager.views.filter((function(e){return e.id===A}))[0],a=t.context.deck.viewManager.viewState[A],s=o.makeViewport(Object(d.a)({},a,{viewState:a}));if(i&&s.containsPixel(i)){var g={x:i.x-s.x,y:i.y-s.y},c=[[g.x-r,g.y],[g.x,g.y+r],[g.x+r,g.y],[g.x,g.y-r]].map((function(e,t){return s.unproject(e)[t%2]}));t.setState({unprojectLensBounds:c})}else t.setState({unprojectLensBounds:[0,0,0,0]})}else t.setState({unprojectLensBounds:[0,0,0,0]})};this.context.deck&&this.context.deck.eventManager.on({pointermove:A,pointerleave:A,wheel:A}),this.setState({onMouseMove:A,unprojectLensBounds:[0,0,0,0]})}}},{key:"draw",value:function(){var e,t=this.state.unprojectLensBounds,A=void 0===t?[0,0,0,0]:t,n=this.props,r=n.bounds,i=n.lensEnabled,o=void 0===i?$i.lensEnabled.value:i,a=n.lensSelection,g=void 0===a?$i.lensSelection.value:a,c=n.lensBorderColor,u=void 0===c?$i.lensBorderColor.value:c,l=n.lensBorderRadius,I=void 0===l?$i.lensBorderRadius.value:l,C=n.colors,h=n.channelsVisible,f=Object(s.a)(A,4),d=f[0],B=f[1],p=f[2],E=f[3],Q=Object(s.a)(r,4),y=Q[0],v=Q[1],m=Q[2],b=Q[3],w=(d-y)/(m-y),S=(B-b)/(v-b),F=(p-y)/(m-y),R=(E-b)/(v-b),D={majorLensAxis:(F-w)/2,minorLensAxis:(S-R)/2,lensCenter:[(F+w)/2,(S+R)/2],lensEnabled:o,lensSelection:g,lensBorderColor:u,lensBorderRadius:I,colors:zi({channelsVisible:h||this.selections.map((function(){return!0})),colors:C||qi(this.props.selections.length)})};null===(e=this.state.model)||void 0===e||e.setUniforms(D)}},{key:"finalizeState",value:function(){var e,t,A;this.context.deck&&this.context.deck.eventManager.off({pointermove:null===(e=this.state)||void 0===e?void 0:e.onMouseMove,pointerleave:null===(t=this.state)||void 0===t?void 0:t.onMouseMove,wheel:null===(A=this.state)||void 0===A?void 0:A.onMouseMove})}}]),A}(m.a);eo.extensionName="LensExtension",eo.defaultProps=$i;var to={name:"color-palette-module",fs:"#define GLSLIFY 1\nvec4 apply_transparent_color_1540259130(vec3 color,vec3 transparentColor,bool useTransparentColor,float opacity){return vec4(color,(color==transparentColor&&useTransparentColor)? 0. : opacity);}uniform vec3 transparentColor;uniform bool useTransparentColor;uniform float opacity;uniform vec3 colors[6];void mutate_color(inout vec3 rgb,float intensity0,float intensity1,float intensity2,float intensity3,float intensity4,float intensity5){rgb+=max(0.0,min(1.0,intensity0))*vec3(colors[0]);rgb+=max(0.0,min(1.0,intensity1))*vec3(colors[1]);rgb+=max(0.0,min(1.0,intensity2))*vec3(colors[2]);rgb+=max(0.0,min(1.0,intensity3))*vec3(colors[3]);rgb+=max(0.0,min(1.0,intensity4))*vec3(colors[4]);rgb+=max(0.0,min(1.0,intensity5))*vec3(colors[5]);}vec4 apply_opacity(vec3 rgb){return vec4(apply_transparent_color_1540259130(rgb,transparentColor,useTransparentColor,opacity));}",inject:{"fs:DECKGL_MUTATE_COLOR":"\n vec3 rgb = rgba.rgb;\n mutate_color(rgb, intensity0, intensity1, intensity2, intensity3, intensity4, intensity5);\n rgba = apply_opacity(rgb);\n "}},Ao={colors:{type:"array",value:null,compare:!0},opacity:{type:"number",value:1,compare:!0},transparentColor:{type:"array",value:null,compare:!0},useTransparentColor:{type:"boolean",value:!1,compare:!0}},no=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"getShaders",value:function(){return Object(d.a)({},Object(C.a)(Object(I.a)(A.prototype),"getShaders",this).call(this),{modules:[to]})}},{key:"draw",value:function(){var e,t=this.props,A=t.colors,n=t.channelsVisible,r=t.opacity,i=void 0===r?Ao.opacity.value:r,o=t.transparentColor,a=void 0===o?Ao.transparentColor.value:o,s=t.useTransparentColor,g=void 0===s?Ao.useTransparentColor.value:s,c={colors:zi({channelsVisible:n||this.selections.map((function(){return!0})),colors:A||qi(this.props.selections.length)}),opacity:i,transparentColor:(a||[0,0,0]).map((function(e){return e/255})),useTransparentColor:Boolean(g)};null===(e=this.state.model)||void 0===e||e.setUniforms(c)}}]),A}(m.a);no.extensionName="ColorPaletteExtension",no.defaultProps=Ao;var ro={name:"additive-colormap",fs:"#define GLSLIFY 1\nvec4 jet(float x_17){const float e0=0.0;const vec4 v0=vec4(0,0,0.5137254901960784,1);const float e1=0.125;const vec4 v1=vec4(0,0.23529411764705882,0.6666666666666666,1);const float e2=0.375;const vec4 v2=vec4(0.0196078431372549,1,1,1);const float e3=0.625;const vec4 v3=vec4(1,1,0,1);const float e4=0.875;const vec4 v4=vec4(0.9803921568627451,0,0,1);const float e5=1.0;const vec4 v5=vec4(0.5019607843137255,0,0,1);float a0=smoothstep(e0,e1,x_17);float a1=smoothstep(e1,e2,x_17);float a2=smoothstep(e2,e3,x_17);float a3=smoothstep(e3,e4,x_17);float a4=smoothstep(e4,e5,x_17);return max(mix(v0,v1,a0)*step(e0,x_17)*step(x_17,e1),max(mix(v1,v2,a1)*step(e1,x_17)*step(x_17,e2),max(mix(v2,v3,a2)*step(e2,x_17)*step(x_17,e3),max(mix(v3,v4,a3)*step(e3,x_17)*step(x_17,e4),mix(v4,v5,a4)*step(e4,x_17)*step(x_17,e5)))));}vec4 hsv(float x_18){const float e0=0.0;const vec4 v0=vec4(1,0,0,1);const float e1=0.169;const vec4 v1=vec4(0.9921568627450981,1,0.00784313725490196,1);const float e2=0.173;const vec4 v2=vec4(0.9686274509803922,1,0.00784313725490196,1);const float e3=0.337;const vec4 v3=vec4(0,0.9882352941176471,0.01568627450980392,1);const float e4=0.341;const vec4 v4=vec4(0,0.9882352941176471,0.0392156862745098,1);const float e5=0.506;const vec4 v5=vec4(0.00392156862745098,0.9764705882352941,1,1);const float e6=0.671;const vec4 v6=vec4(0.00784313725490196,0,0.9921568627450981,1);const float e7=0.675;const vec4 v7=vec4(0.03137254901960784,0,0.9921568627450981,1);const float e8=0.839;const vec4 v8=vec4(1,0,0.984313725490196,1);const float e9=0.843;const vec4 v9=vec4(1,0,0.9607843137254902,1);const float e10=1.0;const vec4 v10=vec4(1,0,0.023529411764705882,1);float a0=smoothstep(e0,e1,x_18);float a1=smoothstep(e1,e2,x_18);float a2=smoothstep(e2,e3,x_18);float a3=smoothstep(e3,e4,x_18);float a4=smoothstep(e4,e5,x_18);float a5=smoothstep(e5,e6,x_18);float a6=smoothstep(e6,e7,x_18);float a7=smoothstep(e7,e8,x_18);float a8=smoothstep(e8,e9,x_18);float a9=smoothstep(e9,e10,x_18);return max(mix(v0,v1,a0)*step(e0,x_18)*step(x_18,e1),max(mix(v1,v2,a1)*step(e1,x_18)*step(x_18,e2),max(mix(v2,v3,a2)*step(e2,x_18)*step(x_18,e3),max(mix(v3,v4,a3)*step(e3,x_18)*step(x_18,e4),max(mix(v4,v5,a4)*step(e4,x_18)*step(x_18,e5),max(mix(v5,v6,a5)*step(e5,x_18)*step(x_18,e6),max(mix(v6,v7,a6)*step(e6,x_18)*step(x_18,e7),max(mix(v7,v8,a7)*step(e7,x_18)*step(x_18,e8),max(mix(v8,v9,a8)*step(e8,x_18)*step(x_18,e9),mix(v9,v10,a9)*step(e9,x_18)*step(x_18,e10))))))))));}vec4 hot(float x_13){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.3;const vec4 v1=vec4(0.9019607843137255,0,0,1);const float e2=0.6;const vec4 v2=vec4(1,0.8235294117647058,0,1);const float e3=1.0;const vec4 v3=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_13);float a1=smoothstep(e1,e2,x_13);float a2=smoothstep(e2,e3,x_13);return max(mix(v0,v1,a0)*step(e0,x_13)*step(x_13,e1),max(mix(v1,v2,a1)*step(e1,x_13)*step(x_13,e2),mix(v2,v3,a2)*step(e2,x_13)*step(x_13,e3)));}vec4 cool(float x_24){const float e0=0.0;const vec4 v0=vec4(0.49019607843137253,0,0.7019607843137254,1);const float e1=0.13;const vec4 v1=vec4(0.4549019607843137,0,0.8549019607843137,1);const float e2=0.25;const vec4 v2=vec4(0.3843137254901961,0.2901960784313726,0.9294117647058824,1);const float e3=0.38;const vec4 v3=vec4(0.26666666666666666,0.5725490196078431,0.9058823529411765,1);const float e4=0.5;const vec4 v4=vec4(0,0.8,0.7725490196078432,1);const float e5=0.63;const vec4 v5=vec4(0,0.9686274509803922,0.5725490196078431,1);const float e6=0.75;const vec4 v6=vec4(0,1,0.34509803921568627,1);const float e7=0.88;const vec4 v7=vec4(0.1568627450980392,1,0.03137254901960784,1);const float e8=1.0;const vec4 v8=vec4(0.5764705882352941,1,0,1);float a0=smoothstep(e0,e1,x_24);float a1=smoothstep(e1,e2,x_24);float a2=smoothstep(e2,e3,x_24);float a3=smoothstep(e3,e4,x_24);float a4=smoothstep(e4,e5,x_24);float a5=smoothstep(e5,e6,x_24);float a6=smoothstep(e6,e7,x_24);float a7=smoothstep(e7,e8,x_24);return max(mix(v0,v1,a0)*step(e0,x_24)*step(x_24,e1),max(mix(v1,v2,a1)*step(e1,x_24)*step(x_24,e2),max(mix(v2,v3,a2)*step(e2,x_24)*step(x_24,e3),max(mix(v3,v4,a3)*step(e3,x_24)*step(x_24,e4),max(mix(v4,v5,a4)*step(e4,x_24)*step(x_24,e5),max(mix(v5,v6,a5)*step(e5,x_24)*step(x_24,e6),max(mix(v6,v7,a6)*step(e6,x_24)*step(x_24,e7),mix(v7,v8,a7)*step(e7,x_24)*step(x_24,e8))))))));}vec4 spring(float x_5){const float e0=0.0;const vec4 v0=vec4(1,0,1,1);const float e1=1.0;const vec4 v1=vec4(1,1,0,1);float a0=smoothstep(e0,e1,x_5);return mix(v0,v1,a0)*step(e0,x_5)*step(x_5,e1);}vec4 summer(float x_12){const float e0=0.0;const vec4 v0=vec4(0,0.5019607843137255,0.4,1);const float e1=1.0;const vec4 v1=vec4(1,1,0.4,1);float a0=smoothstep(e0,e1,x_12);return mix(v0,v1,a0)*step(e0,x_12)*step(x_12,e1);}vec4 autumn(float x_25){const float e0=0.0;const vec4 v0=vec4(1,0,0,1);const float e1=1.0;const vec4 v1=vec4(1,1,0,1);float a0=smoothstep(e0,e1,x_25);return mix(v0,v1,a0)*step(e0,x_25)*step(x_25,e1);}vec4 winter(float x_16){const float e0=0.0;const vec4 v0=vec4(0,0,1,1);const float e1=1.0;const vec4 v1=vec4(0,1,0.5019607843137255,1);float a0=smoothstep(e0,e1,x_16);return mix(v0,v1,a0)*step(e0,x_16)*step(x_16,e1);}vec4 bone(float x_15){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.376;const vec4 v1=vec4(0.32941176470588235,0.32941176470588235,0.4549019607843137,1);const float e2=0.753;const vec4 v2=vec4(0.6627450980392157,0.7843137254901961,0.7843137254901961,1);const float e3=1.0;const vec4 v3=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_15);float a1=smoothstep(e1,e2,x_15);float a2=smoothstep(e2,e3,x_15);return max(mix(v0,v1,a0)*step(e0,x_15)*step(x_15,e1),max(mix(v1,v2,a1)*step(e1,x_15)*step(x_15,e2),mix(v2,v3,a2)*step(e2,x_15)*step(x_15,e3)));}vec4 copper(float x_10){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.804;const vec4 v1=vec4(1,0.6274509803921569,0.4,1);const float e2=1.0;const vec4 v2=vec4(1,0.7803921568627451,0.4980392156862745,1);float a0=smoothstep(e0,e1,x_10);float a1=smoothstep(e1,e2,x_10);return max(mix(v0,v1,a0)*step(e0,x_10)*step(x_10,e1),mix(v1,v2,a1)*step(e1,x_10)*step(x_10,e2));}vec4 greys(float x_4){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=1.0;const vec4 v1=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_4);return mix(v0,v1,a0)*step(e0,x_4)*step(x_4,e1);}vec4 yignbu(float x_32){const float e0=0.0;const vec4 v0=vec4(0.03137254901960784,0.11372549019607843,0.34509803921568627,1);const float e1=0.125;const vec4 v1=vec4(0.1450980392156863,0.20392156862745098,0.5803921568627451,1);const float e2=0.25;const vec4 v2=vec4(0.13333333333333333,0.3686274509803922,0.6588235294117647,1);const float e3=0.375;const vec4 v3=vec4(0.11372549019607843,0.5686274509803921,0.7529411764705882,1);const float e4=0.5;const vec4 v4=vec4(0.2549019607843137,0.7137254901960784,0.7686274509803922,1);const float e5=0.625;const vec4 v5=vec4(0.4980392156862745,0.803921568627451,0.7333333333333333,1);const float e6=0.75;const vec4 v6=vec4(0.7803921568627451,0.9137254901960784,0.7058823529411765,1);const float e7=0.875;const vec4 v7=vec4(0.9294117647058824,0.9725490196078431,0.8509803921568627,1);const float e8=1.0;const vec4 v8=vec4(1,1,0.8509803921568627,1);float a0=smoothstep(e0,e1,x_32);float a1=smoothstep(e1,e2,x_32);float a2=smoothstep(e2,e3,x_32);float a3=smoothstep(e3,e4,x_32);float a4=smoothstep(e4,e5,x_32);float a5=smoothstep(e5,e6,x_32);float a6=smoothstep(e6,e7,x_32);float a7=smoothstep(e7,e8,x_32);return max(mix(v0,v1,a0)*step(e0,x_32)*step(x_32,e1),max(mix(v1,v2,a1)*step(e1,x_32)*step(x_32,e2),max(mix(v2,v3,a2)*step(e2,x_32)*step(x_32,e3),max(mix(v3,v4,a3)*step(e3,x_32)*step(x_32,e4),max(mix(v4,v5,a4)*step(e4,x_32)*step(x_32,e5),max(mix(v5,v6,a5)*step(e5,x_32)*step(x_32,e6),max(mix(v6,v7,a6)*step(e6,x_32)*step(x_32,e7),mix(v7,v8,a7)*step(e7,x_32)*step(x_32,e8))))))));}vec4 greens(float x_34){const float e0=0.0;const vec4 v0=vec4(0,0.26666666666666666,0.10588235294117647,1);const float e1=0.125;const vec4 v1=vec4(0,0.42745098039215684,0.17254901960784313,1);const float e2=0.25;const vec4 v2=vec4(0.13725490196078433,0.5450980392156862,0.27058823529411763,1);const float e3=0.375;const vec4 v3=vec4(0.2549019607843137,0.6705882352941176,0.36470588235294116,1);const float e4=0.5;const vec4 v4=vec4(0.4549019607843137,0.7686274509803922,0.4627450980392157,1);const float e5=0.625;const vec4 v5=vec4(0.6313725490196078,0.8509803921568627,0.6078431372549019,1);const float e6=0.75;const vec4 v6=vec4(0.7803921568627451,0.9137254901960784,0.7529411764705882,1);const float e7=0.875;const vec4 v7=vec4(0.8980392156862745,0.9607843137254902,0.8784313725490196,1);const float e8=1.0;const vec4 v8=vec4(0.9686274509803922,0.9882352941176471,0.9607843137254902,1);float a0=smoothstep(e0,e1,x_34);float a1=smoothstep(e1,e2,x_34);float a2=smoothstep(e2,e3,x_34);float a3=smoothstep(e3,e4,x_34);float a4=smoothstep(e4,e5,x_34);float a5=smoothstep(e5,e6,x_34);float a6=smoothstep(e6,e7,x_34);float a7=smoothstep(e7,e8,x_34);return max(mix(v0,v1,a0)*step(e0,x_34)*step(x_34,e1),max(mix(v1,v2,a1)*step(e1,x_34)*step(x_34,e2),max(mix(v2,v3,a2)*step(e2,x_34)*step(x_34,e3),max(mix(v3,v4,a3)*step(e3,x_34)*step(x_34,e4),max(mix(v4,v5,a4)*step(e4,x_34)*step(x_34,e5),max(mix(v5,v6,a5)*step(e5,x_34)*step(x_34,e6),max(mix(v6,v7,a6)*step(e6,x_34)*step(x_34,e7),mix(v7,v8,a7)*step(e7,x_34)*step(x_34,e8))))))));}vec4 yiorrd(float x_41){const float e0=0.0;const vec4 v0=vec4(0.5019607843137255,0,0.14901960784313725,1);const float e1=0.125;const vec4 v1=vec4(0.7411764705882353,0,0.14901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.8901960784313725,0.10196078431372549,0.10980392156862745,1);const float e3=0.375;const vec4 v3=vec4(0.9882352941176471,0.3058823529411765,0.16470588235294117,1);const float e4=0.5;const vec4 v4=vec4(0.9921568627450981,0.5529411764705883,0.23529411764705882,1);const float e5=0.625;const vec4 v5=vec4(0.996078431372549,0.6980392156862745,0.2980392156862745,1);const float e6=0.75;const vec4 v6=vec4(0.996078431372549,0.8509803921568627,0.4627450980392157,1);const float e7=0.875;const vec4 v7=vec4(1,0.9294117647058824,0.6274509803921569,1);const float e8=1.0;const vec4 v8=vec4(1,1,0.8,1);float a0=smoothstep(e0,e1,x_41);float a1=smoothstep(e1,e2,x_41);float a2=smoothstep(e2,e3,x_41);float a3=smoothstep(e3,e4,x_41);float a4=smoothstep(e4,e5,x_41);float a5=smoothstep(e5,e6,x_41);float a6=smoothstep(e6,e7,x_41);float a7=smoothstep(e7,e8,x_41);return max(mix(v0,v1,a0)*step(e0,x_41)*step(x_41,e1),max(mix(v1,v2,a1)*step(e1,x_41)*step(x_41,e2),max(mix(v2,v3,a2)*step(e2,x_41)*step(x_41,e3),max(mix(v3,v4,a3)*step(e3,x_41)*step(x_41,e4),max(mix(v4,v5,a4)*step(e4,x_41)*step(x_41,e5),max(mix(v5,v6,a5)*step(e5,x_41)*step(x_41,e6),max(mix(v6,v7,a6)*step(e6,x_41)*step(x_41,e7),mix(v7,v8,a7)*step(e7,x_41)*step(x_41,e8))))))));}vec4 bluered(float x_23){const float e0=0.0;const vec4 v0=vec4(0,0,1,1);const float e1=1.0;const vec4 v1=vec4(1,0,0,1);float a0=smoothstep(e0,e1,x_23);return mix(v0,v1,a0)*step(e0,x_23)*step(x_23,e1);}vec4 rdbu(float x_1){const float e0=0.0;const vec4 v0=vec4(0.0196078431372549,0.0392156862745098,0.6745098039215687,1);const float e1=0.35;const vec4 v1=vec4(0.41568627450980394,0.5372549019607843,0.9686274509803922,1);const float e2=0.5;const vec4 v2=vec4(0.7450980392156863,0.7450980392156863,0.7450980392156863,1);const float e3=0.6;const vec4 v3=vec4(0.8627450980392157,0.6666666666666666,0.5176470588235295,1);const float e4=0.7;const vec4 v4=vec4(0.9019607843137255,0.5686274509803921,0.35294117647058826,1);const float e5=1.0;const vec4 v5=vec4(0.6980392156862745,0.0392156862745098,0.10980392156862745,1);float a0=smoothstep(e0,e1,x_1);float a1=smoothstep(e1,e2,x_1);float a2=smoothstep(e2,e3,x_1);float a3=smoothstep(e3,e4,x_1);float a4=smoothstep(e4,e5,x_1);return max(mix(v0,v1,a0)*step(e0,x_1)*step(x_1,e1),max(mix(v1,v2,a1)*step(e1,x_1)*step(x_1,e2),max(mix(v2,v3,a2)*step(e2,x_1)*step(x_1,e3),max(mix(v3,v4,a3)*step(e3,x_1)*step(x_1,e4),mix(v4,v5,a4)*step(e4,x_1)*step(x_1,e5)))));}vec4 picnic(float x_42){const float e0=0.0;const vec4 v0=vec4(0,0,1,1);const float e1=0.1;const vec4 v1=vec4(0.2,0.6,1,1);const float e2=0.2;const vec4 v2=vec4(0.4,0.8,1,1);const float e3=0.3;const vec4 v3=vec4(0.6,0.8,1,1);const float e4=0.4;const vec4 v4=vec4(0.8,0.8,1,1);const float e5=0.5;const vec4 v5=vec4(1,1,1,1);const float e6=0.6;const vec4 v6=vec4(1,0.8,1,1);const float e7=0.7;const vec4 v7=vec4(1,0.6,1,1);const float e8=0.8;const vec4 v8=vec4(1,0.4,0.8,1);const float e9=0.9;const vec4 v9=vec4(1,0.4,0.4,1);const float e10=1.0;const vec4 v10=vec4(1,0,0,1);float a0=smoothstep(e0,e1,x_42);float a1=smoothstep(e1,e2,x_42);float a2=smoothstep(e2,e3,x_42);float a3=smoothstep(e3,e4,x_42);float a4=smoothstep(e4,e5,x_42);float a5=smoothstep(e5,e6,x_42);float a6=smoothstep(e6,e7,x_42);float a7=smoothstep(e7,e8,x_42);float a8=smoothstep(e8,e9,x_42);float a9=smoothstep(e9,e10,x_42);return max(mix(v0,v1,a0)*step(e0,x_42)*step(x_42,e1),max(mix(v1,v2,a1)*step(e1,x_42)*step(x_42,e2),max(mix(v2,v3,a2)*step(e2,x_42)*step(x_42,e3),max(mix(v3,v4,a3)*step(e3,x_42)*step(x_42,e4),max(mix(v4,v5,a4)*step(e4,x_42)*step(x_42,e5),max(mix(v5,v6,a5)*step(e5,x_42)*step(x_42,e6),max(mix(v6,v7,a6)*step(e6,x_42)*step(x_42,e7),max(mix(v7,v8,a7)*step(e7,x_42)*step(x_42,e8),max(mix(v8,v9,a8)*step(e8,x_42)*step(x_42,e9),mix(v9,v10,a9)*step(e9,x_42)*step(x_42,e10))))))))));}vec4 rainbow(float x_31){const float e0=0.0;const vec4 v0=vec4(0.5882352941176471,0,0.35294117647058826,1);const float e1=0.125;const vec4 v1=vec4(0,0,0.7843137254901961,1);const float e2=0.25;const vec4 v2=vec4(0,0.09803921568627451,1,1);const float e3=0.375;const vec4 v3=vec4(0,0.596078431372549,1,1);const float e4=0.5;const vec4 v4=vec4(0.17254901960784313,1,0.5882352941176471,1);const float e5=0.625;const vec4 v5=vec4(0.592156862745098,1,0,1);const float e6=0.75;const vec4 v6=vec4(1,0.9176470588235294,0,1);const float e7=0.875;const vec4 v7=vec4(1,0.43529411764705883,0,1);const float e8=1.0;const vec4 v8=vec4(1,0,0,1);float a0=smoothstep(e0,e1,x_31);float a1=smoothstep(e1,e2,x_31);float a2=smoothstep(e2,e3,x_31);float a3=smoothstep(e3,e4,x_31);float a4=smoothstep(e4,e5,x_31);float a5=smoothstep(e5,e6,x_31);float a6=smoothstep(e6,e7,x_31);float a7=smoothstep(e7,e8,x_31);return max(mix(v0,v1,a0)*step(e0,x_31)*step(x_31,e1),max(mix(v1,v2,a1)*step(e1,x_31)*step(x_31,e2),max(mix(v2,v3,a2)*step(e2,x_31)*step(x_31,e3),max(mix(v3,v4,a3)*step(e3,x_31)*step(x_31,e4),max(mix(v4,v5,a4)*step(e4,x_31)*step(x_31,e5),max(mix(v5,v6,a5)*step(e5,x_31)*step(x_31,e6),max(mix(v6,v7,a6)*step(e6,x_31)*step(x_31,e7),mix(v7,v8,a7)*step(e7,x_31)*step(x_31,e8))))))));}vec4 portland(float x_21){const float e0=0.0;const vec4 v0=vec4(0.047058823529411764,0.2,0.5137254901960784,1);const float e1=0.25;const vec4 v1=vec4(0.0392156862745098,0.5333333333333333,0.7294117647058823,1);const float e2=0.5;const vec4 v2=vec4(0.9490196078431372,0.8274509803921568,0.2196078431372549,1);const float e3=0.75;const vec4 v3=vec4(0.9490196078431372,0.5607843137254902,0.2196078431372549,1);const float e4=1.0;const vec4 v4=vec4(0.8509803921568627,0.11764705882352941,0.11764705882352941,1);float a0=smoothstep(e0,e1,x_21);float a1=smoothstep(e1,e2,x_21);float a2=smoothstep(e2,e3,x_21);float a3=smoothstep(e3,e4,x_21);return max(mix(v0,v1,a0)*step(e0,x_21)*step(x_21,e1),max(mix(v1,v2,a1)*step(e1,x_21)*step(x_21,e2),max(mix(v2,v3,a2)*step(e2,x_21)*step(x_21,e3),mix(v3,v4,a3)*step(e3,x_21)*step(x_21,e4))));}vec4 blackbody(float x_38){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.2;const vec4 v1=vec4(0.9019607843137255,0,0,1);const float e2=0.4;const vec4 v2=vec4(0.9019607843137255,0.8235294117647058,0,1);const float e3=0.7;const vec4 v3=vec4(1,1,1,1);const float e4=1.0;const vec4 v4=vec4(0.6274509803921569,0.7843137254901961,1,1);float a0=smoothstep(e0,e1,x_38);float a1=smoothstep(e1,e2,x_38);float a2=smoothstep(e2,e3,x_38);float a3=smoothstep(e3,e4,x_38);return max(mix(v0,v1,a0)*step(e0,x_38)*step(x_38,e1),max(mix(v1,v2,a1)*step(e1,x_38)*step(x_38,e2),max(mix(v2,v3,a2)*step(e2,x_38)*step(x_38,e3),mix(v3,v4,a3)*step(e3,x_38)*step(x_38,e4))));}vec4 earth(float x_29){const float e0=0.0;const vec4 v0=vec4(0,0,0.5098039215686274,1);const float e1=0.1;const vec4 v1=vec4(0,0.7058823529411765,0.7058823529411765,1);const float e2=0.2;const vec4 v2=vec4(0.1568627450980392,0.8235294117647058,0.1568627450980392,1);const float e3=0.4;const vec4 v3=vec4(0.9019607843137255,0.9019607843137255,0.19607843137254902,1);const float e4=0.6;const vec4 v4=vec4(0.47058823529411764,0.27450980392156865,0.0784313725490196,1);const float e5=1.0;const vec4 v5=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_29);float a1=smoothstep(e1,e2,x_29);float a2=smoothstep(e2,e3,x_29);float a3=smoothstep(e3,e4,x_29);float a4=smoothstep(e4,e5,x_29);return max(mix(v0,v1,a0)*step(e0,x_29)*step(x_29,e1),max(mix(v1,v2,a1)*step(e1,x_29)*step(x_29,e2),max(mix(v2,v3,a2)*step(e2,x_29)*step(x_29,e3),max(mix(v3,v4,a3)*step(e3,x_29)*step(x_29,e4),mix(v4,v5,a4)*step(e4,x_29)*step(x_29,e5)))));}vec4 electric(float x_9){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.15;const vec4 v1=vec4(0.11764705882352941,0,0.39215686274509803,1);const float e2=0.4;const vec4 v2=vec4(0.47058823529411764,0,0.39215686274509803,1);const float e3=0.6;const vec4 v3=vec4(0.6274509803921569,0.35294117647058826,0,1);const float e4=0.8;const vec4 v4=vec4(0.9019607843137255,0.7843137254901961,0,1);const float e5=1.0;const vec4 v5=vec4(1,0.9803921568627451,0.8627450980392157,1);float a0=smoothstep(e0,e1,x_9);float a1=smoothstep(e1,e2,x_9);float a2=smoothstep(e2,e3,x_9);float a3=smoothstep(e3,e4,x_9);float a4=smoothstep(e4,e5,x_9);return max(mix(v0,v1,a0)*step(e0,x_9)*step(x_9,e1),max(mix(v1,v2,a1)*step(e1,x_9)*step(x_9,e2),max(mix(v2,v3,a2)*step(e2,x_9)*step(x_9,e3),max(mix(v3,v4,a3)*step(e3,x_9)*step(x_9,e4),mix(v4,v5,a4)*step(e4,x_9)*step(x_9,e5)))));}vec4 alpha(float x_0){const float e0=0.0;const vec4 v0=vec4(1,1,1,0);const float e1=1.0;const vec4 v1=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_0);return mix(v0,v1,a0)*step(e0,x_0)*step(x_0,e1);}vec4 viridis(float x_22){const float e0=0.0;const vec4 v0=vec4(0.26666666666666666,0.00392156862745098,0.32941176470588235,1);const float e1=0.13;const vec4 v1=vec4(0.2784313725490196,0.17254901960784313,0.47843137254901963,1);const float e2=0.25;const vec4 v2=vec4(0.23137254901960785,0.3176470588235294,0.5450980392156862,1);const float e3=0.38;const vec4 v3=vec4(0.17254901960784313,0.44313725490196076,0.5568627450980392,1);const float e4=0.5;const vec4 v4=vec4(0.12941176470588237,0.5647058823529412,0.5529411764705883,1);const float e5=0.63;const vec4 v5=vec4(0.15294117647058825,0.6784313725490196,0.5058823529411764,1);const float e6=0.75;const vec4 v6=vec4(0.3607843137254902,0.7843137254901961,0.38823529411764707,1);const float e7=0.88;const vec4 v7=vec4(0.6666666666666666,0.8627450980392157,0.19607843137254902,1);const float e8=1.0;const vec4 v8=vec4(0.9921568627450981,0.9058823529411765,0.1450980392156863,1);float a0=smoothstep(e0,e1,x_22);float a1=smoothstep(e1,e2,x_22);float a2=smoothstep(e2,e3,x_22);float a3=smoothstep(e3,e4,x_22);float a4=smoothstep(e4,e5,x_22);float a5=smoothstep(e5,e6,x_22);float a6=smoothstep(e6,e7,x_22);float a7=smoothstep(e7,e8,x_22);return max(mix(v0,v1,a0)*step(e0,x_22)*step(x_22,e1),max(mix(v1,v2,a1)*step(e1,x_22)*step(x_22,e2),max(mix(v2,v3,a2)*step(e2,x_22)*step(x_22,e3),max(mix(v3,v4,a3)*step(e3,x_22)*step(x_22,e4),max(mix(v4,v5,a4)*step(e4,x_22)*step(x_22,e5),max(mix(v5,v6,a5)*step(e5,x_22)*step(x_22,e6),max(mix(v6,v7,a6)*step(e6,x_22)*step(x_22,e7),mix(v7,v8,a7)*step(e7,x_22)*step(x_22,e8))))))));}vec4 inferno(float x_30){const float e0=0.0;const vec4 v0=vec4(0,0,0.01568627450980392,1);const float e1=0.13;const vec4 v1=vec4(0.12156862745098039,0.047058823529411764,0.2823529411764706,1);const float e2=0.25;const vec4 v2=vec4(0.3333333333333333,0.058823529411764705,0.42745098039215684,1);const float e3=0.38;const vec4 v3=vec4(0.5333333333333333,0.13333333333333333,0.41568627450980394,1);const float e4=0.5;const vec4 v4=vec4(0.7294117647058823,0.21176470588235294,0.3333333333333333,1);const float e5=0.63;const vec4 v5=vec4(0.8901960784313725,0.34901960784313724,0.2,1);const float e6=0.75;const vec4 v6=vec4(0.9764705882352941,0.5490196078431373,0.0392156862745098,1);const float e7=0.88;const vec4 v7=vec4(0.9764705882352941,0.788235294117647,0.19607843137254902,1);const float e8=1.0;const vec4 v8=vec4(0.9882352941176471,1,0.6431372549019608,1);float a0=smoothstep(e0,e1,x_30);float a1=smoothstep(e1,e2,x_30);float a2=smoothstep(e2,e3,x_30);float a3=smoothstep(e3,e4,x_30);float a4=smoothstep(e4,e5,x_30);float a5=smoothstep(e5,e6,x_30);float a6=smoothstep(e6,e7,x_30);float a7=smoothstep(e7,e8,x_30);return max(mix(v0,v1,a0)*step(e0,x_30)*step(x_30,e1),max(mix(v1,v2,a1)*step(e1,x_30)*step(x_30,e2),max(mix(v2,v3,a2)*step(e2,x_30)*step(x_30,e3),max(mix(v3,v4,a3)*step(e3,x_30)*step(x_30,e4),max(mix(v4,v5,a4)*step(e4,x_30)*step(x_30,e5),max(mix(v5,v6,a5)*step(e5,x_30)*step(x_30,e6),max(mix(v6,v7,a6)*step(e6,x_30)*step(x_30,e7),mix(v7,v8,a7)*step(e7,x_30)*step(x_30,e8))))))));}vec4 magma(float x_33){const float e0=0.0;const vec4 v0=vec4(0,0,0.01568627450980392,1);const float e1=0.13;const vec4 v1=vec4(0.10980392156862745,0.06274509803921569,0.26666666666666666,1);const float e2=0.25;const vec4 v2=vec4(0.30980392156862746,0.07058823529411765,0.4823529411764706,1);const float e3=0.38;const vec4 v3=vec4(0.5058823529411764,0.1450980392156863,0.5058823529411764,1);const float e4=0.5;const vec4 v4=vec4(0.7098039215686275,0.21176470588235294,0.47843137254901963,1);const float e5=0.63;const vec4 v5=vec4(0.8980392156862745,0.3137254901960784,0.39215686274509803,1);const float e6=0.75;const vec4 v6=vec4(0.984313725490196,0.5294117647058824,0.3803921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.996078431372549,0.7607843137254902,0.5294117647058824,1);const float e8=1.0;const vec4 v8=vec4(0.9882352941176471,0.9921568627450981,0.7490196078431373,1);float a0=smoothstep(e0,e1,x_33);float a1=smoothstep(e1,e2,x_33);float a2=smoothstep(e2,e3,x_33);float a3=smoothstep(e3,e4,x_33);float a4=smoothstep(e4,e5,x_33);float a5=smoothstep(e5,e6,x_33);float a6=smoothstep(e6,e7,x_33);float a7=smoothstep(e7,e8,x_33);return max(mix(v0,v1,a0)*step(e0,x_33)*step(x_33,e1),max(mix(v1,v2,a1)*step(e1,x_33)*step(x_33,e2),max(mix(v2,v3,a2)*step(e2,x_33)*step(x_33,e3),max(mix(v3,v4,a3)*step(e3,x_33)*step(x_33,e4),max(mix(v4,v5,a4)*step(e4,x_33)*step(x_33,e5),max(mix(v5,v6,a5)*step(e5,x_33)*step(x_33,e6),max(mix(v6,v7,a6)*step(e6,x_33)*step(x_33,e7),mix(v7,v8,a7)*step(e7,x_33)*step(x_33,e8))))))));}vec4 plasma(float x_3){const float e0=0.0;const vec4 v0=vec4(0.050980392156862744,0.03137254901960784,0.5294117647058824,1);const float e1=0.13;const vec4 v1=vec4(0.29411764705882354,0.011764705882352941,0.6313725490196078,1);const float e2=0.25;const vec4 v2=vec4(0.49019607843137253,0.011764705882352941,0.6588235294117647,1);const float e3=0.38;const vec4 v3=vec4(0.6588235294117647,0.13333333333333333,0.5882352941176471,1);const float e4=0.5;const vec4 v4=vec4(0.796078431372549,0.27450980392156865,0.4745098039215686,1);const float e5=0.63;const vec4 v5=vec4(0.8980392156862745,0.4196078431372549,0.36470588235294116,1);const float e6=0.75;const vec4 v6=vec4(0.9725490196078431,0.5803921568627451,0.2549019607843137,1);const float e7=0.88;const vec4 v7=vec4(0.9921568627450981,0.7647058823529411,0.1568627450980392,1);const float e8=1.0;const vec4 v8=vec4(0.9411764705882353,0.9764705882352941,0.12941176470588237,1);float a0=smoothstep(e0,e1,x_3);float a1=smoothstep(e1,e2,x_3);float a2=smoothstep(e2,e3,x_3);float a3=smoothstep(e3,e4,x_3);float a4=smoothstep(e4,e5,x_3);float a5=smoothstep(e5,e6,x_3);float a6=smoothstep(e6,e7,x_3);float a7=smoothstep(e7,e8,x_3);return max(mix(v0,v1,a0)*step(e0,x_3)*step(x_3,e1),max(mix(v1,v2,a1)*step(e1,x_3)*step(x_3,e2),max(mix(v2,v3,a2)*step(e2,x_3)*step(x_3,e3),max(mix(v3,v4,a3)*step(e3,x_3)*step(x_3,e4),max(mix(v4,v5,a4)*step(e4,x_3)*step(x_3,e5),max(mix(v5,v6,a5)*step(e5,x_3)*step(x_3,e6),max(mix(v6,v7,a6)*step(e6,x_3)*step(x_3,e7),mix(v7,v8,a7)*step(e7,x_3)*step(x_3,e8))))))));}vec4 warm(float x_43){const float e0=0.0;const vec4 v0=vec4(0.49019607843137253,0,0.7019607843137254,1);const float e1=0.13;const vec4 v1=vec4(0.6745098039215687,0,0.7333333333333333,1);const float e2=0.25;const vec4 v2=vec4(0.8588235294117647,0,0.6666666666666666,1);const float e3=0.38;const vec4 v3=vec4(1,0,0.5098039215686274,1);const float e4=0.5;const vec4 v4=vec4(1,0.24705882352941178,0.2901960784313726,1);const float e5=0.63;const vec4 v5=vec4(1,0.4823529411764706,0,1);const float e6=0.75;const vec4 v6=vec4(0.9176470588235294,0.6901960784313725,0,1);const float e7=0.88;const vec4 v7=vec4(0.7450980392156863,0.8941176470588236,0,1);const float e8=1.0;const vec4 v8=vec4(0.5764705882352941,1,0,1);float a0=smoothstep(e0,e1,x_43);float a1=smoothstep(e1,e2,x_43);float a2=smoothstep(e2,e3,x_43);float a3=smoothstep(e3,e4,x_43);float a4=smoothstep(e4,e5,x_43);float a5=smoothstep(e5,e6,x_43);float a6=smoothstep(e6,e7,x_43);float a7=smoothstep(e7,e8,x_43);return max(mix(v0,v1,a0)*step(e0,x_43)*step(x_43,e1),max(mix(v1,v2,a1)*step(e1,x_43)*step(x_43,e2),max(mix(v2,v3,a2)*step(e2,x_43)*step(x_43,e3),max(mix(v3,v4,a3)*step(e3,x_43)*step(x_43,e4),max(mix(v4,v5,a4)*step(e4,x_43)*step(x_43,e5),max(mix(v5,v6,a5)*step(e5,x_43)*step(x_43,e6),max(mix(v6,v7,a6)*step(e6,x_43)*step(x_43,e7),mix(v7,v8,a7)*step(e7,x_43)*step(x_43,e8))))))));}vec4 rainbow_soft_1310269270(float x_14){const float e0=0.0;const vec4 v0=vec4(0.49019607843137253,0,0.7019607843137254,1);const float e1=0.1;const vec4 v1=vec4(0.7803921568627451,0,0.7058823529411765,1);const float e2=0.2;const vec4 v2=vec4(1,0,0.4745098039215686,1);const float e3=0.3;const vec4 v3=vec4(1,0.4235294117647059,0,1);const float e4=0.4;const vec4 v4=vec4(0.8705882352941177,0.7607843137254902,0,1);const float e5=0.5;const vec4 v5=vec4(0.5882352941176471,1,0,1);const float e6=0.6;const vec4 v6=vec4(0,1,0.21568627450980393,1);const float e7=0.7;const vec4 v7=vec4(0,0.9647058823529412,0.5882352941176471,1);const float e8=0.8;const vec4 v8=vec4(0.19607843137254902,0.6549019607843137,0.8705882352941177,1);const float e9=0.9;const vec4 v9=vec4(0.403921568627451,0.2,0.9215686274509803,1);const float e10=1.0;const vec4 v10=vec4(0.48627450980392156,0,0.7294117647058823,1);float a0=smoothstep(e0,e1,x_14);float a1=smoothstep(e1,e2,x_14);float a2=smoothstep(e2,e3,x_14);float a3=smoothstep(e3,e4,x_14);float a4=smoothstep(e4,e5,x_14);float a5=smoothstep(e5,e6,x_14);float a6=smoothstep(e6,e7,x_14);float a7=smoothstep(e7,e8,x_14);float a8=smoothstep(e8,e9,x_14);float a9=smoothstep(e9,e10,x_14);return max(mix(v0,v1,a0)*step(e0,x_14)*step(x_14,e1),max(mix(v1,v2,a1)*step(e1,x_14)*step(x_14,e2),max(mix(v2,v3,a2)*step(e2,x_14)*step(x_14,e3),max(mix(v3,v4,a3)*step(e3,x_14)*step(x_14,e4),max(mix(v4,v5,a4)*step(e4,x_14)*step(x_14,e5),max(mix(v5,v6,a5)*step(e5,x_14)*step(x_14,e6),max(mix(v6,v7,a6)*step(e6,x_14)*step(x_14,e7),max(mix(v7,v8,a7)*step(e7,x_14)*step(x_14,e8),max(mix(v8,v9,a8)*step(e8,x_14)*step(x_14,e9),mix(v9,v10,a9)*step(e9,x_14)*step(x_14,e10))))))))));}vec4 bathymetry(float x_36){const float e0=0.0;const vec4 v0=vec4(0.1568627450980392,0.10196078431372549,0.17254901960784313,1);const float e1=0.13;const vec4 v1=vec4(0.23137254901960785,0.19215686274509805,0.35294117647058826,1);const float e2=0.25;const vec4 v2=vec4(0.25098039215686274,0.2980392156862745,0.5450980392156862,1);const float e3=0.38;const vec4 v3=vec4(0.24705882352941178,0.43137254901960786,0.592156862745098,1);const float e4=0.5;const vec4 v4=vec4(0.2823529411764706,0.5568627450980392,0.6196078431372549,1);const float e5=0.63;const vec4 v5=vec4(0.3333333333333333,0.6823529411764706,0.6392156862745098,1);const float e6=0.75;const vec4 v6=vec4(0.47058823529411764,0.807843137254902,0.6392156862745098,1);const float e7=0.88;const vec4 v7=vec4(0.7333333333333333,0.9019607843137255,0.6745098039215687,1);const float e8=1.0;const vec4 v8=vec4(0.9921568627450981,0.996078431372549,0.8,1);float a0=smoothstep(e0,e1,x_36);float a1=smoothstep(e1,e2,x_36);float a2=smoothstep(e2,e3,x_36);float a3=smoothstep(e3,e4,x_36);float a4=smoothstep(e4,e5,x_36);float a5=smoothstep(e5,e6,x_36);float a6=smoothstep(e6,e7,x_36);float a7=smoothstep(e7,e8,x_36);return max(mix(v0,v1,a0)*step(e0,x_36)*step(x_36,e1),max(mix(v1,v2,a1)*step(e1,x_36)*step(x_36,e2),max(mix(v2,v3,a2)*step(e2,x_36)*step(x_36,e3),max(mix(v3,v4,a3)*step(e3,x_36)*step(x_36,e4),max(mix(v4,v5,a4)*step(e4,x_36)*step(x_36,e5),max(mix(v5,v6,a5)*step(e5,x_36)*step(x_36,e6),max(mix(v6,v7,a6)*step(e6,x_36)*step(x_36,e7),mix(v7,v8,a7)*step(e7,x_36)*step(x_36,e8))))))));}vec4 cdom(float x_7){const float e0=0.0;const vec4 v0=vec4(0.1843137254901961,0.058823529411764705,0.24313725490196078,1);const float e1=0.13;const vec4 v1=vec4(0.3411764705882353,0.09019607843137255,0.33725490196078434,1);const float e2=0.25;const vec4 v2=vec4(0.5098039215686274,0.10980392156862745,0.38823529411764707,1);const float e3=0.38;const vec4 v3=vec4(0.6705882352941176,0.1607843137254902,0.3764705882352941,1);const float e4=0.5;const vec4 v4=vec4(0.807843137254902,0.2627450980392157,0.33725490196078434,1);const float e5=0.63;const vec4 v5=vec4(0.9019607843137255,0.41568627450980394,0.32941176470588235,1);const float e6=0.75;const vec4 v6=vec4(0.9490196078431372,0.5843137254901961,0.403921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.9764705882352941,0.7568627450980392,0.5294117647058824,1);const float e8=1.0;const vec4 v8=vec4(0.996078431372549,0.9294117647058824,0.6901960784313725,1);float a0=smoothstep(e0,e1,x_7);float a1=smoothstep(e1,e2,x_7);float a2=smoothstep(e2,e3,x_7);float a3=smoothstep(e3,e4,x_7);float a4=smoothstep(e4,e5,x_7);float a5=smoothstep(e5,e6,x_7);float a6=smoothstep(e6,e7,x_7);float a7=smoothstep(e7,e8,x_7);return max(mix(v0,v1,a0)*step(e0,x_7)*step(x_7,e1),max(mix(v1,v2,a1)*step(e1,x_7)*step(x_7,e2),max(mix(v2,v3,a2)*step(e2,x_7)*step(x_7,e3),max(mix(v3,v4,a3)*step(e3,x_7)*step(x_7,e4),max(mix(v4,v5,a4)*step(e4,x_7)*step(x_7,e5),max(mix(v5,v6,a5)*step(e5,x_7)*step(x_7,e6),max(mix(v6,v7,a6)*step(e6,x_7)*step(x_7,e7),mix(v7,v8,a7)*step(e7,x_7)*step(x_7,e8))))))));}vec4 chlorophyll(float x_6){const float e0=0.0;const vec4 v0=vec4(0.07058823529411765,0.1411764705882353,0.0784313725490196,1);const float e1=0.13;const vec4 v1=vec4(0.09803921568627451,0.24705882352941178,0.1607843137254902,1);const float e2=0.25;const vec4 v2=vec4(0.09411764705882353,0.3568627450980392,0.23137254901960785,1);const float e3=0.38;const vec4 v3=vec4(0.050980392156862744,0.4666666666666667,0.2823529411764706,1);const float e4=0.5;const vec4 v4=vec4(0.07058823529411765,0.5803921568627451,0.3137254901960784,1);const float e5=0.63;const vec4 v5=vec4(0.3137254901960784,0.6784313725490196,0.34901960784313724,1);const float e6=0.75;const vec4 v6=vec4(0.5176470588235295,0.7686274509803922,0.47843137254901963,1);const float e7=0.88;const vec4 v7=vec4(0.6862745098039216,0.8666666666666667,0.6352941176470588,1);const float e8=1.0;const vec4 v8=vec4(0.8431372549019608,0.9764705882352941,0.8156862745098039,1);float a0=smoothstep(e0,e1,x_6);float a1=smoothstep(e1,e2,x_6);float a2=smoothstep(e2,e3,x_6);float a3=smoothstep(e3,e4,x_6);float a4=smoothstep(e4,e5,x_6);float a5=smoothstep(e5,e6,x_6);float a6=smoothstep(e6,e7,x_6);float a7=smoothstep(e7,e8,x_6);return max(mix(v0,v1,a0)*step(e0,x_6)*step(x_6,e1),max(mix(v1,v2,a1)*step(e1,x_6)*step(x_6,e2),max(mix(v2,v3,a2)*step(e2,x_6)*step(x_6,e3),max(mix(v3,v4,a3)*step(e3,x_6)*step(x_6,e4),max(mix(v4,v5,a4)*step(e4,x_6)*step(x_6,e5),max(mix(v5,v6,a5)*step(e5,x_6)*step(x_6,e6),max(mix(v6,v7,a6)*step(e6,x_6)*step(x_6,e7),mix(v7,v8,a7)*step(e7,x_6)*step(x_6,e8))))))));}vec4 density(float x_19){const float e0=0.0;const vec4 v0=vec4(0.21176470588235294,0.054901960784313725,0.1411764705882353,1);const float e1=0.13;const vec4 v1=vec4(0.34901960784313724,0.09019607843137255,0.3137254901960784,1);const float e2=0.25;const vec4 v2=vec4(0.43137254901960786,0.17647058823529413,0.5176470588235295,1);const float e3=0.38;const vec4 v3=vec4(0.47058823529411764,0.30196078431372547,0.6980392156862745,1);const float e4=0.5;const vec4 v4=vec4(0.47058823529411764,0.44313725490196076,0.8352941176470589,1);const float e5=0.63;const vec4 v5=vec4(0.45098039215686275,0.592156862745098,0.8941176470588236,1);const float e6=0.75;const vec4 v6=vec4(0.5254901960784314,0.7254901960784313,0.8901960784313725,1);const float e7=0.88;const vec4 v7=vec4(0.6941176470588235,0.8392156862745098,0.8901960784313725,1);const float e8=1.0;const vec4 v8=vec4(0.9019607843137255,0.9450980392156862,0.9450980392156862,1);float a0=smoothstep(e0,e1,x_19);float a1=smoothstep(e1,e2,x_19);float a2=smoothstep(e2,e3,x_19);float a3=smoothstep(e3,e4,x_19);float a4=smoothstep(e4,e5,x_19);float a5=smoothstep(e5,e6,x_19);float a6=smoothstep(e6,e7,x_19);float a7=smoothstep(e7,e8,x_19);return max(mix(v0,v1,a0)*step(e0,x_19)*step(x_19,e1),max(mix(v1,v2,a1)*step(e1,x_19)*step(x_19,e2),max(mix(v2,v3,a2)*step(e2,x_19)*step(x_19,e3),max(mix(v3,v4,a3)*step(e3,x_19)*step(x_19,e4),max(mix(v4,v5,a4)*step(e4,x_19)*step(x_19,e5),max(mix(v5,v6,a5)*step(e5,x_19)*step(x_19,e6),max(mix(v6,v7,a6)*step(e6,x_19)*step(x_19,e7),mix(v7,v8,a7)*step(e7,x_19)*step(x_19,e8))))))));}vec4 freesurface_blue_3154355989(float x_35){const float e0=0.0;const vec4 v0=vec4(0.11764705882352941,0.01568627450980392,0.43137254901960786,1);const float e1=0.13;const vec4 v1=vec4(0.1843137254901961,0.054901960784313725,0.6901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.1607843137254902,0.17647058823529413,0.9254901960784314,1);const float e3=0.38;const vec4 v3=vec4(0.09803921568627451,0.38823529411764707,0.8313725490196079,1);const float e4=0.5;const vec4 v4=vec4(0.26666666666666666,0.5137254901960784,0.7843137254901961,1);const float e5=0.63;const vec4 v5=vec4(0.4470588235294118,0.611764705882353,0.7725490196078432,1);const float e6=0.75;const vec4 v6=vec4(0.615686274509804,0.7098039215686275,0.796078431372549,1);const float e7=0.88;const vec4 v7=vec4(0.7843137254901961,0.8156862745098039,0.8470588235294118,1);const float e8=1.0;const vec4 v8=vec4(0.9450980392156862,0.9294117647058824,0.9254901960784314,1);float a0=smoothstep(e0,e1,x_35);float a1=smoothstep(e1,e2,x_35);float a2=smoothstep(e2,e3,x_35);float a3=smoothstep(e3,e4,x_35);float a4=smoothstep(e4,e5,x_35);float a5=smoothstep(e5,e6,x_35);float a6=smoothstep(e6,e7,x_35);float a7=smoothstep(e7,e8,x_35);return max(mix(v0,v1,a0)*step(e0,x_35)*step(x_35,e1),max(mix(v1,v2,a1)*step(e1,x_35)*step(x_35,e2),max(mix(v2,v3,a2)*step(e2,x_35)*step(x_35,e3),max(mix(v3,v4,a3)*step(e3,x_35)*step(x_35,e4),max(mix(v4,v5,a4)*step(e4,x_35)*step(x_35,e5),max(mix(v5,v6,a5)*step(e5,x_35)*step(x_35,e6),max(mix(v6,v7,a6)*step(e6,x_35)*step(x_35,e7),mix(v7,v8,a7)*step(e7,x_35)*step(x_35,e8))))))));}vec4 freesurface_red_1679163293(float x_20){const float e0=0.0;const vec4 v0=vec4(0.23529411764705882,0.03529411764705882,0.07058823529411765,1);const float e1=0.13;const vec4 v1=vec4(0.39215686274509803,0.06666666666666667,0.10588235294117647,1);const float e2=0.25;const vec4 v2=vec4(0.5568627450980392,0.0784313725490196,0.11372549019607843,1);const float e3=0.38;const vec4 v3=vec4(0.6941176470588235,0.16862745098039217,0.10588235294117647,1);const float e4=0.5;const vec4 v4=vec4(0.7529411764705882,0.3411764705882353,0.24705882352941178,1);const float e5=0.63;const vec4 v5=vec4(0.803921568627451,0.49019607843137253,0.4117647058823529,1);const float e6=0.75;const vec4 v6=vec4(0.8470588235294118,0.6352941176470588,0.5803921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.8901960784313725,0.7803921568627451,0.7568627450980392,1);const float e8=1.0;const vec4 v8=vec4(0.9450980392156862,0.9294117647058824,0.9254901960784314,1);float a0=smoothstep(e0,e1,x_20);float a1=smoothstep(e1,e2,x_20);float a2=smoothstep(e2,e3,x_20);float a3=smoothstep(e3,e4,x_20);float a4=smoothstep(e4,e5,x_20);float a5=smoothstep(e5,e6,x_20);float a6=smoothstep(e6,e7,x_20);float a7=smoothstep(e7,e8,x_20);return max(mix(v0,v1,a0)*step(e0,x_20)*step(x_20,e1),max(mix(v1,v2,a1)*step(e1,x_20)*step(x_20,e2),max(mix(v2,v3,a2)*step(e2,x_20)*step(x_20,e3),max(mix(v3,v4,a3)*step(e3,x_20)*step(x_20,e4),max(mix(v4,v5,a4)*step(e4,x_20)*step(x_20,e5),max(mix(v5,v6,a5)*step(e5,x_20)*step(x_20,e6),max(mix(v6,v7,a6)*step(e6,x_20)*step(x_20,e7),mix(v7,v8,a7)*step(e7,x_20)*step(x_20,e8))))))));}vec4 oxygen(float x_11){const float e0=0.0;const vec4 v0=vec4(0.25098039215686274,0.0196078431372549,0.0196078431372549,1);const float e1=0.13;const vec4 v1=vec4(0.41568627450980394,0.023529411764705882,0.058823529411764705,1);const float e2=0.25;const vec4 v2=vec4(0.5647058823529412,0.10196078431372549,0.027450980392156862,1);const float e3=0.38;const vec4 v3=vec4(0.6588235294117647,0.25098039215686274,0.011764705882352941,1);const float e4=0.5;const vec4 v4=vec4(0.7372549019607844,0.39215686274509803,0.01568627450980392,1);const float e5=0.63;const vec4 v5=vec4(0.807843137254902,0.5333333333333333,0.043137254901960784,1);const float e6=0.75;const vec4 v6=vec4(0.8627450980392157,0.6823529411764706,0.09803921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.9058823529411765,0.8431372549019608,0.17254901960784313,1);const float e8=1.0;const vec4 v8=vec4(0.9725490196078431,0.996078431372549,0.4117647058823529,1);float a0=smoothstep(e0,e1,x_11);float a1=smoothstep(e1,e2,x_11);float a2=smoothstep(e2,e3,x_11);float a3=smoothstep(e3,e4,x_11);float a4=smoothstep(e4,e5,x_11);float a5=smoothstep(e5,e6,x_11);float a6=smoothstep(e6,e7,x_11);float a7=smoothstep(e7,e8,x_11);return max(mix(v0,v1,a0)*step(e0,x_11)*step(x_11,e1),max(mix(v1,v2,a1)*step(e1,x_11)*step(x_11,e2),max(mix(v2,v3,a2)*step(e2,x_11)*step(x_11,e3),max(mix(v3,v4,a3)*step(e3,x_11)*step(x_11,e4),max(mix(v4,v5,a4)*step(e4,x_11)*step(x_11,e5),max(mix(v5,v6,a5)*step(e5,x_11)*step(x_11,e6),max(mix(v6,v7,a6)*step(e6,x_11)*step(x_11,e7),mix(v7,v8,a7)*step(e7,x_11)*step(x_11,e8))))))));}vec4 par(float x_28){const float e0=0.0;const vec4 v0=vec4(0.2,0.0784313725490196,0.09411764705882353,1);const float e1=0.13;const vec4 v1=vec4(0.35294117647058826,0.12549019607843137,0.13725490196078433,1);const float e2=0.25;const vec4 v2=vec4(0.5058823529411764,0.17254901960784313,0.13333333333333333,1);const float e3=0.38;const vec4 v3=vec4(0.6235294117647059,0.26666666666666666,0.09803921568627451,1);const float e4=0.5;const vec4 v4=vec4(0.7137254901960784,0.38823529411764707,0.07450980392156863,1);const float e5=0.63;const vec4 v5=vec4(0.7803921568627451,0.5254901960784314,0.08627450980392157,1);const float e6=0.75;const vec4 v6=vec4(0.8313725490196079,0.6705882352941176,0.13725490196078433,1);const float e7=0.88;const vec4 v7=vec4(0.8666666666666667,0.8235294117647058,0.21176470588235294,1);const float e8=1.0;const vec4 v8=vec4(0.8823529411764706,0.9921568627450981,0.29411764705882354,1);float a0=smoothstep(e0,e1,x_28);float a1=smoothstep(e1,e2,x_28);float a2=smoothstep(e2,e3,x_28);float a3=smoothstep(e3,e4,x_28);float a4=smoothstep(e4,e5,x_28);float a5=smoothstep(e5,e6,x_28);float a6=smoothstep(e6,e7,x_28);float a7=smoothstep(e7,e8,x_28);return max(mix(v0,v1,a0)*step(e0,x_28)*step(x_28,e1),max(mix(v1,v2,a1)*step(e1,x_28)*step(x_28,e2),max(mix(v2,v3,a2)*step(e2,x_28)*step(x_28,e3),max(mix(v3,v4,a3)*step(e3,x_28)*step(x_28,e4),max(mix(v4,v5,a4)*step(e4,x_28)*step(x_28,e5),max(mix(v5,v6,a5)*step(e5,x_28)*step(x_28,e6),max(mix(v6,v7,a6)*step(e6,x_28)*step(x_28,e7),mix(v7,v8,a7)*step(e7,x_28)*step(x_28,e8))))))));}vec4 phase(float x_39){const float e0=0.0;const vec4 v0=vec4(0.5686274509803921,0.4117647058823529,0.07058823529411765,1);const float e1=0.13;const vec4 v1=vec4(0.7215686274509804,0.2784313725490196,0.14901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.7294117647058823,0.22745098039215686,0.45098039215686275,1);const float e3=0.38;const vec4 v3=vec4(0.6274509803921569,0.2784313725490196,0.7254901960784313,1);const float e4=0.5;const vec4 v4=vec4(0.43137254901960786,0.3803921568627451,0.8549019607843137,1);const float e5=0.63;const vec4 v5=vec4(0.19607843137254902,0.4823529411764706,0.6431372549019608,1);const float e6=0.75;const vec4 v6=vec4(0.12156862745098039,0.5137254901960784,0.43137254901960786,1);const float e7=0.88;const vec4 v7=vec4(0.30196078431372547,0.5058823529411764,0.13333333333333333,1);const float e8=1.0;const vec4 v8=vec4(0.5686274509803921,0.4117647058823529,0.07058823529411765,1);float a0=smoothstep(e0,e1,x_39);float a1=smoothstep(e1,e2,x_39);float a2=smoothstep(e2,e3,x_39);float a3=smoothstep(e3,e4,x_39);float a4=smoothstep(e4,e5,x_39);float a5=smoothstep(e5,e6,x_39);float a6=smoothstep(e6,e7,x_39);float a7=smoothstep(e7,e8,x_39);return max(mix(v0,v1,a0)*step(e0,x_39)*step(x_39,e1),max(mix(v1,v2,a1)*step(e1,x_39)*step(x_39,e2),max(mix(v2,v3,a2)*step(e2,x_39)*step(x_39,e3),max(mix(v3,v4,a3)*step(e3,x_39)*step(x_39,e4),max(mix(v4,v5,a4)*step(e4,x_39)*step(x_39,e5),max(mix(v5,v6,a5)*step(e5,x_39)*step(x_39,e6),max(mix(v6,v7,a6)*step(e6,x_39)*step(x_39,e7),mix(v7,v8,a7)*step(e7,x_39)*step(x_39,e8))))))));}vec4 salinity(float x_26){const float e0=0.0;const vec4 v0=vec4(0.16470588235294117,0.09411764705882353,0.4235294117647059,1);const float e1=0.13;const vec4 v1=vec4(0.12941176470588237,0.19607843137254902,0.6352941176470588,1);const float e2=0.25;const vec4 v2=vec4(0.058823529411764705,0.35294117647058826,0.5686274509803921,1);const float e3=0.38;const vec4 v3=vec4(0.1568627450980392,0.4627450980392157,0.5372549019607843,1);const float e4=0.5;const vec4 v4=vec4(0.23137254901960785,0.5725490196078431,0.5294117647058824,1);const float e5=0.63;const vec4 v5=vec4(0.30980392156862746,0.6862745098039216,0.49411764705882355,1);const float e6=0.75;const vec4 v6=vec4(0.47058823529411764,0.796078431372549,0.40784313725490196,1);const float e7=0.88;const vec4 v7=vec4(0.7568627450980392,0.8666666666666667,0.39215686274509803,1);const float e8=1.0;const vec4 v8=vec4(0.9921568627450981,0.9372549019607843,0.6039215686274509,1);float a0=smoothstep(e0,e1,x_26);float a1=smoothstep(e1,e2,x_26);float a2=smoothstep(e2,e3,x_26);float a3=smoothstep(e3,e4,x_26);float a4=smoothstep(e4,e5,x_26);float a5=smoothstep(e5,e6,x_26);float a6=smoothstep(e6,e7,x_26);float a7=smoothstep(e7,e8,x_26);return max(mix(v0,v1,a0)*step(e0,x_26)*step(x_26,e1),max(mix(v1,v2,a1)*step(e1,x_26)*step(x_26,e2),max(mix(v2,v3,a2)*step(e2,x_26)*step(x_26,e3),max(mix(v3,v4,a3)*step(e3,x_26)*step(x_26,e4),max(mix(v4,v5,a4)*step(e4,x_26)*step(x_26,e5),max(mix(v5,v6,a5)*step(e5,x_26)*step(x_26,e6),max(mix(v6,v7,a6)*step(e6,x_26)*step(x_26,e7),mix(v7,v8,a7)*step(e7,x_26)*step(x_26,e8))))))));}vec4 temperature(float x_8){const float e0=0.0;const vec4 v0=vec4(0.01568627450980392,0.13725490196078433,0.2,1);const float e1=0.13;const vec4 v1=vec4(0.09019607843137255,0.2,0.47843137254901963,1);const float e2=0.25;const vec4 v2=vec4(0.3333333333333333,0.23137254901960785,0.615686274509804,1);const float e3=0.38;const vec4 v3=vec4(0.5058823529411764,0.30980392156862746,0.5607843137254902,1);const float e4=0.5;const vec4 v4=vec4(0.6862745098039216,0.37254901960784315,0.5098039215686274,1);const float e5=0.63;const vec4 v5=vec4(0.8705882352941177,0.4392156862745098,0.396078431372549,1);const float e6=0.75;const vec4 v6=vec4(0.9764705882352941,0.5725490196078431,0.25882352941176473,1);const float e7=0.88;const vec4 v7=vec4(0.9764705882352941,0.7686274509803922,0.2549019607843137,1);const float e8=1.0;const vec4 v8=vec4(0.9098039215686274,0.9803921568627451,0.3568627450980392,1);float a0=smoothstep(e0,e1,x_8);float a1=smoothstep(e1,e2,x_8);float a2=smoothstep(e2,e3,x_8);float a3=smoothstep(e3,e4,x_8);float a4=smoothstep(e4,e5,x_8);float a5=smoothstep(e5,e6,x_8);float a6=smoothstep(e6,e7,x_8);float a7=smoothstep(e7,e8,x_8);return max(mix(v0,v1,a0)*step(e0,x_8)*step(x_8,e1),max(mix(v1,v2,a1)*step(e1,x_8)*step(x_8,e2),max(mix(v2,v3,a2)*step(e2,x_8)*step(x_8,e3),max(mix(v3,v4,a3)*step(e3,x_8)*step(x_8,e4),max(mix(v4,v5,a4)*step(e4,x_8)*step(x_8,e5),max(mix(v5,v6,a5)*step(e5,x_8)*step(x_8,e6),max(mix(v6,v7,a6)*step(e6,x_8)*step(x_8,e7),mix(v7,v8,a7)*step(e7,x_8)*step(x_8,e8))))))));}vec4 turbidity(float x_40){const float e0=0.0;const vec4 v0=vec4(0.13333333333333333,0.12156862745098039,0.10588235294117647,1);const float e1=0.13;const vec4 v1=vec4(0.2549019607843137,0.19607843137254902,0.1607843137254902,1);const float e2=0.25;const vec4 v2=vec4(0.3843137254901961,0.27058823529411763,0.20392156862745098,1);const float e3=0.38;const vec4 v3=vec4(0.5137254901960784,0.34901960784313724,0.2235294117647059,1);const float e4=0.5;const vec4 v4=vec4(0.6313725490196078,0.4392156862745098,0.23137254901960785,1);const float e5=0.63;const vec4 v5=vec4(0.7254901960784313,0.5490196078431373,0.25882352941176473,1);const float e6=0.75;const vec4 v6=vec4(0.792156862745098,0.6823529411764706,0.34509803921568627,1);const float e7=0.88;const vec4 v7=vec4(0.8470588235294118,0.8196078431372549,0.49411764705882355,1);const float e8=1.0;const vec4 v8=vec4(0.9137254901960784,0.9647058823529412,0.6705882352941176,1);float a0=smoothstep(e0,e1,x_40);float a1=smoothstep(e1,e2,x_40);float a2=smoothstep(e2,e3,x_40);float a3=smoothstep(e3,e4,x_40);float a4=smoothstep(e4,e5,x_40);float a5=smoothstep(e5,e6,x_40);float a6=smoothstep(e6,e7,x_40);float a7=smoothstep(e7,e8,x_40);return max(mix(v0,v1,a0)*step(e0,x_40)*step(x_40,e1),max(mix(v1,v2,a1)*step(e1,x_40)*step(x_40,e2),max(mix(v2,v3,a2)*step(e2,x_40)*step(x_40,e3),max(mix(v3,v4,a3)*step(e3,x_40)*step(x_40,e4),max(mix(v4,v5,a4)*step(e4,x_40)*step(x_40,e5),max(mix(v5,v6,a5)*step(e5,x_40)*step(x_40,e6),max(mix(v6,v7,a6)*step(e6,x_40)*step(x_40,e7),mix(v7,v8,a7)*step(e7,x_40)*step(x_40,e8))))))));}vec4 velocity_blue_297387650(float x_2){const float e0=0.0;const vec4 v0=vec4(0.06666666666666667,0.12549019607843137,0.25098039215686274,1);const float e1=0.13;const vec4 v1=vec4(0.13725490196078433,0.20392156862745098,0.4549019607843137,1);const float e2=0.25;const vec4 v2=vec4(0.11372549019607843,0.3176470588235294,0.611764705882353,1);const float e3=0.38;const vec4 v3=vec4(0.12156862745098039,0.44313725490196076,0.6352941176470588,1);const float e4=0.5;const vec4 v4=vec4(0.19607843137254902,0.5647058823529412,0.6627450980392157,1);const float e5=0.63;const vec4 v5=vec4(0.3411764705882353,0.6784313725490196,0.6901960784313725,1);const float e6=0.75;const vec4 v6=vec4(0.5843137254901961,0.7686274509803922,0.7411764705882353,1);const float e7=0.88;const vec4 v7=vec4(0.796078431372549,0.8666666666666667,0.8274509803921568,1);const float e8=1.0;const vec4 v8=vec4(0.996078431372549,0.984313725490196,0.9019607843137255,1);float a0=smoothstep(e0,e1,x_2);float a1=smoothstep(e1,e2,x_2);float a2=smoothstep(e2,e3,x_2);float a3=smoothstep(e3,e4,x_2);float a4=smoothstep(e4,e5,x_2);float a5=smoothstep(e5,e6,x_2);float a6=smoothstep(e6,e7,x_2);float a7=smoothstep(e7,e8,x_2);return max(mix(v0,v1,a0)*step(e0,x_2)*step(x_2,e1),max(mix(v1,v2,a1)*step(e1,x_2)*step(x_2,e2),max(mix(v2,v3,a2)*step(e2,x_2)*step(x_2,e3),max(mix(v3,v4,a3)*step(e3,x_2)*step(x_2,e4),max(mix(v4,v5,a4)*step(e4,x_2)*step(x_2,e5),max(mix(v5,v6,a5)*step(e5,x_2)*step(x_2,e6),max(mix(v6,v7,a6)*step(e6,x_2)*step(x_2,e7),mix(v7,v8,a7)*step(e7,x_2)*step(x_2,e8))))))));}vec4 velocity_green_2558432129(float x_27){const float e0=0.0;const vec4 v0=vec4(0.09019607843137255,0.13725490196078433,0.07450980392156863,1);const float e1=0.13;const vec4 v1=vec4(0.09411764705882353,0.25098039215686274,0.14901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.043137254901960784,0.37254901960784315,0.17647058823529413,1);const float e3=0.38;const vec4 v3=vec4(0.15294117647058825,0.4823529411764706,0.13725490196078433,1);const float e4=0.5;const vec4 v4=vec4(0.37254901960784315,0.5725490196078431,0.047058823529411764,1);const float e5=0.63;const vec4 v5=vec4(0.596078431372549,0.6470588235294118,0.07058823529411765,1);const float e6=0.75;const vec4 v6=vec4(0.788235294117647,0.7294117647058823,0.27058823529411763,1);const float e7=0.88;const vec4 v7=vec4(0.9137254901960784,0.8470588235294118,0.5372549019607843,1);const float e8=1.0;const vec4 v8=vec4(1,0.9921568627450981,0.803921568627451,1);float a0=smoothstep(e0,e1,x_27);float a1=smoothstep(e1,e2,x_27);float a2=smoothstep(e2,e3,x_27);float a3=smoothstep(e3,e4,x_27);float a4=smoothstep(e4,e5,x_27);float a5=smoothstep(e5,e6,x_27);float a6=smoothstep(e6,e7,x_27);float a7=smoothstep(e7,e8,x_27);return max(mix(v0,v1,a0)*step(e0,x_27)*step(x_27,e1),max(mix(v1,v2,a1)*step(e1,x_27)*step(x_27,e2),max(mix(v2,v3,a2)*step(e2,x_27)*step(x_27,e3),max(mix(v3,v4,a3)*step(e3,x_27)*step(x_27,e4),max(mix(v4,v5,a4)*step(e4,x_27)*step(x_27,e5),max(mix(v5,v6,a5)*step(e5,x_27)*step(x_27,e6),max(mix(v6,v7,a6)*step(e6,x_27)*step(x_27,e7),mix(v7,v8,a7)*step(e7,x_27)*step(x_27,e8))))))));}vec4 cubehelix(float x_37){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.07;const vec4 v1=vec4(0.08627450980392157,0.0196078431372549,0.23137254901960785,1);const float e2=0.13;const vec4 v2=vec4(0.23529411764705882,0.01568627450980392,0.4117647058823529,1);const float e3=0.2;const vec4 v3=vec4(0.42745098039215684,0.00392156862745098,0.5294117647058824,1);const float e4=0.27;const vec4 v4=vec4(0.6313725490196078,0,0.5764705882352941,1);const float e5=0.33;const vec4 v5=vec4(0.8235294117647058,0.00784313725490196,0.5568627450980392,1);const float e6=0.4;const vec4 v6=vec4(0.984313725490196,0.043137254901960784,0.4823529411764706,1);const float e7=0.47;const vec4 v7=vec4(1,0.11372549019607843,0.3803921568627451,1);const float e8=0.53;const vec4 v8=vec4(1,0.21176470588235294,0.27058823529411763,1);const float e9=0.6;const vec4 v9=vec4(1,0.3333333333333333,0.1803921568627451,1);const float e10=0.67;const vec4 v10=vec4(1,0.47058823529411764,0.13333333333333333,1);const float e11=0.73;const vec4 v11=vec4(1,0.615686274509804,0.1450980392156863,1);const float e12=0.8;const vec4 v12=vec4(0.9450980392156862,0.7490196078431373,0.2235294117647059,1);const float e13=0.87;const vec4 v13=vec4(0.8784313725490196,0.8627450980392157,0.36470588235294116,1);const float e14=0.93;const vec4 v14=vec4(0.8549019607843137,0.9450980392156862,0.5568627450980392,1);const float e15=1.0;const vec4 v15=vec4(0.8901960784313725,0.9921568627450981,0.7764705882352941,1);float a0=smoothstep(e0,e1,x_37);float a1=smoothstep(e1,e2,x_37);float a2=smoothstep(e2,e3,x_37);float a3=smoothstep(e3,e4,x_37);float a4=smoothstep(e4,e5,x_37);float a5=smoothstep(e5,e6,x_37);float a6=smoothstep(e6,e7,x_37);float a7=smoothstep(e7,e8,x_37);float a8=smoothstep(e8,e9,x_37);float a9=smoothstep(e9,e10,x_37);float a10=smoothstep(e10,e11,x_37);float a11=smoothstep(e11,e12,x_37);float a12=smoothstep(e12,e13,x_37);float a13=smoothstep(e13,e14,x_37);float a14=smoothstep(e14,e15,x_37);return max(mix(v0,v1,a0)*step(e0,x_37)*step(x_37,e1),max(mix(v1,v2,a1)*step(e1,x_37)*step(x_37,e2),max(mix(v2,v3,a2)*step(e2,x_37)*step(x_37,e3),max(mix(v3,v4,a3)*step(e3,x_37)*step(x_37,e4),max(mix(v4,v5,a4)*step(e4,x_37)*step(x_37,e5),max(mix(v5,v6,a5)*step(e5,x_37)*step(x_37,e6),max(mix(v6,v7,a6)*step(e6,x_37)*step(x_37,e7),max(mix(v7,v8,a7)*step(e7,x_37)*step(x_37,e8),max(mix(v8,v9,a8)*step(e8,x_37)*step(x_37,e9),max(mix(v9,v10,a9)*step(e9,x_37)*step(x_37,e10),max(mix(v10,v11,a10)*step(e10,x_37)*step(x_37,e11),max(mix(v11,v12,a11)*step(e11,x_37)*step(x_37,e12),max(mix(v12,v13,a12)*step(e12,x_37)*step(x_37,e13),max(mix(v13,v14,a13)*step(e13,x_37)*step(x_37,e14),mix(v14,v15,a14)*step(e14,x_37)*step(x_37,e15)))))))))))))));}vec4 apply_transparent_color_452471729(vec3 color,vec3 transparentColor,bool useTransparentColor,float opacity){return vec4(color,(color==transparentColor&&useTransparentColor)? 0. : opacity);}uniform float opacity;uniform bool useTransparentColor;vec4 colormap(float intensity){return vec4(apply_transparent_color_452471729(COLORMAP_FUNCTION(min(1.,intensity)).xyz,COLORMAP_FUNCTION(0.).xyz,useTransparentColor,opacity));}",inject:{"fs:DECKGL_MUTATE_COLOR":"\n float intensityCombo = 0.;\n intensityCombo += max(0.,intensity0);\n intensityCombo += max(0.,intensity1);\n intensityCombo += max(0.,intensity2);\n intensityCombo += max(0.,intensity3);\n intensityCombo += max(0.,intensity4);\n intensityCombo += max(0.,intensity5);\n rgba = colormap(intensityCombo);\n"}},io={colormap:{type:"string",value:"viridis",compare:!0},opacity:{type:"number",value:1,compare:!0},useTransparentColor:{type:"boolean",value:!1,compare:!0}},oo=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"getShaders",value:function(){var e;return{defines:{COLORMAP_FUNCTION:(null===this||void 0===this||null===(e=this.props)||void 0===e?void 0:e.colormap)||io.colormap.value},modules:[ro]}}},{key:"updateState",value:function(e){var t=e.props,n=e.oldProps,r=e.changeFlags,i=Object(c.a)(e,["props","oldProps","changeFlags"]);if(Object(C.a)(Object(I.a)(A.prototype),"updateState",this).call(this,Object(d.a)({props:t,oldProps:n,changeFlags:r},i)),t.colormap!==n.colormap){var o=this.context.gl;this.state.model&&(this.state.model.delete(),this.setState({model:this._getModel(o)}))}}},{key:"draw",value:function(){var e,t=this.props,A=t.useTransparentColor,n=void 0===A?io.useTransparentColor.value:A,r=t.opacity,i={opacity:void 0===r?io.opacity.value:r,useTransparentColor:n};null===(e=this.state.model)||void 0===e||e.setUniforms(i)}}]),A}(m.a);oo.extensionName="AdditiveColormapExtension",oo.defaultProps=io;var ao={pickable:{type:"boolean",value:!0,compare:!0},coordinateSystem:p.a.CARTESIAN,contrastLimits:{type:"array",value:[],compare:!0},channelsVisible:{type:"array",value:[],compare:!0},selections:{type:"array",value:[],compare:!0},domain:{type:"array",value:[],compare:!0},viewportId:{type:"string",value:"",compare:!0},loader:{type:"object",value:{getRaster:function(){var e=Object(a.a)(o.a.mark((function e(){return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",{data:[],height:0,width:0});case 1:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),dtype:"Uint16"},compare:!0},onClick:{type:"function",value:null,compare:!0},onViewportLoad:{type:"function",value:null,compare:!0},interpolation:{type:"number",value:F.default.NEAREST,compare:!0},extensions:{type:"array",value:[new no],compare:!0}},so=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"finalizeState",value:function(){this.state.abortController.abort()}},{key:"updateState",value:function(e){var t=this,A=e.props,n=e.oldProps,r=A.loader!==n.loader,i=A.selections!==n.selections;if(r||i){var o=this.props,a=o.loader,s=o.selections,g=void 0===s?[]:s,c=o.onViewportLoad,u=new AbortController;this.setState({abortController:u});var l=u.signal,I=g.map((function(e){return a.getRaster({selection:e,signal:l})}));Promise.all(I).then((function(e){var A={data:e.map((function(e){return e.data})),width:e[0].width,height:e[0].height};Hi(a.shape)&&(A.data=A.data[0],A.data.length===A.width*A.height*3&&(A.format=F.default.RGB,A.dataFormat=F.default.RGB)),c&&c(A),t.setState(Object(d.a)({},A))})).catch((function(e){if("__vivSignalAborted"!==e)throw e}))}}},{key:"getPickingInfo",value:function(e){var t=e.info,A=e.sourceLayer;return t.sourceLayer=A,t.tile=A.props.tile,t}},{key:"renderLayers",value:function(){var e=this.props,t=e.loader,A=e.id,n=t.dtype,r=this.state,i=r.width,o=r.height,a=r.data;if(!i||!o)return null;var s=[0,o,i,0];if(Hi(t.shape)){var g=t.meta.photometricInterpretation,c=void 0===g?2:g;return new Oi(this.props,{image:this.state,photometricInterpretation:c,bounds:s,id:"image-sub-layer-".concat(s,"-").concat(A)})}return new Ni(this.props,{channelData:{data:a,height:o,width:i},bounds:s,id:"image-sub-layer-".concat(s,"-").concat(A),dtype:n})}}]),A}(v.a);so.layerName="ImageLayer",so.defaultProps=ao;var go={pickable:{type:"boolean",value:!0,compare:!0},onHover:{type:"function",value:null,compare:!1},contrastLimits:{type:"array",value:[],compare:!0},channelsVisible:{type:"array",value:[],compare:!0},domain:{type:"array",value:[],compare:!0},viewportId:{type:"string",value:"",compare:!0},maxRequests:{type:"number",value:10,compare:!0},onClick:{type:"function",value:null,compare:!0},refinementStrategy:{type:"string",value:null,compare:!0},excludeBackground:{type:"boolean",value:!1,compare:!0},extensions:{type:"array",value:[new no],compare:!0}},co=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"renderLayers",value:function(){var e=this.props,t=e.loader,A=e.selections,n=e.opacity,r=e.viewportId,i=e.onTileError,s=e.onHover,g=e.id,c=e.onClick,u=e.modelMatrix,l=e.excludeBackground,I=e.refinementStrategy,C=t[0],h=C.tileSize,f=C.dtype,d=function(){var e=Object(a.a)(o.a.mark((function e(n){var r,i,a,s,g,c,u,l;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=n.x,i=n.y,a=n.z,s=n.signal,A&&0!==A.length){e.next=3;break}return e.abrupt("return",null);case 3:return g=Math.round(-a),c=function(e){var A={x:r,y:i,selection:e,signal:s};return t[g].getTile(A)},e.prev=5,e.next=8,Promise.all(A.map(c));case 8:if(u=e.sent,l={data:u.map((function(e){return e.data})),width:u[0].width,height:u[0].height},!Hi(t[g].shape)){e.next=14;break}return l.data=l.data[0],l.data.length===l.width*l.height*3&&(l.format=F.default.RGB,l.dataFormat=F.default.RGB),e.abrupt("return",l);case 14:return e.abrupt("return",l);case 17:if(e.prev=17,e.t0=e.catch(5),"__vivSignalAborted"!==e.t0){e.next=21;break}return e.abrupt("return",null);case 21:throw e.t0;case 22:case"end":return e.stop()}}),e,null,[[5,17]])})));return function(t){return e.apply(this,arguments)}}(),B=ji(t[0]),p=B.height,E=B.width,Q=new Ki(this.props,{id:"Tiled-Image-".concat(g),getTileData:d,dtype:f,tileSize:h,zoomOffset:Math.round(Math.log2(u?u.getScale()[0]:1)),extent:[0,0,E,p],minZoom:Math.round(-(t.length-1)),maxZoom:0,refinementStrategy:I||(1===n?"best-available":"no-overlap"),updateTriggers:{getTileData:[t,A]},onTileError:i||t[0].onTileError}),y=t[t.length-1],v="function"===typeof y.getRaster,m=u?u.clone():new S.Matrix4;return[v&&!l&&new so(this.props,{id:"Background-Image-".concat(g),loader:y,modelMatrix:m.scale(Math.pow(2,t.length-1)),visible:!r||this.context.viewport.id===r,onHover:s,onClick:c,interpolation:F.default.LINEAR,onViewportLoad:null}),Q]}}]),A}(v.a);co.layerName="MultiscaleImageLayer",co.defaultProps=go;var uo={pickable:{type:"boolean",value:!0,compare:!0},loader:{type:"object",value:{getRaster:function(){var e=Object(a.a)(o.a.mark((function e(){return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",{data:[],height:0,width:0});case 1:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),getRasterSize:function(){return{height:0,width:0}},dtype:"2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0,i=Array.isArray(e)?e[0]:e,o=ji(i),a=o.width,s=o.height,g=i.shape[i.labels.indexOf("z")],c=Math.log2(Math.min(t.width/a,t.height/s))-A,u=Ri(i),l={target:(r||new S.Matrix4).transformPoint((n?u:new S.Matrix4).transformPoint([a/2,s/2,n?g/2:0])),zoom:c};return l}lo.layerName="OverviewLayer",lo.defaultProps=uo;var fo=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"renderLayers",value:function(){var e,t=this.props,A=t.id,n=t.unit,r=t.size,i=t.position,o=t.viewState,a=t.length,g=Co(o),c=o.zoom,u=.05*(g[2][0]-g[0][0]),l=Math.max(Math.pow(2,1.5-c),.007*(g[2][1]-g[0][1])),I=u*r,C=function(e,t,A){var n=e[2][0]-e[0][0];switch(t){case"bottom-right":return[e[2][1]-(e[2][1]-e[0][1])*A,e[2][0]-n*A];case"top-right":return[(e[2][1]-e[0][1])*A,e[2][0]-n*A];case"top-left":return[(e[2][1]-e[0][1])*A,n*A];case"bottom-left":return[e[2][1]-(e[2][1]-e[0][1])*A,n*A];default:throw new Error("Position ".concat(t," not found"))}}(g,i,a),h=Object(s.a)(C,2),f=h[0],d=h[1];return[new T.a({id:"scale-bar-length-".concat(A),coordinateSystem:p.a.CARTESIAN,data:[[[d,f],[d+u,f]]],getSourcePosition:function(e){return e[0]},getTargetPosition:function(e){return e[1]},getWidth:2,getColor:[220,220,220]}),new T.a({id:"scale-bar-height-left-".concat(A),coordinateSystem:p.a.CARTESIAN,data:[[[d,f-l],[d,f+l]]],getSourcePosition:function(e){return e[0]},getTargetPosition:function(e){return e[1]},getWidth:2,getColor:[220,220,220]}),new T.a({id:"scale-bar-height-right-".concat(A),coordinateSystem:p.a.CARTESIAN,data:[[[d+u,f-l],[d+u,f+l]]],getSourcePosition:function(e){return e[0]},getTargetPosition:function(e){return e[1]},getWidth:2,getColor:[220,220,220]}),new Z.a({id:"units-label-layer-".concat(A),coordinateSystem:p.a.CARTESIAN,data:[{text:String(I).slice(0,5).replace(/\.$/,"")+n,position:[d+.5*u,f+4*l]}],getColor:[220,220,220,255],getSize:12,fontFamily:"-apple-system, 'Helvetica Neue', Arial, sans-serif",sizeUnits:"meters",sizeScale:Math.pow(2,-c),characterSet:[].concat(Object(B.a)(n.split("")),Object(B.a)((e=10,Object(B.a)(Array(e).keys())).map((function(e){return String(e)}))),["."])})]}}]),A}(v.a);fo.layerName="ScaleBarLayer",fo.defaultProps={pickable:{type:"boolean",value:!0,compare:!0},viewState:{type:"object",value:{zoom:0,target:[0,0,0]},compare:!0},unit:{type:"string",value:"",compare:!0},size:{type:"number",value:1,compare:!0},position:{type:"string",value:"bottom-right",compare:!0},length:{type:"number",value:.085,compare:!0}};var Bo={name:"channel-intensity-module",fs:"#define GLSLIFY 1\nvec4 jet(float x_17){const float e0=0.0;const vec4 v0=vec4(0,0,0.5137254901960784,1);const float e1=0.125;const vec4 v1=vec4(0,0.23529411764705882,0.6666666666666666,1);const float e2=0.375;const vec4 v2=vec4(0.0196078431372549,1,1,1);const float e3=0.625;const vec4 v3=vec4(1,1,0,1);const float e4=0.875;const vec4 v4=vec4(0.9803921568627451,0,0,1);const float e5=1.0;const vec4 v5=vec4(0.5019607843137255,0,0,1);float a0=smoothstep(e0,e1,x_17);float a1=smoothstep(e1,e2,x_17);float a2=smoothstep(e2,e3,x_17);float a3=smoothstep(e3,e4,x_17);float a4=smoothstep(e4,e5,x_17);return max(mix(v0,v1,a0)*step(e0,x_17)*step(x_17,e1),max(mix(v1,v2,a1)*step(e1,x_17)*step(x_17,e2),max(mix(v2,v3,a2)*step(e2,x_17)*step(x_17,e3),max(mix(v3,v4,a3)*step(e3,x_17)*step(x_17,e4),mix(v4,v5,a4)*step(e4,x_17)*step(x_17,e5)))));}vec4 hsv(float x_18){const float e0=0.0;const vec4 v0=vec4(1,0,0,1);const float e1=0.169;const vec4 v1=vec4(0.9921568627450981,1,0.00784313725490196,1);const float e2=0.173;const vec4 v2=vec4(0.9686274509803922,1,0.00784313725490196,1);const float e3=0.337;const vec4 v3=vec4(0,0.9882352941176471,0.01568627450980392,1);const float e4=0.341;const vec4 v4=vec4(0,0.9882352941176471,0.0392156862745098,1);const float e5=0.506;const vec4 v5=vec4(0.00392156862745098,0.9764705882352941,1,1);const float e6=0.671;const vec4 v6=vec4(0.00784313725490196,0,0.9921568627450981,1);const float e7=0.675;const vec4 v7=vec4(0.03137254901960784,0,0.9921568627450981,1);const float e8=0.839;const vec4 v8=vec4(1,0,0.984313725490196,1);const float e9=0.843;const vec4 v9=vec4(1,0,0.9607843137254902,1);const float e10=1.0;const vec4 v10=vec4(1,0,0.023529411764705882,1);float a0=smoothstep(e0,e1,x_18);float a1=smoothstep(e1,e2,x_18);float a2=smoothstep(e2,e3,x_18);float a3=smoothstep(e3,e4,x_18);float a4=smoothstep(e4,e5,x_18);float a5=smoothstep(e5,e6,x_18);float a6=smoothstep(e6,e7,x_18);float a7=smoothstep(e7,e8,x_18);float a8=smoothstep(e8,e9,x_18);float a9=smoothstep(e9,e10,x_18);return max(mix(v0,v1,a0)*step(e0,x_18)*step(x_18,e1),max(mix(v1,v2,a1)*step(e1,x_18)*step(x_18,e2),max(mix(v2,v3,a2)*step(e2,x_18)*step(x_18,e3),max(mix(v3,v4,a3)*step(e3,x_18)*step(x_18,e4),max(mix(v4,v5,a4)*step(e4,x_18)*step(x_18,e5),max(mix(v5,v6,a5)*step(e5,x_18)*step(x_18,e6),max(mix(v6,v7,a6)*step(e6,x_18)*step(x_18,e7),max(mix(v7,v8,a7)*step(e7,x_18)*step(x_18,e8),max(mix(v8,v9,a8)*step(e8,x_18)*step(x_18,e9),mix(v9,v10,a9)*step(e9,x_18)*step(x_18,e10))))))))));}vec4 hot(float x_13){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.3;const vec4 v1=vec4(0.9019607843137255,0,0,1);const float e2=0.6;const vec4 v2=vec4(1,0.8235294117647058,0,1);const float e3=1.0;const vec4 v3=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_13);float a1=smoothstep(e1,e2,x_13);float a2=smoothstep(e2,e3,x_13);return max(mix(v0,v1,a0)*step(e0,x_13)*step(x_13,e1),max(mix(v1,v2,a1)*step(e1,x_13)*step(x_13,e2),mix(v2,v3,a2)*step(e2,x_13)*step(x_13,e3)));}vec4 cool(float x_24){const float e0=0.0;const vec4 v0=vec4(0.49019607843137253,0,0.7019607843137254,1);const float e1=0.13;const vec4 v1=vec4(0.4549019607843137,0,0.8549019607843137,1);const float e2=0.25;const vec4 v2=vec4(0.3843137254901961,0.2901960784313726,0.9294117647058824,1);const float e3=0.38;const vec4 v3=vec4(0.26666666666666666,0.5725490196078431,0.9058823529411765,1);const float e4=0.5;const vec4 v4=vec4(0,0.8,0.7725490196078432,1);const float e5=0.63;const vec4 v5=vec4(0,0.9686274509803922,0.5725490196078431,1);const float e6=0.75;const vec4 v6=vec4(0,1,0.34509803921568627,1);const float e7=0.88;const vec4 v7=vec4(0.1568627450980392,1,0.03137254901960784,1);const float e8=1.0;const vec4 v8=vec4(0.5764705882352941,1,0,1);float a0=smoothstep(e0,e1,x_24);float a1=smoothstep(e1,e2,x_24);float a2=smoothstep(e2,e3,x_24);float a3=smoothstep(e3,e4,x_24);float a4=smoothstep(e4,e5,x_24);float a5=smoothstep(e5,e6,x_24);float a6=smoothstep(e6,e7,x_24);float a7=smoothstep(e7,e8,x_24);return max(mix(v0,v1,a0)*step(e0,x_24)*step(x_24,e1),max(mix(v1,v2,a1)*step(e1,x_24)*step(x_24,e2),max(mix(v2,v3,a2)*step(e2,x_24)*step(x_24,e3),max(mix(v3,v4,a3)*step(e3,x_24)*step(x_24,e4),max(mix(v4,v5,a4)*step(e4,x_24)*step(x_24,e5),max(mix(v5,v6,a5)*step(e5,x_24)*step(x_24,e6),max(mix(v6,v7,a6)*step(e6,x_24)*step(x_24,e7),mix(v7,v8,a7)*step(e7,x_24)*step(x_24,e8))))))));}vec4 spring(float x_5){const float e0=0.0;const vec4 v0=vec4(1,0,1,1);const float e1=1.0;const vec4 v1=vec4(1,1,0,1);float a0=smoothstep(e0,e1,x_5);return mix(v0,v1,a0)*step(e0,x_5)*step(x_5,e1);}vec4 summer(float x_12){const float e0=0.0;const vec4 v0=vec4(0,0.5019607843137255,0.4,1);const float e1=1.0;const vec4 v1=vec4(1,1,0.4,1);float a0=smoothstep(e0,e1,x_12);return mix(v0,v1,a0)*step(e0,x_12)*step(x_12,e1);}vec4 autumn(float x_25){const float e0=0.0;const vec4 v0=vec4(1,0,0,1);const float e1=1.0;const vec4 v1=vec4(1,1,0,1);float a0=smoothstep(e0,e1,x_25);return mix(v0,v1,a0)*step(e0,x_25)*step(x_25,e1);}vec4 winter(float x_16){const float e0=0.0;const vec4 v0=vec4(0,0,1,1);const float e1=1.0;const vec4 v1=vec4(0,1,0.5019607843137255,1);float a0=smoothstep(e0,e1,x_16);return mix(v0,v1,a0)*step(e0,x_16)*step(x_16,e1);}vec4 bone(float x_15){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.376;const vec4 v1=vec4(0.32941176470588235,0.32941176470588235,0.4549019607843137,1);const float e2=0.753;const vec4 v2=vec4(0.6627450980392157,0.7843137254901961,0.7843137254901961,1);const float e3=1.0;const vec4 v3=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_15);float a1=smoothstep(e1,e2,x_15);float a2=smoothstep(e2,e3,x_15);return max(mix(v0,v1,a0)*step(e0,x_15)*step(x_15,e1),max(mix(v1,v2,a1)*step(e1,x_15)*step(x_15,e2),mix(v2,v3,a2)*step(e2,x_15)*step(x_15,e3)));}vec4 copper(float x_10){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.804;const vec4 v1=vec4(1,0.6274509803921569,0.4,1);const float e2=1.0;const vec4 v2=vec4(1,0.7803921568627451,0.4980392156862745,1);float a0=smoothstep(e0,e1,x_10);float a1=smoothstep(e1,e2,x_10);return max(mix(v0,v1,a0)*step(e0,x_10)*step(x_10,e1),mix(v1,v2,a1)*step(e1,x_10)*step(x_10,e2));}vec4 greys(float x_4){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=1.0;const vec4 v1=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_4);return mix(v0,v1,a0)*step(e0,x_4)*step(x_4,e1);}vec4 yignbu(float x_32){const float e0=0.0;const vec4 v0=vec4(0.03137254901960784,0.11372549019607843,0.34509803921568627,1);const float e1=0.125;const vec4 v1=vec4(0.1450980392156863,0.20392156862745098,0.5803921568627451,1);const float e2=0.25;const vec4 v2=vec4(0.13333333333333333,0.3686274509803922,0.6588235294117647,1);const float e3=0.375;const vec4 v3=vec4(0.11372549019607843,0.5686274509803921,0.7529411764705882,1);const float e4=0.5;const vec4 v4=vec4(0.2549019607843137,0.7137254901960784,0.7686274509803922,1);const float e5=0.625;const vec4 v5=vec4(0.4980392156862745,0.803921568627451,0.7333333333333333,1);const float e6=0.75;const vec4 v6=vec4(0.7803921568627451,0.9137254901960784,0.7058823529411765,1);const float e7=0.875;const vec4 v7=vec4(0.9294117647058824,0.9725490196078431,0.8509803921568627,1);const float e8=1.0;const vec4 v8=vec4(1,1,0.8509803921568627,1);float a0=smoothstep(e0,e1,x_32);float a1=smoothstep(e1,e2,x_32);float a2=smoothstep(e2,e3,x_32);float a3=smoothstep(e3,e4,x_32);float a4=smoothstep(e4,e5,x_32);float a5=smoothstep(e5,e6,x_32);float a6=smoothstep(e6,e7,x_32);float a7=smoothstep(e7,e8,x_32);return max(mix(v0,v1,a0)*step(e0,x_32)*step(x_32,e1),max(mix(v1,v2,a1)*step(e1,x_32)*step(x_32,e2),max(mix(v2,v3,a2)*step(e2,x_32)*step(x_32,e3),max(mix(v3,v4,a3)*step(e3,x_32)*step(x_32,e4),max(mix(v4,v5,a4)*step(e4,x_32)*step(x_32,e5),max(mix(v5,v6,a5)*step(e5,x_32)*step(x_32,e6),max(mix(v6,v7,a6)*step(e6,x_32)*step(x_32,e7),mix(v7,v8,a7)*step(e7,x_32)*step(x_32,e8))))))));}vec4 greens(float x_34){const float e0=0.0;const vec4 v0=vec4(0,0.26666666666666666,0.10588235294117647,1);const float e1=0.125;const vec4 v1=vec4(0,0.42745098039215684,0.17254901960784313,1);const float e2=0.25;const vec4 v2=vec4(0.13725490196078433,0.5450980392156862,0.27058823529411763,1);const float e3=0.375;const vec4 v3=vec4(0.2549019607843137,0.6705882352941176,0.36470588235294116,1);const float e4=0.5;const vec4 v4=vec4(0.4549019607843137,0.7686274509803922,0.4627450980392157,1);const float e5=0.625;const vec4 v5=vec4(0.6313725490196078,0.8509803921568627,0.6078431372549019,1);const float e6=0.75;const vec4 v6=vec4(0.7803921568627451,0.9137254901960784,0.7529411764705882,1);const float e7=0.875;const vec4 v7=vec4(0.8980392156862745,0.9607843137254902,0.8784313725490196,1);const float e8=1.0;const vec4 v8=vec4(0.9686274509803922,0.9882352941176471,0.9607843137254902,1);float a0=smoothstep(e0,e1,x_34);float a1=smoothstep(e1,e2,x_34);float a2=smoothstep(e2,e3,x_34);float a3=smoothstep(e3,e4,x_34);float a4=smoothstep(e4,e5,x_34);float a5=smoothstep(e5,e6,x_34);float a6=smoothstep(e6,e7,x_34);float a7=smoothstep(e7,e8,x_34);return max(mix(v0,v1,a0)*step(e0,x_34)*step(x_34,e1),max(mix(v1,v2,a1)*step(e1,x_34)*step(x_34,e2),max(mix(v2,v3,a2)*step(e2,x_34)*step(x_34,e3),max(mix(v3,v4,a3)*step(e3,x_34)*step(x_34,e4),max(mix(v4,v5,a4)*step(e4,x_34)*step(x_34,e5),max(mix(v5,v6,a5)*step(e5,x_34)*step(x_34,e6),max(mix(v6,v7,a6)*step(e6,x_34)*step(x_34,e7),mix(v7,v8,a7)*step(e7,x_34)*step(x_34,e8))))))));}vec4 yiorrd(float x_41){const float e0=0.0;const vec4 v0=vec4(0.5019607843137255,0,0.14901960784313725,1);const float e1=0.125;const vec4 v1=vec4(0.7411764705882353,0,0.14901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.8901960784313725,0.10196078431372549,0.10980392156862745,1);const float e3=0.375;const vec4 v3=vec4(0.9882352941176471,0.3058823529411765,0.16470588235294117,1);const float e4=0.5;const vec4 v4=vec4(0.9921568627450981,0.5529411764705883,0.23529411764705882,1);const float e5=0.625;const vec4 v5=vec4(0.996078431372549,0.6980392156862745,0.2980392156862745,1);const float e6=0.75;const vec4 v6=vec4(0.996078431372549,0.8509803921568627,0.4627450980392157,1);const float e7=0.875;const vec4 v7=vec4(1,0.9294117647058824,0.6274509803921569,1);const float e8=1.0;const vec4 v8=vec4(1,1,0.8,1);float a0=smoothstep(e0,e1,x_41);float a1=smoothstep(e1,e2,x_41);float a2=smoothstep(e2,e3,x_41);float a3=smoothstep(e3,e4,x_41);float a4=smoothstep(e4,e5,x_41);float a5=smoothstep(e5,e6,x_41);float a6=smoothstep(e6,e7,x_41);float a7=smoothstep(e7,e8,x_41);return max(mix(v0,v1,a0)*step(e0,x_41)*step(x_41,e1),max(mix(v1,v2,a1)*step(e1,x_41)*step(x_41,e2),max(mix(v2,v3,a2)*step(e2,x_41)*step(x_41,e3),max(mix(v3,v4,a3)*step(e3,x_41)*step(x_41,e4),max(mix(v4,v5,a4)*step(e4,x_41)*step(x_41,e5),max(mix(v5,v6,a5)*step(e5,x_41)*step(x_41,e6),max(mix(v6,v7,a6)*step(e6,x_41)*step(x_41,e7),mix(v7,v8,a7)*step(e7,x_41)*step(x_41,e8))))))));}vec4 bluered(float x_23){const float e0=0.0;const vec4 v0=vec4(0,0,1,1);const float e1=1.0;const vec4 v1=vec4(1,0,0,1);float a0=smoothstep(e0,e1,x_23);return mix(v0,v1,a0)*step(e0,x_23)*step(x_23,e1);}vec4 rdbu(float x_1){const float e0=0.0;const vec4 v0=vec4(0.0196078431372549,0.0392156862745098,0.6745098039215687,1);const float e1=0.35;const vec4 v1=vec4(0.41568627450980394,0.5372549019607843,0.9686274509803922,1);const float e2=0.5;const vec4 v2=vec4(0.7450980392156863,0.7450980392156863,0.7450980392156863,1);const float e3=0.6;const vec4 v3=vec4(0.8627450980392157,0.6666666666666666,0.5176470588235295,1);const float e4=0.7;const vec4 v4=vec4(0.9019607843137255,0.5686274509803921,0.35294117647058826,1);const float e5=1.0;const vec4 v5=vec4(0.6980392156862745,0.0392156862745098,0.10980392156862745,1);float a0=smoothstep(e0,e1,x_1);float a1=smoothstep(e1,e2,x_1);float a2=smoothstep(e2,e3,x_1);float a3=smoothstep(e3,e4,x_1);float a4=smoothstep(e4,e5,x_1);return max(mix(v0,v1,a0)*step(e0,x_1)*step(x_1,e1),max(mix(v1,v2,a1)*step(e1,x_1)*step(x_1,e2),max(mix(v2,v3,a2)*step(e2,x_1)*step(x_1,e3),max(mix(v3,v4,a3)*step(e3,x_1)*step(x_1,e4),mix(v4,v5,a4)*step(e4,x_1)*step(x_1,e5)))));}vec4 picnic(float x_42){const float e0=0.0;const vec4 v0=vec4(0,0,1,1);const float e1=0.1;const vec4 v1=vec4(0.2,0.6,1,1);const float e2=0.2;const vec4 v2=vec4(0.4,0.8,1,1);const float e3=0.3;const vec4 v3=vec4(0.6,0.8,1,1);const float e4=0.4;const vec4 v4=vec4(0.8,0.8,1,1);const float e5=0.5;const vec4 v5=vec4(1,1,1,1);const float e6=0.6;const vec4 v6=vec4(1,0.8,1,1);const float e7=0.7;const vec4 v7=vec4(1,0.6,1,1);const float e8=0.8;const vec4 v8=vec4(1,0.4,0.8,1);const float e9=0.9;const vec4 v9=vec4(1,0.4,0.4,1);const float e10=1.0;const vec4 v10=vec4(1,0,0,1);float a0=smoothstep(e0,e1,x_42);float a1=smoothstep(e1,e2,x_42);float a2=smoothstep(e2,e3,x_42);float a3=smoothstep(e3,e4,x_42);float a4=smoothstep(e4,e5,x_42);float a5=smoothstep(e5,e6,x_42);float a6=smoothstep(e6,e7,x_42);float a7=smoothstep(e7,e8,x_42);float a8=smoothstep(e8,e9,x_42);float a9=smoothstep(e9,e10,x_42);return max(mix(v0,v1,a0)*step(e0,x_42)*step(x_42,e1),max(mix(v1,v2,a1)*step(e1,x_42)*step(x_42,e2),max(mix(v2,v3,a2)*step(e2,x_42)*step(x_42,e3),max(mix(v3,v4,a3)*step(e3,x_42)*step(x_42,e4),max(mix(v4,v5,a4)*step(e4,x_42)*step(x_42,e5),max(mix(v5,v6,a5)*step(e5,x_42)*step(x_42,e6),max(mix(v6,v7,a6)*step(e6,x_42)*step(x_42,e7),max(mix(v7,v8,a7)*step(e7,x_42)*step(x_42,e8),max(mix(v8,v9,a8)*step(e8,x_42)*step(x_42,e9),mix(v9,v10,a9)*step(e9,x_42)*step(x_42,e10))))))))));}vec4 rainbow(float x_31){const float e0=0.0;const vec4 v0=vec4(0.5882352941176471,0,0.35294117647058826,1);const float e1=0.125;const vec4 v1=vec4(0,0,0.7843137254901961,1);const float e2=0.25;const vec4 v2=vec4(0,0.09803921568627451,1,1);const float e3=0.375;const vec4 v3=vec4(0,0.596078431372549,1,1);const float e4=0.5;const vec4 v4=vec4(0.17254901960784313,1,0.5882352941176471,1);const float e5=0.625;const vec4 v5=vec4(0.592156862745098,1,0,1);const float e6=0.75;const vec4 v6=vec4(1,0.9176470588235294,0,1);const float e7=0.875;const vec4 v7=vec4(1,0.43529411764705883,0,1);const float e8=1.0;const vec4 v8=vec4(1,0,0,1);float a0=smoothstep(e0,e1,x_31);float a1=smoothstep(e1,e2,x_31);float a2=smoothstep(e2,e3,x_31);float a3=smoothstep(e3,e4,x_31);float a4=smoothstep(e4,e5,x_31);float a5=smoothstep(e5,e6,x_31);float a6=smoothstep(e6,e7,x_31);float a7=smoothstep(e7,e8,x_31);return max(mix(v0,v1,a0)*step(e0,x_31)*step(x_31,e1),max(mix(v1,v2,a1)*step(e1,x_31)*step(x_31,e2),max(mix(v2,v3,a2)*step(e2,x_31)*step(x_31,e3),max(mix(v3,v4,a3)*step(e3,x_31)*step(x_31,e4),max(mix(v4,v5,a4)*step(e4,x_31)*step(x_31,e5),max(mix(v5,v6,a5)*step(e5,x_31)*step(x_31,e6),max(mix(v6,v7,a6)*step(e6,x_31)*step(x_31,e7),mix(v7,v8,a7)*step(e7,x_31)*step(x_31,e8))))))));}vec4 portland(float x_21){const float e0=0.0;const vec4 v0=vec4(0.047058823529411764,0.2,0.5137254901960784,1);const float e1=0.25;const vec4 v1=vec4(0.0392156862745098,0.5333333333333333,0.7294117647058823,1);const float e2=0.5;const vec4 v2=vec4(0.9490196078431372,0.8274509803921568,0.2196078431372549,1);const float e3=0.75;const vec4 v3=vec4(0.9490196078431372,0.5607843137254902,0.2196078431372549,1);const float e4=1.0;const vec4 v4=vec4(0.8509803921568627,0.11764705882352941,0.11764705882352941,1);float a0=smoothstep(e0,e1,x_21);float a1=smoothstep(e1,e2,x_21);float a2=smoothstep(e2,e3,x_21);float a3=smoothstep(e3,e4,x_21);return max(mix(v0,v1,a0)*step(e0,x_21)*step(x_21,e1),max(mix(v1,v2,a1)*step(e1,x_21)*step(x_21,e2),max(mix(v2,v3,a2)*step(e2,x_21)*step(x_21,e3),mix(v3,v4,a3)*step(e3,x_21)*step(x_21,e4))));}vec4 blackbody(float x_38){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.2;const vec4 v1=vec4(0.9019607843137255,0,0,1);const float e2=0.4;const vec4 v2=vec4(0.9019607843137255,0.8235294117647058,0,1);const float e3=0.7;const vec4 v3=vec4(1,1,1,1);const float e4=1.0;const vec4 v4=vec4(0.6274509803921569,0.7843137254901961,1,1);float a0=smoothstep(e0,e1,x_38);float a1=smoothstep(e1,e2,x_38);float a2=smoothstep(e2,e3,x_38);float a3=smoothstep(e3,e4,x_38);return max(mix(v0,v1,a0)*step(e0,x_38)*step(x_38,e1),max(mix(v1,v2,a1)*step(e1,x_38)*step(x_38,e2),max(mix(v2,v3,a2)*step(e2,x_38)*step(x_38,e3),mix(v3,v4,a3)*step(e3,x_38)*step(x_38,e4))));}vec4 earth(float x_29){const float e0=0.0;const vec4 v0=vec4(0,0,0.5098039215686274,1);const float e1=0.1;const vec4 v1=vec4(0,0.7058823529411765,0.7058823529411765,1);const float e2=0.2;const vec4 v2=vec4(0.1568627450980392,0.8235294117647058,0.1568627450980392,1);const float e3=0.4;const vec4 v3=vec4(0.9019607843137255,0.9019607843137255,0.19607843137254902,1);const float e4=0.6;const vec4 v4=vec4(0.47058823529411764,0.27450980392156865,0.0784313725490196,1);const float e5=1.0;const vec4 v5=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_29);float a1=smoothstep(e1,e2,x_29);float a2=smoothstep(e2,e3,x_29);float a3=smoothstep(e3,e4,x_29);float a4=smoothstep(e4,e5,x_29);return max(mix(v0,v1,a0)*step(e0,x_29)*step(x_29,e1),max(mix(v1,v2,a1)*step(e1,x_29)*step(x_29,e2),max(mix(v2,v3,a2)*step(e2,x_29)*step(x_29,e3),max(mix(v3,v4,a3)*step(e3,x_29)*step(x_29,e4),mix(v4,v5,a4)*step(e4,x_29)*step(x_29,e5)))));}vec4 electric(float x_9){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.15;const vec4 v1=vec4(0.11764705882352941,0,0.39215686274509803,1);const float e2=0.4;const vec4 v2=vec4(0.47058823529411764,0,0.39215686274509803,1);const float e3=0.6;const vec4 v3=vec4(0.6274509803921569,0.35294117647058826,0,1);const float e4=0.8;const vec4 v4=vec4(0.9019607843137255,0.7843137254901961,0,1);const float e5=1.0;const vec4 v5=vec4(1,0.9803921568627451,0.8627450980392157,1);float a0=smoothstep(e0,e1,x_9);float a1=smoothstep(e1,e2,x_9);float a2=smoothstep(e2,e3,x_9);float a3=smoothstep(e3,e4,x_9);float a4=smoothstep(e4,e5,x_9);return max(mix(v0,v1,a0)*step(e0,x_9)*step(x_9,e1),max(mix(v1,v2,a1)*step(e1,x_9)*step(x_9,e2),max(mix(v2,v3,a2)*step(e2,x_9)*step(x_9,e3),max(mix(v3,v4,a3)*step(e3,x_9)*step(x_9,e4),mix(v4,v5,a4)*step(e4,x_9)*step(x_9,e5)))));}vec4 alpha(float x_0){const float e0=0.0;const vec4 v0=vec4(1,1,1,0);const float e1=1.0;const vec4 v1=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_0);return mix(v0,v1,a0)*step(e0,x_0)*step(x_0,e1);}vec4 viridis(float x_22){const float e0=0.0;const vec4 v0=vec4(0.26666666666666666,0.00392156862745098,0.32941176470588235,1);const float e1=0.13;const vec4 v1=vec4(0.2784313725490196,0.17254901960784313,0.47843137254901963,1);const float e2=0.25;const vec4 v2=vec4(0.23137254901960785,0.3176470588235294,0.5450980392156862,1);const float e3=0.38;const vec4 v3=vec4(0.17254901960784313,0.44313725490196076,0.5568627450980392,1);const float e4=0.5;const vec4 v4=vec4(0.12941176470588237,0.5647058823529412,0.5529411764705883,1);const float e5=0.63;const vec4 v5=vec4(0.15294117647058825,0.6784313725490196,0.5058823529411764,1);const float e6=0.75;const vec4 v6=vec4(0.3607843137254902,0.7843137254901961,0.38823529411764707,1);const float e7=0.88;const vec4 v7=vec4(0.6666666666666666,0.8627450980392157,0.19607843137254902,1);const float e8=1.0;const vec4 v8=vec4(0.9921568627450981,0.9058823529411765,0.1450980392156863,1);float a0=smoothstep(e0,e1,x_22);float a1=smoothstep(e1,e2,x_22);float a2=smoothstep(e2,e3,x_22);float a3=smoothstep(e3,e4,x_22);float a4=smoothstep(e4,e5,x_22);float a5=smoothstep(e5,e6,x_22);float a6=smoothstep(e6,e7,x_22);float a7=smoothstep(e7,e8,x_22);return max(mix(v0,v1,a0)*step(e0,x_22)*step(x_22,e1),max(mix(v1,v2,a1)*step(e1,x_22)*step(x_22,e2),max(mix(v2,v3,a2)*step(e2,x_22)*step(x_22,e3),max(mix(v3,v4,a3)*step(e3,x_22)*step(x_22,e4),max(mix(v4,v5,a4)*step(e4,x_22)*step(x_22,e5),max(mix(v5,v6,a5)*step(e5,x_22)*step(x_22,e6),max(mix(v6,v7,a6)*step(e6,x_22)*step(x_22,e7),mix(v7,v8,a7)*step(e7,x_22)*step(x_22,e8))))))));}vec4 inferno(float x_30){const float e0=0.0;const vec4 v0=vec4(0,0,0.01568627450980392,1);const float e1=0.13;const vec4 v1=vec4(0.12156862745098039,0.047058823529411764,0.2823529411764706,1);const float e2=0.25;const vec4 v2=vec4(0.3333333333333333,0.058823529411764705,0.42745098039215684,1);const float e3=0.38;const vec4 v3=vec4(0.5333333333333333,0.13333333333333333,0.41568627450980394,1);const float e4=0.5;const vec4 v4=vec4(0.7294117647058823,0.21176470588235294,0.3333333333333333,1);const float e5=0.63;const vec4 v5=vec4(0.8901960784313725,0.34901960784313724,0.2,1);const float e6=0.75;const vec4 v6=vec4(0.9764705882352941,0.5490196078431373,0.0392156862745098,1);const float e7=0.88;const vec4 v7=vec4(0.9764705882352941,0.788235294117647,0.19607843137254902,1);const float e8=1.0;const vec4 v8=vec4(0.9882352941176471,1,0.6431372549019608,1);float a0=smoothstep(e0,e1,x_30);float a1=smoothstep(e1,e2,x_30);float a2=smoothstep(e2,e3,x_30);float a3=smoothstep(e3,e4,x_30);float a4=smoothstep(e4,e5,x_30);float a5=smoothstep(e5,e6,x_30);float a6=smoothstep(e6,e7,x_30);float a7=smoothstep(e7,e8,x_30);return max(mix(v0,v1,a0)*step(e0,x_30)*step(x_30,e1),max(mix(v1,v2,a1)*step(e1,x_30)*step(x_30,e2),max(mix(v2,v3,a2)*step(e2,x_30)*step(x_30,e3),max(mix(v3,v4,a3)*step(e3,x_30)*step(x_30,e4),max(mix(v4,v5,a4)*step(e4,x_30)*step(x_30,e5),max(mix(v5,v6,a5)*step(e5,x_30)*step(x_30,e6),max(mix(v6,v7,a6)*step(e6,x_30)*step(x_30,e7),mix(v7,v8,a7)*step(e7,x_30)*step(x_30,e8))))))));}vec4 magma(float x_33){const float e0=0.0;const vec4 v0=vec4(0,0,0.01568627450980392,1);const float e1=0.13;const vec4 v1=vec4(0.10980392156862745,0.06274509803921569,0.26666666666666666,1);const float e2=0.25;const vec4 v2=vec4(0.30980392156862746,0.07058823529411765,0.4823529411764706,1);const float e3=0.38;const vec4 v3=vec4(0.5058823529411764,0.1450980392156863,0.5058823529411764,1);const float e4=0.5;const vec4 v4=vec4(0.7098039215686275,0.21176470588235294,0.47843137254901963,1);const float e5=0.63;const vec4 v5=vec4(0.8980392156862745,0.3137254901960784,0.39215686274509803,1);const float e6=0.75;const vec4 v6=vec4(0.984313725490196,0.5294117647058824,0.3803921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.996078431372549,0.7607843137254902,0.5294117647058824,1);const float e8=1.0;const vec4 v8=vec4(0.9882352941176471,0.9921568627450981,0.7490196078431373,1);float a0=smoothstep(e0,e1,x_33);float a1=smoothstep(e1,e2,x_33);float a2=smoothstep(e2,e3,x_33);float a3=smoothstep(e3,e4,x_33);float a4=smoothstep(e4,e5,x_33);float a5=smoothstep(e5,e6,x_33);float a6=smoothstep(e6,e7,x_33);float a7=smoothstep(e7,e8,x_33);return max(mix(v0,v1,a0)*step(e0,x_33)*step(x_33,e1),max(mix(v1,v2,a1)*step(e1,x_33)*step(x_33,e2),max(mix(v2,v3,a2)*step(e2,x_33)*step(x_33,e3),max(mix(v3,v4,a3)*step(e3,x_33)*step(x_33,e4),max(mix(v4,v5,a4)*step(e4,x_33)*step(x_33,e5),max(mix(v5,v6,a5)*step(e5,x_33)*step(x_33,e6),max(mix(v6,v7,a6)*step(e6,x_33)*step(x_33,e7),mix(v7,v8,a7)*step(e7,x_33)*step(x_33,e8))))))));}vec4 plasma(float x_3){const float e0=0.0;const vec4 v0=vec4(0.050980392156862744,0.03137254901960784,0.5294117647058824,1);const float e1=0.13;const vec4 v1=vec4(0.29411764705882354,0.011764705882352941,0.6313725490196078,1);const float e2=0.25;const vec4 v2=vec4(0.49019607843137253,0.011764705882352941,0.6588235294117647,1);const float e3=0.38;const vec4 v3=vec4(0.6588235294117647,0.13333333333333333,0.5882352941176471,1);const float e4=0.5;const vec4 v4=vec4(0.796078431372549,0.27450980392156865,0.4745098039215686,1);const float e5=0.63;const vec4 v5=vec4(0.8980392156862745,0.4196078431372549,0.36470588235294116,1);const float e6=0.75;const vec4 v6=vec4(0.9725490196078431,0.5803921568627451,0.2549019607843137,1);const float e7=0.88;const vec4 v7=vec4(0.9921568627450981,0.7647058823529411,0.1568627450980392,1);const float e8=1.0;const vec4 v8=vec4(0.9411764705882353,0.9764705882352941,0.12941176470588237,1);float a0=smoothstep(e0,e1,x_3);float a1=smoothstep(e1,e2,x_3);float a2=smoothstep(e2,e3,x_3);float a3=smoothstep(e3,e4,x_3);float a4=smoothstep(e4,e5,x_3);float a5=smoothstep(e5,e6,x_3);float a6=smoothstep(e6,e7,x_3);float a7=smoothstep(e7,e8,x_3);return max(mix(v0,v1,a0)*step(e0,x_3)*step(x_3,e1),max(mix(v1,v2,a1)*step(e1,x_3)*step(x_3,e2),max(mix(v2,v3,a2)*step(e2,x_3)*step(x_3,e3),max(mix(v3,v4,a3)*step(e3,x_3)*step(x_3,e4),max(mix(v4,v5,a4)*step(e4,x_3)*step(x_3,e5),max(mix(v5,v6,a5)*step(e5,x_3)*step(x_3,e6),max(mix(v6,v7,a6)*step(e6,x_3)*step(x_3,e7),mix(v7,v8,a7)*step(e7,x_3)*step(x_3,e8))))))));}vec4 warm(float x_43){const float e0=0.0;const vec4 v0=vec4(0.49019607843137253,0,0.7019607843137254,1);const float e1=0.13;const vec4 v1=vec4(0.6745098039215687,0,0.7333333333333333,1);const float e2=0.25;const vec4 v2=vec4(0.8588235294117647,0,0.6666666666666666,1);const float e3=0.38;const vec4 v3=vec4(1,0,0.5098039215686274,1);const float e4=0.5;const vec4 v4=vec4(1,0.24705882352941178,0.2901960784313726,1);const float e5=0.63;const vec4 v5=vec4(1,0.4823529411764706,0,1);const float e6=0.75;const vec4 v6=vec4(0.9176470588235294,0.6901960784313725,0,1);const float e7=0.88;const vec4 v7=vec4(0.7450980392156863,0.8941176470588236,0,1);const float e8=1.0;const vec4 v8=vec4(0.5764705882352941,1,0,1);float a0=smoothstep(e0,e1,x_43);float a1=smoothstep(e1,e2,x_43);float a2=smoothstep(e2,e3,x_43);float a3=smoothstep(e3,e4,x_43);float a4=smoothstep(e4,e5,x_43);float a5=smoothstep(e5,e6,x_43);float a6=smoothstep(e6,e7,x_43);float a7=smoothstep(e7,e8,x_43);return max(mix(v0,v1,a0)*step(e0,x_43)*step(x_43,e1),max(mix(v1,v2,a1)*step(e1,x_43)*step(x_43,e2),max(mix(v2,v3,a2)*step(e2,x_43)*step(x_43,e3),max(mix(v3,v4,a3)*step(e3,x_43)*step(x_43,e4),max(mix(v4,v5,a4)*step(e4,x_43)*step(x_43,e5),max(mix(v5,v6,a5)*step(e5,x_43)*step(x_43,e6),max(mix(v6,v7,a6)*step(e6,x_43)*step(x_43,e7),mix(v7,v8,a7)*step(e7,x_43)*step(x_43,e8))))))));}vec4 rainbow_soft_1310269270(float x_14){const float e0=0.0;const vec4 v0=vec4(0.49019607843137253,0,0.7019607843137254,1);const float e1=0.1;const vec4 v1=vec4(0.7803921568627451,0,0.7058823529411765,1);const float e2=0.2;const vec4 v2=vec4(1,0,0.4745098039215686,1);const float e3=0.3;const vec4 v3=vec4(1,0.4235294117647059,0,1);const float e4=0.4;const vec4 v4=vec4(0.8705882352941177,0.7607843137254902,0,1);const float e5=0.5;const vec4 v5=vec4(0.5882352941176471,1,0,1);const float e6=0.6;const vec4 v6=vec4(0,1,0.21568627450980393,1);const float e7=0.7;const vec4 v7=vec4(0,0.9647058823529412,0.5882352941176471,1);const float e8=0.8;const vec4 v8=vec4(0.19607843137254902,0.6549019607843137,0.8705882352941177,1);const float e9=0.9;const vec4 v9=vec4(0.403921568627451,0.2,0.9215686274509803,1);const float e10=1.0;const vec4 v10=vec4(0.48627450980392156,0,0.7294117647058823,1);float a0=smoothstep(e0,e1,x_14);float a1=smoothstep(e1,e2,x_14);float a2=smoothstep(e2,e3,x_14);float a3=smoothstep(e3,e4,x_14);float a4=smoothstep(e4,e5,x_14);float a5=smoothstep(e5,e6,x_14);float a6=smoothstep(e6,e7,x_14);float a7=smoothstep(e7,e8,x_14);float a8=smoothstep(e8,e9,x_14);float a9=smoothstep(e9,e10,x_14);return max(mix(v0,v1,a0)*step(e0,x_14)*step(x_14,e1),max(mix(v1,v2,a1)*step(e1,x_14)*step(x_14,e2),max(mix(v2,v3,a2)*step(e2,x_14)*step(x_14,e3),max(mix(v3,v4,a3)*step(e3,x_14)*step(x_14,e4),max(mix(v4,v5,a4)*step(e4,x_14)*step(x_14,e5),max(mix(v5,v6,a5)*step(e5,x_14)*step(x_14,e6),max(mix(v6,v7,a6)*step(e6,x_14)*step(x_14,e7),max(mix(v7,v8,a7)*step(e7,x_14)*step(x_14,e8),max(mix(v8,v9,a8)*step(e8,x_14)*step(x_14,e9),mix(v9,v10,a9)*step(e9,x_14)*step(x_14,e10))))))))));}vec4 bathymetry(float x_36){const float e0=0.0;const vec4 v0=vec4(0.1568627450980392,0.10196078431372549,0.17254901960784313,1);const float e1=0.13;const vec4 v1=vec4(0.23137254901960785,0.19215686274509805,0.35294117647058826,1);const float e2=0.25;const vec4 v2=vec4(0.25098039215686274,0.2980392156862745,0.5450980392156862,1);const float e3=0.38;const vec4 v3=vec4(0.24705882352941178,0.43137254901960786,0.592156862745098,1);const float e4=0.5;const vec4 v4=vec4(0.2823529411764706,0.5568627450980392,0.6196078431372549,1);const float e5=0.63;const vec4 v5=vec4(0.3333333333333333,0.6823529411764706,0.6392156862745098,1);const float e6=0.75;const vec4 v6=vec4(0.47058823529411764,0.807843137254902,0.6392156862745098,1);const float e7=0.88;const vec4 v7=vec4(0.7333333333333333,0.9019607843137255,0.6745098039215687,1);const float e8=1.0;const vec4 v8=vec4(0.9921568627450981,0.996078431372549,0.8,1);float a0=smoothstep(e0,e1,x_36);float a1=smoothstep(e1,e2,x_36);float a2=smoothstep(e2,e3,x_36);float a3=smoothstep(e3,e4,x_36);float a4=smoothstep(e4,e5,x_36);float a5=smoothstep(e5,e6,x_36);float a6=smoothstep(e6,e7,x_36);float a7=smoothstep(e7,e8,x_36);return max(mix(v0,v1,a0)*step(e0,x_36)*step(x_36,e1),max(mix(v1,v2,a1)*step(e1,x_36)*step(x_36,e2),max(mix(v2,v3,a2)*step(e2,x_36)*step(x_36,e3),max(mix(v3,v4,a3)*step(e3,x_36)*step(x_36,e4),max(mix(v4,v5,a4)*step(e4,x_36)*step(x_36,e5),max(mix(v5,v6,a5)*step(e5,x_36)*step(x_36,e6),max(mix(v6,v7,a6)*step(e6,x_36)*step(x_36,e7),mix(v7,v8,a7)*step(e7,x_36)*step(x_36,e8))))))));}vec4 cdom(float x_7){const float e0=0.0;const vec4 v0=vec4(0.1843137254901961,0.058823529411764705,0.24313725490196078,1);const float e1=0.13;const vec4 v1=vec4(0.3411764705882353,0.09019607843137255,0.33725490196078434,1);const float e2=0.25;const vec4 v2=vec4(0.5098039215686274,0.10980392156862745,0.38823529411764707,1);const float e3=0.38;const vec4 v3=vec4(0.6705882352941176,0.1607843137254902,0.3764705882352941,1);const float e4=0.5;const vec4 v4=vec4(0.807843137254902,0.2627450980392157,0.33725490196078434,1);const float e5=0.63;const vec4 v5=vec4(0.9019607843137255,0.41568627450980394,0.32941176470588235,1);const float e6=0.75;const vec4 v6=vec4(0.9490196078431372,0.5843137254901961,0.403921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.9764705882352941,0.7568627450980392,0.5294117647058824,1);const float e8=1.0;const vec4 v8=vec4(0.996078431372549,0.9294117647058824,0.6901960784313725,1);float a0=smoothstep(e0,e1,x_7);float a1=smoothstep(e1,e2,x_7);float a2=smoothstep(e2,e3,x_7);float a3=smoothstep(e3,e4,x_7);float a4=smoothstep(e4,e5,x_7);float a5=smoothstep(e5,e6,x_7);float a6=smoothstep(e6,e7,x_7);float a7=smoothstep(e7,e8,x_7);return max(mix(v0,v1,a0)*step(e0,x_7)*step(x_7,e1),max(mix(v1,v2,a1)*step(e1,x_7)*step(x_7,e2),max(mix(v2,v3,a2)*step(e2,x_7)*step(x_7,e3),max(mix(v3,v4,a3)*step(e3,x_7)*step(x_7,e4),max(mix(v4,v5,a4)*step(e4,x_7)*step(x_7,e5),max(mix(v5,v6,a5)*step(e5,x_7)*step(x_7,e6),max(mix(v6,v7,a6)*step(e6,x_7)*step(x_7,e7),mix(v7,v8,a7)*step(e7,x_7)*step(x_7,e8))))))));}vec4 chlorophyll(float x_6){const float e0=0.0;const vec4 v0=vec4(0.07058823529411765,0.1411764705882353,0.0784313725490196,1);const float e1=0.13;const vec4 v1=vec4(0.09803921568627451,0.24705882352941178,0.1607843137254902,1);const float e2=0.25;const vec4 v2=vec4(0.09411764705882353,0.3568627450980392,0.23137254901960785,1);const float e3=0.38;const vec4 v3=vec4(0.050980392156862744,0.4666666666666667,0.2823529411764706,1);const float e4=0.5;const vec4 v4=vec4(0.07058823529411765,0.5803921568627451,0.3137254901960784,1);const float e5=0.63;const vec4 v5=vec4(0.3137254901960784,0.6784313725490196,0.34901960784313724,1);const float e6=0.75;const vec4 v6=vec4(0.5176470588235295,0.7686274509803922,0.47843137254901963,1);const float e7=0.88;const vec4 v7=vec4(0.6862745098039216,0.8666666666666667,0.6352941176470588,1);const float e8=1.0;const vec4 v8=vec4(0.8431372549019608,0.9764705882352941,0.8156862745098039,1);float a0=smoothstep(e0,e1,x_6);float a1=smoothstep(e1,e2,x_6);float a2=smoothstep(e2,e3,x_6);float a3=smoothstep(e3,e4,x_6);float a4=smoothstep(e4,e5,x_6);float a5=smoothstep(e5,e6,x_6);float a6=smoothstep(e6,e7,x_6);float a7=smoothstep(e7,e8,x_6);return max(mix(v0,v1,a0)*step(e0,x_6)*step(x_6,e1),max(mix(v1,v2,a1)*step(e1,x_6)*step(x_6,e2),max(mix(v2,v3,a2)*step(e2,x_6)*step(x_6,e3),max(mix(v3,v4,a3)*step(e3,x_6)*step(x_6,e4),max(mix(v4,v5,a4)*step(e4,x_6)*step(x_6,e5),max(mix(v5,v6,a5)*step(e5,x_6)*step(x_6,e6),max(mix(v6,v7,a6)*step(e6,x_6)*step(x_6,e7),mix(v7,v8,a7)*step(e7,x_6)*step(x_6,e8))))))));}vec4 density(float x_19){const float e0=0.0;const vec4 v0=vec4(0.21176470588235294,0.054901960784313725,0.1411764705882353,1);const float e1=0.13;const vec4 v1=vec4(0.34901960784313724,0.09019607843137255,0.3137254901960784,1);const float e2=0.25;const vec4 v2=vec4(0.43137254901960786,0.17647058823529413,0.5176470588235295,1);const float e3=0.38;const vec4 v3=vec4(0.47058823529411764,0.30196078431372547,0.6980392156862745,1);const float e4=0.5;const vec4 v4=vec4(0.47058823529411764,0.44313725490196076,0.8352941176470589,1);const float e5=0.63;const vec4 v5=vec4(0.45098039215686275,0.592156862745098,0.8941176470588236,1);const float e6=0.75;const vec4 v6=vec4(0.5254901960784314,0.7254901960784313,0.8901960784313725,1);const float e7=0.88;const vec4 v7=vec4(0.6941176470588235,0.8392156862745098,0.8901960784313725,1);const float e8=1.0;const vec4 v8=vec4(0.9019607843137255,0.9450980392156862,0.9450980392156862,1);float a0=smoothstep(e0,e1,x_19);float a1=smoothstep(e1,e2,x_19);float a2=smoothstep(e2,e3,x_19);float a3=smoothstep(e3,e4,x_19);float a4=smoothstep(e4,e5,x_19);float a5=smoothstep(e5,e6,x_19);float a6=smoothstep(e6,e7,x_19);float a7=smoothstep(e7,e8,x_19);return max(mix(v0,v1,a0)*step(e0,x_19)*step(x_19,e1),max(mix(v1,v2,a1)*step(e1,x_19)*step(x_19,e2),max(mix(v2,v3,a2)*step(e2,x_19)*step(x_19,e3),max(mix(v3,v4,a3)*step(e3,x_19)*step(x_19,e4),max(mix(v4,v5,a4)*step(e4,x_19)*step(x_19,e5),max(mix(v5,v6,a5)*step(e5,x_19)*step(x_19,e6),max(mix(v6,v7,a6)*step(e6,x_19)*step(x_19,e7),mix(v7,v8,a7)*step(e7,x_19)*step(x_19,e8))))))));}vec4 freesurface_blue_3154355989(float x_35){const float e0=0.0;const vec4 v0=vec4(0.11764705882352941,0.01568627450980392,0.43137254901960786,1);const float e1=0.13;const vec4 v1=vec4(0.1843137254901961,0.054901960784313725,0.6901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.1607843137254902,0.17647058823529413,0.9254901960784314,1);const float e3=0.38;const vec4 v3=vec4(0.09803921568627451,0.38823529411764707,0.8313725490196079,1);const float e4=0.5;const vec4 v4=vec4(0.26666666666666666,0.5137254901960784,0.7843137254901961,1);const float e5=0.63;const vec4 v5=vec4(0.4470588235294118,0.611764705882353,0.7725490196078432,1);const float e6=0.75;const vec4 v6=vec4(0.615686274509804,0.7098039215686275,0.796078431372549,1);const float e7=0.88;const vec4 v7=vec4(0.7843137254901961,0.8156862745098039,0.8470588235294118,1);const float e8=1.0;const vec4 v8=vec4(0.9450980392156862,0.9294117647058824,0.9254901960784314,1);float a0=smoothstep(e0,e1,x_35);float a1=smoothstep(e1,e2,x_35);float a2=smoothstep(e2,e3,x_35);float a3=smoothstep(e3,e4,x_35);float a4=smoothstep(e4,e5,x_35);float a5=smoothstep(e5,e6,x_35);float a6=smoothstep(e6,e7,x_35);float a7=smoothstep(e7,e8,x_35);return max(mix(v0,v1,a0)*step(e0,x_35)*step(x_35,e1),max(mix(v1,v2,a1)*step(e1,x_35)*step(x_35,e2),max(mix(v2,v3,a2)*step(e2,x_35)*step(x_35,e3),max(mix(v3,v4,a3)*step(e3,x_35)*step(x_35,e4),max(mix(v4,v5,a4)*step(e4,x_35)*step(x_35,e5),max(mix(v5,v6,a5)*step(e5,x_35)*step(x_35,e6),max(mix(v6,v7,a6)*step(e6,x_35)*step(x_35,e7),mix(v7,v8,a7)*step(e7,x_35)*step(x_35,e8))))))));}vec4 freesurface_red_1679163293(float x_20){const float e0=0.0;const vec4 v0=vec4(0.23529411764705882,0.03529411764705882,0.07058823529411765,1);const float e1=0.13;const vec4 v1=vec4(0.39215686274509803,0.06666666666666667,0.10588235294117647,1);const float e2=0.25;const vec4 v2=vec4(0.5568627450980392,0.0784313725490196,0.11372549019607843,1);const float e3=0.38;const vec4 v3=vec4(0.6941176470588235,0.16862745098039217,0.10588235294117647,1);const float e4=0.5;const vec4 v4=vec4(0.7529411764705882,0.3411764705882353,0.24705882352941178,1);const float e5=0.63;const vec4 v5=vec4(0.803921568627451,0.49019607843137253,0.4117647058823529,1);const float e6=0.75;const vec4 v6=vec4(0.8470588235294118,0.6352941176470588,0.5803921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.8901960784313725,0.7803921568627451,0.7568627450980392,1);const float e8=1.0;const vec4 v8=vec4(0.9450980392156862,0.9294117647058824,0.9254901960784314,1);float a0=smoothstep(e0,e1,x_20);float a1=smoothstep(e1,e2,x_20);float a2=smoothstep(e2,e3,x_20);float a3=smoothstep(e3,e4,x_20);float a4=smoothstep(e4,e5,x_20);float a5=smoothstep(e5,e6,x_20);float a6=smoothstep(e6,e7,x_20);float a7=smoothstep(e7,e8,x_20);return max(mix(v0,v1,a0)*step(e0,x_20)*step(x_20,e1),max(mix(v1,v2,a1)*step(e1,x_20)*step(x_20,e2),max(mix(v2,v3,a2)*step(e2,x_20)*step(x_20,e3),max(mix(v3,v4,a3)*step(e3,x_20)*step(x_20,e4),max(mix(v4,v5,a4)*step(e4,x_20)*step(x_20,e5),max(mix(v5,v6,a5)*step(e5,x_20)*step(x_20,e6),max(mix(v6,v7,a6)*step(e6,x_20)*step(x_20,e7),mix(v7,v8,a7)*step(e7,x_20)*step(x_20,e8))))))));}vec4 oxygen(float x_11){const float e0=0.0;const vec4 v0=vec4(0.25098039215686274,0.0196078431372549,0.0196078431372549,1);const float e1=0.13;const vec4 v1=vec4(0.41568627450980394,0.023529411764705882,0.058823529411764705,1);const float e2=0.25;const vec4 v2=vec4(0.5647058823529412,0.10196078431372549,0.027450980392156862,1);const float e3=0.38;const vec4 v3=vec4(0.6588235294117647,0.25098039215686274,0.011764705882352941,1);const float e4=0.5;const vec4 v4=vec4(0.7372549019607844,0.39215686274509803,0.01568627450980392,1);const float e5=0.63;const vec4 v5=vec4(0.807843137254902,0.5333333333333333,0.043137254901960784,1);const float e6=0.75;const vec4 v6=vec4(0.8627450980392157,0.6823529411764706,0.09803921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.9058823529411765,0.8431372549019608,0.17254901960784313,1);const float e8=1.0;const vec4 v8=vec4(0.9725490196078431,0.996078431372549,0.4117647058823529,1);float a0=smoothstep(e0,e1,x_11);float a1=smoothstep(e1,e2,x_11);float a2=smoothstep(e2,e3,x_11);float a3=smoothstep(e3,e4,x_11);float a4=smoothstep(e4,e5,x_11);float a5=smoothstep(e5,e6,x_11);float a6=smoothstep(e6,e7,x_11);float a7=smoothstep(e7,e8,x_11);return max(mix(v0,v1,a0)*step(e0,x_11)*step(x_11,e1),max(mix(v1,v2,a1)*step(e1,x_11)*step(x_11,e2),max(mix(v2,v3,a2)*step(e2,x_11)*step(x_11,e3),max(mix(v3,v4,a3)*step(e3,x_11)*step(x_11,e4),max(mix(v4,v5,a4)*step(e4,x_11)*step(x_11,e5),max(mix(v5,v6,a5)*step(e5,x_11)*step(x_11,e6),max(mix(v6,v7,a6)*step(e6,x_11)*step(x_11,e7),mix(v7,v8,a7)*step(e7,x_11)*step(x_11,e8))))))));}vec4 par(float x_28){const float e0=0.0;const vec4 v0=vec4(0.2,0.0784313725490196,0.09411764705882353,1);const float e1=0.13;const vec4 v1=vec4(0.35294117647058826,0.12549019607843137,0.13725490196078433,1);const float e2=0.25;const vec4 v2=vec4(0.5058823529411764,0.17254901960784313,0.13333333333333333,1);const float e3=0.38;const vec4 v3=vec4(0.6235294117647059,0.26666666666666666,0.09803921568627451,1);const float e4=0.5;const vec4 v4=vec4(0.7137254901960784,0.38823529411764707,0.07450980392156863,1);const float e5=0.63;const vec4 v5=vec4(0.7803921568627451,0.5254901960784314,0.08627450980392157,1);const float e6=0.75;const vec4 v6=vec4(0.8313725490196079,0.6705882352941176,0.13725490196078433,1);const float e7=0.88;const vec4 v7=vec4(0.8666666666666667,0.8235294117647058,0.21176470588235294,1);const float e8=1.0;const vec4 v8=vec4(0.8823529411764706,0.9921568627450981,0.29411764705882354,1);float a0=smoothstep(e0,e1,x_28);float a1=smoothstep(e1,e2,x_28);float a2=smoothstep(e2,e3,x_28);float a3=smoothstep(e3,e4,x_28);float a4=smoothstep(e4,e5,x_28);float a5=smoothstep(e5,e6,x_28);float a6=smoothstep(e6,e7,x_28);float a7=smoothstep(e7,e8,x_28);return max(mix(v0,v1,a0)*step(e0,x_28)*step(x_28,e1),max(mix(v1,v2,a1)*step(e1,x_28)*step(x_28,e2),max(mix(v2,v3,a2)*step(e2,x_28)*step(x_28,e3),max(mix(v3,v4,a3)*step(e3,x_28)*step(x_28,e4),max(mix(v4,v5,a4)*step(e4,x_28)*step(x_28,e5),max(mix(v5,v6,a5)*step(e5,x_28)*step(x_28,e6),max(mix(v6,v7,a6)*step(e6,x_28)*step(x_28,e7),mix(v7,v8,a7)*step(e7,x_28)*step(x_28,e8))))))));}vec4 phase(float x_39){const float e0=0.0;const vec4 v0=vec4(0.5686274509803921,0.4117647058823529,0.07058823529411765,1);const float e1=0.13;const vec4 v1=vec4(0.7215686274509804,0.2784313725490196,0.14901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.7294117647058823,0.22745098039215686,0.45098039215686275,1);const float e3=0.38;const vec4 v3=vec4(0.6274509803921569,0.2784313725490196,0.7254901960784313,1);const float e4=0.5;const vec4 v4=vec4(0.43137254901960786,0.3803921568627451,0.8549019607843137,1);const float e5=0.63;const vec4 v5=vec4(0.19607843137254902,0.4823529411764706,0.6431372549019608,1);const float e6=0.75;const vec4 v6=vec4(0.12156862745098039,0.5137254901960784,0.43137254901960786,1);const float e7=0.88;const vec4 v7=vec4(0.30196078431372547,0.5058823529411764,0.13333333333333333,1);const float e8=1.0;const vec4 v8=vec4(0.5686274509803921,0.4117647058823529,0.07058823529411765,1);float a0=smoothstep(e0,e1,x_39);float a1=smoothstep(e1,e2,x_39);float a2=smoothstep(e2,e3,x_39);float a3=smoothstep(e3,e4,x_39);float a4=smoothstep(e4,e5,x_39);float a5=smoothstep(e5,e6,x_39);float a6=smoothstep(e6,e7,x_39);float a7=smoothstep(e7,e8,x_39);return max(mix(v0,v1,a0)*step(e0,x_39)*step(x_39,e1),max(mix(v1,v2,a1)*step(e1,x_39)*step(x_39,e2),max(mix(v2,v3,a2)*step(e2,x_39)*step(x_39,e3),max(mix(v3,v4,a3)*step(e3,x_39)*step(x_39,e4),max(mix(v4,v5,a4)*step(e4,x_39)*step(x_39,e5),max(mix(v5,v6,a5)*step(e5,x_39)*step(x_39,e6),max(mix(v6,v7,a6)*step(e6,x_39)*step(x_39,e7),mix(v7,v8,a7)*step(e7,x_39)*step(x_39,e8))))))));}vec4 salinity(float x_26){const float e0=0.0;const vec4 v0=vec4(0.16470588235294117,0.09411764705882353,0.4235294117647059,1);const float e1=0.13;const vec4 v1=vec4(0.12941176470588237,0.19607843137254902,0.6352941176470588,1);const float e2=0.25;const vec4 v2=vec4(0.058823529411764705,0.35294117647058826,0.5686274509803921,1);const float e3=0.38;const vec4 v3=vec4(0.1568627450980392,0.4627450980392157,0.5372549019607843,1);const float e4=0.5;const vec4 v4=vec4(0.23137254901960785,0.5725490196078431,0.5294117647058824,1);const float e5=0.63;const vec4 v5=vec4(0.30980392156862746,0.6862745098039216,0.49411764705882355,1);const float e6=0.75;const vec4 v6=vec4(0.47058823529411764,0.796078431372549,0.40784313725490196,1);const float e7=0.88;const vec4 v7=vec4(0.7568627450980392,0.8666666666666667,0.39215686274509803,1);const float e8=1.0;const vec4 v8=vec4(0.9921568627450981,0.9372549019607843,0.6039215686274509,1);float a0=smoothstep(e0,e1,x_26);float a1=smoothstep(e1,e2,x_26);float a2=smoothstep(e2,e3,x_26);float a3=smoothstep(e3,e4,x_26);float a4=smoothstep(e4,e5,x_26);float a5=smoothstep(e5,e6,x_26);float a6=smoothstep(e6,e7,x_26);float a7=smoothstep(e7,e8,x_26);return max(mix(v0,v1,a0)*step(e0,x_26)*step(x_26,e1),max(mix(v1,v2,a1)*step(e1,x_26)*step(x_26,e2),max(mix(v2,v3,a2)*step(e2,x_26)*step(x_26,e3),max(mix(v3,v4,a3)*step(e3,x_26)*step(x_26,e4),max(mix(v4,v5,a4)*step(e4,x_26)*step(x_26,e5),max(mix(v5,v6,a5)*step(e5,x_26)*step(x_26,e6),max(mix(v6,v7,a6)*step(e6,x_26)*step(x_26,e7),mix(v7,v8,a7)*step(e7,x_26)*step(x_26,e8))))))));}vec4 temperature(float x_8){const float e0=0.0;const vec4 v0=vec4(0.01568627450980392,0.13725490196078433,0.2,1);const float e1=0.13;const vec4 v1=vec4(0.09019607843137255,0.2,0.47843137254901963,1);const float e2=0.25;const vec4 v2=vec4(0.3333333333333333,0.23137254901960785,0.615686274509804,1);const float e3=0.38;const vec4 v3=vec4(0.5058823529411764,0.30980392156862746,0.5607843137254902,1);const float e4=0.5;const vec4 v4=vec4(0.6862745098039216,0.37254901960784315,0.5098039215686274,1);const float e5=0.63;const vec4 v5=vec4(0.8705882352941177,0.4392156862745098,0.396078431372549,1);const float e6=0.75;const vec4 v6=vec4(0.9764705882352941,0.5725490196078431,0.25882352941176473,1);const float e7=0.88;const vec4 v7=vec4(0.9764705882352941,0.7686274509803922,0.2549019607843137,1);const float e8=1.0;const vec4 v8=vec4(0.9098039215686274,0.9803921568627451,0.3568627450980392,1);float a0=smoothstep(e0,e1,x_8);float a1=smoothstep(e1,e2,x_8);float a2=smoothstep(e2,e3,x_8);float a3=smoothstep(e3,e4,x_8);float a4=smoothstep(e4,e5,x_8);float a5=smoothstep(e5,e6,x_8);float a6=smoothstep(e6,e7,x_8);float a7=smoothstep(e7,e8,x_8);return max(mix(v0,v1,a0)*step(e0,x_8)*step(x_8,e1),max(mix(v1,v2,a1)*step(e1,x_8)*step(x_8,e2),max(mix(v2,v3,a2)*step(e2,x_8)*step(x_8,e3),max(mix(v3,v4,a3)*step(e3,x_8)*step(x_8,e4),max(mix(v4,v5,a4)*step(e4,x_8)*step(x_8,e5),max(mix(v5,v6,a5)*step(e5,x_8)*step(x_8,e6),max(mix(v6,v7,a6)*step(e6,x_8)*step(x_8,e7),mix(v7,v8,a7)*step(e7,x_8)*step(x_8,e8))))))));}vec4 turbidity(float x_40){const float e0=0.0;const vec4 v0=vec4(0.13333333333333333,0.12156862745098039,0.10588235294117647,1);const float e1=0.13;const vec4 v1=vec4(0.2549019607843137,0.19607843137254902,0.1607843137254902,1);const float e2=0.25;const vec4 v2=vec4(0.3843137254901961,0.27058823529411763,0.20392156862745098,1);const float e3=0.38;const vec4 v3=vec4(0.5137254901960784,0.34901960784313724,0.2235294117647059,1);const float e4=0.5;const vec4 v4=vec4(0.6313725490196078,0.4392156862745098,0.23137254901960785,1);const float e5=0.63;const vec4 v5=vec4(0.7254901960784313,0.5490196078431373,0.25882352941176473,1);const float e6=0.75;const vec4 v6=vec4(0.792156862745098,0.6823529411764706,0.34509803921568627,1);const float e7=0.88;const vec4 v7=vec4(0.8470588235294118,0.8196078431372549,0.49411764705882355,1);const float e8=1.0;const vec4 v8=vec4(0.9137254901960784,0.9647058823529412,0.6705882352941176,1);float a0=smoothstep(e0,e1,x_40);float a1=smoothstep(e1,e2,x_40);float a2=smoothstep(e2,e3,x_40);float a3=smoothstep(e3,e4,x_40);float a4=smoothstep(e4,e5,x_40);float a5=smoothstep(e5,e6,x_40);float a6=smoothstep(e6,e7,x_40);float a7=smoothstep(e7,e8,x_40);return max(mix(v0,v1,a0)*step(e0,x_40)*step(x_40,e1),max(mix(v1,v2,a1)*step(e1,x_40)*step(x_40,e2),max(mix(v2,v3,a2)*step(e2,x_40)*step(x_40,e3),max(mix(v3,v4,a3)*step(e3,x_40)*step(x_40,e4),max(mix(v4,v5,a4)*step(e4,x_40)*step(x_40,e5),max(mix(v5,v6,a5)*step(e5,x_40)*step(x_40,e6),max(mix(v6,v7,a6)*step(e6,x_40)*step(x_40,e7),mix(v7,v8,a7)*step(e7,x_40)*step(x_40,e8))))))));}vec4 velocity_blue_297387650(float x_2){const float e0=0.0;const vec4 v0=vec4(0.06666666666666667,0.12549019607843137,0.25098039215686274,1);const float e1=0.13;const vec4 v1=vec4(0.13725490196078433,0.20392156862745098,0.4549019607843137,1);const float e2=0.25;const vec4 v2=vec4(0.11372549019607843,0.3176470588235294,0.611764705882353,1);const float e3=0.38;const vec4 v3=vec4(0.12156862745098039,0.44313725490196076,0.6352941176470588,1);const float e4=0.5;const vec4 v4=vec4(0.19607843137254902,0.5647058823529412,0.6627450980392157,1);const float e5=0.63;const vec4 v5=vec4(0.3411764705882353,0.6784313725490196,0.6901960784313725,1);const float e6=0.75;const vec4 v6=vec4(0.5843137254901961,0.7686274509803922,0.7411764705882353,1);const float e7=0.88;const vec4 v7=vec4(0.796078431372549,0.8666666666666667,0.8274509803921568,1);const float e8=1.0;const vec4 v8=vec4(0.996078431372549,0.984313725490196,0.9019607843137255,1);float a0=smoothstep(e0,e1,x_2);float a1=smoothstep(e1,e2,x_2);float a2=smoothstep(e2,e3,x_2);float a3=smoothstep(e3,e4,x_2);float a4=smoothstep(e4,e5,x_2);float a5=smoothstep(e5,e6,x_2);float a6=smoothstep(e6,e7,x_2);float a7=smoothstep(e7,e8,x_2);return max(mix(v0,v1,a0)*step(e0,x_2)*step(x_2,e1),max(mix(v1,v2,a1)*step(e1,x_2)*step(x_2,e2),max(mix(v2,v3,a2)*step(e2,x_2)*step(x_2,e3),max(mix(v3,v4,a3)*step(e3,x_2)*step(x_2,e4),max(mix(v4,v5,a4)*step(e4,x_2)*step(x_2,e5),max(mix(v5,v6,a5)*step(e5,x_2)*step(x_2,e6),max(mix(v6,v7,a6)*step(e6,x_2)*step(x_2,e7),mix(v7,v8,a7)*step(e7,x_2)*step(x_2,e8))))))));}vec4 velocity_green_2558432129(float x_27){const float e0=0.0;const vec4 v0=vec4(0.09019607843137255,0.13725490196078433,0.07450980392156863,1);const float e1=0.13;const vec4 v1=vec4(0.09411764705882353,0.25098039215686274,0.14901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.043137254901960784,0.37254901960784315,0.17647058823529413,1);const float e3=0.38;const vec4 v3=vec4(0.15294117647058825,0.4823529411764706,0.13725490196078433,1);const float e4=0.5;const vec4 v4=vec4(0.37254901960784315,0.5725490196078431,0.047058823529411764,1);const float e5=0.63;const vec4 v5=vec4(0.596078431372549,0.6470588235294118,0.07058823529411765,1);const float e6=0.75;const vec4 v6=vec4(0.788235294117647,0.7294117647058823,0.27058823529411763,1);const float e7=0.88;const vec4 v7=vec4(0.9137254901960784,0.8470588235294118,0.5372549019607843,1);const float e8=1.0;const vec4 v8=vec4(1,0.9921568627450981,0.803921568627451,1);float a0=smoothstep(e0,e1,x_27);float a1=smoothstep(e1,e2,x_27);float a2=smoothstep(e2,e3,x_27);float a3=smoothstep(e3,e4,x_27);float a4=smoothstep(e4,e5,x_27);float a5=smoothstep(e5,e6,x_27);float a6=smoothstep(e6,e7,x_27);float a7=smoothstep(e7,e8,x_27);return max(mix(v0,v1,a0)*step(e0,x_27)*step(x_27,e1),max(mix(v1,v2,a1)*step(e1,x_27)*step(x_27,e2),max(mix(v2,v3,a2)*step(e2,x_27)*step(x_27,e3),max(mix(v3,v4,a3)*step(e3,x_27)*step(x_27,e4),max(mix(v4,v5,a4)*step(e4,x_27)*step(x_27,e5),max(mix(v5,v6,a5)*step(e5,x_27)*step(x_27,e6),max(mix(v6,v7,a6)*step(e6,x_27)*step(x_27,e7),mix(v7,v8,a7)*step(e7,x_27)*step(x_27,e8))))))));}vec4 cubehelix(float x_37){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.07;const vec4 v1=vec4(0.08627450980392157,0.0196078431372549,0.23137254901960785,1);const float e2=0.13;const vec4 v2=vec4(0.23529411764705882,0.01568627450980392,0.4117647058823529,1);const float e3=0.2;const vec4 v3=vec4(0.42745098039215684,0.00392156862745098,0.5294117647058824,1);const float e4=0.27;const vec4 v4=vec4(0.6313725490196078,0,0.5764705882352941,1);const float e5=0.33;const vec4 v5=vec4(0.8235294117647058,0.00784313725490196,0.5568627450980392,1);const float e6=0.4;const vec4 v6=vec4(0.984313725490196,0.043137254901960784,0.4823529411764706,1);const float e7=0.47;const vec4 v7=vec4(1,0.11372549019607843,0.3803921568627451,1);const float e8=0.53;const vec4 v8=vec4(1,0.21176470588235294,0.27058823529411763,1);const float e9=0.6;const vec4 v9=vec4(1,0.3333333333333333,0.1803921568627451,1);const float e10=0.67;const vec4 v10=vec4(1,0.47058823529411764,0.13333333333333333,1);const float e11=0.73;const vec4 v11=vec4(1,0.615686274509804,0.1450980392156863,1);const float e12=0.8;const vec4 v12=vec4(0.9450980392156862,0.7490196078431373,0.2235294117647059,1);const float e13=0.87;const vec4 v13=vec4(0.8784313725490196,0.8627450980392157,0.36470588235294116,1);const float e14=0.93;const vec4 v14=vec4(0.8549019607843137,0.9450980392156862,0.5568627450980392,1);const float e15=1.0;const vec4 v15=vec4(0.8901960784313725,0.9921568627450981,0.7764705882352941,1);float a0=smoothstep(e0,e1,x_37);float a1=smoothstep(e1,e2,x_37);float a2=smoothstep(e2,e3,x_37);float a3=smoothstep(e3,e4,x_37);float a4=smoothstep(e4,e5,x_37);float a5=smoothstep(e5,e6,x_37);float a6=smoothstep(e6,e7,x_37);float a7=smoothstep(e7,e8,x_37);float a8=smoothstep(e8,e9,x_37);float a9=smoothstep(e9,e10,x_37);float a10=smoothstep(e10,e11,x_37);float a11=smoothstep(e11,e12,x_37);float a12=smoothstep(e12,e13,x_37);float a13=smoothstep(e13,e14,x_37);float a14=smoothstep(e14,e15,x_37);return max(mix(v0,v1,a0)*step(e0,x_37)*step(x_37,e1),max(mix(v1,v2,a1)*step(e1,x_37)*step(x_37,e2),max(mix(v2,v3,a2)*step(e2,x_37)*step(x_37,e3),max(mix(v3,v4,a3)*step(e3,x_37)*step(x_37,e4),max(mix(v4,v5,a4)*step(e4,x_37)*step(x_37,e5),max(mix(v5,v6,a5)*step(e5,x_37)*step(x_37,e6),max(mix(v6,v7,a6)*step(e6,x_37)*step(x_37,e7),max(mix(v7,v8,a7)*step(e7,x_37)*step(x_37,e8),max(mix(v8,v9,a8)*step(e8,x_37)*step(x_37,e9),max(mix(v9,v10,a9)*step(e9,x_37)*step(x_37,e10),max(mix(v10,v11,a10)*step(e10,x_37)*step(x_37,e11),max(mix(v11,v12,a11)*step(e11,x_37)*step(x_37,e12),max(mix(v12,v13,a12)*step(e12,x_37)*step(x_37,e13),max(mix(v13,v14,a13)*step(e13,x_37)*step(x_37,e14),mix(v14,v15,a14)*step(e14,x_37)*step(x_37,e15)))))))))))))));}float apply_contrast_limits(float intensity,vec2 contrastLimits){float contrastLimitsAppliedToIntensity=(intensity-contrastLimits[0])/max(0.0005,(contrastLimits[1]-contrastLimits[0]));return max(0.,contrastLimitsAppliedToIntensity);}vec4 colormap(float intensity,float opacity){return vec4(COLORMAP_FUNCTION(min(1.,intensity)).xyz,opacity);}"},po=(li={},Object(g.a)(li,pi.MAX_INTENSITY_PROJECTION,{_BEFORE_RENDER:" float maxVals[6] = float[6](-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);\n ",_RENDER:" \n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n\n for(int i = 0; i < 6; i++) {\n if(intensityArray[i] > maxVals[i]) {\n maxVals[i] = intensityArray[i];\n }\n }\n ",_AFTER_RENDER:" vec3 rgbCombo = vec3(0.0);\n for(int i = 0; i < 6; i++) {\n rgbCombo += max(0.0, min(1.0, maxVals[i])) * vec3(colors[i]);\n }\n color = vec4(rgbCombo, 1.0);\n "}),Object(g.a)(li,pi.MIN_INTENSITY_PROJECTION,{_BEFORE_RENDER:" float minVals[6] = float[6](1. / 0., 1. / 0., 1. / 0., 1. / 0., 1. / 0., 1. / 0.);\n ",_RENDER:" \n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n\n for(int i = 0; i < 6; i++) {\n if(intensityArray[i] < minVals[i]) {\n minVals[i] = intensityArray[i];\n }\n }\n ",_AFTER_RENDER:" vec3 rgbCombo = vec3(0.0);\n for(int i = 0; i < 6; i++) {\n rgbCombo += max(0.0, min(1.0, minVals[i])) * vec3(colors[i]);\n }\n color = vec4(rgbCombo, 1.0);\n "}),Object(g.a)(li,pi.ADDITIVE,{_BEFORE_RENDER:"",_RENDER:" vec3 rgbCombo = vec3(0.0);\n vec3 hsvCombo = vec3(0.0);\n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n float total = 0.0;\n for(int i = 0; i < 6; i++) {\n float intensityValue = intensityArray[i];\n rgbCombo += max(0.0, min(1.0, intensityValue)) * colors[i];\n total += intensityValue;\n }\n // Do not go past 1 in opacity.\n total = min(total, 1.0);\n vec4 val_color = vec4(rgbCombo, total);\n // Opacity correction\n val_color.a = 1.0 - pow(1.0 - val_color.a, 1.0);\n color.rgb += (1.0 - color.a) * val_color.a * val_color.rgb;\n color.a += (1.0 - color.a) * val_color.a;\n if (color.a >= 0.95) {\n break;\n }\n ",_AFTER_RENDER:""}),li),Eo=(Ii={},Object(g.a)(Ii,pi.MAX_INTENSITY_PROJECTION,{_BEFORE_RENDER:" float maxVals[6] = float[6](-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);\n ",_RENDER:" \n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n\n for(int i = 0; i < 6; i++) {\n if(intensityArray[i] > maxVals[i]) {\n maxVals[i] = intensityArray[i];\n }\n }\n ",_AFTER_RENDER:" float total = 0.0;\n for(int i = 0; i < 6; i++) {\n total += maxVals[i];\n }\n // Do not go past 1 in opacity/colormap value.\n total = min(total, 1.0);\n color = colormap(total, total);\n "}),Object(g.a)(Ii,pi.MIN_INTENSITY_PROJECTION,{_BEFORE_RENDER:" float minVals[6] = float[6](1. / 0., 1. / 0., 1. / 0., 1. / 0., 1. / 0., 1. / 0.);\n ",_RENDER:" \n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n\n for(int i = 0; i < 6; i++) {\n if(intensityArray[i] < minVals[i]) {\n minVals[i] = intensityArray[i];\n }\n }\n ",_AFTER_RENDER:" float total = 0.0;\n for(int i = 0; i < 6; i++) {\n total += minVals[i];\n }\n // Do not go past 1 in opacity/colormap value.\n total = min(total, 1.0);\n color = colormap(total, total);\n "}),Object(g.a)(Ii,pi.ADDITIVE,{_BEFORE_RENDER:"",_RENDER:" float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n\t\tfloat total = 0.0;\n\n\t\tfor(int i = 0; i < 6; i++) {\n\t\t\ttotal += intensityArray[i];\n\t\t}\n\t\t// Do not go past 1 in opacity/colormap value.\n\t\ttotal = min(total, 1.0);\n\n\t\tvec4 val_color = colormap(total, total);\n\n\t\t// Opacity correction\n\t\tval_color.a = 1.0 - pow(1.0 - val_color.a, 1.0);\n\t\tcolor.rgb += (1.0 - color.a) * val_color.a * val_color.rgb;\n\t\tcolor.a += (1.0 - color.a) * val_color.a;\n\t\tif (color.a >= 0.95) {\n\t\t\tbreak;\n\t\t}\n p += ray_dir * dt;\n ",_AFTER_RENDER:""}),Ii),Qo=[1,1,0,0,1,0,1,1,1,0,1,1,0,0,1,0,1,0,0,0,0,1,1,0,1,0,0,1,1,1,1,0,1,0,0,1,1,0,0,0,0,0],yo={pickable:!1,coordinateSystem:p.a.CARTESIAN,channelData:{type:"object",value:{},compare:!0},colors:{type:"array",value:[],compare:!0},contrastLimits:{type:"array",value:[],compare:!0},dtype:{type:"string",value:"Uint8",compare:!0},colormap:{type:"string",value:"",compare:!0},xSlice:{type:"array",value:null,compare:!0},ySlice:{type:"array",value:null,compare:!0},zSlice:{type:"array",value:null,compare:!0},clippingPlanes:{type:"array",value:[],compare:!0},renderingMode:{type:"string",value:pi.ADDITIVE,compare:!0},resolutionMatrix:{type:"object",value:new S.Matrix4,compare:!0}};function vo(){var e=Si("Float32");return Object(d.a)({},e,{sampler:e.sampler.replace("2D","3D"),cast:function(e){return new Float32Array(e)}})}var mo=function(e){Object(h.a)(A,e);var t=Object(f.a)(A);function A(){return Object(u.a)(this,A),t.apply(this,arguments)}return Object(l.a)(A,[{key:"initializeState",value:function(){var e=this.context.gl;e.pixelStorei(F.default.UNPACK_ALIGNMENT,1),e.pixelStorei(F.default.PACK_ALIGNMENT,1);var t=U.a.getDefaultProgramManager(e),A="fs:DECKGL_PROCESS_INTENSITY(inout float intensity, vec2 contrastLimits, int channelIndex)";t._hookFunctions.includes(A)||t.addShaderHook(A)}},{key:"_isHookDefinedByExtensions",value:function(e){var t=this.props.extensions;return null===t||void 0===t?void 0:t.some((function(t){var A=t.getShaders(),n=A.inject,r=void 0===n?{}:n,i=A.modules,o=void 0===i?[]:i,a=r[e],s=o.some((function(t){return null===t||void 0===t?void 0:t.inject[e]}));return a||s}))}},{key:"getShaders",value:function(){var e=this.props,t=e.colormap,n=e.renderingMode,r=e.clippingPlanes,i=vo().sampler,o=t?Eo[n]:po[n],a=o._BEFORE_RENDER,s=o._RENDER,g=o._AFTER_RENDER,c=function(e){var t=bi.filter((function(t){return t!==(e||"viridis")})).map((function(e){return e.replace(/-/g,"_")})),A=new RegExp("vec4 (".concat(t.join("(_([0-9]*))?|"),")\\(float x_[0-9]+\\){([^}]+)}"),"g");return Object(d.a)({},Bo,{fs:Bo.fs.replace(A,""),defines:{COLORMAP_FUNCTION:e||"viridis"}})}(t),u=this._isHookDefinedByExtensions("fs:DECKGL_PROCESS_INTENSITY"),l=Object(d.a)({},c,{inject:{}});return u||(l.inject["fs:DECKGL_PROCESS_INTENSITY"]="\n intensity = apply_contrast_limits(intensity, contrastLimits);\n "),Object(C.a)(Object(I.a)(A.prototype),"getShaders",this).call(this,{vs:'#version 300 es\n#define GLSLIFY 1\n#define SHADER_NAME xr-layer-vertex-shader\nin vec3 positions;uniform vec3 eye_pos;uniform mat4 proj;uniform mat4 model;uniform mat4 view;uniform mat4 scale;uniform mat4 resolution;out vec3 vray_dir;flat out vec3 transformed_eye;void main(){gl_Position=proj*view*model*scale*resolution*vec4(positions,1.);/*This first diagram is a skewed volume(i.e a "shear" model matrix applied)top down with the eye marked as #,all in world space^___|__\\|\\\\|\\|____|||\n#\nThis next diagram shows the volume after the inverse model matrix has placed it back in model coordinates,but the eye still in world space.^___|___|||||||__|__||||\n#\nFinally,we apply the inverse model matrix transformation to the eye as well to bring it too into world space.Notice that the ray here matches the "voxels" through which the first ray also passes,as desired.^____/__|/||/||/____|///\n#\n*/transformed_eye=(inverse(resolution)*inverse(scale)*inverse(model)*(vec4(eye_pos,1.))).xyz;vray_dir=positions-transformed_eye;}',fs:"#version 300 es\nprecision highp int;precision highp float;precision highp SAMPLER_TYPE;\n#define GLSLIFY 1\nuniform highp SAMPLER_TYPE volume0;uniform highp SAMPLER_TYPE volume1;uniform highp SAMPLER_TYPE volume2;uniform highp SAMPLER_TYPE volume3;uniform highp SAMPLER_TYPE volume4;uniform highp SAMPLER_TYPE volume5;uniform vec3 scaledDimensions;uniform mat4 scale;uniform vec3 normals[NUM_PLANES];uniform float distances[NUM_PLANES];uniform vec3 colors[6];uniform vec2 xSlice;uniform vec2 ySlice;uniform vec2 zSlice;uniform vec2 contrastLimits[6];in vec3 vray_dir;flat in vec3 transformed_eye;out vec4 color;vec2 intersect_box(vec3 orig,vec3 dir){vec3 box_min=vec3(xSlice[0],ySlice[0],zSlice[0]);vec3 box_max=vec3(xSlice[1],ySlice[1],zSlice[1]);vec3 inv_dir=1./dir;vec3 tmin_tmp=(box_min-orig)*inv_dir;vec3 tmax_tmp=(box_max-orig)*inv_dir;vec3 tmin=min(tmin_tmp,tmax_tmp);vec3 tmax=max(tmin_tmp,tmax_tmp);float t0=max(tmin.x,max(tmin.y,tmin.z));float t1=min(tmax.x,min(tmax.y,tmax.z));vec2 val=vec2(t0,t1);return val;}float linear_to_srgb(float x){if(x<=0.0031308f){return 12.92f*x;}return 1.055f*pow(x,1.f/2.4f)-0.055f;}float wang_hash(int seed){seed=(seed ^ 61)^(seed>>16);seed*=9;seed=seed ^(seed>>4);seed*=0x27d4eb2d;seed=seed ^(seed>>15);return float(seed % 2147483647)/float(2147483647);}void main(void){vec3 ray_dir=normalize(vray_dir);vec2 t_hit=intersect_box(transformed_eye,ray_dir);if(t_hit.x>t_hit.y){discard;}t_hit.x=max(t_hit.x,0.);vec3 dt_vec=1./(scale*vec4(abs(ray_dir),1.)).xyz;float dt=1.*min(dt_vec.x,min(dt_vec.y,dt_vec.z));float offset=wang_hash(int(gl_FragCoord.x+640.*gl_FragCoord.y));vec3 p=transformed_eye+(t_hit.x+offset*dt)*ray_dir;_BEFORE_RENDERfor(float t=t_hit.x;t0&&e.data){var n=e.height,r=e.width,i=e.depth;e.data.forEach((function(e,o){A["volume".concat(o)]=t.dataToTexture(e,r,n,i)}),this),this.setState({textures:A,scaleMatrix:(new S.Matrix4).scale(this.props.physicalSizeScalingMatrix.transformPoint([r,n,i]))})}}},{key:"dataToTexture",value:function(e,t,A,n){var r,i,o,a=vo();return new N.a(this.context.gl,{width:t,height:A,depth:n,data:null!==(r=null===(i=a.cast)||void 0===i?void 0:i.call(a,e))&&void 0!==r?r:e,format:a.dataFormat,dataFormat:a.format,type:a.type,mipmaps:!1,parameters:(o={},Object(g.a)(o,F.default.TEXTURE_MIN_FILTER,F.default.LINEAR),Object(g.a)(o,F.default.TEXTURE_MAG_FILTER,F.default.LINEAR),Object(g.a)(o,F.default.TEXTURE_WRAP_S,F.default.CLAMP_TO_EDGE),Object(g.a)(o,F.default.TEXTURE_WRAP_T,F.default.CLAMP_TO_EDGE),Object(g.a)(o,F.default.TEXTURE_WRAP_R,F.default.CLAMP_TO_EDGE),o)})}}]),A}(y.a);function bo(){return(bo=Object(a.a)(o.a.mark((function e(t){var A,n,r,i,s,g,c,u,l,I,C,h,f,B,p,E,Q,y,v;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=t.source,n=t.selection,r=t.onUpdate,i=void 0===r?function(){}:r,s=t.downsampleDepth,g=void 0===s?1:s,c=t.signal,u=A.shape,l=A.labels,I=A.dtype,C=ji(A),h=C.height,f=C.width,B=u[l.indexOf("z")],p=Math.max(1,Math.floor(B/g)),E=h*f,Q="".concat(I,"Array"),y=globalThis[Q],v=new y(E*p),e.next=11,Promise.all(new Array(p).fill(0).map(function(){var e=Object(a.a)(o.a.mark((function e(t,r){var a,s,u,l,I,C;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=Object(d.a)({},n,{z:r*g}),e.next=3,A.getRaster({selection:a,signal:c});case 3:for(s=e.sent,u=s.data,l=0,i();l>u)*c.length,f=function(){C+=.5/h,t.props.onUpdate&&t.props.onUpdate({progress:C}),t.setState({progress:C})},B=new AbortController;this.setState({abortController:B});var p=B.signal,E=c.map((function(e){return function(e){return bo.apply(this,arguments)}({selection:e,source:I,onUpdate:f,downsampleDepth:Math.pow(2,u),signal:p})})),Q=Ri(s[u]);Promise.all(E).then((function(e){l&&l(e);var A={data:e.map((function(e){return e.data})),width:e[0].width,height:e[0].height,depth:e[0].depth};t.setState(Object(d.a)({},A,{physicalSizeScalingMatrix:Q,resolutionMatrix:(new S.Matrix4).scale(Math.pow(2,u))}))}))}}},{key:"renderLayers",value:function(){var e,t=this.props,A=t.loader,n=t.id,r=t.resolution,i=t.useProgressIndicator,o=t.useWebGL1Warning,a=A[r].dtype,s=this.state,c=s.data,u=s.width,l=s.height,I=s.depth,C=s.progress,h=s.physicalSizeScalingMatrix,f=s.resolutionMatrix,d=this.context.gl;if(!Object(D.j)(d)&&o){var B=this.context.viewport;return wo(["Volume rendering is only available on browsers that support WebGL2. If you","are using Safari, you can turn on WebGL2 by navigating in the top menubar","to check Develop > Experimental Features > WebGL 2.0 and then refreshing","the page."].join("\n"),B,n)}if((!u||!l)&&i){var p=this.context.viewport;return wo("Loading Volume ".concat(String(100*(C||0)).slice(0,5),"%..."),p,n)}return new mo(this.props,{channelData:{data:c,width:u,height:l,depth:I},id:"XR3DLayer-".concat(0,"-",l,"-").concat(u,"-",0,"-").concat(r,"-").concat(n),physicalSizeScalingMatrix:h,parameters:(e={},Object(g.a)(e,F.default.CULL_FACE,!0),Object(g.a)(e,F.default.CULL_FACE_MODE,F.default.FRONT),Object(g.a)(e,F.default.DEPTH_TEST,!1),Object(g.a)(e,"blendFunc",[F.default.SRC_ALPHA,F.default.ONE]),Object(g.a)(e,"blend",!0),e),resolutionMatrix:f,dtype:a})}}]),A}(v.a);Fo.layerName="VolumeLayer",Fo.defaultProps=So;var Ro="/Users/ilangold/Projects/Gehlenborg/viv/src/viewers/VivViewer.jsx",Do=(P.PureComponent,function e(){Object(u.a)(this,e)}),Go=(w.a,"".concat("__viv","-offsets"));function ko(e){(function(e,t){return e[t]})(e,Go)||console.warn("GeoTIFF source is missing offsets proxy.")}function xo(e,t){return new Proxy(e,{get:function(e,A){return"getImage"===A?function(A){if(!(A in e.ifdRequests)&&A in t){var n=t[A];e.ifdRequests[A]=e.parseFileDirectoryAt(n)}return e.getImage(A)}:A===Go||Reflect.get(e,A)}})}var No="KGZ1bmN0aW9uICgpIHsKICAndXNlIHN0cmljdCc7CgogIGZ1bmN0aW9uIGRlY29kZVJvd0FjYyhyb3csIHN0cmlkZSkgewogICAgbGV0IGxlbmd0aCA9IHJvdy5sZW5ndGggLSBzdHJpZGU7CiAgICBsZXQgb2Zmc2V0ID0gMDsKICAgIGRvIHsKICAgICAgZm9yIChsZXQgaSA9IHN0cmlkZTsgaSA+IDA7IGktLSkgewogICAgICAgIHJvd1tvZmZzZXQgKyBzdHJpZGVdICs9IHJvd1tvZmZzZXRdOwogICAgICAgIG9mZnNldCsrOwogICAgICB9CgogICAgICBsZW5ndGggLT0gc3RyaWRlOwogICAgfSB3aGlsZSAobGVuZ3RoID4gMCk7CiAgfQoKICBmdW5jdGlvbiBkZWNvZGVSb3dGbG9hdGluZ1BvaW50KHJvdywgc3RyaWRlLCBieXRlc1BlclNhbXBsZSkgewogICAgbGV0IGluZGV4ID0gMDsKICAgIGxldCBjb3VudCA9IHJvdy5sZW5ndGg7CiAgICBjb25zdCB3YyA9IGNvdW50IC8gYnl0ZXNQZXJTYW1wbGU7CgogICAgd2hpbGUgKGNvdW50ID4gc3RyaWRlKSB7CiAgICAgIGZvciAobGV0IGkgPSBzdHJpZGU7IGkgPiAwOyAtLWkpIHsKICAgICAgICByb3dbaW5kZXggKyBzdHJpZGVdICs9IHJvd1tpbmRleF07CiAgICAgICAgKytpbmRleDsKICAgICAgfQogICAgICBjb3VudCAtPSBzdHJpZGU7CiAgICB9CgogICAgY29uc3QgY29weSA9IHJvdy5zbGljZSgpOwogICAgZm9yIChsZXQgaSA9IDA7IGkgPCB3YzsgKytpKSB7CiAgICAgIGZvciAobGV0IGIgPSAwOyBiIDwgYnl0ZXNQZXJTYW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mlwIHdpbGwgYmUgdHJ1bmNhdGVkIGlmIGhlaWdodCAlIHN0cmlwSGVpZ2h0ICE9IDAKICAgICAgaWYgKGkgKiBzdHJpZGUgKiB3aWR0aCAqIGJ5dGVzUGVyU2FtcGxlID49IGJsb2NrLmJ5dGVMZW5ndGgpIHsKICAgICAgICBicmVhazsKICAgICAgfQogICAgICBsZXQgcm93OwogICAgICBpZiAocHJlZGljdG9yID09PSAyKSB7IC8vIGhvcml6b250YWwgcHJlZGljdGlvbgogICAgICAgIHN3aXRjaCAoYml0c1BlclNhbXBsZVswXSkgewogICAgICAgICAgY2FzZSA4OgogICAgICAgICAgICByb3cgPSBuZXcgVWludDhBcnJheSgKICAgICAgICAgICAgICBibG9jaywgaSAqIHN0cmlkZSAqIHdpZHRoICogYnl0ZXNQZXJTYW1wbGUsIHN0cmlkZSAqIHdpZHRoICogYnl0ZXNQZXJTYW1wbGUsCiAgICAgICAgICAgICk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgY2FzZSAxNjoKICAgICAgICAgICAgcm93ID0gbmV3IFVpbnQxNkFycmF5KAogICAgICAgICAgICAgIGJsb2NrLCBpICogc3RyaWRlICogd2lkdGggKiBieXRlc1BlclNhbXBsZSwgc3RyaWRlICogd2lkdGggKiBieXRlc1BlclNhbXBsZSAvIDIsCiAgICAgICAgICAgICk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgY2FzZSAzMjoKICAgICAgICAgICAgcm93ID0gbmV3IFVpbnQzMkFycmF5KAogICAgICAgICAgICAgIGJsb2NrLCBpICogc3RyaWRlICogd2lkdGggKiBieXRlc1BlclNhbXBsZSwgc3RyaWRlICogd2lkdGggKiBieXRlc1BlclNhbXBsZSAvIDQsCiAgICAgICAgICAgICk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBQcmVkaWN0b3IgMiBub3QgYWxsb3dlZCB3aXRoICR7Yml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3RoID4gMCAmJiAhY29kZUxlbmd0aHNbbGVuZ3RoIC0gMV0pIHsKICAgICAgLS1sZW5ndGg7CiAgICB9CiAgICBjb2RlLnB1c2goeyBjaGlsZHJlbjogW10sIGluZGV4OiAwIH0pOwoKICAgIGxldCBwID0gY29kZVswXTsKICAgIGxldCBxOwogICAgZm9yIChsZXQgaSA9IDA7IGkgPCBsZW5ndGg7IGkrKykgewogICAgICBmb3IgKGxldCBqID0gMDsgaiA8IGNvZGVMZW5ndGhzW2ldOyBqKyspIHsKICAgICAgICBwID0gY29kZS5wb3AoKTsKICAgICAgICBwLmNoaWxkcmVuW3AuaW5kZXhdID0gdmFsdWVzW2tdOwogICAgICAgIHdoaWxlIChwLmluZGV4ID4gMCkgewogICAgICAgICAgcCA9IGNvZGUucG9wKCk7CiAgICAgICAgfQogICAgICAgIHAuaW5kZXgrKzsKICAgICAgICBjb2RlLnB1c2gocCk7CiAgICAgICAgd2hpbGUgKGNvZGUubGVuZ3RoIDw9IGkpIHsKICAgICAgICAgIGNvZGUucHVzaChxID0geyBjaGlsZHJlbjogW10sIGluZGV4OiAwIH0pOwogICAgICAgICAgcC5jaGlsZHJlbltwLmluZGV4XSA9IHEuY2hpbGRyZW47CiAgICAgICAgICBwID0gcTsKICAgICAgICB9CiAgICAgICAgaysrOwogICAgICB9CiAgICAgIGlmIChpICsgMSA8IGxlbmd0aCkgewogICAgICAgIC8vIHAgaGVyZSBwb2ludHMgdG8gbGFzdCBjb2RlCiAgICAgICAgY29kZS5wdXNoKHEgPSB7IGNoaWxkcmVuOiBbXSwgaW5kZXg6IDAgfSk7CiAgICAgICAgcC5jaGlsZHJlbltwLmluZGV4XSA9IHEuY2hpbGRyZW47CiAgICAgICAgcCA9IHE7CiAgICAgIH0KICAgIH0KICAgIHJldHVybiBjb2RlWzBdLmNoaWxkcmVuOwogIH0KCiAgZnVuY3Rpb24gZGVjb2RlU2NhbihkYXRhLCBpbml0aWFsT2Zmc2V0LAogICAgZnJhbWUsIGNv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ZS1saW5lIG5vLWNvbmQtYXNzaWduCiAgICAgICAgbm9kZSA9IG5vZGVbYml0XTsKICAgICAgICBpZiAodHlwZW9mIG5vZGUgPT09ICdudW1iZXInKSB7CiAgICAgICAgICByZXR1cm4gbm9kZTsKICAgICAgICB9CiAgICAgICAgaWYgKHR5cGVvZiBub2RlICE9PSAnb2JqZWN0JykgewogICAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdpbnZhbGlkIGh1ZmZtYW4gc2VxdWVuY2UnKTsKICAgICAgICB9CiAgICAgIH0KICAgICAgcmV0dXJuIG51bGw7CiAgICB9CiAgICBmdW5jdGlvbiByZWNlaXZlKGluaXRpYWxMZW5ndGgpIHsKICAgICAgbGV0IGxlbmd0aCA9IGluaXRpYWxMZW5ndGg7CiAgICAgIGxldCBuID0gMDsKICAgICAgd2hpbGUgKGxlbmd0aCA+IDApIHsKICAgICAgICBjb25zdCBiaXQgPSByZWFkQml0KCk7CiAgICAgICAgaWYgKGJpdCA9PT0gbnVsbCkgewogICAgICAgICAgcmV0dXJuIHVuZGVmaW5lZDsKICAgICAgICB9CiAgICAgICAgbiA9IChuIDw8IDEpIHwgYml0OwogICAgICAgIC0tbGVuZ3RoOwogICAgICB9CiAgICAgIHJldHVybiBuOwogICAgfQogICAgZnVuY3Rpb24gcmVjZWl2ZUFuZEV4dGVuZChsZW5ndGgpIHsKICAgICAgY29uc3QgbiA9IHJlY2VpdmUobGVuZ3RoKTsKICAgICAgaWYgKG4gPj0gMSA8PCAobGVuZ3RoIC0gMSkpIHsKICAgICAgICByZXR1cm4gbjsKICAgICAgfQogICAgICByZXR1cm4gbiArICgtMSA8PCBsZW5ndGgpICsgMTsKICAgIH0KICAgIGZ1bmN0aW9uIGRlY29kZUJhc2VsaW5lKGNvbXBvbmVudCwgenopIHsKICAgICAgY29uc3QgdCA9IGRlY29kZUh1ZmZtYW4oY29tcG9uZW50Lmh1ZmZtYW5UYWJsZURDKTsKICAgICAgY29uc3QgZGlmZiA9IHQgPT09IDAgPyAwIDogcmVjZWl2ZUFuZEV4dGVuZCh0KTsKICAgICAgY29tcG9uZW50LnByZWQgKz0gZGlmZjsKICAgICAgenpbMF0gPSBjb21wb25lbnQucHJlZDsKICAgICAgbGV0IGsgPSAxOwogICAgICB3aGlsZSAoayA8IDY0KSB7CiAgICAgICAgY29uc3QgcnMgPSBkZWNvZGVIdWZmbWFuKGNvbXBvbmVudC5odWZmbWFuVGFibGVBQyk7CiAgICAgICAgY29uc3QgcyA9IHJzICYgMTU7CiAgICAgICAgY29uc3QgciA9IHJzID4+IDQ7CiAgICAgICAgaWYgKHMgPT09IDApIHsKICAgICAgICAgIGlmIChyIDwgMTUpIHsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICBrICs9IDE2OwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICBrICs9IHI7CiAgICAgICAgICBjb25zdCB6ID0gZGN0WmlnWmFnW2tdOwogICAgICAgICAgenpbel0gPSByZWNlaXZlQW5kRXh0ZW5kKHMpOwogICAgICAgICAgaysrOwogICAgICAgIH0KICAgICAgfQogICAgfQogICAgZnVuY3Rpb24gZGVjb2RlRENGaXJzdChjb21wb25lbnQsIHp6KSB7CiAgICAgIGNvbnN0IHQgPSBkZWNvZGVIdWZmbWFuKGNvbXBvbmVudC5odWZmbWFuVGFibGVEQyk7CiAgICAgIGNvbnN0IGRpZmYgPSB0ID09PSAwID8gMCA6IChyZWNlaXZlQW5kRXh0ZW5kKHQpIDw8IHN1Y2Nlc3NpdmUpOwogICAgICBjb21wb25lbnQucHJlZCArPSBkaWZmOwogICAgICB6elswXSA9IGNvbXBvbmVudC5wcmVkOwogICAgfQogICAgZnVuY3Rpb24gZGVjb2RlRENTdWNjZXNzaXZlKGNvbXBvbmVudCwgenopIHsKICAgICAgenpbMF0gfD0gcmVhZEJpdCgpIDw8IHN1Y2Nlc3NpdmU7CiAgICB9CiAgICBsZXQgZW9icnVuID0gMDsKICAgIGZ1bmN0aW9uIGRlY29kZUFDRmlyc3QoY29tcG9uZW50LCB6eikgewogICAgICBpZiAoZW9icnVuID4gMCkgewogICAgICAgIGVvYnJ1bi0tOwogICAgICAgIHJldHVybjsKICAgICAgfQogICAgICBsZXQgayA9IHNwZWN0cmFsU3RhcnQ7CiAgICAgIGNvbnN0IGUgPSBzcGVjdHJhbEVuZDsKICAgICAgd2hpbGUgKGsgPD0gZSkgewogICAgICAgIGNvbnN0IHJzID0gZGVjb2RlSHVmZm1hbihjb21wb25lbnQuaHVmZm1hblRhYmxlQUMpOwogICAgICAgIGNvbnN0IHMgPSBycyAmIDE1OwogICAgICAgIGNvbnN0IHIgPSBycyA+PiA0OwogICAgICAgIGlmIChzID09PSAwKSB7CiAgICAgICAgICBpZiAociA8IDE1KSB7CiAgICAgICAgICAgIGVvYnJ1biA9IHJlY2VpdmUocikgKyAoMSA8PCByKSAtIDE7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgayArPSAxNjsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgayArPSByOwogICAgICAgICAgY29uc3QgeiA9IGRjdFppZ1phZ1trXTsKICAgICAgICAgIHp6W3pdID0gcmVjZWl2ZUFuZEV4dGVuZChzKSAqICgxIDw8IHN1Y2Nlc3NpdmUpOwogICAgICAgICAgaysrOwogICAgICAgIH0KICAgICAgfQogICAgfQogICAgbGV0IHN1Y2Nlc3NpdmVBQ1N0YXRlID0gMDsKICAgIGxldCBzdWNjZXNzaXZlQUNOZXh0VmFsdWU7CiAgICBmdW5jdGlvbiBkZWNvZGVBQ1N1Y2Nlc3NpdmUoY29tcG9uZW50LCB6eikgewogICAgICBsZXQgayA9IHNwZWN0cmFsU3RhcnQ7CiAgICAgIGNvbnN0IGUgPSBzcGVjdHJhbEVuZDsKICAgICAgbGV0IHIgPSAwOwogICAgICB3aGlsZSAoayA8PSBlKSB7CiAgICAgICAgY29uc3QgeiA9IGRjdFppZ1phZ1trXTsKICAgICAgICBjb25zdCBkaXJlY3Rpb24gPSB6elt6XSA8IDAgPyAtMSA6IDE7CiAgICAgICAgc3dpdGNoIChzdWNjZXNzaXZlQUNTdGF0ZSkgewogICAgICAgICAgY2FzZSAwOiB7IC8vIGluaXRpYWwgc3RhdGUKICAgICAgICAgICAgY29uc3QgcnMgPSBkZWNvZGVIdWZmbWFuKGNvbXBvbmVudC5odWZmbWFuVGFibGVBQyk7CiAgICAgICAgICAgIGNvbnN0IHMgPSBycyAmIDE1OwogICAgICAgICAgICByID0gcnMgPj4gNDsKICAgICAgICAgICAgaWYgKHMgPT09IDApIHsKICAgICAgICAgICAgICBpZiAociA8IDE1KSB7CiAgICAgICAgICAgICAgICBlb2JydW4gPSByZWNlaXZlKHIpICsgKDEgPDwgcik7CiAgICAgICAgICAgICAgICBzdWNjZXNzaXZlQUNTdGF0ZSA9IDQ7CiAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgIHIgPSAxNjsKICAgICAgICAgICAgICAgIHN1Y2Nlc3NpdmVBQ1N0YXRlID0gMTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgaWYgKHMgIT09IDEpIHsKICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcignaW52YWxpZCBBQ24gZW5jb2RpbmcnKTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgc3VjY2Vzc2l2ZUFDTmV4dFZhbHVlID0gcmVjZWl2ZUFuZEV4dGVuZChzKTsKICAgICAgICAgICAgICBzdWNjZXNzaXZlQUNTdGF0ZSA9IHIgPyAyIDogMzsKICAgICAgICAgICAgfQogICAgICAgICAgICBjb250aW51ZTsgLy8gZXNsaW50LWRpc2FibGUtbGluZSBuby1jb250aW51ZQogICAgICAgICAgfQogICAgICAgICAgY2FzZSAxOiAvLyBza2lwcGluZyByIHplcm8gaXRlbXMKICAgICAgICAgIGNhc2UgMjoKICAgICAgICAgICAgaWYgKHp6W3pdKSB7CiAgICAgICAgICAgICAgenpbel0gKz0gKHJlYWRCaXQoKSA8PCBzdWNjZXNzaXZlKSAqIGRpcmVjdGlvbjsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICByLS07CiAgICAgICAgICAgICAgaWYgKHIgPT09IDApIHsKICAgICAgICAgICAgICAgIHN1Y2Nlc3NpdmVBQ1N0YXRlID0gc3VjY2Vzc2l2ZUFDU3RhdGUgPT09IDIgPyAzIDogMDsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICBjYXNlIDM6IC8vIHNldCB2YWx1ZSBmb3IgYSB6ZXJvIGl0ZW0KICAgICAgICAgICAgaWYgKHp6W3pdKSB7CiAgICAgICAgICAgICAgenpbel0gKz0gKHJlYWRCaXQoKSA8PCBzdWNjZXNzaXZlKSAqIGRpcmVjdGlvbjsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICB6elt6XSA9IHN1Y2Nlc3NpdmVBQ05leHRWYWx1ZSA8PCBzdWNjZXNzaXZlOwogICAgICAgICAgICAgIHN1Y2Nlc3NpdmVBQ1N0YXRlID0gMDsKICAgICAgICAgICAgfQogICAgICAgICAgICBicmVhazsKICAgICAgICAgIGNhc2UgNDogLy8gZW9iCiAgICAgICAgICAgIGlmICh6elt6XSkgewogICAgICAgICAgICAgIHp6W3pdICs9IChyZWFkQml0KCkgPDwgc3VjY2Vzc2l2ZSkgKiBkaXJlY3Rpb247CiAgICAgICAgICAgIH0KICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfQogICAgICAgIGsrKzsKICAgICAgfQogICAgICBpZiAoc3VjY2Vzc2l2ZUFDU3RhdGUgPT09IDQpIHsKICAgICAgICBlb2JydW4tLTsKICAgICAgICBpZiAoZW9icnVuID09PSAwKSB7CiAgICAgICAgICBzdWNjZXNzaXZlQUNTdGF0ZSA9IDA7CiAgICAgICAgfQogICAgICB9CiAgICB9CiAgICBmdW5jdGlvbiBkZWNvZGVNY3U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2UgewogICAgICAgIGRlY29kZUZuID0gc3VjY2Vzc2l2ZVByZXYgPT09IDAgPyBkZWNvZGVBQ0ZpcnN0IDogZGVjb2RlQUNTdWNjZXNzaXZlOwogICAgICB9CiAgICB9IGVsc2UgewogICAgICBkZWNvZGVGbiA9IGRlY29kZUJhc2VsaW5lOwogICAgfQoKICAgIGxldCBtY3UgPSAwOwogICAgbGV0IG1hcmtlcjsKICAgIGxldCBtY3VFeHBlY3RlZDsKICAgIGlmIChjb21wb25lbnRzTGVuZ3RoID09PSAxKSB7CiAgICAgIG1jdUV4cGVjdGVkID0gY29tcG9uZW50c1swXS5ibG9ja3NQZXJMaW5lICogY29tcG9uZW50c1swXS5ibG9ja3NQZXJDb2x1bW47CiAgICB9IGVsc2UgewogICAgICBtY3VFeHBlY3RlZCA9IG1jdXNQZXJMaW5lICogZnJhbWUubWN1c1BlckNvbHVtbjsKICAgIH0KCiAgICBjb25zdCB1c2VkUmVzZXRJbnRlcnZhbCA9IHJlc2V0SW50ZXJ2YWwgfHwgbWN1RXhwZWN0ZWQ7CgogICAgd2hpbGUgKG1jdSA8IG1jdUV4cGVjdGVkKSB7CiAgICAgIC8vIHJlc2V0IGludGVydmFsIHN0dWZmCiAgICAgIGZvciAoaSA9IDA7IGkgPCBjb21wb25lbnRzTGVuZ3RoOyBpKyspIHsKICAgICAgICBjb21wb25lbnRzW2ldLnByZWQgPSAwOwogICAgICB9CiAgICAgIGVvYnJ1biA9IDA7CgogICAgICBpZiAoY29tcG9uZW50c0xlbmd0aCA9PT0gMSkgewogICAgICAgIGNvbXBvbmVudCA9IGNvbXBvbmVudHNbMF07CiAgICAgICAgZm9yIChuID0gMDsgbiA8IHVzZWRSZXNldEludGVydmFsOyBuKyspIHsKICAgICAgICAgIGRlY29kZUJsb2NrKGNvbXBvbmVudCwgZGVjb2RlRm4sIG1jdSk7CiAgICAgICAgICBtY3UrKzsKICAgICAgICB9CiAgICAgIH0gZWxzZSB7CiAgICAgICAgZm9yIChuID0gMDsgbiA8IHVzZWRSZXNldEludGVydmFsOyBuKyspIHsKICAgICAgICAgIGZvciAoaSA9IDA7IGkgPCBjb21wb25lbnRzTGVuZ3RoOyBpKyspIHsKICAgICAgICAgICAgY29tcG9uZW50ID0gY29tcG9uZW50c1tpXTsKICAgICAgICAgICAgY29uc3QgeyBoLCB2IH0gPSBjb21wb25lbnQ7CiAgICAgICAgICAgIGZvciAoaiA9IDA7IGogPCB2OyBqKyspIHsKICAgICAgICAgICAgICBmb3IgKGsgPSAwOyBrIDwgaDsgaysrKSB7CiAgICAgICAgICAgICAgICBkZWNvZGVNY3UoY29tcG9uZW50LCBkZWNvZGVGbiwgbWN1LCBqLCBrKTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIG1jdSsrOwoKICAgICAgICAgIC8vIElmIHdlJ3ZlIHJlYWNoZWQgb3VyIGV4cGVjdGVkIE1DVSdzLCBzdG9wIGRlY29kaW5nCiAgICAgICAgICBpZiAobWN1ID09PSBtY3VFeHBlY3RlZCkgewogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KCiAgICAgIC8vIGZpbmQgbWFya2VyCiAgICAgIGJpdHNDb3VudCA9IDA7CiAgICAgIG1hcmtlciA9IChkYXRhW29mZnNldF0gPDwgOCkgfCBkYXRhW29mZnNldCArIDFdOwogICAgICBpZiAobWFya2VyIDwgMHhGRjAwKSB7CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdtYXJrZXIgd2FzIG5vdCBmb3VuZCcpOwogICAgICB9CgogICAgICBpZiAobWFya2VyID49IDB4RkZEMCAmJiBtYXJrZXIgPD0gMHhGRkQ3KSB7IC8vIFJTVHgKICAgICAgICBvZmZzZXQgKz0gMjsKICAgICAgfSBlbHNlIHsKICAgICAgICBicmVhazsKICAgICAgfQogICAgfQoKICAgIHJldHVybiBvZmZzZXQgLSBzdGFydE9mZnNldDsKICB9CgogIGZ1bmN0aW9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BpKyspIHsKICAgICAgICBwW2ldID0genpbaV0gKiBxdFtpXTsKICAgICAgfQoKICAgICAgLy8gaW52ZXJzZSBEQ1Qgb24gcm93cwogICAgICBmb3IgKGkgPSAwOyBpIDwgODsgKytpKSB7CiAgICAgICAgY29uc3Qgcm93ID0gOCAqIGk7CgogICAgICAgIC8vIGNoZWNrIGZvciBhbGwtemVybyBBQyBjb2VmZmljaWVudHMKICAgICAgICBpZiAocFsxICsgcm93XSA9PT0gMCAmJiBwWzIgKyByb3ddID09PSAwICYmIHBbMyArIHJvd10gPT09IDAKICAgICAgICAgICYmIHBbNCArIHJvd10gPT09IDAgJiYgcFs1ICsgcm93XSA9PT0gMCAmJiBwWzYgKyByb3ddID09PSAwCiAgICAgICAgICAmJiBwWzcgKyByb3ddID09PSAwKSB7CiAgICAgICAgICB0ID0gKChkY3RTcXJ0MiAqIHBbMCArIHJvd10pICsgNTEyKSA+PiAxMDsKICAgICAgICAgIHBbMCArIHJvd10gPSB0OwogICAgICAgICAgcFsxICsgcm93XSA9IHQ7CiAgICAgICAgICBwWzIgKyByb3ddID0gdDsKICAgICAgICAgIHBbMyArIHJvd10gPSB0OwogICAgICAgICAgcFs0ICsgcm93XSA9IHQ7CiAgICAgICAgICBwWzUgKyByb3ddID0gdDsKICAgICAgICAgIHBbNiArIHJvd10gPSB0OwogICAgICAgICAgcFs3ICsgcm93XSA9IHQ7CiAgICAgICAgICBjb250aW51ZTsgLy8gZXNsaW50LWRpc2FibGUtbGluZSBuby1jb250aW51ZQogICAgICAgIH0KCiAgICAgICAgLy8gc3RhZ2UgNAogICAgICAgIHYwID0gKChkY3RTcXJ0MiAqIHBbMCArIHJvd10pICsgMTI4KSA+PiA4OwogICAgICAgIHYxID0gKChkY3RTcXJ0MiAqIHBbNCArIHJvd10pICsgMTI4KSA+PiA4OwogICAgICAgIHYyID0gcFsyICsgcm93XTsKICAgICAgICB2MyA9IHBbNiArIHJvd107CiAgICAgICAgdjQgPSAoKGRjdFNxcnQxZDIgKiAocFsxICsgcm93XSAtIHBbNyArIHJvd10pKSArIDEyOCkgPj4gODsKICAgICAgICB2NyA9ICgoZGN0U3FydDFkMiAqIChwWzEgKyByb3ddICsgcFs3ICsgcm93XSkpICsgMTI4KSA+PiA4OwogICAgICAgIHY1ID0gcFszICsgcm93XSA8PCA0OwogICAgICAgIHY2ID0gcFs1ICsgcm93XSA8PCA0OwoKICAgICAgICAvLyBzdGFnZSAzCiAgICAgICAgdCA9ICh2MCAtIHYxICsgMSkgPj4gMTsKICAgICAgICB2MCA9ICh2MCArIHYxICsgMSkgPj4gMTsKICAgICAgICB2MSA9IHQ7CiAgICAgICAgdCA9ICgodjIgKiBkY3RTaW42KSArICh2MyAqIGRjdENvczYpICsgMTI4KSA+PiA4OwogICAgICAgIHYyID0gKCh2MiAqIGRjdENvczYpIC0gKHYzICogZGN0U2luNikgKyAxMjgpID4+IDg7CiAgICAgICAgdjMgPSB0OwogICAgICAgIHQgPSAodjQgLSB2NiArIDEpID4+IDE7CiAgICAgICAgdjQgPSAodjQgKyB2NiArIDEpID4+IDE7CiAgICAgICAgdjYgPSB0OwogICAgICAgIHQgPSAodjcgKyB2NSArIDEpID4+IDE7CiAgICAgICAgdjUgPSAodjcgLSB2NSArIDEpID4+IDE7CiAgICAgICAgdjcgPSB0OwoKICAgICAgICAvLyBzdGFnZSAyCiAgICAgICAgdCA9ICh2MCAtIHYzICsgMSkgPj4gMTsKICAgICAgICB2MCA9ICh2MCArIHYzICsgMSkgPj4gMTsKICAgICAgICB2MyA9IHQ7CiAgICAgICAgdCA9ICh2MSAtIHYyICsgMSkgPj4gMTsKICAgICAgICB2MSA9ICh2MSArIHYyICsgMSkgPj4gMTsKICAgICAgICB2MiA9IHQ7CiAgICAgICAgdCA9ICgodjQgKiBkY3RTaW4zKSArICh2NyAqIGRjdENvczMpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjQgPSAoKHY0ICogZGN0Q29zMykgLSAodjcgKiBkY3RTaW4zKSArIDIwNDgpID4+IDEyOwogICAgICAgIHY3ID0gdDsKICAgICAgICB0ID0gKCh2NSAqIGRjdFNpbjEpICsgKHY2ICogZGN0Q29zMSkgKyAyMDQ4KSA+PiAxMjsKICAgICAgICB2NSA9ICgodjUgKiBkY3RDb3MxKSAtICh2NiAqIGRjdFNpbjEpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjYgPSB0OwoKICAgICAgICAvLyBzdGFnZSAxCiAgICAgICAgcFswICsgcm93XSA9IHYwICsgdjc7CiAgICAgICAgcFs3ICsgcm93XSA9IHYwIC0gdjc7CiAgICAgICAgcFsxICsgcm93XSA9IHYxICsgdjY7CiAgICAgICAgcFs2ICsgcm93XSA9IHYxIC0gdjY7CiAgICAgICAgcFsyICsgcm93XSA9IHYyICsgdjU7CiAgICAgICAgcFs1ICsgcm93XSA9IHYyIC0gdjU7CiAgICAgICAgcFszICsgcm93XSA9IHYzICsgdjQ7CiAgICAgICAgcFs0ICsgcm93XSA9IHYzIC0gdjQ7CiAgICAgIH0KCiAgICAgIC8vIGludmVyc2UgRENUIG9uIGNvbHVtbnMKICAgICAgZm9yIChpID0gMDsgaSA8IDg7ICsraSkgewogICAgICAgIGNvbnN0IGNvbCA9IGk7CgogICAgICAgIC8vIGNoZWNrIGZvciBhbGwtemVybyBBQyBjb2VmZmljaWVudHMKICAgICAgICBpZiAocFsoMSAqIDgpICsgY29sXSA9PT0gMCAmJiBwWygyICogOCkgKyBjb2xdID09PSAwICYmIHBbKDMgKiA4KSArIGNvbF0gPT09IDAKICAgICAgICAgICYmIHBbKDQgKiA4KSArIGNvbF0gPT09IDAgJiYgcFsoNSAqIDgpICsgY29sXSA9PT0gMCAmJiBwWyg2ICogOCkgKyBjb2xdID09PSAwCiAgICAgICAgICAmJiBwWyg3ICogOCkgKyBjb2xdID09PSAwKSB7CiAgICAgICAgICB0ID0gKChkY3RTcXJ0MiAqIGRhdGFJbltpICsgMF0pICsgODE5MikgPj4gMTQ7CiAgICAgICAgICBwWygwICogOCkgKyBjb2xdID0gdDsKICAgICAgICAgIHBbKDEgKiA4KSArIGNvbF0gPSB0OwogICAgICAgICAgcFsoMiAqIDgpICsgY29sXSA9IHQ7CiAgICAgICAgICBwWygzICogOCkgKyBjb2xdID0gdDsKICAgICAgICAgIHBbKDQgKiA4KSArIGNvbF0gPSB0OwogICAgICAgICAgcFsoNSAqIDgpICsgY29sXSA9IHQ7CiAgICAgICAgICBwWyg2ICogOCkgKyBjb2xdID0gdDsKICAgICAgICAgIHBbKDcgKiA4KSArIGNvbF0gPSB0OwogICAgICAgICAgY29udGludWU7IC8vIGVzbGludC1kaXNhYmxlLWxpbmUgbm8tY29udGludWUKICAgICAgICB9CgogICAgICAgIC8vIHN0YWdlIDQKICAgICAgICB2MCA9ICgoZGN0U3FydDIgKiBwWygwICogOCkgKyBjb2xdKSArIDIwNDgpID4+IDEyOwogICAgICAgIHYxID0gKChkY3RTcXJ0MiAqIHBbKDQgKiA4KSArIGNvbF0pICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjIgPSBwWygyICogOCkgKyBjb2xdOwogICAgICAgIHYzID0gcFsoNiAqIDgpICsgY29sXTsKICAgICAgICB2NCA9ICgoZGN0U3FydDFkMiAqIChwWygxICogOCkgKyBjb2xdIC0gcFsoNyAqIDgpICsgY29sXSkpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjcgPSAoKGRjdFNxcnQxZDIgKiAocFsoMSAqIDgpICsgY29sXSArIHBbKDcgKiA4KSArIGNvbF0pKSArIDIwNDgpID4+IDEyOwogICAgICAgIHY1ID0gcFsoMyAqIDgpICsgY29sXTsKICAgICAgICB2NiA9IHBbKDUgKiA4KSArIGNvbF07CgogICAgICAgIC8vIHN0YWdlIDMKICAgICAgICB0ID0gKHYwIC0gdjEgKyAxKSA+PiAxOwogICAgICAgIHYwID0gKHYwICsgdjEgKyAxKSA+PiAxOwogICAgICAgIHYxID0gdDsKICAgICAgICB0ID0gKCh2MiAqIGRjdFNpbjYpICsgKHYzICogZGN0Q29zNikgKyAyMDQ4KSA+PiAxMjsKICAgICAgICB2MiA9ICgodjIgKiBkY3RDb3M2KSAtICh2MyAqIGRjdFNpbjYpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjMgPSB0OwogICAgICAgIHQgPSAodjQgLSB2NiArIDEpID4+IDE7CiAgICAgICAgdjQgPSAodjQgKyB2NiArIDEpID4+IDE7CiAgICAgICAgdjYgPSB0OwogICAgICAgIHQgPSAodjcgKyB2NSArIDEpID4+IDE7CiAgICAgICAgdjUgPSAodjcgLSB2NSArIDEpID4+IDE7CiAgICAgICAgdjcgPSB0OwoKICAgICAgICAvLyBzdGFnZSAyCiAgICAgICAgdCA9ICh2MCAtIHYzICsgMSkgPj4gMTsKICAgICAgICB2MCA9ICh2MCArIHYzICsgMSkgPj4gMTsKICAgICAgICB2MyA9IHQ7CiAgICAgICAgdCA9ICh2MSAtIHYyICsgMSkgPj4gMTsKICAgICAgICB2MSA9ICh2MSArIHYyICsgMSkgPj4gMTsKICAgICAgICB2MiA9IHQ7CiAgICAgICAgdCA9ICgodjQgKiBkY3RTaW4zKSArICh2NyAqIGRjdENvczMpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjQgPSAoKHY0ICogZGN0Q29zMykgLSAodjcgKiBkY3RTaW4zKSArIDIwNDgpID4+IDEyOwogICAgICAgIHY3ID0gdDsKICAgICAgICB0ID0gKCh2NSAqIGRjdFNpbjEpICsgKHY2ICogZGN0Q29zMSkgKyAyMDQ4KSA+PiAxMjsKICAgICAgICB2NSA9ICgodjUgKiBkY3RDb3MxKSAtICh2NiAqIGRjdFNpbjEpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjYgPSB0OwoKICAgICAgICAvLyBzdGFnZSAxCiAgICAgICAgcFsoMCAqIDgpICsgY29sXSA9IHYwICsgdjc7CiAgICAgICAgcFsoNyAqIDgpICsgY29sXSA9IHYwIC0gdjc7CiAgICAgICAgcFsoMSAqIDgpICsgY29sXSA9IHYxICsgdjY7CiA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CiAgICAgICAgbGV0IG9mZnNldCA9IDA7CiAgICAgICAgY29uc3Qgc2FtcGxlID0gYmxvY2tDb2wgPDwgMzsKICAgICAgICBmb3IgKGxldCBqID0gMDsgaiA8IDg7IGorKykgewogICAgICAgICAgY29uc3QgbGluZSA9IGxpbmVzW3NjYW5MaW5lICsgal07CiAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IDg7IGkrKykgewogICAgICAgICAgICBsaW5lW3NhbXBsZSArIGldID0gcltvZmZzZXQrK107CiAgICAgICAgICB9CiAgICAgICAgfQogICAgICB9CiAgICB9CiAgICByZXR1cm4gbGluZXM7CiAgfQoKICBjbGFzcyBKcGVnU3RyZWFtUmVhZGVyIHsKICAgIGNvbnN0cnVjdG9yKCkgewogICAgICB0aGlzLmpmaWYgPSBudWxsOwogICAgICB0aGlzLmFkb2JlID0gbnVsbDsKCiAgICAgIHRoaXMucXVhbnRpemF0aW9uVGFibGVzID0gW107CiAgICAgIHRoaXMuaHVmZm1hblRhYmxlc0FDID0gW107CiAgICAgIHRoaXMuaHVmZm1hblRhYmxlc0RDID0gW107CiAgICAgIHRoaXMucmVzZXRGcmFtZXMoKTsKICAgIH0KCiAgICByZXNldEZyYW1lcygpIHsKICAgICAgdGhpcy5mcmFtZXMgPSBbXTsKICAgIH0KCiAgICBwYXJzZShkYXRhKSB7CiAgICAgIGxldCBvZmZzZXQgPSAwOwogICAgICAvLyBjb25zdCB7IGxlbmd0aCB9ID0gZGF0YTsKICAgICAgZnVuY3Rpb24gcmVhZFVpbnQxNigpIHsKICAgICAgICBjb25zdCB2YWx1ZSA9IChkYXRhW29mZnNldF0gPDwgOCkgfCBkYXRhW29mZnNldCArIDFdOwogICAgICAgIG9mZnNldCArPSAyOwogICAgICAgIHJldHVybiB2YWx1ZTsKICAgICAgfQogICAgICBmdW5jdGlvbiByZWFkRGF0YUJsb2NrKCkgewogICAgICAgIGNvbnN0IGxlbmd0aCA9IHJlYWRVaW50MTYoKTsKICAgICAgICBjb25zdCBhcnJheSA9IGRhdGEuc3ViYXJyYXkob2Zmc2V0LCBvZmZzZXQgKyBsZW5ndGggLSAyKTsKICAgICAgICBvZmZzZXQgKz0gYXJyYXkubGVuZ3RoOwogICAgICAgIHJldHVybiBhcnJheTsKICAgICAgfQogICAgICBmdW5jdGlvbiBwcmVwYXJlQ29tcG9uZW50cyhmcmFtZSkgewogICAgICAgIGxldCBtYXhIID0gMDsKICAgICAgICBsZXQgbWF4ViA9IDA7CiAgICAgICAgbGV0IGNvbXBvbmVudDsKICAgICAgICBsZXQgY29tcG9uZW50SWQ7CiAgICAgICAgZm9yIChjb21wb25lbnRJZCBpbiBmcmFtZS5jb21wb25lbnRzKSB7CiAgICAgICAgICBpZiAoZnJhbWUuY29tcG9uZW50cy5oYXNPd25Qcm9wZXJ0eShjb21wb25lbnRJZCkpIHsKICAgICAgICAgICAgY29tcG9uZW50ID0gZnJhbWUuY29tcG9uZW50c1tjb21wb25lbnRJZF07CiAgICAgICAgICAgIGlmIChtYXhIIDwgY29tcG9uZW50LmgpIHsKICAgICAgICAgICAgICBtYXhIID0gY29tcG9uZW50Lmg7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKG1heFYgPCBjb21wb25lbnQudikgewogICAgICAgICAgICAgIG1heFYgPSBjb21wb25lbnQudjsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBjb25zdCBtY3VzUGVyTGluZSA9IE1hdGguY2VpbChmcmFtZS5zYW1wbGVzUGVyTGluZSAvIDggLyBtYXhIKTsKICAgICAgICBjb25zdCBtY3VzUGVyQ29sdW1uID0gTWF0aC5jZWlsKGZyYW1lLnNjYW5MaW5lcyAvIDggLyBtYXhWKTsKICAgICAgICBmb3IgKGNvbXBvbmVudElkIGluIGZyYW1lLmNvbXBvbmVudHMpIHsKICAgICAgICAgIGlmIChmcmFtZS5jb21wb25lbnRzLmhhc093blByb3BlcnR5KGNvbXBvbmVudElkKSkgewogICAgICAgICAgICBjb21wb25lbnQgPSBmcmFtZS5jb21wb25lbnRzW2NvbXBvbmVudElkXTsKICAgICAgICAgICAgY29uc3QgYmxvY2tzUGVyTGluZSA9IE1hdGguY2VpbChNYXRoLmNlaWwoZnJhbWUuc2FtcGxlc1BlckxpbmUgLyA4KSAqIGNvbXBvbmVudC5oIC8gbWF4SCk7CiAgICAgICAgICAgIGNvbnN0IGJsb2Nrc1BlckNvbHVtbiA9IE1hdGguY2VpbChNYXRoLmNlaWwoZnJhbWUuc2NhbkxpbmVzIC8gOCkgKiBjb21wb25lbnQudiAvIG1heFYpOwogICAgICAgICAgICBjb25zdCBibG9ja3NQZXJMaW5lRm9yTWN1ID0gbWN1c1BlckxpbmUgKiBjb21wb25lbnQuaDsKICAgICAgICAgICAgY29uc3QgYmxvY2tzUGVyQ29sdW1uRm9yTWN1ID0gbWN1c1BlckNvbHVtbiAqIGNvbXBvbmVudC52OwogICAgICAgICAgICBjb25zdCBibG9ja3MgPSBbXTsKICAgICAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBibG9ja3NQZXJDb2x1bW5Gb3JNY3U7IGkrKykgewogICAgICAgICAgICAgIGNvbnN0IHJvdyA9IFtdOwogICAgICAgICAgICAgIGZvciAobGV0IGogPSAwOyBqIDwgYmxvY2tzUGVyTGluZUZvck1jdTsgaisrKSB7CiAgICAgICAgICAgICAgICByb3cucHVzaChuZXcgSW50MzJBcnJheSg2NCkpOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBibG9ja3MucHVzaChyb3cpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvbXBvbmVudC5ibG9ja3NQZXJMaW5lID0gYmxvY2tzUGVyTGluZTsKICAgICAgICAgICAgY29tcG9uZW50LmJsb2Nrc1BlckNvbHVtbiA9IGJsb2Nrc1BlckNvbHVtbjsKICAgICAgICAgICAgY29tcG9uZW50LmJsb2NrcyA9IGJsb2NrczsKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgICAgZnJhbWUubWF4SCA9IG1heEg7CiAgICAgICAgZnJhbWUubWF4ViA9IG1heFY7CiAgICAgICAgZnJhbWUubWN1c1BlckxpbmUgPSBtY3VzUGVyTGluZTsKICAgICAgICBmcmFtZS5tY3VzUGVyQ29sdW1uID0gbWN1c1BlckNvbHVtbjsKICAgICAgfQoKICAgICAgbGV0IGZpbGVNYXJrZXIgPSByZWFkVWludDE2KCk7CiAgICAgIGlmIChmaWxlTWFya2VyICE9PSAweEZGRDgpIHsgLy8gU09JIChTdGFydCBvZiBJbWFnZSkKICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ1NPSSBub3QgZm91bmQnKTsKICAgICAgfQoKICAgICAgZmlsZU1hcmtlciA9IHJlYWRVaW50MTYoKTsKICAgICAgd2hpbGUgKGZpbGVNYXJrZXIgIT09IDB4RkZEOSkgeyAvLyBFT0kgKEVuZCBvZiBpbWFnZSkKICAgICAgICBzd2l0Y2ggKGZpbGVNYXJrZXIpIHsKICAgICAgICAgIGNhc2UgMHhGRjAwOiBicmVhazsKICAgICAgICAgIGNhc2UgMHhGRkUwOiAvLyBBUFAwIChBcHBsaWNhdGlvbiBTcGVjaWZpYykKICAgICAgICAgIGNhc2UgMHhGRkUxOiAvLyBBUFAxCiAgICAgICAgICBjYXNlIDB4RkZFMjogLy8gQVBQMgogICAgICAgICAgY2FzZSAweEZGRTM6IC8vIEFQUDMKICAgICAgICAgIGNhc2UgMHhGRkU0OiAvLyBBUFA0CiAgICAgICAgICBjYXNlIDB4RkZFNTogLy8gQVBQNQogICAgICAgICAgY2FzZSAweEZGRTY6IC8vIEFQUDYKICAgICAgICAgIGNhc2UgMHhGRkU3OiAvLyBBUFA3CiAgICAgICAgICBjYXNlIDB4RkZFODogLy8gQVBQOAogICAgICAgICAgY2FzZSAweEZGRTk6IC8vIEFQUDkKICAgICAgICAgIGNhc2UgMHhGRkVBOiAvLyBBUFAxMAogICAgICAgICAgY2FzZSAweEZGRUI6IC8vIEFQUDExCiAgICAgICAgICBjYXNlIDB4RkZFQzogLy8gQVBQMTIKICAgICAgICAgIGNhc2UgMHhGRkVEOiAvLyBBUFAxMwogICAgICAgICAgY2FzZSAweEZGRUU6IC8vIEFQUDE0CiAgICAgICAgICBjYXNlIDB4RkZFRjogLy8gQVBQMTUKICAgICAgICAgIGNhc2UgMHhGRkZFOiB7IC8vIENPTSAoQ29tbWVudCkKICAgICAgICAgICAgY29uc3QgYXBwRGF0YSA9IHJlYWREYXRhQmxvY2soKTsKCiAgICAgICAgICAgIGlmIChmaWxlTWFya2VyID09PSAweEZGRTApIHsKICAgICAgICAgICAgICBpZiAoYXBwRGF0YVswXSA9PT0gMHg0QSAmJiBhcHBEYXRhWzFdID09PSAweDQ2ICYmIGFwcERhdGFbMl0gPT09IDB4NDkKICAgICAgICAgICAgICAgICYmIGFwcERhdGFbM10gPT09IDB4NDYgJiYgYXBwRGF0YVs0XSA9PT0gMCkgeyAvLyAnSkZJRlx4MDAnCiAgICAgICAgICAgICAgICB0aGlzLmpmaWYgPSB7CiAgICAgICAgICAgICAgICAgIHZlcnNpb246IHsgbWFqb3I6IGFwcERhdGFbNV0sIG1pbm9yOiBhcHBEYXRhWzZdIH0sCiAgICAgICAgICAgICAgICAgIGRlbnNpdHlVbml0czogYXBwRGF0YVs3XSwKICAgICAgICAgICAgICAgICAgeERlbnNpdHk6IChhcHBEYXRhWzhdIDw8IDgpIHwgYXBwRGF0YVs5XSwKICAgICAgICAgICAgICAgICAgeURlbnNpdHk6IChhcHBEYXRhWzEwXSA8PCA4KSB8IGFwcERhdGFbMTFdLAogICAgICAgICAgICAgICAgICB0aHVtYldpZHRoOiBhcHBEYXRhWzEyXSwKICAgICAgICAgICAgICAgICAgdGh1bWJIZWlnaHQ6IGFwcERhdGFbMTNdLAogICAgICAgICAgICAgICAgICB0aHVtYkRhdGE6IGFwcERhdGEuc3ViYXJyYXkoMTQsIDE0ICsgKDMgKiBhcHBEYXRhWzEyXSAqIGFwcERhdGFbMTNdKSksCiAgICAgICAgICAgICAgICB9OwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICAvLyBUT0RPIEFQUDEgLSBFeGlmCiAgICAgICAgICAgIGlmIChmaWxlTWFya2VyID09PSAweEZGRUUpIHsKICAgICAgICAgICAgICBpZiAoYXBwRGF0YVswXSA9PT0gMHg0MSAmJiBhcHBEYXRhWzFdID09PSAweDY0ICYmIGFwcERhdGFbMl0gPT09IDB4NkYKICAgICAgICAgICAgICAgICYmIGFwcERhdGFbM10gPT09IDB4NjIgJiYgYXBwRGF0YVs0XSA9PT0gMHg2NSAmJiBhcHBEYXRhWzVdID09PSAwKSB7IC8vICdBZG9iZVx4MDAnCiAgICAgICAgICAgICAgICB0aGlzLmFkb2JlID0gewogICAgICAgICAgICAgICAgICB2ZXJzaW9uOiBhcHBEYXRhWzZdLAogICAgICAgICAgICAgICAgICBmbGFnczA6IChhcHBEYXRhWzddIDw8IDgpIHwgYXBwRGF0YVs4XSwKICAgICAgICAgICAgICAgICAgZmxhZ3MxOiAoYXBwRGF0YVs5XSA8PCA4KSB8IGFwcERhdGFbMTBdLAogICAgICAgICAgICAgICAgICB0cmFuc2Zvcm1Db2RlOiBhcHBEYXRhWzExXSwKICAgICAgICAgICAgICAgIH07CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQoKICAgICAgICAgIGNhc2UgMHhGRkRCOiB7IC8vIERRVCAoRGVmaW5lIFF1YW50aXphdGlvbiBUYWJsZXMpCiAgICAgICAgICAgIGNvbnN0IHF1YW50aXphdGlvblRhYmxlc0xlbmd0aCA9IHJlYWRVaW50MTYoKTsKICAgICAgICAgICAgY29uc3QgcXVhbnRpemF0aW9uVGFibGVzRW5kID0gcXVhbnRpemF0aW9uVGFibGVzTGVuZ3RoICsgb2Zmc2V0IC0gMjsKICAgICAgICAgICAgd2hpbGUgKG9mZnNldCA8IHF1YW50aXphdGlvblRhYmxlc0VuZCkgewogICAgICAgICAgICAgIGNvbnN0IHF1YW50aXphdGlvblRhYmxlU3BlYyA9IGRhdGFbb2Zmc2V0KytdOwogICAgICAgICAgICAgIGNvbnN0IHRhYmxlRGF0YSA9IG5ldyBJbnQzMkFycmF5KDY0KTsKICAgICAgICAgICAgICBpZiAoKHF1YW50aXphdGlvblRhYmxlU3BlYyA+PiA0KSA9PT0gMCkgeyAvLyA4IGJpdCB2YWx1ZXMKICAgICAgICAgICAgICAgIGZvciAobGV0IGogPSAwOyBqIDwgNjQ7IGorKykgewogICAgICAgICAgICAgICAgICBjb25zdCB6ID0gZGN0WmlnWmFnW2pdOwogICAgICAgICAgICAgICAgICB0YWJsZURhdGFbel0gPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9IGVsc2UgaWYgKChxdWFudGl6YXRpb25UYWJsZVNwZWMgPj4gNCkgPT09IDEpIHsgLy8gMTYgYml0CiAgICAgICAgICAgICAgICBmb3IgKGxldCBqID0gMDsgaiA8IDY0OyBqKyspIHsKICAgICAgICAgICAgICAgICAgY29uc3QgeiA9IGRjdFppZ1phZ1tqXTsKICAgICAgICAgICAgICAgICAgdGFibGVEYXRhW3pdID0gcmVhZFVpbnQxNigpOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0RRVDogaW52YWxpZCB0YWJsZSBzcGVjJyk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIHRoaXMucXVhbnRpemF0aW9uVGFibGVzW3F1YW50aXphdGlvblRhYmxlU3BlYyAmIDE1XSA9IHRhYmxlRGF0YTsKICAgICAgICAgICAgfQogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KCiAgICAgICAgICBjYXNlIDB4RkZDMDogLy8gU09GMCAoU3RhcnQgb2YgRnJhbWUsIEJhc2VsaW5lIERDVCkKICAgICAgICAgIGNhc2UgMHhGRkMxOiAvLyBTT0YxIChTdGFydCBvZiBGcmFtZSwgRXh0ZW5kZWQgRENUKQogICAgICAgICAgY2FzZSAweEZGQzI6IHsgLy8gU09GMiAoU3RhcnQgb2YgRnJhbWUsIFByb2dyZXNzaXZlIERDVCkKICAgICAgICAgICAgcmVhZFVpbnQxNigpOyAvLyBza2lwIGRhdGEgbGVuZ3RoCiAgICAgICAgICAgIGNvbnN0IGZyYW1lID0gewogICAgICAgICAgICAgIGV4dGVuZGVkOiAoZmlsZU1hcmtlciA9PT0gMHhGRkMxKSwKICAgICAgICAgICAgICBwcm9ncmVzc2l2ZTogKGZpbGVNYXJrZXIgPT09IDB4RkZDMiksCiAgICAgICAgICAgICAgcHJlY2lzaW9uOiBkYXRhW29mZnNldCsrXSwKICAgICAgICAgICAgICBzY2FuTGluZXM6IHJlYWRVaW50MTYoKSwKICAgICAgICAgICAgICBzYW1wbGVzUGVyTGluZTogcmVhZFVpbnQxNigpLAogICAgICAgICAgICAgIGNvbXBvbmVudHM6IHt9LAogICAgICAgICAgICAgIGNvbXBvbmVudHNPcmRlcjogW10sCiAgICAgICAgICAgIH07CgogICAgICAgICAgICBjb25zdCBjb21wb25lbnRzQ291bnQgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgbGV0IGNvbXBvbmVudElkOwogICAgICAgICAgICAvLyBsZXQgbWF4SCA9IDA7CiAgICAgICAgICAgIC8vIGxldCBtYXhWID0gMDsKICAgICAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBjb21wb25lbnRzQ291bnQ7IGkrKykgewogICAgICAgICAgICAgIGNvbXBvbmVudElkID0gZGF0YVtvZmZzZXRdOwogICAgICAgICAgICAgIGNvbnN0IGggPSBkYXRhW29mZnNldCArIDFdID4+IDQ7CiAgICAgICAgICAgICAgY29uc3QgdiA9IGRhdGFbb2Zmc2V0ICsgMV0gJiAxNTsKICAgICAgICAgICAgICBjb25zdCBxSWQgPSBkYXRhW29mZnNldCArIDJdOwogICAgICAgICAgICAgIGZyYW1lLmNvbXBvbmVudHNPcmRlci5wdXNoKGNvbXBvbmVudElkKTsKICAgICAgICAgICAgICBmcmFtZS5jb21wb25lbnRzW2NvbXBvbmVudElkXSA9IHsKICAgICAgICAgICAgICAgIGgsCiAgICAgICAgICAgICAgICB2LAogICAgICAgICAgICAgICAgcXVhbnRpemF0aW9uSWR4OiBxSWQsCiAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICBvZmZzZXQgKz0gMzsKICAgICAgICAgICAgfQogICAgICAgICAgICBwcmVwYXJlQ29tcG9uZW50cyhmcmFtZSk7CiAgICAgICAgICAgIHRoaXMuZnJhbWVzLnB1c2goZnJhbWUpOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KCiAgICAgICAgICBjYXNlIDB4RkZDNDogeyAvLyBESFQgKERlZmluZSBIdWZmbWFuIFRhYmxlcykKICAgICAgICAgICAgY29uc3QgaHVmZm1hbkxlbmd0aCA9IHJlYWRVaW50MTYoKTsKICAgICAgICAgICAgZm9yIChsZXQgaSA9IDI7IGkgPCBodWZmbWFuTGVuZ3RoOykgewogICAgICAgICAgICAgIGNvbnN0IGh1ZmZtYW5UYWJsZVNwZWMgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgICBjb25zdCBjb2RlTGVuZ3RocyA9IG5ldyBVaW50OEFycmF5KDE2KTsKICAgICAgICAgICAgICBsZXQgY29kZUxlbmd0aFN1bSA9IDA7CiAgICAgICAgICAgICAgZm9yIChsZXQgaiA9IDA7IGogPCAxNjsgaisrLCBvZmZzZXQrKykgewogICAgICAgICAgICAgICAgY29kZUxlbmd0aHNbal0gPSBkYXRhW29mZnNldF07CiAgICAgICAgICAgICAgICBjb2RlTGVuZ3RoU3VtICs9IGNvZGVMZW5ndGhzW2pdOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBjb25zdCBodWZmbWFuVmFsdWVzID0gbmV3IFVpbnQ4QXJyYXkoY29kZUxlbmd0aFN1bSk7CiAgICAgICAgICAgICAgZm9yIChsZXQgaiA9IDA7IGogPCBjb2RlTGVuZ3RoU3VtOyBqKyssIG9mZnNldCsrKSB7CiAgICAgICAgICAgICAgICBodWZmbWFuVmFsdWVzW2pdID0gZGF0YVtvZmZzZXRdOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBpICs9IDE3ICsgY29kZUxlbmd0aFN1bTsKCiAgICAgICAgICAgICAgaWYgKChodWZmbWFuVGFibGVTcGVjID4+IDQpID09PSAwKSB7CiAgICAgICAgICAgICAgICB0aGlzLmh1ZmZtYW5UYWJsZXNEQ1todWZmbWFuVGFibGVTcGVjICYgMTVdID0gYnVpbGRIdWZmbWFuVGFibGUoCiAgICAgICAgICAgICAgICAgIGNvZGVMZW5ndGhzLCBodWZmbWFuVmFsdWVzLAogICAgICAgICAgICAgICAgKTsKICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgdGhpcy5odWZmbWFuVGFibGVzQUNbaHVmZm1hblRhYmxlU3BlYyAmIDE1XSA9IGJ1aWxkSHVmZm1hblRhYmxlKAogICAgICAgICAgICAgICAgICBjb2RlTGVuZ3RocywgaHVmZm1hblZhbHVlcywKICAgICAgICAgICAgICAgICk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQoKICAgICAgICAgIGNhc2UgMHhGRkREOiAvLyBEUkkgKERlZmluZSBSZXN0YXJ0IEludGVydmFsKQogICAgICAgICAgICByZWFkVWludDE2KCk7IC8vIHNraXAgZGF0YSBsZW5ndGgKICAgICAgICAgICAgdGhpcy5yZXNldEludGVydmFsID0gcmVhZFVpbnQxNigpOwogICAgICAgICAgICBicmVhazsKCiAgICAgICAgICBjYXNlIDB4RkZEQTogeyAvLyBTT1MgKFN0YXJ0IG9mIFNjYW4pCiAgICAgICAgICAgIHJlYWRVaW50MTYoKTsgLy8gc2tpcCBsZW5ndGgKICAgICAgICAgICAgY29uc3Qgc2VsZWN0b3JzQ291bnQgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgY29uc3QgY29tcG9uZW50cyA9IFtdOwogICAgICAgICAgICBjb25zdCBmcmFtZSA9IHRoaXMuZnJhbWVzWzBdOwogICAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IHNlbGVjdG9yc0NvdW50OyBpKyspIHsKICAgICAgICAgICAgICBjb25zdCBjb21wb25lbnQgPSBmcmFtZS5jb21wb25lbnRzW2RhdGFbb2Zmc2V0KytdXTsKICAgICAgICAgICAgICBjb25zdCB0YWJsZVNwZWMgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgICBjb21wb25lbnQuaHVmZm1hblRhYmxlREMgPSB0aGlzLmh1ZmZtYW5UYWJsZXNEQ1t0YWJsZVNwZWMgPj4gNF07CiAgICAgICAgICAgICAgY29tcG9uZW50Lmh1ZmZtYW5UYWJsZUFDID0gdGhpcy5odWZmbWFuVGFibGVzQUNbdGFibGVTcGVjICYgMTVdOwogICAgICAgICAgICAgIGNvbXBvbmVudHMucHVzaChjb21wb25lbnQpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvbnN0IHNwZWN0cmFsU3RhcnQgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgY29uc3Qgc3BlY3RyYWxFbmQgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgY29uc3Qgc3VjY2Vzc2l2ZUFwcHJveGltYXRpb24gPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgY29uc3QgcHJvY2Vzc2VkID0gZGVjb2RlU2NhbihkYXRhLCBvZmZzZXQsCiAgICAgICAgICAgICAgZnJhbWUsIGNvbXBvbmVudHMsIHRoaXMucmVzZXRJbnRlcnZhbCwKICAgICAgICAgICAgICBzcGVjdHJhbFN0YXJ0LCBzcGVjdHJhbEVuZCwKICAgICAgICAgICAgICBzdWNjZXNzaXZlQXBwcm94aW1hdGlvbiA+PiA0LCBzdWNjZXNzaXZlQXBwcm94aW1hdGlvbiAmIDE1KTsKICAgICAgICAgICAgb2Zmc2V0ICs9IHByb2Nlc3NlZDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CgogICAgICAgICAgY2FzZSAweEZGRkY6IC8vIEZpbGwgYnl0ZXMKICAgICAgICAgICAgaWYgKGRhdGFbb2Zmc2V0XSAhPT0gMHhGRikgeyAvLyBBdm9pZCBza2lwcGluZyBhIHZhbGlkIG1hcmtlci4KICAgICAgICAgICAgICBvZmZzZXQtLTsKICAgICAgICAgICAgfQogICAgICAgICAgICBicmVhazsKCiAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICBpZiAoZGF0YVtvZmZzZXQgLSAzXSA9PT0gMHhGRgogICAgICAgICAgICAgICYmIGRhdGFbb2Zmc2V0IC0gMl0gPj0gMHhDMCAmJiBkYXRhW29mZnNldCAtIDJdIDw9IDB4RkUpIHsKICAgICAgICAgICAgICAvLyBjb3VsZCBiZSBpbmNvcnJlY3QgZW5jb2RpbmcgLS0gbGFzdCAweEZGIGJ5dGUgb2YgdGhlIHByZXZpb3VzCiAgICAgICAgICAgICAgLy8gYmxvY2sgd2FzIGVhdGVuIGJ5IHRoZSBlbmNvZGVyCiAgICAgICAgICAgICAgb2Zmc2V0IC09IDM7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGB1bmtub3duIEpQRUcgbWFya2VyICR7ZmlsZU1hcmtlci50b1N0cmluZygxNil9YCk7CiAgICAgICAgfQogICAgICAgIGZpbGVNYXJrZXIgPSByZWFkVWludDE2KCk7CiAgICAgIH0KICAgIH0KCiAgICBnZXRSZXN1bHQoKSB7CiAgICAgIGNvbnN0IHsgZnJhbWVzIH0gPSB0aGlzOwogICAgICBpZiAodGhpcy5mcmFtZXMubGVuZ3RoID09PSAwKSB7CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdubyBmcmFtZXMgd2VyZSBkZWNvZGVkJyk7CiAgICAgIH0gZWxzZSBpZiAodGhpcy5mcmFtZXMubGVuZ3RoID4gMSkgewogICAgICAgIGNvbnNvbGUud2FybignbW9yZSB0aGFuIG9uZSBmcmFtZSBpcyBub3Qgc3VwcG9ydGVkJyk7CiAgICAgIH0KCiAgICAgIC8vIHNldCBlYWNoIGZyYW1lJ3MgY29tcG9uZW50cyBxdWFudGl6YXRpb24gdGFibGUKICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCB0aGlzLmZyYW1lcy5sZW5ndGg7IGkrKykgewogICAgICAgIGNvbnN0IGNwID0gdGhpcy5mcmFtZXNbaV0uY29tcG9uZW50czsKICAgICAgICBmb3IgKGNvbnN0IGogb2YgT2JqZWN0LmtleXMoY3ApKSB7CiAgICAgICAgICBjcFtqXS5xdWFudGl6YXRpb25UYWJsZSA9IHRoaXMucXVhbnRpemF0aW9uVGFibGVzW2NwW2pdLnF1YW50aXphdGlvbklkeF07CiAgICAgICAgICBkZWxldGUgY3Bbal0ucXVhbnRpemF0aW9uSWR4OwogICAgICAgIH0KICAgICAgfQoKICAgICAgY29uc3QgZnJhbWUgPSBmcmFtZXNbMF07CiAgICAgIGNvbnN0IHsgY29tcG9uZW50cywgY29tcG9uZW50c09yZGVyIH0gPSBmcmFtZTsKICAgICAgY29uc3Qgb3V0Q29tcG9uZW50cyA9IFtdOwogICAgICBjb25zdCB3aWR0aCA9IGZyYW1lLnNhbXBsZXNQZXJMaW5lOwogICAgICBjb25zdCBoZWlnaHQgPSBmcmFtZS5zY2FuTGluZXM7CgogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IGNvbXBvbmVudHNPcmRlci5sZW5ndGg7IGkrKykgewogICAgICAgIGNvbnN0IGNvbXBvbmVudCA9IGNvbXBvbmVudHNbY29tcG9uZW50c09yZGVyW2ldXTsKICAgICAgICBvdXRDb21wb25lbnRzLnB1c2goewogICAgICAgICAgbGluZXM6IGJ1aWxkQ29tcG9uZW50RGF0YShmcmFtZSwgY29tcG9uZW50KSwKICAgICAgICAgIHNjYWxlWDogY29tcG9uZW50LmggLyBmcmFtZS5tYXhILAogICAgICAgICAgc2NhbGVZOiBjb21wb25lbnQudiAvIGZyYW1lLm1heFYsCiAgICAgICAgfSk7CiAgICAgIH0KCiAgICAgIGNvbnN0IG91dCA9IG5ldyBVaW50OEFycmF5KHdpZHRoICogaGVpZ2h0ICogb3V0Q29tcG9uZW50cy5sZW5ndGgpOwogICAgICBsZXQgb2kgPSAwOwogICAgICBmb3IgKGxldCB5ID0gMDsgeSA8IGhlaWdodDsgKyt5KSB7CiAgICAgICAgZm9yIChsZXQgeCA9IDA7IHggPCB3aWR0aDsgKyt4KSB7CiAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IG91dENvbXBvbmVudHMubGVuZ3RoOyArK2kpIHsKICAgICAgICAgICAgY29uc3QgY29tcG9uZW50ID0gb3V0Q29tcG9uZW50c1tpXTsKICAgICAgICAgICAgb3V0W29pXSA9IGNvbXBvbmVudC5saW5lc1swIHwgeSAqIGNvbXBvbmVudC5zY2FsZVldWzAgfCB4ICogY29tcG9uZW50LnNjYWxlWF07CiAgICAgICAgICAgICsrb2k7CiAgICAgICAgICB9CiAgICAgICAgfQogICAgICB9CiAgICAgIHJldHVybiBvdXQ7CiAgICB9CiAgfQoKICBjbGFzcyBKcGVnRGVjb2RlciBleHRlbmRzIEJhc2VEZWNvZGVyIHsKICAgIGNvbnN0cnVjdG9yKGZpbGVEaXJlY3RvcnkpIHsKICAgICAgc3VwZXIoKTsKICAgICAgdGhpcy5yZWFkZXIgPSBuZXcgSnBlZ1N0cmVhbVJlYWRlcigpOwogICAgICBpZiAoZmlsZURpcmVjdG9yeS5KUEVHVGFibGVzKSB7CiAgICAgICAgdGhpcy5yZWFkZXIucGFyc2UoZmlsZURpcmVjdG9yeS5KUEVHVGFibGVzKTsKICAgICAgfQogICAgfQoKICAgIGRlY29kZUJsb2NrKGJ1ZmZlcikgewogICAgICB0aGlzLnJlYWRlci5yZXNldEZyYW1lcygpOwogICAgICB0aGlzLnJlYWRlci5wYXJzZ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0IFpfVEVYVCAgICAgICAgICAgICAgICA9IDE7CiAgLy9jb25zdCBaX0FTQ0lJICAgICAgICAgICAgID0gMTsgLy8gPSBaX1RFWFQKICBjb25zdCBaX1VOS05PV04kMSAgICAgICAgICAgICA9IDI7CgogIC8qPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSovCgoKICBmdW5jdGlvbiB6ZXJvJDEoYnVmKSB7IGxldCBsZW4gPSBidWYubGVuZ3RoOyB3aGlsZSAoLS1sZW4gPj0gMCkgeyBidWZbbGVuXSA9IDA7IH0gfQoKICAvLyBGcm9tIHp1dGlsLmgKCiAgY29uc3QgU1RPUkVEX0JMT0NLID0gMDsKICBjb25zdCBTVEFUSUNfVFJFRVMgPSAxOwogIGNvbnN0IERZTl9UUkVFUyAgICA9IDI7CiAgLyogVGhlIHRocmVlIGtpbmRzIG9mIGJsb2NrIHR5cGUgKi8KCiAgY29uc3QgTUlOX01BVENIJDEgICAgPSAzOwogIGNvbnN0IE1BWF9NQVRDSCQxICAgID0gMjU4OwogIC8qIFRoZSBtaW5pbXVtIGFuZCBtYXhpbXVtIG1hdGNoIGxlbmd0aHMgKi8KCiAgLy8gRnJvbSBkZWZsYXRlLmgKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBJbnRlcm5hbCBjb21wcmVzc2lvbiBzdGF0ZS4KICAgKi8KCiAgY29uc3QgTEVOR1RIX0NPREVTJDEgID0gMjk7CiAgLyogbnVtYmVyIG9mIGxlbmd0aCBjb2Rlcywgbm90IGNvdW50aW5nIHRoZSBzcGVjaWFsIEVORF9CTE9DSyBjb2RlICovCgogIGNvbnN0IExJVEVSQUxTJDEgICAgICA9IDI1NjsKICAvKiBudW1iZXIgb2YgbGl0ZXJhbCBieXRlcyAwLi4yNTUgKi8KCiAgY29uc3Qg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UgKi8KICAgIHRoaXMubWF4X2NvZGUgPSAwOyAgICAgICAgICAgIC8qIGxhcmdlc3QgY29kZSB3aXRoIG5vbiB6ZXJvIGZyZXF1ZW5jeSAqLwogICAgdGhpcy5zdGF0X2Rlc2MgPSBzdGF0X2Rlc2M7ICAgLyogdGhlIGNvcnJlc3BvbmRpbmcgc3RhdGljIHRyZWUgKi8KICB9CgoKCiAgY29uc3QgZF9jb2RlID0gKGRpc3QpID0+IHsKCiAgICByZXR1cm4gZGlzdCA8IDI1NiA/IF9kaXN0X2NvZGVbZGlzdF0gOiBfZGlzdF9jb2RlWzI1NiArIChkaXN0ID4+PiA3KV07CiAgfTsKCgogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQogICAqIE91dHB1dCBhIHNob3J0IExTQiBmaXJzdCBvbiB0aGUgc3RyZWFtLgogICAqIElOIGFzc2VydGlvbjogdGhlcmUgaXMgZW5vdWdoIHJvb20gaW4gcGVuZGluZ0J1Zi4KICAgKi8KICBjb25zdCBwdXRfc2hvcnQgPSAocywgdykgPT4gewogIC8vICAgIHB1dF9ieXRlKHMsICh1Y2gpKCh3KSAmIDB4ZmYpKTsKICAvLyAgICBwdXRfYnl0ZShzLCAodWNoKSgodXNoKSh3KSA+PiA4KSk7CiAgICBzLnBlbmRpbmdfYnVmW3MucGVuZGluZysrXSA9ICh3KSAmIDB4ZmY7CiAgICBzLnBlbmRpbmdfYnVmW3MucGVuZGluZysrXSA9ICh3ID4+PiA4KSAmIDB4ZmY7CiAgfTsKCgogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQogICAqIFNlbmQgYSB2YWx1ZSBvbiBhIGdpdmVuIG51bWJlciBvZiBiaXRzLgogICAqIElOIGFzc2VydGlvbjogbGVuZ3RoIDw9IDE2IGFuZCB2YWx1ZSBma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UgPj4+PSAxOwogICAgICByZXMgPDw9IDE7CiAgICB9IHdoaWxlICgtLWxlbiA+IDApOwogICAgcmV0dXJuIHJlcyA+Pj4gMTsKICB9OwoKCiAgLyogPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09CiAgICogRmx1c2ggdGhlIGJpdCBidWZmZXIsIGtlZXBpbmcgYXQgbW9zdCA3IGJpdHMgaW4gaXQuCiAgICovCiAgY29uc3QgYmlfZmx1c2ggPSAocykgPT4gewoKICAgIGlmIChzLmJpX3ZhbGlkID09PSAxNikgewogICAgICBwdXRfc2hvcnQocywgcy5iaV9idWYpOwogICAgICBzLmJpX2J1ZiA9IDA7CiAgICAgIHMuYmlfdmFsaWQgPSAwOwoKICAgIH0gZWxzZSBpZiAocy5iaV92YWxpZCA+PSA4KSB7CiAgICAgIHMucGVuZGluZ19idWZbcy5wZW5kaW5nKytdID0gcy5iaV9idWYgJiAweGZmOwogICAgICBzLmJpX2J1ZiA+Pj0gODsKICAgICAgcy5iaV92YWxpZCAtPSA4OwogICAgfQogIH07CgoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBDb21wdXRlIHRoZSBvcHRpbWFsIGJpdCBsZW5ndGhzIGZvciBhIHRyZWUgYW5kIHVwZGF0ZSB0aGUgdG90YWwgYml0IGxlbmd0aAogICAqIGZvciB0aGUgY3VycmVudCBibG9jay4KICAgKiBJTiBhc3NlcnRpb246IHRoZSBmaWVsZHMgZnJlcSBhbmQgZGFkIGFyZSBzZXQsIGhlYXBbaGVhcF9tYXhdIGFuZAogICAqICAgIGFib3ZlIGFyZSB0aGUgdHJlZSBub2RlcyBzb3J0ZWQgYnkgaW5jcmVhc2luZyBmcmVxdWVuY3kuCiAgICogT1VUIGFzc2VydGlvbnM6IHRoZSBmaWVsZCBsZW4gaX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Y3QgYmxfY291bnRbbWF4X2xlbmd0aF0KICAgICAgICovCiAgICAgIG92ZXJmbG93IC09IDI7CiAgICB9IHdoaWxlIChvdmVyZmxvdyA+IDApOwoKICAgIC8qIE5vdyByZWNvbXB1dGUgYWxsIGJpdCBsZW5ndGhzLCBzY2FubmluZyBpbiBpbmNyZWFzaW5nIGZyZXF1ZW5jeS4KICAgICAqIGggaXMgc3RpbGwgZXF1YWwgdG8gSEVBUF9TSVpFLiAoSXQgaXMgc2ltcGxlciB0byByZWNvbnN0cnVjdCBhbGwKICAgICAqIGxlbmd0aHMgaW5zdGVhZCBvZiBmaXhpbmcgb25seSB0aGUgd3Jvbmcgb25lcy4gVGhpcyBpZGVhIGlzIHRha2VuCiAgICAgKiBmcm9tICdhcicgd3JpdHRlbiBieSBIYXJ1aGlrbyBPa3VtdXJhLikKICAgICAqLwogICAgZm9yIChiaXRzID0gbWF4X2xlbmd0aDsgYml0cyAhPT0gMDsgYml0cy0tKSB7CiAgICAgIG4gPSBzLmJsX2NvdW50W2JpdHNdOwogICAgICB3aGlsZSAobiAhPT0gMCkgewogICAgICAgIG0gPSBzLmhlYXBbLS1oXTsKICAgICAgICBpZiAobSA+IG1heF9jb2RlKSB7IGNvbnRpbnVlOyB9CiAgICAgICAgaWYgKHRyZWVbbSAqIDIgKyAxXS8qLkxlbiovICE9PSBiaXRzKSB7CiAgICAgICAgICAvLyBUcmFjZSgoc3RkZXJyLCJjb2RlICVkIGJpdHMgJWQtPiVkXG4iLCBtLCB0cmVlW21dLkxlbiwgYml0cykpOwogICAgICAgICAgcy5vcHRfbGVuICs9IChiaXRzIC0gdHJlZVttICogMiArIDFdLyouTGVuKi8pICogdHJlZVttICogMl0vKi5GcmVxKi87CiAgICAgICAgICB0cmVlW20gKiAyICsgMV0vKi5MZW4qLyA9IGJpdHM7CiAgICAgICAgfQogICAgICAgIG4tLTsKICAgICAgfQogICAgfQogIH07CgoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09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CAqLwogICAgbGV0IG47ICAgICAgICAgICAgICAgICAgICAgLyogY29kZSBpbmRleCAqLwoKICAgIC8qIFRoZSBkaXN0cmlidXRpb24gY291bnRzIGFyZSBmaXJzdCB1c2VkIHRvIGdlbmVyYXRlIHRoZSBjb2RlIHZhbHVlcwogICAgICogd2l0aG91dCBiaXQgcmV2ZXJzYWwuCiAgICAgKi8KICAgIGZvciAoYml0cyA9IDE7IGJpdHMgPD0gTUFYX0JJVFMkMTsgYml0cysrKSB7CiAgICAgIG5leHRfY29kZVtiaXRzXSA9IGNvZGUgPSAoY29kZSArIGJsX2NvdW50W2JpdHMgLSAxXSkgPDwgMTsKICAgIH0KICAgIC8qIENoZWNrIHRoYXQgdGhlIGJpdCBjb3VudHMgaW4gYmxfY291bnQgYXJlIGNvbnNpc3RlbnQuIFRoZSBsYXN0IGNvZGUKICAgICAqIG11c3QgYmUgYWxsIG9uZXMuCiAgICAgKi8KICAgIC8vQXNzZXJ0IChjb2RlICsgYmxfY291bnRbTUFYX0JJVFNdLTEgPT0gKDE8PE1BWF9CSVRTKS0xLAogICAgLy8gICAgICAgICJpbmNvbnNpc3RlbnQgYml0IGNvdW50cyIpOwogICAgLy9UcmFjZXYoKHN0ZGVyciwiXG5nZW5fY29kZXM6IG1heF9jb2RlICVkICIsIG1heF9jb2RlKSk7CgogICAgZm9yIChuID0gMDsgIG4gPD0gbWF4X2NvZGU7IG4rKykgewogICAgICBsZXQgbGVuID0gdHJlZVtuICogMiArIDFdLyouTGVuKi87CiAgICAgIGlmIChsZW4gPT09IDApIHsgY29udGludWU7IH0KICAgICAgLyogTm93IHJldmVyc2UgdGhlIGJpdHMgKi8KICAgICAgdHJlZVtuICogMl0vKi5Db2RlKi8gPSBiaV9yZXZlcnNlKG5leHRfY29kZVtsZW5dKyssIGxlbik7CgogICAgICAvL1RyYWNlY3YodHJlZSAhPSBzdGF0aWNfbHRyZWUsIChzdGRlcnIsIlxubiAlM2QgJWMgbCAlMmQgYyAlNHggKCV4K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RFUyQxLCBNQVhfQklUUyQxKTsKICAgIHN0YXRpY19kX2Rlc2MgPSBuZXcgU3RhdGljVHJlZURlc2Moc3RhdGljX2R0cmVlLCBleHRyYV9kYml0cywgMCwgICAgICAgICAgRF9DT0RFUyQxLCBNQVhfQklUUyQxKTsKICAgIHN0YXRpY19ibF9kZXNjID0gbmV3IFN0YXRpY1RyZWVEZXNjKG5ldyBBcnJheSgwKSwgZXh0cmFfYmxiaXRzLCAwLCAgICAgICAgIEJMX0NPREVTJDEsIE1BWF9CTF9CSVRTKTsKCiAgICAvL3N0YXRpY19pbml0X2RvbmUgPSB0cnVlOwogIH07CgoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBJbml0aWFsaXplIGEgbmV3IGJsb2NrLgogICAqLwogIGNvbnN0IGluaXRfYmxvY2sgPSAocykgPT4gewoKICAgIGxldCBuOyAvKiBpdGVyYXRlcyBvdmVyIHRyZWUgZWxlbWVudHMgKi8KCiAgICAvKiBJbml0aWFsaXplIHRoZSB0cmVlcy4gKi8KICAgIGZvciAobiA9IDA7IG4gPCBMX0NPREVTJDE7ICBuKyspIHsgcy5keW5fbHRyZWVbbiAqIDJdLyouRnJlcSovID0gMDsgfQogICAgZm9yIChuID0gMDsgbiA8IERfQ09ERVMkMTsgIG4rKykgeyBzLmR5bl9kdHJlZVtuICogMl0vKi5GcmVxKi8gPSAwOyB9CiAgICBmb3IgKG4gPSAwOyBuIDwgQkxfQ09ERVMkMTsgbisrKSB7IHMuYmxfdHJlZVtuICogMl0vKi5GcmVxKi8gPSAwOyB9CgogICAgcy5keW5fbHRyZWVbRU5EX0JMT0NLICogMl0vKi5GcmVxKi8gPSAxOwogICAgcy5vcHRfbGVuID0gcy5zdGF0aWNfbGVuID0gMDsKICAgIHMubGFzdF9saXQgPSBzLm1hdGNoZXMgPSAwOwogIH07CgoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBGbHVzaCB0aGUgYml0IGJ1ZmZlciBhbmQgYWxpZ24gdGhlIG91dHB1dCBvbiBhIGJ5dGUgYm91bmRhcnkKICAgKi8KICBjb25zdCBiaV93aW5kdXAgPSAocykgPT4KICB7CiAgICBpZiAocy5iaV92YWxpZCA+IDgpIHsKICAgICAgcHV0X3Nob3J0KHMsIHMuYmlfYnVmKTsKICAgIH0gZWxzZSBpZiAocy5iaV92YWxpZCA+IDApIHsKICAgICAgLy9wdXRfYnl0ZShzLCAoQnl0ZSlzLT5iaV9idWYpOwogICAgICBzLnBlbmRpbmdfYnVmW3MucGVuZGluZysrXSA9IHMuYmlfYnVmOwogICAgfQogICAgcy5iaV9idWYgPSAwOwogICAgcy5iaV92YWxpZCA9IDA7CiAgfTsKCiAgLyogPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09CiAgICogQ29weSBhIHN0b3JlZCBibG9jaywgc3RvcmluZyBmaXJzdCB0aGUgbGVuZ3RoIGFuZCBpdHMKICAgKiBvbmUncyBjb21wbGVtZW50IGlmIHJlcXVlc3RlZC4KICAgKi8KICBjb25zdCBjb3B5X2Jsb2NrID0gKHMsIGJ1ZiwgbGVuLCBoZWFkZXIpID0+CiAgLy9EZWZsYXRlU3RhdGUgKnM7CiAgLy9jaGFyZiAgICAqYnVmOyAgICAvKiB0aGUgaW5wdXQgZGF0YSAqLwogIC8vdW5zaWduZWQgbGVuOyAgICAgLyogaXRzIGxlbmd0aCAqLwogIC8vaW50ICAgICAgaGVhZGVyOyAgLyogdHJ1ZSBpZiBibG9jayBoZWFkZXIgbXVzdCBiZSB3cml0dGVuICovCiAgewogICAgYmlfd2luZHVwKHMpOyAgICAgICAgLyogYWxpZ24gb24gYnl0ZSBib3VuZGFyeSAqLwoKICAgIGlmIChoZ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JlZSwgc2V0dGluZyBqIHRvIHRoZSBsZWZ0IHNvbiBvZiBrICovCiAgICAgIGogPDw9IDE7CiAgICB9CiAgICBzLmhlYXBba10gPSB2OwogIH07CgoKICAvLyBpbmxpbmVkIG1hbnVhbGx5CiAgLy8gY29uc3QgU01BTExFU1QgPSAxOwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBTZW5kIHRoZSBibG9jayBkYXRhIGNvbXByZXNzZWQgdXNpbmcgdGhlIGdpdmVuIEh1ZmZtYW4gdHJlZXMKICAgKi8KICBjb25zdCBjb21wcmVzc19ibG9jayA9IChzLCBsdHJlZSwgZHRyZWUpID0+CiAgLy8gICAgZGVmbGF0ZV9zdGF0ZSAqczsKICAvLyAgICBjb25zdCBjdF9kYXRhICpsdHJlZTsgLyogbGl0ZXJhbCB0cmVlICovCiAgLy8gICAgY29uc3QgY3RfZGF0YSAqZHRyZWU7IC8qIGRpc3RhbmNlIHRyZWUgKi8KICB7CiAgICBsZXQgZGlzdDsgICAgICAgICAgIC8qIGRpc3RhbmNlIG9mIG1hdGNoZWQgc3RyaW5nICovCiAgICBsZXQgbGM7ICAgICAgICAgICAgIC8qIG1hdGNoIGxlbmd0aCBvciB1bm1hdGNoZWQgY2hhciAoaWYgZGlzdCA9PSAwKSAqLwogICAgbGV0IGx4ID0gMDsgICAgICAgICAvKiBydW5uaW5nIGluZGV4IGluIGxfYnVmICovCiAgICBsZXQgY29kZTsgICAgICAgICAgIC8qIHRoZSBjb2RlIHRvIHNlbmQgKi8KICAgIGxldCBleHRyYTsgICAgICAgICAgLyogbnVtYmVyIG9mIGV4dHJhIGJpdHMgdG8gc2VuZCAqLwoKICAgIGlmIChzLmxhc3RfbGl0ICE9PSAwKSB7CiAgICAgIGRvIHsKICAgICAgICBkaXN0ID0gKHMucGVuZGluZ19idWZbcy5kX2J1ZiArIGx4ICogMl0gPDwgO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9CiAgICB0cmVlWyhtYXhfY29kZSArIDEpICogMiArIDFdLyouTGVuKi8gPSAweGZmZmY7IC8qIGd1YXJkICovCgogICAgZm9yIChuID0gMDsgbiA8PSBtYXhfY29kZTsgbisrKSB7CiAgICAgIGN1cmxlbiA9IG5leHRsZW47CiAgICAgIG5leHRsZW4gPSB0cmVlWyhuICsgMSkgKiAyICsgMV0vKi5MZW4qLzsKCiAgICAgIGlmICgrK2NvdW50IDwgbWF4X2NvdW50ICYmIGN1cmxlbiA9PT0gbmV4dGxlbikgewogICAgICAgIGNvbnRpbnVlOwoKICAgICAgfSBlbHNlIGlmIChjb3VudCA8IG1pbl9jb3VudCkgewogICAgICAgIHMuYmxfdHJlZVtjdXJsZW4gKiAyXS8qLkZyZXEqLyArPSBjb3VudDsKCiAgICAgIH0gZWxzZSBpZiAoY3VybGVuICE9PSAwKSB7CgogICAgICAgIGlmIChjdXJsZW4gIT09IHByZXZsZW4pIHsgcy5ibF90cmVlW2N1cmxlbiAqIDJdLyouRnJlcSovKys7IH0KICAgICAgICBzLmJsX3RyZWVbUkVQXzNfNiAqIDJdLyouRnJlcSovKys7CgogICAgICB9IGVsc2UgaWYgKGNvdW50IDw9IDEwKSB7CiAgICAgICAgcy5ibF90cmVlW1JFUFpfM18xMCAqIDJdLyouRnJlcSovKys7CgogICAgICB9IGVsc2UgewogICAgICAgIHMuYmxfdHJlZVtSRVBaXzExXzEzOCAqIDJdLyouRnJlcSovKys7CiAgICAgIH0KCiAgICAgIGNvdW50ID0gMDsKICAgICAgcHJldmxlbiA9IGN1cmxlbjsKCiAgICAgIGlmIChuZXh0bGVuID09PSAwKSB7CiAgICAgICAgbWF4X2NvdW50ID0gMTM4OwogICAgICAgIG1pbl9jb3VudCA9IDM7CgogICAgICB9IGVsc2UgaWYgKGN1cmxlbiA9PT0gbmV4dGxlbikgewogICAgICAgIG1heF9jb3VudCA9IDY7CiAgICAgICAgbWluX2NvdW50ID0gMzsKCiAgICAgIH0gZWxzZSB7CiAgICAgICAgbWF4X2NvdW50ID0gNzsKICAgICAgICBtaW5fY291bnQgPSA0OwogICAgICB9CiAgICB9CiAgfTsKCgogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQogICAqIFNlbmQgYSBsaXRlcmFsIG9yIGRpc3RhbmNlIHRyZWUgaW4gY29tcHJlc3NlZCBmb3JtLCB1c2luZyB0aGUgY29kZXMgaW4KICAgKiBibF90cmVlLgogICAqLwogIGNvbnN0IHNlbmRfdHJlZSA9IChzLCB0cmVlLCBtYXhfY29kZSkgPT4KICAvLyAgICBkZWZsYXRlX3N0YXRlICpzOwogIC8vICAgIGN0X2RhdGEgKnRyZWU7IC8qIHRoZSB0cmVlIHRvIGJlIHNjYW5uZWQgKi8KICAvLyAgICBpbnQgbWF4X2NvZGU7ICAgICAgIC8qIGFuZCBpdHMgbGFyZ2VzdCBjb2RlIG9mIG5vbiB6ZXJvIGZyZXF1ZW5jeSAqLwogIHsKICAgIGxldCBuOyAgICAgICAgICAgICAgICAgICAgIC8qIGl0ZXJhdGVzIG92ZXIgYWxsIHRyZWUgZWxlbWVudHMgKi8KICAgIGxldCBwcmV2bGVuID0gLTE7ICAgICAgICAgIC8qIGxhc3QgZW1pdHRlZCBsZW5ndGggKi8KICAgIGxldCBjdXJsZW47ICAgICAgICAgICAgICAgIC8qIGxlbmd0aCBvZiBjdXJyZW50IGNvZGUgKi8KCiAgICBsZXQgbmV4dGxlbiA9IHRyZWVbMCAqIDIgKyAxXS8qLkxlbiovOyAvKiBsZW5ndGggb2YgbmV4dCBjb2RlICovCgogICAgbGV0IGNvdW50ID0gMDsgICAgICAgICAgICAgLyogcmVwZWF0IGNvdW50IG9mIHRoZSBjdXJyZW50IGNvZGUgKi8KICAgIGxldCBtYXhfY291bnQgPSA3OyAgICAgICAgIC8qIG1heCByZXBlYXQgY291bnQgKi8KICAgIGxldCBtaW5fY291bnQgPSA0OyAgICAgICAgIC8qIG1pbiByZXBlYXQgY291bnQgKi8KCiAgICAvKiB0cmVlW21heF9jb2RlKzFdLkxlbiA9IC0xOyAqLyAgLyogZ3VhcmQgYWxyZWFkeSBzZXQgKi8KICAgIGlmIChuZXh0bGVuID09PSAwKSB7CiAgICAgIG1heF9jb3VudCA9IDEzODsKICAgICAgbWluX2NvdW50ID0gMzsKICAgIH0KCiAgICBmb3IgKG4gPSAwOyBuIDw9IG1heF9jb2RlOyBuKyspIHsKICAgICAgY3VybGVuID0gbmV4dGxlbjsKICAgICAgbmV4dGxlbiA9IHRyZWVbKG4gKyAxKSAqIDIgKyAxXS8qLkxlbiovOwoKICAgICAgaWYgKCsrY291bnQgPCBtYXhfY291bnQgJiYgY3VybGVuID09PSBuZXh0bGVuKSB7CiAgICAgICAgY29udGludWU7CgogICAgICB9IGVsc2UgaWYgKGNvdW50IDwgbWluX2NvdW50KSB7CiAgICAgICAgZG8geyBzZW5kX2NvZGUocywgY3VybGVuLCBzLmJsX3RyZWUpOyB9IHdoaWxlICgtLWNvdW50ICE9PSAwKTsKCiAgICAgIH0gZWxzZSBpZiAoY3VybGVuICE9PSAwKSB7CiAgICAgICAgaWYgKGN1cmxlbiAhPT0gcHJldmxlbikgewogICAgICAgICAgc2VuZF9jb2RlKHMsIGN1cmxlbiwgcy5ibF90cmVlKTsKICAgICAgICAgIGNvdW50LS07CiAgICAgICAgfQogICAgICAgIC8vQXNzZXJ0KGNvdW50ID49IDMgJiYgY291bnQgPD0gNiwgIiAzXzY/Iik7CiAgICAgICAgc2VuZF9jb2RlKHMsIFJFUF8zXzYsIHMuYmxfdHJlZSk7CiAgICAgICAgc2VuZF9iaXRzKHMsIGNvdW50IC0gMywgMik7CgogICAgICB9IGVsc2UgaWYgKGNvdW50IDw9IDEwKSB7CiAgICAgICAgc2VuZF9jb2RlKHMsIFJFUFpfM18xMCwgcy5ibF90cmVlKTsKICAgICAgICBzZW5kX2JpdHMocywgY291bnQgLSAzLCAzKTsKCiAgICAgIH0gZWxzZSB7CiAgICAgICAgc2VuZF9jb2RlKHMsIFJFUFpfMTFfMTM4LCBzLmJsX3RyZWUpOwogICAgICAgIHNlbmRfYml0cyhzLCBjb3VudCAtIDExLCA3KTsKICAgICAgfQoKICAgICAgY291bnQgPSAwOwogICAgICBwcmV2bGVuID0gY3VybGVuOwogICAgICBpZiAobmV4dGxlbiA9PT0gMCkgewogICAgICAgIG1heF9jb3VudCA9IDEzODsKICAgICAgICBtaW5fY291bnQgPSAzOwoKICAgICAgfSBlbHNlIGlmIChjdXJsZW4gPT09IG5leHRsZW4pIHsKICAgICAgICBtYXhfY291bnQgPSA2OwogICAgICAgIG1pbl9jb3VudCA9IDM7CgogICAgICB9IGVsc2UgewogICAgICAgIG1heF9jb3VudCA9IDc7CiAgICAgICAgbWluX2NvdW50ID0gNDsKICAgICAgfQogICAgfQogIH07CgoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBDb25zdHJ1Y3QgdGhlIEh1ZmZtYW4gdHJlZSBmb3IgdGhlIGJpdCBsZW5ndGhzIGFuZCByZXR1cm4gdGhlIGluZGV4IGluCiAgICogYmxfb3JkZXIgb2YgdGhlIGxhc3QgYml0IGxlbmd0aCBjb2RlIHRvIHNlbmQuCiAgICovCiAgY29uc3QgYnVpbGRfYmxfdHJlZSA9IChzKSA9PiB7CgogICAgbGV0IG1heF9ibGluZGV4OyAgLyogaW5kZXggb2YgbGFzdCBiaXQgbGVuZ3RoIGNvZGUgb2Ygbm9uIHplcm8gZnJlcSAqLwoKICAgIC8qIERldGVybWluZSB0aGUgYml0IGxlbmd0aCBmcmVxdWVuY2llcyBmb3IgbGl0ZXJhbCBhbmQgZGlzdGFuY2UgdHJlZXMgKi8KICAgIHNjYW5fdHJlZShzLCBzLmR5bl9sdHJlZSwgcy5sX2Rlc2MubWF4X2NvZGUpOwogICAgc2Nhbl90cmVlKH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AgICAvLyAgICAgICAgcy0+b3B0X2xlbiwgcy0+c3RhdGljX2xlbikpOwoKICAgIHJldHVybiBtYXhfYmxpbmRleDsKICB9OwoKCiAgLyogPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09CiAgICogU2VuZCB0aGUgaGVhZGVyIGZvciBhIGJsb2NrIHVzaW5nIGR5bmFtaWMgSHVmZm1hbiB0cmVlczogdGhlIGNvdW50cywgdGhlCiAgICogbGVuZ3RocyBvZiB0aGUgYml0IGxlbmd0aCBjb2RlcywgdGhlIGxpdGVyYWwgdHJlZSBhbmQgdGhlIGRpc3RhbmNlIHRyZWUuCiAgICogSU4gYXNzZXJ0aW9uOiBsY29kZXMgPj0gMjU3LCBkY29kZXMgPj0gMSwgYmxjb2RlcyA+PSA0LgogICAqLwogIGNvbnN0IHNlbmRfYWxsX3RyZWVzID0gKHMsIGxjb2RlcywgZGNvZGVzLCBibGNvZGVzKSA9PgogIC8vICAgIGRlZmxhdGVfc3RhdGUgKnM7CiAgLy8gICAgaW50IGxjb2RlcywgZGNvZGVzLCBibGNvZGVzOyAvKiBudW1iZXIgb2YgY29kZXMgZm9yIGVhY2ggdHJlZSAqLwogIHsKICAgIGxldCByYW5rOyAgICAgICAgICAgICAgICAgICAgLyogaW5kZXggaW4gYmxfb3JkZXIgKi8KCiAgICAvL0Fzc2VydCAobGNvZGVzID49IDI1NyAmJiBkY29kZXMgPj0gMSAmJiBibGNvZGVzID49IDQsICJub3QgZW5vdWdoIGNvZGVzIik7CiAgICAvL0Fzc2VydCAobGNvZGVzIDw9IExfQ09ERVMgJiYgZGNvZGVzIDw9IERfQ09ERVMgJiYgYmxjb2RlcyA8PSBCTF9DT0RFUywKICAgIC8vICAgICAgICAidG9vIG1hbnkgY29kZXMiKTsKICAgIC8vVHJhY2V2KChzdGRlcnIsICJcbmJsIGNvdW50czogIikpOwogICAgc2VuZF9iaXRzKHMsIGxjb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WNrIGZvciBub24tdGV4dHVhbCAoImJsYWNrLWxpc3RlZCIpIGJ5dGVzLiAqLwogICAgZm9yIChuID0gMDsgbiA8PSAzMTsgbisrLCBibGFja19tYXNrID4+Pj0gMSkgewogICAgICBpZiAoKGJsYWNrX21hc2sgJiAxKSAmJiAocy5keW5fbHRyZWVbbiAqIDJdLyouRnJlcSovICE9PSAwKSkgewogICAgICAgIHJldHVybiBaX0JJTkFSWTsKICAgICAgfQogICAgfQoKICAgIC8qIENoZWNrIGZvciB0ZXh0dWFsICgid2hpdGUtbGlzdGVkIikgYnl0ZXMuICovCiAgICBpZiAocy5keW5fbHRyZWVbOSAqIDJdLyouRnJlcSovICE9PSAwIHx8IHMuZHluX2x0cmVlWzEwICogMl0vKi5GcmVxKi8gIT09IDAgfHwKICAgICAgICBzLmR5bl9sdHJlZVsxMyAqIDJdLyouRnJlcSovICE9PSAwKSB7CiAgICAgIHJldHVybiBaX1RFWFQ7CiAgICB9CiAgICBmb3IgKG4gPSAzMjsgbiA8IExJVEVSQUxTJDE7IG4rKykgewogICAgICBpZiAocy5keW5fbHRyZWVbbiAqIDJdLyouRnJlcSovICE9PSAwKSB7CiAgICAgICAgcmV0dXJuIFpfVEVYVDsKICAgICAgfQogICAgfQoKICAgIC8qIFRoZXJlIGFyZSBubyAiYmxhY2stbGlzdGVkIiBvciAid2hpdGUtbGlzdGVkIiBieXRlczoKICAgICAqIHRoaXMgc3RyZWFtIGVpdGhlciBpcyBlbXB0eSBvciBoYXMgdG9sZXJhdGVkICgiZ3JheS1saXN0ZWQiKSBieXRlcyBvbmx5LgogICAgICovCiAgICByZXR1cm4gWl9CSU5BUlk7CiAgfTsKCgogIGxldCBzdGF0aWNfaW5pdF9kb25lID0gZmFsc2U7CgogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQogICAqIEluaXRpYWxpemUgdGhlIHRyZWUgZGF0YSBzdHJ1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Vycm9ycywgcG9zaXRpdmUgdmFsdWVzIGFyZSB1c2VkIGZvciBzcGVjaWFsIGJ1dCBub3JtYWwgZXZlbnRzLgogICAgKi8KICAgIFpfT0s6ICAgICAgICAgICAgICAgMCwKICAgIFpfU1RSRUFNX0VORDogICAgICAgMSwKICAgIFpfTkVFRF9ESUNUOiAgICAgICAgMiwKICAgIFpfRVJSTk86ICAgICAgICAgICAtMSwKICAgIFpfU1RSRUFNX0VSUk9SOiAgICAtMiwKICAgIFpfREFUQV9FUlJPUjogICAgICAtMywKICAgIFpfTUVNX0VSUk9SOiAgICAgICAtNCwKICAgIFpfQlVGX0VSUk9SOiAgICAgICAtNSwKICAgIC8vWl9WRVJTSU9OX0VSUk9SOiAtNiwKCiAgICAvKiBjb21wcmVzc2lvbiBsZXZlbHMgKi8KICAgIFpfTk9fQ09NUFJFU1NJT046ICAgICAgICAgMCwKICAgIFpfQkVTVF9TUEVFRDogICAgICAgICAgICAgMSwKICAgIFpfQkVTVF9DT01QUkVTU0lPTjogICAgICAgOSwKICAgIFpfREVGQVVMVF9DT01QUkVTU0lPTjogICAtMSwKCgogICAgWl9GSUxURVJFRDogICAgICAgICAgICAgICAxLAogICAgWl9IVUZGTUFOX09OTFk6ICAgICAgICAgICAyLAogICAgWl9STEU6ICAgICAgICAgICAgICAgICAgICAzLAogICAgWl9GSVhFRDogICAgICAgICAgICAgICAgICA0LAogICAgWl9ERUZBVUxUX1NUUkFURUdZOiAgICAgICAwLAoKICAgIC8qIFBvc3NpYmxlIHZhbHVlcyBvZiB0aGUgZGF0YV90eXBlIGZpZWxkICh0aG91Z2ggc2VlIGluZmxhdGUoKSkgKi8KICAgIFpfQklOQVJZOiAgICAgICAgICAgICAgICAgMCwKICAgIFpfVEVYVDogICAgICAgICAgICAgICAgICAgMSwKICAgIC8vWl9BU0NJSTogICAgICAgICAgICAgICAgMSwgLy8gPSBaX1RFWFQgKGRlcHJlY2F0ZWQpCiAgICBaX1VOS05PV046ICAgICAgICAgICAgIC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JlKS4KICAgKi8KICBjb25zdCBmaWxsX3dpbmRvdyA9IChzKSA9PiB7CgogICAgY29uc3QgX3dfc2l6ZSA9IHMud19zaXplOwogICAgbGV0IHAsIG4sIG0sIG1vcmUsIHN0cjsKCiAgICAvL0Fzc2VydChzLT5sb29rYWhlYWQgPCBNSU5fTE9PS0FIRUFELCAiYWxyZWFkeSBlbm91Z2ggbG9va2FoZWFkIik7CgogICAgZG8gewogICAgICBtb3JlID0gcy53aW5kb3dfc2l6ZSAtIHMubG9va2FoZWFkIC0gcy5zdHJzdGFydDsKCiAgICAgIC8vIEpTIGludHMgaGF2ZSAzMiBiaXQsIGJsb2NrIGJlbG93IG5vdCBuZWVkZWQKICAgICAgLyogRGVhbCB3aXRoICFAIyQlIDY0SyBsaW1pdDogKi8KICAgICAgLy9pZiAoc2l6ZW9mKGludCkgPD0gMikgewogICAgICAvLyAgICBpZiAobW9yZSA9PSAwICYmIHMtPnN0cnN0YXJ0ID09IDAgJiYgcy0+bG9va2FoZWFkID09IDApIHsKICAgICAgLy8gICAgICAgIG1vcmUgPSB3c2l6ZTsKICAgICAgLy8KICAgICAgLy8gIH0gZWxzZSBpZiAobW9yZSA9PSAodW5zaWduZWQpKC0xKSkgewogICAgICAvLyAgICAgICAgLyogVmVyeSB1bmxpa2VseSwgYnV0IHBvc3NpYmxlIG9uIDE2IGJpdCBtYWNoaW5lIGlmCiAgICAgIC8vICAgICAgICAgKiBzdHJzdGFydCA9PSAwICYmIGxvb2thaGVhZCA9PSAxIChpbnB1dCBkb25lIGEgYnl0ZSBhdCB0aW1lKQogICAgICAvLyAgICAgICAgICovCiAgICAgIC8vICAgICAgICBtb3JlLS07CiAgICAgIC8vICAgIH0KICAgICAgLy99CgoKICAgICAgLyogSWYgdGhlIHdpbmRvdyBpcyBhbG1vc3QgZnVsbCBhbmQgdGhlcmUgaXMgaW5zdWZmaWNpZW50IGxvb2thaGVhZCwKICAgICAgICogbW92ZSB0aGUgdXBwZXIgaGFsZiB0byB0a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ApOwogICAgICAgIH0gd2hpbGUgKC0tbik7CgogICAgICAgIG4gPSBfd19zaXplOwogICAgICAgIHAgPSBuOwoKICAgICAgICBkbyB7CiAgICAgICAgICBtID0gcy5wcmV2Wy0tcF07CiAgICAgICAgICBzLnByZXZbcF0gPSAobSA+PSBfd19zaXplID8gbSAtIF93X3NpemUgOiAwKTsKICAgICAgICAgIC8qIElmIG4gaXMgbm90IG9uIGFueSBoYXNoIGNoYWluLCBwcmV2W25dIGlzIGdhcmJhZ2UgYnV0CiAgICAgICAgICAgKiBpdHMgdmFsdWUgd2lsbCBuZXZlciBiZSB1c2VkLgogICAgICAgICAgICovCiAgICAgICAgfSB3aGlsZSAoLS1uKTsKCiAgICAgICAgbW9yZSArPSBfd19zaXplOwogICAgICB9CiAgICAgIGlmIChzLnN0cm0uYXZhaWxfaW4gPT09IDApIHsKICAgICAgICBicmVhazsKICAgICAgfQoKICAgICAgLyogSWYgdGhlcmUgd2FzIG5vIHNsaWRpbmc6CiAgICAgICAqICAgIHN0cnN0YXJ0IDw9IFdTSVpFK01BWF9ESVNULTEgJiYgbG9va2FoZWFkIDw9IE1JTl9MT09LQUhFQUQgLSAxICYmCiAgICAgICAqICAgIG1vcmUgPT0gd2luZG93X3NpemUgLSBsb29rYWhlYWQgLSBzdHJzdGFydAogICAgICAgKiA9PiBtb3JlID49IHdpbmRvd19zaXplIC0gKE1JTl9MT09LQUhFQUQtMSArIFdTSVpFICsgTUFYX0RJU1QtMSkKICAgICAgICogPT4gbW9yZSA+PSB3aW5kb3dfc2l6ZSAtIDIqV1NJWkUgKyAyCiAgICAgICAqIEluIHRoZSBCSUdfTUVNIG9yIE1NQVAgY2FzZSAobm90IHlldCBzdXBwb3J0ZWQpLAogICAgICAgKiAgIHdpbmRvd19zaXplID09IGlucHV0X3NpemUgKyBNSU5fTE9PS0FIRUFEICAmJgogICAgICAgKiAgIHN0cnN0YXJ0ICsgcy0+bG9va2FoZWFkIDw9IGlucHV0X3NpemUgPT4gbW9yZSA+PSBNSU5fTE9PS0FIRUFELgogICAgICAgKiBPdGhlcndpc2UsIHdpbmRvd19zaXplID09IDIqV1NJWkUgc28gbW9yZSA+PSAyLgogICAgICAgKiBJZiB0aGVyZSB3YXMgc2xpZGluZywgbW9yZSA+PSBXU0laRS4gU28gaW4gYWxsIGNhc2VzLCBtb3JlID49IDIuCiAgICAgICAqLwogICAgICAvL0Fzc2VydChtb3JlID49IDIsICJtb3JlIDwgMiIpOwogICAgICBuID0gcmVhZF9idWYocy5zdHJtLCBzLndpbmRvdywgcy5zdHJzdGFydCArIHMubG9va2FoZWFkLCBtb3JlKTsKICAgICAgcy5sb29rYWhlYWQgKz0gbjsKCiAgICAgIC8qIEluaXRpYWxpemUgdGhlIGhhc2ggdmFsdWUgbm93IHRoYXQgd2UgaGF2ZSBzb21lIGlucHV0OiAqLwogICAgICBpZiAocy5sb29rYWhlYWQgKyBzLmluc2VydCA+PSBNSU5fTUFUQ0gpIHsKICAgICAgICBzdHIgPSBzLnN0cnN0YXJ0IC0gcy5pbnNlcnQ7CiAgICAgICAgcy5pbnNfaCA9IHMud2luZG93W3N0cl07CgogICAgICAgIC8qIFVQREFURV9IQVNIKHMsIHMtPmluc19oLCBzLT53aW5kb3dbc3RyICsgMV0pOyAqLwogICAgICAgIHMuaW5zX2ggPSBIQVNIKHMsIHMuaW5zX2gsIHMud2luZG93W3N0ciArIDFdKTsKICAvLyNpZiBNSU5fTUFUQ0ggIT0gMwogIC8vICAgICAgICBDYWxsIHVwZGF0ZV9oYXNoKCkgTUlOX01BVENILTMgbW9yZSB0aW1lcwogIC8vI2VuZGlmCiAgICAgICAgd2hpbGUgKHMuaW5zZXJ0KSB7CiAgICAgICAgICAvKiBVUERBVEVfSEFTSChzLCBzLT5pbnNfaCwgcy0+d2luZG93W3N0ciArIE1JTl9NQVRDSC0xXSk7ICovCiAgICAgICAgICBzLmluc19oID0gSEFTSChzLCBzLmluc19oLCBzLndpbmRvd1tzdHIgKyBNSU5fTUFUQ0gg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gICAgKiB0byBlbmQgb2Ygd2luZG93LCB3aGljaGV2ZXIgaXMgbGVzcy4KICAvLyAgICAgICAqLwogIC8vICAgICAgaW5pdCA9ICh1bGcpY3VyciArIFdJTl9JTklUIC0gcy0+aGlnaF93YXRlcjsKICAvLyAgICAgIGlmIChpbml0ID4gcy0+d2luZG93X3NpemUgLSBzLT5oaWdoX3dhdGVyKQogIC8vICAgICAgICBpbml0ID0gcy0+d2luZG93X3NpemUgLSBzLT5oaWdoX3dhdGVyOwogIC8vICAgICAgem1lbXplcm8ocy0+d2luZG93ICsgcy0+aGlnaF93YXRlciwgKHVuc2lnbmVkKWluaXQpOwogIC8vICAgICAgcy0+aGlnaF93YXRlciArPSBpbml0OwogIC8vICAgIH0KICAvLyAgfQogIC8vCiAgLy8gIEFzc2VydCgodWxnKXMtPnN0cnN0YXJ0IDw9IHMtPndpbmRvd19zaXplIC0gTUlOX0xPT0tBSEVBRCwKICAvLyAgICAibm90IGVub3VnaCByb29tIGZvciBzZWFyY2giKTsKICB9OwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBDb3B5IHdpdGhvdXQgY29tcHJlc3Npb24gYXMgbXVjaCBhcyBwb3NzaWJsZSBmcm9tIHRoZSBpbnB1dCBzdHJlYW0sIHJldHVybgogICAqIHRoZSBjdXJyZW50IGJsb2NrIHN0YXRlLgogICAqIFRoaXMgZnVuY3Rpb24gZG9lcyBub3QgaW5zZXJ0IG5ldyBzdHJpbmdzIGluIHRoZSBkaWN0aW9uYXJ5IHNpbmNlCiAgICogdW5jb21wcmVzc2libGUgZGF0YSBpcyBwcm9iYWJseSBub3QgdXNlZnVsLiBUaGlzIGZ1bmN0aW9uIGlzIHVzZWQKICAgKiBvbmx5IGZvciB0aGUgbGV2ZWw9MCBjb21wcmVzc2lvbiBvcHRpb24uCiAgICogTk9URTogdGhpcyBmdW5jdGlvbiBzaG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2UpOwogICAgICAgIGlmIChzLnN0cm0uYXZhaWxfb3V0ID09PSAwKSB7CiAgICAgICAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogICAgICAgIH0KICAgICAgICAvKioqLwoKCiAgICAgIH0KICAgICAgLyogRmx1c2ggaWYgd2UgbWF5IGhhdmUgdG8gc2xpZGUsIG90aGVyd2lzZSBibG9ja19zdGFydCBtYXkgYmVjb21lCiAgICAgICAqIG5lZ2F0aXZlIGFuZCB0aGUgZGF0YSB3aWxsIGJlIGdvbmU6CiAgICAgICAqLwogICAgICBpZiAocy5zdHJzdGFydCAtIHMuYmxvY2tfc3RhcnQgPj0gKHMud19zaXplIC0gTUlOX0xPT0tBSEVBRCkpIHsKICAgICAgICAvKioqIEZMVVNIX0JMT0NLKHMsIDApOyAqKiovCiAgICAgICAgZmx1c2hfYmxvY2tfb25seShzLCBmYWxzZSk7CiAgICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICAgIHJldHVybiBCU19ORUVEX01PUkU7CiAgICAgICAgfQogICAgICAgIC8qKiovCiAgICAgIH0KICAgIH0KCiAgICBzLmluc2VydCA9IDA7CgogICAgaWYgKGZsdXNoID09PSBaX0ZJTklTSCQzKSB7CiAgICAgIC8qKiogRkxVU0hfQkxPQ0socywgMSk7ICoqKi8KICAgICAgZmx1c2hfYmxvY2tfb25seShzLCB0cnVlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfRklOSVNIX1NUQVJURUQ7CiAgICAgIH0KICAgICAgLyoqKi8KICAgICAgcmV0dXJuIEJTX0ZJTklTSF9ET05FOwogICAgfQoKICAgIGlmIChzLnN0cnN0YXJ0ID4gcy5ibG9ja19zdGFydCkgewogICAgICAvKioqIEZMVVNIX0JMT0NLKHMsIDApOyAqKiovCiAgICAgIGZsdXNoX2Jsb2NrX29ubHkocywgZmFsc2UpOwogICAgICBpZiAocy5zdHJtLmF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sIHBsdXMgTUlOX01BVENIIGJ5dGVzIHRvIGluc2VydCB0aGUKICAgICAgICogc3RyaW5nIGZvbGxvd2luZyB0aGUgbmV4dCBtYXRjaC4KICAgICAgICovCiAgICAgIGlmIChzLmxvb2thaGVhZCA8IE1JTl9MT09LQUhFQUQpIHsKICAgICAgICBmaWxsX3dpbmRvdyhzKTsKICAgICAgICBpZiAocy5sb29rYWhlYWQgPCBNSU5fTE9PS0FIRUFEICYmIGZsdXNoID09PSBaX05PX0ZMVVNIJDIpIHsKICAgICAgICAgIHJldHVybiBCU19ORUVEX01PUkU7CiAgICAgICAgfQogICAgICAgIGlmIChzLmxvb2thaGVhZCA9PT0gMCkgewogICAgICAgICAgYnJlYWs7IC8qIGZsdXNoIHRoZSBjdXJyZW50IGJsb2NrICovCiAgICAgICAgfQogICAgICB9CgogICAgICAvKiBJbnNlcnQgdGhlIHN0cmluZyB3aW5kb3dbc3Ryc3RhcnQgLi4gc3Ryc3RhcnQrMl0gaW4gdGhlCiAgICAgICAqIGRpY3Rpb25hcnksIGFuZCBzZXQgaGFzaF9oZWFkIHRvIHRoZSBoZWFkIG9mIHRoZSBoYXNoIGNoYWluOgogICAgICAgKi8KICAgICAgaGFzaF9oZWFkID0gMC8qTklMKi87CiAgICAgIGlmIChzLmxvb2thaGVhZCA+PSBNSU5fTUFUQ0gpIHsKICAgICAgICAvKioqIElOU0VSVF9TVFJJTkcocywgcy5zdHJzdGFydCwgaGFzaF9oZWFkKTsgKioqLwogICAgICAgIHMuaW5zX2ggPSBIQVNIKHMsIHMuaW5zX2gsIHMud2luZG93W3Muc3Ryc3RhcnQgKyBNSU5fTUFUQ0ggLSAxXSk7CiAgICAgICAgaGFzaF9oZWFkID0gcy5wcmV2W3Muc3Ryc3RhcnQgJiBzLndfbWFza10gPSBzLmhlYWRbcy5pbnNfaF07CiAgICAgICAgcy5oZWFkW3MuaW5zX2hdID0gcy5zdHJzdGFydDsKICAgICAgICAvKioqLwogICAgICB9CgogICAgICAvKi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0gX3RyX3RhbGx5KHMsIDAsIHMud2luZG93W3Muc3Ryc3RhcnRdKTsKCiAgICAgICAgcy5sb29rYWhlYWQtLTsKICAgICAgICBzLnN0cnN0YXJ0Kys7CiAgICAgIH0KICAgICAgaWYgKGJmbHVzaCkgewogICAgICAgIC8qKiogRkxVU0hfQkxPQ0socywgMCk7ICoqKi8KICAgICAgICBmbHVzaF9ibG9ja19vbmx5KHMsIGZhbHNlKTsKICAgICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgICAgcmV0dXJuIEJTX05FRURfTU9SRTsKICAgICAgICB9CiAgICAgICAgLyoqKi8KICAgICAgfQogICAgfQogICAgcy5pbnNlcnQgPSAoKHMuc3Ryc3RhcnQgPCAoTUlOX01BVENIIC0gMSkpID8gcy5zdHJzdGFydCA6IE1JTl9NQVRDSCAtIDEpOwogICAgaWYgKGZsdXNoID09PSBaX0ZJTklTSCQzKSB7CiAgICAgIC8qKiogRkxVU0hfQkxPQ0socywgMSk7ICoqKi8KICAgICAgZmx1c2hfYmxvY2tfb25seShzLCB0cnVlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfRklOSVNIX1NUQVJURUQ7CiAgICAgIH0KICAgICAgLyoqKi8KICAgICAgcmV0dXJuIEJTX0ZJTklTSF9ET05FOwogICAgfQogICAgaWYgKHMubGFzdF9saXQpIHsKICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAwKTsgKioqLwogICAgICBmbHVzaF9ibG9ja19vbmx5KHMsIGZhbHNlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogICAgICB9CiAgICAgIC8qKiovCiAgICB9CiAgICByZXR1cm4gQlNfQkxPQ0tfRE9ORTsKICB9OwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09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IHRoZSBoYXNoIHRhYmxlLgogICAgICAgICAqLwogICAgICAgIHMubG9va2FoZWFkIC09IHMucHJldl9sZW5ndGggLSAxOwogICAgICAgIHMucHJldl9sZW5ndGggLT0gMjsKICAgICAgICBkbyB7CiAgICAgICAgICBpZiAoKytzLnN0cnN0YXJ0IDw9IG1heF9pbnNlcnQpIHsKICAgICAgICAgICAgLyoqKiBJTlNFUlRfU1RSSU5HKHMsIHMuc3Ryc3RhcnQsIGhhc2hfaGVhZCk7ICoqKi8KICAgICAgICAgICAgcy5pbnNfaCA9IEhBU0gocywgcy5pbnNfaCwgcy53aW5kb3dbcy5zdHJzdGFydCArIE1JTl9NQVRDSCAtIDFdKTsKICAgICAgICAgICAgaGFzaF9oZWFkID0gcy5wcmV2W3Muc3Ryc3RhcnQgJiBzLndfbWFza10gPSBzLmhlYWRbcy5pbnNfaF07CiAgICAgICAgICAgIHMuaGVhZFtzLmluc19oXSA9IHMuc3Ryc3RhcnQ7CiAgICAgICAgICAgIC8qKiovCiAgICAgICAgICB9CiAgICAgICAgfSB3aGlsZSAoLS1zLnByZXZfbGVuZ3RoICE9PSAwKTsKICAgICAgICBzLm1hdGNoX2F2YWlsYWJsZSA9IDA7CiAgICAgICAgcy5tYXRjaF9sZW5ndGggPSBNSU5fTUFUQ0ggLSAxOwogICAgICAgIHMuc3Ryc3RhcnQrKzsKCiAgICAgICAgaWYgKGJmbHVzaCkgewogICAgICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAwKTsgKioqLwogICAgICAgICAgZmx1c2hfYmxvY2tfb25seShzLCBmYWxzZSk7CiAgICAgICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgICAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogICAgICAgICAgfQogICAgICAgICAgLyoqKi8KICAgICAgICB9CgogICAgICB9IGVsc2UgaWYgKHMubWF0Y2hfYXZhaWxhYmxlKSB7CiAgICAgICAgLyogSWYgdGhlcmUgd2FzIG5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AgICAgfQogICAgfQogICAgLy9Bc3NlcnQgKGZsdXNoICE9IFpfTk9fRkxVU0gsICJubyBmbHVzaD8iKTsKICAgIGlmIChzLm1hdGNoX2F2YWlsYWJsZSkgewogICAgICAvL1RyYWNldnYoKHN0ZGVyciwiJWMiLCBzLT53aW5kb3dbcy0+c3Ryc3RhcnQtMV0pKTsKICAgICAgLyoqKiBfdHJfdGFsbHlfbGl0KHMsIHMud2luZG93W3Muc3Ryc3RhcnQtMV0sIGJmbHVzaCk7ICoqKi8KICAgICAgYmZsdXNoID0gX3RyX3RhbGx5KHMsIDAsIHMud2luZG93W3Muc3Ryc3RhcnQgLSAxXSk7CgogICAgICBzLm1hdGNoX2F2YWlsYWJsZSA9IDA7CiAgICB9CiAgICBzLmluc2VydCA9IHMuc3Ryc3RhcnQgPCBNSU5fTUFUQ0ggLSAxID8gcy5zdHJzdGFydCA6IE1JTl9NQVRDSCAtIDE7CiAgICBpZiAoZmx1c2ggPT09IFpfRklOSVNIJDMpIHsKICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAxKTsgKioqLwogICAgICBmbHVzaF9ibG9ja19vbmx5KHMsIHRydWUpOwogICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgIHJldHVybiBCU19GSU5JU0hfU1RBUlRFRDsKICAgICAgfQogICAgICAvKioqLwogICAgICByZXR1cm4gQlNfRklOSVNIX0RPTkU7CiAgICB9CiAgICBpZiAocy5sYXN0X2xpdCkgewogICAgICAvKioqIEZMVVNIX0JMT0NLKHMsIDApOyAqKiovCiAgICAgIGZsdXNoX2Jsb2NrX29ubHkocywgZmFsc2UpOwogICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgIHJldHVybiBCU19ORUVEX01PUkU7CiAgICAgIH0KICAgICAgLyoqKi8KICAgIH0KCiAgICByZXR1cm4gQlNfQkxPQ0tfRE9ORTsKICB9OwoKCiAgLyogPT09PT09PT09PT09PT09PT09PT09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G9va2FoZWFkIDw9IE1BWF9NQVRDSCAmJiBmbHVzaCA9PT0gWl9OT19GTFVTSCQyKSB7CiAgICAgICAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogICAgICAgIH0KICAgICAgICBpZiAocy5sb29rYWhlYWQgPT09IDApIHsgYnJlYWs7IH0gLyogZmx1c2ggdGhlIGN1cnJlbnQgYmxvY2sgKi8KICAgICAgfQoKICAgICAgLyogU2VlIGhvdyBtYW55IHRpbWVzIHRoZSBwcmV2aW91cyBieXRlIHJlcGVhdHMgKi8KICAgICAgcy5tYXRjaF9sZW5ndGggPSAwOwogICAgICBpZiAocy5sb29rYWhlYWQgPj0gTUlOX01BVENIICYmIHMuc3Ryc3RhcnQgPiAwKSB7CiAgICAgICAgc2NhbiA9IHMuc3Ryc3RhcnQgLSAxOwogICAgICAgIHByZXYgPSBfd2luW3NjYW5dOwogICAgICAgIGlmIChwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmIHByZXYgPT09IF93aW5bKytzY2FuXSkgewogICAgICAgICAgc3RyZW5kID0gcy5zdHJzdGFydCArIE1BWF9NQVRDSDsKICAgICAgICAgIGRvIHsKICAgICAgICAgICAgLypqc2hpbnQgbm9lbXB0eTpmYWxzZSovCiAgICAgICAgICB9IHdoaWxlIChwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmCiAgICAgICAgICAgICAgICAgICBwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmCiAgICAgICAgICAgICAgICAgICBwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmCiAgICAgICAgICAgICAgICAgICBwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmCiAgICAgICAgICAgICAgICAgICBzY2FuIDwgc3Ry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dGFsbHlfbGl0KHMsIHMud2luZG93W3Muc3Ryc3RhcnRdLCBiZmx1c2gpOyAqKiovCiAgICAgICAgYmZsdXNoID0gX3RyX3RhbGx5KHMsIDAsIHMud2luZG93W3Muc3Ryc3RhcnRdKTsKCiAgICAgICAgcy5sb29rYWhlYWQtLTsKICAgICAgICBzLnN0cnN0YXJ0Kys7CiAgICAgIH0KICAgICAgaWYgKGJmbHVzaCkgewogICAgICAgIC8qKiogRkxVU0hfQkxPQ0socywgMCk7ICoqKi8KICAgICAgICBmbHVzaF9ibG9ja19vbmx5KHMsIGZhbHNlKTsKICAgICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgICAgcmV0dXJuIEJTX05FRURfTU9SRTsKICAgICAgICB9CiAgICAgICAgLyoqKi8KICAgICAgfQogICAgfQogICAgcy5pbnNlcnQgPSAwOwogICAgaWYgKGZsdXNoID09PSBaX0ZJTklTSCQzKSB7CiAgICAgIC8qKiogRkxVU0hfQkxPQ0socywgMSk7ICoqKi8KICAgICAgZmx1c2hfYmxvY2tfb25seShzLCB0cnVlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfRklOSVNIX1NUQVJURUQ7CiAgICAgIH0KICAgICAgLyoqKi8KICAgICAgcmV0dXJuIEJTX0ZJTklTSF9ET05FOwogICAgfQogICAgaWYgKHMubGFzdF9saXQpIHsKICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAwKTsgKioqLwogICAgICBmbHVzaF9ibG9ja19vbmx5KHMsIGZhbHNlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogICAgICB9CiAgICAgIC8qKiovCiAgICB9CiAgICByZXR1cm4gQlNfQkxPQ0tfRE9ORTsKICB9OwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBGb3IgWl9IVUZGTUFOX09OTFksIGRvIG5vdCBsb29rIGZvciBtYXRjaGVzLiAgRG8gbm90IG1haW50YWluIGEgaGFzaCB0YWJsZS4KICAgKiAoSXQgd2lsbCBiZSByZWdlbmVyYXRlZCBpZiB0aGlzIHJ1biBvZiBkZWZsYXRlIHN3aXRjaGVzIGF3YXkgZnJvbSBIdWZmbWFuLikKICAgKi8KICBjb25zdCBkZWZsYXRlX2h1ZmYgPSAocywgZmx1c2gpID0+IHsKCiAgICBsZXQgYmZsdXNoOyAgICAgICAgICAgICAvKiBzZXQgaWYgY3VycmVudCBibG9jayBtdXN0IGJlIGZsdXNoZWQgKi8KCiAgICBmb3IgKDs7KSB7CiAgICAgIC8qIE1ha2Ugc3VyZSB0aGF0IHdlIGhhdmUgYSBsaXRlcmFsIHRvIHdyaXRlLiAqLwogICAgICBpZiAocy5sb29rYWhlYWQgPT09IDApIHsKICAgICAgICBmaWxsX3dpbmRvdyhzKTsKICAgICAgICBpZiAocy5sb29rYWhlYWQgPT09IDApIHsKICAgICAgICAgIGlmIChmbHVzaCA9PT0gWl9OT19GTFVTSCQyKSB7CiAgICAgICAgICAgIHJldHVybiBCU19ORUVEX01PUkU7CiAgICAgICAgICB9CiAgICAgICAgICBicmVhazsgICAgICAvKiBmbHVzaCB0aGUgY3VycmVudCBibG9jayAqLwogICAgICAgIH0KICAgICAgfQoKICAgICAgLyogT3V0cHV0IGEgbGl0ZXJhbCBieXRlICovCiAgICAgIHMubWF0Y2hfbGVuZ3RoID0gMDsKICAgICAgLy9UcmFjZXZ2KChzdGRlcnIsIiVjIiwgcy0+d2luZG93W3MtPnN0cnN0YXJ0XSkpOwogICAgICAvKioqIF90cl90YWxseV9saXQocywgcy53aW5kb3dbcy5zdHJzdGFydF0sIGJmbHVzaCk7ICoqKi8KICAgICAgYmZsdXNoID0gX3RyX3RhbGx5KHMsIDAsIHMud2luZG93W3Muc3Ryc3RhcnRdKTsKICAgICAgcy5sb29rYWhlYWQtLTsKICAgICAgcy5zdHJzdGFydCsrOwogICAgICBpZiAoYmZsdXNoKSB7CiAgICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAwKTsgKioqLwogICAgICAgIGZsdXNoX2Jsb2NrX29ubHkocywgZmFsc2UpOwogICAgICAgIGlmIChzLnN0cm0uYXZhaWxfb3V0ID09PSAwKSB7CiAgICAgICAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogICAgICAgIH0KICAgICAgICAvKioqLwogICAgICB9CiAgICB9CiAgICBzLmluc2VydCA9IDA7CiAgICBpZiAoZmx1c2ggPT09IFpfRklOSVNIJDMpIHsKICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAxKTsgKioqLwogICAgICBmbHVzaF9ibG9ja19vbmx5KHMsIHRydWUpOwogICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgIHJldHVybiBCU19GSU5JU0hfU1RBUlRFRDsKICAgICAgfQogICAgICAvKioqLwogICAgICByZXR1cm4gQlNfRklOSVNIX0RPTkU7CiAgICB9CiAgICBpZiAocy5sYXN0X2xpdCkgewogICAgICAvKioqIEZMVVNIX0JMT0NLKHMsIDApOyAqKiovCiAgICAgIGZsdXNoX2Jsb2NrX29ubHkocywgZmFsc2UpOwogICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgIHJldHVybiBCU19ORUVEX01PUkU7CiAgICAgIH0KICAgICAgLyoqKi8KICAgIH0KICAgIHJldHVybiBCU19CTE9DS19ET05FOwogIH07CgogIC8qIFZhbHVlcyBmb3IgbWF4X2xhenlfbWF0Y2gsIGdvb2RfbWF0Y2ggYW5kIG1heF9jaGFpbl9sZW5ndGgsIGRlcGVuZGluZyBvbgogICAqIHRoZSBkZXNpcmVkIHBhY2sgbGV2ZWwgKDAuLjkpLiBUaGUgdmFsdWVzIGdpdmVuIGJlbG93IGhhdmUgYmVlbi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iAgICBpZiAocy5zdGF0dXMgPT09IElOSVRfU1RBVEUpIHsKCiAgICAgIGlmIChzLndyYXAgPT09IDIpIHsgLy8gR1pJUCBoZWFkZXIKICAgICAgICBzdHJtLmFkbGVyID0gMDsgIC8vY3JjMzIoMEwsIFpfTlVMTCwgMCk7CiAgICAgICAgcHV0X2J5dGUocywgMzEpOwogICAgICAgIHB1dF9ieXRlKHMsIDEzOSk7CiAgICAgICAgcHV0X2J5dGUocywgOCk7CiAgICAgICAgaWYgKCFzLmd6aGVhZCkgeyAvLyBzLT5nemhlYWQgPT0gWl9OVUxMCiAgICAgICAgICBwdXRfYnl0ZShzLCAwKTsKICAgICAgICAgIHB1dF9ieXRlKHMsIDApOwogICAgICAgICAgcHV0X2J5dGUocywgMCk7CiAgICAgICAgICBwdXRfYnl0ZShzLCAwKTsKICAgICAgICAgIHB1dF9ieXRlKHMsIDApOwogICAgICAgICAgcHV0X2J5dGUocywgcy5sZXZlbCA9PT0gOSA/IDIgOgogICAgICAgICAgICAgICAgICAgICAgKHMuc3RyYXRlZ3kgPj0gWl9IVUZGTUFOX09OTFkgfHwgcy5sZXZlbCA8IDIgPwogICAgICAgICAgICAgICAgICAgICAgIDQgOiAwKSk7CiAgICAgICAgICBwdXRfYnl0ZShzLCBPU19DT0RFKTsKICAgICAgICAgIHMuc3RhdHVzID0gQlVTWV9TVEFURTsKICAgICAgICB9CiAgICAgICAgZWxzZSB7CiAgICAgICAgICBwdXRfYnl0ZShzLCAocy5nemhlYWQudGV4dCA/IDEgOiAwKSArCiAgICAgICAgICAgICAgICAgICAgICAocy5nemhlYWQuaGNyYyA/IDIgOiAwKSArCiAgICAgICAgICAgICAgICAgICAgICAoIXMuZ3poZWFkLmV4dHJhID8gMCA6IDQpICsKICAgICAgICAgICAgICAgICAgICAgICghcy5nemhlYWQubmFtZSA/IDAgOiA4KSArCiAgICAgICAgICAgICAgICAgICAgICAoIXMuZ3poZWFkLmNvbW1lbnQgPyAwIDogMTYpCiAgICAgICAgICApOwogICAgICAgICAgcHV0X2J5dGUocywgcy5nemhlYWQudGltZSAmIDB4ZmYpOwogICAgICAgICAgcHV0X2J5dGUocywgKHMuZ3poZWFkLnRpbWUgPj4gOCkgJiAweGZmKTsKICAgICAgICAgIHB1dF9ieXRlKHMsIChzLmd6aGVhZC50aW1lID4+IDE2KSAmIDB4ZmYpOwogICAgICAgICAgcHV0X2J5dGUocywgKHMuZ3poZWFkLnRpbWUgPj4gMjQpICYgMHhmZik7CiAgICAgICAgICBwdXRfYnl0ZShzLCBzLmxldmVsID09PSA5ID8gMiA6CiAgICAgICAgICAgICAgICAgICAgICAocy5zdHJhdGVneSA+PSBaX0hVRkZNQU5fT05MWSB8fCBzLmxldmVsIDwgMiA/CiAgICAgICAgICAgICAgICAgICAgICAgNCA6IDApKTsKICAgICAgICAgIHB1dF9ieXRlKHMsIHMuZ3poZWFkLm9zICYgMHhmZik7CiAgICAgICAgICBpZiAocy5nemhlYWQuZXh0cmEgJiYgcy5nemhlYWQuZXh0cmEubGVuZ3RoKSB7CiAgICAgICAgICAgIHB1dF9ieXRlKHMsIHMuZ3poZWFkLmV4dHJhLmxlbmd0aCAmIDB4ZmYpOwogICAgICAgICAgICBwdXRfYnl0ZShzLCAocy5nemhlYWQuZXh0cmEubGVuZ3RoID4+IDgpICYgMHhmZik7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAocy5nemhlYWQuaGNyYykgewogICAgICAgICAgICBzdHJtLmFkbGVyID0gY3JjMzJfMShzdHJtLmFkbGVyLCBzLnBlbmRpbmdfYnVmLCBzLnBlbmRpbmcsIDApOwogICAgICAgICAgfQogICAgICAgICAgcy5nemluZGV4ID0gMDsKICAgICAgICAgIHMuc3RhdHVzID0gRVhUUkFfU1RBVEU7CiAgICAgICAgfQogICAgICB9CiAgICAgIGVsc2UgLy8gREVGTEFURSBoZWFkZXIKICAgICAgewogICAgICAgIGxldCBoZWFkZXIgPSAoWl9ERUZMQVRFRCQyICsgKChzLndfYml0cyAtIDgpIDw8IDQpKSA8PCA4OwogICAgICAgIGxldCBsZXZlbF9mbGFncyA9IC0xOwoKICAgICAgICBpZiAocy5zdHJhdGVneSA+PSBaX0hVRkZNQU5fT05MWSB8fCBzLmxldmVsIDwgMikgewogICAgICAgICAgbGV2ZWxfZmxhZ3MgPSAwOwogICAgICAgIH0gZWxzZSBpZiAocy5sZXZlbCA8IDYpIHsKICAgICAgICAgIGxldmVsX2ZsYWdzID0gMTsKICAgICAgICB9IGVsc2UgaWYgKHMubGV2ZWwgPT09IDYpIHsKICAgICAgICAgIGxldmVsX2ZsYWdzID0gMjsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgbGV2ZWxfZmxhZ3MgPSAzOwogICAgICAgIH0KICAgICAgICBoZWFkZXIgfD0gKGxldmVsX2ZsYWdzIDw8IDYpOwogICAgICAgIGlmIChzLnN0cnN0YXJ0ICE9PSAwKSB7IGhlYWRlciB8PSBQUkVTRVRfRElDVDsgfQogICAgICAgIGhlYWRlciArPSAzMSAtIChoZWFkZXIgJSAzMSk7CgogICAgICAgIHMuc3RhdHVzID0gQlVTWV9TVEFURTsKICAgICAgICBwdXRTaG9ydE1TQihzLCBoZWFkZXIpOwoKICAgICAgICAvKiBTYXZlIHRoZSBhZGxlcjMyIG9mIHRoZSBwcmVzZXQgZGljdGlvbmFyeTogKi8KICAgICAgICBpZiAocy5zdHJzdGFydCAhPT0gMCkgewogICAgICAgICAgcHV0U2hvcnRNU0Iocywgc3RybS5hZGxlciA+Pj4gMTYpOwogICAgICAgICAgcHV0U2hvcnRNU0Iocywgc3RybS5hZGxlciAmIDB4ZmZmZik7CiAgICAgICAgfQogICAgICAgIHN0cm0uYWRsZXIgPSAxOyAvLyBhZGxlcjMyKDBMLCBaX05VTEwsIDApOwogICAgICB9CiAgICB9CgogIC8vI2lmZGVmIEdaSVAKICAgIGlmIChzLnN0YXR1cyA9PT0gRVhUUkFfU1RBVEUpIHsKICAgICAgaWYgKHMuZ3poZWFkLmV4dHJhLyogIT0gWl9OVUxMKi8pIHsKICAgICAgICBiZWcgPSBzLnBlbmRpbmc7ICAvKiBzdGFydCBvZiBieXRlcyB0byB1cGRhdGUgY3JjICovCgogICAgICAgIHdoaWxlIChzLmd6aW5kZXggPCAocy5nemhlYWQuZXh0cmEubGVuZ3RoICYgMHhmZmZmKSkgewogICAgICAgICAgaWYgKHMucGVuZGluZyA9PT0gcy5wZW5kaW5nX2J1Zl9zaXplKSB7CiAgICAgICAgICAgIGlmIChzLmd6aGVhZC5oY3JjICYmIHMucGVuZGluZyA+IGJlZykgewogICAgICAgICAgICAgIHN0cm0uYWRsZXIgPSBjcmMzMl8xKHN0cm0uYWRsZXIsIHMucGVuZGluZ19idWYsIHMucGVuZGluZyAtIGJlZywgYmVnKTsKICAgICAgICAgICAgfQogICAgICAgICAgICBmbHVzaF9wZW5kaW5nKHN0cm0pOwogICAgICAgICAgICBiZWcgPSBzLnBlbmRpbmc7CiAgICAgICAgICAgIGlmIChzLnBlbmRpbmcgPT09IHMucGVuZGluZ19idWZfc2l6ZSkgewogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICBwdXRfYnl0ZShzLCBzLmd6aGVhZC5leHRyYVtzLmd6aW5kZXhdICYgMHhmZik7CiAgICAgICAgICBzLmd6aW5kZXgrKzsKICAgICAgICB9CiAgICAgICAgaWYgKHMuZ3poZWFkLmhjcmMgJiYgcy5wZW5kaW5nID4gYmVnKSB7CiAgICAgICAgICBzdHJtLmFkbGVyID0gY3JjMzJfMShzdHJtLmFkbGVyLCBzLnBlbmRpbmdfYnVmLCBzLnBlbmRpbmcgLSBiZWcsIGJlZyk7CiAgICAgICAgfQogICAgICAgIGlmIChzLmd6aW5kZXggPT09IHMuZ3poZWFkLmV4dHJhLmxlbmd0aCkgewogICAgICAgICAgcy5nemluZGV4ID0gMDsKICAgICAgICAgIHMuc3RhdHVzID0gTkFNRV9TVEFURTsKICAgICAgICB9CiAgICAgIH0KICAgICAgZWxzZSB7CiAgICAgICAgcy5zdGF0dXMgPSBOQU1FX1NUQVRFOwogICAgICB9CiAgICB9CiAgICBpZiAocy5zdGF0dXMgPT09IE5BTUVfU1RBVEUpIHsKICAgICAgaWYgKHMuZ3poZWFkLm5hbWUvKiAhPSBaX05VTEwqLykgewogICAgICAgIGJlZyA9IHMucGVuZGluZzsgIC8qIHN0YXJ0IG9mIGJ5dGVzIHRvIHVwZGF0ZSBjcmMgKi8KICAgICAgICAvL2ludCB2YWw7CgogICAgICAgIGRvIHsKICAgICAgICAgIGlmIChzLnBlbmRpbmcgPT09IHMucGVuZGluZ19idWZfc2l6ZSkgewogICAgICAgICAgICBpZiAocy5nemhlYWQuaGNyYyAmJiBzLnBlbmRpbmcgPiBiZWcpIHsKICAgICAgICAgICAgICBzdHJtLmFkbGVyID0gY3JjMzJfMShzdHJtLmFkbGVyLCBzLnBlbmRpbmdfYnVmLCBzLnBlbmRpbmcgLSBiZWcsIGJlZyk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZmx1c2hfcGVuZGluZyhzdHJtKTsKICAgICAgICAgICAgYmVnID0gcy5wZW5kaW5nOwogICAgICAgICAgICBpZiAocy5wZW5kaW5nID09PSBzLnBlbmRpbmdfYnVmX3NpemUpIHsKICAgICAgICAgICAgICB2YWwgPSAxOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICAvLyBKUyBzcGVjaWZpYzogbGl0dGxlIG1hZ2ljIHRvIGFkZCB6ZXJvIHRlcm1pbmF0b3IgdG8gZW5kIG9mIHN0cmluZwogICAgICAgICAgaWYgKHMuZ3ppbmRleCA8IHMuZ3poZWFkLm5hbWUubGVuZ3RoKSB7CiAgICAgICAgICAgIHZhbCA9IHMuZ3poZWFkLm5hbWUuY2hhckNvZGVBdChzLmd6aW5kZXgrKykgJiAweGZmOwogICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgdmFsID0gMDsKICAgICAgICAgIH0KICAgICAgICAgIHB1dF9ieXRlKHMsIHZhbCk7CiAgICAgICAgfSB3aGlsZSAodmFsICE9PSAwKTsKCiAgICAgICAgaWYgKHMuZ3poZWFkLmhjcmMgJiYgcy5wZW5kaW5nID4gYmVnKSB7CiAgICAgICAgICBzdHJtLmFkbGVyID0gY3JjMzJfMShzdHJtLmFkbGVyLCBzLnBlbmRpbmdfYnVmLCBzLnBlbmRpbmcgLSBiZWcsIGJlZyk7CiAgICAgICAgfQogICAgICAgIGlmICh2YWwgPT09IDApIHsKICAgICAgICAgIHMuZ3ppbmRleCA9IDA7CiAgICAgICAgICBzLnN0YXR1cyA9IENPTU1FTlRfU1RBVEU7CiAgICAgICAgfQogICAgICB9CiAgICAgIGVsc2UgewogICAgICAgIHMuc3RhdHVzID0gQ09NTUVOVF9TVEFURTsKICAgICAgfQogICAgfQogICAgaWYgKHMuc3RhdHVzID09PSBDT01NRU5UX1NUQVRFKSB7CiAgICAgIGlmIChzLmd6aGVhZC5jb21tZW50LyogIT0gWl9OVUxMKi8pIHsKICAgICAgICBiZWcgPSBzLnBlbmRpbmc7ICAvKiBzdGFydCBvZiBieXRlcyB0byB1cGRhdGUgY3JjICovCiAgICAgICAgLy9pbnQgdmFsOwoKICAgICAgICBkbyB7CiAgICAgICAgICBpZiAocy5wZW5kaW5nID09PSBzLnBlbmRpbmdfYnVmX3NpemUpIHsKICAgICAgICAgICAgaWYgKHMuZ3poZWFkLmhjcmMgJiYgcy5wZW5kaW5nID4gYmVnKSB7CiAgICAgICAgICAgICAgc3RybS5hZGxlciA9IGNyYzMyXzEoc3RybS5hZGxlciwgcy5wZW5kaW5nX2J1Ziwgcy5wZW5kaW5nIC0gYmVnLCBiZWcpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGZsdXNoX3BlbmRpbmcoc3RybSk7CiAgICAgICAgICAgIGJlZyA9IHMucGVuZGluZzsKICAgICAgICAgICAgaWYgKHMucGVuZGluZyA9PT0gcy5wZW5kaW5nX2J1Zl9zaXplKSB7CiAgICAgICAgICAgICAgdmFsID0gMTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgICAgLy8gSlMgc3BlY2lmaWM6IGxpdHRsZSBtYWdpYyB0byBhZGQgemVybyB0ZXJtaW5hdG9yIHRvIGVuZCBvZiBzdHJpbmcKICAgICAgICAgIGlmIChzLmd6aW5kZXggPCBzLmd6aGVhZC5jb21tZW50Lmxlbmd0aCkgewogICAgICAgICAgICB2YWwgPSBzLmd6aGVhZC5jb21tZW50LmNoYXJDb2RlQXQocy5nemluZGV4KyspICYgMHhmZjsKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIHZhbCA9IDA7CiAgICAgICAgICB9CiAgICAgICAgICBwdXRfYnl0ZShzLCB2YWwpOwogICAgICAgIH0gd2hpbGUgKHZhbCAhPT0gMCk7CgogICAgICAgIGlmIChzLmd6aGVhZC5oY3JjICYmIHMucGVuZGluZyA+IGJlZykgewogICAgICAgICAgc3RybS5hZGxlciA9IGNyYzMyXzEoc3RybS5hZGxlciwgcy5wZW5kaW5nX2J1Ziwgcy5wZW5kaW5nIC0gYmVnLCBiZWcpOwogICAgICAgIH0KICAgICAgICBpZiAodmFsID09PSAwKSB7CiAgICAgICAgICBzLnN0YXR1cyA9IEhDUkNfU1RBVEU7CiAgICAgICAgfQogICAgICB9CiAgICAgIGVsc2UgewogICAgICAgIHMuc3RhdHVzID0gSENSQ19TVEFURTsKICAgICAgfQogICAgfQogICAgaWYgKHMuc3RhdHVzID09PSBIQ1JDX1NUQVRFKSB7CiAgICAgIGlmIChzLmd6aGVhZC5oY3JjKSB7CiAgICAgICAgaWYgKHMucGVuZGluZyArIDIgPiBzLnBlbmRpbmdfYnVmX3NpemUpIHsKICAgICAgICAgIGZsdXNoX3BlbmRpbmcoc3RybSk7CiAgICAgICAgfQogICAgICAgIGlmIChzLnBlbmRpbmcgKyAyIDw9IHMucGVuZGluZ19idWZfc2l6ZSkgewogICAgICAg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CkgewogICAgICAgICAgX3RyX2FsaWduKHMpOwogICAgICAgIH0KICAgICAgICBlbHNlIGlmIChmbHVzaCAhPT0gWl9CTE9DSyQxKSB7IC8qIEZVTExfRkxVU0ggb3IgU1lOQ19GTFVTSCAqLwoKICAgICAgICAgIF90cl9zdG9yZWRfYmxvY2socywgMCwgMCwgZmFsc2UpOwogICAgICAgICAgLyogRm9yIGEgZnVsbCBmbHVzaCwgdGhpcyBlbXB0eSBibG9jayB3aWxsIGJlIHJlY29nbml6ZWQKICAgICAgICAgICAqIGFzIGEgc3BlY2lhbCBtYXJrZXIgYnkgaW5mbGF0ZV9zeW5jKCkuCiAgICAgICAgICAgKi8KICAgICAgICAgIGlmIChmbHVzaCA9PT0gWl9GVUxMX0ZMVVNIJDEpIHsKICAgICAgICAgICAgLyoqKiBDTEVBUl9IQVNIKHMpOyAqKiovICAgICAgICAgICAgIC8qIGZvcmdldCBoaXN0b3J5ICovCiAgICAgICAgICAgIHplcm8ocy5oZWFkKTsgLy8gRmlsbCB3aXRoIE5JTCAoPSAwKTsKCiAgICAgICAgICAgIGlmIChzLmxvb2thaGVhZCA9PT0gMCkgewogICAgICAgICAgICAgIHMuc3Ryc3RhcnQgPSAwOwogICAgICAgICAgICAgIHMuYmxvY2tfc3RhcnQgPSAwOwogICAgICAgICAgICAgIHMuaW5zZXJ0ID0gMDsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBmbHVzaF9wZW5kaW5nKHN0cm0pOwogICAgICAgIGlmIChzdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgICAgcy5sYXN0X2ZsdXNoID0gLTE7IC8qIGF2b2lkIEJVRl9FUlJPUiBhdCBuZXh0IGNhbGwsIHNlZSBhYm92ZSAqLwogICAgICAgICAgcmV0dXJuIFpfT0skMzsKICAgICAgICB9CiAgICAgIH0KICAgIH0KICAgIC8vQXNzZXJ0KHN0cm0tPmF2YWlsX291dCA+IDAsICJidWcyIik7CiAgICAvL2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MDApIHsKICAgICAgICAgIGMgPSAweDEwMDAwICsgKChjIC0gMHhkODAwKSA8PCAxMCkgKyAoYzIgLSAweGRjMDApOwogICAgICAgICAgbV9wb3MrKzsKICAgICAgICB9CiAgICAgIH0KICAgICAgYnVmX2xlbiArPSBjIDwgMHg4MCA/IDEgOiBjIDwgMHg4MDAgPyAyIDogYyA8IDB4MTAwMDAgPyAzIDogNDsKICAgIH0KCiAgICAvLyBhbGxvY2F0ZSBidWZmZXIKICAgIGJ1ZiA9IG5ldyBVaW50OEFycmF5KGJ1Zl9sZW4pOwoKICAgIC8vIGNvbnZlcnQKICAgIGZvciAoaSA9IDAsIG1fcG9zID0gMDsgaSA8IGJ1Zl9sZW47IG1fcG9zKyspIHsKICAgICAgYyA9IHN0ci5jaGFyQ29kZUF0KG1fcG9zKTsKICAgICAgaWYgKChjICYgMHhmYzAwKSA9PT0gMHhkODAwICYmIChtX3BvcyArIDEgPCBzdHJfbGVuKSkgewogICAgICAgIGMyID0gc3RyLmNoYXJDb2RlQXQobV9wb3MgKyAxKTsKICAgICAgICBpZiAoKGMyICYgMHhmYzAwKSA9PT0gMHhkYzAwKSB7CiAgICAgICAgICBjID0gMHgxMDAwMCArICgoYyAtIDB4ZDgwMCkgPDwgMTApICsgKGMyIC0gMHhkYzAwKTsKICAgICAgICAgIG1fcG9zKys7CiAgICAgICAgfQogICAgICB9CiAgICAgIGlmIChjIDwgMHg4MCkgewogICAgICAgIC8qIG9uZSBieXRlICovCiAgICAgICAgYnVmW2krK10gPSBjOwogICAgICB9IGVsc2UgaWYgKGMgPCAweDgwMCkgewogICAgICAgIC8qIHR3byBieXRlcyAqLwogICAgICAgIGJ1ZltpKytdID0gMHhDMCB8IChjID4+PiA2KTsKICAgICAgICBidWZbaSsrXSA9IDB4ODAgfCAoYyAmIDB4M2YpOwogICAgICB9IGVsc2UgaWYgKGMgPCAweDEwMDAwKSB7CiAgICAgICAgLyogdGhyZWUgYnl0ZXMgKi8KICAgICAgICBidWZbaSs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c3MgYWJvdXQgdGhlIGRhdGEgdHlwZTogYmluYXJ5IG9yIHRleHQgKi8KICAgIHRoaXMuZGF0YV90eXBlID0gMi8qWl9VTktOT1dOKi87CiAgICAvKiBhZGxlcjMyIHZhbHVlIG9mIHRoZSB1bmNvbXByZXNzZWQgZGF0YSAqLwogICAgdGhpcy5hZGxlciA9IDA7CiAgfQoKICB2YXIgenN0cmVhbSA9IFpTdHJlYW07CgogIGNvbnN0IHRvU3RyaW5nJDEgPSBPYmplY3QucHJvdG90eXBlLnRvU3RyaW5nOwoKICAvKiBQdWJsaWMgY29uc3RhbnRzID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSovCgogIGNvbnN0IHsKICAgIFpfTk9fRkxVU0g6IFpfTk9fRkxVU0gkMSwgWl9TWU5DX0ZMVVNILCBaX0ZVTExfRkxVU0gsIFpfRklOSVNIOiBaX0ZJTklTSCQyLAogICAgWl9PSzogWl9PSyQyLCBaX1NUUkVBTV9FTkQ6IFpfU1RSRUFNX0VORCQyLAogICAgWl9ERUZBVUxUX0NPTVBSRVNTSU9OLAogICAgWl9ERUZBVUxUX1NUUkFURUdZLAogICAgWl9ERUZMQVRFRDogWl9ERUZMQVRFRCQxCiAgfSA9IGNvbnN0YW50cyQyOwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwoKCiAgLyoqCiAgICogY2xhc3MgRGVmbGF0ZQogICAqCiAgICogR2VuZXJpYyBKUy1zdHlsZSB3cmFwcGVyIGZvciB6bGliIGNhbGxzLiBJZiB5b3UgZG9uJ3QgbmVlZAogICAqIHN0cmVhbWluZyBiZWhhdmlvdXIgLSB1c2UgbW9yZSBzaW1wbGUgZn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ICBtZXRob2Q6IFpfREVGTEFURUQkMSwKICAgICAgY2h1bmtTaXplOiAxNjM4NCwKICAgICAgd2luZG93Qml0czogMTUsCiAgICAgIG1lbUxldmVsOiA4LAogICAgICBzdHJhdGVneTogWl9ERUZBVUxUX1NUUkFURUdZCiAgICB9LCBvcHRpb25zIHx8IHt9KTsKCiAgICBsZXQgb3B0ID0gdGhpcy5vcHRpb25zOwoKICAgIGlmIChvcHQucmF3ICYmIChvcHQud2luZG93Qml0cyA+IDApKSB7CiAgICAgIG9wdC53aW5kb3dCaXRzID0gLW9wdC53aW5kb3dCaXRzOwogICAgfQoKICAgIGVsc2UgaWYgKG9wdC5nemlwICYmIChvcHQud2luZG93Qml0cyA+IDApICYmIChvcHQud2luZG93Qml0cyA8IDE2KSkgewogICAgICBvcHQud2luZG93Qml0cyArPSAxNjsKICAgIH0KCiAgICB0aGlzLmVyciAgICA9IDA7ICAgICAgLy8gZXJyb3IgY29kZSwgaWYgaGFwcGVucyAoMCA9IFpfT0spCiAgICB0aGlzLm1zZyAgICA9ICcnOyAgICAgLy8gZXJyb3IgbWVzc2FnZQogICAgdGhpcy5lbmRlZCAgPSBmYWxzZTsgIC8vIHVzZWQgdG8gYXZvaWQgbXVsdGlwbGUgb25FbmQoKSBjYWxscwogICAgdGhpcy5jaHVua3MgPSBbXTsgICAgIC8vIGNodW5rcyBvZiBjb21wcmVzc2VkIGRhdGEKCiAgICB0aGlzLnN0cm0gPSBuZXcgenN0cmVhbSgpOwogICAgdGhpcy5zdHJtLmF2YWlsX291dCA9IDA7CgogICAgbGV0IHN0YXR1cyA9IGRlZmxhdGVfMSQyLmRlZmxhdGVJbml0MigKICAgICAgdGhpcy5zdHJtLAogICAgICBvcHQubGV2ZWwsCiAgICAgIG9wdC5tZXRob2QsCiAgICAgIG9wdC53aW5kb3dCaXRzLAogICAgICBvcHQubWVtTGV2ZWwsCiAgICAgIG9wdC5zdHJhdGVneQogICAgKTsKCiAgICBpZiAoc3RhdHVzICE9PSBa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gICAgICAgIC8qIGxvY2FsIHN0cm0ub3V0cHV0ICovCiAgICBsZXQgYmVnOyAgICAgICAgICAgICAgICAgICAgLyogaW5mbGF0ZSgpJ3MgaW5pdGlhbCBzdHJtLm91dHB1dCAqLwogICAgbGV0IGVuZDsgICAgICAgICAgICAgICAgICAgIC8qIHdoaWxlIG91dCA8IGVuZCwgZW5vdWdoIHNwYWNlIGF2YWlsYWJsZSAqLwogIC8vI2lmZGVmIElORkxBVEVfU1RSSUNUCiAgICBsZXQgZG1heDsgICAgICAgICAgICAgICAgICAgLyogbWF4aW11bSBkaXN0YW5jZSBmcm9tIHpsaWIgaGVhZGVyICovCiAgLy8jZW5kaWYKICAgIGxldCB3c2l6ZTsgICAgICAgICAgICAgICAgICAvKiB3aW5kb3cgc2l6ZSBvciB6ZXJvIGlmIG5vdCB1c2luZyB3aW5kb3cgKi8KICAgIGxldCB3aGF2ZTsgICAgICAgICAgICAgICAgICAvKiB2YWxpZCBieXRlcyBpbiB0aGUgd2luZG93ICovCiAgICBsZXQgd25leHQ7ICAgICAgICAgICAgICAgICAgLyogd2luZG93IHdyaXRlIGluZGV4ICovCiAgICAvLyBVc2UgYHNfd2luZG93YCBpbnN0ZWFkIGB3aW5kb3dgLCBhdm9pZCBjb25mbGljdCB3aXRoIGluc3RydW1lbnRhdGlvbiB0b29scwogICAgbGV0IHNfd2luZG93OyAgICAgICAgICAgICAgIC8qIGFsbG9jYXRlZCBzbGlkaW5nIHdpbmRvdywgaWYgd3NpemUgIT0gMCAqLwogICAgbGV0IGhvbGQ7ICAgICAgICAgICAgICAgICAgIC8qIGxvY2FsIHN0cm0uaG9sZCAqLwogICAgbGV0IGJpdHM7ICAgICAgICAgICAgICAgICAgIC8qIGxvY2FsIHN0cm0uYml0cyAqLwogICAgbGV0IGxjb2RlOyAgICAgICAgICAgICAgICAgIC8qIGxvY2FsIHN0cm0ubGVuY29kZSAqLwogICAgbGV0IGRjb2RlOyAgICAgICAgICAgICAgICAgIC8qIGxvY2FsIHN0cm0uZGlzdGNvZGUgKi8KICAgIGxldCBsbWFzazsgICAgICAgICAgICAgICAgICAvKiBtYXNrIGZvciBmaXJzdCBsZXZlbCBvZiBsZW5ndGggY29kZXMgKi8KICAgIGxldCBkbWFzazsgICAgICAgICAgICAgICAgICAvKiBtYXNrIGZvciBmaXJzdCBsZXZlbCBvZiBkaXN0YW5jZSBjb2RlcyAqLwogICAgbGV0IGhlcmU7ICAgICAgICAgICAgICAgICAgIC8qIHJldHJpZXZlZCB0YWJsZSBlbnRyeSAqLwogICAgbGV0IG9wOyAgICAgICAgICAgICAgICAgICAgIC8qIGNvZGUgYml0cywgb3BlcmF0aW9uLCBleHRyYSBiaXRzLCBvciAqLwogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8qICB3aW5kb3cgcG9zaXRpb24sIHdpbmRvdyBieXRlcyB0byBjb3B5ICovCiAgICBsZXQgbGVuOyAgICAgICAgICAgICAgICAgICAgLyogbWF0Y2ggbGVuZ3RoLCB1bnVzZWQgYnl0ZXMgKi8KICAgIGxldCBkaXN0OyAgICAgICAgICAgICAgICAgICAvKiBtYXRjaCBkaXN0YW5jZSAqLwogICAgbGV0IGZyb207ICAgICAgICAgICAgICAgICAgIC8qIHdoZXJlIHRvIGNvcHkgbWF0Y2ggZnJvbSAqLwogICAgbGV0IGZyb21fc291cmNlOwoKCiAgICBsZXQgaW5wdXQsIG91dHB1dDsgLy8gSlMgc3BlY2lmaWMsIGJlY2F1c2Ugd2UgaGF2ZSBubyBwb2ludGVycwoKICAgIC8qIGNvcHkgc3RhdGUgdG8gbG9jYWwgdmFyaWFibGVzICovCiAgICBjb25zdCBzdGF0ZSA9IHN0cm0uc3RhdGU7CiAgICAvL2hlcmUgPSBzdGF0ZS5oZXJlOwogICAgX2luID0gc3RybS5uZXh0X2luOwogICAgaW5wdXQgPSBzdHJtLmlucHV0OwogICAgbGFzdCA9IF9pbiArIChzdHJtLmF2YWlsX2luIC0gNSk7CiAgICBfb3V0ID0gc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CA9IGhlcmUgPj4+IDI0LypoZXJlLmJpdHMqLzsKICAgICAgICBob2xkID4+Pj0gb3A7CiAgICAgICAgYml0cyAtPSBvcDsKICAgICAgICBvcCA9IChoZXJlID4+PiAxNikgJiAweGZmLypoZXJlLm9wKi87CiAgICAgICAgaWYgKG9wID09PSAwKSB7ICAgICAgICAgICAgICAgICAgICAgICAgICAvKiBsaXRlcmFsICovCiAgICAgICAgICAvL1RyYWNldnYoKHN0ZGVyciwgaGVyZS52YWwgPj0gMHgyMCAmJiBoZXJlLnZhbCA8IDB4N2YgPwogICAgICAgICAgLy8gICAgICAgICJpbmZsYXRlOiAgICAgICAgIGxpdGVyYWwgJyVjJ1xuIiA6CiAgICAgICAgICAvLyAgICAgICAgImluZmxhdGU6ICAgICAgICAgbGl0ZXJhbCAweCUwMnhcbiIsIGhlcmUudmFsKSk7CiAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IGhlcmUgJiAweGZmZmYvKmhlcmUudmFsKi87CiAgICAgICAgfQogICAgICAgIGVsc2UgaWYgKG9wICYgMTYpIHsgICAgICAgICAgICAgICAgICAgICAvKiBsZW5ndGggYmFzZSAqLwogICAgICAgICAgbGVuID0gaGVyZSAmIDB4ZmZmZi8qaGVyZS52YWwqLzsKICAgICAgICAgIG9wICY9IDE1OyAgICAgICAgICAgICAgICAgICAgICAgICAgIC8qIG51bWJlciBvZiBleHRyYSBiaXRzICovCiAgICAgICAgICBpZiAob3ApIHsKICAgICAgICAgICAgaWYgKGJpdHMgPCBvcCkgewogICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbX2luKytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICB9CiAgICAgICAgICAgIGxlbiArPSBob2xkICYgKCgxIDw8IG9wKSAtIDEpOwogICAgICAgICAgICBob2xkID4+Pj0gb3A7CiAgICAgICAgICAgIGJpdHMgLT0gb3A7CiAgICAgICAgICB9CiAgICAgICAgICAvL1RyYWNldnYoKHN0ZGVyciwgImluZmxhdGU6ICAgICAgICAgbGVuZ3RoICV1XG4iLCBsZW4pKTsKICAgICAgICAgIGlmIChiaXRzIDwgMTUpIHsKICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtfaW4rK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICBob2xkICs9IGlucHV0W19pbisrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICB9CiAgICAgICAgICBoZXJlID0gZGNvZGVbaG9sZCAmIGRtYXNrXTsKCiAgICAgICAgICBkb2Rpc3Q6CiAgICAgICAgICBmb3IgKDs7KSB7IC8vIGdvdG8gZW11bGF0aW9uCiAgICAgICAgICAgIG9wID0gaGVyZSA+Pj4gMjQvKmhlcmUuYml0cyovOwogICAgICAgICAgICBob2xkID4+Pj0gb3A7CiAgICAgICAgICAgIGJpdHMgLT0gb3A7CiAgICAgICAgICAgIG9wID0gKGhlcmUgPj4+IDE2KSAmIDB4ZmYvKmhlcmUub3AqLzsKCiAgICAgICAgICAgIGlmIChvcCAmIDE2KSB7ICAgICAgICAgICAgICAgICAgICAgIC8qIGRpc3RhbmNlIGJhc2UgKi8KICAgICAgICAgICAgICBkaXN0ID0gaGVyZSAmIDB4ZmZmZi8qaGVyZS52YWwqLzsKICAgICAgICAgICAgICBvcCAmPSAxNTsgICAgICAgICAgICAgICAgICAgICAgIC8qIG51bWJlciBvZiBleHRyYSBiaXRzICovCiAgICAgICAgICAgICAgaWYgKGJpdHMgPCBvcCkgewogICAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtfaW4rK10gPDwgYml0czsKICAgICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgICAgIGlmIChiaXRzIDwgb3ApIHsKICAgICAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtfaW4rK10gPDwgYml0czsKICAgICAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBkaXN0ICs9IGhvbGQgJiAoKDEgPDwgb3ApIC0gMSk7CiAgLy8jaWZkZWYgSU5GTEFURV9TVFJJQ1QKICAgICAgICAgICAgICBpZiAoZGlzdCA+IGRtYXgpIHsKICAgICAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgZGlzdGFuY2UgdG9vIGZhciBiYWNrJzsKICAgICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQkMTsKICAgICAgICAgICAgICAgIGJyZWFrIHRvcDsKICAgICAgICAgICAgICB9CiAgLy8jZW5kaWYKICAgICAgICAgICAgICBob2xkID4+Pj0gb3A7CiAgICAgICAgICAgICAgYml0cyAtPSBvcDsKICAgICAgICAgICAgICAvL1RyYWNldnYoKHN0ZGVyciwgImluZmxhdGU6ICAgICAgICAgZGlzdGFuY2UgJXVcbiIsIGRpc3QpKTsKICAgICAgICAgICAgICBvcCA9IF9vdXQgLSBiZWc7ICAgICAgICAgICAgICAgIC8qIG1heCBkaXN0YW5jZSBpbiBvdXRwdXQgKi8KICAgICAgICAgICAgICBpZiAoZGlzdCA+IG9wKSB7ICAgICAgICAgICAgICAgIC8qIHNlZSBpZiBjb3B5IGZyb20gd2luZG93ICovCiAgICAgICAgICAgICAgICBvcCA9IGRpc3QgLSBvcDsgICAgICAgICAgICAgICAvKiBkaXN0YW5jZSBiYWNrIGluIHdpbmRvdyAqLwogICAgICAgICAgICAgICAgaWYgKG9wID4gd2hhdmUpIHsKICAgICAgICAgICAgICAgICAgaWYgKHN0YXRlLnNhbmUpIHsKICAgICAgICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGRpc3RhbmNlIHRvbyBmYXIgYmFjayc7CiAgICAgICAgICAgICAgICAgICAgc3RhdGUubW9kZSA9IEJBRCQxOwogICAgICAgICAgICAgICAgICAgIGJyZWFrIHRvcDsKICAgICAgICAgICAgICAgICAgfQoKICAvLyAoISkgVGhpcyBibG9jayBpcyBkaXNhYmxlZCBpbiB6bGliIGRlZmF1bHRzLAogIC8vIGRvbid0IGVuYWJsZSBpdCBmb3IgYmluYXJ5IGNvbXBhdGliaWxpdHkKICAvLyNpZmRlZiBJTkZMQVRFX0FMTE9XX0lOVkFMSURfRElTVEFOQ0VfVE9PRkFSX0FSUlIKICAvLyAgICAgICAgICAgICAgICBpZiAobGVuIDw9IG9wIC0gd2hhdmUpIHsKICAvLyAgICAgICAgICAgICAgICAgIGRvIHsKICAvLyAgICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSAwOwogIC8vICAgICAgICAgICAgICAgICAgfSB3aGlsZSAoLS1sZW4pOwogIC8vICAgICAgICAgICAgICAgICAgY29udGludWUgdG9wOwogIC8vICAgICAgICAgICAgICAgIH0KICAvLyAgICAgICAgICAgICAgICBsZW4gLT0gb3AgLSB3aGF2ZTsKICAvLyAgICAgICAgICAgICAgICBkbyB7CiAgLy8gICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IDA7CiAgLy8gICAgICAgICAgICAgICAgfSB3aGlsZSAoLS1vcCA+IHdoYXZlKTsKICAvLyAgICAgICAgICAgICAgICBpZiAob3AgPT09IDApIHsKICAvLyAgICAgICAgICAgICAgICAgIGZyb20gPSBfb3V0IC0gZGlzdDsKICAvLyAgICAgICAgICAgICAgICAgIGRvIHsKICAvLyAgICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAvLyAgICAgICAgICAgICAgICAgIH0gd2hpbGUgKC0tbGVuKTsKICAvLyAgICAgICAgICAgICAgICAgIGNvbnRpbnVlIHRvcDsKICAvLyAgICAgICAgICAgICAgICB9CiAgLy8jZW5kaWYKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGZyb20gPSAwOyAvLyB3aW5kb3cgaW5kZXgKICAgICAgICAgICAgICAgIGZyb21fc291cmNlID0gc193aW5kb3c7CiAgICAgICAgICAgICAgICBpZiAod25leHQgPT09IDApIHsgICAgICAgICAgIC8qIHZlcnkgY29tbW9uIGNhc2UgKi8KICAgICAgICAgICAgICAgICAgZnJvbSArPSB3c2l6ZSAtIG9wOwogICAgICAgICAgICAgICAgICBpZiAob3AgPCBsZW4pIHsgICAgICAgICAvKiBzb21lIGZyb20gd2luZG93ICovCiAgICAgICAgICAgICAgICAgICAgbGVuIC09IG9wOwogICAgICAgICAgICAgICAgICAgIGRvIHsKICAgICAgICAgICAgICAgICAgICAgIG91dHB1dFtfb3V0KytdID0gc193aW5kb3dbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgICB9IHdoaWxlICgtLW9wKTsKICAgICAgICAgICAgICAgICAgICBmcm9tID0gX291dCAtIGRpc3Q7ICAvKiByZXN0IGZyb20gb3V0cHV0ICovCiAgICAgICAgICAgICAgICAgICAgZnJvbV9zb3VyY2UgPSBvdXRwdXQ7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGVsc2UgaWYgKHduZXh0IDwgb3ApIHsgICAgICAvKiB3cmFwIGFyb3VuZCB3aW5kb3cgKi8KICAgICAgICAgICAgICAgICAgZnJvbSArPSB3c2l6ZSArIHduZXh0IC0gb3A7CiAgICAgICAgICAgICAgICAgIG9wIC09IHduZXh0OwogICAgICAgICAgICAgICAgICBpZiAob3AgPCBsZW4pIHsgICAgICAgICAvKiBzb21lIGZyb20gZW5kIG9mIHdpbmRvdyAqLwogICAgICAgICAgICAgICAgICAgIGxlbiAtPSBvcDsKICAgICAgICAgICAgICAgICAgICBkbyB7CiAgICAgICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IHNfd2luZG93W2Zyb20rK107CiAgICAgICAgICAgICAgICAgICAgfSB3aGlsZSAoLS1vcCk7CiAgICAgICAgICAgICAgICAgICAgZnJvbSA9IDA7CiAgICAgICAgICAgICAgICAgICAgaWYgKHduZXh0IDwgbGVuKSB7ICAvKiBzb21lIGZyb20gc3RhcnQgb2Ygd2luZG93ICovCiAgICAgICAgICAgICAgICAgICAgICBvcCA9IHduZXh0OwogICAgICAgICAgICAgICAgICAgICAgbGVuIC09IG9wOwogICAgICAgICAgICAgICAgICAgICAgZG8gewogICAgICAgICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IHNfd2luZG93W2Zyb20rK107CiAgICAgICAgICAgICAgICAgICAgICB9IHdoaWxlICgtLW9wKTsKICAgICAgICAgICAgICAgICAgICAgIGZyb20gPSBfb3V0IC0gZGlzdDsgICAgICAvKiByZXN0IGZyb20gb3V0cHV0ICovCiAgICAgICAgICAgICAgICAgICAgICBmcm9tX3NvdXJjZSA9IG91dHB1dDsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGVsc2UgeyAgICAgICAgICAgICAgICAgICAgICAvKiBjb250aWd1b3VzIGluIHdpbmRvdyAqLwogICAgICAgICAgICAgICAgICBmcm9tICs9IHduZXh0IC0gb3A7CiAgICAgICAgICAgICAgICAgIGlmIChvcCA8IGxlbikgeyAgICAgICAgIC8qIHNvbWUgZnJvbSB3aW5kb3cgKi8KICAgICAgICAgICAgICAgICAgICBsZW4gLT0gb3A7CiAgICAgICAgICAgICAgICAgICAgZG8gewogICAgICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBzX3dpbmRvd1tmcm9tKytdOwogICAgICAgICAgICAgICAgICAgIH0gd2hpbGUgKC0tb3ApOwogICAgICAgICAgICAgICAgICAgIGZyb20gPSBfb3V0IC0gZGlzdDsgIC8qIHJlc3QgZnJvbSBvdXRwdXQgKi8KICAgICAgICAgICAgICAgICAgICBmcm9tX3NvdXJjZSA9IG91dHB1dDsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgd2hpbGUgKGxlbiA+IDIpIHsKICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBmcm9tX3NvdXJjZVtmcm9tKytdOwogICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IGZyb21fc291cmNlW2Zyb20rK107CiAgICAgICAgICAgICAgICAgIG91dHB1dFtfb3V0KytdID0gZnJvbV9zb3VyY2VbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgbGVuIC09IDM7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBpZiAobGVuKSB7CiAgICAgICAgICAgICAgICAgIG91dHB1dFtfb3V0KytdID0gZnJvbV9zb3VyY2VbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgaWYgKGxlbiA+IDEpIHsKICAgICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IGZyb21fc291cmNlW2Zyb20rK107CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICBmcm9tID0gX291dCAtIGRpc3Q7ICAgICAgICAgIC8qIGNvcHkgZGlyZWN0IGZyb20gb3V0cHV0ICovCiAgICAgICAgICAgICAgICBkbyB7ICAgICAgICAgICAgICAgICAgICAgICAgLyogbWluaW11bSBsZW5ndGggaXMgdGhyZWUgKi8KICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgbGVuIC09IDM7CiAgICAgICAgICAgICAgICB9IHdoaWxlIChsZW4gPiAyKTsKICAgICAgICAgICAgICAgIGlmIChsZW4pIHsKICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgaWYgKGxlbiA+IDEpIHsKICAgICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IG91dHB1dFtmcm9tKytdOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgaWYgKChvcCAmIDY0KSA9PT0gMCkgeyAgICAgICAgICAvKiAybmQgbGV2ZWwgZGlzdGFuY2UgY29kZSAqLwogICAgICAgICAgICAgIGhlcmUgPSBkY29kZVsoaGVyZSAmIDB4ZmZmZikvKmhlcmUudmFsKi8gKyAoaG9sZCAmICgoMSA8PCBvcCkgLSAxKSldOwogICAgICAgICAgICAgIGNvbnRpbnVlIGRvZGlzdDsKICAgICAgICAgICAgfQogICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGRpc3RhbmNlIGNvZGUnOwogICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQkMTsKICAgICAgICAgICAgICBicmVhayB0b3A7CiAgICAgICAgICAgIH0KCiAgICAgICAgICAgIGJyZWFrOyAvLyBuZWVkIHRvIGVtdWxhdGUgZ290byB2aWEgImNvbnRpbnVlIgogICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBlbHNlIGlmICgob3AgJiA2NCkgPT09IDApIHsgICAgICAgICAgICAgIC8qIDJuZCBsZXZlbCBsZW5ndGggY29kZSAqLwogICAgICAgICAgaGVyZSA9IGxjb2RlWyhoZXJlICYgMHhmZmZmKS8qaGVyZS52YWwqLyArIChob2xkICYgKCgxIDw8IG9wKSAtIDEpKV07CiAgICAgICAgICBjb250aW51ZSBkb2xlbjsKICAgICAgICB9CiAgICAgICAgZWxzZSBpZiAob3AgJiAzMikgeyAgICAgICAgICAgICAgICAgICAgIC8qIGVuZC1vZi1ibG9jayAqLwogICAgICAgICAgLy9UcmFjZXZ2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgICAgIGVuZCBvZiBibG9ja1xuIikp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iBudW1iZXIgb2YgaW5kZXggYml0cyBmb3IgY3VycmVudCB0YWJsZSAqLwogICAgbGV0IGRyb3AgPSAwOyAgICAgICAgICAgICAgLyogY29kZSBiaXRzIHRvIGRyb3AgZm9yIHN1Yi10YWJsZSAqLwogICAgbGV0IGxlZnQgPSAwOyAgICAgICAgICAgICAgICAgICAvKiBudW1iZXIgb2YgcHJlZml4IGNvZGVzIGF2YWlsYWJsZSAqLwogICAgbGV0IHVzZWQgPSAwOyAgICAgICAgICAgICAgLyogY29kZSBlbnRyaWVzIGluIHRhYmxlIHVzZWQgKi8KICAgIGxldCBodWZmID0gMDsgICAgICAgICAgICAgIC8qIEh1ZmZtYW4gY29kZSAqLwogICAgbGV0IGluY3I7ICAgICAgICAgICAgICAvKiBmb3IgaW5jcmVtZW50aW5nIGNvZGUsIGluZGV4ICovCiAgICBsZXQgZmlsbDsgICAgICAgICAgICAgIC8qIGluZGV4IGZvciByZXBsaWNhdGluZyBlbnRyaWVzICovCiAgICBsZXQgbG93OyAgICAgICAgICAgICAgIC8qIGxvdyBiaXRzIGZvciBjdXJyZW50IHJvb3QgZW50cnkgKi8KICAgIGxldCBtYXNrOyAgICAgICAgICAgICAgLyogbWFzayBmb3IgbG93IHJvb3QgYml0cyAqLwogICAgbGV0IG5leHQ7ICAgICAgICAgICAgIC8qIG5leHQgYXZhaWxhYmxlIHNwYWNlIGluIHRhYmxlICovCiAgICBsZXQgYmFzZSA9IG51bGw7ICAgICAvKiBiYXNlIHZhbHVlIHRhYmxlIHRvIHVzZSAqLwogICAgbGV0IGJhc2VfaW5kZXggPSAwOwogIC8vICBsZXQgc2hvZXh0cmE7ICAgIC8qIGV4dHJhIGJpdHMgdGFibGUgdG8gdXNlICovCiAgICBsZXQgZW5kOyAgICAgICAgICAgICAgICAgICAgLyogdXNlIGJhc2UgYW5kIGV4dHJhIGZvciBzeW1ib2wgPiBlbmQgKi8KICAgIGNvbnN0IGNvdW50ID0gbmV3IFVpbnQxNkFycmF5KE1BW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kIGRlb3B0cyBpbiBvbGQgdjgKICAgIGlmICh0eXBlID09PSBDT0RFUyQxKSB7CiAgICAgIGJhc2UgPSBleHRyYSA9IHdvcms7ICAgIC8qIGR1bW15IHZhbHVlLS1ub3QgdXNlZCAqLwogICAgICBlbmQgPSAxOTsKCiAgICB9IGVsc2UgaWYgKHR5cGUgPT09IExFTlMkMSkgewogICAgICBiYXNlID0gbGJhc2U7CiAgICAgIGJhc2VfaW5kZXggLT0gMjU3OwogICAgICBleHRyYSA9IGxleHQ7CiAgICAgIGV4dHJhX2luZGV4IC09IDI1NzsKICAgICAgZW5kID0gMjU2OwoKICAgIH0gZWxzZSB7ICAgICAgICAgICAgICAgICAgICAvKiBESVNUUyAqLwogICAgICBiYXNlID0gZGJhc2U7CiAgICAgIGV4dHJhID0gZGV4dDsKICAgICAgZW5kID0gLTE7CiAgICB9CgogICAgLyogaW5pdGlhbGl6ZSBvcHRzIGZvciBsb29wICovCiAgICBodWZmID0gMDsgICAgICAgICAgICAgICAgICAgLyogc3RhcnRpbmcgY29kZSAqLwogICAgc3ltID0gMDsgICAgICAgICAgICAgICAgICAgIC8qIHN0YXJ0aW5nIGNvZGUgc3ltYm9sICovCiAgICBsZW4gPSBtaW47ICAgICAgICAgICAgICAgICAgLyogc3RhcnRpbmcgY29kZSBsZW5ndGggKi8KICAgIG5leHQgPSB0YWJsZV9pbmRleDsgICAgICAgICAgICAgIC8qIGN1cnJlbnQgdGFibGUgdG8gZmlsbCBpbiAqLwogICAgY3VyciA9IHJvb3Q7ICAgICAgICAgICAgICAgIC8qIGN1cnJlbnQgdGFibGUgaW5kZXggYml0cyAqLwogICAgZHJvcCA9IDA7ICAgICAgICAgICAgICAgICAgIC8qIGN1cnJlbnQgYml0cyB0byBkcm9wIGZyb20gY29kZSBmb3IgaW5kZXggKi8KICAgIGxvdyA9IC0xOyAgICAgICAgICAgICAgICAgICAvKiB0cmlnZ2VyIG5ldyBzdWItdGFibGUgd2hlbiBsZW4gPiByb290ICovCiAgICB1c2VkID0gMSA8PCByb290OyAgICAgICAgICAvKiB1c2Ugcm9vdCB0YWJsZSBlbnRyaWVzICovCiAgICBtYXNrID0gdXNlZCAtIDE7ICAgICAgICAgICAgLyogbWFzayBmb3IgY29tcGFyaW5nIGxvdyAqLwoKICAgIC8qIGNoZWNrIGF2YWlsYWJsZSB0YWJsZSBzcGFjZSAqLwogICAgaWYgKCh0eXBlID09PSBMRU5TJDEgJiYgdXNlZCA+IEVOT1VHSF9MRU5TJDEpIHx8CiAgICAgICh0eXBlID09PSBESVNUUyQxICYmIHVzZWQgPiBFTk9VR0hfRElTVFMkMSkpIHsKICAgICAgcmV0dXJuIDE7CiAgICB9CgogICAgLyogcHJvY2VzcyBhbGwgY29kZXMgYW5kIG1ha2UgdGFibGUgZW50cmllcyAqLwogICAgZm9yICg7OykgewogICAgICAvKiBjcmVhdGUgdGFibGUgZW50cnkgKi8KICAgICAgaGVyZV9iaXRzID0gbGVuIC0gZHJvcDsKICAgICAgaWYgKHdvcmtbc3ltXSA8IGVuZCkgewogICAgICAgIGhlcmVfb3AgPSAwOwogICAgICAgIGhlcmVfdmFsID0gd29ya1tzeW1dOwogICAgICB9CiAgICAgIGVsc2UgaWYgKHdvcmtbc3ltXSA+IGVuZCkgewogICAgICAgIGhlcmVfb3AgPSBleHRyYVtleHRyYV9pbmRleCArIHdvcmtbc3ltXV07CiAgICAgICAgaGVyZV92YWwgPSBiYXNlW2Jhc2VfaW5kZXggKyB3b3JrW3N5bV1dOwogICAgICB9CiAgICAgIGVsc2UgewogICAgICAgIGhlcmVfb3AgPSAzMiArIDY0OyAgICAgICAgIC8qIGVuZCBvZiBibG9jayAqLwogICAgICAgIGhlcmVfdmFsID0gMDsKICAgICAgfQoKICAgICAgLyogcmVwbGljYXRlIGZvciB0aG9zZSBpbmRpY2VzIHdpdGggbG93IGxlbiBiaXRzIGVxdWFsIHRvIGh1ZmYgKi8KICAgICAgaW5jciA9IDEgPDwgKGxlbiAtIGRyb3ApOwogICAgICBmaWxsID0gMSA8PCBjdXJyOwogICAgICBtaW4gPSBmaWxsOyAgICAgICAgICAgICAgICAgLyogc2F2ZSBvZmZzZXQgdG8gbmV4dCB0YWJsZSAqLwogICAgICBkbyB7CiAgICAgICAgZmlsbCAtPSBpbmNyOwogICAgICAgIHRhYmxlW25leHQgKyAoaHVmZiA+PiBkcm9wKSArIGZpbGxdID0gKGhlcmVfYml0cyA8PCAyNCkgfCAoaGVyZV9vcCA8PCAxNikgfCBoZXJlX3ZhbCB8MDsKICAgICAgfSB3aGlsZSAoZmlsbCAhPT0gMCk7CgogICAgICAvKiBiYWNrd2FyZHMgaW5jcmVtZW50IHRoZSBsZW4tYml0IGNvZGUgaHVmZiAqLwogICAgICBpbmNyID0gMSA8PCAobGVuIC0gMSk7CiAgICAgIHdoaWxlIChodWZmICYgaW5jcikgewogICAgICAgIGluY3IgPj49IDE7CiAgICAgIH0KICAgICAgaWYgKGluY3IgIT09IDApIHsKICAgICAgICBodWZmICY9IGluY3IgLSAxOwogICAgICAgIGh1ZmYgKz0gaW5jcjsKICAgICAgfSBlbHNlIHsKICAgICAgICBodWZmID0gMDsKICAgICAgfQoKICAgICAgLyogZ28gdG8gbmV4dCBzeW1ib2wsIHVwZGF0ZSBjb3VudCwgbGVuICovCiAgICAgIHN5bSsrOwogICAgICBpZiAoLS1jb3VudFtsZW5dID09PSAwKSB7CiAgICAgICAgaWYgKGxlbiA9PT0gbWF4KSB7IGJyZWFrOyB9CiAgICAgICAgbGVuID0gbGVuc1tsZW5zX2luZGV4ICsgd29ya1tzeW1dXTsKICAgICAgfQoKICAgICAgLyogY3JlYXRlIG5ldyBzdWItdGFibGUgaWYgbmVlZGVkICovCiAgICAgIGlmIChsZW4gPiByb290ICYmIChodWZmICYgbWFzaykgIT09IGxvdykgewogICAgICAgIC8qIGlmIGZpcnN0IHRpbWUsIHRyYW5zaXRpb24gdG8gc3ViLXRhYmxlcyAqLwogICAgICAgIGlmIChkcm9wID09PSAwKSB7CiAgICAgICAgICBkcm9wID0gcm9vdDsKICAgICAgICB9CgogICAgICAgIC8qIGluY3JlbWVudCBwYXN0IGxhc3QgdGFibGUgKi8KICAgICAgICBuZXh0ICs9IG1pbjsgICAgICAgICAgICAvKiBoZXJlIG1pbiBpcyAxIDw8IGN1cnIgKi8KCiAgICAgICAgLyogZGV0ZXJtaW5lIGxlbmd0aCBvZiBuZXh0IHRhYmxlICovCiAgICAgICAgY3VyciA9IGxlbiAtIGRyb3A7CiAgICAgICAgbGVmdCA9IDEgPDwgY3VycjsKICAgICAgICB3aGlsZSAoY3VyciArIGRyb3AgPCBtYXgpIHsKICAgICAgICAgIGxlZnQgLT0gY291bnRbY3VyciArIGRyb3BdOwogICAgICAgICAgaWYgKGxlZnQgPD0gMCkgeyBicmVhazsgfQogICAgICAgICAgY3VycisrOwogICAgICAgICAgbGVmdCA8PD0gMTsKICAgICAgICB9CgogICAgICAgIC8qIGNoZWNrIGZvciBlbm91Z2ggc3BhY2UgKi8KICAgICAgICB1c2VkICs9IDEgPDwgY3VycjsKICAgICAgICBpZiAoKHR5cGUgPT09IExFTlMkMSAmJiB1c2VkID4gRU5PVUdIX0xFTlMkMSkgfHwKICAgICAgICAgICh0eXBlID09PSBESVNUUyQxICYmIHVzZWQgPiBFTk9VR0hfRElTVFMkMSkpIHsKICAgICAgICAgIHJldHVybiAxOwogICAgICAgIH0KCiAgICAgICAgLyogcG9pbnQgZW50cnkgaW4gcm9vdCB0YWJsZSB0byBzdWItdGFibGUgKi8KICAgICAgICBsb3cgPSBodWZmICYgbWFzazsKICAgICAgICAvKnRhYmxlLm9wW2xvd10gPSBjdXJyOwogICAgICAgIHRhYmxlLmJpdHNbbG93XSA9IHJvb3Q7CiAgICAgICAgdGFibGUudmFsW2xvd10gPSBuZXh0IC0gb3B0cy50YWJsZV9pbmRleDsqLwogICAgICAgIHRhYmxlW2xvd10gPSAocm9vdCA8PCAyNCkgfCAoY3VyciA8PCAxNikgfCAobmV4dCAtIHRhYmxlX2luZGV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Glvbi4KCgoKCgoKICBjb25zdCBDT0RFUyA9IDA7CiAgY29uc3QgTEVOUyA9IDE7CiAgY29uc3QgRElTVFMgPSAyOwoKICAvKiBQdWJsaWMgY29uc3RhbnRzID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSovCgogIGNvbnN0IHsKICAgIFpfRklOSVNIOiBaX0ZJTklTSCQxLCBaX0JMT0NLLCBaX1RSRUVTLAogICAgWl9PSzogWl9PSyQxLCBaX1NUUkVBTV9FTkQ6IFpfU1RSRUFNX0VORCQxLCBaX05FRURfRElDVDogWl9ORUVEX0RJQ1QkMSwgWl9TVFJFQU1fRVJST1I6IFpfU1RSRUFNX0VSUk9SJDEsIFpfREFUQV9FUlJPUjogWl9EQVRBX0VSUk9SJDEsIFpfTUVNX0VSUk9SOiBaX01FTV9FUlJPUiQxLCBaX0JVRl9FUlJPUiwKICAgIFpfREVGTEFURUQKICB9ID0gY29uc3RhbnRzJDI7CgoKICAvKiBTVEFURVMgPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSovCgoKICBjb25zdCAgICBIRUFEID0gMTsgICAgICAgLyogaTogd2FpdGluZyBmb3IgbWFnaWMgaGVhZGVyICovCiAgY29uc3QgICAgRkxBR1MgPSAyOyAgICAgIC8qIGk6IHdhaXRpbmcgZm9yIG1ldGhvZCBhbmQgZmxhZ3MgKGd6aXApICovCiAgY29uc3QgICAgVElNRSA9IDM7ICAgICAgIC8qIGk6IHdhaXRpbmcgZm9yIG1vZGlmaWNhdGlvbiB0aW1lIChnemlwKSAq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BiZSB7fQogICAgdGhpcy5oZWFkID0gbnVsbDsgICAgICAgICAgIC8qIHdoZXJlIHRvIHNhdmUgZ3ppcCBoZWFkZXIgaW5mb3JtYXRpb24gKi8KCiAgICAvKiBzbGlkaW5nIHdpbmRvdyAqLwogICAgdGhpcy53Yml0cyA9IDA7ICAgICAgICAgICAgIC8qIGxvZyBiYXNlIDIgb2YgcmVxdWVzdGVkIHdpbmRvdyBzaXplICovCiAgICB0aGlzLndzaXplID0gMDsgICAgICAgICAgICAgLyogd2luZG93IHNpemUgb3IgemVybyBpZiBub3QgdXNpbmcgd2luZG93ICovCiAgICB0aGlzLndoYXZlID0gMDsgICAgICAgICAgICAgLyogdmFsaWQgYnl0ZXMgaW4gdGhlIHdpbmRvdyAqLwogICAgdGhpcy53bmV4dCA9IDA7ICAgICAgICAgICAgIC8qIHdpbmRvdyB3cml0ZSBpbmRleCAqLwogICAgdGhpcy53aW5kb3cgPSBudWxsOyAgICAgICAgIC8qIGFsbG9jYXRlZCBzbGlkaW5nIHdpbmRvdywgaWYgbmVlZGVkICovCgogICAgLyogYml0IGFjY3VtdWxhdG9yICovCiAgICB0aGlzLmhvbGQgPSAwOyAgICAgICAgICAgICAgLyogaW5wdXQgYml0IGFjY3VtdWxhdG9yICovCiAgICB0aGlzLmJpdHMgPSAwOyAgICAgICAgICAgICAgLyogbnVtYmVyIG9mIGJpdHMgaW4gImluIiAqLwoKICAgIC8qIGZvciBzdHJpbmcgYW5kIHN0b3JlZCBibG9jayBjb3B5aW5nICovCiAgICB0aGlzLmxlbmd0aCA9IDA7ICAgICAgICAgICAgLyogbGl0ZXJhbCBvciBsZW5ndGggb2YgZGF0YSB0byBjb3B5ICovCiAgICB0aGlzLm9mZnNldCA9IDA7ICAgICAgICAgICAgLyogZGlzdGFuY2UgYmFjayB0byBjb3B5IHN0cmluZyBmcm9tICovCgogICAgLyogZm9yIHRhYmxlIGFuZCBjb2RlIGRlY29kaW5nICovCiAgICB0aGlzLmV4dHJhID0gMDs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Uud2hhdmUgPSAwOwogICAgc3RhdGUud25leHQgPSAwOwogICAgcmV0dXJuIGluZmxhdGVSZXNldEtlZXAoc3RybSk7CgogIH07CgoKICBjb25zdCBpbmZsYXRlUmVzZXQyID0gKHN0cm0sIHdpbmRvd0JpdHMpID0+IHsKICAgIGxldCB3cmFwOwoKICAgIC8qIGdldCB0aGUgc3RhdGUgKi8KICAgIGlmICghc3RybSB8fCAhc3RybS5zdGF0ZSkgeyByZXR1cm4gWl9TVFJFQU1fRVJST1IkMTsgfQogICAgY29uc3Qgc3RhdGUgPSBzdHJtLnN0YXRlOwoKICAgIC8qIGV4dHJhY3Qgd3JhcCByZXF1ZXN0IGZyb20gd2luZG93Qml0cyBwYXJhbWV0ZXIgKi8KICAgIGlmICh3aW5kb3dCaXRzIDwgMCkgewogICAgICB3cmFwID0gMDsKICAgICAgd2luZG93Qml0cyA9IC13aW5kb3dCaXRzOwogICAgfQogICAgZWxzZSB7CiAgICAgIHdyYXAgPSAod2luZG93Qml0cyA+PiA0KSArIDE7CiAgICAgIGlmICh3aW5kb3dCaXRzIDwgNDgpIHsKICAgICAgICB3aW5kb3dCaXRzICY9IDE1OwogICAgICB9CiAgICB9CgogICAgLyogc2V0IG51bWJlciBvZiB3aW5kb3cgYml0cywgZnJlZSB3aW5kb3cgaWYgZGlmZmVyZW50ICovCiAgICBpZiAod2luZG93Qml0cyAmJiAod2luZG93Qml0cyA8IDggfHwgd2luZG93Qml0cyA+IDE1KSkgewogICAgICByZXR1cm4gWl9TVFJFQU1fRVJST1IkMTsKICAgIH0KICAgIGlmIChzdGF0ZS53aW5kb3cgIT09IG51bGwgJiYgc3RhdGUud2JpdHMgIT09IHdpbmRvd0JpdHMpIHsKICAgICAgc3RhdGUud2luZG93ID0gbnVsbDsKICAgIH0KCiAgICAvKiB1cGRhdGUgc3RhdGUgYW5kIHJlc2V0IHRoZSByZXN0IG9mIGl0ICovCiAgICBzdGF0ZS53cmFwID0gd3JhcDsKICAgIHN0YXRlLndia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DA7CiAgICAgIHN0YXRlLndoYXZlID0gMDsKCiAgICAgIHN0YXRlLndpbmRvdyA9IG5ldyBVaW50OEFycmF5KHN0YXRlLndzaXplKTsKICAgIH0KCiAgICAvKiBjb3B5IHN0YXRlLT53c2l6ZSBvciBsZXNzIG91dHB1dCBieXRlcyBpbnRvIHRoZSBjaXJjdWxhciB3aW5kb3cgKi8KICAgIGlmIChjb3B5ID49IHN0YXRlLndzaXplKSB7CiAgICAgIHN0YXRlLndpbmRvdy5zZXQoc3JjLnN1YmFycmF5KGVuZCAtIHN0YXRlLndzaXplLCBlbmQpLCAwKTsKICAgICAgc3RhdGUud25leHQgPSAwOwogICAgICBzdGF0ZS53aGF2ZSA9IHN0YXRlLndzaXplOwogICAgfQogICAgZWxzZSB7CiAgICAgIGRpc3QgPSBzdGF0ZS53c2l6ZSAtIHN0YXRlLnduZXh0OwogICAgICBpZiAoZGlzdCA+IGNvcHkpIHsKICAgICAgICBkaXN0ID0gY29weTsKICAgICAgfQogICAgICAvL3ptZW1jcHkoc3RhdGUtPndpbmRvdyArIHN0YXRlLT53bmV4dCwgZW5kIC0gY29weSwgZGlzdCk7CiAgICAgIHN0YXRlLndpbmRvdy5zZXQoc3JjLnN1YmFycmF5KGVuZCAtIGNvcHksIGVuZCAtIGNvcHkgKyBkaXN0KSwgc3RhdGUud25leHQpOwogICAgICBjb3B5IC09IGRpc3Q7CiAgICAgIGlmIChjb3B5KSB7CiAgICAgICAgLy96bWVtY3B5KHN0YXRlLT53aW5kb3csIGVuZCAtIGNvcHksIGNvcHkpOwogICAgICAgIHN0YXRlLndpbmRvdy5zZXQoc3JjLnN1YmFycmF5KGVuZCAtIGNvcHksIGVuZCksIDApOwogICAgICAgIHN0YXRlLnduZXh0ID0gY29weTsKICAgICAgICBzdGF0ZS53aGF2ZSA9IHN0YXRlLndzaXplOwogICAgICB9CiAgICAgIGVsc2UgewogICAgICAgIHN0YXRlLnduZXh0ICs9IGRpc3Q7CiAgICAgICAgaWYgKHN0YXRlLnduZXh0ID09PSBzdGF0ZS53c2l6ZSkgeyBzdGF0ZS53bmV4dCA9IDA7IH0KICAgICAgICBpZiAoc3RhdGUud2hhdmUgPCBzdGF0ZS53c2l6ZSkgeyBzdGF0ZS53aGF2ZSArPSBkaXN0OyB9CiAgICAgIH0KICAgIH0KICAgIHJldHVybiAwOwogIH07CgoKICBjb25zdCBpbmZsYXRlJDIgPSAoc3RybSwgZmx1c2gpID0+IHsKCiAgICBsZXQgc3RhdGU7CiAgICBsZXQgaW5wdXQsIG91dHB1dDsgICAgICAgICAgLy8gaW5wdXQvb3V0cHV0IGJ1ZmZlcnMKICAgIGxldCBuZXh0OyAgICAgICAgICAgICAgICAgICAvKiBuZXh0IGlucHV0IElOREVYICovCiAgICBsZXQgcHV0OyAgICAgICAgICAgICAgICAgICAgLyogbmV4dCBvdXRwdXQgSU5ERVggKi8KICAgIGxldCBoYXZlLCBsZWZ0OyAgICAgICAgICAgICAvKiBhdmFpbGFibGUgaW5wdXQgYW5kIG91dHB1dCAqLwogICAgbGV0IGhvbGQ7ICAgICAgICAgICAgICAgICAgIC8qIGJpdCBidWZmZXIgKi8KICAgIGxldCBiaXRzOyAgICAgICAgICAgICAgICAgICAvKiBiaXRzIGluIGJpdCBidWZmZXIgKi8KICAgIGxldCBfaW4sIF9vdXQ7ICAgICAgICAgICAgICAvKiBzYXZlIHN0YXJ0aW5nIGF2YWlsYWJsZSBpbnB1dCBhbmQgb3V0cHV0ICovCiAgICBsZXQgY29weTsgICAgICAgICAgICAgICAgICAgLyogbnVtYmVyIG9mIHN0b3JlZCBvciBtYXRjaCBieXRlcyB0byBjb3B5ICovCiAgICBsZXQgZnJvbTsgICAgICAgICAgICAgICAgICAgLyogd2hlcmUgdG8gY29weSBtYXRjaCBieXRlcyBmcm9tICovCiAgICBsZXQgZnJvbV9zb3VyY2U7CiAgICBsZXQgaGVyZSA9IDA7ICAgICAgICAgICAgICAgLyogY3VycmVudCBkZWNvZGluZyB0YWJsZSBlbnR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gPT09IFRZUEUpIHsgc3RhdGUubW9kZSA9IFRZUEVETzsgfSAgICAvKiBza2lwIGNoZWNrICovCgoKICAgIC8vLS0tIExPQUQoKSAtLS0KICAgIHB1dCA9IHN0cm0ubmV4dF9vdXQ7CiAgICBvdXRwdXQgPSBzdHJtLm91dHB1dDsKICAgIGxlZnQgPSBzdHJtLmF2YWlsX291dDsKICAgIG5leHQgPSBzdHJtLm5leHRfaW47CiAgICBpbnB1dCA9IHN0cm0uaW5wdXQ7CiAgICBoYXZlID0gc3RybS5hdmFpbF9pbjsKICAgIGhvbGQgPSBzdGF0ZS5ob2xkOwogICAgYml0cyA9IHN0YXRlLmJpdHM7CiAgICAvLy0tLQoKICAgIF9pbiA9IGhhdmU7CiAgICBfb3V0ID0gbGVmdDsKICAgIHJldCA9IFpfT0skMTsKCiAgICBpbmZfbGVhdmU6IC8vIGdvdG8gZW11bGF0aW9uCiAgICBmb3IgKDs7KSB7CiAgICAgIHN3aXRjaCAoc3RhdGUubW9kZSkgewogICAgICAgIGNhc2UgSEVBRDoKICAgICAgICAgIGlmIChzdGF0ZS53cmFwID09PSAwKSB7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBUWVBFRE87CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgLy89PT0gTkVFREJJVFMoMTYpOwogICAgICAgICAgd2hpbGUgKGJpdHMgPCAxNikgewogICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgfQogICAgICAgICAgLy89PT0vLwogICAgICAgICAgaWYgKChzdGF0ZS53cmFwICYgMikgJiYgaG9sZCA9PT0gMHg4YjFmKSB7ICAvKiBnemlwIGhlYWRlciAqLwogICAgICAgICAgICBzdGF0ZS5jaGVjayA9IDAvKmNyYzMyKDBMLCBaX05VTEwsIDApKi87CiAgICAgICAgICAgIC8vPT09IENSQzIoc3RhdGUuY2hlY2ssIGhvbGQpOwogICAgICAgICAgICBoYnVmWzBdID0gaG9sZCAmIDB4ZmY7CiAgICAgICAgICAgIGhidWZbMV0gPSAoaG9sZCA+Pj4gOCkgJiAweGZmOwogICAgICAgICAgICBzdGF0ZS5jaGVjayA9IGNyYzMyXzEoc3RhdGUuY2hlY2ssIGhidWYsIDIsIDApOwogICAgICAgICAgICAvLz09PS8vCgogICAgICAgICAgICAvLz09PSBJTklUQklUUygpOwogICAgICAgICAgICBob2xkID0gMDsKICAgICAgICAgICAgYml0cyA9IDA7CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgc3RhdGUubW9kZSA9IEZMQUdTOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIHN0YXRlLmZsYWdzID0gMDsgICAgICAgICAgIC8qIGV4cGVjdCB6bGliIGhlYWRlciAqLwogICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC5kb25lID0gZmFsc2U7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAoIShzdGF0ZS53cmFwICYgMSkgfHwgICAvKiBjaGVjayBpZiB6bGliIGhlYWRlciBhbGxvd2VkICovCiAgICAgICAgICAgICgoKGhvbGQgJiAweGZmKS8qQklUUyg4KSovIDw8IDgpICsgKGhvbGQgPj4gOCkpICUgMzEpIHsKICAgICAgICAgICAgc3RybS5tc2cgPSAnaW5jb3JyZWN0IGhlYWRlciBjaGVjayc7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgaWYgKChob2xkICYgMHgwZikvKkJJVFMoNCkqLyAhPT0gWl9ERUZMQVRFRCkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICd1bmtub3duIGNvbXByZXNzaW9uIG1ldGhvZCc7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgLy8tLS0gRFJPUEJJVFMoNCkgLS0tLy8KICAgICAgICAgIGhvbGQgPj4+PSA0OwogICAgICAgICAgYml0cyAtPSA0OwogICAgICAgICAgLy8tLS0vLwogICAgICAgICAgbGVuID0gKGhvbGQgJiAweDBmKS8qQklUUyg0KSovICsgODsKICAgICAgICAgIGlmIChzdGF0ZS53Yml0cyA9PT0gMCkgewogICAgICAgICAgICBzdGF0ZS53Yml0cyA9IGxlbjsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgaWYgKGxlbiA+IHN0YXRlLndiaXRzKSB7CiAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgd2luZG93IHNpemUnOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KCiAgICAgICAgICAvLyAhISEgcGFrbyBwYXRjaC4gRm9yY2UgdXNlIGBvcHRpb25zLndpbmRvd0JpdHNgIGlmIHBhc3NlZC4KICAgICAgICAgIC8vIFJlcXVpcmVkIHRvIGFsd2F5cyB1c2UgbWF4IHdpbmRvdyBzaXplIGJ5IGRlZmF1bHQuCiAgICAgICAgICBzdGF0ZS5kbWF4ID0gMSA8PCBzdGF0ZS53Yml0czsKICAgICAgICAgIC8vc3RhdGUuZG1heCA9IDEgPDwgbGVuOwoKICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgIHpsaWIgaGVhZGVyIG9rXG4iKSk7CiAgICAgICAgICBzdHJtLmFkbGVyID0gc3RhdGUuY2hlY2sgPSAxLyphZGxlcjMyKDBMLCBaX05VTEwsIDApKi87CiAgICAgICAgICBzdGF0ZS5tb2RlID0gaG9sZCAmIDB4MjAwID8gRElDVElEIDogVFlQRTsKICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICBob2xkID0gMDsKICAgICAgICAgIGJpdHMgPSAwOwogICAgICAgICAgLy89PT0vLwogICAgICAgICAgYnJlYWs7CiAgICAgICAgY2FzZSBGTEFHUzoKICAgICAgICAgIC8vPT09IE5FRURCSVRTKDE2KTsgKi8KICAgICAgICAgIHdoaWxlIChiaXRzIDwgMTYpIHsKICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgIH0KICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgIHN0YXRlLmZsYWdzID0gaG9sZDsKICAgICAgICAgIGlmICgoc3RhdGUuZmxhZ3MgJiAweGZmKSAhPT0gWl9ERUZMQVRFRCkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICd1bmtub3duIGNvbXByZXNzaW9uIG1ldGhvZCc7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgaWYgKHN0YXRlLmZsYWdzICYgMHhlMDAwKSB7CiAgICAgICAgICAgIHN0cm0ubXNnID0gJ3Vua25vd24gaGVhZGVyIGZsYWdzIHNldCc7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC50ZXh0ID0gKChob2xkID4+IDgpICYgMSk7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAoc3RhdGUuZmxhZ3MgJiAweDAyMDApIHsKICAgICAgICAgICAgLy89PT0gQ1JDMihzdGF0ZS5jaGVjaywgaG9sZCk7CiAgICAgICAgICAgIGhidWZbMF0gPSBob2xkICYgMHhmZjsKICAgICAgICAgICAgaGJ1ZlsxXSA9IChob2xkID4+PiA4KSAmIDB4ZmY7CiAgICAgICAgICAgIHN0YXRlLmNoZWNrID0gY3JjMzJfMShzdGF0ZS5jaGVjaywgaGJ1ZiwgMiwgMCk7CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgIH0KICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICBob2xkID0gMDsKICAgICAgICAgIGJpdHMgPSAwOwogICAgICAgICAgLy89PT0vLwogICAgICAgICAgc3RhdGUubW9kZSA9IFRJTUU7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBUSU1FOgogICAgICAgICAgLy89PT0gTkVFREJJVFMoMzIpOyAqLwogICAgICAgICAgd2hpbGUgKGJpdHMgPCAzMikgewogICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgfQogICAgICAgICAgLy89PT0vLwogICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC50aW1lID0gaG9sZDsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDIwMCkgewogICAgICAgICAgICAvLz09PSBDUkM0KHN0YXRlLmNoZWNrLCBob2xkKQogICAgICAgICAgICBoYnVmWzBdID0gaG9sZCAmIDB4ZmY7CiAgICAgICAgICAgIGhidWZbMV0gPSAoaG9sZCA+Pj4gOCkgJiAweGZmOwogICAgICAgICAgICBoYnVmWzJdID0gKGhvbGQgPj4+IDE2KSAmIDB4ZmY7CiAgICAgICAgICAgIGhidWZbM10gPSAoaG9sZCA+Pj4gMjQpICYgMHhmZjsKICAgICAgICAgICAgc3RhdGUuY2hlY2sgPSBjcmMzMl8xKHN0YXRlLmNoZWNrLCBoYnVmLCA0LCAwKTsKICAgICAgICAgICAgLy89PT0KICAgICAgICAgIH0KICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICBob2xkID0gMDsKICAgICAgICAgIGJpdHMgPSAwOwogICAgICAgICAgLy89PT0vLwogICAgICAgICAgc3RhdGUubW9kZSA9IE9TOwogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgT1M6CiAgICAgICAgICAvLz09PSBORUVEQklUUygxNik7ICovCiAgICAgICAgICB3aGlsZSAoYml0cyA8IDE2KSB7CiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICB9CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBpZiAoc3RhdGUuaGVhZCkgewogICAgICAgICAgICBzdGF0ZS5oZWFkLnhmbGFncyA9IChob2xkICYgMHhmZik7CiAgICAgICAgICAgIHN0YXRlLmhlYWQub3MgPSAoaG9sZCA+PiA4KTsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDIwMCkgewogICAgICAgICAgICAvLz09PSBDUkMyKHN0YXRlLmNoZWNrLCBob2xkKTsKICAgICAgICAgICAgaGJ1ZlswXSA9IGhvbGQgJiAweGZmOwogICAgICAgICAgICBoYnVmWzFdID0gKGhvbGQgPj4+IDgpICYgMHhmZjsKICAgICAgICAgICAgc3RhdGUuY2hlY2sgPSBjcmMzMl8xKHN0YXRlLmNoZWNrLCBoYnVmLCAyLCAwKTsKICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgfQogICAgICAgICAgLy89PT0gSU5JVEJJVFMoKTsKICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgYml0cyA9IDA7CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBzdGF0ZS5tb2RlID0gRVhMRU47CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBFWExFTjoKICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDQwMCkgewogICAgICAgICAgICAvLz09PSBORUVEQklUUygxNik7ICovCiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgMTYpIHsKICAgICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgc3RhdGUubGVuZ3RoID0gaG9sZDsKICAgICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgICBzdGF0ZS5oZWFkLmV4dHJhX2xlbiA9IGhvbGQ7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKHN0YXRlLmZsYWdzICYgMHgwMjAwKSB7CiAgICAgICAgICAgICAgLy89PT0gQ1JDMihzdGF0ZS5jaGVjaywgaG9sZCk7CiAgICAgICAgICAgICAgaGJ1ZlswXSA9IGhvbGQgJiAweGZmOwogICAgICAgICAgICAgIGhidWZbMV0gPSAoaG9sZCA+Pj4gOCkgJiAweGZmOwogICAgICAgICAgICAgIHN0YXRlLmNoZWNrID0gY3JjMzJfMShzdGF0ZS5jaGVjaywgaGJ1ZiwgMiwgMCk7CiAgICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgICBiaXRzID0gMDsKICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgfQogICAgICAgICAgZWxzZSBpZiAoc3RhdGUuaGVhZCkgewogICAgICAgICAgICBzdGF0ZS5oZWFkLmV4dHJhID0gbnVsbC8qWl9OVUxMKi87CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5tb2RlID0gRVhUUkE7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBFWFRSQToKICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDQwMCkgewogICAgICAgICAgICBjb3B5ID0gc3RhdGUubGVuZ3RoOwogICAgICAgICAgICBpZiAoY29weSA+IGhhdmUpIHsgY29weSA9IGhhdmU7IH0KICAgICAgICAgICAgaWYgKGNvcHkpIHsKICAgICAgICAgICAgICBpZiAoc3RhdGUuaGVhZCkgewogICAgICAgICAgICAgICAgbGVuID0gc3RhdGUuaGVhZC5leHRyYV9sZW4gLSBzdGF0ZS5sZW5ndGg7CiAgICAgICAgICAgICAgICBpZiAoIXN0YXRlLmhlYWQuZXh0cmEpIHsKICAgICAgICAgICAgICAgICAgLy8gVXNlIHVudHlwZWQgYXJyYXkgZm9yIG1vcmUgY29udmVuaWVudCBwcm9jZXNzaW5nIGxhdGVyCiAgICAgICAgICAgICAgICAgIHN0YXRlLmhlYWQuZXh0cmEgPSBuZXcgVWludDhBcnJheShzdGF0ZS5oZWFkLmV4dHJhX2xlbik7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBzdGF0ZS5oZWFkLmV4dHJhLnNldCgKICAgICAgICAgICAgICAgICAgaW5wdXQuc3ViYXJyYXkoCiAgICAgICAgICAgICAgICAgICAgbmV4dCwKICAgICAgICAgICAgICAgICAgICAvLyBleHRyYSBmaWVsZCBpcyBsaW1pdGVkIHRvIDY1NTM2IGJ5dGVzCiAgICAgICAgICAgICAgICAgICAgLy8gLSBubyBuZWVkIGZvciBhZGRpdGlvbmFsIHNpemUgY2hlY2sKICAgICAgICAgICAgICAgICAgICBuZXh0ICsgY29weQogICAgICAgICAgICAgICAgICApLAogICAgICAgICAgICAgICAgICAvKmxlbiArIGNvcHkgPiBzdGF0ZS5oZWFkLmV4dHJhX21heCAtIGxlbiA/IHN0YXRlLmhlYWQuZXh0cmFfbWF4IDogY29weSwqLwogICAgICAgICAgICAgICAgICBsZW4KICAgICAgICAgICAgICAgICk7CiAgICAgICAgICAgICAgICAvL3ptZW1jcHkoc3RhdGUuaGVhZC5leHRyYSArIGxlbiwgbmV4dCwKICAgICAgICAgICAgICAgIC8vICAgICAgICBsZW4gKyBjb3B5ID4gc3RhdGUuaGVhZC5leHRyYV9tYXggPwogICAgICAgICAgICAgICAgLy8gICAgICAgIHN0YXRlLmhlYWQuZXh0cmFfbWF4IC0gbGVuIDogY29weSk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDIwMCkgewogICAgICAgICAgICAgICAgc3RhdGUuY2hlY2sgPSBjcmMzMl8xKHN0YXRlLmNoZWNrLCBpbnB1dCwgY29weSwgbmV4dCk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGhhdmUgLT0gY29weTsKICAgICAgICAgICAgICBuZXh0ICs9IGNvcHk7CiAgICAgICAgICAgICAgc3RhdGUubGVuZ3RoIC09IGNvcHk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKHN0YXRlLmxlbmd0aCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgIH0KICAgICAgICAgIHN0YXRlLmxlbmd0aCA9IDA7CiAgICAgICAgICBzdGF0ZS5tb2RlID0gTkFNRTsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIE5BTUU6CiAgICAgICAgICBpZiAoc3RhdGUuZmxhZ3MgJiAweDA4MDApIHsKICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgIGNvcHkgPSAwOwogICAgICAgICAgICBkbyB7CiAgICAgICAgICAgICAgLy8gVE9ETzogMiBvciAxIGJ5dGVzPwogICAgICAgICAgICAgIGxlbiA9IGlucHV0W25leHQgKyBjb3B5KytdOwogICAgICAgICAgICAgIC8qIHVzZSBjb25zdGFudCBsaW1pdCBiZWNhdXNlIGluIGpzIHdlIHNob3VsZCBub3QgcHJlYWxsb2NhdGUgbWVtb3J5ICovCiAgICAgICAgICAgICAgaWYgKHN0YXRlLmhlYWQgJiYgbGVuICYmCiAgICAgICAgICAgICAgICAgIChzdGF0ZS5sZW5ndGggPCA2NTUzNiAvKnN0YXRlLmhlYWQubmFtZV9tYXgqLykpIHsKICAgICAgICAgICAgICAgIHN0YXRlLmhlYWQubmFtZSArPSBTdHJpbmcuZnJvbUNoYXJDb2RlKGxlbik7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9IHdoaWxlIChsZW4gJiYgY29weSA8IGhhdmUpOwoKICAgICAgICAgICAgaWYgKHN0YXRlLmZsYWdzICYgMHgwMjAwKSB7CiAgICAgICAgICAgICAgc3RhdGUuY2hlY2sgPSBjcmMzMl8xKHN0YXRlLmNoZWNrLCBpbnB1dCwgY29weSwgbmV4dCk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaGF2ZSAtPSBjb3B5OwogICAgICAgICAgICBuZXh0ICs9IGNvcHk7CiAgICAgICAgICAgIGlmIChsZW4pIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIGlmIChzdGF0ZS5oZWFkKSB7CiAgICAgICAgICAgIHN0YXRlLmhlYWQubmFtZSA9IG51bGw7CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5sZW5ndGggPSAwOwogICAgICAgICAgc3RhdGUubW9kZSA9IENPTU1FTlQ7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBDT01NRU5UOgogICAgICAgICAgaWYgKHN0YXRlLmZsYWdzICYgMHgxMDAwKSB7CiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBjb3B5ID0gMDsKICAgICAgICAgICAgZG8gewogICAgICAgICAgICAgIGxlbiA9IGlucHV0W25leHQgKyBjb3B5KytdOwogICAgICAgICAgICAgIC8qIHVzZSBjb25zdGFudCBsaW1pdCBiZWNhdXNlIGluIGpzIHdlIHNob3VsZCBub3QgcHJlYWxsb2NhdGUgbWVtb3J5ICovCiAgICAgICAgICAgICAgaWYgKHN0YXRlLmhlYWQgJiYgbGVuICYmCiAgICAgICAgICAgICAgICAgIChzdGF0ZS5sZW5ndGggPCA2NTUzNiAvKnN0YXRlLmhlYWQuY29tbV9tYXgqLykpIHsKICAgICAgICAgICAgICAgIHN0YXRlLmhlYWQuY29tbWVudCArPSBTdHJpbmcuZnJvbUNoYXJDb2RlKGxlbik7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9IHdoaWxlIChsZW4gJiYgY29weSA8IGhhdmUpOwogICAgICAgICAgICBpZiAoc3RhdGUuZmxhZ3MgJiAweDAyMDApIHsKICAgICAgICAgICAgICBzdGF0ZS5jaGVjayA9IGNyYzMyXzEoc3RhdGUuY2hlY2ssIGlucHV0LCBjb3B5LCBuZXh0KTsKICAgICAgICAgICAgfQogICAgICAgICAgICBoYXZlIC09IGNvcHk7CiAgICAgICAgICAgIG5leHQgKz0gY29weTsKICAgICAgICAgICAgaWYgKGxlbikgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC5jb21tZW50ID0gbnVsbDsKICAgICAgICAgIH0KICAgICAgICAgIHN0YXRlLm1vZGUgPSBIQ1JDOwogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgSENSQzoKICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDIwMCkgewogICAgICAgICAgICAvLz09PSBORUVEQklUUygxNik7ICovCiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgMTYpIHsKICAgICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgaWYgKGhvbGQgIT09IChzdGF0ZS5jaGVjayAmIDB4ZmZmZikpIHsKICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdoZWFkZXIgY3JjIG1pc21hdGNoJzsKICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgICBiaXRzID0gMDsKICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgfQogICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC5oY3JjID0gKChzdGF0ZS5mbGFncyA+PiA5KSAmIDEpOwogICAgICAgICAgICBzdGF0ZS5oZWFkLmRvbmUgPSB0cnVlOwogICAgICAgICAgfQogICAgICAgICAgc3RybS5hZGxlciA9IHN0YXRlLmNoZWNrID0gMDsKICAgICAgICAgIHN0YXRlLm1vZGUgPSBUWVBFOwogICAgICAgICAgYnJlYWs7CiAgICAgICAgY2FzZSBESUNUSUQ6CiAgICAgICAgICAvLz09PSBORUVEQklUUygzMik7ICovCiAgICAgICAgICB3aGlsZSAoYml0cyA8IDMyKSB7CiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICB9CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBzdHJtLmFkbGVyID0gc3RhdGUuY2hlY2sgPSB6c3dhcDMyKGhvbGQpOwogICAgICAgICAgLy89PT0gSU5JVEJJVFMoKTsKICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgYml0cyA9IDA7CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBzdGF0ZS5tb2RlID0gRElDVDsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIERJQ1Q6CiAgICAgICAgICBpZiAoc3RhdGUuaGF2ZWRpY3QgPT09IDApIHsKICAgICAgICAgICAgLy8tLS0gUkVTVE9SRSgpIC0tLQogICAgICAgICAgICBzdHJtLm5leHRfb3V0ID0gcHV0OwogICAgICAgICAgICBzdHJtLmF2YWlsX291dCA9IGxlZnQ7CiAgICAgICAgICAgIHN0cm0ubmV4dF9pbiA9IG5leHQ7CiAgICAgICAgICAgIHN0cm0uYXZhaWxfaW4gPSBoYXZlOwogICAgICAgICAgICBzdGF0ZS5ob2xkID0gaG9sZDsKICAgICAgICAgICAgc3RhdGUuYml0cyA9IGJpdHM7CiAgICAgICAgICAgIC8vLS0tCiAgICAgICAgICAgIHJldHVybiBaX05FRURfRElDVCQxOwogICAgICAgICAgfQogICAgICAgICAgc3RybS5hZGxlciA9IHN0YXRlLmNoZWNrID0gMS8qYWRsZXIzMigwTCwgWl9OVUxMLCAwKSovOwogICAgICAgICAgc3RhdGUubW9kZSA9IFRZUEU7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBUWVBFOgogICAgICAgICAgaWYgKGZsdXNoID09PSBaX0JMT0NLIHx8IGZsdXNoID09PSBaX1RSRUVTKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgVFlQRURPOgogICAgICAgICAgaWYgKHN0YXRlLmxhc3QpIHsKICAgICAgICAgICAgLy8tLS0gQllURUJJVFMoKSAtLS0vLwogICAgICAgICAgICBob2xkID4+Pj0gYml0cyAmIDc7CiAgICAgICAgICAgIGJpdHMgLT0gYml0cyAmIDc7CiAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgICAgc3RhdGUubW9kZSA9IENIRUNLOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIC8vPT09IE5FRURCSVRTKDMpOyAqLwogICAgICAgICAgd2hpbGUgKGJpdHMgPCAzKSB7CiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICB9CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBzdGF0ZS5sYXN0ID0gKGhvbGQgJiAweDAxKS8qQklUUygxKSovOwogICAgICAgICAgLy8tLS0gRFJPUEJJVFMoMSkgLS0tLy8KICAgICAgICAgIGhvbGQgPj4+PSAxOwogICAgICAgICAgYml0cyAtPSAxOwogICAgICAgICAgLy8tLS0vLwoKICAgICAgICAgIHN3aXRjaCAoKGhvbGQgJiAweDAzKS8qQklUUygyKSovKSB7CiAgICAgICAgICAgIGNhc2UgMDogICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8qIHN0b3JlZCBibG9jayAqLwogICAgICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgc3RvcmVkIGJsb2NrJXNcbiIsCiAgICAgICAgICAgICAgLy8gICAgICAgIHN0YXRlLmxhc3QgPyAiIChsYXN0KSIgOiAiIikpOwogICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBTVE9SRUQ7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8qIGZpeGVkIGJsb2NrICovCiAgICAgICAgICAgICAgZml4ZWR0YWJsZXMoc3RhdGUpOwogICAgICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgZml4ZWQgY29kZXMgYmxvY2slc1xuIiwKICAgICAgICAgICAgICAvLyAgICAgICAgc3RhdGUubGFzdCA/ICIgKGxhc3QpIiA6ICIiKSk7CiAgICAgICAgICAgICAgc3RhdGUubW9kZSA9IExFTl87ICAgICAgICAgICAgIC8qIGRlY29kZSBjb2RlcyAqLwogICAgICAgICAgICAgIGlmIChmbHVzaCA9PT0gWl9UUkVFUykgewogICAgICAgICAgICAgICAgLy8tLS0gRFJPUEJJVFMoMikgLS0tLy8KICAgICAgICAgICAgICAgIGhvbGQgPj4+PSAyOwogICAgICAgICAgICAgICAgYml0cyAtPSAyOwogICAgICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICAgICAgYnJlYWsgaW5mX2xlYXZlOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAyOiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLyogZHluYW1pYyBibG9jayAqLwogICAgICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgZHluYW1pYyBjb2RlcyBibG9jayVzXG4iLAogICAgICAgICAgICAgIC8vICAgICAgICBzdGF0ZS5sYXN0ID8gIiAobGFzdCkiIDogIiIpKTsKICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gVEFCTEU7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMzoKICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGJsb2NrIHR5cGUnOwogICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICB9CiAgICAgICAgICAvLy0tLSBEUk9QQklUUygyKSAtLS0vLwogICAgICAgICAgaG9sZCA+Pj49IDI7CiAgICAgICAgICBiaXRzIC09IDI7CiAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICBicmVhazsKICAgICAgICBjYXNlIFNUT1JFRDoKICAgICAgICAgIC8vLS0tIEJZVEVCSVRTKCkgLS0tLy8gLyogZ28gdG8gYnl0ZSBib3VuZGFyeSAqLwogICAgICAgICAgaG9sZCA+Pj49IGJpdHMgJiA3OwogICAgICAgICAgYml0cyAtPSBiaXRzICYgNzsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIC8vPT09IE5FRURCSVRTKDMyKTsgKi8KICAgICAgICAgIHdoaWxlIChiaXRzIDwgMzIpIHsKICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgIH0KICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgIGlmICgoaG9sZCAmIDB4ZmZmZikgIT09ICgoaG9sZCA+Pj4gMTYpIF4gMHhmZmZmKSkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIHN0b3JlZCBibG9jayBsZW5ndGhzJzsKICAgICAgICAgICAgc3RhdGUubW9kZSA9IEJBRDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5sZW5ndGggPSBob2xkICYgMHhmZmZmOwogICAgICAgICAgLy9UcmFjZXYoKHN0ZGVyciwgImluZmxhdGU6ICAgICAgIHN0b3JlZCBsZW5ndGggJXVcbiIsCiAgICAgICAgICAvLyAgICAgICAgc3RhdGUubGVuZ3RoKSk7CiAgICAgICAgICAvLz09PSBJTklUQklUUygpOwogICAgICAgICAgaG9sZCA9IDA7CiAgICAgICAgICBiaXRzID0gMDsKICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgIHN0YXRlLm1vZGUgPSBDT1BZXzsKICAgICAgICAgIGlmIChmbHVzaCA9PT0gWl9UUkVFUykgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIENPUFlfOgogICAgICAgICAgc3RhdGUubW9kZSA9IENPUFk7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBDT1BZOgogICAgICAgICAgY29weSA9IHN0YXRlLmxlbmd0aDsKICAgICAgICAgIGlmIChjb3B5KSB7CiAgICAgICAgICAgIGlmIChjb3B5ID4gaGF2ZSkgeyBjb3B5ID0gaGF2ZTsgfQogICAgICAgICAgICBpZiAoY29weSA+IGxlZnQpIHsgY29weSA9IGxlZnQ7IH0KICAgICAgICAgICAgaWYgKGNvcHkgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgIC8vLS0tIHptZW1jcHkocHV0LCBuZXh0LCBjb3B5KTsgLS0tCiAgICAgICAgICAgIG91dHB1dC5zZXQoaW5wdXQuc3ViYXJyYXkobmV4dCwgbmV4dCArIGNvcHkpLCBwdXQpOwogICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgIGhhdmUgLT0gY29weTsKICAgICAgICAgICAgbmV4dCArPSBjb3B5OwogICAgICAgICAgICBsZWZ0IC09IGNvcHk7CiAgICAgICAgICAgIHB1dCArPSBjb3B5OwogICAgICAgICAgICBzdGF0ZS5sZW5ndGggLT0gY29weTsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICAvL1RyYWNldigoc3RkZXJyLCAiaW5mbGF0ZTogICAgICAgc3RvcmVkIGVuZFxuIikpOwogICAgICAgICAgc3RhdGUubW9kZSA9IFRZUEU7CiAgICAgICAgICBicmVhazsKICAgICAgICBjYXNlIFRBQkxFOgogICAgICAgICAgLy89PT0gTkVFREJJVFMoMTQpOyAqLwogICAgICAgICAgd2hpbGUgKGJpdHMgPCAxNCkgewogICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgfQogICAgICAgICAgLy89PT0vLwogICAgICAgICAgc3RhdGUubmxlbiA9IChob2xkICYgMHgxZikvKkJJVFMoNSkqLyArIDI1NzsKICAgICAgICAgIC8vLS0tIERST1BCSVRTKDUpIC0tLS8vCiAgICAgICAgICBob2xkID4+Pj0gNTsKICAgICAgICAgIGJpdHMgLT0gNTsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIHN0YXRlLm5kaXN0ID0gKGhvbGQgJiAweDFmKS8qQklUUyg1KSovICsgMTsKICAgICAgICAgIC8vLS0tIERST1BCSVRTKDUpIC0tLS8vCiAgICAgICAgICBob2xkID4+Pj0gNTsKICAgICAgICAgIGJpdHMgLT0gNTsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIHN0YXRlLm5jb2RlID0gKGhvbGQgJiAweDBmKS8qQklUUyg0KSovICsgNDsKICAgICAgICAgIC8vLS0tIERST1BCSVRTKDQpIC0tLS8vCiAgICAgICAgICBob2xkID4+Pj0gNDsKICAgICAgICAgIGJpdHMgLT0gNDsKICAgICAgICAgIC8vLS0tLy8KICAvLyNpZm5kZWYgUEtaSVBfQlVHX1dPUktBUk9VTkQKICAgICAgICAgIGlmIChzdGF0ZS5ubGVuID4gMjg2IHx8IHN0YXRlLm5kaXN0ID4gMzApIHsKICAgICAgICAgICAgc3RybS5tc2cgPSAndG9vIG1hbnkgbGVuZ3RoIG9yIGRpc3RhbmNlIHN5bWJvbHMnOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAvLyNlbmRpZgogICAgICAgICAgLy9UcmFjZXYoKHN0ZGVyciwgImluZmxhdGU6ICAgICAgIHRhYmxlIHNpemVzIG9rXG4iKSk7CiAgICAgICAgICBzdGF0ZS5oYXZlID0gMDsKICAgICAgICAgIHN0YXRlLm1vZGUgPSBMRU5MRU5TOwogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgTEVOTEVOUzoKICAgICAgICAgIHdoaWxlIChzdGF0ZS5oYXZlIDwgc3RhdGUubmNvZGUpIHsKICAgICAgICAgICAgLy89PT0gTkVFREJJVFMoMyk7CiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgMykgewogICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgICBzdGF0ZS5sZW5zW29yZGVyW3N0YXRlLmhhdmUrK11dID0gKGhvbGQgJiAweDA3KTsvL0JJVFMoMyk7CiAgICAgICAgICAgIC8vLS0tIERST1BCSVRTKDMpIC0tLS8vCiAgICAgICAgICAgIGhvbGQgPj4+PSAzOwogICAgICAgICAgICBiaXRzIC09IDM7CiAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIH0KICAgICAgICAgIHdoaWxlIChzdGF0ZS5oYXZlIDwgMTkpIHsKICAgICAgICAgICAgc3RhdGUubGVuc1tvcmRlcltzdGF0ZS5oYXZlKytdXSA9IDA7CiAgICAgICAgICB9CiAgICAgICAgICAvLyBXZSBoYXZlIHNlcGFyYXRlIHRhYmx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mICgoMSA8PCBzdGF0ZS5sZW5iaXRzKSAtIDEpXTsvKkJJVFMoc3RhdGUubGVuYml0cykqLwogICAgICAgICAgICAgIGhlcmVfYml0cyA9IGhlcmUgPj4+IDI0OwogICAgICAgICAgICAgIGhlcmVfb3AgPSAoaGVyZSA+Pj4gMTYpICYgMHhmZjsKICAgICAgICAgICAgICBoZXJlX3ZhbCA9IGhlcmUgJiAweGZmZmY7CgogICAgICAgICAgICAgIGlmICgoaGVyZV9iaXRzKSA8PSBiaXRzKSB7IGJyZWFrOyB9CiAgICAgICAgICAgICAgLy8tLS0gUFVMTEJZVEUoKSAtLS0vLwogICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmIChoZXJlX3ZhbCA8IDE2KSB7CiAgICAgICAgICAgICAgLy8tLS0gRFJPUEJJVFMoaGVyZS5iaXRzKSAtLS0vLwogICAgICAgICAgICAgIGhvbGQgPj4+PSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgYml0cyAtPSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICAgIHN0YXRlLmxlbnNbc3RhdGUuaGF2ZSsrXSA9IGhlcmVfdmFsOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIGlmIChoZXJlX3ZhbCA9PT0gMTYpIHsKICAgICAgICAgICAgICAgIC8vPT09IE5FRURCSVRTKGhlcmUuYml0cyArIDIpOwogICAgICAgICAgICAgICAgbiA9IGhlcmVfYml0cyArIDI7CiAgICAgICAgICAgICAgICB3aGlsZSAoYml0cyA8IG4pIHsKICAgICAgICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgICAgIC8vLS0tIERST1BCSVRTKGhlcmUuYml0cykgLS0tLy8KICAgICAgICAgICAgICAgIGhvbGQgPj4+PSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgICBiaXRzIC09IGhlcmVfYml0czsKICAgICAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgICAgICAgIGlmIChzdGF0ZS5oYXZlID09PSAwKSB7CiAgICAgICAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgYml0IGxlbmd0aCByZXBlYXQnOwogICAgICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGxlbiA9IHN0YXRlLmxlbnNbc3RhdGUuaGF2ZSAtIDFdOwogICAgICAgICAgICAgICAgY29weSA9IDMgKyAoaG9sZCAmIDB4MDMpOy8vQklUUygyKTsKICAgICAgICAgICAgICAgIC8vLS0tIERST1BCSVRTKDIpIC0tLS8vCiAgICAgICAgICAgICAgICBob2xkID4+Pj0gMjsKICAgICAgICAgICAgICAgIGJpdHMgLT0gMjsKICAgICAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSBpZiAoaGVyZV92YWwgPT09IDE3KSB7CiAgICAgICAgICAgICAgICAvLz09PSBORUVEQklUUyhoZXJlLmJpdHMgKyAzKTsKICAgICAgICAgICAgICAgIG4gPSBoZXJlX2JpdHMgKyAzOwogICAgICAgICAgICAgICAgd2hpbGUgKGJpdHMgPCBuKSB7CiAgICAgICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAvLz09PS8vCiAgICAgICAgICAgICAgICAvLy0tLSBEUk9QQklUUyhoZXJlLmJpdHMpIC0tLS8vCiAgICAgICAgICAgICAgICBob2xkID4+Pj0gaGVyZV9iaXRzOwogICAgICAgICAgICAgICAgYml0cyAtPSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgICAgICBsZW4gPSAwOwogICAgICAgICAgICAgICAgY29weSA9IDMgKyAoaG9sZCAmIDB4MDcpOy8vQklUUygzKTsKICAgICAgICAgICAgICAgIC8vLS0tIERST1BCSVRTKDMpIC0tLS8vCiAgICAgICAgICAgICAgICBob2xkID4+Pj0gMzsKICAgICAgICAgICAgICAgIGJpdHMgLT0gMzsKICAgICAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAvLz09PSBORUVEQklUUyhoZXJlLmJpdHMgKyA3KTsKICAgICAgICAgICAgICAgIG4gPSBoZXJlX2JpdHMgKyA3OwogICAgICAgICAgICAgICAgd2hpbGUgKGJpdHMgPCBuKSB7CiAgICAgICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAvLz09PS8vCiAgICAgICAgICAgICAgICAvLy0tLSBEUk9QQklUUyhoZXJlLmJpdHMpIC0tLS8vCiAgICAgICAgICAgICAgICBob2xkID4+Pj0gaGVyZV9iaXRzOwogICAgICAgICAgICAgICAgYml0cyAtPSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgICAgICBsZW4gPSAwOwogICAgICAgICAgICAgICAgY29weSA9IDExICsgKGhvbGQgJiAweDdmKTsvL0JJVFMoNyk7CiAgICAgICAgICAgICAgICAvLy0tLSBEUk9QQklUUyg3KSAtLS0vLwogICAgICAgICAgICAgICAgaG9sZCA+Pj49IDc7CiAgICAgICAgICAgICAgICBiaXRzIC09IDc7CiAgICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGlmIChzdGF0ZS5oYXZlICsgY29weSA+IHN0YXRlLm5sZW4gKyBzdGF0ZS5uZGlzdCkgewogICAgICAgICAgICAgICAgc3RybS5tc2cgPSAnaW52YWxpZCBiaXQgbGVuZ3RoIHJlcGVhdCc7CiAgICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIHdoaWxlIChjb3B5LS0pIHsKICAgICAgICAgICAgICAgIHN0YXRlLmxlbnNbc3RhdGUuaGF2ZSsrXSA9IGxlbjsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KCiAgICAgICAgICAvKiBoYW5kbGUgZXJyb3IgYnJlYWtzIGluIHdoaWxlICovCiAgICAgICAgICBpZiAoc3RhdGUubW9kZSA9PT0gQkFEKSB7IGJyZWFrOyB9CgogICAgICAgICAgLyogY2hlY2sgZm9yIGVuZC1vZi1ibG9jayBjb2RlIChiZXR0ZXIgaGF2ZSBvbmUpICovCiAgICAgICAgICBpZiAoc3RhdGUubGVuc1syNTZdID09PS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AgICAgICAgc3RhdGUubW9kZSA9IEJBRDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CgogICAgICAgICAgc3RhdGUuZGlzdGJpdHMgPSA2OwogICAgICAgICAgLy9zdGF0ZS5kaXN0Y29kZS5jb3B5KHN0YXRlLmNvZGVzKTsKICAgICAgICAgIC8vIFN3aXRjaCB0byB1c2UgZHluYW1pYyB0YWJsZQogICAgICAgICAgc3RhdGUuZGlzdGNvZGUgPSBzdGF0ZS5kaXN0ZHluOwogICAgICAgICAgb3B0cyA9IHsgYml0czogc3RhdGUuZGlzdGJpdHMgfTsKICAgICAgICAgIHJldCA9IGluZnRyZWVzKERJU1RTLCBzdGF0ZS5sZW5zLCBzdGF0ZS5ubGVuLCBzdGF0ZS5uZGlzdCwgc3RhdGUuZGlzdGNvZGUsIDAsIHN0YXRlLndvcmssIG9wdHMpOwogICAgICAgICAgLy8gV2UgaGF2ZSBzZXBhcmF0ZSB0YWJsZXMgJiBubyBwb2ludGVycy4gMiBjb21tZW50ZWQgbGluZXMgYmVsb3cgbm90IG5lZWRlZC4KICAgICAgICAgIC8vIHN0YXRlLm5leHRfaW5kZXggPSBvcHRzLnRhYmxlX2luZGV4OwogICAgICAgICAgc3RhdGUuZGlzdGJpdHMgPSBvcHRzLmJpdHM7CiAgICAgICAgICAvLyBzdGF0ZS5kaXN0Y29kZSA9IHN0YXRlLm5leHQ7CgogICAgICAgICAgaWYgKHJldCkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGRpc3RhbmNlcyBzZXQnOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICdpbmZsYXRlOiAgICAgICBjb2RlcyBva1xuJykpOwogICAgICAgICAgc3RhdGUubW9kZSA9IExFTl87CiAgICAgICAgICBpZiAoZmx1c2ggPT09IFpfVFJFRVMpIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBMRU5fOgogICAgICAgICAgc3RhdGUubW9kZSA9IExFTjsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIExFTjoKICAgICAgICAgIGlmIChoYXZlID49IDYgJiYgbGVmdCA+PSAyNTgpIHsKICAgICAgICAgICAgLy8tLS0gUkVTVE9SRSgpIC0tLQogICAgICAgICAgICBzdHJtLm5leHRfb3V0ID0gcHV0OwogICAgICAgICAgICBzdHJtLmF2YWlsX291dCA9IGxlZnQ7CiAgICAgICAgICAgIHN0cm0ubmV4dF9pbiA9IG5leHQ7CiAgICAgICAgICAgIHN0cm0uYXZhaWxfaW4gPSBoYXZlOwogICAgICAgICAgICBzdGF0ZS5ob2xkID0gaG9sZDsKICAgICAgICAgICAgc3RhdGUuYml0cyA9IGJpdHM7CiAgICAgICAgICAgIC8vLS0tCiAgICAgICAgICAgIGluZmZhc3Qoc3RybSwgX291dCk7CiAgICAgICAgICAgIC8vLS0tIExPQUQoKSAtLS0KICAgICAgICAgICAgcHV0ID0gc3RybS5uZXh0X291dDsKICAgICAgICAgICAgb3V0cHV0ID0gc3RybS5vdXRwdXQ7CiAgICAgICAgICAgIGxlZnQgPSBzdHJtLmF2YWlsX291dDsKICAgICAgICAgICAgbmV4dCA9IHN0cm0ubmV4dF9pbjsKICAgICAgICAgICAgaW5wdXQgPSBzdHJtLmlucHV0OwogICAgICAgICAgICBoYXZlID0gc3RybS5hdmFpbF9pbjsKICAgICAgICAgICAgaG9sZCA9IHN0YXRlLmhvbGQ7CiAgICAgICAgICAgIGJpdHMgPSBzdGF0ZS5iaXRzOwogICAgICAgICAgICAvLy0tLQoKICAgICAgICAgICAgaWYgKHN0YXRlLm1vZGUgPT09IFRZUEUpIHsKICAgICAgICAgICAgICBzdGF0ZS5iYWNrID0gLTE7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5iYWNrID0gMDsKICAgICAgICAgIGZvciAoOzspIHsKICAgICAgICAgICAgaGVyZSA9IHN0YXRlLmxlbmNvZGVbaG9sZCAmICgoMSA8PCBzdGF0ZS5sZW5iaXRzKSAtIDEpXTsgIC8qQklUUyhzdGF0ZS5sZW5iaXRzKSovCiAgICAgICAgICAgIGhlcmVfYml0cyA9IGhlcmUgPj4+IDI0OwogICAgICAgICAgICBoZXJlX29wID0gKGhlcmUgPj4+IDE2KSAmIDB4ZmY7CiAgICAgICAgICAgIGhlcmVfdmFsID0gaGVyZSAmIDB4ZmZmZjsKCiAgICAgICAgICAgIGlmIChoZXJlX2JpdHMgPD0gYml0cykgeyBicmVhazsgfQogICAgICAgICAgICAvLy0tLSBQVUxMQllURSgpIC0tLS8vCiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIH0KICAgICAgICAgIGlmIChoZXJlX29wICYmIChoZXJlX29wICYgMHhmMCkgPT09IDApIHsKICAgICAgICAgICAgbGFzdF9iaXRzID0gaGVyZV9iaXRzOwogICAgICAgICAgICBsYXN0X29wID0gaGVyZV9vcDsKICAgICAgICAgICAgbGFzdF92YWwgPSBoZXJlX3ZhbDsKICAgICAgICAgICAgZm9yICg7OykgewogICAgICAgICAgICAgIGhlcmUgPSBzdGF0ZS5sZW5jb2RlW2xhc3RfdmFsICsKICAgICAgICAgICAgICAgICAgICAgICgoaG9sZCAmICgoMSA8PCAobGFzdF9iaXRzICsgbGFzdF9vcCkpIC0gMSkpLypCSVRTKGxhc3QuYml0cyArIGxhc3Qub3ApKi8gPj4gbGFzdF9iaXRzKV07CiAgICAgICAgICAgICAgaGVyZV9iaXRzID0gaGVyZSA+Pj4gMjQ7CiAgICAgICAgICAgICAgaGVyZV9vcCA9IChoZXJlID4+PiAxNikgJiAweGZmOwogICAgICAgICAgICAgIGhlcmVfdmFsID0gaGVyZSAmIDB4ZmZmZjsKCiAgICAgICAgICAgICAgaWYgKChsYXN0X2JpdHMgKyBoZXJlX2JpdHMpIDw9IGJpdHMpIHsgYnJlYWs7IH0KICAgICAgICAgICAgICAvLy0tLSBQVUxMQllURSgpIC0tLS8vCiAgICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8tLS0gRFJPUEJJVFMobGFzdC5iaXRzKSAtLS0vLwogICAgICAgICAgICBob2xkID4+Pj0gbGFzdF9iaXRzOwogICAgICAgICAgICBiaXRzIC09IGxhc3RfYml0czsKICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICBzdGF0ZS5iYWNrICs9IGxhc3RfYml0czsKICAgICAgICAgIH0KICAgICAgICAgIC8vLS0tIERST1BCSVRTKGhlcmUuYml0cykgLS0tLy8KICAgICAgICAgIGhvbGQgPj4+PSBoZXJlX2JpdHM7CiAgICAgICAgICBiaXRzIC09IGhlcmVfYml0czsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIHN0YXRlLmJhY2sgKz0gaGVyZV9iaXRzOwogICAgICAgICAgc3RhdGUubGVuZ3RoID0gaGVyZV92YWw7CiAgICAgICAgICBpZiAoaGVyZV9vcCA9PT0gMCkgewogICAgICAgICAgICAvL1RyYWNldnYoKHN0ZGVyciwgaGVyZS52YWwgPj0gMHgyMCAmJiBoZXJlLnZhbCA8IDB4N2YgPwogICAgICAgICAgICAvLyAgICAgICAgImluZmxhdGU6ICAgICAgICAgbGl0ZXJhbCAnJWMnXG4iIDoKICAgICAgICAgICAgLy8gICAgICAgICJpbmZsYXRlOiAgICAgICAgIGxpdGVyYWwgMHglMDJ4XG4iLCBoZXJlLnZhbCkpOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gTElUOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChoZXJlX29wICYgMzIpIHsKICAgICAgICAgICAgLy9UcmFjZXZ2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgICAgIGVuZCBvZiBibG9ja1xuIikpOwogICAgICAgICAgICBzdGF0ZS5iYWNrID0gLTE7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBUWVBFOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChoZXJlX29wICYgNjQpIHsKICAgICAgICAgICAgc3RybS5tc2cgPSAnaW52YWxpZCBsaXRlcmFsL2xlbmd0aCBjb2RlJzsKICAgICAgICAgICAgc3RhdGUubW9kZSA9IEJBRDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5leHRyYSA9IGhlcmVfb3AgJiAxNTsKICAgICAgICAgIHN0YXRlLm1vZGUgPSBMRU5FWFQ7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBMRU5FWFQ6CiAgICAgICAgICBpZiAoc3RhdGUuZXh0cmEpIHsKICAgICAgICAgICAgLy89PT0gTkVFREJJVFMoc3RhdGUuZXh0cmEpOwogICAgICAgICAgICBuID0gc3RhdGUuZXh0cmE7CiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgbikgewogICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICBob2xkICs9IGlucHV0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VEUoKSAtLS0vLwogICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICB9CiAgICAgICAgICBpZiAoKGhlcmVfb3AgJiAweGYwKSA9PT0gMCkgewogICAgICAgICAgICBsYXN0X2JpdHMgPSBoZXJlX2JpdHM7CiAgICAgICAgICAgIGxhc3Rfb3AgPSBoZXJlX29wOwogICAgICAgICAgICBsYXN0X3ZhbCA9IGhlcmVfdmFsOwogICAgICAgICAgICBmb3IgKDs7KSB7CiAgICAgICAgICAgICAgaGVyZSA9IHN0YXRlLmRpc3Rjb2RlW2xhc3RfdmFsICsKICAgICAgICAgICAgICAgICAgICAgICgoaG9sZCAmICgoMSA8PCAobGFzdF9iaXRzICsgbGFzdF9vcCkpIC0gMSkpLypCSVRTKGxhc3QuYml0cyArIGxhc3Qub3ApKi8gPj4gbGFzdF9iaXRzKV07CiAgICAgICAgICAgICAgaGVyZV9iaXRzID0gaGVyZSA+Pj4gMjQ7CiAgICAgICAgICAgICAgaGVyZV9vcCA9IChoZXJlID4+PiAxNikgJiAweGZmOwogICAgICAgICAgICAgIGhlcmVfdmFsID0gaGVyZSAmIDB4ZmZmZjsKCiAgICAgICAgICAgICAgaWYgKChsYXN0X2JpdHMgKyBoZXJlX2JpdHMpIDw9IGJpdHMpIHsgYnJlYWs7IH0KICAgICAgICAgICAgICAvLy0tLSBQVUxMQllURSgpIC0tLS8vCiAgICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8tLS0gRFJPUEJJVFMobGFzdC5iaXRzKSAtLS0vLwogICAgICAgICAgICBob2xkID4+Pj0gbGFzdF9iaXRzOwogICAgICAgICAgICBiaXRzIC09IGxhc3RfYml0czsKICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICBzdGF0ZS5iYWNrICs9IGxhc3RfYml0czsKICAgICAgICAgIH0KICAgICAgICAgIC8vLS0tIERST1BCSVRTKGhlcmUuYml0cykgLS0tLy8KICAgICAgICAgIGhvbGQgPj4+PSBoZXJlX2JpdHM7CiAgICAgICAgICBiaXRzIC09IGhlcmVfYml0czsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIHN0YXRlLmJhY2sgKz0gaGVyZV9iaXRzOwogICAgICAgICAgaWYgKGhlcmVfb3AgJiA2NCkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGRpc3RhbmNlIGNvZGUnOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIHN0YXRlLm9mZnNldCA9IGhlcmVfdmFsOwogICAgICAgICAgc3RhdGUuZXh0cmEgPSAoaGVyZV9vcCkgJiAxNTsKICAgICAgICAgIHN0YXRlLm1vZGUgPSBESVNURVhUOwogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgRElTVEVYVDoKICAgICAgICAgIGlmIChzdGF0ZS5leHRyYSkgewogICAgICAgICAgICAvLz09PSBORUVEQklUUyhzdGF0ZS5leHRyYSk7CiAgICAgICAgICAgIG4gPSBzdGF0ZS5leHRyYTsKICAgICAgICAgICAgd2hpbGUgKGJpdHMgPCBuKSB7CiAgICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgfQogICAgICAgICAgICAvLz09PS8vCiAgICAgICAgICAgIHN0YXRlLm9mZnNldCArPSBob2xkICYgKCgxIDw8IHN0YXRlLmV4dHJhKSAtIDEpLypCSVRTKHN0YXRlLmV4dHJhKSovOwogICAgICAgICAgICAvLy0tLSBEUk9QQklUUyhzdGF0ZS5leHRyYSkgLS0tLy8KICAgICAgICAgICAgaG9sZCA+Pj49IHN0YXRlLmV4dHJhOwogICAgICAgICAgICBiaXRzIC09IHN0YXRlLmV4dHJhOwogICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgIHN0YXRlLmJhY2sgKz0gc3RhdGUuZXh0cmE7CiAgICAgICAgICB9CiAgLy8jaWZkZWYgSU5GTEFURV9TVFJJQ1QKICAgICAgICAgIGlmIChzdGF0ZS5vZmZzZXQgPiBzdGF0ZS5kbWF4KSB7CiAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgZGlzdGFuY2UgdG9vIGZhciBiYWNrJzsKICAgICAgICAgICAgc3RhdGUubW9kZSA9IEJBRDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgLy8jZW5kaWYKICAgICAgICAgIC8vVHJhY2V2digoc3RkZXJyLCAiaW5mbGF0ZTogICAgICAgICBkaXN0YW5jZSAldVxuIiwgc3RhdGUub2Zmc2V0KSk7CiAgICAgICAgICBzdGF0ZS5tb2RlID0gTUFUQ0g7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBNQVRDSDoKICAgICAgICAgIGlmIChsZWZ0ID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgY29weSA9IF9vdXQgLSBsZWZ0OwogICAgICAgICAgaWYgKHN0YXRlLm9mZnNldCA+IGNvcHkpIHsgICAgICAgICAv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YnJlYWs7CiAgLy8jZW5kaWYKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiAoY29weSA+IHN0YXRlLnduZXh0KSB7CiAgICAgICAgICAgICAgY29weSAtPSBzdGF0ZS53bmV4dDsKICAgICAgICAgICAgICBmcm9tID0gc3RhdGUud3NpemUgLSBjb3B5OwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIGZyb20gPSBzdGF0ZS53bmV4dCAtIGNvcHk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGNvcHkgPiBzdGF0ZS5sZW5ndGgpIHsgY29weSA9IHN0YXRlLmxlbmd0aDsgfQogICAgICAgICAgICBmcm9tX3NvdXJjZSA9IHN0YXRlLndpbmRvdzsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgeyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8qIGNvcHkgZnJvbSBvdXRwdXQgKi8KICAgICAgICAgICAgZnJvbV9zb3VyY2UgPSBvdXRwdXQ7CiAgICAgICAgICAgIGZyb20gPSBwdXQgLSBzdGF0ZS5vZmZzZXQ7CiAgICAgICAgICAgIGNvcHkgPSBzdGF0ZS5sZW5ndGg7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAoY29weSA+IGxlZnQpIHsgY29weSA9IGxlZnQ7IH0KICAgICAgICAgIGxlZnQgLT0gY29weTsKICAgICAgICAgIHN0YXRlLmxlbmd0aCAtPSBjb3B5OwogICAgICAgICAgZG8gewogICAgICAgICAgICBvdXRwdXRbcHV0KytdID0gZnJvbV9zb3VyY2VbZnJvbSsrXTsKICAgICAgICAgIH0gd2hpbGUgKC0tY29weSk7CiAgICAgICAgICBpZiAoc3RhdGUubGVuZ3RoID09PSAwKSB7IHN0YXRlLm1vZGUgPSBMRU47IH0KICAgICAgICAgIGJyZWFrOwogICAgICAgIGNhc2UgTElUOgogICAgICAgICAgaWYgKGxlZnQgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICBvdXRwdXRbcHV0KytdID0gc3RhdGUubGVuZ3RoOwogICAgICAgICAgbGVmdC0tOwogICAgICAgICAgc3RhdGUubW9kZSA9IExFTjsKICAgICAgICAgIGJyZWFrOwogICAgICAgIGNhc2UgQ0hFQ0s6CiAgICAgICAgICBpZiAoc3RhdGUud3JhcCkgewogICAgICAgICAgICAvLz09PSBORUVEQklUUygzMik7CiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgMzIpIHsKICAgICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgLy8gVXNlICd8JyBpbnN0ZWFkIG9mICcrJyB0byBtYWtlIHN1cmUgdGhhdCByZXN1bHQgaXMgc2lnbmVkCiAgICAgICAgICAgICAgaG9sZCB8PSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgX291dCAtPSBsZWZ0OwogICAgICAgICAgICBzdHJtLnRvdGFsX291dCArPSBfb3V0OwogICAgICAgICAgICBzdGF0ZS50b3RhbCArPSBfb3V0OwogICAgICAgICAgICBpZiAoX291dCkgewogICAgICAgICAgICAgIHN0cm0uYWRsZXIgPSBzdGF0ZS5jaGVjayA9CiAgICAgICAgICAgICAgICAgIC8qVVBEQVRFKHN0YXRlLmNoZWNrLCBwdXQgLSBfb3V0LCBfb3V0KTsqLwogICAgICAgICAgICAgICAgICAoc3RhdGUuZmxhZ3MgPyBjcmMzMl8xKHN0YXRlLmNoZWNrLCBvdXRwdXQsIF9vdXQsIHB1dCAtIF9vdXQpIDogYWRsZXIzMl8xKHN0YXRlLmNoZWNrLCBvdXRwdXQsIF9vdXQsIHB1dCAtIF9vdXQpKTsKCiAgICAgICAgICAgIH0KICAgICAgICAgICAgX291dCA9IGxlZnQ7CiAgICAgICAgICAgIC8vIE5COiBjcmMzMiBzdG9yZWQgYXMgc2lnbmVkIDMyLWJpdCBpbnQsIHpzd2FwMzIgcmV0dXJucyBzaWduZWQgdG9vCiAgICAgICAgICAgIGlmICgoc3RhdGUuZmxhZ3MgPyBob2xkIDogenN3YXAzMihob2xkKSkgIT09IHN0YXRlLmNoZWNrKSB7CiAgICAgICAgICAgICAgc3RybS5tc2cgPSAnaW5jb3JyZWN0IGRhdGEgY2hlY2snOwogICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy89PT0gSU5JVEJJVFMoKTsKICAgICAgICAgICAgaG9sZCA9IDA7CiAgICAgICAgICAgIGJpdHMgPSAwOwogICAgICAgICAgICAvLz09PS8vCiAgICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgIGNoZWNrIG1hdGNoZXMgdHJhaWxlclxuIikpOwogICAgICAgICAgfQogICAgICAgICAgc3RhdGUubW9kZSA9IExFTkdUSDsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIExFTkdUSDoKICAgICAgICAgIGlmIChzdGF0ZS53cmFwICYmIHN0YXRlLmZsYWdzKSB7CiAgICAgICAgICAgIC8vPT09IE5FRURCSVRTKDMyKTsKICAgICAgICAgICAgd2hpbGUgKGJpdHMgPCAzMikgewogICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgICBpZiAoaG9sZCAhPT0gKHN0YXRlLnRvdGFsICYgMHhmZmZmZmZmZikpIHsKICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdpbmNvcnJlY3QgbGVuZ3RoIGNoZWNrJzsKICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgICBiaXRzID0gMDsKICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgICAvL1RyYWNldigoc3RkZXJyLCAiaW5mbGF0ZTogICBsZW5ndGggbWF0Y2hlcyB0cmFpbGVyXG4iKSk7CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5tb2RlID0gRE9ORTsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIERPTkU6CiAgICAgICAgICByZXQgPSBaX1NUUkVBTV9FTkQkMTsKICAgICAgICAgIGJyZWFrIGluZl9sZWF2ZTsKICAgICAgICBjYXNlIEJBRDoKICAgICAgICAgIHJldCA9IFpfREFUQV9FUlJPUiQxOwogICAgICAgICAgYnJlYWsgaW5mX2xlYXZlOwogICAgICAgIGNhc2UgTUVNOgogICAgICAgICAgcmV0dXJuIFpfTUVNX0VSUk9SJDE7CiAgICAgICAgY2FzZSBTWU5DOgogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICByZXR1cm4gWl9TVFJFQU1fRVJST1IkMTsKICAgICAgfQogICAgfQoKICAgIC8vIGluZl9sZWF2ZSA8LSBoZXJlIGlzIHJlYWwgcGxhY2UgZm9yICJnb3RvIGluZl9sZWF2ZSIsIGVtdWxhdGVkIHZpYSAiYnJlYWsgaW5mX2xlYXZlIgoKICAgIC8qCiAgICAgICBSZXR1cm4gZnJvbSBpbmZsYXRlKCksIHVwZGF0aW5nIHRoZSB0b3RhbCBjb3VudHMgYW5kIHRoZSBjaGVjayB2YWx1ZS4KICAgICAgIElmIH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T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09Ki8KICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwoKICBjb25zdCB7CiAgICBaX05PX0ZMVVNILCBaX0ZJTklTSCwKICAgIFpfT0ssIFpfU1RSRUFNX0VORCwgWl9ORUVEX0RJQ1QsIFpfU1RSRUFNX0VSUk9SLCBaX0RBVEFfRVJST1IsIFpfTUVNX0VSUk9SCiAgfSA9IGNvbnN0YW50cyQyOwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwoKCiAgLyoqCiAgICogY2xhc3MgSW5mbGF0ZQogICAqCiAgICogR2VuZXJpYyBKUy1zdHlsZSB3cmFwcGVyIGZvciB6bGliIGNhbGxzLiBJZiB5b3UgZG9uJ3QgbmVlZAogICAqIHN0cmVhbWluZyBiZWhhdmlvdXIgLSB1c2UgbW9yZSBzaW1wbGUgZnVuY3Rpb25zOiBbW2luZmxhdGVdXQogICAqIGFuZCBbW2luZmxhdGVSYXddXS4KICAgKiovCgogIC8qIGludGVybmFsCiAgICogaW5mbGF0ZS5jaHVua3MgLT4gQXJyYXkKICAgKgogICAqIENodW5rcyBvZiBvdXRwdXQgZGF0YSwgaWYgW1tJbmZsYXRlI29uRGF0YV1dIG5vdCBvdmVycmlkZGVuLgogICAqKi8KCiAgLyoqCiAgICogSW5mbGF0ZS5yZXN1bHQgLT4gVWludDhBcnJheXxTdHJpbmcKICAgKgogICAqIFVuY29tcHJlc3NlZCByZXN1bHQsIGdlbmVyYXRlZCBieSBkZWZhdWx0IFtbSW5mbGF0ZSNvbkRhdGFdXQogICAqIGFuZCBbW0luZmxhdGUjb25FbmRdXSBoYW5kbGVycy4gRmlsbGVkIGFmdGVyIHlvdSBwdXNoIGxhc3QgY2h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F0dXMgPT09IFpfT0spIHsKICAgICAgICAgIHN0YXR1cyA9IGluZmxhdGVfMSQyLmluZmxhdGUoc3RybSwgX2ZsdXNoX21vZGUpOwogICAgICAgIH0gZWxzZSBpZiAoc3RhdHVzID09PSBaX0RBVEFfRVJST1IpIHsKICAgICAgICAgIC8vIFJlcGxhY2UgY29kZSB3aXRoIG1vcmUgdmVyYm9zZQogICAgICAgICAgc3RhdHVzID0gWl9ORUVEX0RJQ1Q7CiAgICAgICAgfQogICAgICB9CgogICAgICAvLyBTa2lwIHNueWMgbWFya2VycyBpZiBtb3JlIGRhdGEgZm9sbG93cyBhbmQgbm90IHJhdyBtb2RlCiAgICAgIHdoaWxlIChzdHJtLmF2YWlsX2luID4gMCAmJgogICAgICAgICAgICAgc3RhdHVzID09PSBaX1NUUkVBTV9FTkQgJiYKICAgICAgICAgICAgIHN0cm0uc3RhdGUud3JhcCA+IDAgJiYKICAgICAgICAgICAgIGRhdGFbc3RybS5uZXh0X2luXSAhPT0gMCkKICAgICAgewogICAgICAgIGluZmxhdGVfMSQyLmluZmxhdGVSZXNldChzdHJtKTsKICAgICAgICBzdGF0dXMgPSBpbmZsYXRlXzEkMi5pbmZsYXRlKHN0cm0sIF9mbHVzaF9tb2RlKTsKICAgICAgfQoKICAgICAgc3dpdGNoIChzdGF0dXMpIHsKICAgICAgICBjYXNlIFpfU1RSRUFNX0VSUk9SOgogICAgICAgIGNhc2UgWl9EQVRBX0VSUk9SOgogICAgICAgIGNhc2UgWl9ORUVEX0RJQ1Q6CiAgICAgICAgY2FzZSBaX01FTV9FUlJPUjoKICAgICAgICAgIHRoaXMub25FbmQoc3RhdHVzKTsKICAgICAgICAgIHRoaXMuZW5kZWQgPSB0cnVlOwogICAgICAgICAgcmV0dXJuIGZhbHNlOwogICAgICB9CgogICAgICAvLyBSZW1lbWJlciByZWFsIGBhdmFpbF9vdXRgIHZhbHVlLCBiZWNhdXNlIHdlIG1heSBwYXRjaCBvdXQgYnVmZmVyIGNvbnR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AgICAgcmV0dXJuIGluZmxhdGVfMShuZXcgVWludDhBcnJheShidWZmZXIpKS5idWZmZXI7CiAgICB9CiAgfQoKICBjbGFzcyBQYWNrYml0c0RlY29kZXIgZXh0ZW5kcyBCYXNlRGVjb2RlciB7CiAgICBkZWNvZGVCbG9jayhidWZmZXIpIHsKICAgICAgY29uc3QgZGF0YVZpZXcgPSBuZXcgRGF0YVZpZXcoYnVmZmVyKTsKICAgICAgY29uc3Qgb3V0ID0gW107CgogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IGJ1ZmZlci5ieXRlTGVuZ3RoOyArK2kpIHsKICAgICAgICBsZXQgaGVhZGVyID0gZGF0YVZpZXcuZ2V0SW50OChpKTsKICAgICAgICBpZiAoaGVhZGVyIDwgMCkgewogICAgICAgICAgY29uc3QgbmV4dCA9IGRhdGFWaWV3LmdldFVpbnQ4KGkgKyAxKTsKICAgICAgICAgIGhlYWRlciA9IC1oZWFkZXI7CiAgICAgICAgICBmb3IgKGxldCBqID0gMDsgaiA8PSBoZWFkZXI7ICsraikgewogICAgICAgICAgICBvdXQucHVzaChuZXh0KTsKICAgICAgICAgIH0KICAgICAgICAgIGkgKz0gMTsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgZm9yIChsZXQgaiA9IDA7IGogPD0gaGVhZGVyOyArK2opIHsKICAgICAgICAgICAgb3V0LnB1c2goZGF0YVZpZXcuZ2V0VWludDgoaSArIGogKyAxKSk7CiAgICAgICAgICB9CiAgICAgICAgICBpICs9IGhlYWRlciArIDE7CiAgICAgICAgfQogICAgICB9CiAgICAgIHJldHVybiBuZXcgVWludDhBcnJheShvdXQpLmJ1ZmZlcjsKICAgIH0KICB9CgogIHZhciBMZXJjRGVjb2RlID0ge2V4cG9ydHM6IHt9fTsKCiAgLyoganNoaW50IGZvcmluOiBmYWxzZSwgYml0d2lzZTogZmFsc2UgKi8KCiAgKGZ1bmN0aW9uIChtb2R1bGUpIHsKICAvKgogIENvcHlyaWdodCAyMDE1LTIwMT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XByZXNzZWREYXRhLnJlc3VsdE1hc2s7CiAgICAgICAgfQoKICAgICAgICBpZiAob3B0aW9ucy5yZXR1cm5FbmNvZGVkTWFzayAmJiBwYXJzZWREYXRhLm1hc2spIHsKICAgICAgICAgIHJlc3VsdC5lbmNvZGVkTWFza0RhdGEgPSBwYXJzZWREYXRhLm1hc2suYml0c2V0ID8gcGFyc2VkRGF0YS5tYXNrLmJpdHNldCA6IG51bGw7CiAgICAgICAgfQoKICAgICAgICBpZiAob3B0aW9ucy5yZXR1cm5GaWxlSW5mbykgewogICAgICAgICAgcmVzdWx0LmZpbGVJbmZvID0gZm9ybWF0RmlsZUluZm8ocGFyc2VkRGF0YSk7CiAgICAgICAgICBpZiAob3B0aW9ucy5jb21wdXRlVXNlZEJpdERlcHRocykgewogICAgICAgICAgICByZXN1bHQuZmlsZUluZm8uYml0RGVwdGhzID0gY29tcHV0ZVVzZWRCaXREZXB0aHMocGFyc2VkRGF0YSk7CiAgICAgICAgICB9CiAgICAgICAgfQoKICAgICAgICByZXR1cm4gcmVzdWx0OwogICAgICB9OwoKICAgICAgdmFyIHVuY29tcHJlc3NQaXhlbFZhbHVlcyA9IGZ1bmN0aW9uKGRhdGEsIFR5cGVkQXJyYXlDbGFzcywgbWFza0JpdHNldCwgbm9EYXRhVmFsdWUsIHN0b3JlRGVjb2RlZE1hc2spIHsKICAgICAgICB2YXIgYmxvY2tJZHggPSAwOwogICAgICAgIHZhciBudW1YID0gZGF0YS5waXhlbHMubnVtQmxvY2tzWDsKICAgICAgICB2YXIgbnVtWSA9IGRhdGEucGl4ZWxzLm51bUJsb2Nrc1k7CiAgICAgICAgdmFyIGJsb2NrV2lkdGggPSBNYXRoLmZsb29yKGRhdGEud2lkdGggLyBudW1YKTsKICAgICAgICB2YXIgYmxvY2tIZWlnaHQgPSBNYXRoLmZsb29yKGRhdGEuaGVpZ2h0IC8gbnVtWSk7CiAgICAgICAgdmFyIHNjYWxlID0gMiAqIGRhdGEubWF4WkVycm9yOwogICAgICAgIHZhciBtaW5WYWx1ZSA9IE51bWJlci5NQVhfVkFMVUUsIGN1cnJlbnRWYWx1ZTsKICAgICAgICBtYXNrQml0c2V0ID0gbWFza0JpdHNldCB8fCAoKGRhdGEubWFzaykgPyBkYXRhLm1hc2suYml0c2V0IDogbnVsbCk7CgogICAgICAgIHZhciByZXN1bHRQaXhlbHMsIHJlc3VsdE1hc2s7CiAgICAgICAgcmVzdWx0UGl4ZWxzID0gbmV3IFR5cGVkQXJyYXlDbGFzcyhkYXRhLndpZHRoICogZGF0YS5oZWlnaHQpOwogICAgICAgIGlmIChzdG9yZURlY29kZWRNYXNrICYmIG1hc2tCaXRzZXQpIHsKICAgICAgICAgIHJlc3VsdE1hc2sgPSBuZXcgVWludDhBcnJheShkYXRhLndpZHRoICogZGF0YS5oZWlnaHQpOwogICAgICAgIH0KICAgICAgICB2YXIgYmxvY2tEYXRhQnVmZmVyID0gbmV3IEZsb2F0MzJBcnJheShibG9ja1dpZHRoICogYmxvY2tIZWlnaHQpOwoKICAgICAgICB2YXIgeHgsIHl5OwogICAgICAgIGZvciAodmFyIHkgPSAwOyB5IDw9IG51bVk7IHkrKykgewogICAgICAgICAgdmFyIHRoaXNCbG9ja0hlaWdodCA9ICh5ICE9PSBudW1ZKSA/IGJsb2NrSGVpZ2h0IDogKGRhdGEuaGVpZ2h0ICUgbnVtWSk7CiAgICAgICAgICBpZiAodGhpc0Jsb2NrSGVpZ2h0ID09PSAwKSB7CiAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgfQogICAgICAgICAgZm9yICh2YXIgeCA9IDA7IHggPD0gbnVtWDsgeCsrKSB7CiAgICAgICAgICAgIHZhciB0aGlzQmxvY2tXaWR0aCA9ICh4ICE9PSBudW1YKSA/IGJsb2NrV2lkdGggOiAoZGF0YS53aWR0aCAlIG51bVgpOwogICAgICAgICAgICBpZiAodGhpc0Jsb2NrV2lkdGggPT09IDApIHsKICAgICAgICAgICAgICBjb250aW51ZTsKICAgICAgICAgICAgfQoKICAgICAgICAgICAgdmFyIG91dFB0ciA9IHkgKiBkYXRhLndpZHRoICogYmxvY2tIZWlnaHQgKyB4ICogYmxvY2tXaWR0aDsKICAgICAgICAgICAgdmFyIG91dFN0cmlkZSA9IGRhdGEud2lkdGggLSB0aGlzQmxvY2tXaWR0aDsKCiAgICAgICAgICAgIHZhciBibG9jayA9IGRhdGEucGl4ZWxzLmJsb2Nrc1tibG9ja0lkeF07CgogICAgICAgICAgICB2YXIgYmxvY2tEYXRhLCBibG9ja1B0ciwgY29uc3RWYWx1ZTsKICAgICAgICAgICAgaWYgKGJsb2NrLmVuY29kaW5nIDwgMikgewogICAgICAgICAgICAgIC8vIGJsb2NrIGlzIGVpdGhlciB1bmNvbXByZXNzZWQgb3IgYml0LXN0dWZmZWQgKGVuY29kaW5ncyAwIGFuZCAxKQogICAgICAgICAgICAgIGlmIChibG9jay5lbmNvZGluZyA9PT0gMCkgewogICAgICAgICAgICAgICAgLy8gYmxvY2sgaXMgdW5jb21wcmVzc2VkCiAgICAgICAgICAgICAgICBibG9ja0RhdGEgPSBibG9jay5yYXdEYXRhOwogICAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgICAvLyBibG9jayBpcyBiaXQtc3R1ZmZlZAogICAgICAgICAgICAgICAgdW5zdHVmZihibG9jay5zdHVmZmVkRGF0YSwgYmxvY2suYml0c1BlclBpeGVsLCBibG9jay5udW1WYWxpZFBpeGVscywgYmxvY2sub2Zmc2V0LCBzY2FsZSwgYmxvY2tEYXRhQnVmZmVyLCBkYXRhLnBpeGVscy5tYXhWYWx1ZSk7CiAgICAgICAgICAgICAgICBibG9ja0RhdGEgPSBibG9ja0RhdGFCdWZmZXI7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGJsb2NrUHRyID0gMDsKICAgICAgICAgICAgfQogICAgICAgICAgICBlbHNlIGlmIChibG9jay5lbmNvZGluZyA9PT0gMikgewogICAgICAgICAgICAgIC8vIGJsb2NrIGlzIGFsbCAwCiAgICAgICAgICAgICAgY29uc3RWYWx1ZSA9IDA7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgLy8gYmxvY2sgaGFzIGNvbnN0YW50IHZhbHVlIChlbmNvZGluZyA9PT0gMykKICAgICAgICAgICAgICBjb25zdFZhbHVlID0gYmxvY2sub2Zmc2V0OwogICAgICAgICAgICB9CgogICAgICAgICAgICB2YXIgbWFza0J5dGU7CiAgICAgICAgICAgIGlmIChtYXNrQml0c2V0KSB7CiAgICAgICAgICAgICAgZm9yICh5eSA9IDA7IHl5IDwgdGhpc0Jsb2NrSGVpZ2h0OyB5eSsrKSB7CiAgICAgICAgICAgICAgICBpZiAob3V0UHRyICYgNykgewogICAgICAgICAgICAgICAgICAvLwogICAgICAgICAgICAgICAgICBtYXNrQnl0ZSA9IG1hc2tCaXRzZXRbb3V0UHRyID4+IDNdOwogICAgICAgICAgICAgICAgICBtYXNrQnl0ZSA8PD0gb3V0UHRyICYgNzsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGZvciAoeHggPSAwOyB4eCA8IHRoaXNCbG9ja1dpZHRoOyB4eCsrKSB7CiAgICAgICAgICAgICAgICAgIGlmICghKG91dFB0ciAmIDcpKSB7CiAgICAgICAgICAgICAgICAgICAgLy8gcmVhZCBuZXh0IGJ5dGUgZnJvbSBtYXNrCiAgICAgICAgICAgICAgICAgICAgbWFza0J5dGUgPSBtYXNrQml0c2V0W291dFB0ciA+PiAzXTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBpZiAobWFza0J5dGUgJiAxMjgpIHsKICAgICAgICAgICAgICAgICAgICAvLyBwaXhlbCBkYXRhIHByZXNlbnQKICAgICAgICAgICAgICAgICAgICBpZiAocmVzdWx0TWFzaykgewogICAgICAgICAgICAgICAgICAgICAgcmVzdWx0TWFza1tvdXRQdHJdID0gMTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgY3VycmVudFZhbHVlID0gKGJsb2NrLmVuY29kaW5nIDwgMikgPyBibG9ja0RhdGFbYmxvY2tQdHIrK10gOiBjb25zdFZhbHVlOwogICAgICAgICAgICAgICAgICAgIG1pblZhbHVlID0gbWluVmFsdWUgPiBjdXJyZW50VmFsdWUgPyBjdXJyZW50VmFsdWUgOiBtaW5WYWx1ZTsKICAgICAgICAgICAgICAgICAgICByZXN1bHRQaXhlbHNbb3V0UHRyKytdID0gY3VycmVudFZhbHVlOwogICAgICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgICAgIC8vIHBpeGVsIGRhdGEgbm90IHByZXNlbnQKICAgICAgICAgICAgICAgICAgICBpZiAocmVzdWx0TWFzaykgewogICAgICAgICAgICAgICAgICAgICAgcmVzdWx0TWFza1tvdXRQdHJdID0gMDsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgcmVzdWx0UGl4ZWxzW291dFB0cisrXSA9IG5vRGF0YVZhbHVlOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIG1hc2tCeXRlIDw8PSAxOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgLy8gbWFzayBub3QgcHJlc2VudCwgc2ltcGx5IGNvcHkgYmxvY2sgb3ZlcgogICAgICAgICAgICAgIGlmIChibG9jay5lbmNvZGluZyA8IDIpIHsKICAgICAgICAgICAgICAgIC8vIGR1cGxpY2F0aW5nIHRoaXMgY29kZSBibG9jayBmb3IgcGVyZm9ybWFuY2UgcmVhc29ucwogICAgICAgICAgICAgICAgLy8gYmxvY2tEYXRhIGNhc2U6CiAgICAgICAgICAgICAgICBmb3IgKHl5ID0gMDsgeXkgPCB0aGlzQmxvY2tIZWlnaHQ7IHl5KyspIHsKICAgICAgICAgICAgICAgICAgZm9yICh4eCA9IDA7IHh4IDwgdGhpc0Jsb2NrV2lkdGg7IHh4KyspIHsKICAgICAgICAgICAgICAgICAgICBjdXJyZW50VmFsdWUgPSBibG9ja0RhdGFbYmxvY2tQdHIrK107CiAgICAgICAgICAgICAgICAgICAgbWluVmFsdWUgPSBtaW5WYWx1ZSA+IGN1cnJlbnRWYWx1ZSA/IGN1cnJlbnRWYWx1ZSA6IG1pblZhbHVlOwogICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHIrK10gPSBjdXJyZW50VmFsdWU7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAvLyBjb25zdFZhbHVlIGNhc2U6CiAgICAgICAgICAgICAgICBtaW5WYWx1ZSA9IG1pblZhbHVlID4gY29uc3RWYWx1ZSA/IGNvbnN0VmFsdWUgOiBtaW5WYWx1ZTsKICAgICAgICAgICAgICAgIGZvciAoeXkgPSAwOyB5eSA8IHRoaXNCbG9ja0hlaWdodDsgeXkrKykgewogICAgICAgICAgICAgICAgICBmb3IgKHh4ID0gMDsgeHggPCB0aGlzQmxvY2tXaWR0aDsgeHgrKykgewogICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHIrK10gPSBjb25zdFZhbHVlOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIG91dFB0ciArPSBvdXRTdHJpZGU7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmICgoYmxvY2suZW5jb2RpbmcgPT09IDEpICYmIChibG9ja1B0ciAhPT0gYmxvY2subnVtVmFsaWRQaXhlbHMpKSB7CiAgICAgICAgICAgICAgdGhyb3cgIkJsb2NrIGFuZCBNYXNrIGRvIG5vdCBtYXRjaCI7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgYmxvY2tJZHgrKzsKICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIHJldHVybiB7CiAgICAgICAgICByZXN1bHRQaXhlbHM6IHJlc3VsdFBpeGVscywKICAgICAgICAgIHJlc3VsdE1hc2s6IHJlc3VsdE1hc2ssCiAgICAgICAgICBtaW5WYWx1ZTogbWluVmFsdWUKICAgICAgICB9OwogICAgICB9OwoKICAgICAgdmFyIGZvcm1hdEZpbGVJbmZvID0gZnVuY3Rpb24oZGF0YSkgewogICAgICAgIHJldHVybiB7CiAgICAgICAgICAiZmlsZUlkZW50aWZpZXJTdHJpbmciOiBkYXRhLmZpbGVJZGVudGlmaWVyU3RyaW5nLAogICAgICAgICAgImZpbGVWZXJzaW9uIjogZGF0YS5maWxlVmVyc2lvbiwKICAgICAgICAgICJpbWFnZVR5cGUiOiBkYXRhLmltYWdlVHlwZSwKICAgICAgICAgICJoZWlnaHQiOiBkYXRhLmhlaWdodCwKICAgICAgICAgICJ3aWR0aCI6IGRhdGEud2lkdGgsCiAgICAgICAgICAibWF4WkVycm9yIjogZGF0YS5tYXhaRXJyb3IsCiAgICAgICAgICAiZW9mT2Zmc2V0IjogZGF0YS5lb2ZPZmZzZXQsCiAgICAgICAgICAibWFzayI6IGRhdGEubWFzayA/IHsKICAgICAgICAgICAgIm51bUJsb2Nrc1giOiBkYXRhLm1hc2subnVtQmxvY2tzWCwKICAgICAgICAgICAgIm51bUJsb2Nrc1kiOiBkYXRhLm1hc2subnVtQmxvY2tzWSwKICAgICAgICAgICAgIm51bUJ5dGVzIjogZGF0YS5tYXNrLm51bUJ5dGVzLAogICAgICAgICAgICAibWF4VmFsdWUiOiBkYXRhLm1hc2subWF4VmFsdWUKICAgICAgICAgIH0gOiBudWxsLAogICAgICAgICAgInBpeGVscyI6IHsKICAgICAgICAgICAgIm51bUJsb2Nrc1giOiBkYXRhLnBpeGVscy5udW1CbG9ja3NYLAogICAgICAgICAgICAibnVtQmxvY2tzWSI6IGRhdGEucGl4ZWxzLm51bUJsb2Nrc1ksCiAgICAgICAgICAgICJudW1CeXRlcyI6IGRhdGEucGl4ZWxzLm51bUJ5dGVzLAogICAgICAgICAgICAibWF4VmFsdWUiOiBkYXRhLnBpeGVscy5tYXhWYWx1ZSwKICAgICAgICAgICAgIm5vRGF0YVZhbHVlIjogZGF0YS5ub0RhdGFWYWx1ZQogICAgICAgICAgfQogICAgICAgIH07CiAgICAgIH07CgogICAgICB2YXIgY29tcHV0ZVVzZWRCaXREZXB0aHMgPSBmdW5jdGlvbihkYXRhKSB7CiAgICAgICAgdmFyIG51bUJsb2NrcyA9IGRhdGEucGl4ZWxzLm51bUJsb2Nrc1ggKiBkYXRhLnBpeGVscy5udW1CbG9ja3NZOwogICAgICAgIHZhciBiaXREZXB0aHMgPSB7fTsKICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IG51bUJsb2NrczsgaSsrKSB7CiAgICAgICAgICB2YXIgYmxvY2sgPSBkYXRhLnBpeGVscy5ibG9ja3NbaV07CiAgICAgICAgICBpZiAoYmxvY2suZW5jb2RpbmcgPT09IDApIHsKICAgICAgICAgICAgYml0RGVwdGhzLmZsb2F0MzIgPSB0cnVlOwogICAgICAgICAgfSBlbHNlIGlmIChibG9jay5lbmNvZGluZyA9PT0gMSkgewogICAgICAgICAgICBiaXREZXB0aHNbYmxvY2suYml0c1BlclBpeGVsXSA9IHRydWU7CiAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICBiaXREZXB0aHNbMF0gPSB0cnVlOwogICAgICAgICAgfQogICAgICAgIH0KCiAgICAgICAgcmV0dXJuIE9iamVjdC5rZXlzKGJpdERlcHRocyk7CiAgICAgIH07CgogICAgICB2YXIgcGFyc2UgPSBmdW5jdGlvbihpbnB1dCwgZnAsIHNraXBNYXNrKSB7CiAgICAgICAgdmFyIGRhdGEgPSB7fTsKCiAgICAgICAgLy8gRmlsZSBoZWFkZXIKICAgICAgICB2YXIgZmls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lKTsKICAgICAgICAgIGRhdGEubWFzay5udW1CeXRlcyA9IHZpZXcuZ2V0VWludDMyKDgsIHRydWUpOwogICAgICAgICAgZGF0YS5tYXNrLm1heFZhbHVlID0gdmlldy5nZXRGbG9hdDMyKDEyLCB0cnVlKTsKICAgICAgICAgIGZwICs9IDE2OwoKICAgICAgICAgIC8vIE1hc2sgRGF0YQogICAgICAgICAgaWYgKGRhdGEubWFzay5udW1CeXRlcyA+IDApIHsKICAgICAgICAgICAgdmFyIGJpdHNldCA9IG5ldyBVaW50OEFycmF5KE1hdGguY2VpbChkYXRhLndpZHRoICogZGF0YS5oZWlnaHQgLyA4KSk7CiAgICAgICAgICAgIHZpZXcgPSBuZXcgRGF0YVZpZXcoaW5wdXQsIGZwLCBkYXRhLm1hc2subnVtQnl0ZXMpOwogICAgICAgICAgICB2YXIgY250ID0gdmlldy5nZXRJbnQxNigwLCB0cnVlKTsKICAgICAgICAgICAgdmFyIGlwID0gMiwgb3AgPSAwOwogICAgICAgICAgICBkbyB7CiAgICAgICAgICAgICAgaWYgKGNudCA+IDApIHsKICAgICAgICAgICAgICAgIHdoaWxlIChjbnQtLSkgeyBiaXRzZXRbb3ArK10gPSB2aWV3LmdldFVpbnQ4KGlwKyspOyB9CiAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgIHZhciB2YWwgPSB2aWV3LmdldFVpbnQ4KGlwKyspOwogICAgICAgICAgICAgICAgY250ID0gLWNudDsKICAgICAgICAgICAgICAgIHdoaWxlIChjbnQtLSkgeyBiaXRzZXRbb3ArK10gPSB2YWw7IH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgY250ID0gdmlldy5nZXRJbnQxNihpcCwgdHJ1ZSk7CiAgICAgICAgICAgICAgaXAgKz0gMjsKICAgICAgICAgICAgfSB3aGlsZSAoaXAgPCBkYXRhLm1hc2subnVtQnl0ZXMpOwogICAgICAgICAgICBpZiAoKGNudCAhPT0gLTMyNzY4KSB8fCAob3AgPCBi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gZnAsIE1hdGgubWluKDEwLCBieXRlc0xlZnQpKTsKICAgICAgICAgICAgdmFyIGJsb2NrID0ge307CiAgICAgICAgICAgIGRhdGEucGl4ZWxzLmJsb2Nrc1tibG9ja0krK10gPSBibG9jazsKICAgICAgICAgICAgdmFyIGhlYWRlckJ5dGUgPSB2aWV3LmdldFVpbnQ4KDApOyBzaXplKys7CiAgICAgICAgICAgIGJsb2NrLmVuY29kaW5nID0gaGVhZGVyQnl0ZSAmIDYzOwogICAgICAgICAgICBpZiAoYmxvY2suZW5jb2RpbmcgPiAzKSB7CiAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgYmxvY2sgZW5jb2RpbmcgKCIgKyBibG9jay5lbmNvZGluZyArICIpIjsKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiAoYmxvY2suZW5jb2RpbmcgPT09IDIpIHsKICAgICAgICAgICAgICBmcCsrOwogICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmICgoaGVhZGVyQnl0ZSAhPT0gMCkgJiYgKGhlYWRlckJ5dGUgIT09IDIpKSB7CiAgICAgICAgICAgICAgaGVhZGVyQnl0ZSA+Pj0gNjsKICAgICAgICAgICAgICBibG9jay5vZmZzZXRUeXBlID0gaGVhZGVyQnl0ZTsKICAgICAgICAgICAgICBpZiAoaGVhZGVyQnl0ZSA9PT0gMikgewogICAgICAgICAgICAgICAgYmxvY2sub2Zmc2V0ID0gdmlldy5nZXRJbnQ4KDEpOyBzaXplKys7CiAgICAgICAgICAgICAgfSBlbHNlIGlmIChoZWFkZXJCeXRlID09PSAxKSB7CiAgICAgICAgICAgICAgICBibG9jay5vZmZzZXQgPSB2aWV3LmdldEludDE2KDEsIHRydWUpOyBzaXplICs9IDI7CiAgICAgICAgICAgICAgfSBlbHNlIGlmIChoZWFkZXJCeXRlID09PSAwKSB7CiAgICAgICAgICAgICAgICBibG9jay5vZmZzZXQgPSB2aWV3LmdldEZsb2F0MzIoMSwgdHJ1ZSk7IHNpemUgKz0gNDsKICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgYmxvY2sgb2Zmc2V0IHR5cGUiOwogICAgICAgICAgICAgIH0KCiAgICAgICAgICAgICAgaWYgKGJsb2NrLmVuY29kaW5nID09PSAxKSB7CiAgICAgICAgICAgICAgICBoZWFkZXJCeXRlID0gdmlldy5nZXRVaW50OChzaXplKTsgc2l6ZSsrOwogICAgICAgICAgICAgICAgYmxvY2suYml0c1BlclBpeGVsID0gaGVhZGVyQnl0ZSAmIDYzOwogICAgICAgICAgICAgICAgaGVhZGVyQnl0ZSA+Pj0gNjsKICAgICAgICAgICAgICAgIGJsb2NrLm51bVZhbGlkUGl4ZWxzVHlwZSA9IGhlYWRlckJ5dGU7CiAgICAgICAgICAgICAgICBpZiAoaGVhZGVyQnl0ZSA9PT0gMikgewogICAgICAgICAgICAgICAgICBibG9jay5udW1WYWxpZFBpeGVscyA9IHZpZXcuZ2V0VWludDgoc2l6ZSk7IHNpemUrKzsKICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAoaGVhZGVyQnl0ZSA9PT0gMSkgewogICAgICAgICAgICAgICAgICBibG9jay5udW1WYWxpZFBpeGVscyA9IHZpZXcuZ2V0VWludDE2KHNpemUsIHRydWUpOyBzaXplICs9IDI7CiAgICAgICAgICAgICAgICB9IGVsc2UgaWYgKGhlYWRlckJ5dGUgPT09IDApIHsKICAgICAgICAgICAgICAgICAgYmxvY2subnVtVmFsaWRQaXhlbHMgPSB2aWV3LmdldFVpbnQzMihzaXplLCB0cnVlKTsgc2l6ZSArPSA0OwogICAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgdmFsaWQgcGl4ZWwgY291bnQgdHlwZSI7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGZwICs9IHNpemU7CgogICAgICAgICAgICBpZiAoYmxvY2suZW5jb2RpbmcgPT09IDMpIHsKICAgICAgICAgICAgICBjb250aW51ZTsKICAgICAgICAgICAgfQoKICAgICAgICAgICAgdmFyIGFycmF5QnVmLCBzdG9yZTg7CiAgICAgICAgICAgIGlmIChibG9jay5lbmNvZGluZyA9PT0gMCkgewogICAgICAgICAgICAgIHZhciBudW1QaXhlbHMgPSAoZGF0YS5waXhlbHMubnVtQnl0ZXMgLSAxKSAvIDQ7CiAgICAgICAgICAgICAgaWYgKG51bVBpeGVscyAhPT0gTWF0aC5mbG9vcihudW1QaXhlbHMpKSB7CiAgICAgICAgICAgICAgICB0aHJvdyAidW5jb21wcmVzc2VkIGJsb2NrIGhhcyBpbnZhbGlkIGxlbmd0aCI7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGFycmF5QnVmID0gbmV3IEFycmF5QnVmZmVyKG51bVBpeGVscyAqIDQpOwogICAgICAgICAgICAgIHN0b3JlOCA9IG5ldyBVaW50OEFycmF5KGFycmF5QnVmKTsKICAgICAgICAgICAgICBzdG9yZTguc2V0KG5ldyBVaW50OEFycmF5KGlucHV0LCBmcCwgbnVtUGl4ZWxzICogNCkpOwogICAgICAgICAgICAgIHZhciByYXdEYXRhID0gbmV3IEZsb2F0MzJBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgICAgYmxvY2sucmF3RGF0YSA9IHJhd0RhdGE7CiAgICAgICAgICAgICAgZnAgKz0gbnVtUGl4ZWxzICogNDsKICAgICAgICAgICAgfSBlbHNlIGlmIChibG9jay5lbmNvZGluZyA9PT0gMSkgewogICAgICAgICAgICAgIHZhciBkYXRhQnl0ZXMgPSBNYXRoLmNlaWwoYmxvY2subnVtVmFsaWRQaXhlbHMgKiBibG9jay5iaXRzUGVyUGl4ZWwgLyA4KTsKICAgICAgICAgICAgICB2YXIgZGF0YVdvcmRzID0gTWF0aC5jZWlsKGRhdGFCeXRlcyAvIDQpOwogICAgICAgICAgICAgIGFycmF5QnVmID0gb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G8gPSAwOyBvIDwgbnVtUGl4ZWxzOyBvKyspIHsKICAgICAgICAgIGlmIChiaXRzTGVmdCA9PT0gMCkgewogICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgYml0c0xlZnQgPSAzMjsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChiaXRzTGVmdCA+PSBiaXRzUGVyUGl4ZWwpIHsKICAgICAgICAgICAgbiA9IChidWZmZXIgPj4+IChiaXRzTGVmdCAtIGJpdHNQZXJQaXhlbCkpICYgYml0TWFzazsKICAgICAgICAgICAgYml0c0xlZnQgLT0gYml0c1BlclBpeGVsOwogICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgdmFyIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJpdHNMZWZ0KTsKICAgICAgICAgICAgbiA9ICgoYnVmZmVyICYgYml0TWFzaykgPDwgbWlzc2luZ0JpdHMpICYgYml0TWFzazsKICAgICAgICAgICAgYnVmZmVyID0gc3JjW2krK107CiAgICAgICAgICAgIGJpdHNMZWZ0ID0gMzIgLSBtaXNzaW5nQml0czsKICAgICAgICAgICAgbiArPSAoYnVmZmVyID4+PiBiaXRzTGVmdCk7CiAgICAgICAgICB9CiAgICAgICAgICAvL3BpeGVsIHZhbHVlcyBtYXkgZXhjZWVkIG1heCBkdWUgdG8gcXVhbnRpemF0aW9uCiAgICAgICAgICBkZXN0W29dID0gbiA8IG5tYXggPyBvZmZzZXQgKyBuICogc2NhbGUgOiBtYXhWYWx1ZTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGRlc3Q7CiAgICAgIH07CgogICAgICByZXR1cm4gQ250WkltYWdlOwogICAgfSkoKTsKCiAgICAvL3ZlcnNpb24gMi4gU3VwcG9ydHMgMi4xLCAyLjIsIDIuMwogICAgdmFyIExlcmMyRGVjb2RlID0gKGZ1bmN0aW9uKCkgewogICAgICAvLyBOb3RlOiBjdXJyZW50bHksIHRoaXMgbW9kdWxlIG9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WR5IHBhcnQgb2YgbmV4dCBibG9jawogICAgICAgICAgdmFyIG51bUludmFsaWRUYWlsQnl0ZXMgPSBzcmMubGVuZ3RoICogNCAtIE1hdGguY2VpbChiaXRzUGVyUGl4ZWwgKiBudW1QaXhlbHMgLyA4KTsKICAgICAgICAgIHNyY1tzcmMubGVuZ3RoIC0gMV0gPDw9IDggKiBudW1JbnZhbGlkVGFpbEJ5dGVzOwogICAgICAgICAgaWYgKGx1dEFycikgewogICAgICAgICAgICBmb3IgKG8gPSAwOyBvIDwgbnVtUGl4ZWxzOyBvKyspIHsKICAgICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMjsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgICAgbiA9IChidWZmZXIgPj4+IChiaXRzTGVmdCAtIGJpdHNQZXJQaXhlbCkpICYgYml0TWFzazsKICAgICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICBtaXNzaW5nQml0cyA9IChiaXRzUGVyUGl4ZWwgLSBiaXRzTGVmdCk7CiAgICAgICAgICAgICAgICBuID0gKChidWZmZXIgJiBiaXRNYXNrKSA8PCBtaXNzaW5nQml0cykgJiBiaXRNYXNrOwogICAgICAgICAgICAgICAgYnVmZmVyID0gc3JjW2krK107CiAgICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyIC0gbWlzc2luZ0JpdHM7CiAgICAgICAgICAgICAgICBuICs9IChidWZmZXIgPj4+IGJpdHNMZWZ0KTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZGVzdFtvXSA9IGx1dEFycltuXTsvL29mZnNldCArIGx1dEFycltuXSAqIHNjYWxlOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgbm1heCA9IE1hdGguY2VpbCgobWF4VmFsdWUgLSBvZmZzZXQpIC8gc2NhbGUpOwogICAgICAgICAgICBmb3IgKG8gPSAwOyBvIDwgbnVtUGl4ZWxzOyBvKyspIHsKICAgICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMjsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgICAgbiA9IChidWZmZXIgPj4+IChiaXRzTGVmdCAtIGJpdHNQZXJQaXhlbCkpICYgYml0TWFzazsKICAgICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICBtaXNzaW5nQml0cyA9IChiaXRzUGVyUGl4ZWwgLSBiaXRzTGVmdCk7CiAgICAgICAgICAgICAgICBuID0gKChidWZmZXIgJiBiaXRNYXNrKSA8PCBtaXNzaW5nQml0cykgJiBiaXRNYXNrOwogICAgICAgICAgICAgICAgYnVmZmVyID0gc3JjW2krK107CiAgICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyIC0gbWlzc2luZ0JpdHM7CiAgICAgICAgICAgICAgICBuICs9IChidWZmZXIgPj4+IGJpdHNMZWZ0KTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgLy9waXhlbCB2YWx1ZXMgbWF5IGV4Y2VlZCBtYXggZHVlIHRvIHF1YW50aXphdGlvbgogICAgICAgICAgICAgIGRlc3Rbb10gPSBuIDwgbm1heCA/IG9mZnNldCArIG4gKiBzY2FsZSA6IG1heFZhbHVlOwogIC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NrOwogICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICBtaXNzaW5nQml0cyA9IChiaXRzUGVyUGl4ZWwgLSBiaXRzTGVmdCk7CiAgICAgICAgICAgICAgbiA9ICgoYnVmZmVyICYgYml0TWFzaykgPDwgbWlzc2luZ0JpdHMpICYgYml0TWFzazsKICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyIC0gbWlzc2luZ0JpdHM7CiAgICAgICAgICAgICAgbiArPSAoYnVmZmVyID4+PiBiaXRzTGVmdCk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy9kZXN0LnB1c2gobik7CiAgICAgICAgICAgIGRlc3Rbb10gPSBuIDwgbm1heCA/IG9mZnNldCArIG4gKiBzY2FsZSA6IG1heFZhbHVlOwogICAgICAgICAgfQogICAgICAgICAgZGVzdC51bnNoaWZ0KG9mZnNldCk7Ly8xc3Qgb25lCiAgICAgICAgICByZXR1cm4gZGVzdDsKICAgICAgICB9LAoKICAgICAgICB1bnN0dWZmMjogZnVuY3Rpb24oc3JjLCBkZXN0LCBiaXRzUGVyUGl4ZWwsIG51bVBpeGVscywgbHV0QXJyLCBvZmZzZXQsIHNjYWxlLCBtYXhWYWx1ZSkgewogICAgICAgICAgdmFyIGJpdE1hc2sgPSAoMSA8PCBiaXRzUGVyUGl4ZWwpIC0gMTsKICAgICAgICAgIHZhciBpID0gMCwgbzsKICAgICAgICAgIHZhciBiaXRzTGVmdCA9IDAsIGJpdFBvcyA9IDA7CiAgICAgICAgICB2YXIgbiwgYnVmZmVyLCBtaXNzaW5nQml0czsKICAgICAgICAgIGlmIChsdXRBcnIpIHsKICAgICAgICAgICAgZm9yIChvID0gMDsgbyA8IG51bVBpeGVsczsgbysrKSB7CiAgICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID09PSAwKSB7CiAgICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICAgIGJpdHNMZWZ0ID0gMzI7CiAgICAgICAgICAgICAgICBiaXRQb3MgPSAwOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBpZiAoYml0c0xlZnQgPj0gYml0c1BlclBpeGVsKSB7CiAgICAgICAgICAgICAgICBuID0gKChidWZmZXIgPj4+IGJpdFBvcykgJiBiaXRNYXNrKTsKICAgICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICAgIGJpdFBvcyArPSBiaXRzUGVyUGl4ZWw7CiAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJpdHNMZWZ0KTsKICAgICAgICAgICAgICAgIG4gPSAoYnVmZmVyID4+PiBiaXRQb3MpICYgYml0TWFzazsKICAgICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMiAtIG1pc3NpbmdCaXRzOwogICAgICAgICAgICAgICAgbiB8PSAoYnVmZmVyICYgKCgxIDw8IG1pc3NpbmdCaXRzKSAtIDEpKSA8PCAoYml0c1BlclBpeGVsIC0gbWlzc2luZ0JpdHMpOwogICAgICAgICAgICAgICAgYml0UG9zID0gbWlzc2luZ0JpdHM7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGRlc3Rbb10gPSBsdXRBcnJbbl07CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgewogICAgICAgICAgICB2YXIgbm1heCA9IE1hdGguY2VpbCgobWF4VmFsdWUgLSBvZmZzZXQpIC8gc2NhbGUpOwogICAgICAgICAgICBmb3IgKG8gPSAwOyBvIDwgbnVtUGl4ZWxzOyBvKyspIHsKICAgICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMjsKICAgICAgICAgICAgICAgIGJpdFBvcyA9IDA7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGlmIChiaXRzTGVmdCA+PSBiaXRzUGVyUGl4ZWwpIHsKICAgICAgICAgICAgICAgIC8vbm8gdW5zaWduZWQgbGVmdCBzaGlmdAogICAgICAgICAgICAgICAgbiA9ICgoYnVmZmVyID4+PiBiaXRQb3MpICYgYml0TWFzayk7CiAgICAgICAgICAgICAgICBiaXRzTGVmdCAtPSBiaXRzUGVyUGl4ZWw7CiAgICAgICAgICAgICAgICBiaXRQb3MgKz0gYml0c1BlclBpeGVsOwogICAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgICBtaXNzaW5nQml0cyA9IChiaXRzUGVyUGl4ZWwgLSBiaXRzTGVmdCk7CiAgICAgICAgICAgICAgICBuID0gKGJ1ZmZlciA+Pj4gYml0UG9zKSAmIGJpdE1hc2s7Ly8oKGJ1ZmZlciAmIGJpdE1hc2spIDw8IG1pc3NpbmdCaXRzKSAmIGJpdE1hc2s7CiAgICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICAgIGJpdHNMZWZ0ID0gMzIgLSBtaXNzaW5nQml0czsKICAgICAgICAgICAgICAgIG4gfD0gKGJ1ZmZlciAmICgoMSA8PCBtaXNzaW5nQml0cykgLSAxKSkgPDwgKGJpdHNQZXJQaXhlbCAtIG1pc3NpbmdCaXRzKTsKICAgICAgICAgICAgICAgIGJpdFBvcyA9IG1pc3NpbmdCaXRzOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAvL3BpeGVsIHZhbHVlcyBtYXkgZXhjZWVkIG1heCBkdWUgdG8gcXVhbnRpemF0aW9uCiAgICAgICAgICAgICAgZGVzdFtvXSA9IG4gPCBubWF4ID8gb2Zmc2V0ICsgbiAqIHNjYWxlIDogbWF4VmFsdWU7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiBkZXN0OwogICAgICAgIH0sCgogICAgICAgIHVuc3R1ZmZMVVQyOiBmdW5jdGlvbihzcmMsIGJpdHNQZXJQaXhlbCwgbnVtUGl4ZWxzLCBvZmZzZXQsIHNjYWxlLCBtYXhWYWx1ZSkgewogICAgICAgICAgdmFyIGJpdE1hc2sgPSAoMSA8PCBiaXRzUGVyUGl4ZWwpIC0gMTsKICAgICAgICAgIHZhciBpID0gMCwgbyA9IDAsIG1pc3NpbmdCaXRzID0gMCwgYml0c0xlZnQgPSAwLCBuID0gMCwgYml0UG9zID0gMDsKICAgICAgICAgIHZhciBidWZmZXI7CiAgICAgICAgICB2YXIgZGVzdCA9IFtdOwogICAgICAgICAgdmFyIG5tYXggPSBNYXRoLmNlaWwoKG1heFZhbHVlIC0gb2Zmc2V0KSAvIHNjYWxlKTsKICAgICAgICAgIGZvciAobyA9IDA7IG8gPCBudW1QaXhlbHM7IG8rKykgewogICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyOwogICAgICAgICAgICAgIGJpdFBvcyA9IDA7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgIC8vbm8gdW5zaWduZWQgbGVmdCBzaGlmdAogICAgICAgICAgICAgIG4gPSAoKGJ1ZmZlciA+Pj4gYml0UG9zKSAmIGJpdE1hc2spOwogICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICBiaXRQb3MgKz0gYml0c1BlclBpeGVsOwogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJp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ZWlsKGJpdHNQZXJQaXhlbCAqIG51bVBpeGVscyAvIDgpOwogICAgICAgICAgc3JjW3NyYy5sZW5ndGggLSAxXSA8PD0gOCAqIG51bUludmFsaWRUYWlsQnl0ZXM7CgogICAgICAgICAgZm9yIChvID0gMDsgbyA8IG51bVBpeGVsczsgbysrKSB7CiAgICAgICAgICAgIGlmIChiaXRzTGVmdCA9PT0gMCkgewogICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgIGJpdHNMZWZ0ID0gMzI7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgIG4gPSAoYnVmZmVyID4+PiAoYml0c0xlZnQgLSBiaXRzUGVyUGl4ZWwpKSAmIGJpdE1hc2s7CiAgICAgICAgICAgICAgYml0c0xlZnQgLT0gYml0c1BlclBpeGVsOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJpdHNMZWZ0KTsKICAgICAgICAgICAgICBuID0gKChidWZmZXIgJiBiaXRNYXNrKSA8PCBtaXNzaW5nQml0cykgJiBiaXRNYXNrOwogICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgIGJpdHNMZWZ0ID0gMzIgLSBtaXNzaW5nQml0czsKICAgICAgICAgICAgICBuICs9IChidWZmZXIgPj4+IGJpdHNMZWZ0KTsKICAgICAgICAgICAgfQogICAgICAgICAgICBkZXN0W29dID0gbjsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiBkZXN0OwogICAgICAgIH0sCgogICAgICAgIG9yaWdpbmFsVW5zdHVmZjI6IGZ1bmN0aW9uKHNyYywgZGVzdCwgYml0c1BlclBpeGVsLCBudW1QaXhlbHMpIHsKICAgICAgICAgIHZhciBiaXRNYXNrID0gKDEgPDwgYml0c1BlclBpeGVsKSAtIDE7CiAgICAgICAgICB2YXIgaSA9IDAsIG87CiAgICAgICAgICB2YXIgYml0c0xlZnQgPSAwLCBiaXRQb3MgPSAwOwogICAgICAgICAgdmFyIG4sIGJ1ZmZlciwgbWlzc2luZ0JpdHM7CiAgICAgICAgICAvL21pY3JvLW9wdGltaXphdGlvbnMKICAgICAgICAgIGZvciAobyA9IDA7IG8gPCBudW1QaXhlbHM7IG8rKykgewogICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyOwogICAgICAgICAgICAgIGJpdFBvcyA9IDA7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgIC8vbm8gdW5zaWduZWQgbGVmdCBzaGlmdAogICAgICAgICAgICAgIG4gPSAoKGJ1ZmZlciA+Pj4gYml0UG9zKSAmIGJpdE1hc2spOwogICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICBiaXRQb3MgKz0gYml0c1BlclBpeGVsOwogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJpdHNMZWZ0KTsKICAgICAgICAgICAgICBuID0gKGJ1ZmZlciA+Pj4gYml0UG9zKSAmIGJpdE1hc2s7Ly8oKGJ1ZmZlciAmIGJpdE1hc2spIDw8IG1pc3NpbmdCaXRzKSAmIGJpdE1hc2s7CiAgICAgICAgICAgICAgYnVmZmVyID0gc3JjW2krK107CiAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMiAtIG1pc3NpbmdCaXRzOwogICAgICAgICAgICAgIG4gfD0gKGJ1ZmZlciAmICgoMSA8PCBtaXNzaW5nQml0cykgLSAxKSkgPDwgKGJpdHNQZXJQaXhlbCAtIG1pc3NpbmdCaXRzKTsKICAgICAgICAgICAgICBiaXRQb3MgPSBtaXNzaW5nQml0czsKICAgICAgICAgICAgfQogICAgICAgICAgICBkZXN0W29dID0gbjsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiBkZXN0OwogICAgICAgIH0KICAgICAgfTsKCiAgICAgIC8qKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKgogICAgICAqcHJpdmF0ZSBzdGF0aWMgY2xhc3MgdXNlZCBieSBMZXJjMkRlY29kZQogICAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgIHZhciBMZXJjMkhlbHBlcnMgPSB7CiAgICAgICAgSFVGRk1BTl9MVVRfQklUU19NQVg6IDEyLCAvL3VzZSAyXjEyIGx1dCwgdHJlYXQgaXQgbGlrZSBjb25zdGFudAogICAgICAgIGNvbXB1dGVDaGVja3N1bUZsZXRjaGVyMzI6IGZ1bmN0aW9uKGlucHV0KSB7CgogICAgICAgICAgdmFyIHN1bTEgPSAweGZmZmYsIHN1bTIgPSAweGZmZmY7CiAgICAgICAgICB2YXIgbGVuID0gaW5wdXQubGVuZ3RoOwogICAgICAgICAgdmFyIHdvcmRzID0gTWF0aC5mbG9vcihsZW4gLyAyKTsKICAgICAgICAgIHZhciBpID0gMDsKICAgICAgICAgIHdoaWxlICh3b3JkcykgewogICAgICAgICAgICB2YXIgdGxlbiA9ICh3b3JkcyA+PSAzNTkpID8gMzU5IDogd29yZHM7CiAgICAgICAgICAgIHdvcmRzIC09IHRsZW47CiAgICAgICAgICAgIGRvIHsKICAgICAgICAgICAgICBzdW0xICs9IChpbnB1dFtpKytdIDw8IDgpOwogICAgICAgICAgICAgIHN1bTIgKz0gc3VtMSArPSBpbnB1dFtpKytdOwogICAgICAgICAgICB9IHdoaWxlICgtLXRsZW4pOwoKICAgICAgICAgICAgc3VtMSA9IChzdW0xICYgMHhmZmZmKSArIChzdW0xID4+PiAx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bGVJZGVudGlmaWVyU3RyaW5nOwogICAgICAgICAgfQogICAgICAgICAgcHRyICs9IDY7CiAgICAgICAgICB2YXIgdmlldyA9IG5ldyBEYXRhVmlldyhpbnB1dCwgcHRyLCA4KTsKICAgICAgICAgIHZhciBmaWxlVmVyc2lvbiA9IHZpZXcuZ2V0SW50MzIoMCwgdHJ1ZSk7CiAgICAgICAgICBoZWFkZXJJbmZvLmZpbGVWZXJzaW9uID0gZmlsZVZlcnNpb247CiAgICAgICAgICBwdHIgKz0gNDsKICAgICAgICAgIGlmIChmaWxlVmVyc2lvbiA+PSAzKSB7CiAgICAgICAgICAgIGhlYWRlckluZm8uY2hlY2tzdW0gPSB2aWV3LmdldFVpbnQzMig0LCB0cnVlKTsgLy9ucm93cwogICAgICAgICAgICBwdHIgKz0gNDsKICAgICAgICAgIH0KCiAgICAgICAgICAvL2tleXMgc3RhcnQgZnJvbSBoZXJlCiAgICAgICAgICB2aWV3ID0gbmV3IERhdGFWaWV3KGlucHV0LCBwdHIsIDEyKTsKICAgICAgICAgIGhlYWRlckluZm8uaGVpZ2h0ID0gdmlldy5nZXRVaW50MzIoMCwgdHJ1ZSk7IC8vbnJvd3MKICAgICAgICAgIGhlYWRlckluZm8ud2lkdGggPSB2aWV3LmdldFVpbnQzMig0LCB0cnVlKTsgLy9uY29scwogICAgICAgICAgcHRyICs9IDg7CiAgICAgICAgICBpZiAoZmlsZVZlcnNpb24gPj0gNCkgewogICAgICAgICAgICBoZWFkZXJJbmZvLm51bURpbXMgPSB2aWV3LmdldFVpbnQzMig4LCB0cnVlKTsKICAgICAgICAgICAgcHRyICs9IDQ7CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgaGVhZGVySW5mby5udW1EaW1zID0gMTsKICAgICAgICAgIH0KCiAgICAgICAgICB2aWV3ID0gbmV3IERhdGFWaWV3KGlucHV0LCBwdHIsIDQwKTsKICAgICAgICAgIGhlYWRlckluZm8ubnVtVmFsaWRQaXhlbCA9IHZpZXcuZ2V0VWludDMyKDAsIHRydWUpOwogICAgICAgICAgaGVhZGVySW5mby5taWNyb0Jsb2NrU2l6ZSA9IHZpZXcuZ2V0SW50MzIoNCwgdHJ1ZSk7CiAgICAgICAgICBoZWFkZXJJbmZvLmJsb2JTaXplID0gdmlldy5nZXRJbnQzMig4LCB0cnVlKTsKICAgICAgICAgIGhlYWRlckluZm8uaW1hZ2VUeXBlID0gdmlldy5nZXRJbnQzMigxMiwgdHJ1ZSk7CgogICAgICAgICAgaGVhZGVySW5mby5tYXhaRXJyb3IgPSB2aWV3LmdldEZsb2F0NjQoMTYsIHRydWUpOwogICAgICAgICAgaGVhZGVySW5mby56TWluID0gdmlldy5nZXRGbG9hdDY0KDI0LCB0cnVlKTsKICAgICAgICAgIGhlYWRlckluZm8uek1heCA9IHZpZXcuZ2V0RmxvYXQ2NCgzMiwgdHJ1ZSk7CiAgICAgICAgICBwdHIgKz0gNDA7CiAgICAgICAgICBkYXRhLmhlYWRlckluZm8gPSBoZWFkZXJJbmZvOwogICAgICAgICAgZGF0YS5wdHIgPSBwdHI7CgogICAgICAgICAgdmFyIGNoZWNrc3VtLCBrZXlMZW5ndGg7CiAgICAgICAgICBpZiAoZmlsZVZlcnNpb24gPj0gMykgewogICAgICAgICAgICBrZXlMZW5ndGggPSBmaWxlVmVyc2lvbiA+PSA0ID8gNTIgOiA0ODsKICAgICAgICAgICAgY2hlY2tzdW0gPSB0aGlzLmNvbXB1dGVDaGVja3N1bUZsZXRjaGVyMzIobmV3IFVpbnQ4QXJyYXkoaW5wdXQsIHB0ciAtIGtleUxlbmd0aCwgaGVhZGVySW5mby5ibG9iU2l6ZSAtIDE0KSk7CiAgICAgICAgICAgIGlmIChjaGVja3N1bSAhPT0gaGVhZGVySW5mby5jaGVja3N1bSkgewogICAgICAgICAgICAgIHRocm93ICJDaGVja3N1bSBmYWlsZWQuIjsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuIHRydWU7Ci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OwogICAgICAgIH0sCgogICAgICAgIHJlYWRTdWJBcnJheTogZnVuY3Rpb24oaW5wdXQsIHB0ciwgT3V0UGl4ZWxUeXBlQXJyYXksIG51bUJ5dGVzKSB7CiAgICAgICAgICB2YXIgcmF3RGF0YTsKICAgICAgICAgIGlmIChPdXRQaXhlbFR5cGVBcnJheSA9PT0gVWludDhBcnJheSkgewogICAgICAgICAgICByYXdEYXRhID0gbmV3IFVpbnQ4QXJyYXkoaW5wdXQsIHB0ciwgbnVtQnl0ZXMpOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgIHZhciBhcnJheUJ1ZiA9IG5ldyBBcnJheUJ1ZmZlcihudW1CeXRlcyk7CiAgICAgICAgICAgIHZhciBzdG9yZTggPSBuZXcgVWludDhBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgIHN0b3JlOC5zZXQobmV3IFVpbnQ4QXJyYXkoaW5wdXQsIHB0ciwgbnVtQnl0ZXMpKTsKICAgICAgICAgICAgcmF3RGF0YSA9IG5ldyBPdXRQaXhlbFR5cGVBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm4gcmF3RGF0YTsKICAgICAgICB9LAoKICAgICAgICByZWFkTWFzazogZnVuY3Rpb24oaW5wdXQsIGRhdGEpIHsKICAgICAgICAgIHZhciBwdHIgPSBkYXRhLnB0cjsKICAgICAgICAgIHZhciBoZWFkZXJJbmZvID0gZGF0YS5oZWFkZXJJbmZvOwogICAgICAgICAgdmFyIG51bVBpeGVscyA9IGhlYWRlckluZm8ud2lkdGggKiBoZWFkZXJJbmZvLmhlaWdodDsKICAgICAgICAgIHZhciBudW1WYWxpZFBpeGVsID0gaGVhZGVySW5mby5udW1WYWxpZFBpeGVsOwoKICAgICAgICAgIHZhciB2aWV3ID0gbmV3IERhdGFWaWV3KGlucHV0LCBwdHIsIDQpOwogICAgICAgICAgdmFyIG1hc2sgPSB7fTsKICAgICAgICAgIG1hc2subnVtQnl0ZXMgPSB2aWV3LmdldFVpbnQzMigwLCB0cnVlKTsKICAgICAgICAgIHB0ciArPSA0OwoKICAgICAgICAgIC8vIE1hc2sgRGF0YQogICAgICAgICAgaWYgKCgwID09PSBudW1WYWxpZFBpeGVsIHx8IG51bVBpeGVscyA9PT0gbnVtVmFsaWRQaXhlbCkgJiYgMCAhPT0gbWFzay5udW1CeXRlcykgewogICAgICAgICAgICB0aHJvdyAoImludmFsaWQgbWFzayIpOwogICAgICAgICAgfQogICAgICAgICAgdmFyIGJpdHNldCwgcmVzdWx0TWFzazsKICAgICAgICAgIGlmIChudW1WYWxpZFBpeGVsID09PSAwKSB7CiAgICAgICAgICAgIGJpdHNldCA9IG5ldyBVaW50OEFycmF5KE1hdGguY2VpbChudW1QaXhlbHMgLyA4KSk7CiAgICAgICAgICAgIG1hc2suYml0c2V0ID0gYml0c2V0OwogICAgICAgICAgICByZXN1bHRNYXNrID0gbmV3IFVpbnQ4QXJyYXkobnVtUGl4ZWxzKTsKICAgICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0TWFzayA9IHJlc3VsdE1hc2s7CiAgICAgICAgICAgIHB0ciArPSBtYXNrLm51bUJ5dGVzOwogICAgICAgICAgfS8vID8/Pz8/IGVsc2UgaWYgKGRhdGEubWFzay5udW1CeXRlcyA+IDAgJiYgZGF0YS5tYXNrLm51bUJ5dGVzPCBkYXRhLm51bVZhbGlkUGl4ZWwpIHsKICAgICAgICAgIGVsc2UgaWYgKG1hc2subnVtQnl0ZXMgPiAwKSB7CiAgICAgICAgICAgIGJpdHNldCA9IG5ldyBVaW50OEFycmF5KE1hdGguY2VpbChudW1QaXhlbHMgLyA4KSk7CiAgICAgICAgICAgIHZpZXcgPSBuZXcgRGF0YVZpZXcoaW5wdXQsIHB0ciwgbWFzay5udW1CeXRlcyk7CiAgICAgICAgICAgIHZhciBjbnQgPSB2aWV3LmdldEludDE2KDAsIHRydWUpOwogICAgICAgICAgICB2YXIgaXAgPSAyLCBvcCA9IDAsIHZhbCA9IDA7CiAgICAgICAgICAgIGRvIHsKICAgICAgICAgICAgICBpZiAoY250ID4gMCkgewogICAgICAgICAgICAgICAgd2hpbGUgKGNudC0tKSB7IGJpdHNldFtvcCsrXSA9IHZpZXcuZ2V0VWludDgoaXArKyk7IH0KICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgdmFsID0gdmlldy5nZXRVaW50OChpcCsrKTsKICAgICAgICAgICAgICAgIGNudCA9IC1jbnQ7CiAgICAgICAgICAgICAgICB3aGlsZSAoY250LS0pIHsgYml0c2V0W29wKytdID0gdmFsOyB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGNudCA9IHZpZXcuZ2V0SW50MTYoaXAsIHRydWUpOwogICAgICAgICAgICAgIGlwICs9IDI7CiAgICAgICAgICAgIH0gd2hpbGUgKGlwIDwgbWFzay5udW1CeXRlcyk7CiAgICAgICAgICAgIGlmICgoY250ICE9PSAtMzI3NjgpIHx8IChvcCA8IGJpdHNldC5sZW5ndGgpKSB7CiAgICAgICAgICAgICAgdGhyb3cgIlVuZXhwZWN0ZWQgZW5kIG9mIG1hc2sgUkxFIGVuY29kaW5nIjsKICAgICAgICAgICAgfQoKICAgICAgICAgICAgcmVzdWx0TWFzayA9IG5ldyBVaW50OEFycmF5KG51bVBpeGVscyk7CiAgICAgICAgICAgIHZhciBtYiA9IDAsIGsgPSAwOwoKICAgICAgICAgICAgZm9yIChrID0gMDsgayA8IG51bVBpeGVsczsgaysrKSB7CiAgICAgICAgICAgICAgaWYgKGsgJiA3KSB7CiAgICAgICAgICAgICAgICBtYiA9IGJpdHNldFtrID4+IDNdOwogICAgICAgICAgICAgICAgbWIgPDw9IGsgJiA3OwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIG1iID0gYml0c2V0W2sgPj4gM107CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGlmIChtYiAmIDEyOCkgewogICAgICAgICAgICAgICAgcmVzdWx0TWFza1trXSA9IDE7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdE1hc2sgPSByZXN1bHRNYXNrOwoKICAgICAgICAgICAgbWFzay5iaXRzZXQgPSBiaXRzZXQ7CiAgICAgICAgICAgIHB0ciArPSBtYXNrLm51bUJ5dGVzOwogICAgICAgICAgfQogICAgICAgICAgZGF0YS5wdHIgPSBwdHI7CiAgICAgICAgICBkYXRhLm1hc2sgPSBtYXNrOwogICAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgICAgfSwKCiAgICAgICAgcmVhZERhdGFPbmVTd2VlcDogZnVuY3Rpb24oaW5wdXQsIGRhdGEsIE91dFBpeGVsVHlwZUFycmF5KSB7CiAgICAgICAgICB2YXIgcHRyID0gZGF0YS5wdHI7CiAgICAgICAgICB2YXIgaGVhZGVySW5mbyA9IGRhdGEuaGVhZGVySW5mbzsKICAgICAgICAgIHZhciBudW1EaW1zID0gaGVhZGVySW5mby5udW1EaW1zOwogICAgICAgICAgdmFyIG51bVBpeGVscyA9IGhlYWRlckluZm8ud2lkdGggKiBoZWFkZXJJbmZvLmhlaWdodDsKICAgICAgICAgIHZhciBpbWFnZVR5cGUgPSBoZWFkZXJJbmZvLmltYWdlVHlwZTsKICAgICAgICAgIHZhciBudW1CeXRlcyA9IGhlYWRlckluZm8ubnVtVmFsaWRQaXhlbCAqIExlcmMySGVscGVycy5nZXREYXRhVHlwZVNpemUoaW1hZ2VUeXBlKSAqIG51bURpbXM7CiAgICAgICAgICAvL2RhdGEucGl4ZWxzLm51bUJ5dGVzID0gbnVtQnl0ZXM7CiAgICAgICAgICB2YXIgcmF3RGF0YTsKICAgICAgICAgIHZhciBtYXNrID0gZGF0YS5waXhlbHMucmVzdWx0TWFzazsKICAgICAgICAgIGlmIChPdXRQaXhlbFR5cGVBcnJheSA9PT0gVWludDhBcnJheSkgewogICAgICAgICAgICByYXdEYXRhID0gbmV3IFVpbnQ4QXJyYXkoaW5wdXQsIHB0ciwgbnVtQnl0ZXMpOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgIHZhciBhcnJheUJ1ZiA9IG5ldyBBcnJheUJ1ZmZlcihudW1CeXRlcyk7CiAgICAgICAgICAgIHZhciBzdG9yZTggPSBuZXcgVWludDhBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgIHN0b3JlOC5zZXQobmV3IFVpbnQ4QXJyYXkoaW5wdXQsIHB0ciwgbnVtQnl0ZXMpKTsKICAgICAgICAgICAgcmF3RGF0YSA9IG5ldyBPdXRQaXhlbFR5cGVBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAocmF3RGF0YS5sZW5ndGggPT09IG51bVBpeGVscyAqIG51bURpbXMpIHsKICAgICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0UGl4ZWxzID0gcmF3RGF0YTsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgIC8vbWFzawogICAgICAgICAgewogICAgICAgICAgICBkYXRhLnBpeGVscy5yZXN1bHRQaXhlbHMgPSBuZXcgT3V0UGl4ZWxUeXBlQXJyYXkobnVtUGl4ZWxzICogbnVtRGltcyk7CiAgICAgICAgICAgIHZhciB6ID0gMCwgayA9IDAsIGkgPSAwLCBuU3RhcnQgPSAwOwogICAgICAgICAgICBpZiAobnVtRGltcyA+IDEpIHsKICAgICAgICAgICAgICBmb3IgKGk9MDsgaSA8IG51bURpbXM7IGkrKykgewogICAgICAgICAgICAgICAgblN0YXJ0ID0gaSAqIG51bVBpeGVsczsKICAgICAgICAgICAgICAgIGZvciAoayA9IDA7IGsgPCBudW1QaXhlbHM7IGsrKykgewogICAgICAgICAgICAgICAgICBpZiAobWFza1trXSkgewogICAgICAgICAgICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdFBpeGVsc1tuU3RhcnQgKyBrXSA9IHJhd0RhdGFbeisrXTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICBmb3IgKGsgPSAwOyBrIDwgbnVtUGl4ZWxzOyBrKyspIHsKICAgICAgICAgICAgICAgIGlmIChtYXNrW2tdKSB7CiAgICAgICAgICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdFBpeGVsc1trXSA9IHJhd0RhdGFbeisrXTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIHB0ciArPSBudW1CeXRlczsKICAgICAgICAgIGRhdGEucHRyID0gcHRyOyAgICAgICAvL3JldHVybiBkYXRhOwogICAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgICAgfSwKCiAgICAgICAgcmVhZEh1ZmZtYW5UcmVlOiBmdW5jdGlvbihpbnB1dCwgZGF0YSkgewogICAgICAgICAgdmFyIEJJVFNfTUFYID0gdGhpcy5IVUZGTUFOX0xVVF9CSVRTX01BWDsgLy84IGlzIHNsb3cgZm9yIHRoZSBsYXJnZSB0ZXN0IGltYWdlCiAgICAgICAgICAvL3ZhciBzaXplX21heCA9IDEgPDwgQklUU19NQVg7CiAgICAgICAgICAvKiAqKioqKioqKioqKioqKioqKioqKioqKioKICAgICAgICAgICAqIHJlYWRpbmcgY29kZSB0YWJsZQogICAgICAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgICAgICB2YXIgdmlldyA9IG5ldyBEYXRhVmlldyhpbnB1dCwgZGF0YS5wdHIsIDE2KTsKICAgICAgICAgIGRhdGEucHRyICs9IDE2OwogICAgICAgICAgdmFyIHZlcnNpb24gPSB2aWV3LmdldEludDMyKDAsIHRydWUpOwogICAgICAgICAgaWYgKHZlcnNpb24gPCAyKSB7CiAgICAgICAgICAgIHRocm93ICJ1bnN1cHBvcnRlZCBIdWZmbWFuIHZlcnNpb24iOwogICAgIC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YUJ5dGVzKSk7CiAgICAgICAgICB2YXIgc3R1ZmZlZERhdGEgPSBuZXcgVWludDMyQXJyYXkoYXJyYXlCdWYpOyAvL211c3Qgc3RhcnQgZnJvbSB4KjQKICAgICAgICAgIHZhciBiaXRQb3MgPSAwLCB3b3JkLCBzcmNQdHIgPSAwOwogICAgICAgICAgd29yZCA9IHN0dWZmZWREYXRhWzBdOwogICAgICAgICAgZm9yIChpID0gaTA7IGkgPCBpMTsgaSsrKSB7CiAgICAgICAgICAgIGogPSBpIC0gKGkgPCBzaXplID8gMCA6IHNpemUpOy8vd3JhcCBhcm91bmQKICAgICAgICAgICAgbGVuID0gY29kZVRhYmxlW2pdLmZpcnN0OwogICAgICAgICAgICBpZiAobGVuID4gMCkgewogICAgICAgICAgICAgIGNvZGVUYWJsZVtqXS5zZWNvbmQgPSAod29yZCA8PCBiaXRQb3MpID4+PiAoMzIgLSBsZW4pOwoKICAgICAgICAgICAgICBpZiAoMzIgLSBiaXRQb3MgPj0gbGVuKSB7CiAgICAgICAgICAgICAgICBiaXRQb3MgKz0gbGVuOwogICAgICAgICAgICAgICAgaWYgKGJpdFBvcyA9PT0gMzIpIHsKICAgICAgICAgICAgICAgICAgYml0UG9zID0gMDsKICAgICAgICAgICAgICAgICAgc3JjUHRyKys7CiAgICAgICAgICAgICAgICAgIHdvcmQgPSBzdHVmZmVkRGF0YVtzcmNQdHJdOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIGJpdFBvcyArPSBsZW4gLSAzMjsKICAgICAgICAgICAgICAgIHNyY1B0cisrOwogICAgICAgICAgICAgICAgd29yZCA9IHN0dWZmZWREYXRhW3NyY1B0cl07CiAgICAgICAgICAgICAgICBjb2RlVGFibGVbal0uc2Vjb25kIHw9IHdvcmQgPj4+ICgzMiAtIGJpdFBvcyk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CgogICAgICAgICAgLy9maW5pc2hlZCByZWFkaW5nIGNvZGUgdGFibGUKCiAgICAgICAgICAvKiAqKioqKioqKioqKioqKioqKioqKioqKioKICAgICAgICAgICAqIGJ1aWxkaW5nIGx1dAogICAgICAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgICAgICB2YXIgbnVtQml0c0xVVCA9IDAsIG51bUJpdHNMVVRRaWNrID0gMDsKICAgICAgICAgIHZhciB0cmVlID0gbmV3IFRyZWVOb2RlKCk7CiAgICAgICAgICBmb3IgKGkgPSAwOyBpIDwgY29kZVRhYmxlLmxlbmd0aDsgaSsrKSB7CiAgICAgICAgICAgIGlmIChjb2RlVGFibGVbaV0gIT09IHVuZGVmaW5lZCkgewogICAgICAgICAgICAgIG51bUJpdHNMVVQgPSBNYXRoLm1heChudW1CaXRzTFVULCBjb2RlVGFibGVbaV0uZmlyc3QpOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICBpZiAobnVtQml0c0xVVCA+PSBCSVRTX01BWCkgewogICAgICAgICAgICBudW1CaXRzTFVUUWljayA9IEJJVFNfTUFYOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgIG51bUJpdHNMVVRRaWNrID0gbnVtQml0c0xVVDsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChudW1CaXRzTFVUID49IDMwKSB7CiAgICAgICAgICAgIGNvbnNvbGUubG9nKCJXQVJuaW5nLCBsYXJnZSBOVU0gTFVUIEJJVFMgSVMgIiArIG51bUJpdHNMVVQpOwogICAgICAgICAgfQogICAgICAgICAgdmFyIGRlY29kZUx1dCA9IFtdLCBlbnRyeSwgY29kZSwgbnVtRW50cmllcywgamosIGN1cnJlbnRCaXQsIG5vZGU7CiAgICAgICAgICBmb3IgKGkgPSBpMDsgaSA8IGkxOyBpKyspIHsKICAgICAgICAgICAgaiA9IGkgLSAoaSA8IHNpemUgPyAwIDogc2l6ZSk7Ly93cmFwIGFyb3VuZAogICAgICAgICAgICBsZW4gPSBjb2RlVGFibGVbal0uZmlyc3Q7CiAgICAgICAgICAgIGlmIChsZW4gPiAwKSB7CiAgICAgICAgICAgICAgZW50cnkgPSBbbGVuLCBqXTsKICAgICAgICAgICAgICBpZiAobGVuIDw9IG51bUJpdHNMVVRRaWNrKSB7CiAgICAgICAgICAgICAgICBjb2RlID0gY29kZVRhYmxlW2pdLnNlY29uZCA8PCAobnVtQml0c0xVVFFpY2sgLSBsZW4pOwogICAgICAgICAgICAgICAgbnVtRW50cmllcyA9IDEgPDwgKG51bUJpdHNMVVRRaWNrIC0gbGVuKTsKICAgICAgICAgICAgICAgIGZvciAoayA9IDA7IGsgPCBudW1FbnRyaWVzOyBrKyspIHsKICAgICAgICAgICAgICAgICAgZGVjb2RlTHV0W2NvZGUgfCBrXSA9IGVudHJ5OwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIC8vYnVpbGQgdHJlZQogICAgICAgICAgICAgICAgY29kZSA9IGNvZGVUYWJsZVtqXS5zZWNvbmQ7CiAgICAgICAgICAgICAgICBub2RlID0gdHJlZTsKICAgICAgICAgICAgICAgIGZvciAoamogPSBsZW4gLSAxOyBqaiA+PSAwOyBqai0tKSB7CiAgICAgICAgICAgICAgICAgIGN1cnJlbnRCaXQgPSBjb2RlID4+PiBqaiAmIDE7IC8vbm8gbGVmdCBzaGlmdCBhcyBsZW5ndGggY291bGQgYmUgMzAsMzEKICAgICAgICAgICAgICAgICAgaWYgKGN1cnJlbnRCaXQpIHsKICAgICAgICAgICAgICAgICAgICBpZiAoIW5vZGUucmlnaHQpIHsKICAgICAgICAgICAgICAgICAgICAgIG5vZGUucmlnaHQgPSBuZXcgVHJlZU5vZGUoKTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgbm9kZSA9IG5vZGUucmlnaHQ7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgaWYgKCFub2RlLmxlZnQpIHsKICAgICAgICAgICAgICAgICAgICAgIG5vZGUubGVmdCA9IG5ldyBUcmVlTm9kZSgpOwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICBub2RlID0gbm9kZS5sZWZ0OwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIGlmIChqaiA9PT0gMCAmJiAhbm9kZS52YWwpIHsKICAgICAgICAgICAgICAgICAgICBub2RlLnZhbCA9IGVudHJ5WzFdOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm4gewogICAgICAgICAgICBkZWNvZGVMdXQ6IGRlY29kZUx1dCwKICAgICAgICAgICAgbnVtQml0c0xVVFFpY2s6IG51bUJpdHNMVVRRaWNrLAogICAgICAgICAgICBudW1CaXRzTFVUOiBudW1CaXRzTFVULAogICAgICAgICAgICB0cmVlOiB0cmVlLAogICAgICAgICAgICBzdHVmZmVkRGF0YTogc3R1ZmZlZERhdGEsCiAgICAgICAgICAgIHNyY1B0cjogc3JjUHRyLAogICAgICAgICAgICBiaXRQb3M6IGJpdFBvcwogICAgICAgICAgfTsKICAgICAgICB9LAoKICAgICAgICByZWFkSHVmZm1hbjogZnVuY3Rpb24oaW5wdXQsIGRhdGEsIE91dFBpeGVsVHlwZUFycmF5KSB7CiAgICAgICAgICB2YXIgaGVhZGVySW5mbyA9IGRhdGEuaGVhZGVySW5mbzsKICAgICAgICAgIHZhciBudW1EaW1zID0gaGVhZGVySW5mby5udW1EaW1zOwogICAgICAgICAgdmFyIGhlaWdodCA9IGRhdGEuaGVhZGVySW5mby5oZWlnaHQ7CiAgICAgICAgICB2YXIgd2lkdGggPSBkYXRhLmhlYWRlckluZm8ud2lkdGg7CiAgICAgICAgICB2YXIgbnVtUGl4ZWxzID0gd2lkdGggKiBoZWlnaHQ7CiAgICAgICAgICAvL3ZhciBzaXplX21heCA9IDEgPDwgQklUU19NQVg7CiAgICAgICAgICAvKiAqKioqKioqKioqKioqKioqKioqKioqKioKICAgICAgICAgICAqIHJlYWRpbmcgaHVmZm1hbiBzdHJ1Y3R1cmUgaW5mbwogICAgICAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgICAgICB2YXIgaHVmZm1hbkluZm8gPSB0aGlzLnJlYWRIdWZmbWFuVHJlZShpbnB1dCwgZGF0YSk7CiAgICAgICAgICB2YXIgZGVjb2RlTHV0ID0gaHVmZm1hbkluZm8uZGVjb2RlTHV0OwogICAgICAgICAgdmFyIHRyZWUgPSBodWZmbWFuSW5mby50cmVlOwogICAgICAgICAgLy9zdHVmZmVkRGF0YSBpbmNsdWRlcyBodWZmbWFuIGhlYWRlcnMKICAgICAgICAgIHZhciBzdHVmZmVkRGF0YSA9IGh1ZmZtYW5JbmZvLnN0dWZmZWREYXRhOwogICAgICAgICAgdmFyIHNyY1B0ciA9IGh1ZmZtYW5JbmZvLnNyY1B0cjsKICAgICAgICAgIHZhciBiaXRQb3MgPSBodWZmbWFuSW5mby5iaXRQb3M7CiAgICAgICAgICB2YXIgbnVtQml0c0xVVFFpY2sgPSBodWZmbWFuSW5mby5udW1CaXRzTFVUUWljazsKICAgICAgICAgIHZhciBudW1CaXRzTFVUID0gaHVmZm1hbkluZm8ubnVtQml0c0xVVDsKICAgICAgICAgIHZhciBvZmZzZXQgPSBkYXRhLmhlYWRlckluZm8uaW1hZ2VUeXBlID09PSAwID8gMTI4IDogMDsKICAgICAgICAgIC8qKioqKioqKioqKioqKioqKioqKioqKioqCiAgICAgICAgICAqICBkZWNvZGUKICAgICAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKioqKi8KICAgICAgICAgIHZhciBub2RlLCB2YWwsIGRlbHRhLCBtYXNrID0gZGF0YS5waXhlbHMucmVzdWx0TWFzaywgdmFsVG1wLCB2YWxUbXBRdWljaywgY3VycmVudEJpdDsKICAgICAgICAgIHZhciBpLCBqLCBrLCBpaTsKICAgICAgICAgIHZhciBwcmV2VmFsID0gMDsKICAgICAgICAgIGlmIChiaXRQb3MgPiAwKSB7CiAgICAgICAgICAgIHNyY1B0cisrOwogICAgICAgICAgICBiaXRQb3MgPSAwOwogICAgICAgICAgfQogICAgICAgICAgdmFyIHdvcmQgPSBzdHVmZmVkRGF0YVtzcmNQdHJdOwogICAgICAgICAgdmFyIGRlbHRhRW5jb2RlID0gZGF0YS5lbmNvZGVNb2RlID09PSAxOwogICAgICAgICAgdmFyIHJlc3VsdFBpeGVsc0FsbERpbSA9IG5ldyBPdXRQaXhlbFR5cGVBcnJheShudW1QaXhlbHMgKiBudW1EaW1zKTsKICAgICAgICAgIHZhciByZXN1bHRQaXhlbHMgPSByZXN1bHRQaXhlbHNBbGxEaW07CiAgICAgICAgICB2YXIgaURpbTsKICAgICAgICAgIGZvciAoaURpbSA9IDA7IGlEaW0gPCBoZWFkZXJJbmZvLm51bURpbXM7IGlEaW0rKykgewogICAgICAgICAgICBpZiAobnVtRGltcyA+IDEpIHsKICAgICAgICAgICAgICAvL2dldCB0aGUgbWVtIGJsb2NrIG9mIGN1cnJlbnQgZGltZW5zaW9uCiAgICAgICAgICAgICAgcmVzdWx0UGl4ZWxzID0gbmV3IE91dFBpeGVsVHlwZUFycmF5KHJlc3VsdFBpeGVsc0FsbERpbS5idWZmZXIsIG51bVBpeGVscyAqIGlEaW0sIG51bVBpeGVscyk7CiAgICAgICAgICAgICAgcHJldlZhbCA9IDA7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGRhdGEuaGVhZGVySW5mby5udW1WYWxpZFBpeGVsID09PSB3aWR0aCAqIGhlaWdodCkgeyAvL2FsbCB2YWxpZAogICAgICAgICAgICAgIGZvciAoayA9IDAsIGkgPSAwOyBpIDwgaGVpZ2h0OyBpKyspIHsKICAgICAgICAgICAgICAgIGZvciAoaiA9IDA7IGogPCB3aWR0aDsgaisrLCBrKyspIHsKICAgICAgICAgICAgICAgICAgdmFsID0gMDsKICAgICAgICAgICAgICAgICAgdmFsVG1wID0gKHdvcmQgPDwgYml0UG9zKSA+Pj4gKDMyIC0gbnVtQml0c0xVVFFpY2spOwogICAgICAgICAgICAgICAgICB2YWxUbXBRdWljayA9IHZhbFRtcDsvLyA+Pj4gZGVsdGFCaXRzOwogICAgICAgICAgICAgICAgICBpZiAoMzIgLSBiaXRQb3MgPCBudW1CaXRzTFVUUWljaykgewogICAgICAgICAgICAgICAgICAgIHZhbFRtcCB8PSAoKHN0dWZmZWREYXRhW3NyY1B0ciArIDFdKSA+Pj4gKDY0IC0gYml0UG9zIC0gbnVtQml0c0xVVFFpY2spKTsKICAgICAgICAgICAgICAgICAgICB2YWxUbXBRdWljayA9IHZhbFRtcDsvLyA+Pj4gZGVsdGFCaXRzOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIGlmIChkZWNvZGVMdXRbdmFsVG1wUXVpY2tdKSAgICAvLyBpZiB0aGVyZSwgbW92ZSB0aGUgY29ycmVjdCBudW1iZXIgb2YgYml0cyBhbmQgZG9uZQogICAgICAgICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAgICAgdmFsID0gZGVjb2RlTHV0W3ZhbFRtcFF1aWNrXVsxXTsKICAgICAgICAgICAgICAgICAgICBiaXRQb3MgKz0gZGVjb2RlTHV0W3ZhbFRtcFF1aWNrXVswXTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICB2YWxUbXAgPSAod29yZCA8PCBiaXRQb3MpID4+PiAoMzIgLSBudW1CaXRzTFVUKTsKICAgICAgICAgICAgICAgICAgICB2YWxUbXBRdWljayA9IHZhbFRtcDsvLyA+Pj4gZGVsdGFCaXRzOwogICAgICAgICAgICAgICAgICAgIGlmICgzMiAtIGJpdFBvcyA8IG51bUJpdHNMVVQpIHsKICAgICAgICAgICAgICAgICAgICAgIHZhbFRtcCB8PSAoKHN0dWZmZWREYXRhW3NyY1B0ciArIDFdKSA+Pj4gKDY0IC0gYml0UG9zIC0gbnVtQml0c0xVVCkpOwogICAgICAgICAgICAgICAgICAgICAgdmFsVG1wUXVpY2sgPSB2YWxUbXA7Ly8gPj4+IGRlbHRhQml0czsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgbm9kZSA9IHRyZWU7CiAgICAgICAgICAgICAgICAgICAgZm9yIChpaSA9IDA7IGlpIDwgbnVtQml0c0xVVDsgaWkrKykgewogICAgICAgICAgICAgICAgICAgICAgY3VycmVudEJpdCA9IHZhbFRtcCA+Pj4gKG51bUJpdHNMVVQgLSBpaSAtIDEpICYgMTsKICAgICAgICAgICAgICAgICAgICAgIG5vZGUgPSBjdXJyZW50Qml0ID8gbm9kZS5yaWdodCA6IG5vZGUubGVmdDsKICAgICAgICAgICAgICAgICAgICAgIGlmICghKG5vZGUubGVmdCB8fCBub2RlLnJpZ2h0KSkgewogICAgICAgICAgICAgICAgICAgICAgICB2YWwgPSBub2RlLnZhbDsKICAgICAgICAgICAgICAgICAgICAgICAgYml0UG9zID0gYml0UG9zICsgaWkgKyAxOwogICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KCiAgICAgICAgICAgICAgICAgIGlmIChiaXRQb3MgPj0gMzIpIHsKICAgICAgICAgICAgICAgICAgICBiaXRQb3MgLT0gMzI7CiAgICAgICAgICAgICAgICAgICAgc3JjUHRyKys7CiAgICAgICAgICAgICAgICAgICAgd29yZCA9IHN0dWZmZWREYXRhW3NyY1B0cl07CiAgICAgICAgICAgICAgICAgIH0KCiAgICAgICAgICAgICAgICAgIGRlbHRhID0gdmFsIC0gb2Zmc2V0OwogICAgICAgICAgICAgICAgICBpZiAoZGVsdGFFbmNvZGUpIHsKICAgICAgICAgICAgICAgICAgICBpZiAoaiA+IDApIHsKICAgICAgICAgICAgICAgICAgICAgIGRlbHRhICs9IHByZXZWYWw7ICAgIC8vIHVzZSBvdmVyZmxvdwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICBlbHNlIGlmIChpID4gMCkgewogICAgICAgICAgICAgICAgICAgICAgZGVsdGEgKz0gcmVzdWx0UGl4ZWxzW2sgLSB3aWR0aF07CiAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgICAgICAgZGVsdGEgKz0gcHJldlZhbDsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgZGVsdGEgJj0gMHhGRjsgLy9vdmVyZmxvdwogICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1trXSA9IGRlbHRhOy8vb3ZlcmZsb3cKICAgICAgICAgICAgICAgICAgICBwcmV2VmFsID0gZGVsdGE7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgcmVzdWx0UGl4ZWxzW2tdID0gZGVsdGE7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZSB7IC8vbm90IGFsbCB2YWxpZCwgdXNlIG1hc2sKICAgICAgICAgICAgICBmb3IgKGsgPSAwLCBpID0gMDsgaSA8IGhlaWdodDsgaSsrKSB7CiAgICAgICAgICAgICAgICBmb3IgKGogPSAwOyBqIDwgd2lkdGg7IGorKywgaysrKSB7CiAgICAgICAgICAgICAgICAgIGlmIChtYXNrW2tdKSB7CiAgICAgICAgICAgICAgICAgICAgdmFsID0gMDsKICAgICAgICAgICAgICAgICAgICB2YWxUbXAgPSAod29yZCA8PCBiaXRQb3MpID4+PiAoMzIgLSBudW1CaXRzTFVUUWljayk7CiAgICAgICAgICAgICAgICAgICAgdmFsVG1wUXVpY2sgPSB2YWxUbXA7Ly8gPj4+IGRlbHRhQml0czsKICAgICAgICAgICAgICAgICAgICBpZiAoMzIgLSBiaXRQb3MgPCBudW1CaXRzTFVUUWljaykgewogICAgICAgICAgICAgICAgICAgICAgdmFsVG1wIHw9ICgoc3R1ZmZlZERhdGFbc3JjUHRyICsgMV0pID4+PiAoNjQgLSBiaXRQb3MgLSBudW1CaXRzTFVUUWljaykpOwogICAgICAgICAgICAgICAgICAgICAgdmFsVG1wUXVpY2sgPSB2YWxUbXA7Ly8gPj4+IGRlbHRhQml0czsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgaWYgKGRlY29kZUx1dFt2YWxUbXBRdWlja10pICAgIC8vIGlmIHRoZXJlLCBtb3ZlIHRoZSBjb3JyZWN0IG51bWJlciBvZiBiaXRzIGFuZCBkb25lCiAgICAgICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgICAgdmFsID0gZGVjb2RlTHV0W3ZhbFRtcFF1aWNrXVsxXTsKICAgICAgICAgICAgICAgICAgICAgIGJpdFBvcyArPSBkZWNvZGVMdXRbdmFsVG1wUXVpY2tdWzBdOwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICAgIHZhbFRtcCA9ICh3b3JkIDw8IGJpdFBvcykgPj4+ICgzMiAtIG51bUJpdHNMVVQpOwogICAgICAgICAgICAgICAgICAgICAgdmFsVG1wUXVpY2sgPSB2YWxUbXA7Ly8gPj4+IGRlbHRhQml0czsKICAgICAgICAgICAgICAgICAgICAgIGlmICgzMiAtIGJpdFBvcyA8IG51bUJpdHNMVVQpIHsKICAgICAgICAgICAgICAgICAgICAgICAgdmFsVG1wIHw9ICgoc3R1ZmZlZERhdGFbc3JjUHRyICsgMV0pID4+PiAoNjQgLSBiaXRQb3MgLSBudW1CaXRzTFVUKSk7CiAgICAgICAgICAgICAgICAgICAgICAgIHZhbFRtcFF1aWNrID0gdmFsVG1wOy8vID4+PiBkZWx0YUJpdHM7CiAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICBub2RlID0gdHJlZTsKICAgICAgICAgICAgICAgICAgICAgIGZvciAoaWkgPSAwOyBpaSA8IG51bUJpdHNMVVQ7IGlpKyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgY3VycmVudEJpdCA9IHZhbFRtcCA+Pj4gKG51bUJpdHNMVVQgLSBpaSAtIDEpICYgMTsKICAgICAgICAgICAgICAgICAgICAgICAgbm9kZSA9IGN1cnJlbnRCaXQgPyBub2RlLnJpZ2h0IDogbm9kZS5sZWZ0OwogICAgICAgICAgICAgICAgICAgICAgICBpZiAoIShub2RlLmxlZnQgfHwgbm9kZS5yaWdodCkpIHsKICAgICAgICAgICAgICAgICAgICAgICAgICB2YWwgPSBub2RlLnZhbDsKICAgICAgICAgICAgICAgICAgICAgICAgICBiaXRQb3MgPSBiaXRQb3MgKyBpaSArIDE7CiAgICAgICAgICAgICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICB9CgogICAgICAgICAgICAgICAgICAgIGlmIChiaXRQb3MgPj0gMzIpIHsKICAgICAgICAgICAgICAgICAgICAgIGJpdFBvcyAtPSAzMjsKICAgICAgICAgICAgICAgICAgICAgIHNyY1B0cisrOwogICAgICAgICAgICAgICAgICAgICAgd29yZCA9IHN0dWZmZWREYXRhW3NyY1B0cl07CiAgICAgICAgICAgICAgICAgICAgfQoKICAgICAgICAgICAgICAgICAgICBkZWx0YSA9IHZhbCAtIG9mZnNldDsKICAgICAgICAgICAgICAgICAgICBpZiAoZGVsdGFFbmNvZGUpIHsKICAgICAgICAgICAgICAgICAgICAgIGlmIChqID4gMCAmJiBtYXNrW2sgLSAxXSkgewogICAgICAgICAgICAgICAgICAgICAgICBkZWx0YSArPSBwcmV2VmFsOyAgICAvLyB1c2Ugb3ZlcmZsb3cKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgIGVsc2UgaWYgKGkgPiAwICYmIG1hc2tbayAtIHdpZHRoXSkgewogICAgICAgICAgICAgICAgICAgICAgICBkZWx0YSArPSByZXN1bHRQaXhlbHNbayAtIHdpZHRoXTsKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgICAgICAgICBkZWx0YSArPSBwcmV2VmFsOwogICAgICAgICAgICAgICAgICAgICAgfQoKICAgICAgICAgICAgICAgICAgICAgIGRlbHRhICY9IDB4RkY7IC8vb3ZlcmZsb3cKICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1trXSA9IGRlbHRhOy8vb3ZlcmZsb3cKICAgICAgICAgICAgICAgICAgICAgIHByZXZWYWwgPSBkZWx0YTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgICByZXN1bHRQaXhlbHNba10gPSBkZWx0YTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZGF0YS5wdHIgPSBkYXRhLnB0ciArIChzcmNQdHIgKyAxKSAqIDQgKyAoYml0UG9zID4gMCA/IDQgOiAwKTsKICAgICAgICAgIH0KICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdFBpeGVscyA9IHJlc3VsdFBpeGVsc0FsbERpbTsKICAgICAgICB9LAoKICAgICAgICBkZWNvZGVCaXRzOiBmdW5jdGlvbihpbnB1dCwgZGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBvZmZzZXQsIGlEaW0pIHsKICAgICAgICAgIHsKICAgICAgICAgICAgLy9iaXRzdHVmZiBlbmNvZGluZyBpcyAzCiAgICAgICAgICAgIHZhciBoZWFkZXJJbmZvID0gZGF0YS5oZWFkZXJJbmZvOwogICAgICAgICAgICB2YXIgZmlsZVZlcnNpb24gPSBoZWFkZXJJbmZvLmZpbGVWZXJzaW9uOwogICAgICAgICAgICAvL3ZhciBibG9jayA9IHt9OwogICAgICAgICAgICB2YXIgYmxvY2tQdHIgPSAwOwogICAgICAgICAgICB2YXIgdmlldyA9IG5ldyBEYXRhVmlldyhpbnB1dCwgZGF0YS5wdHIsIDUpOy8vdG8gZG8KICAgICAgICAgICAgdmFyIGhlYWRlckJ5dGUgPSB2aWV3LmdldFVpbnQ4KDApOwogICAgICAgICAgICBibG9ja1B0cisrOwogICAgICAgICAgICB2YXIgYml0czY3ID0gaGVhZGVyQnl0ZSA+PiA2OwogICAgICAgICAgICB2YXIgbiA9IChiaXRzNjcgPT09IDApID8gNCA6IDMgLSBiaXRzNjc7CiAgICAgICAgICAgIHZhciBkb0x1dCA9IChoZWFkZXJCeXRlICYgMzIpID4gMCA/IHRydWUgOiBmYWxzZTsvLzV0aCBiaXQKICAgICAgICAgICAgdmFyIG51bUJpdHMgPSBoZWFkZXJCeXRlICYgMzE7CiAgICAgICAgICAgIHZhciBudW1FbGVtZW50cyA9IDA7CiAgICAgICAgICAgIGlmIChuID09PSAxKSB7CiAgICAgICAgICAgICAgbnVtRWxlbWVudHMgPSB2aWV3LmdldFVpbnQ4KGJsb2NrUHRyKTsgYmxvY2tQdHIrKzsKICAgICAgICAgICAgfSBlbHNlIGlmIChuID09PSAyKSB7CiAgICAgICAgICAgICAgbnVtRWxlbWVudHMgPSB2aWV3LmdldFVpbnQxNihibG9ja1B0ciwgdHJ1ZSk7IGJsb2NrUHRyICs9IDI7CiAgICAgICAgICAgIH0gZWxzZSBpZiAobiA9PT0gNCkgewogICAgICAgICAgICAgIG51bUVsZW1lbnRzID0gdmlldy5nZXRVaW50MzIoYmxvY2tQdHIsIHRydWUpOyBibG9ja1B0ciArPSA0OwogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgIHRocm93ICJJbnZhbGlkIHZhbGlkIHBpeGVsIGNvdW50IHR5cGUiOwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vZml4OiBodWZmbWFuIGNvZGVzIGFyZSBiaXQgc3R1ZmZlZCwgYnV0IG5vdCBib3VuZCBieSBkYXRhJ3MgbWF4IHZhbHVlLCBzbyBuZWVkIHRvIHVzZSBvcmlnaW5hbFVuc3R1ZmYKICAgICAgICAgICAgLy9vZmZzZXQgPSBvZmZzZXQgfHwgMDsKICAgICAgICAgICAgdmFyIHNjYWxlID0gMiAqIGhlYWRlckluZm8ubWF4WkVycm9yOwogICAgICAgICAgICB2YXIgc3R1ZmZlZERhdGEsIGFycmF5QnVmLCBzdG9yZTgsIGRhdGFCeXRlcywgZGF0YVdvcmRzOwogICAgICAgICAgICB2YXIgbHV0QXJyLCBsdXREYXRhLCBsdXRCeXRlcywgYml0c1BlclBpeGVsOwogICAgICAgICAgICB2YXIgek1heCA9IGhlYWRlckluZm8ubnVtRGltcyA+IDEgPyBoZWFkZXJJbmZvLm1heFZhbHVlc1tpRGltXSA6IGhlYWRlckluZm8uek1heDsKICAgICAgICAgICAgaWYgKGRvTHV0KSB7CiAgICAgICAgICAgICAgZGF0YS5jb3VudGVyLmx1dCsrOwogICAgICAgICAgICAgIGx1dEJ5dGVzID0gdmlldy5nZXRVaW50OChibG9ja1B0cik7CiAgICAgICAgICAgICAgYmxvY2tQdHIrKzsKICAgICAgICAgICAgICBkYXRhQnl0ZXMgPSBNYXRoLmNlaWwoKGx1dEJ5dGVzIC0gMSkgKiBudW1CaXRzIC8gOCk7CiAgICAgICAgICAgICAgZGF0YVdvcmRzID0gTWF0aC5jZWlsKGRhdGFCeXRlcyAvIDQpOwogICAgICAgICAgICAgIGFycmF5QnVmID0gbmV3IEFycmF5QnVmZmVyKGRhdGFXb3JkcyAqIDQpOwogICAgICAgICAgICAgIHN0b3JlOCA9IG5ldyBVaW50OEFyc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x1dEJ5dGVzIC0gMSwgb2Zmc2V0LCBzY2FsZSwgek1heCk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgbHV0QXJyID0gQml0U3R1ZmZlci51bnN0dWZmTFVUKGx1dERhdGEsIG51bUJpdHMsIGx1dEJ5dGVzIC0gMSwgb2Zmc2V0LCBzY2FsZSwgek1heCk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIC8vbHV0QXJyLnVuc2hpZnQoMCk7CiAgICAgICAgICAgICAgaWYgKGZpbGVWZXJzaW9uID49IDMpIHsKICAgICAgICAgICAgICAgIC8vQml0U3R1ZmZlci51bnN0dWZmMihibG9jaywgYmxvY2tEYXRhQnVmZmVyLCBoZWFkZXJJbmZvLnpNYXgpOwogICAgICAgICAgICAgICAgQml0U3R1ZmZlci51bnN0dWZmMihzdHVmZmVkRGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBiaXRzUGVyUGl4ZWwsIG51bUVsZW1lbnRzLCBsdXRBcnIpOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIEJpdFN0dWZmZXIudW5zdHVmZihzdHVmZmVkRGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBiaXRzUGVyUGl4ZWwsIG51bUVsZW1lbnRzLCBsdXRBcnIpOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAvL2NvbnNvbGUuZGVidWcoImJpdHN0dWZmZXIiKTsKICAgICAgICAgICAgICBkYXRhLmNvdW50ZXIuYml0c3R1ZmZlcisrOwogICAgICAgICAgICAgIGJpdHNQZXJQaXhlbCA9IG51bUJpdHM7CiAgICAgICAgICAgICAgZGF0YS5wdHIgKz0gYmxvY2tQdHI7CiAgICAgICAgICAgICAgaWYgKGJpdHNQZXJQaXhlbCA+IDApIHsKICAgICAgICAgICAgICAgIGRhdGFCeXRlcyA9IE1hdGguY2VpbChudW1FbGVtZW50cyAqIGJpdHNQZXJQaXhlbCAvIDgpOwogICAgICAgICAgICAgICAgZGF0YVdvcmRzID0gTWF0aC5jZWlsKGRhdGFCeXRlcyAvIDQpOwogICAgICAgICAgICAgICAgYXJyYXlCdWYgPSBuZXcgQXJyYXlCdWZmZXIoZGF0YVdvcmRzICogNCk7CiAgICAgICAgICAgICAgICBzdG9yZTggPSBuZXcgVWludDhBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgICAgICBzdG9yZTguc2V0KG5ldyBVaW50OEFycmF5KGlucHV0LCBkYXRhLnB0ciwgZGF0YUJ5dGVzKSk7CiAgICAgICAgICAgICAgICBzdHVmZmVkRGF0YSA9IG5ldyBVaW50MzJBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgICAgICBkYXRhLnB0ciArPSBkYXRhQnl0ZXM7CiAgICAgICAgICAgICAgICBpZiAoZmlsZVZlcnNpb24gPj0gMykgewogICAgICAgICAgICAgICAgICBpZiAob2Zmc2V0ID09IG51bGwpIHsKICAgICAgICAgICAgICAgICAgICBCaXRTdHVmZmVyLm9yaWdpbmFsVW5zdHVmZjIoc3R1ZmZlZERhdGEsIGJsb2NrRGF0YUJ1ZmZlciwgYml0c1BlclBpeGVsLCBudW1FbGVtZW50cyk7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgQml0U3R1ZmZlci51bnN0dWZmMihzdHVmZmVkRGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBiaXRzUGVyUGl4ZWwsIG51bUVsZW1lbnRzLCBmYWxzZSwgb2Zmc2V0LCBzY2FsZSwgek1heCk7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgICBpZiAob2Zmc2V0ID09IG51bGwpIHsKICAgICAgICAgICAgICAgICAgICBCaXRTdHVmZmVyLm9yaWdpbmFsVW5zdHVmZihzdHVmZmVkRGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBiaXRzUGVyUGl4ZWwsIG51bUVsZW1lbnRzKTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICBCaXRTdHVmZmVyLnVuc3R1ZmYoc3R1ZmZlZERhdGEsIGJsb2NrRGF0YUJ1ZmZlciwgYml0c1BlclBpeGVsLCBudW1FbGVtZW50cywgZmFsc2UsIG9mZnNldCwgc2NhbGUsIHpNYXgpOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CgogICAgICAgIH0sCgogICAgICAgIHJlYWRUaWxlczogZnVuY3Rpb24oaW5wdXQsIGRhdGEsIE91dFBpeGVsVHlwZUFycmF5KSB7CiAgICAgICAgICB2YXIgaGVhZGVySW5mbyA9IGRhdGEuaGVhZGVySW5mbzsKICAgICAgICAgIHZhciB3aWR0aCA9IGhlYWRlckluZm8ud2lkdGg7CiAgICAgICAgICB2YXIgaGVpZ2h0ID0gaGVhZGVySW5mby5oZWlnaHQ7CiAgICAgICAgICB2YXIgbWljcm9CbG9ja1NpemUgPSBoZWFkZXJJbmZvLm1pY3JvQmxvY2tTaXplOwogICAgICAgICAgdmFyIGltYWdlVHlwZSA9IGhlYWRlckluZm8uaW1hZ2VUeXBlOwogICAgICAgICAgdmFyIGRhdGFUeXBlU2l6ZSA9IExlcmMySGVscGVycy5nZXREYXRhVHlwZVNpemUoaW1hZ2VUeXBlKTsKICAgICAgICAgIHZhciBudW1CbG9ja3NYID0gTWF0aC5jZWlsKHdpZHRoIC8gbWljcm9CbG9ja1NpemUpOwogICAgICAgICAgdmFyIG51bUJsb2Nrc1kgPSBNYXRoLmNlaWwoaGVpZ2h0IC8gbWljcm9CbG9ja1NpemUpOwogICAgICAgICAgZGF0YS5waXhlbHMubnVtQmx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AgICAgICAgICAgICAgdmlldyA9IG5ldyBEYXRhVmlldyhpbnB1dCwgZGF0YS5wdHIsIE1hdGgubWluKDEwLCBieXRlc0xlZnQpKTsKICAgICAgICAgICAgICAgIGJsb2NrID0ge307CiAgICAgICAgICAgICAgICBibG9ja1B0ciA9IDA7CiAgICAgICAgICAgICAgICBoZWFkZXJCeXRlID0gdmlldy5nZXRVaW50OCgwKTsKICAgICAgICAgICAgICAgIGJsb2NrUHRyKys7CiAgICAgICAgICAgICAgICBiaXRzNjcgPSAoaGVhZGVyQnl0ZSA+PiA2KSAmIDB4RkY7CiAgICAgICAgICAgICAgICB0ZXN0Q29kZSA9IChoZWFkZXJCeXRlID4+IDIpICYgMTU7ICAgIC8vIHVzZSBiaXRzIDIzNDUgZm9yIGludGVncml0eSBjaGVjawogICAgICAgICAgICAgICAgaWYgKHRlc3RDb2RlICE9PSAoKChibG9ja1ggKiBtaWNyb0Jsb2NrU2l6ZSkgPj4gMykgJiAxNSkpIHsKICAgICAgICAgICAgICAgICAgdGhyb3cgImludGVncml0eSBpc3N1ZSI7CiAgICAgICAgICAgICAgICAgIC8vcmV0dXJuIGZhbHNlOwogICAgICAgICAgICAgICAgfQoKICAgICAgICAgICAgICAgIGJsb2NrRW5jb2RpbmcgPSBoZWFkZXJCeXRlICYgMzsKICAgICAgICAgICAgICAgIGlmIChibG9ja0VuY29kaW5nID4gMykgewogICAgICAgICAgICAgICAgICBkYXRhLnB0ciArPSBibG9ja1B0cjsKICAgICAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgYmxvY2sgZW5jb2RpbmcgKCIgKyBibG9ja0VuY29kaW5nICsgIikiOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZWxzZSBpZiAoYmxvY2tFbmNvZGluZyA9PT0gMikgeyAvL2NvbnN0YW50IDAKICAgICAgICAgICAgICAgICAgZGF0YS5jb3VudGVyLmNvbnN0YW50Kys7CiAgICAgICAgICAgICAgICAgIGRhdGEucHRyICs9IGJsb2NrUHRyOwogICAgICAgICAgICAgICAgICBjb250aW51ZTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGVsc2UgaWYgKGJsb2NrRW5jb2RpbmcgPT09IDApIHsgIC8vdW5jb21wcmVzc2VkCiAgICAgICAgICAgICAgICAgIGRhdGEuY291bnRlci51bmNvbXByZXNzZWQrKzsKICAgICAgICAgICAgICAgICAgZGF0YS5wdHIgKz0gYmxvY2tQdHI7CiAgICAgICAgICAgICAgICAgIG51bUJ5dGVzID0gdGhpc0Jsb2NrSGVpZ2h0ICogdGhpc0Jsb2NrV2lkdGggKiBkYXRhVHlwZVNpemU7CiAgICAgICAgICAgICAgICAgIGJ5dGVzbGVmdCA9IGlucHV0LmJ5dGVMZW5ndGggLSBkYXRhLnB0cjsKICAgICAgICAgICAgICAgICAgbnVtQnl0ZXMgPSBudW1CeXRlcyA8IGJ5dGVzbGVmdCA/IG51bUJ5dGVzIDogYnl0ZXNsZWZ0OwogICAgICAgICAgICAgICAgICAvL2JpdCBhbGlnbm1lbnQKICAgICAgICAgICAgICAgICAgYXJyYXlCdWYgPSBuZXcgQXJyYXlCdWZmZXIoKG51bUJ5dGVzICUgZGF0YVR5cGVTaXplKSA9PT0gMCA/IG51bUJ5dGVzIDogKG51bUJ5dGVzICsgZGF0YVR5cGVTaXplIC0gbnVtQnl0ZXMgJSBkYXRhVHlwZVNpemUpKTsKICAgICAgICAgICAgICAgICAgc3RvcmU4ID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlCdWYpOwogICAgICAgICAgICAgICAgICBzdG9yZTguc2V0KG5ldyBVaW50OEFycmF5KGlucHV0LCBkYXRhLnB0ciwgbnVtQnl0ZXMpKTsKICAgICAgICAgICAgICAgICAgcmF3RGF0YSA9IG5ldyBPdXRQaXhlbFR5cGVBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgICAgICAgIHogPSAwOwogICAgICAgICAgICAgICAgICBpZiAobWFzaykgewogICAgICAgICAgICAgICAgICAgIGZvciAocm93ID0gMDsgcm93IDwgdGhpc0Jsb2NrSGVpZ2h0OyByb3crKykgewogICAgICAgICAgICAgICAgICAgICAgZm9yIChjb2wgPSAwOyBjb2wgPCB0aGlzQmxvY2tXaWR0aDsgY29sKyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgaWYgKG1hc2tbb3V0UHRyXSkgewogICAgICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHJdID0gcmF3RGF0YVt6KytdOwogICAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICAgIG91dFB0cisrOwogICAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7Ly9hbGwgdmFsaWQKICAgICAgICAgICAgICAgICAgICBmb3IgKHJvdyA9IDA7IHJvdyA8IHRoaXNCbG9ja0hlaWdodDsgcm93KyspIHsKICAgICAgICAgICAgICAgICAgICAgIGZvciAoY29sID0gMDsgY29sIDwgdGhpc0Jsb2NrV2lkdGg7IGNvbCsrKSB7CiAgICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHIrK10gPSByYXdEYXRhW3orK107CiAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICBvdXRQdHIgKz0gb3V0U3RyaWRlOwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBkYXRhLnB0ciArPSB6ICogZGF0YVR5cGVTaXplOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZWxzZSB7IC8vMSBvciAzCiAgICAgICAgICAgICAgICAgIG9mZnNldFR5cGUgPSBMZXJjMkhlbHBlcnMuZ2V0RGF0YVR5cGVVc2VkKGltYWdlVHlwZSwgYml0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1dpZHRoOyBjb2wrKykgewogICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChtYXNrW291dFB0cl0pIHsKICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHJdID0gb2Zmc2V0OwogICAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgICAgICBvdXRQdHIrKzsKICAgICAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgICAgICBvdXRQdHIgKz0gb3V0U3RyaWRlOwogICAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICAgIGZvciAocm93ID0gMDsgcm93IDwgdGhpc0Jsb2NrSGVpZ2h0OyByb3crKykgewogICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGNvbCA9IDA7IGNvbCA8IHRoaXNCbG9ja1dpZHRoOyBjb2wrKykgewogICAgICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHIrK10gPSBvZmZzZXQ7CiAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7IC8vYml0c3R1ZmYgZW5jb2RpbmcgaXMgMwogICAgICAgICAgICAgICAgICAgIGRhdGEucHRyICs9IGJsb2NrUHRyOwogICAgICAgICAgICAgICAgICAgIC8vaGVhdnkgbGlmdGluZwogICAgICAgICAgICAgICAgICAgIExlcmMySGVscGVycy5kZWNvZGVCaXRzKGlucHV0LCBkYXRhLCBibG9ja0RhdGFCdWZmZXIsIG9mZnNldCwgaURpbSk7CiAgICAgICAgICAgICAgICAgICAgYmxvY2tQdHIgPSAwOwogICAgICAgICAgICAgICAgICAgIGlmIChtYXNrKSB7CiAgICAgICAgICAgICAgICAgICAgICBmb3IgKHJvdyA9IDA7IHJvdyA8IHRoaXNCbG9ja0hlaWdodDsgcm93KyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgZm9yIChjb2wgPSAwOyBjb2wgPCB0aGlzQmxvY2tXaWR0aDsgY29sKyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgICBpZiAobWFza1tvdXRQdHJdKSB7CiAgICAgICAgICAgICAgICAgICAgICAgICAgICByZXN1bHRQaXhlbHNbb3V0UHRyXSA9IGJsb2NrRGF0YUJ1ZmZlcltibG9ja1B0cisrXTsKICAgICAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICAgICAgb3V0UHRyKys7CiAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgICBmb3IgKHJvdyA9IDA7IHJvdyA8IHRoaXNCbG9ja0hlaWdodDsgcm93KyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgZm9yIChjb2wgPSAwOyBjb2wgPCB0aGlzQmxvY2tXaWR0aDsgY29sKyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgICByZXN1bHRQaXhlbHNbb3V0UHRyKytdID0gYmxvY2tEYXRhQnVmZmVyW2Jsb2NrUHRyKytdOwogICAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICAgIG91dFB0ciArPSBvdXRTdHJpZGU7CiAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgfSwKCiAgICAgICAgLyoqKioqKioqKioqKioqKioqCiAgICAgICAgKiAgcHJpdmF0ZSBtZXRob2RzIChoZWxwZXIgbWV0aG9kcykKICAgICAgICAqKioqKioqKioqKioqKioqKi8KCiAgICAgICAgZm9ybWF0RmlsZUluZm86IGZ1bmN0aW9uKGRhdGEpIHsKICAgICAgICAgIHJldHVybiB7CiAgICAgICAgICAgICJmaWxlSWRlbnRpZmllclN0cmluZyI6IGRhdGEuaGVhZGVySW5mby5maWxlSWRlbnRpZmllclN0cmluZywKICAgICAgICAgICAgImZpbGVWZXJzaW9uIjogZGF0YS5oZWFkZXJJbmZvLmZpbGVWZXJzaW9uLAogICAgICAgICAgICAiaW1hZ2VUeXBlIjogZGF0YS5oZWFkZXJJbmZvLmltYWdlVHlwZSwKICAgICAgICAgICAgImhlaWdodCI6IGRhdGEuaGVhZGVySW5mby5oZWlnaHQsCiAgICAgICAgICAgICJ3aWR0aCI6IGRhdGEuaGVhZGVySW5mby53aWR0aCwKICAgICAgICAgICAgIm51bVZhbGlkUGl4ZWwiOiBkYXRhLmhlYWRlckluZm8ubnVtVmFsaWRQaXhlbCwKICAgICAgICAgICAgIm1pY3JvQmxvY2tTaXplIjogZGF0YS5oZWFkZXJJbmZvLm1pY3JvQmxvY2tTaXplLAogICAgICAgICAgICAiYmxvYlNpemUiOiBkYXRhLmhlYWRlckluZm8uYmxvYlNpemUsCiAgICAgICAgICAgICJtYXhaRXJyb3IiOiBkYXRhLmhlYWRlckluZm8ubWF4WkVycm9yLAogICAgICAgICAgICAicGl4ZWxUeXBlIjogTGVyYzJIZWxwZXJzLmdldFBpeGVsVHlwZShkYXRhLmhlYWRlckluZm8uaW1hZ2VUeXBlKSwKICAgICAgICAgICAgImVvZk9mZnNldCI6IGRhdGEuZW9mT2Zmc2V0LAogICAgICAgICAgICAibWFzayI6IGRhdGEubWFzayA/IHsKICAgICAgICAgICAgICAibnVtQnl0ZXMiOiBkYXRhLm1hc2subnVtQnl0ZXMKICAgICAgICAgICAgfSA6IG51bGwsCiAgICAgICAgICAgICJwaXhlbHMiOiB7CiAgICAgICAgICAgICAgIm51bUJsb2Nrc1giOiBkYXRhLnBpeGVscy5udW1CbG9ja3NYLAogICAgICAgICAgICAgICJudW1CbG9ja3NZIjogZGF0YS5waXhlbHMubnVtQmxvY2tzWSwKICAgICAgICAgICAgICAvLyJudW1CeXRlcyI6IGRhdGEucGl4ZWxzLm51bUJ5dGVzLAogICAgICAgICAgICAgICJtYXhWYWx1ZSI6IGRhdGEuaGVhZGVySW5mby56TWF4LAogICAgICAgICAgICAgICJtaW5WYWx1ZSI6IGRhdGEuaGVhZGVySW5mby56TWluLAogICAgICAgICAgICAgICJub0RhdGFWYWx1ZSI6IGRhdGEubm9EYXRhVmFsdWUKICAgICAgICAgICAgfQogICAgICAgICAgfTsKICAgICAgICB9LAoKICAgICAgICBjb25zdHJ1Y3RDb25zdGFudFN1cmZhY2U6IGZ1bmN0aW9uKGRhdGEpIHsKICAgICAgICAgIHZhciB2YWwgPSBkYXRhLmhlYWRlckluZm8uek1heDsKICAgICAgICAgIHZhciBudW1EaW1zID0gIGRhdGEuaGVhZGVySW5mby5udW1EaW1zOwogICAgICAgICAgdmFyIG51bVBpeGVscyA9IGRhdGEuaGVhZGVySW5mby5oZWlnaHQgKiBkYXRhLmhlYWRlckluZm8ud2lkdGg7CiAgICAgICAgICB2YXIgbnVtUGl4ZWxBbGxEaW1zID0gbnVtUGl4ZWxzICogbnVtRGltczsKICAgICAgICAgIHZhciBpPTAsIGsgPSAwLCBuU3RhcnQ9MDsKICAgICAgICAgIHZhciBtYXNrID0gZGF0YS5waXhlbHMucmVzdWx0TWFzazsKICAgICAgICAgIGlmIChtYXNrKSB7CiAgICAgICAgICAgIGlmIChudW1EaW1zID4gMSkgewogICAgICAgICAgICAgIGZvciAoaT0wOyBpIDwgbnVtRGltczsgaSsrKSB7CiAgICAgICAgICAgICAgICBuU3RhcnQgPSBpICogbnVtUGl4ZWxzOwogICAgICAgICAgICAgICAgZm9yIChrID0gMDsgayA8IG51bVBpeGVsczsgaysrKSB7CiAgICAgICAgICAgICAgICAgIGlmIChtYXNrW2tdKSB7CiAgICAgICAgICAgICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0UGl4ZWxzW25TdGFydCArIGtdID0gdmFsOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIGZvciAoayA9IDA7IGsgPCBudW1QaXhlbHM7IGsrKykgewogICAgICAgICAgICAgICAgaWYgKG1hc2tba10pIHsKICAgICAgICAgICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0UGl4ZWxzW2tdID0gdmFsOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgIGlmIChkYXRhLnBpeGVscy5yZXN1bHRQaXhlbHMuZmlsbCkgewogICAgICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdFBpeGVscy5maWxsKHZhbCk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgZm9yIChrID0gMDsgayA8IG51bVBpeGVsQWxsRGltczsgaysrKSB7CiAgICAgICAgICAgICAgICBkYXRhLnBpeGVscy5yZXN1bHRQaXhlbHNba10gPSB2YWw7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm47CiAgICAgICAgfSwKCiAgICAgICAgZ2V0RGF0YVR5cGVBcnJheTogZnVuY3Rpb24odCkgewogICAgICAgICAgdmFyIHRwOwogICAgICAgICAgc3dpdGNoICh0KSB7CiAgICAgICAgICAgIGNhc2UgMDogLy9jaGFyCiAgICAgICAgICAgICAgdHAgPSBJbnQ4QXJyYXk7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlCiAgICAgICAgICAgICAgdHAgPSBVaW50OEFycmF5OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDI6IC8vc2hvcnQKICAgICAgICAgICAgICB0cCA9IEludDE2QXJyYXk7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMzogLy91c2hvcnQKICAgICAgICAgICAgICB0cCA9IFVpbnQxNkFycmF5OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDQ6CiAgICAgICAgICAgICAgdHAgPSBJbnQzMkFycmF5OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDU6CiAgICAgICAgICAgICAgdHAgPSBVaW50MzJBcnJheTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA2OgogICAgICAgICAgICAgIHRwID0gRmxvYXQzMkFycmF5OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDc6CiAgICAgICAgICAgICAgdHAgPSBGbG9hdDY0QXJyYXk7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgdHAgPSBGbG9hdDMyQXJyYXk7CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm4gdHA7CiAgICAgICAgfSwKCiAgICAgICAgZ2V0UGl4ZWxUeXBlOiBmdW5jdGlvbih0KSB7CiAgICAgICAgICB2YXIgdHA7CiAgICAgICAgICBzd2l0Y2ggKHQpIHsKICAgICAgICAgICAgY2FzZSAwOiAvL2NoYXIKICAgICAgICAgICAgICB0cCA9ICJTOCI7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlCiAgICAgICAgICAgICAgdHAgPSAiVTgiOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDI6IC8vc2hvcnQKICAgICAgICAgICAgICB0cCA9ICJTMTYiOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDM6IC8vdXNob3J0CiAgICAgICAgICAgICAgdHAgPSAiVTE2IjsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA0OgogICAgICAgICAgICAgIHRwID0gIlMzMiI7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNToKICAgICAgICAgICAgICB0cCA9ICJVMzIiOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDY6CiAgICAgICAgICAgICAgdHAgPSAiRjMyIjsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA3OgogICAgICAgICAgICAgIHRwID0gIkY2NCI7IC8vbm90IHN1cHBvcnRlZAogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgIHRwID0gIkYzMiI7CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm4gdHA7CiAgICAgICAgfSwKCiAgICAgICAgaXNWYWxpZFBpeGVsVmFsdWU6IGZ1bmN0aW9uKHQsIHZhbCkgewogICAgICAgICAgaWYgKHZhbCA9PSBudWxsKSB7CiAgICAgICAgICAgIHJldHVybiBmYWxzZTsKICAgICAgICAgIH0KICAgICAgICAgIHZhciBpc1ZhbGlkOwogICAgICAgICAgc3dpdGNoICh0KSB7CiAgICAgICAgICAgIGNhc2UgMDogLy9jaGFyCiAgICAgICAgICAgICAgaXNWYWxpZCA9IHZhbCA+PSAtMTI4ICYmIHZhbCA8PSAxMjc7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlICAodW5zaWduZWQgY2hhcikKICAgICAgICAgICAgICBpc1ZhbGlkID0gdmFsID49IDAgJiYgdmFsIDw9IDI1NTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAyOiAvL3Nob3J0CiAgICAgICAgICAgICAgaXNWYWxpZCA9IHZhbCA+PSAtMzI3NjggJiYgdmFsIDw9IDMyNzY3OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDM6IC8vdXNob3J0CiAgICAgICAgICAgICAgaXNWYWxpZCA9IHZhbCA+PSAwICYmIHZhbCA8PSA2NTUzNjsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA0OiAvL2ludCAzMgogICAgICAgICAgICAgIGlzVmFsaWQgPSB2YWwgPj0gLTIxNDc0ODM2NDggJiYgdmFsIDw9IDIxNDc0ODM2NDc7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNTogLy91aW5pdCAzMgogICAgICAgICAgICAgIGlzVmFsaWQgPSB2YWwgPj0gMCAmJiB2YWwgPD0gNDI5NDk2NzI5NjsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA2OgogICAgICAgICAgICAgIGlzVmFsaWQgPSB2YWwgPj0gLTMuNDAyNzk5OTM4NzkwMTQ4NGUrMzggJiYgdmFsIDw9IDMuNDAyNzk5OTM4NzkwMTQ4NGUrMzg7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNzoKICAgICAgICAgICAgICBpc1ZhbGlkID0gdmFsID49IDVlLTMyNCAmJiB2YWwgPD0gMS43OTc2OTMxMzQ4NjIzMTU3ZSszMDg7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgaXNWYWxpZCA9IGZhbHNlOwogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuIGlzVmFsaWQ7CiAgICAgICAgfSwKCiAgICAgICAgZ2V0RGF0YVR5cGVTaXplOiBmdW5jdGlvbih0KSB7CiAgICAgICAgICB2YXIgcyA9IDA7CiAgICAgICAgICBzd2l0Y2ggKHQpIHsKICAgICAgICAgICAgY2FzZSAwOiAvL3VieXRlCiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlCiAgICAgICAgICAgICAgcyA9IDE7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMjogLy9zaG9ydAogICAgICAgICAgICBjYXNlIDM6IC8vdXNob3J0CiAgICAgICAgICAgICAgcyA9IDI7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNDoKICAgICAgICAgICAgY2FzZSA1OgogICAgICAgICAgICBjYXNlIDY6CiAgICAgICAgICAgICAgcyA9IDQ7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNzoKICAgICAgICAgICAgICBzID0gODsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICBzID0gdDsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiBzOwogICAgICAgIH0sCgogICAgICAgIGdldERhdGFUeXBlVXNlZDogZnVuY3Rpb24oZHQsIHRjKSB7CiAgICAgICAgICB2YXIgdCA9IGR0OwogICAgICAgICAgc3dpdGNoIChkdCkgewogICAgICAgICAgICBjYXNlIDI6IC8vc2hvcnQKICAgICAgICAgICAgY2FzZSA0OiAvL2xvbmcKICAgICAgICAgICAgICB0ID0gZHQgLSB0YzsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAzOiAvL3VzaG9ydAogICAgICAgICAgICBjYXNlIDU6IC8vdWxvbmcKICAgICAgICAgICAgICB0ID0gZHQgLSAyICogdGM7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNjogLy9mbG9hdAogICAgICAgICAgICAgIGlmICgwID09PSB0YykgewogICAgICAgICAgICAgICAgdCA9IGR0OwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIGlmICgxID09PSB0YykgewogICAgICAgICAgICAgICAgdCA9IDI7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgdCA9IDE7Ly9ieXRlCiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDc6IC8vZG91YmxlCiAgICAgICAgICAgICAgaWYgKDAgPT09IHRjKSB7CiAgICAgICAgICAgICAgICB0ID0gZHQ7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgdCA9IGR0IC0gMiAqIHRjICsgMTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgdCA9IGR0OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuIHQ7CiAgICAgICAgfSwKCiAgICAgICAgZ2V0T25lUGl4ZWw6IGZ1bmN0aW9uKGJsb2NrLCBibG9ja1B0ciwgb2Zmc2V0VHlwZSwgdmlldykgewogICAgICAgICAgdmFyIHRlbXAgPSAwOwogICAgICAgICAgc3dpdGNoIChvZmZzZXRUeXBlKSB7CiAgICAgICAgICAgIGNhc2UgMDogLy9jaGFyCiAgICAgICAgICAgICAgdGVtcCA9IHZpZXcuZ2V0SW50OChibG9ja1B0cik7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlCiAgICAgICAgICAgICAgdGVtcCA9IHZpZXcuZ2V0VWludDgoYmxvY2tQdHIpOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDI6CiAgICAgICAgICAgICAgdGVtcCA9IHZpZXcuZ2V0SW50MTYoYmxvY2tQdHIsIHRydWUpOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDM6CiAgICAgICAgICAgICAgdGVtcCA9IHZpZXcuZ2V0VWludDE2KGJsb2NrUHRyLCB0cnVlKTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA0OgogICAgICAgICAgICAgIHRlbXAgPSB2aWV3LmdldEludDMyKGJsb2NrUHRyLCB0cnVlKTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA1OgogICAgICAgICAgICAgIHRlbXAgPSB2aWV3LmdldFVJbnQzMihibG9ja1B0ciwgdHJ1ZSk7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNjoKICAgICAgICAgICAgICB0ZW1wID0gdmlldy5nZXRGbG9hdDMyKGJsb2NrUHRyLCB0cnVlKTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA3OgogICAgICAgICAgICAgIC8vdGVtcCA9IHZpZXcuZ2V0RmxvYXQ2NChibG9ja1B0ciwgdHJ1ZSk7CiAgICAgICAgICAgICAgLy9ibG9ja1B0ciArPSA4OwogICAgICAgICAgICAgIC8vbGVyYzIgZW5jb2RpbmcgZG9lc250IGhhbmRsZSBmbG9hdCA2NCwgZm9yY2UgdG8gZmxvYXQzMj8/PwogICAgICAgICAgICAgIHRlbXAgPSB2aWV3LmdldEZsb2F0NjQoYmxvY2tQdHIsIHRydWUpOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgIHRocm93ICgidGhlIGRlY29kZXIgZG9lcyBub3QgdW5kZXJzdGFuZCB0aGlzIHBpeGVsIHR5cGUiKTsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiB0ZW1wOwogICAgICAgIH0KICAgICAgfTsKCiAgICAgIC8qKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioKICAgICAgKnByaXZhdGUgY2xhc3MgZm9yIGEgdHJlZSBub2RlLiBIdWZmbWFuIGNvZGUgaXMgaW4gTGVyYzJIZWxwZXJzCiAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgIHZhci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VlID0gb3B0aW9ucy5ub0RhdGFWYWx1ZTsKCiAgICAgICAgICAvL2luaXRpYWxpemUKICAgICAgICAgIHZhciBpID0gMCwgZGF0YSA9IHt9OwogICAgICAgICAgZGF0YS5wdHIgPSBvcHRpb25zLmlucHV0T2Zmc2V0IHx8IDA7CiAgICAgICAgICBkYXRhLnBpeGVscyA9IHt9OwoKICAgICAgICAgIC8vIEZpbGUgaGVhZGVyCiAgICAgICAgICBpZiAoIUxlcmMySGVscGVycy5yZWFkSGVhZGVySW5mbyhpbnB1dCwgZGF0YSkpIDsKICAgICAgICAgIHZhciBoZWFkZXJJbmZvID0gZGF0YS5oZWFkZXJJbmZvOwogICAgICAgICAgdmFyIGZpbGVWZXJzaW9uID0gaGVhZGVySW5mby5maWxlVmVyc2lvbjsKICAgICAgICAgIHZhciBPdXRQaXhlbFR5cGVBcnJheSA9IExlcmMySGVscGVycy5nZXREYXRhVHlwZUFycmF5KGhlYWRlckluZm8uaW1hZ2VUeXBlKTsKCiAgICAgICAgICAvLyBNYXNrIEhlYWRlcgogICAgICAgICAgTGVyYzJIZWxwZXJzLnJlYWRNYXNrKGlucHV0LCBkYXRhKTsKICAgICAgICAgIGlmIChoZWFkZXJJbmZvLm51bVZhbGlkUGl4ZWwgIT09IGhlYWRlckluZm8ud2lkdGggKiBoZWFkZXJJbmZvLmhlaWdodCAmJiAhZGF0YS5waXhlbHMucmVzdWx0TWFzaykgewogICAgICAgICAgICBkYXRhLnBpeGVscy5yZXN1bHRNYXNrID0gb3B0aW9ucy5tYXNrRGF0YTsKICAgICAgICAgIH0KCiAgICAgICAgICB2YXIgbnVtUGl4ZWxzID0gaGVhZGVySW5mby53aWR0aCAqIGhlYWRlckluZm8uaGVpZ2h0OwogICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0UGl4ZWxzID0gbmV3IE91dFBpeGVsVHlwZUFycmF5KG51bVBpeGVscyAqIGhlYWRlckluZm8ubnVtRGltcyk7CgogICAgICAgICAgZGF0YS5jb3VudGVyID0gewogICAgICAgICAgICBvbmVzd2VlcDogMCwKICAgICAgICAgICAgdW5jb21wcmVzc2VkOiAwLAogICAgICAgICAgICBsdXQ6IDAsCiAgICAgICAgICAgIGJpdHN0dWZmZXI6IDAsCiAgICAgICAgICAgIGNvbnN0YW50OiAwLAogICAgICAgICAgICBjb25zdGFudG9mZnNldDogMAogICAgICAgICAgfTsKICAgICAgICAgIGlmIChoZWFkZXJJbmZvLm51bVZhbGlkUGl4ZWwgIT09IDApIHsKICAgICAgICAgICAgLy9ub3QgdGVzdGVkCiAgICAgICAgICAgIGlmIChoZWFkZXJJbmZvLnpNYXggPT09IGhlYWRlckluZm8uek1pbikgLy9jb25zdGFudCBzdXJmYWNlCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICBMZXJjMkhlbHBlcnMuY29uc3RydWN0Q29uc3RhbnRTdXJmYWNlKGRhdGEpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgaWYgKGZpbGVWZXJzaW9uID49IDQgJiYgTGVyYzJIZWxwZXJzLmNoZWNrTWluTWF4UmFuZ2VzKGlucHV0LCBkYXRhKSkgewogICAgICAgICAgICAgIExlcmMySGVscGVycy5jb25zdHJ1Y3RDb25zdGFudFN1cmZhY2UoZGF0YSk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgdmFyIHZpZXcgPSBuZXcgRGF0YVZpZXcoaW5wdXQsIGRhdGEucHRyLCAyKTsKICAgICAgICAgICAgICB2YXIgYlJlYWREYXRhT25lU3dlZXAgPSB2aWV3LmdldFVpbnQ4KDApOwogICAgICAgICAgICAgIGRhdGEucHRyKys7CiAgICAgICAgICAgICAgaWYgKGJSZWFkRGF0YU9uZVN3ZWVwKSB7CiAgICAgICAgICAgICAgICAvL2NvbnNvbGUuZGVidWcoIk9uZVN3ZWVwIik7CiAgICAgICAgICAgICAgICBMZXJjMkhlbHBlcnMucmVhZERhdGFPbmVTd2VlcChpbnB1dCwgZGF0YSwgT3V0UGl4ZWxUeXBlQXJyYXkpOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIC8vbGVyYzIuMTogLy9iaXRzdHVmZmluZyArIGx1dAogICAgICAgICAgICAgICAgLy9sZXJjMi4yOiAvL2JpdHN0dWZmaW5nICsgbHV0ICsgaHVmZm1hbgogICAgICAgICAgICAgICAgLy9sZXJjMi4zOiBuZXcgYml0c3R1ZmZlcgogICAgICAgICAgICAgICAgaWYgKGZpbGVWZXJzaW9uID4gMSAmJiBoZWFkZXJJbmZvLmltYWdlVHlwZSA8PSAxICYmIE1hdGguYWJzKGhlYWRlckluZm8ubWF4WkVycm9yIC0gMC41KSA8IDAuMDAwMDEpIHsKICAgICAgICAgICAgICAgICAgLy90aGlzIGlzIDIueCBwbHVzIDggYml0ICh1bnNpZ25lZCBhbmQgc2lnbmVkKSBkYXRhLCBwb3NzaWJsaXR5IG9mIEh1ZmZtYW4KICAgICAgICAgICAgICAgICAgdmFyIGZsYWdIdWZmbWFuID0gdmlldy5nZXRVaW50OCgxKTsKICAgICAgICAgICAgICAgICAgZGF0YS5wdHIrKzsKICAgICAgICAgICAgICAgICAgZGF0YS5lbmNvZGVNb2RlID0gZmxhZ0h1ZmZtYW47CiAgICAgICAgICAgICAgICAgIGlmIChmbGFnSHVmZm1hbiA+IDIgfHwgKGZpbGVWZXJzaW9uIDwgNCAmJiBmbGFnSHVmZm1hbiA+IDEpKSB7CiAgICAgICAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgSHVmZm1hbiBmbGFnICIgKyBmbGFnSHVmZm1hbjsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBpZiAoZmxhZ0h1ZmZtYW4pIHsvLzEgLSBkZWx0YSBIdWZmbWFuLCAyIC0gSHVmZm1hbgogICAgICAgICAgICAgICAgICAgIC8vY29uc29sZS5sb2coIkh1ZmZtYW4iKTsKICAgICAgICAgICAgICAgICAgICBMZXJjMkhlbHBlcnMucmVhZEh1ZmZtYW4oaW5wdXQsIGRhdGEsIE91dFBpeGVsVHlwZUFycmF5KTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICAvL2NvbnNvbGUubG9nKCJUaWxlcyIpOwogICAgICAgICAgICAgICAgICAgIExlcmMySGVscGVycy5yZWFkVGlsZXMoaW5wdXQsIGRhdGEsIE91dFBpeGVsVHlwZUFycmF5KTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZWxzZSB7IC8vbGVyYzIueCBub24tOCBiaXQgZGF0YQogICAgICAgICAgICAgICAgICAvL2NvbnNvbGUubG9nKCJUaWxlcyIpOwogICAgICAgICAgICAgICAgICBMZXJjMkhlbHBlcnMucmVhZFRpbGVzKGlucHV0LCBkYXRhLCBPdXRQaXhlbFR5cGVBcnJheSk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CgogICAgICAgICAgZGF0YS5lb2ZPZmZzZXQgPSBkYXRhLnB0cjsKICAgICAgICAgIHZhciBkaWZmOwogICAgICAgICAgaWYgKG9wdGlvbnMuaW5wdXRPZmZzZXQpIHsKICAgICAgICAgICAgZGlmZiA9IGRhdGEuaGVhZGVySW5mby5ibG9iU2l6ZSArIG9wdGlvbnMuaW5wdXRPZmZzZXQgLSBkYXRhLnB0cjsKICAgICAgICAgICAgaWYgKE1hdGguYWJzKGRpZmYpID49IDEpIHsKICAgICAgICAgICAgICAvL2NvbnNvbGUuZGVidWcoImluY29ycmVjdCBlb2Y6IGRhdGFwdHIgIiArIGRhdGEucHRyICsgIiBvZmZzZXQgIiArIG9wdGlvbnMuaW5wdXRPZmZzZXQgKyAiIGJsb2JzaXplICIgKyBkYXRhLmhlYWRlckluZm8uYmxvYlNpemUgKyAiIGRpZmY6ICIgKyBkaWZmKTsKICAgICAgICAgICAgICBkYXRhLmVvZk9mZnNldCA9IG9wdGlvbnMuaW5wdXRPZmZzZXQgKyBkYXRhLmhlYWRlckluZm8uYmxvYlNpemU7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgewogICAgICAgICAgICBkaWZmID0gZGF0YS5oZWFkZXJJbmZvLmJsb2JTaXplIC0gZGF0YS5wdHI7CiAgICAgICAgICAgIGlmIChNYXRoLmFicyhkaWZmKSA+PSAxKSB7CiAgICAgICAgICAgICAgLy9jb25zb2xlLmRlYnVnKCJpbmNvcnJlY3QgZmlyc3QgYmFuZCBlb2Y6IGRhdGFwdHIgIiArIGRhdGEucHRyICsgIiBibG9ic2l6ZSAiICsgZGF0YS5oZWFkZXJJbmZvLmJsb2JTaXplICsgIiBkaWZmOiAiICsgZGlmZik7CiAgICAgICAgICAgICAgZGF0YS5lb2ZPZmZzZXQgPSBkYXRhLmhlYWRlckluZm8uYmxvYlNpemU7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KCiAgICAgICAgICB2YXIgcmVzdWx0ID0gewogICAgICAgICAgICB3aWR0aDogaGVhZGVySW5mby53aWR0aCwKICAgICAgICAgICAgaGVpZ2h0OiBoZWFkZXJJbmZvLmhlaWdodCwKICAgICAgICAgICAgcGl4ZWxEYXRhOiBkYXRhLnBpeGVscy5yZXN1bHRQaXhlbHMsCiAgICAgICAgICAgIG1pblZhbHVlOiBoZWFkZXJJbmZvLnpNaW4sCiAgICAgICAgICAgIG1heFZhbHVlOiBoZWFkZXJJbmZvLnpNYXgsCiAgICAgICAgICAgIHZhbGlkUGl4ZWxDb3VudDogaGVhZGVySW5mby5udW1WYWxpZFBpeGVsLAogICAgICAgICAgICBkaW1Db3VudDogaGVhZGVySW5mby5udW1EaW1zLAogICAgICAgICAgICBkaW1TdGF0czogewogICAgICAgICAgICAgIG1pblZhbHVlczogaGVhZGVySW5mby5taW5WYWx1ZXMsCiAgICAgICAgICAgICAgbWF4VmFsdWVzOiBoZWFkZXJJbmZvLm1heFZhbHVlcwogICAgICAgICAgICB9LAogICAgICAgICAgICBtYXNrRGF0YTogZGF0YS5waXhlbHMucmVzdWx0TWFzawogICAgICAgICAgICAvL25vRGF0YVZhbHVlOiBub0RhdGFWYWx1ZQogICAgICAgICAgfTsKCiAgICAgICAgICAvL3dlIHNob3VsZCByZW1vdmUgdGhpcyBpZiB0aGVyZSdzIG5vIGV4aXN0aW5nIGNsaWVudAogICAgICAgICAgLy9vcHRpb25hbCBub0RhdGFWYWx1ZSBwcm9jZXNzaW5nLCBpdCdzIHVzZXIncyByZXNwb25zaWJsaXR5CiAgICAgICAgICBpZiAoZGF0YS5waXhlbHMucmVzdWx0TWFzayAmJiBMZXJjMkhlbHBlcnMuaXNWYWxpZFBpeGVsVmFsdWUoaGVhZGVySW5mby5pbWFnZVR5cGUsIG5vRGF0YVZhbHVlKSkgewogICAgICAgICAgICB2YXIgbWFzayA9IGRhdGEucGl4ZWxzLnJlc3VsdE1hc2s7CiAgICAgICAgICAgIGZvciAoaSA9IDA7IGkgPCBudW1QaXhlbHM7IGkrKykgewogICAgICAgICAgICAgIGlmICghbWFza1tpXSkgewogICAgICAgICAgICAgICAgcmVzdWx0LnBpeGVsRGF0YVtpXSA9IG5vRGF0YVZhbHVlOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICByZXN1bHQubm9EYXRhVmFsdWUgPSBub0RhdGFWYWx1ZTsKICAgICAgICAgIH0KICAgICAgICAgIGRhdGEubm9EYXRhVmFsdWUgPSBub0RhdGFWYWx1ZTsKICAgICAgICAgIGlmIChvcHRpb25zLnJldHVybkZpbGVJbmZvKSB7CiAgICAgICAgICAgIHJlc3VsdC5maWxlSW5mbyA9IExlcmMySGVscGVycy5mb3JtYXRGaWxlSW5mbyhkYXRhKTsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiByZXN1bHQ7CiAgICAgICAgfSwKCiAgICAgICAgZ2V0QmFuZENvdW50OiBmdW5jdGlvbigvKmJ5dGUgYXJyYXkqLyBpbnB1dCkgewogICAgICAgICAgdmFyIGNvdW50ID0gMDsKICAgICAgICAgIHZhciBpID0gMDsKICAgICAgICAgIHZhciB0ZW1wID0ge307CiAgICAgICAgICB0ZW1wLnB0ciA9IDA7CiAgICAgICAgICB0ZW1wLnBpeGVscyA9IHt9OwogICAgICAgICAgd2hpbGUgKGkgPCBpbnB1dC5ieXRlTGVuZ3RoIC0gNTgpIHsKICAgICAgICAgICAgTGVyYzJIZWxwZXJzLnJlYWRIZWFkZXJJbmZvKGlucHV0LCB0ZW1wKTsKICAgICAgICAgICAgaSArPSB0ZW1wLmhlYWRlckluZm8uYmxvYlNpemU7CiAgICAgICAgICAgIGNvdW50Kys7CiAgICAgICAgICAgIHRlbXAucHRyID0gaTsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiBjb3VudDsKICAgICAgICB9CiAgICAgIH07CgogICAgICByZXR1cm4gTGVyYzJEZWNvZGU7CiAgICB9KSgpOwoKICAgIHZhciBpc1BsYXRmb3JtTGl0dGxlRW5kaWFuID0gKGZ1bmN0aW9uKCkgewogICAgICB2YXIgYSA9IG5ldyBBcnJheUJ1ZmZlcig0KTsKICAgICAgdmFyIGIgPSBuZXcgVWludDhBcnJheShhKTsKICAgICAgdmFyIGMgPSBuZXcgVWludDMyQXJyYXkoYSk7CiAgICAgIGNbMF0gPSAxOwogICAgICByZXR1cm4gYlswXSA9PT0gMTsKICAgIH0pKCk7CgogICAgdmFyIExlcmMgPSB7CiAgICAgIC8qKioqKioqKioqKip3cmFwcGVyKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKi8KICAgICAgLyoqCiAgICAgICAqIEEgd3JhcHBlciBmb3IgZGVjb2RpbmcgYm90aCBMRVJDMSBhbmQgTEVSQzIgYnl0ZSBzdHJlYW1zIGNhcGFibGUgb2YgaGFuZGxpbmcgbXVsdGliYW5kIHBpeGVsIGJsb2NrcyBmb3IgdmFyaW91cyBwaXhlbCB0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kZWRQaXhlbEJsb2NrLmJhbmRNYXNrcyA9IGJhbmRNYXNrczsKICAgICAgICAgIG1hc2tEYXRhID0gbmV3IFVpbnQ4QXJyYXkobnVtUGl4ZWxzKTsKICAgICAgICAgIG1hc2tEYXRhLnNldChiYW5kTWFza3NbMF0pOwogICAgICAgICAgZm9yIChpID0gMTsgaSA8IGJhbmRNYXNrcy5sZW5ndGg7IGkrKykgewogICAgICAgICAgICBiYW5kTWFzayA9IGJhbmRNYXNrc1tpXTsKICAgICAgICAgICAgZm9yIChqID0gMDsgaiA8IG51bVBpeGVsczsgaisrKSB7CiAgICAgICAgICAgICAgbWFza0RhdGFbal0gPSBtYXNrRGF0YVtqXSAmIGJhbmRNYXNrW2pdOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICBkZWNvZGVkUGl4ZWxCbG9jay5tYXNrRGF0YSA9IG1hc2tEYXRhOwogICAgICAgIH0KCiAgICAgICAgcmV0dXJuIGRlY29kZWRQaXhlbEJsb2NrOwogICAgICB9CiAgICB9OwoKICAgIGlmIChtb2R1bGUuZXhwb3J0cykgey8qIGpzaGludCBpZ25vcmU6bGluZSAqLwogICAgICAvL2NvbW1vbkpTIG1vZHVsZSAxLjAvMS4xLzEuMS4xIHN5c3RlbXMsIHN1Y2ggYXMgbm9kZUpTCiAgICAgIC8vaHR0cDovL3dpa2kuY29tbW9uanMub3JnL3dpa2kvTW9kdWxlcwogICAgICBtb2R1bGUuZXhwb3J0cyA9IExlcmM7LyoganNoaW50IGlnbm9yZTpsaW5lICovCiAgICB9CiAgICBlbHNlIHsKICAgICAgLy9hc3NpZ24gdG8gdGhpcywgbW9zdCBsaWtlbHkgd2luZG93CiAgICAgIHRoaXMuTGVyYyA9IExlcmM7CiAgICB9CgogIH0pKCk7CiAgfShMZXJjRGVjb2RlKSk7CgogIHZhciBMZXJjID0gTGVyY0RlY29kZS5leHBvcnRzOwoKICBjb25zdCBmaWVsZFRhZ05hbWVzID0gewogICAgLy8gVElGRi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IG5ldyBEZWZsYXRlRGVjb2RlcigpOwogICAgICBjYXNlIDMyNzczOiAvLyBwYWNrYml0cwogICAgICAgIHJldHVybiBuZXcgUGFja2JpdHNEZWNvZGVyKCk7CiAgICAgIGNhc2UgMzQ4ODc6IC8vIExFUkMKICAgICAgICByZXR1cm4gbmV3IExlcmNEZWNvZGVyKGZpbGVEaXJlY3RvcnkpOwogICAgICBkZWZhdWx0OgogICAgICAgIHRocm93IG5ldyBFcnJvcihgVW5rbm93biBjb21wcmVzc2lvbiBtZXRob2QgaWRlbnRpZmllcjogJHtmaWxlRGlyZWN0b3J5LkNvbXByZXNzaW9ufWApOwogICAgfQogIH0KCiAgYXN5bmMgZnVuY3Rpb24gZGVjb2RlKGZpbGVEaXJlY3RvcnksIGJ1ZmZlcikgewogICAgY29uc3QgZGVjb2RlciA9IGdldERlY29kZXIoZmlsZURpcmVjdG9yeSk7CiAgICBjb25zdCByZXN1bHQgPSBhd2FpdCBkZWNvZGVyLmRlY29kZShmaWxlRGlyZWN0b3J5LCBidWZmZXIpOwogICAgc2VsZi5wb3N0TWVzc2FnZShyZXN1bHQsIFtyZXN1bHRdKTsKICB9CiAgaWYgKHR5cGVvZiBzZWxmICE9PSAidW5kZWZpbmVkIikgewogICAgc2VsZi5hZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIiwgKGV2ZW50KSA9PiB7CiAgICAgIGNvbnN0IFtuYW1lLCAuLi5hcmdzXSA9IGV2ZW50LmRhdGE7CiAgICAgIHN3aXRjaCAobmFtZSkgewogICAgICAgIGNhc2UgImRlY29kZSI6CiAgICAgICAgICBkZWNvZGUoYXJnc1swXSwgYXJnc1sxXSk7CiAgICAgICAgICBicmVhazsKICAgICAgfQogICAgfSk7CiAgfQoKfSkoKTsK",Uo="undefined"!==typeof window&&window.Blob&&new Blob([atob(No)],{type:"text/javascript;charset=utf-8"});function _o(){var e=Uo&&(window.URL||window.webkitURL).createObjectURL(Uo);try{return e?new Worker(e):new Worker("data:application/javascript;base64,"+No,{type:"module"})}finally{e&&(window.URL||window.webkitURL).revokeObjectURL(e)}}var Mo=null!==(Ci=null===globalThis||void 0===globalThis||null===(hi=globalThis.navigator)||void 0===hi?void 0:hi.hardwareConcurrency)&&void 0!==Ci?Ci:4,Oo=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Mo;Object(u.a)(this,e),Object(g.a)(this,"workers",void 0),Object(g.a)(this,"idleWorkers",void 0),Object(g.a)(this,"waitQueue",void 0),Object(g.a)(this,"decoder",void 0),this.workers=[],this.idleWorkers=[],this.waitQueue=[],this.decoder=null;for(var A=0;A>e,A[n("y")]=t.SizeY>>e,A};if(!(t.Type in jo))throw Error("Pixel type ".concat(t.Type," not supported."));var o=jo[t.Type];if(t.PhysicalSizeX&&t.PhysicalSizeY){var a={x:{size:t.PhysicalSizeX,unit:t.PhysicalSizeXUnit},y:{size:t.PhysicalSizeY,unit:t.PhysicalSizeYUnit}};return t.PhysicalSizeZ&&(a.z={size:t.PhysicalSizeZ,unit:t.PhysicalSizeZUnit}),{labels:A,getShape:i,physicalSizes:a,dtype:o}}return{labels:A,getShape:i,dtype:o}}function Vo(e){var t=e.getTileWidth(),A=e.getTileHeight();return Pi(Math.min(t,A))}function Ko(e,t){return Wo.apply(this,arguments)}function Wo(){return(Wo=Object(a.a)(o.a.mark((function e(t,A){var n,r,i,a,s,g,c,u,l,I,C,h,f,d,B,p,E;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.getImage(0);case 2:return n=e.sent,r=n.fileDirectory,i=r.ImageDescription,a=r.SubIFDs,s=r.PhotometricInterpretation,g=To(i),a?(c=a.length+1,u=Yo(t,g)):(c=g.length,u=Ho(t,g)),l=g[0],I=Po(l),C=I.labels,h=I.getShape,f=I.physicalSizes,d=I.dtype,B=Vo(n),p={photometricInterpretation:s,physicalSizes:f},E=Array.from({length:c}).map((function(e,t){var n=h(t);return new Zo((function(e){return u(e,t)}),d,B,n,C,p,A)})),e.abrupt("return",{data:E,metadata:l});case 12:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Xo(e){return qo.apply(this,arguments)}function qo(){return(qo=Object(a.a)(o.a.mark((function e(t){var A,n,r,i,a,s,g=arguments;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(A=g.length>1&&void 0!==g[1]?g[1]:{},n=A.headers,r=A.offsets,i=A.pool,a=void 0===i||i,"string"!==typeof t){e.next=8;break}return e.next=5,si(t,Object(d.a)({},n,{cacheSize:1/0}));case 5:s=e.sent,e.next=11;break;case 8:return e.next=10,ci(t);case 10:s=e.sent;case 11:return r&&(s=xo(s,r)),ko(s),e.abrupt("return",a?Ko(s,new Oo):Ko(s));case 14:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function zo(e){return $o.apply(this,arguments)}function $o(){return($o=Object(a.a)(o.a.mark((function e(t){var A,n,r,i,a,s,g,c,u,l=arguments;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=l.length>1&&void 0!==l[1]?l[1]:"",e.next=3,Object(Bi.e)(t,A);case 3:return n=e.sent,e.next=6,n.attrs.asObject();case 6:return r=e.sent,i=["0"],a=["t","c","z","y","x"],"multiscales"in r&&(s=r.multiscales[0],g=s.datasets,c=s.axes,i=g.map((function(e){return e.path})),c&&(a=c)),u=i.map((function(e){return n.getItem(e)})),e.next=13,Promise.all(u);case 13:return e.t0=e.sent,e.t1=r,e.t2=a,e.abrupt("return",{data:e.t0,rootAttrs:e.t1,labels:e.t2});case 17:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ea(e){var t=Hi(e.shape),A=e.chunks.slice(t?-3:-2),n=Object(s.a)(A,2),r=n[0],i=n[1];return Pi(Math.min(r,i))}var ta={u1:"Uint8",u2:"Uint16",u4:"Uint32",f4:"Float32",f8:"Float64",i1:"Int8",i2:"Int16",i4:"Int32"},Aa=function(){function e(t,A,n){Object(u.a)(this,e),Object(g.a)(this,"_data",void 0),Object(g.a)(this,"_indexer",void 0),Object(g.a)(this,"_readChunks",void 0),this.labels=A,this.tileSize=n,this._indexer=function(e){var t=e.length,A=Ji(e);return function(e){if(Array.isArray(e))return Object(B.a)(e);for(var n=Array(t).fill(0),r=0,i=Object.entries(e);r1&&void 0!==r[1]?r[1]:{},n=new Bi.b(t,A),"multiscales"===(null===A||void 0===A?void 0:A.type)){e.next=4;break}throw Error("Only multiscale OME-Zarr is supported.");case 4:return e.abrupt("return",na(n));case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}},function(e,t,A){"use strict";var n=A(16),r=A(271);var i=A(91);function o(e){var t="function"===typeof Map?new Map:void 0;return(o=function(e){if(null===e||(A=e,-1===Function.toString.call(A).indexOf("[native code]")))return e;var A;if("function"!==typeof e)throw new TypeError("Super expression must either be null or a function");if("undefined"!==typeof t){if(t.has(e))return t.get(e);t.set(e,o)}function o(){return Object(i.a)(e,arguments,Object(n.a)(this).constructor)}return o.prototype=Object.create(e.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Object(r.a)(o,e)})(e)}A.d(t,"a",(function(){return o}))},function(e,t,A){"use strict";A.d(t,"f",(function(){return i})),A.d(t,"g",(function(){return o})),A.d(t,"d",(function(){return a})),A.d(t,"a",(function(){return s})),A.d(t,"e",(function(){return g})),A.d(t,"i",(function(){return c})),A.d(t,"b",(function(){return u})),A.d(t,"c",(function(){return l})),A.d(t,"h",(function(){return I}));var n=function(e){return"boolean"===typeof e},r=function(e){return"function"===typeof e},i=function(e){return null!==e&&"object"===typeof e},o=function(e){return i(e)&&e.constructor==={}.constructor},a=function(e){return e&&"function"===typeof e[Symbol.iterator]},s=function(e){return e&&"function"===typeof e[Symbol.asyncIterator]},g=function(e){return e&&r(e.next)},c=function(e){return"undefined"!==typeof Response&&e instanceof Response||e&&e.arrayBuffer&&e.text&&e.json},u=function(e){return"undefined"!==typeof Blob&&e instanceof Blob},l=function(e){return e&&"object"===typeof e&&e.isBuffer},I=function(e){return function(e){return"undefined"!==typeof ReadableStream&&e instanceof ReadableStream||i(e)&&r(e.tee)&&r(e.cancel)&&r(e.getReader)}(e)||function(e){return i(e)&&r(e.read)&&r(e.pipe)&&n(e.readable)}(e)}},function(e,t,A){"use strict";A.d(t,"b",(function(){return r})),A.d(t,"g",(function(){return i})),A.d(t,"c",(function(){return o})),A.d(t,"l",(function(){return a})),A.d(t,"a",(function(){return s})),A.d(t,"k",(function(){return g})),A.d(t,"h",(function(){return c})),A.d(t,"m",(function(){return u})),A.d(t,"j",(function(){return l})),A.d(t,"d",(function(){return I})),A.d(t,"i",(function(){return C})),A.d(t,"n",(function(){return h})),A.d(t,"o",(function(){return f})),A.d(t,"f",(function(){return d})),A.d(t,"e",(function(){return B}));var n=A(31);function r(e){var t=new n.a(4);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}function i(e,t,A,r){var i=new n.a(4);return i[0]=e,i[1]=t,i[2]=A,i[3]=r,i}function o(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}function a(e,t,A,n,r){return e[0]=t,e[1]=A,e[2]=n,e[3]=r,e}function s(e,t,A){return e[0]=t[0]+A[0],e[1]=t[1]+A[1],e[2]=t[2]+A[2],e[3]=t[3]+A[3],e}function g(e,t,A){return e[0]=t[0]*A,e[1]=t[1]*A,e[2]=t[2]*A,e[3]=t[3]*A,e}function c(e){var t=e[0],A=e[1],n=e[2],r=e[3];return Math.hypot(t,A,n,r)}function u(e){var t=e[0],A=e[1],n=e[2],r=e[3];return t*t+A*A+n*n+r*r}function l(e,t){var A=t[0],n=t[1],r=t[2],i=t[3],o=A*A+n*n+r*r+i*i;return o>0&&(o=1/Math.sqrt(o)),e[0]=A*o,e[1]=n*o,e[2]=r*o,e[3]=i*o,e}function I(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}function C(e,t,A,n){var r=t[0],i=t[1],o=t[2],a=t[3];return e[0]=r+n*(A[0]-r),e[1]=i+n*(A[1]-i),e[2]=o+n*(A[2]-o),e[3]=a+n*(A[3]-a),e}function h(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3];return e[0]=A[0]*n+A[4]*r+A[8]*i+A[12]*o,e[1]=A[1]*n+A[5]*r+A[9]*i+A[13]*o,e[2]=A[2]*n+A[6]*r+A[10]*i+A[14]*o,e[3]=A[3]*n+A[7]*r+A[11]*i+A[15]*o,e}function f(e,t,A){var n=t[0],r=t[1],i=t[2],o=A[0],a=A[1],s=A[2],g=A[3],c=g*n+a*i-s*r,u=g*r+s*n-o*i,l=g*i+o*r-a*n,I=-o*n-a*r-s*i;return e[0]=c*g+I*-o+u*-s-l*-a,e[1]=u*g+I*-a+l*-o-c*-s,e[2]=l*g+I*-s+c*-a-u*-o,e[3]=t[3],e}function d(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]}function B(e,t){var A=e[0],r=e[1],i=e[2],o=e[3],a=t[0],s=t[1],g=t[2],c=t[3];return Math.abs(A-a)<=n.b*Math.max(1,Math.abs(A),Math.abs(a))&&Math.abs(r-s)<=n.b*Math.max(1,Math.abs(r),Math.abs(s))&&Math.abs(i-g)<=n.b*Math.max(1,Math.abs(i),Math.abs(g))&&Math.abs(o-c)<=n.b*Math.max(1,Math.abs(o),Math.abs(c))}!function(){var e=function(){var e=new n.a(4);return n.a!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0,e[3]=0),e}()}()},function(e,t,A){"use strict";A.d(t,"c",(function(){return u})),A.d(t,"d",(function(){return l})),A.d(t,"e",(function(){return I})),A.d(t,"f",(function(){return C})),A.d(t,"g",(function(){return h})),A.d(t,"h",(function(){return f})),A.d(t,"i",(function(){return B})),A.d(t,"a",(function(){return p})),A.d(t,"b",(function(){return E}));var n=A(3),r=A.n(n),i=A(1),o=A(24),a=A(9),s=A(10),g=A(54),c=A(12);function u(e,t){for(var A in t)t.hasOwnProperty(A)&&(e[A]=t[A])}function l(e,t){return!(e.length=0))throw new Error("precision must be a positive number");var A=Math.pow(10,t||0);return Math.round(e*A)/A},t.radiansToLength=u,t.lengthToRadians=l,t.lengthToDegrees=function(e,t){return I(l(e,t))},t.bearingToAzimuth=function(e){var t=e%360;return t<0&&(t+=360),t},t.radiansToDegrees=I,t.degreesToRadians=function(e){return e%360*Math.PI/180},t.convertLength=function(e,t,A){if(void 0===t&&(t="kilometers"),void 0===A&&(A="kilometers"),!(e>=0))throw new Error("length must be a positive number");return u(l(e,t),A)},t.convertArea=function(e,A,n){if(void 0===A&&(A="meters"),void 0===n&&(n="kilometers"),!(e>=0))throw new Error("area must be a positive number");var r=t.areaFactors[A];if(!r)throw new Error("invalid original units");var i=t.areaFactors[n];if(!i)throw new Error("invalid final units");return e/r*i},t.isNumber=C,t.isObject=function(e){return!!e&&e.constructor===Object},t.validateBBox=function(e){if(!e)throw new Error("bbox is required");if(!Array.isArray(e))throw new Error("bbox must be an Array");if(4!==e.length&&6!==e.length)throw new Error("bbox must be an Array of 4 or 6 numbers");e.forEach((function(e){if(!C(e))throw new Error("bbox must only contain numbers")}))},t.validateId=function(e){if(!e)throw new Error("id is required");if(-1===["string","number"].indexOf(typeof e))throw new Error("id must be a number or a string")},t.radians2degrees=function(){throw new Error("method has been renamed to `radiansToDegrees`")},t.degrees2radians=function(){throw new Error("method has been renamed to `degreesToRadians`")},t.distanceToDegrees=function(){throw new Error("method has been renamed to `lengthToDegrees`")},t.distanceToRadians=function(){throw new Error("method has been renamed to `lengthToRadians`")},t.radiansToDistance=function(){throw new Error("method has been renamed to `radiansToLength`")},t.bearingToAngle=function(){throw new Error("method has been renamed to `bearingToAzimuth`")},t.convertDistance=function(){throw new Error("method has been renamed to `convertLength`")}},function(e,t,A){"use strict";A.d(t,"c",(function(){return a})),A.d(t,"a",(function(){return g})),A.d(t,"b",(function(){return c})),A.d(t,"d",(function(){return u}));var n=A(717);function r(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return Math.min(Math.max(t,e),A)}function i(e){if(e.type)return e;if("#"===e.charAt(0))return i(function(e){e=e.substr(1);var t=new RegExp(".{1,".concat(e.length>=6?2:1,"}"),"g"),A=e.match(t);return A&&1===A[0].length&&(A=A.map((function(e){return e+e}))),A?"rgb".concat(4===A.length?"a":"","(").concat(A.map((function(e,t){return t<3?parseInt(e,16):Math.round(parseInt(e,16)/255*1e3)/1e3})).join(", "),")"):""}(e));var t=e.indexOf("("),A=e.substring(0,t);if(-1===["rgb","rgba","hsl","hsla"].indexOf(A))throw new Error(Object(n.a)(3,e));var r=e.substring(t+1,e.length-1).split(",");return{type:A,values:r=r.map((function(e){return parseFloat(e)}))}}function o(e){var t=e.type,A=e.values;return-1!==t.indexOf("rgb")?A=A.map((function(e,t){return t<3?parseInt(e,10):e})):-1!==t.indexOf("hsl")&&(A[1]="".concat(A[1],"%"),A[2]="".concat(A[2],"%")),"".concat(t,"(").concat(A.join(", "),")")}function a(e,t){var A=s(e),n=s(t);return(Math.max(A,n)+.05)/(Math.min(A,n)+.05)}function s(e){var t="hsl"===(e=i(e)).type?i(function(e){var t=(e=i(e)).values,A=t[0],n=t[1]/100,r=t[2]/100,a=n*Math.min(r,1-r),s=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e+A/30)%12;return r-a*Math.max(Math.min(t-3,9-t,1),-1)},g="rgb",c=[Math.round(255*s(0)),Math.round(255*s(8)),Math.round(255*s(4))];return"hsla"===e.type&&(g+="a",c.push(t[3])),o({type:g,values:c})}(e)).values:e.values;return t=t.map((function(e){return(e/=255)<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)})),Number((.2126*t[0]+.7152*t[1]+.0722*t[2]).toFixed(3))}function g(e,t){return e=i(e),t=r(t),"rgb"!==e.type&&"hsl"!==e.type||(e.type+="a"),e.values[3]=t,o(e)}function c(e,t){if(e=i(e),t=r(t),-1!==e.type.indexOf("hsl"))e.values[2]*=1-t;else if(-1!==e.type.indexOf("rgb"))for(var A=0;A<3;A+=1)e.values[A]*=1-t;return o(e)}function u(e,t){if(e=i(e),t=r(t),-1!==e.type.indexOf("hsl"))e.values[2]+=(100-e.values[2])*t;else if(-1!==e.type.indexOf("rgb"))for(var A=0;A<3;A+=1)e.values[A]+=(255-e.values[A])*t;return o(e)}},function(e,t,A){var n;!function(){"use strict";var A={}.hasOwnProperty;function r(){for(var e=[],t=0;t0&&(i=1/Math.sqrt(i)),e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e}function s(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function g(e,t,A){var n=t[0],r=t[1],i=t[2],o=A[0],a=A[1],s=A[2];return e[0]=r*s-i*a,e[1]=i*o-n*s,e[2]=n*a-r*o,e}function c(e,t,A){var n=t[0],r=t[1],i=t[2],o=A[3]*n+A[7]*r+A[11]*i+A[15];return o=o||1,e[0]=(A[0]*n+A[4]*r+A[8]*i+A[12])/o,e[1]=(A[1]*n+A[5]*r+A[9]*i+A[13])/o,e[2]=(A[2]*n+A[6]*r+A[10]*i+A[14])/o,e}function u(e,t,A){var n=t[0],r=t[1],i=t[2];return e[0]=n*A[0]+r*A[3]+i*A[6],e[1]=n*A[1]+r*A[4]+i*A[7],e[2]=n*A[2]+r*A[5]+i*A[8],e}function l(e,t,A){var n=A[0],r=A[1],i=A[2],o=A[3],a=t[0],s=t[1],g=t[2],c=r*g-i*s,u=i*a-n*g,l=n*s-r*a,I=r*l-i*u,C=i*c-n*l,h=n*u-r*c,f=2*o;return c*=f,u*=f,l*=f,I*=2,C*=2,h*=2,e[0]=a+c+I,e[1]=s+u+C,e[2]=g+l+h,e}function I(e,t,A,n){var r=[],i=[];return r[0]=t[0]-A[0],r[1]=t[1]-A[1],r[2]=t[2]-A[2],i[0]=r[0],i[1]=r[1]*Math.cos(n)-r[2]*Math.sin(n),i[2]=r[1]*Math.sin(n)+r[2]*Math.cos(n),e[0]=i[0]+A[0],e[1]=i[1]+A[1],e[2]=i[2]+A[2],e}function C(e,t,A,n){var r=[],i=[];return r[0]=t[0]-A[0],r[1]=t[1]-A[1],r[2]=t[2]-A[2],i[0]=r[2]*Math.sin(n)+r[0]*Math.cos(n),i[1]=r[1],i[2]=r[2]*Math.cos(n)-r[0]*Math.sin(n),e[0]=i[0]+A[0],e[1]=i[1]+A[1],e[2]=i[2]+A[2],e}function h(e,t,A,n){var r=[],i=[];return r[0]=t[0]-A[0],r[1]=t[1]-A[1],r[2]=t[2]-A[2],i[0]=r[0]*Math.cos(n)-r[1]*Math.sin(n),i[1]=r[0]*Math.sin(n)+r[1]*Math.cos(n),i[2]=r[2],e[0]=i[0]+A[0],e[1]=i[1]+A[1],e[2]=i[2]+A[2],e}function f(e,t){var A=e[0],n=e[1],r=e[2],i=t[0],o=t[1],a=t[2],g=Math.sqrt(A*A+n*n+r*r)*Math.sqrt(i*i+o*o+a*a),c=g&&s(e,t)/g;return Math.acos(Math.min(Math.max(c,-1),1))}var d=i;!function(){var e=r()}()},,function(e,t,A){"use strict";function n(e){return e&&e.ownerDocument||document}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return r})),A.d(t,"b",(function(){return i})),A.d(t,"c",(function(){return o})),A.d(t,"d",(function(){return a})),A.d(t,"e",(function(){return s})),A.d(t,"f",(function(){return g}));var n=A(31);function r(e,t,A){return e[0]=t[0]+A[0],e[1]=t[1]+A[1],e}function i(e,t){return e[0]=-t[0],e[1]=-t[1],e}function o(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[2]*r,e[1]=A[1]*n+A[3]*r,e}function a(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[2]*r+A[4],e[1]=A[1]*n+A[3]*r+A[5],e}function s(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[3]*r+A[6],e[1]=A[1]*n+A[4]*r+A[7],e}function g(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[4]*r+A[12],e[1]=A[1]*n+A[5]*r+A[13],e}!function(){var e=function(){var e=new n.a(2);return n.a!=Float32Array&&(e[0]=0,e[1]=0),e}()}()},function(e,t,A){"use strict";(function(e,n){var r=A(11),i=A(3),o=A.n(i),a=A(12),s=A(1),g=A(4),c=A(47);A.d(t,"a",(function(){return c.a})),A.d(t,"b",(function(){return c.b})),A.d(t,"c",(function(){return c.c})),A.d(t,"d",(function(){return c.e})),A.d(t,"e",(function(){return c.f})),A.d(t,"f",(function(){return c.g}));function u(e){for(var t=e.length;--t>=0;)e[t]=0}var l=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),I=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),C=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),h=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),f=new Array(576);u(f);var d=new Array(60);u(d);var B=new Array(512);u(B);var p=new Array(256);u(p);var E=new Array(29);u(E);var Q,y,v,m=new Array(30);function b(e,t,A,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=A,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}function w(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}u(m);var S=function(e){return e<256?B[e]:B[256+(e>>>7)]},F=function(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},R=function(e,t,A){e.bi_valid>16-A?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=A-16):(e.bi_buf|=t<>>=1,A<<=1}while(--t>0);return A>>>1},k=function(e,t,A){var n,r,i=new Array(16),o=0;for(n=1;n<=15;n++)i[n]=o=o+A[n-1]<<1;for(r=0;r<=t;r++){var a=e[2*r+1];0!==a&&(e[2*r]=G(i[a]++,a))}},x=function(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0},N=function(e){e.bi_valid>8?F(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},U=function(e,t,A,n){var r=2*t,i=2*A;return e[r]>1;A>=1;A--)_(e,i,A);r=s;do{A=e.heap[1],e.heap[1]=e.heap[e.heap_len--],_(e,i,1),n=e.heap[1],e.heap[--e.heap_max]=A,e.heap[--e.heap_max]=n,i[2*r]=i[2*A]+i[2*n],e.depth[r]=(e.depth[A]>=e.depth[n]?e.depth[A]:e.depth[n])+1,i[2*A+1]=i[2*n+1]=r,e.heap[1]=r++,_(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var A,n,r,i,o,a,s=t.dyn_tree,g=t.max_code,c=t.stat_desc.static_tree,u=t.stat_desc.has_stree,l=t.stat_desc.extra_bits,I=t.stat_desc.extra_base,C=t.stat_desc.max_length,h=0;for(i=0;i<=15;i++)e.bl_count[i]=0;for(s[2*e.heap[e.heap_max]+1]=0,A=e.heap_max+1;A<573;A++)(i=s[2*s[2*(n=e.heap[A])+1]+1]+1)>C&&(i=C,h++),s[2*n+1]=i,n>g||(e.bl_count[i]++,o=0,n>=I&&(o=l[n-I]),a=s[2*n],e.opt_len+=a*(i+o),u&&(e.static_len+=a*(c[2*n+1]+o)));if(0!==h){do{for(i=C-1;0===e.bl_count[i];)i--;e.bl_count[i]--,e.bl_count[i+1]+=2,e.bl_count[C]--,h-=2}while(h>0);for(i=C;0!==i;i--)for(n=e.bl_count[i];0!==n;)(r=e.heap[--A])>g||(s[2*r+1]!==i&&(e.opt_len+=(i-s[2*r+1])*s[2*r],s[2*r+1]=i),n--)}}(e,t),k(i,g,e.bl_count)},L=function(e,t,A){var n,r,i=-1,o=t[1],a=0,s=7,g=4;for(0===o&&(s=138,g=3),t[2*(A+1)+1]=65535,n=0;n<=A;n++)r=o,o=t[2*(n+1)+1],++a>=7;n<30;n++)for(m[n]=r<<7,e=0;e<1<0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,A=4093624447;for(t=0;t<=31;t++,A>>>=1)if(1&A&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),O(e,e.l_desc),O(e,e.d_desc),o=function(e){var t;for(L(e,e.dyn_ltree,e.l_desc.max_code),L(e,e.dyn_dtree,e.d_desc.max_code),O(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*h[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(i=e.static_len+3+7>>>3)<=r&&(r=i)):r=i=A+5,A+4<=r&&-1!==t?H(e,t,A,n):4===e.strategy||i===r?(R(e,2+(n?1:0),3),M(e,f,d)):(R(e,4+(n?1:0),3),function(e,t,A,n){var r;for(R(e,t-257,5),R(e,A-1,5),R(e,n-4,4),r=0;r>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&A,e.last_lit++,0===t?e.dyn_ltree[2*A]++:(e.matches++,t--,e.dyn_ltree[2*(p[A]+256+1)]++,e.dyn_dtree[2*S(t)]++),e.last_lit===e.lit_bufsize-1},_tr_align:function(e){R(e,2,3),D(e,256,f),function(e){16===e.bi_valid?(F(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},J=function(e,t,A,n){for(var r=65535&e|0,i=e>>>16&65535|0,o=0;0!==A;){A-=o=A>2e3?2e3:A;do{i=i+(r=r+t[n++]|0)|0}while(--o);r%=65521,i%=65521}return r|i<<16|0},j=new Uint32Array(function(){for(var e,t=[],A=0;A<256;A++){e=A;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[A]=e}return t}()),P=function(e,t,A,n){var r=j,i=n+A;e^=-1;for(var o=n;o>>8^r[255&(e^t[o])];return-1^e},V={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},K={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},W=Y._tr_init,X=Y._tr_stored_block,q=Y._tr_flush_block,z=Y._tr_tally,$=Y._tr_align,ee=K.Z_NO_FLUSH,te=K.Z_PARTIAL_FLUSH,Ae=K.Z_FULL_FLUSH,ne=K.Z_FINISH,re=K.Z_BLOCK,ie=K.Z_OK,oe=K.Z_STREAM_END,ae=K.Z_STREAM_ERROR,se=K.Z_DATA_ERROR,ge=K.Z_BUF_ERROR,ce=K.Z_DEFAULT_COMPRESSION,ue=K.Z_FILTERED,le=K.Z_HUFFMAN_ONLY,Ie=K.Z_RLE,Ce=K.Z_FIXED,he=K.Z_DEFAULT_STRATEGY,fe=K.Z_UNKNOWN,de=K.Z_DEFLATED,Be=function(e,t){return e.msg=V[t],t},pe=function(e){return(e<<1)-(e>4?9:0)},Ee=function(e){for(var t=e.length;--t>=0;)e[t]=0},Qe=function(e,t,A){return(t<e.avail_out&&(A=e.avail_out),0!==A&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+A),e.next_out),e.next_out+=A,t.pending_out+=A,e.total_out+=A,e.avail_out-=A,t.pending-=A,0===t.pending&&(t.pending_out=0))},ve=function(e,t){q(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ye(e.strm)},me=function(e,t){e.pending_buf[e.pending++]=t},be=function(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},we=function(e,t,A,n){var r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),A),1===e.state.wrap?e.adler=J(e.adler,t,r,A):2===e.state.wrap&&(e.adler=P(e.adler,t,r,A)),e.next_in+=r,e.total_in+=r,r)},Se=function(e,t){var A,n,r=e.max_chain_length,i=e.strstart,o=e.prev_length,a=e.nice_match,s=e.strstart>e.w_size-262?e.strstart-(e.w_size-262):0,g=e.window,c=e.w_mask,u=e.prev,l=e.strstart+258,I=g[i+o-1],C=g[i+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(g[(A=t)+o]===C&&g[A+o-1]===I&&g[A]===g[i]&&g[++A]===g[i+1]){i+=2,A++;do{}while(g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&io){if(e.match_start=t,o=n,n>=a)break;I=g[i+o-1],C=g[i+o]}}}while((t=u[t&c])>s&&0!==--r);return o<=e.lookahead?o:e.lookahead},Fe=function(e){var t,A,n,r,i,o=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=o+(o-262)){e.window.set(e.window.subarray(o,o+o),0),e.match_start-=o,e.strstart-=o,e.block_start-=o,t=A=e.hash_size;do{n=e.head[--t],e.head[t]=n>=o?n-o:0}while(--A);t=A=o;do{n=e.prev[--t],e.prev[t]=n>=o?n-o:0}while(--A);r+=o}if(0===e.strm.avail_in)break;if(A=we(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=A,e.lookahead+e.insert>=3)for(i=e.strstart-e.insert,e.ins_h=e.window[i],e.ins_h=Qe(e,e.ins_h,e.window[i+1]);e.insert&&(e.ins_h=Qe(e,e.ins_h,e.window[i+3-1]),e.prev[i&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=i,i++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<262&&0!==e.strm.avail_in)},Re=function(e,t){for(var A,n;;){if(e.lookahead<262){if(Fe(e),e.lookahead<262&&t===ee)return 1;if(0===e.lookahead)break}if(A=0,e.lookahead>=3&&(e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==A&&e.strstart-A<=e.w_size-262&&(e.match_length=Se(e,A)),e.match_length>=3)if(n=z(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+1]);else n=z(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(ve(e,!1),0===e.strm.avail_out)?1:2},De=function(e,t){for(var A,n,r;;){if(e.lookahead<262){if(Fe(e),e.lookahead<262&&t===ee)return 1;if(0===e.lookahead)break}if(A=0,e.lookahead>=3&&(e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==A&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=z(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(ve(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((n=z(e,0,e.window[e.strstart-1]))&&ve(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=z(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(ve(e,!1),0===e.strm.avail_out)?1:2};function Ge(e,t,A,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=A,this.max_chain=n,this.func=r}var ke=[new Ge(0,0,0,0,(function(e,t){var A=65535;for(A>e.pending_buf_size-5&&(A=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Fe(e),0===e.lookahead&&t===ee)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+A;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,ve(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-262&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(ve(e,!1),e.strm.avail_out),1)})),new Ge(4,4,8,4,Re),new Ge(4,5,16,8,Re),new Ge(4,6,32,32,Re),new Ge(4,4,16,16,De),new Ge(8,16,32,32,De),new Ge(8,16,128,128,De),new Ge(8,32,128,256,De),new Ge(32,128,258,1024,De),new Ge(32,258,258,4096,De)];function xe(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=de,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Ee(this.dyn_ltree),Ee(this.dyn_dtree),Ee(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Ee(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Ee(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var Ne=function(e){if(!e||!e.state)return Be(e,ae);e.total_in=e.total_out=0,e.data_type=fe;var t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:113,e.adler=2===t.wrap?0:1,t.last_flush=ee,W(t),ie},Ue=function(e){var t,A=Ne(e);return A===ie&&((t=e.state).window_size=2*t.w_size,Ee(t.head),t.max_lazy_match=ke[t.level].max_lazy,t.good_match=ke[t.level].good_length,t.nice_match=ke[t.level].nice_length,t.max_chain_length=ke[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),A},_e=function(e,t,A,n,r,i){if(!e)return ae;var o=1;if(t===ce&&(t=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),r<1||r>9||A!==de||n<8||n>15||t<0||t>9||i<0||i>Ce)return Be(e,ae);8===n&&(n=9);var a=new xe;return e.state=a,a.strm=e,a.wrap=o,a.gzhead=null,a.w_bits=n,a.w_size=1<re||t<0)return e?Be(e,ae):ae;var r=e.state;if(!e.output||!e.input&&0!==e.avail_in||666===r.status&&t!==ne)return Be(e,0===e.avail_out?ge:ae);r.strm=e;var i=r.last_flush;if(r.last_flush=t,42===r.status)if(2===r.wrap)e.adler=0,me(r,31),me(r,139),me(r,8),r.gzhead?(me(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),me(r,255&r.gzhead.time),me(r,r.gzhead.time>>8&255),me(r,r.gzhead.time>>16&255),me(r,r.gzhead.time>>24&255),me(r,9===r.level?2:r.strategy>=le||r.level<2?4:0),me(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(me(r,255&r.gzhead.extra.length),me(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=P(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69):(me(r,0),me(r,0),me(r,0),me(r,0),me(r,0),me(r,9===r.level?2:r.strategy>=le||r.level<2?4:0),me(r,3),r.status=113);else{var o=de+(r.w_bits-8<<4)<<8;o|=(r.strategy>=le||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(o|=32),o+=31-o%31,r.status=113,be(r,o),0!==r.strstart&&(be(r,e.adler>>>16),be(r,65535&e.adler)),e.adler=1}if(69===r.status)if(r.gzhead.extra){for(A=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>A&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),ye(e),A=r.pending,r.pending!==r.pending_buf_size));)me(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>A&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=73)}else r.status=73;if(73===r.status)if(r.gzhead.name){A=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>A&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),ye(e),A=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindexA&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),0===n&&(r.gzindex=0,r.status=91)}else r.status=91;if(91===r.status)if(r.gzhead.comment){A=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>A&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),ye(e),A=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindexA&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),0===n&&(r.status=103)}else r.status=103;if(103===r.status&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&ye(e),r.pending+2<=r.pending_buf_size&&(me(r,255&e.adler),me(r,e.adler>>8&255),e.adler=0,r.status=113)):r.status=113),0!==r.pending){if(ye(e),0===e.avail_out)return r.last_flush=-1,ie}else if(0===e.avail_in&&pe(t)<=pe(i)&&t!==ne)return Be(e,ge);if(666===r.status&&0!==e.avail_in)return Be(e,ge);if(0!==e.avail_in||0!==r.lookahead||t!==ee&&666!==r.status){var a=r.strategy===le?function(e,t){for(var A;;){if(0===e.lookahead&&(Fe(e),0===e.lookahead)){if(t===ee)return 1;break}if(e.match_length=0,A=z(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,A&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(ve(e,!1),0===e.strm.avail_out)?1:2}(r,t):r.strategy===Ie?function(e,t){for(var A,n,r,i,o=e.window;;){if(e.lookahead<=258){if(Fe(e),e.lookahead<=258&&t===ee)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(n=o[r=e.strstart-1])===o[++r]&&n===o[++r]&&n===o[++r]){i=e.strstart+258;do{}while(n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(A=z(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(A=z(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),A&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(ve(e,!1),0===e.strm.avail_out)?1:2}(r,t):ke[r.level].func(r,t);if(3!==a&&4!==a||(r.status=666),1===a||3===a)return 0===e.avail_out&&(r.last_flush=-1),ie;if(2===a&&(t===te?$(r):t!==re&&(X(r,0,0,!1),t===Ae&&(Ee(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),ye(e),0===e.avail_out))return r.last_flush=-1,ie}return t!==ne?ie:r.wrap<=0?oe:(2===r.wrap?(me(r,255&e.adler),me(r,e.adler>>8&255),me(r,e.adler>>16&255),me(r,e.adler>>24&255),me(r,255&e.total_in),me(r,e.total_in>>8&255),me(r,e.total_in>>16&255),me(r,e.total_in>>24&255)):(be(r,e.adler>>>16),be(r,65535&e.adler)),ye(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?ie:oe)},deflateEnd:function(e){if(!e||!e.state)return ae;var t=e.state.status;return 42!==t&&69!==t&&73!==t&&91!==t&&103!==t&&113!==t&&666!==t?Be(e,ae):(e.state=null,113===t?Be(e,se):ie)},deflateSetDictionary:function(e,t){var A=t.length;if(!e||!e.state)return ae;var n=e.state,r=n.wrap;if(2===r||1===r&&42!==n.status||n.lookahead)return ae;if(1===r&&(e.adler=J(e.adler,t,A,0)),n.wrap=0,A>=n.w_size){0===r&&(Ee(n.head),n.strstart=0,n.block_start=0,n.insert=0);var i=new Uint8Array(n.w_size);i.set(t.subarray(A-n.w_size,A),0),t=i,A=n.w_size}var o=e.avail_in,a=e.next_in,s=e.input;for(e.avail_in=A,e.next_in=0,e.input=t,Fe(n);n.lookahead>=3;){var g=n.strstart,c=n.lookahead-2;do{n.ins_h=Qe(n,n.ins_h,n.window[g+3-1]),n.prev[g&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=g,g++}while(--c);n.strstart=g,n.lookahead=2,Fe(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=a,e.input=s,e.avail_in=o,n.wrap=r,ie},deflateInfo:"pako deflate (from Nodeca project)"},Oe=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},Le=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var A=t.shift();if(A){if("object"!==typeof A)throw new TypeError(A+"must be non-object");for(var n in A)Oe(A,n)&&(e[n]=A[n])}}return e},Te=function(e){for(var t=0,A=0,n=e.length;A=252?6:Ye>=248?5:Ye>=240?4:Ye>=224?3:Ye>=192?2:1;He[254]=He[254]=1;var Je=function(e){var t,A,n,r,i,o=e.length,a=0;for(r=0;r>>6,t[i++]=128|63&A):A<65536?(t[i++]=224|A>>>12,t[i++]=128|A>>>6&63,t[i++]=128|63&A):(t[i++]=240|A>>>18,t[i++]=128|A>>>12&63,t[i++]=128|A>>>6&63,t[i++]=128|63&A);return t},je=function(e,t){var A,n,r=t||e.length,i=new Array(2*r);for(n=0,A=0;A4)i[n++]=65533,A+=a-1;else{for(o&=2===a?31:3===a?15:7;a>1&&A1?i[n++]=65533:o<65536?i[n++]=o:(o-=65536,i[n++]=55296|o>>10&1023,i[n++]=56320|1023&o)}}}return function(e,t){if(t<65534&&e.subarray&&Ze)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));for(var A="",n=0;ne.length&&(t=e.length);for(var A=t-1;A>=0&&128===(192&e[A]);)A--;return A<0||0===A?t:A+He[e[A]]>t?A:t};var Ve=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},Ke=Object.prototype.toString,We=K.Z_NO_FLUSH,Xe=K.Z_SYNC_FLUSH,qe=K.Z_FULL_FLUSH,ze=K.Z_FINISH,$e=K.Z_OK,et=K.Z_STREAM_END,tt=K.Z_DEFAULT_COMPRESSION,At=K.Z_DEFAULT_STRATEGY,nt=K.Z_DEFLATED;function rt(e){this.options=Le({level:tt,method:nt,chunkSize:16384,windowBits:15,memLevel:8,strategy:At},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ve,this.strm.avail_out=0;var A=Me.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(A!==$e)throw new Error(V[A]);if(t.header&&Me.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(n="string"===typeof t.dictionary?Je(t.dictionary):"[object ArrayBuffer]"===Ke.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(A=Me.deflateSetDictionary(this.strm,n))!==$e)throw new Error(V[A]);this._dict_set=!0}}function it(e,t){var A=new rt(t);if(A.push(e,!0),A.err)throw A.msg||V[A.err];return A.result}rt.prototype.push=function(e,t){var A,n,r=this.strm,i=this.options.chunkSize;if(this.ended)return!1;for(n=t===~~t?t:!0===t?ze:We,"string"===typeof e?r.input=Je(e):"[object ArrayBuffer]"===Ke.call(e)?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;;)if(0===r.avail_out&&(r.output=new Uint8Array(i),r.next_out=0,r.avail_out=i),(n===Xe||n===qe)&&r.avail_out<=6)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else{if((A=Me.deflate(r,n))===et)return r.next_out>0&&this.onData(r.output.subarray(0,r.next_out)),A=Me.deflateEnd(this.strm),this.onEnd(A),this.ended=!0,A===$e;if(0!==r.avail_out){if(n>0&&r.next_out>0)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else if(0===r.avail_in)break}else this.onData(r.output)}return!0},rt.prototype.onData=function(e){this.chunks.push(e)},rt.prototype.onEnd=function(e){e===$e&&(this.result=Te(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ot={Deflate:rt,deflate:it,deflateRaw:function(e,t){return(t=t||{}).raw=!0,it(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,it(e,t)},constants:K},at=function(e,t){var A,n,r,i,o,a,s,g,c,u,l,I,C,h,f,d,B,p,E,Q,y,v,m,b,w=e.state;A=e.next_in,m=e.input,n=A+(e.avail_in-5),r=e.next_out,b=e.output,i=r-(t-e.avail_out),o=r+(e.avail_out-257),a=w.dmax,s=w.wsize,g=w.whave,c=w.wnext,u=w.window,l=w.hold,I=w.bits,C=w.lencode,h=w.distcode,f=(1<>>=p=B>>>24,I-=p,0===(p=B>>>16&255))b[r++]=65535&B;else{if(!(16&p)){if(0===(64&p)){B=C[(65535&B)+(l&(1<>>=p,I-=p),I<15&&(l+=m[A++]<>>=p=B>>>24,I-=p,!(16&(p=B>>>16&255))){if(0===(64&p)){B=h[(65535&B)+(l&(1<a){e.msg="invalid distance too far back",w.mode=30;break e}if(l>>>=p,I-=p,Q>(p=r-i)){if((p=Q-p)>g&&w.sane){e.msg="invalid distance too far back",w.mode=30;break e}if(y=0,v=u,0===c){if(y+=s-p,p2;)b[r++]=v[y++],b[r++]=v[y++],b[r++]=v[y++],E-=3;E&&(b[r++]=v[y++],E>1&&(b[r++]=v[y++]))}else{y=r-Q;do{b[r++]=b[y++],b[r++]=b[y++],b[r++]=b[y++],E-=3}while(E>2);E&&(b[r++]=b[y++],E>1&&(b[r++]=b[y++]))}break}}break}}while(A>3,l&=(1<<(I-=E<<3))-1,e.next_in=A,e.next_out=r,e.avail_in=A=1&&0===D[Q];Q--);if(y>Q&&(y=Q),0===Q)return r[i++]=20971520,r[i++]=20971520,a.bits=1,0;for(E=1;E0&&(0===e||1!==Q))return-1;for(G[1]=0,B=1;B<15;B++)G[B+1]=G[B]+D[B];for(p=0;p852||2===e&&w>592)return 1;for(;;){C=B-m,o[p]I?(h=k[x+o[p]],f=F[R+o[p]]):(h=96,f=0),s=1<>m)+(g-=s)]=C<<24|h<<16|f|0}while(0!==g);for(s=1<>=1;if(0!==s?(S&=s-1,S+=s):S=0,p++,0===--D[B]){if(B===Q)break;B=t[A+o[p]]}if(B>y&&(S&u)!==c){for(0===m&&(m=y),l+=E,b=1<<(v=B-m);v+m852||2===e&&w>592)return 1;r[c=S&u]=y<<24|v<<16|l-i|0}}return 0!==S&&(r[l+S]=B-m<<24|64<<16|0),a.bits=y,0},It=K.Z_FINISH,Ct=K.Z_BLOCK,ht=K.Z_TREES,ft=K.Z_OK,dt=K.Z_STREAM_END,Bt=K.Z_NEED_DICT,pt=K.Z_STREAM_ERROR,Et=K.Z_DATA_ERROR,Qt=K.Z_MEM_ERROR,yt=K.Z_BUF_ERROR,vt=K.Z_DEFLATED,mt=function(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)};function bt(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var wt,St,Ft=function(e){if(!e||!e.state)return pt;var t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,ft},Rt=function(e){if(!e||!e.state)return pt;var t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Ft(e)},Dt=function(e,t){var A;if(!e||!e.state)return pt;var n=e.state;return t<0?(A=0,t=-t):(A=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?pt:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=A,n.wbits=t,Rt(e))},Gt=function(e,t){if(!e)return pt;var A=new bt;e.state=A,A.window=null;var n=Dt(e,t);return n!==ft&&(e.state=null),n},kt=!0,xt=function(e){if(kt){wt=new Int32Array(512),St=new Int32Array(32);for(var t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(lt(1,e.lens,0,288,wt,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;lt(2,e.lens,0,32,St,0,e.work,{bits:5}),kt=!1}e.lencode=wt,e.lenbits=9,e.distcode=St,e.distbits=5},Nt=function(e,t,A,n){var r,i=e.state;return null===i.window&&(i.wsize=1<=i.wsize?(i.window.set(t.subarray(A-i.wsize,A),0),i.wnext=0,i.whave=i.wsize):((r=i.wsize-i.wnext)>n&&(r=n),i.window.set(t.subarray(A-n,A-n+r),i.wnext),(n-=r)?(i.window.set(t.subarray(A-n,A),0),i.wnext=n,i.whave=i.wsize):(i.wnext+=r,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,A.check=P(A.check,S,2,0),g=0,c=0,A.mode=2;break}if(A.flags=0,A.head&&(A.head.done=!1),!(1&A.wrap)||(((255&g)<<8)+(g>>8))%31){e.msg="incorrect header check",A.mode=30;break}if((15&g)!==vt){e.msg="unknown compression method",A.mode=30;break}if(c-=4,y=8+(15&(g>>>=4)),0===A.wbits)A.wbits=y;else if(y>A.wbits){e.msg="invalid window size",A.mode=30;break}A.dmax=1<>8&1),512&A.flags&&(S[0]=255&g,S[1]=g>>>8&255,A.check=P(A.check,S,2,0)),g=0,c=0,A.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,g+=n[i++]<>>8&255,S[2]=g>>>16&255,S[3]=g>>>24&255,A.check=P(A.check,S,4,0)),g=0,c=0,A.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,g+=n[i++]<>8),512&A.flags&&(S[0]=255&g,S[1]=g>>>8&255,A.check=P(A.check,S,2,0)),g=0,c=0,A.mode=5;case 5:if(1024&A.flags){for(;c<16;){if(0===a)break e;a--,g+=n[i++]<>>8&255,A.check=P(A.check,S,2,0)),g=0,c=0}else A.head&&(A.head.extra=null);A.mode=6;case 6:if(1024&A.flags&&((I=A.length)>a&&(I=a),I&&(A.head&&(y=A.head.extra_len-A.length,A.head.extra||(A.head.extra=new Uint8Array(A.head.extra_len)),A.head.extra.set(n.subarray(i,i+I),y)),512&A.flags&&(A.check=P(A.check,n,I,i)),a-=I,i+=I,A.length-=I),A.length))break e;A.length=0,A.mode=7;case 7:if(2048&A.flags){if(0===a)break e;I=0;do{y=n[i+I++],A.head&&y&&A.length<65536&&(A.head.name+=String.fromCharCode(y))}while(y&&I>9&1,A.head.done=!0),e.adler=A.check=0,A.mode=12;break;case 10:for(;c<32;){if(0===a)break e;a--,g+=n[i++]<>>=7&c,c-=7&c,A.mode=27;break}for(;c<3;){if(0===a)break e;a--,g+=n[i++]<>>=1)){case 0:A.mode=14;break;case 1:if(xt(A),A.mode=20,t===ht){g>>>=2,c-=2;break e}break;case 2:A.mode=17;break;case 3:e.msg="invalid block type",A.mode=30}g>>>=2,c-=2;break;case 14:for(g>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,g+=n[i++]<>>16^65535)){e.msg="invalid stored block lengths",A.mode=30;break}if(A.length=65535&g,g=0,c=0,A.mode=15,t===ht)break e;case 15:A.mode=16;case 16:if(I=A.length){if(I>a&&(I=a),I>s&&(I=s),0===I)break e;r.set(n.subarray(i,i+I),o),a-=I,i+=I,s-=I,o+=I,A.length-=I;break}A.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,g+=n[i++]<>>=5,c-=5,A.ndist=1+(31&g),g>>>=5,c-=5,A.ncode=4+(15&g),g>>>=4,c-=4,A.nlen>286||A.ndist>30){e.msg="too many length or distance symbols",A.mode=30;break}A.have=0,A.mode=18;case 18:for(;A.have>>=3,c-=3}for(;A.have<19;)A.lens[F[A.have++]]=0;if(A.lencode=A.lendyn,A.lenbits=7,m={bits:A.lenbits},v=lt(0,A.lens,0,19,A.lencode,0,A.work,m),A.lenbits=m.bits,v){e.msg="invalid code lengths set",A.mode=30;break}A.have=0,A.mode=19;case 19:for(;A.have>>16&255,B=65535&w,!((f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>>=f,c-=f,A.lens[A.have++]=B;else{if(16===B){for(b=f+2;c>>=f,c-=f,0===A.have){e.msg="invalid bit length repeat",A.mode=30;break}y=A.lens[A.have-1],I=3+(3&g),g>>>=2,c-=2}else if(17===B){for(b=f+3;c>>=f)),g>>>=3,c-=3}else{for(b=f+7;c>>=f)),g>>>=7,c-=7}if(A.have+I>A.nlen+A.ndist){e.msg="invalid bit length repeat",A.mode=30;break}for(;I--;)A.lens[A.have++]=y}}if(30===A.mode)break;if(0===A.lens[256]){e.msg="invalid code -- missing end-of-block",A.mode=30;break}if(A.lenbits=9,m={bits:A.lenbits},v=lt(1,A.lens,0,A.nlen,A.lencode,0,A.work,m),A.lenbits=m.bits,v){e.msg="invalid literal/lengths set",A.mode=30;break}if(A.distbits=6,A.distcode=A.distdyn,m={bits:A.distbits},v=lt(2,A.lens,A.nlen,A.ndist,A.distcode,0,A.work,m),A.distbits=m.bits,v){e.msg="invalid distances set",A.mode=30;break}if(A.mode=20,t===ht)break e;case 20:A.mode=21;case 21:if(a>=6&&s>=258){e.next_out=o,e.avail_out=s,e.next_in=i,e.avail_in=a,A.hold=g,A.bits=c,at(e,l),o=e.next_out,r=e.output,s=e.avail_out,i=e.next_in,n=e.input,a=e.avail_in,g=A.hold,c=A.bits,12===A.mode&&(A.back=-1);break}for(A.back=0;d=(w=A.lencode[g&(1<>>16&255,B=65535&w,!((f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>p)])>>>16&255,B=65535&w,!(p+(f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>>=p,c-=p,A.back+=p}if(g>>>=f,c-=f,A.back+=f,A.length=B,0===d){A.mode=26;break}if(32&d){A.back=-1,A.mode=12;break}if(64&d){e.msg="invalid literal/length code",A.mode=30;break}A.extra=15&d,A.mode=22;case 22:if(A.extra){for(b=A.extra;c>>=A.extra,c-=A.extra,A.back+=A.extra}A.was=A.length,A.mode=23;case 23:for(;d=(w=A.distcode[g&(1<>>16&255,B=65535&w,!((f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>p)])>>>16&255,B=65535&w,!(p+(f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>>=p,c-=p,A.back+=p}if(g>>>=f,c-=f,A.back+=f,64&d){e.msg="invalid distance code",A.mode=30;break}A.offset=B,A.extra=15&d,A.mode=24;case 24:if(A.extra){for(b=A.extra;c>>=A.extra,c-=A.extra,A.back+=A.extra}if(A.offset>A.dmax){e.msg="invalid distance too far back",A.mode=30;break}A.mode=25;case 25:if(0===s)break e;if(I=l-s,A.offset>I){if((I=A.offset-I)>A.whave&&A.sane){e.msg="invalid distance too far back",A.mode=30;break}I>A.wnext?(I-=A.wnext,C=A.wsize-I):C=A.wnext-I,I>A.length&&(I=A.length),h=A.window}else h=r,C=o-A.offset,I=A.length;I>s&&(I=s),s-=I,A.length-=I;do{r[o++]=h[C++]}while(--I);0===A.length&&(A.mode=21);break;case 26:if(0===s)break e;r[o++]=A.length,s--,A.mode=21;break;case 27:if(A.wrap){for(;c<32;){if(0===a)break e;a--,g|=n[i++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0===(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ve,this.strm.avail_out=0;var A=Ut.inflateInit2(this.strm,t.windowBits);if(A!==Tt)throw new Error(V[A]);if(this.header=new _t,Ut.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"===typeof t.dictionary?t.dictionary=Je(t.dictionary):"[object ArrayBuffer]"===Mt.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(A=Ut.inflateSetDictionary(this.strm,t.dictionary))!==Tt))throw new Error(V[A])}function Vt(e,t){var A=new Pt(t);if(A.push(e),A.err)throw A.msg||V[A.err];return A.result}Pt.prototype.push=function(e,t){var A,n,r,i=this.strm,o=this.options.chunkSize,a=this.options.dictionary;if(this.ended)return!1;for(n=t===~~t?t:!0===t?Lt:Ot,"[object ArrayBuffer]"===Mt.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(o),i.next_out=0,i.avail_out=o),(A=Ut.inflate(i,n))===Ht&&a&&((A=Ut.inflateSetDictionary(i,a))===Tt?A=Ut.inflate(i,n):A===Jt&&(A=Ht));i.avail_in>0&&A===Zt&&i.state.wrap>0&&0!==e[i.next_in];)Ut.inflateReset(i),A=Ut.inflate(i,n);switch(A){case Yt:case Jt:case Ht:case jt:return this.onEnd(A),this.ended=!0,!1}if(r=i.avail_out,i.next_out&&(0===i.avail_out||A===Zt))if("string"===this.options.to){var s=Pe(i.output,i.next_out),g=i.next_out-s,c=je(i.output,s);i.next_out=g,i.avail_out=o-g,g&&i.output.set(i.output.subarray(s,s+g),0),this.onData(c)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(A!==Tt||0!==r){if(A===Zt)return A=Ut.inflateEnd(this.strm),this.onEnd(A),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},Pt.prototype.onData=function(e){this.chunks.push(e)},Pt.prototype.onEnd=function(e){e===Tt&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Te(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Kt,Wt,Xt={Inflate:Pt,inflate:Vt,inflateRaw:function(e,t){return(t=t||{}).raw=!0,Vt(e,t)},ungzip:Vt,constants:K},qt={Deflate:ot.Deflate,deflate:ot.deflate,deflateRaw:ot.deflateRaw,gzip:ot.gzip,Inflate:Xt.Inflate,inflate:Xt.inflate,inflateRaw:Xt.inflateRaw,ungzip:Xt.ungzip,constants:K},zt=((Kt=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;if(Object(s.a)(this,e),t<0||t>9)throw new Error("Invalid gzip compression level, it should be between 0 and 9");this.level=t}return Object(g.a)(e,[{key:"encode",value:function(e){return qt.gzip(e,{level:this.level})}},{key:"decode",value:function(e,t){var A=qt.ungzip(e);return void 0!==t?(t.set(A),t):A}}],[{key:"fromConfig",value:function(t){return new e(t.level)}}]),e}()).codecId="gzip",Kt),$t=((Wt=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;if(Object(s.a)(this,e),t<-1||t>9)throw new Error("Invalid zlib compression level, it should be between -1 and 9");this.level=t}return Object(g.a)(e,[{key:"encode",value:function(e){return qt.deflate(e,{level:this.level})}},{key:"decode",value:function(e,t){var A=qt.inflate(e);return void 0!==t?(t.set(A),t):A}}],[{key:"fromConfig",value:function(t){return new e(t.level)}}]),e}()).codecId="zlib",Wt),eA="undefined"!==typeof e&&null!=e.versions&&null!=e.versions.node?function(e){return new Uint8Array(n.from(e,"base64"))}:function(){for(var e=new Uint8Array(128),t=0;t<64;t++)e[t<26?t+65:t<52?t+71:t<62?t-4:4*t-205]=t;return function(t){for(var A=t.length,n=new Uint8Array(3*(A-("="==t[A-1])-("="==t[A-2]))/4|0),r=0,i=0;r>4,n[i++]=a<<4|s>>2,n[i++]=s<<6|g}return n}}();function tA(e,t){return e({noInitialRun:!0,wasmBinary:eA(t)})}var AA,nA,rA=("undefined"!==typeof document&&document.currentScript&&document.currentScript.src,function(e){var t,A,n;e=e||{},t||(t="undefined"!==typeof e?e:{}),t.ready=new Promise((function(e,t){A=e,n=t}));var r,i={};for(r in t)t.hasOwnProperty(r)&&(i[r]=t[r]);var o,a="./this.program",s=t.print||console.log.bind(console),g=t.printErr||console.warn.bind(console);for(r in i)i.hasOwnProperty(r)&&(t[r]=i[r]);i=null,t.thisProgram&&(a=t.thisProgram),t.wasmBinary&&(o=t.wasmBinary),t.noExitRuntime&&t.noExitRuntime,"object"!==typeof WebAssembly&&T("no native wasm support detected");var c,u=!1,l="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0;function I(e,t,A){var n=t+A;for(A=t;e[A]&&!(A>=n);)++A;if(16(r=224==(240&r)?(15&r)<<12|i<<6|o:(7&r)<<18|i<<12|o<<6|63&e[t++])?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r))}}else n+=String.fromCharCode(r)}return n}var C,h,f,d,B,p,E,Q,y,v="undefined"!==typeof TextDecoder?new TextDecoder("utf-16le"):void 0;function m(e,t){for(var A=e>>1,n=A+t/2;!(A>=n)&&B[A];)++A;if(32<(A<<=1)-e&&v)return v.decode(f.subarray(e,A));for(A=0,n="";;){var r=d[e+2*A>>1];if(0==r||A==t/2)return n;++A,n+=String.fromCharCode(r)}}function b(e,t,A){if(void 0===A&&(A=2147483647),2>A)return 0;var n=t;A=(A-=2)<2*e.length?A/2:e.length;for(var r=0;r>1]=e.charCodeAt(r),t+=2;return d[t>>1]=0,t-n}function w(e){return 2*e.length}function S(e,t){for(var A=0,n="";!(A>=t/4);){var r=p[e+4*A>>2];if(0==r)break;++A,65536<=r?(r-=65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r)):n+=String.fromCharCode(r)}return n}function F(e,t,A){if(void 0===A&&(A=2147483647),4>A)return 0;var n=t;A=n+A-4;for(var r=0;r=i&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++r)),p[t>>2]=i,(t+=4)+4>A)break}return p[t>>2]=0,t-n}function R(e){for(var t=0,A=0;A=n&&++A,t+=4}return t}function D(e){C=e,t.HEAP8=h=new Int8Array(e),t.HEAP16=d=new Int16Array(e),t.HEAP32=p=new Int32Array(e),t.HEAPU8=f=new Uint8Array(e),t.HEAPU16=B=new Uint16Array(e),t.HEAPU32=E=new Uint32Array(e),t.HEAPF32=Q=new Float32Array(e),t.HEAPF64=y=new Float64Array(e)}var G=t.INITIAL_MEMORY||16777216;(c=t.wasmMemory?t.wasmMemory:new WebAssembly.Memory({initial:G/65536,maximum:32768}))&&(C=c.buffer),G=C.byteLength,D(C);var k,x=[],N=[],U=[],_=[];function M(){var e=t.preRun.shift();x.unshift(e)}var O=0,L=null;function T(e){throw t.onAbort&&t.onAbort(e),g(e),u=!0,e=new WebAssembly.RuntimeError("abort("+e+"). Build with -s ASSERTIONS=1 for more info."),n(e),e}function Z(e){var t=Y;return String.prototype.startsWith?t.startsWith(e):0===t.indexOf(e)}function H(){return Z("data:application/octet-stream;base64,")}t.preloadedImages={},t.preloadedAudios={};var Y="blosc_codec.wasm";if(!H()){var J=Y;Y=t.locateFile?t.locateFile(J,""):""+J}function j(){try{if(o)return new Uint8Array(o);throw"both async and sync fetching of the wasm failed"}catch(e){T(e)}}function P(e){for(;0>2]=e},this.X=function(e){p[this.N+0>>2]=e},this.Y=function(){p[this.N+4>>2]=0},this.W=function(){h[this.N+12>>0]=0},this.Z=function(){h[this.N+13>>0]=0},this.V=function(e,t){this.$(e),this.X(t),this.Y(),this.W(),this.Z()}}function K(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+e)}}var W=void 0;function X(e){for(var t="";f[e];)t+=W[f[e++]];return t}var q={},z={},$={};function ee(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return 48<=t&&57>=t?"_"+e:e}function te(e,t){return e=ee(e),new Function("body","return function "+e+'() {\n "use strict"; return body.apply(this, arguments);\n};\n')(t)}function Ae(e){var t=Error,A=te(e,(function(t){this.name=e,this.message=t,void 0!==(t=Error(t).stack)&&(this.stack=this.toString()+"\n"+t.replace(/^Error(:[^\n]*)?\n/,""))}));return A.prototype=Object.create(t.prototype),A.prototype.constructor=A,A.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message},A}var ne=void 0;function re(e){throw new ne(e)}var ie=void 0;function oe(e,t,A){if(A=A||{},!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");var n=t.name;if(e||re('type "'+n+'" must have a positive integer typeid pointer'),z.hasOwnProperty(e)){if(A.U)return;re("Cannot register type '"+n+"' twice")}z[e]=t,delete $[e],q.hasOwnProperty(e)&&(t=q[e],delete q[e],t.forEach((function(e){e()})))}var ae=[],se=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function ge(e){4>2])}function le(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function Ie(e,t){switch(t){case 2:return function(e){return this.fromWireType(Q[e>>2])};case 3:return function(e){return this.fromWireType(y[e>>3])};default:throw new TypeError("Unknown float type: "+e)}}function Ce(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function he(e,A,n){t.hasOwnProperty(e)?((void 0===n||void 0!==t[e].L&&void 0!==t[e].L[n])&&re("Cannot register public name '"+e+"' twice"),function(e,A){var n=t;if(void 0===n[e].L){var r=n[e];n[e]=function(){return n[e].L.hasOwnProperty(arguments.length)||re("Function '"+A+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+n[e].L+")!"),n[e].L[arguments.length].apply(this,arguments)},n[e].L=[],n[e].L[r.S]=r}}(e,e),t.hasOwnProperty(n)&&re("Cannot register multiple overloads of a function with the same number of arguments ("+n+")!"),t[e].L[n]=A):(t[e]=A,void 0!==n&&(t[e].ba=n))}function fe(e,A){var n=-1!=(e=X(e)).indexOf("j")?function(e,A){0<=e.indexOf("j")||T("Assertion failed: getDynCaller should only be called with i64 sigs");var n=[];return function(){n.length=arguments.length;for(var r=0;r>1]}:function(e){return B[e>>1]};case 2:return A?function(e){return p[e>>2]}:function(e){return E[e>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var Ee={};function Qe(){if(!ye){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"===typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:a||"./this.program"};for(e in Ee)t[e]=Ee[e];var A=[];for(e in t)A.push(e+"="+t[e]);ye=A}return ye}for(var ye,ve=[null,[],[]],me=Array(256),be=0;256>be;++be)me[be]=String.fromCharCode(be);W=me,ne=t.BindingError=Ae("BindingError"),ie=t.InternalError=Ae("InternalError"),t.count_emval_handles=function(){for(var e=0,t=5;t>i])},M:null})},y:function(e,t){oe(e,{name:t=X(t),fromWireType:function(e){var t=se[e].value;return ge(e),t},toWireType:function(e,t){return ce(t)},argPackAdvance:8,readValueFromPointer:ue,M:null})},h:function(e,t,A){A=K(A),oe(e,{name:t=X(t),fromWireType:function(e){return e},toWireType:function(e,t){if("number"!==typeof t&&"boolean"!==typeof t)throw new TypeError('Cannot convert "'+le(t)+'" to '+this.name);return t},argPackAdvance:8,readValueFromPointer:Ie(t,A),M:null})},e:function(e,A,n,r,i,o){var a=function(e,t){for(var A=[],n=0;n>2)+n]);return A}(A,n);e=X(e),i=fe(r,i),he(e,(function(){!function(e,t){var A=[],n={};throw t.forEach((function e(t){n[t]||z[t]||($[t]?$[t].forEach(e):(A.push(t),n[t]=!0))})),new de(e+": "+A.map(Be).join([", "]))}("Cannot call "+e+" due to unbound types",a)}),A-1),function(e,t){function A(e){if((e=t(e)).length!==n.length)throw new ie("Mismatched type converter count");for(var A=0;Ag&&re("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var c=null!==n[1]&&!1,u=!1,l=1;l>>a}}var s=-1!=t.indexOf("unsigned");oe(e,{name:t,fromWireType:i,toWireType:function(e,A){if("number"!==typeof A&&"boolean"!==typeof A)throw new TypeError('Cannot convert "'+le(A)+'" to '+this.name);if(Ar)throw new TypeError('Passing a number "'+le(A)+'" from JS side to C/C++ side to an argument of type "'+t+'", which is outside the valid range ['+n+", "+r+"]!");return s?A>>>0:0|A},argPackAdvance:8,readValueFromPointer:pe(t,o,0!==n),M:null})},b:function(e,t,A){function n(e){var t=E;return new r(C,t[1+(e>>=2)],t[e])}var r=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];oe(e,{name:A=X(A),fromWireType:n,argPackAdvance:8,readValueFromPointer:n},{U:!0})},i:function(e,t){var A="std::string"===(t=X(t));oe(e,{name:t,fromWireType:function(e){var t=E[e>>2];if(A)for(var n=e+4,r=0;r<=t;++r){var i=e+4+r;if(r==t||0==f[i]){if(n=n?I(f,n,i-n):"",void 0===o)var o=n;else o+=String.fromCharCode(0),o+=n;n=i+1}}else{for(o=Array(t),r=0;r=n&&(n=65536+((1023&n)<<10)|1023&t.charCodeAt(++A)),127>=n?++e:e=2047>=n?e+2:65535>=n?e+3:e+4}return e}:function(){return t.length})(),i=Re(4+r+1);if(E[i>>2]=r,A&&n)!function(e,t,A){var n=f;if(0=i&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++r)),127>=i){if(t>=A)break;n[t++]=i}else{if(2047>=i){if(t+1>=A)break;n[t++]=192|i>>6}else{if(65535>=i){if(t+2>=A)break;n[t++]=224|i>>12}else{if(t+3>=A)break;n[t++]=240|i>>18,n[t++]=128|i>>12&63}n[t++]=128|i>>6&63}n[t++]=128|63&i}}n[t]=0}}(t,i+4,r+1);else if(n)for(n=0;n>2],i=o(),s=e+4,g=0;g<=r;++g){var c=e+4+g*t;g!=r&&0!=i[c>>a]||(s=n(s,c-s),void 0===A?A=s:(A+=String.fromCharCode(0),A+=s),s=c+t)}return De(e),A},toWireType:function(e,n){"string"!==typeof n&&re("Cannot pass non-string to C++ string type "+A);var o=i(n),s=Re(4+o+t);return E[s>>2]=o>>a,r(n,s+4,o+t),null!==e&&e.push(De,s),s},argPackAdvance:8,readValueFromPointer:ue,M:function(e){De(e)}})},A:function(e,t){oe(e,{aa:!0,name:t=X(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},n:ge,x:function(e){4>>=0;var t=f.length;if(2147483648=A;A*=2){var n=t*(1+.2/A);n=Math.min(n,e+100663296),0<(n=Math.max(16777216,e,n))%65536&&(n+=65536-n%65536);e:{try{c.grow(Math.min(2147483648,n)-C.byteLength+65535>>>16),D(c.buffer);var r=1;break e}catch(i){}r=void 0}if(r)return!0}return!1},u:function(e,t){var A=0;return Qe().forEach((function(n,r){var i=t+A;for(r=p[e+4*r>>2]=i,i=0;i>0]=n.charCodeAt(i);h[r>>0]=0,A+=n.length+1})),0},v:function(e,t){var A=Qe();p[e>>2]=A.length;var n=0;return A.forEach((function(e){n+=e.length+1})),p[t>>2]=n,0},w:function(){return 0},q:function(){},g:function(e,t,A,n){for(var r=0,i=0;i>2],a=p[t+(8*i+4)>>2],c=0;c>2]=r,0},a:c,l:function(){return 0},k:function(){return 0},j:function(){},B:function(){return 6},m:function(){},f:function(){}};!function(){function e(e){t.asm=e.exports,k=t.asm.D,O--,t.monitorRunDependencies&&t.monitorRunDependencies(O),0==O&&L&&(e=L,L=null,e())}function A(t){e(t.instance)}function r(e){return Promise.resolve().then(j).then((function(e){return WebAssembly.instantiate(e,i)})).then(e,(function(e){g("failed to asynchronously prepare wasm: "+e),T(e)}))}var i={a:we};if(O++,t.monitorRunDependencies&&t.monitorRunDependencies(O),t.instantiateWasm)try{return t.instantiateWasm(i,e)}catch(a){return g("Module.instantiateWasm callback failed with error: "+a),!1}(o||"function"!==typeof WebAssembly.instantiateStreaming||H()||Z("file://")||"function"!==typeof fetch?r(A):fetch(Y,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,i).then(A,(function(e){return g("wasm streaming compile failed: "+e),g("falling back to ArrayBuffer instantiation"),r(A)}))}))).catch(n)}();var Se,Fe=t.___wasm_call_ctors=function(){return(Fe=t.___wasm_call_ctors=t.asm.E).apply(null,arguments)},Re=t._malloc=function(){return(Re=t._malloc=t.asm.F).apply(null,arguments)},De=t._free=function(){return(De=t._free=t.asm.G).apply(null,arguments)},Ge=t.___getTypeName=function(){return(Ge=t.___getTypeName=t.asm.H).apply(null,arguments)};function ke(){function e(){if(!Se&&(Se=!0,t.calledRun=!0,!u)){if(P(N),P(U),A(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();_.unshift(e)}P(_)}}if(!(00&&void 0!==arguments[0]?arguments[0]:5,A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"lz4",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:nA.SHUFFLE,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(Object(s.a)(this,e),t<0||t>9)throw new Error("Invalid compression level: '".concat(t,"'. It should be between 0 and 9"));if(!aA.has(A))throw new Error("Invalid compressor '".concat(A,"'. Valid compressors include\n 'blosclz', 'lz4', 'lz4hc','snappy', 'zlib', 'zstd'."));if(n<-1||n>2)throw new Error("Invalid shuffle ".concat(n,". Must be one of 0 (NOSHUFFLE),\n 1 (SHUFFLE), 2 (BITSHUFFLE), -1 (AUTOSHUFFLE)."));this.blocksize=r,this.clevel=t,this.cname=A,this.shuffle=n}return Object(g.a)(e,[{key:"encode",value:function(){var e=Object(a.a)(o.a.mark((function e(t){var A,n,r;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return oA||(oA=tA(rA,iA)),e.next=3,oA;case 3:return A=e.sent,n=A.compress(t,this.cname,this.clevel,this.shuffle,this.blocksize),r=new Uint8Array(n),A.free_result(),e.abrupt("return",r);case 8:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"decode",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A){var n,r,i;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return oA||(oA=tA(rA,iA)),e.next=3,oA;case 3:if(n=e.sent,r=n.decompress(t),i=new Uint8Array(r),n.free_result(),void 0===A){e.next=10;break}return A.set(i),e.abrupt("return",A);case 10:return e.abrupt("return",i);case 11:case"end":return e.stop()}}),e)})));return function(t,A){return e.apply(this,arguments)}}()}],[{key:"fromConfig",value:function(t){var A=t.blocksize;return new e(t.clevel,t.cname,t.shuffle,A)}}]),e}()).codecId="blosc",AA.COMPRESSORS=Object(r.a)(aA),AA.NOSHUFFLE=nA.NOSHUFFLE,AA.SHUFFLE=nA.SHUFFLE,AA.BITSHUFFLE=nA.BITSHUFFLE,AA.AUTOSHUFFLE=nA.AUTOSHUFFLE,AA);Object(c.d)($t.codecId,(function(){return $t})),Object(c.d)(zt.codecId,(function(){return zt})),Object(c.d)(sA.codecId,(function(){return sA}))}).call(this,A(90),A(188).Buffer)},function(e,t,A){"use strict";A.d(t,"d",(function(){return r})),A.d(t,"e",(function(){return i})),A.d(t,"c",(function(){return o})),A.d(t,"b",(function(){return a})),A.d(t,"a",(function(){return s}));var n=A(85);function r(e){return"undefined"!==typeof WebGLRenderingContext&&e instanceof WebGLRenderingContext||("undefined"!==typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext||Boolean(e&&Number.isFinite(e._version)))}function i(e){return"undefined"!==typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext||Boolean(e&&2===e._version)}function o(e){return i(e)?e:null}function a(e){return Object(n.a)(r(e),"Invalid WebGLRenderingContext"),e}function s(e){return Object(n.a)(i(e),"Requires WebGL2"),e}},function(e,t,A){"use strict";A.d(t,"a",(function(){return a}));var n=A(393),r=A(395),i=A(203),o=A(394);function a(e){return Object(n.a)(e)||Object(r.a)(e)||Object(i.a)(e)||Object(o.a)()}},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=A(993);Object.defineProperty(t,"Alpha",{enumerable:!0,get:function(){return u(n).default}});var r=A(488);Object.defineProperty(t,"Checkboard",{enumerable:!0,get:function(){return u(r).default}});var i=A(996);Object.defineProperty(t,"EditableInput",{enumerable:!0,get:function(){return u(i).default}});var o=A(997);Object.defineProperty(t,"Hue",{enumerable:!0,get:function(){return u(o).default}});var a=A(999);Object.defineProperty(t,"Raised",{enumerable:!0,get:function(){return u(a).default}});var s=A(1004);Object.defineProperty(t,"Saturation",{enumerable:!0,get:function(){return u(s).default}});var g=A(617);Object.defineProperty(t,"ColorWrap",{enumerable:!0,get:function(){return u(g).default}});var c=A(1009);function u(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"Swatch",{enumerable:!0,get:function(){return u(c).default}})},function(e,t,A){"use strict";A.r(t);var n=A(650),r=A(648),i=A(269),o=A(649),a=A(651),s=A(388),g=A(387),c=A(1),u=A(4),l=A(9),I=A(10),C=A(1256),h=A(36),f=function(e){Object(l.a)(A,e);var t=Object(I.a)(A);function A(){return Object(c.a)(this,A),t.apply(this,arguments)}return Object(u.a)(A,[{key:"getGeometry",value:function(e){return new C.a}},{key:"draw",value:function(e){var t=e.uniforms,A=this.props,n=A.elevationScale,r=A.extruded,i=A.offset,o=A.coverage,a=A.cellSize,s=A.angle,g=A.radiusUnits;this.state.model.setUniforms(t).setUniforms({radius:a/2,radiusUnits:h.d[g],angle:s,offset:i,extruded:r,coverage:o,elevationScale:n,edgeDistance:1,isWireframe:!1}).draw()}}]),A}(g.a);f.layerName="GridCellLayer",f.defaultProps={cellSize:{type:"number",min:0,value:1e3},offset:{type:"array",min:0,value:[1,1]}};var d=A(268),B=A(580),p=A(646),E=A(386),Q=A(267),y=A(391),v=A(389);A.d(t,"ArcLayer",(function(){return n.a})),A.d(t,"BitmapLayer",(function(){return r.a})),A.d(t,"IconLayer",(function(){return i.a})),A.d(t,"LineLayer",(function(){return o.a})),A.d(t,"PointCloudLayer",(function(){return a.a})),A.d(t,"ScatterplotLayer",(function(){return s.a})),A.d(t,"ColumnLayer",(function(){return g.a})),A.d(t,"GridCellLayer",(function(){return f})),A.d(t,"PathLayer",(function(){return d.a})),A.d(t,"PolygonLayer",(function(){return B.a})),A.d(t,"GeoJsonLayer",(function(){return p.a})),A.d(t,"TextLayer",(function(){return E.a})),A.d(t,"SolidPolygonLayer",(function(){return Q.a})),A.d(t,"_MultiIconLayer",(function(){return y.a})),A.d(t,"_TextBackgroundLayer",(function(){return v.a}))},function(e,t,A){"use strict";var n={};function r(e){var t=e&&e.lastIndexOf("/");return t>=0?e.substr(0,t):""}function i(){for(var e=arguments.length,t=new Array(e),A=0;A0&&r[e]&&(t=r[e]).call.apply(t,arguments)}},function(e,t,A){"use strict";A.d(t,"a",(function(){return n})),A.d(t,"b",(function(){return r}));var n={NO_STATE:"Awaiting state",MATCHED:"Matched. State transferred from previous layer",INITIALIZED:"Initialized",AWAITING_GC:"Discarded. Awaiting garbage collection",AWAITING_FINALIZATION:"No longer matched. Awaiting garbage collection",FINALIZED:"Finalized! Awaiting garbage collection"},r={COMPONENT:Symbol.for("component"),ASYNC_DEFAULTS:Symbol.for("asyncPropDefaults"),ASYNC_ORIGINAL:Symbol.for("asyncPropOriginal"),ASYNC_RESOLVED:Symbol.for("asyncPropResolved")}},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getIntermediatePosition=function(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]},t.GeoJsonEditMode=void 0;var n=g(A(1154)),r=g(A(376)),i=g(A(1155)),o=g(A(1150)),a=A(99),s=A(158);function g(e){return e&&e.__esModule?e:{default:e}}function c(e){return function(e){if(Array.isArray(e))return l(e)}(e)||function(e){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||u(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e,t){if(e){if("string"===typeof e)return l(e,t);var A=Object.prototype.toString.call(e).slice(8,-1);return"Object"===A&&e.constructor&&(A=e.constructor.name),"Map"===A||"Set"===A?Array.from(A):"Arguments"===A||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(A)?l(e,t):void 0}}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var A=0,n=new Array(t);A=e.length?{done:!0}:{done:!1,value:e[t++]}},e:function(e){throw e},f:A}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,r,i=!0,o=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return i=e.done,e},e:function(e){o=!0,r=e},f:function(){try{i||null==n.return||n.return()}finally{if(o)throw r}}}}(n);try{for(a.s();!(A=a.n()).done;){var g=A.value,c=g.properties,l=g.geometry;r=r.addFeature({type:"Feature",properties:c,geometry:l}),o.push(i+o.length)}}catch(I){a.e(I)}finally{a.f()}return{updatedData:r.getObject(),editType:"addFeature",editContext:{featureIndexes:o}}}},{key:"getAddFeatureOrBooleanPolygonAction",value:function(e,t){var A=e,o=this.getSelectedFeature(t),a=t.modeConfig;if(a&&a.booleanOperation){if(!o||"Polygon"!==o.geometry.type&&"MultiPolygon"!==o.geometry.type)return console.warn("booleanOperation only supported for single Polygon or MultiPolygon selection"),null;var g,c="Feature"===A.type?A:{type:"Feature",geometry:A};if("union"===a.booleanOperation)g=(0,n.default)(o,c);else if("difference"===a.booleanOperation)g=(0,r.default)(o,c);else{if("intersection"!==a.booleanOperation)return console.warn("Invalid booleanOperation ".concat(a.booleanOperation)),null;g=(0,i.default)(o,c)}if(!g)return console.warn("Canceling edit. Boolean operation erased entire polygon."),null;var u=t.selectedIndexes[0];return{updatedData:new s.ImmutableFeatureCollection(t.data).replaceGeometry(u,g.geometry).getObject(),editType:"unionGeometry",editContext:{featureIndexes:[u]}}}return this.getAddFeatureAction(e,t.data)}},{key:"createTentativeFeature",value:function(e){return null}},{key:"handleClick",value:function(e,t){}},{key:"handlePointerMove",value:function(e,t){var A=this.createTentativeFeature(t);A&&t.onEdit({updatedData:t.data,editType:"updateTentativeFeature",editContext:{feature:A}})}},{key:"handleStartDragging",value:function(e,t){}},{key:"handleStopDragging",value:function(e,t){}},{key:"handleDragging",value:function(e,t){}},{key:"handleKeyUp",value:function(e,t){"Escape"===e.key&&(this.resetClickSequence(),t.onEdit({updatedData:t.data,editType:"cancelFeature",editContext:{}}))}}])&&I(t.prototype,A),g&&I(t,g),e}();t.GeoJsonEditMode=f},function(e,t,A){"use strict";A.d(t,"a",(function(){return d}));var n=A(1),r=A(4),i=A(24),o=A(9),a=A(10),s=A(92),g=A(139),c=A(119),u=A(18),l=A(26),I=A(323),C={offset:"accessor.offset",stride:"accessor.stride",type:"accessor.type",size:"accessor.size",divisor:"accessor.divisor",normalized:"accessor.normalized",integer:"accessor.integer",instanced:"accessor.divisor",isInstanced:"accessor.divisor"},h={removedProps:{},replacedProps:{bytes:"byteLength"},deprecatedProps:C},f={removedProps:C},d=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(e){var r,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object(n.a)(this,A),(r=t.call(this,e,o)).stubRemovedMethods("Buffer","v6.0",["layout","setLayout","getIndexedParameter"]),r.target=o.target||(r.gl.webgl2?36662:34962),r.initialize(o),Object.seal(Object(i.a)(r)),r}return Object(r.a)(A,[{key:"getElementCount",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.accessor;return Math.round(this.byteLength/g.a.getBytesPerElement(e))}},{key:"getVertexCount",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.accessor;return Math.round(this.byteLength/g.a.getBytesPerVertex(e))}},{key:"initialize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ArrayBuffer.isView(e)&&(e={data:e}),Number.isFinite(e)&&(e={byteLength:e}),e=Object(I.a)("Buffer",e,h),this.usage=e.usage||35044,this.debugData=null,this.setAccessor(Object.assign({},e,e.accessor)),e.data?this._setData(e.data,e.offset,e.byteLength):this._setByteLength(e.byteLength||0),this}},{key:"setProps",value:function(e){return"accessor"in(e=Object(I.a)("Buffer",e,f))&&this.setAccessor(e.accessor),this}},{key:"setAccessor",value:function(e){return delete(e=Object.assign({},e)).buffer,this.accessor=new g.a(e),this}},{key:"reallocate",value:function(e){return e>this.byteLength?(this._setByteLength(e),!0):(this.bytesUsed=e,!1)}},{key:"setData",value:function(e){return this.initialize(e)}},{key:"subData",value:function(e){ArrayBuffer.isView(e)&&(e={data:e});var t=e,A=t.data,n=t.offset,r=void 0===n?0:n,i=t.srcOffset,o=void 0===i?0:i,a=e.byteLength||e.length;Object(l.a)(A);var s=this.gl.webgl2?36663:this.target;return this.gl.bindBuffer(s,this.handle),0!==o||void 0!==a?(Object(u.a)(this.gl),this.gl.bufferSubData(this.target,r,A,o,a)):this.gl.bufferSubData(s,r,A),this.gl.bindBuffer(s,null),this.debugData=null,this._inferType(A),this}},{key:"copyData",value:function(e){var t=e.sourceBuffer,A=e.readOffset,n=void 0===A?0:A,r=e.writeOffset,i=void 0===r?0:r,o=e.size,a=this.gl;return Object(u.a)(a),a.bindBuffer(36662,t.handle),a.bindBuffer(36663,this.handle),a.copyBufferSubData(36662,36663,n,i,o),a.bindBuffer(36662,null),a.bindBuffer(36663,null),this.debugData=null,this}},{key:"getData",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.dstData,A=void 0===t?null:t,n=e.srcByteOffset,r=void 0===n?0:n,i=e.dstOffset,o=void 0===i?0:i,a=e.length,s=void 0===a?0:a;Object(u.a)(this.gl);var g,I,C=Object(c.c)(this.accessor.type||5126,{clamped:!1}),h=this._getAvailableElementCount(r),f=o;A?g=(I=A.length)-f:I=f+(g=Math.min(h,s||h));var d=Math.min(h,g);return s=s||d,Object(l.a)(s<=d),A=A||new C(I),this.gl.bindBuffer(36662,this.handle),this.gl.getBufferSubData(36662,r,A,o,s),this.gl.bindBuffer(36662,null),A}},{key:"bind",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.target,A=void 0===t?this.target:t,n=e.index,r=void 0===n?this.accessor&&this.accessor.index:n,i=e.offset,o=void 0===i?0:i,a=e.size;return 35345===A||35982===A?void 0!==a?this.gl.bindBufferRange(A,r,this.handle,o,a):(Object(l.a)(0===o),this.gl.bindBufferBase(A,r,this.handle)):this.gl.bindBuffer(A,this.handle),this}},{key:"unbind",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.target,A=void 0===t?this.target:t,n=e.index,r=void 0===n?this.accessor&&this.accessor.index:n,i=35345===A||35982===A;return i?this.gl.bindBufferBase(A,r,null):this.gl.bindBuffer(A,null),this}},{key:"getDebugData",value:function(){return this.debugData?{data:this.debugData,changed:!1}:(this.debugData=this.getData({length:Math.min(10,this.byteLength)}),{data:this.debugData,changed:!0})}},{key:"invalidateDebugData",value:function(){this.debugData=null}},{key:"_setData",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.byteLength+t;Object(l.a)(ArrayBuffer.isView(e)),this._trackDeallocatedMemory();var n=this._getTarget();this.gl.bindBuffer(n,this.handle),this.gl.bufferData(n,A,this.usage),this.gl.bufferSubData(n,t,e),this.gl.bindBuffer(n,null),this.debugData=e.slice(0,10),this.bytesUsed=A,this._trackAllocatedMemory(A);var r=Object(c.b)(e);return Object(l.a)(r),this.setAccessor(new g.a(this.accessor,{type:r})),this}},{key:"_setByteLength",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.usage;Object(l.a)(e>=0),this._trackDeallocatedMemory();var A=e;0===e&&(A=new Float32Array(0));var n=this._getTarget();return this.gl.bindBuffer(n,this.handle),this.gl.bufferData(n,A,t),this.gl.bindBuffer(n,null),this.usage=t,this.debugData=null,this.bytesUsed=e,this._trackAllocatedMemory(e),this}},{key:"_getTarget",value:function(){return this.gl.webgl2?36663:this.target}},{key:"_getAvailableElementCount",value:function(e){var t=e/Object(c.c)(this.accessor.type||5126,{clamped:!1}).BYTES_PER_ELEMENT;return this.getElementCount()-t}},{key:"_inferType",value:function(e){this.accessor.type||this.setAccessor(new g.a(this.accessor,{type:Object(c.b)(e)}))}},{key:"_createHandle",value:function(){return this.gl.createBuffer()}},{key:"_deleteHandle",value:function(){this.gl.deleteBuffer(this.handle),this._trackDeallocatedMemory()}},{key:"_getParameter",value:function(e){this.gl.bindBuffer(this.target,this.handle);var t=this.gl.getBufferParameter(this.target,e);return this.gl.bindBuffer(this.target,null),t}},{key:"setByteLength",value:function(e){return u.k.deprecated("setByteLength","reallocate")(),this.reallocate(e)}},{key:"updateAccessor",value:function(e){return u.k.deprecated("updateAccessor(...)","setAccessor(new Accessor(buffer.accessor, ...)")(),this.accessor=new g.a(this.accessor,e),this}},{key:"type",get:function(){return u.k.deprecated("Buffer.type","Buffer.accessor.type")(),this.accessor.type}},{key:"bytes",get:function(){return u.k.deprecated("Buffer.bytes","Buffer.byteLength")(),this.byteLength}}]),A}(s.a)},function(e,t,A){"use strict";var n=Object.freeze({OUTSIDE:-1,INTERSECTING:0,INSIDE:1}),r=A(1),i=A(4),o=A(9),a=A(10),s=(A(91),A(11));function g(e,t){if(!e)throw new Error("math.gl assertion ".concat(t))}Math.PI,Math.PI;var c={};function u(e){return Math.round(e/c.EPSILON)*c.EPSILON}function l(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.precision,n=void 0===A?c.precision||4:A;return e=u(e),"".concat(parseFloat(e.toPrecision(n)))}function I(e){return Array.isArray(e)||ArrayBuffer.isView(e)&&!(e instanceof DataView)}function C(e,t,A){var n=c.EPSILON;A&&(c.EPSILON=A);try{if(e===t)return!0;if(I(e)&&I(t)){if(e.length!==t.length)return!1;for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:0,A=0;A0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,A=0;A0?", ":"")+l(this[A],e);return"".concat(e.printTypes?this.constructor.name:"","[").concat(t,"]")}},{key:"equals",value:function(e){if(!e||this.length!==e.length)return!1;for(var t=0;t2&&void 0!==arguments[2]?arguments[2]:"";if(c.debug&&!f(e,t))throw new Error("math.gl: ".concat(A," some fields set to invalid numbers'"));return e}var p={};function E(e,t){p[e]||(p[e]=!0,console.warn("".concat(e," has been removed in version ").concat(t,", see upgrade guide for more information")))}var Q=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(){return Object(r.a)(this,A),t.apply(this,arguments)}return Object(i.a)(A,[{key:"copy",value:function(e){return g(!1),this}},{key:"len",value:function(){return Math.sqrt(this.lengthSquared())}},{key:"magnitude",value:function(){return this.len()}},{key:"lengthSquared",value:function(){for(var e=0,t=0;t=0&&e=0&&e0&&void 0!==arguments[0]?arguments[0]:0,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return Object(r.a)(this,A),e=t.call(this,-0,-0,-0),1===arguments.length&&I(n)?e.copy(n):(c.debug&&(d(n),d(i),d(o)),e[0]=n,e[1]=i,e[2]=o),e}return Object(i.a)(A,null,[{key:"ZERO",get:function(){return b.ZERO=b.ZERO||Object.freeze(new A(0,0,0,0))}}]),Object(i.a)(A,[{key:"set",value:function(e,t,A){return this[0]=e,this[1]=t,this[2]=A,this.check()}},{key:"copy",value:function(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this.check()}},{key:"fromObject",value:function(e){return c.debug&&(d(e.x),d(e.y),d(e.z)),this[0]=e.x,this[1]=e.y,this[2]=e.z,this.check()}},{key:"toObject",value:function(e){return e.x=this[0],e.y=this[1],e.z=this[2],e}},{key:"angle",value:function(e){return y.a(this,e)}},{key:"cross",value:function(e){return y.c(this,this,e),this.check()}},{key:"rotateX",value:function(e){var t=e.radians,A=e.origin,n=void 0===A?m:A;return y.j(this,this,n,t),this.check()}},{key:"rotateY",value:function(e){var t=e.radians,A=e.origin,n=void 0===A?m:A;return y.k(this,this,n,t),this.check()}},{key:"rotateZ",value:function(e){var t=e.radians,A=e.origin,n=void 0===A?m:A;return y.l(this,this,n,t),this.check()}},{key:"transform",value:function(e){return this.transformAsPoint(e)}},{key:"transformAsPoint",value:function(e){return y.p(this,this,e),this.check()}},{key:"transformAsVector",value:function(e){return v(this,this,e),this.check()}},{key:"transformByMatrix3",value:function(e){return y.o(this,this,e),this.check()}},{key:"transformByMatrix2",value:function(e){return function(e,t,A){var n=t[0],r=t[1];e[0]=A[0]*n+A[2]*r,e[1]=A[1]*n+A[3]*r,e[2]=t[2]}(this,this,e),this.check()}},{key:"transformByQuaternion",value:function(e){return y.q(this,this,e),this.check()}},{key:"ELEMENTS",get:function(){return 3}},{key:"z",get:function(){return this[2]},set:function(e){this[2]=d(e)}}]),A}(Q),S=new w,F=new w,R=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0,0],A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0,0,0],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;Object(r.a)(this,e),n=n||S.copy(t).add(A).scale(.5),this.center=new w(n),this.halfDiagonal=new w(A).subtract(this.center),this.minimum=new w(t),this.maximum=new w(A)}return Object(i.a)(e,[{key:"clone",value:function(){return new e(this.minimum,this.maximum,this.center)}},{key:"equals",value:function(e){return this===e||Boolean(e)&&this.minimum.equals(e.minimum)&&this.maximum.equals(e.maximum)}},{key:"transform",value:function(e){return this.center.transformAsPoint(e),this.halfDiagonal.transform(e),this.minimum.transform(e),this.maximum.transform(e),this}},{key:"intersectPlane",value:function(e){var t=this.halfDiagonal,A=F.from(e.normal),r=t.x*Math.abs(A.x)+t.y*Math.abs(A.y)+t.z*Math.abs(A.z),i=this.center.dot(A)+e.distance;return i-r>0?n.INSIDE:i+r<0?n.OUTSIDE:n.INTERSECTING}},{key:"distanceTo",value:function(e){return Math.sqrt(this.distanceSquaredTo(e))}},{key:"distanceSquaredTo",value:function(e){var t,A=S.from(e).subtract(this.center),n=this.halfDiagonal,r=0;return(t=Math.abs(A.x)-n.x)>0&&(r+=t*t),(t=Math.abs(A.y)-n.y)>0&&(r+=t*t),(t=Math.abs(A.z)-n.z)>0&&(r+=t*t),r}}]),e}(),D=A(27),G=new w,k=new w,x=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0,0],A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;Object(r.a)(this,e),this.radius=-0,this.center=new w,this.fromCenterRadius(t,A)}return Object(i.a)(e,[{key:"fromCenterRadius",value:function(e,t){return this.center.from(e),this.radius=t,this}},{key:"fromCornerPoints",value:function(e,t){return t=G.from(t),this.center=(new w).from(e).add(t).scale(.5),this.radius=this.center.distance(t),this}},{key:"equals",value:function(e){return this===e||Boolean(e)&&this.center.equals(e.center)&&this.radius===e.radius}},{key:"clone",value:function(){return new e(this.center,this.radius)}},{key:"union",value:function(e){var t=this.center,A=this.radius,n=e.center,r=e.radius,i=G.copy(n).subtract(t),o=i.magnitude();if(A>=o+r)return this.clone();if(r>=o+A)return e.clone();var a=.5*(A+o+r);return k.copy(i).scale((-A+a)/o).add(t),this.center.copy(k),this.radius=a,this}},{key:"expand",value:function(e){var t=(e=G.from(e)).subtract(this.center).magnitude();return t>this.radius&&(this.radius=t),this}},{key:"transform",value:function(e){this.center.transform(e);var t=D.d(G,e);return this.radius=Math.max(t[0],Math.max(t[1],t[2]))*this.radius,this}},{key:"distanceSquaredTo",value:function(e){var t=this.distanceTo(e);return t*t}},{key:"distanceTo",value:function(e){var t=(e=G.from(e)).subtract(this.center);return Math.max(0,t.len()-this.radius)}},{key:"intersectPlane",value:function(e){var t=this.center,A=this.radius,r=e.normal.dot(t)+e.distance;return r<-A?n.OUTSIDE:r1&&void 0!==arguments[1]?arguments[1]:new Array(this.RANK).fill(-0),A=e*this.RANK,n=0;n0&&void 0!==arguments[0]?arguments[0]:0,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;return Object(r.a)(this,A),e=t.call(this,-0,-0,-0,-0),Array.isArray(n)&&1===arguments.length?e.copy(n):e.set(n,i,o,a),e}return Object(i.a)(A,[{key:"copy",value:function(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this.check()}},{key:"set",value:function(e,t,A,n){return this[0]=e,this[1]=t,this[2]=A,this[3]=n,this.check()}},{key:"fromMatrix3",value:function(e){return H.e(this,e),this.check()}},{key:"identity",value:function(){return H.f(this),this.check()}},{key:"fromAxisRotation",value:function(e,t){return H.p(this,e,t),this.check()}},{key:"setAxisAngle",value:function(e,t){return this.fromAxisRotation(e,t)}},{key:"len",value:function(){return H.h(this)}},{key:"lengthSquared",value:function(){return H.r(this)}},{key:"dot",value:function(e,t){if(void 0!==t)throw new Error("Quaternion.dot only takes one argument");return H.d(this,e)}},{key:"rotationTo",value:function(e,t){return H.n(this,e,t),this.check()}},{key:"add",value:function(e,t){if(void 0!==t)throw new Error("Quaternion.add only takes one argument");return H.a(this,this,e),this.check()}},{key:"calculateW",value:function(){return H.b(this,this),this.check()}},{key:"conjugate",value:function(){return H.c(this,this),this.check()}},{key:"invert",value:function(){return H.g(this,this),this.check()}},{key:"lerp",value:function(e,t,A){return H.i(this,e,t,A),this.check()}},{key:"multiplyRight",value:function(e,t){return g(!t),H.j(this,this,e),this.check()}},{key:"multiplyLeft",value:function(e,t){return g(!t),H.j(this,e,this),this.check()}},{key:"normalize",value:function(){var e=this.len(),t=e>0?1/e:0;return this[0]=this[0]*t,this[1]=this[1]*t,this[2]=this[2]*t,this[3]=this[3]*t,0===e&&(this[3]=1),this.check()}},{key:"rotateX",value:function(e){return H.k(this,this,e),this.check()}},{key:"rotateY",value:function(e){return H.l(this,this,e),this.check()}},{key:"rotateZ",value:function(e){return H.m(this,this,e),this.check()}},{key:"scale",value:function(e){return H.o(this,this,e),this.check()}},{key:"slerp",value:function(e,t,A){switch(arguments.length){case 1:var n=arguments[0],r=n.start;e=void 0===r?J:r,t=n.target,A=n.ratio;break;case 2:var i=Array.prototype.slice.call(arguments);t=i[0],A=i[1],e=this}return H.q(this,e,t,A),this.check()}},{key:"transformVector4",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;return Y.o(t,e,this),B(t,4)}},{key:"lengthSq",value:function(){return this.lengthSquared()}},{key:"setFromAxisAngle",value:function(e,t){return this.setAxisAngle(e,t)}},{key:"premultiply",value:function(e,t){return this.multiplyLeft(e,t)}},{key:"multiply",value:function(e,t){return this.multiplyRight(e,t)}},{key:"ELEMENTS",get:function(){return 4}},{key:"x",get:function(){return this[0]},set:function(e){this[0]=d(e)}},{key:"y",get:function(){return this[1]},set:function(e){this[1]=d(e)}},{key:"z",get:function(){return this[2]},set:function(e){this[2]=d(e)}},{key:"w",get:function(){return this[3]},set:function(e){this[3]=d(e)}}]),A}(h),P=new w,V=new w,K=new w,W=new w,X=new w,q=new w,z=new w,$=0,ee=1,te=2,Ae=3,ne=4,re=5,ie=6,oe=7,ae=8,se=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0,0],A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0,0,0,0,0,0,0,0,0];Object(r.a)(this,e),this.center=(new w).from(t),this.halfAxes=new Z(A)}return Object(i.a)(e,[{key:"fromCenterHalfSizeQuaternion",value:function(e,t,A){var n=new j(A),r=(new Z).fromQuaternion(n);return r[0]=r[0]*t[0],r[1]=r[1]*t[0],r[2]=r[2]*t[0],r[3]=r[3]*t[1],r[4]=r[4]*t[1],r[5]=r[5]*t[1],r[6]=r[6]*t[2],r[7]=r[7]*t[2],r[8]=r[8]*t[2],this.center=(new w).from(e),this.halfAxes=r,this}},{key:"clone",value:function(){return new e(this.center,this.halfAxes)}},{key:"equals",value:function(e){return this===e||Boolean(e)&&this.center.equals(e.center)&&this.halfAxes.equals(e.halfAxes)}},{key:"getBoundingSphere",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new x,t=this.halfAxes,A=t.getColumn(0,K),n=t.getColumn(1,W),r=t.getColumn(2,X),i=P.copy(A).add(n).add(r);return e.center.copy(this.center),e.radius=i.magnitude(),e}},{key:"intersectPlane",value:function(e){var t=this.center,A=e.normal,r=this.halfAxes,i=A.x,o=A.y,a=A.z,s=Math.abs(i*r[$]+o*r[ee]+a*r[te])+Math.abs(i*r[Ae]+o*r[ne]+a*r[re])+Math.abs(i*r[ie]+o*r[oe]+a*r[ae]),g=A.dot(t)+e.distance;return g<=-s?n.OUTSIDE:g>=s?n.INSIDE:n.INTERSECTING}},{key:"distanceTo",value:function(e){return Math.sqrt(this.distanceSquaredTo(e))}},{key:"distanceSquaredTo",value:function(e){var t=V.from(e).subtract(this.center),A=this.halfAxes,n=A.getColumn(0,K),r=A.getColumn(1,W),i=A.getColumn(2,X),o=n.magnitude(),a=r.magnitude(),s=i.magnitude();n.normalize(),r.normalize(),i.normalize();var g,c=0;return(g=Math.abs(t.dot(n))-o)>0&&(c+=g*g),(g=Math.abs(t.dot(r))-a)>0&&(c+=g*g),(g=Math.abs(t.dot(i))-s)>0&&(c+=g*g),c}},{key:"computePlaneDistances",value:function(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[-0,-0],n=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,i=this.center,o=this.halfAxes,a=o.getColumn(0,K),s=o.getColumn(1,W),g=o.getColumn(2,X),c=q.copy(a).add(s).add(g).add(i),u=z.copy(c).subtract(e),l=t.dot(u);return n=Math.min(l,n),r=Math.max(l,r),c.copy(i).add(a).add(s).subtract(g),u.copy(c).subtract(e),l=t.dot(u),n=Math.min(l,n),r=Math.max(l,r),c.copy(i).add(a).subtract(s).add(g),u.copy(c).subtract(e),l=t.dot(u),n=Math.min(l,n),r=Math.max(l,r),c.copy(i).add(a).subtract(s).subtract(g),u.copy(c).subtract(e),l=t.dot(u),n=Math.min(l,n),r=Math.max(l,r),i.copy(c).subtract(a).add(s).add(g),u.copy(c).subtract(e),l=t.dot(u),n=Math.min(l,n),r=Math.max(l,r),i.copy(c).subtract(a).add(s).subtract(g),u.copy(c).subtract(e),l=t.dot(u),n=Math.min(l,n),r=Math.max(l,r),i.copy(c).subtract(a).subtract(s).add(g),u.copy(c).subtract(e),l=t.dot(u),n=Math.min(l,n),r=Math.max(l,r),i.copy(c).subtract(a).subtract(s).subtract(g),u.copy(c).subtract(e),l=t.dot(u),n=Math.min(l,n),r=Math.max(l,r),A[0]=n,A[1]=r,A}},{key:"transform",value:function(e){this.center.transformAsPoint(e);var t=this.halfAxes.getColumn(0,K);t.transformAsPoint(e);var A=this.halfAxes.getColumn(1,W);A.transformAsPoint(e);var n=this.halfAxes.getColumn(2,X);return n.transformAsPoint(e),this.halfAxes=new Z([].concat(Object(s.a)(t),Object(s.a)(A),Object(s.a)(n))),this}},{key:"getTransform",value:function(){throw new Error("not implemented")}},{key:"halfSize",get:function(){var e=this.halfAxes.getColumn(0),t=this.halfAxes.getColumn(1),A=this.halfAxes.getColumn(2);return[new w(e).len(),new w(t).len(),new w(A).len()]}},{key:"quaternion",get:function(){var e=this.halfAxes.getColumn(0),t=this.halfAxes.getColumn(1),A=this.halfAxes.getColumn(2),n=new w(e).normalize(),r=new w(t).normalize(),i=new w(A).normalize();return(new j).fromMatrix3(new Z([].concat(Object(s.a)(n),Object(s.a)(r),Object(s.a)(i))))}}]),e}(),ge=A(6),ce=new w,ue=new w,le=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0,1],A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;Object(r.a)(this,e),this.normal=new w,this.distance=-0,this.fromNormalDistance(t,A)}return Object(i.a)(e,[{key:"fromNormalDistance",value:function(e,t){return g(Number.isFinite(t)),this.normal.from(e).normalize(),this.distance=t,this}},{key:"fromPointNormal",value:function(e,t){e=ce.from(e),this.normal.from(t).normalize();var A=-this.normal.dot(e);return this.distance=A,this}},{key:"fromCoefficients",value:function(e,t,A,n){return this.normal.set(e,t,A),g(C(this.normal.len(),1)),this.distance=n,this}},{key:"clone",value:function(t){return new e(this.normal,this.distance)}},{key:"equals",value:function(e){return C(this.distance,e.distance)&&C(this.normal,e.normal)}},{key:"getPointDistance",value:function(e){return this.normal.dot(e)+this.distance}},{key:"transform",value:function(e){var t=ue.copy(this.normal).transformAsVector(e).normalize(),A=this.normal.scale(-this.distance).transform(e);return this.fromPointNormal(A,t)}},{key:"projectPointOntoPlane",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0,0,0];e=ce.from(e);var A=this.getPointDistance(e),n=ue.copy(this.normal).scale(A);return e.subtract(n).to(t)}}]),e}(),Ie=[new w([1,0,0]),new w([0,1,0]),new w([0,0,1])],Ce=new w,he=new w,fe=(new le(new w(1,0,0),0),function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];Object(r.a)(this,e),this.planes=t,g(this.planes.every((function(e){return e instanceof le})))}return Object(i.a)(e,null,[{key:"MASK_OUTSIDE",get:function(){return 4294967295}},{key:"MASK_INSIDE",get:function(){return 0}},{key:"MASK_INDETERMINATE",get:function(){return 2147483647}}]),Object(i.a)(e,[{key:"fromBoundingSphere",value:function(e){this.planes.length=2*Ie.length;var t,A=e.center,n=e.radius,r=0,i=Object(ge.a)(Ie);try{for(i.s();!(t=i.n()).done;){var o=t.value,a=this.planes[r],s=this.planes[r+1];a||(a=this.planes[r]=new le),s||(s=this.planes[r+1]=new le);var g=Ce.copy(o).scale(-n).add(A);o.dot(g);a.fromPointNormal(g,o);var c=Ce.copy(o).scale(n).add(A),u=he.copy(o).negate();u.dot(c);s.fromPointNormal(c,u),r+=2}}catch(l){i.e(l)}finally{i.f()}return this}},{key:"computeVisibility",value:function(e){g(e);var t,A=n.INSIDE,r=Object(ge.a)(this.planes);try{for(r.s();!(t=r.n()).done;){var i=t.value;switch(e.intersectPlane(i)){case n.OUTSIDE:return n.OUTSIDE;case n.INTERSECTING:A=n.INTERSECTING}}}catch(o){r.e(o)}finally{r.f()}return A}},{key:"computeVisibilityWithPlaneMask",value:function(t,A){if(g(t,"boundingVolume is required."),g(Number.isFinite(A),"parentPlaneMask is required."),A===e.MASK_OUTSIDE||A===e.MASK_INSIDE)return A;for(var r=e.MASK_INSIDE,i=this.planes,o=0;o1&&void 0!==arguments[1]?arguments[1]:{},A=Be,n=10,r=0,i=0,o=Ee,a=Qe;o.identity(),a.copy(e);for(var s=A*be(a);is;)Re(a,ye),ve.copy(ye).transpose(),a.multiplyRight(ye),a.multiplyLeft(ve),o.multiplyRight(ye),++r>2&&(++i,r=0);return t.unitary=o.toTarget(t.unitary),t.diagonal=a.toTarget(t.diagonal),t}function be(e){for(var t=0,A=0;A<9;++A){var n=e[A];t+=n*n}return Math.sqrt(t)}var we=[1,0,0],Se=[2,2,1];function Fe(e){for(var t=0,A=0;A<3;++A){var n=e[pe.getElementIndex(Se[A],we[A])];t+=2*n*n}return Math.sqrt(t)}function Re(e,t){for(var A=de,n=0,r=1,i=0;i<3;++i){var o=Math.abs(e[pe.getElementIndex(Se[i],we[i])]);o>n&&(r=i,n=o)}var a=we[r],s=Se[r],g=1,c=0;if(Math.abs(e[pe.getElementIndex(s,a)])>A){var u,l=(e[pe.getElementIndex(s,s)]-e[pe.getElementIndex(a,a)])/2/e[pe.getElementIndex(s,a)];c=(u=l<0?-1/(-l+Math.sqrt(1+l*l)):1/(l+Math.sqrt(1+l*l)))*(g=1/Math.sqrt(1+u*u))}return Z.IDENTITY.to(t),t[pe.getElementIndex(a,a)]=t[pe.getElementIndex(s,s)]=g,t[pe.getElementIndex(s,a)]=c,t[pe.getElementIndex(a,s)]=-c,t}var De=new w,Ge=new w,ke=new w,xe=new w,Ne=new w,Ue=new Z,_e={diagonal:new Z,unitary:new Z};function Me(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new se;if(!e||0===e.length)return t.halfAxes=new Z([0,0,0,0,0,0,0,0,0]),t.center=new w,t;var A,n=e.length,r=new w(0,0,0),i=Object(ge.a)(e);try{for(i.s();!(A=i.n()).done;){var o=A.value;r.add(o)}}catch(M){i.e(M)}finally{i.f()}var a=1/n;r.multiplyByScalar(a);var s,g=0,c=0,u=0,l=0,I=0,C=0,h=Object(ge.a)(e);try{for(h.s();!(s=h.n()).done;){var f=s.value,d=De.copy(f).subtract(r);g+=d.x*d.x,c+=d.x*d.y,u+=d.x*d.z,l+=d.y*d.y,I+=d.y*d.z,C+=d.z*d.z}}catch(M){h.e(M)}finally{h.f()}g*=a,c*=a,u*=a,l*=a,I*=a,C*=a;var B=Ue;B[0]=g,B[1]=c,B[2]=u,B[3]=c,B[4]=l,B[5]=I,B[6]=u,B[7]=I,B[8]=C;var p,E=me(B,_e),Q=E.unitary,y=t.halfAxes.copy(Q),v=y.getColumn(0,ke),m=y.getColumn(1,xe),b=y.getColumn(2,Ne),S=-Number.MAX_VALUE,F=-Number.MAX_VALUE,R=-Number.MAX_VALUE,D=Number.MAX_VALUE,G=Number.MAX_VALUE,k=Number.MAX_VALUE,x=Object(ge.a)(e);try{for(x.s();!(p=x.n()).done;){var N=p.value;De.copy(N),S=Math.max(De.dot(v),S),F=Math.max(De.dot(m),F),R=Math.max(De.dot(b),R),D=Math.min(De.dot(v),D),G=Math.min(De.dot(m),G),k=Math.min(De.dot(b),k)}}catch(M){x.e(M)}finally{x.f()}v=v.multiplyByScalar(.5*(D+S)),m=m.multiplyByScalar(.5*(G+F)),b=b.multiplyByScalar(.5*(k+R)),t.center.copy(v).add(m).add(b);var U=Ge.set(S-D,F-G,R-k).multiplyByScalar(.5),_=new Z([U[0],0,0,0,U[1],0,0,0,U[2]]);return t.halfAxes.multiplyRight(_),t}A.d(t,"a",(function(){return R})),A.d(t,"b",(function(){return x})),A.d(t,"d",(function(){return se})),A.d(t,"c",(function(){return fe})),A.d(t,"e",(function(){return le})),A.d(t,"f",(function(){return Me}))},function(e,t,A){var n=A(813)();e.exports=n},function(e,t,A){"use strict";function n(e,t){if(null==e)return{};var A,n,r=function(e,t){if(null==e)return{};var A,n,r={},i=Object.keys(e);for(n=0;n=0||(r[A]=e[A]);return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,A)&&(r[A]=e[A])}return r}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return i})),A.d(t,"e",(function(){return o})),A.d(t,"c",(function(){return a})),A.d(t,"d",(function(){return s})),A.d(t,"b",(function(){return l})),A.d(t,"f",(function(){return I}));var n=A(150),r=A(23);function i(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function o(e,t){var A=e%t;return A<0?t+A:A}function a(e){return[e[12],e[13],e[14]]}function s(e){var t={};return t.left=u(e[3]+e[0],e[7]+e[4],e[11]+e[8],e[15]+e[12]),t.right=u(e[3]-e[0],e[7]-e[4],e[11]-e[8],e[15]-e[12]),t.bottom=u(e[3]+e[1],e[7]+e[5],e[11]+e[9],e[15]+e[13]),t.top=u(e[3]-e[1],e[7]-e[5],e[11]-e[9],e[15]-e[13]),t.near=u(e[3]+e[2],e[7]+e[6],e[11]+e[10],e[15]+e[14]),t.far=u(e[3]-e[2],e[7]-e[6],e[11]-e[10],e[15]-e[14]),t}var g,c=new r.Vector3;function u(e,t,A,n){c.set(e,t,A);var i=c.len();return{distance:n/i,normal:new r.Vector3(-e/i,-t/i,-A/i)}}function l(e){return e-Math.fround(e)}function I(e,t){var A=t.size,r=void 0===A?1:A,i=t.startIndex,o=void 0===i?0:i,a=t.endIndex;Number.isFinite(a)||(a=e.length);var s=(a-o)/r;g=n.a.allocate(g,s,{type:Float32Array,size:2*r});for(var c=o,u=0;c2&&void 0!==arguments[2]?arguments[2]:{},n=i(e,A);return n!==t&&(a(e,A),!0)}function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Math.sign(o(e,t))}function o(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.start,n=void 0===A?0:A,r=t.end,i=void 0===r?e.length:r,o=t.size||2,a=0,s=n,g=i-o;s80*A){a=i=e[0],s=o=e[1];for(var Q=A;Qi&&(i=l),I>o&&(o=I);r=0!==(r=Math.max(i-a,o-s))?1/r:0}return u(B,p,A,a,s,r),p}function g(e,t,A,n,r,i){var a,s;if(void 0===i&&(i=o(e,{start:t,end:A,size:n})),r===i<0)for(a=t;a=t;a-=n)s=D(a,e[a],e[a+1],s);return s&&m(s,s.next)&&(G(s),s=s.next),s}function c(e,t){if(!e)return e;t||(t=e);var A,n=e;do{if(A=!1,n.steiner||!m(n,n.next)&&0!==v(n.prev,n,n.next))n=n.next;else{if(G(n),(n=t=n.prev)===n.next)break;A=!0}}while(A||n!==t);return t}function u(e,t,A,n,r,i,o){if(e){!o&&i&&function(e,t,A,n){var r=e;do{null===r.z&&(r.z=p(r.x,r.y,t,A,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){var t,A,n,r,i,o,a,s,g=1;do{for(r=e,e=null,s=null,n=0;r;){for(n++,o=r,i=0,A=0;A0||a>0&&o;)0!==i&&(0===a||!o||r.z<=o.z)?(t=r,r=r.nextZ,i--):(t=o,o=o.nextZ,a--),s?s.nextZ=t:e=t,t.prevZ=s,s=t;r=o}s.nextZ=null,g*=2}while(n>1)}(r)}(e,n,r,i);for(var a,s,g=e;e.prev!==e.next;)if(a=e.prev,s=e.next,i?I(e,n,r,i):l(e))t.push(a.i/A),t.push(e.i/A),t.push(s.i/A),G(e),e=s.next,g=s.next;else if((e=s)===g){o?1===o?u(e=C(c(e),t,A),t,A,n,r,i,2):2===o&&h(e,t,A,n,r,i):u(c(e),t,A,n,r,i,1);break}}}function l(e){var t=e.prev,A=e,n=e.next;if(v(t,A,n)>=0)return!1;for(var r=e.next.next;r!==e.prev;){if(Q(t.x,t.y,A.x,A.y,n.x,n.y,r.x,r.y)&&v(r.prev,r,r.next)>=0)return!1;r=r.next}return!0}function I(e,t,A,n){var r=e.prev,i=e,o=e.next;if(v(r,i,o)>=0)return!1;for(var a=r.xi.x?r.x>o.x?r.x:o.x:i.x>o.x?i.x:o.x,c=r.y>i.y?r.y>o.y?r.y:o.y:i.y>o.y?i.y:o.y,u=p(a,s,t,A,n),l=p(g,c,t,A,n),I=e.prevZ,C=e.nextZ;I&&I.z>=u&&C&&C.z<=l;){if(I!==e.prev&&I!==e.next&&Q(r.x,r.y,i.x,i.y,o.x,o.y,I.x,I.y)&&v(I.prev,I,I.next)>=0)return!1;if(I=I.prevZ,C!==e.prev&&C!==e.next&&Q(r.x,r.y,i.x,i.y,o.x,o.y,C.x,C.y)&&v(C.prev,C,C.next)>=0)return!1;C=C.nextZ}for(;I&&I.z>=u;){if(I!==e.prev&&I!==e.next&&Q(r.x,r.y,i.x,i.y,o.x,o.y,I.x,I.y)&&v(I.prev,I,I.next)>=0)return!1;I=I.prevZ}for(;C&&C.z<=l;){if(C!==e.prev&&C!==e.next&&Q(r.x,r.y,i.x,i.y,o.x,o.y,C.x,C.y)&&v(C.prev,C,C.next)>=0)return!1;C=C.nextZ}return!0}function C(e,t,A){var n=e;do{var r=n.prev,i=n.next.next;!m(r,i)&&b(r,n,n.next,i)&&F(r,i)&&F(i,r)&&(t.push(r.i/A),t.push(n.i/A),t.push(i.i/A),G(n),G(n.next),n=e=i),n=n.next}while(n!==e);return c(n)}function h(e,t,A,n,r,i){var o=e;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&y(o,a)){var s=R(o,a);return o=c(o,o.next),s=c(s,s.next),u(o,t,A,n,r,i),void u(s,t,A,n,r,i)}a=a.next}o=o.next}while(o!==e)}function f(e,t){return e.x-t.x}function d(e,t){if(t=function(e,t){var A,n=t,r=e.x,i=e.y,o=-1/0;do{if(i<=n.y&&i>=n.next.y&&n.next.y!==n.y){var a=n.x+(i-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=r&&a>o){if(o=a,a===r){if(i===n.y)return n;if(i===n.next.y)return n.next}A=n.x=n.x&&n.x>=c&&r!==n.x&&Q(iA.x||n.x===A.x&&B(A,n)))&&(A=n,l=s)),n=n.next}while(n!==g);return A}(e,t)){var A=R(t,e);c(t,t.next),c(A,A.next)}}function B(e,t){return v(e.prev,e,t.prev)<0&&v(t.next,e,e.next)<0}function p(e,t,A,n,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-A)*r)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-n)*r)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function E(e){var t=e,A=e;do{(t.x=0&&(e-o)*(n-a)-(A-o)*(t-a)>=0&&(A-o)*(i-a)-(r-o)*(n-a)>=0}function y(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var A=e;do{if(A.i!==e.i&&A.next.i!==e.i&&A.i!==t.i&&A.next.i!==t.i&&b(A,A.next,e,t))return!0;A=A.next}while(A!==e);return!1}(e,t)&&(F(e,t)&&F(t,e)&&function(e,t){var A=e,n=!1,r=(e.x+t.x)/2,i=(e.y+t.y)/2;do{A.y>i!==A.next.y>i&&A.next.y!==A.y&&r<(A.next.x-A.x)*(i-A.y)/(A.next.y-A.y)+A.x&&(n=!n),A=A.next}while(A!==e);return n}(e,t)&&(v(e.prev,e,t.prev)||v(e,t.prev,t))||m(e,t)&&v(e.prev,e,e.next)>0&&v(t.prev,t,t.next)>0)}function v(e,t,A){return(t.y-e.y)*(A.x-t.x)-(t.x-e.x)*(A.y-t.y)}function m(e,t){return e.x===t.x&&e.y===t.y}function b(e,t,A,n){var r=S(v(e,t,A)),i=S(v(e,t,n)),o=S(v(A,n,e)),a=S(v(A,n,t));return r!==i&&o!==a||(!(0!==r||!w(e,A,t))||(!(0!==i||!w(e,n,t))||(!(0!==o||!w(A,e,n))||!(0!==a||!w(A,t,n)))))}function w(e,t,A){return t.x<=Math.max(e.x,A.x)&&t.x>=Math.min(e.x,A.x)&&t.y<=Math.max(e.y,A.y)&&t.y>=Math.min(e.y,A.y)}function S(e){return e>0?1:e<0?-1:0}function F(e,t){return v(e.prev,e,e.next)<0?v(e,t,e.next)>=0&&v(e,e.prev,t)>=0:v(e,t,e.prev)<0||v(e,e.next,t)<0}function R(e,t){var A=new k(e.i,e.x,e.y),n=new k(t.i,t.x,t.y),r=e.next,i=t.prev;return e.next=t,t.prev=e,A.next=r,r.prev=A,n.next=A,A.prev=n,i.next=n,n.prev=i,n}function D(e,t,A,n){var r=new k(e,t,A);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r}function G(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function k(e,t,A){this.i=e,this.x=t,this.y=A,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function x(e,t){var A=t.length,n=e.length;if(n>0){for(var r=!0,i=0;i4&&void 0!==arguments[4]?arguments[4]:[],i=n+t*A,o=0;o4&&void 0!==arguments[4]?arguments[4]:[];if(8&A)r=(n[3]-e[1])/(t[1]-e[1]),i=3;else if(4&A)r=(n[1]-e[1])/(t[1]-e[1]),i=1;else if(2&A)r=(n[2]-e[0])/(t[0]-e[0]),i=2;else{if(!(1&A))return null;r=(n[0]-e[0])/(t[0]-e[0]),i=0}for(var a=0;at[2]&&(A|=2),e[1]t[3]&&(A|=8),A}function O(e){var t,A,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.size,i=void 0===r?2:r,o=n.broken,a=void 0!==o&&o,s=n.gridResolution,g=void 0===s?10:s,c=n.gridOffset,u=void 0===c?[0,0]:c,l=n.startIndex,I=void 0===l?0:l,C=n.endIndex,h=void 0===C?e.length:C,f=(h-I)/i,d=[],B=[d],p=U(e,0,i,I),E=H(p,g,u,[]),Q=[];x(d,p);for(var y=1;yi&&(d=[],B.push(d),x(d,p)),A=M(t,E)}x(d,t),N(p,t)}return a?B:B[0]}function L(e,t){for(var A=0;A2&&void 0!==arguments[2]?arguments[2]:{};if(!e.length)return[];for(var n=A.size,r=void 0===n?2:n,i=A.gridResolution,o=void 0===i?10:i,a=A.gridOffset,s=void 0===a?[0,0]:a,g=A.edgeTypes,c=void 0!==g&&g,u=[],l=[{pos:e,types:c&&new Array(e.length/r).fill(1),holes:t||[]}],I=[[],[]],C=[];l.length;){var h=l.shift(),f=h.pos,d=h.types,B=h.holes;J(f,r,B[0]||f.length,I),C=H(I[0],o,s,C);var p=M(I[1],C);if(p){var E=Z(f,d,r,0,B[0]||f.length,C,p),Q={pos:E[0].pos,types:E[0].types,holes:[]},y={pos:E[1].pos,types:E[1].types,holes:[]};l.push(Q,y);for(var v=0;v=0?(x(l,a)&&C.push(g),E+=s):C.length&&(C[C.length-1]=0),N(f,a),d=s,B=g;return[p?{pos:u,types:t&&I}:null,E?{pos:l,types:t&&C}:null]}function H(e,t,A,n){var r=Math.floor((e[0]-A[0])/t)*t+A[0],i=Math.floor((e[1]-A[1])/t)*t+A[1];return n[0]=r,n[1]=i,n[2]=r+t,n[3]=i+t,n}function Y(e,t,A){8&A?(e[1]+=t,e[3]+=t):4&A?(e[1]-=t,e[3]-=t):2&A?(e[0]+=t,e[2]+=t):1&A&&(e[0]-=t,e[2]-=t)}function J(e,t,A,n){for(var r=1/0,i=-1/0,o=1/0,a=-1/0,s=0;si?g:i,o=ca?c:a}return n[0][0]=r,n[0][1]=o,n[1][0]=i,n[1][1]=a,n}var j=A(6);function P(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.size,n=void 0===A?2:A,r=t.startIndex,i=void 0===r?0:r,o=t.endIndex,a=void 0===o?e.length:o,s=t.normalize,g=void 0===s||s,c=e.slice(i,a);X(c,n,0,a-i);var u=O(c,{size:n,broken:!0,gridResolution:360,gridOffset:[-180,-180]});if(g){var l,I=Object(j.a)(u);try{for(I.s();!(l=I.n()).done;){var C=l.value;q(C,n)}}catch(h){I.e(h)}finally{I.f()}}return u}function V(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=A.size,r=void 0===n?2:n,i=A.normalize,o=void 0===i||i,a=A.edgeTypes,s=void 0!==a&&a;t=t||[];for(var g=[],c=[],u=0,l=0,I=0;I<=t.length;I++){for(var C=t[I]||e.length,h=l,f=K(e,r,u,C),d=f;dr&&(r=a,i=o-1)}return i}function W(e,t,A,n){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:85.051129,i=e[A],o=e[n-t];if(Math.abs(i-o)>180){var a=U(e,0,t,A);a[0]+=360*Math.round((o-i)/360),x(e,a),a[1]=Math.sign(a[1])*r,x(e,a),a[0]=i,x(e,a)}}function X(e,t,A,n){for(var r,i=e[0],o=A;o180||a<-180)&&(r-=360*Math.round(a/360)),e[o]=i=r}}function q(e,t){for(var A,n=e.length/t,r=0;r1)for(var A=1;A1&&void 0!==arguments[1]?arguments[1]:{};Object(r.a)(this,e),Object(o.b)(t);var n=A.id,i=A.userData,a=void 0===i?{}:i;this.gl=t,this.gl2=t,this.id=n||Object(c.c)(this.constructor.name),this.userData=a,this._bound=!1,this._handle=A.handle,void 0===this._handle&&(this._handle=this._createHandle()),this.byteLength=0,this._addStats()}return Object(i.a)(e,[{key:"toString",value:function(){return"".concat(this.constructor.name,"(").concat(this.id,")")}},{key:"delete",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.deleteChildren,A=void 0!==t&&t,n=this._handle&&this._deleteHandle(this._handle);return this._handle&&this._removeStats(),this._handle=null,n&&A&&n.filter(Boolean).forEach((function(e){return e.delete()})),this}},{key:"bind",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.handle;return"function"!==typeof t?(this._bindHandle(t),this):(this._bound?e=t():(this._bindHandle(this.handle),this._bound=!0,e=t(),this._bound=!1,this._bindHandle(null)),e)}},{key:"unbind",value:function(){this.bind(null)}},{key:"getParameter",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e=Object(s.b)(this.gl,e),Object(g.a)(e);var A=this.constructor.PARAMETERS||{},n=A[e];if(n){var r=Object(o.j)(this.gl),i=(!("webgl2"in n)||r)&&(!("extension"in n)||this.gl.getExtension(n.extension));if(!i){var a=n.webgl1,c="webgl2"in n?n.webgl2:n.webgl1,u=r?c:a;return u}}return this._getParameter(e,t)}},{key:"getParameters",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},A=t.parameters,r=t.keys,i=this.constructor.PARAMETERS||{},a=Object(o.j)(this.gl),g={},c=A||Object.keys(i),u=Object(n.a)(c);try{for(u.s();!(e=u.n()).done;){var l=e.value,I=i[l],C=I&&(!("webgl2"in I)||a)&&(!("extension"in I)||this.gl.getExtension(I.extension));if(C){var h=r?Object(s.a)(this.gl,l):l;g[h]=this.getParameter(l,t),r&&"GLenum"===I.type&&(g[h]=Object(s.a)(this.gl,g[h]))}}}catch(f){u.e(f)}finally{u.f()}return g}},{key:"setParameter",value:function(e,t){e=Object(s.b)(this.gl,e),Object(g.a)(e);var A=(this.constructor.PARAMETERS||{})[e];if(A){var n=Object(o.j)(this.gl);if(!((!("webgl2"in A)||n)&&(!("extension"in A)||this.gl.getExtension(A.extension))))throw new Error("Parameter not available on this platform");"GLenum"===A.type&&(t=Object(s.b)(t))}return this._setParameter(e,t),this}},{key:"setParameters",value:function(e){for(var t in e)this.setParameter(t,e[t]);return this}},{key:"stubRemovedMethods",value:function(e,t,A){return Object(u.a)(this,e,t,A)}},{key:"initialize",value:function(e){}},{key:"_createHandle",value:function(){throw new Error(l)}},{key:"_deleteHandle",value:function(){throw new Error(l)}},{key:"_bindHandle",value:function(e){throw new Error(l)}},{key:"_getOptsFromHandle",value:function(){throw new Error(l)}},{key:"_getParameter",value:function(e,t){throw new Error(l)}},{key:"_setParameter",value:function(e,t){throw new Error(l)}},{key:"_context",value:function(){return this.gl.luma=this.gl.luma||{},this.gl.luma}},{key:"_addStats",value:function(){var e=this.constructor.name,t=a.a.get("Resource Counts");t.get("Resources Created").incrementCount(),t.get("".concat(e,"s Created")).incrementCount(),t.get("".concat(e,"s Active")).incrementCount()}},{key:"_removeStats",value:function(){var e=this.constructor.name;a.a.get("Resource Counts").get("".concat(e,"s Active")).decrementCount()}},{key:"_trackAllocatedMemory",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.constructor.name,A=a.a.get("Memory Usage");A.get("GPU Memory").addCount(e),A.get("".concat(t," Memory")).addCount(e),this.byteLength=e}},{key:"_trackDeallocatedMemory",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.constructor.name,t=a.a.get("Memory Usage");t.get("GPU Memory").subtractCount(this.byteLength),t.get("".concat(e," Memory")).subtractCount(this.byteLength),this.byteLength=0}},{key:"handle",get:function(){return this._handle}}]),e}()},function(e,t,A){"use strict";t.__esModule=!0;var n,r=A(925),i=(n=r)&&n.__esModule?n:{default:n};t.default=i.default||function(e){for(var t=1;t0&&(o=1/Math.sqrt(o)),e[0]=A*o,e[1]=n*o,e[2]=r*o,e[3]=i*o,e}function I(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}function C(e,t,A,n){var r=t[0],i=t[1],o=t[2],a=t[3];return e[0]=r+n*(A[0]-r),e[1]=i+n*(A[1]-i),e[2]=o+n*(A[2]-o),e[3]=a+n*(A[3]-a),e}function h(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3];return e[0]=A[0]*n+A[4]*r+A[8]*i+A[12]*o,e[1]=A[1]*n+A[5]*r+A[9]*i+A[13]*o,e[2]=A[2]*n+A[6]*r+A[10]*i+A[14]*o,e[3]=A[3]*n+A[7]*r+A[11]*i+A[15]*o,e}function f(e,t,A){var n=t[0],r=t[1],i=t[2],o=A[0],a=A[1],s=A[2],g=A[3],c=g*n+a*i-s*r,u=g*r+s*n-o*i,l=g*i+o*r-a*n,I=-o*n-a*r-s*i;return e[0]=c*g+I*-o+u*-s-l*-a,e[1]=u*g+I*-a+l*-o-c*-s,e[2]=l*g+I*-s+c*-a-u*-o,e[3]=t[3],e}function d(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]}function B(e,t){var A=e[0],r=e[1],i=e[2],o=e[3],a=t[0],s=t[1],g=t[2],c=t[3];return Math.abs(A-a)<=n.b*Math.max(1,Math.abs(A),Math.abs(a))&&Math.abs(r-s)<=n.b*Math.max(1,Math.abs(r),Math.abs(s))&&Math.abs(i-g)<=n.b*Math.max(1,Math.abs(i),Math.abs(g))&&Math.abs(o-c)<=n.b*Math.max(1,Math.abs(o),Math.abs(c))}!function(){var e=function(){var e=new n.a(4);return n.a!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0,e[3]=0),e}()}()},function(e,t){e.exports=function(e){return e&&e.__esModule?e:{default:e}}},function(e,t,A){"use strict";A.d(t,"a",(function(){return f}));var n=A(8),r=A(1),i=A(4),o=A(41),a=A(84),s=A(23),g=A(27),c=A(42),u=A(36),l=Math.PI/180,I=Object(a.a)(),C=[0,0,0],h={unitsPerMeter:[1,1,1],metersPerUnit:[1,1,1]},f=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(r.a)(this,e);var A=t.id,n=void 0===A?null:A,i=t.x,o=void 0===i?0:i,a=t.y,s=void 0===a?0:a,g=t.width,c=void 0===g?1:g,u=t.height,l=void 0===u?1:u;this.id=n||this.constructor.displayName||"viewport",this.x=o,this.y=s,this.width=c||1,this.height=l||1,this._frustumPlanes={},this._initViewMatrix(t),this._initProjectionMatrix(t),this._initPixelMatrices(),this.equals=this.equals.bind(this),this.project=this.project.bind(this),this.unproject=this.unproject.bind(this),this.projectPosition=this.projectPosition.bind(this),this.unprojectPosition=this.unprojectPosition.bind(this),this.projectFlat=this.projectFlat.bind(this),this.unprojectFlat=this.unprojectFlat.bind(this)}return Object(i.a)(e,[{key:"equals",value:function(t){return t instanceof e&&(this===t||t.width===this.width&&t.height===this.height&&t.scale===this.scale&&Object(s.equals)(t.projectionMatrix,this.projectionMatrix)&&Object(s.equals)(t.viewMatrix,this.viewMatrix))}},{key:"project",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.topLeft,r=void 0===A||A,i=this.projectPosition(e),o=Object(c.s)(i,this.pixelProjectionMatrix),a=Object(n.a)(o,2),s=a[0],g=a[1],u=r?g:this.height-g;return 2===e.length?[s,u]:[s,u,o[2]]}},{key:"unproject",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.topLeft,r=void 0===A||A,i=t.targetZ,o=Object(n.a)(e,3),a=o[0],s=o[1],g=o[2],u=r?s:this.height-s,l=i&&i*this.distanceScales.unitsPerMeter[2],I=Object(c.p)([a,u,g],this.pixelUnprojectionMatrix,l),C=this.unprojectPosition(I),h=Object(n.a)(C,3),f=h[0],d=h[1],B=h[2];return Number.isFinite(g)?[f,d,B]:Number.isFinite(i)?[f,d,i]:[f,d]}},{key:"projectPosition",value:function(e){var t=this.projectFlat(e),A=Object(n.a)(t,2);return[A[0],A[1],(e[2]||0)*this.distanceScales.unitsPerMeter[2]]}},{key:"unprojectPosition",value:function(e){var t=this.unprojectFlat(e),A=Object(n.a)(t,2);return[A[0],A[1],(e[2]||0)*this.distanceScales.metersPerUnit[2]]}},{key:"projectFlat",value:function(e){return this.isGeospatial?Object(c.n)(e):e}},{key:"unprojectFlat",value:function(e){return this.isGeospatial?Object(c.r)(e):e}},{key:"getBounds",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={targetZ:e.z||0},A=this.unproject([0,0],t),n=this.unproject([this.width,0],t),r=this.unproject([0,this.height],t),i=this.unproject([this.width,this.height],t);return[Math.min(A[0],n[0],r[0],i[0]),Math.min(A[1],n[1],r[1],i[1]),Math.max(A[0],n[0],r[0],i[0]),Math.max(A[1],n[1],r[1],i[1])]}},{key:"getDistanceScales",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return e?Object(c.h)({longitude:e[0],latitude:e[1],highPrecision:!0}):this.distanceScales}},{key:"containsPixel",value:function(e){var t=e.x,A=e.y,n=e.width,r=void 0===n?1:n,i=e.height,o=void 0===i?1:i;return t1&&void 0!==arguments[1]?arguments[1]:[255,0,0,255];if(!Array.isArray(e))return t;return[255*e[0],255*e[1],255*e[2],255*e[3]]},t.recursivelyTraverseNestedArrays=function e(t,A,n){if(!Array.isArray(t[0]))return!0;for(var r=0;r1&&C.length){var h,f;i?(h=I.map((function(e){return i.project(e)})),f=i.project(C)):(h=I,f=C);for(var d=1;dE&&(l=Math.sqrt(Math.min(Q,y))),(null===A||void 0===A||A>l)&&(m>E?y=0&&"existing"===t.editHandleType}))},t.getPickedIntermediateEditHandle=function(e){return d(e).find((function(e){var t=e.properties;return t.featureIndex>=0&&"intermediate"===t.editHandleType}))},t.getPickedEditHandles=d,t.getEditHandlesForGeometry=function(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"existing",n=[];switch(e.type){case"Point":n=[{type:"Feature",properties:{guideType:"editHandle",editHandleType:A,positionIndexes:[],featureIndex:t},geometry:{type:"Point",coordinates:e.coordinates}}];break;case"MultiPoint":case"LineString":n=n.concat(B(e.coordinates,[],t,A));break;case"Polygon":case"MultiLineString":for(var r=0;re.length)&&(t=e.length);for(var A=0,n=new Array(t);A3&&void 0!==arguments[3]?arguments[3]:"existing",r=[],i=0;i<+~=|^:(),"'`\s])/g,B="undefined"!==typeof CSS&&CSS.escape,p=function(e){return B?B(e):e.replace(d,"\\$1")},E=function(){function e(e,t,A){this.type="style",this.isProcessed=!1;var n=A.sheet,r=A.Renderer;this.key=e,this.options=A,this.style=t,n?this.renderer=n.renderer:r&&(this.renderer=new r)}return e.prototype.prop=function(e,t,A){if(void 0===t)return this.style[e];var n=!!A&&A.force;if(!n&&this.style[e]===t)return this;var r=t;A&&!1===A.process||(r=this.options.jss.plugins.onChangeValue(t,e,this));var i=null==r||!1===r,o=e in this.style;if(i&&!o&&!n)return this;var a=i&&o;if(a?delete this.style[e]:this.style[e]=r,this.renderable&&this.renderer)return a?this.renderer.removeProperty(this.renderable,e):this.renderer.setProperty(this.renderable,e,r),this;var s=this.options.sheet;return s&&s.attached,this},e}(),Q=function(e){function t(t,A,n){var r;r=e.call(this,t,A,n)||this;var i=n.selector,o=n.scoped,s=n.sheet,g=n.generateId;return i?r.selectorText=i:!1!==o&&(r.id=g(Object(a.a)(Object(a.a)(r)),s),r.selectorText="."+p(r.id)),r}Object(o.a)(t,e);var A=t.prototype;return A.applyTo=function(e){var t=this.renderer;if(t){var A=this.toJSON();for(var n in A)t.setProperty(e,n,A[n])}return this},A.toJSON=function(){var e={};for(var t in this.style){var A=this.style[t];"object"!==typeof A?e[t]=A:Array.isArray(A)&&(e[t]=I(A))}return e},A.toString=function(e){var t=this.options.sheet,A=!!t&&t.options.link?Object(n.a)({},e,{allowEmpty:!0}):e;return f(this.selectorText,this.style,A)},Object(i.a)(t,[{key:"selector",set:function(e){if(e!==this.selectorText){this.selectorText=e;var t=this.renderer,A=this.renderable;if(A&&t)t.setSelector(A,e)||t.replaceRule(A,this)}},get:function(){return this.selectorText}}]),t}(E),y={onCreateRule:function(e,t,A){return"@"===e[0]||A.parent&&"keyframes"===A.parent.type?null:new Q(e,t,A)}},v={indent:1,children:!0},m=/@([\w-]+)/,b=function(){function e(e,t,A){this.type="conditional",this.isProcessed=!1,this.key=e;var r=e.match(m);for(var i in this.at=r?r[1]:"unknown",this.query=A.name||"@"+this.at,this.options=A,this.rules=new K(Object(n.a)({},A,{parent:this})),t)this.rules.add(i,t[i]);this.rules.process()}var t=e.prototype;return t.getRule=function(e){return this.rules.get(e)},t.indexOf=function(e){return this.rules.indexOf(e)},t.addRule=function(e,t,A){var n=this.rules.add(e,t,A);return n?(this.options.jss.plugins.onProcessRule(n),n):null},t.toString=function(e){void 0===e&&(e=v);var t=C(e).linebreak;if(null==e.indent&&(e.indent=v.indent),null==e.children&&(e.children=v.children),!1===e.children)return this.query+" {}";var A=this.rules.toString(e);return A?this.query+" {"+t+A+t+"}":""},e}(),w=/@media|@supports\s+/,S={onCreateRule:function(e,t,A){return w.test(e)?new b(e,t,A):null}},F={indent:1,children:!0},R=/@keyframes\s+([\w-]+)/,D=function(){function e(e,t,A){this.type="keyframes",this.at="@keyframes",this.isProcessed=!1;var r=e.match(R);r&&r[1]?this.name=r[1]:this.name="noname",this.key=this.type+"-"+this.name,this.options=A;var i=A.scoped,o=A.sheet,a=A.generateId;for(var s in this.id=!1===i?this.name:p(a(this,o)),this.rules=new K(Object(n.a)({},A,{parent:this})),t)this.rules.add(s,t[s],Object(n.a)({},A,{parent:this}));this.rules.process()}return e.prototype.toString=function(e){void 0===e&&(e=F);var t=C(e).linebreak;if(null==e.indent&&(e.indent=F.indent),null==e.children&&(e.children=F.children),!1===e.children)return this.at+" "+this.id+" {}";var A=this.rules.toString(e);return A&&(A=""+t+A+t),this.at+" "+this.id+" {"+A+"}"},e}(),G=/@keyframes\s+/,k=/\$([\w-]+)/g,x=function(e,t){return"string"===typeof e?e.replace(k,(function(e,A){return A in t?t[A]:e})):e},N=function(e,t,A){var n=e[t],r=x(n,A);r!==n&&(e[t]=r)},U={onCreateRule:function(e,t,A){return"string"===typeof e&&G.test(e)?new D(e,t,A):null},onProcessStyle:function(e,t,A){return"style"===t.type&&A?("animation-name"in e&&N(e,"animation-name",A.keyframes),"animation"in e&&N(e,"animation",A.keyframes),e):e},onChangeValue:function(e,t,A){var n=A.options.sheet;if(!n)return e;switch(t){case"animation":case"animation-name":return x(e,n.keyframes);default:return e}}},_=function(e){function t(){return e.apply(this,arguments)||this}return Object(o.a)(t,e),t.prototype.toString=function(e){var t=this.options.sheet,A=!!t&&t.options.link?Object(n.a)({},e,{allowEmpty:!0}):e;return f(this.key,this.style,A)},t}(E),M={onCreateRule:function(e,t,A){return A.parent&&"keyframes"===A.parent.type?new _(e,t,A):null}},O=function(){function e(e,t,A){this.type="font-face",this.at="@font-face",this.isProcessed=!1,this.key=e,this.style=t,this.options=A}return e.prototype.toString=function(e){var t=C(e).linebreak;if(Array.isArray(this.style)){for(var A="",n=0;n=this.index)t.push(e);else for(var n=0;nA)return void t.splice(n,0,e)},t.reset=function(){this.registry=[]},t.remove=function(e){var t=this.registry.indexOf(e);this.registry.splice(t,1)},t.toString=function(e){for(var t=void 0===e?{}:e,A=t.attached,n=Object(s.a)(t,["attached"]),r=C(n).linebreak,i="",o=0;o0){var A=function(e,t){for(var A=0;At.index&&n.options.insertionPoint===t.insertionPoint)return n}return null}(t,e);if(A&&A.renderer)return{parent:A.renderer.element.parentNode,node:A.renderer.element};if((A=function(e,t){for(var A=e.length-1;A>=0;A--){var n=e[A];if(n.attached&&n.options.insertionPoint===t.insertionPoint)return n}return null}(t,e))&&A.renderer)return{parent:A.renderer.element.parentNode,node:A.renderer.element.nextSibling}}var n=e.insertionPoint;if(n&&"string"===typeof n){var r=function(e){for(var t=ae(),A=0;AA?A:t},le=function(){function e(e){this.getPropertyValue=ne,this.setProperty=re,this.removeProperty=ie,this.setSelector=oe,this.hasInsertedRules=!1,this.cssRules=[],e&&q.add(e),this.sheet=e;var t=this.sheet?this.sheet.options:{},A=t.media,n=t.meta,r=t.element;this.element=r||function(){var e=document.createElement("style");return e.textContent="\n",e}(),this.element.setAttribute("data-jss",""),A&&this.element.setAttribute("media",A),n&&this.element.setAttribute("data-meta",n);var i=ge();i&&this.element.setAttribute("nonce",i)}var t=e.prototype;return t.attach=function(){if(!this.element.parentNode&&this.sheet){!function(e,t){var A=t.insertionPoint,n=se(t);if(!1!==n&&n.parent)n.parent.insertBefore(e,n.node);else if(A&&"number"===typeof A.nodeType){var r=A,i=r.parentNode;i&&i.insertBefore(e,r.nextSibling)}else ae().appendChild(e)}(this.element,this.sheet.options);var e=Boolean(this.sheet&&this.sheet.deployed);this.hasInsertedRules&&e&&(this.hasInsertedRules=!1,this.deploy())}},t.detach=function(){if(this.sheet){var e=this.element.parentNode;e&&e.removeChild(this.element),this.sheet.options.link&&(this.cssRules=[],this.element.textContent="\n")}},t.deploy=function(){var e=this.sheet;e&&(e.options.link?this.insertRules(e.rules):this.element.textContent="\n"+e.toString()+"\n")},t.insertRules=function(e,t){for(var A=0;Ag)A.set(t.subarray(0,g),r);else if(A.set(t,r),a)for(var c=s;c=h)){var d=f?n.value:n.getBuffer().getData({srcByteOffset:l});if(n.settings.normalized&&!f){var B=s;s=function(e,t){return n._normalizeConstant(B(e,t))}}var p=f?function(e,t){return s(d,t)}:function(e,t){return s(d.subarray(e,e+u),t)},E=t.getData({length:i}),Q=new Float32Array(h);!function(e){var t=e.source,A=e.target,n=e.size,i=e.getData,o=e.sourceStartIndices,a=e.targetStartIndices;if(!Array.isArray(a))return r({source:t,target:A,size:n,getData:i}),A;for(var s=0,g=0,c=i&&function(e,t){return i(e+g,t)},u=Math.min(o.length,a.length),l=1;l=2&&!Array.isArray(e[0])&&!Array.isArray(e[1]))return e;throw new Error("coord must be GeoJSON Point or an Array of numbers")},t.getCoords=function(e){if(Array.isArray(e))return e;if("Feature"===e.type){if(null!==e.geometry)return e.geometry.coordinates}else if(e.coordinates)return e.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")},t.containsNumber=function e(t){if(t.length>1&&n.isNumber(t[0])&&n.isNumber(t[1]))return!0;if(Array.isArray(t[0])&&t[0].length)return e(t[0]);throw new Error("coordinates must only contain numbers")},t.geojsonType=function(e,t,A){if(!t||!A)throw new Error("type and name required");if(!e||e.type!==t)throw new Error("Invalid input to "+A+": must be a "+t+", given "+e.type)},t.featureOf=function(e,t,A){if(!e)throw new Error("No feature passed");if(!A)throw new Error(".featureOf() requires a name");if(!e||"Feature"!==e.type||!e.geometry)throw new Error("Invalid input to "+A+", Feature with geometry required");if(!e.geometry||e.geometry.type!==t)throw new Error("Invalid input to "+A+": must be a "+t+", given "+e.geometry.type)},t.collectionOf=function(e,t,A){if(!e)throw new Error("No featureCollection passed");if(!A)throw new Error(".collectionOf() requires a name");if(!e||"FeatureCollection"!==e.type)throw new Error("Invalid input to "+A+", FeatureCollection required");for(var n=0,r=e.features;na)throw new TypeError("version is longer than ".concat(a," characters"));i("SemVer",t,A),this.options=A,this.loose=!!A.loose,this.includePrerelease=!!A.includePrerelease;var r=t.trim().match(A.loose?c[u.LOOSE]:c[u.FULL]);if(!r)throw new TypeError("Invalid Version: ".concat(t));if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>s||this.major<0)throw new TypeError("Invalid major version");if(this.minor>s||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>s||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"===typeof this.prerelease[A]&&(this.prerelease[A]++,A=-2);-1===A&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: ".concat(e))}return this.format(),this.raw=this.version,this}}]),e}();e.exports=C},function(e,t,A){var n=A(127),r=A(882),i=A(460),o=Math.max,a=Math.min;e.exports=function(e,t,A){var s,g,c,u,l,I,C=0,h=!1,f=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function B(t){var A=s,n=g;return s=g=void 0,C=t,u=e.apply(n,A)}function p(e){return C=e,l=setTimeout(Q,t),h?B(e):u}function E(e){var A=e-I;return void 0===I||A>=t||A<0||f&&e-C>=c}function Q(){var e=r();if(E(e))return y(e);l=setTimeout(Q,function(e){var A=t-(e-I);return f?a(A,c-(e-C)):A}(e))}function y(e){return l=void 0,d&&s?B(e):(s=g=void 0,u)}function v(){var e=r(),A=E(e);if(s=arguments,g=this,I=e,A){if(void 0===l)return p(I);if(f)return clearTimeout(l),l=setTimeout(Q,t),B(I)}return void 0===l&&(l=setTimeout(Q,t)),u}return t=i(t)||0,n(A)&&(h=!!A.leading,c=(f="maxWait"in A)?o(i(A.maxWait)||0,t):c,d="trailing"in A?!!A.trailing:d),v.cancel=function(){void 0!==l&&clearTimeout(l),C=0,s=I=g=l=void 0},v.flush=function(){return void 0===l?u:y(r())},v}},function(e,t,A){"use strict";A.d(t,"c",(function(){return i})),A.d(t,"b",(function(){return o})),A.d(t,"a",(function(){return a}));var n=A(26),r={};function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"id";r[e]=r[e]||1;var t=r[e]++;return"".concat(e,"-").concat(t)}function o(e){return Object(n.a)("number"===typeof e,"Input must be a number"),e&&0===(e&e-1)}function a(e){var t=!0;for(var A in e){t=!1;break}return t}},function(e,t,A){"use strict";A.d(t,"b",(function(){return r})),A.d(t,"a",(function(){return i}));var n=A(26);function r(e,t){if("string"!==typeof t)return t;var A=Number(t);if(!isNaN(A))return A;var r=e[t=t.replace(/^.*\./,"")];return Object(n.a)(void 0!==r,"Accessing undefined constant GL.".concat(t)),r}function i(e,t){for(var A in t=Number(t),e)if(e[A]===t)return"GL.".concat(A);return String(t)}},function(e,t,A){var n;!function(A){"use strict";var r=function(e){return.5*(Math.exp(e)+Math.exp(-e))},i=function(e){return.5*(Math.exp(e)-Math.exp(-e))},o=function(){throw SyntaxError("Invalid Param")};function a(e,t){var A=Math.abs(e),n=Math.abs(t);return 0===e?Math.log(n):0===t?Math.log(A):A<3e3&&n<3e3?.5*Math.log(e*e+t*t):Math.log(e/Math.cos(Math.atan2(t,e)))}function s(e,t){if(!(this instanceof s))return new s(e,t);var A=function(e,t){var A={re:0,im:0};if(void 0===e||null===e)A.re=A.im=0;else if(void 0!==t)A.re=e,A.im=t;else switch(typeof e){case"object":if("im"in e&&"re"in e)A.re=e.re,A.im=e.im;else if("abs"in e&&"arg"in e){if(!Number.isFinite(e.abs)&&Number.isFinite(e.arg))return s.INFINITY;A.re=e.abs*Math.cos(e.arg),A.im=e.abs*Math.sin(e.arg)}else if("r"in e&&"phi"in e){if(!Number.isFinite(e.r)&&Number.isFinite(e.phi))return s.INFINITY;A.re=e.r*Math.cos(e.phi),A.im=e.r*Math.sin(e.phi)}else 2===e.length?(A.re=e[0],A.im=e[1]):o();break;case"string":A.im=A.re=0;var n=e.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g),r=1,i=0;null===n&&o();for(var a=0;a0&&o();break;case"number":A.im=0,A.re=e;break;default:o()}return isNaN(A.re)||isNaN(A.im),A}(e,t);this.re=A.re,this.im=A.im}s.prototype={re:0,im:0,sign:function(){var e=this.abs();return new s(this.re/e,this.im/e)},add:function(e,t){var A=new s(e,t);return this.isInfinite()&&A.isInfinite()?s.NAN:this.isInfinite()||A.isInfinite()?s.INFINITY:new s(this.re+A.re,this.im+A.im)},sub:function(e,t){var A=new s(e,t);return this.isInfinite()&&A.isInfinite()?s.NAN:this.isInfinite()||A.isInfinite()?s.INFINITY:new s(this.re-A.re,this.im-A.im)},mul:function(e,t){var A=new s(e,t);return this.isInfinite()&&A.isZero()||this.isZero()&&A.isInfinite()?s.NAN:this.isInfinite()||A.isInfinite()?s.INFINITY:0===A.im&&0===this.im?new s(this.re*A.re,0):new s(this.re*A.re-this.im*A.im,this.re*A.im+this.im*A.re)},div:function(e,t){var A=new s(e,t);if(this.isZero()&&A.isZero()||this.isInfinite()&&A.isInfinite())return s.NAN;if(this.isInfinite()||A.isZero())return s.INFINITY;if(this.isZero()||A.isInfinite())return s.ZERO;e=this.re,t=this.im;var n,r,i=A.re,o=A.im;return 0===o?new s(e/i,t/i):Math.abs(i)=0)return new s(Math.pow(e,A.re),0);if(0===e)switch((A.re%4+4)%4){case 0:return new s(Math.pow(t,A.re),0);case 1:return new s(0,Math.pow(t,A.re));case 2:return new s(-Math.pow(t,A.re),0);case 3:return new s(0,-Math.pow(t,A.re))}}if(0===e&&0===t&&A.re>0&&A.im>=0)return s.ZERO;var n=Math.atan2(t,e),r=a(e,t);return e=Math.exp(A.re*r-A.im*n),t=A.im*r+A.re*n,new s(e*Math.cos(t),e*Math.sin(t))},sqrt:function(){var e,t,A=this.re,n=this.im,r=this.abs();if(A>=0){if(0===n)return new s(Math.sqrt(A),0);e=.5*Math.sqrt(2*(r+A))}else e=Math.abs(n)/Math.sqrt(2*(r-A));return t=A<=0?.5*Math.sqrt(2*(r-A)):Math.abs(n)/Math.sqrt(2*(r+A)),new s(e,n<0?-t:t)},exp:function(){var e=Math.exp(this.re);return this.im,new s(e*Math.cos(this.im),e*Math.sin(this.im))},expm1:function(){var e=this.re,t=this.im;return new s(Math.expm1(e)*Math.cos(t)+function(e){var t=Math.PI/4;if(e<-t||e>t)return Math.cos(e)-1;var A=e*e;return A*(A*(1/24+A*(-1/720+A*(1/40320+A*(-1/3628800+A*(1/4790014600+A*(-1/87178291200+A*(1/20922789888e3)))))))-.5)}(t),Math.exp(e)*Math.sin(t))},log:function(){var e=this.re,t=this.im;return new s(a(e,t),Math.atan2(t,e))},abs:function(){return function(e,t){var A=Math.abs(e),n=Math.abs(t);return A<3e3&&n<3e3?Math.sqrt(A*A+n*n):(A1&&0===t,n=1-e,r=1+e,i=n*n+t*t,o=0!==i?new s((r*n-t*t)/i,(t*n+r*t)/i):new s(-1!==e?e/0:0,0!==t?t/0:0),g=o.re;return o.re=a(o.re,o.im)/2,o.im=Math.atan2(o.im,g)/2,A&&(o.im=-o.im),o},acoth:function(){var e=this.re,t=this.im;if(0===e&&0===t)return new s(0,Math.PI/2);var A=e*e+t*t;return 0!==A?new s(e/A,-t/A).atanh():new s(0!==e?e/0:0,0!==t?-t/0:0).atanh()},acsch:function(){var e=this.re,t=this.im;if(0===t)return new s(0!==e?Math.log(e+Math.sqrt(e*e+1)):1/0,0);var A=e*e+t*t;return 0!==A?new s(e/A,-t/A).asinh():new s(0!==e?e/0:0,0!==t?-t/0:0).asinh()},asech:function(){var e=this.re,t=this.im;if(this.isZero())return s.INFINITY;var A=e*e+t*t;return 0!==A?new s(e/A,-t/A).acosh():new s(0!==e?e/0:0,0!==t?-t/0:0).acosh()},inverse:function(){if(this.isZero())return s.INFINITY;if(this.isInfinite())return s.ZERO;var e=this.re,t=this.im,A=e*e+t*t;return new s(e/A,-t/A)},conjugate:function(){return new s(this.re,-this.im)},neg:function(){return new s(-this.re,-this.im)},ceil:function(e){return e=Math.pow(10,e||0),new s(Math.ceil(this.re*e)/e,Math.ceil(this.im*e)/e)},floor:function(e){return e=Math.pow(10,e||0),new s(Math.floor(this.re*e)/e,Math.floor(this.im*e)/e)},round:function(e){return e=Math.pow(10,e||0),new s(Math.round(this.re*e)/e,Math.round(this.im*e)/e)},equals:function(e,t){var A=new s(e,t);return Math.abs(A.re-this.re)<=s.EPSILON&&Math.abs(A.im-this.im)<=s.EPSILON},clone:function(){return new s(this.re,this.im)},toString:function(){var e=this.re,t=this.im,A="";return this.isNaN()?"NaN":this.isZero()?"0":this.isInfinite()?"Infinity":(0!==e&&(A+=e),0!==t&&(0!==e?A+=t<0?" - ":" + ":t<0&&(A+="-"),1!==(t=Math.abs(t))&&(A+=t),A+="i"),A||"0")},toVector:function(){return[this.re,this.im]},valueOf:function(){return 0===this.im?this.re:null},isNaN:function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(){return isNaN(this.re)||isNaN(this.im)})),isZero:function(){return(0===this.re||-0===this.re)&&(0===this.im||-0===this.im)},isFinite:function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(){return isFinite(this.re)&&isFinite(this.im)})),isInfinite:function(){return!(this.isNaN()||this.isFinite())}},s.ZERO=new s(0,0),s.ONE=new s(1,0),s.I=new s(0,1),s.PI=new s(Math.PI,0),s.E=new s(Math.E,0),s.INFINITY=new s(1/0,1/0),s.NAN=new s(NaN,NaN),s.EPSILON=1e-16,void 0===(n=function(){return s}.apply(t,[]))||(e.exports=n)}()},function(e,t){var A=Array.isArray;e.exports=A},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=A(105),r=A(59);t.default=function(e,t,A){void 0===A&&(A={});var i=n.getCoord(e),o=n.getCoord(t),a=r.degreesToRadians(o[1]-i[1]),s=r.degreesToRadians(o[0]-i[0]),g=r.degreesToRadians(i[1]),c=r.degreesToRadians(o[1]),u=Math.pow(Math.sin(a/2),2)+Math.pow(Math.sin(s/2),2)*Math.cos(g)*Math.cos(c);return r.radiansToLength(2*Math.atan2(Math.sqrt(u),Math.sqrt(1-u)),A.units)}},function(e,t,A){"use strict";var n=A(14),r=A(0),i=A.n(r),o=A(21),a=(A(13),A(19)),s=A(28),g=A(40),c=r.forwardRef((function(e,t){var A=e.children,i=e.classes,s=e.className,c=e.color,u=void 0===c?"inherit":c,l=e.component,I=void 0===l?"svg":l,C=e.fontSize,h=void 0===C?"medium":C,f=e.htmlColor,d=e.titleAccess,B=e.viewBox,p=void 0===B?"0 0 24 24":B,E=Object(o.a)(e,["children","classes","className","color","component","fontSize","htmlColor","titleAccess","viewBox"]);return r.createElement(I,Object(n.a)({className:Object(a.a)(i.root,s,"inherit"!==u&&i["color".concat(Object(g.a)(u))],"default"!==h&&"medium"!==h&&i["fontSize".concat(Object(g.a)(h))]),focusable:"false",viewBox:p,color:f,"aria-hidden":!d||void 0,role:d?"img":void 0,ref:t},E),A,d?r.createElement("title",null,d):null)}));c.muiName="SvgIcon";var u=Object(s.a)((function(e){return{root:{userSelect:"none",width:"1em",height:"1em",display:"inline-block",fill:"currentColor",flexShrink:0,fontSize:e.typography.pxToRem(24),transition:e.transitions.create("fill",{duration:e.transitions.duration.shorter})},colorPrimary:{color:e.palette.primary.main},colorSecondary:{color:e.palette.secondary.main},colorAction:{color:e.palette.action.active},colorError:{color:e.palette.error.main},colorDisabled:{color:e.palette.action.disabled},fontSizeInherit:{fontSize:"inherit"},fontSizeSmall:{fontSize:e.typography.pxToRem(20)},fontSizeLarge:{fontSize:e.typography.pxToRem(35)}}}),{name:"MuiSvgIcon"})(c);function l(e,t){var A=function(t,A){return i.a.createElement(u,Object(n.a)({ref:A},t),e)};return A.muiName=u.muiName,i.a.memo(i.a.forwardRef(A))}A.d(t,"a",(function(){return l}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return i}));var n=A(532),r=(A(0),A(205));function i(){return Object(n.a)()||r.a}},function(e,t,A){"use strict";function n(e,t){if(!e)throw new Error(t||"loaders.gl assertion failed.")}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return i})),A.d(t,"c",(function(){return o})),A.d(t,"b",(function(){return a}));var n=[],r=[];function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1/0,i=n,o={index:-1,data:e,target:[]};return e?"function"===typeof e[Symbol.iterator]?i=e:e.length>0&&(r.length=e.length,i=r):i=n,(t>0||Number.isFinite(A))&&(i=(Array.isArray(i)?i:Array.from(i)).slice(t,A),o.index=t-1),{iterable:i,objectInfo:o}}function o(e){return e&&e[Symbol.asyncIterator]}function a(e,t){var A=t.size,n=t.stride,r=t.offset,i=t.startIndices,o=t.nested,a=e.BYTES_PER_ELEMENT,s=n?n/a:A,g=r?r/a:0,c=Math.floor((e.length-g)/s);return function(t,n){var r=n.index,a=n.target;if(!i){for(var u=r*s+g,l=0;l0))return o;do{o.push(i=new Date(+A)),t(A,r),e(A)}while(i=t)for(;e(t),!A(t);)t.setTime(t-1)}),(function(e,n){if(e>=e)if(n<0)for(;++n<=0;)for(;t(e,-1),!A(e););else for(;--n>=0;)for(;t(e,1),!A(e););}))},A&&(a.count=function(t,i){return n.setTime(+t),r.setTime(+i),e(n),e(r),Math.floor(A(n,r))},a.every=function(e){return e=Math.floor(e),isFinite(e)&&e>0?e>1?a.filter(o?function(t){return o(t)%e===0}:function(t){return a.count(0,t)%e===0}):a:null}),a}},,function(e,t,A){"use strict";A.d(t,"b",(function(){return n})),A.d(t,"c",(function(){return r})),A.d(t,"a",(function(){return i})),A.d(t,"d",(function(){return o}));function n(e){switch(ArrayBuffer.isView(e)?e.constructor:e){case Float32Array:return 5126;case Uint16Array:return 5123;case Uint32Array:return 5125;case Uint8Array:case Uint8ClampedArray:return 5121;case Int8Array:return 5120;case Int16Array:return 5122;case Int32Array:return 5124;default:throw new Error("Failed to deduce GL constant from typed array")}}function r(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.clamped,n=void 0===A||A;switch(e){case 5126:return Float32Array;case 5123:case 33635:case 32819:case 32820:return Uint16Array;case 5125:return Uint32Array;case 5121:return n?Uint8ClampedArray:Uint8Array;case 5120:return Int8Array;case 5122:return Int16Array;case 5124:return Int32Array;default:throw new Error("Failed to deduce typed array type from GL constant")}}function i(e){var t=e.data,A=e.width,n=e.height,r=e.bytesPerPixel,i=void 0===r?4:r,o=e.temp,a=A*i;o=o||new Uint8Array(a);for(var s=0;s=r){var l=c.distanceTo(t.cameraPosition)*t.scale/t.height;u+=Math.floor(Math.log2(l))}if(u>=o)return this.selected=!0,!0}this.selected=!1,this.childVisible=!0;var I,C=Object(i.a)(this.children);try{for(C.s();!(I=C.n()).done;){I.value.update(e)}}catch(h){C.e(h)}finally{C.f()}return!0}},{key:"getSelected",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(this.selected&&e.push(this),this._children){var t,A=Object(i.a)(this._children);try{for(A.s();!(t=A.n()).done;){var n=t.value;n.getSelected(e)}}catch(r){A.e(r)}finally{A.f()}}return e}},{key:"insideBounds",value:function(e){var t=Object(n.a)(e,4),A=t[0],r=t[1],i=t[2],o=t[3],a=512/Math.pow(2,this.z);return this.x*aA&&(this.y+1)*a>r}},{key:"getBoundingVolume",value:function(e,t,A){if(A){var n,r=this.z<1?l:this.z<2?u:c,o=[],a=Object(i.a)(r);try{for(a.s();!(n=a.n()).done;){var g=n.value,I=p(this.x+g[0],this.y+g[1],this.z);I[2]=e[0],o.push(A(I)),e[0]!==e[1]&&(I[2]=e[1],o.push(A(I)))}}catch(d){a.e(d)}finally{a.f()}return Object(s.f)(o)}var C=512/Math.pow(2,this.z),h=this.x*C+512*t,f=512-(this.y+1)*C;return new s.a([h,f,e[0]],[h+C,f+C,e[1]])}},{key:"children",get:function(){if(!this._children){var t=2*this.x,A=2*this.y,n=this.z+1;this._children=[new e(t,A,n),new e(t,A+1,n),new e(t+1,A,n),new e(t+1,A+1,n)]}return this._children}}]),e}();A.d(t,"f",(function(){return h})),A.d(t,"b",(function(){return d})),A.d(t,"d",(function(){return p})),A.d(t,"e",(function(){return Q})),A.d(t,"a",(function(){return v})),A.d(t,"c",(function(){return m}));var C=[-1/0,-1/0,1/0,1/0],h={type:"url",value:null,validate:function(e,t){return t.optional&&null===e||"string"===typeof e||Array.isArray(e)&&e.every((function(e){return"string"===typeof e}))},equals:function(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t))return!1;var A=e.length;if(A!==t.length)return!1;for(var n=0;n4&&void 0!==arguments[4]?arguments[4]:512;if(e.isGeospatial){var o=p(t,A,r),a=Object(n.a)(o,2),s=a[0],g=a[1],c=p(t+1,A+1,r),u=Object(n.a)(c,2),l=u[0],I=u[1];return{west:s,north:g,east:l,south:I}}var C=E(t,A,r,i),h=Object(n.a)(C,2),f=h[0],d=h[1],B=E(t+1,A+1,r,i),Q=Object(n.a)(B,2),y=Q[0],v=Q[1];return{left:f,top:d,right:y,bottom:v}}function y(e,t,A,r,i){for(var o=function(e,t,A){return A?f(e,A).map((function(e){return e*t/512})):e.map((function(e){return e*t/512}))}(function(e,t,A){var r;if(t&&2===t.length){var i=Object(n.a)(t,2),o=i[0],a=i[1],s=e.getBounds({z:o}),g=e.getBounds({z:a});r=[Math.min(s[0],g[0]),Math.min(s[1],g[1]),Math.max(s[2],g[2]),Math.max(s[3],g[3])]}else r=e.getBounds();return e.isGeospatial?[Math.max(r[0],A[0]),Math.max(r[1],A[1]),Math.min(r[2],A[2]),Math.min(r[3],A[3])]:[Math.max(Math.min(r[0],A[2]),A[0]),Math.max(Math.min(r[1],A[3]),A[1]),Math.min(Math.max(r[2],A[0]),A[2]),Math.min(Math.max(r[3],A[1]),A[3])]}(e,null,r),B(t,A),i),a=Object(n.a)(o,4),s=a[0],g=a[1],c=a[2],u=a[3],l=[],I=Math.floor(s);IA&&(B=A);var p=o;return u&&l&&o&&!t.isGeospatial&&(p=f(o,u)),t.isGeospatial?function(e,t,A,r){var i=e.resolution?e.projectPosition:null,o=Object.values(e.getFrustumPlanes()).map((function(e){var t=e.normal,A=e.distance;return new s.e(t.clone().negate(),A)})),a=new s.c(o),c=e.distanceScales.unitsPerMeter[2],u=A&&A[0]*c||0,l=A&&A[1]*c||0,C=e.pitch<=60?t:0;if(r){var h=r,f=Object(n.a)(h,4),d=f[0],B=f[1],p=f[2],E=f[3],Q=Object(g.n)([d,E]),y=Object(g.n)([p,B]);r=[Q[0],512-Q[1],y[0],512-y[1]]}var v=new I(0,0,0),m={viewport:e,project:i,cullingVolume:a,elevationBounds:[u,l],minZ:C,maxZ:t,bounds:r,offset:0};if(v.update(m),e.subViewports&&e.subViewports.length>1){for(m.offset=-1;v.update(m)&&!(--m.offset<-3););for(m.offset=1;v.update(m)&&!(++m.offset>3););}return v.getSelected()}(t,B,i,o):y(t,B,c,p||C,l)}function m(e){return/(?=.*{z})(?=.*{x})(?=.*({y}|{-y}))/.test(e)}},function(e,t,A){"use strict";var n=A(816),r=A(461),i=A(820),o=A(560),a=A(272),s=A(821),g=A(822),c=A(843),u=A(250);e.exports=d,d.prototype.validate=function(e,t){var A;if("string"==typeof e){if(!(A=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var n=this._addSchema(e);A=n.validate||this._compile(n)}var r=A(t);!0!==A.$async&&(this.errors=A.errors);return r},d.prototype.compile=function(e,t){var A=this._addSchema(e,void 0,t);return A.validate||this._compile(A)},d.prototype.addSchema=function(e,t,A,n){if(Array.isArray(e)){for(var i=0;i0))return 0;for(var r=A,i=A+n-1,o=0;o=55296&&a<=57343){var s=e.charCodeAt(++o);a=65536+((1023&a)<<10)|1023&s}if(a<=127){if(A>=i)break;t[A++]=a}else if(a<=2047){if(A+1>=i)break;t[A++]=192|a>>6,t[A++]=128|63&a}else if(a<=65535){if(A+2>=i)break;t[A++]=224|a>>12,t[A++]=128|a>>6&63,t[A++]=128|63&a}else{if(A+3>=i)break;t[A++]=240|a>>18,t[A++]=128|a>>12&63,t[A++]=128|a>>6&63,t[A++]=128|63&a}}t[A]=0})(e,B,t,A)})(e,t=ee(A),A)}return t},array:function(e){var t=ee(e.length);return function(e,t){d.set(e,t)}(e,t),t}};var o=l(e),a=[],s=0;if(n)for(var g=0;g=n);)++r;if(r-t>16&&e.subarray&&C)return C.decode(e.subarray(t,r));for(var i="";t>10,56320|1023&g)}}else i+=String.fromCharCode((31&o)<<6|a)}else i+=String.fromCharCode(o)}return i}(B,e,t):""}var f,d,B,p,E,Q,y;"undefined"!==typeof TextDecoder&&new TextDecoder("utf-16le");function v(e,t){return e%t>0&&(e+=t-e%t),e}function m(e){f=e,A.HEAP8=d=new Int8Array(e),A.HEAP16=p=new Int16Array(e),A.HEAP32=E=new Int32Array(e),A.HEAPU8=B=new Uint8Array(e),A.HEAPU16=new Uint16Array(e),A.HEAPU32=new Uint32Array(e),A.HEAPF32=Q=new Float32Array(e),A.HEAPF64=y=new Float64Array(e)}var b=A.TOTAL_MEMORY||33554432;function w(e){for(;e.length>0;){var t=e.shift();if("function"!=typeof t){var n=t.func;"number"===typeof n?void 0===t.arg?A.dynCall_v(n):A.dynCall_vi(n,t.arg):n(void 0===t.arg?null:t.arg)}else t()}}b=(f=A.buffer?A.buffer:new ArrayBuffer(b)).byteLength,m(f),E[6004]=5266928;var S=[],F=[],R=[],D=[];var G=Math.abs,k=Math.ceil,x=Math.floor,N=Math.min,U=0,_=null,M=null;A.preloadedImages={},A.preloadedAudios={};var O,L,T=null,Z="data:application/octet-stream;base64,";function H(e){return String.prototype.startsWith?e.startsWith(Z):0===e.indexOf(Z)}T="data:application/octet-stream;base64,AAAAAAAAAAACAAAAAwAAAAEAAAAFAAAABAAAAAYAAAAAAAAAAAAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAYAAAABAAAABAAAAAMAAAAGAAAABQAAAAIAAAAAAAAAAgAAAAMAAAABAAAABAAAAAYAAAAAAAAABQAAAAMAAAAGAAAABAAAAAUAAAAAAAAAAQAAAAIAAAAEAAAABQAAAAYAAAAAAAAAAgAAAAMAAAABAAAABQAAAAIAAAAAAAAAAQAAAAMAAAAGAAAABAAAAAYAAAAAAAAABQAAAAIAAAABAAAABAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAgAAAAMAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAABgAAAAAAAAAFAAAAAAAAAAAAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAABgAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAAA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TwDy84z/Z6jfQ2TgTQChOCXMnWwpAhrW3daoz8z/HYJvVPI4VQLT3ik5FcA5Angi7LOZd+z+NNVzDy5gXQBXdvVTFUA1AYNMgOeYe+T8+qHXGCwkXQKQTOKwa5AJA8gFVoEMW0T+FwzJyttIRQAEAAAD/////BwAAAP////8xAAAA/////1cBAAD/////YQkAAP////+nQQAA/////5HLAQD/////95AMAP/////B9lcAAAAAAAAAAAAAAAAAAgAAAP////8OAAAA/////2IAAAD/////rgIAAP/////CEgAA/////06DAAD/////IpcDAP/////uIRkA/////4LtrwAAAAAAAAAAAAAAAAAAAAAAAgAAAP//////////AQAAAAMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////wIAAAD//////////wEAAAAAAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA/////////////////////wEAAAD///////////////8CAAAA////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD///////////////////////////////8CAAAA////////////////AQAAAP////////////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAAAQAAAP//////////AgAAAP//////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAAEAAAD//////////wIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAgAAAAAAAAACAAAAAQAAAAEAAAACAAAAAgAAAAAAAAAFAAAABQAAAAAAAAACAAAAAgAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAABAAAAAgAAAAIAAAACAAAAAAAAAAUAAAAGAAAAAAAAAAIAAAACAAAAAwAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAAAAAAAAgAAAAEAAAADAAAAAgAAAAIAAAAAAAAABQAAAAcAAAAAAAAAAgAAAAIAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAACAAAAAQAAAAQAAAACAAAAAgAAAAAAAAAFAAAACAAAAAAAAAACAAAAAgAAAAMAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAACAAAAAAAAAAIAAAABAAAAAAAAAAIAAAACAAAAAAAAAAUAAAAJAAAAAAAAAAIAAAACAAAAAwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAIAAAACAAAAAAAAAAMAAAAOAAAAAgAAAAAAAAACAAAAAwAAAAAAAAAAAAAAAgAAAAIAAAADAAAABgAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAgAAAAIAAAAAAAAAAwAAAAoAAAACAAAAAAAAAAIAAAADAAAAAQAAAAAAAAACAAAAAgAAAAMAAAAHAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAACAAAAAgAAAAAAAAADAAAACwAAAAIAAAAAAAAAAgAAAAMAAAACAAAAAAAAAAIAAAACAAAAAwAAAAgAAAAAAAAAAAAAAAAAAAAA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LNAP6jGS5cA5zBBwcqhBdCNGUEGEhQ/JVEDQT6WPnRbNO1AB/AWSJgT1kDfUWNCNLDAQNk+5C33OqlAchWL34QSk0DKvtDIrNV8QNF0G3kFzGVASSeWhBl6UED+/0mNGuk4QGjA/dm/1CJALPLPMql6DEDSHoDrwpP1P2jouzWST+A/egAAAAAAAABKAwAAAAAAAPoWAAAAAAAAyqAAAAAAAAB6ZQQAAAAAAErGHgAAAAAA+mvXAAAAAADK8+MFAAAAAHqqOykAAAAASqmhIAEAAAD6oGvkBwAAAMpm8T43AAAAes+ZuIIBAABKrDQMkwoAAPq1cFUFSgAAyvkUViUGAgAAAAAAAwAAAAYAAAACAAAABQAAAAEAAAAEAAAAAAAAAAAAAAAFAAAAAwAAAAEAAAAGAAAABAAAAAIAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAA/////wAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAP////8AAAAAAAAAAAEAAAABAAAAAAAAAAAAAAD/////AAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAA/////wUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////AAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////////////////////wAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAA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ZXJJSksuZmFjZV1bZmFjZTJdID09IEtJAF9mYWNlSWprVG9HZW9Cb3VuZGFyeQBwb2x5Z29uLT5uZXh0ID09IE5VTEwAbGlua2VkR2VvLmMAYWRkTmV3TGlua2VkUG9seWdvbgBuZXh0ICE9IE5VTEwAbG9vcCAhPSBOVUxMAGFkZE5ld0xpbmtlZExvb3AAcG9seWdvbi0+Zmlyc3QgPT0gTlVMTABhZGRMaW5rZWRMb29wAGNvb3JkICE9IE5VTEwAYWRkTGlua2VkQ29vcmQAbG9vcC0+Zmlyc3QgPT0gTlVMTABpbm5lckxvb3BzICE9IE5VTEwAbm9ybWFsaXplTXVsdGlQb2x5Z29uAGJib3hlcyAhPSBOVUxMAGNhbmRpZGF0ZXMgIT0gTlVMTABmaW5kUG9seWdvbkZvckhvbGUAY2FuZGlkYXRlQkJveGVzICE9IE5VTEwAcmV2RGlyICE9IElOVkFMSURfRElHSVQAbG9jYWxpai5jAGgzVG9Mb2NhbElqawBiYXNlQ2VsbCAhPSBvcmlnaW5CYXNlQ2VsbAAhKG9yaWdpbk9uUGVudCAmJiBpbmRleE9uUGVudCkAcGVudGFnb25Sb3RhdGlvbnMgPj0gMABkaXJlY3Rpb25Sb3RhdGlvbnMgPj0gMABiYXNlQ2VsbCA9PSBvcmlnaW5CYXNlQ2VsbABiYXNlQ2VsbCAhPSBJTlZBTElEX0JBU0VfQ0VMTABsb2NhbElqa1RvSDMAIV9pc0Jhc2VDZWxsUGVudGFnb24oYmFzZUNlbGwpAGJhc2VDZWxsUm90YXRpb25zID49IDAAd2l0aGluUGVudGFnb25Sb3RhdGlvbnMgPj0gMABncmFwaC0+YnVja2V0cyAhPSBOVUxMAHZlcnRleEdyYXBoLmMAaW5pdFZlcnRleEdyYXBoAG5vZGUgIT0gTlVMTABhZGRWZXJ0ZXhOb2Rl";function Y(e){return e}function J(e){return e.replace(/\b__Z[\w\d_]+/g,(function(e){return e===e?e:e+" ["+e+"]"}))}function j(){var e=new Error;if(!e.stack){try{throw new Error(0)}catch(t){e=t}if(!e.stack)return"(no stack trace available)"}return e.stack.toString()}function P(){return d.length}function V(e){try{var t=new ArrayBuffer(e);if(t.byteLength!=e)return;return new Int8Array(t).set(d),$(t),m(t),1}catch(A){}}var K="function"===typeof atob?atob:function(e){var t,A,n,r,i,o,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",s="",g=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{t=a.indexOf(e.charAt(g++))<<2|(r=a.indexOf(e.charAt(g++)))>>4,A=(15&r)<<4|(i=a.indexOf(e.charAt(g++)))>>2,n=(3&i)<<6|(o=a.indexOf(e.charAt(g++))),s+=String.fromCharCode(t),64!==i&&(s+=String.fromCharCode(A)),64!==o&&(s+=String.fromCharCode(n))}while(g>2]=e,r[a+4>>2]=t,(a=0!=(0|i))&&(r[i>>2]=0),0|Ne(e,t))return D=o,0|(C=1);r[C>>2]=0;e:do{if((0|A)>=1)if(a)for(u=0,l=1,I=1,s=0,a=e;;){if(!(s|u)){if(0==(0|(a=0|N(a,t,4,C)))&0==(0|(t=0|v()))){a=2;break e}if(0|Ne(a,t)){a=1;break e}}if(0==(0|(a=0|N(a,t,0|r[16+(u<<2)>>2],C)))&0==(0|(t=0|v()))){a=2;break e}if(r[(e=n+(I<<3)|0)>>2]=a,r[e+4>>2]=t,r[i+(I<<2)>>2]=l,e=(0|(s=s+1|0))==(0|l),c=6==(0|(g=u+1|0)),0|Ne(a,t)){a=1;break e}if((0|(l=l+(c&e&1)|0))>(0|A)){a=0;break}u=e?c?0:g:u,I=I+1|0,s=e?0:s}else for(u=0,l=1,I=1,s=0,a=e;;){if(!(s|u)){if(0==(0|(a=0|N(a,t,4,C)))&0==(0|(t=0|v()))){a=2;break e}if(0|Ne(a,t)){a=1;break e}}if(0==(0|(a=0|N(a,t,0|r[16+(u<<2)>>2],C)))&0==(0|(t=0|v()))){a=2;break e}if(r[(e=n+(I<<3)|0)>>2]=a,r[e+4>>2]=t,e=(0|(s=s+1|0))==(0|l),c=6==(0|(g=u+1|0)),0|Ne(a,t)){a=1;break e}if((0|(l=l+(c&e&1)|0))>(0|A)){a=0;break}u=e?c?0:g:u,I=I+1|0,s=e?0:s}else a=0}while(0);return D=o,0|(C=a)}function x(e,t,A,n,i,o,a){A|=0,n|=0,i|=0,o|=0,a|=0;var s,g,c=0,u=0,l=0,I=0,C=0;if(g=D,D=D+16|0,s=g,0==(0|(e|=0))&0==(0|(t|=0)))D=g;else{if(c=0|vt(0|e,0|t,0|o,((0|o)<0)<<31>>31|0),v(),!(0==(0|(C=0|r[(I=u=n+(c<<3)|0)>>2]))&0==(0|(I=0|r[I+4>>2]))|(l=(0|C)==(0|e)&(0|I)==(0|t))))do{l=(0|(I=0|r[(C=u=n+((c=(c+1|0)%(0|o)|0)<<3)|0)>>2]))==(0|e)&(0|(C=0|r[C+4>>2]))==(0|t)}while(!(0==(0|I)&0==(0|C)|l));c=i+(c<<2)|0,l&&(0|r[c>>2])<=(0|a)||(r[(C=u)>>2]=e,r[C+4>>2]=t,r[c>>2]=a,(0|a)>=(0|A)||(C=a+1|0,r[s>>2]=0,x(I=0|N(e,t,2,s),0|v(),A,n,i,o,C),r[s>>2]=0,x(I=0|N(e,t,3,s),0|v(),A,n,i,o,C),r[s>>2]=0,x(I=0|N(e,t,1,s),0|v(),A,n,i,o,C),r[s>>2]=0,x(I=0|N(e,t,5,s),0|v(),A,n,i,o,C),r[s>>2]=0,x(I=0|N(e,t,4,s),0|v(),A,n,i,o,C),r[s>>2]=0,x(I=0|N(e,t,6,s),0|v(),A,n,i,o,C))),D=g}}function N(e,t,A,n){e|=0,t|=0,A|=0;var i,o,a=0,s=0,g=0,c=0,u=0,l=0,I=0;if((0|r[(n|=0)>>2])>0){a=0;do{A=0|se(A),a=a+1|0}while((0|a)<(0|r[n>>2]))}i=0|mt(0|e,0|t,45),v(),o=127&i,s=0|Ue(e,t),a=0|mt(0|e,0|t,52),v(),a&=15;e:do{if(a)for(;;){if(l=0|mt(0|e,0|t,0|(u=3*(15-a|0)|0)),v(),l&=7,I=0==(0|Te(a)),a=a+-1|0,c=0|bt(7,0,0|u),t&=~(0|v()),e=(u=0|bt(0|r[(I?464:48)+(28*l|0)+(A<<2)>>2],0,0|u))|e&~c,t|=0|v(),!(A=0|r[(I?672:256)+(28*l|0)+(A<<2)>>2])){A=0;break e}if(!a){g=6;break}}else g=6}while(0);6==(0|g)&&(e|=l=0|bt(0|(I=0|r[880+(28*o|0)+(A<<2)>>2]),0,45),t=0|v()|-1040385&t,A=0|r[4304+(28*o|0)+(A<<2)>>2],127==(127&I|0)&&(I=0|bt(0|r[880+(28*o|0)+20>>2],0,45),t=0|v()|-1040385&t,A=0|r[4304+(28*o|0)+20>>2],e=0|Me(I|e,t),t=0|v(),r[n>>2]=1+(0|r[n>>2]))),g=0|mt(0|e,0|t,45),v(),g&=127;e:do{if(0|_(g)){t:do{if(1==(0|Ue(e,t))){if((0|o)!=(0|g)){if(0|T(g,0|r[7728+(28*o|0)>>2])){e=0|Le(e,t),s=1,t=0|v();break}e=0|Me(e,t),s=1,t=0|v();break}switch(0|s){case 5:e=0|Le(e,t),t=0|v(),r[n>>2]=5+(0|r[n>>2]),s=0;break t;case 3:e=0|Me(e,t),t=0|v(),r[n>>2]=1+(0|r[n>>2]),s=0;break t;default:return I=0,y(0|(l=0)),0|I}}else s=0}while(0);if((0|A)>0){a=0;do{e=0|_e(e,t),t=0|v(),a=a+1|0}while((0|a)!=(0|A))}if((0|o)!=(0|g)){if(!(0|M(g))){if(0!=(0|s)|5!=(0|Ue(e,t)))break;r[n>>2]=1+(0|r[n>>2]);break}switch(127&i){case 8:case 118:break e}3!=(0|Ue(e,t))&&(r[n>>2]=1+(0|r[n>>2]))}}else if((0|A)>0){a=0;do{e=0|Me(e,t),t=0|v(),a=a+1|0}while((0|a)!=(0|A))}}while(0);return r[n>>2]=((0|r[n>>2])+A|0)%6|0,I=e,y(0|(l=t)),0|I}function U(e,t,A,n,o,a){t|=0,A|=0,n|=0,o|=0,a|=0;var s,g,c,u,l,I,C,h,f,d=0,B=0,p=0,E=0,Q=0,y=0,m=0,b=0,w=0,S=0,F=0,R=0,G=0,k=0;if(f=D,D=D+48|0,I=f+32|0,C=f+16|0,h=f,(0|(d=0|r[(e|=0)>>2]))<=0)return D=f,0|(R=0);s=e+4|0,g=I+8|0,c=C+8|0,u=h+8|0,l=((0|t)<0)<<31>>31,F=0;e:for(;;){w=(B=0|r[s>>2])+(F<<4)|0,r[I>>2]=r[w>>2],r[I+4>>2]=r[w+4>>2],r[I+8>>2]=r[w+8>>2],r[I+12>>2]=r[w+12>>2],(0|F)==(d+-1|0)?(r[C>>2]=r[B>>2],r[C+4>>2]=r[B+4>>2],r[C+8>>2]=r[B+8>>2],r[C+12>>2]=r[B+12>>2]):(w=B+(F+1<<4)|0,r[C>>2]=r[w>>2],r[C+4>>2]=r[w+4>>2],r[C+8>>2]=r[w+8>>2],r[C+12>>2]=r[w+12>>2]),w=0|P(I,C,A);t:do{if((0|w)>0){S=+(0|w),b=0;A:for(;;){k=+(w-b|0),G=+(0|b),i[h>>3]=+i[I>>3]*k/S+ +i[C>>3]*G/S,i[u>>3]=+i[g>>3]*k/S+ +i[c>>3]*G/S,B=0|vt(0|(y=0|Ze(h,A)),0|(m=0|v()),0|t,0|l),v(),E=0|r[(p=d=a+(B<<3)|0)>>2],p=0|r[p+4>>2];n:do{if(0==(0|E)&0==(0|p))R=14;else for(Q=0;;){if((0|Q)>(0|t)){d=1;break n}if((0|E)==(0|y)&(0|p)==(0|m)){d=7;break n}if(0==(0|(E=0|r[(p=d=a+((B=(B+1|0)%(0|t)|0)<<3)|0)>>2]))&0==(0|(p=0|r[p+4>>2]))){R=14;break}Q=Q+1|0}}while(0);switch(14==(0|R)&&(R=0,0==(0|y)&0==(0|m)?d=7:(r[d>>2]=y,r[d+4>>2]=m,d=0|r[n>>2],r[(Q=o+(d<<3)|0)>>2]=y,r[Q+4>>2]=m,r[n>>2]=d+1,d=0)),7&d){case 7:case 0:break;default:break A}if((0|w)<=(0|(b=b+1|0))){R=8;break t}}if(0|d){d=-1,R=20;break e}}else R=8}while(0);if(8==(0|R)&&(R=0),(0|(F=F+1|0))>=(0|(d=0|r[e>>2]))){d=0,R=20;break}}return 20==(0|R)?(D=f,0|d):0}function _(e){return 0|r[7728+(28*(e|=0)|0)+16>>2]}function M(e){return 4==(0|(e|=0))|117==(0|e)|0}function O(e){return 0|r[11152+(216*(0|r[(e|=0)>>2])|0)+(72*(0|r[e+4>>2])|0)+(24*(0|r[e+8>>2])|0)+(r[e+12>>2]<<3)>>2]}function L(e){return 0|r[11152+(216*(0|r[(e|=0)>>2])|0)+(72*(0|r[e+4>>2])|0)+(24*(0|r[e+8>>2])|0)+(r[e+12>>2]<<3)+4>>2]}function T(e,t){return t|=0,(0|r[7728+(28*(e|=0)|0)+20>>2])==(0|t)?0|(t=1):0|(t=(0|r[7728+(28*e|0)+24>>2])==(0|t))}function Z(e,t){return 0|r[880+(28*(e|=0)|0)+((t|=0)<<2)>>2]}function H(e,t){return t|=0,(0|r[880+(28*(e|=0)|0)>>2])==(0|t)?0|(t=0):(0|r[880+(28*e|0)+4>>2])==(0|t)?0|(t=1):(0|r[880+(28*e|0)+8>>2])==(0|t)?0|(t=2):(0|r[880+(28*e|0)+12>>2])==(0|t)?0|(t=3):(0|r[880+(28*e|0)+16>>2])==(0|t)?0|(t=4):(0|r[880+(28*e|0)+20>>2])==(0|t)?0|(t=5):0|((0|r[880+(28*e|0)+24>>2])==(0|t)?6:7)}function Y(e){return+i[(e|=0)+16>>3]<+i[e+24>>3]|0}function J(e,t){e|=0;var A,n,r=0;return(r=+i[(t|=0)>>3])>=+i[e+8>>3]&&r<=+i[e>>3]?(A=+i[e+16>>3],r=+i[e+24>>3],t=(n=+i[t+8>>3])>=r,e=n<=A&1,A>2]=0,u=u+4|0}while((0|u)<(0|l));return Pe(t,o),Je(l=0|r[(u=o)>>2],u=0|r[u+4>>2],A),je(l,u,n),g=+Fe(A,n+8|0),i[A>>3]=+i[e>>3],i[(u=A+8|0)>>3]=+i[e+16>>3],i[n>>3]=+i[e+8>>3],i[(l=n+8|0)>>3]=+i[e+24>>3],c=+Fe(A,n),l=~~+B(+c*c/+wt(+ +s(+(+i[u>>3]-+i[l>>3])/(+i[A>>3]-+i[n>>3])),3)/(g*(2.59807621135*g)*.8)),D=a,0|(0==(0|l)?1:l)}function P(e,t,A){e|=0,t|=0,A|=0;var n,i,o,a,s,g=0,c=0;a=D,D=D+288|0,n=a+264|0,i=a+96|0,c=(g=o=a)+96|0;do{r[g>>2]=0,g=g+4|0}while((0|g)<(0|c));return Pe(A,o),Je(g=0|r[(c=o)>>2],c=0|r[c+4>>2],n),je(g,c,i),s=+Fe(n,i+8|0),c=~~+B(+ +Fe(e,t)/(2*s)),D=a,0|(0==(0|c)?1:c)}function V(e,t,A,n){t|=0,A|=0,n|=0,r[(e|=0)>>2]=t,r[e+4>>2]=A,r[e+8>>2]=n}function K(e,t){e|=0;var A,n,o,a,g=0,c=0,u=0,l=0,I=0,C=0,h=0;r[(a=(t|=0)+8|0)>>2]=0,n=+i[e>>3],l=+s(+n),o=+i[e+8>>3],l+=.5*(I=+s(+o)/.8660254037844386),l-=+(0|(g=~~l)),I-=+(0|(e=~~I));do{if(l<.5){if(l<.3333333333333333){if(r[t>>2]=g,I<.5*(l+1)){r[t+4>>2]=e;break}e=e+1|0,r[t+4>>2]=e;break}if(e=(1&!(I<(h=1-l)))+e|0,r[t+4>>2]=e,h<=I&I<2*l){g=g+1|0,r[t>>2]=g;break}r[t>>2]=g;break}if(!(l<.6666666666666666)){if(g=g+1|0,r[t>>2]=g,I<.5*l){r[t+4>>2]=e;break}e=e+1|0,r[t+4>>2]=e;break}if(I<1-l){if(r[t+4>>2]=e,2*l-1>2]=g;break}}else e=e+1|0,r[t+4>>2]=e;g=g+1|0,r[t>>2]=g}while(0);do{if(n<0){if(1&e){g=~~(+(0|g)-(2*(+((C=0|Et(0|g,((0|g)<0)<<31>>31|0,0|(C=(e+1|0)/2|0),((0|C)<0)<<31>>31|0))>>>0)+4294967296*+(0|v()))+1)),r[t>>2]=g;break}g=~~(+(0|g)-2*(+((C=0|Et(0|g,((0|g)<0)<<31>>31|0,0|(C=(0|e)/2|0),((0|C)<0)<<31>>31|0))>>>0)+4294967296*+(0|v()))),r[t>>2]=g;break}}while(0);C=t+4|0,o<0&&(g=g-((1|e<<1)/2|0)|0,r[t>>2]=g,e=0-e|0,r[C>>2]=e),c=e-g|0,(0|g)<0?(u=0-g|0,r[C>>2]=c,r[a>>2]=u,r[t>>2]=0,e=c,g=0):u=0,(0|e)<0&&(g=g-e|0,r[t>>2]=g,u=u-e|0,r[a>>2]=u,r[C>>2]=0,e=0),A=g-u|0,c=e-u|0,(0|u)<0&&(r[t>>2]=A,r[C>>2]=c,r[a>>2]=0,e=c,g=A,u=0),(0|(c=(0|u)<(0|(c=(0|e)<(0|g)?e:g))?u:c))<=0||(r[t>>2]=g-c,r[C>>2]=e-c,r[a>>2]=u-c)}function W(e){var t,A=0,n=0,i=0,o=0,a=0;A=0|r[(e|=0)>>2],n=0|r[(t=e+4|0)>>2],(0|A)<0&&(n=n-A|0,r[t>>2]=n,r[(a=e+8|0)>>2]=(0|r[a>>2])-A,r[e>>2]=0,A=0),(0|n)<0?(A=A-n|0,r[e>>2]=A,o=(0|r[(a=e+8|0)>>2])-n|0,r[a>>2]=o,r[t>>2]=0,n=0):(a=o=e+8|0,o=0|r[o>>2]),(0|o)<0&&(A=A-o|0,r[e>>2]=A,n=n-o|0,r[t>>2]=n,r[a>>2]=0,o=0),(0|(i=(0|o)<(0|(i=(0|n)<(0|A)?n:A))?o:i))<=0||(r[e>>2]=A-i,r[t>>2]=n-i,r[a>>2]=o-i)}function X(e,t){t|=0;var A,n;n=0|r[(e|=0)+8>>2],A=+((0|r[e+4>>2])-n|0),i[t>>3]=+((0|r[e>>2])-n|0)-.5*A,i[t+8>>3]=.8660254037844386*A}function q(e,t,A){e|=0,t|=0,r[(A|=0)>>2]=(0|r[t>>2])+(0|r[e>>2]),r[A+4>>2]=(0|r[t+4>>2])+(0|r[e+4>>2]),r[A+8>>2]=(0|r[t+8>>2])+(0|r[e+8>>2])}function z(e,t,A){e|=0,t|=0,r[(A|=0)>>2]=(0|r[e>>2])-(0|r[t>>2]),r[A+4>>2]=(0|r[e+4>>2])-(0|r[t+4>>2]),r[A+8>>2]=(0|r[e+8>>2])-(0|r[t+8>>2])}function $(e,t){t|=0;var A,n=0;n=0|p(0|r[(e|=0)>>2],t),r[e>>2]=n,A=0|p(0|r[(n=e+4|0)>>2],t),r[n>>2]=A,t=0|p(0|r[(e=e+8|0)>>2],t),r[e>>2]=t}function ee(e){var t,A,n=0,i=0,o=0,a=0,s=0;s=(0|(A=0|r[(e|=0)>>2]))<0,e=(e=(i=(0|(a=((t=(0|(o=(0|r[e+4>>2])-(s?A:0)|0))<0)?0-o|0:0)+((0|r[e+8>>2])-(s?A:0))|0))<0)?0:a)-((o=(0|(i=(0|e)<(0|(i=(0|(n=(t?0:o)-(i?a:0)|0))<(0|(a=(s?0:A)-(t?o:0)-(i?a:0)|0))?n:a))?e:i))>0)?i:0)|0,n=n-(o?i:0)|0;e:do{switch(a-(o?i:0)|0){case 0:switch(0|n){case 0:return 0|(s=0==(0|e)?0:1==(0|e)?1:7);case 1:return 0|(s=0==(0|e)?2:1==(0|e)?3:7);default:break e}case 1:switch(0|n){case 0:return 0|(s=0==(0|e)?4:1==(0|e)?5:7);case 1:if(e)break e;return 0|(e=6);default:break e}}}while(0);return 0|(s=7)}function te(e){var t,A,n=0,i=0,o=0,a=0,s=0;i=0|r[(t=(e|=0)+8|0)>>2],o=0|ft(+((3*(n=(0|r[e>>2])-i|0)|0)-(i=(0|r[(A=e+4|0)>>2])-i|0)|0)/7),r[e>>2]=o,n=0|ft(+((i<<1)+n|0)/7),r[A>>2]=n,r[t>>2]=0,i=n-o|0,(0|o)<0?(s=0-o|0,r[A>>2]=i,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){var t,A,n,i=0,o=0,a=0,s=0;s=0|r[(e|=0)>>2],a=(i=0|r[(A=e+4|0)>>2])+s|0,s=(o=0|r[(n=e+8|0)>>2])+s|0,r[e>>2]=s,r[A>>2]=a,i=o+i|0,r[n>>2]=i,o=a-s|0,(0|s)<0?(i=i-s|0,r[A>>2]=o,r[n>>2]=i,r[e>>2]=0,a=0):(o=a,a=s),(0|o)<0&&(a=a-o|0,r[e>>2]=a,i=i-o|0,r[n>>2]=i,r[A>>2]=0,o=0),t=a-i|0,s=o-i|0,(0|i)<0?(r[e>>2]=t,r[A>>2]=s,r[n>>2]=0,a=t,i=0):s=o,(0|(o=(0|i)<(0|(o=(0|s)<(0|a)?s:a))?i:o))<=0||(r[e>>2]=a-o,r[A>>2]=s-o,r[n>>2]=i-o)}function ae(e){var t,A,n,i=0,o=0,a=0,s=0;i=0|r[(e|=0)>>2],a=0|r[(A=e+4|0)>>2],o=0|r[(n=e+8|0)>>2],s=a+i|0,r[e>>2]=s,a=o+a|0,r[A>>2]=a,i=o+i|0,r[n>>2]=i,o=a-s|0,(0|s)<0?(i=i-s|0,r[A>>2]=o,r[n>>2]=i,r[e>>2]=0,a=0):(o=a,a=s),(0|o)<0&&(a=a-o|0,r[e>>2]=a,i=i-o|0,r[n>>2]=i,r[A>>2]=0,o=0),t=a-i|0,s=o-i|0,(0|i)<0?(r[e>>2]=t,r[A>>2]=s,r[n>>2]=0,a=t,i=0):s=o,(0|(o=(0|i)<(0|(o=(0|s)<(0|a)?s:a))?i:o))<=0||(r[e>>2]=a-o,r[A>>2]=s-o,r[n>>2]=i-o)}function se(e){switch(0|(e|=0)){case 1:e=5;break;case 5:e=4;break;case 4:e=6;break;case 6:e=2;break;case 2:e=3;break;case 3:e=1}return 0|e}function ge(e){switch(0|(e|=0)){case 1:e=3;break;case 3:e=2;break;case 2:e=6;break;case 6:e=4;break;case 4:e=5;break;case 5:e=1}return 0|e}function ce(e){var t,A,n,i=0,o=0,a=0,s=0;i=0|r[(e|=0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>>2]=a,r[A>>2]=n,r[t>>2]=0,o=n,i=0):(o=0,a=s)):a=n,(0|(n=(0|i)<(0|(n=(0|o)<(0|a)?o:a))?i:n))<=0||(r[e>>2]=a-n,r[A>>2]=o-n,r[t>>2]=i-n)}function de(e,t,A,n){t|=0,A|=0,n|=0;var o,a=0,s=0,g=0,c=0;if(o=D,D=D+32|0,function(e,t){t|=0;var A,n,r=0;r=+i[(e=e|0)>>3],A=+u(+r),r=+l(+r),i[t+16>>3]=r,r=+i[e+8>>3],n=A*+u(+r),i[t>>3]=n,r=A*+l(+r),i[t+8>>3]=r}(e|=0,s=o),r[A>>2]=0,a=+st(15888,s),(g=+st(15912,s))>2]=1,a=g),(g=+st(15936,s))>2]=2,a=g),(g=+st(15960,s))>2]=3,a=g),(g=+st(15984,s))>2]=4,a=g),(g=+st(16008,s))>2]=5,a=g),(g=+st(16032,s))>2]=6,a=g),(g=+st(16056,s))>2]=7,a=g),(g=+st(16080,s))>2]=8,a=g),(g=+st(16104,s))>2]=9,a=g),(g=+st(16128,s))>2]=10,a=g),(g=+st(16152,s))>2]=11,a=g),(g=+st(16176,s))>2]=12,a=g),(g=+st(16200,s))>2]=13,a=g),(g=+st(16224,s))>2]=14,a=g),(g=+st(16248,s))>2]=15,a=g),(g=+st(16272,s))>2]=16,a=g),(g=+st(16296,s))>2]=17,a=g),(g=+st(16320,s))>2]=18,a=g),(g=+st(16344,s))>2]=19,a=g),(g=+C(+(1-.5*a)))<1e-16)return r[n>>2]=0,r[n+4>>2]=0,r[n+8>>2]=0,r[n+12>>2]=0,void(D=o);if(A=0|r[A>>2],a=+we((a=+i[16368+(24*A|0)>>3])-+we(+function(e,t){e|=0;var A,n,r,o,a;return o=+i[(t=t|0)>>3],n=+u(+o),r=+i[t+8>>3]-+i[e+8>>3],a=n*+l(+r),A=+i[e>>3],+ +d(+a,+(+l(+o)*+u(+A)-+u(+r)*(n*+l(+A))))}(15568+(A<<4)|0,e))),c=0|Te(t)?+we(a+-.3334731722518321):a,a=+I(+g)/.381966011250105,(0|t)>0){s=0;do{a*=2.6457513110645907,s=s+1|0}while((0|s)!=(0|t))}g=+u(+c)*a,i[n>>3]=g,c=+l(+c)*a,i[n+8>>3]=c,D=o}function Be(e,t,A,n,o){t|=0,A|=0,n|=0,o|=0;var a=0,c=0;if((a=+function(e){var t,A;return A=+i[(e=e|0)>>3],t=+i[e+8>>3],+ +g(+(A*A+t*t))}(e|=0))<1e-16)return t=15568+(t<<4)|0,r[o>>2]=r[t>>2],r[o+4>>2]=r[t+4>>2],r[o+8>>2]=r[t+8>>2],void(r[o+12>>2]=r[t+12>>2]);if(c=+d(+ +i[e+8>>3],+ +i[e>>3]),(0|A)>0){e=0;do{a/=2.6457513110645907,e=e+1|0}while((0|e)!=(0|A))}n?(a/=3,A=0==(0|Te(A)),a=+f(.381966011250105*(A?a:a/2.6457513110645907))):(a=+f(.381966011250105*a),0|Te(A)&&(c=+we(c+.3334731722518321))),function(e,t,A,n){e|=0,t=+t,n|=0;var o=0,a=0,g=0,c=0;if((A=+A)<1e-16)return r[n>>2]=r[e>>2],r[n+4>>2]=r[e+4>>2],r[n+8>>2]=r[e+8>>2],void(r[n+12>>2]=r[e+12>>2]);a=t<0?t+6.283185307179586:t,a=t>=6.283185307179586?a+-6.283185307179586:a;do{if(!(a<1e-16)){if(o=+s(+(a+-3.141592653589793))<1e-16,t=+i[e>>3],o){t-=A,i[n>>3]=t,o=n;break}if(g=+u(+A),A=+l(+A),t=g*+l(+t)+ +u(+a)*(A*+u(+t)),t=+h(+((t=t>1?1:t)<-1?-1:t)),i[n>>3]=t,+s(+(t+-1.5707963267948966))<1e-16)return i[n>>3]=1.5707963267948966,void(i[n+8>>3]=0);if(+s(+(t+1.5707963267948966))<1e-16)return i[n>>3]=-1.5707963267948966,void(i[n+8>>3]=0);if(c=+u(+t),a=A*+l(+a)/c,A=+i[e>>3],t=(g-+l(+t)*+l(+A))/+u(+A)/c,g=a>1?1:a,t=t>1?1:t,(t=+i[e+8>>3]+ +d(+(g<-1?-1:g),+(t<-1?-1:t)))>3.141592653589793)do{t+=-6.283185307179586}while(t>3.141592653589793);if(t<-3.141592653589793)do{t+=6.283185307179586}while(t<-3.141592653589793);return void(i[n+8>>3]=t)}t=+i[e>>3]+A,i[n>>3]=t,o=n}while(0);if(+s(+(t+-1.5707963267948966))<1e-16)return i[o>>3]=1.5707963267948966,void(i[n+8>>3]=0);if(+s(+(t+1.5707963267948966))<1e-16)return i[o>>3]=-1.5707963267948966,void(i[n+8>>3]=0);if((t=+i[e+8>>3])>3.141592653589793)do{t+=-6.283185307179586}while(t>3.141592653589793);if(t<-3.141592653589793)do{t+=6.283185307179586}while(t<-3.141592653589793);i[n+8>>3]=t}(15568+(t<<4)|0,+we(+i[16368+(24*t|0)>>3]-c),a,o)}function pe(e,t,A){t|=0,A|=0;var n,i;n=D,D=D+16|0,X((e|=0)+4|0,i=n),Be(i,0|r[e>>2],t,0,A),D=n}function Ee(e,t,A,n,o){e|=0,t|=0,A|=0,n|=0,o|=0;var a,s,g,c,u,l,I,C,h,f,d,B,p,E,Q,y,v,b,w,S,F,R,G=0,k=0,x=0,N=0,U=0,_=0;if(R=D,D=D+272|0,N=R+240|0,w=R,S=R+224|0,F=R+208|0,d=R+176|0,B=R+160|0,p=R+192|0,E=R+144|0,Q=R+128|0,y=R+112|0,v=R+96|0,b=R+80|0,r[(G=R+256|0)>>2]=t,r[N>>2]=r[e>>2],r[N+4>>2]=r[e+4>>2],r[N+8>>2]=r[e+8>>2],r[N+12>>2]=r[e+12>>2],Qe(N,G,w),r[o>>2]=0,(0|(N=n+A+(5==(0|n)&1)|0))<=(0|A))D=R;else{s=S+4|0,g=d+4|0,c=A+5|0,u=16848+((a=0|r[G>>2])<<2)|0,l=16928+(a<<2)|0,I=Q+8|0,C=y+8|0,h=v+8|0,f=F+4|0,x=A;e:for(;;){k=w+(((0|x)%5|0)<<4)|0,r[F>>2]=r[k>>2],r[F+4>>2]=r[k+4>>2],r[F+8>>2]=r[k+8>>2],r[F+12>>2]=r[k+12>>2];do{}while(2==(0|ye(F,a,0,1)));if((0|x)>(0|A)&0!=(0|Te(t))){if(r[d>>2]=r[F>>2],r[d+4>>2]=r[F+4>>2],r[d+8>>2]=r[F+8>>2],r[d+12>>2]=r[F+12>>2],X(s,B),n=0|r[d>>2],G=0|r[17008+(80*n|0)+(r[S>>2]<<2)>>2],r[d>>2]=r[18608+(80*n|0)+(20*G|0)>>2],(0|(k=0|r[18608+(80*n|0)+(20*G|0)+16>>2]))>0){e=0;do{oe(g),e=e+1|0}while((0|e)<(0|k))}switch(k=18608+(80*n|0)+(20*G|0)+4|0,r[p>>2]=r[k>>2],r[p+4>>2]=r[k+4>>2],r[p+8>>2]=r[k+8>>2],$(p,3*(0|r[u>>2])|0),q(g,p,g),W(g),X(g,E),U=+(0|r[l>>2]),i[Q>>3]=3*U,i[I>>3]=0,_=-1.5*U,i[y>>3]=_,i[C>>3]=2.598076211353316*U,i[v>>3]=_,i[h>>3]=-2.598076211353316*U,0|r[17008+(80*(0|r[d>>2])|0)+(r[F>>2]<<2)>>2]){case 1:e=y,n=Q;break;case 3:e=v,n=y;break;case 2:e=Q,n=v;break;default:e=12;break e}ot(B,E,n,e,b),Be(b,0|r[d>>2],a,1,o+8+(r[o>>2]<<4)|0),r[o>>2]=1+(0|r[o>>2])}if((0|x)<(0|c)&&(X(f,d),Be(d,0|r[F>>2],a,1,o+8+(r[o>>2]<<4)|0),r[o>>2]=1+(0|r[o>>2])),r[S>>2]=r[F>>2],r[S+4>>2]=r[F+4>>2],r[S+8>>2]=r[F+8>>2],r[S+12>>2]=r[F+12>>2],(0|(x=x+1|0))>=(0|N)){e=3;break}}3!=(0|e)?12==(0|e)&&m(22474,22521,581,22531):D=R}}function Qe(e,t,A){e|=0,t|=0,A|=0;var n,i=0,o=0,a=0,s=0,g=0;n=D,D=D+128|0,o=n,s=20208,g=(a=i=n+64|0)+60|0;do{r[a>>2]=r[s>>2],a=a+4|0,s=s+4|0}while((0|a)<(0|g));s=20272,g=(a=o)+60|0;do{r[a>>2]=r[s>>2],a=a+4|0,s=s+4|0}while((0|a)<(0|g));i=(g=0==(0|Te(0|r[t>>2])))?i:o,ce(o=e+4|0),ue(o),0|Te(0|r[t>>2])&&(re(o),r[t>>2]=1+(0|r[t>>2])),r[A>>2]=r[e>>2],q(o,i,t=A+4|0),W(t),r[A+16>>2]=r[e>>2],q(o,i+12|0,t=A+20|0),W(t),r[A+32>>2]=r[e>>2],q(o,i+24|0,t=A+36|0),W(t),r[A+48>>2]=r[e>>2],q(o,i+36|0,t=A+52|0),W(t),r[A+64>>2]=r[e>>2],q(o,i+48|0,A=A+68|0),W(A),D=n}function ye(e,t,A,n){A|=0,n|=0;var i,o,a,s,g,c,u=0,l=0,I=0,C=0,h=0;if(c=D,D=D+32|0,g=c+12|0,o=c,h=(e|=0)+4|0,C=0|r[16928+((t|=0)<<2)>>2],C=(s=0!=(0|n))?3*C|0:C,u=0|r[h>>2],i=0|r[(a=e+8|0)>>2],s){if((0|(u=i+u+(n=0|r[(l=e+12|0)>>2])|0))==(0|C))return D=c,0|(h=1);I=l}else u=i+u+(n=0|r[(I=e+12|0)>>2])|0;if((0|u)<=(0|C))return D=c,0|(h=0);do{if((0|n)>0){if(n=0|r[e>>2],(0|i)>0){l=18608+(80*n|0)+60|0,n=e;break}n=18608+(80*n|0)+40|0,A?(V(g,C,0,0),z(h,g,o),ae(o),q(o,g,h),l=n,n=e):(l=n,n=e)}else l=18608+(80*(0|r[e>>2])|0)+20|0,n=e}while(0);if(r[n>>2]=r[l>>2],(0|r[(u=l+16|0)>>2])>0){n=0;do{oe(h),n=n+1|0}while((0|n)<(0|r[u>>2]))}return e=l+4|0,r[g>>2]=r[e>>2],r[g+4>>2]=r[e+4>>2],r[g+8>>2]=r[e+8>>2],t=0|r[16848+(t<<2)>>2],$(g,s?3*t|0:t),q(h,g,h),W(h),n=s&&((0|r[a>>2])+(0|r[h>>2])+(0|r[I>>2])|0)==(0|C)?1:2,D=c,0|(h=n)}function ve(e,t){e|=0,t|=0;var A=0;do{A=0|ye(e,t,0,1)}while(2==(0|A));return 0|A}function me(e,t,A,n,o){e|=0,t|=0,A|=0,n|=0,o|=0;var a,s,g,c,u,l,I,C,h,f,d,B,p,E,Q,y,v,b,w=0,S=0,F=0,R=0,G=0;if(b=D,D=D+240|0,E=b+208|0,Q=b,y=b+192|0,v=b+176|0,h=b+160|0,f=b+144|0,d=b+128|0,B=b+112|0,p=b+96|0,r[(w=b+224|0)>>2]=t,r[E>>2]=r[e>>2],r[E+4>>2]=r[e+4>>2],r[E+8>>2]=r[e+8>>2],r[E+12>>2]=r[e+12>>2],be(E,w,Q),r[o>>2]=0,(0|(C=n+A+(6==(0|n)&1)|0))<=(0|A))D=b;else{s=A+6|0,g=16928+((a=0|r[w>>2])<<2)|0,c=f+8|0,u=d+8|0,l=B+8|0,I=y+4|0,S=0,F=A,n=-1;e:for(;;){if(e=Q+((w=(0|F)%6|0)<<4)|0,r[y>>2]=r[e>>2],r[y+4>>2]=r[e+4>>2],r[y+8>>2]=r[e+8>>2],r[y+12>>2]=r[e+12>>2],e=S,S=0|ye(y,a,0,1),(0|F)>(0|A)&0!=(0|Te(t))&&(1!=(0|e)&&(0|r[y>>2])!=(0|n))){switch(X(Q+(((w+5|0)%6|0)<<4)+4|0,v),X(Q+(w<<4)+4|0,h),R=+(0|r[g>>2]),i[f>>3]=3*R,i[c>>3]=0,G=-1.5*R,i[d>>3]=G,i[u>>3]=2.598076211353316*R,i[B>>3]=G,i[l>>3]=-2.598076211353316*R,w=0|r[E>>2],0|r[17008+(80*w|0)+(((0|n)==(0|w)?0|r[y>>2]:n)<<2)>>2]){case 1:e=d,n=f;break;case 3:e=B,n=d;break;case 2:e=f,n=B;break;default:e=8;break e}ot(v,h,n,e,p),0|at(v,p)||0|at(h,p)||(Be(p,0|r[E>>2],a,1,o+8+(r[o>>2]<<4)|0),r[o>>2]=1+(0|r[o>>2]))}if((0|F)<(0|s)&&(X(I,v),Be(v,0|r[y>>2],a,1,o+8+(r[o>>2]<<4)|0),r[o>>2]=1+(0|r[o>>2])),(0|(F=F+1|0))>=(0|C)){e=3;break}n=0|r[y>>2]}3!=(0|e)?8==(0|e)&&m(22557,22521,746,22602):D=b}}function be(e,t,A){e|=0,t|=0,A|=0;var n,i=0,o=0,a=0,s=0,g=0;n=D,D=D+160|0,o=n,s=20336,g=(a=i=n+80|0)+72|0;do{r[a>>2]=r[s>>2],a=a+4|0,s=s+4|0}while((0|a)<(0|g));s=20416,g=(a=o)+72|0;do{r[a>>2]=r[s>>2],a=a+4|0,s=s+4|0}while((0|a)<(0|g));i=(g=0==(0|Te(0|r[t>>2])))?i:o,ce(o=e+4|0),ue(o),0|Te(0|r[t>>2])&&(re(o),r[t>>2]=1+(0|r[t>>2])),r[A>>2]=r[e>>2],q(o,i,t=A+4|0),W(t),r[A+16>>2]=r[e>>2],q(o,i+12|0,t=A+20|0),W(t),r[A+32>>2]=r[e>>2],q(o,i+24|0,t=A+36|0),W(t),r[A+48>>2]=r[e>>2],q(o,i+36|0,t=A+52|0),W(t),r[A+64>>2]=r[e>>2],q(o,i+48|0,t=A+68|0),W(t),r[A+80>>2]=r[e>>2],q(o,i+60|0,A=A+84|0),W(A),D=n}function we(e){var t;return t=(e=+e)<0?e+6.283185307179586:e,+(e>=6.283185307179586?t+-6.283185307179586:t)}function Se(e,t){return t|=0,+s(+(+i[(e|=0)>>3]-+i[t>>3]))<17453292519943298e-27?0|(t=+s(+(+i[e+8>>3]-+i[t+8>>3]))<17453292519943298e-27):0|(t=0)}function Fe(e,t){e|=0;var A,n,r,o=0;return n=+i[(t|=0)>>3],A=+i[e>>3],o=(r=+l(.5*(n-A)))*r+(o=+l(.5*(+i[t+8>>3]-+i[e+8>>3])))*(+u(+n)*+u(+A)*o),2*+d(+ +g(+o),+ +g(+(1-o)))*6371.007180918475}function Re(e,t,A){e|=0,A|=0;var n,r,o,a,s=0,c=0,C=0,h=0,B=0,p=0;return p=+i[(t|=0)>>3],o=+i[e>>3],B=+l(.5*(p-o)),C=+i[t+8>>3],r=+i[e+8>>3],h=+l(.5*(C-r)),n=+u(+o),a=+u(+p),h=2*+d(+ +g(+(h=B*B+h*(a*n*h))),+ +g(+(1-h))),B=+i[A>>3],p=+l(.5*(B-p)),s=+i[A+8>>3],C=+l(.5*(s-C)),c=+u(+B),C=2*+d(+ +g(+(C=p*p+C*(a*c*C))),+ +g(+(1-C))),B=+l(.5*(o-B)),s=+l(.5*(r-s)),s=2*+d(+ +g(+(s=B*B+s*(n*c*s))),+ +g(+(1-s))),4*+f(+ +g(+ +I(.5*(c=.5*(h+C+s)))*+I(.5*(c-h))*+I(.5*(c-C))*+I(.5*(c-s))))}function De(e,t){return t=0|mt(0|(e|=0),0|(t|=0),45),v(),127&t|0}function Ge(e,t){var A=0,n=0,r=0,i=0,o=0,a=0;if(!(!0&134217728==(-16777216&(t|=0)|0)))return 0|(t=0);if(o=0|mt(0|(e|=0),0|t,45),v(),(o&=127)>>>0>121)return 0|(t=0);A=0|mt(0|e,0|t,52),v(),A&=15;do{if(0|A){for(r=1,n=0;;){if(i=0|mt(0|e,0|t,3*(15-r|0)|0),v(),0!=(0|(i&=7))&(1^n)){if(1==(0|i)&0!=(0|_(o))){a=0,n=13;break}n=1}if(7==(0|i)){a=0,n=13;break}if(!(r>>>0>>0)){n=9;break}r=r+1|0}if(9==(0|n)){if(15!=(0|A))break;return 0|(a=1)}if(13==(0|n))return 0|a}}while(0);for(;;){if(a=0|mt(0|e,0|t,3*(14-A|0)|0),v(),!(7==(7&a|0)&!0)){a=0,n=13;break}if(!(A>>>0<14)){a=1,n=13;break}A=A+1|0}return 13==(0|n)?0|a:0}function ke(e,t,A){A|=0;var n=0,r=0;if(n=0|mt(0|(e|=0),0|(t|=0),52),v(),(0|(n&=15))>=(0|A)){if((0|n)!=(0|A))if(A>>>0<=15){if(e|=r=0|bt(0|A,0,52),t=0|v()|-15728641&t,(0|n)>(0|A))do{r=0|bt(7,0,3*(14-A|0)|0),A=A+1|0,e|=r,t=0|v()|t}while((0|A)<(0|n))}else t=0,e=0}else t=0,e=0;return y(0|t),0|e}function xe(e,t,A,n){A|=0,n|=0;var i,o=0,a=0,s=0,g=0,c=0,u=0;if(s=0|mt(0|(e|=0),0|(t|=0),52),v(),(0|A)<16&(0|(s&=15))<=(0|A)){if((0|s)==(0|A))return r[(A=n)>>2]=e,void(r[A+4>>2]=t);if(i=(0|(c=0|tt(7,A-s|0)))/7|0,g=0|mt(0|e,0|t,45),v(),0|_(127&g)){e:do{if(s)for(a=1;;){if(o=0|mt(0|e,0|t,3*(15-a|0)|0),v(),0|(o&=7))break e;if(!(a>>>0>>0)){o=0;break}a=a+1|0}else o=0}while(0);a=0==(0|o)}else a=0;if(u=0|bt(s+1|0,0,52),o=0|v()|-15728641&t,xe(t=(u|e)&~(t=0|bt(7,0,0|(g=3*(14-s|0)|0))),s=o&~(0|v()),A,n),o=n+(i<<3)|0,!a)return xe((u=0|bt(1,0,0|g))|t,0|v()|s,A,o),u=o+(i<<3)|0,xe((c=0|bt(2,0,0|g))|t,0|v()|s,A,u),u=u+(i<<3)|0,xe((c=0|bt(3,0,0|g))|t,0|v()|s,A,u),u=u+(i<<3)|0,xe((c=0|bt(4,0,0|g))|t,0|v()|s,A,u),u=u+(i<<3)|0,xe((c=0|bt(5,0,0|g))|t,0|v()|s,A,u),void xe((c=0|bt(6,0,0|g))|t,0|v()|s,A,u+(i<<3)|0);a=o+(i<<3)|0,(0|c)>6&&(Rt(0|o,0,(u=(a>>>0>(c=o+8|0)>>>0?a:c)+-1+(0-o)|0)+8&-8|0),o=c+(u>>>3<<3)|0),xe((u=0|bt(2,0,0|g))|t,0|v()|s,A,o),u=o+(i<<3)|0,xe((c=0|bt(3,0,0|g))|t,0|v()|s,A,u),u=u+(i<<3)|0,xe((c=0|bt(4,0,0|g))|t,0|v()|s,A,u),u=u+(i<<3)|0,xe((c=0|bt(5,0,0|g))|t,0|v()|s,A,u),xe((c=0|bt(6,0,0|g))|t,0|v()|s,A,u+(i<<3)|0)}}function Ne(e,t){var A=0,n=0,r=0;if(r=0|mt(0|(e|=0),0|(t|=0),45),v(),!(0|_(127&r)))return 0|(r=0);r=0|mt(0|e,0|t,52),v(),r&=15;e:do{if(r)for(n=1;;){if(A=0|mt(0|e,0|t,3*(15-n|0)|0),v(),0|(A&=7))break e;if(!(n>>>0>>0)){A=0;break}n=n+1|0}else A=0}while(0);return 0|(r=0==(0|A)&1)}function Ue(e,t){var A=0,n=0,r=0;if(r=0|mt(0|(e|=0),0|(t|=0),52),v(),!(r&=15))return 0|(r=0);for(n=1;;){if(A=0|mt(0|e,0|t,3*(15-n|0)|0),v(),0|(A&=7)){n=5;break}if(!(n>>>0>>0)){A=0,n=5;break}n=n+1|0}return 5==(0|n)?0|A:0}function _e(e,t){var A=0,n=0,r=0,i=0,o=0,a=0,s=0;if(s=0|mt(0|(e|=0),0|(t|=0),52),v(),!(s&=15))return s=e,y(0|(a=t)),0|s;for(a=1,A=0;;){n=0|bt(7,0,0|(i=3*(15-a|0)|0)),r=0|v(),o=0|mt(0|e,0|t,0|i),v(),e=(i=0|bt(0|se(7&o),0,0|i))|e&~n,t=(o=0|v())|t&~r;e:do{if(!A)if(0==(i&n|0)&0==(o&r|0))A=0;else if(n=0|mt(0|e,0|t,52),v(),n&=15){A=1;t:for(;;){switch(o=0|mt(0|e,0|t,3*(15-A|0)|0),v(),7&o){case 1:break t;case 0:break;default:A=1;break e}if(!(A>>>0>>0)){A=1;break e}A=A+1|0}for(A=1;;){if(r=0|mt(0|e,0|t,0|(o=3*(15-A|0)|0)),v(),i=0|bt(7,0,0|o),t&=~(0|v()),e=e&~i|(o=0|bt(0|se(7&r),0,0|o)),t=0|t|v(),!(A>>>0>>0)){A=1;break}A=A+1|0}}else A=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return y(0|t),0|e}function Me(e,t){var A=0,n=0,r=0,i=0,o=0;if(n=0|mt(0|(e|=0),0|(t|=0),52),v(),!(n&=15))return n=e,y(0|(A=t)),0|n;for(A=1;o=0|mt(0|e,0|t,0|(i=3*(15-A|0)|0)),v(),r=0|bt(7,0,0|i),t&=~(0|v()),e=(i=0|bt(0|se(7&o),0,0|i))|e&~r,t=0|v()|t,A>>>0>>0;)A=A+1|0;return y(0|t),0|e}function Oe(e,t){var A=0,n=0,r=0,i=0,o=0,a=0,s=0;if(s=0|mt(0|(e|=0),0|(t|=0),52),v(),!(s&=15))return s=e,y(0|(a=t)),0|s;for(a=1,A=0;;){n=0|bt(7,0,0|(i=3*(15-a|0)|0)),r=0|v(),o=0|mt(0|e,0|t,0|i),v(),e=(i=0|bt(0|ge(7&o),0,0|i))|e&~n,t=(o=0|v())|t&~r;e:do{if(!A)if(0==(i&n|0)&0==(o&r|0))A=0;else if(n=0|mt(0|e,0|t,52),v(),n&=15){A=1;t:for(;;){switch(o=0|mt(0|e,0|t,3*(15-A|0)|0),v(),7&o){case 1:break t;case 0:break;default:A=1;break e}if(!(A>>>0>>0)){A=1;break e}A=A+1|0}for(A=1;;){if(i=0|bt(7,0,0|(r=3*(15-A|0)|0)),o=t&~(0|v()),t=0|mt(0|e,0|t,0|r),v(),e=e&~i|(t=0|bt(0|ge(7&t),0,0|r)),t=0|o|v(),!(A>>>0>>0)){A=1;break}A=A+1|0}}else A=1}while(0);if(!(a>>>0>>0))break;a=a+1|0}return y(0|t),0|e}function Le(e,t){var A=0,n=0,r=0,i=0,o=0;if(n=0|mt(0|(e|=0),0|(t|=0),52),v(),!(n&=15))return n=e,y(0|(A=t)),0|n;for(A=1;i=0|bt(7,0,0|(o=3*(15-A|0)|0)),r=t&~(0|v()),t=0|mt(0|e,0|t,0|o),v(),e=(t=0|bt(0|ge(7&t),0,0|o))|e&~i,t=0|v()|r,A>>>0>>0;)A=A+1|0;return y(0|t),0|e}function Te(e){return 0|(0|(e|=0))%2}function Ze(e,t){e|=0;var A,n;return n=D,D=D+16|0,A=n,(t|=0)>>>0<=15&&2146435072!=(2146435072&r[e+4>>2]|0)&&2146435072!=(2146435072&r[e+8+4>>2]|0)?(!function(e,t,A){var n,r;n=D,D=D+16|0,de(e|=0,t|=0,A|=0,r=n),K(r,A+4|0),D=n}(e,t,A),t=0|function(e,t){e|=0;var A,n=0,i=0,o=0,a=0,s=0,g=0,c=0,u=0;if(A=D,D=D+64|0,g=A+40|0,i=A+24|0,o=A+12|0,a=A,bt(0|(t|=0),0,52),n=134225919|v(),!t)return(0|r[e+4>>2])>2||(0|r[e+8>>2])>2||(0|r[e+12>>2])>2?(g=0,y(0|(s=0)),D=A,0|g):(bt(0|O(e),0,45),s=0|v()|n,g=-1,y(0|s),D=A,0|g);if(r[g>>2]=r[e>>2],r[g+4>>2]=r[e+4>>2],r[g+8>>2]=r[e+8>>2],r[g+12>>2]=r[e+12>>2],s=g+4|0,(0|t)>0)for(e=-1;r[i>>2]=r[s>>2],r[i+4>>2]=r[s+4>>2],r[i+8>>2]=r[s+8>>2],1&t?(te(s),r[o>>2]=r[s>>2],r[o+4>>2]=r[s+4>>2],r[o+8>>2]=r[s+8>>2],ne(o)):(Ae(s),r[o>>2]=r[s>>2],r[o+4>>2]=r[s+4>>2],r[o+8>>2]=r[s+8>>2],re(o)),z(i,o,a),W(a),c=0|bt(7,0,0|(u=3*(15-t|0)|0)),n&=~(0|v()),e=(u=0|bt(0|ee(a),0,0|u))|e&~c,n=0|v()|n,(0|t)>1;)t=t+-1|0;else e=-1;e:do{if((0|r[s>>2])<=2&&(0|r[g+8>>2])<=2&&(0|r[g+12>>2])<=2){if(t=0|bt(0|(i=0|O(g)),0,45),t|=e,e=0|v()|-1040385&n,a=0|L(g),!(0|_(i))){if((0|a)<=0)break;for(o=0;;){if(i=0|mt(0|t,0|e,52),v(),i&=15)for(n=1;g=0|mt(0|t,0|e,0|(u=3*(15-n|0)|0)),v(),c=0|bt(7,0,0|u),e&=~(0|v()),t=t&~c|(u=0|bt(0|se(7&g),0,0|u)),e=0|e|v(),n>>>0>>0;)n=n+1|0;if((0|(o=o+1|0))==(0|a))break e}}o=0|mt(0|t,0|e,52),v(),o&=15;t:do{if(o){n=1;A:for(;;){switch(u=0|mt(0|t,0|e,3*(15-n|0)|0),v(),7&u){case 1:break A;case 0:break;default:break t}if(!(n>>>0>>0))break t;n=n+1|0}if(0|T(i,0|r[g>>2]))for(n=1;c=0|bt(7,0,0|(g=3*(15-n|0)|0)),u=e&~(0|v()),e=0|mt(0|t,0|e,0|g),v(),t=t&~c|(e=0|bt(0|ge(7&e),0,0|g)),e=0|u|v(),n>>>0>>0;)n=n+1|0;else for(n=1;g=0|mt(0|t,0|e,0|(u=3*(15-n|0)|0)),v(),c=0|bt(7,0,0|u),e&=~(0|v()),t=t&~c|(u=0|bt(0|se(7&g),0,0|u)),e=0|e|v(),n>>>0>>0;)n=n+1|0}}while(0);if((0|a)>0){n=0;do{t=0|_e(t,e),e=0|v(),n=n+1|0}while((0|n)!=(0|a))}}else t=0,e=0}while(0);return u=t,y(0|(c=e)),D=A,0|u}(A,t),e=0|v()):(e=0,t=0),y(0|e),D=n,0|t}function He(e,t,A){var n,i=0,o=0,a=0;if(n=(A|=0)+4|0,o=0|mt(0|(e|=0),0|(t|=0),52),v(),o&=15,a=0|mt(0|e,0|t,45),v(),i=0==(0|o),0|_(127&a)){if(i)return 0|(a=1);i=1}else{if(i)return 0|(a=0);i=0==(0|r[n>>2])&&0==(0|r[A+8>>2])?0!=(0|r[A+12>>2])&1:1}for(A=1;1&A?ne(n):re(n),a=0|mt(0|e,0|t,3*(15-A|0)|0),v(),ie(n,7&a),A>>>0>>0;)A=A+1|0;return 0|i}function Ye(e,t,A){A|=0;var n,i,o=0,a=0,s=0,g=0,c=0,u=0;i=D,D=D+16|0,n=i,u=0|mt(0|(e|=0),0|(t|=0),45),v(),u&=127;e:do{if(0!=(0|_(u))&&(s=0|mt(0|e,0|t,52),v(),0!=(0|(s&=15)))){o=1;t:for(;;){switch(c=0|mt(0|e,0|t,3*(15-o|0)|0),v(),7&c){case 5:break t;case 0:break;default:o=t;break e}if(!(o>>>0>>0)){o=t;break e}o=o+1|0}for(a=1,o=t;g=0|bt(7,0,0|(t=3*(15-a|0)|0)),c=o&~(0|v()),o=0|mt(0|e,0|o,0|t),v(),e=e&~g|(o=0|bt(0|ge(7&o),0,0|t)),o=0|c|v(),a>>>0>>0;)a=a+1|0}else o=t}while(0);if(c=7728+(28*u|0)|0,r[A>>2]=r[c>>2],r[A+4>>2]=r[c+4>>2],r[A+8>>2]=r[c+8>>2],r[A+12>>2]=r[c+12>>2],0|He(e,o,A)){if(g=A+4|0,r[n>>2]=r[g>>2],r[n+4>>2]=r[g+4>>2],r[n+8>>2]=r[g+8>>2],s=0|mt(0|e,0|o,52),v(),c=15&s,1&s?(re(g),s=c+1|0):s=c,0|_(u)){e:do{if(c)for(t=1;;){if(a=0|mt(0|e,0|o,3*(15-t|0)|0),v(),0|(a&=7)){o=a;break e}if(!(t>>>0>>0)){o=0;break}t=t+1|0}else o=0}while(0);o=4==(0|o)&1}else o=0;if(0|ye(A,s,o,0)){if(0|_(u))do{}while(0!=(0|ye(A,s,0,0)));(0|s)!=(0|c)&&Ae(g)}else(0|s)!=(0|c)&&(r[g>>2]=r[n>>2],r[g+4>>2]=r[n+4>>2],r[g+8>>2]=r[n+8>>2]);D=i}else D=i}function Je(e,t,A){A|=0;var n,r;n=D,D=D+16|0,Ye(e|=0,t|=0,r=n),t=0|mt(0|e,0|t,52),v(),pe(r,15&t,A),D=n}function je(e,t,A){A|=0;var n,r,i=0,o=0;r=D,D=D+16|0,Ye(e|=0,t|=0,n=r),i=0|mt(0|e,0|t,45),v(),i=0==(0|_(127&i)),o=0|mt(0|e,0|t,52),v(),o&=15;e:do{if(!i){if(0|o)for(i=1;;){if(!(0==((0|bt(7,0,3*(15-i|0)|0))&e|0)&0==((0|v())&t|0)))break e;if(!(i>>>0>>0))break;i=i+1|0}return Ee(n,o,0,5,A),void(D=r)}}while(0);me(n,o,0,6,A),D=r}function Pe(e,t){t|=0;var A,n=0,i=0,o=0,a=0,s=0,g=0;if(bt(0|(e|=0),0,52),A=134225919|v(),(0|e)<1){i=0,n=0;do{0|_(i)&&(bt(0|i,0,45),s=0|A|v(),r[(e=t+(n<<3)|0)>>2]=-1,r[e+4>>2]=s,n=n+1|0),i=i+1|0}while(122!=(0|i))}else{s=0,n=0;do{if(0|_(s)){for(bt(0|s,0,45),i=1,o=-1,a=0|A|v();o&=~(g=0|bt(7,0,3*(15-i|0)|0)),a&=~(0|v()),(0|i)!=(0|e);)i=i+1|0;r[(g=t+(n<<3)|0)>>2]=o,r[g+4>>2]=a,n=n+1|0}s=s+1|0}while(122!=(0|s))}}function Ve(e,t,A,n){var i,o=0,a=0,s=0,g=0,c=0;if(i=D,D=D+64|0,s=i,(0|(e|=0))==(0|(A|=0))&(0|(t|=0))==(0|(n|=0))|!1|134217728!=(2013265920&t|0)|!1|134217728!=(2013265920&n|0))return D=i,0|(s=0);if(o=0|mt(0|e,0|t,52),v(),o&=15,a=0|mt(0|A,0|n,52),v(),(0|o)!=(15&a|0))return D=i,0|(s=0);if(a=o+-1|0,o>>>0>1&&(c=0|ke(e,t,a),g=0|v(),(0|c)==(0|(a=0|ke(A,n,a)))&(0|g)==(0|v()))){if(o=0|mt(0|e,0|t,0|(a=3*(15^o)|0)),v(),o&=7,a=0|mt(0|A,0|n,0|a),v(),0==(0|o)|0==(0|(a&=7)))return D=i,0|(c=1);if((0|r[21136+(o<<2)>>2])==(0|a))return D=i,0|(c=1);if((0|r[21168+(o<<2)>>2])==(0|a))return D=i,0|(c=1)}a=(o=s)+56|0;do{r[o>>2]=0,o=o+4|0}while((0|o)<(0|a));return G(e,t,1,s),o=(0|r[(c=s)>>2])==(0|A)&&(0|r[c+4>>2])==(0|n)||(0|r[(c=s+8|0)>>2])==(0|A)&&(0|r[c+4>>2])==(0|n)||(0|r[(c=s+16|0)>>2])==(0|A)&&(0|r[c+4>>2])==(0|n)||(0|r[(c=s+24|0)>>2])==(0|A)&&(0|r[c+4>>2])==(0|n)||(0|r[(c=s+32|0)>>2])==(0|A)&&(0|r[c+4>>2])==(0|n)||(0|r[(c=s+40|0)>>2])==(0|A)&&(0|r[c+4>>2])==(0|n)?1:1&((0|r[(o=s+48|0)>>2])==(0|A)?(0|r[o+4>>2])==(0|n):0),D=i,0|(c=o)}function Ke(e,t,A){A|=0;var n,i,o,a,s=0;if(o=D,D=D+16|0,i=o,s=0|mt(0|(e|=0),0|(t|=0),56),v(),-1==(0|(t=0|function(e,t,A){A|=0;var n,i=0;if(i=0|Ne(e=e|0,t=t|0),(A+-1|0)>>>0>5)return 0|(A=-1);if(1==(0|A)&(n=0!=(0|i)))return 0|(A=-1);return i=0|function(e,t){var A,n,i,o=0,a=0,s=0,g=0,c=0;if(i=D,D=D+32|0,n=i,Ye(e=e|0,t=t|0,A=i+16|0),s=0|De(e,t),c=0|Ue(e,t),function(e,t){e=7728+(28*(e|=0)|0)|0,r[(t|=0)>>2]=r[e>>2],r[t+4>>2]=r[e+4>>2],r[t+8>>2]=r[e+8>>2],r[t+12>>2]=r[e+12>>2]}(s,n),t=0|function(e,t){e|=0;var A=0,n=0;if((t|=0)>>>0>20)return 0|(t=-1);do{if((0|r[11152+(216*t|0)>>2])!=(0|e))if((0|r[11152+(216*t|0)+8>>2])!=(0|e))if((0|r[11152+(216*t|0)+16>>2])!=(0|e))if((0|r[11152+(216*t|0)+24>>2])!=(0|e))if((0|r[11152+(216*t|0)+32>>2])!=(0|e))if((0|r[11152+(216*t|0)+40>>2])!=(0|e))if((0|r[11152+(216*t|0)+48>>2])!=(0|e))if((0|r[11152+(216*t|0)+56>>2])!=(0|e))if((0|r[11152+(216*t|0)+64>>2])!=(0|e))if((0|r[11152+(216*t|0)+72>>2])!=(0|e))if((0|r[11152+(216*t|0)+80>>2])!=(0|e))if((0|r[11152+(216*t|0)+88>>2])!=(0|e))if((0|r[11152+(216*t|0)+96>>2])!=(0|e))if((0|r[11152+(216*t|0)+104>>2])!=(0|e))if((0|r[11152+(216*t|0)+112>>2])!=(0|e))if((0|r[11152+(216*t|0)+120>>2])!=(0|e))if((0|r[11152+(216*t|0)+128>>2])!=(0|e)){if((0|r[11152+(216*t|0)+136>>2])!=(0|e)){if((0|r[11152+(216*t|0)+144>>2])==(0|e)){e=0,A=2,n=0;break}if((0|r[11152+(216*t|0)+152>>2])==(0|e)){e=0,A=2,n=1;break}if((0|r[11152+(216*t|0)+160>>2])==(0|e)){e=0,A=2,n=2;break}if((0|r[11152+(216*t|0)+168>>2])==(0|e)){e=1,A=2,n=0;break}if((0|r[11152+(216*t|0)+176>>2])==(0|e)){e=1,A=2,n=1;break}if((0|r[11152+(216*t|0)+184>>2])==(0|e)){e=1,A=2,n=2;break}if((0|r[11152+(216*t|0)+192>>2])==(0|e)){e=2,A=2,n=0;break}if((0|r[11152+(216*t|0)+200>>2])==(0|e)){e=2,A=2,n=1;break}if((0|r[11152+(216*t|0)+208>>2])==(0|e)){e=2,A=2,n=2;break}return 0|(e=-1)}e=2,A=1,n=2}else e=2,A=1,n=1;else e=2,A=1,n=0;else e=1,A=1,n=2;else e=1,A=1,n=1;else e=1,A=1,n=0;else e=0,A=1,n=2;else e=0,A=1,n=1;else e=0,A=1,n=0;else e=2,A=0,n=2;else e=2,A=0,n=1;else e=2,A=0,n=0;else e=1,A=0,n=2;else e=1,A=0,n=1;else e=1,A=0,n=0;else e=0,A=0,n=2;else e=0,A=0,n=1;else e=0,A=0,n=0}while(0);return 0|(t=0|r[11152+(216*t|0)+(72*A|0)+(24*e|0)+(n<<3)+4>>2])}(s,0|r[A>>2]),!(0|_(s)))return D=i,0|(c=t);switch(0|s){case 4:e=0,o=14;break;case 14:e=1,o=14;break;case 24:e=2,o=14;break;case 38:e=3,o=14;break;case 49:e=4,o=14;break;case 58:e=5,o=14;break;case 63:e=6,o=14;break;case 72:e=7,o=14;break;case 83:e=8,o=14;break;case 97:e=9,o=14;break;case 107:e=10,o=14;break;case 117:e=11,o=14;break;default:g=0,a=0}14==(0|o)&&(g=0|r[22096+(24*e|0)+8>>2],a=0|r[22096+(24*e|0)+16>>2]);(0|(e=0|r[A>>2]))!=(0|r[n>>2])&&(s=0|M(s),e=0|r[A>>2],s|(0|e)==(0|a)&&(t=(t+1|0)%6|0));if(3==(0|c)&(0|e)==(0|a))return D=i,0|(c=(t+5|0)%6|0);if(!(5==(0|c)&(0|e)==(0|g)))return D=i,0|(c=t);return D=i,0|(c=(t+1|0)%6|0)}(e,t),n?0|(A=(5-i+(0|r[22384+(A<<2)>>2])|0)%5|0):0|(A=(6-i+(0|r[22416+(A<<2)>>2])|0)%6|0)}(n=(a=!0&268435456==(2013265920&t|0))?e:0,e=a?-2130706433&t|134217728:0,7&s))))return r[A>>2]=0,void(D=o);Ye(n,e,i),s=0|mt(0|n,0|e,52),v(),s&=15,0|Ne(n,e)?Ee(i,s,t,2,A):me(i,s,t,2,A),D=o}function We(e){e|=0;var t,A,n=0;return(t=0|pt(1,12))||m(22691,22646,49,22704),0|(n=0|r[(A=e+4|0)>>2])?(r[(n=n+8|0)>>2]=t,r[A>>2]=t,0|t):(0|r[e>>2]&&m(22721,22646,61,22744),r[(n=e)>>2]=t,r[A>>2]=t,0|t)}function Xe(e,t){e|=0,t|=0;var A,n;return(n=0|dt(24))||m(22758,22646,78,22772),r[n>>2]=r[t>>2],r[n+4>>2]=r[t+4>>2],r[n+8>>2]=r[t+8>>2],r[n+12>>2]=r[t+12>>2],r[n+16>>2]=0,0|(A=0|r[(t=e+4|0)>>2])?(r[A+16>>2]=n,r[t>>2]=n,0|n):(0|r[e>>2]&&m(22787,22646,82,22772),r[e>>2]=n,r[t>>2]=n,0|n)}function qe(e){var t,A,n=0,o=0,a=0,g=0,c=0,u=0,l=0,I=0,C=0,h=0,f=0,d=0,B=0,p=0,E=0,Q=0,y=0,v=0,b=0,w=0,S=0,F=0,R=0,D=0,G=0,k=0,x=0,N=0,U=0,_=0;if(0|r[(g=(e|=0)+8|0)>>2])return 0|(_=1);if(!(a=0|r[e>>2]))return 0|(_=0);n=a,o=0;do{o=o+1|0,n=0|r[n+8>>2]}while(0!=(0|n));if(o>>>0<2)return 0|(_=0);(A=0|dt(o<<2))||m(22807,22646,317,22826),(t=0|dt(o<<5))||m(22848,22646,321,22826),r[e>>2]=0,r[(F=e+4|0)>>2]=0,r[g>>2]=0,o=0,N=0,S=0,f=0;e:for(;;){if(h=0|r[a>>2]){c=0,u=h;do{if(I=+i[u+8>>3],n=u,u=0|r[u+16>>2],l=+i[(g=(C=0==(0|u))?h:u)+8>>3],+s(+(I-l))>3.141592653589793){_=14;break}c+=(l-I)*(+i[n>>3]+ +i[g>>3])}while(!C);if(14==(0|_)){_=0,c=0,n=h;do{w=+i[n+8>>3],k=0|r[(x=n+16|0)>>2],b=+i[(k=0==(0|k)?h:k)+8>>3],c+=(+i[n>>3]+ +i[k>>3])*((b<0?b+6.283185307179586:b)-(w<0?w+6.283185307179586:w)),n=0|r[(0==(0|n)?a:x)>>2]}while(0!=(0|n))}c>0?(r[A+(N<<2)>>2]=a,N=N+1|0,g=S,n=f):_=19}else _=19;if(19==(0|_)){_=0;do{if(!o){if(f){g=F,u=f+8|0,n=a,o=e;break}if(0|r[e>>2]){_=27;break e}g=F,u=e,n=a,o=e;break}if(0|r[(n=o+8|0)>>2]){_=21;break e}if(!(o=0|pt(1,12))){_=23;break e}r[n>>2]=o,g=o+4|0,u=o,n=f}while(0);if(r[u>>2]=a,r[g>>2]=a,u=t+(S<<5)|0,C=0|r[a>>2]){for(i[(h=t+(S<<5)+8|0)>>3]=17976931348623157e292,i[(f=t+(S<<5)+24|0)>>3]=17976931348623157e292,i[u>>3]=-17976931348623157e292,i[(d=t+(S<<5)+16|0)>>3]=-17976931348623157e292,y=17976931348623157e292,v=-17976931348623157e292,g=0,B=C,I=17976931348623157e292,E=17976931348623157e292,Q=-17976931348623157e292,l=-17976931348623157e292;c=+i[B>>3],w=+i[B+8>>3],B=0|r[B+16>>2],b=+i[((p=0==(0|B))?C:B)+8>>3],c>3]=c,I=c),w>3]=w,E=w),c>Q?i[u>>3]=c:c=Q,w>l&&(i[d>>3]=w,l=w),y=w>0&wv?w:v,g|=+s(+(w-b))>3.141592653589793,!p;)Q=c;g&&(i[d>>3]=v,i[f>>3]=y)}else r[u>>2]=0,r[u+4>>2]=0,r[u+8>>2]=0,r[u+12>>2]=0,r[u+16>>2]=0,r[u+20>>2]=0,r[u+24>>2]=0,r[u+28>>2]=0;g=S+1|0}if(a=0|r[(x=a+8|0)>>2],r[x>>2]=0,!a){_=45;break}S=g,f=n}if(21==(0|_))m(22624,22646,35,22658);else if(23==(0|_))m(22678,22646,37,22658);else if(27==(0|_))m(22721,22646,61,22744);else if(45==(0|_)){e:do{if((0|N)>0){for(x=0==(0|g),G=g<<2,k=0==(0|e),D=0,n=0;;){if(R=0|r[A+(D<<2)>>2],x)_=73;else{if(!(S=0|dt(G))){_=50;break}if(!(F=0|dt(G))){_=52;break}t:do{if(k)o=0;else{for(g=0,o=0,u=e;a=t+(g<<5)|0,0|ze(0|r[u>>2],a,0|r[R>>2])?(r[S+(o<<2)>>2]=u,r[F+(o<<2)>>2]=a,p=o+1|0):p=o,u=0|r[u+8>>2];)g=g+1|0,o=p;if((0|p)>0)if(a=0|r[S>>2],1==(0|p))o=a;else for(d=0,B=-1,o=a,f=a;;){for(C=0|r[f>>2],a=0,u=0;h=(0|(g=0|r[r[S+(u<<2)>>2]>>2]))==(0|C)?a:a+(1&(0|ze(g,0|r[F+(u<<2)>>2],0|r[C>>2])))|0,(0|(u=u+1|0))!=(0|p);)a=h;if(o=(g=(0|h)>(0|B))?f:o,(0|(a=d+1|0))==(0|p))break t;d=a,B=g?h:B,f=0|r[S+(a<<2)>>2]}else o=0}}while(0);if(Bt(S),Bt(F),o){if(a=0|r[(g=o+4|0)>>2])o=a+8|0;else if(0|r[o>>2]){_=70;break}r[o>>2]=R,r[g>>2]=R}else _=73}if(73==(0|_)){if(_=0,0|(n=0|r[R>>2]))do{F=n,n=0|r[n+16>>2],Bt(F)}while(0!=(0|n));Bt(R),n=2}if((0|(D=D+1|0))>=(0|N)){U=n;break e}}50==(0|_)?m(22863,22646,249,22882):52==(0|_)?m(22901,22646,252,22882):70==(0|_)&&m(22721,22646,61,22744)}else U=0}while(0);return Bt(A),Bt(t),0|(_=U)}return 0}function ze(e,t,A){e|=0;var n,o=0,a=0,s=0,g=0,c=0,u=0,l=0;if(!(0|J(t|=0,A|=0)))return 0|(e=0);if(t=0|Y(t),n=+i[A>>3],o=t&(o=+i[A+8>>3])<0?o+6.283185307179586:o,!(e=0|r[e>>2]))return 0|(e=0);if(t){t=0,A=e;e:for(;;){for(;g=+i[A>>3],u=+i[A+8>>3],l=0|r[(A=A+16|0)>>2],s=+i[(l=0==(0|l)?e:l)>>3],a=+i[l+8>>3],g>s?(c=g,g=u):(c=s,s=g,g=a,a=u),nc;)if(!(A=0|r[A>>2])){A=22;break e}if(o=(g=g<0?g+6.283185307179586:g)==o|(u=a<0?a+6.283185307179586:a)==o?o+-2220446049250313e-31:o,((u+=(n-s)/(c-s)*(g-u))<0?u+6.283185307179586:u)>o&&(t^=1),!(A=0|r[A>>2])){A=22;break}}if(22==(0|A))return 0|t}else{t=0,A=e;e:for(;;){for(;g=+i[A>>3],u=+i[A+8>>3],l=0|r[(A=A+16|0)>>2],s=+i[(l=0==(0|l)?e:l)>>3],a=+i[l+8>>3],g>s?(c=g,g=u):(c=s,s=g,g=a,a=u),nc;)if(!(A=0|r[A>>2])){A=22;break e}if(a+(n-s)/(c-s)*(g-a)>(o=g==o|a==o?o+-2220446049250313e-31:o)&&(t^=1),!(A=0|r[A>>2])){A=22;break}}if(22==(0|A))return 0|t}return 0}function $e(e,t,A,i,o){A|=0,i|=0,o|=0;var a,s,g,c,u=0,l=0,I=0,C=0,h=0,f=0,d=0,B=0,p=0,E=0;if(c=D,D=D+32|0,E=c+16|0,g=c,u=0|mt(0|(e|=0),0|(t|=0),52),v(),u&=15,d=0|mt(0|A,0|i,52),v(),(0|u)!=(15&d|0))return D=c,0|(E=1);if(h=0|mt(0|e,0|t,45),v(),h&=127,f=0|mt(0|A,0|i,45),v(),d=(0|h)!=(0|(f&=127))){if(7==(0|(I=0|H(h,f))))return D=c,0|(E=2);7==(0|(C=0|H(f,h)))?m(22925,22949,151,22959):(B=I,l=C)}else B=0,l=0;a=0|_(h),s=0|_(f),r[E>>2]=0,r[E+4>>2]=0,r[E+8>>2]=0,r[E+12>>2]=0;do{if(B){if(I=(0|(f=0|r[4304+(28*h|0)+(B<<2)>>2]))>0,s)if(I){h=0,C=A,I=i;do{C=0|Oe(C,I),I=0|v(),1==(0|(l=0|ge(l)))&&(l=0|ge(1)),h=h+1|0}while((0|h)!=(0|f));f=l,h=C,C=I}else f=l,h=A,C=i;else if(I){h=0,C=A,I=i;do{C=0|Le(C,I),I=0|v(),l=0|ge(l),h=h+1|0}while((0|h)!=(0|f));f=l,h=C,C=I}else f=l,h=A,C=i;if(He(h,C,E),d||m(22972,22949,181,22959),(I=0!=(0|a))&(l=0!=(0|s))&&m(22999,22949,182,22959),I){if(l=0|Ue(e,t),0|n[22032+(7*l|0)+B>>0]){u=3;break}h=C=0|r[21200+(28*l|0)+(B<<2)>>2],p=26}else if(l){if(l=0|Ue(h,C),0|n[22032+(7*l|0)+f>>0]){u=4;break}h=0,C=0|r[21200+(28*f|0)+(l<<2)>>2],p=26}else l=0;if(26==(0|p))if((0|C)<=-1&&m(23030,22949,212,22959),(0|h)<=-1&&m(23053,22949,213,22959),(0|C)>0){I=E+4|0,l=0;do{ae(I),l=l+1|0}while((0|l)!=(0|C));l=h}else l=h;if(r[g>>2]=0,r[g+4>>2]=0,r[g+8>>2]=0,ie(g,B),0|u)for(;0|Te(u)?ne(g):re(g),(0|u)>1;)u=u+-1|0;if((0|l)>0){u=0;do{ae(g),u=u+1|0}while((0|u)!=(0|l))}q(p=E+4|0,g,p),W(p),p=50}else if(He(A,i,E),0!=(0|a)&0!=(0|s))if((0|f)!=(0|h)&&m(23077,22949,243,22959),l=0|Ue(e,t),u=0|Ue(A,i),0|n[22032+(7*l|0)+u>>0])u=5;else if((0|(l=0|r[21200+(28*l|0)+(u<<2)>>2]))>0){I=E+4|0,u=0;do{ae(I),u=u+1|0}while((0|u)!=(0|l));p=50}else p=50;else p=50}while(0);return 50==(0|p)&&(u=E+4|0,r[o>>2]=r[u>>2],r[o+4>>2]=r[u+4>>2],r[o+8>>2]=r[u+8>>2],u=0),D=c,0|(E=u)}function et(e,t,A,n){A|=0,n|=0;var i,o,a=0,s=0,g=0,c=0,u=0,l=0,I=0,C=0,h=0,f=0,d=0,B=0,p=0;if(o=D,D=D+48|0,g=o+36|0,c=o+24|0,u=o+12|0,l=o,s=0|mt(0|(e|=0),0|(t|=0),52),v(),s&=15,C=0|mt(0|e,0|t,45),v(),i=0|_(C&=127),bt(0|s,0,52),d=134225919|v(),r[(f=n)>>2]=-1,r[f+4>>2]=d,!s)return(0|r[A>>2])>1||(0|r[A+4>>2])>1||(0|r[A+8>>2])>1||127==(0|(a=0|Z(C,0|ee(A))))?(D=o,0|(d=1)):(h=0|bt(0|a,0,45),f=0|v(),f=-1040385&r[(C=n)+4>>2]|f,r[(d=n)>>2]=r[C>>2]|h,r[d+4>>2]=f,D=o,0|(d=0));for(r[g>>2]=r[A>>2],r[g+4>>2]=r[A+4>>2],r[g+8>>2]=r[A+8>>2];r[c>>2]=r[g>>2],r[c+4>>2]=r[g+4>>2],r[c+8>>2]=r[g+8>>2],0|Te(s)?(te(g),r[u>>2]=r[g>>2],r[u+4>>2]=r[g+4>>2],r[u+8>>2]=r[g+8>>2],ne(u)):(Ae(g),r[u>>2]=r[g>>2],r[u+4>>2]=r[g+4>>2],r[u+8>>2]=r[g+8>>2],re(u)),z(c,u,l),W(l),B=0|r[(f=n)>>2],f=0|r[f+4>>2],A=0|bt(7,0,0|(p=3*(15-s|0)|0)),f&=~(0|v()),p=0|bt(0|ee(l),0,0|p),f=0|v()|f,r[(d=n)>>2]=p|B&~A,r[d+4>>2]=f,(0|s)>1;)s=s+-1|0;e:do{if((0|r[g>>2])<=1&&(0|r[g+4>>2])<=1&&(0|r[g+8>>2])<=1){l=127==(0|(c=0|Z(C,s=0|ee(g))))?0:0|_(c);t:do{if(s){if(i){if(g=21408+(28*(0|Ue(e,t))|0)+(s<<2)|0,(0|(g=0|r[g>>2]))>0){A=0;do{s=0|se(s),A=A+1|0}while((0|A)!=(0|g))}if(1==(0|s)){a=3;break e}127==(0|(A=0|Z(C,s)))&&m(23104,22949,376,23134),0|_(A)?m(23147,22949,377,23134):(h=g,I=s,a=A)}else h=0,I=s,a=c;if((0|(u=0|r[4304+(28*C|0)+(I<<2)>>2]))<=-1&&m(23178,22949,384,23134),!l){if((0|h)<=-1&&m(23030,22949,417,23134),0|h){s=0,A=0|r[(g=n)>>2],g=0|r[g+4>>2];do{A=0|Me(A,g),g=0|v(),r[(p=n)>>2]=A,r[p+4>>2]=g,s=s+1|0}while((0|s)<(0|h))}if((0|u)<=0){s=54;break}for(s=0,A=0|r[(g=n)>>2],g=0|r[g+4>>2];;)if(A=0|Me(A,g),g=0|v(),r[(p=n)>>2]=A,r[p+4>>2]=g,(0|(s=s+1|0))==(0|u)){s=54;break t}}if(7==(0|(c=0|H(a,C)))&&m(22925,22949,393,23134),A=0|r[(s=n)>>2],s=0|r[s+4>>2],(0|u)>0){g=0;do{A=0|Me(A,s),s=0|v(),r[(p=n)>>2]=A,r[p+4>>2]=s,g=g+1|0}while((0|g)!=(0|u))}if(A=0|Ue(A,s),p=0|M(a),(0|(A=0|r[(p?21824:21616)+(28*c|0)+(A<<2)>>2]))<=-1&&m(23030,22949,412,23134),A){s=0,g=0|r[(c=n)>>2],c=0|r[c+4>>2];do{g=0|_e(g,c),c=0|v(),r[(p=n)>>2]=g,r[p+4>>2]=c,s=s+1|0}while((0|s)<(0|A));s=54}else s=54}else if(0!=(0|i)&0!=(0|l))if(s=21408+(28*(p=0|Ue(e,t))|0)+((0|Ue(0|r[(s=n)>>2],0|r[s+4>>2]))<<2)|0,(0|(s=0|r[s>>2]))<=-1&&m(23201,22949,433,23134),s){a=0,A=0|r[(g=n)>>2],g=0|r[g+4>>2];do{A=0|Me(A,g),g=0|v(),r[(p=n)>>2]=A,r[p+4>>2]=g,a=a+1|0}while((0|a)<(0|s));a=c,s=54}else a=c,s=55;else a=c,s=54}while(0);if(54==(0|s)&&l&&(s=55),55==(0|s)&&1==(0|Ue(0|r[(p=n)>>2],0|r[p+4>>2]))){a=4;break}d=0|r[(p=n)>>2],p=-1040385&r[p+4>>2],B=0|bt(0|a,0,45),p=0|p|v(),r[(a=n)>>2]=d|B,r[a+4>>2]=p,a=0}else a=2}while(0);return D=o,0|(p=a)}function tt(e,t){var A=0;if(!(t|=0))return 0|(A=1);A=e|=0,e=1;do{e=0|p(0==(1&t|0)?1:A,e),t>>=1,A=0|p(A,A)}while(0!=(0|t));return 0|e}function At(e,t,A){e|=0;var n,o,a=0,s=0,g=0,c=0,u=0,l=0,I=0,C=0;if(!(0|J(t|=0,A|=0)))return 0|(C=0);if(t=0|Y(t),o=+i[A>>3],a=t&(a=+i[A+8>>3])<0?a+6.283185307179586:a,(0|(C=0|r[e>>2]))<=0)return 0|(C=0);if(n=0|r[e+4>>2],t){t=0,A=-1,e=0;e:for(;;){for(I=e;c=+i[n+(I<<4)>>3],l=+i[n+(I<<4)+8>>3],g=+i[n+((e=(A+2|0)%(0|C)|0)<<4)>>3],s=+i[n+(e<<4)+8>>3],c>g?(u=c,c=l):(u=g,g=c,c=s,s=l),ou;){if(!((0|(A=I+1|0))<(0|C))){A=22;break e}e=I,I=A,A=e}if(a=(c=c<0?c+6.283185307179586:c)==a|(l=s<0?s+6.283185307179586:s)==a?a+-2220446049250313e-31:a,((l+=(o-g)/(u-g)*(c-l))<0?l+6.283185307179586:l)>a&&(t^=1),(0|(e=I+1|0))>=(0|C)){A=22;break}A=I}if(22==(0|A))return 0|t}else{t=0,A=-1,e=0;e:for(;;){for(I=e;c=+i[n+(I<<4)>>3],l=+i[n+(I<<4)+8>>3],g=+i[n+((e=(A+2|0)%(0|C)|0)<<4)>>3],s=+i[n+(e<<4)+8>>3],c>g?(u=c,c=l):(u=g,g=c,c=s,s=l),ou;){if(!((0|(A=I+1|0))<(0|C))){A=22;break e}e=I,I=A,A=e}if(s+(o-g)/(u-g)*(c-s)>(a=c==a|s==a?a+-2220446049250313e-31:a)&&(t^=1),(0|(e=I+1|0))>=(0|C)){A=22;break}A=I}if(22==(0|A))return 0|t}return 0}function nt(e,t){t|=0;var A,n,o,a,g,c=0,u=0,l=0,I=0,C=0,h=0,f=0,d=0,B=0,p=0,E=0,Q=0;if(!(n=0|r[(e|=0)>>2]))return r[t>>2]=0,r[t+4>>2]=0,r[t+8>>2]=0,r[t+12>>2]=0,r[t+16>>2]=0,r[t+20>>2]=0,r[t+24>>2]=0,void(r[t+28>>2]=0);if(i[(o=t+8|0)>>3]=17976931348623157e292,i[(a=t+24|0)>>3]=17976931348623157e292,i[t>>3]=-17976931348623157e292,i[(g=t+16|0)>>3]=-17976931348623157e292,!((0|n)<=0)){for(A=0|r[e+4>>2],d=17976931348623157e292,B=-17976931348623157e292,p=0,e=-1,I=17976931348623157e292,C=17976931348623157e292,f=-17976931348623157e292,u=-17976931348623157e292,E=0;c=+i[A+(E<<4)>>3],h=+i[A+(E<<4)+8>>3],l=+i[A+(((0|(e=e+2|0))==(0|n)?0:e)<<4)+8>>3],c>3]=c,I=c),h>3]=h,C=h),c>f?i[t>>3]=c:c=f,h>u&&(i[g>>3]=h,u=h),d=h>0&hB?h:B,p|=+s(+(h-l))>3.141592653589793,(0|(e=E+1|0))!=(0|n);)Q=E,f=c,E=e,e=Q;p&&(i[g>>3]=B,i[a>>3]=d)}}function rt(e,t){t|=0;var A,n=0,o=0,a=0,g=0,c=0,u=0,l=0,I=0,C=0,h=0,f=0,d=0,B=0,p=0,E=0,Q=0,y=0,v=0,m=0,b=0,w=0;if(B=0|r[(e|=0)>>2]){if(i[(p=t+8|0)>>3]=17976931348623157e292,i[(E=t+24|0)>>3]=17976931348623157e292,i[t>>3]=-17976931348623157e292,i[(Q=t+16|0)>>3]=-17976931348623157e292,(0|B)>0){for(a=0|r[e+4>>2],f=17976931348623157e292,d=-17976931348623157e292,o=0,n=-1,l=17976931348623157e292,I=17976931348623157e292,h=-17976931348623157e292,c=-17976931348623157e292,y=0;g=+i[a+(y<<4)>>3],C=+i[a+(y<<4)+8>>3],u=+i[a+(((0|(b=n+2|0))==(0|B)?0:b)<<4)+8>>3],g>3]=g,l=g),C>3]=C,I=C),g>h?i[t>>3]=g:g=h,C>c&&(i[Q>>3]=C,c=C),f=C>0&Cd?C:d,o|=+s(+(C-u))>3.141592653589793,(0|(n=y+1|0))!=(0|B);)b=y,h=g,y=n,n=b;o&&(i[Q>>3]=d,i[E>>3]=f)}}else r[t>>2]=0,r[t+4>>2]=0,r[t+8>>2]=0,r[t+12>>2]=0,r[t+16>>2]=0,r[t+20>>2]=0,r[t+24>>2]=0,r[t+28>>2]=0;if(!((0|(n=0|r[(b=e+8|0)>>2]))<=0)){A=e+12|0,m=0;do{if(a=0|r[A>>2],o=m,E=t+((m=m+1|0)<<5)|0,Q=0|r[a+(o<<3)>>2]){if(i[(y=t+(m<<5)+8|0)>>3]=17976931348623157e292,i[(e=t+(m<<5)+24|0)>>3]=17976931348623157e292,i[E>>3]=-17976931348623157e292,i[(v=t+(m<<5)+16|0)>>3]=-17976931348623157e292,(0|Q)>0){for(B=0|r[a+(o<<3)+4>>2],f=17976931348623157e292,d=-17976931348623157e292,a=0,o=-1,p=0,l=17976931348623157e292,I=17976931348623157e292,C=-17976931348623157e292,c=-17976931348623157e292;g=+i[B+(p<<4)>>3],h=+i[B+(p<<4)+8>>3],u=+i[B+(((0|(o=o+2|0))==(0|Q)?0:o)<<4)+8>>3],g>3]=g,l=g),h>3]=h,I=h),g>C?i[E>>3]=g:g=C,h>c&&(i[v>>3]=h,c=h),f=h>0&hd?h:d,a|=+s(+(h-u))>3.141592653589793,(0|(o=p+1|0))!=(0|Q);)w=p,p=o,C=g,o=w;a&&(i[v>>3]=d,i[e>>3]=f)}}else r[E>>2]=0,r[E+4>>2]=0,r[E+8>>2]=0,r[E+12>>2]=0,r[E+16>>2]=0,r[E+20>>2]=0,r[E+24>>2]=0,r[E+28>>2]=0,n=0|r[b>>2]}while((0|m)<(0|n))}}function it(e,t,A){var n=0,i=0,o=0;if(!(0|At(e|=0,t|=0,A|=0)))return 0|(i=0);if((0|r[(i=e+8|0)>>2])<=0)return 0|(i=1);for(n=e+12|0,e=0;;){if(o=e,e=e+1|0,0|At((0|r[n>>2])+(o<<3)|0,t+(e<<5)|0,A)){e=0,n=6;break}if((0|e)>=(0|r[i>>2])){e=1,n=6;break}}return 6==(0|n)?0|e:0}function ot(e,t,A,n,r){t|=0,A|=0,n|=0,r|=0;var o,a,s,g,c,u,l,I=0;g=+i[(e|=0)>>3],s=+i[t>>3]-g,a=+i[e+8>>3],o=+i[t+8>>3]-a,u=+i[A>>3],I=((I=+i[n>>3]-u)*(a-(l=+i[A+8>>3]))-(g-u)*(c=+i[n+8>>3]-l))/(s*c-o*I),i[r>>3]=g+s*I,i[r+8>>3]=a+o*I}function at(e,t){return t|=0,+i[(e|=0)>>3]!=+i[t>>3]?0|(t=0):0|(t=+i[e+8>>3]==+i[t+8>>3])}function st(e,t){t|=0;var A,n,r;return+((r=+i[(e|=0)>>3]-+i[t>>3])*r+(n=+i[e+8>>3]-+i[t+8>>3])*n+(A=+i[e+16>>3]-+i[t+16>>3])*A)}function gt(e,t,A){e|=0,A|=0;var n=0;(0|(t|=0))>0?(n=0|pt(t,4),r[e>>2]=n,n||m(23230,23253,40,23267)):r[e>>2]=0,r[e+4>>2]=t,r[e+8>>2]=0,r[e+12>>2]=A}function ct(e){var t,A,n,o=0,a=0,g=0,u=0;t=(e|=0)+4|0,A=e+12|0,n=e+8|0;e:for(;;){for(a=0|r[t>>2],o=0;;){if((0|o)>=(0|a))break e;if(g=0|r[e>>2],u=0|r[g+(o<<2)>>2])break;o=o+1|0}o=g+(~~(+s(+ +c(10,+ +(15-(0|r[A>>2])|0))*(+i[u>>3]+ +i[u+8>>3]))%+(0|a))>>>0<<2)|0,a=0|r[o>>2];t:do{if(0|a){if(g=u+32|0,(0|a)==(0|u))r[o>>2]=r[g>>2];else{if(!(o=0|r[(a=a+32|0)>>2]))break;for(;(0|o)!=(0|u);)if(!(o=0|r[(a=o+32|0)>>2]))break t;r[a>>2]=r[g>>2]}Bt(u),r[n>>2]=(0|r[n>>2])-1}}while(0)}Bt(0|r[e>>2])}function ut(e){var t,A=0,n=0;for(t=0|r[(e|=0)+4>>2],n=0;;){if((0|n)>=(0|t)){A=0,n=4;break}if(A=0|r[(0|r[e>>2])+(n<<2)>>2]){n=4;break}n=n+1|0}return 4==(0|n)?0|A:0}function lt(e,t){t|=0;var A=0,n=0,o=0,a=0;if(A=~~(+s(+ +c(10,+ +(15-(0|r[(e|=0)+12>>2])|0))*(+i[t>>3]+ +i[t+8>>3]))%+(0|r[e+4>>2]))>>>0,A=(0|r[e>>2])+(A<<2)|0,!(n=0|r[A>>2]))return 0|(a=1);a=t+32|0;do{if((0|n)!=(0|t)){if(!(A=0|r[n+32>>2]))return 0|(a=1);for(o=A;;){if((0|o)==(0|t)){o=8;break}if(!(A=0|r[o+32>>2])){A=1,o=10;break}n=o,o=A}if(8==(0|o)){r[n+32>>2]=r[a>>2];break}if(10==(0|o))return 0|A}else r[A>>2]=r[a>>2]}while(0);return Bt(t),r[(a=e+8|0)>>2]=(0|r[a>>2])-1,0|(a=0)}function It(e,t,A){e|=0,t|=0,A|=0;var n,o=0,a=0,g=0;(n=0|dt(40))||m(23283,23253,98,23296),r[n>>2]=r[t>>2],r[n+4>>2]=r[t+4>>2],r[n+8>>2]=r[t+8>>2],r[n+12>>2]=r[t+12>>2],r[(a=n+16|0)>>2]=r[A>>2],r[a+4>>2]=r[A+4>>2],r[a+8>>2]=r[A+8>>2],r[a+12>>2]=r[A+12>>2],r[n+32>>2]=0,a=~~(+s(+ +c(10,+ +(15-(0|r[e+12>>2])|0))*(+i[t>>3]+ +i[t+8>>3]))%+(0|r[e+4>>2]))>>>0,a=(0|r[e>>2])+(a<<2)|0,o=0|r[a>>2];do{if(o){for(;!(0|Se(o,t)&&0|Se(o+16|0,A));)if(a=0|r[o+32>>2],!(0|r[(o=0==(0|a)?o:a)+32>>2])){g=10;break}if(10==(0|g)){r[o+32>>2]=n;break}return Bt(n),0|(g=o)}r[a>>2]=n}while(0);return r[(g=e+8|0)>>2]=1+(0|r[g>>2]),0|(g=n)}function Ct(e,t,A){t|=0,A|=0;var n=0,o=0;if(o=~~(+s(+ +c(10,+ +(15-(0|r[(e|=0)+12>>2])|0))*(+i[t>>3]+ +i[t+8>>3]))%+(0|r[e+4>>2]))>>>0,!(o=0|r[(0|r[e>>2])+(o<<2)>>2]))return 0|(A=0);if(!A){for(e=o;;){if(0|Se(e,t)){n=10;break}if(!(e=0|r[e+32>>2])){e=0,n=10;break}}if(10==(0|n))return 0|e}for(e=o;;){if(0|Se(e,t)&&0|Se(e+16|0,A)){n=10;break}if(!(e=0|r[e+32>>2])){e=0,n=10;break}}return 10==(0|n)?0|e:0}function ht(e,t){t|=0;var A=0;if(A=~~(+s(+ +c(10,+ +(15-(0|r[(e|=0)+12>>2])|0))*(+i[t>>3]+ +i[t+8>>3]))%+(0|r[e+4>>2]))>>>0,!(e=0|r[(0|r[e>>2])+(A<<2)>>2]))return 0|(A=0);for(;;){if(0|Se(e,t)){t=5;break}if(!(e=0|r[e+32>>2])){e=0,t=5;break}}return 5==(0|t)?0|e:0}function ft(e){return 0|~~+function(e){return+ +Dt(+(e=+e))}(e=+e)}function dt(e){e|=0;var t,A=0,n=0,i=0,o=0,a=0,s=0,g=0,c=0,u=0,l=0,I=0,C=0,h=0,f=0,d=0,B=0,p=0,E=0,Q=0,y=0;t=D,D=D+16|0,C=t;do{if(e>>>0<245){if(e=(u=e>>>0<11?16:e+11&-8)>>>3,3&(n=(I=0|r[5829])>>>e)|0)return i=0|r[(n=(e=23356+((A=(1&n^1)+e|0)<<1<<2)|0)+8|0)>>2],(0|(a=0|r[(o=i+8|0)>>2]))==(0|e)?r[5829]=I&~(1<>2]=e,r[n>>2]=a),y=A<<3,r[i+4>>2]=3|y,r[(y=i+y+4|0)>>2]=1|r[y>>2],D=t,0|(y=o);if(u>>>0>(l=0|r[5831])>>>0){if(0|n)return A=((A=n<>>=g=A>>>12&16)>>>5&8)|g|(a=(A>>>=n)>>>2&4)|(e=(A>>>=a)>>>1&2)|(i=(A>>>=e)>>>1&1))+(A>>>i)|0)<<1<<2)|0)+8|0)>>2],(0|(n=0|r[(g=a+8|0)>>2]))==(0|A)?(e=I&~(1<>2]=A,r[e>>2]=n,e=I),s=(y=i<<3)-u|0,r[a+4>>2]=3|u,r[(o=a+u|0)+4>>2]=1|s,r[a+y>>2]=s,0|l&&(i=0|r[5834],n=23356+((A=l>>>3)<<1<<2)|0,e&(A=1<>2]:(r[5829]=e|A,A=n,e=n+8|0),r[e>>2]=i,r[A+12>>2]=i,r[i+8>>2]=A,r[i+12>>2]=n),r[5831]=s,r[5834]=o,D=t,0|(y=g);if(a=0|r[5830]){for(n=(a&0-a)-1|0,n=c=0|r[23620+(((i=(n>>>=o=n>>>12&16)>>>5&8)|o|(s=(n>>>=i)>>>2&4)|(g=(n>>>=s)>>>1&2)|(c=(n>>>=g)>>>1&1))+(n>>>c)<<2)>>2],g=c,c=(-8&r[c+4>>2])-u|0;(e=0|r[n+16>>2])||(e=0|r[n+20>>2]);)n=e,g=(o=(s=(-8&r[e+4>>2])-u|0)>>>0>>0)?e:g,c=o?s:c;if((s=g+u|0)>>>0>g>>>0){o=0|r[g+24>>2],A=0|r[g+12>>2];do{if((0|A)==(0|g)){if(!(A=0|r[(e=g+20|0)>>2])&&!(A=0|r[(e=g+16|0)>>2])){n=0;break}for(;;)if(n=0|r[(i=A+20|0)>>2])A=n,e=i;else{if(!(n=0|r[(i=A+16|0)>>2]))break;A=n,e=i}r[e>>2]=0,n=A}else n=0|r[g+8>>2],r[n+12>>2]=A,r[A+8>>2]=n,n=A}while(0);do{if(0|o){if(A=0|r[g+28>>2],(0|g)==(0|r[(e=23620+(A<<2)|0)>>2])){if(r[e>>2]=n,!n){r[5830]=a&~(1<>2])==(0|g)?y:o+20|0)>>2]=n,!n)break;r[n+24>>2]=o,0|(A=0|r[g+16>>2])&&(r[n+16>>2]=A,r[A+24>>2]=n),0|(A=0|r[g+20>>2])&&(r[n+20>>2]=A,r[A+24>>2]=n)}}while(0);return c>>>0<16?(y=c+u|0,r[g+4>>2]=3|y,r[(y=g+y+4|0)>>2]=1|r[y>>2]):(r[g+4>>2]=3|u,r[s+4>>2]=1|c,r[s+c>>2]=c,0|l&&(i=0|r[5834],n=23356+((A=l>>>3)<<1<<2)|0,(A=1<>2]:(r[5829]=A|I,A=n,e=n+8|0),r[e>>2]=i,r[A+12>>2]=i,r[i+8>>2]=A,r[i+12>>2]=n),r[5831]=c,r[5834]=s),D=t,0|(y=g+8|0)}I=u}else I=u}else I=u}else if(e>>>0<=4294967231)if(u=-8&(e=e+11|0),i=0|r[5830]){o=0-u|0,c=(e>>>=8)?u>>>0>16777215?31:u>>>((c=14-((g=((d=e<<(I=(e+1048320|0)>>>16&8))+520192|0)>>>16&4)|I|(c=((d<<=g)+245760|0)>>>16&2))+(d<>>15)|0)+7|0)&1|c<<1:0,n=0|r[23620+(c<<2)>>2];e:do{if(n)for(e=0,g=u<<(31==(0|c)?0:25-(c>>>1)|0),a=0;;){if((s=(-8&r[n+4>>2])-u|0)>>>0>>0){if(!s){e=n,o=0,d=65;break e}e=n,o=s}if(a=0==(0|(d=0|r[n+20>>2]))|(0|d)==(0|(n=0|r[n+16+(g>>>31<<2)>>2]))?a:d,!n){n=a,d=61;break}g<<=1}else n=0,e=0,d=61}while(0);if(61==(0|d)){if(0==(0|n)&0==(0|e)){if(!(e=((e=2<>>=s=I>>>12&16)>>>5&8)|s|(g=(I>>>=a)>>>2&4)|(c=(I>>>=g)>>>1&2)|(n=(I>>>=c)>>>1&1))+(I>>>n)<<2)>>2]}n?d=65:(g=e,s=o)}if(65==(0|d))for(a=n;;){if(o=(n=(I=(-8&r[a+4>>2])-u|0)>>>0>>0)?I:o,e=n?a:e,(n=0|r[a+16>>2])||(n=0|r[a+20>>2]),!n){g=e,s=o;break}a=n}if(0!=(0|g)&&s>>>0<((0|r[5831])-u|0)>>>0&&(l=g+u|0)>>>0>g>>>0){a=0|r[g+24>>2],A=0|r[g+12>>2];do{if((0|A)==(0|g)){if(!(A=0|r[(e=g+20|0)>>2])&&!(A=0|r[(e=g+16|0)>>2])){A=0;break}for(;;)if(n=0|r[(o=A+20|0)>>2])A=n,e=o;else{if(!(n=0|r[(o=A+16|0)>>2]))break;A=n,e=o}r[e>>2]=0}else y=0|r[g+8>>2],r[y+12>>2]=A,r[A+8>>2]=y}while(0);do{if(a){if(e=0|r[g+28>>2],(0|g)==(0|r[(n=23620+(e<<2)|0)>>2])){if(r[n>>2]=A,!A){i&=~(1<>2])==(0|g)?y:a+20|0)>>2]=A,!A)break;r[A+24>>2]=a,0|(e=0|r[g+16>>2])&&(r[A+16>>2]=e,r[e+24>>2]=A),(e=0|r[g+20>>2])&&(r[A+20>>2]=e,r[e+24>>2]=A)}}while(0);e:do{if(s>>>0<16)y=s+u|0,r[g+4>>2]=3|y,r[(y=g+y+4|0)>>2]=1|r[y>>2];else{if(r[g+4>>2]=3|u,r[l+4>>2]=1|s,r[l+s>>2]=s,A=s>>>3,s>>>0<256){n=23356+(A<<1<<2)|0,(e=0|r[5829])&(A=1<>2]:(r[5829]=e|A,A=n,e=n+8|0),r[e>>2]=l,r[A+12>>2]=l,r[l+8>>2]=A,r[l+12>>2]=n;break}if(A=23620+((n=(A=s>>>8)?s>>>0>16777215?31:s>>>((n=14-((E=((y=A<<(Q=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|Q|(n=((y<<=E)+245760|0)>>>16&2))+(y<>>15)|0)+7|0)&1|n<<1:0)<<2)|0,r[l+28>>2]=n,r[(e=l+16|0)+4>>2]=0,r[e>>2]=0,!(i&(e=1<>2]=l,r[l+24>>2]=A,r[l+12>>2]=l,r[l+8>>2]=l;break}A=0|r[A>>2];t:do{if((-8&r[A+4>>2]|0)!=(0|s)){for(i=s<<(31==(0|n)?0:25-(n>>>1)|0);e=0|r[(n=A+16+(i>>>31<<2)|0)>>2];){if((-8&r[e+4>>2]|0)==(0|s)){A=e;break t}i<<=1,A=e}r[n>>2]=l,r[l+24>>2]=A,r[l+12>>2]=l,r[l+8>>2]=l;break e}}while(0);y=0|r[(Q=A+8|0)>>2],r[y+12>>2]=l,r[Q>>2]=l,r[l+8>>2]=y,r[l+12>>2]=A,r[l+24>>2]=0}}while(0);return D=t,0|(y=g+8|0)}I=u}else I=u;else I=-1}while(0);if((n=0|r[5831])>>>0>=I>>>0)return A=n-I|0,e=0|r[5834],A>>>0>15?(y=e+I|0,r[5834]=y,r[5831]=A,r[y+4>>2]=1|A,r[e+n>>2]=A,r[e+4>>2]=3|I):(r[5831]=0,r[5834]=0,r[e+4>>2]=3|n,r[(y=e+n+4|0)>>2]=1|r[y>>2]),D=t,0|(y=e+8|0);if((s=0|r[5832])>>>0>I>>>0)return E=s-I|0,r[5832]=E,Q=(y=0|r[5835])+I|0,r[5835]=Q,r[Q+4>>2]=1|E,r[y+4>>2]=3|I,D=t,0|(y=y+8|0);if(0|r[5947]?e=0|r[5949]:(r[5949]=4096,r[5948]=4096,r[5950]=-1,r[5951]=-1,r[5952]=0,r[5940]=0,r[5947]=-16&C^1431655768,e=4096),g=I+48|0,(u=(a=e+(c=I+47|0)|0)&(o=0-e|0))>>>0<=I>>>0)return D=t,0|(y=0);if(0|(e=0|r[5939])&&(C=(l=0|r[5937])+u|0)>>>0<=l>>>0|C>>>0>e>>>0)return D=t,0|(y=0);e:do{if(4&r[5940])A=0,d=143;else{n=0|r[5835];t:do{if(n){for(i=23764;!((C=0|r[i>>2])>>>0<=n>>>0&&(C+(0|r[i+4>>2])|0)>>>0>n>>>0);){if(!(e=0|r[i+8>>2])){d=128;break t}i=e}if((A=a-s&o)>>>0<2147483647)if((0|(e=0|Gt(0|A)))==((0|r[i>>2])+(0|r[i+4>>2])|0)){if(-1!=(0|e)){s=A,a=e,d=145;break e}}else i=e,d=136;else A=0}else d=128}while(0);do{if(128==(0|d))if(-1!=(0|(n=0|Gt(0)))&&(A=n,f=(A=(0==((f=(h=0|r[5948])+-1|0)&A|0)?0:(f+A&0-h)-A|0)+u|0)+(h=0|r[5937])|0,A>>>0>I>>>0&A>>>0<2147483647)){if(0|(C=0|r[5939])&&f>>>0<=h>>>0|f>>>0>C>>>0){A=0;break}if((0|(e=0|Gt(0|A)))==(0|n)){s=A,a=n,d=145;break e}i=e,d=136}else A=0}while(0);do{if(136==(0|d)){if(n=0-A|0,!(g>>>0>A>>>0&A>>>0<2147483647&-1!=(0|i))){if(-1==(0|i)){A=0;break}s=A,a=i,d=145;break e}if((e=c-A+(e=0|r[5949])&0-e)>>>0>=2147483647){s=A,a=i,d=145;break e}if(-1==(0|Gt(0|e))){Gt(0|n),A=0;break}s=e+A|0,a=i,d=145;break e}}while(0);r[5940]=4|r[5940],d=143}}while(0);if(143==(0|d)&&u>>>0<2147483647&&!(-1==(0|(E=0|Gt(0|u)))|1^(p=(B=(f=0|Gt(0))-E|0)>>>0>(I+40|0)>>>0)|E>>>0>>0&-1!=(0|E)&-1!=(0|f)^1)&&(s=p?B:A,a=E,d=145),145==(0|d)){A=(0|r[5937])+s|0,r[5937]=A,A>>>0>(0|r[5938])>>>0&&(r[5938]=A),c=0|r[5835];e:do{if(c){for(A=23764;;){if((0|a)==((e=0|r[A>>2])+(n=0|r[A+4>>2])|0)){d=154;break}if(!(i=0|r[A+8>>2]))break;A=i}if(154==(0|d)&&(Q=A+4|0,0==(8&r[A+12>>2]|0))&&a>>>0>c>>>0&e>>>0<=c>>>0){r[Q>>2]=n+s,Q=c+(E=0==(7&(E=c+8|0)|0)?0:0-E&7)|0,E=(y=(0|r[5832])+s|0)-E|0,r[5835]=Q,r[5832]=E,r[Q+4>>2]=1|E,r[c+y+4>>2]=40,r[5836]=r[5951];break}for(a>>>0<(0|r[5833])>>>0&&(r[5833]=a),n=a+s|0,A=23764;;){if((0|r[A>>2])==(0|n)){d=162;break}if(!(e=0|r[A+8>>2]))break;A=e}if(162==(0|d)&&0==(8&r[A+12>>2]|0)){r[A>>2]=a,r[(l=A+4|0)>>2]=(0|r[l>>2])+s,u=(l=a+(0==(7&(l=a+8|0)|0)?0:0-l&7)|0)+I|0,g=(A=n+(0==(7&(A=n+8|0)|0)?0:0-A&7)|0)-l-I|0,r[l+4>>2]=3|I;t:do{if((0|c)==(0|A))y=(0|r[5832])+g|0,r[5832]=y,r[5835]=u,r[u+4>>2]=1|y;else{if((0|r[5834])==(0|A)){y=(0|r[5831])+g|0,r[5831]=y,r[5834]=u,r[u+4>>2]=1|y,r[u+y>>2]=y;break}if(1==(3&(e=0|r[A+4>>2])|0)){s=-8&e,i=e>>>3;A:do{if(e>>>0<256){if(e=0|r[A+8>>2],(0|(n=0|r[A+12>>2]))==(0|e)){r[5829]=r[5829]&~(1<>2]=n,r[n+8>>2]=e;break}a=0|r[A+24>>2],e=0|r[A+12>>2];do{if((0|e)==(0|A)){if(e=0|r[(i=(n=A+16|0)+4|0)>>2])n=i;else if(!(e=0|r[n>>2])){e=0;break}for(;;)if(i=0|r[(o=e+20|0)>>2])e=i,n=o;else{if(!(i=0|r[(o=e+16|0)>>2]))break;e=i,n=o}r[n>>2]=0}else y=0|r[A+8>>2],r[y+12>>2]=e,r[e+8>>2]=y}while(0);if(!a)break;i=23620+((n=0|r[A+28>>2])<<2)|0;do{if((0|r[i>>2])==(0|A)){if(r[i>>2]=e,0|e)break;r[5830]=r[5830]&~(1<>2])==(0|A)?y:a+20|0)>>2]=e,!e)break A}while(0);if(r[e+24>>2]=a,0|(i=0|r[(n=A+16|0)>>2])&&(r[e+16>>2]=i,r[i+24>>2]=e),!(n=0|r[n+4>>2]))break;r[e+20>>2]=n,r[n+24>>2]=e}while(0);A=A+s|0,o=s+g|0}else o=g;if(r[(A=A+4|0)>>2]=-2&r[A>>2],r[u+4>>2]=1|o,r[u+o>>2]=o,A=o>>>3,o>>>0<256){n=23356+(A<<1<<2)|0,(e=0|r[5829])&(A=1<>2]:(r[5829]=e|A,A=n,e=n+8|0),r[e>>2]=u,r[A+12>>2]=u,r[u+8>>2]=A,r[u+12>>2]=n;break}A=o>>>8;do{if(A){if(o>>>0>16777215){i=31;break}i=o>>>((i=14-((E=((y=A<<(Q=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|Q|(i=((y<<=E)+245760|0)>>>16&2))+(y<>>15)|0)+7|0)&1|i<<1}else i=0}while(0);if(A=23620+(i<<2)|0,r[u+28>>2]=i,r[(e=u+16|0)+4>>2]=0,r[e>>2]=0,!((e=0|r[5830])&(n=1<>2]=u,r[u+24>>2]=A,r[u+12>>2]=u,r[u+8>>2]=u;break}A=0|r[A>>2];A:do{if((-8&r[A+4>>2]|0)!=(0|o)){for(i=o<<(31==(0|i)?0:25-(i>>>1)|0);e=0|r[(n=A+16+(i>>>31<<2)|0)>>2];){if((-8&r[e+4>>2]|0)==(0|o)){A=e;break A}i<<=1,A=e}r[n>>2]=u,r[u+24>>2]=A,r[u+12>>2]=u,r[u+8>>2]=u;break t}}while(0);y=0|r[(Q=A+8|0)>>2],r[y+12>>2]=u,r[Q>>2]=u,r[u+8>>2]=y,r[u+12>>2]=A,r[u+24>>2]=0}}while(0);return D=t,0|(y=l+8|0)}for(A=23764;!((e=0|r[A>>2])>>>0<=c>>>0&&(y=e+(0|r[A+4>>2])|0)>>>0>c>>>0);)A=0|r[A+8>>2];A=(e=(e=(o=y+-47|0)+(0==(7&(e=o+8|0)|0)?0:0-e&7)|0)>>>0<(o=c+16|0)>>>0?c:e)+8|0,Q=a+(E=0==(7&(E=a+8|0)|0)?0:0-E&7)|0,E=(n=s+-40|0)-E|0,r[5835]=Q,r[5832]=E,r[Q+4>>2]=1|E,r[a+n+4>>2]=40,r[5836]=r[5951],r[(n=e+4|0)>>2]=27,r[A>>2]=r[5941],r[A+4>>2]=r[5942],r[A+8>>2]=r[5943],r[A+12>>2]=r[5944],r[5941]=a,r[5942]=s,r[5944]=0,r[5943]=A,A=e+24|0;do{Q=A,r[(A=A+4|0)>>2]=7}while((Q+8|0)>>>0>>0);if((0|e)!=(0|c)){if(a=e-c|0,r[n>>2]=-2&r[n>>2],r[c+4>>2]=1|a,r[e>>2]=a,A=a>>>3,a>>>0<256){n=23356+(A<<1<<2)|0,(e=0|r[5829])&(A=1<>2]:(r[5829]=e|A,A=n,e=n+8|0),r[e>>2]=c,r[A+12>>2]=c,r[c+8>>2]=A,r[c+12>>2]=n;break}if(n=23620+((i=(A=a>>>8)?a>>>0>16777215?31:a>>>((i=14-((E=((y=A<<(Q=(A+1048320|0)>>>16&8))+520192|0)>>>16&4)|Q|(i=((y<<=E)+245760|0)>>>16&2))+(y<>>15)|0)+7|0)&1|i<<1:0)<<2)|0,r[c+28>>2]=i,r[c+20>>2]=0,r[o>>2]=0,!((A=0|r[5830])&(e=1<>2]=c,r[c+24>>2]=n,r[c+12>>2]=c,r[c+8>>2]=c;break}A=0|r[n>>2];t:do{if((-8&r[A+4>>2]|0)!=(0|a)){for(i=a<<(31==(0|i)?0:25-(i>>>1)|0);e=0|r[(n=A+16+(i>>>31<<2)|0)>>2];){if((-8&r[e+4>>2]|0)==(0|a)){A=e;break t}i<<=1,A=e}r[n>>2]=c,r[c+24>>2]=A,r[c+12>>2]=c,r[c+8>>2]=c;break e}}while(0);y=0|r[(Q=A+8|0)>>2],r[y+12>>2]=c,r[Q>>2]=c,r[c+8>>2]=y,r[c+12>>2]=A,r[c+24>>2]=0}}else 0==(0|(y=0|r[5833]))|a>>>0>>0&&(r[5833]=a),r[5941]=a,r[5942]=s,r[5944]=0,r[5838]=r[5947],r[5837]=-1,r[5842]=23356,r[5841]=23356,r[5844]=23364,r[5843]=23364,r[5846]=23372,r[5845]=23372,r[5848]=23380,r[5847]=23380,r[5850]=23388,r[5849]=23388,r[5852]=23396,r[5851]=23396,r[5854]=23404,r[5853]=23404,r[5856]=23412,r[5855]=23412,r[5858]=23420,r[5857]=23420,r[5860]=23428,r[5859]=23428,r[5862]=23436,r[5861]=23436,r[5864]=23444,r[5863]=23444,r[5866]=23452,r[5865]=23452,r[5868]=23460,r[5867]=23460,r[5870]=23468,r[5869]=23468,r[5872]=23476,r[5871]=23476,r[5874]=23484,r[5873]=23484,r[5876]=23492,r[5875]=23492,r[5878]=23500,r[5877]=23500,r[5880]=23508,r[5879]=23508,r[5882]=23516,r[5881]=23516,r[5884]=23524,r[5883]=23524,r[5886]=23532,r[5885]=23532,r[5888]=23540,r[5887]=23540,r[5890]=23548,r[5889]=23548,r[5892]=23556,r[5891]=23556,r[5894]=23564,r[5893]=23564,r[5896]=23572,r[5895]=23572,r[5898]=23580,r[5897]=23580,r[5900]=23588,r[5899]=23588,r[5902]=23596,r[5901]=23596,r[5904]=23604,r[5903]=23604,Q=a+(E=0==(7&(E=a+8|0)|0)?0:0-E&7)|0,E=(y=s+-40|0)-E|0,r[5835]=Q,r[5832]=E,r[Q+4>>2]=1|E,r[a+y+4>>2]=40,r[5836]=r[5951]}while(0);if((A=0|r[5832])>>>0>I>>>0)return E=A-I|0,r[5832]=E,Q=(y=0|r[5835])+I|0,r[5835]=Q,r[Q+4>>2]=1|E,r[y+4>>2]=3|I,D=t,0|(y=y+8|0)}return r[(y=23312)>>2]=12,D=t,0|(y=0)}function Bt(e){var t=0,A=0,n=0,i=0,o=0,a=0,s=0,g=0;if(e|=0){A=e+-8|0,i=0|r[5833],g=A+(t=-8&(e=0|r[e+-4>>2]))|0;do{if(1&e)s=A,a=A;else{if(n=0|r[A>>2],!(3&e))return;if(o=n+t|0,(a=A+(0-n)|0)>>>0>>0)return;if((0|r[5834])==(0|a)){if(3!=(3&(t=0|r[(e=g+4|0)>>2])|0)){s=a,t=o;break}return r[5831]=o,r[e>>2]=-2&t,r[a+4>>2]=1|o,void(r[a+o>>2]=o)}if(A=n>>>3,n>>>0<256){if(e=0|r[a+8>>2],(0|(t=0|r[a+12>>2]))==(0|e)){r[5829]=r[5829]&~(1<>2]=t,r[t+8>>2]=e,s=a,t=o;break}i=0|r[a+24>>2],e=0|r[a+12>>2];do{if((0|e)==(0|a)){if(e=0|r[(A=(t=a+16|0)+4|0)>>2])t=A;else if(!(e=0|r[t>>2])){e=0;break}for(;;)if(A=0|r[(n=e+20|0)>>2])e=A,t=n;else{if(!(A=0|r[(n=e+16|0)>>2]))break;e=A,t=n}r[t>>2]=0}else s=0|r[a+8>>2],r[s+12>>2]=e,r[e+8>>2]=s}while(0);if(i){if(t=0|r[a+28>>2],(0|r[(A=23620+(t<<2)|0)>>2])==(0|a)){if(r[A>>2]=e,!e){r[5830]=r[5830]&~(1<>2])==(0|a)?s:i+20|0)>>2]=e,!e){s=a,t=o;break}r[e+24>>2]=i,0|(A=0|r[(t=a+16|0)>>2])&&(r[e+16>>2]=A,r[A+24>>2]=e),(t=0|r[t+4>>2])?(r[e+20>>2]=t,r[t+24>>2]=e,s=a,t=o):(s=a,t=o)}else s=a,t=o}}while(0);if(!(a>>>0>=g>>>0)&&1&(n=0|r[(e=g+4|0)>>2])){if(2&n)r[e>>2]=-2&n,r[s+4>>2]=1|t,r[a+t>>2]=t,i=t;else{if((0|r[5835])==(0|g)){if(g=(0|r[5832])+t|0,r[5832]=g,r[5835]=s,r[s+4>>2]=1|g,(0|s)!=(0|r[5834]))return;return r[5834]=0,void(r[5831]=0)}if((0|r[5834])==(0|g))return g=(0|r[5831])+t|0,r[5831]=g,r[5834]=a,r[s+4>>2]=1|g,void(r[a+g>>2]=g);i=(-8&n)+t|0,A=n>>>3;do{if(n>>>0<256){if(t=0|r[g+8>>2],(0|(e=0|r[g+12>>2]))==(0|t)){r[5829]=r[5829]&~(1<>2]=e,r[e+8>>2]=t;break}o=0|r[g+24>>2],e=0|r[g+12>>2];do{if((0|e)==(0|g)){if(e=0|r[(A=(t=g+16|0)+4|0)>>2])t=A;else if(!(e=0|r[t>>2])){A=0;break}for(;;)if(A=0|r[(n=e+20|0)>>2])e=A,t=n;else{if(!(A=0|r[(n=e+16|0)>>2]))break;e=A,t=n}r[t>>2]=0,A=e}else A=0|r[g+8>>2],r[A+12>>2]=e,r[e+8>>2]=A,A=e}while(0);if(0|o){if(e=0|r[g+28>>2],(0|r[(t=23620+(e<<2)|0)>>2])==(0|g)){if(r[t>>2]=A,!A){r[5830]=r[5830]&~(1<>2])==(0|g)?n:o+20|0)>>2]=A,!A)break;r[A+24>>2]=o,0|(t=0|r[(e=g+16|0)>>2])&&(r[A+16>>2]=t,r[t+24>>2]=A),0|(e=0|r[e+4>>2])&&(r[A+20>>2]=e,r[e+24>>2]=A)}}while(0);if(r[s+4>>2]=1|i,r[a+i>>2]=i,(0|s)==(0|r[5834]))return void(r[5831]=i)}if(e=i>>>3,i>>>0<256)return A=23356+(e<<1<<2)|0,(t=0|r[5829])&(e=1<>2]:(r[5829]=t|e,e=A,t=A+8|0),r[t>>2]=s,r[e+12>>2]=s,r[s+8>>2]=e,void(r[s+12>>2]=A);e=23620+((n=(e=i>>>8)?i>>>0>16777215?31:i>>>((n=14-((o=((g=e<<(a=(e+1048320|0)>>>16&8))+520192|0)>>>16&4)|a|(n=((g<<=o)+245760|0)>>>16&2))+(g<>>15)|0)+7|0)&1|n<<1:0)<<2)|0,r[s+28>>2]=n,r[s+20>>2]=0,r[s+16>>2]=0,t=0|r[5830],A=1<>2];t:do{if((-8&r[e+4>>2]|0)!=(0|i)){for(n=i<<(31==(0|n)?0:25-(n>>>1)|0);t=0|r[(A=e+16+(n>>>31<<2)|0)>>2];){if((-8&r[t+4>>2]|0)==(0|i)){e=t;break t}n<<=1,e=t}r[A>>2]=s,r[s+24>>2]=e,r[s+12>>2]=s,r[s+8>>2]=s;break e}}while(0);g=0|r[(a=e+8|0)>>2],r[g+12>>2]=s,r[a>>2]=s,r[s+8>>2]=g,r[s+12>>2]=e,r[s+24>>2]=0}else r[5830]=t|A,r[e>>2]=s,r[s+24>>2]=e,r[s+12>>2]=s,r[s+8>>2]=s}while(0);if(g=(0|r[5837])-1|0,r[5837]=g,!(0|g)){for(e=23772;e=0|r[e>>2];)e=e+8|0;r[5837]=-1}}}}function pt(e,t){t|=0;var A=0;return(e|=0)?(A=0|p(t,e),(t|e)>>>0>65535&&(A=(0|(A>>>0)/(e>>>0))==(0|t)?A:-1)):A=0,(e=0|dt(A))&&3&r[e+-4>>2]?(Rt(0|e,0,0|A),0|e):0|e}function Et(e,t,A,n){return 0|(y(0|(n=(t|=0)-(n|=0)-((A|=0)>>>0>(e|=0)>>>0|0)>>>0)),e-A>>>0|0)}function Qt(e){return 0|((e|=0)?31-(0|Q(e^e-1))|0:32)}function yt(e,t,A,n,i){i|=0;var o=0,a=0,s=0,g=0,c=0,u=0,l=0,I=0,C=0,h=0;if(u=e|=0,a=A|=0,s=I=n|=0,!(c=g=t|=0))return o=0!=(0|i),s?o?(r[i>>2]=0|e,r[i+4>>2]=0&t,i=0,0|(y(0|(I=0)),i)):(i=0,0|(y(0|(I=0)),i)):(o&&(r[i>>2]=(u>>>0)%(a>>>0),r[i+4>>2]=0),i=(u>>>0)/(a>>>0)>>>0,0|(y(0|(I=0)),i));o=0==(0|s);do{if(a){if(!o){if((o=(0|Q(0|s))-(0|Q(0|c))|0)>>>0<=31){a=l=o+1|0,e=u>>>(l>>>0)&(t=o-31>>31)|c<<(s=31-o|0),t&=c>>>(l>>>0),o=0,s=u<>2]=0|e,r[i+4>>2]=g|0&t,i=0,0|(y(0|(I=0)),i)):(i=0,0|(y(0|(I=0)),i))}if((o=a-1|0)&a|0){a=s=33+(0|Q(0|a))-(0|Q(0|c))|0,e=(l=32-s|0)-1>>31&c>>>((C=s-32|0)>>>0)|(c<>>(s>>>0))&(t=C>>31),t&=c>>>(s>>>0),o=u<<(h=64-s|0)&(g=l>>31),s=(c<>>(C>>>0))&g|u<>31;break}return 0|i&&(r[i>>2]=o&u,r[i+4>>2]=0),1==(0|a)?(h=0|e,0|(y(0|(C=g|0&t)),h)):(C=c>>>((h=0|Qt(0|a))>>>0)|0,h=c<<32-h|u>>>(h>>>0)|0,0|(y(0|C),h))}if(o)return 0|i&&(r[i>>2]=(c>>>0)%(a>>>0),r[i+4>>2]=0),h=(c>>>0)/(a>>>0)>>>0,0|(y(0|(C=0)),h);if(!u)return 0|i&&(r[i>>2]=0,r[i+4>>2]=(c>>>0)%(s>>>0)),h=(c>>>0)/(s>>>0)>>>0,0|(y(0|(C=0)),h);if(!((o=s-1|0)&s))return 0|i&&(r[i>>2]=0|e,r[i+4>>2]=o&c|0&t),C=0,h=c>>>((0|Qt(0|s))>>>0),0|(y(0|C),h);if((o=(0|Q(0|s))-(0|Q(0|c))|0)>>>0<=30){a=t=o+1|0,e=c<<(s=31-o|0)|u>>>(t>>>0),t=c>>>(t>>>0),o=0,s=u<>2]=0|e,r[i+4>>2]=g|0&t,h=0,0|(y(0|(C=0)),h)):(h=0,0|(y(0|(C=0)),h))}while(0);if(a){c=0|function(e,t,A,n){return 0|(y((t|=0)+(n|=0)+((A=(e|=0)+(A|=0)>>>0)>>>0>>0|0)>>>0|0),0|A)}(0|(l=0|A),0|(u=I|0&n),-1,-1),A=0|v(),g=s,s=0;do{n=g,g=o>>>31|g<<1,o=s|o<<1,Et(0|c,0|A,0|(n=e<<1|n>>>31|0),0|(I=e>>>31|t<<1|0)),s=1&(C=(h=0|v())>>31|((0|h)<0?-1:0)<<1),e=0|Et(0|n,0|I,C&l|0,(((0|h)<0?-1:0)>>31|((0|h)<0?-1:0)<<1)&u|0),t=0|v(),a=a-1|0}while(0!=(0|a));c=g,g=0}else c=s,g=0,s=0;return a=0,0|i&&(r[i>>2]=e,r[i+4>>2]=t),h=-2&(o<<1|0)|s,0|(y(0|(C=(0|o)>>>31|(c|a)<<1|0&(a<<1|o>>>31)|g)),h)}function vt(e,t,A,n){var i,o;return o=D,D=D+16|0,yt(e|=0,t|=0,A|=0,n|=0,i=0|o),D=o,0|(y(0|r[i+4>>2]),0|r[i>>2])}function mt(e,t,A){return e|=0,t|=0,(0|(A|=0))<32?(y(t>>>A|0),e>>>A|(t&(1<>>A-32|0)}function bt(e,t,A){return e|=0,t|=0,(0|(A|=0))<32?(y(t<>>32-A|0),e<=0?+a(e+.5):+B(e-.5)}function Ft(e,t,A){e|=0,t|=0;var i,o,a=0;if((0|(A|=0))>=8192)return S(0|e,0|t,0|A),0|e;if(o=0|e,i=e+A|0,(3&e)==(3&t)){for(;3&e;){if(!A)return 0|o;n[e>>0]=0|n[t>>0],e=e+1|0,t=t+1|0,A=A-1|0}for(a=(A=-4&i|0)-64|0;(0|e)<=(0|a);)r[e>>2]=r[t>>2],r[e+4>>2]=r[t+4>>2],r[e+8>>2]=r[t+8>>2],r[e+12>>2]=r[t+12>>2],r[e+16>>2]=r[t+16>>2],r[e+20>>2]=r[t+20>>2],r[e+24>>2]=r[t+24>>2],r[e+28>>2]=r[t+28>>2],r[e+32>>2]=r[t+32>>2],r[e+36>>2]=r[t+36>>2],r[e+40>>2]=r[t+40>>2],r[e+44>>2]=r[t+44>>2],r[e+48>>2]=r[t+48>>2],r[e+52>>2]=r[t+52>>2],r[e+56>>2]=r[t+56>>2],r[e+60>>2]=r[t+60>>2],e=e+64|0,t=t+64|0;for(;(0|e)<(0|A);)r[e>>2]=r[t>>2],e=e+4|0,t=t+4|0}else for(A=i-4|0;(0|e)<(0|A);)n[e>>0]=0|n[t>>0],n[e+1>>0]=0|n[t+1>>0],n[e+2>>0]=0|n[t+2>>0],n[e+3>>0]=0|n[t+3>>0],e=e+4|0,t=t+4|0;for(;(0|e)<(0|i);)n[e>>0]=0|n[t>>0],e=e+1|0,t=t+1|0;return 0|o}function Rt(e,t,A){t|=0;var i,o=0,a=0,s=0;if(i=(e|=0)+(A|=0)|0,t&=255,(0|A)>=67){for(;3&e;)n[e>>0]=t,e=e+1|0;for(s=t|t<<8|t<<16|t<<24,a=(o=-4&i|0)-64|0;(0|e)<=(0|a);)r[e>>2]=s,r[e+4>>2]=s,r[e+8>>2]=s,r[e+12>>2]=s,r[e+16>>2]=s,r[e+20>>2]=s,r[e+24>>2]=s,r[e+28>>2]=s,r[e+32>>2]=s,r[e+36>>2]=s,r[e+40>>2]=s,r[e+44>>2]=s,r[e+48>>2]=s,r[e+52>>2]=s,r[e+56>>2]=s,r[e+60>>2]=s,e=e+64|0;for(;(0|e)<(0|o);)r[e>>2]=s,e=e+4|0}for(;(0|e)<(0|i);)n[e>>0]=t,e=e+1|0;return i-A|0}function Dt(e){return(e=+e)>=0?+a(e+.5):+B(e-.5)}function Gt(e){e|=0;var t,A,n;return n=0|w(),(0|e)>0&(0|(t=(A=0|r[o>>2])+e|0))<(0|A)|(0|t)<0?(R(0|t),b(12),-1):(0|t)>(0|n)&&!(0|F(0|t))?(b(12),-1):(r[o>>2]=t,0|A)}return{___uremdi3:vt,_bitshift64Lshr:mt,_bitshift64Shl:bt,_calloc:pt,_cellAreaKm2:function(e,t){var A,n,i,o=0;if(i=D,D=D+192|0,n=i,Je(e|=0,t|=0,A=i+168|0),je(e,t,n),(0|(t=0|r[n>>2]))>0){if(o=+Re(n+8|0,n+8+((1!=(0|t)&1)<<4)|0,A)+0,1!=(0|t)){e=1;do{o+=+Re(n+8+(e<<4)|0,n+8+(((0|(e=e+1|0))%(0|t)|0)<<4)|0,A)}while((0|e)<(0|t))}}else o=0;return D=i,6371.007180918475*o*6371.007180918475},_cellAreaM2:function(e,t){var A,n,i,o=0;if(i=D,D=D+192|0,n=i,Je(e|=0,t|=0,A=i+168|0),je(e,t,n),(0|(t=0|r[n>>2]))>0){if(o=+Re(n+8|0,n+8+((1!=(0|t)&1)<<4)|0,A)+0,1!=(0|t)){e=1;do{o+=+Re(n+8+(e<<4)|0,n+8+(((0|(e=e+1|0))%(0|t)|0)<<4)|0,A)}while((0|e)<(0|t))}}else o=0;return D=i,6371.007180918475*o*6371.007180918475*1e3*1e3},_cellAreaRads2:function(e,t){var A,n,i,o=0;if(i=D,D=D+192|0,n=i,Je(e|=0,t|=0,A=i+168|0),je(e,t,n),(0|(t=0|r[n>>2]))<=0)return D=i,+(o=0);if(o=+Re(n+8|0,n+8+((1!=(0|t)&1)<<4)|0,A)+0,1==(0|t))return D=i,+o;e=1;do{o+=+Re(n+8+(e<<4)|0,n+8+(((0|(e=e+1|0))%(0|t)|0)<<4)|0,A)}while((0|e)<(0|t));return D=i,+o},_compact:function(e,t,A){t|=0;var n,i=0,o=0,a=0,s=0,g=0,c=0,u=0,l=0,I=0,C=0,h=0,f=0,d=0,B=0,p=0,E=0,Q=0,y=0,m=0,b=0,w=0;if(!(A|=0))return 0|(b=0);if(i=0|r[(o=e|=0)>>2],!0&0==(15728640&(o=0|r[o+4>>2])|0)){if((0|A)<=0)return 0|(b=0);if(r[(b=t)>>2]=i,r[b+4>>2]=o,1==(0|A))return 0|(b=0);i=1;do{m=0|r[(y=e+(i<<3)|0)+4>>2],r[(b=t+(i<<3)|0)>>2]=r[y>>2],r[b+4>>2]=m,i=i+1|0}while((0|i)!=(0|A));return 0|(i=0)}if(!(m=0|dt(y=A<<3)))return 0|(b=-3);if(Ft(0|m,0|e,0|y),!(n=0|pt(A,8)))return Bt(m),0|(b=-3);i=A;e:for(;;){E=0|mt(0|(l=0|r[(s=m)>>2]),0|(s=0|r[s+4>>2]),52),v(),Q=(E&=15)+-1|0,p=(0|i)>0;t:do{if(p){if(B=((0|i)<0)<<31>>31,f=0|bt(0|Q,0,52),d=0|v(),Q>>>0>15)for(o=0,e=l,A=s;;){if(!(0==(0|e)&0==(0|A))){if(a=0|mt(0|e,0|A,52),v(),g=(0|(a&=15))<(0|Q),a=(0|a)==(0|Q),A=0|vt(0|(u=g?0:a?e:0),0|(e=g?0:a?A:0),0|i,0|B),v(),0==(0|(c=0|r[(g=a=n+(A<<3)|0)>>2]))&0==(0|(g=0|r[g+4>>2])))A=u;else for(f=0,h=A,C=g,A=u;;){if((0|f)>(0|i)){b=41;break e}if((0|c)==(0|A)&(-117440513&C|0)==(0|e)){u=0|mt(0|c,0|C,56),v(),I=(u&=7)+1|0,d=0|mt(0|c,0|C,45),v();A:do{if(0|_(127&d)){if(c=0|mt(0|c,0|C,52),v(),!(c&=15)){g=6;break}for(g=1;;){if(!(0==((d=0|bt(7,0,3*(15-g|0)|0))&A|0)&0==((0|v())&e|0))){g=7;break A}if(!(g>>>0>>0)){g=6;break}g=g+1|0}}else g=7}while(0);if((u+2|0)>>>0>g>>>0){b=51;break e}d=0|bt(0|I,0,56),e=0|v()|-117440513&e,r[(g=a)>>2]=0,r[g+4>>2]=0,g=h,A|=d}else g=(h+1|0)%(0|i)|0;if(0==(0|(c=0|r[(C=a=n+(g<<3)|0)>>2]))&0==(0|(C=0|r[C+4>>2])))break;f=f+1|0,h=g}r[(d=a)>>2]=A,r[d+4>>2]=e}if((0|(o=o+1|0))>=(0|i))break t;e=0|r[(A=m+(o<<3)|0)>>2],A=0|r[A+4>>2]}for(o=0,e=l,A=s;;){if(!(0==(0|e)&0==(0|A))){if(g=0|mt(0|e,0|A,52),v(),(0|(g&=15))>=(0|Q)){if((0|g)!=(0|Q)&&(e|=f,A=-15728641&A|d,g>>>0>=E>>>0)){a=Q;do{h=0|bt(7,0,3*(14-a|0)|0),a=a+1|0,e|=h,A=0|v()|A}while(a>>>0>>0)}}else e=0,A=0;if(g=0|vt(0|e,0|A,0|i,0|B),v(),!(0==(0|(u=0|r[(c=a=n+(g<<3)|0)>>2]))&0==(0|(c=0|r[c+4>>2]))))for(h=0;;){if((0|h)>(0|i)){b=41;break e}if((0|u)==(0|e)&(-117440513&c|0)==(0|A)){I=0|mt(0|u,0|c,56),v(),C=(I&=7)+1|0,w=0|mt(0|u,0|c,45),v();A:do{if(0|_(127&w)){if(u=0|mt(0|u,0|c,52),v(),!(u&=15)){c=6;break}for(c=1;;){if(!(0==((w=0|bt(7,0,3*(15-c|0)|0))&e|0)&0==((0|v())&A|0))){c=7;break A}if(!(c>>>0>>0)){c=6;break}c=c+1|0}}else c=7}while(0);if((I+2|0)>>>0>c>>>0){b=51;break e}w=0|bt(0|C,0,56),A=0|v()|-117440513&A,r[(C=a)>>2]=0,r[C+4>>2]=0,e|=w}else g=(g+1|0)%(0|i)|0;if(0==(0|(u=0|r[(c=a=n+(g<<3)|0)>>2]))&0==(0|(c=0|r[c+4>>2])))break;h=h+1|0}r[(w=a)>>2]=e,r[w+4>>2]=A}if((0|(o=o+1|0))>=(0|i))break t;e=0|r[(A=m+(o<<3)|0)>>2],A=0|r[A+4>>2]}}}while(0);if((i+5|0)>>>0<11){b=99;break}if(!(d=0|pt((0|i)/6|0,8))){b=58;break}t:do{if(p){h=0,C=0;do{if(!(0==(0|(o=0|r[(e=g=n+(h<<3)|0)>>2]))&0==(0|(e=0|r[e+4>>2])))){c=0|mt(0|o,0|e,56),v(),A=(c&=7)+1|0,u=-117440513&e,w=0|mt(0|o,0|e,45),v();A:do{if(0|_(127&w)){if(I=0|mt(0|o,0|e,52),v(),0|(I&=15))for(a=1;;){if(!(0==(o&(w=0|bt(7,0,3*(15-a|0)|0))|0)&0==(u&(0|v())|0)))break A;if(!(a>>>0>>0))break;a=a+1|0}o|=e=0|bt(0|A,0,56),e=0|v()|u,r[(A=g)>>2]=o,r[A+4>>2]=e,A=c+2|0}}while(0);7==(0|A)&&(r[(w=d+(C<<3)|0)>>2]=o,r[w+4>>2]=-117440513&e,C=C+1|0)}h=h+1|0}while((0|h)!=(0|i));if(p){if(f=((0|i)<0)<<31>>31,I=0|bt(0|Q,0,52),h=0|v(),Q>>>0>15)for(e=0,o=0;;){do{if(!(0==(0|l)&0==(0|s))){for(c=0|mt(0|l,0|s,52),v(),a=(0|(c&=15))<(0|Q),c=(0|c)==(0|Q),a=0|vt(0|(g=a?0:c?l:0),0|(c=a?0:c?s:0),0|i,0|f),v(),A=0;;){if((0|A)>(0|i)){b=98;break e}if((-117440513&(u=0|r[(w=n+(a<<3)|0)+4>>2])|0)==(0|c)&&(0|r[w>>2])==(0|g)){b=70;break}if((0|r[(w=n+((a=(a+1|0)%(0|i)|0)<<3)|0)>>2])==(0|g)&&(0|r[w+4>>2])==(0|c))break;A=A+1|0}if(70==(0|b)&&(b=0,!0&100663296==(117440512&u|0)))break;r[(w=t+(o<<3)|0)>>2]=l,r[w+4>>2]=s,o=o+1|0}}while(0);if((0|(e=e+1|0))>=(0|i)){i=C;break t}l=0|r[(s=m+(e<<3)|0)>>2],s=0|r[s+4>>2]}for(e=0,o=0;;){do{if(!(0==(0|l)&0==(0|s))){if(c=0|mt(0|l,0|s,52),v(),(0|(c&=15))>=(0|Q))if((0|c)!=(0|Q))if(A=l|I,a=-15728641&s|h,c>>>0>>0)c=a;else{g=Q;do{w=0|bt(7,0,3*(14-g|0)|0),g=g+1|0,A|=w,a=0|v()|a}while(g>>>0>>0);c=a}else A=l,c=s;else A=0,c=0;for(g=0|vt(0|A,0|c,0|i,0|f),v(),a=0;;){if((0|a)>(0|i)){b=98;break e}if((-117440513&(u=0|r[(w=n+(g<<3)|0)+4>>2])|0)==(0|c)&&(0|r[w>>2])==(0|A)){b=93;break}if((0|r[(w=n+((g=(g+1|0)%(0|i)|0)<<3)|0)>>2])==(0|A)&&(0|r[w+4>>2])==(0|c))break;a=a+1|0}if(93==(0|b)&&(b=0,!0&100663296==(117440512&u|0)))break;r[(w=t+(o<<3)|0)>>2]=l,r[w+4>>2]=s,o=o+1|0}}while(0);if((0|(e=e+1|0))>=(0|i)){i=C;break t}l=0|r[(s=m+(e<<3)|0)>>2],s=0|r[s+4>>2]}}else o=0,i=C}else o=0,i=0}while(0);if(Rt(0|n,0,0|y),Ft(0|m,0|d,i<<3|0),Bt(d),!i)break;t=t+(o<<3)|0}return 41==(0|b)?(Bt(m),Bt(n),0|(w=-1)):51==(0|b)?(Bt(m),Bt(n),0|(w=-2)):58==(0|b)?(Bt(m),Bt(n),0|(w=-3)):98==(0|b)?(Bt(d),Bt(m),Bt(n),0|(w=-1)):(99==(0|b)&&Ft(0|t,0|m,i<<3|0),Bt(m),Bt(n),0|(w=0))},_destroyLinkedPolygon:function(e){var t=0,A=0,n=0,i=0;if(e|=0)for(n=1;;){if(0|(t=0|r[e>>2]))do{if(0|(A=0|r[t>>2]))do{i=A,A=0|r[A+16>>2],Bt(i)}while(0!=(0|A));i=t,t=0|r[t+8>>2],Bt(i)}while(0!=(0|t));if(t=e,e=0|r[e+8>>2],n||Bt(t),!e)break;n=0}},_edgeLengthKm:function(e){return+ +i[20752+((e|=0)<<3)>>3]},_edgeLengthM:function(e){return+ +i[20880+((e|=0)<<3)>>3]},_emscripten_replace_memory:function(e){return n=new Int8Array(e),new Uint8Array(e),r=new Int32Array(e),new Float32Array(e),i=new Float64Array(e),A=e,!0},_exactEdgeLengthKm:function(e,t){var A,n,o=0,a=0,s=0,c=0,I=0,C=0;if(n=D,D=D+176|0,Ke(e|=0,t|=0,A=n),(0|(e=0|r[A>>2]))<=1)return D=n,+(s=0);t=e+-1|0,e=0,o=0,a=+i[A+8>>3],s=+i[A+16>>3];do{I=a,a=+i[A+8+((e=e+1|0)<<4)>>3],C=+l(.5*(a-I)),c=s,s=+i[A+8+(e<<4)+8>>3],c=C*C+(c=+l(.5*(s-c)))*(+u(+I)*+u(+a)*c),o+=2*+d(+ +g(+c),+ +g(+(1-c)))}while((0|e)!=(0|t));return D=n,+(C=6371.007180918475*o)},_exactEdgeLengthM:function(e,t){var A,n,o=0,a=0,s=0,c=0,I=0,C=0;if(n=D,D=D+176|0,Ke(e|=0,t|=0,A=n),(0|(e=0|r[A>>2]))<=1)return D=n,+(s=0);t=e+-1|0,e=0,o=0,a=+i[A+8>>3],s=+i[A+16>>3];do{I=a,a=+i[A+8+((e=e+1|0)<<4)>>3],C=+l(.5*(a-I)),c=s,s=+i[A+8+(e<<4)+8>>3],c=C*C+(c=+l(.5*(s-c)))*(+u(+I)*+u(+a)*c),o+=2*+d(+ +g(+c),+ +g(+(1-c)))}while((0|e)!=(0|t));return D=n,+(C=6371.007180918475*o*1e3)},_exactEdgeLengthRads:function(e,t){var A,n,o=0,a=0,s=0,c=0,I=0,C=0;if(n=D,D=D+176|0,Ke(e|=0,t|=0,A=n),(0|(e=0|r[A>>2]))<=1)return D=n,+(s=0);t=e+-1|0,e=0,o=0,a=+i[A+8>>3],s=+i[A+16>>3];do{I=a,a=+i[A+8+((e=e+1|0)<<4)>>3],C=+l(.5*(a-I)),c=s,s=+i[A+8+(e<<4)+8>>3],c=C*C+(c=+l(.5*(s-c)))*(+u(+a)*+u(+I)*c),o+=2*+d(+ +g(+c),+ +g(+(1-c)))}while((0|e)<(0|t));return D=n,+o},_experimentalH3ToLocalIj:function(e,t,A,n,r){var i,o;return r|=0,o=D,D=D+16|0,(e=0|$e(e|=0,t|=0,A|=0,n|=0,i=o))||(Ie(i,r),e=0),D=o,0|e},_experimentalLocalIjToH3:function(e,t,A,n){var r,i;return e|=0,t|=0,n|=0,r=D,D=D+16|0,Ce(A|=0,i=r),n=0|et(e,t,i,n),D=r,0|n},_free:Bt,_geoToH3:Ze,_getDestinationH3IndexFromUnidirectionalEdge:function(e,t){e|=0;var A,n,i=0;return A=D,D=D+16|0,i=A,!0&268435456==(2013265920&(t|=0)|0)?(n=0|mt(0|e,0|t,56),v(),r[i>>2]=0,i=0|N(e,-2130706433&t|134217728,7&n,i),t=0|v(),y(0|t),D=A,0|i):(i=0,y(0|(t=0)),D=A,0|i)},_getH3IndexesFromUnidirectionalEdge:function(e,t,A){e|=0;var n,i,o,a,s=0;o=D,D=D+16|0,n=o,a=!0&268435456==(2013265920&(t|=0)|0),i=-2130706433&t|134217728,r[(s=A|=0)>>2]=a?e:0,r[s+4>>2]=a?i:0,a?(t=0|mt(0|e,0|t,56),v(),r[n>>2]=0,e=0|N(e,i,7&t,n),t=0|v()):(e=0,t=0),r[(s=A+8|0)>>2]=e,r[s+4>>2]=t,D=o},_getH3UnidirectionalEdge:function(e,t,A,n){var i,o,a=0,s=0,g=0,c=0,u=0;if(o=D,D=D+16|0,i=o,!(0|Ve(e|=0,t|=0,A|=0,n|=0)))return c=0,y(0|(g=0)),D=o,0|c;for(g=-2130706433&t,a=(a=0==(0|Ne(e,t)))?1:2;r[i>>2]=0,s=a+1|0,!((0|(u=0|N(e,t,a,i)))==(0|A)&(0|v())==(0|n));){if(!(s>>>0<7)){a=0,e=0,c=6;break}a=s}return 6==(0|c)?(y(0|a),D=o,0|e):(u=0|bt(0|a,0,56),c=0|g|v()|268435456,u|=e,y(0|c),D=o,0|u)},_getH3UnidirectionalEdgeBoundary:Ke,_getH3UnidirectionalEdgesFromHexagon:function(e,t,A){A|=0;var n,i=0;n=0==(0|Ne(e|=0,t|=0)),t&=-2130706433,r[(i=A)>>2]=n?e:0,r[i+4>>2]=n?285212672|t:0,r[(i=A+8|0)>>2]=e,r[i+4>>2]=301989888|t,r[(i=A+16|0)>>2]=e,r[i+4>>2]=318767104|t,r[(i=A+24|0)>>2]=e,r[i+4>>2]=335544320|t,r[(i=A+32|0)>>2]=e,r[i+4>>2]=352321536|t,r[(A=A+40|0)>>2]=e,r[A+4>>2]=369098752|t},_getOriginH3IndexFromUnidirectionalEdge:function(e,t){var A;return e|=0,y(0|((A=!0&268435456==(2013265920&(t|=0)|0))?-2130706433&t|134217728:0)),0|(A?e:0)},_getPentagonIndexes:Pe,_getRes0Indexes:function(e){e|=0;var t=0,A=0,n=0;t=0;do{bt(0|t,0,45),n=134225919|v(),r[(A=e+(t<<3)|0)>>2]=-1,r[A+4>>2]=n,t=t+1|0}while(122!=(0|t))},_h3Distance:function(e,t,A,n){var r,i,o;return A|=0,n|=0,o=D,D=D+32|0,i=o,e=0==(0|$e(e|=0,t|=0,e,t,r=o+12|0))&&0==(0|$e(e,t,A,n,i))?0|le(r,i):-1,D=o,0|e},_h3GetBaseCell:De,_h3GetFaces:function e(t,A,n){n|=0;var i,o=0,a=0,s=0,g=0,c=0,u=0,l=0,I=0;i=D,D=D+128|0,l=i+112|0,s=i+96|0,I=i,a=0|mt(0|(t|=0),0|(A|=0),52),v(),c=15&a,r[l>>2]=c,g=0|mt(0|t,0|A,45),v(),g&=127;e:do{if(0|_(g)){if(0|c)for(o=1;;){if(!(0==((u=0|bt(7,0,3*(15-o|0)|0))&t|0)&0==((0|v())&A|0))){a=0;break e}if(!(o>>>0>>0))break;o=o+1|0}if(!(1&a))return u=0|bt(c+1|0,0,52),I=0|v()|-15728641&A,e((u|t)&~(l=0|bt(7,0,3*(14-c|0)|0)),I&~(0|v()),n),void(D=i);a=1}else a=0}while(0);Ye(t,A,s),a?(Qe(s,l,I),u=5):(be(s,l,I),u=6);e:do{if(0|_(g))if(c)for(o=1;;){if(!(0==((g=0|bt(7,0,3*(15-o|0)|0))&t|0)&0==((0|v())&A|0))){o=8;break e}if(!(o>>>0>>0)){o=20;break}o=o+1|0}else o=20;else o=8}while(0);if(Rt(0|n,-1,0|o),a){a=0;do{for(ve(s=I+(a<<4)|0,0|r[l>>2]),s=0|r[s>>2],o=0;!(-1==(0|(c=0|r[(g=n+(o<<2)|0)>>2]))|(0|c)==(0|s));)o=o+1|0;r[g>>2]=s,a=a+1|0}while((0|a)!=(0|u))}else{a=0;do{for(ye(s=I+(a<<4)|0,0|r[l>>2],0,1),s=0|r[s>>2],o=0;!(-1==(0|(c=0|r[(g=n+(o<<2)|0)>>2]))|(0|c)==(0|s));)o=o+1|0;r[g>>2]=s,a=a+1|0}while((0|a)!=(0|u))}D=i},_h3IndexesAreNeighbors:Ve,_h3IsPentagon:Ne,_h3IsResClassIII:function(e,t){return t=0|mt(0|(e|=0),0|(t|=0),52),v(),1&t|0},_h3IsValid:Ge,_h3Line:function(e,t,A,n,i){A|=0,n|=0,i|=0;var o,a=0,g=0,c=0,u=0,l=0,I=0,C=0,h=0,f=0,d=0,B=0,p=0,E=0,Q=0,y=0,v=0,m=0;if(o=D,D=D+48|0,g=o+12|0,v=o,0==(0|$e(e|=0,t|=0,e,t,a=o+24|0))&&0==(0|$e(e,t,A,n,g))){if((0|(y=0|le(a,g)))<0)return D=o,0|(v=y);for(r[a>>2]=0,r[a+4>>2]=0,r[a+8>>2]=0,r[g>>2]=0,r[g+4>>2]=0,r[g+8>>2]=0,$e(e,t,e,t,a),$e(e,t,A,n,g),he(a),he(g),y?(f=+(0|y),Q=a,A=I=0|r[a>>2],n=C=0|r[(p=a+4|0)>>2],a=h=0|r[(E=a+8|0)>>2],d=+((0|r[g>>2])-I|0)/f,B=+((0|r[g+4>>2])-C|0)/f,f=+((0|r[g+8>>2])-h|0)/f):(p=n=a+4|0,E=h=a+8|0,Q=a,A=0|r[a>>2],n=0|r[n>>2],a=0|r[h>>2],d=0,B=0,f=0),r[v>>2]=A,r[(h=v+4|0)>>2]=n,r[(C=v+8|0)>>2]=a,I=0;;){m=d*(u=+(0|I))+ +(0|A),c=B*u+ +(0|r[p>>2]),u=f*u+ +(0|r[E>>2]),n=~~+St(+m),g=~~+St(+c),A=~~+St(+u),m=+s(+(+(0|n)-m)),c=+s(+(+(0|g)-c)),u=+s(+(+(0|A)-u));do{if(!(m>c&m>u)){if(l=0-n|0,c>u){a=l-A|0;break}a=g,A=l-g|0;break}n=0-(g+A)|0,a=g}while(0);if(r[v>>2]=n,r[h>>2]=a,r[C>>2]=A,fe(v),et(e,t,v,i+(I<<3)|0),(0|I)==(0|y))break;I=I+1|0,A=0|r[Q>>2]}return D=o,0|(v=0)}return D=o,0|(v=-1)},_h3LineSize:function(e,t,A,n){var r,i,o;return A|=0,n|=0,o=D,D=D+32|0,i=o,e=0==(0|$e(e|=0,t|=0,e,t,r=o+12|0))&&0==(0|$e(e,t,A,n,i))?0|le(r,i):-1,D=o,(e>>>31^1)+e|0},_h3SetToLinkedGeo:function(e,t,A){A|=0;var n,i,o,a=0;if(o=D,D=D+32|0,n=o,function(e,t,A){e|=0,A|=0;var n,i,o=0,a=0,s=0,g=0,c=0;if(i=D,D=D+176|0,n=i,(0|(t|=0))<1)return gt(A,0,0),void(D=i);g=0|mt(0|r[(g=e)>>2],0|r[g+4>>2],52),v(),gt(A,(0|t)>6?t:6,15&g),g=0;do{if(je(0|r[(o=e+(g<<3)|0)>>2],0|r[o+4>>2],n),(0|(o=0|r[n>>2]))>0){c=0;do{s=n+8+(c<<4)|0,(a=0|Ct(A,o=n+8+(((0|(c=c+1|0))%(0|o)|0)<<4)|0,s))?lt(A,a):It(A,s,o),o=0|r[n>>2]}while((0|c)<(0|o))}g=g+1|0}while((0|g)!=(0|t));D=i}(e|=0,t|=0,i=o+16|0),r[A>>2]=0,r[A+4>>2]=0,r[A+8>>2]=0,!(e=0|ut(i)))return qe(A),ct(i),void(D=o);do{t=0|We(A);do{Xe(t,e),a=e+16|0,r[n>>2]=r[a>>2],r[n+4>>2]=r[a+4>>2],r[n+8>>2]=r[a+8>>2],r[n+12>>2]=r[a+12>>2],lt(i,e),e=0|ht(i,n)}while(0!=(0|e));e=0|ut(i)}while(0!=(0|e));qe(A),ct(i),D=o},_h3ToCenterChild:function(e,t,A){A|=0;var n=0,r=0;if(n=0|mt(0|(e|=0),0|(t|=0),52),v(),(0|A)<16&(0|(n&=15))<=(0|A)){if((0|n)!=(0|A)&&(e|=r=0|bt(0|A,0,52),t=0|v()|-15728641&t,(0|n)<(0|A)))do{r=0|bt(7,0,3*(14-n|0)|0),n=n+1|0,e&=~r,t&=~(0|v())}while((0|n)<(0|A))}else t=0,e=0;return y(0|t),0|e},_h3ToChildren:xe,_h3ToGeo:Je,_h3ToGeoBoundary:je,_h3ToParent:ke,_h3UnidirectionalEdgeIsValid:function(e,t){var A=0;if(!(!0&268435456==(2013265920&(t|=0)|0)))return 0|(A=0);switch(A=0|mt(0|(e|=0),0|t,56),v(),7&A){case 0:case 7:return 0|(A=0)}return!0&16777216==(117440512&t|0)&0!=(0|Ne(e,A=-2130706433&t|134217728))?0|(A=0):0|(A=0|Ge(e,A))},_hexAreaKm2:function(e){return+ +i[20496+((e|=0)<<3)>>3]},_hexAreaM2:function(e){return+ +i[20624+((e|=0)<<3)>>3]},_hexRing:function(e,t,A,n){e|=0,t|=0,n|=0;var i,o=0,a=0,s=0,g=0,c=0,u=0,l=0;if(i=D,D=D+16|0,l=i,!(A|=0))return r[(l=n)>>2]=e,r[l+4>>2]=t,D=i,0|(l=0);r[l>>2]=0;e:do{if(0|Ne(e,t))e=1;else{if(a=(0|A)>0){o=0,u=e;do{if(0==(0|(u=0|N(u,t,4,l)))&0==(0|(t=0|v()))){e=2;break e}if(o=o+1|0,0|Ne(u,t)){e=1;break e}}while((0|o)<(0|A));if(r[(c=n)>>2]=u,r[c+4>>2]=t,c=A+-1|0,a){a=0,s=1,o=u,e=t;do{if(0==(0|(o=0|N(o,e,2,l)))&0==(0|(e=0|v()))){e=2;break e}if(r[(g=n+(s<<3)|0)>>2]=o,r[g+4>>2]=e,s=s+1|0,0|Ne(o,e)){e=1;break e}a=a+1|0}while((0|a)<(0|A));g=0,a=s;do{if(0==(0|(o=0|N(o,e,3,l)))&0==(0|(e=0|v()))){e=2;break e}if(r[(s=n+(a<<3)|0)>>2]=o,r[s+4>>2]=e,a=a+1|0,0|Ne(o,e)){e=1;break e}g=g+1|0}while((0|g)<(0|A));s=0;do{if(0==(0|(o=0|N(o,e,1,l)))&0==(0|(e=0|v()))){e=2;break e}if(r[(g=n+(a<<3)|0)>>2]=o,r[g+4>>2]=e,a=a+1|0,0|Ne(o,e)){e=1;break e}s=s+1|0}while((0|s)<(0|A));s=0;do{if(0==(0|(o=0|N(o,e,5,l)))&0==(0|(e=0|v()))){e=2;break e}if(r[(g=n+(a<<3)|0)>>2]=o,r[g+4>>2]=e,a=a+1|0,0|Ne(o,e)){e=1;break e}s=s+1|0}while((0|s)<(0|A));s=0;do{if(0==(0|(o=0|N(o,e,4,l)))&0==(0|(e=0|v()))){e=2;break e}if(r[(g=n+(a<<3)|0)>>2]=o,r[g+4>>2]=e,a=a+1|0,0|Ne(o,e)){e=1;break e}s=s+1|0}while((0|s)<(0|A));for(s=0;;){if(0==(0|(o=0|N(o,e,6,l)))&0==(0|(e=0|v()))){e=2;break e}if((0|s)!=(0|c)){if(r[(g=n+(a<<3)|0)>>2]=o,r[g+4>>2]=e,0|Ne(o,e)){e=1;break e}a=a+1|0}if((0|(s=s+1|0))>=(0|A)){s=u,a=t;break}}}else s=u,o=u,a=t,e=t}else r[(s=n)>>2]=e,r[s+4>>2]=t,s=e,o=e,a=t,e=t;e=1&((0|s)!=(0|o)|(0|a)!=(0|e))}}while(0);return D=i,0|(l=e)},_i64Subtract:Et,_kRing:G,_kRingDistances:function(e,t,A,n,r){var i;if(0|k(e|=0,t|=0,A|=0,n|=0,r|=0)){if(Rt(0|n,0,(i=1+(0|p(3*A|0,A+1|0))|0)<<3|0),0|r)return Rt(0|r,0,i<<2|0),void x(e,t,A,n,r,i,0);(r=0|pt(i,4))&&(x(e,t,A,n,r,i,0),Bt(r))}},_llvm_minnum_f64:wt,_llvm_round_f64:St,_malloc:dt,_maxFaceCount:function(e,t){var A=0,n=0;if(n=0|mt(0|(e|=0),0|(t|=0),45),v(),!(0|_(127&n)))return 0|(n=2);if(n=0|mt(0|e,0|t,52),v(),!(n&=15))return 0|(n=5);for(A=1;;){if(!(0==((0|bt(7,0,3*(15-A|0)|0))&e|0)&0==((0|v())&t|0))){A=2,e=6;break}if(!(A>>>0>>0)){A=5,e=6;break}A=A+1|0}return 6==(0|e)?0|A:0},_maxH3ToChildrenSize:function(e,t,A){return A|=0,e=0|mt(0|(e|=0),0|(t|=0),52),v(),(0|A)<16&(0|(e&=15))<=(0|A)?0|(A=0|tt(7,A-e|0)):0|(A=0)},_maxKringSize:function(e){return 1+(0|p(3*(e|=0)|0,e+1|0))|0},_maxPolyfillSize:function(e,t){t|=0;var A,n=0,i=0,o=0,a=0,s=0;if(A=D,D=D+48|0,o=A+8|0,i=A,a=0|r[(s=e|=0)+4>>2],r[(n=i)>>2]=r[s>>2],r[n+4>>2]=a,nt(i,o),o=0|j(o,t),t=0|r[i>>2],(0|(i=0|r[e+8>>2]))<=0)return D=A,0|(s=(s=(a=(0|o)<(0|(s=t)))?s:o)+12|0);n=0|r[e+12>>2],e=0;do{t=(0|r[n+(e<<3)>>2])+t|0,e=e+1|0}while((0|e)<(0|i));return D=A,0|(s=(s=(s=(0|o)<(0|t))?t:o)+12|0)},_maxUncompactSize:function(e,t,A){e|=0,A|=0;var n=0,i=0,o=0,a=0;if((0|(t|=0))<=0)return 0|(A=0);if((0|A)>=16){for(n=0;;){if(!(0==(0|r[(a=e+(n<<3)|0)>>2])&0==(0|r[a+4>>2]))){n=-1,i=13;break}if((0|(n=n+1|0))>=(0|t)){n=0,i=13;break}}if(13==(0|i))return 0|n}n=0,a=0;e:for(;;){o=0|r[(i=e+(a<<3)|0)>>2],i=0|r[i+4>>2];do{if(!(0==(0|o)&0==(0|i))){if(i=0|mt(0|o,0|i,52),v(),(0|(i&=15))>(0|A)){n=-1,i=13;break e}if((0|i)==(0|A)){n=n+1|0;break}n=(0|tt(7,A-i|0))+n|0;break}}while(0);if((0|(a=a+1|0))>=(0|t)){i=13;break}}return 13==(0|i)?0|n:0},_memcpy:Ft,_memset:Rt,_numHexagons:function(e){var t;return e=0|r[(t=21008+((e|=0)<<3)|0)>>2],y(0|r[t+4>>2]),0|e},_pentagonIndexCount:function(){return 12},_pointDistKm:Fe,_pointDistM:function(e,t){e|=0;var A,n,r,o=0;return n=+i[(t|=0)>>3],A=+i[e>>3],o=(r=+l(.5*(n-A)))*r+(o=+l(.5*(+i[t+8>>3]-+i[e+8>>3])))*(+u(+n)*+u(+A)*o),2*+d(+ +g(+o),+ +g(+(1-o)))*6371.007180918475*1e3},_pointDistRads:function(e,t){e|=0;var A,n,r,o=0;return n=+i[(t|=0)>>3],A=+i[e>>3],o=(r=+l(.5*(n-A)))*r+(o=+l(.5*(+i[t+8>>3]-+i[e+8>>3])))*(+u(+n)*+u(+A)*o),2*+d(+ +g(+o),+ +g(+(1-o)))},_polyfill:function(e,t,A){var n,i=0,o=0,a=0,s=0,g=0;if(n=D,D=D+48|0,i=n+8|0,o=n,0|function(e,t,A){t|=0,A|=0;var n,i,o,a,s,g=0,c=0,u=0,l=0,I=0,C=0,h=0,f=0,d=0,B=0,p=0,E=0,Q=0,y=0,b=0,w=0,S=0,F=0,R=0,G=0,N=0,_=0,M=0,O=0,L=0;s=D,D=D+112|0,i=s+80|0,C=s+72|0,o=s,a=s+56|0,(L=0|dt(32+(r[(h=(e=e|0)+8|0)>>2]<<5)|0))||m(22848,22448,800,22456);if(rt(e,L),g=0|r[(u=e)+4>>2],r[(I=C)>>2]=r[u>>2],r[I+4>>2]=g,nt(C,i),I=0|j(i,t),g=0|r[C>>2],(0|(u=0|r[h>>2]))>0){l=0|r[e+12>>2],c=0;do{g=(0|r[l+(c<<3)>>2])+g|0,c=c+1|0}while((0|c)!=(0|u))}if(c=0|pt(n=(I=(0|I)<(0|g)?g:I)+12|0,8),f=0|pt(n,8),r[i>>2]=0,O=0|r[(M=e)+4>>2],r[(g=C)>>2]=r[M>>2],r[g+4>>2]=O,0|(g=0|U(C,n,t,i,c,f)))return Bt(c),Bt(f),Bt(L),D=s,0|(L=g);e:do{if((0|r[h>>2])>0){for(u=e+12|0,g=0;l=0|U((0|r[u>>2])+(g<<3)|0,n,t,i,c,f),g=g+1|0,!(0|l);)if((0|g)>=(0|r[h>>2]))break e;return Bt(c),Bt(f),Bt(L),D=s,0|(L=l)}}while(0);(0|I)>-12&&Rt(0|f,0,((0|n)>1?n:1)<<3|0);e:do{if((0|r[i>>2])>0){O=((0|n)<0)<<31>>31,F=c,R=f,G=c,N=c,_=f,M=c,g=c,y=c,b=f,w=f,S=f,c=f;t:for(;;){for(Q=0|r[i>>2],p=0,E=0,u=0;;){I=(l=o)+56|0;do{r[l>>2]=0,l=l+4|0}while((0|l)<(0|I));if(C=0|r[(t=F+(p<<3)|0)>>2],t=0|r[t+4>>2],0|k(C,t,1,o,0)){I=(l=o)+56|0;do{r[l>>2]=0,l=l+4|0}while((0|l)<(0|I));0|(l=0|pt(7,4))&&(x(C,t,1,o,l,7,0),Bt(l))}B=0;do{f=0|r[(d=o+(B<<3)|0)>>2],d=0|r[d+4>>2];A:do{if(!(0==(0|f)&0==(0|d))){if(C=0|vt(0|f,0|d,0|n,0|O),v(),t=0|r[(I=l=A+(C<<3)|0)>>2],I=0|r[I+4>>2],!(0==(0|t)&0==(0|I)))for(h=0;;){if((0|h)>(0|n))break t;if((0|t)==(0|f)&(0|I)==(0|d))break A;if(t=0|r[(I=l=A+((C=(C+1|0)%(0|n)|0)<<3)|0)>>2],I=0|r[I+4>>2],0==(0|t)&0==(0|I))break;h=h+1|0}0==(0|f)&0==(0|d)||(Je(f,d,a),0|it(e,L,a)&&(r[(h=l)>>2]=f,r[h+4>>2]=d,r[(h=R+(u<<3)|0)>>2]=f,r[h+4>>2]=d,u=u+1|0))}}while(0);B=B+1|0}while(B>>>0<7);if((0|(E=E+1|0))>=(0|Q))break;p=p+1|0}if((0|Q)>0&&Rt(0|G,0,Q<<3|0),r[i>>2]=u,!((0|u)>0))break e;f=c,d=S,B=M,p=w,E=b,Q=R,c=y,S=g,w=N,b=G,y=f,g=d,M=_,_=B,N=p,G=E,R=F,F=Q}return Bt(N),Bt(_),Bt(L),D=s,0|(L=-1)}g=f}while(0);return Bt(L),Bt(c),Bt(g),D=s,0|(L=0)}(e|=0,t|=0,A|=0)){if(a=0|r[(g=e)+4>>2],r[(s=o)>>2]=r[g>>2],r[s+4>>2]=a,nt(o,i),s=0|j(i,t),t=0|r[o>>2],(0|(a=0|r[e+8>>2]))>0){o=0|r[e+12>>2],i=0;do{t=(0|r[o+(i<<3)>>2])+t|0,i=i+1|0}while((0|i)!=(0|a))}(0|(t=(0|s)<(0|t)?t:s))<=-12||Rt(0|A,0,8+(((0|(g=t+11|0))>0?g:0)<<3)|0),D=n}else D=n},_res0IndexCount:function(){return 122},_round:Dt,_sbrk:Gt,_sizeOfCoordIJ:function(){return 8},_sizeOfGeoBoundary:function(){return 168},_sizeOfGeoCoord:function(){return 16},_sizeOfGeoPolygon:function(){return 16},_sizeOfGeofence:function(){return 8},_sizeOfH3Index:function(){return 8},_sizeOfLinkedGeoPolygon:function(){return 12},_uncompact:function(e,t,A,n,i){e|=0,A|=0,n|=0,i|=0;var o=0,a=0,s=0,g=0,c=0,u=0;if((0|(t|=0))<=0)return 0|(i=0);if((0|i)>=16){for(o=0;;){if(!(0==(0|r[(u=e+(o<<3)|0)>>2])&0==(0|r[u+4>>2]))){o=14;break}if((0|(o=o+1|0))>=(0|t)){a=0,o=16;break}}if(14==(0|o))return 0|((0|n)>0?-2:-1);if(16==(0|o))return 0|a}o=0,u=0;e:for(;;){a=0|r[(s=c=e+(u<<3)|0)>>2],s=0|r[s+4>>2];do{if(!(0==(0|a)&0==(0|s))){if((0|o)>=(0|n)){a=-1,o=16;break e}if(g=0|mt(0|a,0|s,52),v(),(0|(g&=15))>(0|i)){a=-2,o=16;break e}if((0|g)==(0|i)){r[(c=A+(o<<3)|0)>>2]=a,r[c+4>>2]=s,o=o+1|0;break}if((0|(a=(0|tt(7,i-g|0))+o|0))>(0|n)){a=-1,o=16;break e}xe(0|r[c>>2],0|r[c+4>>2],i,A+(o<<3)|0),o=a}}while(0);if((0|(u=u+1|0))>=(0|t)){a=0,o=16;break}}return 16==(0|o)?0|a:0},establishStackSpace:function(e,t){D=e|=0},stackAlloc:function(e){var t;return t=D,D=(D=D+(e|=0)|0)+15&-16,0|t},stackRestore:function(e){D=e|=0},stackSave:function(){return 0|D}}}({Math:Math,Int8Array:Int8Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Float32Array:Float32Array,Float64Array:Float64Array},{a:se,b:function(e){g=e},c:c,d:function(e,t,A,n){se("Assertion failed: "+h(e)+", at: "+[t?h(t):"unknown filename",A,n?h(n):"unknown function"])},e:function(e){return A.___errno_location&&(E[A.___errno_location()>>2]=e),e},f:P,g:function(e,t,A){B.set(B.subarray(t,t+A),e)},h:function(e){var t=P();if(e>2130706432)return!1;for(var A=Math.max(t,16777216);A>0]=t;break;case"i16":p[e>>1]=t;break;case"i32":E[e>>2]=t;break;case"i64":L=[t>>>0,(O=t,+G(O)>=1?O>0?(0|N(+x(O/4294967296),4294967295))>>>0:~~+k((O-+(~~O>>>0))/4294967296)>>>0:0)],E[e>>2]=L[0],E[e+4>>2]=L[1];break;case"float":Q[e>>2]=t;break;case"double":y[e>>3]=t;break;default:se("invalid type for setValue: "+A)}},A.getValue=function(e,t,A){switch("*"===(t=t||"i8").charAt(t.length-1)&&(t="i32"),t){case"i1":case"i8":return d[e>>0];case"i16":return p[e>>1];case"i32":case"i64":return E[e>>2];case"float":return Q[e>>2];case"double":return y[e>>3];default:se("invalid type for getValue: "+t)}return null},A.getTempRet0=c,T){H(T)||(X=T,T=A.locateFile?A.locateFile(X,o):o+X),U++,A.monitorRunDependencies&&A.monitorRunDependencies(U);var ne=function(e){e.byteLength&&(e=new Uint8Array(e)),B.set(e,8),A.memoryInitializerRequest&&delete A.memoryInitializerRequest.response,function(e){if(U--,A.monitorRunDependencies&&A.monitorRunDependencies(U),0==U&&(null!==_&&(clearInterval(_),_=null),M)){var t=M;M=null,t()}}()},re=function(){r(T,ne,(function(){throw"could not load memory initializer "+T}))},ie=W(T);if(ie)ne(ie.buffer);else if(A.memoryInitializerRequest){var oe=function(){var e=A.memoryInitializerRequest,t=e.response;if(200!==e.status&&0!==e.status){var n=W(A.memoryInitializerRequestURL);if(!n)return console.warn("a problem seems to have happened with Module.memoryInitializerRequest, status: "+e.status+", retrying "+T),void re();t=n.buffer}ne(t)};A.memoryInitializerRequest.response?setTimeout(oe,0):A.memoryInitializerRequest.addEventListener("load",oe)}else re()}function ae(e){function t(){q||(q=!0,u||(w(F),w(R),A.onRuntimeInitialized&&A.onRuntimeInitialized(),function(){if(A.postRun)for("function"==typeof A.postRun&&(A.postRun=[A.postRun]);A.postRun.length;)e=A.postRun.shift(),D.unshift(e);var e;w(D)}()))}e=e||i,U>0||(!function(){if(A.preRun)for("function"==typeof A.preRun&&(A.preRun=[A.preRun]);A.preRun.length;)e=A.preRun.shift(),S.unshift(e);var e;w(S)}(),U>0||(A.setStatus?(A.setStatus("Running..."),setTimeout((function(){setTimeout((function(){A.setStatus("")}),1),t()}),1)):t()))}function se(e){throw A.onAbort&&A.onAbort(e),a(e+=""),s(e),u=!0,"abort("+e+"). Build with -s ASSERTIONS=1 for more info."}if(M=function e(){q||ae(),q||(M=e)},A.run=ae,A.abort=se,A.preInit)for("function"==typeof A.preInit&&(A.preInit=[A.preInit]);A.preInit.length>0;)A.preInit.pop()();return ae(),e}("object"===typeof n?n:{}),r="number",i={};[["sizeOfH3Index",r],["sizeOfGeoCoord",r],["sizeOfGeoBoundary",r],["sizeOfGeoPolygon",r],["sizeOfGeofence",r],["sizeOfLinkedGeoPolygon",r],["sizeOfCoordIJ",r],["h3IsValid","number",["number","number"]],["geoToH3","number",[r,r,"number"]],["h3ToGeo",null,["number","number",r]],["h3ToGeoBoundary",null,["number","number",r]],["maxKringSize",r,[r]],["kRing",null,["number","number",r,r]],["kRingDistances",null,["number","number",r,r,r]],["hexRing",null,["number","number",r,r]],["maxPolyfillSize",r,[r,"number"]],["polyfill",null,[r,"number",r]],["h3SetToLinkedGeo",null,[r,r,r]],["destroyLinkedPolygon",null,[r]],["compact",r,[r,r,r]],["uncompact",r,[r,r,r,r,"number"]],["maxUncompactSize",r,[r,r,"number"]],["h3IsPentagon","number",["number","number"]],["h3IsResClassIII","number",["number","number"]],["h3GetBaseCell",r,["number","number"]],["maxFaceCount",r,["number","number"]],["h3GetFaces",null,["number","number",r]],["h3ToParent","number",["number","number","number"]],["h3ToChildren",null,["number","number","number",r]],["h3ToCenterChild","number",["number","number","number"]],["maxH3ToChildrenSize",r,["number","number","number"]],["h3IndexesAreNeighbors","number",["number","number","number","number"]],["getH3UnidirectionalEdge","number",["number","number","number","number"]],["getOriginH3IndexFromUnidirectionalEdge","number",["number","number"]],["getDestinationH3IndexFromUnidirectionalEdge","number",["number","number"]],["h3UnidirectionalEdgeIsValid","number",["number","number"]],["getH3IndexesFromUnidirectionalEdge",null,["number","number",r]],["getH3UnidirectionalEdgesFromHexagon",null,["number","number",r]],["getH3UnidirectionalEdgeBoundary",null,["number","number",r]],["h3Distance",r,["number","number","number","number"]],["h3Line",r,["number","number","number","number",r]],["h3LineSize",r,["number","number","number","number"]],["experimentalH3ToLocalIj",r,["number","number","number","number",r]],["experimentalLocalIjToH3",r,["number","number",r,r]],["hexAreaM2",r,["number"]],["hexAreaKm2",r,["number"]],["edgeLengthM",r,["number"]],["edgeLengthKm",r,["number"]],["pointDistM",r,[r,r]],["pointDistKm",r,[r,r]],["pointDistRads",r,[r,r]],["cellAreaM2",r,["number","number"]],["cellAreaKm2",r,["number","number"]],["cellAreaRads2",r,["number","number"]],["exactEdgeLengthM",r,["number","number"]],["exactEdgeLengthKm",r,["number","number"]],["exactEdgeLengthRads",r,["number","number"]],["numHexagons",r,["number"]],["getRes0Indexes",null,[r]],["res0IndexCount",r],["getPentagonIndexes",null,[r,r]],["pentagonIndexCount",r]].forEach((function(e){i[e[0]]=n.cwrap.apply(n,e)}));var o=i.sizeOfH3Index(),a=i.sizeOfGeoCoord(),s=i.sizeOfGeoBoundary(),g=i.sizeOfGeoPolygon(),c=i.sizeOfGeofence(),u=i.sizeOfLinkedGeoPolygon(),l=i.sizeOfCoordIJ(),I={m:"m",m2:"m2",km:"km",km2:"km2",rads:"rads",rads2:"rads2"};function C(e){if("number"!==typeof e||e<0||e>15||Math.floor(e)!==e)throw new Error("Invalid resolution: "+e)}var h=/[^0-9a-fA-F]/;function f(e){if(Array.isArray(e)&&2===e.length&&Number.isInteger(e[0])&&Number.isInteger(e[1]))return e;if("string"!==typeof e||h.test(e))return[0,0];var t=parseInt(e.substring(0,e.length-8),16);return[parseInt(e.substring(e.length-8),16),t]}function d(e){if(e>=0)return e.toString(16);var t=p(8,(e&=2147483647).toString(16));return t=(parseInt(t[0],16)+8).toString(16)+t.substring(1)}function B(e,t){return d(t)+p(8,d(e))}function p(e,t){for(var A=e-t.length,n="",r=0;r=0&&A.push(i)}return A}(a,o);return n._free(a),s}function M(e){return"string"!==typeof e?-1:parseInt(e.charAt(1),16)}function O(e,t,A){var r=n._malloc(a);n.HEAPF64.set([e,t].map(de),r/8);var o=y(i.geoToH3(r,A));return n._free(r),o}function L(e){var t=n._malloc(a),A=f(e),r=A[0],o=A[1];i.h3ToGeo(r,o,t);var s=R(t);return n._free(t),s}function T(e,t){var A=n._malloc(s),r=f(e),o=r[0],a=r[1];i.h3ToGeoBoundary(o,a,A);var g=G(A,t,t);return n._free(A),g}function Z(e,t){var A=f(e),n=A[0],r=A[1];return y(i.h3ToParent(n,r,t))}function H(e,t){if(!k(e))return[];var A=f(e),r=A[0],a=A[1],s=i.maxH3ToChildrenSize(r,a,t),g=n._calloc(s,o);i.h3ToChildren(r,a,t,g);var c=b(g,s);return n._free(g),c}function Y(e,t){var A=f(e),n=A[0],r=A[1];return y(i.h3ToCenterChild(n,r,t))}function J(e,t){var A=f(e),r=A[0],a=A[1],s=i.maxKringSize(t),g=n._calloc(s,o);i.kRing(r,a,t,g);var c=b(g,s);return n._free(g),c}function j(e,t){var A=f(e),r=A[0],a=A[1],s=i.maxKringSize(t),g=n._calloc(s,o),c=n._calloc(s,4);i.kRingDistances(r,a,t,g,c);for(var u=[],l=0;l0){A=n._calloc(r,c);for(var s=0;s1&&void 0!==arguments[1]?arguments[1]:{},A=t.format,n=t.linearFiltering,r=!0;return A&&(r=(r=r&&Object(I.d)(e,A))&&(!n||Object(I.e)(e,A))),r}}]),Object(o.a)(A,[{key:"toString",value:function(){return"Texture(".concat(this.id,",").concat(this.width,"x").concat(this.height,")")}},{key:"initialize",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},A=t.data;if(A instanceof Promise)return A.then((function(A){return e.initialize(Object.assign({},t,{pixels:A,data:A}))})),this;var n="undefined"!==typeof HTMLVideoElement&&A instanceof HTMLVideoElement;if(n&&A.readyState=HTMLVideoElement.HAVE_CURRENT_DATA?A.currentTime:-1}),this}},{key:"update",value:function(){if(this._video){var e=this._video,t=e.video,A=e.parameters;if(e.lastTime===t.currentTime||t.readyState0&&void 0!==arguments[0]?arguments[0]:{};return this._isNPOT()?(g.k.warn("texture: ".concat(this," is Non-Power-Of-Two, disabling mipmaping"))(),this):(this.mipmaps=!0,this.gl.bindTexture(this.target,this.handle),Object(g.o)(this.gl,t,(function(){e.gl.generateMipmap(e.target)})),this.gl.bindTexture(this.target,null),this)}},{key:"setImageData",value:function(e){this._trackDeallocatedMemory("Texture");var t=e.target,A=void 0===t?this.target:t,i=e.pixels,o=void 0===i?null:i,a=e.level,s=void 0===a?0:a,c=e.format,u=void 0===c?this.format:c,l=e.border,h=void 0===l?this.border:l,f=e.offset,d=void 0===f?0:f,B=e.parameters,p=void 0===B?{}:B,E=e.data,Q=void 0===E?null:E,y=e.type,v=void 0===y?this.type:y,m=e.width,b=void 0===m?this.width:m,w=e.height,S=void 0===w?this.height:w,F=e.dataFormat,R=void 0===F?this.dataFormat:F,D=e.compressed,G=void 0!==D&&D;Q||(Q=o);var k=this._deduceParameters({format:u,type:v,dataFormat:R,compressed:G,data:Q,width:b,height:S});v=k.type,R=k.dataFormat,G=k.compressed,b=k.width,S=k.height;var x=this.gl;x.bindTexture(this.target,this.handle);var N,U,_=this._getDataType({data:Q,compressed:G});if(Q=_.data,N=_.dataType,Object(g.o)(this.gl,p,(function(){switch(N){case"null":x.texImage2D(A,s,u,b,S,h,R,v,Q);break;case"typed-array":x.texImage2D(A,s,u,b,S,h,R,v,Q,d);break;case"buffer":(U=Object(g.a)(x)).bindBuffer(35052,Q.handle||Q),U.texImage2D(A,s,u,b,S,h,R,v,d),U.bindBuffer(35052,null);break;case"browser-object":Object(g.j)(x)?x.texImage2D(A,s,u,b,S,h,R,v,Q):x.texImage2D(A,s,u,R,v,Q);break;case"compressed":var e,t=Object(r.a)(Q.entries());try{for(t.s();!(e=t.n()).done;){var i=Object(n.a)(e.value,2),o=i[0],a=i[1];x.compressedTexImage2D(A,o,a.format,a.width,a.height,h,a.data)}}catch(c){t.e(c)}finally{t.f()}break;default:Object(C.a)(!1,"Unknown image data type")}})),Q&&Q.byteLength)this._trackAllocatedMemory(Q.byteLength,"Texture");else{var M=I.a[this.dataFormat]||4,O=I.c[this.type]||1;this._trackAllocatedMemory(this.width*this.height*M*O,"Texture")}return this.loaded=!0,this}},{key:"setSubImageData",value:function(e){var t=this,A=e.target,n=void 0===A?this.target:A,r=e.pixels,i=void 0===r?null:r,o=e.data,a=void 0===o?null:o,s=e.x,c=void 0===s?0:s,u=e.y,I=void 0===u?0:u,h=e.width,f=void 0===h?this.width:h,B=e.height,p=void 0===B?this.height:B,E=e.level,Q=void 0===E?0:E,y=e.format,v=void 0===y?this.format:y,m=e.type,b=void 0===m?this.type:m,w=e.dataFormat,S=void 0===w?this.dataFormat:w,F=e.compressed,R=void 0!==F&&F,D=e.offset,G=void 0===D?0:D,k=e.border,x=(void 0===k&&this.border,e.parameters),N=void 0===x?{}:x,U=this._deduceParameters({format:v,type:b,dataFormat:S,compressed:R,data:a,width:f,height:p});if(b=U.type,S=U.dataFormat,R=U.compressed,f=U.width,p=U.height,Object(C.a)(0===this.depth,"texSubImage not supported for 3D textures"),a||(a=i),a&&a.data){var _=a;a=_.data,f=_.shape[0],p=_.shape[1]}a instanceof l.a&&(a=a.handle),this.gl.bindTexture(this.target,this.handle),Object(g.o)(this.gl,N,(function(){if(R)t.gl.compressedTexSubImage2D(n,Q,c,I,f,p,v,a);else if(null===a)t.gl.texSubImage2D(n,Q,c,I,f,p,S,b,null);else if(ArrayBuffer.isView(a))t.gl.texSubImage2D(n,Q,c,I,f,p,S,b,a,G);else if(a instanceof d){var e=Object(g.a)(t.gl);e.bindBuffer(35052,a),e.texSubImage2D(n,Q,c,I,f,p,S,b,G),e.bindBuffer(35052,null)}else if(Object(g.j)(t.gl)){Object(g.a)(t.gl).texSubImage2D(n,Q,c,I,f,p,S,b,a)}else t.gl.texSubImage2D(n,Q,c,I,S,b,a)})),this.gl.bindTexture(this.target,null)}},{key:"copyFramebuffer",value:function(){arguments.length>0&&void 0!==arguments[0]&&arguments[0];return g.k.error("Texture.copyFramebuffer({...}) is no logner supported, use copyToTexture(source, target, opts})")(),null}},{key:"getActiveUnit",value:function(){return this.gl.getParameter(34016)-33984}},{key:"bind",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.textureUnit,t=this.gl;return void 0!==e&&(this.textureUnit=e,t.activeTexture(33984+e)),t.bindTexture(this.target,this.handle),e}},{key:"unbind",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.textureUnit,t=this.gl;return void 0!==e&&(this.textureUnit=e,t.activeTexture(33984+e)),t.bindTexture(this.target,null),e}},{key:"_getDataType",value:function(e){var t=e.data,A=e.compressed;return void 0!==A&&A?{data:t,dataType:"compressed"}:null===t?{data:t,dataType:"null"}:ArrayBuffer.isView(t)?{data:t,dataType:"typed-array"}:t instanceof l.a?{data:t.handle,dataType:"buffer"}:t instanceof d?{data:t,dataType:"buffer"}:{data:t,dataType:"browser-object"}}},{key:"_deduceParameters",value:function(e){var t=e.format,A=e.data,n=e.width,r=e.height,i=e.dataFormat,o=e.type,a=e.compressed,s=I.b[t];i=i||s&&s.dataFormat,o=o||s&&s.types[0],a=a||s&&s.compressed;var g=this._deduceImageSize(A,n,r);return{dataFormat:i,type:o,compressed:a,width:n=g.width,height:r=g.height,format:t,data:A}}},{key:"_deduceImageSize",value:function(e,t,A){var n;return n="undefined"!==typeof ImageData&&e instanceof ImageData?{width:e.width,height:e.height}:"undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement?{width:e.naturalWidth,height:e.naturalHeight}:"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap?{width:e.width,height:e.height}:"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement?{width:e.videoWidth,height:e.videoHeight}:e?{width:t,height:A}:{width:t>=0?t:1,height:A>=0?A:1},Object(C.a)(n,"Could not deduced texture size"),Object(C.a)(void 0===t||n.width===t,"Deduced texture width does not match supplied width"),Object(C.a)(void 0===A||n.height===A,"Deduced texture height does not match supplied height"),n}},{key:"_createHandle",value:function(){return this.gl.createTexture()}},{key:"_deleteHandle",value:function(){this.gl.deleteTexture(this.handle),this._trackDeallocatedMemory("Texture")}},{key:"_getParameter",value:function(e){switch(e){case 4096:return this.width;case 4097:return this.height;default:this.gl.bindTexture(this.target,this.handle);var t=this.gl.getTexParameter(this.target,e);return this.gl.bindTexture(this.target,null),t}}},{key:"_setParameter",value:function(e,t){switch(this.gl.bindTexture(this.target,this.handle),t=this._getNPOTParam(e,t),e){case 33082:case 33083:this.gl.texParameterf(this.handle,e,t);break;case 4096:case 4097:Object(C.a)(!1);break;default:this.gl.texParameteri(this.target,e,t)}return this.gl.bindTexture(this.target,null),this}},{key:"_isNPOT",value:function(){return!Object(g.j)(this.gl)&&(!(!this.width||!this.height)&&(!Object(h.b)(this.width)||!Object(h.b)(this.height)))}},{key:"_updateForNPOT",value:function(e){void 0===e[this.gl.TEXTURE_MIN_FILTER]&&(e[this.gl.TEXTURE_MIN_FILTER]=this.gl.LINEAR),void 0===e[this.gl.TEXTURE_WRAP_S]&&(e[this.gl.TEXTURE_WRAP_S]=this.gl.CLAMP_TO_EDGE),void 0===e[this.gl.TEXTURE_WRAP_T]&&(e[this.gl.TEXTURE_WRAP_T]=this.gl.CLAMP_TO_EDGE)}},{key:"_getNPOTParam",value:function(e,t){if(this._isNPOT())switch(e){case 10241:-1===f.indexOf(t)&&(t=9729);break;case 10242:case 10243:33071!==t&&(t=33071)}return t}}]),A}(u.a)},function(e,t,A){"use strict";function n(e,t,A){var n=t[0],r=t[1],i=A[3]*n+A[7]*r||1;return e[0]=(A[0]*n+A[4]*r)/i,e[1]=(A[1]*n+A[5]*r)/i,e}function r(e,t,A){var n=t[0],r=t[1],i=t[2],o=A[3]*n+A[7]*r+A[11]*i||1;return e[0]=(A[0]*n+A[4]*r+A[8]*i)/o,e[1]=(A[1]*n+A[5]*r+A[9]*i)/o,e[2]=(A[2]*n+A[6]*r+A[10]*i)/o,e}function i(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[2]*r,e[1]=A[1]*n+A[3]*r,e[2]=t[2],e}function o(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[2]*r,e[1]=A[1]*n+A[3]*r,e[2]=t[2],e[3]=t[3],e}function a(e,t,A){var n=t[0],r=t[1],i=t[2];return e[0]=A[0]*n+A[3]*r+A[6]*i,e[1]=A[1]*n+A[4]*r+A[7]*i,e[2]=A[2]*n+A[5]*r+A[8]*i,e[3]=t[3],e}A.d(t,"a",(function(){return n})),A.d(t,"c",(function(){return r})),A.d(t,"b",(function(){return i})),A.d(t,"d",(function(){return o})),A.d(t,"e",(function(){return a}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return r})),A.d(t,"i",(function(){return i})),A.d(t,"d",(function(){return o})),A.d(t,"b",(function(){return a})),A.d(t,"e",(function(){return s})),A.d(t,"h",(function(){return g})),A.d(t,"f",(function(){return c})),A.d(t,"g",(function(){return u})),A.d(t,"c",(function(){return l}));var n=A(30);function r(){var e=new n.a(9);return n.a!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[5]=0,e[6]=0,e[7]=0),e[0]=1,e[4]=1,e[8]=1,e}function i(e,t){if(e===t){var A=t[1],n=t[2],r=t[5];e[1]=t[3],e[2]=t[6],e[3]=A,e[5]=t[7],e[6]=n,e[7]=r}else e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8];return e}function o(e,t){var A=t[0],n=t[1],r=t[2],i=t[3],o=t[4],a=t[5],s=t[6],g=t[7],c=t[8],u=c*o-a*g,l=-c*i+a*s,I=g*i-o*s,C=A*u+n*l+r*I;return C?(C=1/C,e[0]=u*C,e[1]=(-c*n+r*g)*C,e[2]=(a*n-r*o)*C,e[3]=l*C,e[4]=(c*A-r*s)*C,e[5]=(-a*A+r*i)*C,e[6]=I*C,e[7]=(-g*A+n*s)*C,e[8]=(o*A-n*i)*C,e):null}function a(e){var t=e[0],A=e[1],n=e[2],r=e[3],i=e[4],o=e[5],a=e[6],s=e[7],g=e[8];return t*(g*i-o*s)+A*(-g*r+o*a)+n*(s*r-i*a)}function s(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],s=t[5],g=t[6],c=t[7],u=t[8],l=A[0],I=A[1],C=A[2],h=A[3],f=A[4],d=A[5],B=A[6],p=A[7],E=A[8];return e[0]=l*n+I*o+C*g,e[1]=l*r+I*a+C*c,e[2]=l*i+I*s+C*u,e[3]=h*n+f*o+d*g,e[4]=h*r+f*a+d*c,e[5]=h*i+f*s+d*u,e[6]=B*n+p*o+E*g,e[7]=B*r+p*a+E*c,e[8]=B*i+p*s+E*u,e}function g(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],s=t[5],g=t[6],c=t[7],u=t[8],l=A[0],I=A[1];return e[0]=n,e[1]=r,e[2]=i,e[3]=o,e[4]=a,e[5]=s,e[6]=l*n+I*o+g,e[7]=l*r+I*a+c,e[8]=l*i+I*s+u,e}function c(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],s=t[5],g=t[6],c=t[7],u=t[8],l=Math.sin(A),I=Math.cos(A);return e[0]=I*n+l*o,e[1]=I*r+l*a,e[2]=I*i+l*s,e[3]=I*o-l*n,e[4]=I*a-l*r,e[5]=I*s-l*i,e[6]=g,e[7]=c,e[8]=u,e}function u(e,t,A){var n=A[0],r=A[1];return e[0]=n*t[0],e[1]=n*t[1],e[2]=n*t[2],e[3]=r*t[3],e[4]=r*t[4],e[5]=r*t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e}function l(e,t){var A=t[0],n=t[1],r=t[2],i=t[3],o=A+A,a=n+n,s=r+r,g=A*o,c=n*o,u=n*a,l=r*o,I=r*a,C=r*s,h=i*o,f=i*a,d=i*s;return e[0]=1-u-C,e[3]=c-d,e[6]=l+f,e[1]=c+d,e[4]=1-g-C,e[7]=I-h,e[2]=l-f,e[5]=I+h,e[8]=1-g-u,e}},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t){e.exports=function(){throw new Error("define cannot be used indirect")}},function(e,t,A){var n=A(251);function r(){if("function"!==typeof WeakMap)return null;var e=new WeakMap;return r=function(){return e},e}e.exports=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==n(e)&&"function"!==typeof e)return{default:e};var t=r();if(t&&t.has(e))return t.get(e);var A={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if(Object.prototype.hasOwnProperty.call(e,o)){var a=i?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(A,o,a):A[o]=e[o]}return A.default=e,t&&t.set(e,A),A}},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n.createSvgIcon}});var n=A(654)},function(e,t,A){"use strict";var n=Math.sqrt(50),r=Math.sqrt(10),i=Math.sqrt(2);var o=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function a(e){if(!(t=o.exec(e)))throw new Error("invalid format: "+e);var t;return new s({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}function s(e){this.fill=void 0===e.fill?" ":e.fill+"",this.align=void 0===e.align?">":e.align+"",this.sign=void 0===e.sign?"-":e.sign+"",this.symbol=void 0===e.symbol?"":e.symbol+"",this.zero=!!e.zero,this.width=void 0===e.width?void 0:+e.width,this.comma=!!e.comma,this.precision=void 0===e.precision?void 0:+e.precision,this.trim=!!e.trim,this.type=void 0===e.type?"":e.type+""}a.prototype=s.prototype,s.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};function g(e,t){if((A=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"))<0)return null;var A,n=e.slice(0,A);return[n.length>1?n[0]+n.slice(2):n,+e.slice(A+1)]}var c,u,l,I,C=function(e){return(e=g(Math.abs(e)))?e[1]:NaN},h=function(e,t){var A=g(e,t);if(!A)return e+"";var n=A[0],r=A[1];return r<0?"0."+new Array(-r).join("0")+n:n.length>r+1?n.slice(0,r+1)+"."+n.slice(r+1):n+new Array(r-n.length+2).join("0")},f={"%":function(e,t){return(100*e).toFixed(t)},b:function(e){return Math.round(e).toString(2)},c:function(e){return e+""},d:function(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},g:function(e,t){return e.toPrecision(t)},o:function(e){return Math.round(e).toString(8)},p:function(e,t){return h(100*e,t)},r:h,s:function(e,t){var A=g(e,t);if(!A)return e+"";var n=A[0],r=A[1],i=r-(c=3*Math.max(-8,Math.min(8,Math.floor(r/3))))+1,o=n.length;return i===o?n:i>o?n+new Array(i-o+1).join("0"):i>0?n.slice(0,i)+"."+n.slice(i):"0."+new Array(1-i).join("0")+g(e,Math.max(0,t+i-1))[0]},X:function(e){return Math.round(e).toString(16).toUpperCase()},x:function(e){return Math.round(e).toString(16)}},d=function(e){return e},B=Array.prototype.map,p=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"],E=function(e){var t,A,n=void 0===e.grouping||void 0===e.thousands?d:(t=B.call(e.grouping,Number),A=e.thousands+"",function(e,n){for(var r=e.length,i=[],o=0,a=t[0],s=0;r>0&&a>0&&(s+a+1>n&&(a=Math.max(1,n-s)),i.push(e.substring(r-=a,r+a)),!((s+=a+1)>n));)a=t[o=(o+1)%t.length];return i.reverse().join(A)}),r=void 0===e.currency?"":e.currency[0]+"",i=void 0===e.currency?"":e.currency[1]+"",o=void 0===e.decimal?".":e.decimal+"",s=void 0===e.numerals?d:function(e){return function(t){return t.replace(/[0-9]/g,(function(t){return e[+t]}))}}(B.call(e.numerals,String)),g=void 0===e.percent?"%":e.percent+"",u=void 0===e.minus?"\u2212":e.minus+"",l=void 0===e.nan?"NaN":e.nan+"";function I(e){var t=(e=a(e)).fill,A=e.align,I=e.sign,C=e.symbol,h=e.zero,d=e.width,B=e.comma,E=e.precision,Q=e.trim,y=e.type;"n"===y?(B=!0,y="g"):f[y]||(void 0===E&&(E=12),Q=!0,y="g"),(h||"0"===t&&"="===A)&&(h=!0,t="0",A="=");var v="$"===C?r:"#"===C&&/[boxX]/.test(y)?"0"+y.toLowerCase():"",m="$"===C?i:/[%p]/.test(y)?g:"",b=f[y],w=/[defgprs%]/.test(y);function S(e){var r,i,a,g=v,C=m;if("c"===y)C=b(e)+C,e="";else{var f=(e=+e)<0||1/e<0;if(e=isNaN(e)?l:b(Math.abs(e),E),Q&&(e=function(e){e:for(var t,A=e.length,n=1,r=-1;n0&&(r=0)}return r>0?e.slice(0,r)+e.slice(t+1):e}(e)),f&&0===+e&&"+"!==I&&(f=!1),g=(f?"("===I?I:u:"-"===I||"("===I?"":I)+g,C=("s"===y?p[8+c/3]:"")+C+(f&&"("===I?")":""),w)for(r=-1,i=e.length;++r(a=e.charCodeAt(r))||a>57){C=(46===a?o+e.slice(r+1):e.slice(r))+C,e=e.slice(0,r);break}}B&&!h&&(e=n(e,1/0));var S=g.length+e.length+C.length,F=S>1)+g+e+C+F.slice(S);break;default:e=F+g+e+C}return s(e)}return E=void 0===E?6:/[gprs]/.test(y)?Math.max(1,Math.min(21,E)):Math.max(0,Math.min(20,E)),S.toString=function(){return e+""},S}return{format:I,formatPrefix:function(e,t){var A=I(((e=a(e)).type="f",e)),n=3*Math.max(-8,Math.min(8,Math.floor(C(t)/3))),r=Math.pow(10,-n),i=p[8+n/3];return function(e){return A(r*e)+i}}}};u=E({thousands:",",grouping:[3],currency:["$",""]}),l=u.format,I=u.formatPrefix;var Q=A(46),y=A(5),v=A(1270),m=A(1271),b=A(1272),w=A(1273),S=A(1274),F=A(1275);function R(e){if(0<=e.y&&e.y<100){var t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function D(e){if(0<=e.y&&e.y<100){var t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function G(e,t,A){return{y:e,m:t,d:A,H:0,M:0,S:0,L:0}}function k(e){var t=e.dateTime,A=e.date,n=e.time,r=e.periods,i=e.days,o=e.shortDays,a=e.months,s=e.shortMonths,g=P(r),c=V(r),u=P(i),l=V(i),I=P(o),C=V(o),h=P(a),f=V(a),d=P(s),B=V(s),p={a:function(e){return o[e.getDay()]},A:function(e){return i[e.getDay()]},b:function(e){return s[e.getMonth()]},B:function(e){return a[e.getMonth()]},c:null,d:Ce,e:Ce,f:pe,g:De,G:ke,H:he,I:fe,j:de,L:Be,m:Ee,M:Qe,p:function(e){return r[+(e.getHours()>=12)]},q:function(e){return 1+~~(e.getMonth()/3)},Q:tt,s:At,S:ye,u:ve,U:me,V:we,w:Se,W:Fe,x:null,X:null,y:Re,Y:Ge,Z:xe,"%":et},E={a:function(e){return o[e.getUTCDay()]},A:function(e){return i[e.getUTCDay()]},b:function(e){return s[e.getUTCMonth()]},B:function(e){return a[e.getUTCMonth()]},c:null,d:Ne,e:Ne,f:Le,g:Xe,G:ze,H:Ue,I:_e,j:Me,L:Oe,m:Te,M:Ze,p:function(e){return r[+(e.getUTCHours()>=12)]},q:function(e){return 1+~~(e.getUTCMonth()/3)},Q:tt,s:At,S:He,u:Ye,U:Je,V:Pe,w:Ve,W:Ke,x:null,X:null,y:We,Y:qe,Z:$e,"%":et},Q={a:function(e,t,A){var n=I.exec(t.slice(A));return n?(e.w=C.get(n[0].toLowerCase()),A+n[0].length):-1},A:function(e,t,A){var n=u.exec(t.slice(A));return n?(e.w=l.get(n[0].toLowerCase()),A+n[0].length):-1},b:function(e,t,A){var n=d.exec(t.slice(A));return n?(e.m=B.get(n[0].toLowerCase()),A+n[0].length):-1},B:function(e,t,A){var n=h.exec(t.slice(A));return n?(e.m=f.get(n[0].toLowerCase()),A+n[0].length):-1},c:function(e,A,n){return F(e,t,A,n)},d:re,e:re,f:ce,g:ee,G:$,H:oe,I:oe,j:ie,L:ge,m:ne,M:ae,p:function(e,t,A){var n=g.exec(t.slice(A));return n?(e.p=c.get(n[0].toLowerCase()),A+n[0].length):-1},q:Ae,Q:le,s:Ie,S:se,u:W,U:X,V:q,w:K,W:z,x:function(e,t,n){return F(e,A,t,n)},X:function(e,t,A){return F(e,n,t,A)},y:ee,Y:$,Z:te,"%":ue};function y(e,t){return function(A){var n,r,i,o=[],a=-1,s=0,g=e.length;for(A instanceof Date||(A=new Date(+A));++a53)return null;"w"in i||(i.w=1),"Z"in i?(r=(n=D(G(i.y,0,1))).getUTCDay(),n=r>4||0===r?v.a.ceil(n):Object(v.a)(n),n=m.a.offset(n,7*(i.V-1)),i.y=n.getUTCFullYear(),i.m=n.getUTCMonth(),i.d=n.getUTCDate()+(i.w+6)%7):(r=(n=R(G(i.y,0,1))).getDay(),n=r>4||0===r?b.a.ceil(n):Object(b.a)(n),n=w.a.offset(n,7*(i.V-1)),i.y=n.getFullYear(),i.m=n.getMonth(),i.d=n.getDate()+(i.w+6)%7)}else("W"in i||"U"in i)&&("w"in i||(i.w="u"in i?i.u%7:"W"in i?1:0),r="Z"in i?D(G(i.y,0,1)).getUTCDay():R(G(i.y,0,1)).getDay(),i.m=0,i.d="W"in i?(i.w+6)%7+7*i.W-(r+5)%7:i.w+7*i.U-(r+6)%7);return"Z"in i?(i.H+=i.Z/100|0,i.M+=i.Z%100,D(i)):R(i)}}function F(e,t,A,n){for(var r,i,o=0,a=t.length,s=A.length;o=s)return-1;if(37===(r=t.charCodeAt(o++))){if(r=t.charAt(o++),!(i=Q[r in T?t.charAt(o++):r])||(n=i(e,A,n))<0)return-1}else if(r!=A.charCodeAt(n++))return-1}return n}return p.x=y(A,p),p.X=y(n,p),p.c=y(t,p),E.x=y(A,E),E.X=y(n,E),E.c=y(t,E),{format:function(e){var t=y(e+="",p);return t.toString=function(){return e},t},parse:function(e){var t=S(e+="",!1);return t.toString=function(){return e},t},utcFormat:function(e){var t=y(e+="",E);return t.toString=function(){return e},t},utcParse:function(e){var t=S(e+="",!0);return t.toString=function(){return e},t}}}var x,N,U,_,M,O,L,T={"-":"",_:" ",0:"0"},Z=/^\s*\d+/,H=/^%/,Y=/[\\^$*+?|[\]().{}]/g;function J(e,t,A){var n=e<0?"-":"",r=(n?-e:e)+"",i=r.length;return n+(i68?1900:2e3),A+n[0].length):-1}function te(e,t,A){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(A,A+6));return n?(e.Z=n[1]?0:-(n[2]+(n[3]||"00")),A+n[0].length):-1}function Ae(e,t,A){var n=Z.exec(t.slice(A,A+1));return n?(e.q=3*n[0]-3,A+n[0].length):-1}function ne(e,t,A){var n=Z.exec(t.slice(A,A+2));return n?(e.m=n[0]-1,A+n[0].length):-1}function re(e,t,A){var n=Z.exec(t.slice(A,A+2));return n?(e.d=+n[0],A+n[0].length):-1}function ie(e,t,A){var n=Z.exec(t.slice(A,A+3));return n?(e.m=0,e.d=+n[0],A+n[0].length):-1}function oe(e,t,A){var n=Z.exec(t.slice(A,A+2));return n?(e.H=+n[0],A+n[0].length):-1}function ae(e,t,A){var n=Z.exec(t.slice(A,A+2));return n?(e.M=+n[0],A+n[0].length):-1}function se(e,t,A){var n=Z.exec(t.slice(A,A+2));return n?(e.S=+n[0],A+n[0].length):-1}function ge(e,t,A){var n=Z.exec(t.slice(A,A+3));return n?(e.L=+n[0],A+n[0].length):-1}function ce(e,t,A){var n=Z.exec(t.slice(A,A+6));return n?(e.L=Math.floor(n[0]/1e3),A+n[0].length):-1}function ue(e,t,A){var n=H.exec(t.slice(A,A+1));return n?A+n[0].length:-1}function le(e,t,A){var n=Z.exec(t.slice(A));return n?(e.Q=+n[0],A+n[0].length):-1}function Ie(e,t,A){var n=Z.exec(t.slice(A));return n?(e.s=+n[0],A+n[0].length):-1}function Ce(e,t){return J(e.getDate(),t,2)}function he(e,t){return J(e.getHours(),t,2)}function fe(e,t){return J(e.getHours()%12||12,t,2)}function de(e,t){return J(1+w.a.count(Object(S.a)(e),e),t,3)}function Be(e,t){return J(e.getMilliseconds(),t,3)}function pe(e,t){return Be(e,t)+"000"}function Ee(e,t){return J(e.getMonth()+1,t,2)}function Qe(e,t){return J(e.getMinutes(),t,2)}function ye(e,t){return J(e.getSeconds(),t,2)}function ve(e){var t=e.getDay();return 0===t?7:t}function me(e,t){return J(b.b.count(Object(S.a)(e)-1,e),t,2)}function be(e){var t=e.getDay();return t>=4||0===t?Object(b.c)(e):b.c.ceil(e)}function we(e,t){return e=be(e),J(b.c.count(Object(S.a)(e),e)+(4===Object(S.a)(e).getDay()),t,2)}function Se(e){return e.getDay()}function Fe(e,t){return J(b.a.count(Object(S.a)(e)-1,e),t,2)}function Re(e,t){return J(e.getFullYear()%100,t,2)}function De(e,t){return J((e=be(e)).getFullYear()%100,t,2)}function Ge(e,t){return J(e.getFullYear()%1e4,t,4)}function ke(e,t){var A=e.getDay();return J((e=A>=4||0===A?Object(b.c)(e):b.c.ceil(e)).getFullYear()%1e4,t,4)}function xe(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+J(t/60|0,"0",2)+J(t%60,"0",2)}function Ne(e,t){return J(e.getUTCDate(),t,2)}function Ue(e,t){return J(e.getUTCHours(),t,2)}function _e(e,t){return J(e.getUTCHours()%12||12,t,2)}function Me(e,t){return J(1+m.a.count(Object(F.a)(e),e),t,3)}function Oe(e,t){return J(e.getUTCMilliseconds(),t,3)}function Le(e,t){return Oe(e,t)+"000"}function Te(e,t){return J(e.getUTCMonth()+1,t,2)}function Ze(e,t){return J(e.getUTCMinutes(),t,2)}function He(e,t){return J(e.getUTCSeconds(),t,2)}function Ye(e){var t=e.getUTCDay();return 0===t?7:t}function Je(e,t){return J(v.b.count(Object(F.a)(e)-1,e),t,2)}function je(e){var t=e.getUTCDay();return t>=4||0===t?Object(v.c)(e):v.c.ceil(e)}function Pe(e,t){return e=je(e),J(v.c.count(Object(F.a)(e),e)+(4===Object(F.a)(e).getUTCDay()),t,2)}function Ve(e){return e.getUTCDay()}function Ke(e,t){return J(v.a.count(Object(F.a)(e)-1,e),t,2)}function We(e,t){return J(e.getUTCFullYear()%100,t,2)}function Xe(e,t){return J((e=je(e)).getUTCFullYear()%100,t,2)}function qe(e,t){return J(e.getUTCFullYear()%1e4,t,4)}function ze(e,t){var A=e.getUTCDay();return J((e=A>=4||0===A?Object(v.c)(e):v.c.ceil(e)).getUTCFullYear()%1e4,t,4)}function $e(){return"+0000"}function et(){return"%"}function tt(e){return+e}function At(e){return Math.floor(+e/1e3)}function nt(e){var t={};return function(A){return t[A]||(t[A]=e(A))}}function rt(e){var t=nt(e.format),A=e.formatPrefix;return{format:t,formatPrefix:A,formatFloat:function(e){var A,n,r=a(e||",");if(null==r.precision){switch(r.precision=12,r.type){case"%":r.precision-=2;break;case"e":r.precision-=1}return A=t(r),n=t(".1f")(1)[1],function(e){var t=A(e),r=t.indexOf(n);if(r<0)return t;for(var i=function(e,t){var A,n=e.lastIndexOf("e");if(n>0)return n;for(n=e.length;--n>t;)if((A=e.charCodeAt(n))>=48&&A<=57)return n+1}(t,r),o=ir;)if("0"!==t[i]){++i;break}return t.slice(0,i)+o}}return t(r)},formatSpan:function(e,o,s,g){g=a(null==g?",f":g);var c,u=function(e,t,A){var o=Math.abs(t-e)/Math.max(0,A),a=Math.pow(10,Math.floor(Math.log(o)/Math.LN10)),s=o/a;return s>=n?a*=10:s>=r?a*=5:s>=i&&(a*=2),t1&&void 0!==arguments[1]?arguments[1]:{};Object(r.a)(this,e),this.ControllerState=t,this.controllerState=null,this.controllerStateProps=null,this.eventManager=null,this.transitionManager=new o.b(t,Object(n.a)({},A,{onViewStateChange:this._onTransition.bind(this),onStateChange:this._setInteractionState.bind(this)}));var i=this.linearTransitionProps;this._transition=i&&Object(n.a)({},g,{transitionInterpolator:new a.a({transitionProps:i})}),this._events=null,this._interactionState={isDragging:!1},this._customEvents=[],this.onViewStateChange=null,this.onStateChange=null,this.handleEvent=this.handleEvent.bind(this),this.setProps(A)}return Object(i.a)(e,[{key:"finalize",value:function(){for(var e in this._events)this._events[e]&&this.eventManager.off(e,this.handleEvent);this.transitionManager.finalize()}},{key:"handleEvent",value:function(e){var t=this.ControllerState;this.controllerState=new t(Object(n.a)({makeViewport:this.makeViewport},this.controllerStateProps,{},this._state));var A=this._eventStartBlocked;switch(e.type){case"panstart":return!A&&this._onPanStart(e);case"panmove":return this._onPan(e);case"panend":return this._onPanEnd(e);case"pinchstart":return!A&&this._onPinchStart(e);case"pinchmove":return this._onPinch(e);case"pinchend":return this._onPinchEnd(e);case"tripanstart":return!A&&this._onTriplePanStart(e);case"tripanmove":return this._onTriplePan(e);case"tripanend":return this._onTriplePanEnd(e);case"doubletap":return this._onDoubleTap(e);case"wheel":return this._onWheel(e);case"keydown":return this._onKeyDown(e);default:return!1}}},{key:"getCenter",value:function(e){var t=this.controllerStateProps,A=t.x,n=t.y,r=e.offsetCenter;return[r.x-A,r.y-n]}},{key:"isPointInBounds",value:function(e,t){var A=this.controllerStateProps,n=A.width,r=A.height;if(t&&t.handled)return!1;var i=e[0]>=0&&e[0]<=n&&e[1]>=0&&e[1]<=r;return i&&t&&t.stopPropagation(),i}},{key:"isFunctionKeyPressed",value:function(e){var t=e.srcEvent;return Boolean(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}},{key:"isDragging",value:function(){return this._interactionState.isDragging}},{key:"blockEvents",value:function(e){var t=this,A=setTimeout((function(){t._eventStartBlocked===A&&(t._eventStartBlocked=null)}),e);this._eventStartBlocked=A}},{key:"setProps",value:function(e){"onViewStateChange"in e&&(this.onViewStateChange=e.onViewStateChange),"onStateChange"in e&&(this.onStateChange=e.onStateChange),"makeViewport"in e&&(this.makeViewport=e.makeViewport),"dragMode"in e&&(this.dragMode=e.dragMode),this.controllerStateProps=e,"eventManager"in e&&this.eventManager!==e.eventManager&&(this.eventManager=e.eventManager,this._events={},this.toggleEvents(this._customEvents,!0)),"transitionInterpolator"in e||(e.transitionInterpolator=this._getTransitionProps().transitionInterpolator),this.transitionManager.processViewStateChange(e);var t=e.inertia;!0===t&&(t=300),this.inertia=t;var A=e.scrollZoom,n=void 0===A||A,r=e.dragPan,i=void 0===r||r,o=e.dragRotate,a=void 0===o||o,s=e.doubleClickZoom,g=void 0===s||s,c=e.touchZoom,d=void 0===c||c,B=e.touchRotate,p=void 0!==B&&B,E=e.keyboard,Q=void 0===E||E,y=Boolean(this.onViewStateChange);this.toggleEvents(u,y&&n),this.toggleEvents(l,y&&(i||a)),this.toggleEvents(I,y&&(d||p)),this.toggleEvents(C,y&&p),this.toggleEvents(h,y&&g),this.toggleEvents(f,y&&Q),this.scrollZoom=n,this.dragPan=i,this.dragRotate=a,this.doubleClickZoom=g,this.touchZoom=d,this.touchRotate=p,this.keyboard=Q}},{key:"updateTransition",value:function(){this.transitionManager.updateTransition()}},{key:"toggleEvents",value:function(e,t){var A=this;this.eventManager&&e.forEach((function(e){A._events[e]!==t&&(A._events[e]=t,t?A.eventManager.on(e,A.handleEvent):A.eventManager.off(e,A.handleEvent))}))}},{key:"updateViewport",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=Object(n.a)({},e.getViewportProps(),{},t),i=this.controllerState!==e;if(this._state=e.getState(),this._setInteractionState(A),i){var o=this.controllerState?this.controllerState.getViewportProps():null;this.onViewStateChange&&this.onViewStateChange({viewState:r,interactionState:this._interactionState,oldViewState:o})}}},{key:"_onTransition",value:function(e){this.onViewStateChange&&(e.interactionState=this._interactionState,this.onViewStateChange(e))}},{key:"_setInteractionState",value:function(e){Object.assign(this._interactionState,e),this.onStateChange&&this.onStateChange(this._interactionState)}},{key:"_onPanStart",value:function(e){var t=this.getCenter(e);if(!this.isPointInBounds(t,e))return!1;var A=this.isFunctionKeyPressed(e)||e.rightButton;(this.invertPan||"pan"===this.dragMode)&&(A=!A);var n=this.controllerState[A?"panStart":"rotateStart"]({pos:t});return this._panMove=A,this.updateViewport(n,s,{isDragging:!0}),!0}},{key:"_onPan",value:function(e){return!!this.isDragging()&&(this._panMove?this._onPanMove(e):this._onPanRotate(e))}},{key:"_onPanEnd",value:function(e){return!!this.isDragging()&&(this._panMove?this._onPanMoveEnd(e):this._onPanRotateEnd(e))}},{key:"_onPanMove",value:function(e){if(!this.dragPan)return!1;var t=this.getCenter(e),A=this.controllerState.pan({pos:t});return this.updateViewport(A,s,{isDragging:!0,isPanning:!0}),!0}},{key:"_onPanMoveEnd",value:function(e){var t=this.inertia;if(this.dragPan&&t&&e.velocity){var A=this.getCenter(e),r=[A[0]+e.velocityX*t/2,A[1]+e.velocityY*t/2],i=this.controllerState.pan({pos:r}).panEnd();this.updateViewport(i,Object(n.a)({},this._getTransitionProps(),{transitionDuration:t,transitionEasing:c}),{isDragging:!1,isPanning:!0})}else{var o=this.controllerState.panEnd();this.updateViewport(o,null,{isDragging:!1,isPanning:!1})}return!0}},{key:"_onPanRotate",value:function(e){if(!this.dragRotate)return!1;var t=this.getCenter(e),A=this.controllerState.rotate({pos:t});return this.updateViewport(A,s,{isDragging:!0,isRotating:!0}),!0}},{key:"_onPanRotateEnd",value:function(e){var t=this.inertia;if(this.dragRotate&&t&&e.velocity){var A=this.getCenter(e),r=[A[0]+e.velocityX*t/2,A[1]+e.velocityY*t/2],i=this.controllerState.rotate({pos:r}).rotateEnd();this.updateViewport(i,Object(n.a)({},this._getTransitionProps(),{transitionDuration:t,transitionEasing:c}),{isDragging:!1,isRotating:!0})}else{var o=this.controllerState.rotateEnd();this.updateViewport(o,null,{isDragging:!1,isRotating:!1})}return!0}},{key:"_onWheel",value:function(e){if(!this.scrollZoom)return!1;e.preventDefault();var t=this.getCenter(e);if(!this.isPointInBounds(t,e))return!1;var A=this.scrollZoom,r=A.speed,i=void 0===r?.01:r,o=A.smooth,a=void 0!==o&&o,s=e.delta,g=2/(1+Math.exp(-Math.abs(s*i)));s<0&&0!==g&&(g=1/g);var c=this.controllerState.zoom({pos:t,scale:g});return this.updateViewport(c,Object(n.a)({},this._getTransitionProps({around:t}),{transitionDuration:a?250:1}),{isZooming:!0,isPanning:!0}),!0}},{key:"_onTriplePanStart",value:function(e){var t=this.getCenter(e);if(!this.isPointInBounds(t,e))return!1;var A=this.controllerState.rotateStart({pos:t});return this.updateViewport(A,s,{isDragging:!0}),!0}},{key:"_onTriplePan",value:function(e){if(!this.touchRotate)return!1;if(!this.isDragging())return!1;var t=this.getCenter(e);t[0]-=e.deltaX;var A=this.controllerState.rotate({pos:t});return this.updateViewport(A,s,{isDragging:!0,isRotating:!0}),!0}},{key:"_onTriplePanEnd",value:function(e){if(!this.isDragging())return!1;var t=this.inertia;if(this.touchRotate&&t&&e.velocityY){var A=this.getCenter(e),r=[A[0],A[1]+=e.velocityY*t/2],i=this.controllerState.rotate({pos:r});this.updateViewport(i,Object(n.a)({},this._getTransitionProps(),{transitionDuration:t,transitionEasing:c}),{isDragging:!1,isRotating:!0}),this.blockEvents(t)}else{var o=this.controllerState.rotateEnd();this.updateViewport(o,null,{isDragging:!1,isRotating:!1})}return!0}},{key:"_onPinchStart",value:function(e){var t=this.getCenter(e);if(!this.isPointInBounds(t,e))return!1;var A=this.controllerState.zoomStart({pos:t}).rotateStart({pos:t});return this._startPinchRotation=e.rotation,this._lastPinchEvent=e,this.updateViewport(A,s,{isDragging:!0}),!0}},{key:"_onPinch",value:function(e){if(!this.touchZoom&&!this.touchRotate)return!1;if(!this.isDragging())return!1;var t=this.controllerState;if(this.touchZoom){var A=e.scale,n=this.getCenter(e);t=t.zoom({pos:n,scale:A})}if(this.touchRotate){var r=e.rotation;t=t.rotate({deltaAngleX:this._startPinchRotation-r})}return this.updateViewport(t,s,{isDragging:!0,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:this.touchRotate}),this._lastPinchEvent=e,!0}},{key:"_onPinchEnd",value:function(e){if(!this.isDragging())return!1;var t=this.inertia,A=this._lastPinchEvent;if(this.touchZoom&&t&&A&&e.scale!==A.scale){var r=this.getCenter(e),i=this.controllerState.rotateEnd(),o=Math.log2(e.scale),a=(o-Math.log2(A.scale))/(e.deltaTime-A.deltaTime),s=Math.pow(2,o+a*t/2);i=i.zoom({pos:r,scale:s}).zoomEnd(),this.updateViewport(i,Object(n.a)({},this._getTransitionProps({around:r}),{transitionDuration:t,transitionEasing:c}),{isDragging:!1,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:!1}),this.blockEvents(t)}else{var g=this.controllerState.zoomEnd().rotateEnd();this.updateViewport(g,null,{isDragging:!1,isPanning:!1,isZooming:!1,isRotating:!1})}return this._startPinchRotation=null,this._lastPinchEvent=null,!0}},{key:"_onDoubleTap",value:function(e){if(!this.doubleClickZoom)return!1;var t=this.getCenter(e);if(!this.isPointInBounds(t,e))return!1;var A=this.isFunctionKeyPressed(e),n=this.controllerState.zoom({pos:t,scale:A?.5:2});return this.updateViewport(n,this._getTransitionProps({around:t}),{isZooming:!0,isPanning:!0}),this.blockEvents(100),!0}},{key:"_onKeyDown",value:function(e){if(!this.keyboard)return!1;var t,A=this.isFunctionKeyPressed(e),n=this.keyboard,r=n.zoomSpeed,i=n.moveSpeed,o=n.rotateSpeedX,a=n.rotateSpeedY,s=this.controllerState,g={};switch(e.srcEvent.code){case"Minus":t=A?s.zoomOut(r).zoomOut(r):s.zoomOut(r),g.isZooming=!0;break;case"Equal":t=A?s.zoomIn(r).zoomIn(r):s.zoomIn(r),g.isZooming=!0;break;case"ArrowLeft":A?(t=s.rotateLeft(o),g.isRotating=!0):(t=s.moveLeft(i),g.isPanning=!0);break;case"ArrowRight":A?(t=s.rotateRight(o),g.isRotating=!0):(t=s.moveRight(i),g.isPanning=!0);break;case"ArrowUp":A?(t=s.rotateUp(a),g.isRotating=!0):(t=s.moveUp(i),g.isPanning=!0);break;case"ArrowDown":A?(t=s.rotateDown(a),g.isRotating=!0):(t=s.moveDown(i),g.isPanning=!0);break;default:return!1}return this.updateViewport(t,this._getTransitionProps(),g),!0}},{key:"_getTransitionProps",value:function(e){var t=this._transition;return t?e?Object(n.a)({},t,{transitionInterpolator:new a.a(Object(n.a)({},e,{transitionProps:this.linearTransitionProps,makeViewport:this.controllerState.makeViewport}))}):t:s}},{key:"linearTransitionProps",get:function(){return null}},{key:"events",set:function(e){this.toggleEvents(this._customEvents,!1),this.toggleEvents(e,!0),this._customEvents=e,this.setProps(this.controllerStateProps)}}]),e}()},function(e,t,A){"use strict";var n=A(7),r=A(1),i=A(4),o=A(96),a=/([0-9]+\.?[0-9]*)(%|px)/;function s(e){switch(typeof e){case"number":return{position:e,relative:!1};case"string":var t=e.match(a);if(t&&t.length>=3){var A="%"===t[2],n=parseFloat(t[1]);return{position:A?n/100:n,relative:A}}default:throw new Error("Could not parse position string ".concat(e))}}function g(e,t){return e.relative?Math.round(e.position*t):e.position}var c=A(163),u=A(87);A.d(t,"a",(function(){return l}));var l=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(r.a)(this,e);var A=t.id,i=void 0===A?null:A,a=t.x,s=void 0===a?0:a,g=t.y,c=void 0===g?0:g,l=t.width,I=void 0===l?"100%":l,C=t.height,h=void 0===C?"100%":C,f=t.viewportInstance,d=t.type,B=void 0===d?o.a:d;Object(u.a)(!f||f instanceof o.a),this.viewportInstance=f,this.id=i||this.constructor.displayName||"view",this.type=B,this.props=Object(n.a)({},t,{id:this.id}),this._parseDimensions({x:s,y:c,width:I,height:h}),this.equals=this.equals.bind(this),Object.seal(this)}return Object(i.a)(e,[{key:"equals",value:function(e){return this===e||(this.viewportInstance?e.viewportInstance&&this.viewportInstance.equals(e.viewportInstance):Object(c.a)(this.props,e.props))}},{key:"makeViewport",value:function(e){var t=e.width,A=e.height,n=e.viewState;if(this.viewportInstance)return this.viewportInstance;n=this.filterViewState(n);var r=this.getDimensions({width:t,height:A});return this._getViewport(n,r)}},{key:"getViewStateId",value:function(){switch(typeof this.props.viewState){case"string":return this.props.viewState;case"object":return this.props.viewState&&this.props.viewState.id;default:return this.id}}},{key:"filterViewState",value:function(e){if(this.props.viewState&&"object"===typeof this.props.viewState){if(!this.props.viewState.id)return this.props.viewState;var t=Object(n.a)({},e);for(var A in this.props.viewState)"id"!==A&&(t[A]=this.props.viewState[A]);return t}return e}},{key:"getDimensions",value:function(e){var t=e.width,A=e.height;return{x:g(this._x,t),y:g(this._y,A),width:g(this._width,t),height:g(this._height,A)}}},{key:"_getControllerProps",value:function(e){var t=this.props.controller;return t?!0===t?e:("function"===typeof t&&(t={type:t}),Object(n.a)({},e,{},t)):null}},{key:"_getViewport",value:function(e,t){return new(0,this.type)(Object(n.a)({},e,{},this.props,{},t))}},{key:"_parseDimensions",value:function(e){var t=e.x,A=e.y,n=e.width,r=e.height;this._x=s(t),this._y=s(A),this._width=s(n),this._height=s(r)}}]),e}()},function(e,t,A){"use strict";A.d(t,"a",(function(){return g}));var n=A(7),r=A(1),i=A(4),o=A(108),a=A(26),s={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},g=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(r.a)(this,e);var A=t.id,n=void 0===A?Object(o.c)("geometry"):A,i=t.drawMode,a=void 0===i?s.TRIANGLES:i,g=t.attributes,c=void 0===g?{}:g,u=t.indices,l=void 0===u?null:u,I=t.vertexCount,C=void 0===I?null:I;this.id=n,this.drawMode=0|a,this.attributes={},this.userData={},this._setAttributes(c,l),this.vertexCount=C||this._calculateVertexCount(this.attributes,this.indices)}return Object(i.a)(e,null,[{key:"DRAW_MODE",get:function(){return s}}]),Object(i.a)(e,[{key:"getVertexCount",value:function(){return this.vertexCount}},{key:"getAttributes",value:function(){return this.indices?Object(n.a)({indices:this.indices},this.attributes):this.attributes}},{key:"_print",value:function(e){return"Geometry ".concat(this.id," attribute ").concat(e)}},{key:"_setAttributes",value:function(e,t){for(var A in t&&(this.indices=ArrayBuffer.isView(t)?{value:t,size:1}:t),e){var n=e[A];n=ArrayBuffer.isView(n)?{value:n}:n,Object(a.a)(ArrayBuffer.isView(n.value),"".concat(this._print(A),": must be typed array or object with value as typed array")),"POSITION"!==A&&"positions"!==A||n.size||(n.size=3),"indices"===A?(Object(a.a)(!this.indices),this.indices=n):this.attributes[A]=n}return this.indices&&void 0!==this.indices.isIndexed&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this}},{key:"_calculateVertexCount",value:function(e,t){if(t)return t.value.length;var A=1/0;for(var n in e){var r=e[n],i=r.value,o=r.size;!r.constant&&i&&o>=1&&(A=Math.min(A,i.length/o))}return Object(a.a)(Number.isFinite(A)),A}},{key:"mode",get:function(){return this.drawMode}}]),e}()},function(e,t,A){"use strict";function n(e,t){"function"===typeof e?e(t):e&&(e.current=t)}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";var n=A(397);function r(e){return function(e){if(Array.isArray(e)){for(var t=0,A=new Array(e.length);t0&&void 0!==arguments[0]?arguments[0]:{};return void 0!==(e=Object(s.a)("Accessor",e,c)).type&&(this.type=e.type,5124!==e.type&&5125!==e.type||(this.integer=!0)),void 0!==e.size&&(this.size=e.size),void 0!==e.offset&&(this.offset=e.offset),void 0!==e.stride&&(this.stride=e.stride),void 0!==e.normalized&&(this.normalized=e.normalized),void 0!==e.integer&&(this.integer=e.integer),void 0!==e.divisor&&(this.divisor=e.divisor),void 0!==e.buffer&&(this.buffer=e.buffer),void 0!==e.index&&("boolean"===typeof e.index?this.index=e.index?1:0:this.index=e.index),void 0!==e.instanced&&(this.divisor=e.instanced?1:0),void 0!==e.isInstanced&&(this.divisor=e.isInstanced?1:0),this}},{key:"BYTES_PER_ELEMENT",get:function(){return e.getBytesPerElement(this)}},{key:"BYTES_PER_VERTEX",get:function(){return e.getBytesPerVertex(this)}}]),e}()},function(e,t,A){var n=A(543),r="object"==typeof self&&self&&self.Object===Object&&self,i=n||r||Function("return this")();e.exports=i},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=A(59);function r(e,t,A){if(null!==e)for(var n,i,o,a,s,g,c,u,l=0,I=0,C=e.type,h="FeatureCollection"===C,f="Feature"===C,d=h?e.features.length:1,B=0;Bg||I>c||C>u)return s=r,g=A,c=I,u=C,void(o=0);var h=n.lineString([s,r],e.properties);if(!1===t(h,A,i,C,o))return!1;o++,s=r}))&&void 0}}}))}function c(e,t){if(!e)throw new Error("geojson is required");s(e,(function(e,A,r){if(null!==e.geometry){var i=e.geometry.type,o=e.geometry.coordinates;switch(i){case"LineString":if(!1===t(e,A,r,0,0))return!1;break;case"Polygon":for(var a=0;a=128?"#000":"#fff"},t.red={hsl:{a:1,h:0,l:.5,s:1},hex:"#ff0000",rgb:{r:255,g:0,b:0,a:1},hsv:{h:0,s:1,v:1,a:1}};t.default=t},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=A(59),r=A(105);function i(e,t,A){if(void 0===A&&(A={}),!0===A.final)return function(e,t){var A=i(t,e);return A=(A+180)%360}(e,t);var o=r.getCoord(e),a=r.getCoord(t),s=n.degreesToRadians(o[0]),g=n.degreesToRadians(a[0]),c=n.degreesToRadians(o[1]),u=n.degreesToRadians(a[1]),l=Math.sin(g-s)*Math.cos(u),I=Math.cos(c)*Math.sin(u)-Math.sin(c)*Math.cos(u)*Math.cos(g-s);return n.radiansToDegrees(Math.atan2(l,I))}t.default=i},function(e,t,A){var n=A(106);e.exports=function(e,t,A){return new n(e,A).compare(new n(t,A))}},function(e,t,A){var n=A(1123),r=A(505),i=A(299),o=A(300),a=function(){"use strict";function e(t,A){var n=this;if(i(this,e),A=g(A),t instanceof e)return t.loose===!!A.loose&&t.includePrerelease===!!A.includePrerelease?t:new e(t.raw,A);if(t instanceof c)return this.raw=t.value,this.set=[[t]],this.format(),this;if(this.options=A,this.loose=!!A.loose,this.includePrerelease=!!A.includePrerelease,this.raw=t,this.set=t.split(/\s*\|\|\s*/).map((function(e){return n.parseRange(e.trim())})).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: ".concat(t));if(this.set.length>1){var o=this.set[0];if(this.set=this.set.filter((function(e){return!p(e[0])})),0===this.set.length)this.set=[o];else if(this.set.length>1){var a,s=r(this.set);try{for(s.s();!(a=s.n()).done;){var u=a.value;if(1===u.length&&E(u[0])){this.set=[u];break}}}catch(l){s.e(l)}finally{s.f()}}}this.format()}return o(e,[{key:"format",value:function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range}},{key:"toString",value:function(){return this.range}},{key:"parseRange",value:function(e){var t=this;e=e.trim();var A=Object.keys(this.options).join(","),i="parseRange:".concat(A,":").concat(e),o=s.get(i);if(o)return o;var a=this.options.loose,g=a?C[h.HYPHENRANGELOOSE]:C[h.HYPHENRANGE];e=e.replace(g,k(this.options.includePrerelease)),u("hyphen replace",e),e=e.replace(C[h.COMPARATORTRIM],f),u("comparator trim",e,C[h.COMPARATORTRIM]),e=(e=(e=e.replace(C[h.TILDETRIM],d)).replace(C[h.CARETTRIM],B)).split(/\s+/).join(" ");var l,I=a?C[h.COMPARATORLOOSE]:C[h.COMPARATOR],E=e.split(" ").map((function(e){return y(e,t.options)})).join(" ").split(/\s+/).map((function(e){return G(e,t.options)})).filter(this.options.loose?function(e){return!!e.match(I)}:function(){return!0}).map((function(e){return new c(e,t.options)})),Q=(E.length,new Map),v=r(E);try{for(v.s();!(l=v.n()).done;){var m=l.value;if(p(m))return[m];Q.set(m.value,m)}}catch(w){v.e(w)}finally{v.f()}Q.size>1&&Q.has("")&&Q.delete("");var b=n(Q.values());return s.set(i,b),b}},{key:"intersects",value:function(t,A){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some((function(e){return Q(e,A)&&t.set.some((function(t){return Q(t,A)&&e.every((function(e){return t.every((function(t){return e.intersects(t,A)}))}))}))}))}},{key:"test",value:function(e){if(!e)return!1;if("string"===typeof e)try{e=new l(e,this.options)}catch(A){return!1}for(var t=0;t=".concat(A,".").concat(r,".0").concat(n," <").concat(A,".").concat(+r+1,".0-0"):">=".concat(A,".").concat(r,".0").concat(n," <").concat(+A+1,".0.0-0"):o?(u("replaceCaret pr",o),a="0"===A?"0"===r?">=".concat(A,".").concat(r,".").concat(i,"-").concat(o," <").concat(A,".").concat(r,".").concat(+i+1,"-0"):">=".concat(A,".").concat(r,".").concat(i,"-").concat(o," <").concat(A,".").concat(+r+1,".0-0"):">=".concat(A,".").concat(r,".").concat(i,"-").concat(o," <").concat(+A+1,".0.0-0")):(u("no pr"),a="0"===A?"0"===r?">=".concat(A,".").concat(r,".").concat(i).concat(n," <").concat(A,".").concat(r,".").concat(+i+1,"-0"):">=".concat(A,".").concat(r,".").concat(i).concat(n," <").concat(A,".").concat(+r+1,".0-0"):">=".concat(A,".").concat(r,".").concat(i," <").concat(+A+1,".0.0-0")),u("caret return",a),a}))},F=function(e,t){return u("replaceXRanges",e,t),e.split(/\s+/).map((function(e){return R(e,t)})).join(" ")},R=function(e,t){e=e.trim();var A=t.loose?C[h.XRANGELOOSE]:C[h.XRANGE];return e.replace(A,(function(A,n,r,i,o,a){u("xRange",e,A,n,r,i,o,a);var s=v(r),g=s||v(i),c=g||v(o),l=c;return"="===n&&l&&(n=""),a=t.includePrerelease?"-0":"",s?A=">"===n||"<"===n?"<0.0.0-0":"*":n&&l?(g&&(i=0),o=0,">"===n?(n=">=",g?(r=+r+1,i=0,o=0):(i=+i+1,o=0)):"<="===n&&(n="<",g?r=+r+1:i=+i+1),"<"===n&&(a="-0"),A="".concat(n+r,".").concat(i,".").concat(o).concat(a)):g?A=">=".concat(r,".0.0").concat(a," <").concat(+r+1,".0.0-0"):c&&(A=">=".concat(r,".").concat(i,".0").concat(a," <").concat(r,".").concat(+i+1,".0-0")),u("xRange return",A),A}))},D=function(e,t){return u("replaceStars",e,t),e.trim().replace(C[h.STAR],"")},G=function(e,t){return u("replaceGTE0",e,t),e.trim().replace(C[t.includePrerelease?h.GTE0PRE:h.GTE0],"")},k=function(e){return function(t,A,n,r,i,o,a,s,g,c,u,l,I){return A=v(n)?"":v(r)?">=".concat(n,".0.0").concat(e?"-0":""):v(i)?">=".concat(n,".").concat(r,".0").concat(e?"-0":""):o?">=".concat(A):">=".concat(A).concat(e?"-0":""),s=v(g)?"":v(c)?"<".concat(+g+1,".0.0-0"):v(u)?"<".concat(g,".").concat(+c+1,".0-0"):l?"<=".concat(g,".").concat(c,".").concat(u,"-").concat(l):e?"<".concat(g,".").concat(c,".").concat(+u+1,"-0"):"<=".concat(s),"".concat(A," ").concat(s).trim()}},x=function(e,t,A){for(var n=0;n0){var i=e[r].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0}},function(e,t,A){"use strict";e.exports=function e(t,A){if(t===A)return!0;if(t&&A&&"object"==typeof t&&"object"==typeof A){if(t.constructor!==A.constructor)return!1;var n,r,i;if(Array.isArray(t)){if((n=t.length)!=A.length)return!1;for(r=n;0!==r--;)if(!e(t[r],A[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===A.source&&t.flags===A.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===A.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===A.toString();if((n=(i=Object.keys(t)).length)!==Object.keys(A).length)return!1;for(r=n;0!==r--;)if(!Object.prototype.hasOwnProperty.call(A,i[r]))return!1;for(r=n;0!==r--;){var o=i[r];if(!e(t[o],A[o]))return!1}return!0}return t!==t&&A!==A}},function(e,t,A){"use strict";function n(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0};return Array.isArray(e)?r(e,t,[]):t(e)?[e]:[]}function r(e,t,A){for(var n=-1;++n1&&void 0!==arguments[1]?arguments[1]:166;function n(){for(var n=arguments.length,r=new Array(n),i=0;in&&(r=n);var i=this._pool,o=e.BYTES_PER_ELEMENT*r,a=i.findIndex((function(e){return e.byteLength>=o}));if(a>=0){var s=new e(i.splice(a,1)[0],0,r);return A&&s.fill(0),s}return new e(r)}},{key:"_release",value:function(e){if(ArrayBuffer.isView(e)){var t=this._pool,A=e.buffer,n=A.byteLength,r=t.findIndex((function(e){return e.byteLength>=n}));r<0?t.push(A):(r>0||t.lengththis.props.poolSize&&t.shift()}}}]),e}();t.a=new i},function(e,t,A){"use strict";A.d(t,"b",(function(){return n})),A.d(t,"a",(function(){return r}));var n=function(e){return e.scrollTop};function r(e,t){var A=e.timeout,n=e.style,r=void 0===n?{}:n;return{duration:r.transitionDuration||"number"===typeof A?A:A[t.mode]||0,delay:r.transitionDelay}}},function(e,t,A){"use strict";A.d(t,"c",(function(){return c})),A.d(t,"e",(function(){return h})),A.d(t,"a",(function(){return d})),A.d(t,"b",(function(){return B})),A.d(t,"d",(function(){return E}));var n,r,i,o=A(8),a=A(11),s=A(2),g=A(72),c=(n={},Object(s.a)(n,3042,!1),Object(s.a)(n,32773,new Float32Array([0,0,0,0])),Object(s.a)(n,32777,32774),Object(s.a)(n,34877,32774),Object(s.a)(n,32969,1),Object(s.a)(n,32968,0),Object(s.a)(n,32971,1),Object(s.a)(n,32970,0),Object(s.a)(n,3106,new Float32Array([0,0,0,0])),Object(s.a)(n,3107,[!0,!0,!0,!0]),Object(s.a)(n,2884,!1),Object(s.a)(n,2885,1029),Object(s.a)(n,2929,!1),Object(s.a)(n,2931,1),Object(s.a)(n,2932,513),Object(s.a)(n,2928,new Float32Array([0,1])),Object(s.a)(n,2930,!0),Object(s.a)(n,3024,!0),Object(s.a)(n,36006,null),Object(s.a)(n,2886,2305),Object(s.a)(n,33170,4352),Object(s.a)(n,2849,1),Object(s.a)(n,32823,!1),Object(s.a)(n,32824,0),Object(s.a)(n,10752,0),Object(s.a)(n,32938,1),Object(s.a)(n,32939,!1),Object(s.a)(n,3089,!1),Object(s.a)(n,3088,new Int32Array([0,0,1024,1024])),Object(s.a)(n,2960,!1),Object(s.a)(n,2961,0),Object(s.a)(n,2968,4294967295),Object(s.a)(n,36005,4294967295),Object(s.a)(n,2962,519),Object(s.a)(n,2967,0),Object(s.a)(n,2963,4294967295),Object(s.a)(n,34816,519),Object(s.a)(n,36003,0),Object(s.a)(n,36004,4294967295),Object(s.a)(n,2964,7680),Object(s.a)(n,2965,7680),Object(s.a)(n,2966,7680),Object(s.a)(n,34817,7680),Object(s.a)(n,34818,7680),Object(s.a)(n,34819,7680),Object(s.a)(n,2978,[0,0,1024,1024]),Object(s.a)(n,3333,4),Object(s.a)(n,3317,4),Object(s.a)(n,37440,!1),Object(s.a)(n,37441,!1),Object(s.a)(n,37443,37444),Object(s.a)(n,35723,4352),Object(s.a)(n,36010,null),Object(s.a)(n,35977,!1),Object(s.a)(n,3330,0),Object(s.a)(n,3332,0),Object(s.a)(n,3331,0),Object(s.a)(n,3314,0),Object(s.a)(n,32878,0),Object(s.a)(n,3316,0),Object(s.a)(n,3315,0),Object(s.a)(n,32877,0),n),u=function(e,t,A){return t?e.enable(A):e.disable(A)},l=function(e,t,A){return e.hint(A,t)},I=function(e,t,A){return e.pixelStorei(A,t)};function C(e){return Array.isArray(e)||ArrayBuffer.isView(e)}var h=(r={},Object(s.a)(r,3042,u),Object(s.a)(r,32773,(function(e,t){return e.blendColor.apply(e,Object(a.a)(t))})),Object(s.a)(r,32777,"blendEquation"),Object(s.a)(r,34877,"blendEquation"),Object(s.a)(r,32969,"blendFunc"),Object(s.a)(r,32968,"blendFunc"),Object(s.a)(r,32971,"blendFunc"),Object(s.a)(r,32970,"blendFunc"),Object(s.a)(r,3106,(function(e,t){return e.clearColor.apply(e,Object(a.a)(t))})),Object(s.a)(r,3107,(function(e,t){return e.colorMask.apply(e,Object(a.a)(t))})),Object(s.a)(r,2884,u),Object(s.a)(r,2885,(function(e,t){return e.cullFace(t)})),Object(s.a)(r,2929,u),Object(s.a)(r,2931,(function(e,t){return e.clearDepth(t)})),Object(s.a)(r,2932,(function(e,t){return e.depthFunc(t)})),Object(s.a)(r,2928,(function(e,t){return e.depthRange.apply(e,Object(a.a)(t))})),Object(s.a)(r,2930,(function(e,t){return e.depthMask(t)})),Object(s.a)(r,3024,u),Object(s.a)(r,35723,l),Object(s.a)(r,36006,(function(e,t){var A=Object(g.e)(e)?36009:36160;return e.bindFramebuffer(A,t)})),Object(s.a)(r,2886,(function(e,t){return e.frontFace(t)})),Object(s.a)(r,33170,l),Object(s.a)(r,2849,(function(e,t){return e.lineWidth(t)})),Object(s.a)(r,32823,u),Object(s.a)(r,32824,"polygonOffset"),Object(s.a)(r,10752,"polygonOffset"),Object(s.a)(r,35977,u),Object(s.a)(r,32938,"sampleCoverage"),Object(s.a)(r,32939,"sampleCoverage"),Object(s.a)(r,3089,u),Object(s.a)(r,3088,(function(e,t){return e.scissor.apply(e,Object(a.a)(t))})),Object(s.a)(r,2960,u),Object(s.a)(r,2961,(function(e,t){return e.clearStencil(t)})),Object(s.a)(r,2968,(function(e,t){return e.stencilMaskSeparate(1028,t)})),Object(s.a)(r,36005,(function(e,t){return e.stencilMaskSeparate(1029,t)})),Object(s.a)(r,2962,"stencilFuncFront"),Object(s.a)(r,2967,"stencilFuncFront"),Object(s.a)(r,2963,"stencilFuncFront"),Object(s.a)(r,34816,"stencilFuncBack"),Object(s.a)(r,36003,"stencilFuncBack"),Object(s.a)(r,36004,"stencilFuncBack"),Object(s.a)(r,2964,"stencilOpFront"),Object(s.a)(r,2965,"stencilOpFront"),Object(s.a)(r,2966,"stencilOpFront"),Object(s.a)(r,34817,"stencilOpBack"),Object(s.a)(r,34818,"stencilOpBack"),Object(s.a)(r,34819,"stencilOpBack"),Object(s.a)(r,2978,(function(e,t){return e.viewport.apply(e,Object(a.a)(t))})),Object(s.a)(r,3333,I),Object(s.a)(r,3317,I),Object(s.a)(r,37440,I),Object(s.a)(r,37441,I),Object(s.a)(r,37443,I),Object(s.a)(r,3330,I),Object(s.a)(r,3332,I),Object(s.a)(r,3331,I),Object(s.a)(r,36010,(function(e,t){return e.bindFramebuffer(36008,t)})),Object(s.a)(r,3314,I),Object(s.a)(r,32878,I),Object(s.a)(r,3316,I),Object(s.a)(r,3315,I),Object(s.a)(r,32877,I),Object(s.a)(r,"framebuffer",(function(e,t){var A=t&&"handle"in t?t.handle:t;return e.bindFramebuffer(36160,A)})),Object(s.a)(r,"blend",(function(e,t){return t?e.enable(3042):e.disable(3042)})),Object(s.a)(r,"blendColor",(function(e,t){return e.blendColor.apply(e,Object(a.a)(t))})),Object(s.a)(r,"blendEquation",(function(e,t){t=C(t)?t:[t,t],e.blendEquationSeparate.apply(e,Object(a.a)(t))})),Object(s.a)(r,"blendFunc",(function(e,t){t=C(t)&&2===t.length?[].concat(Object(a.a)(t),Object(a.a)(t)):t,e.blendFuncSeparate.apply(e,Object(a.a)(t))})),Object(s.a)(r,"clearColor",(function(e,t){return e.clearColor.apply(e,Object(a.a)(t))})),Object(s.a)(r,"clearDepth",(function(e,t){return e.clearDepth(t)})),Object(s.a)(r,"clearStencil",(function(e,t){return e.clearStencil(t)})),Object(s.a)(r,"colorMask",(function(e,t){return e.colorMask.apply(e,Object(a.a)(t))})),Object(s.a)(r,"cull",(function(e,t){return t?e.enable(2884):e.disable(2884)})),Object(s.a)(r,"cullFace",(function(e,t){return e.cullFace(t)})),Object(s.a)(r,"depthTest",(function(e,t){return t?e.enable(2929):e.disable(2929)})),Object(s.a)(r,"depthFunc",(function(e,t){return e.depthFunc(t)})),Object(s.a)(r,"depthMask",(function(e,t){return e.depthMask(t)})),Object(s.a)(r,"depthRange",(function(e,t){return e.depthRange.apply(e,Object(a.a)(t))})),Object(s.a)(r,"dither",(function(e,t){return t?e.enable(3024):e.disable(3024)})),Object(s.a)(r,"derivativeHint",(function(e,t){e.hint(35723,t)})),Object(s.a)(r,"frontFace",(function(e,t){return e.frontFace(t)})),Object(s.a)(r,"mipmapHint",(function(e,t){return e.hint(33170,t)})),Object(s.a)(r,"lineWidth",(function(e,t){return e.lineWidth(t)})),Object(s.a)(r,"polygonOffsetFill",(function(e,t){return t?e.enable(32823):e.disable(32823)})),Object(s.a)(r,"polygonOffset",(function(e,t){return e.polygonOffset.apply(e,Object(a.a)(t))})),Object(s.a)(r,"sampleCoverage",(function(e,t){return e.sampleCoverage.apply(e,Object(a.a)(t))})),Object(s.a)(r,"scissorTest",(function(e,t){return t?e.enable(3089):e.disable(3089)})),Object(s.a)(r,"scissor",(function(e,t){return e.scissor.apply(e,Object(a.a)(t))})),Object(s.a)(r,"stencilTest",(function(e,t){return t?e.enable(2960):e.disable(2960)})),Object(s.a)(r,"stencilMask",(function(e,t){var A=t=C(t)?t:[t,t],n=Object(o.a)(A,2),r=n[0],i=n[1];e.stencilMaskSeparate(1028,r),e.stencilMaskSeparate(1029,i)})),Object(s.a)(r,"stencilFunc",(function(e,t){var A=t=C(t)&&3===t.length?[].concat(Object(a.a)(t),Object(a.a)(t)):t,n=Object(o.a)(A,6),r=n[0],i=n[1],s=n[2],g=n[3],c=n[4],u=n[5];e.stencilFuncSeparate(1028,r,i,s),e.stencilFuncSeparate(1029,g,c,u)})),Object(s.a)(r,"stencilOp",(function(e,t){var A=t=C(t)&&3===t.length?[].concat(Object(a.a)(t),Object(a.a)(t)):t,n=Object(o.a)(A,6),r=n[0],i=n[1],s=n[2],g=n[3],c=n[4],u=n[5];e.stencilOpSeparate(1028,r,i,s),e.stencilOpSeparate(1029,g,c,u)})),Object(s.a)(r,"viewport",(function(e,t){return e.viewport.apply(e,Object(a.a)(t))})),r);function f(e,t,A){return void 0!==t[e]?t[e]:A[e]}var d={blendEquation:function(e,t,A){return e.blendEquationSeparate(f(32777,t,A),f(34877,t,A))},blendFunc:function(e,t,A){return e.blendFuncSeparate(f(32969,t,A),f(32968,t,A),f(32971,t,A),f(32970,t,A))},polygonOffset:function(e,t,A){return e.polygonOffset(f(32824,t,A),f(10752,t,A))},sampleCoverage:function(e,t,A){return e.sampleCoverage(f(32938,t,A),f(32939,t,A))},stencilFuncFront:function(e,t,A){return e.stencilFuncSeparate(1028,f(2962,t,A),f(2967,t,A),f(2963,t,A))},stencilFuncBack:function(e,t,A){return e.stencilFuncSeparate(1029,f(34816,t,A),f(36003,t,A),f(36004,t,A))},stencilOpFront:function(e,t,A){return e.stencilOpSeparate(1028,f(2964,t,A),f(2965,t,A),f(2966,t,A))},stencilOpBack:function(e,t,A){return e.stencilOpSeparate(1029,f(34817,t,A),f(34818,t,A),f(34819,t,A))}},B={enable:function(e,t){return e(Object(s.a)({},t,!0))},disable:function(e,t){return e(Object(s.a)({},t,!1))},pixelStorei:function(e,t,A){return e(Object(s.a)({},t,A))},hint:function(e,t,A){return e(Object(s.a)({},t,A))},bindFramebuffer:function(e,t,A){var n;switch(t){case 36160:return e((n={},Object(s.a)(n,36006,A),Object(s.a)(n,36010,A),n));case 36009:return e(Object(s.a)({},36006,A));case 36008:return e(Object(s.a)({},36010,A));default:return null}},blendColor:function(e,t,A,n,r){return e(Object(s.a)({},32773,new Float32Array([t,A,n,r])))},blendEquation:function(e,t){var A;return e((A={},Object(s.a)(A,32777,t),Object(s.a)(A,34877,t),A))},blendEquationSeparate:function(e,t,A){var n;return e((n={},Object(s.a)(n,32777,t),Object(s.a)(n,34877,A),n))},blendFunc:function(e,t,A){var n;return e((n={},Object(s.a)(n,32969,t),Object(s.a)(n,32968,A),Object(s.a)(n,32971,t),Object(s.a)(n,32970,A),n))},blendFuncSeparate:function(e,t,A,n,r){var i;return e((i={},Object(s.a)(i,32969,t),Object(s.a)(i,32968,A),Object(s.a)(i,32971,n),Object(s.a)(i,32970,r),i))},clearColor:function(e,t,A,n,r){return e(Object(s.a)({},3106,new Float32Array([t,A,n,r])))},clearDepth:function(e,t){return e(Object(s.a)({},2931,t))},clearStencil:function(e,t){return e(Object(s.a)({},2961,t))},colorMask:function(e,t,A,n,r){return e(Object(s.a)({},3107,[t,A,n,r]))},cullFace:function(e,t){return e(Object(s.a)({},2885,t))},depthFunc:function(e,t){return e(Object(s.a)({},2932,t))},depthRange:function(e,t,A){return e(Object(s.a)({},2928,new Float32Array([t,A])))},depthMask:function(e,t){return e(Object(s.a)({},2930,t))},frontFace:function(e,t){return e(Object(s.a)({},2886,t))},lineWidth:function(e,t){return e(Object(s.a)({},2849,t))},polygonOffset:function(e,t,A){var n;return e((n={},Object(s.a)(n,32824,t),Object(s.a)(n,10752,A),n))},sampleCoverage:function(e,t,A){var n;return e((n={},Object(s.a)(n,32938,t),Object(s.a)(n,32939,A),n))},scissor:function(e,t,A,n,r){return e(Object(s.a)({},3088,new Int32Array([t,A,n,r])))},stencilMask:function(e,t){var A;return e((A={},Object(s.a)(A,2968,t),Object(s.a)(A,36005,t),A))},stencilMaskSeparate:function(e,t,A){return e(Object(s.a)({},1028===t?2968:36005,A))},stencilFunc:function(e,t,A,n){var r;return e((r={},Object(s.a)(r,2962,t),Object(s.a)(r,2967,A),Object(s.a)(r,2963,n),Object(s.a)(r,34816,t),Object(s.a)(r,36003,A),Object(s.a)(r,36004,n),r))},stencilFuncSeparate:function(e,t,A,n,r){var i;return e((i={},Object(s.a)(i,1028===t?2962:34816,A),Object(s.a)(i,1028===t?2967:36003,n),Object(s.a)(i,1028===t?2963:36004,r),i))},stencilOp:function(e,t,A,n){var r;return e((r={},Object(s.a)(r,2964,t),Object(s.a)(r,2965,A),Object(s.a)(r,2966,n),Object(s.a)(r,34817,t),Object(s.a)(r,34818,A),Object(s.a)(r,34819,n),r))},stencilOpSeparate:function(e,t,A,n,r){var i;return e((i={},Object(s.a)(i,1028===t?2964:34817,A),Object(s.a)(i,1028===t?2965:34818,n),Object(s.a)(i,1028===t?2966:34819,r),i))},viewport:function(e,t,A,n,r){return e(Object(s.a)({},2978,[t,A,n,r]))}},p=function(e,t){return e.isEnabled(t)},E=(i={},Object(s.a)(i,3042,p),Object(s.a)(i,2884,p),Object(s.a)(i,2929,p),Object(s.a)(i,3024,p),Object(s.a)(i,32823,p),Object(s.a)(i,32926,p),Object(s.a)(i,32928,p),Object(s.a)(i,3089,p),Object(s.a)(i,2960,p),Object(s.a)(i,35977,p),i)},,function(e,t){e.exports=function(e){return null!=e&&"object"==typeof e}},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,A){"use strict";(function(e){var n=A(32),r=A(568);A.d(t,"g",(function(){return r.a}));var i=A(221);A.d(t,"h",(function(){return i.a}));var o=A(569);A.d(t,"i",(function(){return o.a}));var a=A(570);A.d(t,"b",(function(){return a.a}));var s=A(286);A.d(t,"c",(function(){return s.a}));var g=A(319);A.d(t,"e",(function(){return g.a})),A.d(t,"u",(function(){return n.f})),A.d(t,"v",(function(){return n.g})),A.d(t,"A",(function(){return n.l})),A.d(t,"B",(function(){return n.m})),A.d(t,"t",(function(){return n.e})),A.d(t,"y",(function(){return n.j})),A.d(t,"z",(function(){return n.k})),A.d(t,"H",(function(){return n.s})),A.d(t,"G",(function(){return n.r})),A.d(t,"D",(function(){return n.o})),A.d(t,"x",(function(){return n.i})),A.d(t,"E",(function(){return n.p})),A.d(t,"w",(function(){return n.h})),A.d(t,"F",(function(){return n.q})),A.d(t,"o",(function(){return n.b})),A.d(t,"n",(function(){return n.a})),A.d(t,"q",(function(){return n.c})),A.d(t,"s",(function(){return n.d})),A.d(t,"C",(function(){return n.n})),A.d(t,"I",(function(){return n.t}));var c=A(33);A.d(t,"r",(function(){return c.a}));var u=A(571);A.d(t,"k",(function(){return u.a}));var l=A(354);A.d(t,"f",(function(){return l.a}));var I=A(355);A.d(t,"d",(function(){return I.a}));var C=A(197);A.d(t,"a",(function(){return C.a}));var h=A(97);A.d(t,"p",(function(){return h.a})),A.d(t,"m",(function(){return l.a})),A.d(t,"l",(function(){return I.a})),A.d(t,"j",(function(){return C.a}));var f={self:"undefined"!==typeof self&&self,window:"undefined"!==typeof window&&window,global:"undefined"!==typeof e&&e};(f.global||f.self||f.window).mathgl={config:n.f}}).call(this,A(86))},function(e,t,A){"use strict";function n(e,t){return function(){return null}}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";function n(e){return function(e){if(Array.isArray(e))return r(e)}(e)||function(e){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"===typeof e)return r(e,t);var A=Object.prototype.toString.call(e).slice(8,-1);"Object"===A&&e.constructor&&(A=e.constructor.name);if("Map"===A||"Set"===A)return Array.from(A);if("Arguments"===A||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(A))return r(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var A=0,n=new Array(t);A=0;r--){var i=t[r];i>=0&&i1&&void 0!==arguments[1]?arguments[1]:{},r=A.copyState,a=void 0!==r&&r,s=A.log,g=void 0===s?function(){}:s;Object(n.a)(this,e),this.gl=t,this.program=null,this.stateStack=[],this.enable=!0,this.cache=a?Object(o.a)(t):Object.assign({},i.c),this.log=g,this._updateCache=this._updateCache.bind(this),Object.seal(this)}return Object(r.a)(e,[{key:"push",value:function(){arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stateStack.push({})}},{key:"pop",value:function(){Object(a.a)(this.stateStack.length>0);var e=this.stateStack[this.stateStack.length-1];Object(o.c)(this.gl,e),this.stateStack.pop()}},{key:"_updateCache",value:function(e){var t,A=!1,n=this.stateStack.length>0&&this.stateStack[this.stateStack.length-1];for(var r in e){Object(a.a)(void 0!==r);var i=e[r],o=this.cache[r];Object(s.a)(i,o)||(A=!0,t=o,n&&!(r in n)&&(n[r]=o),this.cache[r]=i)}return{valueChanged:A,oldValue:t}}}]),e}();function I(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=A.enable,r=void 0===n||n,o=A.copyState;if(Object(a.a)(void 0!==o),!t.state){var s="undefined"!==typeof e?e:window,I=s.polyfillContext;for(var C in I&&I(t),t.state=new l(t,{copyState:o}),u(t),i.b){var h=i.b[C];c(t,C,h)}g(t,"getParameter"),g(t,"isEnabled")}return t.state.enable=r,t}function C(e){e.state||I(e,{copyState:!1}),e.state.push()}function h(e){Object(a.a)(e.state),e.state.pop()}}).call(this,A(86))},function(e,t,A){"use strict";A.d(t,"a",(function(){return r}));var n=A(0);function r(e){var t=e.controlled,A=e.default,r=(e.name,e.state,n.useRef(void 0!==t).current),i=n.useState(A),o=i[0],a=i[1];return[r?t:o,n.useCallback((function(e){r||a(e)}),[])]}},function(e,t,A){"use strict";A.d(t,"a",(function(){return y}));var n=A(2),r=A(8),i=A(6),o=A(1),a=A(24),s=A(16),g=A(17),c=A(4),u=A(9),l=A(10),I=A(18),C=A(92),h=A(232),f=A(238),d=A(428),B=A(530),p=A(718),E=A(109),Q=A(26),y=function(e){Object(u.a)(A,e);var t=Object(l.a)(A);function A(e){var n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object(o.a)(this,A),(n=t.call(this,e,r)).width=null,n.height=null,n.attachments={},n.readBuffer=36064,n.drawBuffers=[36064],n.ownResources=[],n.initialize(r),Object.seal(Object(a.a)(n)),n}return Object(c.a)(A,[{key:"MAX_COLOR_ATTACHMENTS",get:function(){var e=Object(I.a)(this.gl);return e.getParameter(e.MAX_COLOR_ATTACHMENTS)}},{key:"MAX_DRAW_BUFFERS",get:function(){var e=Object(I.a)(this.gl);return e.getParameter(e.MAX_DRAW_BUFFERS)}}],[{key:"isSupported",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.colorBufferFloat,n=t.colorBufferHalfFloat,r=!0;return A&&(r=Boolean(e.getExtension("EXT_color_buffer_float")||e.getExtension("WEBGL_color_buffer_float")||e.getExtension("OES_texture_float"))),n&&(r=r&&Boolean(e.getExtension("EXT_color_buffer_float")||e.getExtension("EXT_color_buffer_half_float"))),r}},{key:"getDefaultFramebuffer",value:function(e){return e.luma=e.luma||{},e.luma.defaultFramebuffer=e.luma.defaultFramebuffer||new A(e,{id:"default-framebuffer",handle:null,attachments:{}}),e.luma.defaultFramebuffer}}]),Object(c.a)(A,[{key:"initialize",value:function(e){var t=e.width,A=void 0===t?1:t,n=e.height,r=void 0===n?1:n,i=e.attachments,o=void 0===i?null:i,a=e.color,s=void 0===a||a,g=e.depth,c=void 0===g||g,u=e.stencil,l=void 0!==u&&u,I=e.check,C=void 0===I||I,h=e.readBuffer,f=void 0===h?void 0:h,d=e.drawBuffers,B=void 0===d?void 0:d;if(Object(Q.a)(A>=0&&r>=0,"Width and height need to be integers"),this.width=A,this.height=r,o)for(var p in o){var E=o[p];(Array.isArray(E)?E[0]:E).resize({width:A,height:r})}else o=this._createDefaultAttachments(s,c,l,A,r);this.update({clearAttachments:!0,attachments:o,readBuffer:f,drawBuffers:B}),o&&C&&this.checkStatus()}},{key:"delete",value:function(){var e,t=Object(i.a)(this.ownResources);try{for(t.s();!(e=t.n()).done;){e.value.delete()}}catch(n){t.e(n)}finally{t.f()}return Object(g.a)(Object(s.a)(A.prototype),"delete",this).call(this),this}},{key:"update",value:function(e){var t=e.attachments,A=void 0===t?{}:t,n=e.readBuffer,r=e.drawBuffers,i=e.clearAttachments,o=void 0!==i&&i,a=e.resizeAttachments,s=void 0===a||a;this.attach(A,{clearAttachments:o,resizeAttachments:s});var g=this.gl,c=g.bindFramebuffer(36160,this.handle);return n&&this._setReadBuffer(n),r&&this._setDrawBuffers(r),g.bindFramebuffer(36160,c||null),this}},{key:"resize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.width,A=e.height;if(null===this.handle)return Object(Q.a)(void 0===t&&void 0===A),this.width=this.gl.drawingBufferWidth,this.height=this.gl.drawingBufferHeight,this;for(var n in void 0===t&&(t=this.gl.drawingBufferWidth),void 0===A&&(A=this.gl.drawingBufferHeight),t!==this.width&&A!==this.height&&I.k.log(2,"Resizing framebuffer ".concat(this.id," to ").concat(t,"x").concat(A))(),this.attachments)this.attachments[n].resize({width:t,height:A});return this.width=t,this.height=A,this}},{key:"attach",value:function(e){var t=this,A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=A.clearAttachments,i=void 0!==n&&n,o=A.resizeAttachments,a=void 0===o||o,s={};i&&Object.keys(this.attachments).forEach((function(e){s[e]=null})),Object.assign(s,e);var g=this.gl.bindFramebuffer(36160,this.handle);for(var c in s){Object(Q.a)(void 0!==c,"Misspelled framebuffer binding point?");var u=Number(c),l=s[u],I=l;if(I)if(I instanceof f.a)this._attachRenderbuffer({attachment:u,renderbuffer:I});else if(Array.isArray(l)){var C=Object(r.a)(l,3),h=C[0],d=C[1],B=void 0===d?0:d,p=C[2],E=void 0===p?0:p;I=h,this._attachTexture({attachment:u,texture:h,layer:B,level:E})}else this._attachTexture({attachment:u,texture:I,layer:0,level:0});else this._unattach(u);a&&I&&I.resize({width:this.width,height:this.height})}this.gl.bindFramebuffer(36160,g||null),Object.assign(this.attachments,e),Object.keys(this.attachments).filter((function(e){return!t.attachments[e]})).forEach((function(e){delete t.attachments[e]}))}},{key:"checkStatus",value:function(){this.gl;var e=this.getStatus();if(36053!==e)throw new Error(v(e));return this}},{key:"getStatus",value:function(){var e=this.gl,t=e.bindFramebuffer(36160,this.handle),A=e.checkFramebufferStatus(36160);return e.bindFramebuffer(36160,t||null),A}},{key:"clear",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},A=t.color,n=t.depth,r=t.stencil,i=t.drawBuffers,o=void 0===i?[]:i,a=this.gl.bindFramebuffer(36160,this.handle);return(A||n||r)&&Object(d.a)(this.gl,{color:A,depth:n,stencil:r}),o.forEach((function(t,A){Object(d.b)(e.gl,{drawBuffer:A,value:t})})),this.gl.bindFramebuffer(36160,a||null),this}},{key:"readPixels",value:function(){arguments.length>0&&void 0!==arguments[0]&&arguments[0];return I.k.error("Framebuffer.readPixels() is no logner supported, use readPixelsToArray(framebuffer)")(),null}},{key:"readPixelsToBuffer",value:function(){arguments.length>0&&void 0!==arguments[0]&&arguments[0];return I.k.error("Framebuffer.readPixelsToBuffer()is no logner supported, use readPixelsToBuffer(framebuffer)")(),null}},{key:"copyToDataUrl",value:function(){arguments.length>0&&void 0!==arguments[0]&&arguments[0];return I.k.error("Framebuffer.copyToDataUrl() is no logner supported, use copyToDataUrl(framebuffer)")(),null}},{key:"copyToImage",value:function(){arguments.length>0&&void 0!==arguments[0]&&arguments[0];return I.k.error("Framebuffer.copyToImage() is no logner supported, use copyToImage(framebuffer)")(),null}},{key:"copyToTexture",value:function(){arguments.length>0&&void 0!==arguments[0]&&arguments[0];return I.k.error("Framebuffer.copyToTexture({...}) is no logner supported, use copyToTexture(source, target, opts})")(),null}},{key:"blit",value:function(){arguments.length>0&&void 0!==arguments[0]&&arguments[0];return I.k.error("Framebuffer.blit({...}) is no logner supported, use blit(source, target, opts)")(),null}},{key:"invalidate",value:function(e){var t=e.attachments,A=void 0===t?[]:t,n=e.x,r=void 0===n?0:n,i=e.y,o=void 0===i?0:i,a=e.width,s=e.height,g=Object(I.a)(this.gl),c=g.bindFramebuffer(36008,this.handle);return 0===r&&0===o&&void 0===a&&void 0===s?g.invalidateFramebuffer(36008,A):g.invalidateFramebuffer(36008,A,r,o,a,s),g.bindFramebuffer(36008,c),this}},{key:"getAttachmentParameter",value:function(e,t,A){var n=this._getAttachmentParameterFallback(t);return null===n&&(this.gl.bindFramebuffer(36160,this.handle),n=this.gl.getFramebufferAttachmentParameter(36160,e,t),this.gl.bindFramebuffer(36160,null)),A&&n>1e3&&(n=Object(E.a)(this.gl,n)),n}},{key:"getAttachmentParameters",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:36064,A=arguments.length>1?arguments[1]:void 0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.constructor.ATTACHMENT_PARAMETERS||[],r={},o=Object(i.a)(n);try{for(o.s();!(e=o.n()).done;){var a=e.value,s=A?Object(E.a)(this.gl,a):a;r[s]=this.getAttachmentParameter(t,a,A)}}catch(g){o.e(g)}finally{o.f()}return r}},{key:"getParameters",value:function(){for(var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=Object.keys(this.attachments),A={},n=0,r=t;n0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(e>I.k.level||"undefined"===typeof window)return this;t=t||"Framebuffer ".concat(this.id);var A=Object(B.a)(this,{targetMaxHeight:100});return I.k.image({logLevel:e,message:t,image:A},t)(),this}},{key:"bind",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.target,A=void 0===t?36160:t;return this.gl.bindFramebuffer(A,this.handle),this}},{key:"unbind",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.target,A=void 0===t?36160:t;return this.gl.bindFramebuffer(A,null),this}},{key:"_createDefaultAttachments",value:function(e,t,A,r,i){var o,a=null;e&&((a=a||{})[36064]=new h.a(this.gl,{id:"".concat(this.id,"-color0"),pixels:null,format:6408,type:5121,width:r,height:i,mipmaps:!1,parameters:(o={},Object(n.a)(o,10241,9729),Object(n.a)(o,10240,9729),Object(n.a)(o,10242,33071),Object(n.a)(o,10243,33071),o)}),this.ownResources.push(a[36064]));return t&&A?((a=a||{})[33306]=new f.a(this.gl,{id:"".concat(this.id,"-depth-stencil"),format:35056,width:r,height:111}),this.ownResources.push(a[33306])):t?((a=a||{})[36096]=new f.a(this.gl,{id:"".concat(this.id,"-depth"),format:33189,width:r,height:i}),this.ownResources.push(a[36096])):A&&Object(Q.a)(!1),a}},{key:"_unattach",value:function(e){var t=this.attachments[e];t&&(t instanceof f.a?this.gl.framebufferRenderbuffer(36160,e,36161,null):this.gl.framebufferTexture2D(36160,e,3553,null,0),delete this.attachments[e])}},{key:"_attachRenderbuffer",value:function(e){var t=e.attachment,A=void 0===t?36064:t,n=e.renderbuffer;this.gl.framebufferRenderbuffer(36160,A,36161,n.handle),this.attachments[A]=n}},{key:"_attachTexture",value:function(e){var t=e.attachment,A=void 0===t?36064:t,n=e.texture,r=e.layer,i=e.level,o=this.gl;switch(o.bindTexture(n.target,n.handle),n.target){case 35866:case 32879:Object(I.a)(o).framebufferTextureLayer(36160,A,n.target,i,r);break;case 34067:var a=function(e){return e<34069?e+34069:e}(r);o.framebufferTexture2D(36160,A,a,n.handle,i);break;case 3553:o.framebufferTexture2D(36160,A,3553,n.handle,i);break;default:Object(Q.a)(!1,"Illegal texture type")}o.bindTexture(n.target,null),this.attachments[A]=n}},{key:"_setReadBuffer",value:function(e){var t=Object(I.g)(this.gl);t?t.readBuffer(e):Object(Q.a)(36064===e||1029===e,"Multiple render targets not supported"),this.readBuffer=e}},{key:"_setDrawBuffers",value:function(e){var t=this.gl,A=Object(I.a)(t);if(A)A.drawBuffers(e);else{var n=t.getExtension("WEBGL_draw_buffers");n?n.drawBuffersWEBGL(e):Object(Q.a)(1===e.length&&(36064===e[0]||1029===e[0]),"Multiple render targets not supported")}this.drawBuffers=e}},{key:"_getAttachmentParameterFallback",value:function(e){var t=Object(p.a)(this.gl);switch(e){case 36052:return t.WEBGL2?null:0;case 33298:case 33299:case 33300:case 33301:case 33302:case 33303:return t.WEBGL2?null:8;case 33297:return t.WEBGL2?null:5125;case 33296:return t.WEBGL2||t.EXT_sRGB?null:9729;default:return null}}},{key:"_createHandle",value:function(){return this.gl.createFramebuffer()}},{key:"_deleteHandle",value:function(){this.gl.deleteFramebuffer(this.handle)}},{key:"_bindHandle",value:function(e){return this.gl.bindFramebuffer(36160,e)}},{key:"color",get:function(){return this.attachments[36064]||null}},{key:"texture",get:function(){return this.attachments[36064]||null}},{key:"depth",get:function(){return this.attachments[36096]||this.attachments[33306]||null}},{key:"stencil",get:function(){return this.attachments[36128]||this.attachments[33306]||null}}]),A}(C.a);function v(e){return(y.STATUS||{})[e]||"Framebuffer error ".concat(e)}y.ATTACHMENT_PARAMETERS=[36049,36048,33296,33298,33299,33300,33301,33302,33303]},function(e,t,A){"use strict";A.d(t,"a",(function(){return s}));var n=A(7),r=A(1),i=A(4);function o(){}var a={onStart:o,onUpdate:o,onInterrupt:o,onEnd:o},s=function(){function e(t){Object(r.a)(this,e),this._inProgress=!1,this._handle=null,this.timeline=t,this.settings={}}return Object(i.a)(e,[{key:"start",value:function(e){this.cancel(),this.settings=Object(n.a)({},a,{},e),this._inProgress=!0,this.settings.onStart(this)}},{key:"end",value:function(){this._inProgress&&(this.timeline.removeChannel(this._handle),this._handle=null,this._inProgress=!1,this.settings.onEnd(this))}},{key:"cancel",value:function(){this._inProgress&&(this.settings.onInterrupt(this),this.timeline.removeChannel(this._handle),this._handle=null,this._inProgress=!1)}},{key:"update",value:function(){if(!this._inProgress)return!1;if(null===this._handle){var e=this.timeline,t=this.settings;this._handle=e.addChannel({delay:e.getTime(),duration:t.duration})}return this.time=this.timeline.getTime(this._handle),this._onUpdate(),this.settings.onUpdate(this),this.timeline.isFinished(this._handle)&&this.end(),!0}},{key:"_onUpdate",value:function(){}},{key:"inProgress",get:function(){return this._inProgress}}]),e}()},function(e,t,A){"use strict";function n(e,t){if(e===t)return!0;if(!e||!t)return!1;for(var A in e){var r=e[A],i=t[A];if(!(r===i||Array.isArray(r)&&Array.isArray(i)&&n(r,i)))return!1}return!0}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return s}));var n=A(3),r=A.n(n),i=A(12),o=A(1),a=A(4),s=function(){function e(){Object(o.a)(this,e)}return Object(a.a)(e,[{key:"fetch",value:function(){var e=Object(i.a)(r.a.mark((function e(t){var A,n=this,i=arguments;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=i.length>1&&void 0!==i[1]?i[1]:void 0,e.next=3,Promise.all(t.map((function(e){return n.fetchSlice(e,A)})));case 3:return e.abrupt("return",e.sent);case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()},{key:"fetchSlice",value:function(){var e=Object(i.a)(r.a.mark((function e(t){return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:throw new Error("fetching of slice ".concat(t," not possible, not implemented"));case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()},{key:"close",value:function(){var e=Object(i.a)(r.a.mark((function e(){return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}()},{key:"fileSize",get:function(){return null}}]),e}()},function(e,t,A){"use strict";function n(){for(var e=arguments.length,t=new Array(e),A=0;A1?(U[e]=t,this):Object(a.w)(U,e)?U[e]:null}function M(e){var t=_(e);return t&&t.responseType||"text"}function O(e,t,A,n){var r=_((t=t||{}).type||"json");return r||Object(a.o)("Unknown data format type: "+t.type),e=r(e,t),t.parse&&function(e,t,A,n){if(!e.length)return;var r=Object(c.e)();A=A||r.timeParse,n=n||r.utcParse;var i,o,a,s,g,u,l=e.columns||Object.keys(e[0]);"auto"===t&&(t=R(e,l));var I=(l=Object.keys(t)).map((function(e){var r,i,o=t[e];if(o&&(o.startsWith("date:")||o.startsWith("utc:")))return("'"===(i=(r=o.split(/:(.+)?/,2))[1])[0]&&"'"===i[i.length-1]||'"'===i[0]&&'"'===i[i.length-1])&&(i=i.slice(1,-1)),("utc"===r[0]?n:A)(i);if(!b[o])throw Error("Illegal format pattern: "+e+":"+o);return b[o]}));for(a=0,g=e.length,u=l.length;a=0))throw new Error("length must be a positive number");return function(e,t){void 0===t&&(t="kilometers");var A=n[t];if(!A)throw new Error(t+" units is invalid");return e*A}(o(e,t),A)}function g(e){return!isNaN(e)&&null!==e&&!Array.isArray(e)}t.a=function(e,t,A,n){void 0===n&&(n={});var r=t<0,o=s(Math.abs(t),n.units,"meters");r&&(o=-Math.abs(o));var g=function(e){if(!e)throw new Error("coord is required");if(!Array.isArray(e)){if("Feature"===e.type&&null!==e.geometry&&"Point"===e.geometry.type)return e.geometry.coordinates;if("Point"===e.type)return e.coordinates}if(Array.isArray(e)&&e.length>=2&&!Array.isArray(e[0])&&!Array.isArray(e[1]))return e;throw new Error("coord must be GeoJSON Point or an Array of numbers")}(e),c=function(e,t,A,n){n=void 0===n?6371008.8:Number(n);var r=t/n,i=e[0]*Math.PI/180,o=a(e[1]),s=a(A),g=r*Math.cos(s),c=o+g;Math.abs(c)>Math.PI/2&&(c=c>0?Math.PI-c:-Math.PI-c);var u=Math.log(Math.tan(c/2+Math.PI/4)/Math.tan(o/2+Math.PI/4)),l=Math.abs(u)>1e-11?g/u:Math.cos(o),I=r*Math.sin(s)/l;return[(180*(i+I)/Math.PI+540)%360-180,180*c/Math.PI]}(g,o,A);return c[0]+=c[0]-g[0]>180?-360:g[0]-c[0]>180?360:0,i(c,n.properties)}},function(e,t,A){"use strict";A.d(t,"a",(function(){return r})),A.d(t,"b",(function(){return i})),A.d(t,"c",(function(){return o})),A.d(t,"d",(function(){return a}));var n=A(30);function r(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[2]*r,e[1]=A[1]*n+A[3]*r,e}function i(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[2]*r+A[4],e[1]=A[1]*n+A[3]*r+A[5],e}function o(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[3]*r+A[6],e[1]=A[1]*n+A[4]*r+A[7],e}function a(e,t,A){var n=t[0],r=t[1];return e[0]=A[0]*n+A[4]*r+A[12],e[1]=A[1]*n+A[5]*r+A[13],e}!function(){var e=function(){var e=new n.a(2);return n.a!=Float32Array&&(e[0]=0,e[1]=0),e}()}()},function(e,t,A){"use strict";A.d(t,"b",(function(){return s})),A.d(t,"a",(function(){return g}));var n=A(3),r=A.n(n),i=A(12),o=A(1),a=A(4),s=function(){function e(){Object(o.a)(this,e)}return Object(a.a)(e,[{key:"getHeader",value:function(e){throw new Error("not implemented")}},{key:"getData",value:function(){var e=Object(i.a)(r.a.mark((function e(){return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:throw new Error("not implemented");case 1:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}()},{key:"ok",get:function(){return this.status>=200&&this.status<=299}},{key:"status",get:function(){throw new Error("not implemented")}}]),e}(),g=function(){function e(t){Object(o.a)(this,e),this.url=t}return Object(a.a)(e,[{key:"request",value:function(){var e=Object(i.a)(r.a.mark((function e(){var t,A=arguments;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:throw t=A.length>0&&void 0!==A[0]?A[0]:{},t.headers,t.credentials,t.signal,new Error("request is not implemented");case 2:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}()}]),e}()},,function(e,t,A){(function(t){for(var n=A(964),r="undefined"===typeof window?t:window,i=["moz","webkit"],o="AnimationFrame",a=r["request"+o],s=r["cancel"+o]||r["cancelRequest"+o],g=0;!a&&g=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|e}function C(e,t){if(s.isBuffer(e))return e.length;if("undefined"!==typeof ArrayBuffer&&"function"===typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!==typeof e&&(e=""+e);var A=e.length;if(0===A)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":case void 0:return T(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*A;case"hex":return A>>>1;case"base64":return Z(e).length;default:if(n)return T(e).length;t=(""+t).toLowerCase(),n=!0}}function h(e,t,A){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===A||A>this.length)&&(A=this.length),A<=0)return"";if((A>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,A);case"utf8":case"utf-8":return w(this,t,A);case"ascii":return S(this,t,A);case"latin1":case"binary":return F(this,t,A);case"base64":return b(this,t,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,t,A);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function f(e,t,A){var n=e[t];e[t]=e[A],e[A]=n}function d(e,t,A,n,r){if(0===e.length)return-1;if("string"===typeof A?(n=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,isNaN(A)&&(A=r?0:e.length-1),A<0&&(A=e.length+A),A>=e.length){if(r)return-1;A=e.length-1}else if(A<0){if(!r)return-1;A=0}if("string"===typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:B(e,t,A,n,r);if("number"===typeof t)return t&=255,s.TYPED_ARRAY_SUPPORT&&"function"===typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,A):Uint8Array.prototype.lastIndexOf.call(e,t,A):B(e,[t],A,n,r);throw new TypeError("val must be string, number or Buffer")}function B(e,t,A,n,r){var i,o=1,a=e.length,s=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;o=2,a/=2,s/=2,A/=2}function g(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(r){var c=-1;for(i=A;ia&&(A=a-s),i=A;i>=0;i--){for(var u=!0,l=0;lr&&(n=r):n=r;var i=t.length;if(i%2!==0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var o=0;o>8,r=A%256,i.push(r),i.push(n);return i}(t,e.length-A),e,A,n)}function b(e,t,A){return 0===t&&A===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,A))}function w(e,t,A){A=Math.min(e.length,A);for(var n=[],r=t;r239?4:g>223?3:g>191?2:1;if(r+u<=A)switch(u){case 1:g<128&&(c=g);break;case 2:128===(192&(i=e[r+1]))&&(s=(31&g)<<6|63&i)>127&&(c=s);break;case 3:i=e[r+1],o=e[r+2],128===(192&i)&&128===(192&o)&&(s=(15&g)<<12|(63&i)<<6|63&o)>2047&&(s<55296||s>57343)&&(c=s);break;case 4:i=e[r+1],o=e[r+2],a=e[r+3],128===(192&i)&&128===(192&o)&&128===(192&a)&&(s=(15&g)<<18|(63&i)<<12|(63&o)<<6|63&a)>65535&&s<1114112&&(c=s)}null===c?(c=65533,u=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),r+=u}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var A="",n=0;for(;n0&&(e=this.toString("hex",0,A).match(/.{2}/g).join(" "),this.length>A&&(e+=" ... ")),""},s.prototype.compare=function(e,t,A,n,r){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===A&&(A=e?e.length:0),void 0===n&&(n=0),void 0===r&&(r=this.length),t<0||A>e.length||n<0||r>this.length)throw new RangeError("out of range index");if(n>=r&&t>=A)return 0;if(n>=r)return-1;if(t>=A)return 1;if(this===e)return 0;for(var i=(r>>>=0)-(n>>>=0),o=(A>>>=0)-(t>>>=0),a=Math.min(i,o),g=this.slice(n,r),c=e.slice(t,A),u=0;ur)&&(A=r),e.length>0&&(A<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return p(this,e,t,A);case"utf8":case"utf-8":return E(this,e,t,A);case"ascii":return Q(this,e,t,A);case"latin1":case"binary":return y(this,e,t,A);case"base64":return v(this,e,t,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return m(this,e,t,A);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function S(e,t,A){var n="";A=Math.min(e.length,A);for(var r=t;rn)&&(A=n);for(var r="",i=t;iA)throw new RangeError("Trying to access beyond buffer length")}function k(e,t,A,n,r,i){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError("Index out of range")}function x(e,t,A,n){t<0&&(t=65535+t+1);for(var r=0,i=Math.min(e.length-A,2);r>>8*(n?r:1-r)}function N(e,t,A,n){t<0&&(t=4294967295+t+1);for(var r=0,i=Math.min(e.length-A,4);r>>8*(n?r:3-r)&255}function U(e,t,A,n,r,i){if(A+n>e.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function _(e,t,A,n,i){return i||U(e,0,A,4),r.write(e,t,A,n,23,4),A+4}function M(e,t,A,n,i){return i||U(e,0,A,8),r.write(e,t,A,n,52,8),A+8}s.prototype.slice=function(e,t){var A,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(r*=256);)n+=this[e+--t]*r;return n},s.prototype.readUInt8=function(e,t){return t||G(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return t||G(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return t||G(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return t||G(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return t||G(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,A){e|=0,t|=0,A||G(e,t,this.length);for(var n=this[e],r=1,i=0;++i=(r*=128)&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,A){e|=0,t|=0,A||G(e,t,this.length);for(var n=t,r=1,i=this[e+--n];n>0&&(r*=256);)i+=this[e+--n]*r;return i>=(r*=128)&&(i-=Math.pow(2,8*t)),i},s.prototype.readInt8=function(e,t){return t||G(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){t||G(e,2,this.length);var A=this[e]|this[e+1]<<8;return 32768&A?4294901760|A:A},s.prototype.readInt16BE=function(e,t){t||G(e,2,this.length);var A=this[e+1]|this[e]<<8;return 32768&A?4294901760|A:A},s.prototype.readInt32LE=function(e,t){return t||G(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return t||G(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return t||G(e,4,this.length),r.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return t||G(e,4,this.length),r.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return t||G(e,8,this.length),r.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return t||G(e,8,this.length),r.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,A,n){(e=+e,t|=0,A|=0,n)||k(this,e,t,A,Math.pow(2,8*A)-1,0);var r=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+r]=e/i&255;return t+A},s.prototype.writeUInt8=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,1,255,0),s.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,2,65535,0),s.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):x(this,e,t,!0),t+2},s.prototype.writeUInt16BE=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,2,65535,0),s.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):x(this,e,t,!1),t+2},s.prototype.writeUInt32LE=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,4,4294967295,0),s.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):N(this,e,t,!0),t+4},s.prototype.writeUInt32BE=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,4,4294967295,0),s.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},s.prototype.writeIntLE=function(e,t,A,n){if(e=+e,t|=0,!n){var r=Math.pow(2,8*A-1);k(this,e,t,A,r-1,-r)}var i=0,o=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+A},s.prototype.writeIntBE=function(e,t,A,n){if(e=+e,t|=0,!n){var r=Math.pow(2,8*A-1);k(this,e,t,A,r-1,-r)}var i=A-1,o=1,a=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+A},s.prototype.writeInt8=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,1,127,-128),s.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,2,32767,-32768),s.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):x(this,e,t,!0),t+2},s.prototype.writeInt16BE=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,2,32767,-32768),s.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):x(this,e,t,!1),t+2},s.prototype.writeInt32LE=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,4,2147483647,-2147483648),s.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):N(this,e,t,!0),t+4},s.prototype.writeInt32BE=function(e,t,A){return e=+e,t|=0,A||k(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),s.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):N(this,e,t,!1),t+4},s.prototype.writeFloatLE=function(e,t,A){return _(this,e,t,!0,A)},s.prototype.writeFloatBE=function(e,t,A){return _(this,e,t,!1,A)},s.prototype.writeDoubleLE=function(e,t,A){return M(this,e,t,!0,A)},s.prototype.writeDoubleBE=function(e,t,A){return M(this,e,t,!1,A)},s.prototype.copy=function(e,t,A,n){if(A||(A=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--r)e[r+t]=this[r+A];else if(i<1e3||!s.TYPED_ARRAY_SUPPORT)for(r=0;r>>=0,A=void 0===A?this.length:A>>>0,e||(e=0),"number"===typeof e)for(i=t;i55295&&A<57344){if(!r){if(A>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&i.push(239,191,189);continue}r=A;continue}if(A<56320){(t-=3)>-1&&i.push(239,191,189),r=A;continue}A=65536+(r-55296<<10|A-56320)}else r&&(t-=3)>-1&&i.push(239,191,189);if(r=null,A<128){if((t-=1)<0)break;i.push(A)}else if(A<2048){if((t-=2)<0)break;i.push(A>>6|192,63&A|128)}else if(A<65536){if((t-=3)<0)break;i.push(A>>12|224,A>>6&63|128,63&A|128)}else{if(!(A<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(A>>18|240,A>>12&63|128,A>>6&63|128,63&A|128)}}return i}function Z(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(O,"")).length<2)return"";for(;e.length%4!==0;)e+="=";return e}(e))}function H(e,t,A,n){for(var r=0;r=t.length||r>=e.length);++r)t[r+A]=e[r];return r}}).call(this,A(86))},function(e,t,A){"use strict";(function(e,n){A.d(t,"a",(function(){return i})),A.d(t,"b",(function(){return o}));var r={self:"undefined"!==typeof self&&self,window:"undefined"!==typeof window&&window,global:"undefined"!==typeof e&&e,document:"undefined"!==typeof document&&document},i=r.global||r.self||r.window||{},o="object"!==typeof n||"[object process]"!==String(n)||n.browser,a="undefined"!==typeof n&&n.version&&/v([0-9]*)/.exec(n.version);a&&parseFloat(a[1])}).call(this,A(86),A(90))},function(e,t){var A=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=A)},function(e,t){var A=e.exports={version:"2.6.11"};"number"==typeof __e&&(__e=A)},function(e,t,A){e.exports=!A(303)((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}))},function(e,t,A){var n=A(472),r=A(969),i=A(986),o=A(111);e.exports=function(e,t){return(o(e)?n:i)(e,r(t,3))}},function(e,t,A){"use strict";A.d(t,"d",(function(){return i})),A.d(t,"a",(function(){return o})),A.d(t,"b",(function(){return a})),A.d(t,"c",(function(){return s}));var n=A(6),r=A(219);function i(e){if(r.b(e)&&(e=r.a(e)),e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);if("string"===typeof e){var t=e;return(new TextEncoder).encode(t).buffer}if(e&&"object"===typeof e&&e._toArrayBuffer)return e._toArrayBuffer();throw new Error("toArrayBuffer")}function o(e,t,A){if(A=A||e.byteLength,e.byteLength0&&void 0!==arguments[0]?arguments[0]:0,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:A.DefaultOrder;(Object(r.a)(this,A),e=t.call(this,-0,-0,-0,-0),arguments.length>0&&Array.isArray(arguments[0]))?(n=e).fromVector3.apply(n,arguments):e.set(i,o,a,s);return e}return Object(i.a)(A,[{key:"ELEMENTS",get:function(){return 4}}],[{key:"rotationOrder",value:function(e){return A.RotationOrders[e]}},{key:"ZYX",get:function(){return 0}},{key:"YXZ",get:function(){return 1}},{key:"XZY",get:function(){return 2}},{key:"ZXY",get:function(){return 3}},{key:"YZX",get:function(){return 4}},{key:"XYZ",get:function(){return 5}},{key:"RollPitchYaw",get:function(){return 0}},{key:"DefaultOrder",get:function(){return A.ZYX}},{key:"RotationOrders",get:function(){return["ZYX","YXZ","XZY","ZXY","YZX","XYZ"]}}]),Object(i.a)(A,[{key:"fromQuaternion",value:function(e){var t=Object(n.a)(e,4),r=t[0],i=t[1],o=t[2],a=t[3],s=i*i,g=-2*(s+o*o)+1,c=2*(r*i+a*o),u=-2*(r*o-a*i),l=2*(i*o+a*r),I=-2*(r*r+s)+1;return u=(u=u>1?1:u)<-1?-1:u,new A(Math.atan2(l,I),Math.asin(u),Math.atan2(c,g),A.RollPitchYaw)}},{key:"copy",value:function(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=Number.isFinite(e[3])||this.order,this.check()}},{key:"set",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3?arguments[3]:void 0;return this[0]=e,this[1]=t,this[2]=A,this[3]=Number.isFinite(n)?n:this[3],this.check()}},{key:"validate",value:function(){return(e=this[3])>=0&&e<6&&Number.isFinite(this[0])&&Number.isFinite(this[1])&&Number.isFinite(this[2]);var e}},{key:"toArray",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e[t]=this[0],e[t+1]=this[1],e[t+2]=this[2],e}},{key:"toArray4",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e[t]=this[0],e[t+1]=this[1],e[t+2]=this[2],e[t+3]=this[3],e}},{key:"toVector3",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[-0,-0,-0];return e[0]=this[0],e[1]=this[1],e[2]=this[2],e}},{key:"fromVector3",value:function(e,t){return this.set(e[0],e[1],e[2],Number.isFinite(t)?t:this[3])}},{key:"fromArray",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return this[0]=e[0+t],this[1]=e[1+t],this[2]=e[2+t],void 0!==e[3]&&(this[3]=e[3]),this.check()}},{key:"fromRollPitchYaw",value:function(e,t,n){return this.set(e,t,n,A.ZYX)}},{key:"fromRotationMatrix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:A.DefaultOrder;return this._fromRotationMatrix(e,t),this.check()}},{key:"getRotationMatrix",value:function(e){return this._getRotationMatrix(e)}},{key:"getQuaternion",value:function(){var e=new u.a;switch(this[3]){case A.XYZ:return e.rotateX(this[0]).rotateY(this[1]).rotateZ(this[2]);case A.YXZ:return e.rotateY(this[0]).rotateX(this[1]).rotateZ(this[2]);case A.ZXY:return e.rotateZ(this[0]).rotateX(this[1]).rotateY(this[2]);case A.ZYX:return e.rotateZ(this[0]).rotateY(this[1]).rotateX(this[2]);case A.YZX:return e.rotateY(this[0]).rotateZ(this[1]).rotateX(this[2]);case A.XZY:return e.rotateX(this[0]).rotateZ(this[1]).rotateY(this[2]);default:throw new Error(l)}}},{key:"_fromRotationMatrix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:A.DefaultOrder,n=e.elements,r=n[0],i=n[4],o=n[8],a=n[1],s=n[5],c=n[9],u=n[2],I=n[6],C=n[10];switch(t=t||this[3]){case A.XYZ:this[1]=Math.asin(Object(g.d)(o,-1,1)),Math.abs(o)<.99999?(this[0]=Math.atan2(-c,C),this[2]=Math.atan2(-i,r)):(this[0]=Math.atan2(I,s),this[2]=0);break;case A.YXZ:this[0]=Math.asin(-Object(g.d)(c,-1,1)),Math.abs(c)<.99999?(this[1]=Math.atan2(o,C),this[2]=Math.atan2(a,s)):(this[1]=Math.atan2(-u,r),this[2]=0);break;case A.ZXY:this[0]=Math.asin(Object(g.d)(I,-1,1)),Math.abs(I)<.99999?(this[1]=Math.atan2(-u,C),this[2]=Math.atan2(-i,s)):(this[1]=0,this[2]=Math.atan2(a,r));break;case A.ZYX:this[1]=Math.asin(-Object(g.d)(u,-1,1)),Math.abs(u)<.99999?(this[0]=Math.atan2(I,C),this[2]=Math.atan2(a,r)):(this[0]=0,this[2]=Math.atan2(-i,s));break;case A.YZX:this[2]=Math.asin(Object(g.d)(a,-1,1)),Math.abs(a)<.99999?(this[0]=Math.atan2(-c,s),this[1]=Math.atan2(-u,r)):(this[0]=0,this[1]=Math.atan2(o,C));break;case A.XZY:this[2]=Math.asin(-Object(g.d)(i,-1,1)),Math.abs(i)<.99999?(this[0]=Math.atan2(I,s),this[1]=Math.atan2(o,r)):(this[0]=Math.atan2(-c,C),this[1]=0);break;default:throw new Error(l)}return this[3]=t,this}},{key:"_getRotationMatrix",value:function(e){var t=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0],n=this.x,r=this.y,i=this.z,o=Math.cos(n),a=Math.cos(r),s=Math.cos(i),g=Math.sin(n),c=Math.sin(r),u=Math.sin(i);switch(this[3]){case A.XYZ:var I=o*s,C=o*u,h=g*s,f=g*u;t[0]=a*s,t[4]=-a*u,t[8]=c,t[1]=C+h*c,t[5]=I-f*c,t[9]=-g*a,t[2]=f-I*c,t[6]=h+C*c,t[10]=o*a;break;case A.YXZ:var d=a*s,B=a*u,p=c*s,E=c*u;t[0]=d+E*g,t[4]=p*g-B,t[8]=o*c,t[1]=o*u,t[5]=o*s,t[9]=-g,t[2]=B*g-p,t[6]=E+d*g,t[10]=o*a;break;case A.ZXY:var Q=a*s,y=a*u,v=c*s,m=c*u;t[0]=Q-m*g,t[4]=-o*u,t[8]=v+y*g,t[1]=y+v*g,t[5]=o*s,t[9]=m-Q*g,t[2]=-o*c,t[6]=g,t[10]=o*a;break;case A.ZYX:var b=o*s,w=o*u,S=g*s,F=g*u;t[0]=a*s,t[4]=S*c-w,t[8]=b*c+F,t[1]=a*u,t[5]=F*c+b,t[9]=w*c-S,t[2]=-c,t[6]=g*a,t[10]=o*a;break;case A.YZX:var R=o*a,D=o*c,G=g*a,k=g*c;t[0]=a*s,t[4]=k-R*u,t[8]=G*u+D,t[1]=u,t[5]=o*s,t[9]=-g*s,t[2]=-c*s,t[6]=D*u+G,t[10]=R-k*u;break;case A.XZY:var x=o*a,N=o*c,U=g*a,_=g*c;t[0]=a*s,t[4]=-u,t[8]=c*s,t[1]=x*u+_,t[5]=o*s,t[9]=N*u-U,t[2]=U*u-N,t[6]=g*s,t[10]=_*u+x;break;default:throw new Error(l)}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}},{key:"toQuaternion",value:function(){var e=Math.cos(.5*this.yaw),t=Math.sin(.5*this.yaw),A=Math.cos(.5*this.roll),n=Math.sin(.5*this.roll),r=Math.cos(.5*this.pitch),i=Math.sin(.5*this.pitch),o=e*A*r+t*n*i,a=e*n*r-t*A*i,s=e*A*i+t*n*r,g=t*A*r-e*n*i;return new u.a(a,s,g,o)}},{key:"x",get:function(){return this[0]},set:function(e){this[0]=Object(c.a)(e)}},{key:"y",get:function(){return this[1]},set:function(e){this[1]=Object(c.a)(e)}},{key:"z",get:function(){return this[2]},set:function(e){this[2]=Object(c.a)(e)}},{key:"alpha",get:function(){return this[0]},set:function(e){this[0]=Object(c.a)(e)}},{key:"beta",get:function(){return this[1]},set:function(e){this[1]=Object(c.a)(e)}},{key:"gamma",get:function(){return this[2]},set:function(e){this[2]=Object(c.a)(e)}},{key:"phi",get:function(){return this[0]},set:function(e){this[0]=Object(c.a)(e)}},{key:"theta",get:function(){return this[1]},set:function(e){this[1]=Object(c.a)(e)}},{key:"psi",get:function(){return this[2]},set:function(e){this[2]=Object(c.a)(e)}},{key:"roll",get:function(){return this[0]},set:function(e){this[0]=Object(c.a)(e)}},{key:"pitch",get:function(){return this[1]},set:function(e){this[1]=Object(c.a)(e)}},{key:"yaw",get:function(){return this[2]},set:function(e){this[2]=Object(c.a)(e)}},{key:"order",get:function(){return this[3]},set:function(e){this[3]=function(e){if(e<0&&e>=6)throw new Error(l);return e}(e)}}]),A}(s.a)},function(e,t,A){"use strict";A.d(t,"a",(function(){return o}));var n=A(7),r=A(1),i=A(4),o=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(r.a)(this,e);var A=t.id,i=void 0===A?"effect":A;this.id=i,this.props=Object(n.a)({},t)}return Object(i.a)(e,[{key:"preRender",value:function(){}},{key:"getModuleParameters",value:function(){}},{key:"cleanup",value:function(){}}]),e}()},function(e,t,A){"use strict";A.d(t,"a",(function(){return u}));var n=A(6),r=A(1),i=A(4),o=A(9),a=A(10),s=A(410),g=A(18),c=A(428),u=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(){return Object(r.a)(this,A),t.apply(this,arguments)}return Object(i.a)(A,[{key:"render",value:function(e){var t=this.gl;return Object(g.n)(t,{framebuffer:e.target}),this._drawLayers(e)}},{key:"_drawLayers",value:function(e){var t=e.viewports,A=e.views,r=e.onViewportActive,i=e.clearCanvas,o=void 0===i||i;e.pass=e.pass||"unknown";var a=this.gl;o&&function(e){var t=e.drawingBufferWidth,A=e.drawingBufferHeight;Object(g.n)(e,{viewport:[0,0,t,A]}),e.clear(16640)}(a);var s,c=[],u=Object(n.a)(t);try{for(u.s();!(s=u.n()).done;){var l=s.value,I=l.viewport||l,C=A&&A[I.id];r(I);var h=this._getDrawLayerParams(I,e);e.view=C;var f,d=I.subViewports||[I],B=Object(n.a)(d);try{for(B.s();!(f=B.n()).done;){var p=f.value;e.viewport=p;var E=this._drawLayersInViewport(a,e,h);c.push(E)}}catch(Q){B.e(Q)}finally{B.f()}}}catch(Q){u.e(Q)}finally{u.f()}return c}},{key:"_getDrawLayerParams",value:function(e,t){for(var A=t.layers,n=t.pass,r=t.layerFilter,i=t.effects,o=t.moduleParameters,a=[],s=function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={},r=function r(i,o){var a,s=i.props._offset,g=i.id,c=i.parent&&i.parent.id;if(c&&!(c in A)&&r(i.parent,!1),c in n){var u=n[c]=n[c]||e(A[c],A);a=u(i,o),n[g]=u}else Number.isFinite(s)?(a=s+(A[c]||0),n[g]=null):a=t;return o&&a>=t&&(t=a+1),A[g]=a,a};return r}(),g={viewport:e,isPicking:n.startsWith("picking"),renderPass:n},c={},u=0;u=0||(r[A]=e[A]);return r}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";var n=A(716),r=Object(n.a)();t.a=r},function(e,t,A){"use strict";A.d(t,"a",(function(){return g}));var n=A(1),r=A(4),i=A(9),o=A(10),a=A(32),s=A(97);var g=function(e){Object(i.a)(A,e);var t=Object(o.a)(A);function A(){return Object(n.a)(this,A),t.apply(this,arguments)}return Object(r.a)(A,[{key:"clone",value:function(){return(new this.constructor).copy(this)}},{key:"from",value:function(e){return Array.isArray(e)?this.copy(e):this.fromObject(e)}},{key:"fromArray",value:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,A=0;A0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,A=0;A0?", ":"")+Object(a.l)(this[A],e);return"".concat(e.printTypes?this.constructor.name:"","[").concat(t,"]")}},{key:"equals",value:function(e){if(!e||this.length!==e.length)return!1;for(var t=0;t0&&void 0!==arguments[0]?arguments[0]:0,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return Object(n.a)(this,A),e=t.call(this,-0,-0,-0),1===arguments.length&&Object(s.m)(r)?e.copy(r):(s.f.debug&&(Object(g.a)(r),Object(g.a)(i),Object(g.a)(o)),e[0]=r,e[1]=i,e[2]=o),e}return Object(r.a)(A,null,[{key:"ZERO",get:function(){return I.ZERO=I.ZERO||Object.freeze(new A(0,0,0,0))}}]),Object(r.a)(A,[{key:"set",value:function(e,t,A){return this[0]=e,this[1]=t,this[2]=A,this.check()}},{key:"copy",value:function(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this.check()}},{key:"fromObject",value:function(e){return s.f.debug&&(Object(g.a)(e.x),Object(g.a)(e.y),Object(g.a)(e.z)),this[0]=e.x,this[1]=e.y,this[2]=e.z,this.check()}},{key:"toObject",value:function(e){return e.x=this[0],e.y=this[1],e.z=this[2],e}},{key:"angle",value:function(e){return c.a(this,e)}},{key:"cross",value:function(e){return c.c(this,this,e),this.check()}},{key:"rotateX",value:function(e){var t=e.radians,A=e.origin,n=void 0===A?l:A;return c.i(this,this,n,t),this.check()}},{key:"rotateY",value:function(e){var t=e.radians,A=e.origin,n=void 0===A?l:A;return c.j(this,this,n,t),this.check()}},{key:"rotateZ",value:function(e){var t=e.radians,A=e.origin,n=void 0===A?l:A;return c.k(this,this,n,t),this.check()}},{key:"transform",value:function(e){return this.transformAsPoint(e)}},{key:"transformAsPoint",value:function(e){return c.m(this,this,e),this.check()}},{key:"transformAsVector",value:function(e){return Object(u.c)(this,this,e),this.check()}},{key:"transformByMatrix3",value:function(e){return c.l(this,this,e),this.check()}},{key:"transformByMatrix2",value:function(e){return Object(u.b)(this,this,e),this.check()}},{key:"transformByQuaternion",value:function(e){return c.n(this,this,e),this.check()}},{key:"ELEMENTS",get:function(){return 3}},{key:"z",get:function(){return this[2]},set:function(e){this[2]=Object(g.a)(e)}}]),A}(a.a)},function(e,t,A){"use strict";A.d(t,"a",(function(){return g}));var n=A(1),r=A(4),i=A(23),o=[255,255,255],a=[0,0,-1],s=0,g=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(n.a)(this,e);var A=t.color,r=void 0===A?o:A,g=t.intensity,c=void 0===g?1:g,u=t.direction,l=void 0===u?a:u,I=t._shadow,C=void 0!==I&&I;this.id=t.id||"directional-".concat(s++),this.color=r,this.intensity=c,this.type="directional",this.direction=new i.Vector3(l).normalize().toArray(),this.shadow=C}return Object(r.a)(e,[{key:"getProjectedLight",value:function(){return this}}]),e}()},function(e,t,A){"use strict";var n=A(1245),r={name:"geometry",vs:"\nstruct VertexGeometry {\n vec4 position;\n vec3 worldPosition;\n vec3 worldPositionAlt;\n vec3 normal;\n vec2 uv;\n vec3 pickingColor;\n} geometry = VertexGeometry(\n vec4(0.0),\n vec3(0.0),\n vec3(0.0),\n vec3(0.0),\n vec2(0.0),\n vec3(0.0)\n);\n",fs:"\n#define SMOOTH_EDGE_RADIUS 0.5\n\nstruct FragmentGeometry {\n vec2 uv;\n} geometry;\n\nfloat smoothedge(float edge, float x) {\n return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x);\n}\n"},i=A(36),o=Object.keys(i.a).map((function(e){return"const int COORDINATE_SYSTEM_".concat(e," = ").concat(i.a[e],";")})).join(""),a=Object.keys(i.c).map((function(e){return"const int PROJECTION_MODE_".concat(e," = ").concat(i.c[e],";")})).join(""),s=Object.keys(i.d).map((function(e){return"const int UNIT_".concat(e.toUpperCase()," = ").concat(i.d[e],";")})).join(""),g="".concat(o,"\n").concat(a,"\n").concat(s,"\n\nuniform int project_uCoordinateSystem;\nuniform int project_uProjectionMode;\nuniform float project_uScale;\nuniform bool project_uWrapLongitude;\nuniform vec3 project_uCommonUnitsPerMeter;\nuniform vec3 project_uCommonUnitsPerWorldUnit;\nuniform vec3 project_uCommonUnitsPerWorldUnit2;\nuniform vec4 project_uCenter;\nuniform mat4 project_uModelMatrix;\nuniform mat4 project_uViewProjectionMatrix;\nuniform vec2 project_uViewportSize;\nuniform float project_uDevicePixelRatio;\nuniform float project_uFocalDistance;\nuniform vec3 project_uCameraPosition;\nuniform vec3 project_uCoordinateOrigin;\nuniform vec3 project_uCommonOrigin;\nuniform bool project_uPseudoMeters;\n\nconst float TILE_SIZE = 512.0;\nconst float PI = 3.1415926536;\nconst float WORLD_SCALE = TILE_SIZE / (PI * 2.0);\nconst vec3 ZERO_64_LOW = vec3(0.0);\nconst float EARTH_RADIUS = 6370972.0;\nconst float GLOBE_RADIUS = 256.0;\nfloat project_size() {\n if (project_uProjectionMode == PROJECTION_MODE_WEB_MERCATOR &&\n project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT &&\n project_uPseudoMeters == false) {\n \n if (geometry.position.w == 0.0) {\n float y = clamp(geometry.worldPosition.y, -89.9, 89.9);\n return 1.0 / cos(radians(y));\n }\n \n float y = geometry.position.y / TILE_SIZE * 2.0 - 1.0;\n float y2 = y * y;\n float y4 = y2 * y2;\n float y6 = y4 * y2;\n return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6;\n }\n return 1.0;\n}\nfloat project_size(float meters) {\n return meters * project_uCommonUnitsPerMeter.z * project_size();\n}\n\nvec2 project_size(vec2 meters) {\n return meters * project_uCommonUnitsPerMeter.xy * project_size();\n}\n\nvec3 project_size(vec3 meters) {\n return meters * project_uCommonUnitsPerMeter * project_size();\n}\n\nvec4 project_size(vec4 meters) {\n return vec4(meters.xyz * project_uCommonUnitsPerMeter, meters.w);\n}\nvec3 project_normal(vec3 vector) {\n vec4 normal_modelspace = project_uModelMatrix * vec4(vector, 0.0);\n return normalize(normal_modelspace.xyz * project_uCommonUnitsPerMeter);\n}\n\nvec4 project_offset_(vec4 offset) {\n float dy = offset.y;\n vec3 commonUnitsPerWorldUnit = project_uCommonUnitsPerWorldUnit + project_uCommonUnitsPerWorldUnit2 * dy;\n return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w);\n}\nvec2 project_mercator_(vec2 lnglat) {\n float x = lnglat.x;\n if (project_uWrapLongitude) {\n x = mod(x + 180., 360.0) - 180.;\n }\n float y = clamp(lnglat.y, -89.9, 89.9);\n return vec2(\n radians(x) + PI,\n PI + log(tan_fp32(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\nvec3 project_globe_(vec3 lnglatz) {\n float lambda = radians(lnglatz.x);\n float phi = radians(lnglatz.y);\n float cosPhi = cos(phi);\n float D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS;\n\n return vec3(\n sin(lambda) * cosPhi,\n -cos(lambda) * cosPhi,\n sin(phi)\n ) * D;\n}\nvec4 project_position(vec4 position, vec3 position64Low) {\n vec4 position_world = project_uModelMatrix * position;\n if (project_uProjectionMode == PROJECTION_MODE_WEB_MERCATOR) {\n if (project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_mercator_(position_world.xy),\n project_size(position_world.z),\n position_world.w\n );\n }\n if (project_uCoordinateSystem == COORDINATE_SYSTEM_CARTESIAN) {\n position_world.xyz += project_uCoordinateOrigin;\n }\n }\n if (project_uProjectionMode == PROJECTION_MODE_GLOBE) {\n if (project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_globe_(position_world.xyz),\n position_world.w\n );\n }\n }\n if (project_uProjectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\n if (project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n if (abs(position_world.y - project_uCoordinateOrigin.y) > 0.25) {\n return vec4(\n project_mercator_(position_world.xy) - project_uCommonOrigin.xy,\n project_size(position_world.z),\n position_world.w\n );\n }\n }\n }\n if (project_uProjectionMode == PROJECTION_MODE_IDENTITY ||\n (project_uProjectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET &&\n (project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project_uCoordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) {\n position_world.xyz -= project_uCoordinateOrigin;\n }\n return project_offset_(position_world + project_uModelMatrix * vec4(position64Low, 0.0));\n}\n\nvec4 project_position(vec4 position) {\n return project_position(position, ZERO_64_LOW);\n}\n\nvec3 project_position(vec3 position, vec3 position64Low) {\n vec4 projected_position = project_position(vec4(position, 1.0), position64Low);\n return projected_position.xyz;\n}\n\nvec3 project_position(vec3 position) {\n vec4 projected_position = project_position(vec4(position, 1.0), ZERO_64_LOW);\n return projected_position.xyz;\n}\n\nvec2 project_position(vec2 position) {\n vec4 projected_position = project_position(vec4(position, 0.0, 1.0), ZERO_64_LOW);\n return projected_position.xy;\n}\n\nvec4 project_common_position_to_clipspace(vec4 position, mat4 viewProjectionMatrix, vec4 center) {\n return viewProjectionMatrix * position + center;\n}\nvec4 project_common_position_to_clipspace(vec4 position) {\n return project_common_position_to_clipspace(position, project_uViewProjectionMatrix, project_uCenter);\n}\nvec2 project_pixel_size_to_clipspace(vec2 pixels) {\n vec2 offset = pixels / project_uViewportSize * project_uDevicePixelRatio * 2.0;\n return offset * project_uFocalDistance;\n}\n\nfloat project_size_to_pixel(float meters) {\n return project_size(meters) * project_uScale;\n}\nfloat project_size_to_pixel(float size, int unit) {\n if (unit == UNIT_METERS) return project_size_to_pixel(size);\n if (unit == UNIT_COMMON) return size * project_uScale;\n return size;\n}\nfloat project_pixel_size(float pixels) {\n return pixels / project_uScale;\n}\nvec2 project_pixel_size(vec2 pixels) {\n return pixels / project_uScale;\n}\nmat3 project_get_orientation_matrix(vec3 up) {\n vec3 uz = normalize(up);\n vec3 ux = abs(uz.z) == 1.0 ? vec3(1.0, 0.0, 0.0) : normalize(vec3(uz.y, -uz.x, 0));\n vec3 uy = cross(uz, ux);\n return mat3(ux, uy, uz);\n}\n\nbool project_needs_rotation(vec3 commonPosition, out mat3 transform) {\n if (project_uProjectionMode == PROJECTION_MODE_GLOBE) {\n transform = project_get_orientation_matrix(commonPosition);\n return true;\n }\n return false;\n}\n"),c=A(274),u={};t.a={name:"project",dependencies:[n.a,r],vs:g,getUniforms:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:u;return e.viewport?Object(c.b)(e):{}}}},function(e,t,A){"use strict";var n=A(7),r=A(1),i=A(4),o=A(9),a=A(10),s=A(147),g=A(511),c=A(646),u=A(8),l=A(6),I=A(3),C=A.n(I),h=A(12),f=A(41),d=function(){function e(t){var A=t.x,n=t.y,i=t.z;Object(r.a)(this,e),this.x=A,this.y=n,this.z=i,this.isVisible=!1,this.isSelected=!1,this.parent=null,this.children=[],this.content=null,this._loaderId=0,this._isLoaded=!1,this._isCancelled=!1,this._needsReload=!1}return Object(i.a)(e,[{key:"_loadData",value:function(){var e=Object(h.a)(C.a.mark((function e(t){var A,n,r,i,o,a,s,g,c,u,l,I,h;return C.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=t.getData,n=t.requestScheduler,r=t.onLoad,i=t.onError,o=this.x,a=this.y,s=this.z,g=this.bbox,c=this._loaderId,this._abortController=new AbortController,u=this._abortController.signal,e.next=7,n.scheduleRequest(this,(function(e){return e.isSelected?1:-1}));case 7:if(l=e.sent){e.next=11;break}return this._isCancelled=!0,e.abrupt("return");case 11:if(!this._isCancelled){e.next=14;break}return l.done(),e.abrupt("return");case 14:return I=null,e.prev=15,e.next=18,A({x:o,y:a,z:s,bbox:g,signal:u});case 18:I=e.sent,e.next=24;break;case 21:e.prev=21,e.t0=e.catch(15),h=e.t0||!0;case 24:return e.prev=24,l.done(),e.finish(24);case 27:if(c===this._loaderId){e.next=29;break}return e.abrupt("return");case 29:if(this._loader=void 0,this.content=I,!this._isCancelled||I){e.next=34;break}return this._isLoaded=!1,e.abrupt("return");case 34:this._isLoaded=!0,this._isCancelled=!1,h?i(h,this):r(this);case 37:case"end":return e.stop()}}),e,this,[[15,21,24,27]])})));return function(t){return e.apply(this,arguments)}}()},{key:"loadData",value:function(e){return this._isLoaded=!1,this._isCancelled=!1,this._needsReload=!1,this._loaderId++,this._loader=this._loadData(e),this._loader}},{key:"setNeedsReload",value:function(){this.isLoading&&(this.abort(),this._loader=void 0),this._needsReload=!0}},{key:"abort",value:function(){this.isLoaded||(this._isCancelled=!0,this._abortController.abort())}},{key:"data",get:function(){var e=this;return this.isLoading?this._loader.then((function(){return e.data})):this.content}},{key:"isLoaded",get:function(){return this._isLoaded&&!this._needsReload}},{key:"isLoading",get:function(){return Boolean(this._loader)&&!this._isCancelled}},{key:"needsReload",get:function(){return this._needsReload||this._isCancelled}},{key:"byteLength",get:function(){var e=this.content?this.content.byteLength:0;return Number.isFinite(e)||f.a.error("byteLength not defined in tile data")(),e}}]),e}(),B=A(120),p=A(578),E=A(23),Q=function(){function e(t){var A=this;Object(r.a)(this,e),this.opts=t,this.onTileLoad=function(e){A.opts.onTileLoad(e),A.opts.maxCacheByteSize&&(A._cacheByteSize+=e.byteLength,A._resizeCache())},this._requestScheduler=new p.a({maxRequests:t.maxRequests,throttleRequests:t.maxRequests>0}),this._cache=new Map,this._tiles=[],this._dirty=!1,this._cacheByteSize=0,this._viewport=null,this._selectedTiles=null,this._frameNumber=0,this.setOptions(t)}return Object(i.a)(e,[{key:"setOptions",value:function(e){Object.assign(this.opts,e),Number.isFinite(e.maxZoom)&&(this._maxZoom=Math.floor(e.maxZoom)),Number.isFinite(e.minZoom)&&(this._minZoom=Math.ceil(e.minZoom))}},{key:"finalize",value:function(){var e,t=Object(l.a)(this._cache.values());try{for(t.s();!(e=t.n()).done;){var A=e.value;A.isLoading&&A.abort()}}catch(n){t.e(n)}finally{t.f()}this._cache.clear(),this._tiles=[],this._selectedTiles=null}},{key:"reloadAll",value:function(){var e,t=Object(l.a)(this._cache.keys());try{for(t.s();!(e=t.n()).done;){var A=e.value,n=this._cache.get(A);this._selectedTiles.includes(n)?n.setNeedsReload():this._cache.delete(A)}}catch(r){t.e(r)}finally{t.f()}}},{key:"update",value:function(e){var t=this,A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=A.zRange,r=A.modelMatrix,i=new E.Matrix4(r),o=!i.equals(this._modelMatrix);if(!e.equals(this._viewport)||o){o&&(this._modelMatrixInverse=r&&i.clone().invert(),this._modelMatrix=r&&i),this._viewport=e;var a=this.getTileIndices({viewport:e,maxZoom:this._maxZoom,minZoom:this._minZoom,zRange:n,modelMatrix:this._modelMatrix,modelMatrixInverse:this._modelMatrixInverse});this._selectedTiles=a.map((function(e){return t._getTile(e,!0)})),this._dirty&&this._rebuildTree()}var s=this.updateTileStates();return this._dirty&&this._resizeCache(),s&&this._frameNumber++,this._frameNumber}},{key:"getTileIndices",value:function(e){var t=e.viewport,A=e.maxZoom,n=e.minZoom,r=e.zRange,i=e.modelMatrix,o=e.modelMatrixInverse,a=this.opts,s=a.tileSize,g=a.extent,c=a.zoomOffset;return Object(B.a)({viewport:t,maxZoom:A,minZoom:n,zRange:r,tileSize:s,extent:g,modelMatrix:i,modelMatrixInverse:o,zoomOffset:c})}},{key:"getTileMetadata",value:function(e){var t=e.x,A=e.y,n=e.z,r=this.opts.tileSize;return{bbox:Object(B.e)(this._viewport,t,A,n,r)}}},{key:"getParentIndex",value:function(e){return e.x=Math.floor(e.x/2),e.y=Math.floor(e.y/2),e.z-=1,e}},{key:"updateTileStates",value:function(){this._updateTileStates(this.selectedTiles);var e,t=this.opts.maxRequests,A=[],n=0,r=!1,i=Object(l.a)(this._cache.values());try{for(i.s();!(e=i.n()).done;){var o=e.value,a=Boolean(1&o.state);o.isVisible!==a&&(r=!0,o.isVisible=a),o.isSelected=5===o.state,o.isLoading&&(n++,o.isSelected||A.push(o))}}catch(s){i.e(s)}finally{i.f()}if(t>0)for(;n>t&&A.length>0;){A.shift().abort(),n--}return r}},{key:"_rebuildTree",value:function(){var e,t=this._cache,A=Object(l.a)(t.values());try{for(A.s();!(e=A.n()).done;){var n=e.value;n.parent=null,n.children.length=0}}catch(s){A.e(s)}finally{A.f()}var r,i=Object(l.a)(t.values());try{for(i.s();!(r=i.n()).done;){var o=r.value,a=this._getNearestAncestor(o.x,o.y,o.z);o.parent=a,a&&a.children.push(o)}}catch(s){i.e(s)}finally{i.f()}}},{key:"_updateTileStates",value:function(e){var t,A=this._cache,n=this.opts.refinementStrategy||"best-available",r=Object(l.a)(A.values());try{for(r.s();!(t=r.n()).done;){t.value.state=0}}catch(I){r.e(I)}finally{r.f()}var i,o=Object(l.a)(e);try{for(o.s();!(i=o.n()).done;){i.value.state=5}}catch(I){o.e(I)}finally{o.f()}if("never"!==n){var a,s=Object(l.a)(e);try{for(s.s();!(a=s.n()).done;){v(a.value,n)}}catch(I){s.e(I)}finally{s.f()}var g,c=Object(l.a)(e);try{for(c.s();!(g=c.n()).done;){var u=g.value;y(u)&&m(u)}}catch(I){c.e(I)}finally{c.f()}}}},{key:"_resizeCache",value:function(){var e=this._cache,t=this.opts,A=t.maxCacheSize||(t.maxCacheByteSize?1/0:5*this.selectedTiles.length),n=t.maxCacheByteSize||1/0;if(e.size>A||this._cacheByteSize>n){var r,i=Object(l.a)(e);try{for(i.s();!(r=i.n()).done;){var o=Object(u.a)(r.value,2),a=o[0],s=o[1];if(s.isVisible||(this._cacheByteSize-=t.maxCacheByteSize?s.byteLength:0,e.delete(a),this.opts.onTileUnload(s)),e.size<=A&&this._cacheByteSize<=n)break}}catch(g){i.e(g)}finally{i.f()}this._rebuildTree(),this._dirty=!0}this._dirty&&(this._tiles=Array.from(this._cache.values()).sort((function(e,t){return e.z-t.z})),this._dirty=!1)}},{key:"_getTile",value:function(e,t){var A=e.x,n=e.y,r=e.z,i="".concat(A,",").concat(n,",").concat(r),o=this._cache.get(i),a=!1;return!o&&t?(o=new d({x:A,y:n,z:r}),Object.assign(o,this.getTileMetadata(o)),a=!0,this._cache.set(i,o),this._dirty=!0):o&&o.needsReload&&(a=!0),a&&o.loadData({getData:this.opts.getTileData,requestScheduler:this._requestScheduler,onLoad:this.onTileLoad,onError:this.opts.onTileError}),o}},{key:"_getNearestAncestor",value:function(e,t,A){for(var n=this._minZoom,r=void 0===n?0:n,i={x:e,y:t,z:A};i.z>r;){i=this.getParentIndex(i);var o=this._getTile(i);if(o)return o}return null}},{key:"tiles",get:function(){return this._tiles}},{key:"selectedTiles",get:function(){return this._selectedTiles}},{key:"isLoaded",get:function(){return this._selectedTiles.every((function(e){return e.isLoaded}))}}]),e}();function y(e){for(var t=e;t;){if(!1&t.state)return!0;if(t.isLoaded)return!1;t=t.parent}return!0}function v(e,t){for(var A,n=3;A=e.parent;){if(e.isLoaded&&(n=4,"best-available"===t))return;A.state=Math.max(A.state,n),e=A}}function m(e){var t,A=Object(l.a)(e.children);try{for(A.s();!(t=A.n()).done;){var n=t.value;n.state=Math.max(n.state,3),n.isLoaded||m(n)}}catch(r){A.e(r)}finally{A.f()}}A.d(t,"a",(function(){return w}));var b={data:[],dataComparator:B.f.equals,renderSubLayers:{type:"function",value:function(e){return new c.a(e)},compare:!1},getTileData:{type:"function",optional:!0,value:null,compare:!1},onViewportLoad:{type:"function",optional:!0,value:null,compare:!1},onTileLoad:{type:"function",value:function(e){},compare:!1},onTileUnload:{type:"function",value:function(e){},compare:!1},onTileError:{type:"function",value:function(e){return console.error(e)},compare:!1},extent:{type:"array",optional:!0,value:null,compare:!0},tileSize:512,maxZoom:null,minZoom:0,maxCacheSize:null,maxCacheByteSize:null,refinementStrategy:"best-available",zRange:null,maxRequests:6,zoomOffset:0},w=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(){return Object(r.a)(this,A),t.apply(this,arguments)}return Object(i.a)(A,[{key:"initializeState",value:function(){this.state={tileset:null,isLoaded:!1}}},{key:"finalizeState",value:function(){var e;null===(e=this.state.tileset)||void 0===e||e.finalize()}},{key:"shouldUpdateState",value:function(e){return e.changeFlags.somethingChanged}},{key:"updateState",value:function(e){var t=e.props,A=e.changeFlags,n=this.state.tileset,r=A.propsOrDataChanged||A.updateTriggersChanged,i=A.dataChanged||A.updateTriggersChanged&&(A.updateTriggersChanged.all||A.updateTriggersChanged.getTileData);n?r&&(n.setOptions(this._getTilesetOptions(t)),i?n.reloadAll():this.state.tileset.tiles.forEach((function(e){e.layers=null}))):(n=new Q(this._getTilesetOptions(t)),this.setState({tileset:n})),this._updateTileset()}},{key:"_getTilesetOptions",value:function(e){var t=e.tileSize,A=e.maxCacheSize,n=e.maxCacheByteSize,r=e.refinementStrategy,i=e.extent;return{maxCacheSize:A,maxCacheByteSize:n,maxZoom:e.maxZoom,minZoom:e.minZoom,tileSize:t,refinementStrategy:r,extent:i,maxRequests:e.maxRequests,zoomOffset:e.zoomOffset,getTileData:this.getTileData.bind(this),onTileLoad:this._onTileLoad.bind(this),onTileError:this._onTileError.bind(this),onTileUnload:this._onTileUnload.bind(this)}}},{key:"_updateTileset",value:function(){var e=this.state.tileset,t=this.props,A=t.zRange,n=t.modelMatrix,r=e.update(this.context.viewport,{zRange:A,modelMatrix:n}),i=e.isLoaded,o=this.state.isLoaded!==i,a=this.state.frameNumber!==r;i&&(o||a)&&this._onViewportLoad(),a&&this.setState({frameNumber:r}),this.state.isLoaded=i}},{key:"_onViewportLoad",value:function(){var e=this.state.tileset,t=this.props.onViewportLoad;t&&t(e.selectedTiles)}},{key:"_onTileLoad",value:function(e){this.props.onTileLoad(e),e.layers=null,e.isVisible&&this.setNeedsUpdate()}},{key:"_onTileError",value:function(e,t){this.props.onTileError(e),t.layers=null,t.isVisible&&this.setNeedsUpdate()}},{key:"_onTileUnload",value:function(e){this.props.onTileUnload(e)}},{key:"getTileData",value:function(e){var t=this.props,A=t.data,n=t.getTileData,r=t.fetch,i=e.signal;return e.url=Object(B.b)(A,e),n?n(e):e.url?r(e.url,{propName:"data",layer:this,signal:i}):null}},{key:"renderSubLayers",value:function(e){return this.props.renderSubLayers(e)}},{key:"getHighlightedObjectIndex",value:function(){return-1}},{key:"getPickingInfo",value:function(e){var t=e.info,A=e.sourceLayer;return t.tile=A.props.tile,t}},{key:"_updateAutoHighlight",value:function(e){e.sourceLayer&&e.sourceLayer.updateAutoHighlight(e)}},{key:"renderLayers",value:function(){var e=this;return this.state.tileset.tiles.map((function(t){var A=e.getHighlightedObjectIndex(t);if(t.isLoaded||t.content)if(t.layers)t.layers[0]&&t.layers[0].props.highlightedObjectIndex!==A&&(t.layers=t.layers.map((function(e){return e.clone({highlightedObjectIndex:A})})));else{var r=e.renderSubLayers(Object(n.a)({},e.props,{id:"".concat(e.id,"-").concat(t.x,"-").concat(t.y,"-").concat(t.z),data:t.content,_offset:0,tile:t}));t.layers=Object(s.b)(r,Boolean).map((function(e){return e.clone({tile:t,highlightedObjectIndex:A})}))}else;return t.layers}))}},{key:"filterSubLayer",value:function(e){return e.layer.props.tile.isVisible}},{key:"isLoaded",get:function(){return this.state.tileset.selectedTiles.every((function(e){return e.isLoaded&&e.layers&&e.layers.every((function(e){return e.isLoaded}))}))}}]),A}(g.a);w.layerName="TileLayer",w.defaultProps=b},function(e,t,A){"use strict";function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";A.d(t,"b",(function(){return i}));var n=A(21),r={easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)",easeOut:"cubic-bezier(0.0, 0, 0.2, 1)",easeIn:"cubic-bezier(0.4, 0, 1, 1)",sharp:"cubic-bezier(0.4, 0, 0.6, 1)"},i={shortest:150,shorter:200,short:250,standard:300,complex:375,enteringScreen:225,leavingScreen:195};function o(e){return"".concat(Math.round(e),"ms")}t.a={easing:r,duration:i,create:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["all"],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.duration,a=void 0===A?i.standard:A,s=t.easing,g=void 0===s?r.easeInOut:s,c=t.delay,u=void 0===c?0:c;Object(n.a)(t,["duration","easing","delay"]);return(Array.isArray(e)?e:[e]).map((function(e){return"".concat(e," ").concat("string"===typeof a?a:o(a)," ").concat(g," ").concat("string"===typeof u?u:o(u))})).join(",")},getAutoHeightDuration:function(e){if(!e)return 0;var t=e/36;return Math.round(10*(4+15*Math.pow(t,.25)+t/5))}}},function(e,t,A){"use strict";function n(e,t){if(!e)throw new Error(t||"loader assertion failed.")}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";function n(e){var t;if("undefined"!==typeof Symbol){if(Symbol.asyncIterator&&null!=(t=e[Symbol.asyncIterator]))return t.call(e);if(Symbol.iterator&&null!=(t=e[Symbol.iterator]))return t.call(e)}throw new TypeError("Object is not async iterable")}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return o}));var n=A(0),r=A.n(n),i=A(195);function o(e){var t=[];return r.a.Children.forEach(e,(function(e){void 0!==e&&null!==e&&(Array.isArray(e)?t=t.concat(o(e)):Object(i.isFragment)(e)&&e.props?t=t.concat(o(e.props.children)):t.push(e))})),t}},function(e,t,A){"use strict";A.d(t,"b",(function(){return i}));var n=A(0),r=n.createContext();function i(){return n.useContext(r)}t.a=r},function(e,t,A){"use strict";function n(e){return null!=e&&!(Array.isArray(e)&&0===e.length)}function r(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return e&&(n(e.value)&&""!==e.value||t&&n(e.defaultValue)&&""!==e.defaultValue)}function i(e){return e.startAdornment}A.d(t,"b",(function(){return r})),A.d(t,"a",(function(){return i}))},function(e,t,A){"use strict";var n=A(1),r=A(24),i=A(4),o=A(9),a=A(10),s=A(18),g=A(124),c=A(26),u="";function l(e,t){return Object(c.a)("string"===typeof e),e=u+e,new Promise((function(A,n){try{var r=new Image;r.onload=function(){return A(r)},r.onerror=function(){return n(new Error("Could not load image ".concat(e,".")))},r.crossOrigin=t&&t.crossOrigin||"anonymous",r.src=e}catch(i){n(i)}}))}A.d(t,"a",(function(){return I}));var I=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(e){var i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object(n.a)(this,A),Object(s.b)(e),(o instanceof Promise||"string"===typeof o)&&(o={data:o}),"string"===typeof o.data&&(o=Object.assign({},o,{data:l(o.data)})),(i=t.call(this,e,Object.assign({},o,{target:3553}))).initialize(o),Object.seal(Object(r.a)(i)),i}return Object(i.a)(A,null,[{key:"isSupported",value:function(e,t){return g.a.isSupported(e,t)}}]),A}(g.a)},function(e,t,A){"use strict";var n="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"===typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r="object"===("undefined"===typeof window?"undefined":n(window))&&"object"===("undefined"===typeof document?"undefined":n(document))&&9===document.nodeType;t.a=r},function(e,t,A){"use strict";A.d(t,"b",(function(){return s})),A.d(t,"a",(function(){return c}));var n=A(3),r=A.n(n),i=A(12),o=A(55),a=A(209);function s(e){return g.apply(this,arguments)}function g(){return(g=Object(i.a)(r.a.mark((function e(t){var A,n,i,s,g,c,u;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!Object(o.i)(t)){e.next=2;break}return e.abrupt("return",t);case 2:return A={},(n=Object(a.a)(t))>=0&&(A["content-length"]=String(n)),i=Object(a.b)(t),s=i.url,(g=i.type)&&(A["content-type"]=g),e.next=9,C(t);case 9:return(c=e.sent)&&(A["x-first-bytes"]=c),"string"===typeof t&&(t=(new TextEncoder).encode(t)),u=new Response(t,{headers:A}),Object.defineProperty(u,"url",{value:s}),e.abrupt("return",u);case 15:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function c(e){return u.apply(this,arguments)}function u(){return(u=Object(i.a)(r.a.mark((function e(t){var A;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.ok){e.next=5;break}return e.next=3,l(t);case 3:throw A=e.sent,new Error(A);case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function l(e){return I.apply(this,arguments)}function I(){return(I=Object(i.a)(r.a.mark((function e(t){var A,n,i;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(A="Failed to fetch resource ".concat(t.url," (").concat(t.status,"): "),e.prev=1,n=t.headers.get("Content-Type"),i=t.statusText,!n.includes("application/json")){e.next=11;break}return e.t0=i,e.t1=" ",e.next=9,t.text();case 9:e.t2=e.sent,i=e.t0+=e.t1.concat.call(e.t1,e.t2);case 11:A=(A+=i).length>60?"".concat(A.slice(60),"..."):A,e.next=17;break;case 15:e.prev=15,e.t3=e.catch(1);case 17:return e.abrupt("return",A);case 18:case"end":return e.stop()}}),e,null,[[1,15]])})))).apply(this,arguments)}function C(e){return h.apply(this,arguments)}function h(){return(h=Object(i.a)(r.a.mark((function e(t){var A,n,i,o;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(A=5,"string"!==typeof t){e.next=3;break}return e.abrupt("return","data:,".concat(t.slice(0,A)));case 3:if(!(t instanceof Blob)){e.next=8;break}return n=t.slice(0,5),e.next=7,new Promise((function(e){var t=new FileReader;t.onload=function(t){var A;return e(null===t||void 0===t||null===(A=t.target)||void 0===A?void 0:A.result)},t.readAsDataURL(n)}));case 7:return e.abrupt("return",e.sent);case 8:if(!(t instanceof ArrayBuffer)){e.next=12;break}return i=t.slice(0,A),o=f(i),e.abrupt("return","data:base64,".concat(o));case 12:return e.abrupt("return",null);case 13:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function f(e){for(var t="",A=new Uint8Array(e),n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,A)&&(i[A]=e[A])}return i}},function(e,t,A){"use strict";var n=function(){};e.exports=n},function(e,t,A){"use strict";var n,r=A(1),i=A(24),o=A(4),a=A(9),s=A(10),g=A(92),c=A(2),u="EXT_color_buffer_float",l=(n={},Object(c.a)(n,33189,{bpp:2}),Object(c.a)(n,33190,{gl2:!0,bpp:3}),Object(c.a)(n,36012,{gl2:!0,bpp:4}),Object(c.a)(n,36168,{bpp:1}),Object(c.a)(n,34041,{bpp:4}),Object(c.a)(n,35056,{gl2:!0,bpp:4}),Object(c.a)(n,36013,{gl2:!0,bpp:5}),Object(c.a)(n,32854,{bpp:2}),Object(c.a)(n,36194,{bpp:2}),Object(c.a)(n,32855,{bpp:2}),Object(c.a)(n,33321,{gl2:!0,bpp:1}),Object(c.a)(n,33330,{gl2:!0,bpp:1}),Object(c.a)(n,33329,{gl2:!0,bpp:1}),Object(c.a)(n,33332,{gl2:!0,bpp:2}),Object(c.a)(n,33331,{gl2:!0,bpp:2}),Object(c.a)(n,33334,{gl2:!0,bpp:4}),Object(c.a)(n,33333,{gl2:!0,bpp:4}),Object(c.a)(n,33323,{gl2:!0,bpp:2}),Object(c.a)(n,33336,{gl2:!0,bpp:2}),Object(c.a)(n,33335,{gl2:!0,bpp:2}),Object(c.a)(n,33338,{gl2:!0,bpp:4}),Object(c.a)(n,33337,{gl2:!0,bpp:4}),Object(c.a)(n,33340,{gl2:!0,bpp:8}),Object(c.a)(n,33339,{gl2:!0,bpp:8}),Object(c.a)(n,32849,{gl2:!0,bpp:3}),Object(c.a)(n,32856,{gl2:!0,bpp:4}),Object(c.a)(n,32857,{gl2:!0,bpp:4}),Object(c.a)(n,36220,{gl2:!0,bpp:4}),Object(c.a)(n,36238,{gl2:!0,bpp:4}),Object(c.a)(n,36975,{gl2:!0,bpp:4}),Object(c.a)(n,36214,{gl2:!0,bpp:8}),Object(c.a)(n,36232,{gl2:!0,bpp:8}),Object(c.a)(n,36226,{gl2:!0,bpp:16}),Object(c.a)(n,36208,{gl2:!0,bpp:16}),Object(c.a)(n,33325,{gl2:u,bpp:2}),Object(c.a)(n,33327,{gl2:u,bpp:4}),Object(c.a)(n,34842,{gl2:u,bpp:8}),Object(c.a)(n,33326,{gl2:u,bpp:4}),Object(c.a)(n,33328,{gl2:u,bpp:8}),Object(c.a)(n,34836,{gl2:u,bpp:16}),Object(c.a)(n,35898,{gl2:u,bpp:4}),n),I=A(18),C=A(26);function h(e,t,A){var n=A[t];if(!n)return!1;var r=Object(I.j)(e)&&n.gl2||n.gl1;return"string"===typeof r?e.getExtension(r):r}A.d(t,"a",(function(){return f}));var f=function(e){Object(a.a)(A,e);var t=Object(s.a)(A);function A(e){var n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object(r.a)(this,A),(n=t.call(this,e,o)).initialize(o),Object.seal(Object(i.a)(n)),n}return Object(o.a)(A,null,[{key:"isSupported",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{format:null},A=t.format;return!A||h(e,A,l)}},{key:"getSamplesForFormat",value:function(e,t){var A=t.format;return e.getInternalformatParameter(36161,A,32937)}}]),Object(o.a)(A,[{key:"initialize",value:function(e){var t=e.format,A=e.width,n=void 0===A?1:A,r=e.height,i=void 0===r?1:r,o=e.samples,a=void 0===o?0:o;return Object(C.a)(t,"Needs format"),this._trackDeallocatedMemory(),this.gl.bindRenderbuffer(36161,this.handle),0!==a&&Object(I.j)(this.gl)?this.gl.renderbufferStorageMultisample(36161,a,t,n,i):this.gl.renderbufferStorage(36161,t,n,i),this.format=t,this.width=n,this.height=i,this.samples=a,this._trackAllocatedMemory(this.width*this.height*(this.samples||1)*l[this.format].bpp),this}},{key:"resize",value:function(e){var t=e.width,A=e.height;return t!==this.width||A!==this.height?this.initialize({width:t,height:A,format:this.format,samples:this.samples}):this}},{key:"_createHandle",value:function(){return this.gl.createRenderbuffer()}},{key:"_deleteHandle",value:function(){this.gl.deleteRenderbuffer(this.handle),this._trackDeallocatedMemory()}},{key:"_bindHandle",value:function(e){this.gl.bindRenderbuffer(36161,e)}},{key:"_syncHandle",value:function(e){this.format=this.getParameter(36164),this.width=this.getParameter(36162),this.height=this.getParameter(36163),this.samples=this.getParameter(36011)}},{key:"_getParameter",value:function(e){return this.gl.bindRenderbuffer(36161,this.handle),this.gl.getRenderbufferParameter(36161,e)}}]),A}(g.a)},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=A(0);function r(e){var t,A=new Set,n=function(e,n){var r="function"===typeof e?e(t):e;if(r!==t){var i=t;t=n?r:Object.assign({},t,r),A.forEach((function(e){return e(t,i)}))}},r=function(){return t},i={setState:n,getState:r,subscribe:function(e,n,i){return n||i?function(e,n,i){void 0===n&&(n=r),void 0===i&&(i=Object.is);var o=n(t);function a(){var A=n(t);if(!i(o,A)){var r=o;e(o=A,r)}}return A.add(a),function(){return A.delete(a)}}(e,n,i):(A.add(e),function(){return A.delete(e)})},destroy:function(){return A.clear()}};return t=e(n,r,i),i}var i="undefined"===typeof window||!window.navigator||/ServerSideRendering|^Deno\//.test(window.navigator.userAgent)?n.useEffect:n.useLayoutEffect;t.default=function(e){var t="function"===typeof e?r(e):e,A=function(e,A){void 0===e&&(e=t.getState),void 0===A&&(A=Object.is);var r,o=n.useReducer((function(e){return e+1}),0)[1],a=t.getState(),s=n.useRef(a),g=n.useRef(e),c=n.useRef(A),u=n.useRef(!1),l=n.useRef();void 0===l.current&&(l.current=e(a));var I=!1;(s.current!==a||g.current!==e||c.current!==A||u.current)&&(r=e(a),I=!A(l.current,r)),i((function(){I&&(l.current=r),s.current=a,g.current=e,c.current=A,u.current=!1}));var C=n.useRef(a);return i((function(){var e=function(){try{var e=t.getState(),A=g.current(e);c.current(l.current,A)||(s.current=e,l.current=A,o())}catch(n){u.current=!0,o()}},A=t.subscribe(e);return t.getState()!==C.current&&e(),A}),[]),I?r:l.current};return Object.assign(A,t),A[Symbol.iterator]=function(){console.warn("[useStore, api] = create() is deprecated and will be removed in v4");var e=[A,t];return{next:function(){var t=e.length<=0;return{value:e.shift(),done:t}}}},A}},function(e,t,A){"use strict";(function(e){A.d(t,"b",(function(){return n})),A.d(t,"c",(function(){return r})),A.d(t,"a",(function(){return i}));var n="undefined"!==typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",r="undefined"!==typeof window?window:e,i=("undefined"!==typeof e||window,"undefined"!==typeof document&&document,!1);try{var o={get passive(){return i=!0,!0}};r.addEventListener("test",o,o),r.removeEventListener("test",o,o)}catch(a){}}).call(this,A(86))},function(e,t,A){var n;!function(A){"use strict";var r={s:1,n:0,d:1};function i(e){function t(){var t=Error.apply(this,arguments);t.name=this.name=e,this.stack=t.stack,this.message=t.message}function A(){}return A.prototype=Error.prototype,t.prototype=new A,t}var o=l.DivisionByZero=i("DivisionByZero"),a=l.InvalidParameter=i("InvalidParameter");function s(e,t){return isNaN(e=parseInt(e,10))&&g(),e*t}function g(){throw new a}var c=function(e,t){var A,n=0,i=1,a=1,c=0,u=0,l=0,I=1,C=1,h=0,f=1,d=1,B=1,p=1e7;if(void 0===e||null===e);else if(void 0!==t)a=(n=e)*(i=t);else switch(typeof e){case"object":"d"in e&&"n"in e?(n=e.n,i=e.d,"s"in e&&(n*=e.s)):0 in e?(n=e[0],1 in e&&(i=e[1])):g(),a=n*i;break;case"number":if(e<0&&(a=e,e=-e),e%1===0)n=e;else if(e>0){for(e>=1&&(e/=C=Math.pow(10,Math.floor(1+Math.log(e)/Math.LN10)));f<=p&&B<=p;){if(e===(A=(h+d)/(f+B))){f+B<=p?(n=h+d,i=f+B):B>f?(n=d,i=B):(n=h,i=f);break}e>A?(h+=d,f+=B):(d+=h,B+=f),f>p?(n=d,i=B):(n=h,i=f)}n*=C}else(isNaN(e)||isNaN(t))&&(i=n=NaN);break;case"string":if(null===(f=e.match(/\d+|./g))&&g(),"-"===f[h]?(a=-1,h++):"+"===f[h]&&h++,f.length===h+1?u=s(f[h++],a):"."===f[h+1]||"."===f[h]?("."!==f[h]&&(c=s(f[h++],a)),(++h+1===f.length||"("===f[h+1]&&")"===f[h+3]||"'"===f[h+1]&&"'"===f[h+3])&&(u=s(f[h],a),I=Math.pow(10,f[h].length),h++),("("===f[h]&&")"===f[h+2]||"'"===f[h]&&"'"===f[h+2])&&(l=s(f[h+1],a),C=Math.pow(10,f[h+1].length)-1,h+=3)):"/"===f[h+1]||":"===f[h+1]?(u=s(f[h],a),I=s(f[h+2],1),h+=3):"/"===f[h+3]&&" "===f[h+1]&&(c=s(f[h],a),u=s(f[h+2],a),I=s(f[h+4],1),h+=5),f.length<=h){a=n=l+(i=I*C)*c+C*u;break}default:g()}if(0===i)throw new o;r.s=a<0?-1:1,r.n=Math.abs(n),r.d=Math.abs(i)};function u(e,t){if(!e)return t;if(!t)return e;for(;;){if(!(e%=t))return t;if(!(t%=e))return e}}function l(e,t){if(!(this instanceof l))return new l(e,t);c(e,t),e=l.REDUCE?u(r.d,r.n):1,this.s=r.s,this.n=r.n/e,this.d=r.d/e}l.REDUCE=1,l.prototype={s:1,n:0,d:1,abs:function(){return new l(this.n,this.d)},neg:function(){return new l(-this.s*this.n,this.d)},add:function(e,t){return c(e,t),new l(this.s*this.n*r.d+r.s*this.d*r.n,this.d*r.d)},sub:function(e,t){return c(e,t),new l(this.s*this.n*r.d-r.s*this.d*r.n,this.d*r.d)},mul:function(e,t){return c(e,t),new l(this.s*r.s*this.n*r.n,this.d*r.d)},div:function(e,t){return c(e,t),new l(this.s*r.s*this.n*r.d,this.d*r.n)},clone:function(){return new l(this)},mod:function(e,t){return isNaN(this.n)||isNaN(this.d)?new l(NaN):void 0===e?new l(this.s*this.n%this.d,1):(c(e,t),0===r.n&&0===this.d&&l(0,0),new l(this.s*(r.d*this.n)%(r.n*this.d),r.d*this.d))},gcd:function(e,t){return c(e,t),new l(u(r.n,this.n)*u(r.d,this.d),r.d*this.d)},lcm:function(e,t){return c(e,t),0===r.n&&0===this.n?new l:new l(r.n*this.n,u(r.n,this.n)*u(r.d,this.d))},ceil:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):new l(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):new l(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=Math.pow(10,e||0),isNaN(this.n)||isNaN(this.d)?new l(NaN):new l(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return new l(this.s*this.d,this.n)},pow:function(e){return e<0?new l(Math.pow(this.s*this.d,-e),Math.pow(this.n,-e)):new l(Math.pow(this.s*this.n,e),Math.pow(this.d,e))},equals:function(e,t){return c(e,t),this.s*this.n*r.d===r.s*r.n*this.d},compare:function(e,t){c(e,t);var A=this.s*this.n*r.d-r.s*r.n*this.d;return(00&&(A+=t,A+=" ",n%=r),A+=n,A+="/",A+=r),A},toLatex:function(e){var t,A="",n=this.n,r=this.d;return this.s<0&&(A+="-"),1===r?A+=n:(e&&(t=Math.floor(n/r))>0&&(A+=t,n%=r),A+="\\frac{",A+=n,A+="}{",A+=r,A+="}"),A},toContinued:function(){var e,t=this.n,A=this.d,n=[];if(isNaN(t)||isNaN(A))return n;do{n.push(Math.floor(t/A)),e=t%A,t=A,A=e}while(1!==t);return n},toString:function(e){var t,A=this.n,n=this.d;if(isNaN(A)||isNaN(n))return"NaN";l.REDUCE||(A/=t=u(A,n),n/=t),e=e||15;var r=function(e,t){for(;t%2===0;t/=2);for(;t%5===0;t/=5);if(1===t)return 0;for(var A=10%t,n=1;1!==A;n++)if(A=10*A%t,n>2e3)return 0;return n}(0,n),i=function(e,t,A){for(var n=1,r=function(e,t,A){for(var n=1;t>0;e=e*e%A,t>>=1)1&t&&(n=n*e%A);return n}(10,A,t),i=0;i<300;i++){if(n===r)return i;n=10*n%t,r=10*r%t}return 0}(0,n,r),o=-1===this.s?"-":"";if(o+=A/n|0,A%=n,(A*=10)&&(o+="."),r){for(var a=i;a--;)o+=A/n|0,A%=n,A*=10;o+="(";for(a=r;a--;)o+=A/n|0,A%=n,A*=10;o+=")"}else for(a=e;A&&a--;)o+=A/n|0,A%=n,A*=10;return o}},void 0===(n=function(){return l}.apply(t,[]))||(e.exports=n)}()},function(e,t){e.exports=function e(t,A){"use strict";var n,r,i=/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,o=/(^[ ]*|[ ]*$)/g,a=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,s=/^0x[0-9a-f]+$/i,g=/^0/,c=function(t){return e.insensitive&&(""+t).toLowerCase()||""+t},u=c(t).replace(o,"")||"",l=c(A).replace(o,"")||"",I=u.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),C=l.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),h=parseInt(u.match(s),16)||1!==I.length&&u.match(a)&&Date.parse(u),f=parseInt(l.match(s),16)||h&&l.match(a)&&Date.parse(l)||null;if(f){if(hf)return 1}for(var d=0,B=Math.max(I.length,C.length);dr)return 1}return 0}},,,,,function(e,t,A){var n=A(140).Symbol;e.exports=n},function(e,t,A){var n=A(446),r=A(455);e.exports=function(e){return null!=e&&r(e.length)&&!n(e)}},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.bottom=g,t.cloneLayout=function(e){for(var t=Array(e.length),A=0,n=e.length;AA&&(A=t);return A}function c(e){return{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,minW:e.minW,maxW:e.maxW,minH:e.minH,maxH:e.maxH,moved:Boolean(e.moved),static:Boolean(e.static),isDraggable:e.isDraggable,isResizable:e.isResizable,resizeHandles:e.resizeHandles,isBounded:e.isBounded}}var u=A(800);function l(e,t){return e.i!==t.i&&(!(e.x+e.w<=t.x)&&(!(e.x>=t.x+t.w)&&(!(e.y+e.h<=t.y)&&!(e.y>=t.y+t.h))))}function I(e,t,A){for(var n=Q(e),r=m(e,t),i=Array(e.length),o=0,a=r.length;ot.y+t.h)break;l(t,o)&&h(e,o,A+t[r],n)}}t[n]=A}function f(e,t,A,n,r){var i,o="horizontal"===A;if("vertical"===A)for(t.y=Math.min(g(e),t.y);t.y>0&&!p(e,t);)t.y--;else if(o)for(t.y=Math.min(g(e),t.y);t.x>0&&!p(e,t);)t.x--;for(;i=p(e,t);)o?h(r,t,i.x+i.w,"x"):h(r,t,i.y+i.h,"y"),o&&t.x+t.w>n&&(t.x=n-t.w,t.y++);return t}function d(e,t){for(var A=Q(e),n=0,r=e.length;nt.cols&&(i.x=t.cols-i.w),i.x<0&&(i.x=0,i.w=t.cols),i.static)for(;p(A,i);)i.y++;else A.push(i)}return e}function B(e,t){for(var A=0,n=e.length;A=n:"horizontal"===o&&"number"===typeof A&&s>=A)&&(c=c.reverse());var u=E(c,t);if(i&&u.length)return F("Collision prevented on ".concat(t.i,", reverting.")),t.x=s,t.y=g,t.moved=!1,e;for(var l=0,I=u.length;lt.y||e.y===t.y&&e.x>t.x?1:e.y===t.y&&e.x===t.x?0:-1}))}function w(e){return e.slice(0).sort((function(e,t){return e.x>t.x||e.x===t.x&&e.y>t.y?1:-1}))}function S(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Layout",A=["x","y","w","h"];if(!Array.isArray(e))throw new Error(t+" must be an array!");for(var n=0,r=e.length;n=t)throw new Error("Cannot access property/index "+n+" levels up, current level is "+t);return A[t-n]}if(n>t)throw new Error("Cannot access data "+n+" levels up, current level is "+t);if(i="data"+(t-n||""),!r)return i}for(var a=i,g=r.split("/"),c=0;ce[0]&&(t[0]=e[0]),t[1]>e[1]&&(t[1]=e[1]),t[2])?=?)"),g("XRANGEIDENTIFIERLOOSE","".concat(o[a.NUMERICIDENTIFIERLOOSE],"|x|X|\\*")),g("XRANGEIDENTIFIER","".concat(o[a.NUMERICIDENTIFIER],"|x|X|\\*")),g("XRANGEPLAIN","[v=\\s]*(".concat(o[a.XRANGEIDENTIFIER],")")+"(?:\\.(".concat(o[a.XRANGEIDENTIFIER],")")+"(?:\\.(".concat(o[a.XRANGEIDENTIFIER],")")+"(?:".concat(o[a.PRERELEASE],")?").concat(o[a.BUILD],"?")+")?)?"),g("XRANGEPLAINLOOSE","[v=\\s]*(".concat(o[a.XRANGEIDENTIFIERLOOSE],")")+"(?:\\.(".concat(o[a.XRANGEIDENTIFIERLOOSE],")")+"(?:\\.(".concat(o[a.XRANGEIDENTIFIERLOOSE],")")+"(?:".concat(o[a.PRERELEASELOOSE],")?").concat(o[a.BUILD],"?")+")?)?"),g("XRANGE","^".concat(o[a.GTLT],"\\s*").concat(o[a.XRANGEPLAIN],"$")),g("XRANGELOOSE","^".concat(o[a.GTLT],"\\s*").concat(o[a.XRANGEPLAINLOOSE],"$")),g("COERCE","".concat("(^|[^\\d])(\\d{1,").concat(n,"})")+"(?:\\.(\\d{1,".concat(n,"}))?")+"(?:\\.(\\d{1,".concat(n,"}))?")+"(?:$|[^\\d])"),g("COERCERTL",o[a.COERCE],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM","(\\s*)".concat(o[a.LONETILDE],"\\s+"),!0),t.tildeTrimReplace="$1~",g("TILDE","^".concat(o[a.LONETILDE]).concat(o[a.XRANGEPLAIN],"$")),g("TILDELOOSE","^".concat(o[a.LONETILDE]).concat(o[a.XRANGEPLAINLOOSE],"$")),g("LONECARET","(?:\\^)"),g("CARETTRIM","(\\s*)".concat(o[a.LONECARET],"\\s+"),!0),t.caretTrimReplace="$1^",g("CARET","^".concat(o[a.LONECARET]).concat(o[a.XRANGEPLAIN],"$")),g("CARETLOOSE","^".concat(o[a.LONECARET]).concat(o[a.XRANGEPLAINLOOSE],"$")),g("COMPARATORLOOSE","^".concat(o[a.GTLT],"\\s*(").concat(o[a.LOOSEPLAIN],")$|^$")),g("COMPARATOR","^".concat(o[a.GTLT],"\\s*(").concat(o[a.FULLPLAIN],")$|^$")),g("COMPARATORTRIM","(\\s*)".concat(o[a.GTLT],"\\s*(").concat(o[a.LOOSEPLAIN],"|").concat(o[a.XRANGEPLAIN],")"),!0),t.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE","^\\s*(".concat(o[a.XRANGEPLAIN],")")+"\\s+-\\s+"+"(".concat(o[a.XRANGEPLAIN],")")+"\\s*$"),g("HYPHENRANGELOOSE","^\\s*(".concat(o[a.XRANGEPLAINLOOSE],")")+"\\s+-\\s+"+"(".concat(o[a.XRANGEPLAINLOOSE],")")+"\\s*$"),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0.0.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")},function(e,t,A){var n=A(370).MAX_LENGTH,r=A(260),i=r.re,o=r.t,a=A(106),s=A(372);e.exports=function(e,t){if(t=s(t),e instanceof a)return e;if("string"!==typeof e)return null;if(e.length>n)return null;if(!(t.loose?i[o.LOOSE]:i[o.FULL]).test(e))return null;try{return new a(e,t)}catch(A){return null}}},function(e,t,A){"use strict";A.r(t);function n(e,t,A){void 0===A&&(A={});var n={type:"Feature"};return(0===A.id||A.id)&&(n.id=A.id),A.bbox&&(n.bbox=A.bbox),n.properties=t||{},n.geometry=e,n}function r(e,t,A){void 0===A&&(A={});for(var r=0,i=e;r0&&void 0!==arguments[0]?arguments[0]:{};Object(i.a)(this,A);var o,s=n.latitude,g=void 0===s?0:s,c=n.longitude,u=void 0===c?0:c,l=n.zoom,C=void 0===l?11:l,f=n.pitch,d=void 0===f?0:f,B=n.bearing,p=void 0===B?0:B,E=n.nearZMultiplier,Q=void 0===E?.1:E,y=n.farZMultiplier,v=void 0===y?1.01:y,m=n.orthographic,b=void 0!==m&&m,w=n.projectionMatrix,S=n.repeat,F=void 0!==S&&S,R=n.worldOffset,D=void 0===R?0:R,G=n.legacyMeterSizes,k=void 0!==G&&G,x=n.width,N=n.height,U=n.altitude,_=void 0===U?1.5:U,M=Math.pow(2,C);x=x||1,N=N||1;var O=null;w?(_=w[5]/2,o=Object(I.c)(_)):(n.fovy?(o=n.fovy,_=Object(I.f)(o)):o=Object(I.c)(_),O=Object(I.l)({width:x,height:N,pitch:d,fovy:o,nearZMultiplier:Q,farZMultiplier:v}));var L=Object(I.m)({height:N,pitch:d,bearing:p,scale:M,altitude:_});if(D){var T=(new h.Matrix4).translate([512*D,0,0]);L=T.multiplyLeft(L)}return(e=t.call(this,Object(r.a)({},n,{width:x,height:N,viewMatrix:L,longitude:u,latitude:g,zoom:C},O,{fovy:o,focalDistance:_}))).latitude=g,e.longitude=u,e.zoom=C,e.pitch=d,e.bearing=p,e.altitude=_,e.fovy=o,e.orthographic=b,e._subViewports=F?[]:null,e._pseudoMeters=k,Object.freeze(Object(a.a)(e)),e}return Object(o.a)(A,[{key:"projectPosition",value:function(e){if(this._pseudoMeters)return Object(g.a)(Object(s.a)(A.prototype),"projectPosition",this).call(this,e);var t=this.projectFlat(e),r=Object(n.a)(t,2);return[r[0],r[1],(e[2]||0)*d(e[1])]}},{key:"unprojectPosition",value:function(e){if(this._pseudoMeters)return Object(g.a)(Object(s.a)(A.prototype),"unprojectPosition",this).call(this,e);var t=this.unprojectFlat(e),r=Object(n.a)(t,2),i=r[0],o=r[1];return[i,o,(e[2]||0)/d(o)]}},{key:"addMetersToLngLat",value:function(e,t){return Object(I.b)(e,t)}},{key:"panByPosition",value:function(e,t){var A=Object(I.p)(t,this.pixelUnprojectionMatrix),r=this.projectFlat(e),i=C.a([],r,C.b([],A)),o=C.a([],this.center,i),a=this.unprojectFlat(o),s=Object(n.a)(a,2);return{longitude:s[0],latitude:s[1]}}},{key:"getBounds",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=Object(I.g)(this,e.z||0);return[Math.min(t[0][0],t[1][0],t[2][0],t[3][0]),Math.min(t[0][1],t[1][1],t[2][1],t[3][1]),Math.max(t[0][0],t[1][0],t[2][0],t[3][0]),Math.max(t[0][1],t[1][1],t[2][1],t[3][1])]}},{key:"fitBounds",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.width,i=this.height,o=Object(I.d)(Object(r.a)({width:n,height:i,bounds:e},t)),a=o.longitude,s=o.latitude,g=o.zoom;return new A({width:n,height:i,longitude:a,latitude:s,zoom:g})}},{key:"subViewports",get:function(){if(this._subViewports&&!this._subViewports.length)for(var e=this.getBounds(),t=Math.floor((e[0]+180)/360),n=Math.ceil((e[2]-180)/360),i=t;i<=n;i++){var o=i?new A(Object(r.a)({},this,{worldOffset:i})):this;this._subViewports.push(o)}return this._subViewports}}]),A}(l.a);B.displayName="WebMercatorViewport"},function(e,t,A){"use strict";A.d(t,"a",(function(){return I})),A.d(t,"b",(function(){return C}));var n=A(7),r=A(1),i=A(4),o=A(9),a=A(10),s=A(23),g=A(133),c=A(275),u=A(84),l={rotationX:0,rotationOrbit:0,zoom:0,target:[0,0,0],minRotationX:-90,maxRotationX:90,minZoom:-1/0,maxZoom:1/0},I=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(e){var n,i=e.makeViewport,o=e.width,a=e.height,s=e.rotationX,g=void 0===s?l.rotationX:s,c=e.rotationOrbit,u=void 0===c?l.rotationOrbit:c,I=e.target,C=void 0===I?l.target:I,h=e.zoom,f=void 0===h?l.zoom:h,d=e.minRotationX,B=void 0===d?l.minRotationX:d,p=e.maxRotationX,E=void 0===p?l.maxRotationX:p,Q=e.minZoom,y=void 0===Q?l.minZoom:Q,v=e.maxZoom,m=void 0===v?l.maxZoom:v,b=e.startPanPosition,w=e.startRotatePos,S=e.startRotationX,F=e.startRotationOrbit,R=e.startZoomPosition,D=e.startZoom;return Object(r.a)(this,A),(n=t.call(this,{width:o,height:a,rotationX:g,rotationOrbit:u,target:C,zoom:f,minRotationX:B,maxRotationX:E,minZoom:y,maxZoom:m}))._state={startPanPosition:b,startRotatePos:w,startRotationX:S,startRotationOrbit:F,startZoomPosition:R,startZoom:D},n.makeViewport=i,n}return Object(i.a)(A,[{key:"panStart",value:function(e){var t=e.pos;return this._getUpdatedState({startPanPosition:this._unproject(t)})}},{key:"pan",value:function(e){var t=e.pos,A=e.startPosition,n=this._state.startPanPosition||A;if(!n)return this;var r=this.makeViewport(this._viewportProps).panByPosition(n,t);return this._getUpdatedState(r)}},{key:"panEnd",value:function(){return this._getUpdatedState({startPanPosition:null})}},{key:"rotateStart",value:function(e){var t=e.pos;return this._getUpdatedState({startRotatePos:t,startRotationX:this._viewportProps.rotationX,startRotationOrbit:this._viewportProps.rotationOrbit})}},{key:"rotate",value:function(e){var t,A=e.pos,n=e.deltaAngleX,r=void 0===n?0:n,i=e.deltaAngleY,o=void 0===i?0:i,a=this._state,s=a.startRotatePos,g=a.startRotationX,c=a.startRotationOrbit,u=this._viewportProps,l=u.width,I=u.height;if(!s||!Number.isFinite(g)||!Number.isFinite(c))return this;if(A){var C=(A[0]-s[0])/l;(g<-90||g>90)&&(C*=-1),t={rotationX:g+180*((A[1]-s[1])/I),rotationOrbit:c+180*C}}else t={rotationX:g+o,rotationOrbit:c+r};return this._getUpdatedState(t)}},{key:"rotateEnd",value:function(){return this._getUpdatedState({startRotationX:null,startRotationOrbit:null})}},{key:"shortestPathFrom",value:function(e){var t=e.getViewportProps(),A=Object(n.a)({},this._viewportProps),r=A.rotationOrbit;return Math.abs(r-t.rotationOrbit)>180&&(A.rotationOrbit=r<0?r+360:r-360),A}},{key:"zoomStart",value:function(e){var t=e.pos;return this._getUpdatedState({startZoomPosition:this._unproject(t),startZoom:this._viewportProps.zoom})}},{key:"zoom",value:function(e){var t=e.pos,A=e.startPos,r=e.scale,i=this._viewportProps.zoom,o=this._state,a=o.startZoom,s=o.startZoomPosition;Number.isFinite(a)||(a=i,s=this._unproject(A)||this._unproject(t));var g=this._calculateNewZoom({scale:r,startZoom:a}),c=this.makeViewport(Object(n.a)({},this._viewportProps,{zoom:g}));return this._getUpdatedState(Object(n.a)({zoom:g},c.panByPosition(s,t)))}},{key:"zoomEnd",value:function(){return this._getUpdatedState({startZoomPosition:null,startZoom:null})}},{key:"zoomIn",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2;return this._getUpdatedState({zoom:this._calculateNewZoom({scale:e})})}},{key:"zoomOut",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2;return this._getUpdatedState({zoom:this._calculateNewZoom({scale:1/e})})}},{key:"moveLeft",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:50;return this._panFromCenter([-e,0])}},{key:"moveRight",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:50;return this._panFromCenter([e,0])}},{key:"moveUp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:50;return this._panFromCenter([0,-e])}},{key:"moveDown",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:50;return this._panFromCenter([0,e])}},{key:"rotateLeft",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15;return this._getUpdatedState({rotationOrbit:this._viewportProps.rotationOrbit-e})}},{key:"rotateRight",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15;return this._getUpdatedState({rotationOrbit:this._viewportProps.rotationOrbit+e})}},{key:"rotateUp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this._getUpdatedState({rotationX:this._viewportProps.rotationX-e})}},{key:"rotateDown",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this._getUpdatedState({rotationX:this._viewportProps.rotationX+e})}},{key:"_unproject",value:function(e){var t=this.makeViewport(this._viewportProps);return e&&t.unproject(e)}},{key:"_calculateNewZoom",value:function(e){var t=e.scale,A=e.startZoom,n=this._viewportProps,r=n.maxZoom,i=n.minZoom;Number.isFinite(A)||(A=this._viewportProps.zoom);var o=A+Math.log2(t);return Object(s.clamp)(o,i,r)}},{key:"_panFromCenter",value:function(e){var t=this._viewportProps,A=t.width,n=t.height,r=t.target;return this.pan({startPosition:r,pos:[A/2+e[0],n/2+e[1]]})}},{key:"_getUpdatedState",value:function(e){return new this.constructor(Object(n.a)({},this._viewportProps,{},this._state,{},e))}},{key:"_applyConstraints",value:function(e){var t=e.maxZoom,A=e.minZoom,n=e.zoom,r=e.maxRotationX,i=e.minRotationX,o=e.rotationOrbit;return e.zoom=Object(s.clamp)(n,A,t),e.rotationX=Object(s.clamp)(e.rotationX,i,r),(o<-180||o>180)&&(e.rotationOrbit=Object(u.e)(o+180,360)-180),e}}]),A}(c.a),C=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(e){return Object(r.a)(this,A),t.call(this,I,e)}return Object(i.a)(A,[{key:"linearTransitionProps",get:function(){return["target","zoom","rotationX","rotationOrbit"]}}]),A}(g.a)},function(e,t,A){"use strict";A.d(t,"a",(function(){return s}));var n=A(6),r=A(1),i=A(4),o=A(23),a=A(87),s=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(r.a)(this,e),Array.isArray(t)&&(t={compare:t,extract:t,required:t});var A=t,n=A.compare,i=A.extract,o=A.required;this._propsToCompare=n,this._propsToExtract=i,this._requiredProps=o}return Object(i.a)(e,[{key:"arePropsEqual",value:function(e,t){var A,r=Object(n.a)(this._propsToCompare||Object.keys(t));try{for(r.s();!(A=r.n()).done;){var i=A.value;if(!(i in e)||!(i in t)||!Object(o.equals)(e[i],t[i]))return!1}}catch(a){r.e(a)}finally{r.f()}return!0}},{key:"initializeProps",value:function(e,t){var A;if(this._propsToExtract){var r,i={},o={},a=Object(n.a)(this._propsToExtract);try{for(a.s();!(r=a.n()).done;){var s=r.value;i[s]=e[s],o[s]=t[s]}}catch(g){a.e(g)}finally{a.f()}A={start:i,end:o}}else A={start:e,end:t};return this._checkRequiredProps(A.start),this._checkRequiredProps(A.end),A}},{key:"interpolateProps",value:function(e,t,A){return t}},{key:"getDuration",value:function(e,t){return t.transitionDuration}},{key:"_checkRequiredProps",value:function(e){this._requiredProps&&this._requiredProps.forEach((function(t){var A=e[t];Object(a.a)(Number.isFinite(A)||Array.isArray(A),"".concat(t," is required for transition"))}))}}]),e}()},function(e,t,A){"use strict";A.d(t,"a",(function(){return y})),A.d(t,"b",(function(){return v}));var n=A(16),r=A(17),i=A(7),o=A(1),a=A(4),s=A(9),g=A(10),c=A(23),u=A(133),l=A(275),I=A(42),C=A(87),h=0,f=0,d=1.5,B=0,p=20,E=0,Q=60,y=function(e){Object(s.a)(A,e);var t=Object(g.a)(A);function A(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=n.makeViewport,i=n.width,a=n.height,s=n.latitude,g=n.longitude,c=n.zoom,u=n.bearing,l=void 0===u?f:u,I=n.pitch,y=void 0===I?h:I,v=n.altitude,m=void 0===v?d:v,b=n.maxZoom,w=void 0===b?p:b,S=n.minZoom,F=void 0===S?B:S,R=n.maxPitch,D=void 0===R?Q:R,G=n.minPitch,k=void 0===G?E:G,x=n.startPanLngLat,N=n.startZoomLngLat,U=n.startRotatePos,_=n.startBearing,M=n.startPitch,O=n.startZoom,L=n.normalize;return Object(o.a)(this,A),Object(C.a)(Number.isFinite(g)),Object(C.a)(Number.isFinite(s)),Object(C.a)(Number.isFinite(c)),(e=t.call(this,{width:i,height:a,latitude:s,longitude:g,zoom:c,bearing:l,pitch:y,altitude:m,maxZoom:w,minZoom:F,maxPitch:D,minPitch:k,normalize:L}))._state={startPanLngLat:x,startZoomLngLat:N,startRotatePos:U,startBearing:_,startPitch:M,startZoom:O},e.makeViewport=r,e}return Object(a.a)(A,[{key:"panStart",value:function(e){var t=e.pos;return this._getUpdatedState({startPanLngLat:this._unproject(t)})}},{key:"pan",value:function(e){var t=e.pos,A=e.startPos,n=this._state.startPanLngLat||this._unproject(A);if(!n)return this;var r=this.makeViewport(this._viewportProps).panByPosition(n,t);return this._getUpdatedState(r)}},{key:"panEnd",value:function(){return this._getUpdatedState({startPanLngLat:null})}},{key:"rotateStart",value:function(e){var t=e.pos;return this._getUpdatedState({startRotatePos:t,startBearing:this._viewportProps.bearing,startPitch:this._viewportProps.pitch})}},{key:"rotate",value:function(e){var t,A=e.pos,n=e.deltaAngleX,r=void 0===n?0:n,o=e.deltaAngleY,a=void 0===o?0:o,s=this._state,g=s.startRotatePos,c=s.startBearing,u=s.startPitch;return g&&Number.isFinite(c)&&Number.isFinite(u)?(t=A?this._calculateNewPitchAndBearing(Object(i.a)({},this._getRotationParams(A,g),{startBearing:c,startPitch:u})):{bearing:c+r,pitch:u+a},this._getUpdatedState(t)):this}},{key:"rotateEnd",value:function(){return this._getUpdatedState({startBearing:null,startPitch:null})}},{key:"zoomStart",value:function(e){var t=e.pos;return this._getUpdatedState({startZoomLngLat:this._unproject(t),startZoom:this._viewportProps.zoom})}},{key:"zoom",value:function(e){var t=e.pos,A=e.startPos,n=e.scale,r=this._state,o=r.startZoom,a=r.startZoomLngLat;Number.isFinite(o)||(o=this._viewportProps.zoom,a=this._unproject(A)||this._unproject(t));var s=this._calculateNewZoom({scale:n,startZoom:o}),g=this.makeViewport(Object(i.a)({},this._viewportProps,{zoom:s}));return this._getUpdatedState(Object(i.a)({zoom:s},g.panByPosition(a,t)))}},{key:"zoomEnd",value:function(){return this._getUpdatedState({startZoomLngLat:null,startZoom:null})}},{key:"zoomIn",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2;return this._zoomFromCenter(e)}},{key:"zoomOut",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2;return this._zoomFromCenter(1/e)}},{key:"moveLeft",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;return this._panFromCenter([e,0])}},{key:"moveRight",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;return this._panFromCenter([-e,0])}},{key:"moveUp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;return this._panFromCenter([0,e])}},{key:"moveDown",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;return this._panFromCenter([0,-e])}},{key:"rotateLeft",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15;return this._getUpdatedState({bearing:this._viewportProps.bearing-e})}},{key:"rotateRight",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:15;return this._getUpdatedState({bearing:this._viewportProps.bearing+e})}},{key:"rotateUp",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this._getUpdatedState({pitch:this._viewportProps.pitch+e})}},{key:"rotateDown",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return this._getUpdatedState({pitch:this._viewportProps.pitch-e})}},{key:"shortestPathFrom",value:function(e){var t=e.getViewportProps(),A=Object(i.a)({},this._viewportProps),n=A.bearing,r=A.longitude;return Math.abs(n-t.bearing)>180&&(A.bearing=n<0?n+360:n-360),Math.abs(r-t.longitude)>180&&(A.longitude=r<0?r+360:r-360),A}},{key:"_zoomFromCenter",value:function(e){var t=this._viewportProps,A=t.width,n=t.height;return this.zoom({pos:[A/2,n/2],scale:e})}},{key:"_panFromCenter",value:function(e){var t=this._viewportProps,A=t.width,n=t.height;return this.pan({startPos:[A/2,n/2],pos:[A/2+e[0],n/2+e[1]]})}},{key:"_getUpdatedState",value:function(e){return new this.constructor(Object(i.a)({makeViewport:this.makeViewport},this._viewportProps,{},this._state,{},e))}},{key:"_applyConstraints",value:function(e){var t=e.maxZoom,A=e.minZoom,n=e.zoom;e.zoom=Object(c.clamp)(n,A,t);var r=e.maxPitch,i=e.minPitch,o=e.pitch;e.pitch=Object(c.clamp)(o,i,r);var a=e.normalize;return(void 0===a||a)&&Object.assign(e,Object(I.o)(e)),e}},{key:"_unproject",value:function(e){var t=this.makeViewport(this._viewportProps);return e&&t.unproject(e)}},{key:"_calculateNewZoom",value:function(e){var t=e.scale,A=e.startZoom,n=this._viewportProps,r=n.maxZoom,i=n.minZoom,o=A+Math.log2(t);return Object(c.clamp)(o,i,r)}},{key:"_calculateNewPitchAndBearing",value:function(e){var t=e.deltaScaleX,A=e.deltaScaleY,n=e.startBearing,r=e.startPitch;A=Object(c.clamp)(A,-1,1);var i=this._viewportProps,o=i.minPitch,a=i.maxPitch,s=r;return A>0?s=r+A*(a-r):A<0&&(s=r-A*(o-r)),{pitch:s,bearing:n+180*t}}},{key:"_getRotationParams",value:function(e,t){var A=e[0]-t[0],n=e[1]-t[1],r=e[1],i=t[1],o=this._viewportProps,a=o.width,s=o.height,g=A/a,c=0;return n>0?Math.abs(s-i)>5&&(c=n/(i-s)*1.2):n<0&&i>5&&(c=1-r/i),{deltaScaleX:g,deltaScaleY:c=Math.min(1,Math.max(-1,c))}}}]),A}(l.a),v=function(e){Object(s.a)(A,e);var t=Object(g.a)(A);function A(e){return Object(o.a)(this,A),e.dragMode=e.dragMode||"pan",t.call(this,y,e)}return Object(a.a)(A,[{key:"setProps",value:function(e){var t=this.controllerStateProps;Object(r.a)(Object(n.a)(A.prototype),"setProps",this).call(this,e),(!t||t.height!==e.height)&&this.updateViewport(new this.ControllerState(Object(i.a)({makeViewport:this.makeViewport},this.controllerStateProps,{},this._state)))}},{key:"linearTransitionProps",get:function(){return["longitude","latitude","zoom","bearing","pitch"]}}]),A}(u.a)},function(e,t,A){"use strict";var n=A(7),r=A(1),i=A(4),o=A(16),a=A(17),s=A(9),g=A(10),c=A(575),u=A(655),l=A(576),I=A(36),C=A(384),h=A(718),f=A(427),d=A(422),B=A(135),p=A(6),E=A(326),Q=A(577),y=A(89),v=function(e){Object(s.a)(A,e);var t=Object(g.a)(A);function A(e){Object(r.a)(this,A);var i=e.fp64,o=e.IndexType,a=void 0===o?Uint32Array:o;return t.call(this,Object(n.a)({},e,{attributes:{positions:{size:3,type:i?Float64Array:Float32Array},vertexValid:{type:Uint8ClampedArray,size:1},indices:{type:a,size:1}}}))}return Object(i.a)(A,[{key:"get",value:function(e){var t=this.attributes;return"indices"===e?t.indices&&t.indices.subarray(0,this.vertexCount):t[e]}},{key:"updateGeometry",value:function(e){Object(a.a)(Object(o.a)(A.prototype),"updateGeometry",this).call(this,e);var t=this.buffers.indices;t&&(this.vertexCount=(t.value||t).length)}},{key:"normalizeGeometry",value:function(e){if(this.normalize){if(e=E.b(e,this.positionSize),this.opts.resolution)return Object(y.b)(e.positions||e,e.holeIndices,{size:this.positionSize,gridResolution:this.opts.resolution,edgeTypes:!0});if(this.opts.wrapLongitude)return Object(y.c)(e.positions||e,e.holeIndices,{size:this.positionSize,maxLatitude:86,edgeTypes:!0})}return e}},{key:"getGeometrySize",value:function(e){if(Array.isArray(e)&&!Number.isFinite(e[0])){var t,A=0,n=Object(p.a)(e);try{for(n.s();!(t=n.n()).done;){var r=t.value;A+=this.getGeometrySize(r)}}catch(i){n.e(i)}finally{n.f()}return A}return(e.positions||e).length/this.positionSize}},{key:"getGeometryFromBuffer",value:function(e){return this.normalize||!this.buffers.indices?Object(a.a)(Object(o.a)(A.prototype),"getGeometryFromBuffer",this).call(this,e):function(){return null}}},{key:"updateGeometryAttributes",value:function(e,t){if(Array.isArray(e)&&!Number.isFinite(e[0])){var A,n=Object(p.a)(e);try{for(n.s();!(A=n.n()).done;){var r=A.value,i=this.getGeometrySize(r);t.geometrySize=i,this.updateGeometryAttributes(r,t),t.vertexStart+=i,t.indexStart=this.indexStarts[t.geometryIndex+1]}}catch(o){n.e(o)}finally{n.f()}}else this._updateIndices(e,t),this._updatePositions(e,t),this._updateVertexValid(e,t)}},{key:"_updateIndices",value:function(e,t){var A=t.geometryIndex,n=t.vertexStart,r=t.indexStart,i=this.attributes,o=this.indexStarts,a=this.typedArrayManager,s=i.indices;if(s){var g=r,c=E.a(e,this.positionSize,this.opts.preproject);s=a.allocate(s,r+c.length,{copy:!0});for(var u=0;u2?o[s*i+2]:0;r[3*a]=g,r[3*a+1]=c,r[3*a+2]=u}}},{key:"_updateVertexValid",value:function(e,t){var A=t.vertexStart,n=t.geometrySize,r=this.attributes.vertexValid,i=this.positionSize,o=e&&e.holeIndices;if(e&&e.edgeTypes?r.set(e.edgeTypes,A):r.fill(1,A,A+n),o)for(var a=0;a2&&void 0!==arguments[2]?arguments[2]:[],n=this.positionSize;t*n>=e.length&&(t+=1-e.length/n);var r=t*n;return A[0]=e[r],A[1]=e[r+1],A[2]=3===n&&e[r+2]||0,A}},{key:"isClosed",value:function(e){if(!this.normalize)return this.opts.loop;var t=this.positionSize,A=e.length-t;return e[0]===e[A]&&e[1]===e[A+1]&&(2===t||e[2]===e[A+2])}}]),A}(B.a);A.d(t,"a",(function(){return m}));var Q=[0,0,0,255],y={widthUnits:"meters",widthScale:{type:"number",min:0,value:1},widthMinPixels:{type:"number",min:0,value:0},widthMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},jointRounded:!1,capRounded:!1,miterLimit:{type:"number",min:0,value:4},billboard:!1,_pathType:null,getPath:{type:"accessor",value:function(e){return e.path}},getColor:{type:"accessor",value:Q},getWidth:{type:"accessor",value:1},rounded:{deprecatedFor:["jointRounded","capRounded"]}},v={enter:function(e,t){return t.length?t.subarray(t.length-e.length):e}},m=function(e){Object(s.a)(A,e);var t=Object(g.a)(A);function A(){return Object(r.a)(this,A),t.apply(this,arguments)}return Object(i.a)(A,[{key:"getShaders",value:function(){return Object(a.a)(Object(o.a)(A.prototype),"getShaders",this).call(this,{vs:"#define SHADER_NAME path-layer-vertex-shader\n\nattribute vec2 positions;\n\nattribute float instanceTypes;\nattribute vec3 instanceStartPositions;\nattribute vec3 instanceEndPositions;\nattribute vec3 instanceLeftPositions;\nattribute vec3 instanceRightPositions;\nattribute vec3 instanceLeftPositions64Low;\nattribute vec3 instanceStartPositions64Low;\nattribute vec3 instanceEndPositions64Low;\nattribute vec3 instanceRightPositions64Low;\nattribute float instanceStrokeWidths;\nattribute vec4 instanceColors;\nattribute vec3 instancePickingColors;\n\nuniform float widthScale;\nuniform float widthMinPixels;\nuniform float widthMaxPixels;\nuniform float jointType;\nuniform float capType;\nuniform float miterLimit;\nuniform bool billboard;\nuniform int widthUnits;\n\nuniform float opacity;\n\nvarying vec4 vColor;\nvarying vec2 vCornerOffset;\nvarying float vMiterLength;\nvarying vec2 vPathPosition;\nvarying float vPathLength;\nvarying float vJointType;\n\nconst float EPSILON = 0.001;\nconst vec3 ZERO_OFFSET = vec3(0.0);\n\nfloat flipIfTrue(bool flag) {\n return -(float(flag) * 2. - 1.);\n}\nvec3 lineJoin(\n vec3 prevPoint, vec3 currPoint, vec3 nextPoint,\n vec2 width\n) {\n bool isEnd = positions.x > 0.0;\n float sideOfPath = positions.y;\n float isJoint = float(sideOfPath == 0.0);\n\n vec3 deltaA3 = (currPoint - prevPoint);\n vec3 deltaB3 = (nextPoint - currPoint);\n\n mat3 rotationMatrix;\n bool needsRotation = !billboard && project_needs_rotation(currPoint, rotationMatrix);\n if (needsRotation) {\n deltaA3 = deltaA3 * rotationMatrix;\n deltaB3 = deltaB3 * rotationMatrix;\n }\n vec2 deltaA = deltaA3.xy / width;\n vec2 deltaB = deltaB3.xy / width;\n\n float lenA = length(deltaA);\n float lenB = length(deltaB);\n\n vec2 dirA = lenA > 0. ? normalize(deltaA) : vec2(0.0, 0.0);\n vec2 dirB = lenB > 0. ? normalize(deltaB) : vec2(0.0, 0.0);\n\n vec2 perpA = vec2(-dirA.y, dirA.x);\n vec2 perpB = vec2(-dirB.y, dirB.x);\n vec2 tangent = dirA + dirB;\n tangent = length(tangent) > 0. ? normalize(tangent) : perpA;\n vec2 miterVec = vec2(-tangent.y, tangent.x);\n vec2 dir = isEnd ? dirA : dirB;\n vec2 perp = isEnd ? perpA : perpB;\n float L = isEnd ? lenA : lenB;\n float sinHalfA = abs(dot(miterVec, perp));\n float cosHalfA = abs(dot(dirA, miterVec));\n float turnDirection = flipIfTrue(dirA.x * dirB.y >= dirA.y * dirB.x);\n float cornerPosition = sideOfPath * turnDirection;\n\n float miterSize = 1.0 / max(sinHalfA, EPSILON);\n miterSize = mix(\n min(miterSize, max(lenA, lenB) / max(cosHalfA, EPSILON)),\n miterSize,\n step(0.0, cornerPosition)\n );\n\n vec2 offsetVec = mix(miterVec * miterSize, perp, step(0.5, cornerPosition))\n * (sideOfPath + isJoint * turnDirection);\n bool isStartCap = lenA == 0.0 || (!isEnd && (instanceTypes == 1.0 || instanceTypes == 3.0));\n bool isEndCap = lenB == 0.0 || (isEnd && (instanceTypes == 2.0 || instanceTypes == 3.0));\n bool isCap = isStartCap || isEndCap;\n if (isCap) {\n offsetVec = mix(perp * sideOfPath, dir * capType * 4.0 * flipIfTrue(isStartCap), isJoint);\n vJointType = capType;\n } else {\n vJointType = jointType;\n }\n vPathLength = L;\n vCornerOffset = offsetVec;\n vMiterLength = dot(vCornerOffset, miterVec * turnDirection);\n vMiterLength = isCap ? isJoint : vMiterLength;\n\n vec2 offsetFromStartOfPath = vCornerOffset + deltaA * float(isEnd);\n vPathPosition = vec2(\n dot(offsetFromStartOfPath, perp),\n dot(offsetFromStartOfPath, dir)\n );\n geometry.uv = vPathPosition;\n\n float isValid = step(instanceTypes, 3.5);\n vec3 offset = vec3(offsetVec * width * isValid, 0.0);\n\n if (needsRotation) {\n offset = rotationMatrix * offset;\n }\n return currPoint + offset;\n}\nvoid clipLine(inout vec4 position, vec4 refPosition) {\n if (position.w < EPSILON) {\n float r = (EPSILON - refPosition.w) / (position.w - refPosition.w);\n position = refPosition + (position - refPosition) * r;\n }\n}\n\nvoid main() {\n geometry.pickingColor = instancePickingColors;\n\n vColor = vec4(instanceColors.rgb, instanceColors.a * opacity);\n\n float isEnd = positions.x;\n\n vec3 prevPosition = mix(instanceLeftPositions, instanceStartPositions, isEnd);\n vec3 prevPosition64Low = mix(instanceLeftPositions64Low, instanceStartPositions64Low, isEnd);\n\n vec3 currPosition = mix(instanceStartPositions, instanceEndPositions, isEnd);\n vec3 currPosition64Low = mix(instanceStartPositions64Low, instanceEndPositions64Low, isEnd);\n\n vec3 nextPosition = mix(instanceEndPositions, instanceRightPositions, isEnd);\n vec3 nextPosition64Low = mix(instanceEndPositions64Low, instanceRightPositions64Low, isEnd);\n\n geometry.worldPosition = currPosition;\n vec2 widthPixels = vec2(clamp(\n project_size_to_pixel(instanceStrokeWidths * widthScale, widthUnits),\n widthMinPixels, widthMaxPixels) / 2.0);\n vec3 width;\n\n if (billboard) {\n vec4 prevPositionScreen = project_position_to_clipspace(prevPosition, prevPosition64Low, ZERO_OFFSET);\n vec4 currPositionScreen = project_position_to_clipspace(currPosition, currPosition64Low, ZERO_OFFSET, geometry.position);\n vec4 nextPositionScreen = project_position_to_clipspace(nextPosition, nextPosition64Low, ZERO_OFFSET);\n\n clipLine(prevPositionScreen, currPositionScreen);\n clipLine(nextPositionScreen, currPositionScreen);\n clipLine(currPositionScreen, mix(nextPositionScreen, prevPositionScreen, isEnd));\n\n width = vec3(widthPixels, 0.0);\n DECKGL_FILTER_SIZE(width, geometry);\n\n vec3 pos = lineJoin(\n prevPositionScreen.xyz / prevPositionScreen.w,\n currPositionScreen.xyz / currPositionScreen.w,\n nextPositionScreen.xyz / nextPositionScreen.w,\n project_pixel_size_to_clipspace(width.xy)\n );\n\n gl_Position = vec4(pos * currPositionScreen.w, currPositionScreen.w);\n } else {\n prevPosition = project_position(prevPosition, prevPosition64Low);\n currPosition = project_position(currPosition, currPosition64Low);\n nextPosition = project_position(nextPosition, nextPosition64Low);\n\n width = vec3(project_pixel_size(widthPixels), 0.0);\n DECKGL_FILTER_SIZE(width, geometry);\n\n vec4 pos = vec4(\n lineJoin(prevPosition, currPosition, nextPosition, width.xy),\n 1.0);\n geometry.position = pos;\n gl_Position = project_common_position_to_clipspace(pos);\n }\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#define SHADER_NAME path-layer-fragment-shader\n\nprecision highp float;\n\nuniform float miterLimit;\n\nvarying vec4 vColor;\nvarying vec2 vCornerOffset;\nvarying float vMiterLength;\nvarying vec2 vPathPosition;\nvarying float vPathLength;\nvarying float vJointType;\n\nvoid main(void) {\n geometry.uv = vPathPosition;\n\n if (vPathPosition.y < 0.0 || vPathPosition.y > vPathLength) {\n if (vJointType > 0.5 && length(vCornerOffset) > 1.0) {\n discard;\n }\n if (vJointType < 0.5 && vMiterLength > miterLimit + 1.0) {\n discard;\n }\n }\n gl_FragColor = vColor;\n\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n",modules:[c.a,u.a]})}},{key:"initializeState",value:function(){var e=this;this.getAttributeManager().addInstanced({positions:{size:3,vertexOffset:1,type:5130,fp64:this.use64bitPositions(),transition:v,accessor:"getPath",update:this.calculatePositions,noAlloc:!0,shaderAttributes:{instanceLeftPositions:{vertexOffset:0},instanceStartPositions:{vertexOffset:1},instanceEndPositions:{vertexOffset:2},instanceRightPositions:{vertexOffset:3}}},instanceTypes:{size:1,type:5121,update:this.calculateSegmentTypes,noAlloc:!0},instanceStrokeWidths:{size:1,accessor:"getWidth",transition:v,defaultValue:1},instanceColors:{size:this.props.colorFormat.length,type:5121,normalized:!0,accessor:"getColor",transition:v,defaultValue:Q},instancePickingColors:{size:3,type:5121,accessor:function(t,A){var n=A.index,r=A.target;return e.encodePickingColor(t&&t.__source?t.__source.index:n,r)}}}),this.setState({pathTesselator:new E({fp64:this.use64bitPositions()})}),this.props.getDashArray&&!this.props.extensions.length&&l.a.removed("getDashArray","PathStyleExtension")()}},{key:"updateState",value:function(e){var t=e.oldProps,n=e.props,r=e.changeFlags;Object(a.a)(Object(o.a)(A.prototype),"updateState",this).call(this,{props:n,oldProps:t,changeFlags:r});var i=this.getAttributeManager();if(r.dataChanged||r.updateTriggersChanged&&(r.updateTriggersChanged.all||r.updateTriggersChanged.getPath)){var s=this.state.pathTesselator,g=n.data.attributes||{};s.updateGeometry({data:n.data,geometryBuffer:g.getPath,buffers:g,normalize:!n._pathType,loop:"loop"===n._pathType,getGeometry:n.getPath,positionFormat:n.positionFormat,wrapLongitude:n.wrapLongitude,resolution:this.context.viewport.resolution,dataChanged:r.dataChanged}),this.setState({numInstances:s.instanceCount,startIndices:s.vertexStarts}),r.dataChanged||i.invalidateAll()}if(r.extensionsChanged){var c,u=this.context.gl;null===(c=this.state.model)||void 0===c||c.delete(),this.state.model=this._getModel(u),i.invalidateAll()}}},{key:"getPickingInfo",value:function(e){var t=Object(a.a)(Object(o.a)(A.prototype),"getPickingInfo",this).call(this,e),n=t.index,r=this.props.data;return r[0]&&r[0].__source&&(t.object=r.find((function(e){return e.__source.index===n}))),t}},{key:"disablePickingIndex",value:function(e){var t=this.props.data;if(t[0]&&t[0].__source)for(var A=0;A0){var A=function(e){for(var t,A=e.icons,n=e.buffer,r=e.mapping,i=void 0===r?{}:r,o=e.xOffset,a=void 0===o?0:o,s=e.yOffset,g=void 0===s?0:s,c=e.rowHeight,u=void 0===c?0:c,l=e.canvasWidth,I=[],C=0;Cl&&(R(i,I,g),a=0,g=u+g+n,u=0,I=[]),I.push({icon:h,xOffset:a}),a=a+d+n,u=Math.max(u,f)}}return I.length>0&&R(i,I,g),{mapping:i,rowHeight:u,xOffset:a,yOffset:g,canvasWidth:l,canvasHeight:(t=u+g+n,Math.pow(2,Math.ceil(Math.log2(t))))}}({icons:t,buffer:this._buffer,canvasWidth:this._canvasWidth,mapping:this._mapping,rowHeight:this._rowHeight,xOffset:this._xOffset,yOffset:this._yOffset}),n=A.mapping,i=A.xOffset,o=A.yOffset,a=A.rowHeight,s=A.canvasHeight;this._rowHeight=a,this._mapping=n,this._xOffset=i,this._yOffset=o,this._canvasHeight=s,this._texture||(this._texture=new y.a(this.gl,{width:this._canvasWidth,height:this._canvasHeight,parameters:S})),this._texture.height!==this._canvasHeight&&(this._texture=function(e,t,A,n){var r=t.width,i=t.height,o=Object(E.a)(t,{width:A,height:n});return Object(Q.b)(t,o,{targetY:0,width:r,height:i}),t.delete(),o}(this.gl,this._texture,this._canvasWidth,this._canvasHeight)),this.onUpdate(),this._loadIcons(t)}}},{key:"_loadIcons",value:function(e){var t,A=this,n=this._canvas.getContext("2d"),r=Object(B.a)(e);try{var i=function(){var e=t.value;A._pendingCount++,Object(m.a)(e.url,v.a,A._loadOptions).then((function(t){var r=F(e),i=A._mapping[r],o=i.x,a=i.y,s=i.width,g=i.height,c=function(e,t,A,n){return A===t.width&&n===t.height?t:(e.canvas.height=n,e.canvas.width=A,e.clearRect(0,0,e.canvas.width,e.canvas.height),e.drawImage(t,0,0,t.width,t.height,0,0,A,n),e.canvas)}(n,t,s,g);A._texture.setSubImageData({data:c,x:o,y:a,width:s,height:g}),A._texture.generateMipmap(),A.onUpdate()})).catch((function(t){A.onError({url:e.url,source:e.source,sourceIndex:e.sourceIndex,loadOptions:A._loadOptions,error:t})})).finally((function(){A._pendingCount--}))};for(r.s();!(t=r.n()).done;)i()}catch(o){r.e(o)}finally{r.f()}}},{key:"isLoaded",get:function(){return 0===this._pendingCount}}]),e}();A.d(t,"a",(function(){return x}));var G=[0,0,0,255],k={iconAtlas:{type:"image",value:null,async:!0},iconMapping:{type:"object",value:{},async:!0},sizeScale:{type:"number",value:1,min:0},billboard:!0,sizeUnits:"pixels",sizeMinPixels:{type:"number",min:0,value:0},sizeMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},alphaCutoff:{type:"number",value:.05,min:0,max:1},getPosition:{type:"accessor",value:function(e){return e.position}},getIcon:{type:"accessor",value:function(e){return e.icon}},getColor:{type:"accessor",value:G},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},onIconError:{type:"function",value:null,compare:!1,optional:!0}},x=function(e){Object(g.a)(A,e);var t=Object(c.a)(A);function A(){return Object(i.a)(this,A),t.apply(this,arguments)}return Object(o.a)(A,[{key:"getShaders",value:function(){return Object(s.a)(Object(a.a)(A.prototype),"getShaders",this).call(this,{vs:"#define SHADER_NAME icon-layer-vertex-shader\n\nattribute vec2 positions;\n\nattribute vec3 instancePositions;\nattribute vec3 instancePositions64Low;\nattribute float instanceSizes;\nattribute float instanceAngles;\nattribute vec4 instanceColors;\nattribute vec3 instancePickingColors;\nattribute vec4 instanceIconFrames;\nattribute float instanceColorModes;\nattribute vec2 instanceOffsets;\nattribute vec2 instancePixelOffset;\n\nuniform float sizeScale;\nuniform vec2 iconsTextureDim;\nuniform float sizeMinPixels;\nuniform float sizeMaxPixels;\nuniform bool billboard;\nuniform int sizeUnits;\n\nvarying float vColorMode;\nvarying vec4 vColor;\nvarying vec2 vTextureCoords;\nvarying vec2 uv;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = angle * PI / 180.0;\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n\n vec2 iconSize = instanceIconFrames.zw;\n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * sizeScale, sizeUnits), \n sizeMinPixels, sizeMaxPixels\n );\n float instanceScale = iconSize.y == 0.0 ? 0.0 : sizePixels / iconSize.y;\n vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\n pixelOffset += instancePixelOffset;\n pixelOffset.y *= -1.0;\n\n if (billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n DECKGL_FILTER_SIZE(offset_common, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); \n }\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n vTextureCoords = mix(\n instanceIconFrames.xy,\n instanceIconFrames.xy + iconSize,\n (positions.xy + 1.0) / 2.0\n ) / iconsTextureDim;\n\n vColor = instanceColors;\n DECKGL_FILTER_COLOR(vColor, geometry);\n\n vColorMode = instanceColorModes;\n}\n",fs:"#define SHADER_NAME icon-layer-fragment-shader\n\nprecision highp float;\n\nuniform float opacity;\nuniform sampler2D iconsTexture;\nuniform float alphaCutoff;\n\nvarying float vColorMode;\nvarying vec4 vColor;\nvarying vec2 vTextureCoords;\nvarying vec2 uv;\n\nvoid main(void) {\n geometry.uv = uv;\n\n vec4 texColor = texture2D(iconsTexture, vTextureCoords);\n vec3 color = mix(texColor.rgb, vColor.rgb, vColorMode);\n float a = texColor.a * opacity * vColor.a;\n\n if (a < alphaCutoff) {\n discard;\n }\n\n gl_FragColor = vec4(color, a);\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n",modules:[u.a,l.a]})}},{key:"initializeState",value:function(){this.state={iconManager:new D(this.context.gl,{onUpdate:this._onUpdate.bind(this),onError:this._onError.bind(this)})},this.getAttributeManager().addInstanced({instancePositions:{size:3,type:5130,fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,accessor:"getSize",defaultValue:1},instanceOffsets:{size:2,accessor:"getIcon",transform:this.getInstanceOffset},instanceIconFrames:{size:4,accessor:"getIcon",transform:this.getInstanceIconFrame},instanceColorModes:{size:1,type:5121,accessor:"getIcon",transform:this.getInstanceColorMode},instanceColors:{size:this.props.colorFormat.length,type:5121,normalized:!0,transition:!0,accessor:"getColor",defaultValue:G},instanceAngles:{size:1,transition:!0,accessor:"getAngle"},instancePixelOffset:{size:2,transition:!0,accessor:"getPixelOffset"}})}},{key:"updateState",value:function(e){var t=e.oldProps,n=e.props,r=e.changeFlags;Object(s.a)(Object(a.a)(A.prototype),"updateState",this).call(this,{props:n,oldProps:t,changeFlags:r});var i=this.getAttributeManager(),o=n.iconAtlas,g=n.iconMapping,c=n.data,u=n.getIcon,l=this.state.iconManager;l.setProps({loadOptions:n.loadOptions});var I=!1;if(o||this.internalState.isAsyncPropLoading("iconAtlas")?(t.iconAtlas!==n.iconAtlas&&l.setProps({iconAtlas:o,autoPacking:!1}),t.iconMapping!==n.iconMapping&&(l.setProps({iconMapping:g}),I=!0)):l.setProps({autoPacking:!0}),(r.dataChanged||r.updateTriggersChanged&&(r.updateTriggersChanged.all||r.updateTriggersChanged.getIcon))&&l.setProps({data:c,getIcon:u}),I&&(i.invalidate("instanceOffsets"),i.invalidate("instanceIconFrames"),i.invalidate("instanceColorModes")),r.extensionsChanged){var C,h=this.context.gl;null===(C=this.state.model)||void 0===C||C.delete(),this.state.model=this._getModel(h),i.invalidateAll()}}},{key:"finalizeState",value:function(){Object(s.a)(Object(a.a)(A.prototype),"finalizeState",this).call(this),this.state.iconManager.finalize()}},{key:"draw",value:function(e){var t=e.uniforms,A=this.props,n=A.sizeScale,r=A.sizeMinPixels,i=A.sizeMaxPixels,o=A.sizeUnits,a=A.billboard,s=A.alphaCutoff,g=this.state.iconManager.getTexture();g&&this.state.model.setUniforms(t).setUniforms({iconsTexture:g,iconsTextureDim:[g.width,g.height],sizeUnits:I.d[o],sizeScale:n,sizeMinPixels:r,sizeMaxPixels:i,billboard:a,alphaCutoff:s}).draw()}},{key:"_getModel",value:function(e){return new f.a(e,Object(r.a)({},this.getShaders(),{id:this.props.id,geometry:new d.a({drawMode:6,attributes:{positions:{size:2,value:new Float32Array([-1,-1,-1,1,1,1,1,-1])}}}),isInstanced:!0}))}},{key:"_onUpdate",value:function(){this.setNeedsRedraw()}},{key:"_onError",value:function(e){var t=this.getCurrentLayer().props.onIconError;t?t(e):C.a.error(e.error)()}},{key:"getInstanceOffset",value:function(e){var t=this.state.iconManager.getIconMapping(e);return[t.width/2-t.anchorX||0,t.height/2-t.anchorY||0]}},{key:"getInstanceColorMode",value:function(e){return this.state.iconManager.getIconMapping(e).mask?1:0}},{key:"getInstanceIconFrame",value:function(e){var t=this.state.iconManager.getIconMapping(e);return[t.x||0,t.y||0,t.width||0,t.height||0]}},{key:"isLoaded",get:function(){return Object(s.a)(Object(a.a)(A.prototype),"isLoaded",this)&&this.state.iconManager.isLoaded}}]),A}(h.a);x.layerName="IconLayer",x.defaultProps=k},function(e,t,A){"use strict";A.r(t);function n(e,t,A){void 0===A&&(A={});var n={type:"Feature"};return(0===A.id||A.id)&&(n.id=A.id),A.bbox&&(n.bbox=A.bbox),n.properties=t||{},n.geometry=e,n}function r(e,t,A){if(void 0===A&&(A={}),!e)throw new Error("coordinates is required");if(!Array.isArray(e))throw new Error("coordinates must be an Array");if(e.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!i(e[0])||!i(e[1]))throw new Error("coordinates must contain numbers");return n({type:"Point",coordinates:e},t,A)}function i(e){return!isNaN(e)&&null!==e&&!Array.isArray(e)}function o(e,t,A){if(null!==e)for(var n,r,i,a,s,g,c,u,l=0,I=0,C=e.type,h="FeatureCollection"===C,f="Feature"===C,d=h?e.features.length:1,B=0;Be[0]&&(t[0]=e[0]),t[1]>e[1]&&(t[1]=e[1]),t[2]=0&&e=0&&e2&&void 0!==arguments[2]?arguments[2]:u,r=n,o=!0;switch(A=t===i.a.LNGLAT_OFFSETS||t===i.a.METER_OFFSETS?n:e.isGeospatial?[Math.fround(e.longitude),Math.fround(e.latitude),0]:null,e.projectionMode){case i.c.WEB_MERCATOR:t!==i.a.LNGLAT&&t!==i.a.CARTESIAN||(A=[0,0,0],o=!1);break;case i.c.WEB_MERCATOR_AUTO_OFFSET:t===i.a.LNGLAT?r=A:t===i.a.CARTESIAN&&(r=[Math.fround(e.center[0]),Math.fround(e.center[1]),0],A=e.unprojectPosition(r),r[0]-=n[0],r[1]-=n[1],r[2]-=n[2]);break;case i.c.IDENTITY:r=e.position.map(Math.fround);break;case i.c.GLOBE:o=!1,A=null;break;default:o=!1}return r[2]=r[2]||0,{geospatialOrigin:A,shaderCoordinateOrigin:r,offsetMode:o}}function C(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.viewport,A=e.devicePixelRatio,n=void 0===A?1:A,r=e.modelMatrix,o=void 0===r?null:r,a=e.coordinateSystem,s=void 0===a?i.a.DEFAULT:a,c=e.coordinateOrigin,u=e.autoWrapLongitude,I=void 0!==u&&u;s===i.a.DEFAULT&&(s=t.isGeospatial?i.a.LNGLAT:i.a.CARTESIAN);var C=l({viewport:t,devicePixelRatio:n,coordinateSystem:s,coordinateOrigin:c});return C.project_uWrapLongitude=I,C.project_uModelMatrix=o||g,C}},function(e,t,A){"use strict";A.d(t,"a",(function(){return i}));var n=A(1),r=A(4),i=function(){function e(t){Object(n.a)(this,e),this._viewportProps=this._applyConstraints(t)}return Object(r.a)(e,[{key:"getViewportProps",value:function(){return this._viewportProps}},{key:"getState",value:function(){return this._state}},{key:"shortestPathFrom",value:function(e){return this._viewportProps}},{key:"_applyConstraints",value:function(e){return e}}]),e}()},function(e,t,A){"use strict";var n=A(11),r=A(6),i=A(8),o=A(36),a=A(223),s=A(23),g=A(173),c=A(42),u=Object(g.a)((function(e){var t=e.viewport,A=e.center;return new s.Matrix4(t.viewProjectionMatrix).invert().transform(A)})),l=Object(g.a)((function(e){var t,A=e.viewport,o=e.shadowMatrices,a=[],g=A.pixelUnprojectionMatrix,u=A.isGeospatial?void 0:1,l=[[0,0,u],[A.width,0,u],[0,A.height,u],[A.width,A.height,u],[0,0,-1],[A.width,0,-1],[0,A.height,-1],[A.width,A.height,-1]].map((function(e){return function(e,t){var A=Object(i.a)(e,3),n=A[0],r=A[1],o=A[2],a=Object(c.p)([n,r,o],t);if(Number.isFinite(o))return a;return[a[0],a[1],0]}(e,g)})),I=Object(r.a)(o);try{var C=function(){var e=t.value,r=e.clone().translate(new s.Vector3(A.center).negate()),i=l.map((function(e){return r.transform(e)})),o=(new s.Matrix4).ortho({left:Math.min.apply(Math,Object(n.a)(i.map((function(e){return e[0]})))),right:Math.max.apply(Math,Object(n.a)(i.map((function(e){return e[0]})))),bottom:Math.min.apply(Math,Object(n.a)(i.map((function(e){return e[1]})))),top:Math.max.apply(Math,Object(n.a)(i.map((function(e){return e[1]})))),near:Math.min.apply(Math,Object(n.a)(i.map((function(e){return-e[2]})))),far:Math.max.apply(Math,Object(n.a)(i.map((function(e){return-e[2]}))))});a.push(o.multiplyRight(e))};for(I.s();!(t=I.n()).done;)C()}catch(h){I.e(h)}finally{I.f()}return a})),I=[0,0,0,1],C=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0];function h(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A={shadow_uDrawShadowMap:Boolean(e.drawToShadowMap),shadow_uUseShadowMap:!!e.shadowMaps&&e.shadowMaps.length>0,shadow_uColor:e.shadowColor||I,shadow_uLightId:e.shadowLightId||0,shadow_uLightCount:e.shadowMatrices.length},n=u({viewport:e.viewport,center:t.project_uCenter}),r=[],i=l({shadowMatrices:e.shadowMatrices,viewport:e.viewport}).slice(),a=0;a0?A["shadow_uShadowMap".concat(h)]=e.shadowMaps[h]:A["shadow_uShadowMap".concat(h)]=e.dummyShadowMap;return A}t.a={name:"shadow",dependencies:[a.a],vs:"\nconst int max_lights = 2;\nuniform mat4 shadow_uViewProjectionMatrices[max_lights];\nuniform vec4 shadow_uProjectCenters[max_lights];\nuniform bool shadow_uDrawShadowMap;\nuniform bool shadow_uUseShadowMap;\nuniform int shadow_uLightId;\nuniform float shadow_uLightCount;\n\nvarying vec3 shadow_vPosition[max_lights];\n\nvec4 shadow_setVertexPosition(vec4 position_commonspace) {\n if (shadow_uDrawShadowMap) {\n return project_common_position_to_clipspace(position_commonspace, shadow_uViewProjectionMatrices[shadow_uLightId], shadow_uProjectCenters[shadow_uLightId]);\n }\n if (shadow_uUseShadowMap) {\n for (int i = 0; i < max_lights; i++) {\n if(i < int(shadow_uLightCount)) {\n vec4 shadowMap_position = project_common_position_to_clipspace(position_commonspace, shadow_uViewProjectionMatrices[i], shadow_uProjectCenters[i]);\n shadow_vPosition[i] = (shadowMap_position.xyz / shadowMap_position.w + 1.0) / 2.0;\n }\n }\n }\n return gl_Position;\n}\n",fs:"\nconst int max_lights = 2;\nuniform bool shadow_uDrawShadowMap;\nuniform bool shadow_uUseShadowMap;\nuniform sampler2D shadow_uShadowMap0;\nuniform sampler2D shadow_uShadowMap1;\nuniform vec4 shadow_uColor;\nuniform float shadow_uLightCount;\n\nvarying vec3 shadow_vPosition[max_lights];\n\nconst vec4 bitPackShift = vec4(1.0, 255.0, 65025.0, 16581375.0);\nconst vec4 bitUnpackShift = 1.0 / bitPackShift;\nconst vec4 bitMask = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n\nfloat shadow_getShadowWeight(vec3 position, sampler2D shadowMap) {\n vec4 rgbaDepth = texture2D(shadowMap, position.xy);\n\n float z = dot(rgbaDepth, bitUnpackShift);\n return smoothstep(0.001, 0.01, position.z - z);\n}\n\nvec4 shadow_filterShadowColor(vec4 color) {\n if (shadow_uDrawShadowMap) {\n vec4 rgbaDepth = fract(gl_FragCoord.z * bitPackShift);\n rgbaDepth -= rgbaDepth.gbaa * bitMask;\n return rgbaDepth;\n }\n if (shadow_uUseShadowMap) {\n float shadowAlpha = 0.0;\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[0], shadow_uShadowMap0);\n if(shadow_uLightCount > 1.0) {\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[1], shadow_uShadowMap1);\n }\n shadowAlpha *= shadow_uColor.a / shadow_uLightCount;\n float blendedAlpha = shadowAlpha + color.a * (1.0 - shadowAlpha);\n\n return vec4(\n mix(color.rgb, shadow_uColor.rgb, shadowAlpha / blendedAlpha),\n blendedAlpha\n );\n }\n return color;\n}\n",inject:{"vs:DECKGL_FILTER_GL_POSITION":"\n position = shadow_setVertexPosition(geometry.position);\n ","fs:DECKGL_FILTER_COLOR":"\n color = shadow_filterShadowColor(color);\n "},getUniforms:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e.drawToShadowMap||e.shadowMaps&&e.shadowMaps.length>0){var A=e.shadowEnabled,n=void 0===A||A;return n&&e.shadowMatrices&&e.shadowMatrices.length>0?h(e,t):{shadow_uDrawShadowMap:!1,shadow_uUseShadowMap:!1}}return{}}}},function(e,t,A){var n;!function(r){"use strict";var i,o,a,s=9e15,g="0123456789abcdef",c="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",u="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",l={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-s,maxE:s,crypto:!1},I=!0,C="[DecimalError] Invalid argument: ",h=Math.floor,f=Math.pow,d=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,B=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,p=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,E=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Q=1e7,y=c.length-1,v=u.length-1,m={name:"[object Decimal]"};function b(e){var t,A,n,r=e.length-1,i="",o=e[0];if(r>0){for(i+=o,t=1;tA)throw Error(C+e)}function S(e,t,A,n){var r,i,o,a;for(i=e[0];i>=10;i/=10)--t;return--t<0?(t+=7,r=0):(r=Math.ceil((t+1)/7),t%=7),i=f(10,7-t),a=e[r]%i|0,null==n?t<3?(0==t?a=a/100|0:1==t&&(a=a/10|0),o=A<4&&99999==a||A>3&&49999==a||5e4==a||0==a):o=(A<4&&a+1==i||A>3&&a+1==i/2)&&(e[r+1]/i/100|0)==f(10,t-2)-1||(a==i/2||0==a)&&0==(e[r+1]/i/100|0):t<4?(0==t?a=a/1e3|0:1==t?a=a/100|0:2==t&&(a=a/10|0),o=(n||A<4)&&9999==a||!n&&A>3&&4999==a):o=((n||A<4)&&a+1==i||!n&&A>3&&a+1==i/2)&&(e[r+1]/i/1e3|0)==f(10,t-3)-1,o}function F(e,t,A){for(var n,r,i=[0],o=0,a=e.length;oA-1&&(void 0===i[n+1]&&(i[n+1]=0),i[n+1]+=i[n]/A|0,i[n]%=A)}return i.reverse()}m.absoluteValue=m.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),D(e)},m.ceil=function(){return D(new this.constructor(this),this.e+1,2)},m.comparedTo=m.cmp=function(e){var t,A,n,r,i=this,o=i.d,a=(e=new i.constructor(e)).d,s=i.s,g=e.s;if(!o||!a)return s&&g?s!==g?s:o===a?0:!o^s<0?1:-1:NaN;if(!o[0]||!a[0])return o[0]?s:a[0]?-g:0;if(s!==g)return s;if(i.e!==e.e)return i.e>e.e^s<0?1:-1;for(t=0,A=(n=o.length)<(r=a.length)?n:r;ta[t]^s<0?1:-1;return n===r?0:n>r^s<0?1:-1},m.cosine=m.cos=function(){var e,t,A=this,n=A.constructor;return A.d?A.d[0]?(e=n.precision,t=n.rounding,n.precision=e+Math.max(A.e,A.sd())+7,n.rounding=1,A=function(e,t){var A,n,r=t.d.length;r<32?(A=Math.ceil(r/3),n=(1/P(4,A)).toString()):(A=16,n="2.3283064365386962890625e-10");e.precision+=A,t=j(e,1,t.times(n),new e(1));for(var i=A;i--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=A,t}(n,V(n,A)),n.precision=e,n.rounding=t,D(2==a||3==a?A.neg():A,e,t,!0)):new n(1):new n(NaN)},m.cubeRoot=m.cbrt=function(){var e,t,A,n,r,i,o,a,s,g,c=this,u=c.constructor;if(!c.isFinite()||c.isZero())return new u(c);for(I=!1,(i=c.s*f(c.s*c,1/3))&&Math.abs(i)!=1/0?n=new u(i.toString()):(A=b(c.d),(i=((e=c.e)-A.length+1)%3)&&(A+=1==i||-2==i?"0":"00"),i=f(A,1/3),e=h((e+1)/3)-(e%3==(e<0?-1:2)),(n=new u(A=i==1/0?"5e"+e:(A=i.toExponential()).slice(0,A.indexOf("e")+1)+e)).s=c.s),o=(e=u.precision)+3;;)if(g=(s=(a=n).times(a).times(a)).plus(c),n=R(g.plus(c).times(a),g.plus(s),o+2,1),b(a.d).slice(0,o)===(A=b(n.d)).slice(0,o)){if("9999"!=(A=A.slice(o-3,o+1))&&(r||"4999"!=A)){+A&&(+A.slice(1)||"5"!=A.charAt(0))||(D(n,e+1,1),t=!n.times(n).times(n).eq(c));break}if(!r&&(D(a,e+1,0),a.times(a).times(a).eq(c))){n=a;break}o+=4,r=1}return I=!0,D(n,e,u.rounding,t)},m.decimalPlaces=m.dp=function(){var e,t=this.d,A=NaN;if(t){if(A=7*((e=t.length-1)-h(this.e/7)),e=t[e])for(;e%10==0;e/=10)A--;A<0&&(A=0)}return A},m.dividedBy=m.div=function(e){return R(this,new this.constructor(e))},m.dividedToIntegerBy=m.divToInt=function(e){var t=this.constructor;return D(R(this,new t(e),0,1,1),t.precision,t.rounding)},m.equals=m.eq=function(e){return 0===this.cmp(e)},m.floor=function(){return D(new this.constructor(this),this.e+1,3)},m.greaterThan=m.gt=function(e){return this.cmp(e)>0},m.greaterThanOrEqualTo=m.gte=function(e){var t=this.cmp(e);return 1==t||0===t},m.hyperbolicCosine=m.cosh=function(){var e,t,A,n,r,i=this,o=i.constructor,a=new o(1);if(!i.isFinite())return new o(i.s?1/0:NaN);if(i.isZero())return a;A=o.precision,n=o.rounding,o.precision=A+Math.max(i.e,i.sd())+4,o.rounding=1,(r=i.d.length)<32?t=(1/P(4,e=Math.ceil(r/3))).toString():(e=16,t="2.3283064365386962890625e-10"),i=j(o,1,i.times(t),new o(1),!0);for(var s,g=e,c=new o(8);g--;)s=i.times(i),i=a.minus(s.times(c.minus(s.times(c))));return D(i,o.precision=A,o.rounding=n,!0)},m.hyperbolicSine=m.sinh=function(){var e,t,A,n,r=this,i=r.constructor;if(!r.isFinite()||r.isZero())return new i(r);if(t=i.precision,A=i.rounding,i.precision=t+Math.max(r.e,r.sd())+4,i.rounding=1,(n=r.d.length)<3)r=j(i,2,r,r,!0);else{e=(e=1.4*Math.sqrt(n))>16?16:0|e,r=j(i,2,r=r.times(1/P(5,e)),r,!0);for(var o,a=new i(5),s=new i(16),g=new i(20);e--;)o=r.times(r),r=r.times(a.plus(o.times(s.times(o).plus(g))))}return i.precision=t,i.rounding=A,D(r,t,A,!0)},m.hyperbolicTangent=m.tanh=function(){var e,t,A=this,n=A.constructor;return A.isFinite()?A.isZero()?new n(A):(e=n.precision,t=n.rounding,n.precision=e+7,n.rounding=1,R(A.sinh(),A.cosh(),n.precision=e,n.rounding=t)):new n(A.s)},m.inverseCosine=m.acos=function(){var e,t=this,A=t.constructor,n=t.abs().cmp(1),r=A.precision,i=A.rounding;return-1!==n?0===n?t.isNeg()?N(A,r,i):new A(0):new A(NaN):t.isZero()?N(A,r+4,i).times(.5):(A.precision=r+6,A.rounding=1,t=t.asin(),e=N(A,r+4,i).times(.5),A.precision=r,A.rounding=i,e.minus(t))},m.inverseHyperbolicCosine=m.acosh=function(){var e,t,A=this,n=A.constructor;return A.lte(1)?new n(A.eq(1)?0:NaN):A.isFinite()?(e=n.precision,t=n.rounding,n.precision=e+Math.max(Math.abs(A.e),A.sd())+4,n.rounding=1,I=!1,A=A.times(A).minus(1).sqrt().plus(A),I=!0,n.precision=e,n.rounding=t,A.ln()):new n(A)},m.inverseHyperbolicSine=m.asinh=function(){var e,t,A=this,n=A.constructor;return!A.isFinite()||A.isZero()?new n(A):(e=n.precision,t=n.rounding,n.precision=e+2*Math.max(Math.abs(A.e),A.sd())+6,n.rounding=1,I=!1,A=A.times(A).plus(1).sqrt().plus(A),I=!0,n.precision=e,n.rounding=t,A.ln())},m.inverseHyperbolicTangent=m.atanh=function(){var e,t,A,n,r=this,i=r.constructor;return r.isFinite()?r.e>=0?new i(r.abs().eq(1)?r.s/0:r.isZero()?r:NaN):(e=i.precision,t=i.rounding,n=r.sd(),Math.max(n,e)<2*-r.e-1?D(new i(r),e,t,!0):(i.precision=A=n-r.e,r=R(r.plus(1),new i(1).minus(r),A+e,1),i.precision=e+4,i.rounding=1,r=r.ln(),i.precision=e,i.rounding=t,r.times(.5))):new i(NaN)},m.inverseSine=m.asin=function(){var e,t,A,n,r=this,i=r.constructor;return r.isZero()?new i(r):(t=r.abs().cmp(1),A=i.precision,n=i.rounding,-1!==t?0===t?((e=N(i,A+4,n).times(.5)).s=r.s,e):new i(NaN):(i.precision=A+6,i.rounding=1,r=r.div(new i(1).minus(r.times(r)).sqrt().plus(1)).atan(),i.precision=A,i.rounding=n,r.times(2)))},m.inverseTangent=m.atan=function(){var e,t,A,n,r,i,o,a,s,g=this,c=g.constructor,u=c.precision,l=c.rounding;if(g.isFinite()){if(g.isZero())return new c(g);if(g.abs().eq(1)&&u+4<=v)return(o=N(c,u+4,l).times(.25)).s=g.s,o}else{if(!g.s)return new c(NaN);if(u+4<=v)return(o=N(c,u+4,l).times(.5)).s=g.s,o}for(c.precision=a=u+10,c.rounding=1,e=A=Math.min(28,a/7+2|0);e;--e)g=g.div(g.times(g).plus(1).sqrt().plus(1));for(I=!1,t=Math.ceil(a/7),n=1,s=g.times(g),o=new c(g),r=g;-1!==e;)if(r=r.times(s),i=o.minus(r.div(n+=2)),r=r.times(s),void 0!==(o=i.plus(r.div(n+=2))).d[t])for(e=t;o.d[e]===i.d[e]&&e--;);return A&&(o=o.times(2<this.d.length-2},m.isNaN=function(){return!this.s},m.isNegative=m.isNeg=function(){return this.s<0},m.isPositive=m.isPos=function(){return this.s>0},m.isZero=function(){return!!this.d&&0===this.d[0]},m.lessThan=m.lt=function(e){return this.cmp(e)<0},m.lessThanOrEqualTo=m.lte=function(e){return this.cmp(e)<1},m.logarithm=m.log=function(e){var t,A,n,r,i,o,a,s,g=this.constructor,c=g.precision,u=g.rounding;if(null==e)e=new g(10),t=!0;else{if(A=(e=new g(e)).d,e.s<0||!A||!A[0]||e.eq(1))return new g(NaN);t=e.eq(10)}if(A=this.d,this.s<0||!A||!A[0]||this.eq(1))return new g(A&&!A[0]?-1/0:1!=this.s?NaN:A?0:1/0);if(t)if(A.length>1)i=!0;else{for(r=A[0];r%10===0;)r/=10;i=1!==r}if(I=!1,o=Z(this,a=c+5),n=t?x(g,a+10):Z(e,a),S((s=R(o,n,a,1)).d,r=c,u))do{if(o=Z(this,a+=10),n=t?x(g,a+10):Z(e,a),s=R(o,n,a,1),!i){+b(s.d).slice(r+1,r+15)+1==1e14&&(s=D(s,c+1,0));break}}while(S(s.d,r+=10,u));return I=!0,D(s,c,u)},m.minus=m.sub=function(e){var t,A,n,r,i,o,a,s,g,c,u,l,C=this,f=C.constructor;if(e=new f(e),!C.d||!e.d)return C.s&&e.s?C.d?e.s=-e.s:e=new f(e.d||C.s!==e.s?C:NaN):e=new f(NaN),e;if(C.s!=e.s)return e.s=-e.s,C.plus(e);if(g=C.d,l=e.d,a=f.precision,s=f.rounding,!g[0]||!l[0]){if(l[0])e.s=-e.s;else{if(!g[0])return new f(3===s?-0:0);e=new f(C)}return I?D(e,a,s):e}if(A=h(e.e/7),c=h(C.e/7),g=g.slice(),i=c-A){for((u=i<0)?(t=g,i=-i,o=l.length):(t=l,A=c,o=g.length),i>(n=Math.max(Math.ceil(a/7),o)+2)&&(i=n,t.length=1),t.reverse(),n=i;n--;)t.push(0);t.reverse()}else{for((u=(n=g.length)<(o=l.length))&&(o=n),n=0;n0;--n)g[o++]=0;for(n=l.length;n>i;){if(g[--n](o=(i=Math.ceil(a/7))>o?i+1:o+1)&&(r=o,A.length=1),A.reverse();r--;)A.push(0);A.reverse()}for((o=g.length)-(r=c.length)<0&&(r=o,A=c,c=g,g=A),t=0;r;)t=(g[--r]=g[r]+c[r]+t)/Q|0,g[r]%=Q;for(t&&(g.unshift(t),++n),o=g.length;0==g[--o];)g.pop();return e.d=g,e.e=k(g,n),I?D(e,a,s):e},m.precision=m.sd=function(e){var t,A=this;if(void 0!==e&&e!==!!e&&1!==e&&0!==e)throw Error(C+e);return A.d?(t=U(A.d),e&&A.e+1>t&&(t=A.e+1)):t=NaN,t},m.round=function(){var e=this,t=e.constructor;return D(new t(e),e.e+1,t.rounding)},m.sine=m.sin=function(){var e,t,A=this,n=A.constructor;return A.isFinite()?A.isZero()?new n(A):(e=n.precision,t=n.rounding,n.precision=e+Math.max(A.e,A.sd())+7,n.rounding=1,A=function(e,t){var A,n=t.d.length;if(n<3)return j(e,2,t,t);A=(A=1.4*Math.sqrt(n))>16?16:0|A,t=t.times(1/P(5,A)),t=j(e,2,t,t);for(var r,i=new e(5),o=new e(16),a=new e(20);A--;)r=t.times(t),t=t.times(i.plus(r.times(o.times(r).minus(a))));return t}(n,V(n,A)),n.precision=e,n.rounding=t,D(a>2?A.neg():A,e,t,!0)):new n(NaN)},m.squareRoot=m.sqrt=function(){var e,t,A,n,r,i,o=this,a=o.d,s=o.e,g=o.s,c=o.constructor;if(1!==g||!a||!a[0])return new c(!g||g<0&&(!a||a[0])?NaN:a?o:1/0);for(I=!1,0==(g=Math.sqrt(+o))||g==1/0?(((t=b(a)).length+s)%2==0&&(t+="0"),g=Math.sqrt(t),s=h((s+1)/2)-(s<0||s%2),n=new c(t=g==1/0?"5e"+s:(t=g.toExponential()).slice(0,t.indexOf("e")+1)+s)):n=new c(g.toString()),A=(s=c.precision)+3;;)if(n=(i=n).plus(R(o,i,A+2,1)).times(.5),b(i.d).slice(0,A)===(t=b(n.d)).slice(0,A)){if("9999"!=(t=t.slice(A-3,A+1))&&(r||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(D(n,s+1,1),e=!n.times(n).eq(o));break}if(!r&&(D(i,s+1,0),i.times(i).eq(o))){n=i;break}A+=4,r=1}return I=!0,D(n,s,c.rounding,e)},m.tangent=m.tan=function(){var e,t,A=this,n=A.constructor;return A.isFinite()?A.isZero()?new n(A):(e=n.precision,t=n.rounding,n.precision=e+10,n.rounding=1,(A=A.sin()).s=1,A=R(A,new n(1).minus(A.times(A)).sqrt(),e+10,0),n.precision=e,n.rounding=t,D(2==a||4==a?A.neg():A,e,t,!0)):new n(NaN)},m.times=m.mul=function(e){var t,A,n,r,i,o,a,s,g,c=this,u=c.constructor,l=c.d,C=(e=new u(e)).d;if(e.s*=c.s,!l||!l[0]||!C||!C[0])return new u(!e.s||l&&!l[0]&&!C||C&&!C[0]&&!l?NaN:l&&C?0*e.s:e.s/0);for(A=h(c.e/7)+h(e.e/7),(s=l.length)<(g=C.length)&&(i=l,l=C,C=i,o=s,s=g,g=o),i=[],n=o=s+g;n--;)i.push(0);for(n=g;--n>=0;){for(t=0,r=s+n;r>n;)a=i[r]+C[n]*l[r-n-1]+t,i[r--]=a%Q|0,t=a/Q|0;i[r]=(i[r]+t)%Q|0}for(;!i[--o];)i.pop();return t?++A:i.shift(),e.d=i,e.e=k(i,A),I?D(e,u.precision,u.rounding):e},m.toBinary=function(e,t){return K(this,2,e,t)},m.toDecimalPlaces=m.toDP=function(e,t){var A=this,n=A.constructor;return A=new n(A),void 0===e?A:(w(e,0,1e9),void 0===t?t=n.rounding:w(t,0,8),D(A,e+A.e+1,t))},m.toExponential=function(e,t){var A,n=this,r=n.constructor;return void 0===e?A=G(n,!0):(w(e,0,1e9),void 0===t?t=r.rounding:w(t,0,8),A=G(n=D(new r(n),e+1,t),!0,e+1)),n.isNeg()&&!n.isZero()?"-"+A:A},m.toFixed=function(e,t){var A,n,r=this,i=r.constructor;return void 0===e?A=G(r):(w(e,0,1e9),void 0===t?t=i.rounding:w(t,0,8),A=G(n=D(new i(r),e+r.e+1,t),!1,e+n.e+1)),r.isNeg()&&!r.isZero()?"-"+A:A},m.toFraction=function(e){var t,A,n,r,i,o,a,s,g,c,u,l,h=this,d=h.d,B=h.constructor;if(!d)return new B(h);if(g=A=new B(1),n=s=new B(0),o=(i=(t=new B(n)).e=U(d)-h.e-1)%7,t.d[0]=f(10,o<0?7+o:o),null==e)e=i>0?t:g;else{if(!(a=new B(e)).isInt()||a.lt(g))throw Error(C+a);e=a.gt(t)?i>0?t:g:a}for(I=!1,a=new B(b(d)),c=B.precision,B.precision=i=7*d.length*2;u=R(a,t,0,1,1),1!=(r=A.plus(u.times(n))).cmp(e);)A=n,n=r,r=g,g=s.plus(u.times(r)),s=r,r=t,t=a.minus(u.times(r)),a=r;return r=R(e.minus(A),n,0,1,1),s=s.plus(r.times(g)),A=A.plus(r.times(n)),s.s=g.s=h.s,l=R(g,n,i,1).minus(h).abs().cmp(R(s,A,i,1).minus(h).abs())<1?[g,n]:[s,A],B.precision=c,I=!0,l},m.toHexadecimal=m.toHex=function(e,t){return K(this,16,e,t)},m.toNearest=function(e,t){var A=this,n=A.constructor;if(A=new n(A),null==e){if(!A.d)return A;e=new n(1),t=n.rounding}else{if(e=new n(e),void 0===t?t=n.rounding:w(t,0,8),!A.d)return e.s?A:e;if(!e.d)return e.s&&(e.s=A.s),e}return e.d[0]?(I=!1,A=R(A,e,0,t,1).times(e),I=!0,D(A)):(e.s=A.s,A=e),A},m.toNumber=function(){return+this},m.toOctal=function(e,t){return K(this,8,e,t)},m.toPower=m.pow=function(e){var t,A,n,r,i,o,a=this,s=a.constructor,g=+(e=new s(e));if(!a.d||!e.d||!a.d[0]||!e.d[0])return new s(f(+a,g));if((a=new s(a)).eq(1))return a;if(n=s.precision,i=s.rounding,e.eq(1))return D(a,n,i);if((t=h(e.e/7))>=e.d.length-1&&(A=g<0?-g:g)<=9007199254740991)return r=M(s,a,A,n),e.s<0?new s(1).div(r):D(r,n,i);if((o=a.s)<0){if(ts.maxE+1||t0?o/0:0):(I=!1,s.rounding=a.s=1,A=Math.min(12,(t+"").length),(r=T(e.times(Z(a,n+A)),n)).d&&S((r=D(r,n+5,1)).d,n,i)&&(t=n+10,+b((r=D(T(e.times(Z(a,t+A)),t),t+5,1)).d).slice(n+1,n+15)+1==1e14&&(r=D(r,n+1,0))),r.s=o,I=!0,s.rounding=i,D(r,n,i))},m.toPrecision=function(e,t){var A,n=this,r=n.constructor;return void 0===e?A=G(n,n.e<=r.toExpNeg||n.e>=r.toExpPos):(w(e,1,1e9),void 0===t?t=r.rounding:w(t,0,8),A=G(n=D(new r(n),e,t),e<=n.e||n.e<=r.toExpNeg,e)),n.isNeg()&&!n.isZero()?"-"+A:A},m.toSignificantDigits=m.toSD=function(e,t){var A=this.constructor;return void 0===e?(e=A.precision,t=A.rounding):(w(e,1,1e9),void 0===t?t=A.rounding:w(t,0,8)),D(new A(this),e,t)},m.toString=function(){var e=this,t=e.constructor,A=G(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+A:A},m.truncated=m.trunc=function(){return D(new this.constructor(this),this.e+1,1)},m.valueOf=m.toJSON=function(){var e=this,t=e.constructor,A=G(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+A:A};var R=function(){function e(e,t,A){var n,r=0,i=e.length;for(e=e.slice();i--;)n=e[i]*t+r,e[i]=n%A|0,r=n/A|0;return r&&e.unshift(r),e}function t(e,t,A,n){var r,i;if(A!=n)i=A>n?1:-1;else for(r=i=0;rt[r]?1:-1;break}return i}function A(e,t,A,n){for(var r=0;A--;)e[A]-=r,r=e[A]1;)e.shift()}return function(n,r,i,a,s,g){var c,u,l,I,C,f,d,B,p,E,y,v,m,b,w,S,F,R,G,k,x=n.constructor,N=n.s==r.s?1:-1,U=n.d,_=r.d;if(!U||!U[0]||!_||!_[0])return new x(n.s&&r.s&&(U?!_||U[0]!=_[0]:_)?U&&0==U[0]||!_?0*N:N/0:NaN);for(g?(C=1,u=n.e-r.e):(g=Q,C=7,u=h(n.e/C)-h(r.e/C)),G=_.length,F=U.length,E=(p=new x(N)).d=[],l=0;_[l]==(U[l]||0);l++);if(_[l]>(U[l]||0)&&u--,null==i?(b=i=x.precision,a=x.rounding):b=s?i+(n.e-r.e)+1:i,b<0)E.push(1),f=!0;else{if(b=b/C+2|0,l=0,1==G){for(I=0,_=_[0],b++;(l1&&(_=e(_,I,g),U=e(U,I,g),G=_.length,F=U.length),S=G,v=(y=U.slice(0,G)).length;v=g/2&&++R;do{I=0,(c=t(_,y,G,v))<0?(m=y[0],G!=v&&(m=m*g+(y[1]||0)),(I=m/R|0)>1?(I>=g&&(I=g-1),1==(c=t(d=e(_,I,g),y,B=d.length,v=y.length))&&(I--,A(d,G=10;I/=10)l++;p.e=l+u*C-1,D(p,s?i+p.e+1:i,a,f)}return p}}();function D(e,t,A,n){var r,i,o,a,s,g,c,u,l,C=e.constructor;e:if(null!=t){if(!(u=e.d))return e;for(r=1,a=u[0];a>=10;a/=10)r++;if((i=t-r)<0)i+=7,o=t,s=(c=u[l=0])/f(10,r-o-1)%10|0;else if((l=Math.ceil((i+1)/7))>=(a=u.length)){if(!n)break e;for(;a++<=l;)u.push(0);c=s=0,r=1,o=(i%=7)-7+1}else{for(c=a=u[l],r=1;a>=10;a/=10)r++;s=(o=(i%=7)-7+r)<0?0:c/f(10,r-o-1)%10|0}if(n=n||t<0||void 0!==u[l+1]||(o<0?c:c%f(10,r-o-1)),g=A<4?(s||n)&&(0==A||A==(e.s<0?3:2)):s>5||5==s&&(4==A||n||6==A&&(i>0?o>0?c/f(10,r-o):0:u[l-1])%10&1||A==(e.s<0?8:7)),t<1||!u[0])return u.length=0,g?(t-=e.e+1,u[0]=f(10,(7-t%7)%7),e.e=-t||0):u[0]=e.e=0,e;if(0==i?(u.length=l,a=1,l--):(u.length=l+1,a=f(10,7-i),u[l]=o>0?(c/f(10,r-o)%f(10,o)|0)*a:0),g)for(;;){if(0==l){for(i=1,o=u[0];o>=10;o/=10)i++;for(o=u[0]+=a,a=1;o>=10;o/=10)a++;i!=a&&(e.e++,u[0]==Q&&(u[0]=1));break}if(u[l]+=a,u[l]!=Q)break;u[l--]=0,a=1}for(i=u.length;0===u[--i];)u.pop()}return I&&(e.e>C.maxE?(e.d=null,e.e=NaN):e.e0?i=i.charAt(0)+"."+i.slice(1)+_(n):o>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(e.e<0?"e":"e+")+e.e):r<0?(i="0."+_(-r-1)+i,A&&(n=A-o)>0&&(i+=_(n))):r>=o?(i+=_(r+1-o),A&&(n=A-r-1)>0&&(i=i+"."+_(n))):((n=r+1)0&&(r+1===o&&(i+="."),i+=_(n))),i}function k(e,t){var A=e[0];for(t*=7;A>=10;A/=10)t++;return t}function x(e,t,A){if(t>y)throw I=!0,A&&(e.precision=A),Error("[DecimalError] Precision limit exceeded");return D(new e(c),t,1,!0)}function N(e,t,A){if(t>v)throw Error("[DecimalError] Precision limit exceeded");return D(new e(u),t,A,!0)}function U(e){var t=e.length-1,A=7*t+1;if(t=e[t]){for(;t%10==0;t/=10)A--;for(t=e[0];t>=10;t/=10)A++}return A}function _(e){for(var t="";e--;)t+="0";return t}function M(e,t,A,n){var r,i=new e(1),o=Math.ceil(n/7+4);for(I=!1;;){if(A%2&&W((i=i.times(t)).d,o)&&(r=!0),0===(A=h(A/2))){A=i.d.length-1,r&&0===i.d[A]&&++i.d[A];break}W((t=t.times(t)).d,o)}return I=!0,i}function O(e){return 1&e.d[e.d.length-1]}function L(e,t,A){for(var n,r=new e(t[0]),i=0;++i17)return new l(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(null==t?(I=!1,s=h):s=t,a=new l(.03125);e.e>-2;)e=e.times(a),u+=5;for(s+=n=Math.log(f(2,u))/Math.LN10*2+5|0,A=i=o=new l(1),l.precision=s;;){if(i=D(i.times(e),s,1),A=A.times(++c),b((a=o.plus(R(i,A,s,1))).d).slice(0,s)===b(o.d).slice(0,s)){for(r=u;r--;)o=D(o.times(o),s,1);if(null!=t)return l.precision=h,o;if(!(g<3&&S(o.d,s-n,C,g)))return D(o,l.precision=h,C,I=!0);l.precision=s+=10,A=i=a=new l(1),c=0,g++}o=a}}function Z(e,t){var A,n,r,i,o,a,s,g,c,u,l,C=1,h=e,f=h.d,d=h.constructor,B=d.rounding,p=d.precision;if(h.s<0||!f||!f[0]||!h.e&&1==f[0]&&1==f.length)return new d(f&&!f[0]?-1/0:1!=h.s?NaN:f?0:h);if(null==t?(I=!1,c=p):c=t,d.precision=c+=10,n=(A=b(f)).charAt(0),!(Math.abs(i=h.e)<15e14))return g=x(d,c+2,p).times(i+""),h=Z(new d(n+"."+A.slice(1)),c-10).plus(g),d.precision=p,null==t?D(h,p,B,I=!0):h;for(;n<7&&1!=n||1==n&&A.charAt(1)>3;)n=(A=b((h=h.times(e)).d)).charAt(0),C++;for(i=h.e,n>1?(h=new d("0."+A),i++):h=new d(n+"."+A.slice(1)),u=h,s=o=h=R(h.minus(1),h.plus(1),c,1),l=D(h.times(h),c,1),r=3;;){if(o=D(o.times(l),c,1),b((g=s.plus(R(o,new d(r),c,1))).d).slice(0,c)===b(s.d).slice(0,c)){if(s=s.times(2),0!==i&&(s=s.plus(x(d,c+2,p).times(i+""))),s=R(s,new d(C),c,1),null!=t)return d.precision=p,s;if(!S(s.d,c-10,B,a))return D(s,d.precision=p,B,I=!0);d.precision=c+=10,g=o=h=R(u.minus(1),u.plus(1),c,1),l=D(h.times(h),c,1),r=a=1}s=g,r+=2}}function H(e){return String(e.s*e.s/0)}function Y(e,t){var A,n,r;for((A=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(A<0&&(A=n),A+=+t.slice(n+1),t=t.substring(0,n)):A<0&&(A=t.length),n=0;48===t.charCodeAt(n);n++);for(r=t.length;48===t.charCodeAt(r-1);--r);if(t=t.slice(n,r)){if(r-=n,e.e=A=A-n-1,e.d=[],n=(A+1)%7,A<0&&(n+=7),ne.constructor.maxE?(e.d=null,e.e=NaN):e.e0?(g=+t.slice(o+1),t=t.substring(2,o)):t=t.slice(2),a=(o=t.indexOf("."))>=0,n=e.constructor,a&&(o=(s=(t=t.replace(".","")).length)-o,r=M(n,new n(A),o,2*o)),o=u=(c=F(t,A,Q)).length-1;0===c[o];--o)c.pop();return o<0?new n(0*e.s):(e.e=k(c,u),e.d=c,I=!1,a&&(e=R(e,r,4*s)),g&&(e=e.times(Math.abs(g)<54?f(2,g):i.pow(2,g))),I=!0,e)}function j(e,t,A,n,r){var i,o,a,s,g=e.precision,c=Math.ceil(g/7);for(I=!1,s=A.times(A),a=new e(n);;){if(o=R(a.times(s),new e(t++*t++),g,1),a=r?n.plus(o):n.minus(o),n=R(o.times(s),new e(t++*t++),g,1),void 0!==(o=a.plus(n)).d[c]){for(i=c;o.d[i]===a.d[i]&&i--;);if(-1==i)break}i=a,a=n,n=o,o=i}return I=!0,o.d.length=c+1,o}function P(e,t){for(var A=e;--t;)A*=e;return A}function V(e,t){var A,n=t.s<0,r=N(e,e.precision,1),i=r.times(.5);if((t=t.abs()).lte(i))return a=n?4:1,t;if((A=t.divToInt(r)).isZero())a=n?3:2;else{if((t=t.minus(A.times(r))).lte(i))return a=O(A)?n?2:3:n?4:1,t;a=O(A)?n?1:4:n?3:2}return t.minus(r).abs()}function K(e,t,A,n){var r,i,a,s,c,u,l,I,C,h=e.constructor,f=void 0!==A;if(f?(w(A,1,1e9),void 0===n?n=h.rounding:w(n,0,8)):(A=h.precision,n=h.rounding),e.isFinite()){for(f?(r=2,16==t?A=4*A-3:8==t&&(A=3*A-2)):r=t,(a=(l=G(e)).indexOf("."))>=0&&(l=l.replace(".",""),(C=new h(1)).e=l.length-a,C.d=F(G(C),10,r),C.e=C.d.length),i=c=(I=F(l,10,r)).length;0==I[--c];)I.pop();if(I[0]){if(a<0?i--:((e=new h(e)).d=I,e.e=i,I=(e=R(e,C,A,n,0,r)).d,i=e.e,u=o),a=I[A],s=r/2,u=u||void 0!==I[A+1],u=n<4?(void 0!==a||u)&&(0===n||n===(e.s<0?3:2)):a>s||a===s&&(4===n||u||6===n&&1&I[A-1]||n===(e.s<0?8:7)),I.length=A,u)for(;++I[--A]>r-1;)I[A]=0,A||(++i,I.unshift(1));for(c=I.length;!I[c-1];--c);for(a=0,l="";a1)if(16==t||8==t){for(a=16==t?4:3,--c;c%a;c++)l+="0";for(c=(I=F(l,r,t)).length;!I[c-1];--c);for(a=1,l="1.";ac)for(i-=c;i--;)l+="0";else it)return e.length=t,!0}function X(e){return new this(e).abs()}function q(e){return new this(e).acos()}function z(e){return new this(e).acosh()}function $(e,t){return new this(e).plus(t)}function ee(e){return new this(e).asin()}function te(e){return new this(e).asinh()}function Ae(e){return new this(e).atan()}function ne(e){return new this(e).atanh()}function re(e,t){e=new this(e),t=new this(t);var A,n=this.precision,r=this.rounding,i=n+4;return e.s&&t.s?e.d||t.d?!t.d||e.isZero()?(A=t.s<0?N(this,n,r):new this(0)).s=e.s:!e.d||t.isZero()?(A=N(this,i,1).times(.5)).s=e.s:t.s<0?(this.precision=i,this.rounding=1,A=this.atan(R(e,t,i,1)),t=N(this,i,1),this.precision=n,this.rounding=r,A=e.s<0?A.minus(t):A.plus(t)):A=this.atan(R(e,t,i,1)):(A=N(this,i,1).times(t.s>0?.25:.75)).s=e.s:A=new this(NaN),A}function ie(e){return new this(e).cbrt()}function oe(e){return D(e=new this(e),e.e+1,2)}function ae(e){if(!e||"object"!==typeof e)throw Error("[DecimalError] Object expected");var t,A,n,r=!0===e.defaults,i=["precision",1,1e9,"rounding",0,8,"toExpNeg",-s,0,"toExpPos",0,s,"maxE",0,s,"minE",-s,0,"modulo",0,9];for(t=0;t=i[t+1]&&n<=i[t+2]))throw Error(C+A+": "+n);this[A]=n}if(A="crypto",r&&(this[A]=l[A]),void 0!==(n=e[A])){if(!0!==n&&!1!==n&&0!==n&&1!==n)throw Error(C+A+": "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw Error("[DecimalError] crypto unavailable");this[A]=!0}else this[A]=!1}return this}function se(e){return new this(e).cos()}function ge(e){return new this(e).cosh()}function ce(e,t){return new this(e).div(t)}function ue(e){return new this(e).exp()}function le(e){return D(e=new this(e),e.e+1,3)}function Ie(){var e,t,A=new this(0);for(I=!1,e=0;e=429e7?t[i]=crypto.getRandomValues(new Uint32Array(1))[0]:a[i++]=r%1e7;else{if(!crypto.randomBytes)throw Error("[DecimalError] crypto unavailable");for(t=crypto.randomBytes(n*=4);i=214e7?crypto.randomBytes(4).copy(t,i):(a.push(r%1e7),i+=4);i=n/4}else for(;i=10;r/=10)n++;n<7&&(A-=7-n)}return o.e=A,o.d=a,o}function be(e){return D(e=new this(e),e.e+1,this.rounding)}function we(e){return(e=new this(e)).d?e.d[0]?e.s:0*e.s:e.s||NaN}function Se(e){return new this(e).sin()}function Fe(e){return new this(e).sinh()}function Re(e){return new this(e).sqrt()}function De(e,t){return new this(e).sub(t)}function Ge(e){return new this(e).tan()}function ke(e){return new this(e).tanh()}function xe(e){return D(e=new this(e),e.e+1,1)}(i=function e(t){var A,n,r;function i(e){var t,A,n,r=this;if(!(r instanceof i))return new i(e);if(r.constructor=i,e instanceof i)return r.s=e.s,void(I?!e.d||e.e>i.maxE?(r.e=NaN,r.d=null):e.e=10;A/=10)t++;return void(I?t>i.maxE?(r.e=NaN,r.d=null):tt?1:e0))break;if(null===t.right)break;if(A(e,t.right.key)>0&&(s=t.right,t.right=s.left,s.left=t,null===(t=s).right))break;i.right=t,i=t,t=t.right}}return i.right=t.left,o.left=t.right,t.left=n.right,t.right=n.left,t}function a(e,t,A,n){var i=new r(e,t);if(null===A)return i.left=i.right=null,i;var a=n(e,(A=o(e,A,n)).key);return a<0?(i.left=A.left,i.right=A,A.left=null):a>=0&&(i.right=A.right,i.left=A,A.right=null),i}function s(e,t,A){var n=null,r=null;if(t){var i=A((t=o(e,t,A)).key,e);0===i?(n=t.left,r=t.right):i<0?(r=t.right,t.right=null,n=t):(n=t.left,t.left=null,r=t)}return{left:n,right:r}}var g=function(){function e(e){void 0===e&&(e=i),this._root=null,this._size=0,this._comparator=e}return e.prototype.insert=function(e,t){return this._size++,this._root=a(e,t,this._root,this._comparator)},e.prototype.add=function(e,t){var A=new r(e,t);null===this._root&&(A.left=A.right=null,this._size++,this._root=A);var n=this._comparator,i=o(e,this._root,n),a=n(e,i.key);return 0===a?this._root=i:(a<0?(A.left=i.left,A.right=i,i.left=null):a>0&&(A.right=i.right,A.left=i,i.right=null),this._size++,this._root=A),this._root},e.prototype.remove=function(e){this._root=this._remove(e,this._root,this._comparator)},e.prototype._remove=function(e,t,A){var n;return null===t?null:0===A(e,(t=o(e,t,A)).key)?(null===t.left?n=t.right:(n=o(e,t.left,A)).right=t.right,this._size--,n):t},e.prototype.pop=function(){var e=this._root;if(e){for(;e.left;)e=e.left;return this._root=o(e.key,this._root,this._comparator),this._root=this._remove(e.key,this._root,this._comparator),{key:e.key,data:e.data}}return null},e.prototype.findStatic=function(e){for(var t=this._root,A=this._comparator;t;){var n=A(e,t.key);if(0===n)return t;t=n<0?t.left:t.right}return null},e.prototype.find=function(e){return this._root&&(this._root=o(e,this._root,this._comparator),0!==this._comparator(e,this._root.key))?null:this._root},e.prototype.contains=function(e){for(var t=this._root,A=this._comparator;t;){var n=A(e,t.key);if(0===n)return!0;t=n<0?t.left:t.right}return!1},e.prototype.forEach=function(e,t){for(var A=this._root,n=[],r=!1;!r;)null!==A?(n.push(A),A=A.left):0!==n.length?(A=n.pop(),e.call(t,A),A=A.right):r=!0;return this},e.prototype.range=function(e,t,A,n){for(var r=[],i=this._comparator,o=this._root;0!==r.length||o;)if(o)r.push(o),o=o.left;else{if(i((o=r.pop()).key,t)>0)break;if(i(o.key,e)>=0&&A.call(n,o))return this;o=o.right}return this},e.prototype.keys=function(){var e=[];return this.forEach((function(t){var A=t.key;return e.push(A)})),e},e.prototype.values=function(){var e=[];return this.forEach((function(t){var A=t.data;return e.push(A)})),e},e.prototype.min=function(){return this._root?this.minNode(this._root).key:null},e.prototype.max=function(){return this._root?this.maxNode(this._root).key:null},e.prototype.minNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.left;)e=e.left;return e},e.prototype.maxNode=function(e){if(void 0===e&&(e=this._root),e)for(;e.right;)e=e.right;return e},e.prototype.at=function(e){for(var t=this._root,A=!1,n=0,r=[];!A;)if(t)r.push(t),t=t.left;else if(r.length>0){if(t=r.pop(),n===e)return t;n++,t=t.right}else A=!0;return null},e.prototype.next=function(e){var t=this._root,A=null;if(e.right){for(A=e.right;A.left;)A=A.left;return A}for(var n=this._comparator;t;){var r=n(e.key,t.key);if(0===r)break;r<0?(A=t,t=t.left):t=t.right}return A},e.prototype.prev=function(e){var t=this._root,A=null;if(null!==e.left){for(A=e.left;A.right;)A=A.right;return A}for(var n=this._comparator;t;){var r=n(e.key,t.key);if(0===r)break;r<0?t=t.left:(A=t,t=t.right)}return A},e.prototype.clear=function(){return this._root=null,this._size=0,this},e.prototype.toList=function(){return function(e){for(var t=e,A=[],n=!1,i=new r(null,null),o=i;!n;)t?(A.push(t),t=t.left):A.length>0?t=(t=o=o.next=A.pop()).right:n=!0;return o.next=null,i.next}(this._root)},e.prototype.load=function(e,t,A){void 0===t&&(t=[]),void 0===A&&(A=!1);var n=e.length,i=this._comparator;if(A&&function e(t,A,n,r,i){if(!(n>=r)){for(var o=t[n+r>>1],a=n-1,s=r+1;;){do{a++}while(i(t[a],o)<0);do{s--}while(i(t[s],o)>0);if(a>=s)break;var g=t[a];t[a]=t[s],t[s]=g,g=A[a],A[a]=A[s],A[s]=g}e(t,A,n,s,i),e(t,A,s+1,r,i)}}(e,t,0,n-1,i),null===this._root)this._root=function e(t,A,n,i){var o=i-n;if(o>0){var a=n+Math.floor(o/2),s=t[a],g=A[a],c=new r(s,g);return c.left=e(t,A,n,a),c.right=e(t,A,a+1,i),c}return null}(e,t,0,n),this._size=n;else{var o=function(e,t,A){for(var n=new r(null,null),i=n,o=e,a=t;null!==o&&null!==a;)A(o.key,a.key)<0?(i.next=o,o=o.next):(i.next=a,a=a.next),i=i.next;return null!==o?i.next=o:null!==a&&(i.next=a),n.next}(this.toList(),function(e,t){for(var A=new r(null,null),n=A,i=0;i0){var i=A+Math.floor(r/2),o=e(t,A,i),a=t.head;return a.left=o,t.head=t.head.next,a.right=e(t,i+1,n),a}return null}({head:o},0,n)}return this},e.prototype.isEmpty=function(){return null===this._root},Object.defineProperty(e.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"root",{get:function(){return this._root},enumerable:!0,configurable:!0}),e.prototype.toString=function(e){void 0===e&&(e=function(e){return String(e.key)});var t=[];return function e(t,A,n,r,i){if(t){r(A+(n?"\u2514\u2500\u2500 ":"\u251c\u2500\u2500 ")+i(t)+"\n");var o=A+(n?" ":"\u2502 ");t.left&&e(t.left,o,!1,r,i),t.right&&e(t.right,o,!0,r,i)}}(this._root,"",!0,(function(e){return t.push(e)}),e),t.join("")},e.prototype.update=function(e,t,A){var n=this._comparator,r=s(e,this._root,n),i=r.left,g=r.right;n(e,t)<0?g=a(t,A,g,n):i=a(t,A,i,n),this._root=function(e,t,A){return null===t?e:(null===e||((t=o(e.key,t,A)).left=e),t)}(i,g,n)},e.prototype.split=function(e){return s(e,this._root,this._comparator)},e}(),c=function(e,t){return e.ll.x<=t.x&&t.x<=e.ur.x&&e.ll.y<=t.y&&t.y<=e.ur.y},u=function(e,t){if(t.ur.xt.x?1:e.yt.y?1:0}}]),n(t,[{key:"link",value:function(e){if(e.point===this.point)throw new Error("Tried to link already linked events");for(var t=e.point.events,A=0,n=t.length;A=0&&s>=0?og?-1:0:i<0&&s<0?og?1:0:si?1:0}}}]),t}(),S=0,F=function(){function t(A,n,r,i){e(this,t),this.id=++S,this.leftSE=A,A.segment=this,A.otherSE=n,this.rightSE=n,n.segment=this,n.otherSE=A,this.rings=r,this.windings=i}return n(t,null,[{key:"compare",value:function(e,t){var A=e.leftSE.point.x,n=t.leftSE.point.x,r=e.rightSE.point.x,i=t.rightSE.point.x;if(io&&a>s)return-1;var c=e.comparePoint(t.leftSE.point);if(c<0)return 1;if(c>0)return-1;var u=t.comparePoint(e.rightSE.point);return 0!==u?u:-1}if(A>n){if(oa&&o>g)return 1;var l=t.comparePoint(e.leftSE.point);if(0!==l)return l;var I=e.comparePoint(t.rightSE.point);return I<0?1:I>0?-1:1}if(oa)return 1;if(ri){var h=e.comparePoint(t.rightSE.point);if(h<0)return 1;if(h>0)return-1}if(r!==i){var f=s-o,d=r-A,B=g-a,p=i-n;if(f>d&&Bp)return-1}return r>i?1:rg?1:e.idt.id?1:0}}]),n(t,[{key:"replaceRightSE",value:function(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}},{key:"bbox",value:function(){var e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:et?e:t}}}},{key:"vector",value:function(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}},{key:"isAnEndpoint",value:function(e){return e.x===this.leftSE.point.x&&e.y===this.leftSE.point.y||e.x===this.rightSE.point.x&&e.y===this.rightSE.point.y}},{key:"comparePoint",value:function(e){if(this.isAnEndpoint(e))return 0;var t=this.leftSE.point,A=this.rightSE.point,n=this.vector();if(t.x===A.x)return e.x===t.x?0:e.x0&&a.swapEvents(),w.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),i.checkForConsuming()),A}},{key:"swapEvents",value:function(){var e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(var t=0,A=this.windings.length;t0){var i=A;A=n,n=i}if(A.prev===n){var o=A;A=n,n=o}for(var a=0,s=n.rings.length;a0))throw new Error("Tried to create degenerate segment at [".concat(e.x,", ").concat(e.y,"]"));r=A,i=e,o=-1}return new t(new w(r,!0),new w(i,!1),[n],[o])}}]),t}(),R=function(){function t(A,n,r){if(e(this,t),!Array.isArray(A)||0===A.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=n,this.isExterior=r,this.segments=[],"number"!==typeof A[0][0]||"number"!==typeof A[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");var i=d.round(A[0][0],A[0][1]);this.bbox={ll:{x:i.x,y:i.y},ur:{x:i.x,y:i.y}};for(var o=i,a=1,s=A.length;athis.bbox.ur.x&&(this.bbox.ur.x=g.x),g.y>this.bbox.ur.y&&(this.bbox.ur.y=g.y),o=g)}i.x===o.x&&i.y===o.y||this.segments.push(F.fromRing(o,i,this))}return n(t,[{key:"getSweepEvents",value:function(){for(var e=[],t=0,A=this.segments.length;tthis.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.interiorRings.push(o)}this.multiPoly=n}return n(t,[{key:"getSweepEvents",value:function(){for(var e=this.exteriorRing.getSweepEvents(),t=0,A=this.interiorRings.length;tthis.bbox.ur.x&&(this.bbox.ur.x=o.bbox.ur.x),o.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=o.bbox.ur.y),this.polys.push(o)}this.isSubject=n}return n(t,[{key:"getSweepEvents",value:function(){for(var e=[],t=0,A=this.polys.length;t0&&(e=n)}for(var r=e.segment.prevInResult(),i=r?r.prevInResult():null;;){if(!r)return null;if(!i)return r.ringOut;if(i.ringOut!==r.ringOut)return i.ringOut.enclosingRing()!==r.ringOut?r.ringOut:r.ringOut.enclosingRing();r=i.prevInResult(),i=r?r.prevInResult():null}}}]),t}(),x=function(){function t(A){e(this,t),this.exteriorRing=A,A.poly=this,this.interiorRings=[]}return n(t,[{key:"addInterior",value:function(e){this.interiorRings.push(e),e.poly=this}},{key:"getGeom",value:function(){var e=[this.exteriorRing.getGeom()];if(null===e[0])return null;for(var t=0,A=this.interiorRings.length;t1&&void 0!==arguments[1]?arguments[1]:F.compare;e(this,t),this.queue=A,this.tree=new g(n),this.segments=[]}return n(t,[{key:"process",value:function(e){var t=e.segment,A=[];if(e.consumedBy)return e.isLeft?this.queue.remove(e.otherSE):this.tree.remove(t),A;var n=e.isLeft?this.tree.insert(t):this.tree.find(t);if(!n)throw new Error("Unable to find segment #".concat(t.id," ")+"[".concat(t.leftSE.point.x,", ").concat(t.leftSE.point.y,"] -> ")+"[".concat(t.rightSE.point.x,", ").concat(t.rightSE.point.y,"] ")+"in SweepLine tree. Please submit a bug report.");for(var r=n,i=n,o=void 0,a=void 0;void 0===o;)null===(r=this.tree.prev(r))?o=null:void 0===r.key.consumedBy&&(o=r.key);for(;void 0===a;)null===(i=this.tree.next(i))?a=null:void 0===i.key.consumedBy&&(a=i.key);if(e.isLeft){var s=null;if(o){var g=o.getIntersection(t);if(null!==g&&(t.isAnEndpoint(g)||(s=g),!o.isAnEndpoint(g)))for(var c=this._splitSafely(o,g),u=0,l=c.length;u0?(this.tree.remove(t),A.push(e)):(this.segments.push(t),t.prev=o)}else{if(o&&a){var y=o.getIntersection(a);if(null!==y){if(!o.isAnEndpoint(y))for(var v=this._splitSafely(o,y),m=0,b=v.length;m_)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big). Please file a bug report.");for(var y=new U(h),v=h.size,m=h.pop();m;){var b=m.key;if(h.size===v){var S=b.segment;throw new Error("Unable to pop() ".concat(b.isLeft?"left":"right"," SweepEvent ")+"[".concat(b.point.x,", ").concat(b.point.y,"] from segment #").concat(S.id," ")+"[".concat(S.leftSE.point.x,", ").concat(S.leftSE.point.y,"] -> ")+"[".concat(S.rightSE.point.x,", ").concat(S.rightSE.point.y,"] from queue. ")+"Please file a bug report.")}if(h.size>_)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big). Please file a bug report.");if(y.segments.length>M)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments). Please file a bug report.");for(var F=y.process(b),R=0,D=F.length;R1?t-1:0),n=1;n1?t-1:0),n=1;n1?t-1:0),n=1;n1?t-1:0),n=1;n=0))throw new Error("length must be a positive number");return function(e,t){void 0===t&&(t="kilometers");var A=n[t];if(!A)throw new Error(t+" units is invalid");return e*A}(r(e,t),A)}function o(e){if(!e)throw new Error("coord is required");if(!Array.isArray(e)){if("Feature"===e.type&&null!==e.geometry&&"Point"===e.geometry.type)return e.geometry.coordinates;if("Point"===e.type)return e.coordinates}if(Array.isArray(e)&&e.length>=2&&!Array.isArray(e[0])&&!Array.isArray(e[1]))return e;throw new Error("coord must be GeoJSON Point or an Array of numbers")}t.a=function(e,t,A){void 0===A&&(A={});var n=o(e),r=o(t);return r[0]+=r[0]-n[0]>180?-360:n[0]-r[0]>180?360:0,i(function(e,t,A){var n=A=void 0===A?6371008.8:Number(A),r=e[1]*Math.PI/180,i=t[1]*Math.PI/180,o=i-r,a=Math.abs(t[0]-e[0])*Math.PI/180;a>Math.PI&&(a-=2*Math.PI);var s=Math.log(Math.tan(i/2+Math.PI/4)/Math.tan(r/2+Math.PI/4)),g=Math.abs(s)>1e-11?o/s:Math.cos(r);return Math.sqrt(o*o+g*g*a*a)*n}(n,r),"meters",A.units)}},function(e,t,A){"use strict";var n=A(8),r=A(1),i=A(4),o=A(9),a=A(10),s=A(33),g=A(404),c=A(125),u=A(30);function l(e,t,A){var n=t[0],r=t[1],i=t[2],o=t[3],a=t[4],s=t[5],g=t[6],c=t[7],u=t[8],l=t[9],I=t[10],C=t[11],h=t[12],f=t[13],d=t[14],B=t[15],p=A[0],E=A[1],Q=A[2],y=A[3];return e[0]=p*n+E*a+Q*u+y*h,e[1]=p*r+E*s+Q*l+y*f,e[2]=p*i+E*g+Q*I+y*d,e[3]=p*o+E*c+Q*C+y*B,p=A[4],E=A[5],Q=A[6],y=A[7],e[4]=p*n+E*a+Q*u+y*h,e[5]=p*r+E*s+Q*l+y*f,e[6]=p*i+E*g+Q*I+y*d,e[7]=p*o+E*c+Q*C+y*B,p=A[8],E=A[9],Q=A[10],y=A[11],e[8]=p*n+E*a+Q*u+y*h,e[9]=p*r+E*s+Q*l+y*f,e[10]=p*i+E*g+Q*I+y*d,e[11]=p*o+E*c+Q*C+y*B,p=A[12],E=A[13],Q=A[14],y=A[15],e[12]=p*n+E*a+Q*u+y*h,e[13]=p*r+E*s+Q*l+y*f,e[14]=p*i+E*g+Q*I+y*d,e[15]=p*o+E*c+Q*C+y*B,e}function I(e,t,A){var n=A[0],r=A[1],i=A[2];return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*i,e[9]=t[9]*i,e[10]=t[10]*i,e[11]=t[11]*i,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function C(e,t,A,n,r){var i,o=1/Math.tan(t/2);return e[0]=o/A,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=o,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,null!=r&&r!==1/0?(i=1/(n-r),e[10]=(r+n)*i,e[14]=2*r*n*i):(e[10]=-1,e[14]=-2*n),e}function h(e,t,A,n){var r,i,o,a,s,g,c,l,I,C,h=t[0],f=t[1],d=t[2],B=n[0],p=n[1],E=n[2],Q=A[0],y=A[1],v=A[2];return Math.abs(h-Q)2*Math.PI)throw Error("radians");var l=n/2,I=a*Math.tan(l),C=I*i;return(new A).ortho({left:-C,right:C,bottom:-I,top:I,near:g,far:u})}},{key:"perspective",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.fovy,A=void 0===t?void 0:t,n=e.fov,r=void 0===n?45*Math.PI/180:n,i=e.aspect,o=void 0===i?1:i,a=e.near,s=void 0===a?.1:a,g=e.far,c=void 0===g?500:g;if((A=A||r)>2*Math.PI)throw Error("radians");return C(this,A,o,s,c),this.check()}},{key:"determinant",value:function(){return function(e){var t=e[0],A=e[1],n=e[2],r=e[3],i=e[4],o=e[5],a=e[6],s=e[7],g=e[8],c=e[9],u=e[10],l=e[11],I=e[12],C=e[13],h=e[14],f=e[15];return(t*o-A*i)*(u*f-l*h)-(t*a-n*i)*(c*f-l*C)+(t*s-r*i)*(c*h-u*C)+(A*a-n*o)*(g*f-l*I)-(A*s-r*o)*(g*h-u*I)+(n*s-r*a)*(g*C-c*I)}(this)}},{key:"getScale",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[-0,-0,-0];return e[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]),e[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]),e[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]),e}},{key:"getTranslation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[-0,-0,-0];return e[0]=this[12],e[1]=this[13],e[2]=this[14],e}},{key:"getRotation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,A=this.getScale(t||[-0,-0,-0]),n=1/A[0],r=1/A[1],i=1/A[2];return e[0]=this[0]*n,e[1]=this[1]*r,e[2]=this[2]*i,e[3]=0,e[4]=this[4]*n,e[5]=this[5]*r,e[6]=this[6]*i,e[7]=0,e[8]=this[8]*n,e[9]=this[9]*r,e[10]=this[10]*i,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{key:"getRotationMatrix3",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[-0,-0,-0,-0,-0,-0,-0,-0,-0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,A=this.getScale(t||[-0,-0,-0]),n=1/A[0],r=1/A[1],i=1/A[2];return e[0]=this[0]*n,e[1]=this[1]*r,e[2]=this[2]*i,e[3]=this[4]*n,e[4]=this[5]*r,e[5]=this[6]*i,e[6]=this[8]*n,e[7]=this[9]*r,e[8]=this[10]*i,e}},{key:"transpose",value:function(){return function(e,t){if(e===t){var A=t[1],n=t[2],r=t[3],i=t[6],o=t[7],a=t[11];e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=A,e[6]=t[9],e[7]=t[13],e[8]=n,e[9]=i,e[11]=t[14],e[12]=r,e[13]=o,e[14]=a}else e[0]=t[0],e[1]=t[4],e[2]=t[8],e[3]=t[12],e[4]=t[1],e[5]=t[5],e[6]=t[9],e[7]=t[13],e[8]=t[2],e[9]=t[6],e[10]=t[10],e[11]=t[14],e[12]=t[3],e[13]=t[7],e[14]=t[11],e[15]=t[15]}(this,this),this.check()}},{key:"invert",value:function(){return function(e,t){var A=t[0],n=t[1],r=t[2],i=t[3],o=t[4],a=t[5],s=t[6],g=t[7],c=t[8],u=t[9],l=t[10],I=t[11],C=t[12],h=t[13],f=t[14],d=t[15],B=A*a-n*o,p=A*s-r*o,E=A*g-i*o,Q=n*s-r*a,y=n*g-i*a,v=r*g-i*s,m=c*h-u*C,b=c*f-l*C,w=c*d-I*C,S=u*f-l*h,F=u*d-I*h,R=l*d-I*f,D=B*R-p*F+E*S+Q*w-y*b+v*m;D&&(D=1/D,e[0]=(a*R-s*F+g*S)*D,e[1]=(r*F-n*R-i*S)*D,e[2]=(h*v-f*y+d*Q)*D,e[3]=(l*y-u*v-I*Q)*D,e[4]=(s*w-o*R-g*b)*D,e[5]=(A*R-r*w+i*b)*D,e[6]=(f*E-C*v-d*p)*D,e[7]=(c*v-l*E+I*p)*D,e[8]=(o*F-a*w+g*m)*D,e[9]=(n*w-A*F-i*m)*D,e[10]=(C*y-h*E+d*B)*D,e[11]=(u*E-c*y-I*B)*D,e[12]=(a*b-o*S-s*m)*D,e[13]=(A*S-n*b+r*m)*D,e[14]=(h*p-C*Q-f*B)*D,e[15]=(c*Q-u*p+l*B)*D)}(this,this),this.check()}},{key:"multiplyLeft",value:function(e){return l(this,e,this),this.check()}},{key:"multiplyRight",value:function(e){return l(this,this,e),this.check()}},{key:"rotateX",value:function(e){return function(e,t,A){var n=Math.sin(A),r=Math.cos(A),i=t[4],o=t[5],a=t[6],s=t[7],g=t[8],c=t[9],u=t[10],l=t[11];t!==e&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[4]=i*r+g*n,e[5]=o*r+c*n,e[6]=a*r+u*n,e[7]=s*r+l*n,e[8]=g*r-i*n,e[9]=c*r-o*n,e[10]=u*r-a*n,e[11]=l*r-s*n}(this,this,e),this.check()}},{key:"rotateY",value:function(e){return function(e,t,A){var n=Math.sin(A),r=Math.cos(A),i=t[0],o=t[1],a=t[2],s=t[3],g=t[8],c=t[9],u=t[10],l=t[11];t!==e&&(e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=i*r-g*n,e[1]=o*r-c*n,e[2]=a*r-u*n,e[3]=s*r-l*n,e[8]=i*n+g*r,e[9]=o*n+c*r,e[10]=a*n+u*r,e[11]=s*n+l*r}(this,this,e),this.check()}},{key:"rotateZ",value:function(e){return function(e,t,A){var n=Math.sin(A),r=Math.cos(A),i=t[0],o=t[1],a=t[2],s=t[3],g=t[4],c=t[5],u=t[6],l=t[7];t!==e&&(e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=i*r+g*n,e[1]=o*r+c*n,e[2]=a*r+u*n,e[3]=s*r+l*n,e[4]=g*r-i*n,e[5]=c*r-o*n,e[6]=u*r-a*n,e[7]=l*r-s*n}(this,this,e),this.check()}},{key:"rotateXYZ",value:function(e){var t=Object(n.a)(e,3),A=t[0],r=t[1],i=t[2];return this.rotateX(A).rotateY(r).rotateZ(i)}},{key:"rotateAxis",value:function(e,t){return function(e,t,A,n){var r,i,o,a,s,g,c,l,I,C,h,f,d,B,p,E,Q,y,v,m,b,w,S,F,R=n[0],D=n[1],G=n[2],k=Math.hypot(R,D,G);k>>=0)&&e<256)&&(i=n[e])?i:(r=o(e,(0|e)<0?-1:0,!0),a&&(n[e]=r),r):(a=-128<=(e|=0)&&e<128)&&(i=A[e])?i:(r=o(e,e<0?-1:0,!1),a&&(A[e]=r),r)}function i(e,t){if(isNaN(e)||!isFinite(e))return t?h:C;if(t){if(e<0)return h;if(e>=u)return E}else{if(e<=-l)return Q;if(e+1>=l)return p}return e<0?i(-e,t).neg():o(e%c|0,e/c|0,t)}function o(t,A,n){return new e(t,A,n)}e.fromInt=r,e.fromNumber=i,e.fromBits=o;var a=Math.pow;function s(e,t,A){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return C;if("number"===typeof t?(A=t,t=!1):t=!!t,(A=A||10)<2||360)throw Error("interior hyphen");if(0===n)return s(e.substring(1),t,A).neg();for(var r=i(a(A,8)),o=C,g=0;g>>0:this.low},y.toNumber=function(){return this.unsigned?(this.high>>>0)*c+(this.low>>>0):this.high*c+(this.low>>>0)},y.toString=function(e){if((e=e||10)<2||36>>0).toString(e);if((o=g).isZero())return c+s;for(;c.length<6;)c="0"+c;s=""+c+s}},y.getHighBits=function(){return this.high},y.getHighBitsUnsigned=function(){return this.high>>>0},y.getLowBits=function(){return this.low},y.getLowBitsUnsigned=function(){return this.low>>>0},y.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Q)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},y.isOdd=function(){return 1===(1&this.low)},y.isEven=function(){return 0===(1&this.low)},y.equals=function(e){return t(e)||(e=g(e)),(this.unsigned===e.unsigned||this.high>>>31!==1||e.high>>>31!==1)&&this.high===e.high&&this.low===e.low},y.eq=y.equals,y.notEquals=function(e){return!this.eq(e)},y.neq=y.notEquals,y.lessThan=function(e){return this.comp(e)<0},y.lt=y.lessThan,y.lessThanOrEqual=function(e){return this.comp(e)<=0},y.lte=y.lessThanOrEqual,y.greaterThan=function(e){return this.comp(e)>0},y.gt=y.greaterThan,y.greaterThanOrEqual=function(e){return this.comp(e)>=0},y.gte=y.greaterThanOrEqual,y.compare=function(e){if(t(e)||(e=g(e)),this.eq(e))return 0;var A=this.isNegative(),n=e.isNegative();return A&&!n?-1:!A&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},y.comp=y.compare,y.negate=function(){return!this.unsigned&&this.eq(Q)?Q:this.not().add(f)},y.neg=y.negate,y.add=function(e){t(e)||(e=g(e));var A=this.high>>>16,n=65535&this.high,r=this.low>>>16,i=65535&this.low,a=e.high>>>16,s=65535&e.high,c=e.low>>>16,u=0,l=0,I=0,C=0;return I+=(C+=i+(65535&e.low))>>>16,l+=(I+=r+c)>>>16,u+=(l+=n+s)>>>16,u+=A+a,o((I&=65535)<<16|(C&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},y.subtract=function(e){return t(e)||(e=g(e)),this.add(e.neg())},y.sub=y.subtract,y.multiply=function(e){if(this.isZero())return C;if(t(e)||(e=g(e)),e.isZero())return C;if(this.eq(Q))return e.isOdd()?Q:C;if(e.eq(Q))return this.isOdd()?Q:C;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(I)&&e.lt(I))return i(this.toNumber()*e.toNumber(),this.unsigned);var A=this.high>>>16,n=65535&this.high,r=this.low>>>16,a=65535&this.low,s=e.high>>>16,c=65535&e.high,u=e.low>>>16,l=65535&e.low,h=0,f=0,d=0,B=0;return d+=(B+=a*l)>>>16,f+=(d+=r*l)>>>16,d&=65535,f+=(d+=a*u)>>>16,h+=(f+=n*l)>>>16,f&=65535,h+=(f+=r*u)>>>16,f&=65535,h+=(f+=a*c)>>>16,h+=A*l+n*u+r*c+a*s,o((d&=65535)<<16|(B&=65535),(h&=65535)<<16|(f&=65535),this.unsigned)},y.mul=y.multiply,y.divide=function(e){if(t(e)||(e=g(e)),e.isZero())throw Error("division by zero");if(this.isZero())return this.unsigned?h:C;var A,n,r;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return h;if(e.gt(this.shru(1)))return d;r=h}else{if(this.eq(Q))return e.eq(f)||e.eq(B)?Q:e.eq(Q)?f:(A=this.shr(1).div(e).shl(1)).eq(C)?e.isNegative()?f:B:(n=this.sub(e.mul(A)),r=A.add(n.div(e)));if(e.eq(Q))return this.unsigned?h:C;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();r=C}for(n=this;n.gte(e);){A=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var o=Math.ceil(Math.log(A)/Math.LN2),s=o<=48?1:a(2,o-48),c=i(A),u=c.mul(e);u.isNegative()||u.gt(n);)u=(c=i(A-=s,this.unsigned)).mul(e);c.isZero()&&(c=f),r=r.add(c),n=n.sub(u)}return r},y.div=y.divide,y.modulo=function(e){return t(e)||(e=g(e)),this.sub(this.div(e).mul(e))},y.mod=y.modulo,y.not=function(){return o(~this.low,~this.high,this.unsigned)},y.and=function(e){return t(e)||(e=g(e)),o(this.low&e.low,this.high&e.high,this.unsigned)},y.or=function(e){return t(e)||(e=g(e)),o(this.low|e.low,this.high|e.high,this.unsigned)},y.xor=function(e){return t(e)||(e=g(e)),o(this.low^e.low,this.high^e.high,this.unsigned)},y.shiftLeft=function(e){return t(e)&&(e=e.toInt()),0===(e&=63)?this:e<32?o(this.low<>>32-e,this.unsigned):o(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):o(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},y.shr=y.shiftRight,y.shiftRightUnsigned=function(e){if(t(e)&&(e=e.toInt()),0===(e&=63))return this;var A=this.high;return e<32?o(this.low>>>e|A<<32-e,A>>>e,this.unsigned):o(32===e?A:A>>>e-32,0,this.unsigned)},y.shru=y.shiftRightUnsigned,y.toSigned=function(){return this.unsigned?o(this.low,this.high,!1):this},y.toUnsigned=function(){return this.unsigned?this:o(this.low,this.high,!0)},y.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},y.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&e,e>>>8&255,e>>>16&255,e>>>24&255]},y.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24&255,e>>>16&255,e>>>8&255,255&e,t>>>24&255,t>>>16&255,t>>>8&255,255&t]},e})?n.apply(t,r):n)||(e.exports=i)},function(e,t,A){"use strict";A.d(t,"a",(function(){return u})),A.d(t,"b",(function(){return l}));var n=A(6),r=A(116),i=A(36),o=Math.PI/180,a=new Float32Array(16),s=new Float32Array(12);function g(e,t,A){var n=t[0]*o,r=t[1]*o,i=t[2]*o,a=Math.sin(i),s=Math.sin(n),g=Math.sin(r),c=Math.cos(i),u=Math.cos(n),l=Math.cos(r),I=A[0],C=A[1],h=A[2];e[0]=I*l*u,e[1]=I*g*u,e[2]=I*-s,e[3]=C*(-g*c+l*s*a),e[4]=C*(l*c+g*s*a),e[5]=C*u*a,e[6]=h*(g*a+l*s*c),e[7]=h*(-l*a+g*s*c),e[8]=h*u*c}function c(e){return e[0]=e[0],e[1]=e[1],e[2]=e[2],e[3]=e[4],e[4]=e[5],e[5]=e[6],e[6]=e[8],e[7]=e[9],e[8]=e[10],e[9]=e[12],e[10]=e[13],e[11]=e[14],e.subarray(0,12)}var u={size:12,accessor:["getOrientation","getScale","getTranslation","getTransformMatrix"],shaderAttributes:{instanceModelMatrix__LOCATION_0:{size:3,elementOffset:0},instanceModelMatrix__LOCATION_1:{size:3,elementOffset:3},instanceModelMatrix__LOCATION_2:{size:3,elementOffset:6},instanceTranslation:{size:3,elementOffset:9}},update:function(e,t){var A=t.startRow,i=t.endRow,o=this.props,u=o.data,l=o.getOrientation,I=o.getScale,C=o.getTranslation,h=o.getTransformMatrix,f=Array.isArray(h),d=f&&16===h.length,B=Array.isArray(I),p=Array.isArray(l),E=Array.isArray(C),Q=d||!f&&Boolean(h(u[0]));e.constant=Q?d:p&&B&&E;var y=e.value;if(e.constant){var v;if(Q)a.set(h),v=c(a);else g(v=s,l,I),v.set(C,9);e.value=new Float32Array(v)}else{var m,b=A*e.size,w=Object(r.a)(u,A,i),S=w.iterable,F=w.objectInfo,R=Object(n.a)(S);try{for(R.s();!(m=R.n()).done;){var D=m.value;F.index++;var G=void 0;if(Q)a.set(d?h:h(D,F)),G=c(a);else g(G=s,p?l:l(D,F),B?I:I(D,F)),G.set(E?C:C(D,F),9);y[b++]=G[0],y[b++]=G[1],y[b++]=G[2],y[b++]=G[3],y[b++]=G[4],y[b++]=G[5],y[b++]=G[6],y[b++]=G[7],y[b++]=G[8],y[b++]=G[9],y[b++]=G[10],y[b++]=G[11]}}catch(k){R.e(k)}finally{R.f()}}}};function l(e,t){return t===i.a.CARTESIAN||t===i.a.METER_OFFSETS||t===i.a.DEFAULT&&!e.isGeospatial}},function(e,t,A){"use strict";e.exports=A(854)},function(e,t,A){"use strict";var n,r,i=A(2),o=A(85),a=A(72),s=function(e){return Object(a.e)(e)?void 0:0},g=(n={},Object(i.a)(n,3074,(function(e){return Object(a.e)(e)?void 0:36064})),Object(i.a)(n,35723,(function(e){return Object(a.e)(e)?void 0:4352})),Object(i.a)(n,35977,s),Object(i.a)(n,32937,s),Object(i.a)(n,36795,(function(e,t){var A=Object(a.e)(e)?e.getExtension("EXT_disjoint_timer_query_webgl2"):e.getExtension("EXT_disjoint_timer_query");return A&&A.GPU_DISJOINT_EXT?t(A.GPU_DISJOINT_EXT):0})),Object(i.a)(n,37445,(function(e,t){var A=e.getExtension("WEBGL_debug_renderer_info");return t(A&&A.UNMASKED_VENDOR_WEBGL||7936)})),Object(i.a)(n,37446,(function(e,t){var A=e.getExtension("WEBGL_debug_renderer_info");return t(A&&A.UNMASKED_RENDERER_WEBGL||7937)})),Object(i.a)(n,34047,(function(e,t){var A=e.luma.extensions.EXT_texture_filter_anisotropic;return A?t(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT):1})),Object(i.a)(n,32883,s),Object(i.a)(n,35071,s),Object(i.a)(n,37447,s),Object(i.a)(n,36063,(function(e,t){if(!Object(a.e)(e)){var A=e.getExtension("WEBGL_draw_buffers");return A?t(A.MAX_COLOR_ATTACHMENTS_WEBGL):0}})),Object(i.a)(n,35379,s),Object(i.a)(n,35374,s),Object(i.a)(n,35377,s),Object(i.a)(n,34852,(function(e){if(!Object(a.e)(e)){var t=e.getExtension("WEBGL_draw_buffers");return t?t.MAX_DRAW_BUFFERS_WEBGL:0}})),Object(i.a)(n,36203,(function(e){return e.getExtension("OES_element_index")?2147483647:65535})),Object(i.a)(n,33001,(function(e){return e.getExtension("OES_element_index")?16777216:65535})),Object(i.a)(n,33e3,(function(e){return 16777216})),Object(i.a)(n,37157,s),Object(i.a)(n,35373,s),Object(i.a)(n,35657,s),Object(i.a)(n,36183,s),Object(i.a)(n,37137,s),Object(i.a)(n,34045,s),Object(i.a)(n,35978,s),Object(i.a)(n,35979,s),Object(i.a)(n,35968,s),Object(i.a)(n,35376,s),Object(i.a)(n,35375,s),Object(i.a)(n,35659,s),Object(i.a)(n,37154,s),Object(i.a)(n,35371,s),Object(i.a)(n,35658,s),Object(i.a)(n,35076,s),Object(i.a)(n,35077,s),Object(i.a)(n,35380,s),n);A.d(t,"b",(function(){return c})),A.d(t,"a",(function(){return u}));var c=(r={},Object(i.a)(r,"OES_vertex_array_object",{meta:{suffix:"OES"},createVertexArray:function(){Object(o.a)(!1,"VertexArray requires WebGL2 or OES_vertex_array_object extension")},deleteVertexArray:function(){},bindVertexArray:function(){},isVertexArray:function(){return!1}}),Object(i.a)(r,"ANGLE_instanced_arrays",{meta:{suffix:"ANGLE"},vertexAttribDivisor:function(e,t){Object(o.a)(0===t,"WebGL instanced rendering not supported")},drawElementsInstanced:function(){},drawArraysInstanced:function(){}}),Object(i.a)(r,"WEBGL_draw_buffers",{meta:{suffix:"WEBGL"},drawBuffers:function(){Object(o.a)(!1)}}),Object(i.a)(r,"EXT_disjoint_timer_query",{meta:{suffix:"EXT"},createQuery:function(){Object(o.a)(!1)},deleteQuery:function(){Object(o.a)(!1)},beginQuery:function(){Object(o.a)(!1)},endQuery:function(){},getQuery:function(e,t){return this.getQueryObject(e,t)},getQueryParameter:function(e,t){return this.getQueryObject(e,t)},getQueryObject:function(){}}),r),u={readBuffer:function(e,t,A){Object(a.e)(e)&&t(A)},getVertexAttrib:function(e,t,A,n){var r,i=function(e,t){return{webgl2:Object(a.e)(e),ext:e.getExtension(t)}}(e,"ANGLE_instanced_arrays"),o=i.webgl2,s=i.ext;switch(n){case 35069:r=!!o&&void 0;break;case 35070:r=o||s?void 0:0}return void 0!==r?r:t(A,n)},getProgramParameter:function(e,t,A,n){if(!Object(a.e)(e))switch(n){case 35967:return 35981;case 35971:case 35382:return 0}return t(A,n)},getInternalformatParameter:function(e,t,A,n,r){if(!Object(a.e)(e))switch(r){case 32937:return new Int32Array([0])}return e.getInternalformatParameter(A,n,r)},getTexParameter:function(e,t,A,n){switch(n){case 34046:var r=e.luma.extensions.EXT_texture_filter_anisotropic;n=r&&r.TEXTURE_MAX_ANISOTROPY_EXT||34046}return t(A,n)},getParameter:function(e,t,A){var n=g[A],r="function"===typeof n?n(e,t,A):n;return void 0!==r?r:t(A)},hint:function(e,t,A,n){return t(A,n)}}},,,,function(e,t){e.exports=function(e,t){return e===t||e!==e&&t!==t}},function(e,t,A){var n=A(550),r=A(793),i=A(248);e.exports=function(e){return i(e)?n(e):r(e)}},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t){function A(e,t){for(var A=0;A1&&A&&"Polygon"===A.geometry.type){var n={type:"Feature",properties:{shape:A.properties.shape},geometry:{type:"Polygon",coordinates:A.geometry.coordinates}},r=this.getAddFeatureOrBooleanPolygonAction(n,e);this.resetClickSequence(),r&&e.onEdit(r)}}},{key:"getGuides",value:function(e){var t=e.lastPointerMoveEvent,A=e.modeConfig,n=this.getClickSequence(),r={type:"FeatureCollection",features:[]};if(0===n.length)return r;var i=n[0],o=t.mapCoords,a=this.getTwoClickPolygon(i,o,A);return a&&r.features.push({type:"Feature",properties:{shape:a.properties&&a.properties.shape,guideType:"tentative"},geometry:a.geometry}),r}},{key:"getTwoClickPolygon",value:function(e,t,A){return null}},{key:"handlePointerMove",value:function(e,t){t.onUpdateCursor("cell"),o(g(I.prototype),"handlePointerMove",this).call(this,e,t)}},{key:"createTentativeFeature",value:function(e){var t,A=e.lastPointerMoveEvent,n=this.getClickSequence(),r=A?[A.mapCoords]:[];return 1===n.length&&(t=this.getTwoClickPolygon(n[0],r[0],e.modeConfig)),t}}])&&i(A.prototype,n),u&&i(A,u),I}(A(79).GeoJsonEditMode);t.TwoClickPolygonMode=u},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=A(141),r=A(59);t.default=function(e,t){void 0===t&&(t={});var A=0,i=0,o=0;return n.coordEach(e,(function(e){A+=e[0],i+=e[1],o++})),r.point([A/o,i/o],t.properties)}},function(e,t,A){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=A(105);function r(e,t,A){var n=!1;t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]&&(t=t.slice(0,t.length-1));for(var r=0,i=t.length-1;re[1]!==g>e[1]&&e[0]<(s-o)*(e[1]-a)/(g-a)+o&&(n=!n)}return n}t.default=function(e,t,A){if(void 0===A&&(A={}),!e)throw new Error("point is required");if(!t)throw new Error("polygon is required");var i=n.getCoord(e),o=n.getGeom(t),a=o.type,s=t.bbox,g=o.coordinates;if(s&&!1===function(e,t){return t[0]<=e[0]&&t[1]<=e[1]&&t[2]>=e[0]&&t[3]>=e[1]}(i,s))return!1;"Polygon"===a&&(g=[g]);for(var c=!1,u=0;u1&&void 0!==arguments[1]?arguments[1]:5;if("string"===typeof e)return e.slice(0,t);if(ArrayBuffer.isView(e))return r(e.buffer,e.byteOffset,t);if(e instanceof ArrayBuffer){var A=0;return r(e,A,t)}return""}function r(e,t,A){if(e.byteLength<=t+A)return"";for(var n=new DataView(e),r="",i=0;i0&&void 0!==arguments[0]?arguments[0]:{},t=e.newProps,A=e.oldProps,n=e.ignoreProps,r=void 0===n?{}:n,i=e.propTypes,o=void 0===i?{}:i,a=e.triggerName,g=void 0===a?"props":a;if(A===t)return null;if("object"!==typeof t||null===t)return"".concat(g," changed shallowly");if("object"!==typeof A||null===A)return"".concat(g," changed shallowly");for(var c=0,u=Object.keys(t);c1&&void 0!==arguments[1]?arguments[1]:{};Object(r.a)(this,e),this.ControllerState=t,this.props=Object(n.a)({},g,{},A),this.propsInTransition=null,this.transition=new o.a(A.timeline),this.onViewStateChange=A.onViewStateChange||a,this.onStateChange=A.onStateChange||a,this._onTransitionUpdate=this._onTransitionUpdate.bind(this)}return Object(i.a)(e,[{key:"finalize",value:function(){this.transition.cancel()}},{key:"getViewportInTransition",value:function(){return this.propsInTransition}},{key:"processViewStateChange",value:function(e){var t=!1,A=this.props;if(e=Object(n.a)({},g,{},e),this.props=e,this._shouldIgnoreViewportChange(A,e))return t;if(this._isTransitionEnabled(e)){var r=this.transition.settings,i=r.interruption,o=r.endProps,a=Object(n.a)({},A,{},i===s.SNAP_TO_END?o:this.propsInTransition||A);this._triggerTransition(a,e),t=!0}else this.transition.cancel();return t}},{key:"updateTransition",value:function(){this.transition.update()}},{key:"_isTransitionEnabled",value:function(e){var t=e.transitionDuration,A=e.transitionInterpolator;return(t>0||"auto"===t)&&Boolean(A)}},{key:"_isUpdateDueToCurrentTransition",value:function(e){return!!this.transition.inProgress&&this.transition.settings.interpolator.arePropsEqual(e,this.propsInTransition)}},{key:"_shouldIgnoreViewportChange",value:function(e,t){return this.transition.inProgress?this.transition.settings.interruption===s.IGNORE||this._isUpdateDueToCurrentTransition(t):!this._isTransitionEnabled(t)||t.transitionInterpolator.arePropsEqual(e,t)}},{key:"_triggerTransition",value:function(e,t){var A=new this.ControllerState(e),n=new this.ControllerState(t).shortestPathFrom(A),r=t.transitionInterpolator,i=r.getDuration?r.getDuration(e,t):t.transitionDuration;if(0!==i){var o=t.transitionInterpolator.initializeProps(e,n);this.propsInTransition={},this.duration=i,this.transition.start({duration:i,easing:t.transitionEasing,interpolator:t.transitionInterpolator,interruption:t.transitionInterruption,startProps:o.start,endProps:o.end,onStart:t.onTransitionStart,onUpdate:this._onTransitionUpdate,onInterrupt:this._onTransitionEnd(t.onTransitionInterrupt),onEnd:this._onTransitionEnd(t.onTransitionEnd)}),this.onStateChange({inTransition:!0}),this.updateTransition()}}},{key:"_onTransitionEnd",value:function(e){var t=this;return function(A){t.propsInTransition=null,t.onStateChange({inTransition:!1,isZooming:!1,isPanning:!1,isRotating:!1}),e(A)}}},{key:"_onTransitionUpdate",value:function(e){var t=e.time,A=e.settings,r=A.interpolator,i=A.startProps,o=A.endProps,a=A.duration,s=(0,A.easing)(t/a),g=r.interpolateProps(i,o,s);this.propsInTransition=new this.ControllerState(Object(n.a)({},this.props,{},g)).getViewportProps(),this.onViewStateChange({viewState:this.propsInTransition,oldViewState:this.props})}}]),e}()},function(e,t,A){"use strict";A.d(t,"a",(function(){return h}));var n=A(7),r=A(6),i=A(1),o=A(4),a=A(16),s=A(17),g=A(9),c=A(10),u=A(265),l=A(23),I=["longitude","latitude","zoom","bearing","pitch"],C=["longitude","latitude","zoom"],h=function(e){Object(g.a)(A,e);var t=Object(c.a)(A);function A(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(i.a)(this,A);var r=Array.isArray(n)?n:n.transitionProps;return(e=t.call(this,r||{compare:I,extract:I,required:C})).opts=n,e}return Object(o.a)(A,[{key:"initializeProps",value:function(e,t){var n=Object(s.a)(Object(a.a)(A.prototype),"initializeProps",this).call(this,e,t),r=this.opts,i=r.makeViewport,o=r.around;if(i&&o){var g=i(e),c=i(t),u=g.unproject(o);n.start.around=o,Object.assign(n.end,{around:c.project(u),aroundPosition:u,width:t.width,height:t.height})}return n}},{key:"interpolateProps",value:function(e,t,A){var i,o={},a=Object(r.a)(this._propsToExtract);try{for(a.s();!(i=a.n()).done;){var s=i.value;o[s]=Object(l.lerp)(e[s]||0,t[s]||0,A)}}catch(c){a.e(c)}finally{a.f()}if(t.aroundPosition){var g=this.opts.makeViewport(Object(n.a)({},t,{},o));Object.assign(o,g.panByPosition(t.aroundPosition,Object(l.lerp)(e.around,t.around,A)))}return o}}]),A}(u.a)},function(e,t,A){"use strict";var n=A(98),r=A.n(n),i=A(416),o=A.n(i),a=A(93),s=A.n(a),g=A(278),c=A.n(g),u=A(279),l=A.n(u),I=A(280),C=A.n(I),h=A(281),f=A.n(h),d=A(0),B=A.n(d),p=A(13),E=A.n(p),Q=A(61),y=A.n(Q),v=A(100),m=A(282),b=A(183),w=A.n(b),S=!("undefined"===typeof window||!window.document||!window.document.createElement);function F(e,t){var A={};return A[e.toLowerCase()]=t.toLowerCase(),A["Webkit"+e]="webkit"+t,A["Moz"+e]="moz"+t,A["ms"+e]="MS"+t,A["O"+e]="o"+t.toLowerCase(),A}var R=function(e,t){var A={animationend:F("Animation","AnimationEnd"),transitionend:F("Transition","TransitionEnd")};return e&&("AnimationEvent"in t||delete A.animationend.animation,"TransitionEvent"in t||delete A.transitionend.transition),A}(S,"undefined"!==typeof window?window:{}),D={};S&&(D=document.createElement("div").style);var G={};function k(e){if(G[e])return G[e];var t=R[e];if(t)for(var A=Object.keys(t),n=A.length,r=0;rc.b?(r=Math.acos(i),o=Math.sin(r),a=Math.sin((1-n)*r)/o,s=Math.sin(n*r)/o):(a=1-n,s=n),e[0]=a*g+s*C,e[1]=a*u+s*h,e[2]=a*l+s*f,e[3]=a*I+s*d,e}function B(e,t){var A,n=t[0]+t[4]+t[8];if(n>0)A=Math.sqrt(n+1),e[3]=.5*A,A=.5/A,e[0]=(t[5]-t[7])*A,e[1]=(t[6]-t[2])*A,e[2]=(t[1]-t[3])*A;else{var r=0;t[4]>t[0]&&(r=1),t[8]>t[3*r+r]&&(r=2);var i=(r+1)%3,o=(r+2)%3;A=Math.sqrt(t[3*r+r]-t[3*i+i]-t[3*o+o]+1),e[r]=.5*A,A=.5/A,e[3]=(t[3*i+o]-t[3*o+i])*A,e[i]=(t[3*i+r]+t[3*r+i])*A,e[o]=(t[3*o+r]+t[3*r+o])*A}return e}I.b,I.g,I.c,I.l;var p=I.a,E=I.k,Q=I.d,y=I.i,v=I.h,m=I.m,b=I.j,w=(I.f,I.e,function(){var e=l.b(),t=l.e(1,0,0),A=l.e(0,1,0);return function(n,r,i){var o=l.d(r,i);return o<-.999999?(l.c(e,t,r),l.f(e)<1e-6&&l.c(e,A,r),l.h(e,e),h(n,e,Math.PI),n):o>.999999?(n[0]=0,n[1]=0,n[2]=0,n[3]=1,n):(l.c(e,r,i),n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=1+o,b(n,n))}}());(function(){var e=C(),t=C()})(),function(){var e=u.a()}();A.d(t,"a",(function(){return F}));var S=[0,0,0,1],F=function(e){Object(i.a)(A,e);var t=Object(o.a)(A);function A(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;return Object(n.a)(this,A),e=t.call(this,-0,-0,-0,-0),Array.isArray(r)&&1===arguments.length?e.copy(r):e.set(r,i,o,a),e}return Object(r.a)(A,[{key:"copy",value:function(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this.check()}},{key:"set",value:function(e,t,A,n){return this[0]=e,this[1]=t,this[2]=A,this[3]=n,this.check()}},{key:"fromMatrix3",value:function(e){return B(this,e),this.check()}},{key:"identity",value:function(){var e;return(e=this)[0]=0,e[1]=0,e[2]=0,e[3]=1,this.check()}},{key:"fromAxisRotation",value:function(e,t){return h(this,e,t),this.check()}},{key:"setAxisAngle",value:function(e,t){return this.fromAxisRotation(e,t)}},{key:"len",value:function(){return v(this)}},{key:"lengthSquared",value:function(){return m(this)}},{key:"dot",value:function(e,t){if(void 0!==t)throw new Error("Quaternion.dot only takes one argument");return Q(this,e)}},{key:"rotationTo",value:function(e,t){return w(this,e,t),this.check()}},{key:"add",value:function(e,t){if(void 0!==t)throw new Error("Quaternion.add only takes one argument");return p(this,this,e),this.check()}},{key:"calculateW",value:function(){return function(e,t){var A=t[0],n=t[1],r=t[2];e[0]=A,e[1]=n,e[2]=r,e[3]=Math.sqrt(Math.abs(1-A*A-n*n-r*r))}(this,this),this.check()}},{key:"conjugate",value:function(){var e,t;return t=this,(e=this)[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=t[3],this.check()}},{key:"invert",value:function(){return function(e,t){var A=t[0],n=t[1],r=t[2],i=t[3],o=A*A+n*n+r*r+i*i,a=o?1/o:0;e[0]=-A*a,e[1]=-n*a,e[2]=-r*a,e[3]=i*a}(this,this),this.check()}},{key:"lerp",value:function(e,t,A){return y(this,e,t,A),this.check()}},{key:"multiplyRight",value:function(e,t){return Object(g.a)(!t),f(this,this,e),this.check()}},{key:"multiplyLeft",value:function(e,t){return Object(g.a)(!t),f(this,e,this),this.check()}},{key:"normalize",value:function(){var e=this.len(),t=e>0?1/e:0;return this[0]=this[0]*t,this[1]=this[1]*t,this[2]=this[2]*t,this[3]=this[3]*t,0===e&&(this[3]=1),this.check()}},{key:"rotateX",value:function(e){return function(e,t,A){A*=.5;var n=t[0],r=t[1],i=t[2],o=t[3],a=Math.sin(A),s=Math.cos(A);e[0]=n*s+o*a,e[1]=r*s+i*a,e[2]=i*s-r*a,e[3]=o*s-n*a}(this,this,e),this.check()}},{key:"rotateY",value:function(e){return function(e,t,A){A*=.5;var n=t[0],r=t[1],i=t[2],o=t[3],a=Math.sin(A),s=Math.cos(A);e[0]=n*s-i*a,e[1]=r*s+o*a,e[2]=i*s+n*a,e[3]=o*s-r*a}(this,this,e),this.check()}},{key:"rotateZ",value:function(e){return function(e,t,A){A*=.5;var n=t[0],r=t[1],i=t[2],o=t[3],a=Math.sin(A),s=Math.cos(A);e[0]=n*s+r*a,e[1]=r*s-n*a,e[2]=i*s+o*a,e[3]=o*s-i*a}(this,this,e),this.check()}},{key:"scale",value:function(e){return E(this,this,e),this.check()}},{key:"slerp",value:function(e,t,A){switch(arguments.length){case 1:var n=arguments[0],r=n.start;e=void 0===r?S:r,t=n.target,A=n.ratio;break;case 2:var i=Array.prototype.slice.call(arguments);t=i[0],A=i[1],e=this}return d(this,e,t,A),this.check()}},{key:"transformVector4",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;return I.o(t,e,this),Object(s.b)(t,4)}},{key:"lengthSq",value:function(){return this.lengthSquared()}},{key:"setFromAxisAngle",value:function(e,t){return this.setAxisAngle(e,t)}},{key:"premultiply",value:function(e,t){return this.multiplyLeft(e,t)}},{key:"multiply",value:function(e,t){return this.multiplyRight(e,t)}},{key:"ELEMENTS",get:function(){return 4}},{key:"x",get:function(){return this[0]},set:function(e){this[0]=Object(s.a)(e)}},{key:"y",get:function(){return this[1]},set:function(e){this[1]=Object(s.a)(e)}},{key:"z",get:function(){return this[2]},set:function(e){this[2]=Object(s.a)(e)}},{key:"w",get:function(){return this[3]},set:function(e){this[3]=Object(s.a)(e)}}]),A}(a.a)},function(e,t,A){"use strict";function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var A=0,n=new Array(t);A2&&void 0!==arguments[2]&&arguments[2],n=t.projectPosition(e);if(A&&t instanceof a.a){var i=Object(r.a)(e,3),o=i[0],s=i[1],g=i[2],c=void 0===g?0:g,u=t.getDistanceScales([o,s]);n[2]=c*u.unitsPerMeter[2]}return n}function l(e,t){var A=t.viewport,n=t.modelMatrix,o=t.coordinateSystem,a=t.coordinateOrigin,g=t.offsetMode,l=Object(r.a)(e,3),I=l[0],C=l[1],h=l[2],f=void 0===h?0:h;if(n){var d=s.n([],[I,C,f,1],n),B=Object(r.a)(d,3);I=B[0],C=B[1],f=B[2]}switch(o){case i.a.LNGLAT:return u([I,C,f],A,g);case i.a.LNGLAT_OFFSETS:return u([I+a[0],C+a[1],f+(a[2]||0)],A,g);case i.a.METER_OFFSETS:return u(Object(c.b)(a,[I,C,f]),A,g);case i.a.CARTESIAN:default:return A.isGeospatial?[I+a[0],C+a[1],f+a[2]]:A.projectPosition([I,C,f])}}function I(e,t){var A=function(e){var t=Object(n.a)({},e),A=e.coordinateSystem,r=e.viewport,o=e.coordinateOrigin,a=e.fromCoordinateSystem,s=e.fromCoordinateOrigin;return A===i.a.DEFAULT&&(A=r.isGeospatial?i.a.LNGLAT:i.a.CARTESIAN),void 0===a&&(t.fromCoordinateSystem=A),void 0===s&&(t.fromCoordinateOrigin=o),t.coordinateSystem=A,t}(t),r=A.viewport,a=A.coordinateSystem,s=A.coordinateOrigin,c=A.modelMatrix,u=A.fromCoordinateSystem,I=A.fromCoordinateOrigin,C=Object(o.a)(r,a,s),h=C.geospatialOrigin,f=C.shaderCoordinateOrigin,d=C.offsetMode,B=l(e,{viewport:r,modelMatrix:c,coordinateSystem:u,coordinateOrigin:I,offsetMode:d});if(d){var p=r.projectPosition(h||f);g.n(B,B,p)}return B}},function(e,t,A){"use strict";(function(e,n){A.d(t,"a",(function(){return i})),A.d(t,"b",(function(){return o}));var r={self:"undefined"!==typeof self&&self,window:"undefined"!==typeof window&&window,global:"undefined"!==typeof e&&e,document:"undefined"!==typeof document&&document},i=r.global||r.self||r.window,o="object"!==typeof n||"[object process]"!==String(n)||n.browser,a="undefined"!==typeof n&&n.version&&/v([0-9]*)/.exec(n.version);a&&parseFloat(a[1])}).call(this,A(86),A(90))},function(e,t,A){"use strict";A.d(t,"b",(function(){return C})),A.d(t,"a",(function(){return h}));var n=A(8),r=A(6),i=A(668),o=A.n(i),a=A(89),s=a.a.CLOCKWISE,g=a.a.COUNTER_CLOCKWISE,c={isClosed:!0};function u(e,t,A,n){for(var r=0;r4&&void 0!==arguments[4]?arguments[4]:0,i=arguments.length>5?arguments[5]:void 0,o=arguments.length>6?arguments[6]:void 0,s=(i=i||A.length)-r;if(s<=0)return t;for(var g=t,l=0;l=1&&e[0].length>=2&&Number.isFinite(e[0][0])}(e)){var h,f=0,d=Object(r.a)(e.entries());try{for(d.s();!(h=d.n()).done;){var B=Object(n.a)(h.value,2),p=B[0];f=l(A,f,B[1],t,0===p?s:g),i.push(f)}}catch(E){d.e(E)}finally{d.f()}return i.pop(),{positions:A,holeIndices:i}}return l(A,0,e,t,s),A}function h(e,t,A){var n=null;e.holeIndices&&(n=e.holeIndices.map((function(e){return e/t})));var r=e.positions||e;if(A){var i=r.length;r=r.slice();for(var a=[],s=0;s0&&void 0!==arguments[0]?arguments[0]:{},t=e.color,A=void 0===t?[0,0,0]:t,n=e.intensity,r=void 0===n?1:n;return A.map((function(e){return e*r/255}))}function a(e){var t=e.ambientLight,A=e.pointLights,n=void 0===A?[]:A,r=e.directionalLights,i=void 0===r?[]:r,a={};return a["lighting_uAmbientLight.color"]=t?o(t):[0,0,0],n.forEach((function(e,t){a["lighting_uPointLight[".concat(t,"].color")]=o(e),a["lighting_uPointLight[".concat(t,"].position")]=e.position,a["lighting_uPointLight[".concat(t,"].attenuation")]=e.attenuation||[1,0,0]})),a.lighting_uPointLightCount=n.length,i.forEach((function(e,t){a["lighting_uDirectionalLight[".concat(t,"].color")]=o(e),a["lighting_uDirectionalLight[".concat(t,"].direction")]=e.direction})),a.lighting_uDirectionalLightCount=i.length,a}var s={name:"lights",vs:r,fs:r,getUniforms:function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i;if("lightSources"in t){var A=t.lightSources||{},r=A.ambientLight,o=A.pointLights,s=A.directionalLights,g=r||o&&o.length>0||s&&s.length>0;return g?Object.assign({},a({ambientLight:r,pointLights:o,directionalLights:s}),{lighting_uEnabled:!0}):{lighting_uEnabled:!1}}if("lights"in t){var c,u={pointLights:[],directionalLights:[]},l=Object(n.a)(t.lights||[]);try{for(l.s();!(c=l.n()).done;){var I=c.value;switch(I.type){case"ambient":u.ambientLight=I;break;case"directional":u.directionalLights.push(I);break;case"point":u.pointLights.push(I)}}}catch(C){l.e(C)}finally{l.f()}return e({lightSources:u})}return{}},defines:{MAX_LIGHTS:3}}},function(e,t,A){"use strict";A.d(t,"a",(function(){return s}));var n=A(1),r=A(4),i=A(18),o=A(1165),a=A(62),s=new(function(){function e(){Object(n.a)(this,e),this.stats=new Map}return Object(r.a)(e,[{key:"get",value:function(e){return this.stats.has(e)||this.stats.set(e,new o.a({id:e})),this.stats.get(e)}}]),e}());if(a.global.luma&&"8.5.10"!==a.global.luma.VERSION)throw new Error("luma.gl - multiple VERSIONs detected: ".concat(a.global.luma.VERSION," vs ").concat("8.5.10"));a.global.luma||(Object(a.isBrowser)()&&i.k.log(1,"luma.gl ".concat("8.5.10"," - ").concat("set luma.log.level=1 (or higher) to trace rendering"))(),a.global.luma=a.global.luma||{VERSION:"8.5.10",version:"8.5.10",log:i.k,stats:s,globals:{modules:{},nodeIO:{}}});a.global.luma},,function(e,t,A){var n;!function(r,i,o,a){"use strict";var s,g=["","webkit","Moz","MS","ms","o"],c=i.createElement("div"),u=Math.round,l=Math.abs,I=Date.now;function C(e,t,A){return setTimeout(Q(e,A),t)}function h(e,t,A){return!!Array.isArray(e)&&(f(e,A[t],A),!0)}function f(e,t,A){var n;if(e)if(e.forEach)e.forEach(t,A);else if(void 0!==e.length)for(n=0;n\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",i=r.console&&(r.console.warn||r.console.log);return i&&i.call(r.console,n,A),e.apply(this,arguments)}}s="function"!==typeof Object.assign?function(e){if(void 0===e||null===e)throw new TypeError("Cannot convert undefined or null to object");for(var t=Object(e),A=1;A-1}function F(e){return e.trim().split(/\s+/g)}function R(e,t,A){if(e.indexOf&&!A)return e.indexOf(t);for(var n=0;nA[t]})):n.sort()),n}function k(e,t){for(var A,n,r=t[0].toUpperCase()+t.slice(1),i=0;i1&&!A.firstMultiple?A.firstMultiple=H(t):1===r&&(A.firstMultiple=!1);var i=A.firstInput,o=A.firstMultiple,a=o?o.center:i.center,s=t.center=Y(n);t.timeStamp=I(),t.deltaTime=t.timeStamp-i.timeStamp,t.angle=V(a,s),t.distance=P(a,s),function(e,t){var A=t.center,n=e.offsetDelta||{},r=e.prevDelta||{},i=e.prevInput||{};1!==t.eventType&&4!==i.eventType||(r=e.prevDelta={x:i.deltaX||0,y:i.deltaY||0},n=e.offsetDelta={x:A.x,y:A.y});t.deltaX=r.x+(A.x-n.x),t.deltaY=r.y+(A.y-n.y)}(A,t),t.offsetDirection=j(t.deltaX,t.deltaY);var g=J(t.deltaTime,t.deltaX,t.deltaY);t.overallVelocityX=g.x,t.overallVelocityY=g.y,t.overallVelocity=l(g.x)>l(g.y)?g.x:g.y,t.scale=o?(c=o.pointers,u=n,P(u[0],u[1],L)/P(c[0],c[1],L)):1,t.rotation=o?function(e,t){return V(t[1],t[0],L)+V(e[1],e[0],L)}(o.pointers,n):0,t.maxPointers=A.prevInput?t.pointers.length>A.prevInput.maxPointers?t.pointers.length:A.prevInput.maxPointers:t.pointers.length,function(e,t){var A,n,r,i,o=e.lastInterval||t,a=t.timeStamp-o.timeStamp;if(8!=t.eventType&&(a>25||void 0===o.velocity)){var s=t.deltaX-o.deltaX,g=t.deltaY-o.deltaY,c=J(a,s,g);n=c.x,r=c.y,A=l(c.x)>l(c.y)?c.x:c.y,i=j(s,g),e.lastInterval=t}else A=o.velocity,n=o.velocityX,r=o.velocityY,i=o.direction;t.velocity=A,t.velocityX=n,t.velocityY=r,t.direction=i}(A,t);var c,u;var C=e.element;w(t.srcEvent.target,C)&&(C=t.srcEvent.target);t.target=C}(e,A),e.emit("hammer.input",A),e.recognize(A),e.session.prevInput=A}function H(e){for(var t=[],A=0;A=l(t)?e<0?2:4:t<0?8:16}function P(e,t,A){A||(A=O);var n=t[A[0]]-e[A[0]],r=t[A[1]]-e[A[1]];return Math.sqrt(n*n+r*r)}function V(e,t,A){A||(A=O);var n=t[A[0]]-e[A[0]],r=t[A[1]]-e[A[1]];return 180*Math.atan2(r,n)/Math.PI}T.prototype={handler:function(){},init:function(){this.evEl&&m(this.element,this.evEl,this.domHandler),this.evTarget&&m(this.target,this.evTarget,this.domHandler),this.evWin&&m(N(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&b(this.element,this.evEl,this.domHandler),this.evTarget&&b(this.target,this.evTarget,this.domHandler),this.evWin&&b(N(this.element),this.evWin,this.domHandler)}};var K={mousedown:1,mousemove:2,mouseup:4};function W(){this.evEl="mousedown",this.evWin="mousemove mouseup",this.pressed=!1,T.apply(this,arguments)}E(W,T,{handler:function(e){var t=K[e.type];1&t&&0===e.button&&(this.pressed=!0),2&t&&1!==e.which&&(t=4),this.pressed&&(4&t&&(this.pressed=!1),this.callback(this.manager,t,{pointers:[e],changedPointers:[e],pointerType:"mouse",srcEvent:e}))}});var X={pointerdown:1,pointermove:2,pointerup:4,pointercancel:8,pointerout:8},q={2:"touch",3:"pen",4:"mouse",5:"kinect"},z="pointerdown",$="pointermove pointerup pointercancel";function ee(){this.evEl=z,this.evWin=$,T.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}r.MSPointerEvent&&!r.PointerEvent&&(z="MSPointerDown",$="MSPointerMove MSPointerUp MSPointerCancel"),E(ee,T,{handler:function(e){var t=this.store,A=!1,n=e.type.toLowerCase().replace("ms",""),r=X[n],i=q[e.pointerType]||e.pointerType,o="touch"==i,a=R(t,e.pointerId,"pointerId");1&r&&(0===e.button||o)?a<0&&(t.push(e),a=t.length-1):12&r&&(A=!0),a<0||(t[a]=e,this.callback(this.manager,r,{pointers:t,changedPointers:[e],pointerType:i,srcEvent:e}),A&&t.splice(a,1))}});var te={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function Ae(){this.evTarget="touchstart",this.evWin="touchstart touchmove touchend touchcancel",this.started=!1,T.apply(this,arguments)}function ne(e,t){var A=D(e.touches),n=D(e.changedTouches);return 12&t&&(A=G(A.concat(n),"identifier",!0)),[A,n]}E(Ae,T,{handler:function(e){var t=te[e.type];if(1===t&&(this.started=!0),this.started){var A=ne.call(this,e,t);12&t&&A[0].length-A[1].length===0&&(this.started=!1),this.callback(this.manager,t,{pointers:A[0],changedPointers:A[1],pointerType:"touch",srcEvent:e})}}});var re={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function ie(){this.evTarget="touchstart touchmove touchend touchcancel",this.targetIds={},T.apply(this,arguments)}function oe(e,t){var A=D(e.touches),n=this.targetIds;if(3&t&&1===A.length)return n[A[0].identifier]=!0,[A,A];var r,i,o=D(e.changedTouches),a=[],s=this.target;if(i=A.filter((function(e){return w(e.target,s)})),1===t)for(r=0;r-1&&n.splice(e,1)}),2500)}}function ce(e){for(var t=e.srcEvent.clientX,A=e.srcEvent.clientY,n=0;n-1&&this.requireFail.splice(t,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(e){return!!this.simultaneous[e.id]},emit:function(e){var t=this,A=this.state;function n(A){t.manager.emit(A,e)}A<8&&n(t.options.event+fe(A)),n(t.options.event),e.additionalEvent&&n(e.additionalEvent),A>=8&&n(t.options.event+fe(A))},tryEmit:function(e){if(this.canEmit())return this.emit(e);this.state=32},canEmit:function(){for(var e=0;et.threshold&&r&t.direction},attrTest:function(e){return pe.prototype.attrTest.call(this,e)&&(2&this.state||!(2&this.state)&&this.directionTest(e))},emit:function(e){this.pX=e.deltaX,this.pY=e.deltaY;var t=de(e.direction);t&&(e.additionalEvent=this.options.event+t),this._super.emit.call(this,e)}}),E(Qe,pe,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return["none"]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.scale-1)>this.options.threshold||2&this.state)},emit:function(e){if(1!==e.scale){var t=e.scale<1?"in":"out";e.additionalEvent=this.options.event+t}this._super.emit.call(this,e)}}),E(ye,he,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return["auto"]},process:function(e){var t=this.options,A=e.pointers.length===t.pointers,n=e.distancet.time;if(this._input=e,!n||!A||12&e.eventType&&!r)this.reset();else if(1&e.eventType)this.reset(),this._timer=C((function(){this.state=8,this.tryEmit()}),t.time,this);else if(4&e.eventType)return 8;return 32},reset:function(){clearTimeout(this._timer)},emit:function(e){8===this.state&&(e&&4&e.eventType?this.manager.emit(this.options.event+"up",e):(this._input.timeStamp=I(),this.manager.emit(this.options.event,this._input)))}}),E(ve,pe,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return["none"]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.rotation)>this.options.threshold||2&this.state)}}),E(me,pe,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:30,pointers:1},getTouchAction:function(){return Ee.prototype.getTouchAction.call(this)},attrTest:function(e){var t,A=this.options.direction;return 30&A?t=e.overallVelocity:6&A?t=e.overallVelocityX:24&A&&(t=e.overallVelocityY),this._super.attrTest.call(this,e)&&A&e.offsetDirection&&e.distance>this.options.threshold&&e.maxPointers==this.options.pointers&&l(t)>this.options.velocity&&4&e.eventType},emit:function(e){var t=de(e.offsetDirection);t&&this.manager.emit(this.options.event+t,e),this.manager.emit(this.options.event,e)}}),E(be,he,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return["manipulation"]},process:function(e){var t=this.options,A=e.pointers.length===t.pointers,n=e.distance=0;)e[t]=0}var l=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),I=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),C=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),h=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),f=new Array(576);u(f);var d=new Array(60);u(d);var B=new Array(512);u(B);var p=new Array(256);u(p);var E=new Array(29);u(E);var Q,y,v,m=new Array(30);function b(e,t,A,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=A,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}function w(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}u(m);var S=function(e){return e<256?B[e]:B[256+(e>>>7)]},F=function(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},R=function(e,t,A){e.bi_valid>16-A?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=A-16):(e.bi_buf|=t<>>=1,A<<=1}while(--t>0);return A>>>1},k=function(e,t,A){var n,r,i=new Array(16),o=0;for(n=1;n<=15;n++)i[n]=o=o+A[n-1]<<1;for(r=0;r<=t;r++){var a=e[2*r+1];0!==a&&(e[2*r]=G(i[a]++,a))}},x=function(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0},N=function(e){e.bi_valid>8?F(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},U=function(e,t,A,n){var r=2*t,i=2*A;return e[r]>1;A>=1;A--)_(e,i,A);r=s;do{A=e.heap[1],e.heap[1]=e.heap[e.heap_len--],_(e,i,1),n=e.heap[1],e.heap[--e.heap_max]=A,e.heap[--e.heap_max]=n,i[2*r]=i[2*A]+i[2*n],e.depth[r]=(e.depth[A]>=e.depth[n]?e.depth[A]:e.depth[n])+1,i[2*A+1]=i[2*n+1]=r,e.heap[1]=r++,_(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var A,n,r,i,o,a,s=t.dyn_tree,g=t.max_code,c=t.stat_desc.static_tree,u=t.stat_desc.has_stree,l=t.stat_desc.extra_bits,I=t.stat_desc.extra_base,C=t.stat_desc.max_length,h=0;for(i=0;i<=15;i++)e.bl_count[i]=0;for(s[2*e.heap[e.heap_max]+1]=0,A=e.heap_max+1;A<573;A++)(i=s[2*s[2*(n=e.heap[A])+1]+1]+1)>C&&(i=C,h++),s[2*n+1]=i,n>g||(e.bl_count[i]++,o=0,n>=I&&(o=l[n-I]),a=s[2*n],e.opt_len+=a*(i+o),u&&(e.static_len+=a*(c[2*n+1]+o)));if(0!==h){do{for(i=C-1;0===e.bl_count[i];)i--;e.bl_count[i]--,e.bl_count[i+1]+=2,e.bl_count[C]--,h-=2}while(h>0);for(i=C;0!==i;i--)for(n=e.bl_count[i];0!==n;)(r=e.heap[--A])>g||(s[2*r+1]!==i&&(e.opt_len+=(i-s[2*r+1])*s[2*r],s[2*r+1]=i),n--)}}(e,t),k(i,g,e.bl_count)},L=function(e,t,A){var n,r,i=-1,o=t[1],a=0,s=7,g=4;for(0===o&&(s=138,g=3),t[2*(A+1)+1]=65535,n=0;n<=A;n++)r=o,o=t[2*(n+1)+1],++a>=7;n<30;n++)for(m[n]=r<<7,e=0;e<1<0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,A=4093624447;for(t=0;t<=31;t++,A>>>=1)if(1&A&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),O(e,e.l_desc),O(e,e.d_desc),o=function(e){var t;for(L(e,e.dyn_ltree,e.l_desc.max_code),L(e,e.dyn_dtree,e.d_desc.max_code),O(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*h[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(i=e.static_len+3+7>>>3)<=r&&(r=i)):r=i=A+5,A+4<=r&&-1!==t?H(e,t,A,n):4===e.strategy||i===r?(R(e,2+(n?1:0),3),M(e,f,d)):(R(e,4+(n?1:0),3),function(e,t,A,n){var r;for(R(e,t-257,5),R(e,A-1,5),R(e,n-4,4),r=0;r>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&A,e.last_lit++,0===t?e.dyn_ltree[2*A]++:(e.matches++,t--,e.dyn_ltree[2*(p[A]+256+1)]++,e.dyn_dtree[2*S(t)]++),e.last_lit===e.lit_bufsize-1},_tr_align:function(e){R(e,2,3),D(e,256,f),function(e){16===e.bi_valid?(F(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},J=function(e,t,A,n){for(var r=65535&e|0,i=e>>>16&65535|0,o=0;0!==A;){A-=o=A>2e3?2e3:A;do{i=i+(r=r+t[n++]|0)|0}while(--o);r%=65521,i%=65521}return r|i<<16|0},j=new Uint32Array(function(){for(var e,t=[],A=0;A<256;A++){e=A;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[A]=e}return t}()),P=function(e,t,A,n){var r=j,i=n+A;e^=-1;for(var o=n;o>>8^r[255&(e^t[o])];return-1^e},V={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},K={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},W=Y._tr_init,X=Y._tr_stored_block,q=Y._tr_flush_block,z=Y._tr_tally,$=Y._tr_align,ee=K.Z_NO_FLUSH,te=K.Z_PARTIAL_FLUSH,Ae=K.Z_FULL_FLUSH,ne=K.Z_FINISH,re=K.Z_BLOCK,ie=K.Z_OK,oe=K.Z_STREAM_END,ae=K.Z_STREAM_ERROR,se=K.Z_DATA_ERROR,ge=K.Z_BUF_ERROR,ce=K.Z_DEFAULT_COMPRESSION,ue=K.Z_FILTERED,le=K.Z_HUFFMAN_ONLY,Ie=K.Z_RLE,Ce=K.Z_FIXED,he=K.Z_DEFAULT_STRATEGY,fe=K.Z_UNKNOWN,de=K.Z_DEFLATED,Be=function(e,t){return e.msg=V[t],t},pe=function(e){return(e<<1)-(e>4?9:0)},Ee=function(e){for(var t=e.length;--t>=0;)e[t]=0},Qe=function(e,t,A){return(t<e.avail_out&&(A=e.avail_out),0!==A&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+A),e.next_out),e.next_out+=A,t.pending_out+=A,e.total_out+=A,e.avail_out-=A,t.pending-=A,0===t.pending&&(t.pending_out=0))},ve=function(e,t){q(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ye(e.strm)},me=function(e,t){e.pending_buf[e.pending++]=t},be=function(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},we=function(e,t,A,n){var r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),A),1===e.state.wrap?e.adler=J(e.adler,t,r,A):2===e.state.wrap&&(e.adler=P(e.adler,t,r,A)),e.next_in+=r,e.total_in+=r,r)},Se=function(e,t){var A,n,r=e.max_chain_length,i=e.strstart,o=e.prev_length,a=e.nice_match,s=e.strstart>e.w_size-262?e.strstart-(e.w_size-262):0,g=e.window,c=e.w_mask,u=e.prev,l=e.strstart+258,I=g[i+o-1],C=g[i+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(g[(A=t)+o]===C&&g[A+o-1]===I&&g[A]===g[i]&&g[++A]===g[i+1]){i+=2,A++;do{}while(g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&g[++i]===g[++A]&&io){if(e.match_start=t,o=n,n>=a)break;I=g[i+o-1],C=g[i+o]}}}while((t=u[t&c])>s&&0!==--r);return o<=e.lookahead?o:e.lookahead},Fe=function(e){var t,A,n,r,i,o=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=o+(o-262)){e.window.set(e.window.subarray(o,o+o),0),e.match_start-=o,e.strstart-=o,e.block_start-=o,t=A=e.hash_size;do{n=e.head[--t],e.head[t]=n>=o?n-o:0}while(--A);t=A=o;do{n=e.prev[--t],e.prev[t]=n>=o?n-o:0}while(--A);r+=o}if(0===e.strm.avail_in)break;if(A=we(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=A,e.lookahead+e.insert>=3)for(i=e.strstart-e.insert,e.ins_h=e.window[i],e.ins_h=Qe(e,e.ins_h,e.window[i+1]);e.insert&&(e.ins_h=Qe(e,e.ins_h,e.window[i+3-1]),e.prev[i&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=i,i++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<262&&0!==e.strm.avail_in)},Re=function(e,t){for(var A,n;;){if(e.lookahead<262){if(Fe(e),e.lookahead<262&&t===ee)return 1;if(0===e.lookahead)break}if(A=0,e.lookahead>=3&&(e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==A&&e.strstart-A<=e.w_size-262&&(e.match_length=Se(e,A)),e.match_length>=3)if(n=z(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+1]);else n=z(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(ve(e,!1),0===e.strm.avail_out)?1:2},De=function(e,t){for(var A,n,r;;){if(e.lookahead<262){if(Fe(e),e.lookahead<262&&t===ee)return 1;if(0===e.lookahead)break}if(A=0,e.lookahead>=3&&(e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==A&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=z(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=Qe(e,e.ins_h,e.window[e.strstart+3-1]),A=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(ve(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((n=z(e,0,e.window[e.strstart-1]))&&ve(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=z(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(ve(e,!1),0===e.strm.avail_out)?1:2};function Ge(e,t,A,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=A,this.max_chain=n,this.func=r}var ke=[new Ge(0,0,0,0,(function(e,t){var A=65535;for(A>e.pending_buf_size-5&&(A=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Fe(e),0===e.lookahead&&t===ee)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+A;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,ve(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-262&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(ve(e,!1),e.strm.avail_out),1)})),new Ge(4,4,8,4,Re),new Ge(4,5,16,8,Re),new Ge(4,6,32,32,Re),new Ge(4,4,16,16,De),new Ge(8,16,32,32,De),new Ge(8,16,128,128,De),new Ge(8,32,128,256,De),new Ge(32,128,258,1024,De),new Ge(32,258,258,4096,De)];function xe(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=de,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Ee(this.dyn_ltree),Ee(this.dyn_dtree),Ee(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Ee(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Ee(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var Ne=function(e){if(!e||!e.state)return Be(e,ae);e.total_in=e.total_out=0,e.data_type=fe;var t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:113,e.adler=2===t.wrap?0:1,t.last_flush=ee,W(t),ie},Ue=function(e){var t,A=Ne(e);return A===ie&&((t=e.state).window_size=2*t.w_size,Ee(t.head),t.max_lazy_match=ke[t.level].max_lazy,t.good_match=ke[t.level].good_length,t.nice_match=ke[t.level].nice_length,t.max_chain_length=ke[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),A},_e=function(e,t,A,n,r,i){if(!e)return ae;var o=1;if(t===ce&&(t=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),r<1||r>9||A!==de||n<8||n>15||t<0||t>9||i<0||i>Ce)return Be(e,ae);8===n&&(n=9);var a=new xe;return e.state=a,a.strm=e,a.wrap=o,a.gzhead=null,a.w_bits=n,a.w_size=1<re||t<0)return e?Be(e,ae):ae;var r=e.state;if(!e.output||!e.input&&0!==e.avail_in||666===r.status&&t!==ne)return Be(e,0===e.avail_out?ge:ae);r.strm=e;var i=r.last_flush;if(r.last_flush=t,42===r.status)if(2===r.wrap)e.adler=0,me(r,31),me(r,139),me(r,8),r.gzhead?(me(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),me(r,255&r.gzhead.time),me(r,r.gzhead.time>>8&255),me(r,r.gzhead.time>>16&255),me(r,r.gzhead.time>>24&255),me(r,9===r.level?2:r.strategy>=le||r.level<2?4:0),me(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(me(r,255&r.gzhead.extra.length),me(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=P(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69):(me(r,0),me(r,0),me(r,0),me(r,0),me(r,0),me(r,9===r.level?2:r.strategy>=le||r.level<2?4:0),me(r,3),r.status=113);else{var o=de+(r.w_bits-8<<4)<<8;o|=(r.strategy>=le||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(o|=32),o+=31-o%31,r.status=113,be(r,o),0!==r.strstart&&(be(r,e.adler>>>16),be(r,65535&e.adler)),e.adler=1}if(69===r.status)if(r.gzhead.extra){for(A=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>A&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),ye(e),A=r.pending,r.pending!==r.pending_buf_size));)me(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>A&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=73)}else r.status=73;if(73===r.status)if(r.gzhead.name){A=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>A&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),ye(e),A=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindexA&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),0===n&&(r.gzindex=0,r.status=91)}else r.status=91;if(91===r.status)if(r.gzhead.comment){A=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>A&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),ye(e),A=r.pending,r.pending===r.pending_buf_size)){n=1;break}n=r.gzindexA&&(e.adler=P(e.adler,r.pending_buf,r.pending-A,A)),0===n&&(r.status=103)}else r.status=103;if(103===r.status&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&ye(e),r.pending+2<=r.pending_buf_size&&(me(r,255&e.adler),me(r,e.adler>>8&255),e.adler=0,r.status=113)):r.status=113),0!==r.pending){if(ye(e),0===e.avail_out)return r.last_flush=-1,ie}else if(0===e.avail_in&&pe(t)<=pe(i)&&t!==ne)return Be(e,ge);if(666===r.status&&0!==e.avail_in)return Be(e,ge);if(0!==e.avail_in||0!==r.lookahead||t!==ee&&666!==r.status){var a=r.strategy===le?function(e,t){for(var A;;){if(0===e.lookahead&&(Fe(e),0===e.lookahead)){if(t===ee)return 1;break}if(e.match_length=0,A=z(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,A&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(ve(e,!1),0===e.strm.avail_out)?1:2}(r,t):r.strategy===Ie?function(e,t){for(var A,n,r,i,o=e.window;;){if(e.lookahead<=258){if(Fe(e),e.lookahead<=258&&t===ee)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(n=o[r=e.strstart-1])===o[++r]&&n===o[++r]&&n===o[++r]){i=e.strstart+258;do{}while(n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&n===o[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(A=z(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(A=z(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),A&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ne?(ve(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(ve(e,!1),0===e.strm.avail_out)?1:2}(r,t):ke[r.level].func(r,t);if(3!==a&&4!==a||(r.status=666),1===a||3===a)return 0===e.avail_out&&(r.last_flush=-1),ie;if(2===a&&(t===te?$(r):t!==re&&(X(r,0,0,!1),t===Ae&&(Ee(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),ye(e),0===e.avail_out))return r.last_flush=-1,ie}return t!==ne?ie:r.wrap<=0?oe:(2===r.wrap?(me(r,255&e.adler),me(r,e.adler>>8&255),me(r,e.adler>>16&255),me(r,e.adler>>24&255),me(r,255&e.total_in),me(r,e.total_in>>8&255),me(r,e.total_in>>16&255),me(r,e.total_in>>24&255)):(be(r,e.adler>>>16),be(r,65535&e.adler)),ye(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?ie:oe)},deflateEnd:function(e){if(!e||!e.state)return ae;var t=e.state.status;return 42!==t&&69!==t&&73!==t&&91!==t&&103!==t&&113!==t&&666!==t?Be(e,ae):(e.state=null,113===t?Be(e,se):ie)},deflateSetDictionary:function(e,t){var A=t.length;if(!e||!e.state)return ae;var n=e.state,r=n.wrap;if(2===r||1===r&&42!==n.status||n.lookahead)return ae;if(1===r&&(e.adler=J(e.adler,t,A,0)),n.wrap=0,A>=n.w_size){0===r&&(Ee(n.head),n.strstart=0,n.block_start=0,n.insert=0);var i=new Uint8Array(n.w_size);i.set(t.subarray(A-n.w_size,A),0),t=i,A=n.w_size}var o=e.avail_in,a=e.next_in,s=e.input;for(e.avail_in=A,e.next_in=0,e.input=t,Fe(n);n.lookahead>=3;){var g=n.strstart,c=n.lookahead-2;do{n.ins_h=Qe(n,n.ins_h,n.window[g+3-1]),n.prev[g&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=g,g++}while(--c);n.strstart=g,n.lookahead=2,Fe(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=a,e.input=s,e.avail_in=o,n.wrap=r,ie},deflateInfo:"pako deflate (from Nodeca project)"},Oe=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},Le=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var A=t.shift();if(A){if("object"!==typeof A)throw new TypeError(A+"must be non-object");for(var n in A)Oe(A,n)&&(e[n]=A[n])}}return e},Te=function(e){for(var t=0,A=0,n=e.length;A=252?6:Ye>=248?5:Ye>=240?4:Ye>=224?3:Ye>=192?2:1;He[254]=He[254]=1;var Je=function(e){var t,A,n,r,i,o=e.length,a=0;for(r=0;r>>6,t[i++]=128|63&A):A<65536?(t[i++]=224|A>>>12,t[i++]=128|A>>>6&63,t[i++]=128|63&A):(t[i++]=240|A>>>18,t[i++]=128|A>>>12&63,t[i++]=128|A>>>6&63,t[i++]=128|63&A);return t},je=function(e,t){var A,n,r=t||e.length,i=new Array(2*r);for(n=0,A=0;A4)i[n++]=65533,A+=a-1;else{for(o&=2===a?31:3===a?15:7;a>1&&A1?i[n++]=65533:o<65536?i[n++]=o:(o-=65536,i[n++]=55296|o>>10&1023,i[n++]=56320|1023&o)}}}return function(e,t){if(t<65534&&e.subarray&&Ze)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));for(var A="",n=0;ne.length&&(t=e.length);for(var A=t-1;A>=0&&128===(192&e[A]);)A--;return A<0||0===A?t:A+He[e[A]]>t?A:t};var Ve=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},Ke=Object.prototype.toString,We=K.Z_NO_FLUSH,Xe=K.Z_SYNC_FLUSH,qe=K.Z_FULL_FLUSH,ze=K.Z_FINISH,$e=K.Z_OK,et=K.Z_STREAM_END,tt=K.Z_DEFAULT_COMPRESSION,At=K.Z_DEFAULT_STRATEGY,nt=K.Z_DEFLATED;function rt(e){this.options=Le({level:tt,method:nt,chunkSize:16384,windowBits:15,memLevel:8,strategy:At},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ve,this.strm.avail_out=0;var A=Me.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(A!==$e)throw new Error(V[A]);if(t.header&&Me.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(n="string"===typeof t.dictionary?Je(t.dictionary):"[object ArrayBuffer]"===Ke.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(A=Me.deflateSetDictionary(this.strm,n))!==$e)throw new Error(V[A]);this._dict_set=!0}}function it(e,t){var A=new rt(t);if(A.push(e,!0),A.err)throw A.msg||V[A.err];return A.result}rt.prototype.push=function(e,t){var A,n,r=this.strm,i=this.options.chunkSize;if(this.ended)return!1;for(n=t===~~t?t:!0===t?ze:We,"string"===typeof e?r.input=Je(e):"[object ArrayBuffer]"===Ke.call(e)?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;;)if(0===r.avail_out&&(r.output=new Uint8Array(i),r.next_out=0,r.avail_out=i),(n===Xe||n===qe)&&r.avail_out<=6)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else{if((A=Me.deflate(r,n))===et)return r.next_out>0&&this.onData(r.output.subarray(0,r.next_out)),A=Me.deflateEnd(this.strm),this.onEnd(A),this.ended=!0,A===$e;if(0!==r.avail_out){if(n>0&&r.next_out>0)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else if(0===r.avail_in)break}else this.onData(r.output)}return!0},rt.prototype.onData=function(e){this.chunks.push(e)},rt.prototype.onEnd=function(e){e===$e&&(this.result=Te(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ot={Deflate:rt,deflate:it,deflateRaw:function(e,t){return(t=t||{}).raw=!0,it(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,it(e,t)},constants:K},at=function(e,t){var A,n,r,i,o,a,s,g,c,u,l,I,C,h,f,d,B,p,E,Q,y,v,m,b,w=e.state;A=e.next_in,m=e.input,n=A+(e.avail_in-5),r=e.next_out,b=e.output,i=r-(t-e.avail_out),o=r+(e.avail_out-257),a=w.dmax,s=w.wsize,g=w.whave,c=w.wnext,u=w.window,l=w.hold,I=w.bits,C=w.lencode,h=w.distcode,f=(1<>>=p=B>>>24,I-=p,0===(p=B>>>16&255))b[r++]=65535&B;else{if(!(16&p)){if(0===(64&p)){B=C[(65535&B)+(l&(1<>>=p,I-=p),I<15&&(l+=m[A++]<>>=p=B>>>24,I-=p,!(16&(p=B>>>16&255))){if(0===(64&p)){B=h[(65535&B)+(l&(1<a){e.msg="invalid distance too far back",w.mode=30;break e}if(l>>>=p,I-=p,Q>(p=r-i)){if((p=Q-p)>g&&w.sane){e.msg="invalid distance too far back",w.mode=30;break e}if(y=0,v=u,0===c){if(y+=s-p,p2;)b[r++]=v[y++],b[r++]=v[y++],b[r++]=v[y++],E-=3;E&&(b[r++]=v[y++],E>1&&(b[r++]=v[y++]))}else{y=r-Q;do{b[r++]=b[y++],b[r++]=b[y++],b[r++]=b[y++],E-=3}while(E>2);E&&(b[r++]=b[y++],E>1&&(b[r++]=b[y++]))}break}}break}}while(A>3,l&=(1<<(I-=E<<3))-1,e.next_in=A,e.next_out=r,e.avail_in=A=1&&0===D[Q];Q--);if(y>Q&&(y=Q),0===Q)return r[i++]=20971520,r[i++]=20971520,a.bits=1,0;for(E=1;E0&&(0===e||1!==Q))return-1;for(G[1]=0,B=1;B<15;B++)G[B+1]=G[B]+D[B];for(p=0;p852||2===e&&w>592)return 1;for(;;){C=B-m,o[p]I?(h=k[x+o[p]],f=F[R+o[p]]):(h=96,f=0),s=1<>m)+(g-=s)]=C<<24|h<<16|f|0}while(0!==g);for(s=1<>=1;if(0!==s?(S&=s-1,S+=s):S=0,p++,0===--D[B]){if(B===Q)break;B=t[A+o[p]]}if(B>y&&(S&u)!==c){for(0===m&&(m=y),l+=E,b=1<<(v=B-m);v+m852||2===e&&w>592)return 1;r[c=S&u]=y<<24|v<<16|l-i|0}}return 0!==S&&(r[l+S]=B-m<<24|64<<16|0),a.bits=y,0},It=K.Z_FINISH,Ct=K.Z_BLOCK,ht=K.Z_TREES,ft=K.Z_OK,dt=K.Z_STREAM_END,Bt=K.Z_NEED_DICT,pt=K.Z_STREAM_ERROR,Et=K.Z_DATA_ERROR,Qt=K.Z_MEM_ERROR,yt=K.Z_BUF_ERROR,vt=K.Z_DEFLATED,mt=function(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)};function bt(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var wt,St,Ft=function(e){if(!e||!e.state)return pt;var t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,ft},Rt=function(e){if(!e||!e.state)return pt;var t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Ft(e)},Dt=function(e,t){var A;if(!e||!e.state)return pt;var n=e.state;return t<0?(A=0,t=-t):(A=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?pt:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=A,n.wbits=t,Rt(e))},Gt=function(e,t){if(!e)return pt;var A=new bt;e.state=A,A.window=null;var n=Dt(e,t);return n!==ft&&(e.state=null),n},kt=!0,xt=function(e){if(kt){wt=new Int32Array(512),St=new Int32Array(32);for(var t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(lt(1,e.lens,0,288,wt,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;lt(2,e.lens,0,32,St,0,e.work,{bits:5}),kt=!1}e.lencode=wt,e.lenbits=9,e.distcode=St,e.distbits=5},Nt=function(e,t,A,n){var r,i=e.state;return null===i.window&&(i.wsize=1<=i.wsize?(i.window.set(t.subarray(A-i.wsize,A),0),i.wnext=0,i.whave=i.wsize):((r=i.wsize-i.wnext)>n&&(r=n),i.window.set(t.subarray(A-n,A-n+r),i.wnext),(n-=r)?(i.window.set(t.subarray(A-n,A),0),i.wnext=n,i.whave=i.wsize):(i.wnext+=r,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,A.check=P(A.check,S,2,0),g=0,c=0,A.mode=2;break}if(A.flags=0,A.head&&(A.head.done=!1),!(1&A.wrap)||(((255&g)<<8)+(g>>8))%31){e.msg="incorrect header check",A.mode=30;break}if((15&g)!==vt){e.msg="unknown compression method",A.mode=30;break}if(c-=4,y=8+(15&(g>>>=4)),0===A.wbits)A.wbits=y;else if(y>A.wbits){e.msg="invalid window size",A.mode=30;break}A.dmax=1<>8&1),512&A.flags&&(S[0]=255&g,S[1]=g>>>8&255,A.check=P(A.check,S,2,0)),g=0,c=0,A.mode=3;case 3:for(;c<32;){if(0===a)break e;a--,g+=n[i++]<>>8&255,S[2]=g>>>16&255,S[3]=g>>>24&255,A.check=P(A.check,S,4,0)),g=0,c=0,A.mode=4;case 4:for(;c<16;){if(0===a)break e;a--,g+=n[i++]<>8),512&A.flags&&(S[0]=255&g,S[1]=g>>>8&255,A.check=P(A.check,S,2,0)),g=0,c=0,A.mode=5;case 5:if(1024&A.flags){for(;c<16;){if(0===a)break e;a--,g+=n[i++]<>>8&255,A.check=P(A.check,S,2,0)),g=0,c=0}else A.head&&(A.head.extra=null);A.mode=6;case 6:if(1024&A.flags&&((I=A.length)>a&&(I=a),I&&(A.head&&(y=A.head.extra_len-A.length,A.head.extra||(A.head.extra=new Uint8Array(A.head.extra_len)),A.head.extra.set(n.subarray(i,i+I),y)),512&A.flags&&(A.check=P(A.check,n,I,i)),a-=I,i+=I,A.length-=I),A.length))break e;A.length=0,A.mode=7;case 7:if(2048&A.flags){if(0===a)break e;I=0;do{y=n[i+I++],A.head&&y&&A.length<65536&&(A.head.name+=String.fromCharCode(y))}while(y&&I>9&1,A.head.done=!0),e.adler=A.check=0,A.mode=12;break;case 10:for(;c<32;){if(0===a)break e;a--,g+=n[i++]<>>=7&c,c-=7&c,A.mode=27;break}for(;c<3;){if(0===a)break e;a--,g+=n[i++]<>>=1)){case 0:A.mode=14;break;case 1:if(xt(A),A.mode=20,t===ht){g>>>=2,c-=2;break e}break;case 2:A.mode=17;break;case 3:e.msg="invalid block type",A.mode=30}g>>>=2,c-=2;break;case 14:for(g>>>=7&c,c-=7&c;c<32;){if(0===a)break e;a--,g+=n[i++]<>>16^65535)){e.msg="invalid stored block lengths",A.mode=30;break}if(A.length=65535&g,g=0,c=0,A.mode=15,t===ht)break e;case 15:A.mode=16;case 16:if(I=A.length){if(I>a&&(I=a),I>s&&(I=s),0===I)break e;r.set(n.subarray(i,i+I),o),a-=I,i+=I,s-=I,o+=I,A.length-=I;break}A.mode=12;break;case 17:for(;c<14;){if(0===a)break e;a--,g+=n[i++]<>>=5,c-=5,A.ndist=1+(31&g),g>>>=5,c-=5,A.ncode=4+(15&g),g>>>=4,c-=4,A.nlen>286||A.ndist>30){e.msg="too many length or distance symbols",A.mode=30;break}A.have=0,A.mode=18;case 18:for(;A.have>>=3,c-=3}for(;A.have<19;)A.lens[F[A.have++]]=0;if(A.lencode=A.lendyn,A.lenbits=7,m={bits:A.lenbits},v=lt(0,A.lens,0,19,A.lencode,0,A.work,m),A.lenbits=m.bits,v){e.msg="invalid code lengths set",A.mode=30;break}A.have=0,A.mode=19;case 19:for(;A.have>>16&255,B=65535&w,!((f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>>=f,c-=f,A.lens[A.have++]=B;else{if(16===B){for(b=f+2;c>>=f,c-=f,0===A.have){e.msg="invalid bit length repeat",A.mode=30;break}y=A.lens[A.have-1],I=3+(3&g),g>>>=2,c-=2}else if(17===B){for(b=f+3;c>>=f)),g>>>=3,c-=3}else{for(b=f+7;c>>=f)),g>>>=7,c-=7}if(A.have+I>A.nlen+A.ndist){e.msg="invalid bit length repeat",A.mode=30;break}for(;I--;)A.lens[A.have++]=y}}if(30===A.mode)break;if(0===A.lens[256]){e.msg="invalid code -- missing end-of-block",A.mode=30;break}if(A.lenbits=9,m={bits:A.lenbits},v=lt(1,A.lens,0,A.nlen,A.lencode,0,A.work,m),A.lenbits=m.bits,v){e.msg="invalid literal/lengths set",A.mode=30;break}if(A.distbits=6,A.distcode=A.distdyn,m={bits:A.distbits},v=lt(2,A.lens,A.nlen,A.ndist,A.distcode,0,A.work,m),A.distbits=m.bits,v){e.msg="invalid distances set",A.mode=30;break}if(A.mode=20,t===ht)break e;case 20:A.mode=21;case 21:if(a>=6&&s>=258){e.next_out=o,e.avail_out=s,e.next_in=i,e.avail_in=a,A.hold=g,A.bits=c,at(e,l),o=e.next_out,r=e.output,s=e.avail_out,i=e.next_in,n=e.input,a=e.avail_in,g=A.hold,c=A.bits,12===A.mode&&(A.back=-1);break}for(A.back=0;d=(w=A.lencode[g&(1<>>16&255,B=65535&w,!((f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>p)])>>>16&255,B=65535&w,!(p+(f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>>=p,c-=p,A.back+=p}if(g>>>=f,c-=f,A.back+=f,A.length=B,0===d){A.mode=26;break}if(32&d){A.back=-1,A.mode=12;break}if(64&d){e.msg="invalid literal/length code",A.mode=30;break}A.extra=15&d,A.mode=22;case 22:if(A.extra){for(b=A.extra;c>>=A.extra,c-=A.extra,A.back+=A.extra}A.was=A.length,A.mode=23;case 23:for(;d=(w=A.distcode[g&(1<>>16&255,B=65535&w,!((f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>p)])>>>16&255,B=65535&w,!(p+(f=w>>>24)<=c);){if(0===a)break e;a--,g+=n[i++]<>>=p,c-=p,A.back+=p}if(g>>>=f,c-=f,A.back+=f,64&d){e.msg="invalid distance code",A.mode=30;break}A.offset=B,A.extra=15&d,A.mode=24;case 24:if(A.extra){for(b=A.extra;c>>=A.extra,c-=A.extra,A.back+=A.extra}if(A.offset>A.dmax){e.msg="invalid distance too far back",A.mode=30;break}A.mode=25;case 25:if(0===s)break e;if(I=l-s,A.offset>I){if((I=A.offset-I)>A.whave&&A.sane){e.msg="invalid distance too far back",A.mode=30;break}I>A.wnext?(I-=A.wnext,C=A.wsize-I):C=A.wnext-I,I>A.length&&(I=A.length),h=A.window}else h=r,C=o-A.offset,I=A.length;I>s&&(I=s),s-=I,A.length-=I;do{r[o++]=h[C++]}while(--I);0===A.length&&(A.mode=21);break;case 26:if(0===s)break e;r[o++]=A.length,s--,A.mode=21;break;case 27:if(A.wrap){for(;c<32;){if(0===a)break e;a--,g|=n[i++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0===(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ve,this.strm.avail_out=0;var A=Ut.inflateInit2(this.strm,t.windowBits);if(A!==Tt)throw new Error(V[A]);if(this.header=new _t,Ut.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"===typeof t.dictionary?t.dictionary=Je(t.dictionary):"[object ArrayBuffer]"===Mt.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(A=Ut.inflateSetDictionary(this.strm,t.dictionary))!==Tt))throw new Error(V[A])}function Vt(e,t){var A=new Pt(t);if(A.push(e),A.err)throw A.msg||V[A.err];return A.result}Pt.prototype.push=function(e,t){var A,n,r,i=this.strm,o=this.options.chunkSize,a=this.options.dictionary;if(this.ended)return!1;for(n=t===~~t?t:!0===t?Lt:Ot,"[object ArrayBuffer]"===Mt.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(o),i.next_out=0,i.avail_out=o),(A=Ut.inflate(i,n))===Ht&&a&&((A=Ut.inflateSetDictionary(i,a))===Tt?A=Ut.inflate(i,n):A===Jt&&(A=Ht));i.avail_in>0&&A===Zt&&i.state.wrap>0&&0!==e[i.next_in];)Ut.inflateReset(i),A=Ut.inflate(i,n);switch(A){case Yt:case Jt:case Ht:case jt:return this.onEnd(A),this.ended=!0,!1}if(r=i.avail_out,i.next_out&&(0===i.avail_out||A===Zt))if("string"===this.options.to){var s=Pe(i.output,i.next_out),g=i.next_out-s,c=je(i.output,s);i.next_out=g,i.avail_out=o-g,g&&i.output.set(i.output.subarray(s,s+g),0),this.onData(c)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(A!==Tt||0!==r){if(A===Zt)return A=Ut.inflateEnd(this.strm),this.onEnd(A),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},Pt.prototype.onData=function(e){this.chunks.push(e)},Pt.prototype.onEnd=function(e){e===Tt&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Te(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Kt={Inflate:Pt,inflate:Vt,inflateRaw:function(e,t){return(t=t||{}).raw=!0,Vt(e,t)},ungzip:Vt,constants:K},Wt={Deflate:ot.Deflate,deflate:ot.deflate,deflateRaw:ot.deflateRaw,gzip:ot.gzip,Inflate:Kt.Inflate,inflate:Kt.inflate,inflateRaw:Kt.inflateRaw,ungzip:Kt.ungzip,constants:K},Xt=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;if(Object(s.a)(this,e),t<0||t>9)throw new Error("Invalid gzip compression level, it should be between 0 and 9");this.level=t}return Object(g.a)(e,[{key:"encode",value:function(e){return Wt.gzip(e,{level:this.level})}},{key:"decode",value:function(e,t){var A=Wt.ungzip(e);return void 0!==t?(t.set(A),t):A}}],[{key:"fromConfig",value:function(t){return new e(t.level)}}]),e}();Xt.codecId="gzip";var qt=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;if(Object(s.a)(this,e),t<-1||t>9)throw new Error("Invalid zlib compression level, it should be between -1 and 9");this.level=t}return Object(g.a)(e,[{key:"encode",value:function(e){return Wt.deflate(e,{level:this.level})}},{key:"decode",value:function(e,t){var A=Wt.inflate(e);return void 0!==t?(t.set(A),t):A}}],[{key:"fromConfig",value:function(t){return new e(t.level)}}]),e}();qt.codecId="zlib";var zt="undefined"!==typeof e&&null!=e.versions&&null!=e.versions.node?function(e){return new Uint8Array(n.from(e,"base64"))}:function(){for(var e=new Uint8Array(128),t=0;t<64;t++)e[t<26?t+65:t<52?t+71:t<62?t-4:4*t-205]=t;return function(t){for(var A=t.length,n=new Uint8Array(3*(A-("="==t[A-1])-("="==t[A-2]))/4|0),r=0,i=0;r>4,n[i++]=a<<4|s>>2,n[i++]=s<<6|g}return n}}();function $t(e,t){return e({noInitialRun:!0,wasmBinary:zt(t)})}var eA,tA=function(){"undefined"!==typeof document&&document.currentScript&&document.currentScript.src;return function(e){var t,A,n;e=e||{},t||(t="undefined"!==typeof e?e:{}),t.ready=new Promise((function(e,t){A=e,n=t}));var r,i={};for(r in t)t.hasOwnProperty(r)&&(i[r]=t[r]);var o,a="./this.program",s=t.print||console.log.bind(console),g=t.printErr||console.warn.bind(console);for(r in i)i.hasOwnProperty(r)&&(t[r]=i[r]);i=null,t.thisProgram&&(a=t.thisProgram),t.wasmBinary&&(o=t.wasmBinary),t.noExitRuntime&&t.noExitRuntime,"object"!==typeof WebAssembly&&T("no native wasm support detected");var c,u=!1,l="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0;function I(e,t,A){var n=t+A;for(A=t;e[A]&&!(A>=n);)++A;if(16(r=224==(240&r)?(15&r)<<12|i<<6|o:(7&r)<<18|i<<12|o<<6|63&e[t++])?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r))}}else n+=String.fromCharCode(r)}return n}var C,h,f,d,B,p,E,Q,y,v="undefined"!==typeof TextDecoder?new TextDecoder("utf-16le"):void 0;function m(e,t){for(var A=e>>1,n=A+t/2;!(A>=n)&&B[A];)++A;if(32<(A<<=1)-e&&v)return v.decode(f.subarray(e,A));for(A=0,n="";;){var r=d[e+2*A>>1];if(0==r||A==t/2)return n;++A,n+=String.fromCharCode(r)}}function b(e,t,A){if(void 0===A&&(A=2147483647),2>A)return 0;var n=t;A=(A-=2)<2*e.length?A/2:e.length;for(var r=0;r>1]=e.charCodeAt(r),t+=2;return d[t>>1]=0,t-n}function w(e){return 2*e.length}function S(e,t){for(var A=0,n="";!(A>=t/4);){var r=p[e+4*A>>2];if(0==r)break;++A,65536<=r?(r-=65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r)):n+=String.fromCharCode(r)}return n}function F(e,t,A){if(void 0===A&&(A=2147483647),4>A)return 0;var n=t;A=n+A-4;for(var r=0;r=i)i=65536+((1023&i)<<10)|1023&e.charCodeAt(++r);if(p[t>>2]=i,(t+=4)+4>A)break}return p[t>>2]=0,t-n}function R(e){for(var t=0,A=0;A=n&&++A,t+=4}return t}function D(e){C=e,t.HEAP8=h=new Int8Array(e),t.HEAP16=d=new Int16Array(e),t.HEAP32=p=new Int32Array(e),t.HEAPU8=f=new Uint8Array(e),t.HEAPU16=B=new Uint16Array(e),t.HEAPU32=E=new Uint32Array(e),t.HEAPF32=Q=new Float32Array(e),t.HEAPF64=y=new Float64Array(e)}var G=t.INITIAL_MEMORY||16777216;(c=t.wasmMemory?t.wasmMemory:new WebAssembly.Memory({initial:G/65536,maximum:32768}))&&(C=c.buffer),G=C.byteLength,D(C);var k,x=[],N=[],U=[],_=[];function M(){var e=t.preRun.shift();x.unshift(e)}var O=0,L=null;function T(e){throw t.onAbort&&t.onAbort(e),g(e),u=!0,e=new WebAssembly.RuntimeError("abort("+e+"). Build with -s ASSERTIONS=1 for more info."),n(e),e}function Z(e){var t=Y;return String.prototype.startsWith?t.startsWith(e):0===t.indexOf(e)}function H(){return Z("data:application/octet-stream;base64,")}t.preloadedImages={},t.preloadedAudios={};var Y="blosc_codec.wasm";if(!H()){var J=Y;Y=t.locateFile?t.locateFile(J,""):""+J}function j(){try{if(o)return new Uint8Array(o);throw"both async and sync fetching of the wasm failed"}catch(e){T(e)}}function P(e){for(;0>2]=e},this.X=function(e){p[this.N+0>>2]=e},this.Y=function(){p[this.N+4>>2]=0},this.W=function(){h[this.N+12>>0]=0},this.Z=function(){h[this.N+13>>0]=0},this.V=function(e,t){this.$(e),this.X(t),this.Y(),this.W(),this.Z()}}function K(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+e)}}var W=void 0;function X(e){for(var t="";f[e];)t+=W[f[e++]];return t}var q={},z={},$={};function ee(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return 48<=t&&57>=t?"_"+e:e}function te(e,t){return e=ee(e),new Function("body","return function "+e+'() {\n "use strict"; return body.apply(this, arguments);\n};\n')(t)}function Ae(e){var t=Error,A=te(e,(function(t){this.name=e,this.message=t,void 0!==(t=Error(t).stack)&&(this.stack=this.toString()+"\n"+t.replace(/^Error(:[^\n]*)?\n/,""))}));return A.prototype=Object.create(t.prototype),A.prototype.constructor=A,A.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message},A}var ne=void 0;function re(e){throw new ne(e)}var ie=void 0;function oe(e,t,A){if(A=A||{},!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");var n=t.name;if(e||re('type "'+n+'" must have a positive integer typeid pointer'),z.hasOwnProperty(e)){if(A.U)return;re("Cannot register type '"+n+"' twice")}z[e]=t,delete $[e],q.hasOwnProperty(e)&&(t=q[e],delete q[e],t.forEach((function(e){e()})))}var ae=[],se=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function ge(e){4>2])}function le(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function Ie(e,t){switch(t){case 2:return function(e){return this.fromWireType(Q[e>>2])};case 3:return function(e){return this.fromWireType(y[e>>3])};default:throw new TypeError("Unknown float type: "+e)}}function Ce(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function he(e,A,n){t.hasOwnProperty(e)?((void 0===n||void 0!==t[e].L&&void 0!==t[e].L[n])&&re("Cannot register public name '"+e+"' twice"),function(e,A){var n=t;if(void 0===n[e].L){var r=n[e];n[e]=function(){return n[e].L.hasOwnProperty(arguments.length)||re("Function '"+A+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+n[e].L+")!"),n[e].L[arguments.length].apply(this,arguments)},n[e].L=[],n[e].L[r.S]=r}}(e,e),t.hasOwnProperty(n)&&re("Cannot register multiple overloads of a function with the same number of arguments ("+n+")!"),t[e].L[n]=A):(t[e]=A,void 0!==n&&(t[e].ba=n))}function fe(e,A){var n=-1!=(e=X(e)).indexOf("j")?function(e,A){0<=e.indexOf("j")||T("Assertion failed: getDynCaller should only be called with i64 sigs");var n=[];return function(){n.length=arguments.length;for(var r=0;r>1]}:function(e){return B[e>>1]};case 2:return A?function(e){return p[e>>2]}:function(e){return E[e>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var Ee={};function Qe(){if(!ye){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"===typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:a||"./this.program"};for(e in Ee)t[e]=Ee[e];var A=[];for(e in t)A.push(e+"="+t[e]);ye=A}return ye}for(var ye,ve=[null,[],[]],me=Array(256),be=0;256>be;++be)me[be]=String.fromCharCode(be);W=me,ne=t.BindingError=Ae("BindingError"),ie=t.InternalError=Ae("InternalError"),t.count_emval_handles=function(){for(var e=0,t=5;t>i])},M:null})},y:function(e,t){oe(e,{name:t=X(t),fromWireType:function(e){var t=se[e].value;return ge(e),t},toWireType:function(e,t){return ce(t)},argPackAdvance:8,readValueFromPointer:ue,M:null})},h:function(e,t,A){A=K(A),oe(e,{name:t=X(t),fromWireType:function(e){return e},toWireType:function(e,t){if("number"!==typeof t&&"boolean"!==typeof t)throw new TypeError('Cannot convert "'+le(t)+'" to '+this.name);return t},argPackAdvance:8,readValueFromPointer:Ie(t,A),M:null})},e:function(e,A,n,r,i,o){var a=function(e,t){for(var A=[],n=0;n>2)+n]);return A}(A,n);e=X(e),i=fe(r,i),he(e,(function(){!function(e,t){var A=[],n={};throw t.forEach((function e(t){n[t]||z[t]||($[t]?$[t].forEach(e):(A.push(t),n[t]=!0))})),new de(e+": "+A.map(Be).join([", "]))}("Cannot call "+e+" due to unbound types",a)}),A-1),function(e,t){function A(e){if((e=t(e)).length!==n.length)throw new ie("Mismatched type converter count");for(var A=0;Ag&&re("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var c=null!==n[1]&&!1,u=!1,l=1;l>>a}}var s=-1!=t.indexOf("unsigned");oe(e,{name:t,fromWireType:i,toWireType:function(e,A){if("number"!==typeof A&&"boolean"!==typeof A)throw new TypeError('Cannot convert "'+le(A)+'" to '+this.name);if(Ar)throw new TypeError('Passing a number "'+le(A)+'" from JS side to C/C++ side to an argument of type "'+t+'", which is outside the valid range ['+n+", "+r+"]!");return s?A>>>0:0|A},argPackAdvance:8,readValueFromPointer:pe(t,o,0!==n),M:null})},b:function(e,t,A){function n(e){var t=E;return new r(C,t[(e>>=2)+1],t[e])}var r=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];oe(e,{name:A=X(A),fromWireType:n,argPackAdvance:8,readValueFromPointer:n},{U:!0})},i:function(e,t){var A="std::string"===(t=X(t));oe(e,{name:t,fromWireType:function(e){var t=E[e>>2];if(A)for(var n=e+4,r=0;r<=t;++r){var i=e+4+r;if(r==t||0==f[i]){if(n=n?I(f,n,i-n):"",void 0===o)var o=n;else o+=String.fromCharCode(0),o+=n;n=i+1}}else{for(o=Array(t),r=0;r=n&&(n=65536+((1023&n)<<10)|1023&t.charCodeAt(++A)),127>=n?++e:e=2047>=n?e+2:65535>=n?e+3:e+4}return e}:function(){return t.length})(),i=Re(4+r+1);if(E[i>>2]=r,A&&n)!function(e,t,A){var n=f;if(0=i)i=65536+((1023&i)<<10)|1023&e.charCodeAt(++r);if(127>=i){if(t>=A)break;n[t++]=i}else{if(2047>=i){if(t+1>=A)break;n[t++]=192|i>>6}else{if(65535>=i){if(t+2>=A)break;n[t++]=224|i>>12}else{if(t+3>=A)break;n[t++]=240|i>>18,n[t++]=128|i>>12&63}n[t++]=128|i>>6&63}n[t++]=128|63&i}}n[t]=0}}(t,i+4,r+1);else if(n)for(n=0;n>2],i=o(),s=e+4,g=0;g<=r;++g){var c=e+4+g*t;g!=r&&0!=i[c>>a]||(s=n(s,c-s),void 0===A?A=s:(A+=String.fromCharCode(0),A+=s),s=c+t)}return De(e),A},toWireType:function(e,n){"string"!==typeof n&&re("Cannot pass non-string to C++ string type "+A);var o=i(n),s=Re(4+o+t);return E[s>>2]=o>>a,r(n,s+4,o+t),null!==e&&e.push(De,s),s},argPackAdvance:8,readValueFromPointer:ue,M:function(e){De(e)}})},A:function(e,t){oe(e,{aa:!0,name:t=X(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},n:ge,x:function(e){4>>=0;var t=f.length;if(2147483648=A;A*=2){var n=t*(1+.2/A);n=Math.min(n,e+100663296),0<(n=Math.max(16777216,e,n))%65536&&(n+=65536-n%65536);e:{try{c.grow(Math.min(2147483648,n)-C.byteLength+65535>>>16),D(c.buffer);var r=1;break e}catch(i){}r=void 0}if(r)return!0}return!1},u:function(e,t){var A=0;return Qe().forEach((function(n,r){var i=t+A;for(r=p[e+4*r>>2]=i,i=0;i>0]=n.charCodeAt(i);h[r>>0]=0,A+=n.length+1})),0},v:function(e,t){var A=Qe();p[e>>2]=A.length;var n=0;return A.forEach((function(e){n+=e.length+1})),p[t>>2]=n,0},w:function(){return 0},q:function(){},g:function(e,t,A,n){for(var r=0,i=0;i>2],a=p[t+(8*i+4)>>2],c=0;c>2]=r,0},a:c,l:function(){return 0},k:function(){return 0},j:function(){},B:function(){return 6},m:function(){},f:function(){}};!function(){function e(e){t.asm=e.exports,k=t.asm.D,O--,t.monitorRunDependencies&&t.monitorRunDependencies(O),0==O&&L&&(e=L,L=null,e())}function A(t){e(t.instance)}function r(e){return Promise.resolve().then(j).then((function(e){return WebAssembly.instantiate(e,i)})).then(e,(function(e){g("failed to asynchronously prepare wasm: "+e),T(e)}))}var i={a:we};if(O++,t.monitorRunDependencies&&t.monitorRunDependencies(O),t.instantiateWasm)try{return t.instantiateWasm(i,e)}catch(a){return g("Module.instantiateWasm callback failed with error: "+a),!1}(o||"function"!==typeof WebAssembly.instantiateStreaming||H()||Z("file://")||"function"!==typeof fetch?r(A):fetch(Y,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,i).then(A,(function(e){return g("wasm streaming compile failed: "+e),g("falling back to ArrayBuffer instantiation"),r(A)}))}))).catch(n)}();var Se,Fe=t.___wasm_call_ctors=function(){return(Fe=t.___wasm_call_ctors=t.asm.E).apply(null,arguments)},Re=t._malloc=function(){return(Re=t._malloc=t.asm.F).apply(null,arguments)},De=t._free=function(){return(De=t._free=t.asm.G).apply(null,arguments)},Ge=t.___getTypeName=function(){return(Ge=t.___getTypeName=t.asm.H).apply(null,arguments)};function ke(){function e(){if(!Se&&(Se=!0,t.calledRun=!0,!u)){if(P(N),P(U),A(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();_.unshift(e)}P(_)}}if(!(00&&void 0!==arguments[0]?arguments[0]:5,A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"lz4",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eA.SHUFFLE,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(Object(s.a)(this,e),t<0||t>9)throw new Error("Invalid compression level: '".concat(t,"'. It should be between 0 and 9"));if(!rA.has(A))throw new Error("Invalid compressor '".concat(A,"'. Valid compressors include\n 'blosclz', 'lz4', 'lz4hc','snappy', 'zlib', 'zstd'."));if(n<-1||n>2)throw new Error("Invalid shuffle ".concat(n,". Must be one of 0 (NOSHUFFLE),\n 1 (SHUFFLE), 2 (BITSHUFFLE), -1 (AUTOSHUFFLE)."));this.blocksize=r,this.clevel=t,this.cname=A,this.shuffle=n}return Object(g.a)(e,[{key:"encode",value:function(){var e=Object(a.a)(o.a.mark((function e(t){var A,n,r;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return nA||(nA=$t(tA,AA)),e.next=3,nA;case 3:return A=e.sent,n=A.compress(t,this.cname,this.clevel,this.shuffle,this.blocksize),r=new Uint8Array(n),A.free_result(),e.abrupt("return",r);case 8:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"decode",value:function(){var e=Object(a.a)(o.a.mark((function e(t,A){var n,r,i;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return nA||(nA=$t(tA,AA)),e.next=3,nA;case 3:if(n=e.sent,r=n.decompress(t),i=new Uint8Array(r),n.free_result(),void 0===A){e.next=10;break}return A.set(i),e.abrupt("return",A);case 10:return e.abrupt("return",i);case 11:case"end":return e.stop()}}),e)})));return function(t,A){return e.apply(this,arguments)}}()}],[{key:"fromConfig",value:function(t){var A=t.blocksize;return new e(t.clevel,t.cname,t.shuffle,A)}}]),e}();iA.codecId="blosc",iA.COMPRESSORS=Object(r.a)(rA),iA.NOSHUFFLE=eA.NOSHUFFLE,iA.SHUFFLE=eA.SHUFFLE,iA.BITSHUFFLE=eA.BITSHUFFLE,iA.AUTOSHUFFLE=eA.AUTOSHUFFLE,Object(c.b)(qt.codecId,(function(){return qt})),Object(c.b)(Xt.codecId,(function(){return Xt})),Object(c.b)(iA.codecId,(function(){return iA}))}).call(this,A(90),A(188).Buffer)},,,,,,,,function(e,t,A){var n=A(344),r=A(759),i=A(760),o=A(761),a=A(762),s=A(763);function g(e){var t=this.__data__=new n(e);this.size=t.size}g.prototype.clear=r,g.prototype.delete=i,g.prototype.get=o,g.prototype.has=a,g.prototype.set=s,e.exports=g},function(e,t,A){var n=A(754),r=A(755),i=A(756),o=A(757),a=A(758);function s(e){var t=-1,A=null==e?0:e.length;for(this.clear();++t0&&void 0!==arguments[0]?arguments[0]:{},A=t.phi,n=void 0===A?0:A,i=t.theta,o=void 0===i?0:i,a=t.radius,s=void 0===a?1:a,g=t.bearing,c=void 0===g?void 0:g,u=t.pitch,l=void 0===u?void 0:u,I=t.altitude,C=void 0===I?void 0:I,h=t.radiusScale,f=void 0===h?6371e3:h;Object(r.a)(this,e),this.phi=n,this.theta=o,this.radius=s||C||1,this.radiusScale=f||1,void 0!==c&&(this.bearing=c),void 0!==l&&(this.pitch=l),this.check()}return Object(i.a)(e,[{key:"toString",value:function(){return this.formatString(o.f)}},{key:"formatString",value:function(e){var t=e.printTypes,A=void 0!==t&&t,n=o.l;return"".concat(A?"Spherical":"","[rho:").concat(n(this.radius),",theta:").concat(n(this.theta),",phi:").concat(n(this.phi),"]")}},{key:"equals",value:function(e){return Object(o.j)(this.radius,e.radius)&&Object(o.j)(this.theta,e.theta)&&Object(o.j)(this.phi,e.phi)}},{key:"exactEquals",value:function(e){return this.radius===e.radius&&this.theta===e.theta&&this.phi===e.phi}},{key:"set",value:function(e,t,A){return this.radius=e,this.phi=t,this.theta=A,this.check()}},{key:"clone",value:function(){return(new e).copy(this)}},{key:"copy",value:function(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this.check()}},{key:"fromLngLatZ",value:function(e){var t=Object(n.a)(e,3),A=t[0],r=t[1],i=t[2];this.radius=1+i/this.radiusScale,this.phi=Object(o.o)(r),this.theta=Object(o.o)(A)}},{key:"fromVector3",value:function(e){return this.radius=s.g(e),this.radius>0&&(this.theta=Math.atan2(e[0],e[1]),this.phi=Math.acos(Object(o.d)(e[2]/this.radius,-1,1))),this.check()}},{key:"toVector3",value:function(){return new a.a(0,0,this.radius).rotateX({radians:this.theta}).rotateZ({radians:this.phi})}},{key:"makeSafe",value:function(){return this.phi=Math.max(1e-6,Math.min(Math.PI-1e-6,this.phi)),this}},{key:"check",value:function(){if(!Number.isFinite(this.phi)||!Number.isFinite(this.theta)||!(this.radius>0))throw new Error("SphericalCoordinates: some fields set to invalid numbers");return this}},{key:"bearing",get:function(){return 180-Object(o.i)(this.phi)},set:function(e){this.phi=Math.PI-Object(o.o)(e)}},{key:"pitch",get:function(){return Object(o.i)(this.theta)},set:function(e){this.theta=Object(o.o)(e)}},{key:"longitude",get:function(){return Object(o.i)(this.phi)}},{key:"latitude",get:function(){return Object(o.i)(this.theta)}},{key:"lng",get:function(){return Object(o.i)(this.phi)}},{key:"lat",get:function(){return Object(o.i)(this.theta)}},{key:"z",get:function(){return(this.radius-1)*this.radiusScale}}]),e}()},function(e,t,A){"use strict";A.d(t,"a",(function(){return s}));var n=A(1),r=A(4),i=A(286),o=A(221),a=A(197),s=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},A=t.x,r=void 0===A?0:A,i=t.y,s=void 0===i?0:i,g=t.z,c=void 0===g?0:g,u=t.roll,l=void 0===u?0:u,I=t.pitch,C=void 0===I?0:I,h=t.yaw,f=void 0===h?0:h,d=t.position,B=void 0===d?void 0:d,p=t.orientation,E=void 0===p?void 0:p;Object(n.a)(this,e),Array.isArray(B)&&3===B.length?this.position=new o.a(B):this.position=new o.a(r,s,c),Array.isArray(E)&&4===E.length?this.orientation=new a.a(E,E[3]):this.orientation=new a.a(l,C,f,a.a.RollPitchYaw)}return Object(r.a)(e,[{key:"getPosition",value:function(){return this.position}},{key:"getOrientation",value:function(){return this.orientation}},{key:"equals",value:function(e){return!!e&&(this.position.equals(e.position)&&this.orientation.equals(e.orientation))}},{key:"exactEquals",value:function(e){return!!e&&(this.position.exactEquals(e.position)&&this.orientation.exactEquals(e.orientation))}},{key:"getTransformationMatrix",value:function(){var e=Math.sin(this.roll),t=Math.sin(this.pitch),A=Math.sin(this.yaw),n=Math.cos(this.roll),r=Math.cos(this.pitch),o=Math.cos(this.yaw);return(new i.a).setRowMajor(o*r,-A*n+o*t*e,A*e+o*t*n,this.x,A*r,o*n+A*t*e,-o*e+A*t*n,this.y,-t,r*e,r*n,this.z,0,0,0,1)}},{key:"getTransformationMatrixFromPose",value:function(e){return(new i.a).multiplyRight(this.getTransformationMatrix()).multiplyRight(e.getTransformationMatrix().invert())}},{key:"getTransformationMatrixToPose",value:function(e){return(new i.a).multiplyRight(e.getTransformationMatrix()).multiplyRight(this.getTransformationMatrix().invert())}},{key:"x",get:function(){return this.position.x},set:function(e){this.position.x=e}},{key:"y",get:function(){return this.position.y},set:function(e){this.position.y=e}},{key:"z",get:function(){return this.position.z},set:function(e){this.position.z=e}},{key:"roll",get:function(){return this.orientation.roll},set:function(e){this.orientation.roll=e}},{key:"pitch",get:function(){return this.orientation.pitch},set:function(e){this.orientation.pitch=e}},{key:"yaw",get:function(){return this.orientation.yaw},set:function(e){this.orientation.yaw=e}}]),e}()},function(e,t,A){"use strict";var n=A(172),r=A(172).buildOptions,i=A(856),o=A(857);"<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)".replace(/NAME/g,n.nameRegexp);!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var a={attributeNamePrefix:"@_",attrNodeName:!1,textNodeName:"#text",ignoreAttributes:!0,ignoreNameSpace:!1,allowBooleanAttributes:!1,parseNodeValue:!0,parseAttributeValue:!1,arrayMode:!1,trimValues:!0,cdataTagName:!1,cdataPositionChar:"\\c",numParseOptions:{hex:!0,leadingZeros:!0},tagValueProcessor:function(e,t){return e},attrValueProcessor:function(e,t){return e},stopNodes:[],alwaysCreateTextNode:!1};t.defaultOptions=a;var s=["attributeNamePrefix","attrNodeName","textNodeName","ignoreAttributes","ignoreNameSpace","allowBooleanAttributes","parseNodeValue","parseAttributeValue","arrayMode","trimValues","cdataTagName","cdataPositionChar","tagValueProcessor","attrValueProcessor","parseTrueNumberOnly","numParseOptions","stopNodes","alwaysCreateTextNode"];function g(e,t,A){return t&&(A.trimValues&&(t=t.trim()),t=u(t=A.tagValueProcessor(t,e),A.parseNodeValue,A.numParseOptions)),t}function c(e,t){if(t.ignoreNameSpace){var A=e.split(":"),n="/"===e.charAt(0)?"/":"";if("xmlns"===A[0])return"";2===A.length&&(e=n+A[1])}return e}function u(e,t,A){if(t&&"string"===typeof e){var r=e.trim();return"true"===r||"false"!==r&&o(e,A)}return n.isExist(e)?e:""}t.props=s;var l=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])(.*?)\\3)?","g");function I(e,t){if(!t.ignoreAttributes&&"string"===typeof e){e=e.replace(/\r?\n/g," ");for(var A=n.getAllMatches(e,l),r=A.length,i={},o=0;o"===i)return{data:n,index:r};"\t"===i&&(i=" ")}n+=i}}function h(e,t,A,n){var r=e.indexOf(t,A);if(-1===r)throw new Error(n);return r+t.length-1}t.getTraversalObj=function(e,t){e=e.replace(/\r\n?/g,"\n"),t=r(t,a,s);for(var A=new i("!xml"),o=A,c="",u=0;u",u,"Closing Tag is not closed."),f=e.substring(u+2,l).trim();if(t.ignoreNameSpace){var d=f.indexOf(":");-1!==d&&(f=f.substr(d+1))}o&&(o.val?o.val=n.getValue(o.val)+""+g(f,c,t):o.val=g(f,c,t)),t.stopNodes.length&&t.stopNodes.includes(o.tagname)&&(o.child=[],void 0==o.attrsMap&&(o.attrsMap={}),o.val=e.substr(o.startIndex+1,u-o.startIndex-1)),o=o.parent,c="",u=l}else if("?"===e[u+1])u=h(e,"?>",u,"Pi Tag is not closed.");else if("!--"===e.substr(u+1,3))u=h(e,"--\x3e",u,"Comment is not closed.");else if("!D"===e.substr(u+1,2)){var B=h(e,">",u,"DOCTYPE is not closed.");u=e.substring(u,B).indexOf("[")>=0?e.indexOf("]>",u)+1:B}else if("!["===e.substr(u+1,2)){var p=h(e,"]]>",u,"CDATA is not closed.")-2,E=e.substring(u+9,p);if(c&&(o.val=n.getValue(o.val)+""+g(o.tagname,c,t),c=""),t.cdataTagName){var Q=new i(t.cdataTagName,o,E);o.addChild(Q),o.val=n.getValue(o.val)+t.cdataPositionChar,E&&(Q.val=E)}else o.val=(o.val||"")+(E||"");u=p+2}else{var y=C(e,u+1),v=y.data,m=y.index,b=v.indexOf(" "),w=v,S=!0;if(-1!==b&&(w=v.substr(0,b).replace(/\s\s*$/,""),v=v.substr(b+1)),t.ignoreNameSpace){var F=w.indexOf(":");-1!==F&&(S=(w=w.substr(F+1))!==y.data.substr(F+1))}if(o&&c&&"!xml"!==o.tagname&&(o.val=n.getValue(o.val)+""+g(o.tagname,c,t)),v.length>0&&v.lastIndexOf("/")===v.length-1){v="/"===w[w.length-1]?w=w.substr(0,w.length-1):v.substr(0,v.length-1);var R=new i(w,o,"");w!==v&&(R.attrsMap=I(v,t)),o.addChild(R)}else{var D=new i(w,o);t.stopNodes.length&&t.stopNodes.includes(D.tagname)&&(D.startIndex=m),w!==v&&S&&(D.attrsMap=I(v,t)),o.addChild(D),o=D}c="",u=m}else c+=e[u]}return A}},function(e,t,A){var n=A(550),r=A(886),i=A(248);e.exports=function(e){return i(e)?n(e,!0):r(e)}},function(e,t){e.exports=function(e){return e}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,A){var n=A(597),r=A(478);e.exports=Object.keys||function(e){return n(e,r)}},function(e,t){e.exports=!0},function(e,t){var A=0,n=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++A+n).toString(36))}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,A){var n=A(353);e.exports=function(e){if("string"==typeof e||n(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}},function(e,t,A){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var r=A(59),i=A(105),o=n(A(620)),a=A(141),s=n(A(619));function g(e,t){var A=i.getCoords(e),n=i.getCoords(t);if(2!==A.length)throw new Error(" line1 must only contain 2 coordinates");if(2!==n.length)throw new Error(" line2 must only contain 2 coordinates");var o=A[0][0],a=A[0][1],s=A[1][0],g=A[1][1],c=n[0][0],u=n[0][1],l=n[1][0],I=n[1][1],C=(I-u)*(s-o)-(l-c)*(g-a),h=(l-c)*(a-u)-(I-u)*(o-c),f=(s-o)*(a-u)-(g-a)*(o-c);if(0===C)return null;var d=h/C,B=f/C;if(d>=0&&d<=1&&B>=0&&B<=1){var p=o+d*(s-o),E=a+d*(g-a);return r.point([p,E])}return null}t.default=function(e,t){var A={},n=[];if("LineString"===e.type&&(e=r.feature(e)),"LineString"===t.type&&(t=r.feature(t)),"Feature"===e.type&&"Feature"===t.type&&null!==e.geometry&&null!==t.geometry&&"LineString"===e.geometry.type&&"LineString"===t.geometry.type&&2===e.geometry.coordinates.length&&2===t.geometry.coordinates.length){var c=g(e,t);return c&&n.push(c),r.featureCollection(n)}var u=s.default();return u.load(o.default(t)),a.featureEach(o.default(e),(function(e){a.featureEach(u.search(e),(function(t){var r=g(e,t);if(r){var o=i.getCoords(r).join(",");A[o]||(A[o]=!0,n.push(r))}}))})),r.featureCollection(n)}},,function(e,t,A){"use strict";A.d(t,"b",(function(){return r})),A.d(t,"a",(function(){return i}));var n=A(227);function r(e,t){return Object(n.a)(e>=0),Object(n.a)(t>0),e+(t-1)&~(t-1)}function i(e,t,A){var n;if(e instanceof ArrayBuffer)n=new Uint8Array(e);else{var i=e.byteOffset,o=e.byteLength;n=new Uint8Array(e.buffer||e.arrayBuffer,i,o)}return t.set(n,A),A+r(n.byteLength,4)}},function(e,t,A){"use strict";A.r(t);var n=A(652);A.d(t,"SimpleMeshLayer",(function(){return n.a}));var r=A(645);A.d(t,"ScenegraphLayer",(function(){return r.a}))},function(e,t,A){"use strict";function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var A=0,n=new Array(t);A1&&void 0!==arguments[1]?arguments[1]:[255,0,0,255];if(!Array.isArray(e))return t;return[255*e[0],255*e[1],255*e[2],255*e[3]]},t.recursivelyTraverseNestedArrays=function e(t,A,r){if(!Array.isArray(t[0]))return!0;for(var i=0;i0}},function(e,t,A){var n=A(299),r=A(300),i=Symbol("SemVer ANY"),o=function(){"use strict";function e(t,A){if(n(this,e),A=a(A),t instanceof e){if(t.loose===!!A.loose)return t;t=t.value}l("comparator",t,A),this.options=A,this.loose=!!A.loose,this.parse(t),this.semver===i?this.value="":this.value=this.operator+this.semver.version,l("comp",this)}return r(e,null,[{key:"ANY",get:function(){return i}}]),r(e,[{key:"parse",value:function(e){var t=this.options.loose?g[c.COMPARATORLOOSE]:g[c.COMPARATOR],A=e.match(t);if(!A)throw new TypeError("Invalid comparator: ".concat(e));this.operator=void 0!==A[1]?A[1]:"","="===this.operator&&(this.operator=""),A[2]?this.semver=new I(A[2],this.options.loose):this.semver=i}},{key:"toString",value:function(){return this.value}},{key:"test",value:function(e){if(l("Comparator.test",e,this.options.loose),this.semver===i||e===i)return!0;if("string"===typeof e)try{e=new I(e,this.options)}catch(t){return!1}return u(e,this.operator,this.semver,this.options)}},{key:"intersects",value:function(t,A){if(!(t instanceof e))throw new TypeError("a Comparator is required");if(A&&"object"===typeof A||(A={loose:!!A,includePrerelease:!1}),""===this.operator)return""===this.value||new C(t.value,A).test(this.value);if(""===t.operator)return""===t.value||new C(this.value,A).test(t.semver);var n=(">="===this.operator||">"===this.operator)&&(">="===t.operator||">"===t.operator),r=("<="===this.operator||"<"===this.operator)&&("<="===t.operator||"<"===t.operator),i=this.semver.version===t.semver.version,o=(">="===this.operator||"<="===this.operator)&&(">="===t.operator||"<="===t.operator),a=u(this.semver,"<",t.semver,A)&&(">="===this.operator||">"===this.operator)&&("<="===t.operator||"<"===t.operator),s=u(this.semver,">",t.semver,A)&&("<="===this.operator||"<"===this.operator)&&(">="===t.operator||">"===t.operator);return n||r||i&&o||a||s}}]),e}();e.exports=o;var a=A(372),s=A(260),g=s.re,c=s.t,u=A(641),l=A(371),I=A(106),C=A(145)},function(e,t,A){var n=A(145);e.exports=function(e,t,A){try{t=new n(t,A)}catch(r){return!1}return t.test(e)}},function(e,t,A){"use strict";A.r(t);var n=A(283),r=A.n(n);function i(e,t,A){void 0===A&&(A={});var n={type:"Feature"};return(0===A.id||A.id)&&(n.id=A.id),A.bbox&&(n.bbox=A.bbox),n.properties=t||{},n.geometry=e,n}function o(e,t,A){void 0===A&&(A={});for(var n=0,r=e;n=0&&A.modules.splice(r,1)}if("inject"in t)if(e.inject){var i=Object(n.a)({},e.inject);for(var o in t.inject)i[o]=(i[o]||"")+t.inject[o];A.inject=i}else A.inject=t.inject;return A}},function(e,t,A){"use strict";A.d(t,"a",(function(){return n}));function n(e){if(null===(t=e)||"object"!==typeof t)throw new Error("count(): argument not an object");var t;if("function"===typeof e.count)return e.count();if(Number.isFinite(e.size))return e.size;if(Number.isFinite(e.length))return e.length;if(function(e){return null!==e&&"object"===typeof e&&e.constructor===Object}(e))return Object.keys(e).length;throw new Error("count(): argument not a container")}},function(e,t,A){"use strict";A.d(t,"a",(function(){return u}));var n=A(8),r=A(1),i=A(4),o=A(9),a=A(10),s=A(23),g=A(133),c=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(e){var n;return Object(r.a)(this,A),(n=t.call(this,e)).zoomAxis=e.zoomAxis||"all",n}return Object(i.a)(A,[{key:"_applyConstraints",value:function(e){var t=e.maxZoom,A=e.minZoom,n=e.zoom;return e.zoom=Array.isArray(n)?[Object(s.clamp)(n[0],A,t),Object(s.clamp)(n[1],A,t)]:Object(s.clamp)(n,A,t),e}},{key:"_calculateNewZoom",value:function(e){var t=e.scale,A=e.startZoom,r=this._viewportProps,i=r.maxZoom,o=r.minZoom;A||0===A||(A=this._viewportProps.zoom);var a=Math.log2(t);if(Array.isArray(A)){var g=A,c=Object(n.a)(g,2),u=c[0],l=c[1];switch(this.zoomAxis){case"X":u=Object(s.clamp)(u+a,o,i);break;case"Y":l=Object(s.clamp)(l+a,o,i);break;default:var I=Math.min(u+a,l+a);Ii&&(a+=i-I),u+=a,l+=a}return[u,l]}return Object(s.clamp)(A+a,o,i)}}]),A}(A(264).a),u=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(e){return Object(r.a)(this,A),e.dragMode=e.dragMode||"pan",t.call(this,c,e)}return Object(i.a)(A,[{key:"_onPanRotate",value:function(e){return!1}},{key:"linearTransitionProps",get:function(){return["target","zoom"]}}]),A}(g.a)},function(e,t,A){"use strict";A.d(t,"a",(function(){return u}));var n=A(7),r=A(1),i=A(4),o=A(9),a=A(10),s=A(134),g=A(263),c=A(266),u=function(e){Object(o.a)(A,e);var t=Object(a.a)(A);function A(e){return Object(r.a)(this,A),t.call(this,Object(n.a)({},e,{type:g.a}))}return Object(i.a)(A,[{key:"controller",get:function(){return this._getControllerProps({type:c.b})}}]),A}(s.a);u.displayName="MapView"},function(e,t,A){"use strict";A.d(t,"a",(function(){return a}));var n=A(6),r=A(528),i=[A(223).a],o=["vs:DECKGL_FILTER_SIZE(inout vec3 size, VertexGeometry geometry)","vs:DECKGL_FILTER_GL_POSITION(inout vec4 position, VertexGeometry geometry)","vs:DECKGL_FILTER_COLOR(inout vec4 color, VertexGeometry geometry)","fs:DECKGL_FILTER_COLOR(inout vec4 color, FragmentGeometry geometry)"];function a(e){var t,A=r.a.getDefaultProgramManager(e),a=Object(n.a)(i);try{for(a.s();!(t=a.n()).done;){var s=t.value;A.addDefaultModule(s)}}catch(l){a.e(l)}finally{a.f()}var g,c=Object(n.a)(o);try{for(c.s();!(g=c.n()).done;){var u=g.value;A.addShaderHook(u)}}catch(l){c.e(l)}finally{c.f()}return A}},function(e,t,A){"use strict";A.d(t,"a",(function(){return o}));var n=A(1),r=[255,255,255],i=0,o=function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(n.a)(this,e);var A=t.color,o=void 0===A?r:A,a=t.intensity,s=void 0===a?1:a;this.id=t.id||"ambient-".concat(i++),this.color=o,this.intensity=s,this.type="ambient"}},function(e,t,A){"use strict";var n=A(6),r=A(8),i=A(1),o=A(4),a=A(9),s=A(10),g=A(7),c=A(36),u=A(385),l=A(104),I=A(23),C=A(162),h=function(e){Object(a.a)(A,e);var t=Object(s.a)(A);function A(){return Object(i.a)(this,A),t.apply(this,arguments)}return Object(o.a)(A,[{key:"_onUpdate",value:function(){var e=this.time,t=this.settings,A=t.fromValue,n=t.toValue,r=t.duration,i=(0,t.easing)(e/r);this._value=Object(I.lerp)(A,n,i)}},{key:"value",get:function(){return this._value}}]),A}(C.a);function f(e,t,A,n,r){var i=t-e;return(A-t)*r+-i*n+i+t}function d(e,t){if(Array.isArray(e)){for(var A=0,n=0;n0}}]),e}(),v=A(313),m=A(379),b=A(77),w=A(18),S=A(87),F=A(173),R=A(378),D=A(324),G=A(150),k=A(78),x=A(116),N=A(2),U=A(232),_=(B={},Object(N.a)(B,10241,9987),Object(N.a)(B,10240,9729),Object(N.a)(B,10242,33071),Object(N.a)(B,10243,33071),B),M={};var O={boolean:{validate:function(e,t){return!0},equal:function(e,t,A){return Boolean(e)===Boolean(t)}},number:{validate:function(e,t){return Number.isFinite(e)&&(!("max"in t)||e<=t.max)&&(!("min"in t)||e>=t.min)}},color:{validate:function(e,t){return t.optional&&!e||H(e)&&(3===e.length||4===e.length)},equal:function(e,t,A){return L(e,t)}},accessor:{validate:function(e,t){var A=Y(e);return"function"===A||A===Y(t.value)},equal:function(e,t,A){return"function"===typeof t||L(e,t)}},array:{validate:function(e,t){return t.optional&&!e||H(e)},equal:function(e,t,A){return A.compare?L(e,t):e===t}},function:{validate:function(e,t){return t.optional&&!e||"function"===typeof e},equal:function(e,t,A){return!A.compare||e===t}},data:{transform:function(e,t,A){var n=(A?A.props:{}).dataTransform;return n&&e?n(e):e}},image:{transform:function(e,t,A){return function(e,t){var A=e.context&&e.context.gl;if(!A||!t)return null;if(t instanceof U.a)return t;t.constructor&&"Object"!==t.constructor.name&&(t={data:t});var n=null;t.compressed&&(n=Object(N.a)({},10241,t.data.length>1?9985:9729));var r=new U.a(A,Object(g.a)({},t,{parameters:Object(g.a)({},_,{},n,{},e.props.textureParameters)}));return M[r.id]=!0,r}(A,e)},release:function(e){var t;(t=e)&&t instanceof U.a&&M[t.id]&&(t.delete(),delete M[t.id])}}};function L(e,t){if(e===t)return!0;if(!H(e)||!H(t))return!1;var A=e.length;if(A!==t.length)return!1;for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:null;Object(i.a)(this,e),this.component=t,this.asyncProps={},this.onAsyncPropUpdated=function(){},this.oldProps=oe,this.oldAsyncProps=null}return Object(o.a)(e,[{key:"finalize",value:function(){for(var e in this.asyncProps){var t=this.asyncProps[e];t.type&&t.type.release&&t.type.release(t.resolvedValue,t.type,this.component)}}},{key:"getOldProps",value:function(){return this.oldAsyncProps||this.oldProps}},{key:"resetOldProps",value:function(){this.oldAsyncProps=null,this.oldProps=this.component.props}},{key:"freezeAsyncOldProps",value:function(){if(!this.oldAsyncProps)for(var e in this.oldProps=this.oldProps||this.component.props,this.oldAsyncProps=Object.create(this.oldProps),this.asyncProps)Object.defineProperty(this.oldAsyncProps,e,{enumerable:!0,value:this.oldProps[e]})}},{key:"hasAsyncProp",value:function(e){return e in this.asyncProps}},{key:"getAsyncProp",value:function(e){var t=this.asyncProps[e];return t&&t.resolvedValue}},{key:"isAsyncPropLoading",value:function(e){if(e){var t=this.asyncProps[e];return Boolean(t&&t.pendingLoadCount>0&&t.pendingLoadCount!==t.resolvedLoadCount)}for(var A in this.asyncProps)if(this.isAsyncPropLoading(A))return!0;return!1}},{key:"reloadAsyncProp",value:function(e,t){this._watchPromise(e,Promise.resolve(t))}},{key:"setAsyncProps",value:function(e){var t=e[re]||{},A=e[ne]||e,n=e[ie]||{};for(var r in t){var i=t[r];this._createAsyncPropData(r,n[r]),this._updateAsyncProp(r,i),t[r]=this.getAsyncProp(r)}for(var o in A){var a=A[o];this._createAsyncPropData(o,n[o]),this._updateAsyncProp(o,a)}}},{key:"_updateAsyncProp",value:function(e,t){if(this._didAsyncInputValueChange(e,t)){if("string"===typeof t){var A,n=null===(A=this.layer)||void 0===A?void 0:A.props.fetch;n&&(t=n(t,{propName:e,layer:this.layer}))}t instanceof Promise?this._watchPromise(e,t):Object(x.c)(t)?this._resolveAsyncIterable(e,t):this._setPropValue(e,t)}}},{key:"_didAsyncInputValueChange",value:function(e,t){var A=this.asyncProps[e];return t!==A.resolvedValue&&t!==A.lastValue&&(A.lastValue=t,!0)}},{key:"_setPropValue",value:function(e,t){this.freezeAsyncOldProps();var A=this.asyncProps[e];t=this._postProcessValue(A,t),A.resolvedValue=t,A.pendingLoadCount++,A.resolvedLoadCount=A.pendingLoadCount}},{key:"_setAsyncPropValue",value:function(e,t,A){var n=this.asyncProps[e];n&&A>=n.resolvedLoadCount&&void 0!==t&&(this.freezeAsyncOldProps(),n.resolvedValue=t,n.resolvedLoadCount=A,this.onAsyncPropUpdated(e,t))}},{key:"_watchPromise",value:function(e,t){var A=this,n=this.asyncProps[e];n.pendingLoadCount++;var r=n.pendingLoadCount;t.then((function(t){var i;t=A._postProcessValue(n,t),A._setAsyncPropValue(e,t,r);var o=null===(i=A.layer)||void 0===i?void 0:i.props.onDataLoad;"data"===e&&o&&o(t,{propName:e,layer:A.layer})})).catch((function(t){var n;null===(n=A.layer)||void 0===n||n.raiseError(t,"loading ".concat(e," of ").concat(A.layer))}))}},{key:"_resolveAsyncIterable",value:function(){var e=Object(te.a)(ee.a.mark((function e(t,A){var n,r,i,o,a,s,g,c,u,l,I,C,h,f,d;return ee.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:"data"!==t&&this._setPropValue(t,A),(r=this.asyncProps[t]).pendingLoadCount++,i=r.pendingLoadCount,o=[],a=0,s=!0,g=!1,e.prev=8,u=Object(Ae.a)(A);case 10:return e.next=12,u.next();case 12:return l=e.sent,s=l.done,e.next=16,l.value;case 16:if(I=e.sent,s){e.next=27;break}C=I,h=this.component?this.component.props:{},f=h.dataTransform,o=f?f(C,o):o.concat(C),Object.defineProperty(o,"__diff",{enumerable:!1,value:[{startRow:a,endRow:o.length}]}),a=o.length,this._setAsyncPropValue(t,o,i);case 24:s=!0,e.next=10;break;case 27:e.next=33;break;case 29:e.prev=29,e.t0=e.catch(8),g=!0,c=e.t0;case 33:if(e.prev=33,e.prev=34,s||null==u.return){e.next=38;break}return e.next=38,u.return();case 38:if(e.prev=38,!g){e.next=41;break}throw c;case 41:return e.finish(38);case 42:return e.finish(33);case 43:(d=null===(n=this.layer)||void 0===n?void 0:n.props.onDataLoad)&&d(o,{propName:t,layer:this.layer});case 45:case"end":return e.stop()}}),e,this,[[8,29,33,43],[34,,38,42]])})));return function(t,A){return e.apply(this,arguments)}}()},{key:"_postProcessValue",value:function(e,t){var A=e.type;return A&&(A.release&&A.release(e.resolvedValue,A,this.component),A.transform)?A.transform(t,A,this.component):t}},{key:"_createAsyncPropData",value:function(e,t){if(!this.asyncProps[e]){var A=this.component&&this.component.constructor._propTypes;this.asyncProps[e]={type:A&&A[e],lastValue:null,resolvedValue:t,pendingLoadCount:0,resolvedLoadCount:0}}}}]),e}(),se=k.b.ASYNC_ORIGINAL,ge=k.b.ASYNC_RESOLVED,ce=k.b.ASYNC_DEFAULTS,ue=0,le=function(){function e(){Object(i.a)(this,e),this.props=K.apply(this,arguments),this.id=this.props.id,this.count=ue++,this.lifecycle=k.a.NO_STATE,this.parent=null,this.context=null,this.state=null,this.internalState=null,Object.seal(this)}return Object(o.a)(e,[{key:"clone",value:function(e){var t=this.props,A={};for(var n in t[ce])n in t[ge]?A[n]=t[ge][n]:n in t[se]&&(A[n]=t[se][n]);return new this.constructor(Object(g.a)({},t,{},A,{},e))}},{key:"_initState",value:function(){this.internalState=new ae({})}},{key:"root",get:function(){for(var e=this;e.parent;)e=e.parent;return e}},{key:"stats",get:function(){return this.internalState.stats}}]),e}();le.componentName="Component",le.defaultProps={};var Ie=function(e){Object(a.a)(A,e);var t=Object(s.a)(A);function A(e){var n,r=e.attributeManager,o=e.layer;return Object(i.a)(this,A),(n=t.call(this,o)).attributeManager=r,n.model=null,n.needsRedraw=!0,n.subLayers=null,n.usesPickingColorCache=!1,n}return Object(o.a)(A,[{key:"layer",get:function(){return this.component},set:function(e){this.component=e}}]),A}(ae),Ce=A(42),he=A(1283);A.d(t,"a",(function(){return Qe}));var fe=Math.pow(2,24)-1,de=Object.freeze([]),Be=Object(F.a)((function(e){var t=e.oldViewport,A=e.viewport;return t.equals(A)})),pe=new Uint8ClampedArray(0),Ee={data:{type:"data",value:de,async:!0},dataComparator:null,_dataDiff:{type:"function",value:function(e){return e&&e.__diff},compare:!1,optional:!0},dataTransform:{type:"function",value:null,compare:!1,optional:!0},onDataLoad:{type:"function",value:null,compare:!1,optional:!0},onError:{type:"function",value:null,compare:!1,optional:!0},fetch:{type:"function",value:function(e,t){var A,n=t.propName,r=t.layer,i=t.loaders,o=t.loadOptions,a=t.signal,s=r.context.resourceManager;(o=o||r.getLoadOptions(),i=i||r.props.loaders,a)&&(o=Object(g.a)({},o,{fetch:Object(g.a)({},null===(A=o)||void 0===A?void 0:A.fetch,{signal:a})}));var c=s.contains(e);return c||o||(s.add({resourceId:e,data:Object(he.a)(e,i),persistent:!1}),c=!0),c?s.subscribe({resourceId:e,onChange:function(e){return r.internalState.reloadAsyncProp(n,e)},consumerId:r.id,requestId:n}):Object(he.a)(e,i,o)},compare:!1},updateTriggers:{},visible:!0,pickable:!1,opacity:{type:"number",min:0,max:1,value:1},onHover:{type:"function",value:null,compare:!1,optional:!0},onClick:{type:"function",value:null,compare:!1,optional:!0},onDragStart:{type:"function",value:null,compare:!1,optional:!0},onDrag:{type:"function",value:null,compare:!1,optional:!0},onDragEnd:{type:"function",value:null,compare:!1,optional:!0},coordinateSystem:c.a.DEFAULT,coordinateOrigin:{type:"array",value:[0,0,0],compare:!0},modelMatrix:{type:"array",value:null,compare:!0,optional:!0},wrapLongitude:!1,positionFormat:"XYZ",colorFormat:"RGBA",parameters:{},transitions:null,extensions:[],loaders:{type:"array",value:[],optional:!0,compare:!0},getPolygonOffset:{type:"function",value:function(e){return[0,100*-e.layerIndex]},compare:!1},highlightedObjectIndex:-1,autoHighlight:!1,highlightColor:{type:"accessor",value:[0,0,128,128]}},Qe=function(e){Object(a.a)(A,e);var t=Object(s.a)(A);function A(){return Object(i.a)(this,A),t.apply(this,arguments)}return Object(o.a)(A,[{key:"toString",value:function(){var e=this.constructor.layerName||this.constructor.name;return"".concat(e,"({id: '").concat(this.props.id,"'})")}},{key:"raiseError",value:function(e,t){var A,n,r,i;(t&&(e.message="".concat(t,": ").concat(e.message)),null===(A=(n=this.props).onError)||void 0===A?void 0:A.call(n,e))||(null===(r=this.context)||void 0===r||null===(i=r.onError)||void 0===i||i.call(r,e,this))}},{key:"setState",value:function(e){this.setChangeFlags({stateChanged:!0}),Object.assign(this.state,e),this.setNeedsRedraw()}},{key:"setNeedsRedraw",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.internalState&&(this.internalState.needsRedraw=e)}},{key:"setNeedsUpdate",value:function(){this.context.layerManager.setNeedsUpdate(String(this)),this.internalState.needsUpdate=!0}},{key:"getNeedsRedraw",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{clearRedrawFlags:!1};return this._getNeedsRedraw(e)}},{key:"needsUpdate",value:function(){return this.internalState.needsUpdate||this.hasUniformTransition()||this.shouldUpdateState(this._getUpdateParams())}},{key:"hasUniformTransition",value:function(){return this.internalState.uniformTransitions.active}},{key:"isPickable",value:function(){return this.props.pickable&&this.props.visible}},{key:"getModels",value:function(){return this.state&&(this.state.models||(this.state.model?[this.state.model]:[]))}},{key:"getAttributeManager",value:function(){return this.internalState&&this.internalState.attributeManager}},{key:"getCurrentLayer",value:function(){return this.internalState&&this.internalState.layer}},{key:"getLoadOptions",value:function(){return this.props.loadOptions}},{key:"project",value:function(e){var t=this.context.viewport,A=Object(D.a)(e,{viewport:t,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem}),n=Object(Ce.s)(A,t.pixelProjectionMatrix),i=Object(r.a)(n,3),o=i[0],a=i[1],s=i[2];return 2===e.length?[o,a]:[o,a,s]}},{key:"unproject",value:function(e){return this.context.viewport.unproject(e)}},{key:"projectPosition",value:function(e){return Object(D.b)(e,{viewport:this.context.viewport,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem})}},{key:"use64bitPositions",value:function(){var e=this.props.coordinateSystem;return e===c.a.DEFAULT||e===c.a.LNGLAT||e===c.a.CARTESIAN}},{key:"onHover",value:function(e,t){return!!this.props.onHover&&this.props.onHover(e,t)}},{key:"onClick",value:function(e,t){return!!this.props.onClick&&this.props.onClick(e,t)}},{key:"nullPickingColor",value:function(){return[0,0,0]}},{key:"encodePickingColor",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return t[0]=e+1&255,t[1]=e+1>>8&255,t[2]=e+1>>8>>8&255,t}},{key:"decodePickingColor",value:function(e){Object(S.a)(e instanceof Uint8Array);var t=Object(r.a)(e,3);return t[0]+256*t[1]+65536*t[2]-1}},{key:"initializeState",value:function(){throw new Error("Layer ".concat(this," has not defined initializeState"))}},{key:"getShaders",value:function(e){var t,A=Object(n.a)(this.props.extensions);try{for(A.s();!(t=A.n()).done;){var r=t.value;e=Object(R.a)(e,r.getShaders.call(this,r))}}catch(i){A.e(i)}finally{A.f()}return e}},{key:"shouldUpdateState",value:function(e){e.oldProps,e.props,e.context;return e.changeFlags.propsOrDataChanged}},{key:"updateState",value:function(e){var t=e.oldProps,A=e.props,r=(e.context,e.changeFlags),i=this.getAttributeManager();if(r.dataChanged&&i){var o=r.dataChanged;if(Array.isArray(o)){var a,s=Object(n.a)(o);try{for(s.s();!(a=s.n()).done;){var g=a.value;i.invalidateAll(g)}}catch(f){s.e(f)}finally{s.f()}}else i.invalidateAll()}var c=t.highlightedObjectIndex>=0||t.pickable,u=A.highlightedObjectIndex>=0||A.pickable;if(c!==u&&i){var l=i.attributes,I=l.pickingColors,C=l.instancePickingColors,h=I||C;h&&(u&&h.constant&&(h.constant=!1,i.invalidate(h.id)),h.value||u||(h.constant=!0,h.value=[0,0,0]))}}},{key:"finalizeState",value:function(){var e,t=Object(n.a)(this.getModels());try{for(t.s();!(e=t.n()).done;){e.value.delete()}}catch(r){t.e(r)}finally{t.f()}var A=this.getAttributeManager();A&&A.finalize(),this.context.resourceManager.unsubscribe({consumerId:this.id}),this.internalState.uniformTransitions.clear(),this.internalState.finalize()}},{key:"draw",value:function(e){var t,A=Object(n.a)(this.getModels());try{for(A.s();!(t=A.n()).done;){t.value.draw(e)}}catch(r){A.e(r)}finally{A.f()}}},{key:"getPickingInfo",value:function(e){var t=e.info,A=(e.mode,t.index);return A>=0&&Array.isArray(this.props.data)&&(t.object=this.props.data[A]),t}},{key:"activateViewport",value:function(e){var t=this.internalState.viewport;this.internalState.viewport=e,t&&Be({oldViewport:t,viewport:e})||(this.setChangeFlags({viewportChanged:!0}),this.isComposite?this.needsUpdate()&&this.setNeedsUpdate():this._update())}},{key:"invalidateAttribute",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"all",t=(arguments.length>1&&void 0!==arguments[1]&&arguments[1],this.getAttributeManager());t&&("all"===e?t.invalidateAll():t.invalidate(e))}},{key:"updateAttributes",value:function(e){var t,A=Object(n.a)(this.getModels());try{for(A.s();!(t=A.n()).done;){var r=t.value;this._setModelAttributes(r,e)}}catch(i){A.e(i)}finally{A.f()}}},{key:"_updateAttributes",value:function(e){var t=this.getAttributeManager();if(t){var A=this.getNumInstances(e),n=this.getStartIndices(e);t.update({data:e.data,numInstances:A,startIndices:n,props:e,transitions:e.transitions,buffers:e.data.attributes,context:this,ignoreUnknownAttributes:!0});var r=t.getChangedAttributes({clearChangedFlags:!0});this.updateAttributes(r)}}},{key:"_updateAttributeTransition",value:function(){var e=this.getAttributeManager();e&&e.updateTransition()}},{key:"_updateUniformTransition",value:function(){var e=this.internalState.uniformTransitions;if(e.active){var t=e.update(),A=Object.create(this.props);for(var n in t)Object.defineProperty(A,n,{value:t[n]});return A}return this.props}},{key:"calculateInstancePickingColors",value:function(e,t){var A=t.numInstances;if(!e.constant){var n=Math.floor(pe.length/3);if(this.internalState.usesPickingColorCache=!0,nfe&&E.a.warn("Layer has too many data objects. Picking might not be able to distinguish all objects.")(),pe=G.a.allocate(pe,A,{size:3,copy:!0,maxCount:Math.max(A,fe)});for(var r=Math.floor(pe.length/3),i=[],o=n;o=0?this.encodePickingColor(i):null),this.setModuleParameters(a)}}},{key:"_getUpdateParams",value:function(){return{props:this.props,oldProps:this.internalState.getOldProps(),context:this.context,changeFlags:this.internalState.changeFlags}}},{key:"_getNeedsRedraw",value:function(e){if(!this.internalState)return!1;var t=!1;t=t||this.internalState.needsRedraw&&this.id,this.internalState.needsRedraw=this.internalState.needsRedraw&&!e.clearRedrawFlags;var A=this.getAttributeManager(),n=A&&A.getNeedsRedraw(e);return t=t||n}},{key:"_getAttributeManager",value:function(){return new u.a(this.context.gl,{id:this.props.id,stats:this.context.stats,timeline:this.context.timeline})}},{key:"_initState",value:function(){Object(S.a)(!this.internalState&&!this.state),Object(S.a)(isFinite(this.props.coordinateSystem));var e=this._getAttributeManager();e&&e.addInstanced({instancePickingColors:{type:5121,size:3,noAlloc:!0,update:this.calculateInstancePickingColors}}),this.internalState=new Ie({attributeManager:e,layer:this}),this.clearChangeFlags(),this.state={},Object.defineProperty(this.state,"attributeManager",{get:function(){return E.a.deprecated("layer.state.attributeManager","layer.getAttributeManager()"),e}}),this.internalState.layer=this,this.internalState.uniformTransitions=new y(this.context.timeline),this.internalState.onAsyncPropUpdated=this._onAsyncPropUpdated.bind(this),this.internalState.setAsyncProps(this.props)}},{key:"_transferState",value:function(e){Object(b.a)("layer.matched",this,this===e);var t=e.state,A=e.internalState;this!==e&&(this.internalState=A,this.internalState.layer=this,this.state=t,this.internalState.setAsyncProps(this.props),this.diffProps(this.props,this.internalState.getOldProps()))}},{key:"_onAsyncPropUpdated",value:function(){this.diffProps(this.props,this.internalState.getOldProps()),this.setNeedsUpdate()}},{key:"isLoaded",get:function(){return this.internalState&&!this.internalState.isAsyncPropLoading()}},{key:"wrapLongitude",get:function(){return this.props.wrapLongitude}}]),A}(le);Qe.layerName="Layer",Qe.defaultProps=Ee},function(e,t,A){"use strict";var n=A(7),r=A(1),i=A(4),o=A(2),a=A(8),s=A(6),g=A(16),c=A(17),u=A(9),l=A(10),I=A(718),C=A(427),h=A(80),f=function(){function e(t,A){Object(r.a)(this,e),this.opts=A,this.source=t}return Object(i.a)(e,[{key:"getValue",value:function(){var e=this.source.getBuffer(),t=this.getAccessor();if(e)return[e,t];var A=this.source.value,n=t.size,r=A;if(A&&A.length!==n){r=new Float32Array(n);for(var i=t.elementOffset||0,o=0;o0&&void 0!==arguments[0]?arguments[0]:{},t=this.value,A=e.startOffset,n=void 0===A?0:A,r=e.endOffset;this.buffer.subData({data:this.doublePrecision&&t instanceof Float64Array?Object(B.f)(t,{size:this.size,startIndex:n,endIndex:r}):t.subarray(n,r),offset:n*t.BYTES_PER_ELEMENT+this.byteOffset})}},{key:"allocate",value:function(e){var t=e.numInstances,A=e.copy,n=void 0!==A&&A,r=this.state,i=r.allocatedValue,o=d.a.allocate(i,t+1,{size:this.size,type:this.defaultType,copy:n});this.value=o;var a=this.buffer,s=this.byteOffset;return a.byteLength=0;)t[A+o]=Number.isFinite(e[o])?e[o]:r[o]}return t}},{key:"_areValuesEqual",value:function(e,t){if(!e||!t)return!1;for(var A=this.size,n=0;n=t[1])return e;for(var A=[],n=e.length,r=0,i=0;it[1]?A.push(o):t=[Math.min(o[0],t[0]),Math.max(o[1],t[1])]}return A.splice(r,0,t),A}var R=A(104),D=function(e){Object(u.a)(A,e);var t=Object(l.a)(A);function A(e){var n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object(r.a)(this,A),n=t.call(this,e,i);var o=i.transition,a=void 0!==o&&o,s=i.noAlloc,g=void 0!==s&&s,c=i.update,u=void 0===c?null:c,l=i.accessor,I=void 0===l?null:l,C=i.transform,h=void 0===C?null:C,f=i.startIndices,d=void 0===f?null:f;return Object.assign(n.settings,{transition:a,noAlloc:g,update:u||I&&n._autoUpdater,accessor:I,transform:h}),Object.assign(n.state,{lastExternalBuffer:null,binaryValue:null,binaryAccessor:null,needsUpdate:!0,needsRedraw:!1,updateRanges:S,startIndices:d}),Object.seal(n.settings),Object.seal(n.state),n._validateAttributeUpdaters(),n}return Object(i.a)(A,[{key:"needsUpdate",value:function(){return this.state.needsUpdate}},{key:"needsRedraw",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.clearChangedFlags,A=void 0!==t&&t,n=this.state.needsRedraw;return this.state.needsRedraw=n&&!A,n}},{key:"getUpdateTriggers",value:function(){var e=this.settings.accessor;return[this.id].concat("function"!==typeof e&&e||[])}},{key:"supportsTransition",value:function(){return Boolean(this.settings.transition)}},{key:"getTransitionSetting",value:function(e){if(!e||!this.supportsTransition())return null;var t=this.settings.accessor,A=this.settings.transition,n=Array.isArray(t)?e[t.find((function(t){return e[t]}))]:e[t];return Object(R.e)(n,A)}},{key:"setNeedsUpdate",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.id,t=arguments.length>1?arguments[1]:void 0;if(this.state.needsUpdate=this.state.needsUpdate||e,this.setNeedsRedraw(e),t){var A=t.startRow,n=void 0===A?0:A,r=t.endRow,i=void 0===r?1/0:r;this.state.updateRanges=F(this.state.updateRanges,[n,i])}else this.state.updateRanges=S}},{key:"clearNeedsUpdate",value:function(){this.state.needsUpdate=!1,this.state.updateRanges=w}},{key:"setNeedsRedraw",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.id;this.state.needsRedraw=this.state.needsRedraw||e}},{key:"update",value:function(e){this.setData(e)}},{key:"allocate",value:function(e){var t=this.state,n=this.settings;return!n.noAlloc&&(!!n.update&&(Object(c.a)(Object(g.a)(A.prototype),"allocate",this).call(this,{numInstances:e,copy:t.updateRanges!==S}),!0))}},{key:"updateBuffer",value:function(e){var t=e.numInstances,n=e.data,r=e.props,i=e.context;if(!this.needsUpdate())return!1;var o=this.state.updateRanges,u=this.settings,l=u.update,I=u.noAlloc,C=!0;if(l){var h,f=Object(s.a)(o);try{for(f.s();!(h=f.n()).done;){var d=Object(a.a)(h.value,2),B=d[0],p=d[1];l.call(i,this,{data:n,startRow:B,endRow:p,props:r,numInstances:t})}}catch(S){f.e(S)}finally{f.f()}if(this.value)if(this.constant||this.buffer.byteLength1&&void 0!==arguments[1]?arguments[1]:null,A=this.state,n=this.settings;if(!e)return A.binaryValue=null,A.binaryAccessor=null,!1;if(n.noAlloc)return!1;if(A.binaryValue===e)return this.clearNeedsUpdate(),!0;A.binaryValue=e,this.setNeedsRedraw(),ArrayBuffer.isView(e)&&(e={value:e});var r=n.transform||t!==this.startIndices;if(r){Object(v.a)(ArrayBuffer.isView(e.value),"invalid ".concat(n.accessor));var i=e.size&&e.size!==this.size;return A.binaryAccessor=Object(m.b)(e.value,{size:e.size||this.size,stride:e.stride,offset:e.offset,startIndices:t,nested:i}),!1}return this.clearNeedsUpdate(),this.setData(e),!0}},{key:"getVertexOffset",value:function(e){var t=this.startIndices;return(t?t[e]:e)*this.size}},{key:"getShaderAttributes",value:function(){var e=this.settings.shaderAttributes||Object(o.a)({},this.id,null),t={};for(var n in e)Object.assign(t,Object(c.a)(Object(g.a)(A.prototype),"getShaderAttributes",this).call(this,n,e[n]));return t}},{key:"_autoUpdater",value:function(e,t){var A=t.data,n=t.startRow,r=t.endRow,i=t.props,o=t.numInstances;if(!e.constant){var a=e.settings,g=e.state,c=e.value,u=e.size,l=e.startIndices,I=a.accessor,C=a.transform,h=g.binaryAccessor||("function"===typeof I?I:i[I]);Object(v.a)("function"===typeof h,'accessor "'.concat(I,'" is not a function'));var f,d=e.getVertexOffset(n),B=Object(m.a)(A,n,r),p=B.iterable,E=B.objectInfo,Q=Object(s.a)(p);try{for(Q.s();!(f=Q.n()).done;){var y=f.value;E.index++;var w=h(y,E);if(C&&(w=C.call(this,w)),l){var S=(E.indexu?c.set(w,d):(e._normalizeValue(w,E.target,0),Object(b.a)({target:c,source:E.target,start:d,count:S}));d+=S*u}else e._normalizeValue(w,c,d),d+=u}}catch(k){Q.e(k)}finally{Q.f()}}}},{key:"_validateAttributeUpdaters",value:function(){var e=this.settings;if(!(e.noAlloc||"function"===typeof e.update))throw new Error("Attribute ".concat(this.id," missing update or accessor"))}},{key:"_checkAttributeArray",value:function(){var e=this.value,t=Math.min(4,this.size);if(e&&e.length>=t){var A=!0;switch(t){case 4:A=A&&Number.isFinite(e[3]);case 3:A=A&&Number.isFinite(e[2]);case 2:A=A&&Number.isFinite(e[1]);case 1:A=A&&Number.isFinite(e[0]);break;default:A=!1}if(!A)throw new Error("Illegal attribute generated for ".concat(this.id))}}},{key:"startIndices",get:function(){return this.state.startIndices},set:function(e){this.state.startIndices=e}}]),A}(y),G=A(77),k=A(1289),x=A(162),N=function(){function e(t){var A=t.gl,n=t.attribute,i=t.timeline;Object(r.a)(this,e),this.gl=A,this.type="interpolation",this.transition=new x.a(i),this.attribute=n,this.attributeInTransition=new D(A,n.settings),this.currentStartIndices=n.startIndices,this.currentLength=0,this.transform=function(e,t){var A=Object(R.c)(t.size);return new k.a(e,{vs:"\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nuniform float time;\nattribute ATTRIBUTE_TYPE aFrom;\nattribute ATTRIBUTE_TYPE aTo;\nvarying ATTRIBUTE_TYPE vCurrent;\n\nvoid main(void) {\n vCurrent = mix(aFrom, aTo, time);\n gl_Position = vec4(0.0);\n}\n",defines:{ATTRIBUTE_TYPE:A},varyings:["vCurrent"]})}(A,n);var o={byteLength:0,usage:35050};this.buffers=[new h.a(A,o),new h.a(A,o)]}return Object(i.a)(e,[{key:"start",value:function(e,t){if(e.duration<=0)this.transition.cancel();else{var A=this.gl,r=this.buffers,i=this.attribute;Object(R.a)(r);var o,a={numInstances:t,attribute:i,fromLength:this.currentLength,fromStartIndices:this.currentStartIndices,getData:e.enter},g=Object(s.a)(r);try{for(g.s();!(o=g.n()).done;){var c=o.value;Object(R.f)(Object(n.a)({buffer:c},a))}}catch(u){g.e(u)}finally{g.f()}this.currentStartIndices=i.startIndices,this.currentLength=Object(R.b)(i,t),this.attributeInTransition.update({buffer:r[1],value:i.value}),this.transition.start(e),this.transform.update({elementCount:Math.floor(this.currentLength/i.size),sourceBuffers:{aFrom:r[0],aTo:Object(R.d)(A,i)},feedbackBuffers:{vCurrent:r[1]}})}}},{key:"update",value:function(){var e=this.transition.update();if(e){var t=this.transition,A=t.time,n=t.settings,r=n.duration,i=(0,n.easing)(A/r);this.transform.run({uniforms:{time:i}})}return e}},{key:"cancel",value:function(){for(this.transition.cancel(),this.transform.delete();this.buffers.length;)this.buffers.pop().delete()}},{key:"inProgress",get:function(){return this.transition.inProgress}}]),e}();var U=A(530),_=A(232),M=A(161);var O={interpolation:N,spring:function(){function e(t){var A=t.gl,i=t.attribute,a=t.timeline;Object(r.a)(this,e),this.gl=A,this.type="spring",this.transition=new x.a(a),this.attribute=i,this.attributeInTransition=new D(A,Object(n.a)({},i.settings,{normalized:!1})),this.currentStartIndices=i.startIndices,this.currentLength=0,this.texture=function(e){return new _.a(e,{data:new Uint8Array(4),format:6408,type:5121,border:0,mipmaps:!1,dataFormat:6408,width:1,height:1})}(A),this.framebuffer=function(e,t){return new M.a(e,{id:"spring-transition-is-transitioning-framebuffer",width:1,height:1,attachments:Object(o.a)({},36064,t)})}(A,this.texture),this.transform=function(e,t,A){var n=Object(R.c)(t.size);return new k.a(e,{framebuffer:A,vs:"\n#define SHADER_NAME spring-transition-vertex-shader\n\n#define EPSILON 0.00001\n\nuniform float stiffness;\nuniform float damping;\nattribute ATTRIBUTE_TYPE aPrev;\nattribute ATTRIBUTE_TYPE aCur;\nattribute ATTRIBUTE_TYPE aTo;\nvarying ATTRIBUTE_TYPE vNext;\nvarying float vIsTransitioningFlag;\n\nATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) {\n ATTRIBUTE_TYPE velocity = cur - prev;\n ATTRIBUTE_TYPE delta = dest - cur;\n ATTRIBUTE_TYPE spring = delta * stiffness;\n ATTRIBUTE_TYPE damper = velocity * -1.0 * damping;\n return spring + damper + velocity + cur;\n}\n\nvoid main(void) {\n bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON;\n vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0;\n\n vNext = getNextValue(aCur, aPrev, aTo);\n gl_Position = vec4(0, 0, 0, 1);\n gl_PointSize = 100.0;\n}\n",fs:"\n#define SHADER_NAME spring-transition-is-transitioning-fragment-shader\n\nvarying float vIsTransitioningFlag;\n\nvoid main(void) {\n if (vIsTransitioningFlag == 0.0) {\n discard;\n }\n gl_FragColor = vec4(1.0);\n}",defines:{ATTRIBUTE_TYPE:n},varyings:["vNext"]})}(A,i,this.framebuffer);var s={byteLength:0,usage:35050};this.buffers=[new h.a(A,s),new h.a(A,s),new h.a(A,s)]}return Object(i.a)(e,[{key:"start",value:function(e,t){var A,r=this.gl,i=this.buffers,o=this.attribute,a={numInstances:t,attribute:o,fromLength:this.currentLength,fromStartIndices:this.currentStartIndices,getData:e.enter},g=Object(s.a)(i);try{for(g.s();!(A=g.n()).done;){var c=A.value;Object(R.f)(Object(n.a)({buffer:c},a))}}catch(u){g.e(u)}finally{g.f()}this.currentStartIndices=o.startIndices,this.currentLength=Object(R.b)(o,t),this.attributeInTransition.update({buffer:i[1],value:o.value}),this.transition.start(e),this.transform.update({elementCount:Math.floor(this.currentLength/o.size),sourceBuffers:{aTo:Object(R.d)(r,o)}})}},{key:"update",value:function(){var e=this.buffers,t=this.transform,A=this.framebuffer,n=this.transition;return!!n.update()&&(t.update({sourceBuffers:{aPrev:e[0],aCur:e[1]},feedbackBuffers:{vNext:e[2]}}),t.run({framebuffer:A,discard:!1,clearRenderTarget:!0,uniforms:{stiffness:n.settings.stiffness,damping:n.settings.damping},parameters:{depthTest:!1,blend:!0,viewport:[0,0,1,1],blendFunc:[1,1],blendEquation:[32776,32776]}}),Object(R.a)(e),this.attributeInTransition.update({buffer:e[1],value:this.attribute.value}),Object(U.c)(A)[0]>0||n.end(),!0)}},{key:"cancel",value:function(){for(this.transition.cancel(),this.transform.delete();this.buffers.length;)this.buffers.pop().delete();this.texture.delete(),this.texture=null,this.framebuffer.delete(),this.framebuffer=null}},{key:"inProgress",get:function(){return this.transition.inProgress}}]),e}()},L=function(){function e(t,A){var n=A.id,i=A.timeline;Object(r.a)(this,e),this.id=n,this.gl=t,this.timeline=i,this.transitions={},this.needsRedraw=!1,this.numInstances=1,this.isSupported=k.a.isSupported(t)}return Object(i.a)(e,[{key:"finalize",value:function(){for(var e in this.transitions)this._removeTransition(e)}},{key:"update",value:function(e){var t=e.attributes,A=e.transitions,n=e.numInstances;for(var r in this.numInstances=n||1,t){var i=t[r],o=i.getTransitionSetting(A);o&&this._updateAttribute(r,i,o)}for(var a in this.transitions){var s=t[a];s&&s.getTransitionSetting(A)||this._removeTransition(a)}}},{key:"hasAttribute",value:function(e){var t=this.transitions[e];return t&&t.inProgress}},{key:"getAttributes",value:function(){var e={};for(var t in this.transitions){var A=this.transitions[t];A.inProgress&&(e[t]=A.attributeInTransition)}return e}},{key:"run",value:function(){if(!this.isSupported||0===this.numInstances)return!1;for(var e in this.transitions){this.transitions[e].update()&&(this.needsRedraw=!0)}var t=this.needsRedraw;return this.needsRedraw=!1,t}},{key:"_removeTransition",value:function(e){this.transitions[e].cancel(),delete this.transitions[e]}},{key:"_updateAttribute",value:function(e,t,A){var n=this.transitions[e],r=!n||n.type!==A.type;if(r){if(!this.isSupported)return void p.a.warn("WebGL2 not supported by this browser. Transition for ".concat(e," is disabled."))();n&&this._removeTransition(e);var i=O[A.type];i?this.transitions[e]=new i({attribute:t,timeline:this.timeline,gl:this.gl}):(p.a.error("unsupported transition type '".concat(A.type,"'"))(),r=!1)}(r||t.needsRedraw())&&(this.needsRedraw=!0,this.transitions[e].start(A,this.numInstances))}}]),e}();A.d(t,"a",(function(){return T}));var T=function(){function e(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=A.id,i=void 0===n?"attribute-manager":n,o=A.stats,a=A.timeline;Object(r.a)(this,e),this.id=i,this.gl=t,this.attributes={},this.updateTriggers={},this.accessors={},this.needsRedraw=!0,this.userData={},this.stats=o,this.attributeTransitionManager=new L(t,{id:"".concat(i,"-transitions"),timeline:a}),Object.seal(this)}return Object(i.a)(e,[{key:"finalize",value:function(){for(var e in this.attributes)this.attributes[e].delete();this.attributeTransitionManager.finalize()}},{key:"getNeedsRedraw",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{clearRedrawFlags:!1},t=this.needsRedraw;return this.needsRedraw=this.needsRedraw&&!e.clearRedrawFlags,t&&this.id}},{key:"setNeedsRedraw",value:function(){!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this.needsRedraw=!0,this}},{key:"add",value:function(e,t){this._add(e,t)}},{key:"addInstanced",value:function(e,t){this._add(e,t,{instanced:1})}},{key:"remove",value:function(e){for(var t=0;t0&&void 0!==arguments[0]?arguments[0]:{},t=e.data,A=e.numInstances,n=e.startIndices,r=void 0===n?null:n,i=e.transitions,o=e.props,a=void 0===o?{}:o,s=e.buffers,g=void 0===s?{}:s,c=e.context,u=void 0===c?{}:c,l=!1;for(var I in Object(G.a)("attributeManager.updateStart",this),this.stats&&this.stats.get("Update Attributes").timeStart(),this.attributes){var C=this.attributes[I],h=C.settings.accessor;C.startIndices=r,a[I]&&p.a.removed("props.".concat(I),"data.attributes.".concat(I))(),C.setExternalBuffer(g[I])||C.setBinaryValue(g[h],t.startIndices)||!g[h]&&C.setConstantValue(a[h])||C.needsUpdate()&&(l=!0,this._updateAttribute({attribute:C,numInstances:A,data:t,props:a,context:u})),this.needsRedraw|=C.needsRedraw()}l&&Object(G.a)("attributeManager.updateEnd",this,A),this.stats&&this.stats.get("Update Attributes").timeEnd(),this.attributeTransitionManager.update({attributes:this.attributes,numInstances:A,transitions:i})}},{key:"updateTransition",value:function(){var e=this.attributeTransitionManager.run();return this.needsRedraw=this.needsRedraw||e,e}},{key:"getAttributes",value:function(){return this.attributes}},{key:"getChangedAttributes",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{clearChangedFlags:!1},t=this.attributes,A=this.attributeTransitionManager,r=Object(n.a)({},A.getAttributes());for(var i in t){var o=t[i];o.needsRedraw(e)&&!A.hasAttribute(i)&&(r[i]=o)}return r}},{key:"getShaderAttributes",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e||(e=this.getAttributes());var A={};for(var n in e)t[n]||Object.assign(A,e[n].getShaderAttributes());return A}},{key:"getAccessors",value:function(){return this.updateTriggers}},{key:"_add",value:function(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};for(var n in t&&p.a.warn("AttributeManager.add({updaters}) - updater map no longer supported")(),e){var r=e[n];this.attributes[n]=this._createAttribute(n,r,A)}this._mapUpdateTriggersToAttributes()}},{key:"_createAttribute",value:function(e,t,A){var r=Object(n.a)({},t,{id:e,isIndexed:t.isIndexed||t.elements||!1,constant:t.constant||!1,size:(t.elements?1:t.size)||1,value:t.value||null,divisor:t.instanced||A.instanced?1:t.divisor||0});return new D(this.gl,r)}},{key:"_mapUpdateTriggersToAttributes",value:function(){var e=this,t={},A=function(A){e.attributes[A].getUpdateTriggers().forEach((function(e){t[e]||(t[e]=[]),t[e].push(A)}))};for(var n in this.attributes)A(n);this.updateTriggers=t}},{key:"_invalidateTrigger",value:function(e,t){var A=this.attributes,n=this.updateTriggers[e];return n&&n.forEach((function(e){var n=A[e];n&&n.setNeedsUpdate(n.id,t)})),n}},{key:"_updateAttribute",value:function(e){var t=e.attribute,A=e.numInstances;(Object(G.a)("attribute.updateStart",t),t.constant)?t.setConstantValue(t.value):(t.allocate(A)&&Object(G.a)("attribute.allocate",t,A),t.updateBuffer(e)&&(this.needsRedraw=!0,Object(G.a)("attribute.updateEnd",t,A)))}}]),e}()},function(e,t,A){"use strict";var n=A(8),r=A(6),i=A(7),o=A(1),a=A(4),s=A(9),g=A(10),c=A(116),u=A(511),l=A(391),I=A(667),C=A.n(I),h=A(41),f=[];function d(e,t,A,n){for(var r=0,i=t;in&&(oa){var u=d(e,a,s,r);g+u>n&&(on&&(u=B(e,a,s,n,r,i),o=i[i.length-1])),a=s,g+=u}return g}function E(e,t,A,n){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,i=arguments.length>5?arguments[5]:void 0;void 0===i&&(i=e.length);var o=[];return"break-all"===t?B(e,r,i,A,n,o):p(e,r,i,A,n,o),o}function Q(e,t,A,n,r,i){for(var o=0,a=0,s=t;s0,c=[0,0],u=[],l=0,I=0,C=0,h=0;h<=i;h++){var d=e[h];if("\n"!==d&&h!==i||(C=h),C>I){for(var B=g?E(e,A,n,r,I,C):f,p=0;p<=B.length;p++){var y=0===p?I:B[p-1],v=p0&&void 0!==arguments[0]?arguments[0]:5;Object(o.a)(this,e),this.limit=t,this.clear()}return Object(a.a)(e,[{key:"clear",value:function(){this._cache={},this._order=[]}},{key:"get",value:function(e){var t=this._cache[e];return t&&(this._deleteOrder(e),this._appendOrder(e)),t}},{key:"set",value:function(e,t){this._cache[e]?(this.delete(e),this._cache[e]=t,this._appendOrder(e)):(Object.keys(this._cache).length===this.limit&&this.delete(this._order[0]),this._cache[e]=t,this._appendOrder(e))}},{key:"delete",value:function(e){this._cache[e]&&(this._deleteCache(e),this._deleteOrder(e))}},{key:"_deleteCache",value:function(e){delete this._cache[e]}},{key:"_deleteOrder",value:function(e){var t=this._order.findIndex((function(t){return t===e}));t>=0&&this._order.splice(t,1)}},{key:"_appendOrder",value:function(e){this._order.push(e)}}]),e}();var m=function(){for(var e=[],t=32;t<128;t++)e.push(String.fromCharCode(t));return e}(),b=new v(3),w=["fontFamily","fontWeight","characterSet","fontSize","sdf","buffer","cutoff","radius"];function S(e,t){var A=b.get(e);if(!A)return t;var n=[],r=A.mapping,i=Object.keys(r);i=new Set(i);var o=t;return o instanceof Array&&(o=new Set(o)),o.forEach((function(e){i.has(e)||n.push(e)})),n}function F(e,t){for(var A=0;A0&&void 0!==arguments[0]?arguments[0]:{};w.forEach((function(A){A in t&&(e.props[A]=t[A])}));var A=this._key;this._key=this._getKey();var n=S(this._key,this.props.characterSet),r=b.get(this._key);if(r&&0===n.length)this._key!==A&&(this._atlas=r);else{var i=this._generateFontAtlas(this._key,n,r);this._atlas=i,b.set(this._key,i)}}},{key:"_generateFontAtlas",value:function(e,t,A){var n=this.props,o=n.fontFamily,a=n.fontWeight,s=n.fontSize,g=n.buffer,c=n.sdf,u=n.radius,l=n.cutoff,I=A&&A.data;I||((I=document.createElement("canvas")).width=1024);var h=I.getContext("2d");R(h,o,s,a);var f=function(e){var t,A=e.characterSet,n=e.getFontWidth,i=e.fontHeight,o=e.buffer,a=e.maxCanvasWidth,s=e.mapping,g=void 0===s?{}:s,c=e.xOffset,u=void 0===c?0:c,l=e.yOffset,I=void 0===l?0:l,C=0,h=u,f=0,d=Object(r.a)(A);try{for(d.s();!(t=d.n()).done;){var B=t.value;if(!g[B]){var p=n(B,f++);h+p+2*o>a&&(h=0,C++),g[B]={x:h+o,y:I+C*(i+2*o)+o,width:p,height:i},h+=p+2*o}}}catch(y){d.e(y)}finally{d.f()}var E,Q=i+2*o;return{mapping:g,xOffset:h,yOffset:I+C*Q,canvasHeight:(E=I+(C+1)*Q,Math.pow(2,Math.ceil(Math.log2(E))))}}(Object(i.a)({getFontWidth:function(e){return h.measureText(e).width},fontHeight:1.2*s,buffer:g,characterSet:t,maxCanvasWidth:1024},A&&{mapping:A.mapping,xOffset:A.xOffset,yOffset:A.yOffset})),d=f.mapping,B=f.canvasHeight,p=f.xOffset,E=f.yOffset;if(I.height!==B){var Q=h.getImageData(0,0,I.width,I.height);I.height=B,h.putImageData(Q,0,0)}if(R(h,o,s,a),c){var y,v=new C.a(s,g,u,l,o,a),m=h.getImageData(0,0,v.size,v.size),b=Object(r.a)(t);try{for(b.s();!(y=b.n()).done;){var w=y.value;F(v.draw(w),m),h.putImageData(m,d[w].x-g,d[w].y+g)}}catch(k){b.e(k)}finally{b.f()}}else{var S,D=Object(r.a)(t);try{for(D.s();!(S=D.n()).done;){var G=S.value;h.fillText(G,d[G].x,d[G].y+.9*s)}}catch(k){D.e(k)}finally{D.f()}}return{xOffset:p,yOffset:E,mapping:d,data:I,width:I.width,height:I.height}}},{key:"_getKey",value:function(){var e=this.props,t=e.fontFamily,A=e.fontWeight,n=e.fontSize,r=e.buffer,i=e.sdf,o=e.radius,a=e.cutoff;return i?"".concat(t," ").concat(A," ").concat(n," ").concat(r," ").concat(o," ").concat(a):"".concat(t," ").concat(A," ").concat(n," ").concat(r)}},{key:"texture",get:function(){return this._atlas}},{key:"mapping",get:function(){return this._atlas&&this._atlas.mapping}},{key:"scale",get:function(){return 1.2}}]),e}(),G=A(389);A.d(t,"a",(function(){return O}));var k={fontSize:64,buffer:4,sdf:!1,radius:12,cutoff:.25,smoothing:.1},x={start:1,middle:0,end:-1},N={top:1,center:0,bottom:-1},U=[0,0,0,255],_=["fontSize","buffer","sdf","radius","cutoff"],M={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,background:!1,getBackgroundColor:{type:"accessor",value:[255,255,255,255]},getBorderColor:{type:"accessor",value:U},getBorderWidth:{type:"accessor",value:0},backgroundPadding:{type:"array",value:[0,0,0,0]},characterSet:{type:"object",value:m},fontFamily:"Monaco, monospace",fontWeight:"normal",lineHeight:1,outlineWidth:{type:"number",value:0,min:0},outlineColor:{type:"color",value:U},fontSettings:{},wordBreak:"break-word",maxWidth:{type:"number",value:-1},getText:{type:"accessor",value:function(e){return e.text}},getPosition:{type:"accessor",value:function(e){return e.position}},getColor:{type:"accessor",value:U},getSize:{type:"accessor",value:32},getAngle:{type:"accessor",value:0},getTextAnchor:{type:"accessor",value:"middle"},getAlignmentBaseline:{type:"accessor",value:"center"},getPixelOffset:{type:"accessor",value:[0,0]},backgroundColor:{deprecatedFor:["background","getBackgroundColor"]}},O=function(e){Object(s.a)(A,e);var t=Object(g.a)(A);function A(){return Object(o.a)(this,A),t.apply(this,arguments)}return Object(a.a)(A,[{key:"initializeState",value:function(){this.state={styleVersion:0,fontAtlasManager:new D}}},{key:"updateState",value:function(e){var t=e.props,A=e.oldProps,n=e.changeFlags,r=n.dataChanged||n.updateTriggersChanged&&(n.updateTriggersChanged.all||n.updateTriggersChanged.getText),i=this.state.characterSet;r&&this._updateText();var o=i!==this.state.characterSet||this._fontChanged(A,t);o&&this._updateFontAtlas(A,t),(o||t.lineHeight!==A.lineHeight||t.wordBreak!==A.wordBreak||t.maxWidth!==A.maxWidth)&&this.setState({styleVersion:this.state.styleVersion+1})}},{key:"getPickingInfo",value:function(e){var t=e.info;return t.object=t.index>=0?this.props.data[t.index]:null,t}},{key:"_updateFontAtlas",value:function(e,t){var A=t.fontSettings,n=t.fontFamily,r=t.fontWeight,o=this.state,a=o.fontAtlasManager,s=o.characterSet;a.setProps(Object(i.a)({},k,{},A,{characterSet:s,fontFamily:n,fontWeight:r}))}},{key:"_fontChanged",value:function(e,t){if(e.fontFamily!==t.fontFamily||e.fontWeight!==t.fontWeight)return!0;if(e.fontSettings===t.fontSettings)return!1;var A=e.fontSettings||{},n=t.fontSettings||{};return _.some((function(e){return A[e]!==n[e]}))}},{key:"_updateText",value:function(){var e,t=this.props,A=t.data,n=t.characterSet,o=A.attributes&&A.attributes.getText,a=this.props.getText,s=A.startIndices,g="auto"===n&&new Set;if(o&&s){var u=function(e){var t=e.value,A=e.length,n=e.stride,i=e.offset,o=e.startIndices,a=e.characterSet,s=t.BYTES_PER_ELEMENT,g=n?n/s:1,c=i?i/s:0,u=o[A]||Math.ceil((t.length-c)/g),l=a&&new Set,I=new Array(A),C=t;if(g>1||c>0){C=new t.constructor(u);for(var h=0;h0&&void 0!==arguments[0]?arguments[0]:{};Object(r.a)(this,A);var i=e.id,o=void 0===i?Object(d.c)("column-geometry"):i,a=Q(e),s=a.indices,g=a.attributes;return t.call(this,Object(n.a)({},e,{id:o,indices:s,attributes:g}))}return A}(B.a);function Q(e){var t=e.radius,A=e.height,n=void 0===A?1:A,r=e.nradial,i=void 0===r?10:r,o=e.vertices;o&&(f.a.assert(o.length>=i),o=o.flatMap((function(e){return[e[0],e[1]]})),Object(p.h)(o,p.a.COUNTER_CLOCKWISE));var a=n>0,s=i+1,g=a?3*s+1:i,c=2*Math.PI/i,u=new Uint16Array(a?3*i*2:0),l=new Float32Array(3*g),I=new Float32Array(3*g),C=0;if(a){for(var h=0;h 0.0 && instanceElevations >= 0.0);\n float dotRadius = radius * coverage * shouldRender;\n\n geometry.normal = project_normal(vec3(rotationMatrix * normals.xy, normals.z));\n geometry.pickingColor = instancePickingColors;\n vec3 centroidPosition = vec3(instancePositions.xy, instancePositions.z + elevation);\n vec3 centroidPosition64Low = instancePositions64Low;\n vec2 offset = (rotationMatrix * positions.xy * strokeOffsetRatio + offset) * dotRadius;\n if (radiusUnits == UNIT_METERS) {\n offset = project_size(offset);\n }\n vec3 pos = vec3(offset, 0.);\n DECKGL_FILTER_SIZE(pos, geometry);\n\n gl_Position = project_position_to_clipspace(centroidPosition, centroidPosition64Low, pos, geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n if (extruded && !isStroke) {\n vec3 lightColor = lighting_getLightColor(color.rgb, project_uCameraPosition, geometry.position.xyz, geometry.normal);\n vColor = vec4(lightColor, color.a * opacity);\n } else {\n vColor = vec4(color.rgb, color.a * opacity);\n }\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#define SHADER_NAME column-layer-fragment-shader\n\nprecision highp float;\n\nvarying vec4 vColor;\n\nvoid main(void) {\n gl_FragColor = vColor;\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n",modules:[c.a,u.a,l.a]})}},{key:"initializeState",value:function(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:5130,fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceElevations:{size:1,transition:!0,accessor:"getElevation"},instanceFillColors:{size:this.props.colorFormat.length,type:5121,normalized:!0,transition:!0,accessor:"getFillColor",defaultValue:y},instanceLineColors:{size:this.props.colorFormat.length,type:5121,normalized:!0,transition:!0,accessor:"getLineColor",defaultValue:y},instanceStrokeWidths:{size:1,accessor:"getLineWidth",transition:!0}})}},{key:"updateState",value:function(e){var t=e.props,n=e.oldProps,r=e.changeFlags;Object(a.a)(Object(o.a)(A.prototype),"updateState",this).call(this,{props:t,oldProps:n,changeFlags:r});var i=r.extensionsChanged;if(i){var s,g=this.context.gl;null===(s=this.state.model)||void 0===s||s.delete(),this.state.model=this._getModel(g),this.getAttributeManager().invalidateAll()}(i||t.diskResolution!==n.diskResolution||t.vertices!==n.vertices||(t.extruded||t.stroked)!==(n.extruded||n.stroked))&&this._updateGeometry(t)}},{key:"getGeometry",value:function(e,t,A){var n=new E({radius:1,height:A?2:0,vertices:t,nradial:e}),r=0;if(t)for(var i=0;i 0.5) {\n float isLine = antialiasing ? \n smoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) :\n step(innerUnitRadius * outerRadiusPixels, distToCenter);\n\n if (filled) {\n gl_FragColor = mix(vFillColor, vLineColor, isLine);\n } else {\n if (isLine == 0.0) {\n discard;\n }\n gl_FragColor = vec4(vLineColor.rgb, vLineColor.a * isLine);\n }\n } else if (filled) {\n gl_FragColor = vFillColor;\n } else {\n discard;\n }\n\n gl_FragColor.a *= inCircle;\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n",modules:[c.a,u.a]})}},{key:"initializeState",value:function(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:5130,fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceRadius:{size:1,transition:!0,accessor:"getRadius",defaultValue:1},instanceFillColors:{size:this.props.colorFormat.length,transition:!0,normalized:!0,type:5121,accessor:"getFillColor",defaultValue:[0,0,0,255]},instanceLineColors:{size:this.props.colorFormat.length,transition:!0,normalized:!0,type:5121,accessor:"getLineColor",defaultValue:[0,0,0,255]},instanceLineWidths:{size:1,transition:!0,accessor:"getLineWidth",defaultValue:1}})}},{key:"updateState",value:function(e){var t=e.props,n=e.oldProps,r=e.changeFlags;if(Object(a.a)(Object(o.a)(A.prototype),"updateState",this).call(this,{props:t,oldProps:n,changeFlags:r}),r.extensionsChanged){var i,s=this.context.gl;null===(i=this.state.model)||void 0===i||i.delete(),this.state.model=this._getModel(s),this.getAttributeManager().invalidateAll()}}},{key:"draw",value:function(e){var t=e.uniforms,A=this.props,n=A.radiusUnits,r=A.radiusScale,i=A.radiusMinPixels,o=A.radiusMaxPixels,a=A.stroked,s=A.filled,g=A.billboard,c=A.antialiasing,u=A.lineWidthUnits,I=A.lineWidthScale,C=A.lineWidthMinPixels,h=A.lineWidthMaxPixels;this.state.model.setUniforms(t).setUniforms({stroked:a?1:0,filled:s,billboard:g,antialiasing:c,radiusUnits:l.d[n],radiusScale:r,radiusMinPixels:i,radiusMaxPixels:o,lineWidthUnits:l.d[u],lineWidthScale:I,lineWidthMinPixels:C,lineWidthMaxPixels:h}).draw()}},{key:"_getModel",value:function(e){return new C.a(e,Object(n.a)({},this.getShaders(),{id:this.props.id,geometry:new h.a({drawMode:6,vertexCount:4,attributes:{positions:{size:3,value:new Float32Array([-1,-1,0,1,-1,0,1,1,0,-1,1,0])}}}),isInstanced:!0}))}}]),A}(I.a);B.layerName="ScatterplotLayer",B.defaultProps=d},function(e,t,A){"use strict";var n=A(7),r=A(1),i=A(4),o=A(16),a=A(17),s=A(9),g=A(10),c=A(575),u=A(576),l=A(36),I=A(384),C=A(422),h=A(135);A.d(t,"a",(function(){return d}));var f={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,padding:{type:"array",value:[0,0,0,0]},getPosition:{type:"accessor",value:function(e){return e.position}},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},getBoundingRect:{type:"accessor",value:[0,0,0,0]},getFillColor:{type:"accessor",value:[0,0,0,255]},getLineColor:{type:"accessor",value:[0,0,0,255]},getLineWidth:{type:"accessor",value:1}},d=function(e){Object(s.a)(A,e);var t=Object(g.a)(A);function A(){return Object(r.a)(this,A),t.apply(this,arguments)}return Object(i.a)(A,[{key:"getShaders",value:function(){return Object(a.a)(Object(o.a)(A.prototype),"getShaders",this).call(this,{vs:"#define SHADER_NAME text-background-layer-vertex-shader\n\nattribute vec2 positions;\n\nattribute vec3 instancePositions;\nattribute vec3 instancePositions64Low;\nattribute vec4 instanceRects;\nattribute float instanceSizes;\nattribute float instanceAngles;\nattribute vec2 instancePixelOffsets;\nattribute float instanceLineWidths;\nattribute vec4 instanceFillColors;\nattribute vec4 instanceLineColors;\nattribute vec3 instancePickingColors;\n\nuniform bool billboard;\nuniform float opacity;\nuniform float sizeScale;\nuniform float sizeMinPixels;\nuniform float sizeMaxPixels;\nuniform vec4 padding;\nuniform int sizeUnits;\n\nvarying vec4 vFillColor;\nvarying vec4 vLineColor;\nvarying float vLineWidth;\nvarying vec2 uv;\nvarying vec2 dimensions;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = radians(angle);\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n vLineWidth = instanceLineWidths;\n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * sizeScale, sizeUnits),\n sizeMinPixels, sizeMaxPixels\n );\n\n dimensions = instanceRects.zw * sizePixels + padding.xy + padding.zw;\n\n vec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * sizePixels + mix(-padding.xy, padding.zw, positions);\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles);\n pixelOffset += instancePixelOffsets;\n pixelOffset.y *= -1.0;\n\n if (billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n DECKGL_FILTER_SIZE(offset_common, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\n }\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * opacity);\n DECKGL_FILTER_COLOR(vFillColor, geometry);\n vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * opacity);\n DECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n",fs:"#define SHADER_NAME text-background-layer-fragment-shader\n\nprecision highp float;\n\nuniform bool stroked;\n\nvarying vec4 vFillColor;\nvarying vec4 vLineColor;\nvarying float vLineWidth;\nvarying vec2 uv;\nvarying vec2 dimensions;\n\nvoid main(void) {\n geometry.uv = uv;\n\n vec2 pixelPosition = uv * dimensions;\n if (stroked) {\n float distToEdge = min(\n min(pixelPosition.x, dimensions.x - pixelPosition.x),\n min(pixelPosition.y, dimensions.y - pixelPosition.y)\n );\n float isBorder = smoothedge(distToEdge, vLineWidth);\n gl_FragColor = mix(vFillColor, vLineColor, isBorder);\n } else {\n gl_FragColor = vFillColor;\n }\n\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n",modules:[c.a,u.a]})}},{key:"initializeState",value:function(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:5130,fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,accessor:"getSize",defaultValue:1},instanceAngles:{size:1,transition:!0,accessor:"getAngle"},instanceRects:{size:4,accessor:"getBoundingRect"},instancePixelOffsets:{size:2,transition:!0,accessor:"getPixelOffset"},instanceFillColors:{size:4,transition:!0,normalized:!0,type:5121,accessor:"getFillColor",defaultValue:[0,0,0,255]},instanceLineColors:{size:4,transition:!0,normalized:!0,type:5121,accessor:"getLineColor",defaultValue:[0,0,0,255]},instanceLineWidths:{size:1,transition:!0,accessor:"getLineWidth",defaultValue:1}})}},{key:"updateState",value:function(e){var t=e.props,n=e.oldProps,r=e.changeFlags;if(Object(a.a)(Object(o.a)(A.prototype),"updateState",this).call(this,{props:t,oldProps:n,changeFlags:r}),r.extensionsChanged){var i,s=this.context.gl;null===(i=this.state.model)||void 0===i||i.delete(),this.state.model=this._getModel(s),this.getAttributeManager().invalidateAll()}}},{key:"draw",value:function(e){var t=e.uniforms,A=this.props,n=A.billboard,r=A.sizeScale,i=A.sizeUnits,o=A.sizeMinPixels,a=A.sizeMaxPixels,s=A.getLineWidth,g=this.props.padding;g.length<4&&(g=[g[0],g[1],g[0],g[1]]),this.state.model.setUniforms(t).setUniforms({billboard:n,stroked:Boolean(s),padding:g,sizeUnits:l.d[i],sizeScale:r,sizeMinPixels:o,sizeMaxPixels:a}).draw()}},{key:"_getModel",value:function(e){return new C.a(e,Object(n.a)({},this.getShaders(),{id:this.props.id,geometry:new h.a({drawMode:6,vertexCount:4,attributes:{positions:{size:2,value:new Float32Array([0,0,1,0,1,1,0,1])}}}),isInstanced:!0}))}}]),A}(I.a);d.layerName="TextBackgroundLayer",d.defaultProps=f},function(e,t,A){"use strict";var n=A(6),r=A(7),i=A(1),o=A(4),a=A(1247),s=A(78),g=A(41),c=A(77),u=A(147),l=A(1165),I=A(1283),C=function(){function e(t,A,n){Object(i.a)(this,e),this.id=t,this.context=n,this._loadCount=0,this._subscribers=new Set,this.setData(A)}return Object(o.a)(e,[{key:"subscribe",value:function(e){this._subscribers.add(e)}},{key:"unsubscribe",value:function(e){this._subscribers.delete(e)}},{key:"inUse",value:function(){return this._subscribers.size>0}},{key:"delete",value:function(){}},{key:"getData",value:function(){var e=this;return this.isLoaded?this._error?Promise.reject(this._error):this._content:this._loader.then((function(){return e.getData()}))}},{key:"setData",value:function(e,t){var A=this;if(e!==this._data||t){this._data=e;var r=++this._loadCount,i=e;"string"===typeof e&&(i=Object(I.a)(e)),i instanceof Promise?(this.isLoaded=!1,this._loader=i.then((function(e){A._loadCount===r&&(A.isLoaded=!0,A._error=null,A._content=e)})).catch((function(e){A._loadCount===r&&(A.isLoaded=!0,A._error=e||!0)}))):(this.isLoaded=!0,this._error=null,this._content=e);var o,a=Object(n.a)(this._subscribers);try{for(a.s();!(o=a.n()).done;){o.value.onChange(this.getData())}}catch(s){a.e(s)}finally{a.f()}}}}]),e}(),h=function(){function e(t){var A=t.gl,n=t.protocol;Object(i.a)(this,e),this.protocol=n||"resource://",this._context={gl:A,resourceManager:this},this._resources={},this._consumers={},this._pruneRequest=null}return Object(o.a)(e,[{key:"contains",value:function(e){return!!e.startsWith(this.protocol)||e in this._resources}},{key:"add",value:function(e){var t=e.resourceId,A=e.data,n=e.forceUpdate,r=void 0!==n&&n,i=e.persistent,o=void 0===i||i,a=this._resources[t];a?a.setData(A,r):(a=new C(t,A,this._context),this._resources[t]=a),a.persistent=o}},{key:"remove",value:function(e){var t=this._resources[e];t&&(t.delete(),delete this._resources[e])}},{key:"unsubscribe",value:function(e){var t=e.consumerId,A=this._consumers[t];if(A){for(var n in A){var r=A[n];r.resource&&r.resource.unsubscribe(r)}delete this._consumers[t],this.prune()}}},{key:"subscribe",value:function(e){var t=e.resourceId,A=e.onChange,n=e.consumerId,r=e.requestId,i=void 0===r?"default":r,o=this._resources,a=this.protocol;t.startsWith(a)&&(o[t=t.replace(a,"")]||this.add({resourceId:t,data:null,persistent:!1}));var s=o[t];if(this._track(n,i,s,A),s)return s.getData()}},{key:"prune",value:function(){var e=this;this._pruneRequest||(this._pruneRequest=setTimeout((function(){return e._prune()}),0))}},{key:"finalize",value:function(){for(var e in this._resources)this._resources[e].delete()}},{key:"_track",value:function(e,t,A,n){var r=this._consumers,i=r[e]=r[e]||{},o=i[t]||{};o.resource&&(o.resource.unsubscribe(o),o.resource=null,this.prune()),A&&(i[t]=o,o.onChange=n,o.resource=A,A.subscribe(o))}},{key:"_prune",value:function(){this._pruneRequest=null;for(var e=0,t=Object.keys(this._resources);e1&&void 0!==arguments[1]?arguments[1]:{},n=A.deck,o=A.stats,s=A.viewport,g=A.timeline;Object(i.a)(this,e),this.lastRenderedLayers=[],this.layers=[],this.resourceManager=new h({gl:t,protocol:"deck://"}),this.context=Object(r.a)({},B,{layerManager:this,gl:t,deck:n,programManager:t&&Object(d.a)(t),stats:o||new l.a({id:"deck.gl"}),viewport:s||new f.a({id:"DEFAULT-INITIAL-VIEWPORT"}),timeline:g||new a.a,resourceManager:this.resourceManager}),this._nextLayers=null,this._needsRedraw="Initial render",this._needsUpdate=!1,this._debug=!1,this.activateViewport=this.activateViewport.bind(this),Object.seal(this)}return Object(o.a)(e,[{key:"finalize",value:function(){this.resourceManager.finalize();var e,t=Object(n.a)(this.layers);try{for(t.s();!(e=t.n()).done;){var A=e.value;this._finalizeLayer(A)}}catch(r){t.e(r)}finally{t.f()}}},{key:"needsRedraw",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{clearRedrawFlags:!1},t=this._needsRedraw;e.clearRedrawFlags&&(this._needsRedraw=!1);var A,r=Object(n.a)(this.layers);try{for(r.s();!(A=r.n()).done;){var i=A.value,o=i.getNeedsRedraw(e);t=t||o}}catch(a){r.e(a)}finally{r.f()}return t}},{key:"needsUpdate",value:function(){return this._nextLayers&&this._nextLayers!==this.lastRenderedLayers?"layers changed":this._needsUpdate}},{key:"setNeedsRedraw",value:function(e){this._needsRedraw=this._needsRedraw||e}},{key:"setNeedsUpdate",value:function(e){this._needsUpdate=this._needsUpdate||e}},{key:"getLayers",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.layerIds,A=void 0===t?null:t;return A?this.layers.filter((function(e){return A.find((function(t){return 0===e.id.indexOf(t)}))})):this.layers}},{key:"setProps",value:function(e){"debug"in e&&(this._debug=e.debug),"userData"in e&&(this.context.userData=e.userData),"layers"in e&&(this._nextLayers=e.layers),"onError"in e&&(this.context.onError=e.onError)}},{key:"setLayers",value:function(e,t){Object(c.a)("layerManager.setLayers",this,t,e),this.lastRenderedLayers=e,e=Object(u.b)(e,Boolean);var A,r=Object(n.a)(e);try{for(r.s();!(A=r.n()).done;){A.value.context=this.context}}catch(i){r.e(i)}finally{r.f()}return this._updateLayers(this.layers,e),this}},{key:"updateLayers",value:function(){var e=this.needsUpdate();e&&(this.setNeedsRedraw("updating layers: ".concat(e)),this.setLayers(this._nextLayers||this.lastRenderedLayers,e)),this._nextLayers=null}},{key:"activateViewport",value:function(e){return Object(c.a)("layerManager.activateViewport",this,e),e&&(this.context.viewport=e),this}},{key:"_handleError",value:function(e,t,A){A.raiseError(t,"".concat(e," of ").concat(A))}},{key:"_updateLayers",value:function(e,t){var A,r={},i=Object(n.a)(e);try{for(i.s();!(A=i.n()).done;){var o=A.value;r[o.id]?g.a.warn("Multiple old layers with same id ".concat(o.id))():r[o.id]=o}}catch(l){i.e(l)}finally{i.f()}var a=[];this._updateSublayersRecursively(t,r,a),this._finalizeOldLayers(r);for(var s=!1,c=0,u=a;c 0.0) {\n float inFill = alpha;\n float inBorder = smoothstep(outlineBuffer - gamma, outlineBuffer + gamma, distance);\n color = mix(outlineColor, vColor, inFill);\n alpha = inBorder;\n }\n }\n float a = alpha * color.a;\n \n if (a < alphaCutoff) {\n discard;\n }\n\n gl_FragColor = vec4(color.rgb, a * opacity);\n }\n\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n"})}},{key:"initializeState",value:function(){var e=this;Object(a.a)(Object(o.a)(A.prototype),"initializeState",this).call(this),this.getAttributeManager().addInstanced({instanceOffsets:{size:2,accessor:"getIconOffsets"},instancePickingColors:{type:5121,size:3,accessor:function(t,A){var n=A.index,r=A.target;return e.encodePickingColor(n,r)}}})}},{key:"updateState",value:function(e){Object(a.a)(Object(o.a)(A.prototype),"updateState",this).call(this,e);var t=e.props,n=e.oldProps,r=t.outlineColor;r!==n.outlineColor&&((r=r.map((function(e){return e/255})))[3]=Number.isFinite(r[3])?r[3]:1,this.setState({outlineColor:r})),!t.sdf&&t.outlineWidth&&c.a.warn("".concat(this.id,": fontSettings.sdf is required to render outline"))()}},{key:"draw",value:function(e){var t=this.props,r=t.sdf,i=t.smoothing,s=t.outlineWidth,g=this.state.outlineColor;e.uniforms=Object(n.a)({},e.uniforms,{buffer:.75,outlineBuffer:s?Math.max(i,.75*(1-s)):-1,gamma:i,sdf:Boolean(r),outlineColor:g}),Object(a.a)(Object(o.a)(A.prototype),"draw",this).call(this,e)}},{key:"getInstanceOffset",value:function(e){var t=this;return e?Array.from(e).map((function(e){return Object(a.a)(Object(o.a)(A.prototype),"getInstanceOffset",t).call(t,e)})):l}},{key:"getInstanceColorMode",value:function(e){return 1}},{key:"getInstanceIconFrame",value:function(e){var t=this;return e?Array.from(e).map((function(e){return Object(a.a)(Object(o.a)(A.prototype),"getInstanceIconFrame",t).call(t,e)})):l}}]),A}(u.a);I.layerName="MultiIconLayer",I.defaultProps={getIconOffsets:{type:"accessor",value:function(e){return e.offsets}},alphaCutoff:.001,smoothing:.1,outlineWidth:0,outlineColor:{type:"color",value:[0,0,0,255]}}},function(e,t,A){"use strict";var n=A(6),r=A(7),i=A(1),o=A(4),a=A(77),s=A(9),g=A(10),c=function(e){Object(s.a)(A,e);var t=Object(g.a)(A);function A(){return Object(i.a)(this,A),t.apply(this,arguments)}return A}(A(199).a),u=A(411),l=A(161);A.d(t,"a",(function(){return I}));var I=function(){function e(t){Object(i.a)(this,e),this.gl=t,this.layerFilter=null,this.drawPickingColors=!1,this.drawLayersPass=new c(t),this.pickLayersPass=new u.a(t),this.renderCount=0,this._needsRedraw="Initial render",this.renderBuffers=[],this.lastPostProcessEffect=null}return Object(o.a)(e,[{key:"setProps",value:function(e){"layerFilter"in e&&this.layerFilter!==e.layerFilter&&(this.layerFilter=e.layerFilter,this._needsRedraw="layerFilter changed"),"drawPickingColors"in e&&this.drawPickingColors!==e.drawPickingColors&&(this.drawPickingColors=e.drawPickingColors,this._needsRedraw="drawPickingColors changed")}},{key:"renderLayers",value:function(e){var t=this.drawPickingColors?this.pickLayersPass:this.drawLayersPass;e.layerFilter=e.layerFilter||this.layerFilter,e.effects=e.effects||[],e.target=e.target||l.a.getDefaultFramebuffer(this.gl),this._preRender(e.effects,e);var A=this.lastPostProcessEffect?this.renderBuffers[0]:e.target,n=t.render(Object(r.a)({},e,{target:A}));this._postRender(e.effects,e),this.renderCount++,Object(a.a)("deckRenderer.renderLayers",this,n,e)}},{key:"needsRedraw",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{clearRedrawFlags:!1},t=this._needsRedraw;return e.clearRedrawFlags&&(this._needsRedraw=!1),t}},{key:"finalize",value:function(){var e,t=this.renderBuffers,A=Object(n.a)(t);try{for(A.s();!(e=A.n()).done;){e.value.delete()}}catch(r){A.e(r)}finally{A.f()}t.length=0}},{key:"_preRender",value:function(e,t){var A,r=null,i=Object(n.a)(e);try{for(i.s();!(A=i.n()).done;){var o=A.value;o.preRender(this.gl,t),o.postRender&&(r=o)}}catch(a){i.e(a)}finally{i.f()}r&&this._resizeRenderBuffers(),this.lastPostProcessEffect=r}},{key:"_resizeRenderBuffers",value:function(){var e=this.renderBuffers;0===e.length&&e.push(new l.a(this.gl),new l.a(this.gl));var t,A=Object(n.a)(e);try{for(A.s();!(t=A.n()).done;){t.value.resize()}}catch(r){A.e(r)}finally{A.f()}}},{key:"_postRender",value:function(e,t){var A,r=this.renderBuffers,i={inputBuffer:r[0],swapBuffer:r[1],target:null},o=Object(n.a)(e);try{for(o.s();!(A=o.n()).done;){var a=A.value;if(a.postRender){if(a===this.lastPostProcessEffect){i.target=t.target,a.postRender(this.gl,i);break}var s=a.postRender(this.gl,i);i.inputBuffer=s,i.swapBuffer=s===r[0]?r[1]:r[0]}}}catch(g){o.e(g)}finally{o.f()}}}]),e}()},function(e,t,A){"use strict";function n(e){if(Array.isArray(e))return e}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";function n(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";function n(e){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";var n=A(0),r=A.n(n).a.createContext(null);t.a=r},function(e,t,A){"use strict";function n(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";var n="function"===typeof Symbol&&Symbol.for;t.a=n?Symbol.for("mui.nested"):"__THEME_NESTED__"},function(e,t,A){"use strict";function n(e){if(Array.isArray(e))return e}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";function n(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return o}));A(137),A(14);var n=A(220),r=(A(13),A(174),{xs:0,sm:600,md:960,lg:1280,xl:1920}),i={keys:["xs","sm","md","lg","xl"],up:function(e){return"@media (min-width:".concat(r[e],"px)")}};function o(e,t,A){if(Array.isArray(t)){var r=e.theme.breakpoints||i;return t.reduce((function(e,n,i){return e[r.up(r.keys[i])]=A(t[i]),e}),{})}if("object"===Object(n.a)(t)){var o=e.theme.breakpoints||i;return Object.keys(t).reduce((function(e,n){return e[o.up(n)]=A(t[n]),e}),{})}return A(t)}},function(e,t,A){"use strict";t.a={mobileStepper:1e3,speedDial:1050,appBar:1100,drawer:1200,modal:1300,snackbar:1400,tooltip:1500}},function(e,t,A){"use strict";function n(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";A.d(t,"a",(function(){return u}));var n=A(1),r=A(4),i=A(9),o=A(10),a=A(206),s=A(33),g=A(32),c=A(97),u=function(e){Object(i.a)(A,e);var t=Object(o.a)(A);function A(){return Object(n.a)(this,A),t.apply(this,arguments)}return Object(r.a)(A,[{key:"toString",value:function(){var e="[";if(g.f.printRowMajor){e+="row-major:";for(var t=0;t1&&void 0!==arguments[1]?arguments[1]:new Array(this.RANK).fill(-0),A=e*this.RANK,n=0;n=0)}A.d(t,"a",(function(){return n}))}).call(this,A(90))},function(e,t,A){"use strict";A.d(t,"a",(function(){return r}));var n=A(18);function r(e,t,A,r){var i="See luma.gl ".concat(A," Upgrade Guide at https://luma.gl/docs/upgrade-guide"),o=Object.getPrototypeOf(e);r.forEach((function(e){o.methodName||(o[e]=function(){throw n.k.removed("Calling removed method ".concat(t,".").concat(e,": "),i)(),new Error(e)})}))}},function(e,t,A){"use strict";A.d(t,"a",(function(){return n}));function n(e){var t=r(e);return function(e){var t=r(e);if(!(t.byteLength>=24&&2303741511===t.getUint32(0,!1)))return null;return{mimeType:"image/png",width:t.getUint32(16,!1),height:t.getUint32(20,!1)}}(t)||function(e){var t=r(e);if(!(t.byteLength>=3&&65496===t.getUint16(0,!1)&&255===t.getUint8(2)))return null;var A=function(){for(var e=new Set([65499,65476,65484,65501,65534]),t=65504;t<65520;++t)e.add(t);var A=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:A}}(),n=A.tableMarkers,i=A.sofMarkers,o=2;for(;o+9=10&&1195984440===t.getUint32(0,!1)))return null;return{mimeType:"image/gif",width:t.getUint16(6,!0),height:t.getUint16(8,!0)}}(t)||function(e){var t=r(e);if(!(t.byteLength>=14&&16973===t.getUint16(0,!1)&&t.getUint32(2,!0)===t.byteLength))return null;return{mimeType:"image/bmp",width:t.getUint32(18,!0),height:t.getUint32(22,!0)}}(t)}function r(e){if(e instanceof DataView)return e;if(ArrayBuffer.isView(e))return new DataView(e.buffer);if(e instanceof ArrayBuffer)return new DataView(e);throw new Error("toDataView")}},function(e,t,A){"use strict";function n(e){for(var t=e.data,A=e.getIndex,n=e.dataRange,r=e.replace,i=n.startRow,o=void 0===i?0:i,a=n.endRow,s=void 0===a?1/0:a,g=t.length,c=g,u=g,l=0;ll&&I>=o&&(c=l),I>=s){u=l;break}}for(var C=c,h=u-c!==r.length,f=h&&t.slice(u),d=0;d1&&void 0!==arguments[1]?arguments[1]:{};Object(r.a)(this,e);var i=A.id,o=void 0===i?"pass":i;this.id=o,this.gl=t,this.props=Object(n.a)({},A)}return Object(i.a)(e,[{key:"setProps",value:function(e){Object.assign(this.props,e)}},{key:"render",value:function(){}},{key:"cleanup",value:function(){}}]),e}()},function(e,t,A){"use strict";A.d(t,"a",(function(){return C}));var n=A(7),r=A(1),i=A(4),o=A(16),a=A(17),s=A(9),g=A(10),c=A(199),u=A(18),l=A(41),I={blendFunc:[1,0,32771,0],blendEquation:32774},C=function(e){Object(s.a)(A,e);var t=Object(g.a)(A);function A(){return Object(r.a)(this,A),t.apply(this,arguments)}return Object(i.a)(A,[{key:"render",value:function(e){return e.pickingFBO?this._drawPickingBuffer(e):Object(a.a)(Object(o.a)(A.prototype),"render",this).call(this,e)}},{key:"_drawPickingBuffer",value:function(e){var t=this,r=e.layers,i=e.layerFilter,s=e.views,g=e.viewports,c=e.onViewportActive,l=e.pickingFBO,C=e.deviceRect,f=C.x,d=C.y,B=C.width,p=C.height,E=e.pass,Q=void 0===E?"picking":E,y=e.redrawReason,v=e.pickZ,m=this.gl;this.pickZ=v;var b=!v&&{byLayer:new Map,byAlpha:[]};this._colors=b;var w=Object(u.o)(m,Object(n.a)({scissorTest:!0,scissor:[f,d,B,p],clearColor:[0,0,0,0],depthMask:!0,depthTest:!0,depthRange:[0,1],colorMask:[!0,!0,!0,!0]},I,{blend:!v}),(function(){return Object(a.a)(Object(o.a)(A.prototype),"render",t).call(t,{target:l,layers:r,layerFilter:i,views:s,viewports:g,onViewportActive:c,pass:Q,redrawReason:y})}));return this._colors=null,{decodePickingColor:b&&h.bind(null,b),stats:w}}},{key:"shouldDrawLayer",value:function(e){return e.props.pickable}},{key:"getModuleParameters",value:function(){return{pickingActive:1,pickingAttribute:this.pickZ,lightSources:{}}}},{key:"getLayerParameters",value:function(e,t,A){var r=Object(n.a)({},e.props.parameters);return this.pickZ?r.blend=!1:(Object.assign(r,I),r.blend=!0,r.blendColor=function(e,t,A){var n,r=e.byLayer,i=e.byAlpha;if(r.has(t)){var o=r.get(t);o.viewports.push(A),n=o.a}else if((n=r.size+1)<=255){var a={a:n,layer:t,viewports:[A]};r.set(t,a),i[n]=a}else l.a.warn("Too many pickable layers, only picking the first 255")(),n=0;return[0,0,0,n/255]}(this._colors,e,A)),r}}]),A}(c.a);function h(e,t){var A=e.byAlpha[t[3]];return A&&{pickedLayer:A.layer,pickedViewports:A.viewports,pickedObjectIndex:A.layer.decodePickingColor(t)}}},function(e,t,A){var n;!function(r){var i=/^\s+/,o=/\s+$/,a=0,s=r.round,g=r.min,c=r.max,u=r.random;function l(e,t){if(t=t||{},(e=e||"")instanceof l)return e;if(!(this instanceof l))return new l(e,t);var A=function(e){var t={r:0,g:0,b:0},A=1,n=null,a=null,s=null,u=!1,l=!1;"string"==typeof e&&(e=function(e){e=e.replace(i,"").replace(o,"").toLowerCase();var t,A=!1;if(D[e])e=D[e],A=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(t=T.rgb.exec(e))return{r:t[1],g:t[2],b:t[3]};if(t=T.rgba.exec(e))return{r:t[1],g:t[2],b:t[3],a:t[4]};if(t=T.hsl.exec(e))return{h:t[1],s:t[2],l:t[3]};if(t=T.hsla.exec(e))return{h:t[1],s:t[2],l:t[3],a:t[4]};if(t=T.hsv.exec(e))return{h:t[1],s:t[2],v:t[3]};if(t=T.hsva.exec(e))return{h:t[1],s:t[2],v:t[3],a:t[4]};if(t=T.hex8.exec(e))return{r:U(t[1]),g:U(t[2]),b:U(t[3]),a:L(t[4]),format:A?"name":"hex8"};if(t=T.hex6.exec(e))return{r:U(t[1]),g:U(t[2]),b:U(t[3]),format:A?"name":"hex"};if(t=T.hex4.exec(e))return{r:U(t[1]+""+t[1]),g:U(t[2]+""+t[2]),b:U(t[3]+""+t[3]),a:L(t[4]+""+t[4]),format:A?"name":"hex8"};if(t=T.hex3.exec(e))return{r:U(t[1]+""+t[1]),g:U(t[2]+""+t[2]),b:U(t[3]+""+t[3]),format:A?"name":"hex"};return!1}(e));"object"==typeof e&&(Z(e.r)&&Z(e.g)&&Z(e.b)?(I=e.r,C=e.g,h=e.b,t={r:255*x(I,255),g:255*x(C,255),b:255*x(h,255)},u=!0,l="%"===String(e.r).substr(-1)?"prgb":"rgb"):Z(e.h)&&Z(e.s)&&Z(e.v)?(n=M(e.s),a=M(e.v),t=function(e,t,A){e=6*x(e,360),t=x(t,100),A=x(A,100);var n=r.floor(e),i=e-n,o=A*(1-t),a=A*(1-i*t),s=A*(1-(1-i)*t),g=n%6;return{r:255*[A,a,o,o,s,A][g],g:255*[s,A,A,a,o,o][g],b:255*[o,o,s,A,A,a][g]}}(e.h,n,a),u=!0,l="hsv"):Z(e.h)&&Z(e.s)&&Z(e.l)&&(n=M(e.s),s=M(e.l),t=function(e,t,A){var n,r,i;function o(e,t,A){return A<0&&(A+=1),A>1&&(A-=1),A<1/6?e+6*(t-e)*A:A<.5?t:A<2/3?e+(t-e)*(2/3-A)*6:e}if(e=x(e,360),t=x(t,100),A=x(A,100),0===t)n=r=i=A;else{var a=A<.5?A*(1+t):A+t-A*t,s=2*A-a;n=o(s,a,e+1/3),r=o(s,a,e),i=o(s,a,e-1/3)}return{r:255*n,g:255*r,b:255*i}}(e.h,n,s),u=!0,l="hsl"),e.hasOwnProperty("a")&&(A=e.a));var I,C,h;return A=k(A),{ok:u,format:e.format||l,r:g(255,c(t.r,0)),g:g(255,c(t.g,0)),b:g(255,c(t.b,0)),a:A}}(e);this._originalInput=e,this._r=A.r,this._g=A.g,this._b=A.b,this._a=A.a,this._roundA=s(100*this._a)/100,this._format=t.format||A.format,this._gradientType=t.gradientType,this._r<1&&(this._r=s(this._r)),this._g<1&&(this._g=s(this._g)),this._b<1&&(this._b=s(this._b)),this._ok=A.ok,this._tc_id=a++}function I(e,t,A){e=x(e,255),t=x(t,255),A=x(A,255);var n,r,i=c(e,t,A),o=g(e,t,A),a=(i+o)/2;if(i==o)n=r=0;else{var s=i-o;switch(r=a>.5?s/(2-i-o):s/(i+o),i){case e:n=(t-A)/s+(t>1)+720)%360;--t;)n.h=(n.h+r)%360,i.push(l(n));return i}function R(e,t){t=t||6;for(var A=l(e).toHsv(),n=A.h,r=A.s,i=A.v,o=[],a=1/t;t--;)o.push(l({h:n,s:r,v:i})),i=(i+a)%1;return o}l.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var e,t,A,n=this.toRgb();return e=n.r/255,t=n.g/255,A=n.b/255,.2126*(e<=.03928?e/12.92:r.pow((e+.055)/1.055,2.4))+.7152*(t<=.03928?t/12.92:r.pow((t+.055)/1.055,2.4))+.0722*(A<=.03928?A/12.92:r.pow((A+.055)/1.055,2.4))},setAlpha:function(e){return this._a=k(e),this._roundA=s(100*this._a)/100,this},toHsv:function(){var e=C(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=C(this._r,this._g,this._b),t=s(360*e.h),A=s(100*e.s),n=s(100*e.v);return 1==this._a?"hsv("+t+", "+A+"%, "+n+"%)":"hsva("+t+", "+A+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var e=I(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=I(this._r,this._g,this._b),t=s(360*e.h),A=s(100*e.s),n=s(100*e.l);return 1==this._a?"hsl("+t+", "+A+"%, "+n+"%)":"hsla("+t+", "+A+"%, "+n+"%, "+this._roundA+")"},toHex:function(e){return h(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,A,n,r){var i=[_(s(e).toString(16)),_(s(t).toString(16)),_(s(A).toString(16)),_(O(n))];if(r&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)&&i[3].charAt(0)==i[3].charAt(1))return i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0)+i[3].charAt(0);return i.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:s(this._r),g:s(this._g),b:s(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+s(this._r)+", "+s(this._g)+", "+s(this._b)+")":"rgba("+s(this._r)+", "+s(this._g)+", "+s(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:s(100*x(this._r,255))+"%",g:s(100*x(this._g,255))+"%",b:s(100*x(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+s(100*x(this._r,255))+"%, "+s(100*x(this._g,255))+"%, "+s(100*x(this._b,255))+"%)":"rgba("+s(100*x(this._r,255))+"%, "+s(100*x(this._g,255))+"%, "+s(100*x(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(G[h(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+f(this._r,this._g,this._b,this._a),A=t,n=this._gradientType?"GradientType = 1, ":"";if(e){var r=l(e);A="#"+f(r._r,r._g,r._b,r._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+t+",endColorstr="+A+")"},toString:function(e){var t=!!e;e=e||this._format;var A=!1,n=this._a<1&&this._a>=0;return t||!n||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(A=this.toRgbString()),"prgb"===e&&(A=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(A=this.toHexString()),"hex3"===e&&(A=this.toHexString(!0)),"hex4"===e&&(A=this.toHex8String(!0)),"hex8"===e&&(A=this.toHex8String()),"name"===e&&(A=this.toName()),"hsl"===e&&(A=this.toHslString()),"hsv"===e&&(A=this.toHsvString()),A||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return l(this.toString())},_applyModification:function(e,t){var A=e.apply(null,[this].concat([].slice.call(t)));return this._r=A._r,this._g=A._g,this._b=A._b,this.setAlpha(A._a),this},lighten:function(){return this._applyModification(E,arguments)},brighten:function(){return this._applyModification(Q,arguments)},darken:function(){return this._applyModification(y,arguments)},desaturate:function(){return this._applyModification(d,arguments)},saturate:function(){return this._applyModification(B,arguments)},greyscale:function(){return this._applyModification(p,arguments)},spin:function(){return this._applyModification(v,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(F,arguments)},complement:function(){return this._applyCombination(m,arguments)},monochromatic:function(){return this._applyCombination(R,arguments)},splitcomplement:function(){return this._applyCombination(S,arguments)},triad:function(){return this._applyCombination(b,arguments)},tetrad:function(){return this._applyCombination(w,arguments)}},l.fromRatio=function(e,t){if("object"==typeof e){var A={};for(var n in e)e.hasOwnProperty(n)&&(A[n]="a"===n?e[n]:M(e[n]));e=A}return l(e,t)},l.equals=function(e,t){return!(!e||!t)&&l(e).toRgbString()==l(t).toRgbString()},l.random=function(){return l.fromRatio({r:u(),g:u(),b:u()})},l.mix=function(e,t,A){A=0===A?0:A||50;var n=l(e).toRgb(),r=l(t).toRgb(),i=A/100;return l({r:(r.r-n.r)*i+n.r,g:(r.g-n.g)*i+n.g,b:(r.b-n.b)*i+n.b,a:(r.a-n.a)*i+n.a})},l.readability=function(e,t){var A=l(e),n=l(t);return(r.max(A.getLuminance(),n.getLuminance())+.05)/(r.min(A.getLuminance(),n.getLuminance())+.05)},l.isReadable=function(e,t,A){var n,r,i=l.readability(e,t);switch(r=!1,(n=function(e){var t,A;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),A=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==A&&"large"!==A&&(A="small");return{level:t,size:A}}(A)).level+n.size){case"AAsmall":case"AAAlarge":r=i>=4.5;break;case"AAlarge":r=i>=3;break;case"AAAsmall":r=i>=7}return r},l.mostReadable=function(e,t,A){var n,r,i,o,a=null,s=0;r=(A=A||{}).includeFallbackColors,i=A.level,o=A.size;for(var g=0;gs&&(s=n,a=l(t[g]));return l.isReadable(e,a,{level:i,size:o})||!r?a:(A.includeFallbackColors=!1,l.mostReadable(e,["#fff","#000"],A))};var D=l.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},G=l.hexNames=function(e){var t={};for(var A in e)e.hasOwnProperty(A)&&(t[e[A]]=A);return t}(D);function k(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function x(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var A=function(e){return"string"===typeof e&&-1!=e.indexOf("%")}(e);return e=g(t,c(0,parseFloat(e))),A&&(e=parseInt(e*t,10)/100),r.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function N(e){return g(1,c(0,e))}function U(e){return parseInt(e,16)}function _(e){return 1==e.length?"0"+e:""+e}function M(e){return e<=1&&(e=100*e+"%"),e}function O(e){return r.round(255*parseFloat(e)).toString(16)}function L(e){return U(e)/255}var T=function(){var e="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)",t="[\\s|\\(]+("+e+")[,|\\s]+("+e+")[,|\\s]+("+e+")\\s*\\)?",A="[\\s|\\(]+("+e+")[,|\\s]+("+e+")[,|\\s]+("+e+")[,|\\s]+("+e+")\\s*\\)?";return{CSS_UNIT:new RegExp(e),rgb:new RegExp("rgb"+t),rgba:new RegExp("rgba"+A),hsl:new RegExp("hsl"+t),hsla:new RegExp("hsla"+A),hsv:new RegExp("hsv"+t),hsva:new RegExp("hsva"+A),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();function Z(e){return!!T.CSS_UNIT.exec(e)}e.exports?e.exports=l:void 0===(n=function(){return l}.call(t,A,t,e))||(e.exports=n)}(Math)},function(e,t,A){"use strict";var n=A(195),r={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},i={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},o={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},a={};function s(e){return n.isMemo(e)?o:a[e.$$typeof]||r}a[n.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},a[n.Memo]=o;var g=Object.defineProperty,c=Object.getOwnPropertyNames,u=Object.getOwnPropertySymbols,l=Object.getOwnPropertyDescriptor,I=Object.getPrototypeOf,C=Object.prototype;e.exports=function e(t,A,n){if("string"!==typeof A){if(C){var r=I(A);r&&r!==C&&e(t,r,n)}var o=c(A);u&&(o=o.concat(u(A)));for(var a=s(t),h=s(A),f=0;f div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; z-index: -1; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',n=e.head||e.getElementsByTagName("head")[0],r=e.createElement("style");r.id="detectElementResize",r.type="text/css",null!=t&&r.setAttribute("nonce",t),r.styleSheet?r.styleSheet.cssText=A:r.appendChild(e.createTextNode(A)),n.appendChild(r)}}(i),e.__resizeLast__={},e.__resizeListeners__=[],(e.__resizeTriggers__=i.createElement("div")).className="resize-triggers",e.__resizeTriggers__.innerHTML='
',e.appendChild(e.__resizeTriggers__),a(e),e.addEventListener("scroll",s,!0),u&&(e.__resizeTriggers__.__animationListener__=function(t){t.animationName==f&&a(e)},e.__resizeTriggers__.addEventListener(u,e.__resizeTriggers__.__animationListener__))}e.__resizeListeners__.push(A)}},removeResizeListener:function(e,t){if(r)e.detachEvent("onresize",t);else if(e.__resizeListeners__.splice(e.__resizeListeners__.indexOf(t),1),!e.__resizeListeners__.length){e.removeEventListener("scroll",s,!0),e.__resizeTriggers__.__animationListener__&&(e.__resizeTriggers__.removeEventListener(u,e.__resizeTriggers__.__animationListener__),e.__resizeTriggers__.__animationListener__=null);try{e.__resizeTriggers__=!e.removeChild(e.__resizeTriggers__)}catch(A){}}}}}A.d(t,"a",(function(){return n}))}).call(this,A(86))},function(e,t,A){"use strict";t.__esModule=!0,t.default=function(e,t){var A={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(A[n]=e[n]);return A}},function(e,t,A){"use strict";var n=A(0),r=n.createContext();t.a=r},function(e,t,A){"use strict";var n=A(0),r=n.createContext({});t.a=r},function(e,t,A){"use strict";var n=A(95),r=A(129);Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=r(A(0)),o=(0,n(A(130)).default)(i.createElement("path",{d:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"}),"Add");t.default=o},function(e,t,A){"use strict";A.d(t,"a",(function(){return c}));var n=A(1),r=A(4),i=A(6),o=A(5);function a(e,t){return JSON.stringify(e,function(e){var t=[];return function(A,n){if("object"!==typeof n||null===n)return n;var r=t.indexOf(this)+1;return t.length=r,t.length>e?"[Object]":t.indexOf(n)>=0?"[Circular]":(t.push(n),n)}}(t))}var s="vg-tooltip-element",g={offsetX:10,offsetY:10,id:s,styleId:"vega-tooltip-style",theme:"light",disableDefaultStyle:!1,sanitize:function(e){return String(e).replace(/&/g,"&").replace(/")),g&&(n+=''));var u=Object.keys(c);if(u.length>0){n+="";var l,I=Object(i.a)(u);try{for(I.s();!(l=I.n()).done;){var C=l.value,h=c[C];void 0!==h&&(Object(o.H)(h)&&(h=a(h,A)),n+='"))}}catch(f){I.e(f)}finally{I.f()}n+="
'.concat(t(C),':').concat(t(h),"
"}return n||"{}"}return t(e)}};var c=function(){function e(t){Object(n.a)(this,e),this.options=Object.assign(Object.assign({},g),t);var A=this.options.id;if(this.el=null,this.call=this.tooltipHandler.bind(this),!this.options.disableDefaultStyle&&!document.getElementById(this.options.styleId)){var r=document.createElement("style");r.setAttribute("id",this.options.styleId),r.innerHTML=function(e){if(!/^[A-Za-z]+[-:.\w]*$/.test(e))throw new Error("Invalid HTML ID");return"#vg-tooltip-element {\n visibility: hidden;\n padding: 8px;\n position: fixed;\n z-index: 1000;\n font-family: sans-serif;\n font-size: 11px;\n border-radius: 3px;\n box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);\n /* The default theme is the light theme. */\n background-color: rgba(255, 255, 255, 0.95);\n border: 1px solid #d9d9d9;\n color: black; }\n #vg-tooltip-element.visible {\n visibility: visible; }\n #vg-tooltip-element h2 {\n margin-top: 0;\n margin-bottom: 10px;\n font-size: 13px; }\n #vg-tooltip-element img {\n max-width: 200px;\n max-height: 200px; }\n #vg-tooltip-element table {\n border-spacing: 0; }\n #vg-tooltip-element table tr {\n border: none; }\n #vg-tooltip-element table tr td {\n overflow: hidden;\n text-overflow: ellipsis;\n padding-top: 2px;\n padding-bottom: 2px; }\n #vg-tooltip-element table tr td.key {\n color: #808080;\n max-width: 150px;\n text-align: right;\n padding-right: 4px; }\n #vg-tooltip-element table tr td.value {\n display: block;\n max-width: 300px;\n max-height: 7em;\n text-align: left; }\n #vg-tooltip-element.dark-theme {\n background-color: rgba(32, 32, 32, 0.9);\n border: 1px solid #f5f5f5;\n color: white; }\n #vg-tooltip-element.dark-theme td.key {\n color: #bfbfbf; }\n".toString().replace(s,e)}(A);var i=document.head;i.childNodes.length>0?i.insertBefore(r,i.childNodes[0]):i.appendChild(r)}}return Object(r.a)(e,[{key:"tooltipHandler",value:function(e,t,A,n){var r;if(this.el=document.getElementById(this.options.id),this.el||(this.el=document.createElement("div"),this.el.setAttribute("id",this.options.id),this.el.classList.add("vg-tooltip"),document.body.appendChild(this.el)),(null!==(r=document.fullscreenElement)&&void 0!==r?r:document.body).appendChild(this.el),null!=n&&""!==n){this.el.innerHTML=this.options.formatTooltip(n,this.options.sanitize,this.options.maxDepth),this.el.classList.add("visible","".concat(this.options.theme,"-theme"));var i=function(e,t,A,n){var r=e.clientX+A;r+t.width>window.innerWidth&&(r=+e.clientX-A-t.width);var i=e.clientY+n;return i+t.height>window.innerHeight&&(i=+e.clientY-n-t.height),{x:r,y:i}}(t,this.el.getBoundingClientRect(),this.options.offsetX,this.options.offsetY),o=i.x,a=i.y;this.el.setAttribute("style","top: ".concat(a,"px; left: ").concat(o,"px"))}else this.el.classList.remove("visible","".concat(this.options.theme,"-theme"))}}]),e}()},function(e,t,A){"use strict";var n=A(3),r=A.n(n),i=A(12),o=A(7),a={name:"Draco",id:"draco",module:"draco",version:"3.0.12",worker:!0,extensions:["drc"],mimeTypes:["application/octet-stream"],binary:!0,tests:["DRACO"],options:{draco:{decoderType:"object"===typeof WebAssembly?"wasm":"js",libraryPath:"libs/",extraAttributes:{},attributeNameEntry:void 0}}},s=A(6),g=A(11),c=A(8),u=A(1),l=A(4),I=A(25);function C(e){for(var t=1/0,A=1/0,n=1/0,r=-1/0,i=-1/0,o=-1/0,a=e.POSITION?e.POSITION.value:[],s=a&&a.length,g=0;gr?c:r,i=u>i?u:i,o=l>o?l:o}return[[t,A,n],[r,i,o]]}var h=function(){function e(t,A){Object(u.a)(this,e),Object(I.a)(this,"fields",void 0),Object(I.a)(this,"metadata",void 0),function(e,t){if(!e)throw new Error(t||"loader assertion failed.")}(Array.isArray(t)),function(e){var t,A={},n=Object(s.a)(e);try{for(n.s();!(t=n.n()).done;){var r=t.value;A[r.name]&&console.warn("Schema: duplicated field name",r.name,r),A[r.name]=!0}}catch(i){n.e(i)}finally{n.f()}}(t),this.fields=t,this.metadata=A||new Map}return Object(l.a)(e,[{key:"compareTo",value:function(e){if(this.metadata!==e.metadata)return!1;if(this.fields.length!==e.fields.length)return!1;for(var t=0;t")}},{key:"typeId",get:function(){return d.FixedSizeList}},{key:"valueType",get:function(){return this.children[0].type}},{key:"valueField",get:function(){return this.children[0]}},{key:E,get:function(){return"FixedSizeList"}}]),A}(m);var O=function(){function e(t,A){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:new Map;Object(u.a)(this,e),Object(I.a)(this,"name",void 0),Object(I.a)(this,"type",void 0),Object(I.a)(this,"nullable",void 0),Object(I.a)(this,"metadata",void 0),this.name=t,this.type=A,this.nullable=n,this.metadata=r}return Object(l.a)(e,[{key:"clone",value:function(){return new e(this.name,this.type,this.nullable,this.metadata)}},{key:"compareTo",value:function(e){return this.name===e.name&&this.type===e.type&&this.nullable===e.nullable&&this.metadata===e.metadata}},{key:"toString",value:function(){return"".concat(this.type).concat(this.nullable?", nullable":"").concat(this.metadata?", metadata: ".concat(this.metadata):"")}},{key:"typeId",get:function(){return this.type&&this.type.typeId}}]),e}();function L(e,t,A){var n=Z(t.metadata),r=[],i=function(e){var t={};for(var A in e){var n=e[A];t[n.name||"undefined"]=n}return t}(t.attributes);for(var o in e){var a=T(o,e[o],i[o]);r.push(a)}if(A){var s=T("indices",A);r.push(s)}return new h(r,n)}function T(e,t,A){var n=A?Z(A.metadata):void 0,r=function(e){switch(e.constructor){case Int8Array:return new w;case Uint8Array:return new R;case Int16Array:return new S;case Uint16Array:return new D;case Int32Array:return new F;case Uint32Array:return new G;case Float32Array:return new U;case Float64Array:return new _;default:throw new Error("array type not supported")}}(t.value);return new O(e,new M(t.size,new O("value",r)),!1,n)}function Z(e){var t=new Map;for(var A in e)t.set("".concat(A,".string"),JSON.stringify(e[A]));return t}var H={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},Y={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array},J=function(){function e(t){Object(u.a)(this,e),Object(I.a)(this,"draco",void 0),Object(I.a)(this,"decoder",void 0),Object(I.a)(this,"metadataQuerier",void 0),this.draco=t,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}return Object(l.a)(e,[{key:"destroy",value:function(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}},{key:"parseSync",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=new this.draco.DecoderBuffer;A.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(t);var n=this.decoder.GetEncodedGeometryType(A),r=n===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{var i;switch(n){case this.draco.TRIANGULAR_MESH:i=this.decoder.DecodeBufferToMesh(A,r);break;case this.draco.POINT_CLOUD:i=this.decoder.DecodeBufferToPointCloud(A,r);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!i.ok()||!r.ptr){var a="DRACO decompression failed: ".concat(i.error_msg());throw new Error(a)}var s=this._getDracoLoaderData(r,n,t),g=this._getMeshData(r,s,t),c=C(g.attributes),u=L(g.attributes,s,g.indices),l=Object(o.a)({loader:"draco",loaderData:s,header:{vertexCount:r.num_points(),boundingBox:c}},g,{schema:u});return l}finally{this.draco.destroy(A),r&&this.draco.destroy(r)}}},{key:"_getDracoLoaderData",value:function(e,t,A){var n=this._getTopLevelMetadata(e),r=this._getDracoAttributes(e,A);return{geometry_type:t,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:n,attributes:r}}},{key:"_getDracoAttributes",value:function(e,t){for(var A={},n=0;n1&&void 0!==i[1]?i[1]:null,n=i.length>2&&void 0!==i[2]?i[2]:{},A&&(t=q(t,A,n)),K[t]=K[t]||z(t),e.next=6,K[t];case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function q(e,t,A){if(e.startsWith("http"))return e;var n=A.modules||{};return n[e]?n[e]:j.b?A.CDN?(Object(V.a)(A.CDN.startsWith("http")),"".concat(A.CDN,"/").concat(t,"@").concat("3.0.12","/dist/libs/").concat(e)):j.d?"../src/libs/".concat(e):"modules/".concat(t,"/src/libs/").concat(e):"modules/".concat(t,"/dist/libs/").concat(e)}function z(e){return $.apply(this,arguments)}function $(){return($=Object(i.a)(r.a.mark((function e(t){var A,n,i;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.endsWith("wasm")){e.next=7;break}return e.next=3,fetch(t);case 3:return A=e.sent,e.next=6,A.arrayBuffer();case 6:return e.abrupt("return",e.sent);case 7:if(j.b){e.next=14;break}if(e.t0=P.requireFromFile,!e.t0){e.next=13;break}return e.next=12,P.requireFromFile(t);case 12:e.t0=e.sent;case 13:return e.abrupt("return",e.t0);case 14:if(!j.d){e.next=16;break}return e.abrupt("return",importScripts(t));case 16:return e.next=18,fetch(t);case 18:return n=e.sent,e.next=21,n.text();case 21:return i=e.sent,e.abrupt("return",ee(i,t));case 23:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ee(e,t){if(!j.b)return P.requireFromString&&P.requireFromString(e,t);if(j.d)return eval.call(j.a,e),null;var A=document.createElement("script");A.id=t;try{A.appendChild(document.createTextNode(e))}catch(n){A.text=e}return document.body.appendChild(A),null}var te,Ae="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.js"),ne="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_wasm_wrapper.js"),re="https://www.gstatic.com/draco/versioned/decoders/".concat("1.4.1","/draco_decoder.wasm");"https://raw.githubusercontent.com/google/draco/".concat("1.4.1","/javascript/draco_encoder.js");function ie(e){return oe.apply(this,arguments)}function oe(){return(oe=Object(i.a)(r.a.mark((function e(t){var A;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return A=t.modules||{},te=A.draco3d?te||A.draco3d.createDecoderModule({}).then((function(e){return{draco:e}})):te||ae(t),e.next=4,te;case 4:return e.abrupt("return",e.sent);case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ae(e){return se.apply(this,arguments)}function se(){return(se=Object(i.a)(r.a.mark((function e(t){var A,n,i,o;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:e.t0=t.draco&&t.draco.decoderType,e.next="js"===e.t0?3:(e.t0,7);break;case 3:return e.next=5,W(Ae,"draco",t);case 5:return A=e.sent,e.abrupt("break",21);case 7:return e.t1=Promise,e.next=10,W(ne,"draco",t);case 10:return e.t2=e.sent,e.next=13,W(re,"draco",t);case 13:return e.t3=e.sent,e.t4=[e.t2,e.t3],e.next=17,e.t1.all.call(e.t1,e.t4);case 17:i=e.sent,o=Object(c.a)(i,2),A=o[0],n=o[1];case 21:return A=A||globalThis.DracoDecoderModule,e.next=24,ge(A,n);case 24:return e.abrupt("return",e.sent);case 25:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ge(e,t){var A={};return t&&(A.wasmBinary=t),new Promise((function(t){e(Object(o.a)({},A,{onModuleLoaded:function(e){return t({draco:e})}}))}))}A.d(t,"a",(function(){return ce}));var ce=Object(o.a)({},a,{parse:function(e,t){return ue.apply(this,arguments)}});function ue(){return(ue=Object(i.a)(r.a.mark((function e(t,A){var n,i,o;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ie(A);case 2:return n=e.sent,i=n.draco,o=new J(i),e.prev=5,e.abrupt("return",o.parseSync(t,null===A||void 0===A?void 0:A.draco));case 7:return e.prev=7,o.destroy(),e.finish(7);case 10:case"end":return e.stop()}}),e,null,[[5,,7,10]])})))).apply(this,arguments)}},function(e,t,A){"use strict";var n=A(2),r=A(1),i=A(4),o=A(18),a=A(528),s=A(108),g=A(26),c=A(428),u=A(1288),l=A(139),I=A(80),C=A(24),h=A(16),f=A(17),d=A(9),B=A(10),p=A(92),E=null;function Q(e,t){var A;return new e((A=e.BYTES_PER_ELEMENT*t,(!E||E.byteLength-1)return"Edge";var n=-1!==A.indexOf("MSIE "),r=-1!==A.indexOf("Trident/");return n||r?"IE":y.b.chrome?"Chrome":y.b.safari?"Safari":y.b.mozInnerScreenX?"Firefox":"Unknown"}var w="elements must be GL.ELEMENT_ARRAY_BUFFER",S=function(e){Object(d.a)(A,e);var t=Object(B.a)(A);function A(e){var n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object(r.a)(this,A);var o=i.id||i.program&&i.program.id;return(n=t.call(this,e,Object.assign({},i,{id:o}))).buffer=null,n.bufferValue=null,n.isDefaultArray=i.isDefaultArray||!1,n.gl2=e,n.initialize(i),Object.seal(Object(C.a)(n)),n}return Object(i.a)(A,null,[{key:"isSupported",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return!t.constantAttributeZero||(Object(o.j)(e)||"Chrome"===b())}},{key:"getDefaultArray",value:function(e){return e.luma=e.luma||{},e.luma.defaultVertexArray||(e.luma.defaultVertexArray=new A(e,{handle:null,isDefaultArray:!0})),e.luma.defaultVertexArray}},{key:"getMaxAttributes",value:function(e){return A.MAX_ATTRIBUTES=A.MAX_ATTRIBUTES||e.getParameter(34921),A.MAX_ATTRIBUTES}},{key:"setConstant",value:function(e,t,n){switch(n.constructor){case Float32Array:A._setConstantFloatArray(e,t,n);break;case Int32Array:A._setConstantIntArray(e,t,n);break;case Uint32Array:A._setConstantUintArray(e,t,n);break;default:Object(g.a)(!1)}}}]),Object(i.a)(A,[{key:"delete",value:function(){return Object(f.a)(Object(h.a)(A.prototype),"delete",this).call(this),this.buffer&&this.buffer.delete(),this}},{key:"initialize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.setProps(e)}},{key:"setProps",value:function(e){return this}},{key:"setElementBuffer",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Object(g.a)(!t||34963===t.target,w),this.bind((function(){e.gl.bindBuffer(34963,t?t.handle:null)})),this}},{key:"setBuffer",value:function(e,t,A){if(34963===t.target)return this.setElementBuffer(t,A);var n=A.size,r=A.type,i=A.stride,a=A.offset,s=A.normalized,c=A.integer,u=A.divisor,l=this.gl,I=this.gl2;return e=Number(e),this.bind((function(){l.bindBuffer(34962,t.handle),c?(Object(g.a)(Object(o.j)(l)),I.vertexAttribIPointer(e,n,r,i,a)):l.vertexAttribPointer(e,n,r,s,i,a),l.enableVertexAttribArray(e),I.vertexAttribDivisor(e,u||0)})),this}},{key:"enable",value:function(e){var t=this,n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=!n&&0===e&&!A.isSupported(this.gl,{constantAttributeZero:!0});return r||(e=Number(e),this.bind((function(){return n?t.gl.enableVertexAttribArray(e):t.gl.disableVertexAttribArray(e)}))),this}},{key:"getConstantBuffer",value:function(e,t){var A=this._normalizeConstantArrayValue(t),n=A.byteLength*e,r=A.length*e,i=!this.buffer;if(this.buffer=this.buffer||new I.a(this.gl,n),i=(i=i||this.buffer.reallocate(n))||!this._compareConstantArrayValues(A,this.bufferValue)){var o=Q(t.constructor,r);!function(e){for(var t=e.target,A=e.source,n=e.start,r=void 0===n?0:n,i=e.count,o=void 0===i?1:i,a=A.length,s=o*a,g=0,c=r;g1&&void 0!==arguments[1]?arguments[1]:{};Object(r.a)(this,e);var n=A.id||A.program&&A.program.id;this.id=n,this.gl=t,this.configuration=null,this.elements=null,this.elementsAccessor=null,this.values=null,this.accessors=null,this.unused=null,this.drawParams=null,this.buffer=null,this.attributes={},this.vertexArrayObject=new S(t),Object(F.a)(this,"VertexArray","v6.0",D),this.initialize(A),Object.seal(this)}return Object(i.a)(e,[{key:"delete",value:function(){this.buffer&&this.buffer.delete(),this.vertexArrayObject.delete()}},{key:"initialize",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.reset(),this.configuration=null,this.bindOnUse=!1,this.setProps(e)}},{key:"reset",value:function(){this.elements=null,this.elementsAccessor=null;var e=this.vertexArrayObject.MAX_ATTRIBUTES;return this.values=new Array(e).fill(null),this.accessors=new Array(e).fill(null),this.unused={},this.drawParams=null,this}},{key:"setProps",value:function(e){return"program"in e&&(this.configuration=e.program&&e.program.configuration),"configuration"in e&&(this.configuration=e.configuration),"attributes"in e&&this.setAttributes(e.attributes),"elements"in e&&this.setElementBuffer(e.elements),"bindOnUse"in e&&(e=e.bindOnUse),this}},{key:"clearDrawParams",value:function(){this.drawParams=null}},{key:"getDrawParams",value:function(){return this.drawParams=this.drawParams||this._updateDrawParams(),this.drawParams}},{key:"setAttributes",value:function(e){var t=this;return Object.assign(this.attributes,e),this.vertexArrayObject.bind((function(){for(var A in e){var n=e[A];t._setAttribute(A,n)}t.gl.bindBuffer(34962,null)})),this}},{key:"setElementBuffer",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.elements=e,this.elementsAccessor=t,this.clearDrawParams(),this.vertexArrayObject.setElementBuffer(e,t),this}},{key:"setBuffer",value:function(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(34963===t.target)return this.setElementBuffer(t,A);var n=this._resolveLocationAndAccessor(e,t,t.accessor,A),r=n.location,i=n.accessor;return r>=0&&(this.values[r]=t,this.accessors[r]=i,this.clearDrawParams(),this.vertexArrayObject.setBuffer(r,t,i)),this}},{key:"setConstant",value:function(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this._resolveLocationAndAccessor(e,t,Object.assign({size:t.length},A)),r=n.location,i=n.accessor;return r>=0&&(t=this.vertexArrayObject._normalizeConstantArrayValue(t),this.values[r]=t,this.accessors[r]=i,this.clearDrawParams(),this.vertexArrayObject.enable(r,!1)),this}},{key:"unbindBuffers",value:function(){var e=this;return this.vertexArrayObject.bind((function(){e.elements&&e.vertexArrayObject.setElementBuffer(null),e.buffer=e.buffer||new I.a(e.gl,{accessor:{size:4}});for(var t=0;t0;if(e.isInstanced=e.isInstanced||r,A instanceof I.a){var i=A;if(r){var o=i.getVertexCount(n);e.instanceCount=Math.min(e.instanceCount,o)}else{var a=i.getVertexCount(n);e.vertexCount=Math.min(e.vertexCount,a)}}}}},{key:"setElements",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return o.k.deprecated("setElements","setElementBuffer")(),this.setElementBuffer(e,t)}}]),e}(),k=A(1246),x=A(109),N=A(175);function U(e,t){for(var A=t.maxElts,n=void 0===A?16:A,r=t.size,i=void 0===r?1:r,o="[",a=0;a0&&(o+=",".concat(a%i===0?" ":"")),o+=_(e[a],t);var s=e.length>n?"...":"]";return"".concat(o).concat(s)}function _(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=1e-16,n=t.isInteger,r=void 0!==n&&n;if(Array.isArray(e)||ArrayBuffer.isView(e))return U(e,t);if(!Number.isFinite(e))return String(e);if(Math.abs(e)100&&Math.abs(e)<1e4)return e.toFixed(0);var i=e.toPrecision(2),o=i.indexOf(".0");return o===i.length-2?i.slice(0,-1):i}function M(e,t,A,r){var i,o,a=e.gl;if(!t)return o={},Object(n.a)(o,r,"null"),Object(n.a)(o,"Format ","N/A"),o;var s,g,c,u="NOT PROVIDED",l=1,C=0,h=0;if(A&&(u=A.type,l=A.size,s=-1!==(u=String(u).replace("Array","")).indexOf("nt")),t instanceof I.a){var f,d,B=t,p=B.getDebugData(),E=p.data;if(g=p.changed?"*":"",c=E,C=(h=B.byteLength)/E.BYTES_PER_ELEMENT/l,A){var Q=A.divisor>0;d="".concat(Q?"I ":"P "," ").concat(C," (x").concat(l,"=").concat(h," bytes ").concat(Object(x.a)(a,u),")")}else s=!0,d="".concat(h," bytes");return f={},Object(n.a)(f,r,"".concat(g).concat(_(c,{size:l,isInteger:s}))),Object(n.a)(f,"Format ",d),f}return c=t,l=t.length,s=-1!==(u=String(t.constructor.name).replace("Array","")).indexOf("nt"),i={},Object(n.a)(i,r,"".concat(_(c,{size:l,isInteger:s})," (constant)")),Object(n.a)(i,"Format ","".concat(l,"x").concat(u," (constant)")),i}function O(e,t){var A=t.type,n=t.size,r=Object(N.b)(A,n);return r?"".concat(e," (").concat(r.name,")"):e}var L=A(6);function T(e){var t=e.header,A=void 0===t?"Uniforms":t,r=e.program,i=e.uniforms,o=e.undefinedOnly,a=void 0!==o&&o;Object(g.a)(r);var s,c=r._uniformSetters,u={},l=Object.keys(c).sort(),I=0,C=Object(L.a)(l);try{for(C.s();!(s=C.n()).done;){var h=s.value;h.match(".*_.*")||h.match(".*Matrix")||Z({table:u,header:A,uniforms:i,uniformName:h,undefinedOnly:a})&&I++}}catch(w){C.e(w)}finally{C.f()}var f,d=Object(L.a)(l);try{for(d.s();!(f=d.n()).done;){var B=f.value;B.match(".*Matrix")&&Z({table:u,header:A,uniforms:i,uniformName:B,undefinedOnly:a})&&I++}}catch(w){d.e(w)}finally{d.f()}var p,E=Object(L.a)(l);try{for(E.s();!(p=E.n()).done;){var Q=p.value;u[Q]||Z({table:u,header:A,uniforms:i,uniformName:Q,undefinedOnly:a})&&I++}}catch(w){E.e(w)}finally{E.f()}var y=0,v={};if(!a)for(var m in i){var b=i[m];u[m]||(y++,v[m]=Object(n.a)({Type:"NOT USED: ".concat(b)},A,_(b)))}return{table:u,count:I,unusedTable:v,unusedCount:y}}function Z(e){var t,A=e.table,r=e.header,i=e.uniforms,o=e.uniformName,a=e.undefinedOnly,s=i[o],g=function(e){return void 0!==e&&null!==e}(s);return(!a||!g)&&(A[o]=(t={},Object(n.a)(t,r,g?_(s):"N/A"),Object(n.a)(t,"Uniform Type",g?s:"NOT PROVIDED"),t),!0)}function H(e){var t=e.accessor,A=t.type,n=t.size,r=Object(N.b)(A,n);return r?"".concat(r.name," ").concat(e.name):e.name}var Y=A(7),J={POSITION:"positions",NORMAL:"normals",COLOR_0:"colors",TEXCOORD_0:"texCoords",TEXCOORD_1:"texCoords1",TEXCOORD_2:"texCoords2"};function j(e,t){var A=(t||{}).attributeMap,n=void 0===A?J:A;return n&&n[e]||e}function P(e,t){var A;switch(e){case"texCoords":case"texCoord1":case"texCoord2":case"texCoord3":A="uvs";break;case"vertices":case"positions":case"normals":case"pickingColors":A="vectors"}switch(A){case"vectors":t.size=t.size||3;break;case"uvs":t.size=t.size||2}Object(g.a)(Number.isFinite(t.size),"attribute ".concat(e," needs size"))}A.d(t,"a",(function(){return W}));var V=function(){},K={},W=function(){function e(t){var A=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object(r.a)(this,e);var n=A.id,i=void 0===n?Object(s.c)("model"):n;Object(g.a)(Object(o.i)(t)),this.id=i,this.gl=t,this.id=A.id||Object(s.c)("Model"),this.lastLogTime=0,this.animated=!1,this.initialize(A)}return Object(i.a)(e,[{key:"initialize",value:function(e){this.props={},this.programManager=e.programManager||a.a.getDefaultProgramManager(this.gl),this._programManagerState=-1,this._managedProgram=!1;var t=e.program,A=void 0===t?null:t,n=e.vs,r=e.fs,i=e.modules,o=e.defines,s=e.inject,c=e.varyings,u=e.bufferMode,l=e.transpileToGLSL100;this.programProps={program:A,vs:n,fs:r,modules:i,defines:o,inject:s,varyings:c,bufferMode:u,transpileToGLSL100:l},this.program=null,this.vertexArray=null,this._programDirty=!0,this.userData={},this.needsRedraw=!0,this._attributes={},this.attributes={},this.uniforms={},this.pickable=!0,this._checkProgram(),this.setUniforms(Object.assign({},this.getModuleUniforms(e.moduleSettings))),this.drawMode=void 0!==e.drawMode?e.drawMode:4,this.vertexCount=e.vertexCount||0,this.geometryBuffers={},this.isInstanced=e.isInstanced||e.instanced||e.instanceCount>0,this._setModelProps(e),this.geometry={},Object(g.a)(void 0!==this.drawMode&&Number.isFinite(this.vertexCount),"Model needs drawMode and vertexCount")}},{key:"setProps",value:function(e){this._setModelProps(e)}},{key:"delete",value:function(){for(var e in this._attributes)this._attributes[e]!==this.attributes[e]&&this._attributes[e].delete();this._managedProgram&&(this.programManager.release(this.program),this._managedProgram=!1),this.vertexArray.delete(),this._deleteGeometryBuffers()}},{key:"getDrawMode",value:function(){return this.drawMode}},{key:"getVertexCount",value:function(){return this.vertexCount}},{key:"getInstanceCount",value:function(){return this.instanceCount}},{key:"getAttributes",value:function(){return this.attributes}},{key:"getProgram",value:function(){return this.program}},{key:"setProgram",value:function(e){var t=e.program,A=e.vs,n=e.fs,r=e.modules,i=e.defines,o=e.inject,a=e.varyings,s=e.bufferMode,g=e.transpileToGLSL100;this.programProps={program:t,vs:A,fs:n,modules:r,defines:i,inject:o,varyings:a,bufferMode:s,transpileToGLSL100:g},this._programDirty=!0}},{key:"getUniforms",value:function(){return this.uniforms}},{key:"setDrawMode",value:function(e){return this.drawMode=e,this}},{key:"setVertexCount",value:function(e){return Object(g.a)(Number.isFinite(e)),this.vertexCount=e,this}},{key:"setInstanceCount",value:function(e){return Object(g.a)(Number.isFinite(e)),this.instanceCount=e,this}},{key:"setGeometry",value:function(e){return this.drawMode=e.drawMode,this.vertexCount=e.getVertexCount(),this._deleteGeometryBuffers(),this.geometryBuffers=function(e,t,A){var n={},r=t.indices;for(var i in t.attributes){var o=t.attributes[i],a=j(i,A);if("indices"===i)r=o;else if(o.constant)n[a]=o.value;else{var s=o.value,c=Object(Y.a)({},o);delete c.value,n[a]=[new I.a(e,s),c],P(i,c)}}if(r){var u=r.value||r;Object(g.a)(u instanceof Uint16Array||u instanceof Uint32Array,'attribute array for "indices" must be of integer type');var l={size:1,isIndexed:void 0===r.isIndexed||r.isIndexed};n.indices=[new I.a(e,{data:u,target:34963}),l]}return n}(this.gl,e),this.vertexArray.setAttributes(this.geometryBuffers),this}},{key:"setAttributes",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Object(s.a)(e))return this;var t={};for(var A in e){var n=e[A];t[A]=n.getValue?n.getValue():n}return this.vertexArray.setAttributes(t),this}},{key:"setUniforms",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object.assign(this.uniforms,e),this}},{key:"getModuleUniforms",value:function(e){this._checkProgram();var t=this.programManager.getUniforms(this.program);return t?t(e):{}}},{key:"updateModuleSettings",value:function(e){var t=this.getModuleUniforms(e||{});return this.setUniforms(t)}},{key:"clear",value:function(e){return Object(c.a)(this.program.gl,e),this}},{key:"draw",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._checkProgram();var t,A=e.moduleSettings,n=void 0===A?null:A,r=e.framebuffer,i=e.uniforms,a=void 0===i?{}:i,s=e.attributes,g=void 0===s?{}:s,c=e.transformFeedback,u=void 0===c?this.transformFeedback:c,l=e.parameters,I=void 0===l?{}:l,C=e.vertexArray,h=void 0===C?this.vertexArray:C;this.setAttributes(g),this.updateModuleSettings(n),this.setUniforms(a),o.k.priority>=2&&(t=this._logDrawCallStart(2));var f=this.vertexArray.getDrawParams(),d=this.props,B=d.isIndexed,p=void 0===B?f.isIndexed:B,E=d.indexType,Q=void 0===E?f.indexType:E,y=d.indexOffset,v=void 0===y?f.indexOffset:y,m=d.vertexArrayInstanced,b=void 0===m?f.isInstanced:m;b&&!this.isInstanced&&o.k.warn("Found instanced attributes on non-instanced model",this.id)();var w=this.isInstanced,S=this.instanceCount,F=this.props,R=F.onBeforeRender,D=void 0===R?V:R,G=F.onAfterRender,k=void 0===G?V:G;D(),this.program.setUniforms(this.uniforms);var x=this.program.draw(Object.assign(K,e,{logPriority:t,uniforms:null,framebuffer:r,parameters:I,drawMode:this.getDrawMode(),vertexCount:this.getVertexCount(),vertexArray:h,transformFeedback:u,isIndexed:p,indexType:Q,isInstanced:w,instanceCount:S,offset:p?v:0}));return k(),o.k.priority>=2&&this._logDrawCallEnd(t,h,r),x}},{key:"transform",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.discard,A=void 0===t||t,r=e.feedbackBuffers,i=e.unbindModels,o=void 0===i?[]:i,a=e.parameters;r&&this._setFeedbackBuffers(r),A&&(a=Object.assign({},a,Object(n.a)({},35977,A))),o.forEach((function(e){return e.vertexArray.unbindBuffers()}));try{this.draw(Object.assign({},e,{parameters:a}))}finally{o.forEach((function(e){return e.vertexArray.bindBuffers()}))}return this}},{key:"render",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return o.k.warn("Model.render() is deprecated. Use Model.setUniforms() and Model.draw()")(),this.setUniforms(e).draw()}},{key:"_setModelProps",value:function(e){Object.assign(this.props,e),"uniforms"in e&&this.setUniforms(e.uniforms),"pickable"in e&&(this.pickable=e.pickable),"instanceCount"in e&&(this.instanceCount=e.instanceCount),"geometry"in e&&this.setGeometry(e.geometry),"attributes"in e&&this.setAttributes(e.attributes),"_feedbackBuffers"in e&&this._setFeedbackBuffers(e._feedbackBuffers)}},{key:"_checkProgram",value:function(){if(this._programDirty||this.programManager.stateHash!==this._programManagerState){var e=this.programProps.program;if(e)this._managedProgram=!1;else{var t=this.programProps,A=t.vs,n=t.fs,r=t.modules,i=t.inject,o=t.defines,a=t.varyings,s=t.bufferMode,c=t.transpileToGLSL100;e=this.programManager.get({vs:A,fs:n,modules:r,inject:i,defines:o,varyings:a,bufferMode:s,transpileToGLSL100:c}),this.program&&this._managedProgram&&this.programManager.release(this.program),this._programManagerState=this.programManager.stateHash,this._managedProgram=!0}Object(g.a)(e instanceof u.a,"Model needs a program"),this._programDirty=!1,e!==this.program&&(this.program=e,this.vertexArray?this.vertexArray.setProps({program:this.program,attributes:this.vertexArray.attributes}):this.vertexArray=new G(this.gl,{program:this.program}),this.setUniforms(Object.assign({},this.getModuleUniforms())))}}},{key:"_deleteGeometryBuffers",value:function(){for(var e in this.geometryBuffers){var t=this.geometryBuffers[e][0]||this.geometryBuffers[e];t instanceof I.a&&t.delete()}}},{key:"_setAnimationProps",value:function(e){this.animated&&Object(g.a)(e,"Model.draw(): animated uniforms but no animationProps")}},{key:"_setFeedbackBuffers",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Object(s.a)(e))return this;var t=this.program.gl;return this.transformFeedback=this.transformFeedback||new k.a(t,{program:this.program}),this.transformFeedback.setBuffers(e),this}},{key:"_logDrawCallStart",value:function(e){var t=e>3?0:1e4;if(!(Date.now()-this.lastLogTime>> DRAWING MODEL ".concat(this.id),{collapsed:o.k.level<=2})(),e}},{key:"_logDrawCallEnd",value:function(e,t,A,r){if(void 0!==e){var i=function(e){var t=e.vertexArray,A=e.header,n=void 0===A?"Attributes":A;if(!t.configuration)return{};var r={};t.elements&&(r.ELEMENT_ARRAY_BUFFER=M(t,t.elements,null,n));var i=t.values;for(var o in i){var a=t._getAttributeInfo(o);if(a){var s="".concat(o,": ").concat(a.name),g=t.accessors[a.location];g&&(s="".concat(o,": ").concat(O(a.name,g))),r[s]=M(t,i[o],g,n)}}return r}({vertexArray:t,header:"".concat(this.id," attributes"),attributes:this._attributes}),a=T({header:"".concat(this.id," uniforms"),program:this.program,uniforms:Object.assign({},this.program.uniforms,A)}),s=a.table,g=a.unusedTable,c=a.unusedCount,u=T({header:"".concat(this.id," uniforms"),program:this.program,uniforms:Object.assign({},this.program.uniforms,A),undefinedOnly:!0}),l=u.table;u.count>0&&o.k.log("MISSING UNIFORMS",Object.keys(l))(),c>0&&o.k.log("UNUSED UNIFORMS",Object.keys(g))();var I=function(e){var t,A={},r="Accessors for ".concat(e.id),i=Object(L.a)(e.attributeInfos);try{for(i.s();!(t=i.n()).done;){var o=t.value;if(o){var a=H(o);A["in ".concat(a)]=Object(n.a)({},r,JSON.stringify(o.accessor))}}}catch(l){i.e(l)}finally{i.f()}var s,g=Object(L.a)(e.varyingInfos);try{for(g.s();!(s=g.n()).done;){var c=s.value;if(c){var u=H(c);A["out ".concat(u)]=Object(n.a)({},r,JSON.stringify(c.accessor))}}}catch(l){g.e(l)}finally{g.f()}return A}(this.vertexArray.configuration);o.k.table(e,i)(),o.k.table(e,s)(),o.k.table(e+1,I)(),r&&r.log({logLevel:2,message:"Rendered to ".concat(r.id)}),o.k.groupEnd(2,">>> DRAWING MODEL ".concat(this.id))()}}}]),e}()},function(e,t,A){"use strict";var n=A(1),r=A(4),i=A(314),o=function(){function e(t,A){Object(n.a)(this,e),this.name=t,this.type=A,this.sampleSize=1,this.reset()}return Object(r.a)(e,[{key:"setSampleSize",value:function(e){return this.sampleSize=e,this}},{key:"incrementCount",value:function(){return this.addCount(1),this}},{key:"decrementCount",value:function(){return this.subtractCount(1),this}},{key:"addCount",value:function(e){return this._count+=e,this._samples++,this._checkSampling(),this}},{key:"subtractCount",value:function(e){return this._count-=e,this._samples++,this._checkSampling(),this}},{key:"addTime",value:function(e){return this._time+=e,this.lastTiming=e,this._samples++,this._checkSampling(),this}},{key:"timeStart",value:function(){return this._startTime=Object(i.a)(),this._timerPending=!0,this}},{key:"timeEnd",value:function(){return this._timerPending?(this.addTime(Object(i.a)()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}},{key:"getSampleAverageCount",value:function(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}},{key:"getSampleAverageTime",value:function(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}},{key:"getSampleHz",value:function(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}},{key:"getAverageCount",value:function(){return this.samples>0?this.count/this.samples:0}},{key:"getAverageTime",value:function(){return this.samples>0?this.time/this.samples:0}},{key:"getHz",value:function(){return this.time>0?this.samples/(this.time/1e3):0}},{key:"reset",value:function(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}},{key:"_checkSampling",value:function(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}}]),e}(),a=function(){function e(t){var A=t.id,r=t.stats;Object(n.a)(this,e),this.id=A,this.stats={},this._initializeStats(r),Object.seal(this)}return Object(r.a)(e,[{key:"get",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"count";return this._getOrCreate({name:e,type:t})}},{key:"reset",value:function(){for(var e in this.stats)this.stats[e].reset();return this}},{key:"forEach",value:function(e){for(var t in this.stats)e(this.stats[t])}},{key:"getTable",value:function(){var e={};return this.forEach((function(t){e[t.name]={time:t.time||0,count:t.count||0,average:t.getAverageTime()||0,hz:t.getHz()||0}})),e}},{key:"_initializeStats",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];t.forEach((function(t){return e._getOrCreate(t)}))}},{key:"_getOrCreate",value:function(e){if(!e||!e.name)return null;var t=e.name,A=e.type;return this.stats[t]||(this.stats[t]=e instanceof o?e:new o(t,A)),this.stats[t]}},{key:"size",get:function(){return Object.keys(this.stats).length}}]),e}();A.d(t,"a",(function(){return a}))},function(e,t,A){"use strict";function n(e){return 180*(e%(2*Math.PI))/Math.PI}function r(e){return e%360*Math.PI/180}function i(e){if(!e)throw new Error("coord is required");if(!Array.isArray(e)){if("Feature"===e.type&&null!==e.geometry&&"Point"===e.geometry.type)return e.geometry.coordinates;if("Point"===e.type)return e.coordinates}if(Array.isArray(e)&&e.length>=2&&!Array.isArray(e[0])&&!Array.isArray(e[1]))return e;throw new Error("coord must be GeoJSON Point or an Array of numbers")}function o(e,t){var A=r(e[1]),i=r(t[1]),o=r(t[0]-e[0]);o>Math.PI&&(o-=2*Math.PI),o<-Math.PI&&(o+=2*Math.PI);var a=Math.log(Math.tan(i/2+Math.PI/4)/Math.tan(A/2+Math.PI/4));return(n(Math.atan2(o,a))+360)%360}t.a=function(e,t,A){var n;return void 0===A&&(A={}),(n=A.final?o(i(t),i(e)):o(i(e),i(t)))>180?-(360-n):n}},function(e,t,A){"use strict";var n=A(93),r=A.n(n),i=A(98),o=A.n(i),a=A(278),s=A.n(a),g=A(279),c=A.n(g),u=A(280),l=A.n(u),I=A(281),C=A.n(I),h=A(0),f=A.n(h),d=A(13),B=A.n(d),p=A(61),E=A.n(p),Q=A(237),y=A.n(Q),v=A(229),m=A(100),b=A(328),w=A(52),S=function(e){function t(e){s()(this,t);var A=l()(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return A.onNodeDragStart=function(e,t){var n=A.state.expandedKeys,r=A.props.onDragStart,i=t.props,o=i.eventKey,a=i.children;A.dragNode=t,A.setState({dragNodesKeys:Object(w.j)(a,t),expandedKeys:Object(w.b)(n,o)}),r&&r({event:e,node:t})},A.onNodeDragEnter=function(e,t){var n=A.state.expandedKeys,r=A.props.onDragEnter,i=t.props,o=i.pos,a=i.eventKey;if(A.dragNode){var s=Object(w.c)(e,t);A.dragNode.props.eventKey!==a||0!==s?setTimeout((function(){A.setState({dragOverNodeKey:a,dropPosition:s}),A.delayedDragEnterLogic||(A.delayedDragEnterLogic={}),Object.keys(A.delayedDragEnterLogic).forEach((function(e){clearTimeout(A.delayedDragEnterLogic[e])})),A.delayedDragEnterLogic[o]=setTimeout((function(){var i=Object(w.a)(n,a);"expandedKeys"in A.props||A.setState({expandedKeys:i}),r&&r({event:e,node:t,expandedKeys:i})}),400)}),0):A.setState({dragOverNodeKey:"",dropPosition:null})}},A.onNodeDragOver=function(e,t){var n=A.props.onDragOver,r=t.props.eventKey;if(A.dragNode&&r===A.state.dragOverNodeKey){var i=Object(w.c)(e,t);if(i===A.state.dropPosition)return;A.setState({dropPosition:i})}n&&n({event:e,node:t})},A.onNodeDragLeave=function(e,t){var n=A.props.onDragLeave;A.setState({dragOverNodeKey:""}),n&&n({event:e,node:t})},A.onNodeDragEnd=function(e,t){var n=A.props.onDragEnd;A.setState({dragOverNodeKey:""}),n&&n({event:e,node:t}),A.dragNode=null},A.onNodeDrop=function(e,t){var n=A.state,r=n.dragNodesKeys,i=void 0===r?[]:r,o=n.dropPosition,a=A.props.onDrop,s=t.props,g=s.eventKey,c=s.pos;if(A.setState({dragOverNodeKey:""}),-1===i.indexOf(g)){var u=Object(w.o)(c),l={event:e,node:t,dragNode:A.dragNode,dragNodesKeys:i.slice(),dropPosition:o+Number(u[u.length-1])};0!==o&&(l.dropToGap=!0),a&&a(l),A.dragNode=null}else y()(!1,"Can not drop to dragNode(include it's children node)")},A.onNodeClick=function(e,t){var n=A.props.onClick;n&&n(e,t)},A.onNodeDoubleClick=function(e,t){var n=A.props.onDoubleClick;n&&n(e,t)},A.onNodeSelect=function(e,t){var n=A.state.selectedKeys,r=A.state.keyEntities,i=A.props,o=i.onSelect,a=i.multiple,s=t.props,g=s.selected,c=s.eventKey,u=!g,l=(n=u?a?Object(w.a)(n,c):[c]:Object(w.b)(n,c)).map((function(e){var t=r[e];return t?t.node:null})).filter((function(e){return e}));(A.setUncontrolledState({selectedKeys:n}),o)&&o(n,{event:"select",selected:u,node:t,selectedNodes:l,nativeEvent:e.nativeEvent})},A.onNodeCheck=function(e,t,n){var r=A.state,i=r.keyEntities,o=r.checkedKeys,a=r.halfCheckedKeys,s=A.props,g=s.checkStrictly,c=s.onCheck,u=t.props.eventKey,l=void 0,I={event:"check",node:t,checked:n,nativeEvent:e.nativeEvent};if(g){var C=n?Object(w.a)(o,u):Object(w.b)(o,u);l={checked:C,halfChecked:Object(w.b)(a,u)},I.checkedNodes=C.map((function(e){return i[e]})).filter((function(e){return e})).map((function(e){return e.node})),A.setUncontrolledState({checkedKeys:C})}else{var h=Object(w.e)([u],n,i,{checkedKeys:o,halfCheckedKeys:a}),f=h.checkedKeys,d=h.halfCheckedKeys;l=f,I.checkedNodes=[],I.checkedNodesPositions=[],I.halfCheckedKeys=d,f.forEach((function(e){var t=i[e];if(t){var A=t.node,n=t.pos;I.checkedNodes.push(A),I.checkedNodesPositions.push({node:A,pos:n})}})),A.setUncontrolledState({checkedKeys:f,halfCheckedKeys:d})}c&&c(l,I)},A.onNodeLoad=function(e){return new Promise((function(t){A.setState((function(n){var r=n.loadedKeys,i=void 0===r?[]:r,o=n.loadingKeys,a=void 0===o?[]:o,s=A.props,g=s.loadData,c=s.onLoad,u=e.props.eventKey;return g&&-1===i.indexOf(u)&&-1===a.indexOf(u)?(g(e).then((function(){var n=Object(w.a)(A.state.loadedKeys,u),r=Object(w.b)(A.state.loadingKeys,u);c&&c(n,{event:"load",node:e});A.setUncontrolledState({loadedKeys:n}),A.setState({loadingKeys:r}),t()})),{loadingKeys:Object(w.a)(a,u)}):{}}))}))},A.onNodeExpand=function(e,t){var n=A.state.expandedKeys,r=A.props,i=r.onExpand,o=r.loadData,a=t.props,s=a.eventKey,g=a.expanded,c=n.indexOf(s),u=!g;if(y()(g&&-1!==c||!g&&-1===c,"Expand state not sync with index check"),n=u?Object(w.a)(n,s):Object(w.b)(n,s),A.setUncontrolledState({expandedKeys:n}),i&&i(n,{node:t,expanded:u,nativeEvent:e.nativeEvent}),u&&o){var l=A.onNodeLoad(t);return l?l.then((function(){A.setUncontrolledState({expandedKeys:n})})):null}return null},A.onNodeMouseEnter=function(e,t){var n=A.props.onMouseEnter;n&&n({event:e,node:t})},A.onNodeMouseLeave=function(e,t){var n=A.props.onMouseLeave;n&&n({event:e,node:t})},A.onNodeContextMenu=function(e,t){var n=A.props.onRightClick;n&&(e.preventDefault(),n({event:e,node:t}))},A.setUncontrolledState=function(e){var t=!1,n={};Object.keys(e).forEach((function(r){r in A.props||(t=!0,n[r]=e[r])})),t&&A.setState(n)},A.registerTreeNode=function(e,t){t?A.domTreeNodes[e]=t:delete A.domTreeNodes[e]},A.isKeyChecked=function(e){var t=A.state.checkedKeys;return-1!==(void 0===t?[]:t).indexOf(e)},A.renderTreeNode=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=A.state,i=r.keyEntities,o=r.expandedKeys,a=void 0===o?[]:o,s=r.selectedKeys,g=void 0===s?[]:s,c=r.halfCheckedKeys,u=void 0===c?[]:c,l=r.loadedKeys,I=void 0===l?[]:l,C=r.loadingKeys,h=void 0===C?[]:C,d=r.dragOverNodeKey,B=r.dropPosition,p=Object(w.l)(n,t),E=e.key||p;return i[E]?f.a.cloneElement(e,{key:E,eventKey:E,expanded:-1!==a.indexOf(E),selected:-1!==g.indexOf(E),loaded:-1!==I.indexOf(E),loading:-1!==h.indexOf(E),checked:A.isKeyChecked(E),halfChecked:-1!==u.indexOf(E),pos:p,dragOver:d===E&&0===B,dragOverGapTop:d===E&&-1===B,dragOverGapBottom:d===E&&1===B}):(Object(w.p)(),null)},A.state={posEntities:{},keyEntities:{},selectedKeys:[],checkedKeys:[],halfCheckedKeys:[],loadedKeys:[],loadingKeys:[],treeNode:[]},A.domTreeNodes={},A}return C()(t,e),c()(t,[{key:"getChildContext",value:function(){var e=this.props,t=e.prefixCls,A=e.selectable,n=e.showIcon,r=e.icon,i=e.draggable,o=e.checkable,a=e.checkStrictly,s=e.disabled,g=e.loadData,c=e.filterTreeNode,u=e.motion;return{rcTree:{prefixCls:t,selectable:A,showIcon:n,icon:r,switcherIcon:e.switcherIcon,draggable:i,checkable:o,checkStrictly:a,disabled:s,motion:u,loadData:g,filterTreeNode:c,renderTreeNode:this.renderTreeNode,isKeyChecked:this.isKeyChecked,onNodeClick:this.onNodeClick,onNodeDoubleClick:this.onNodeDoubleClick,onNodeExpand:this.onNodeExpand,onNodeSelect:this.onNodeSelect,onNodeCheck:this.onNodeCheck,onNodeLoad:this.onNodeLoad,onNodeMouseEnter:this.onNodeMouseEnter,onNodeMouseLeave:this.onNodeMouseLeave,onNodeContextMenu:this.onNodeContextMenu,onNodeDragStart:this.onNodeDragStart,onNodeDragEnter:this.onNodeDragEnter,onNodeDragOver:this.onNodeDragOver,onNodeDragLeave:this.onNodeDragLeave,onNodeDragEnd:this.onNodeDragEnd,onNodeDrop:this.onNodeDrop,registerTreeNode:this.registerTreeNode}}}},{key:"render",value:function(){var e=this,t=this.state.treeNode,A=this.props,n=A.prefixCls,i=A.className,a=A.focusable,s=A.style,g=A.showLine,c=A.tabIndex,u=void 0===c?0:c,l=Object(w.i)(this.props);return a&&(l.tabIndex=u,l.onKeyDown=this.onKeyDown),f.a.createElement("ul",r()({},l,{className:E()(n,i,o()({},n+"-show-line",g)),style:s,role:"tree",unselectable:"on"}),Object(w.m)(t,(function(t,A){return e.renderTreeNode(t,A)})))}}],[{key:"getDerivedStateFromProps",value:function(e,t){var A=t.prevProps,n={prevProps:e};function r(t){return!A&&t in e||A&&A[t]!==e[t]}var i=null;if(r("treeData")?i=Object(w.g)(e.treeData):r("children")&&(i=Object(v.a)(e.children)),i){n.treeNode=i;var o=Object(w.h)(i);n.posEntities=o.posEntities,n.keyEntities=o.keyEntities}var a=n.keyEntities||t.keyEntities;if(r("expandedKeys")||A&&r("autoExpandParent")?n.expandedKeys=e.autoExpandParent||!A&&e.defaultExpandParent?Object(w.f)(e.expandedKeys,a):e.expandedKeys:!A&&e.defaultExpandAll?n.expandedKeys=Object.keys(a):!A&&e.defaultExpandedKeys&&(n.expandedKeys=e.autoExpandParent||e.defaultExpandParent?Object(w.f)(e.defaultExpandedKeys,a):e.defaultExpandedKeys),e.selectable&&(r("selectedKeys")?n.selectedKeys=Object(w.d)(e.selectedKeys,e):!A&&e.defaultSelectedKeys&&(n.selectedKeys=Object(w.d)(e.defaultSelectedKeys,e))),e.checkable){var s=void 0;if(r("checkedKeys")?s=Object(w.n)(e.checkedKeys)||{}:!A&&e.defaultCheckedKeys?s=Object(w.n)(e.defaultCheckedKeys)||{}:i&&(s=Object(w.n)(e.checkedKeys)||{checkedKeys:t.checkedKeys,halfCheckedKeys:t.halfCheckedKeys}),s){var g=s,c=g.checkedKeys,u=void 0===c?[]:c,l=g.halfCheckedKeys,I=void 0===l?[]:l;if(!e.checkStrictly){var C=Object(w.e)(u,!0,a);u=C.checkedKeys,I=C.halfCheckedKeys}n.checkedKeys=u,n.halfCheckedKeys=I}}return r("loadedKeys")&&(n.loadedKeys=e.loadedKeys),n}}]),t}(f.a.Component);S.propTypes={prefixCls:B.a.string,className:B.a.string,style:B.a.object,tabIndex:B.a.oneOfType([B.a.string,B.a.number]),children:B.a.any,treeData:B.a.array,showLine:B.a.bool,showIcon:B.a.bool,icon:B.a.oneOfType([B.a.node,B.a.func]),focusable:B.a.bool,selectable:B.a.bool,disabled:B.a.bool,multiple:B.a.bool,checkable:B.a.oneOfType([B.a.bool,B.a.node]),checkStrictly:B.a.bool,draggable:B.a.bool,defaultExpandParent:B.a.bool,autoExpandParent:B.a.bool,defaultExpandAll:B.a.bool,defaultExpandedKeys:B.a.arrayOf(B.a.string),expandedKeys:B.a.arrayOf(B.a.string),defaultCheckedKeys:B.a.arrayOf(B.a.string),checkedKeys:B.a.oneOfType([B.a.arrayOf(B.a.oneOfType([B.a.string,B.a.number])),B.a.object]),defaultSelectedKeys:B.a.arrayOf(B.a.string),selectedKeys:B.a.arrayOf(B.a.string),onClick:B.a.func,onDoubleClick:B.a.func,onExpand:B.a.func,onCheck:B.a.func,onSelect:B.a.func,onLoad:B.a.func,loadData:B.a.func,loadedKeys:B.a.arrayOf(B.a.string),onMouseEnter:B.a.func,onMouseLeave:B.a.func,onRightClick:B.a.func,onDragStart:B.a.func,onDragEnter:B.a.func,onDragOver:B.a.func,onDragLeave:B.a.func,onDragEnd:B.a.func,onDrop:B.a.func,filterTreeNode:B.a.func,motion:B.a.object,switcherIcon:B.a.oneOfType([B.a.node,B.a.func])},S.childContextTypes=b.b,S.defaultProps={prefixCls:"rc-tree",showLine:!1,showIcon:!0,selectable:!0,multiple:!1,checkable:!1,disabled:!1,checkStrictly:!1,draggable:!1,defaultExpandParent:!0,autoExpandParent:!1,defaultExpandAll:!1,defaultExpandedKeys:[],defaultCheckedKeys:[],defaultSelectedKeys:[]},Object(m.a)(S);var F=S,R=A(317);A.d(t,"a",(function(){return R.a})),F.TreeNode=R.a;t.b=F},function(e,t,A){"use strict";t.a={50:"#fafafa",100:"#f5f5f5",200:"#eeeeee",300:"#e0e0e0",400:"#bdbdbd",500:"#9e9e9e",600:"#757575",700:"#616161",800:"#424242",900:"#212121",A100:"#d5d5d5",A200:"#aaaaaa",A400:"#303030",A700:"#616161"}},function(e,t,A){"use strict";A.d(t,"a",(function(){return a}));var n,r=A(2),i=A(161),o=A(232),a={WEBGL2:"WEBGL2",VERTEX_ARRAY_OBJECT:"VERTEX_ARRAY_OBJECT",TIMER_QUERY:"TIMER_QUERY",INSTANCED_RENDERING:"INSTANCED_RENDERING",MULTIPLE_RENDER_TARGETS:"MULTIPLE_RENDER_TARGETS",ELEMENT_INDEX_UINT32:"ELEMENT_INDEX_UINT32",BLEND_EQUATION_MINMAX:"BLEND_EQUATION_MINMAX",FLOAT_BLEND:"FLOAT_BLEND",COLOR_ENCODING_SRGB:"COLOR_ENCODING_SRGB",TEXTURE_DEPTH:"TEXTURE_DEPTH",TEXTURE_FLOAT:"TEXTURE_FLOAT",TEXTURE_HALF_FLOAT:"TEXTURE_HALF_FLOAT",TEXTURE_FILTER_LINEAR_FLOAT:"TEXTURE_FILTER_LINEAR_FLOAT",TEXTURE_FILTER_LINEAR_HALF_FLOAT:"TEXTURE_FILTER_LINEAR_HALF_FLOAT",TEXTURE_FILTER_ANISOTROPIC:"TEXTURE_FILTER_ANISOTROPIC",COLOR_ATTACHMENT_RGBA32F:"COLOR_ATTACHMENT_RGBA32F",COLOR_ATTACHMENT_FLOAT:"COLOR_ATTACHMENT_FLOAT",COLOR_ATTACHMENT_HALF_FLOAT:"COLOR_ATTACHMENT_HALF_FLOAT",GLSL_FRAG_DATA:"GLSL_FRAG_DATA",GLSL_FRAG_DEPTH:"GLSL_FRAG_DEPTH",GLSL_DERIVATIVES:"GLSL_DERIVATIVES",GLSL_TEXTURE_LOD:"GLSL_TEXTURE_LOD"};t.b=(n={},Object(r.a)(n,a.WEBGL2,[!1,!0]),Object(r.a)(n,a.VERTEX_ARRAY_OBJECT,["OES_vertex_array_object",!0]),Object(r.a)(n,a.TIMER_QUERY,["EXT_disjoint_timer_query","EXT_disjoint_timer_query_webgl2"]),Object(r.a)(n,a.INSTANCED_RENDERING,["ANGLE_instanced_arrays",!0]),Object(r.a)(n,a.MULTIPLE_RENDER_TARGETS,["WEBGL_draw_buffers",!0]),Object(r.a)(n,a.ELEMENT_INDEX_UINT32,["OES_element_index_uint",!0]),Object(r.a)(n,a.BLEND_EQUATION_MINMAX,["EXT_blend_minmax",!0]),Object(r.a)(n,a.FLOAT_BLEND,["EXT_float_blend"]),Object(r.a)(n,a.COLOR_ENCODING_SRGB,["EXT_sRGB",!0]),Object(r.a)(n,a.TEXTURE_DEPTH,["WEBGL_depth_texture",!0]),Object(r.a)(n,a.TEXTURE_FLOAT,["OES_texture_float",!0]),Object(r.a)(n,a.TEXTURE_HALF_FLOAT,["OES_texture_half_float",!0]),Object(r.a)(n,a.TEXTURE_FILTER_LINEAR_FLOAT,["OES_texture_float_linear"]),Object(r.a)(n,a.TEXTURE_FILTER_LINEAR_HALF_FLOAT,["OES_texture_half_float_linear"]),Object(r.a)(n,a.TEXTURE_FILTER_ANISOTROPIC,["EXT_texture_filter_anisotropic"]),Object(r.a)(n,a.COLOR_ATTACHMENT_RGBA32F,[function(e){var t=new o.a(e,{format:6408,type:5126,dataFormat:6408}),A=new i.a(e,{id:"test-framebuffer",check:!1,attachments:Object(r.a)({},36064,t)}),n=A.getStatus();return t.delete(),A.delete(),36053===n},"EXT_color_buffer_float"]),Object(r.a)(n,a.COLOR_ATTACHMENT_FLOAT,[!1,"EXT_color_buffer_float"]),Object(r.a)(n,a.COLOR_ATTACHMENT_HALF_FLOAT,["EXT_color_buffer_half_float"]),Object(r.a)(n,a.GLSL_FRAG_DATA,["WEBGL_draw_buffers",!0]),Object(r.a)(n,a.GLSL_FRAG_DEPTH,["EXT_frag_depth",!0]),Object(r.a)(n,a.GLSL_DERIVATIVES,["OES_standard_derivatives",!0]),Object(r.a)(n,a.GLSL_TEXTURE_LOD,["EXT_shader_texture_lod",!0]),n)},function(e,t,A){"use strict";A.d(t,"a",(function(){return o})),A.d(t,"b",(function(){return a}));var n=A(8),r=A(18),i=A(26);function o(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.framebuffer,n=void 0===A?null:A,o=t.color,a=void 0===o?null:o,s=t.depth,g=void 0===s?null:s,c=t.stencil,u=void 0===c?null:c,l={};n&&(l.framebuffer=n);var I=0;a&&(I|=16384,!0!==a&&(l.clearColor=a)),g&&(I|=256,!0!==g&&(l.clearDepth=g)),u&&(I|=1024,!0!==g&&(l.clearStencil=g)),Object(i.a)(0!==I,"clear: bad arguments"),Object(r.o)(e,l,(function(){e.clear(I)}))}function a(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=t.framebuffer,o=void 0===A?null:A,a=t.buffer,s=void 0===a?6144:a,g=t.drawBuffer,c=void 0===g?0:g,u=t.value,l=void 0===u?[0,0,0,0]:u;Object(r.a)(e),Object(r.o)(e,{framebuffer:o},(function(){switch(s){case 6144:switch(l.constructor){case Int32Array:e.clearBufferiv(s,c,l);break;case Uint32Array:e.clearBufferuiv(s,c,l);break;case Float32Array:default:e.clearBufferfv(s,c,l)}break;case 6145:e.clearBufferfv(6145,0,[l]);break;case 6146:e.clearBufferiv(6146,0,[l]);break;case 34041:var t=Object(n.a)(l,2),A=t[0],r=t[1];e.clearBufferfi(34041,0,A,r);break;default:Object(i.a)(!1,"clear: bad arguments")}}))}},function(e,t,A){"use strict";function n(e,t){if(!e)throw new Error(t||"shadertools: assertion failed.")}A.d(t,"a",(function(){return n}))},function(e,t,A){!function(e){"use strict";function t(){}function A(e){this.message=e||""}function n(e){this.message=e||""}function r(e){this.message=e||""}function i(){}function o(e){return null===e?Ne:e.color}function a(e){return null===e?null:e.parent}function s(e,t){null!==e&&(e.color=t)}function g(e){return null===e?null:e.left}function c(e){return null===e?null:e.right}function u(){this.root_=null,this.size_=0}function l(){}function I(){this.array_=[],arguments[0]instanceof Ee&&this.addAll(arguments[0])}function C(){}function h(e){this.message=e||""}function f(){this.array_=[]}"fill"in Array.prototype||Object.defineProperty(Array.prototype,"fill",{configurable:!0,value:function(e){if(void 0===this||null===this)throw new TypeError(this+" is not an object");var t=Object(this),A=Math.max(Math.min(t.length,9007199254740991),0)||0,n=1 in arguments&&parseInt(Number(arguments[1]),10)||0;n=n<0?Math.max(A+n,0):Math.min(n,A);var r=2 in arguments&&void 0!==arguments[2]?parseInt(Number(arguments[2]),10)||0:A;for(r=r<0?Math.max(A+arguments[2],0):Math.min(r,A);nt.x?1:this.yt.y?1:0},m.prototype.clone=function(){},m.prototype.copy=function(){return new m(this)},m.prototype.toString=function(){return"("+this.x+", "+this.y+", "+this.z+")"},m.prototype.distance3D=function(e){var t=this.x-e.x,A=this.y-e.y,n=this.z-e.z;return Math.sqrt(t*t+A*A+n*n)},m.prototype.distance=function(e){var t=this.x-e.x,A=this.y-e.y;return Math.sqrt(t*t+A*A)},m.prototype.hashCode=function(){var e=17;return 37*(e=37*e+m.hashCode(this.x))+m.hashCode(this.y)},m.prototype.setCoordinate=function(e){this.x=e.x,this.y=e.y,this.z=e.z},m.prototype.interfaces_=function(){return[Q,y,t]},m.prototype.getClass=function(){return m},m.hashCode=function(){if(1===arguments.length){var e=arguments[0],t=p.doubleToLongBits(e);return Math.trunc((t^t)>>>32)}},b.DimensionalComparator.get=function(){return w},b.serialVersionUID.get=function(){return 0x5cbf2c235c7e5800},b.NULL_ORDINATE.get=function(){return p.NaN},b.X.get=function(){return 0},b.Y.get=function(){return 1},b.Z.get=function(){return 2},Object.defineProperties(m,b);var w=function(e){if(this._dimensionsToTest=2,0===arguments.length);else if(1===arguments.length){var t=arguments[0];if(2!==t&&3!==t)throw new B("only 2 or 3 dimensions may be specified");this._dimensionsToTest=t}};w.prototype.compare=function(e,t){var A=e,n=t,r=w.compare(A.x,n.x);if(0!==r)return r;var i=w.compare(A.y,n.y);return 0!==i?i:this._dimensionsToTest<=2?0:w.compare(A.z,n.z)},w.prototype.interfaces_=function(){return[v]},w.prototype.getClass=function(){return w},w.compare=function(e,t){return et?1:p.isNaN(e)?p.isNaN(t)?0:-1:p.isNaN(t)?1:0};var S=function(){};S.prototype.create=function(){},S.prototype.interfaces_=function(){return[]},S.prototype.getClass=function(){return S};var F=function(){},R={INTERIOR:{configurable:!0},BOUNDARY:{configurable:!0},EXTERIOR:{configurable:!0},NONE:{configurable:!0}};F.prototype.interfaces_=function(){return[]},F.prototype.getClass=function(){return F},F.toLocationSymbol=function(e){switch(e){case F.EXTERIOR:return"e";case F.BOUNDARY:return"b";case F.INTERIOR:return"i";case F.NONE:return"-"}throw new B("Unknown location value: "+e)},R.INTERIOR.get=function(){return 0},R.BOUNDARY.get=function(){return 1},R.EXTERIOR.get=function(){return 2},R.NONE.get=function(){return-1},Object.defineProperties(F,R);var D=function(e,t){return e.interfaces_&&e.interfaces_().indexOf(t)>-1},G=function(){},k={LOG_10:{configurable:!0}};G.prototype.interfaces_=function(){return[]},G.prototype.getClass=function(){return G},G.log10=function(e){var t=Math.log(e);return p.isInfinite(t)||p.isNaN(t)?t:t/G.LOG_10},G.min=function(e,t,A,n){var r=e;return tA?A:e}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var n=arguments[0],r=arguments[1],i=arguments[2];return ni?i:n}},G.wrap=function(e,t){return e<0?t- -e%t:e%t},G.max=function(){if(3===arguments.length){var e=arguments[0],t=arguments[1],A=arguments[2],n=e;return t>n&&(n=t),A>n&&(n=A),n}if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],a=arguments[3],s=r;return i>s&&(s=i),o>s&&(s=o),a>s&&(s=a),s}},G.average=function(e,t){return(e+t)/2},k.LOG_10.get=function(){return Math.log(10)},Object.defineProperties(G,k);var x=function(e){this.str=e};x.prototype.append=function(e){this.str+=e},x.prototype.setCharAt=function(e,t){this.str=this.str.substr(0,e)+t+this.str.substr(e+1)},x.prototype.toString=function(e){return this.str};var N=function(e){this.value=e};N.prototype.intValue=function(){return this.value},N.prototype.compareTo=function(e){return this.valuee?1:0},N.isNaN=function(e){return Number.isNaN(e)};var U=function(){};U.isWhitespace=function(e){return e<=32&&e>=0||127===e},U.toUpperCase=function(e){return e.toUpperCase()};var _=function e(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if("number"==typeof arguments[0]){var t=arguments[0];this.init(t)}else if(arguments[0]instanceof e){var A=arguments[0];this.init(A)}else if("string"==typeof arguments[0]){var n=arguments[0];e.call(this,e.parse(n))}}else if(2===arguments.length){var r=arguments[0],i=arguments[1];this.init(r,i)}},M={PI:{configurable:!0},TWO_PI:{configurable:!0},PI_2:{configurable:!0},E:{configurable:!0},NaN:{configurable:!0},EPS:{configurable:!0},SPLIT:{configurable:!0},MAX_PRINT_DIGITS:{configurable:!0},TEN:{configurable:!0},ONE:{configurable:!0},SCI_NOT_EXPONENT_CHAR:{configurable:!0},SCI_NOT_ZERO:{configurable:!0}};_.prototype.le=function(e){return(this._hi9?(c=!0,u="9"):u="0"+g,o.append(u),A=A.subtract(_.valueOf(g)).multiply(_.TEN),c&&A.selfAdd(_.TEN);var l=!0,I=_.magnitude(A._hi);if(I<0&&Math.abs(I)>=a-s&&(l=!1),!l)break}return t[0]=n,o.toString()},_.prototype.sqr=function(){return this.multiply(this)},_.prototype.doubleValue=function(){return this._hi+this._lo},_.prototype.subtract=function(){if(arguments[0]instanceof _){var e=arguments[0];return this.add(e.negate())}if("number"==typeof arguments[0]){var t=arguments[0];return this.add(-t)}},_.prototype.equals=function(){if(1===arguments.length){var e=arguments[0];return this._hi===e._hi&&this._lo===e._lo}},_.prototype.isZero=function(){return 0===this._hi&&0===this._lo},_.prototype.selfSubtract=function(){if(arguments[0]instanceof _){var e=arguments[0];return this.isNaN()?this:this.selfAdd(-e._hi,-e._lo)}if("number"==typeof arguments[0]){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t,0)}},_.prototype.getSpecialNumberString=function(){return this.isZero()?"0.0":this.isNaN()?"NaN ":null},_.prototype.min=function(e){return this.le(e)?this:e},_.prototype.selfDivide=function(){if(1===arguments.length){if(arguments[0]instanceof _){var e=arguments[0];return this.selfDivide(e._hi,e._lo)}if("number"==typeof arguments[0]){var t=arguments[0];return this.selfDivide(t,0)}}else if(2===arguments.length){var A=arguments[0],n=arguments[1],r=null,i=null,o=null,a=null,s=null,g=null,c=null,u=null;return s=this._hi/A,u=(r=(g=_.SPLIT*s)-(r=g-s))*(o=(u=_.SPLIT*A)-(o=u-A))-(c=s*A)+r*(a=A-o)+(i=s-r)*o+i*a,u=s+(g=(this._hi-c-u+this._lo-s*n)/A),this._hi=u,this._lo=s-u+g,this}},_.prototype.dump=function(){return"DD<"+this._hi+", "+this._lo+">"},_.prototype.divide=function(){if(arguments[0]instanceof _){var e=arguments[0],t=null,A=null,n=null,r=null,i=null,o=null,a=null,s=null;return A=(i=this._hi/e._hi)-(t=(o=_.SPLIT*i)-(t=o-i)),s=t*(n=(s=_.SPLIT*e._hi)-(n=s-e._hi))-(a=i*e._hi)+t*(r=e._hi-n)+A*n+A*r,o=(this._hi-a-s+this._lo-i*e._lo)/e._hi,new _(s=i+o,i-s+o)}if("number"==typeof arguments[0]){var g=arguments[0];return p.isNaN(g)?_.createNaN():_.copy(this).selfDivide(g,0)}},_.prototype.ge=function(e){return(this._hi>e._hi||this._hi===e._hi)&&this._lo>=e._lo},_.prototype.pow=function(e){if(0===e)return _.valueOf(1);var t=new _(this),A=_.valueOf(1),n=Math.abs(e);if(n>1)for(;n>0;)n%2==1&&A.selfMultiply(t),(n/=2)>0&&(t=t.sqr());else A=t;return e<0?A.reciprocal():A},_.prototype.ceil=function(){if(this.isNaN())return _.NaN;var e=Math.ceil(this._hi),t=0;return e===this._hi&&(t=Math.ceil(this._lo)),new _(e,t)},_.prototype.compareTo=function(e){var t=e;return this._hit._hi?1:this._lot._lo?1:0},_.prototype.rint=function(){return this.isNaN()?this:this.add(.5).floor()},_.prototype.setValue=function(){if(arguments[0]instanceof _){var e=arguments[0];return this.init(e),this}if("number"==typeof arguments[0]){var t=arguments[0];return this.init(t),this}},_.prototype.max=function(e){return this.ge(e)?this:e},_.prototype.sqrt=function(){if(this.isZero())return _.valueOf(0);if(this.isNegative())return _.NaN;var e=1/Math.sqrt(this._hi),t=this._hi*e,A=_.valueOf(t),n=this.subtract(A.sqr())._hi*(.5*e);return A.add(n)},_.prototype.selfAdd=function(){if(1===arguments.length){if(arguments[0]instanceof _){var e=arguments[0];return this.selfAdd(e._hi,e._lo)}if("number"==typeof arguments[0]){var t=arguments[0],A=null,n=null,r=null,i=null,o=null,a=null;return i=(r=this._hi+t)-(o=r-this._hi),n=(a=(i=t-o+(this._hi-i))+this._lo)+(r-(A=r+a)),this._hi=A+n,this._lo=n+(A-this._hi),this}}else if(2===arguments.length){var s=arguments[0],g=arguments[1],c=null,u=null,l=null,I=null,C=null,h=null,f=null;I=this._hi+s,u=this._lo+g,C=I-(h=I-this._hi),l=u-(f=u-this._lo);var d=(c=I+(h=(C=s-h+(this._hi-C))+u))+(h=(l=g-f+(this._lo-l))+(h+(I-c))),B=h+(c-d);return this._hi=d,this._lo=B,this}},_.prototype.selfMultiply=function(){if(1===arguments.length){if(arguments[0]instanceof _){var e=arguments[0];return this.selfMultiply(e._hi,e._lo)}if("number"==typeof arguments[0]){var t=arguments[0];return this.selfMultiply(t,0)}}else if(2===arguments.length){var A=arguments[0],n=arguments[1],r=null,i=null,o=null,a=null,s=null,g=null;r=(s=_.SPLIT*this._hi)-this._hi,g=_.SPLIT*A,r=s-r,i=this._hi-r,o=g-A;var c=(s=this._hi*A)+(g=r*(o=g-o)-s+r*(a=A-o)+i*o+i*a+(this._hi*n+this._lo*A)),u=g+(r=s-c);return this._hi=c,this._lo=u,this}},_.prototype.selfSqr=function(){return this.selfMultiply(this)},_.prototype.floor=function(){if(this.isNaN())return _.NaN;var e=Math.floor(this._hi),t=0;return e===this._hi&&(t=Math.floor(this._lo)),new _(e,t)},_.prototype.negate=function(){return this.isNaN()?this:new _(-this._hi,-this._lo)},_.prototype.clone=function(){},_.prototype.multiply=function(){if(arguments[0]instanceof _){var e=arguments[0];return e.isNaN()?_.createNaN():_.copy(this).selfMultiply(e)}if("number"==typeof arguments[0]){var t=arguments[0];return p.isNaN(t)?_.createNaN():_.copy(this).selfMultiply(t,0)}},_.prototype.isNaN=function(){return p.isNaN(this._hi)},_.prototype.intValue=function(){return Math.trunc(this._hi)},_.prototype.toString=function(){var e=_.magnitude(this._hi);return e>=-3&&e<=20?this.toStandardNotation():this.toSciNotation()},_.prototype.toStandardNotation=function(){var e=this.getSpecialNumberString();if(null!==e)return e;var t=new Array(1).fill(null),A=this.extractSignificantDigits(!0,t),n=t[0]+1,r=A;if("."===A.charAt(0))r="0"+A;else if(n<0)r="0."+_.stringOfChar("0",-n)+A;else if(-1===A.indexOf(".")){var i=n-A.length;r=A+_.stringOfChar("0",i)+".0"}return this.isNegative()?"-"+r:r},_.prototype.reciprocal=function(){var e,t,A,n,r=null,i=null,o=null,a=null;e=(A=1/this._hi)-(r=(o=_.SPLIT*A)-(r=o-A)),i=(a=_.SPLIT*this._hi)-this._hi;var s=A+(o=(1-(n=A*this._hi)-(a=r*(i=a-i)-n+r*(t=this._hi-i)+e*i+e*t)-A*this._lo)/this._hi);return new _(s,A-s+o)},_.prototype.toSciNotation=function(){if(this.isZero())return _.SCI_NOT_ZERO;var e=this.getSpecialNumberString();if(null!==e)return e;var t=new Array(1).fill(null),A=this.extractSignificantDigits(!1,t),n=_.SCI_NOT_EXPONENT_CHAR+t[0];if("0"===A.charAt(0))throw new Error("Found leading zero: "+A);var r="";A.length>1&&(r=A.substring(1));var i=A.charAt(0)+"."+r;return this.isNegative()?"-"+i+n:i+n},_.prototype.abs=function(){return this.isNaN()?_.NaN:this.isNegative()?this.negate():new _(this)},_.prototype.isPositive=function(){return(this._hi>0||0===this._hi)&&this._lo>0},_.prototype.lt=function(e){return(this._hie._hi||this._hi===e._hi)&&this._lo>e._lo},_.prototype.isNegative=function(){return(this._hi<0||0===this._hi)&&this._lo<0},_.prototype.trunc=function(){return this.isNaN()?_.NaN:this.isPositive()?this.floor():this.ceil()},_.prototype.signum=function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0},_.prototype.interfaces_=function(){return[t,Q,y]},_.prototype.getClass=function(){return _},_.sqr=function(e){return _.valueOf(e).selfMultiply(e)},_.valueOf=function(){if("string"==typeof arguments[0]){var e=arguments[0];return _.parse(e)}if("number"==typeof arguments[0]){var t=arguments[0];return new _(t)}},_.sqrt=function(e){return _.valueOf(e).sqrt()},_.parse=function(e){for(var t=0,A=e.length;U.isWhitespace(e.charAt(t));)t++;var n=!1;if(t=A);){var g=e.charAt(t);if(t++,U.isDigit(g)){var c=g-"0";i.selfMultiply(_.TEN),i.selfAdd(c),o++}else{if("."!==g){if("e"===g||"E"===g){var u=e.substring(t);try{s=N.parseInt(u)}catch(t){throw t instanceof Error?new Error("Invalid exponent "+u+" in string "+e):t}break}throw new Error("Unexpected character '"+g+"' at position "+t+" in string "+e)}a=o}}var l=i,I=o-a-s;if(0===I)l=i;else if(I>0){var C=_.TEN.pow(I);l=i.divide(C)}else if(I<0){var h=_.TEN.pow(-I);l=i.multiply(h)}return n?l.negate():l},_.createNaN=function(){return new _(p.NaN,p.NaN)},_.copy=function(e){return new _(e)},_.magnitude=function(e){var t=Math.abs(e),A=Math.log(t)/Math.log(10),n=Math.trunc(Math.floor(A));return 10*Math.pow(10,n)<=t&&(n+=1),n},_.stringOfChar=function(e,t){for(var A=new x,n=0;n0){if(i<=0)return O.signum(o);n=r+i}else{if(!(r<0))return O.signum(o);if(i>=0)return O.signum(o);n=-r-i}var a=O.DP_SAFE_EPSILON*n;return o>=a||-o>=a?O.signum(o):2},O.signum=function(e){return e>0?1:e<0?-1:0},L.DP_SAFE_EPSILON.get=function(){return 1e-15},Object.defineProperties(O,L);var T=function(){},Z={X:{configurable:!0},Y:{configurable:!0},Z:{configurable:!0},M:{configurable:!0}};Z.X.get=function(){return 0},Z.Y.get=function(){return 1},Z.Z.get=function(){return 2},Z.M.get=function(){return 3},T.prototype.setOrdinate=function(e,t,A){},T.prototype.size=function(){},T.prototype.getOrdinate=function(e,t){},T.prototype.getCoordinate=function(){},T.prototype.getCoordinateCopy=function(e){},T.prototype.getDimension=function(){},T.prototype.getX=function(e){},T.prototype.clone=function(){},T.prototype.expandEnvelope=function(e){},T.prototype.copy=function(){},T.prototype.getY=function(e){},T.prototype.toCoordinateArray=function(){},T.prototype.interfaces_=function(){return[y]},T.prototype.getClass=function(){return T},Object.defineProperties(T,Z);var H=function(){},Y=function(e){function t(){e.call(this,"Projective point not representable on the Cartesian plane.")}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(H),J=function(){};J.arraycopy=function(e,t,A,n,r){for(var i=0,o=t;oe._minx?this._minx:e._minx,A=this._miny>e._miny?this._miny:e._miny,n=this._maxx=this._minx&&t.getMaxX()<=this._maxx&&t.getMinY()>=this._miny&&t.getMaxY()<=this._maxy}}else if(2===arguments.length){var A=arguments[0],n=arguments[1];return!this.isNull()&&A>=this._minx&&A<=this._maxx&&n>=this._miny&&n<=this._maxy}},P.prototype.intersects=function(){if(1===arguments.length){if(arguments[0]instanceof P){var e=arguments[0];return!this.isNull()&&!e.isNull()&&!(e._minx>this._maxx||e._maxxthis._maxy||e._maxythis._maxx||Athis._maxy||nthis._maxx&&(this._maxx=t._maxx),t._minythis._maxy&&(this._maxy=t._maxy))}}else if(2===arguments.length){var A=arguments[0],n=arguments[1];this.isNull()?(this._minx=A,this._maxx=A,this._miny=n,this._maxy=n):(Athis._maxx&&(this._maxx=A),nthis._maxy&&(this._maxy=n))}},P.prototype.minExtent=function(){if(this.isNull())return 0;var e=this.getWidth(),t=this.getHeight();return et._minx?1:this._minyt._miny?1:this._maxxt._maxx?1:this._maxyt._maxy?1:0},P.prototype.translate=function(e,t){if(this.isNull())return null;this.init(this.getMinX()+e,this.getMaxX()+e,this.getMinY()+t,this.getMaxY()+t)},P.prototype.toString=function(){return"Env["+this._minx+" : "+this._maxx+", "+this._miny+" : "+this._maxy+"]"},P.prototype.setToNull=function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1},P.prototype.getHeight=function(){return this.isNull()?0:this._maxy-this._miny},P.prototype.maxExtent=function(){if(this.isNull())return 0;var e=this.getWidth(),t=this.getHeight();return e>t?e:t},P.prototype.expandBy=function(){if(1===arguments.length){var e=arguments[0];this.expandBy(e,e)}else if(2===arguments.length){var t=arguments[0],A=arguments[1];if(this.isNull())return null;this._minx-=t,this._maxx+=t,this._miny-=A,this._maxy+=A,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}},P.prototype.contains=function(){if(1===arguments.length){if(arguments[0]instanceof P){var e=arguments[0];return this.covers(e)}if(arguments[0]instanceof m){var t=arguments[0];return this.covers(t)}}else if(2===arguments.length){var A=arguments[0],n=arguments[1];return this.covers(A,n)}},P.prototype.centre=function(){return this.isNull()?null:new m((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)},P.prototype.init=function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof m){var e=arguments[0];this.init(e.x,e.x,e.y,e.y)}else if(arguments[0]instanceof P){var t=arguments[0];this._minx=t._minx,this._maxx=t._maxx,this._miny=t._miny,this._maxy=t._maxy}}else if(2===arguments.length){var A=arguments[0],n=arguments[1];this.init(A.x,n.x,A.y,n.y)}else if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],a=arguments[3];re._maxx&&(t=this._minx-e._maxx);var A=0;return this._maxye._maxy&&(A=this._miny-e._maxy),0===t?A:0===A?t:Math.sqrt(t*t+A*A)},P.prototype.hashCode=function(){var e=17;return 37*(e=37*(e=37*(e=37*e+m.hashCode(this._minx))+m.hashCode(this._maxx))+m.hashCode(this._miny))+m.hashCode(this._maxy)},P.prototype.interfaces_=function(){return[Q,t]},P.prototype.getClass=function(){return P},P.intersects=function(){if(3===arguments.length){var e=arguments[0],t=arguments[1],A=arguments[2];return A.x>=(e.xt.x?e.x:t.x)&&A.y>=(e.yt.y?e.y:t.y)}if(4===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2],o=arguments[3],a=Math.min(i.x,o.x),s=Math.max(i.x,o.x),g=Math.min(n.x,r.x),c=Math.max(n.x,r.x);return!(g>s)&&!(cs)&&!(cthis.getEdgeDistance(e,1)?(this._intLineIndex[e][0]=0,this._intLineIndex[e][1]=1):(this._intLineIndex[e][0]=1,this._intLineIndex[e][1]=0)}},Ae.prototype.isProper=function(){return this.hasIntersection()&&this._isProper},Ae.prototype.setPrecisionModel=function(e){this._precisionModel=e},Ae.prototype.isInteriorIntersection=function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var e=arguments[0],t=0;tr?n:r;else{var o=Math.abs(e.x-t.x),a=Math.abs(e.y-t.y);0!==(i=n>r?o:a)||e.equals(t)||(i=Math.max(o,a))}return te.isTrue(!(0===i&&!e.equals(t)),"Bad distance calculation"),i},Ae.nonRobustComputeEdgeDistance=function(e,t,A){var n=e.x-t.x,r=e.y-t.y,i=Math.sqrt(n*n+r*r);return te.isTrue(!(0===i&&!e.equals(t)),"Invalid distance calculation"),i},ne.DONT_INTERSECT.get=function(){return 0},ne.DO_INTERSECT.get=function(){return 1},ne.COLLINEAR.get=function(){return 2},ne.NO_INTERSECTION.get=function(){return 0},ne.POINT_INTERSECTION.get=function(){return 1},ne.COLLINEAR_INTERSECTION.get=function(){return 2},Object.defineProperties(Ae,ne);var re=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.isInSegmentEnvelopes=function(e){var t=new P(this._inputLines[0][0],this._inputLines[0][1]),A=new P(this._inputLines[1][0],this._inputLines[1][1]);return t.contains(e)&&A.contains(e)},t.prototype.computeIntersection=function(){if(3!==arguments.length)return e.prototype.computeIntersection.apply(this,arguments);var t=arguments[0],A=arguments[1],n=arguments[2];if(this._isProper=!1,P.intersects(A,n,t)&&0===ae.orientationIndex(A,n,t)&&0===ae.orientationIndex(n,A,t))return this._isProper=!0,(t.equals(A)||t.equals(n))&&(this._isProper=!1),this._result=e.POINT_INTERSECTION,null;this._result=e.NO_INTERSECTION},t.prototype.normalizeToMinimum=function(e,t,A,n,r){r.x=this.smallestInAbsValue(e.x,t.x,A.x,n.x),r.y=this.smallestInAbsValue(e.y,t.y,A.y,n.y),e.x-=r.x,e.y-=r.y,t.x-=r.x,t.y-=r.y,A.x-=r.x,A.y-=r.y,n.x-=r.x,n.y-=r.y},t.prototype.safeHCoordinateIntersection=function(e,A,n,r){var i=null;try{i=j.intersection(e,A,n,r)}catch(o){if(!(o instanceof Y))throw o;i=t.nearestEndpoint(e,A,n,r)}return i},t.prototype.intersection=function(e,A,n,r){var i=this.intersectionWithNormalization(e,A,n,r);return this.isInSegmentEnvelopes(i)||(i=new m(t.nearestEndpoint(e,A,n,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(i),i},t.prototype.smallestInAbsValue=function(e,t,A,n){var r=e,i=Math.abs(r);return Math.abs(t)1e-4&&J.out.println("Distance = "+r.distance(i))},t.prototype.intersectionWithNormalization=function(e,t,A,n){var r=new m(e),i=new m(t),o=new m(A),a=new m(n),s=new m;this.normalizeToEnvCentre(r,i,o,a,s);var g=this.safeHCoordinateIntersection(r,i,o,a);return g.x+=s.x,g.y+=s.y,g},t.prototype.computeCollinearIntersection=function(t,A,n,r){var i=P.intersects(t,A,n),o=P.intersects(t,A,r),a=P.intersects(n,r,t),s=P.intersects(n,r,A);return i&&o?(this._intPt[0]=n,this._intPt[1]=r,e.COLLINEAR_INTERSECTION):a&&s?(this._intPt[0]=t,this._intPt[1]=A,e.COLLINEAR_INTERSECTION):i&&a?(this._intPt[0]=n,this._intPt[1]=t,!n.equals(t)||o||s?e.COLLINEAR_INTERSECTION:e.POINT_INTERSECTION):i&&s?(this._intPt[0]=n,this._intPt[1]=A,!n.equals(A)||o||a?e.COLLINEAR_INTERSECTION:e.POINT_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=t,!r.equals(t)||i||s?e.COLLINEAR_INTERSECTION:e.POINT_INTERSECTION):o&&s?(this._intPt[0]=r,this._intPt[1]=A,!r.equals(A)||i||a?e.COLLINEAR_INTERSECTION:e.POINT_INTERSECTION):e.NO_INTERSECTION},t.prototype.normalizeToEnvCentre=function(e,t,A,n,r){var i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y,g=A.xn.x?A.x:n.x,l=A.y>n.y?A.y:n.y,I=((i>g?i:g)+(ac?o:c)+(s0&&o>0||i<0&&o<0)return e.NO_INTERSECTION;var a=ae.orientationIndex(n,r,t),s=ae.orientationIndex(n,r,A);return a>0&&s>0||a<0&&s<0?e.NO_INTERSECTION:0===i&&0===o&&0===a&&0===s?this.computeCollinearIntersection(t,A,n,r):(0===i||0===o||0===a||0===s?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:A.equals2D(n)||A.equals2D(r)?this._intPt[0]=A:0===i?this._intPt[0]=new m(n):0===o?this._intPt[0]=new m(r):0===a?this._intPt[0]=new m(t):0===s&&(this._intPt[0]=new m(A))):(this._isProper=!0,this._intPt[0]=this.intersection(t,A,n,r)),e.POINT_INTERSECTION)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t.nearestEndpoint=function(e,t,A,n){var r=e,i=ae.distancePointLine(e,A,n),o=ae.distancePointLine(t,A,n);return o0?A>0?-r:r:A>0?r:-r;if(0===t||0===A)return n>0?e>0?r:-r:e>0?-r:r;if(t>0?n>0?t<=n||(r=-r,i=e,e=A,A=i,i=t,t=n,n=i):t<=-n?(r=-r,A=-A,n=-n):(i=e,e=-A,A=i,i=t,t=-n,n=i):n>0?-t<=n?(r=-r,e=-e,t=-t):(i=-e,e=A,A=i,i=-t,t=n,n=i):t>=n?(e=-e,t=-t,A=-A,n=-n):(r=-r,i=-e,e=-A,A=i,i=-t,t=-n,n=i),e>0){if(!(A>0))return r;if(!(e<=A))return r}else{if(A>0)return-r;if(!(e>=A))return-r;r=-r,e=-e,A=-A}for(;;){if((n-=(o=Math.floor(A/e))*t)<0)return-r;if(n>t)return r;if(e>(A-=o*e)+A){if(tn+n)return-r;A=e-A,n=t-n,r=-r}if(0===n)return 0===A?0:-r;if(0===A)return r;if((t-=(o=Math.floor(e/A))*n)<0)return r;if(t>n)return-r;if(A>(e-=o*A)+e){if(nt+t)return r;e=A-e,t=n-t,r=-r}if(0===t)return 0===e?0:r;if(0===e)return-r}};var oe=function(){this._p=null,this._crossingCount=0,this._isPointOnSegment=!1;var e=arguments[0];this._p=e};oe.prototype.countSegment=function(e,t){if(e.xn&&(A=t.x,n=e.x),this._p.x>=A&&this._p.x<=n&&(this._isPointOnSegment=!0),null}if(e.y>this._p.y&&t.y<=this._p.y||t.y>this._p.y&&e.y<=this._p.y){var r=e.x-this._p.x,i=e.y-this._p.y,o=t.x-this._p.x,a=t.y-this._p.y,s=ie.signOfDet2x2(r,i,o,a);if(0===s)return this._isPointOnSegment=!0,null;a0&&this._crossingCount++}},oe.prototype.isPointInPolygon=function(){return this.getLocation()!==F.EXTERIOR},oe.prototype.getLocation=function(){return this._isPointOnSegment?F.BOUNDARY:this._crossingCount%2==1?F.INTERIOR:F.EXTERIOR},oe.prototype.isOnSegment=function(){return this._isPointOnSegment},oe.prototype.interfaces_=function(){return[]},oe.prototype.getClass=function(){return oe},oe.locatePointInRing=function(){if(arguments[0]instanceof m&&D(arguments[1],T)){for(var e=arguments[0],t=arguments[1],A=new oe(e),n=new m,r=new m,i=1;i1||a<0||a>1)&&(r=!0)}}else r=!0;return r?G.min(ae.distancePointLine(e,A,n),ae.distancePointLine(t,A,n),ae.distancePointLine(A,e,t),ae.distancePointLine(n,e,t)):0},ae.isPointInRing=function(e,t){return ae.locatePointInRing(e,t)!==F.EXTERIOR},ae.computeLength=function(e){var t=e.size();if(t<=1)return 0;var A=0,n=new m;e.getCoordinate(0,n);for(var r=n.x,i=n.y,o=1;oA.y&&(A=i,n=r)}var o=n;do{(o-=1)<0&&(o=t)}while(e[o].equals2D(A)&&o!==n);var a=n;do{a=(a+1)%t}while(e[a].equals2D(A)&&a!==n);var s=e[o],g=e[a];if(s.equals2D(A)||g.equals2D(A)||s.equals2D(g))return!1;var c=ae.computeOrientation(s,A,g);return 0===c?s.x>g.x:c>0},ae.locatePointInRing=function(e,t){return oe.locatePointInRing(e,t)},ae.distancePointLinePerpendicular=function(e,t,A){var n=(A.x-t.x)*(A.x-t.x)+(A.y-t.y)*(A.y-t.y),r=((t.y-e.y)*(A.x-t.x)-(t.x-e.x)*(A.y-t.y))/n;return Math.abs(r)*Math.sqrt(n)},ae.computeOrientation=function(e,t,A){return ae.orientationIndex(e,t,A)},ae.distancePointLine=function(){if(2===arguments.length){var e=arguments[0],t=arguments[1];if(0===t.length)throw new B("Line array must contain at least one vertex");for(var A=e.distance(t[0]),n=0;n=1)return i.distance(a);var c=((o.y-i.y)*(a.x-o.x)-(o.x-i.x)*(a.y-o.y))/s;return Math.abs(c)*Math.sqrt(s)}},ae.isOnLine=function(e,t){for(var A=new re,n=1;n0},de.prototype.interfaces_=function(){return[Ce]},de.prototype.getClass=function(){return de};var Be=function(){};Be.prototype.isInBoundary=function(e){return e>1},Be.prototype.interfaces_=function(){return[Ce]},Be.prototype.getClass=function(){return Be};var pe=function(){};pe.prototype.isInBoundary=function(e){return 1===e},pe.prototype.interfaces_=function(){return[Ce]},pe.prototype.getClass=function(){return pe};var Ee=function(){};Ee.prototype.add=function(){},Ee.prototype.addAll=function(){},Ee.prototype.isEmpty=function(){},Ee.prototype.iterator=function(){},Ee.prototype.size=function(){},Ee.prototype.toArray=function(){},Ee.prototype.remove=function(){},(A.prototype=new Error).name="IndexOutOfBoundsException";var Qe=function(){};Qe.prototype.hasNext=function(){},Qe.prototype.next=function(){},Qe.prototype.remove=function(){};var ye=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.get=function(){},t.prototype.set=function(){},t.prototype.isEmpty=function(){},t}(Ee);(n.prototype=new Error).name="NoSuchElementException";var ve=function(e){function t(){e.call(this),this.array_=[],arguments[0]instanceof Ee&&this.addAll(arguments[0])}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.ensureCapacity=function(){},t.prototype.interfaces_=function(){return[e,Ee]},t.prototype.add=function(e){return 1===arguments.length?this.array_.push(e):this.array_.splice(arguments[0],arguments[1]),!0},t.prototype.clear=function(){this.array_=[]},t.prototype.addAll=function(e){for(var t=e.iterator();t.hasNext();)this.add(t.next());return!0},t.prototype.set=function(e,t){var A=this.array_[e];return this.array_[e]=t,A},t.prototype.iterator=function(){return new me(this)},t.prototype.get=function(e){if(e<0||e>=this.size())throw new A;return this.array_[e]},t.prototype.isEmpty=function(){return 0===this.array_.length},t.prototype.size=function(){return this.array_.length},t.prototype.toArray=function(){for(var e=[],t=0,A=this.array_.length;t=1&&this.get(this.size()-1).equals2D(r))return null;e.prototype.add.call(this,r)}else if(arguments[0]instanceof Object&&"boolean"==typeof arguments[1]){var i=arguments[0],o=arguments[1];return this.add(i,o),!0}}else if(3===arguments.length){if("boolean"==typeof arguments[2]&&arguments[0]instanceof Array&&"boolean"==typeof arguments[1]){var a=arguments[0],s=arguments[1];if(arguments[2])for(var g=0;g=0;c--)this.add(a[c],s);return!0}if("boolean"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof m){var u=arguments[0],l=arguments[1];if(!arguments[2]){var I=this.size();if(I>0){if(u>0&&this.get(u-1).equals2D(l))return null;if(ud&&(B=-1);for(var p=f;p!==d;p+=B)this.add(C[p],h);return!0}},t.prototype.closeRing=function(){this.size()>0&&this.add(new m(this.get(0)),!1)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},Object.defineProperties(t,A),t}(ve),we=function(){},Se={ForwardComparator:{configurable:!0},BidirectionalComparator:{configurable:!0},coordArrayType:{configurable:!0}};Se.ForwardComparator.get=function(){return Fe},Se.BidirectionalComparator.get=function(){return Re},Se.coordArrayType.get=function(){return new Array(0).fill(null)},we.prototype.interfaces_=function(){return[]},we.prototype.getClass=function(){return we},we.isRing=function(e){return!(e.length<4)&&!!e[0].equals2D(e[e.length-1])},we.ptNotInList=function(e,t){for(var A=0;A=e?t:[]},we.indexOf=function(e,t){for(var A=0;A0)&&(t=e[A]);return t},we.extract=function(e,t,A){t=G.clamp(t,0,e.length);var n=(A=G.clamp(A,-1,e.length))-t+1;A<0&&(n=0),t>=e.length&&(n=0),An.length)return 1;if(0===A.length)return 0;var r=we.compare(A,n);return we.isEqualReversed(A,n)?0:r},Re.prototype.OLDcompare=function(e,t){var A=e,n=t;if(A.lengthn.length)return 1;if(0===A.length)return 0;for(var r=we.increasingDirection(A),i=we.increasingDirection(n),o=r>0?0:A.length-1,a=i>0?0:A.length-1,s=0;s0))return t.value;t=t.right}}return null},u.prototype.put=function(e,t){if(null===this.root_)return this.root_={key:e,value:t,left:null,right:null,parent:null,color:Ne,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var A,n,r=this.root_;do{if(A=r,(n=e.compareTo(r.key))<0)r=r.left;else{if(!(n>0)){var i=r.value;return r.value=t,i}r=r.right}}while(null!==r);var o={key:e,left:null,right:null,value:t,parent:A,color:Ne,getValue:function(){return this.value},getKey:function(){return this.key}};return n<0?A.left=o:A.right=o,this.fixAfterInsertion(o),this.size_++,null},u.prototype.fixAfterInsertion=function(e){for(e.color=1;null!=e&&e!==this.root_&&1===e.parent.color;)if(a(e)===g(a(a(e)))){var t=c(a(a(e)));1===o(t)?(s(a(e),Ne),s(t,Ne),s(a(a(e)),1),e=a(a(e))):(e===c(a(e))&&(e=a(e),this.rotateLeft(e)),s(a(e),Ne),s(a(a(e)),1),this.rotateRight(a(a(e))))}else{var A=g(a(a(e)));1===o(A)?(s(a(e),Ne),s(A,Ne),s(a(a(e)),1),e=a(a(e))):(e===g(a(e))&&(e=a(e),this.rotateRight(e)),s(a(e),Ne),s(a(a(e)),1),this.rotateLeft(a(a(e))))}this.root_.color=Ne},u.prototype.values=function(){var e=new ve,t=this.getFirstEntry();if(null!==t)for(e.add(t.value);null!==(t=u.successor(t));)e.add(t.value);return e},u.prototype.entrySet=function(){var e=new ke,t=this.getFirstEntry();if(null!==t)for(e.add(t);null!==(t=u.successor(t));)e.add(t);return e},u.prototype.rotateLeft=function(e){if(null!=e){var t=e.right;e.right=t.left,null!=t.left&&(t.left.parent=e),t.parent=e.parent,null===e.parent?this.root_=t:e.parent.left===e?e.parent.left=t:e.parent.right=t,t.left=e,e.parent=t}},u.prototype.rotateRight=function(e){if(null!=e){var t=e.left;e.left=t.right,null!=t.right&&(t.right.parent=e),t.parent=e.parent,null===e.parent?this.root_=t:e.parent.right===e?e.parent.right=t:e.parent.left=t,t.right=e,e.parent=t}},u.prototype.getFirstEntry=function(){var e=this.root_;if(null!=e)for(;null!=e.left;)e=e.left;return e},u.successor=function(e){if(null===e)return null;if(null!==e.right){for(var t=e.right;null!==t.left;)t=t.left;return t}for(var A=e.parent,n=e;null!==A&&n===A.right;)n=A,A=A.parent;return A},u.prototype.size=function(){return this.size_};var Ue=function(){};Ue.prototype.interfaces_=function(){return[]},Ue.prototype.getClass=function(){return Ue},l.prototype=new i,(I.prototype=new l).contains=function(e){for(var t=0,A=this.array_.length;t=0;){var o=r.substring(0,i);n.add(o),i=(r=r.substring(i+A)).indexOf(t)}r.length>0&&n.add(r);for(var a=new Array(n.size()).fill(null),s=0;s0)for(var i=r;i0&&n.append(" ");for(var i=0;i0&&n.append(","),n.append(Pe.toString(e.getOrdinate(r,i)))}return n.append(")"),n.toString()}},Ke.ensureValidRing=function(e,t){var A=t.size();return 0===A?t:A<=3?Ke.createClosedRing(e,t,4):t.getOrdinate(0,T.X)===t.getOrdinate(A-1,T.X)&&t.getOrdinate(0,T.Y)===t.getOrdinate(A-1,T.Y)?t:Ke.createClosedRing(e,t,A+1)},Ke.createClosedRing=function(e,t,A){var n=e.create(A,t.getDimension()),r=t.size();Ke.copy(t,0,n,0,r);for(var i=r;i0&&Ke.reverse(this._points),null}},t.prototype.getCoordinate=function(){return this.isEmpty()?null:this._points.getCoordinate(0)},t.prototype.getBoundaryDimension=function(){return this.isClosed()?Oe.FALSE:0},t.prototype.isClosed=function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))},t.prototype.getEndPoint=function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)},t.prototype.getDimension=function(){return 1},t.prototype.getLength=function(){return ae.computeLength(this._points)},t.prototype.getNumPoints=function(){return this._points.size()},t.prototype.reverse=function(){var e=this._points.copy();return Ke.reverse(e),this.getFactory().createLineString(e)},t.prototype.compareToSameClass=function(){if(1===arguments.length){for(var e=arguments[0],t=0,A=0;t= 2)");this._points=e},t.prototype.isCoordinate=function(e){for(var t=0;t=1&&this.getCoordinateSequence().size()= 4)")},t.prototype.getGeometryType=function(){return"LinearRing"},t.prototype.copy=function(){return new t(this._points.copy(),this._factory)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},A.MINIMUM_VALID_SIZE.get=function(){return 4},A.serialVersionUID.get=function(){return-0x3b229e262367a600},Object.defineProperties(t,A),t}(We),At=function(e){function t(){e.apply(this,arguments)}e&&(t.__proto__=e),(t.prototype=Object.create(e&&e.prototype)).constructor=t;var A={serialVersionUID:{configurable:!0}};return t.prototype.getSortIndex=function(){return ce.SORTINDEX_MULTIPOLYGON},t.prototype.equalsExact=function(){if(2===arguments.length){var t=arguments[0],A=arguments[1];return!!this.isEquivalentClass(t)&&e.prototype.equalsExact.call(this,t,A)}return e.prototype.equalsExact.apply(this,arguments)},t.prototype.getBoundaryDimension=function(){return 1},t.prototype.getDimension=function(){return 2},t.prototype.reverse=function(){for(var e=this._geometries.length,t=new Array(e).fill(null),A=0;A0?t.createPoint(A[0]):t.createPoint():e},ot.prototype.interfaces_=function(){return[nt.GeometryEditorOperation]},ot.prototype.getClass=function(){return ot};var at=function(){};at.prototype.edit=function(e,t){return e instanceof tt?t.createLinearRing(this.edit(e.getCoordinateSequence(),e)):e instanceof We?t.createLineString(this.edit(e.getCoordinateSequence(),e)):e instanceof qe?t.createPoint(this.edit(e.getCoordinateSequence(),e)):e},at.prototype.interfaces_=function(){return[nt.GeometryEditorOperation]},at.prototype.getClass=function(){return at};var st=function(){if(this._dimension=3,this._coordinates=null,1===arguments.length){if(arguments[0]instanceof Array)this._coordinates=arguments[0],this._dimension=3;else if(Number.isInteger(arguments[0])){var e=arguments[0];this._coordinates=new Array(e).fill(null);for(var t=0;t0){var e=new x(17*this._coordinates.length);e.append("("),e.append(this._coordinates[0]);for(var t=1;t3&&(n=3),n<2?new st(A):new st(A,n)}},ct.prototype.interfaces_=function(){return[S,t]},ct.prototype.getClass=function(){return ct},ct.instance=function(){return ct.instanceObject},ut.serialVersionUID.get=function(){return-0x38e49fa6cf6f2e00},ut.instanceObject.get=function(){return new ct},Object.defineProperties(ct,ut);var lt=function(e){function t(){e.call(this),this.map_=new Map}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.get=function(e){return this.map_.get(e)||null},t.prototype.put=function(e,t){return this.map_.set(e,t),t},t.prototype.values=function(){for(var e=new ve,t=this.map_.values(),A=t.next();!A.done;)e.add(A.value),A=t.next();return e},t.prototype.entrySet=function(){var e=new ke;return this.map_.entries().forEach((function(t){return e.add(t)})),e},t.prototype.size=function(){return this.map_.size()},t}(De),It=function e(){if(this._modelType=null,this._scale=null,0===arguments.length)this._modelType=e.FLOATING;else if(1===arguments.length)if(arguments[0]instanceof ht){var t=arguments[0];this._modelType=t,t===e.FIXED&&this.setScale(1)}else if("number"==typeof arguments[0]){var A=arguments[0];this._modelType=e.FIXED,this.setScale(A)}else if(arguments[0]instanceof e){var n=arguments[0];this._modelType=n._modelType,this._scale=n._scale}},Ct={serialVersionUID:{configurable:!0},maximumPreciseValue:{configurable:!0}};It.prototype.equals=function(e){if(!(e instanceof It))return!1;var t=e;return this._modelType===t._modelType&&this._scale===t._scale},It.prototype.compareTo=function(e){var t=e,A=this.getMaximumSignificantDigits(),n=t.getMaximumSignificantDigits();return new N(A).compareTo(new N(n))},It.prototype.getScale=function(){return this._scale},It.prototype.isFloating=function(){return this._modelType===It.FLOATING||this._modelType===It.FLOATING_SINGLE},It.prototype.getType=function(){return this._modelType},It.prototype.toString=function(){var e="UNKNOWN";return this._modelType===It.FLOATING?e="Floating":this._modelType===It.FLOATING_SINGLE?e="Floating-Single":this._modelType===It.FIXED&&(e="Fixed (Scale="+this.getScale()+")"),e},It.prototype.makePrecise=function(){if("number"==typeof arguments[0]){var e=arguments[0];return p.isNaN(e)||this._modelType===It.FLOATING_SINGLE?e:this._modelType===It.FIXED?Math.round(e*this._scale)/this._scale:e}if(arguments[0]instanceof m){var t=arguments[0];if(this._modelType===It.FLOATING)return null;t.x=this.makePrecise(t.x),t.y=this.makePrecise(t.y)}},It.prototype.getMaximumSignificantDigits=function(){var e=16;return this._modelType===It.FLOATING?e=16:this._modelType===It.FLOATING_SINGLE?e=6:this._modelType===It.FIXED&&(e=1+Math.trunc(Math.ceil(Math.log(this.getScale())/Math.log(10)))),e},It.prototype.setScale=function(e){this._scale=Math.abs(e)},It.prototype.interfaces_=function(){return[t,Q]},It.prototype.getClass=function(){return It},It.mostPrecise=function(e,t){return e.compareTo(t)>=0?e:t},Ct.serialVersionUID.get=function(){return 0x6bee6404e9a25c00},Ct.maximumPreciseValue.get=function(){return 9007199254740992},Object.defineProperties(It,Ct);var ht=function e(t){this._name=t||null,e.nameToTypeMap.put(t,this)},ft={serialVersionUID:{configurable:!0},nameToTypeMap:{configurable:!0}};ht.prototype.readResolve=function(){return ht.nameToTypeMap.get(this._name)},ht.prototype.toString=function(){return this._name},ht.prototype.interfaces_=function(){return[t]},ht.prototype.getClass=function(){return ht},ft.serialVersionUID.get=function(){return-552860263173159e4},ft.nameToTypeMap.get=function(){return new lt},Object.defineProperties(ht,ft),It.Type=ht,It.FIXED=new ht("FIXED"),It.FLOATING=new ht("FLOATING"),It.FLOATING_SINGLE=new ht("FLOATING SINGLE");var dt=function e(){this._precisionModel=new It,this._SRID=0,this._coordinateSequenceFactory=e.getDefaultCoordinateSequenceFactory(),0===arguments.length||(1===arguments.length?D(arguments[0],S)?this._coordinateSequenceFactory=arguments[0]:arguments[0]instanceof It&&(this._precisionModel=arguments[0]):2===arguments.length?(this._precisionModel=arguments[0],this._SRID=arguments[1]):3===arguments.length&&(this._precisionModel=arguments[0],this._SRID=arguments[1],this._coordinateSequenceFactory=arguments[2]))},Bt={serialVersionUID:{configurable:!0}};dt.prototype.toGeometry=function(e){return e.isNull()?this.createPoint(null):e.getMinX()===e.getMaxX()&&e.getMinY()===e.getMaxY()?this.createPoint(new m(e.getMinX(),e.getMinY())):e.getMinX()===e.getMaxX()||e.getMinY()===e.getMaxY()?this.createLineString([new m(e.getMinX(),e.getMinY()),new m(e.getMaxX(),e.getMaxY())]):this.createPolygon(this.createLinearRing([new m(e.getMinX(),e.getMinY()),new m(e.getMinX(),e.getMaxY()),new m(e.getMaxX(),e.getMaxY()),new m(e.getMaxX(),e.getMinY()),new m(e.getMinX(),e.getMinY())]),null)},dt.prototype.createLineString=function(e){return e?e instanceof Array?new We(this.getCoordinateSequenceFactory().create(e),this):D(e,T)?new We(e,this):void 0:new We(this.getCoordinateSequenceFactory().create([]),this)},dt.prototype.createMultiLineString=function(){if(0===arguments.length)return new Ye(null,this);if(1===arguments.length){var e=arguments[0];return new Ye(e,this)}},dt.prototype.buildGeometry=function(e){for(var t=null,A=!1,n=!1,r=e.iterator();r.hasNext();){var i=r.next(),o=i.getClass();null===t&&(t=o),o!==t&&(A=!0),i.isGeometryCollectionOrDerived()&&(n=!0)}if(null===t)return this.createGeometryCollection();if(A||n)return this.createGeometryCollection(dt.toGeometryArray(e));var a=e.iterator().next();if(e.size()>1){if(a instanceof $e)return this.createMultiPolygon(dt.toPolygonArray(e));if(a instanceof We)return this.createMultiLineString(dt.toLineStringArray(e));if(a instanceof qe)return this.createMultiPoint(dt.toPointArray(e));te.shouldNeverReachHere("Unhandled class: "+a.getClass().getName())}return a},dt.prototype.createMultiPointFromCoords=function(e){return this.createMultiPoint(null!==e?this.getCoordinateSequenceFactory().create(e):null)},dt.prototype.createPoint=function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof m){var e=arguments[0];return this.createPoint(null!==e?this.getCoordinateSequenceFactory().create([e]):null)}if(D(arguments[0],T)){var t=arguments[0];return new qe(t,this)}}},dt.prototype.getCoordinateSequenceFactory=function(){return this._coordinateSequenceFactory},dt.prototype.createPolygon=function(){if(0===arguments.length)return new $e(null,null,this);if(1===arguments.length){if(D(arguments[0],T)){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof Array){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof tt){var A=arguments[0];return this.createPolygon(A,null)}}else if(2===arguments.length){var n=arguments[0],r=arguments[1];return new $e(n,r,this)}},dt.prototype.getSRID=function(){return this._SRID},dt.prototype.createGeometryCollection=function(){if(0===arguments.length)return new He(null,this);if(1===arguments.length){var e=arguments[0];return new He(e,this)}},dt.prototype.createGeometry=function(e){return new nt(this).edit(e,{edit:function(){if(2===arguments.length){var e=arguments[0];return this._coordinateSequenceFactory.create(e)}}})},dt.prototype.getPrecisionModel=function(){return this._precisionModel},dt.prototype.createLinearRing=function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var e=arguments[0];return this.createLinearRing(null!==e?this.getCoordinateSequenceFactory().create(e):null)}if(D(arguments[0],T)){var t=arguments[0];return new tt(t,this)}}},dt.prototype.createMultiPolygon=function(){if(0===arguments.length)return new At(null,this);if(1===arguments.length){var e=arguments[0];return new At(e,this)}},dt.prototype.createMultiPoint=function(){if(0===arguments.length)return new et(null,this);if(1===arguments.length){if(arguments[0]instanceof Array){var e=arguments[0];return new et(e,this)}if(arguments[0]instanceof Array){var t=arguments[0];return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(D(arguments[0],T)){var A=arguments[0];if(null===A)return this.createMultiPoint(new Array(0).fill(null));for(var n=new Array(A.size()).fill(null),r=0;r=this.size())throw new Error;return this.array_[e]},f.prototype.push=function(e){return this.array_.push(e),e},f.prototype.pop=function(e){if(0===this.array_.length)throw new h;return this.array_.pop()},f.prototype.peek=function(){if(0===this.array_.length)throw new h;return this.array_[this.array_.length-1]},f.prototype.empty=function(){return 0===this.array_.length},f.prototype.isEmpty=function(){return this.empty()},f.prototype.search=function(e){return this.array_.indexOf(e)},f.prototype.size=function(){return this.array_.length},f.prototype.toArray=function(){for(var e=[],t=0,A=this.array_.length;t0&&this._minIndexthis._minCoord.y&&A.y>this._minCoord.y&&n===ae.CLOCKWISE)&&(r=!0),r&&(this._minIndex=this._minIndex-1)},St.prototype.getRightmostSideOfSegment=function(e,t){var A=e.getEdge().getCoordinates();if(t<0||t+1>=A.length)return-1;if(A[t].y===A[t+1].y)return-1;var n=bt.LEFT;return A[t].ythis._minCoord.x)&&(this._minDe=e,this._minIndex=A,this._minCoord=t[A])},St.prototype.findRightmostEdgeAtNode=function(){var e=this._minDe.getNode().getEdges();this._minDe=e.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)},St.prototype.findEdge=function(e){for(var t=e.iterator();t.hasNext();){var A=t.next();A.isForward()&&this.checkForRightmostCoordinate(A)}te.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===bt.LEFT&&(this._orientedDe=this._minDe.getSym())},St.prototype.interfaces_=function(){return[]},St.prototype.getClass=function(){return St};var Ft=function(e){function t(A,n){e.call(this,t.msgWithCoord(A,n)),this.pt=n?new m(n):null,this.name="TopologyException"}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.getCoordinate=function(){return this.pt},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t.msgWithCoord=function(e,t){return t?e:e+" [ "+t+" ]"},t}($),Rt=function(){this.array_=[]};Rt.prototype.addLast=function(e){this.array_.push(e)},Rt.prototype.removeFirst=function(){return this.array_.shift()},Rt.prototype.isEmpty=function(){return 0===this.array_.length};var Dt=function(){this._finder=null,this._dirEdgeList=new ve,this._nodes=new ve,this._rightMostCoord=null,this._env=null,this._finder=new St};Dt.prototype.clearVisitedEdges=function(){for(var e=this._dirEdgeList.iterator();e.hasNext();)e.next().setVisited(!1)},Dt.prototype.getRightmostCoordinate=function(){return this._rightMostCoord},Dt.prototype.computeNodeDepth=function(e){for(var t=null,A=e.getEdges().iterator();A.hasNext();){var n=A.next();if(n.isVisited()||n.getSym().isVisited()){t=n;break}}if(null===t)throw new Ft("unable to find edge to compute depths at "+e.getCoordinate());e.getEdges().computeDepths(t);for(var r=e.getEdges().iterator();r.hasNext();){var i=r.next();i.setVisited(!0),this.copySymDepths(i)}},Dt.prototype.computeDepth=function(e){this.clearVisitedEdges();var t=this._finder.getEdge();t.setEdgeDepths(bt.RIGHT,e),this.copySymDepths(t),this.computeDepths(t)},Dt.prototype.create=function(e){this.addReachable(e),this._finder.findEdge(this._dirEdgeList),this._rightMostCoord=this._finder.getCoordinate()},Dt.prototype.findResultEdges=function(){for(var e=this._dirEdgeList.iterator();e.hasNext();){var t=e.next();t.getDepth(bt.RIGHT)>=1&&t.getDepth(bt.LEFT)<=0&&!t.isInteriorAreaEdge()&&t.setInResult(!0)}},Dt.prototype.computeDepths=function(e){var t=new ke,A=new Rt,n=e.getNode();for(A.addLast(n),t.add(n),e.setVisited(!0);!A.isEmpty();){var r=A.removeFirst();t.add(r),this.computeNodeDepth(r);for(var i=r.getEdges().iterator();i.hasNext();){var o=i.next().getSym();if(!o.isVisited()){var a=o.getNode();t.contains(a)||(A.addLast(a),t.add(a))}}}},Dt.prototype.compareTo=function(e){var t=e;return this._rightMostCoord.xt._rightMostCoord.x?1:0},Dt.prototype.getEnvelope=function(){if(null===this._env){for(var e=new P,t=this._dirEdgeList.iterator();t.hasNext();)for(var A=t.next().getEdge().getCoordinates(),n=0;nthis.location.length){var t=new Array(3).fill(null);t[bt.ON]=this.location[bt.ON],t[bt.LEFT]=F.NONE,t[bt.RIGHT]=F.NONE,this.location=t}for(var A=0;A1&&e.append(F.toLocationSymbol(this.location[bt.LEFT])),e.append(F.toLocationSymbol(this.location[bt.ON])),this.location.length>1&&e.append(F.toLocationSymbol(this.location[bt.RIGHT])),e.toString()},Gt.prototype.setLocations=function(e,t,A){this.location[bt.ON]=e,this.location[bt.LEFT]=t,this.location[bt.RIGHT]=A},Gt.prototype.get=function(e){return e1},Gt.prototype.isAnyNull=function(){for(var e=0;ethis._maxNodeDegree&&(this._maxNodeDegree=t),e=this.getNext(e)}while(e!==this._startDe);this._maxNodeDegree*=2},xt.prototype.addPoints=function(e,t,A){var n=e.getCoordinates();if(t){var r=1;A&&(r=0);for(var i=r;i=0;a--)this._pts.add(n[a])}},xt.prototype.isHole=function(){return this._isHole},xt.prototype.setInResult=function(){var e=this._startDe;do{e.getEdge().setInResult(!0),e=e.getNext()}while(e!==this._startDe)},xt.prototype.containsPoint=function(e){var t=this.getLinearRing();if(!t.getEnvelopeInternal().contains(e))return!1;if(!ae.isPointInRing(e,t.getCoordinates()))return!1;for(var A=this._holes.iterator();A.hasNext();)if(A.next().containsPoint(e))return!1;return!0},xt.prototype.addHole=function(e){this._holes.add(e)},xt.prototype.isShell=function(){return null===this._shell},xt.prototype.getLabel=function(){return this._label},xt.prototype.getEdges=function(){return this._edges},xt.prototype.getMaxNodeDegree=function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree},xt.prototype.getShell=function(){return this._shell},xt.prototype.mergeLabel=function(){if(1===arguments.length){var e=arguments[0];this.mergeLabel(e,0),this.mergeLabel(e,1)}else if(2===arguments.length){var t=arguments[0],A=arguments[1],n=t.getLocation(A,bt.RIGHT);if(n===F.NONE)return null;if(this._label.getLocation(A)===F.NONE)return this._label.setLocation(A,n),null}},xt.prototype.setShell=function(e){this._shell=e,null!==e&&e.addHole(this)},xt.prototype.toPolygon=function(e){for(var t=new Array(this._holes.size()).fill(null),A=0;A=2,"found partial label"),this.computeIM(e)},_t.prototype.isInResult=function(){return this._isInResult},_t.prototype.isVisited=function(){return this._isVisited},_t.prototype.interfaces_=function(){return[]},_t.prototype.getClass=function(){return _t};var Mt=function(e){function t(){e.call(this),this._coord=null,this._edges=null;var t=arguments[0],A=arguments[1];this._coord=t,this._edges=A,this._label=new kt(0,F.NONE)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.isIncidentEdgeInResult=function(){for(var e=this.getEdges().getEdges().iterator();e.hasNext();)if(e.next().getEdge().isInResult())return!0;return!1},t.prototype.isIsolated=function(){return 1===this._label.getGeometryCount()},t.prototype.getCoordinate=function(){return this._coord},t.prototype.print=function(e){e.println("node "+this._coord+" lbl: "+this._label)},t.prototype.computeIM=function(e){},t.prototype.computeMergedLocation=function(e,t){var A=F.NONE;if(A=this._label.getLocation(t),!e.isNull(t)){var n=e.getLocation(t);A!==F.BOUNDARY&&(A=n)}return A},t.prototype.setLabel=function(){if(2!==arguments.length)return e.prototype.setLabel.apply(this,arguments);var t=arguments[0],A=arguments[1];null===this._label?this._label=new kt(t,A):this._label.setLocation(t,A)},t.prototype.getEdges=function(){return this._edges},t.prototype.mergeLabel=function(){if(arguments[0]instanceof t){var e=arguments[0];this.mergeLabel(e._label)}else if(arguments[0]instanceof kt)for(var A=arguments[0],n=0;n<2;n++){var r=this.computeMergedLocation(A,n);this._label.getLocation(n)===F.NONE&&this._label.setLocation(n,r)}},t.prototype.add=function(e){this._edges.insert(e),e.setNode(this)},t.prototype.setLabelBoundary=function(e){if(null===this._label)return null;var t=F.NONE;null!==this._label&&(t=this._label.getLocation(e));var A=null;switch(t){case F.BOUNDARY:A=F.INTERIOR;break;case F.INTERIOR:default:A=F.BOUNDARY}this._label.setLocation(e,A)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(_t),Ot=function(){this.nodeMap=new u,this.nodeFact=null;var e=arguments[0];this.nodeFact=e};Ot.prototype.find=function(e){return this.nodeMap.get(e)},Ot.prototype.addNode=function(){if(arguments[0]instanceof m){var e=arguments[0],t=this.nodeMap.get(e);return null===t&&(t=this.nodeFact.createNode(e),this.nodeMap.put(e,t)),t}if(arguments[0]instanceof Mt){var A=arguments[0],n=this.nodeMap.get(A.getCoordinate());return null===n?(this.nodeMap.put(A.getCoordinate(),A),A):(n.mergeLabel(A),n)}},Ot.prototype.print=function(e){for(var t=this.iterator();t.hasNext();)t.next().print(e)},Ot.prototype.iterator=function(){return this.nodeMap.values().iterator()},Ot.prototype.values=function(){return this.nodeMap.values()},Ot.prototype.getBoundaryNodes=function(e){for(var t=new ve,A=this.iterator();A.hasNext();){var n=A.next();n.getLabel().getLocation(e)===F.BOUNDARY&&t.add(n)}return t},Ot.prototype.add=function(e){var t=e.getCoordinate();this.addNode(t).add(e)},Ot.prototype.interfaces_=function(){return[]},Ot.prototype.getClass=function(){return Ot};var Lt=function(){},Tt={NE:{configurable:!0},NW:{configurable:!0},SW:{configurable:!0},SE:{configurable:!0}};Lt.prototype.interfaces_=function(){return[]},Lt.prototype.getClass=function(){return Lt},Lt.isNorthern=function(e){return e===Lt.NE||e===Lt.NW},Lt.isOpposite=function(e,t){return e!==t&&2===(e-t+4)%4},Lt.commonHalfPlane=function(e,t){if(e===t)return e;if(2===(e-t+4)%4)return-1;var A=et?e:t)?3:A},Lt.isInHalfPlane=function(e,t){return t===Lt.SE?e===Lt.SE||e===Lt.SW:e===t||e===t+1},Lt.quadrant=function(){if("number"==typeof arguments[0]&&"number"==typeof arguments[1]){var e=arguments[0],t=arguments[1];if(0===e&&0===t)throw new B("Cannot compute the quadrant for point ( "+e+", "+t+" )");return e>=0?t>=0?Lt.NE:Lt.SE:t>=0?Lt.NW:Lt.SW}if(arguments[0]instanceof m&&arguments[1]instanceof m){var A=arguments[0],n=arguments[1];if(n.x===A.x&&n.y===A.y)throw new B("Cannot compute the quadrant for two identical points "+A);return n.x>=A.x?n.y>=A.y?Lt.NE:Lt.SE:n.y>=A.y?Lt.NW:Lt.SW}},Tt.NE.get=function(){return 0},Tt.NW.get=function(){return 1},Tt.SW.get=function(){return 2},Tt.SE.get=function(){return 3},Object.defineProperties(Lt,Tt);var Zt=function(){if(this._edge=null,this._label=null,this._node=null,this._p0=null,this._p1=null,this._dx=null,this._dy=null,this._quadrant=null,1===arguments.length){var e=arguments[0];this._edge=e}else if(3===arguments.length){var t=arguments[0],A=arguments[1],n=arguments[2];this._edge=t,this.init(A,n),this._label=null}else if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],a=arguments[3];this._edge=r,this.init(i,o),this._label=a}};Zt.prototype.compareDirection=function(e){return this._dx===e._dx&&this._dy===e._dy?0:this._quadrant>e._quadrant?1:this._quadrant2){i.linkDirectedEdgesForMinimalEdgeRings();var o=i.buildMinimalRings(),a=this.findShell(o);null!==a?(this.placePolygonHoles(a,o),t.add(a)):A.addAll(o)}else n.add(i)}return n},jt.prototype.containsPoint=function(e){for(var t=this._shellList.iterator();t.hasNext();)if(t.next().containsPoint(e))return!0;return!1},jt.prototype.buildMaximalEdgeRings=function(e){for(var t=new ve,A=e.iterator();A.hasNext();){var n=A.next();if(n.isInResult()&&n.getLabel().isArea()&&null===n.getEdgeRing()){var r=new Ut(n,this._geometryFactory);t.add(r),r.setInResult()}}return t},jt.prototype.placePolygonHoles=function(e,t){for(var A=t.iterator();A.hasNext();){var n=A.next();n.isHole()&&n.setShell(e)}},jt.prototype.getPolygons=function(){return this.computePolygons(this._shellList)},jt.prototype.findEdgeRingContaining=function(e,t){for(var A=e.getLinearRing(),n=A.getEnvelopeInternal(),r=A.getCoordinateN(0),i=null,o=null,a=t.iterator();a.hasNext();){var s=a.next(),g=s.getLinearRing(),c=g.getEnvelopeInternal();null!==i&&(o=i.getLinearRing().getEnvelopeInternal());var u=!1;c.contains(n)&&ae.isPointInRing(r,g.getCoordinates())&&(u=!0),u&&(null===i||o.contains(c))&&(i=s)}return i},jt.prototype.findShell=function(e){for(var t=0,A=null,n=e.iterator();n.hasNext();){var r=n.next();r.isHole()||(A=r,t++)}return te.isTrue(t<=1,"found two shells in MinimalEdgeRing list"),A},jt.prototype.add=function(){if(1===arguments.length){var e=arguments[0];this.add(e.getEdgeEnds(),e.getNodes())}else if(2===arguments.length){var t=arguments[0],A=arguments[1];Jt.linkResultDirectedEdges(A);var n=this.buildMaximalEdgeRings(t),r=new ve,i=this.buildMinimalEdgeRings(n,this._shellList,r);this.sortShellsAndHoles(i,this._shellList,r),this.placeFreeHoles(this._shellList,r)}},jt.prototype.interfaces_=function(){return[]},jt.prototype.getClass=function(){return jt};var Pt=function(){};Pt.prototype.getBounds=function(){},Pt.prototype.interfaces_=function(){return[]},Pt.prototype.getClass=function(){return Pt};var Vt=function(){this._bounds=null,this._item=null;var e=arguments[0],t=arguments[1];this._bounds=e,this._item=t};Vt.prototype.getItem=function(){return this._item},Vt.prototype.getBounds=function(){return this._bounds},Vt.prototype.interfaces_=function(){return[Pt,t]},Vt.prototype.getClass=function(){return Vt};var Kt=function(){this._size=null,this._items=null,this._size=0,this._items=new ve,this._items.add(null)};Kt.prototype.poll=function(){if(this.isEmpty())return null;var e=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),e},Kt.prototype.size=function(){return this._size},Kt.prototype.reorder=function(e){for(var t=null,A=this._items.get(e);2*e<=this._size&&((t=2*e)!==this._size&&this._items.get(t+1).compareTo(this._items.get(t))<0&&t++,this._items.get(t).compareTo(A)<0);e=t)this._items.set(e,this._items.get(t));this._items.set(e,A)},Kt.prototype.clear=function(){this._size=0,this._items.clear()},Kt.prototype.isEmpty=function(){return 0===this._size},Kt.prototype.add=function(e){this._items.add(null),this._size+=1;var t=this._size;for(this._items.set(0,e);e.compareTo(this._items.get(Math.trunc(t/2)))<0;t/=2)this._items.set(t,this._items.get(Math.trunc(t/2)));this._items.set(t,e)},Kt.prototype.interfaces_=function(){return[]},Kt.prototype.getClass=function(){return Kt};var Wt=function(){};Wt.prototype.visitItem=function(e){},Wt.prototype.interfaces_=function(){return[]},Wt.prototype.getClass=function(){return Wt};var Xt=function(){};Xt.prototype.insert=function(e,t){},Xt.prototype.remove=function(e,t){},Xt.prototype.query=function(){},Xt.prototype.interfaces_=function(){return[]},Xt.prototype.getClass=function(){return Xt};var qt=function(){if(this._childBoundables=new ve,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var e=arguments[0];this._level=e}},zt={serialVersionUID:{configurable:!0}};qt.prototype.getLevel=function(){return this._level},qt.prototype.size=function(){return this._childBoundables.size()},qt.prototype.getChildBoundables=function(){return this._childBoundables},qt.prototype.addChildBoundable=function(e){te.isTrue(null===this._bounds),this._childBoundables.add(e)},qt.prototype.isEmpty=function(){return this._childBoundables.isEmpty()},qt.prototype.getBounds=function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds},qt.prototype.interfaces_=function(){return[Pt,t]},qt.prototype.getClass=function(){return qt},zt.serialVersionUID.get=function(){return 0x5a1e55ec41369800},Object.defineProperties(qt,zt);var $t=function(){};$t.reverseOrder=function(){return{compare:function(e,t){return t.compareTo(e)}}},$t.min=function(e){return $t.sort(e),e.get(0)},$t.sort=function(e,t){var A=e.toArray();t?Me.sort(A,t):Me.sort(A);for(var n=e.iterator(),r=0,i=A.length;reA.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,e,t),null):(this.expand(this._boundable2,this._boundable1,e,t),null);if(A)return this.expand(this._boundable1,this._boundable2,e,t),null;if(n)return this.expand(this._boundable2,this._boundable1,e,t),null;throw new B("neither boundable is composite")},eA.prototype.isLeaves=function(){return!(eA.isComposite(this._boundable1)||eA.isComposite(this._boundable2))},eA.prototype.compareTo=function(e){var t=e;return this._distancet._distance?1:0},eA.prototype.expand=function(e,t,A,n){for(var r=e.getChildBoundables().iterator();r.hasNext();){var i=r.next(),o=new eA(i,t,this._itemDistance);o.getDistance()1,"Node capacity must be greater than 1"),this._nodeCapacity=A}},AA={IntersectsOp:{configurable:!0},serialVersionUID:{configurable:!0},DEFAULT_NODE_CAPACITY:{configurable:!0}};tA.prototype.getNodeCapacity=function(){return this._nodeCapacity},tA.prototype.lastNode=function(e){return e.get(e.size()-1)},tA.prototype.size=function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.size(this._root));if(1===arguments.length){for(var e=0,t=arguments[0].getChildBoundables().iterator();t.hasNext();){var A=t.next();A instanceof qt?e+=this.size(A):A instanceof Vt&&(e+=1)}return e}},tA.prototype.removeItem=function(e,t){for(var A=null,n=e.getChildBoundables().iterator();n.hasNext();){var r=n.next();r instanceof Vt&&r.getItem()===t&&(A=r)}return null!==A&&(e.getChildBoundables().remove(A),!0)},tA.prototype.itemsTree=function(){if(0===arguments.length){this.build();var e=this.itemsTree(this._root);return null===e?new ve:e}if(1===arguments.length){for(var t=arguments[0],A=new ve,n=t.getChildBoundables().iterator();n.hasNext();){var r=n.next();if(r instanceof qt){var i=this.itemsTree(r);null!==i&&A.add(i)}else r instanceof Vt?A.add(r.getItem()):te.shouldNeverReachHere()}return A.size()<=0?null:A}},tA.prototype.insert=function(e,t){te.isTrue(!this._built,"Cannot insert items into an STR packed R-tree after it has been built."),this._itemBoundables.add(new Vt(e,t))},tA.prototype.boundablesAtLevel=function(){if(1===arguments.length){var e=arguments[0],t=new ve;return this.boundablesAtLevel(e,this._root,t),t}if(3===arguments.length){var A=arguments[0],n=arguments[1],r=arguments[2];if(te.isTrue(A>-2),n.getLevel()===A)return r.add(n),null;for(var i=n.getChildBoundables().iterator();i.hasNext();){var o=i.next();o instanceof qt?this.boundablesAtLevel(A,o,r):(te.isTrue(o instanceof Vt),-1===A&&r.add(o))}return null}},tA.prototype.query=function(){if(1===arguments.length){var e=arguments[0];this.build();var t=new ve;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),e)&&this.query(e,this._root,t),t}if(2===arguments.length){var A=arguments[0],n=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),A)&&this.query(A,this._root,n)}else if(3===arguments.length)if(D(arguments[2],Wt)&&arguments[0]instanceof Object&&arguments[1]instanceof qt)for(var r=arguments[0],i=arguments[1],o=arguments[2],a=i.getChildBoundables(),s=0;se&&(e=n)}}return e+1}},tA.prototype.createParentBoundables=function(e,t){te.isTrue(!e.isEmpty());var A=new ve;A.add(this.createNode(t));var n=new ve(e);$t.sort(n,this.getComparator());for(var r=n.iterator();r.hasNext();){var i=r.next();this.lastNode(A).getChildBoundables().size()===this.getNodeCapacity()&&A.add(this.createNode(t)),this.lastNode(A).addChildBoundable(i)}return A},tA.prototype.isEmpty=function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()},tA.prototype.interfaces_=function(){return[t]},tA.prototype.getClass=function(){return tA},tA.compareDoubles=function(e,t){return e>t?1:e0);for(var A=new ve,n=0;n0;){var u=c.poll(),l=u.getDistance();if(l>=s)break;u.isLeaves()?(s=l,g=u):u.expandToQueue(c,s)}return[g.getBoundable(0).getItem(),g.getBoundable(1).getItem()]}}else if(3===arguments.length){var I=arguments[0],C=arguments[1],h=arguments[2],f=new Vt(I,C),d=new eA(this.getRoot(),f,h);return this.nearestNeighbour(d)[0]}},A.prototype.interfaces_=function(){return[Xt,t]},A.prototype.getClass=function(){return A},A.centreX=function(e){return A.avg(e.getMinX(),e.getMaxX())},A.avg=function(e,t){return(e+t)/2},A.centreY=function(e){return A.avg(e.getMinY(),e.getMaxY())},n.STRtreeNode.get=function(){return oA},n.serialVersionUID.get=function(){return 0x39920f7d5f261e0},n.xComparator.get=function(){return{interfaces_:function(){return[v]},compare:function(t,n){return e.compareDoubles(A.centreX(t.getBounds()),A.centreX(n.getBounds()))}}},n.yComparator.get=function(){return{interfaces_:function(){return[v]},compare:function(t,n){return e.compareDoubles(A.centreY(t.getBounds()),A.centreY(n.getBounds()))}}},n.intersectsOp.get=function(){return{interfaces_:function(){return[e.IntersectsOp]},intersects:function(e,t){return e.intersects(t)}}},n.DEFAULT_NODE_CAPACITY.get=function(){return 10},Object.defineProperties(A,n),A}(tA),oA=function(e){function t(){var t=arguments[0];e.call(this,t)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.computeBounds=function(){for(var e=null,t=this.getChildBoundables().iterator();t.hasNext();){var A=t.next();null===e?e=new P(A.getBounds()):e.expandToInclude(A.getBounds())}return e},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(qt),aA=function(){};aA.prototype.interfaces_=function(){return[]},aA.prototype.getClass=function(){return aA},aA.relativeSign=function(e,t){return et?1:0},aA.compare=function(e,t,A){if(t.equals2D(A))return 0;var n=aA.relativeSign(t.x,A.x),r=aA.relativeSign(t.y,A.y);switch(e){case 0:return aA.compareValue(n,r);case 1:return aA.compareValue(r,n);case 2:return aA.compareValue(r,-n);case 3:return aA.compareValue(-n,r);case 4:return aA.compareValue(-n,-r);case 5:return aA.compareValue(-r,-n);case 6:return aA.compareValue(-r,n);case 7:return aA.compareValue(n,-r)}return te.shouldNeverReachHere("invalid octant value"),0},aA.compareValue=function(e,t){return e<0?-1:e>0?1:t<0?-1:t>0?1:0};var sA=function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var e=arguments[0],t=arguments[1],A=arguments[2],n=arguments[3];this._segString=e,this.coord=new m(t),this.segmentIndex=A,this._segmentOctant=n,this._isInterior=!t.equals2D(e.getCoordinate(A))};sA.prototype.getCoordinate=function(){return this.coord},sA.prototype.print=function(e){e.print(this.coord),e.print(" seg # = "+this.segmentIndex)},sA.prototype.compareTo=function(e){var t=e;return this.segmentIndext.segmentIndex?1:this.coord.equals2D(t.coord)?0:aA.compare(this._segmentOctant,this.coord,t.coord)},sA.prototype.isEndPoint=function(e){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===e},sA.prototype.isInterior=function(){return this._isInterior},sA.prototype.interfaces_=function(){return[Q]},sA.prototype.getClass=function(){return sA};var gA=function(){this._nodeMap=new u,this._edge=null;var e=arguments[0];this._edge=e};gA.prototype.getSplitCoordinates=function(){var e=new be;this.addEndpoints();for(var t=this.iterator(),A=t.next();t.hasNext();){var n=t.next();this.addEdgeCoordinates(A,n,e),A=n}return e.toCoordinateArray()},gA.prototype.addCollapsedNodes=function(){var e=new ve;this.findCollapsesFromInsertedNodes(e),this.findCollapsesFromExistingVertices(e);for(var t=e.iterator();t.hasNext();){var A=t.next().intValue();this.add(this._edge.getCoordinate(A),A)}},gA.prototype.print=function(e){e.println("Intersections:");for(var t=this.iterator();t.hasNext();)t.next().print(e)},gA.prototype.findCollapsesFromExistingVertices=function(e){for(var t=0;t=0?t>=0?A>=n?0:1:A>=n?7:6:t>=0?A>=n?3:2:A>=n?4:5}if(arguments[0]instanceof m&&arguments[1]instanceof m){var r=arguments[0],i=arguments[1],o=i.x-r.x,a=i.y-r.y;if(0===o&&0===a)throw new B("Cannot compute the octant for two identical points "+r);return cA.octant(o,a)}};var uA=function(){};uA.prototype.getCoordinates=function(){},uA.prototype.size=function(){},uA.prototype.getCoordinate=function(e){},uA.prototype.isClosed=function(){},uA.prototype.setData=function(e){},uA.prototype.getData=function(){},uA.prototype.interfaces_=function(){return[]},uA.prototype.getClass=function(){return uA};var lA=function(){};lA.prototype.addIntersection=function(e,t){},lA.prototype.interfaces_=function(){return[uA]},lA.prototype.getClass=function(){return lA};var IA=function(){this._nodeList=new gA(this),this._pts=null,this._data=null;var e=arguments[0],t=arguments[1];this._pts=e,this._data=t};IA.prototype.getCoordinates=function(){return this._pts},IA.prototype.size=function(){return this._pts.length},IA.prototype.getCoordinate=function(e){return this._pts[e]},IA.prototype.isClosed=function(){return this._pts[0].equals(this._pts[this._pts.length-1])},IA.prototype.getSegmentOctant=function(e){return e===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(e),this.getCoordinate(e+1))},IA.prototype.setData=function(e){this._data=e},IA.prototype.safeOctant=function(e,t){return e.equals2D(t)?0:cA.octant(e,t)},IA.prototype.getData=function(){return this._data},IA.prototype.addIntersection=function(){if(2===arguments.length){var e=arguments[0],t=arguments[1];this.addIntersectionNode(e,t)}else if(4===arguments.length){var A=arguments[0],n=arguments[1],r=arguments[3],i=new m(A.getIntersection(r));this.addIntersection(i,n)}},IA.prototype.toString=function(){return z.toLineString(new st(this._pts))},IA.prototype.getNodeList=function(){return this._nodeList},IA.prototype.addIntersectionNode=function(e,t){var A=t,n=A+1;if(n=0&&A>=0||t<=0&&A<=0?Math.max(t,A):0}if(arguments[0]instanceof m){var n=arguments[0];return ae.orientationIndex(this.p0,this.p1,n)}},CA.prototype.toGeometry=function(e){return e.createLineString([this.p0,this.p1])},CA.prototype.isVertical=function(){return this.p0.x===this.p1.x},CA.prototype.equals=function(e){if(!(e instanceof CA))return!1;var t=e;return this.p0.equals(t.p0)&&this.p1.equals(t.p1)},CA.prototype.intersection=function(e){var t=new re;return t.computeIntersection(this.p0,this.p1,e.p0,e.p1),t.hasIntersection()?t.getIntersection(0):null},CA.prototype.project=function(){if(arguments[0]instanceof m){var e=arguments[0];if(e.equals(this.p0)||e.equals(this.p1))return new m(e);var t=this.projectionFactor(e),A=new m;return A.x=this.p0.x+t*(this.p1.x-this.p0.x),A.y=this.p0.y+t*(this.p1.y-this.p0.y),A}if(arguments[0]instanceof CA){var n=arguments[0],r=this.projectionFactor(n.p0),i=this.projectionFactor(n.p1);if(r>=1&&i>=1)return null;if(r<=0&&i<=0)return null;var o=this.project(n.p0);r<0&&(o=this.p0),r>1&&(o=this.p1);var a=this.project(n.p1);return i<0&&(a=this.p0),i>1&&(a=this.p1),new CA(o,a)}},CA.prototype.normalize=function(){this.p1.compareTo(this.p0)<0&&this.reverse()},CA.prototype.angle=function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)},CA.prototype.getCoordinate=function(e){return 0===e?this.p0:this.p1},CA.prototype.distancePerpendicular=function(e){return ae.distancePointLinePerpendicular(e,this.p0,this.p1)},CA.prototype.minY=function(){return Math.min(this.p0.y,this.p1.y)},CA.prototype.midPoint=function(){return CA.midPoint(this.p0,this.p1)},CA.prototype.projectionFactor=function(e){if(e.equals(this.p0))return 0;if(e.equals(this.p1))return 1;var t=this.p1.x-this.p0.x,A=this.p1.y-this.p0.y,n=t*t+A*A;return n<=0?p.NaN:((e.x-this.p0.x)*t+(e.y-this.p0.y)*A)/n},CA.prototype.closestPoints=function(e){var t=this.intersection(e);if(null!==t)return[t,t];var A=new Array(2).fill(null),n=p.MAX_VALUE,r=null,i=this.closestPoint(e.p0);n=i.distance(e.p0),A[0]=i,A[1]=e.p0;var o=this.closestPoint(e.p1);(r=o.distance(e.p1))0&&t<1?this.project(e):this.p0.distance(e)1||p.isNaN(t))&&(t=1),t},CA.prototype.toString=function(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"},CA.prototype.isHorizontal=function(){return this.p0.y===this.p1.y},CA.prototype.distance=function(){if(arguments[0]instanceof CA){var e=arguments[0];return ae.distanceLineLine(this.p0,this.p1,e.p0,e.p1)}if(arguments[0]instanceof m){var t=arguments[0];return ae.distancePointLine(t,this.p0,this.p1)}},CA.prototype.pointAlong=function(e){var t=new m;return t.x=this.p0.x+e*(this.p1.x-this.p0.x),t.y=this.p0.y+e*(this.p1.y-this.p0.y),t},CA.prototype.hashCode=function(){var e=p.doubleToLongBits(this.p0.x);e^=31*p.doubleToLongBits(this.p0.y);var t=Math.trunc(e)^Math.trunc(e>>32),A=p.doubleToLongBits(this.p1.x);return A^=31*p.doubleToLongBits(this.p1.y),t^Math.trunc(A)^Math.trunc(A>>32)},CA.prototype.interfaces_=function(){return[Q,t]},CA.prototype.getClass=function(){return CA},CA.midPoint=function(e,t){return new m((e.x+t.x)/2,(e.y+t.y)/2)},hA.serialVersionUID.get=function(){return 0x2d2172135f411c00},Object.defineProperties(CA,hA);var fA=function(){this.tempEnv1=new P,this.tempEnv2=new P,this._overlapSeg1=new CA,this._overlapSeg2=new CA};fA.prototype.overlap=function(){if(2===arguments.length);else if(4===arguments.length){var e=arguments[0],t=arguments[1],A=arguments[2],n=arguments[3];e.getLineSegment(t,this._overlapSeg1),A.getLineSegment(n,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}},fA.prototype.interfaces_=function(){return[]},fA.prototype.getClass=function(){return fA};var dA=function(){this._pts=null,this._start=null,this._end=null,this._env=null,this._context=null,this._id=null;var e=arguments[0],t=arguments[1],A=arguments[2],n=arguments[3];this._pts=e,this._start=t,this._end=A,this._context=n};dA.prototype.getLineSegment=function(e,t){t.p0=this._pts[e],t.p1=this._pts[e+1]},dA.prototype.computeSelect=function(e,t,A,n){var r=this._pts[t],i=this._pts[A];if(n.tempEnv1.init(r,i),A-t==1)return n.select(this,t),null;if(!e.intersects(n.tempEnv1))return null;var o=Math.trunc((t+A)/2);t=e.length-1)return e.length-1;for(var n=Lt.quadrant(e[A],e[A+1]),r=t+1;rA.getId()&&(A.computeOverlaps(r,e),this._nOverlaps++),this._segInt.isDone())return null}},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},A.SegmentOverlapAction.get=function(){return yA},Object.defineProperties(t,A),t}(EA),yA=function(e){function t(){e.call(this),this._si=null;var t=arguments[0];this._si=t}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.overlap=function(){if(4!==arguments.length)return e.prototype.overlap.apply(this,arguments);var t=arguments[0],A=arguments[1],n=arguments[2],r=arguments[3],i=t.getContext(),o=n.getContext();this._si.processIntersections(i,A,o,r)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(fA),vA=function e(){if(this._quadrantSegments=e.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=e.CAP_ROUND,this._joinStyle=e.JOIN_ROUND,this._mitreLimit=e.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=e.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this.setQuadrantSegments(t)}else if(2===arguments.length){var A=arguments[0],n=arguments[1];this.setQuadrantSegments(A),this.setEndCapStyle(n)}else if(4===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2],a=arguments[3];this.setQuadrantSegments(r),this.setEndCapStyle(i),this.setJoinStyle(o),this.setMitreLimit(a)}},mA={CAP_ROUND:{configurable:!0},CAP_FLAT:{configurable:!0},CAP_SQUARE:{configurable:!0},JOIN_ROUND:{configurable:!0},JOIN_MITRE:{configurable:!0},JOIN_BEVEL:{configurable:!0},DEFAULT_QUADRANT_SEGMENTS:{configurable:!0},DEFAULT_MITRE_LIMIT:{configurable:!0},DEFAULT_SIMPLIFY_FACTOR:{configurable:!0}};vA.prototype.getEndCapStyle=function(){return this._endCapStyle},vA.prototype.isSingleSided=function(){return this._isSingleSided},vA.prototype.setQuadrantSegments=function(e){this._quadrantSegments=e,0===this._quadrantSegments&&(this._joinStyle=vA.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=vA.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),e<=0&&(this._quadrantSegments=1),this._joinStyle!==vA.JOIN_ROUND&&(this._quadrantSegments=vA.DEFAULT_QUADRANT_SEGMENTS)},vA.prototype.getJoinStyle=function(){return this._joinStyle},vA.prototype.setJoinStyle=function(e){this._joinStyle=e},vA.prototype.setSimplifyFactor=function(e){this._simplifyFactor=e<0?0:e},vA.prototype.getSimplifyFactor=function(){return this._simplifyFactor},vA.prototype.getQuadrantSegments=function(){return this._quadrantSegments},vA.prototype.setEndCapStyle=function(e){this._endCapStyle=e},vA.prototype.getMitreLimit=function(){return this._mitreLimit},vA.prototype.setMitreLimit=function(e){this._mitreLimit=e},vA.prototype.setSingleSided=function(e){this._isSingleSided=e},vA.prototype.interfaces_=function(){return[]},vA.prototype.getClass=function(){return vA},vA.bufferDistanceError=function(e){var t=Math.PI/2/e;return 1-Math.cos(t/2)},mA.CAP_ROUND.get=function(){return 1},mA.CAP_FLAT.get=function(){return 2},mA.CAP_SQUARE.get=function(){return 3},mA.JOIN_ROUND.get=function(){return 1},mA.JOIN_MITRE.get=function(){return 2},mA.JOIN_BEVEL.get=function(){return 3},mA.DEFAULT_QUADRANT_SEGMENTS.get=function(){return 8},mA.DEFAULT_MITRE_LIMIT.get=function(){return 5},mA.DEFAULT_SIMPLIFY_FACTOR.get=function(){return.01},Object.defineProperties(vA,mA);var bA=function(e){this._distanceTol=null,this._isDeleted=null,this._angleOrientation=ae.COUNTERCLOCKWISE,this._inputLine=e||null},wA={INIT:{configurable:!0},DELETE:{configurable:!0},KEEP:{configurable:!0},NUM_PTS_TO_CHECK:{configurable:!0}};bA.prototype.isDeletable=function(e,t,A,n){var r=this._inputLine[e],i=this._inputLine[t],o=this._inputLine[A];return!!this.isConcave(r,i,o)&&!!this.isShallow(r,i,o,n)&&this.isShallowSampled(r,i,e,A,n)},bA.prototype.deleteShallowConcavities=function(){for(var e=1,t=this.findNextNonDeletedIndex(e),A=this.findNextNonDeletedIndex(t),n=!1;A=0;n--)this.addPt(e[n])},SA.prototype.isRedundant=function(e){if(this._ptList.size()<1)return!1;var t=this._ptList.get(this._ptList.size()-1);return e.distance(t)Math.PI;)e-=RA.PI_TIMES_2;for(;e<=-Math.PI;)e+=RA.PI_TIMES_2;return e},RA.angle=function(){if(1===arguments.length){var e=arguments[0];return Math.atan2(e.y,e.x)}if(2===arguments.length){var t=arguments[0],A=arguments[1],n=A.x-t.x,r=A.y-t.y;return Math.atan2(r,n)}},RA.isAcute=function(e,t,A){var n=e.x-t.x,r=e.y-t.y;return n*(A.x-t.x)+r*(A.y-t.y)>0},RA.isObtuse=function(e,t,A){var n=e.x-t.x,r=e.y-t.y;return n*(A.x-t.x)+r*(A.y-t.y)<0},RA.interiorAngle=function(e,t,A){var n=RA.angle(t,e),r=RA.angle(t,A);return Math.abs(r-n)},RA.normalizePositive=function(e){if(e<0){for(;e<0;)e+=RA.PI_TIMES_2;e>=RA.PI_TIMES_2&&(e=0)}else{for(;e>=RA.PI_TIMES_2;)e-=RA.PI_TIMES_2;e<0&&(e=0)}return e},RA.angleBetween=function(e,t,A){var n=RA.angle(t,e),r=RA.angle(t,A);return RA.diff(n,r)},RA.diff=function(e,t){var A=null;return(A=eMath.PI&&(A=2*Math.PI-A),A},RA.toRadians=function(e){return e*Math.PI/180},RA.getTurn=function(e,t){var A=Math.sin(t-e);return A>0?RA.COUNTERCLOCKWISE:A<0?RA.CLOCKWISE:RA.NONE},RA.angleBetweenOriented=function(e,t,A){var n=RA.angle(t,e),r=RA.angle(t,A)-n;return r<=-Math.PI?r+RA.PI_TIMES_2:r>Math.PI?r-RA.PI_TIMES_2:r},DA.PI_TIMES_2.get=function(){return 2*Math.PI},DA.PI_OVER_2.get=function(){return Math.PI/2},DA.PI_OVER_4.get=function(){return Math.PI/4},DA.COUNTERCLOCKWISE.get=function(){return ae.COUNTERCLOCKWISE},DA.CLOCKWISE.get=function(){return ae.CLOCKWISE},DA.NONE.get=function(){return ae.COLLINEAR},Object.defineProperties(RA,DA);var GA=function e(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new CA,this._seg1=new CA,this._offset0=new CA,this._offset1=new CA,this._side=0,this._hasNarrowConcaveAngle=!1;var t=arguments[0],A=arguments[1],n=arguments[2];this._precisionModel=t,this._bufParams=A,this._li=new re,this._filletAngleQuantum=Math.PI/2/A.getQuadrantSegments(),A.getQuadrantSegments()>=8&&A.getJoinStyle()===vA.JOIN_ROUND&&(this._closingSegLengthFactor=e.MAX_CLOSING_SEG_LEN_FACTOR),this.init(n)},kA={OFFSET_SEGMENT_SEPARATION_FACTOR:{configurable:!0},INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR:{configurable:!0},CURVE_VERTEX_SNAP_DISTANCE_FACTOR:{configurable:!0},MAX_CLOSING_SEG_LEN_FACTOR:{configurable:!0}};GA.prototype.addNextSegment=function(e,t){if(this._s0=this._s1,this._s1=this._s2,this._s2=e,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var A=ae.computeOrientation(this._s0,this._s1,this._s2),n=A===ae.CLOCKWISE&&this._side===bt.LEFT||A===ae.COUNTERCLOCKWISE&&this._side===bt.RIGHT;0===A?this.addCollinear(t):n?this.addOutsideTurn(A,t):this.addInsideTurn(A,t)},GA.prototype.addLineEndCap=function(e,t){var A=new CA(e,t),n=new CA;this.computeOffsetSegment(A,bt.LEFT,this._distance,n);var r=new CA;this.computeOffsetSegment(A,bt.RIGHT,this._distance,r);var i=t.x-e.x,o=t.y-e.y,a=Math.atan2(o,i);switch(this._bufParams.getEndCapStyle()){case vA.CAP_ROUND:this._segList.addPt(n.p1),this.addFilletArc(t,a+Math.PI/2,a-Math.PI/2,ae.CLOCKWISE,this._distance),this._segList.addPt(r.p1);break;case vA.CAP_FLAT:this._segList.addPt(n.p1),this._segList.addPt(r.p1);break;case vA.CAP_SQUARE:var s=new m;s.x=Math.abs(this._distance)*Math.cos(a),s.y=Math.abs(this._distance)*Math.sin(a);var g=new m(n.p1.x+s.x,n.p1.y+s.y),c=new m(r.p1.x+s.x,r.p1.y+s.y);this._segList.addPt(g),this._segList.addPt(c)}},GA.prototype.getCoordinates=function(){return this._segList.getCoordinates()},GA.prototype.addMitreJoin=function(e,t,A,n){var r=!0,i=null;try{i=j.intersection(t.p0,t.p1,A.p0,A.p1),(n<=0?1:i.distance(e)/Math.abs(n))>this._bufParams.getMitreLimit()&&(r=!1)}catch(e){if(!(e instanceof Y))throw e;i=new m(0,0),r=!1}r?this._segList.addPt(i):this.addLimitedMitreJoin(t,A,n,this._bufParams.getMitreLimit())},GA.prototype.addFilletCorner=function(e,t,A,n,r){var i=t.x-e.x,o=t.y-e.y,a=Math.atan2(o,i),s=A.x-e.x,g=A.y-e.y,c=Math.atan2(g,s);n===ae.CLOCKWISE?a<=c&&(a+=2*Math.PI):a>=c&&(a-=2*Math.PI),this._segList.addPt(t),this.addFilletArc(e,a,c,n,r),this._segList.addPt(A)},GA.prototype.addOutsideTurn=function(e,t){if(this._offset0.p1.distance(this._offset1.p0)0){var A=new m((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(A);var n=new m((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(n)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}},GA.prototype.createCircle=function(e){var t=new m(e.x+this._distance,e.y);this._segList.addPt(t),this.addFilletArc(e,0,2*Math.PI,-1,this._distance),this._segList.closeRing()},GA.prototype.addBevelJoin=function(e,t){this._segList.addPt(e.p1),this._segList.addPt(t.p0)},GA.prototype.init=function(e){this._distance=e,this._maxCurveSegmentError=e*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new SA,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(e*GA.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)},GA.prototype.addCollinear=function(e){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===vA.JOIN_BEVEL||this._bufParams.getJoinStyle()===vA.JOIN_MITRE?(e&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addFilletCorner(this._s1,this._offset0.p1,this._offset1.p0,ae.CLOCKWISE,this._distance))},GA.prototype.closeRing=function(){this._segList.closeRing()},GA.prototype.hasNarrowConcaveAngle=function(){return this._hasNarrowConcaveAngle},GA.prototype.interfaces_=function(){return[]},GA.prototype.getClass=function(){return GA},kA.OFFSET_SEGMENT_SEPARATION_FACTOR.get=function(){return.001},kA.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR.get=function(){return.001},kA.CURVE_VERTEX_SNAP_DISTANCE_FACTOR.get=function(){return 1e-6},kA.MAX_CLOSING_SEG_LEN_FACTOR.get=function(){return 80},Object.defineProperties(GA,kA);var xA=function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var e=arguments[0],t=arguments[1];this._precisionModel=e,this._bufParams=t};xA.prototype.getOffsetCurve=function(e,t){if(this._distance=t,0===t)return null;var A=t<0,n=Math.abs(t),r=this.getSegGen(n);e.length<=1?this.computePointCurve(e[0],r):this.computeOffsetCurve(e,A,r);var i=r.getCoordinates();return A&&we.reverse(i),i},xA.prototype.computeSingleSidedBufferCurve=function(e,t,A){var n=this.simplifyTolerance(this._distance);if(t){A.addSegments(e,!0);var r=bA.simplify(e,-n),i=r.length-1;A.initSideSegments(r[i],r[i-1],bt.LEFT),A.addFirstSegment();for(var o=i-2;o>=0;o--)A.addNextSegment(r[o],!0)}else{A.addSegments(e,!1);var a=bA.simplify(e,n),s=a.length-1;A.initSideSegments(a[0],a[1],bt.LEFT),A.addFirstSegment();for(var g=2;g<=s;g++)A.addNextSegment(a[g],!0)}A.addLastSegment(),A.closeRing()},xA.prototype.computeRingBufferCurve=function(e,t,A){var n=this.simplifyTolerance(this._distance);t===bt.RIGHT&&(n=-n);var r=bA.simplify(e,n),i=r.length-1;A.initSideSegments(r[i-1],r[0],t);for(var o=1;o<=i;o++){var a=1!==o;A.addNextSegment(r[o],a)}A.closeRing()},xA.prototype.computeLineBufferCurve=function(e,t){var A=this.simplifyTolerance(this._distance),n=bA.simplify(e,A),r=n.length-1;t.initSideSegments(n[0],n[1],bt.LEFT);for(var i=2;i<=r;i++)t.addNextSegment(n[i],!0);t.addLastSegment(),t.addLineEndCap(n[r-1],n[r]);var o=bA.simplify(e,-A),a=o.length-1;t.initSideSegments(o[a],o[a-1],bt.LEFT);for(var s=a-2;s>=0;s--)t.addNextSegment(o[s],!0);t.addLastSegment(),t.addLineEndCap(o[1],o[0]),t.closeRing()},xA.prototype.computePointCurve=function(e,t){switch(this._bufParams.getEndCapStyle()){case vA.CAP_ROUND:t.createCircle(e);break;case vA.CAP_SQUARE:t.createSquare(e)}},xA.prototype.getLineCurve=function(e,t){if(this._distance=t,t<0&&!this._bufParams.isSingleSided())return null;if(0===t)return null;var A=Math.abs(t),n=this.getSegGen(A);if(e.length<=1)this.computePointCurve(e[0],n);else if(this._bufParams.isSingleSided()){var r=t<0;this.computeSingleSidedBufferCurve(e,r,n)}else this.computeLineBufferCurve(e,n);return n.getCoordinates()},xA.prototype.getBufferParameters=function(){return this._bufParams},xA.prototype.simplifyTolerance=function(e){return e*this._bufParams.getSimplifyFactor()},xA.prototype.getRingCurve=function(e,t,A){if(this._distance=A,e.length<=2)return this.getLineCurve(e,A);if(0===A)return xA.copyCoordinates(e);var n=this.getSegGen(A);return this.computeRingBufferCurve(e,t,n),n.getCoordinates()},xA.prototype.computeOffsetCurve=function(e,t,A){var n=this.simplifyTolerance(this._distance);if(t){var r=bA.simplify(e,-n),i=r.length-1;A.initSideSegments(r[i],r[i-1],bt.LEFT),A.addFirstSegment();for(var o=i-2;o>=0;o--)A.addNextSegment(r[o],!0)}else{var a=bA.simplify(e,n),s=a.length-1;A.initSideSegments(a[0],a[1],bt.LEFT),A.addFirstSegment();for(var g=2;g<=s;g++)A.addNextSegment(a[g],!0)}A.addLastSegment()},xA.prototype.getSegGen=function(e){return new GA(this._precisionModel,this._bufParams,e)},xA.prototype.interfaces_=function(){return[]},xA.prototype.getClass=function(){return xA},xA.copyCoordinates=function(e){for(var t=new Array(e.length).fill(null),A=0;Ar.getMaxY()||this.findStabbedSegments(e,n.getDirectedEdges(),t)}return t}if(3===arguments.length)if(D(arguments[2],ye)&&arguments[0]instanceof m&&arguments[1]instanceof Ht){for(var i=arguments[0],o=arguments[1],a=arguments[2],s=o.getEdge().getCoordinates(),g=0;gthis._seg.p1.y&&this._seg.reverse(),!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||ae.computeOrientation(this._seg.p0,this._seg.p1,i)===ae.RIGHT)){var c=o.getDepth(bt.LEFT);this._seg.p0.equals(s[g])||(c=o.getDepth(bt.RIGHT));var u=new _A(this._seg,c);a.add(u)}}else if(D(arguments[2],ye)&&arguments[0]instanceof m&&D(arguments[1],ye))for(var l=arguments[0],I=arguments[1],C=arguments[2],h=I.iterator();h.hasNext();){var f=h.next();f.isForward()&&this.findStabbedSegments(l,f,C)}},NA.prototype.getDepth=function(e){var t=this.findStabbedSegments(e);return 0===t.size()?0:$t.min(t)._leftDepth},NA.prototype.interfaces_=function(){return[]},NA.prototype.getClass=function(){return NA},UA.DepthSegment.get=function(){return _A},Object.defineProperties(NA,UA);var _A=function(){this._upwardSeg=null,this._leftDepth=null;var e=arguments[0],t=arguments[1];this._upwardSeg=new CA(e),this._leftDepth=t};_A.prototype.compareTo=function(e){var t=e;if(this._upwardSeg.minX()>=t._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=t._upwardSeg.minX())return-1;var A=this._upwardSeg.orientationIndex(t._upwardSeg);return 0!==A||0!=(A=-1*t._upwardSeg.orientationIndex(this._upwardSeg))?A:this._upwardSeg.compareTo(t._upwardSeg)},_A.prototype.compareX=function(e,t){var A=e.p0.compareTo(t.p0);return 0!==A?A:e.p1.compareTo(t.p1)},_A.prototype.toString=function(){return this._upwardSeg.toString()},_A.prototype.interfaces_=function(){return[Q]},_A.prototype.getClass=function(){return _A};var MA=function(e,t,A){this.p0=e||null,this.p1=t||null,this.p2=A||null};MA.prototype.area=function(){return MA.area(this.p0,this.p1,this.p2)},MA.prototype.signedArea=function(){return MA.signedArea(this.p0,this.p1,this.p2)},MA.prototype.interpolateZ=function(e){if(null===e)throw new B("Supplied point is null.");return MA.interpolateZ(e,this.p0,this.p1,this.p2)},MA.prototype.longestSideLength=function(){return MA.longestSideLength(this.p0,this.p1,this.p2)},MA.prototype.isAcute=function(){return MA.isAcute(this.p0,this.p1,this.p2)},MA.prototype.circumcentre=function(){return MA.circumcentre(this.p0,this.p1,this.p2)},MA.prototype.area3D=function(){return MA.area3D(this.p0,this.p1,this.p2)},MA.prototype.centroid=function(){return MA.centroid(this.p0,this.p1,this.p2)},MA.prototype.inCentre=function(){return MA.inCentre(this.p0,this.p1,this.p2)},MA.prototype.interfaces_=function(){return[]},MA.prototype.getClass=function(){return MA},MA.area=function(e,t,A){return Math.abs(((A.x-e.x)*(t.y-e.y)-(t.x-e.x)*(A.y-e.y))/2)},MA.signedArea=function(e,t,A){return((A.x-e.x)*(t.y-e.y)-(t.x-e.x)*(A.y-e.y))/2},MA.det=function(e,t,A,n){return e*n-t*A},MA.interpolateZ=function(e,t,A,n){var r=t.x,i=t.y,o=A.x-r,a=n.x-r,s=A.y-i,g=n.y-i,c=o*g-a*s,u=e.x-r,l=e.y-i,I=(g*u-a*l)/c,C=(-s*u+o*l)/c;return t.z+I*(A.z-t.z)+C*(n.z-t.z)},MA.longestSideLength=function(e,t,A){var n=e.distance(t),r=t.distance(A),i=A.distance(e),o=n;return r>o&&(o=r),i>o&&(o=i),o},MA.isAcute=function(e,t,A){return!!RA.isAcute(e,t,A)&&!!RA.isAcute(t,A,e)&&!!RA.isAcute(A,e,t)},MA.circumcentre=function(e,t,A){var n=A.x,r=A.y,i=e.x-n,o=e.y-r,a=t.x-n,s=t.y-r,g=2*MA.det(i,o,a,s),c=MA.det(o,i*i+o*o,s,a*a+s*s),u=MA.det(i,i*i+o*o,a,a*a+s*s);return new m(n-c/g,r+u/g)},MA.perpendicularBisector=function(e,t){var A=t.x-e.x,n=t.y-e.y,r=new j(e.x+A/2,e.y+n/2,1),i=new j(e.x-n+A/2,e.y+A+n/2,1);return new j(r,i)},MA.angleBisector=function(e,t,A){var n=t.distance(e),r=n/(n+t.distance(A)),i=A.x-e.x,o=A.y-e.y;return new m(e.x+r*i,e.y+r*o)},MA.area3D=function(e,t,A){var n=t.x-e.x,r=t.y-e.y,i=t.z-e.z,o=A.x-e.x,a=A.y-e.y,s=A.z-e.z,g=r*s-i*a,c=i*o-n*s,u=n*a-r*o,l=g*g+c*c+u*u;return Math.sqrt(l)/2},MA.centroid=function(e,t,A){var n=(e.x+t.x+A.x)/3,r=(e.y+t.y+A.y)/3;return new m(n,r)},MA.inCentre=function(e,t,A){var n=t.distance(A),r=e.distance(A),i=e.distance(t),o=n+r+i,a=(n*e.x+r*t.x+i*A.x)/o,s=(n*e.y+r*t.y+i*A.y)/o;return new m(a,s)};var OA=function(){this._inputGeom=null,this._distance=null,this._curveBuilder=null,this._curveList=new ve;var e=arguments[0],t=arguments[1],A=arguments[2];this._inputGeom=e,this._distance=t,this._curveBuilder=A};OA.prototype.addPoint=function(e){if(this._distance<=0)return null;var t=e.getCoordinates(),A=this._curveBuilder.getLineCurve(t,this._distance);this.addCurve(A,F.EXTERIOR,F.INTERIOR)},OA.prototype.addPolygon=function(e){var t=this._distance,A=bt.LEFT;this._distance<0&&(t=-this._distance,A=bt.RIGHT);var n=e.getExteriorRing(),r=we.removeRepeatedPoints(n.getCoordinates());if(this._distance<0&&this.isErodedCompletely(n,this._distance))return null;if(this._distance<=0&&r.length<3)return null;this.addPolygonRing(r,t,A,F.EXTERIOR,F.INTERIOR);for(var i=0;i0&&this.isErodedCompletely(o,-this._distance)||this.addPolygonRing(a,t,bt.opposite(A),F.INTERIOR,F.EXTERIOR)}},OA.prototype.isTriangleErodedCompletely=function(e,t){var A=new MA(e[0],e[1],e[2]),n=A.inCentre();return ae.distancePointLine(n,A.p0,A.p1)=tt.MINIMUM_VALID_SIZE&&ae.isCCW(e)&&(i=r,o=n,A=bt.opposite(A));var a=this._curveBuilder.getRingCurve(e,A,t);this.addCurve(a,i,o)},OA.prototype.add=function(e){if(e.isEmpty())return null;e instanceof $e?this.addPolygon(e):e instanceof We?this.addLineString(e):e instanceof qe?this.addPoint(e):(e instanceof et||e instanceof Ye||e instanceof At||e instanceof He)&&this.addCollection(e)},OA.prototype.isErodedCompletely=function(e,t){var A=e.getCoordinates();if(A.length<4)return t<0;if(4===A.length)return this.isTriangleErodedCompletely(A,t);var n=e.getEnvelopeInternal(),r=Math.min(n.getHeight(),n.getWidth());return t<0&&2*Math.abs(t)>r},OA.prototype.addCollection=function(e){for(var t=0;t=this._max)throw new n;var e=this._parent.getGeometryN(this._index++);return e instanceof He?(this._subcollectionIterator=new TA(e),this._subcollectionIterator.next()):e},TA.prototype.remove=function(){throw new Error(this.getClass().getName())},TA.prototype.hasNext=function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)},TA.prototype.interfaces_=function(){return[Qe]},TA.prototype.getClass=function(){return TA},TA.isAtomic=function(e){return!(e instanceof He)};var ZA=function(){this._geom=null;var e=arguments[0];this._geom=e};ZA.prototype.locate=function(e){return ZA.locate(e,this._geom)},ZA.prototype.interfaces_=function(){return[LA]},ZA.prototype.getClass=function(){return ZA},ZA.isPointInRing=function(e,t){return!!t.getEnvelopeInternal().intersects(e)&&ae.isPointInRing(e,t.getCoordinates())},ZA.containsPointInPolygon=function(e,t){if(t.isEmpty())return!1;var A=t.getExteriorRing();if(!ZA.isPointInRing(e,A))return!1;for(var n=0;n=0;A--){var n=this._edgeList.get(A),r=n.getSym();null===t&&(t=r),null!==e&&r.setNext(e),e=n}t.setNext(e)},t.prototype.computeDepths=function(){if(1===arguments.length){var e=arguments[0],t=this.findIndex(e),A=e.getDepth(bt.LEFT),n=e.getDepth(bt.RIGHT),r=this.computeDepths(t+1,this._edgeList.size(),A);if(this.computeDepths(0,t,r)!==n)throw new Ft("depth mismatch at "+e.getCoordinate())}else if(3===arguments.length){for(var i=arguments[0],o=arguments[1],a=arguments[2],s=i;s=0;r--){var i=this._resultAreaEdgeList.get(r),o=i.getSym();switch(null===t&&i.getEdgeRing()===e&&(t=i),n){case this._SCANNING_FOR_INCOMING:if(o.getEdgeRing()!==e)continue;A=o,n=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(i.getEdgeRing()!==e)continue;A.setNextMin(i),n=this._SCANNING_FOR_INCOMING}}n===this._LINKING_TO_OUTGOING&&(te.isTrue(null!==t,"found null for first outgoing dirEdge"),te.isTrue(t.getEdgeRing()===e,"unable to link last incoming dirEdge"),A.setNextMin(t))},t.prototype.getOutgoingDegree=function(){if(0===arguments.length){for(var e=0,t=this.iterator();t.hasNext();)t.next().isInResult()&&e++;return e}if(1===arguments.length){for(var A=arguments[0],n=0,r=this.iterator();r.hasNext();)r.next().getEdgeRing()===A&&n++;return n}},t.prototype.getLabel=function(){return this._label},t.prototype.findCoveredLineEdges=function(){for(var e=F.NONE,t=this.iterator();t.hasNext();){var A=t.next(),n=A.getSym();if(!A.isLineEdge()){if(A.isInResult()){e=F.INTERIOR;break}if(n.isInResult()){e=F.EXTERIOR;break}}}if(e===F.NONE)return null;for(var r=e,i=this.iterator();i.hasNext();){var o=i.next(),a=o.getSym();o.isLineEdge()?o.getEdge().setCovered(r===F.INTERIOR):(o.isInResult()&&(r=F.EXTERIOR),a.isInResult()&&(r=F.INTERIOR))}},t.prototype.computeLabelling=function(t){e.prototype.computeLabelling.call(this,t),this._label=new kt(F.NONE);for(var A=this.iterator();A.hasNext();)for(var n=A.next().getEdge().getLabel(),r=0;r<2;r++){var i=n.getLocation(r);i!==F.INTERIOR&&i!==F.BOUNDARY||this._label.setLocation(r,F.INTERIOR)}},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(HA),JA=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.createNode=function(e){return new Mt(e,new YA)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(Yt),jA=function e(){this._pts=null,this._orientation=null;var t=arguments[0];this._pts=t,this._orientation=e.orientation(t)};jA.prototype.compareTo=function(e){var t=e;return jA.compareOriented(this._pts,this._orientation,t._pts,t._orientation)},jA.prototype.interfaces_=function(){return[Q]},jA.prototype.getClass=function(){return jA},jA.orientation=function(e){return 1===we.increasingDirection(e)},jA.compareOriented=function(e,t,A,n){for(var r=t?1:-1,i=n?1:-1,o=t?e.length:-1,a=n?A.length:-1,s=t?0:e.length-1,g=n?0:A.length-1;;){var c=e[s].compareTo(A[g]);if(0!==c)return c;var u=(s+=r)===o,l=(g+=i)===a;if(u&&!l)return-1;if(!u&&l)return 1;if(u&&l)return 0}};var PA=function(){this._edges=new ve,this._ocaMap=new u};PA.prototype.print=function(e){e.print("MULTILINESTRING ( ");for(var t=0;t0&&e.print(","),e.print("(");for(var n=A.getCoordinates(),r=0;r0&&e.print(","),e.print(n[r].x+" "+n[r].y);e.println(")")}e.print(") ")},PA.prototype.addAll=function(e){for(var t=e.iterator();t.hasNext();)this.add(t.next())},PA.prototype.findEdgeIndex=function(e){for(var t=0;t0||!t.coord.equals2D(n);r||A--;var i=new Array(A).fill(null),o=0;i[o++]=new m(e.coord);for(var a=e.segmentIndex+1;a<=t.segmentIndex;a++)i[o++]=this.edge.pts[a];return r&&(i[o]=t.coord),new tn(i,new kt(this.edge._label))},XA.prototype.add=function(e,t,A){var n=new WA(e,t,A),r=this._nodeMap.get(n);return null!==r?r:(this._nodeMap.put(n,n),n)},XA.prototype.isIntersection=function(e){for(var t=this.iterator();t.hasNext();)if(t.next().coord.equals(e))return!0;return!1},XA.prototype.interfaces_=function(){return[]},XA.prototype.getClass=function(){return XA};var qA=function(){};qA.prototype.getChainStartIndices=function(e){var t=0,A=new ve;A.add(new N(t));do{var n=this.findChainEnd(e,t);A.add(new N(n)),t=n}while(tA?t:A},zA.prototype.getMinX=function(e){var t=this.pts[this.startIndex[e]].x,A=this.pts[this.startIndex[e+1]].x;return tt&&(n=1),this._depth[e][A]=n}}},$A.prototype.getDelta=function(e){return this._depth[e][bt.RIGHT]-this._depth[e][bt.LEFT]},$A.prototype.getLocation=function(e,t){return this._depth[e][t]<=0?F.EXTERIOR:F.INTERIOR},$A.prototype.toString=function(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]},$A.prototype.add=function(){if(1===arguments.length)for(var e=arguments[0],t=0;t<2;t++)for(var A=1;A<3;A++){var n=e.getLocation(t,A);n!==F.EXTERIOR&&n!==F.INTERIOR||(this.isNull(t,A)?this._depth[t][A]=$A.depthAtLocation(n):this._depth[t][A]+=$A.depthAtLocation(n))}else if(3===arguments.length){var r=arguments[0],i=arguments[1];arguments[2]===F.INTERIOR&&this._depth[r][i]++}},$A.prototype.interfaces_=function(){return[]},$A.prototype.getClass=function(){return $A},$A.depthAtLocation=function(e){return e===F.EXTERIOR?0:e===F.INTERIOR?1:$A.NULL_VALUE},en.NULL_VALUE.get=function(){return-1},Object.defineProperties($A,en);var tn=function(e){function t(){if(e.call(this),this.pts=null,this._env=null,this.eiList=new XA(this),this._name=null,this._mce=null,this._isIsolated=!0,this._depth=new $A,this._depthDelta=0,1===arguments.length){var A=arguments[0];t.call(this,A,null)}else if(2===arguments.length){var n=arguments[0],r=arguments[1];this.pts=n,this._label=r}}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.getDepth=function(){return this._depth},t.prototype.getCollapsedEdge=function(){var e=new Array(2).fill(null);return e[0]=this.pts[0],e[1]=this.pts[1],new t(e,kt.toLineLabel(this._label))},t.prototype.isIsolated=function(){return this._isIsolated},t.prototype.getCoordinates=function(){return this.pts},t.prototype.setIsolated=function(e){this._isIsolated=e},t.prototype.setName=function(e){this._name=e},t.prototype.equals=function(e){if(!(e instanceof t))return!1;var A=e;if(this.pts.length!==A.pts.length)return!1;for(var n=!0,r=!0,i=this.pts.length,o=0;o0?this.pts[0]:null;if(1===arguments.length){var e=arguments[0];return this.pts[e]}},t.prototype.print=function(e){e.print("edge "+this._name+": "),e.print("LINESTRING (");for(var t=0;t0&&e.print(","),e.print(this.pts[t].x+" "+this.pts[t].y);e.print(") "+this._label+" "+this._depthDelta)},t.prototype.computeIM=function(e){t.updateIM(this._label,e)},t.prototype.isCollapsed=function(){return!!this._label.isArea()&&3===this.pts.length&&!!this.pts[0].equals(this.pts[2])},t.prototype.isClosed=function(){return this.pts[0].equals(this.pts[this.pts.length-1])},t.prototype.getMaximumSegmentIndex=function(){return this.pts.length-1},t.prototype.getDepthDelta=function(){return this._depthDelta},t.prototype.getNumPoints=function(){return this.pts.length},t.prototype.printReverse=function(e){e.print("edge "+this._name+": ");for(var t=this.pts.length-1;t>=0;t--)e.print(this.pts[t]+" ");e.println("")},t.prototype.getMonotoneChainEdge=function(){return null===this._mce&&(this._mce=new zA(this)),this._mce},t.prototype.getEnvelope=function(){if(null===this._env){this._env=new P;for(var e=0;e0&&e.append(","),e.append(this.pts[t].x+" "+this.pts[t].y);return e.append(") "+this._label+" "+this._depthDelta),e.toString()},t.prototype.isPointwiseEqual=function(e){if(this.pts.length!==e.pts.length)return!1;for(var t=0;tn||this._maxyi;if(o)return!1;var a=this.intersectsToleranceSquare(e,t);return te.isTrue(!(o&&a),"Found bad envelope test"),a},an.prototype.initCorners=function(e){this._minx=e.x-.5,this._maxx=e.x+.5,this._miny=e.y-.5,this._maxy=e.y+.5,this._corner[0]=new m(this._maxx,this._maxy),this._corner[1]=new m(this._minx,this._maxy),this._corner[2]=new m(this._minx,this._miny),this._corner[3]=new m(this._maxx,this._miny)},an.prototype.intersects=function(e,t){return 1===this._scaleFactor?this.intersectsScaled(e,t):(this.copyScaled(e,this._p0Scaled),this.copyScaled(t,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))},an.prototype.scale=function(e){return Math.round(e*this._scaleFactor)},an.prototype.getCoordinate=function(){return this._originalPt},an.prototype.copyScaled=function(e,t){t.x=this.scale(e.x),t.y=this.scale(e.y)},an.prototype.getSafeEnvelope=function(){if(null===this._safeEnv){var e=an.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new P(this._originalPt.x-e,this._originalPt.x+e,this._originalPt.y-e,this._originalPt.y+e)}return this._safeEnv},an.prototype.intersectsPixelClosure=function(e,t){return this._li.computeIntersection(e,t,this._corner[0],this._corner[1]),!!this._li.hasIntersection()||(this._li.computeIntersection(e,t,this._corner[1],this._corner[2]),!!this._li.hasIntersection()||(this._li.computeIntersection(e,t,this._corner[2],this._corner[3]),!!this._li.hasIntersection()||(this._li.computeIntersection(e,t,this._corner[3],this._corner[0]),!!this._li.hasIntersection())))},an.prototype.intersectsToleranceSquare=function(e,t){var A=!1,n=!1;return this._li.computeIntersection(e,t,this._corner[0],this._corner[1]),!!this._li.isProper()||(this._li.computeIntersection(e,t,this._corner[1],this._corner[2]),!!this._li.isProper()||(this._li.hasIntersection()&&(A=!0),this._li.computeIntersection(e,t,this._corner[2],this._corner[3]),!!this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(e,t,this._corner[3],this._corner[0]),!!this._li.isProper()||!(!A||!n)||!!e.equals(this._pt)||!!t.equals(this._pt))))},an.prototype.addSnappedNode=function(e,t){var A=e.getCoordinate(t),n=e.getCoordinate(t+1);return!!this.intersects(A,n)&&(e.addIntersection(this.getCoordinate(),t),!0)},an.prototype.interfaces_=function(){return[]},an.prototype.getClass=function(){return an},sn.SAFE_ENV_EXPANSION_FACTOR.get=function(){return.75},Object.defineProperties(an,sn);var gn=function(){this.tempEnv1=new P,this.selectedSegment=new CA};gn.prototype.select=function(){if(1===arguments.length);else if(2===arguments.length){var e=arguments[0],t=arguments[1];e.getLineSegment(t,this.selectedSegment),this.select(this.selectedSegment)}},gn.prototype.interfaces_=function(){return[]},gn.prototype.getClass=function(){return gn};var cn=function(){this._index=null;var e=arguments[0];this._index=e},un={HotPixelSnapAction:{configurable:!0}};cn.prototype.snap=function(){if(1===arguments.length){var e=arguments[0];return this.snap(e,null,-1)}if(3===arguments.length){var t=arguments[0],A=arguments[1],n=arguments[2],r=t.getSafeEnvelope(),i=new ln(t,A,n);return this._index.query(r,{interfaces_:function(){return[Wt]},visitItem:function(e){e.select(r,i)}}),i.isNodeAdded()}},cn.prototype.interfaces_=function(){return[]},cn.prototype.getClass=function(){return cn},un.HotPixelSnapAction.get=function(){return ln},Object.defineProperties(cn,un);var ln=function(e){function t(){e.call(this),this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var t=arguments[0],A=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=A,this._hotPixelVertexIndex=n}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.isNodeAdded=function(){return this._isNodeAdded},t.prototype.select=function(){if(2!==arguments.length)return e.prototype.select.apply(this,arguments);var t=arguments[0],A=arguments[1],n=t.getContext();if(null!==this._parentEdge&&n===this._parentEdge&&A===this._hotPixelVertexIndex)return null;this._isNodeAdded=this._hotPixel.addSnappedNode(n,A)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(gn),In=function(){this._li=null,this._interiorIntersections=null;var e=arguments[0];this._li=e,this._interiorIntersections=new ve};In.prototype.processIntersections=function(e,t,A,n){if(e===A&&t===n)return null;var r=e.getCoordinates()[t],i=e.getCoordinates()[t+1],o=A.getCoordinates()[n],a=A.getCoordinates()[n+1];if(this._li.computeIntersection(r,i,o,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var s=0;s=0;t--){try{e.bufferReducedPrecision(t)}catch(t){if(!(t instanceof Ft))throw t;e._saveException=t}if(null!==e._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var A=arguments[0],n=hn.precisionScaleFactor(this._argGeom,this._distance,A),r=new It(n);this.bufferFixedPrecision(r)}},hn.prototype.computeGeometry=function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var e=this._argGeom.getFactory().getPrecisionModel();e.getType()===It.FIXED?this.bufferFixedPrecision(e):this.bufferReducedPrecision()},hn.prototype.setQuadrantSegments=function(e){this._bufParams.setQuadrantSegments(e)},hn.prototype.bufferOriginalPrecision=function(){try{var e=new An(this._bufParams);this._resultGeometry=e.buffer(this._argGeom,this._distance)}catch(e){if(!(e instanceof $))throw e;this._saveException=e}},hn.prototype.getResultGeometry=function(e){return this._distance=e,this.computeGeometry(),this._resultGeometry},hn.prototype.setEndCapStyle=function(e){this._bufParams.setEndCapStyle(e)},hn.prototype.interfaces_=function(){return[]},hn.prototype.getClass=function(){return hn},hn.bufferOp=function(){if(2===arguments.length){var e=arguments[0],t=arguments[1];return new hn(e).getResultGeometry(t)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof ce&&"number"==typeof arguments[1]){var A=arguments[0],n=arguments[1],r=arguments[2],i=new hn(A);return i.setQuadrantSegments(r),i.getResultGeometry(n)}if(arguments[2]instanceof vA&&arguments[0]instanceof ce&&"number"==typeof arguments[1]){var o=arguments[0],a=arguments[1],s=arguments[2];return new hn(o,s).getResultGeometry(a)}}else if(4===arguments.length){var g=arguments[0],c=arguments[1],u=arguments[2],l=arguments[3],I=new hn(g);return I.setQuadrantSegments(u),I.setEndCapStyle(l),I.getResultGeometry(c)}},hn.precisionScaleFactor=function(e,t,A){var n=e.getEnvelopeInternal(),r=G.max(Math.abs(n.getMaxX()),Math.abs(n.getMaxY()),Math.abs(n.getMinX()),Math.abs(n.getMinY()))+2*(t>0?t:0),i=A-Math.trunc(Math.log(r)/Math.log(10)+1);return Math.pow(10,i)},fn.CAP_ROUND.get=function(){return vA.CAP_ROUND},fn.CAP_BUTT.get=function(){return vA.CAP_FLAT},fn.CAP_FLAT.get=function(){return vA.CAP_FLAT},fn.CAP_SQUARE.get=function(){return vA.CAP_SQUARE},fn.MAX_PRECISION_DIGITS.get=function(){return 12},Object.defineProperties(hn,fn);var dn=function(){this._pt=[new m,new m],this._distance=p.NaN,this._isNull=!0};dn.prototype.getCoordinates=function(){return this._pt},dn.prototype.getCoordinate=function(e){return this._pt[e]},dn.prototype.setMinimum=function(){if(1===arguments.length){var e=arguments[0];this.setMinimum(e._pt[0],e._pt[1])}else if(2===arguments.length){var t=arguments[0],A=arguments[1];if(this._isNull)return this.initialize(t,A),null;var n=t.distance(A);nthis._distance&&this.initialize(t,A,n)}},dn.prototype.interfaces_=function(){return[]},dn.prototype.getClass=function(){return dn};var Bn=function(){};Bn.prototype.interfaces_=function(){return[]},Bn.prototype.getClass=function(){return Bn},Bn.computeDistance=function(){if(arguments[2]instanceof dn&&arguments[0]instanceof We&&arguments[1]instanceof m)for(var e=arguments[0],t=arguments[1],A=arguments[2],n=e.getCoordinates(),r=new CA,i=0;i0||this._isIn?F.INTERIOR:F.EXTERIOR)},bn.prototype.interfaces_=function(){return[]},bn.prototype.getClass=function(){return bn};var wn=function e(){if(this._component=null,this._segIndex=null,this._pt=null,2===arguments.length){var t=arguments[0],A=arguments[1];e.call(this,t,e.INSIDE_AREA,A)}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];this._component=n,this._segIndex=r,this._pt=i}},Sn={INSIDE_AREA:{configurable:!0}};wn.prototype.isInsideArea=function(){return this._segIndex===wn.INSIDE_AREA},wn.prototype.getCoordinate=function(){return this._pt},wn.prototype.getGeometryComponent=function(){return this._component},wn.prototype.getSegmentIndex=function(){return this._segIndex},wn.prototype.interfaces_=function(){return[]},wn.prototype.getClass=function(){return wn},Sn.INSIDE_AREA.get=function(){return-1},Object.defineProperties(wn,Sn);var Fn=function(e){this._pts=e||null};Fn.prototype.filter=function(e){e instanceof qe&&this._pts.add(e)},Fn.prototype.interfaces_=function(){return[Te]},Fn.prototype.getClass=function(){return Fn},Fn.getPoints=function(){if(1===arguments.length){var e=arguments[0];return e instanceof qe?$t.singletonList(e):Fn.getPoints(e,new ve)}if(2===arguments.length){var t=arguments[0],A=arguments[1];return t instanceof qe?A.add(t):t instanceof He&&t.apply(new Fn(A)),A}};var Rn=function(){this._locations=null;var e=arguments[0];this._locations=e};Rn.prototype.filter=function(e){(e instanceof qe||e instanceof We||e instanceof $e)&&this._locations.add(new wn(e,0,e.getCoordinate()))},Rn.prototype.interfaces_=function(){return[Te]},Rn.prototype.getClass=function(){return Rn},Rn.getLocations=function(e){var t=new ve;return e.apply(new Rn(t)),t};var Dn=function(){if(this._geom=null,this._terminateDistance=0,this._ptLocator=new bn,this._minDistanceLocation=null,this._minDistance=p.MAX_VALUE,2===arguments.length){var e=arguments[0],t=arguments[1];this._geom=[e,t],this._terminateDistance=0}else if(3===arguments.length){var A=arguments[0],n=arguments[1],r=arguments[2];this._geom=new Array(2).fill(null),this._geom[0]=A,this._geom[1]=n,this._terminateDistance=r}};Dn.prototype.computeContainmentDistance=function(){if(0===arguments.length){var e=new Array(2).fill(null);if(this.computeContainmentDistance(0,e),this._minDistance<=this._terminateDistance)return null;this.computeContainmentDistance(1,e)}else if(2===arguments.length){var t=arguments[0],A=arguments[1],n=1-t,r=vn.getPolygons(this._geom[t]);if(r.size()>0){var i=Rn.getLocations(this._geom[n]);if(this.computeContainmentDistance(i,r,A),this._minDistance<=this._terminateDistance)return this._minDistanceLocation[n]=A[0],this._minDistanceLocation[t]=A[1],null}}else if(3===arguments.length)if(arguments[2]instanceof Array&&D(arguments[0],ye)&&D(arguments[1],ye)){for(var o=arguments[0],a=arguments[1],s=arguments[2],g=0;gthis._minDistance)return null;for(var n=e.getCoordinates(),r=t.getCoordinate(),i=0;ithis._minDistance)return null;for(var u=s.getCoordinates(),l=g.getCoordinates(),I=0;Ithis._distance&&this.initialize(t,A,n)}},Gn.prototype.interfaces_=function(){return[]},Gn.prototype.getClass=function(){return Gn};var kn=function(){};kn.prototype.interfaces_=function(){return[]},kn.prototype.getClass=function(){return kn},kn.computeDistance=function(){if(arguments[2]instanceof Gn&&arguments[0]instanceof We&&arguments[1]instanceof m)for(var e=arguments[0],t=arguments[1],A=arguments[2],n=new CA,r=e.getCoordinates(),i=0;i1||e<=0)throw new B("Fraction is not in range (0.0 - 1.0]");this._densifyFrac=e},xn.prototype.compute=function(e,t){this.computeOrientedDistance(e,t,this._ptDist),this.computeOrientedDistance(t,e,this._ptDist)},xn.prototype.distance=function(){return this.compute(this._g0,this._g1),this._ptDist.getDistance()},xn.prototype.computeOrientedDistance=function(e,t,A){var n=new Un(t);if(e.apply(n),A.setMaximum(n.getMaxPointDistance()),this._densifyFrac>0){var r=new _n(t,this._densifyFrac);e.apply(r),A.setMaximum(r.getMaxPointDistance())}},xn.prototype.orientedDistance=function(){return this.computeOrientedDistance(this._g0,this._g1,this._ptDist),this._ptDist.getDistance()},xn.prototype.interfaces_=function(){return[]},xn.prototype.getClass=function(){return xn},xn.distance=function(){if(2===arguments.length){var e=arguments[0],t=arguments[1];return new xn(e,t).distance()}if(3===arguments.length){var A=arguments[0],n=arguments[1],r=arguments[2],i=new xn(A,n);return i.setDensifyFraction(r),i.distance()}},Nn.MaxPointDistanceFilter.get=function(){return Un},Nn.MaxDensifiedByFractionDistanceFilter.get=function(){return _n},Object.defineProperties(xn,Nn);var Un=function(){this._maxPtDist=new Gn,this._minPtDist=new Gn,this._euclideanDist=new kn,this._geom=null;var e=arguments[0];this._geom=e};Un.prototype.filter=function(e){this._minPtDist.initialize(),kn.computeDistance(this._geom,e,this._minPtDist),this._maxPtDist.setMaximum(this._minPtDist)},Un.prototype.getMaxPointDistance=function(){return this._maxPtDist},Un.prototype.interfaces_=function(){return[Ie]},Un.prototype.getClass=function(){return Un};var _n=function(){this._maxPtDist=new Gn,this._minPtDist=new Gn,this._geom=null,this._numSubSegs=0;var e=arguments[0],t=arguments[1];this._geom=e,this._numSubSegs=Math.trunc(Math.round(1/t))};_n.prototype.filter=function(e,t){if(0===t)return null;for(var A=e.getCoordinate(t-1),n=e.getCoordinate(t),r=(n.x-A.x)/this._numSubSegs,i=(n.y-A.y)/this._numSubSegs,o=0;oA){this._isValid=!1;var r=n.getCoordinates();this._errorLocation=r[1],this._errorIndicator=e.getFactory().createLineString(r),this._errMsg="Distance between buffer curve and input is too large ("+this._maxDistanceFound+" at "+z.toLineString(r[0],r[1])+")"}},Mn.prototype.isValid=function(){var e=Math.abs(this._bufDistance),t=Mn.MAX_DISTANCE_DIFF_FRAC*e;return this._minValidDistance=e-t,this._maxValidDistance=e+t,!(!this._input.isEmpty()&&!this._result.isEmpty())||(this._bufDistance>0?this.checkPositiveValid():this.checkNegativeValid(),Mn.VERBOSE&&J.out.println("Min Dist= "+this._minDistanceFound+" err= "+(1-this._minDistanceFound/this._bufDistance)+" Max Dist= "+this._maxDistanceFound+" err= "+(this._maxDistanceFound/this._bufDistance-1)),this._isValid)},Mn.prototype.checkNegativeValid=function(){if(!(this._input instanceof $e||this._input instanceof At||this._input instanceof He))return null;var e=this.getPolygonLines(this._input);if(this.checkMinimumDistance(e,this._result,this._minValidDistance),!this._isValid)return null;this.checkMaximumDistance(e,this._result,this._maxValidDistance)},Mn.prototype.getErrorIndicator=function(){return this._errorIndicator},Mn.prototype.checkMinimumDistance=function(e,t,A){var n=new Dn(e,t,A);if(this._minDistanceFound=n.distance(),this._minDistanceFound0&&e>t&&(this._isValid=!1,this._errorMsg="Area of positive buffer is smaller than input",this._errorIndicator=this._result),this._distance<0&&e=2||this._distance>0?null:(this._result.isEmpty()||(this._isValid=!1,this._errorMsg="Result is non-empty",this._errorIndicator=this._result),void this.report("ExpectedEmpty"))},Ln.prototype.report=function(e){if(!Ln.VERBOSE)return null;J.out.println("Check "+e+": "+(this._isValid?"passed":"FAILED"))},Ln.prototype.getErrorMessage=function(){return this._errorMsg},Ln.prototype.interfaces_=function(){return[]},Ln.prototype.getClass=function(){return Ln},Ln.isValidMsg=function(e,t,A){var n=new Ln(e,t,A);return n.isValid()?null:n.getErrorMessage()},Ln.isValid=function(e,t,A){return!!new Ln(e,t,A).isValid()},Tn.VERBOSE.get=function(){return!1},Tn.MAX_ENV_DIFF_FRAC.get=function(){return.012},Object.defineProperties(Ln,Tn);var Zn=function(){this._pts=null,this._data=null;var e=arguments[0],t=arguments[1];this._pts=e,this._data=t};Zn.prototype.getCoordinates=function(){return this._pts},Zn.prototype.size=function(){return this._pts.length},Zn.prototype.getCoordinate=function(e){return this._pts[e]},Zn.prototype.isClosed=function(){return this._pts[0].equals(this._pts[this._pts.length-1])},Zn.prototype.getSegmentOctant=function(e){return e===this._pts.length-1?-1:cA.octant(this.getCoordinate(e),this.getCoordinate(e+1))},Zn.prototype.setData=function(e){this._data=e},Zn.prototype.getData=function(){return this._data},Zn.prototype.toString=function(){return z.toLineString(new st(this._pts))},Zn.prototype.interfaces_=function(){return[uA]},Zn.prototype.getClass=function(){return Zn};var Hn=function(){this._findAllIntersections=!1,this._isCheckEndSegmentsOnly=!1,this._li=null,this._interiorIntersection=null,this._intSegments=null,this._intersections=new ve,this._intersectionCount=0,this._keepIntersections=!0;var e=arguments[0];this._li=e,this._interiorIntersection=null};Hn.prototype.getInteriorIntersection=function(){return this._interiorIntersection},Hn.prototype.setCheckEndSegmentsOnly=function(e){this._isCheckEndSegmentsOnly=e},Hn.prototype.getIntersectionSegments=function(){return this._intSegments},Hn.prototype.count=function(){return this._intersectionCount},Hn.prototype.getIntersections=function(){return this._intersections},Hn.prototype.setFindAllIntersections=function(e){this._findAllIntersections=e},Hn.prototype.setKeepIntersections=function(e){this._keepIntersections=e},Hn.prototype.processIntersections=function(e,t,A,n){if(!this._findAllIntersections&&this.hasIntersection())return null;if(e===A&&t===n)return null;if(this._isCheckEndSegmentsOnly&&!this.isEndSegment(e,t)&&!this.isEndSegment(A,n))return null;var r=e.getCoordinates()[t],i=e.getCoordinates()[t+1],o=A.getCoordinates()[n],a=A.getCoordinates()[n+1];this._li.computeIntersection(r,i,o,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()&&(this._intSegments=new Array(4).fill(null),this._intSegments[0]=r,this._intSegments[1]=i,this._intSegments[2]=o,this._intSegments[3]=a,this._interiorIntersection=this._li.getIntersection(0),this._keepIntersections&&this._intersections.add(this._interiorIntersection),this._intersectionCount++)},Hn.prototype.isEndSegment=function(e,t){return 0===t||t>=e.size()-2},Hn.prototype.hasIntersection=function(){return null!==this._interiorIntersection},Hn.prototype.isDone=function(){return!this._findAllIntersections&&null!==this._interiorIntersection},Hn.prototype.interfaces_=function(){return[VA]},Hn.prototype.getClass=function(){return Hn},Hn.createAllIntersectionsFinder=function(e){var t=new Hn(e);return t.setFindAllIntersections(!0),t},Hn.createAnyIntersectionFinder=function(e){return new Hn(e)},Hn.createIntersectionCounter=function(e){var t=new Hn(e);return t.setFindAllIntersections(!0),t.setKeepIntersections(!1),t};var Yn=function(){this._li=new re,this._segStrings=null,this._findAllIntersections=!1,this._segInt=null,this._isValid=!0;var e=arguments[0];this._segStrings=e};Yn.prototype.execute=function(){if(null!==this._segInt)return null;this.checkInteriorIntersections()},Yn.prototype.getIntersections=function(){return this._segInt.getIntersections()},Yn.prototype.isValid=function(){return this.execute(),this._isValid},Yn.prototype.setFindAllIntersections=function(e){this._findAllIntersections=e},Yn.prototype.checkInteriorIntersections=function(){this._isValid=!0,this._segInt=new Hn(this._li),this._segInt.setFindAllIntersections(this._findAllIntersections);var e=new QA;if(e.setSegmentIntersector(this._segInt),e.computeNodes(this._segStrings),this._segInt.hasIntersection())return this._isValid=!1,null},Yn.prototype.checkValid=function(){if(this.execute(),!this._isValid)throw new Ft(this.getErrorMessage(),this._segInt.getInteriorIntersection())},Yn.prototype.getErrorMessage=function(){if(this._isValid)return"no intersections found";var e=this._segInt.getIntersectionSegments();return"found non-noded intersection between "+z.toLineString(e[0],e[1])+" and "+z.toLineString(e[2],e[3])},Yn.prototype.interfaces_=function(){return[]},Yn.prototype.getClass=function(){return Yn},Yn.computeIntersections=function(e){var t=new Yn(e);return t.setFindAllIntersections(!0),t.isValid(),t.getIntersections()};var Jn=function e(){this._nv=null;var t=arguments[0];this._nv=new Yn(e.toSegmentStrings(t))};Jn.prototype.checkValid=function(){this._nv.checkValid()},Jn.prototype.interfaces_=function(){return[]},Jn.prototype.getClass=function(){return Jn},Jn.toSegmentStrings=function(e){for(var t=new ve,A=e.iterator();A.hasNext();){var n=A.next();t.add(new Zn(n.getCoordinates(),n))}return t},Jn.checkValid=function(e){new Jn(e).checkValid()};var jn=function(e){this._mapOp=e};jn.prototype.map=function(e){for(var t=new ve,A=0;A0&&n<4&&!this._preserveType?this._factory.createLineString(A):this._factory.createLinearRing(A)},Kn.prototype.interfaces_=function(){return[]},Kn.prototype.getClass=function(){return Kn};var Wn=function e(){if(this._snapTolerance=0,this._srcPts=null,this._seg=new CA,this._allowSnappingToSourceVertices=!1,this._isClosed=!1,arguments[0]instanceof We&&"number"==typeof arguments[1]){var t=arguments[0],A=arguments[1];e.call(this,t.getCoordinates(),A)}else if(arguments[0]instanceof Array&&"number"==typeof arguments[1]){var n=arguments[0],r=arguments[1];this._srcPts=n,this._isClosed=e.isClosed(n),this._snapTolerance=r}};Wn.prototype.snapVertices=function(e,t){for(var A=this._isClosed?e.size()-1:e.size(),n=0;n=0&&e.add(i+1,new m(r),!1)}},Wn.prototype.findSegmentIndexToSnap=function(e,t){for(var A=p.MAX_VALUE,n=-1,r=0;rt&&(t=n)}return t}if(2===arguments.length){var r=arguments[0],i=arguments[1];return Math.min(Xn.computeOverlaySnapTolerance(r),Xn.computeOverlaySnapTolerance(i))}},Xn.computeSizeBasedSnapTolerance=function(e){var t=e.getEnvelopeInternal();return Math.min(t.getHeight(),t.getWidth())*Xn.SNAP_PRECISION_FACTOR},Xn.snapToSelf=function(e,t,A){return new Xn(e).snapToSelf(t,A)},qn.SNAP_PRECISION_FACTOR.get=function(){return 1e-9},Object.defineProperties(Xn,qn);var zn=function(e){function t(t,A,n){e.call(this),this._snapTolerance=t||null,this._snapPts=A||null,this._isSelfSnap=void 0!==n&&n}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.snapLine=function(e,t){var A=new Wn(e,this._snapTolerance);return A.setAllowSnappingToSourceVertices(this._isSelfSnap),A.snapTo(t)},t.prototype.transformCoordinates=function(e,t){var A=e.toCoordinateArray(),n=this.snapLine(A,this._snapPts);return this._factory.getCoordinateSequenceFactory().create(n)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(Kn),$n=function(){this._isFirst=!0,this._commonMantissaBitsCount=53,this._commonBits=0,this._commonSignExp=null};$n.prototype.getCommon=function(){return p.longBitsToDouble(this._commonBits)},$n.prototype.add=function(e){var t=p.doubleToLongBits(e);return this._isFirst?(this._commonBits=t,this._commonSignExp=$n.signExpBits(this._commonBits),this._isFirst=!1,null):$n.signExpBits(t)!==this._commonSignExp?(this._commonBits=0,null):(this._commonMantissaBitsCount=$n.numCommonMostSigMantissaBits(this._commonBits,t),void(this._commonBits=$n.zeroLowerBits(this._commonBits,64-(12+this._commonMantissaBitsCount))))},$n.prototype.toString=function(){if(1===arguments.length){var e=arguments[0],t=p.longBitsToDouble(e),A="0000000000000000000000000000000000000000000000000000000000000000"+p.toBinaryString(e),n=A.substring(A.length-64);return n.substring(0,1)+" "+n.substring(1,12)+"(exp) "+n.substring(12)+" [ "+t+" ]"}},$n.prototype.interfaces_=function(){return[]},$n.prototype.getClass=function(){return $n},$n.getBit=function(e,t){return 0!=(e&1<>52},$n.zeroLowerBits=function(e,t){return e&~((1<=0;n--){if($n.getBit(e,n)!==$n.getBit(t,n))return A;A++}return 52};var er=function(){this._commonCoord=null,this._ccFilter=new Ar},tr={CommonCoordinateFilter:{configurable:!0},Translater:{configurable:!0}};er.prototype.addCommonBits=function(e){var t=new nr(this._commonCoord);e.apply(t),e.geometryChanged()},er.prototype.removeCommonBits=function(e){if(0===this._commonCoord.x&&0===this._commonCoord.y)return e;var t=new m(this._commonCoord);t.x=-t.x,t.y=-t.y;var A=new nr(t);return e.apply(A),e.geometryChanged(),e},er.prototype.getCommonCoordinate=function(){return this._commonCoord},er.prototype.add=function(e){e.apply(this._ccFilter),this._commonCoord=this._ccFilter.getCommonCoordinate()},er.prototype.interfaces_=function(){return[]},er.prototype.getClass=function(){return er},tr.CommonCoordinateFilter.get=function(){return Ar},tr.Translater.get=function(){return nr},Object.defineProperties(er,tr);var Ar=function(){this._commonBitsX=new $n,this._commonBitsY=new $n};Ar.prototype.filter=function(e){this._commonBitsX.add(e.x),this._commonBitsY.add(e.y)},Ar.prototype.getCommonCoordinate=function(){return new m(this._commonBitsX.getCommon(),this._commonBitsY.getCommon())},Ar.prototype.interfaces_=function(){return[Ie]},Ar.prototype.getClass=function(){return Ar};var nr=function(){this.trans=null;var e=arguments[0];this.trans=e};nr.prototype.filter=function(e,t){var A=e.getOrdinate(t,0)+this.trans.x,n=e.getOrdinate(t,1)+this.trans.y;e.setOrdinate(t,0,A),e.setOrdinate(t,1,n)},nr.prototype.isDone=function(){return!1},nr.prototype.isGeometryChanged=function(){return!0},nr.prototype.interfaces_=function(){return[Ze]},nr.prototype.getClass=function(){return nr};var rr=function(e,t){this._geom=new Array(2).fill(null),this._snapTolerance=null,this._cbr=null,this._geom[0]=e,this._geom[1]=t,this.computeSnapTolerance()};rr.prototype.selfSnap=function(e){return new Xn(e).snapTo(e,this._snapTolerance)},rr.prototype.removeCommonBits=function(e){this._cbr=new er,this._cbr.add(e[0]),this._cbr.add(e[1]);var t=new Array(2).fill(null);return t[0]=this._cbr.removeCommonBits(e[0].copy()),t[1]=this._cbr.removeCommonBits(e[1].copy()),t},rr.prototype.prepareResult=function(e){return this._cbr.addCommonBits(e),e},rr.prototype.getResultGeometry=function(e){var t=this.snap(this._geom),A=wr.overlayOp(t[0],t[1],e);return this.prepareResult(A)},rr.prototype.checkValid=function(e){e.isValid()||J.out.println("Snapped geometry is invalid")},rr.prototype.computeSnapTolerance=function(){this._snapTolerance=Xn.computeOverlaySnapTolerance(this._geom[0],this._geom[1])},rr.prototype.snap=function(e){var t=this.removeCommonBits(e);return Xn.snap(t[0],t[1],this._snapTolerance)},rr.prototype.interfaces_=function(){return[]},rr.prototype.getClass=function(){return rr},rr.overlayOp=function(e,t,A){return new rr(e,t).getResultGeometry(A)},rr.union=function(e,t){return rr.overlayOp(e,t,wr.UNION)},rr.intersection=function(e,t){return rr.overlayOp(e,t,wr.INTERSECTION)},rr.symDifference=function(e,t){return rr.overlayOp(e,t,wr.SYMDIFFERENCE)},rr.difference=function(e,t){return rr.overlayOp(e,t,wr.DIFFERENCE)};var ir=function(e,t){this._geom=new Array(2).fill(null),this._geom[0]=e,this._geom[1]=t};ir.prototype.getResultGeometry=function(e){var t=null,A=!1,n=null;try{t=wr.overlayOp(this._geom[0],this._geom[1],e),A=!0}catch(e){if(!(e instanceof $))throw e;n=e}if(!A)try{t=rr.overlayOp(this._geom[0],this._geom[1],e)}catch(e){throw e instanceof $?n:e}return t},ir.prototype.interfaces_=function(){return[]},ir.prototype.getClass=function(){return ir},ir.overlayOp=function(e,t,A){return new ir(e,t).getResultGeometry(A)},ir.union=function(e,t){return ir.overlayOp(e,t,wr.UNION)},ir.intersection=function(e,t){return ir.overlayOp(e,t,wr.INTERSECTION)},ir.symDifference=function(e,t){return ir.overlayOp(e,t,wr.SYMDIFFERENCE)},ir.difference=function(e,t){return ir.overlayOp(e,t,wr.DIFFERENCE)};var or=function(){this.mce=null,this.chainIndex=null;var e=arguments[0],t=arguments[1];this.mce=e,this.chainIndex=t};or.prototype.computeIntersections=function(e,t){this.mce.computeIntersectsForChain(this.chainIndex,e.mce,e.chainIndex,t)},or.prototype.interfaces_=function(){return[]},or.prototype.getClass=function(){return or};var ar=function e(){if(this._label=null,this._xValue=null,this._eventType=null,this._insertEvent=null,this._deleteEventIndex=null,this._obj=null,2===arguments.length){var t=arguments[0],A=arguments[1];this._eventType=e.DELETE,this._xValue=t,this._insertEvent=A}else if(3===arguments.length){var n=arguments[0],r=arguments[1],i=arguments[2];this._eventType=e.INSERT,this._label=n,this._xValue=r,this._obj=i}},sr={INSERT:{configurable:!0},DELETE:{configurable:!0}};ar.prototype.isDelete=function(){return this._eventType===ar.DELETE},ar.prototype.setDeleteEventIndex=function(e){this._deleteEventIndex=e},ar.prototype.getObject=function(){return this._obj},ar.prototype.compareTo=function(e){var t=e;return this._xValuet._xValue?1:this._eventTypet._eventType?1:0},ar.prototype.getInsertEvent=function(){return this._insertEvent},ar.prototype.isInsert=function(){return this._eventType===ar.INSERT},ar.prototype.isSameLabel=function(e){return null!==this._label&&this._label===e._label},ar.prototype.getDeleteEventIndex=function(){return this._deleteEventIndex},ar.prototype.interfaces_=function(){return[Q]},ar.prototype.getClass=function(){return ar},sr.INSERT.get=function(){return 1},sr.DELETE.get=function(){return 2},Object.defineProperties(ar,sr);var gr=function(){};gr.prototype.interfaces_=function(){return[]},gr.prototype.getClass=function(){return gr};var cr=function(){this._hasIntersection=!1,this._hasProper=!1,this._hasProperInterior=!1,this._properIntersectionPoint=null,this._li=null,this._includeProper=null,this._recordIsolated=null,this._isSelfIntersection=null,this._numIntersections=0,this.numTests=0,this._bdyNodes=null,this._isDone=!1,this._isDoneWhenProperInt=!1;var e=arguments[0],t=arguments[1],A=arguments[2];this._li=e,this._includeProper=t,this._recordIsolated=A};cr.prototype.isTrivialIntersection=function(e,t,A,n){if(e===A&&1===this._li.getIntersectionNum()){if(cr.isAdjacentSegments(t,n))return!0;if(e.isClosed()){var r=e.getNumPoints()-1;if(0===t&&n===r||0===n&&t===r)return!0}}return!1},cr.prototype.getProperIntersectionPoint=function(){return this._properIntersectionPoint},cr.prototype.setIsDoneIfProperInt=function(e){this._isDoneWhenProperInt=e},cr.prototype.hasProperInteriorIntersection=function(){return this._hasProperInterior},cr.prototype.isBoundaryPointInternal=function(e,t){for(var A=t.iterator();A.hasNext();){var n=A.next().getCoordinate();if(e.isIntersection(n))return!0}return!1},cr.prototype.hasProperIntersection=function(){return this._hasProper},cr.prototype.hasIntersection=function(){return this._hasIntersection},cr.prototype.isDone=function(){return this._isDone},cr.prototype.isBoundaryPoint=function(e,t){return null!==t&&(!!this.isBoundaryPointInternal(e,t[0])||!!this.isBoundaryPointInternal(e,t[1]))},cr.prototype.setBoundaryNodes=function(e,t){this._bdyNodes=new Array(2).fill(null),this._bdyNodes[0]=e,this._bdyNodes[1]=t},cr.prototype.addIntersections=function(e,t,A,n){if(e===A&&t===n)return null;this.numTests++;var r=e.getCoordinates()[t],i=e.getCoordinates()[t+1],o=A.getCoordinates()[n],a=A.getCoordinates()[n+1];this._li.computeIntersection(r,i,o,a),this._li.hasIntersection()&&(this._recordIsolated&&(e.setIsolated(!1),A.setIsolated(!1)),this._numIntersections++,this.isTrivialIntersection(e,t,A,n)||(this._hasIntersection=!0,!this._includeProper&&this._li.isProper()||(e.addIntersections(this._li,t,0),A.addIntersections(this._li,n,1)),this._li.isProper()&&(this._properIntersectionPoint=this._li.getIntersection(0).copy(),this._hasProper=!0,this._isDoneWhenProperInt&&(this._isDone=!0),this.isBoundaryPoint(this._li,this._bdyNodes)||(this._hasProperInterior=!0))))},cr.prototype.interfaces_=function(){return[]},cr.prototype.getClass=function(){return cr},cr.isAdjacentSegments=function(e,t){return 1===Math.abs(e-t)};var ur=function(e){function t(){e.call(this),this.events=new ve,this.nOverlaps=null}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.prepareEvents=function(){$t.sort(this.events);for(var e=0;et||this._maxi?1:0},Cr.prototype.interfaces_=function(){return[v]},Cr.prototype.getClass=function(){return Cr};var hr=function(e){function t(){e.call(this),this._item=null;var t=arguments[0],A=arguments[1],n=arguments[2];this._min=t,this._max=A,this._item=n}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.query=function(e,t,A){if(!this.intersects(e,t))return null;A.visitItem(this._item)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(lr),fr=function(e){function t(){e.call(this),this._node1=null,this._node2=null;var t=arguments[0],A=arguments[1];this._node1=t,this._node2=A,this.buildExtent(this._node1,this._node2)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.buildExtent=function(e,t){this._min=Math.min(e._min,t._min),this._max=Math.max(e._max,t._max)},t.prototype.query=function(e,t,A){if(!this.intersects(e,t))return null;null!==this._node1&&this._node1.query(e,t,A),null!==this._node2&&this._node2.query(e,t,A)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t}(lr),dr=function(){this._leaves=new ve,this._root=null,this._level=0};dr.prototype.buildTree=function(){$t.sort(this._leaves,new lr.NodeComparator);for(var e=this._leaves,t=null,A=new ve;;){if(this.buildLevel(e,A),1===A.size())return A.get(0);t=e,e=A,A=t}},dr.prototype.insert=function(e,t,A){if(null!==this._root)throw new Error("Index cannot be added to once it has been queried");this._leaves.add(new hr(e,t,A))},dr.prototype.query=function(e,t,A){this.init(),this._root.query(e,t,A)},dr.prototype.buildRoot=function(){if(null!==this._root)return null;this._root=this.buildTree()},dr.prototype.printNode=function(e){J.out.println(z.toLineString(new m(e._min,this._level),new m(e._max,this._level)))},dr.prototype.init=function(){if(null!==this._root)return null;this.buildRoot()},dr.prototype.buildLevel=function(e,t){this._level++,t.clear();for(var A=0;A=2,"found LineString with single point"),this.insertBoundaryPoint(this._argIndex,t[0]),this.insertBoundaryPoint(this._argIndex,t[t.length-1])},t.prototype.getInvalidPoint=function(){return this._invalidPoint},t.prototype.getBoundaryPoints=function(){for(var e=this.getBoundaryNodes(),t=new Array(e.size()).fill(null),A=0,n=e.iterator();n.hasNext();){var r=n.next();t[A++]=r.getCoordinate().copy()}return t},t.prototype.getBoundaryNodes=function(){return null===this._boundaryNodes&&(this._boundaryNodes=this._nodes.getBoundaryNodes(this._argIndex)),this._boundaryNodes},t.prototype.addSelfIntersectionNode=function(e,t,A){if(this.isBoundaryNode(e,t))return null;A===F.BOUNDARY&&this._useBoundaryDeterminationRule?this.insertBoundaryPoint(e,t):this.insertPoint(e,t,A)},t.prototype.addPolygonRing=function(e,t,A){if(e.isEmpty())return null;var n=we.removeRepeatedPoints(e.getCoordinates());if(n.length<4)return this._hasTooFewPoints=!0,this._invalidPoint=n[0],null;var r=t,i=A;ae.isCCW(n)&&(r=A,i=t);var o=new tn(n,new kt(this._argIndex,F.BOUNDARY,r,i));this._lineEdgeMap.put(e,o),this.insertEdge(o),this.insertPoint(this._argIndex,n[0],F.BOUNDARY)},t.prototype.insertPoint=function(e,t,A){var n=this._nodes.addNode(t),r=n.getLabel();null===r?n._label=new kt(e,A):r.setLocation(e,A)},t.prototype.createEdgeSetIntersector=function(){return new ur},t.prototype.addSelfIntersectionNodes=function(e){for(var t=this._edges.iterator();t.hasNext();)for(var A=t.next(),n=A.getLabel().getLocation(e),r=A.eiList.iterator();r.hasNext();){var i=r.next();this.addSelfIntersectionNode(e,i.coord,n)}},t.prototype.add=function(){if(1!==arguments.length)return e.prototype.add.apply(this,arguments);var t=arguments[0];if(t.isEmpty())return null;if(t instanceof At&&(this._useBoundaryDeterminationRule=!1),t instanceof $e)this.addPolygon(t);else if(t instanceof We)this.addLineString(t);else if(t instanceof qe)this.addPoint(t);else if(t instanceof et)this.addCollection(t);else if(t instanceof Ye)this.addCollection(t);else if(t instanceof At)this.addCollection(t);else{if(!(t instanceof He))throw new Error(t.getClass().getName());this.addCollection(t)}},t.prototype.addCollection=function(e){for(var t=0;t50?(null===this._areaPtLocator&&(this._areaPtLocator=new pr(this._parentGeom)),this._areaPtLocator.locate(e)):this._ptLocator.locate(e,this._parentGeom)},t.prototype.findEdge=function(){if(1===arguments.length){var t=arguments[0];return this._lineEdgeMap.get(t)}return e.prototype.findEdge.apply(this,arguments)},t.prototype.interfaces_=function(){return[]},t.prototype.getClass=function(){return t},t.determineBoundary=function(e,t){return e.isInBoundary(t)?F.BOUNDARY:F.INTERIOR},t}(Jt),mr=function(){if(this._li=new re,this._resultPrecisionModel=null,this._arg=null,1===arguments.length){var e=arguments[0];this.setComputationPrecision(e.getPrecisionModel()),this._arg=new Array(1).fill(null),this._arg[0]=new vr(0,e)}else if(2===arguments.length){var t=arguments[0],A=arguments[1],n=Ce.OGC_SFS_BOUNDARY_RULE;t.getPrecisionModel().compareTo(A.getPrecisionModel())>=0?this.setComputationPrecision(t.getPrecisionModel()):this.setComputationPrecision(A.getPrecisionModel()),this._arg=new Array(2).fill(null),this._arg[0]=new vr(0,t,n),this._arg[1]=new vr(1,A,n)}else if(3===arguments.length){var r=arguments[0],i=arguments[1],o=arguments[2];r.getPrecisionModel().compareTo(i.getPrecisionModel())>=0?this.setComputationPrecision(r.getPrecisionModel()):this.setComputationPrecision(i.getPrecisionModel()),this._arg=new Array(2).fill(null),this._arg[0]=new vr(0,r,o),this._arg[1]=new vr(1,i,o)}};mr.prototype.getArgGeometry=function(e){return this._arg[e].getGeometry()},mr.prototype.setComputationPrecision=function(e){this._resultPrecisionModel=e,this._li.setPrecisionModel(this._resultPrecisionModel)},mr.prototype.interfaces_=function(){return[]},mr.prototype.getClass=function(){return mr};var br=function(){};br.prototype.interfaces_=function(){return[]},br.prototype.getClass=function(){return br},br.map=function(){if(arguments[0]instanceof ce&&D(arguments[1],br.MapOp)){for(var e=arguments[0],t=arguments[1],A=new ve,n=0;n=e.size()?null:e.get(t)},xr.union=function(e){return new xr(e).union()},Nr.STRTREE_NODE_CAPACITY.get=function(){return 4},Object.defineProperties(xr,Nr);var Ur=function(){};Ur.prototype.interfaces_=function(){return[]},Ur.prototype.getClass=function(){return Ur},Ur.union=function(e,t){if(e.isEmpty()||t.isEmpty()){if(e.isEmpty()&&t.isEmpty())return wr.createEmptyResult(wr.UNION,e,t,e.getFactory());if(e.isEmpty())return t.copy();if(t.isEmpty())return e.copy()}return e.checkNotGeometryCollection(e),e.checkNotGeometryCollection(t),ir.overlayOp(e,t,wr.UNION)},e.GeoJSONReader=vt,e.GeoJSONWriter=mt,e.OverlayOp=wr,e.UnionOp=Ur,e.BufferOp=hn,Object.defineProperty(e,"__esModule",{value:!0})}(t)},function(e,t,A){"use strict";var n=/("(?:[^\\"]|\\.)*")|[:,]/g;e.exports=function(e,t){var A,r,i;return t=t||{},A=JSON.stringify([1],void 0,void 0===t.indent?2:t.indent).slice(2,-3),r=""===A?1/0:void 0===t.maxLength?80:t.maxLength,i=t.replacer,function e(t,o,a){var s,g,c,u,l,I,C,h,f,d,B,p;if(t&&"function"===typeof t.toJSON&&(t=t.toJSON()),void 0===(B=JSON.stringify(t,i)))return B;if(C=r-o.length-a,B.length<=C&&(f=B.replace(n,(function(e,t){return t||e+" "}))).length<=C)return f;if(null!=i&&(t=JSON.parse(B),i=void 0),"object"===typeof t&&null!==t){if(h=o+A,c=[],g=0,Array.isArray(t))for(d="[",s="]",C=t.length;g0)return[d,A+c.join(",\n"+h),s].join("\n"+o)}return B}(e,"",0)}},function(e,t,A){"use strict";var n,r=A(2),i=A(169),o=A(429);A.d(t,"a",(function(){return s})),A.d(t,"c",(function(){return l})),A.d(t,"b",(function(){return I}));var a=(n={},Object(r.a)(n,i.b,"#ifdef MODULE_LOGDEPTH\n logdepth_adjustPosition(gl_Position);\n#endif\n"),Object(r.a)(n,i.a,"#ifdef MODULE_MATERIAL\n gl_FragColor = material_filterColor(gl_FragColor);\n#endif\n\n#ifdef MODULE_LIGHTING\n gl_FragColor = lighting_filterColor(gl_FragColor);\n#endif\n\n#ifdef MODULE_FOG\n gl_FragColor = fog_filterColor(gl_FragColor);\n#endif\n\n#ifdef MODULE_PICKING\n gl_FragColor = picking_filterHighlightColor(gl_FragColor);\n gl_FragColor = picking_filterPickingColor(gl_FragColor);\n#endif\n\n#ifdef MODULE_LOGDEPTH\n logdepth_setFragDepth();\n#endif\n"),n),s="__LUMA_INJECT_DECLARATIONS__",g=/void\s+main\s*\([^)]*\)\s*\{\n?/,c=/}\n?[^{}]*$/,u=[];function l(e,t,A){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=t===i.b,o=function(t){var n=A[t];n.sort((function(e,t){return e.order-t.order})),u.length=n.length;for(var i=0,o=n.length;i1),e.forEach((function(e){for(var A in e)t[A]=t[A]?"".concat(t[A],"\n").concat(e[A]):e[A]})),t}},function(e,t,A){"use strict";var n=A(14),r=A(21),i=A(0),o=A.n(i),a=(A(13),A(39)),s=A(19),g=A(51),c=A(66),u=A(28),l=A(200),I=A(137),C=A(204),h=A(321),f=A(225),d=A(288);function B(e,t){var A=Object.create(null);return e&&i.Children.map(e,(function(e){return e})).forEach((function(e){A[e.key]=function(e){return t&&Object(i.isValidElement)(e)?t(e):e}(e)})),A}function p(e,t,A){return null!=A[t]?A[t]:e.props[t]}function E(e,t,A){var n=B(e.children),r=function(e,t){function A(A){return A in t?t[A]:e[A]}e=e||{},t=t||{};var n,r=Object.create(null),i=[];for(var o in e)o in t?i.length&&(r[o]=i,i=[]):i.push(o);var a={};for(var s in t){if(r[s])for(n=0;n0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},A=arguments.length>2?arguments[2]:void 0,n=t.pulsate,r=void 0!==n&&n,i=t.center,a=void 0===i?o||t.pulsate:i,s=t.fakeElement,g=void 0!==s&&s;if("mousedown"===e.type&&d.current)d.current=!1;else{"touchstart"===e.type&&(d.current=!0);var c,u,l,I=g?null:E.current,C=I?I.getBoundingClientRect():{width:0,height:0,left:0,top:0};if(a||0===e.clientX&&0===e.clientY||!e.clientX&&!e.touches)c=Math.round(C.width/2),u=Math.round(C.height/2);else{var h=e.touches?e.touches[0]:e,f=h.clientX,y=h.clientY;c=Math.round(f-C.left),u=Math.round(y-C.top)}if(a)(l=Math.sqrt((2*Math.pow(C.width,2)+Math.pow(C.height,2))/3))%2===0&&(l+=1);else{var v=2*Math.max(Math.abs((I?I.clientWidth:0)-c),c)+2,m=2*Math.max(Math.abs((I?I.clientHeight:0)-u),u)+2;l=Math.sqrt(Math.pow(v,2)+Math.pow(m,2))}e.touches?null===p.current&&(p.current=function(){Q({pulsate:r,rippleX:c,rippleY:u,rippleSize:l,cb:A})},B.current=setTimeout((function(){p.current&&(p.current(),p.current=null)}),80)):Q({pulsate:r,rippleX:c,rippleY:u,rippleSize:l,cb:A})}}),[o,Q]),m=i.useCallback((function(){y({},{pulsate:!0})}),[y]),w=i.useCallback((function(e,t){if(clearTimeout(B.current),"touchend"===e.type&&p.current)return e.persist(),p.current(),p.current=null,void(B.current=setTimeout((function(){w(e,t)})));p.current=null,C((function(e){return e.length>0?e.slice(1):e})),f.current=t}),[]);return i.useImperativeHandle(t,(function(){return{pulsate:m,start:y,stop:w}}),[m,y,w]),i.createElement("span",Object(n.a)({className:Object(s.a)(a.root,g),ref:E},c),i.createElement(v,{component:null,exit:!0},l))})),S=Object(u.a)((function(e){return{root:{overflow:"hidden",pointerEvents:"none",position:"absolute",zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:"inherit"},ripple:{opacity:0,position:"absolute"},rippleVisible:{opacity:.3,transform:"scale(1)",animation:"$enter ".concat(550,"ms ").concat(e.transitions.easing.easeInOut)},ripplePulsate:{animationDuration:"".concat(e.transitions.duration.shorter,"ms")},child:{opacity:1,display:"block",width:"100%",height:"100%",borderRadius:"50%",backgroundColor:"currentColor"},childLeaving:{opacity:0,animation:"$exit ".concat(550,"ms ").concat(e.transitions.easing.easeInOut)},childPulsate:{position:"absolute",left:0,top:0,animation:"$pulsate 2500ms ".concat(e.transitions.easing.easeInOut," 200ms infinite")},"@keyframes enter":{"0%":{transform:"scale(0)",opacity:.1},"100%":{transform:"scale(1)",opacity:.3}},"@keyframes exit":{"0%":{opacity:1},"100%":{opacity:0}},"@keyframes pulsate":{"0%":{transform:"scale(1)"},"50%":{transform:"scale(0.92)"},"100%":{transform:"scale(1)"}}}}),{flip:!1,name:"MuiTouchRipple"})(i.memo(w)),F=i.forwardRef((function(e,t){var A=e.action,o=e.buttonRef,u=e.centerRipple,I=void 0!==u&&u,C=e.children,h=e.classes,f=e.className,d=e.component,B=void 0===d?"button":d,p=e.disabled,E=void 0!==p&&p,Q=e.disableRipple,y=void 0!==Q&&Q,v=e.disableTouchRipple,m=void 0!==v&&v,b=e.focusRipple,w=void 0!==b&&b,F=e.focusVisibleClassName,R=e.onBlur,D=e.onClick,G=e.onFocus,k=e.onFocusVisible,x=e.onKeyDown,N=e.onKeyUp,U=e.onMouseDown,_=e.onMouseLeave,M=e.onMouseUp,O=e.onTouchEnd,L=e.onTouchMove,T=e.onTouchStart,Z=e.onDragLeave,H=e.tabIndex,Y=void 0===H?0:H,J=e.TouchRippleProps,j=e.type,P=void 0===j?"button":j,V=Object(r.a)(e,["action","buttonRef","centerRipple","children","classes","className","component","disabled","disableRipple","disableTouchRipple","focusRipple","focusVisibleClassName","onBlur","onClick","onFocus","onFocusVisible","onKeyDown","onKeyUp","onMouseDown","onMouseLeave","onMouseUp","onTouchEnd","onTouchMove","onTouchStart","onDragLeave","tabIndex","TouchRippleProps","type"]),K=i.useRef(null);var W=i.useRef(null),X=i.useState(!1),q=X[0],z=X[1];E&&q&&z(!1);var $=Object(l.a)(),ee=$.isFocusVisible,te=$.onBlurVisible,Ae=$.ref;function ne(e,t){var A=arguments.length>2&&void 0!==arguments[2]?arguments[2]:m;return Object(c.a)((function(n){return t&&t(n),!A&&W.current&&W.current[e](n),!0}))}i.useImperativeHandle(A,(function(){return{focusVisible:function(){z(!0),K.current.focus()}}}),[]),i.useEffect((function(){q&&w&&!y&&W.current.pulsate()}),[y,w,q]);var re=ne("start",U),ie=ne("stop",Z),oe=ne("stop",M),ae=ne("stop",(function(e){q&&e.preventDefault(),_&&_(e)})),se=ne("start",T),ge=ne("stop",O),ce=ne("stop",L),ue=ne("stop",(function(e){q&&(te(e),z(!1)),R&&R(e)}),!1),le=Object(c.a)((function(e){K.current||(K.current=e.currentTarget),ee(e)&&(z(!0),k&&k(e)),G&&G(e)})),Ie=function(){var e=a.findDOMNode(K.current);return B&&"button"!==B&&!("A"===e.tagName&&e.href)},Ce=i.useRef(!1),he=Object(c.a)((function(e){w&&!Ce.current&&q&&W.current&&" "===e.key&&(Ce.current=!0,e.persist(),W.current.stop(e,(function(){W.current.start(e)}))),e.target===e.currentTarget&&Ie()&&" "===e.key&&e.preventDefault(),x&&x(e),e.target===e.currentTarget&&Ie()&&"Enter"===e.key&&!E&&(e.preventDefault(),D&&D(e))})),fe=Object(c.a)((function(e){w&&" "===e.key&&W.current&&q&&!e.defaultPrevented&&(Ce.current=!1,e.persist(),W.current.stop(e,(function(){W.current.pulsate(e)}))),N&&N(e),D&&e.target===e.currentTarget&&Ie()&&" "===e.key&&!e.defaultPrevented&&D(e)})),de=B;"button"===de&&V.href&&(de="a");var Be={};"button"===de?(Be.type=P,Be.disabled=E):("a"===de&&V.href||(Be.role="button"),Be["aria-disabled"]=E);var pe=Object(g.a)(o,t),Ee=Object(g.a)(Ae,K),Qe=Object(g.a)(pe,Ee),ye=i.useState(!1),ve=ye[0],me=ye[1];i.useEffect((function(){me(!0)}),[]);var be=ve&&!y&&!E;return i.createElement(de,Object(n.a)({className:Object(s.a)(h.root,f,q&&[h.focusVisible,F],E&&h.disabled),onBlur:ue,onClick:D,onFocus:le,onKeyDown:he,onKeyUp:fe,onMouseDown:re,onMouseLeave:ae,onMouseUp:oe,onDragLeave:ie,onTouchEnd:ge,onTouchMove:ce,onTouchStart:se,ref:Qe,tabIndex:E?-1:Y},Be,V),C,be?i.createElement(S,Object(n.a)({ref:W,center:I},J)):null)}));t.a=Object(u.a)({root:{display:"inline-flex",alignItems:"center",justifyContent:"center",position:"relative",WebkitTapHighlightColor:"transparent",backgroundColor:"transparent",outline:0,border:0,margin:0,borderRadius:0,padding:0,cursor:"pointer",userSelect:"none",verticalAlign:"middle","-moz-appearance":"none","-webkit-appearance":"none",textDecoration:"none",color:"inherit","&::-moz-focus-inner":{borderStyle:"none"},"&$disabled":{pointerEvents:"none",cursor:"default"},"@media print":{colorAdjust:"exact"}},disabled:{},focusVisible:{}},{name:"MuiButtonBase"})(F)},,,,,,,,,,function(e,t,A){"use strict";var n=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function o(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},A=0;A<10;A++)t["_"+String.fromCharCode(A)]=A;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach((function(e){n[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(r){return!1}}()?Object.assign:function(e,t){for(var A,a,s=o(e),g=1;g-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}},function(e,t,A){(function(e){var n=A(543),r=t&&!t.nodeType&&t,i=r&&"object"==typeof e&&e&&!e.nodeType&&e,o=i&&i.exports===r&&n.process,a=function(){try{var e=i&&i.require&&i.require("util").types;return e||o&&o.binding&&o.binding("util")}catch(t){}}();e.exports=a}).call(this,A(155)(e))},function(e,t){var A=Object.prototype;e.exports=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||A)}},function(e,t,A){(function(e,A){var n="[object Arguments]",r="[object Map]",i="[object Object]",o="[object Set]",a=/^\[object .+?Constructor\]$/,s=/^(?:0|[1-9]\d*)$/,g={};g["[object Float32Array]"]=g["[object Float64Array]"]=g["[object Int8Array]"]=g["[object Int16Array]"]=g["[object Int32Array]"]=g["[object Uint8Array]"]=g["[object Uint8ClampedArray]"]=g["[object Uint16Array]"]=g["[object Uint32Array]"]=!0,g[n]=g["[object Array]"]=g["[object ArrayBuffer]"]=g["[object Boolean]"]=g["[object DataView]"]=g["[object Date]"]=g["[object Error]"]=g["[object Function]"]=g[r]=g["[object Number]"]=g[i]=g["[object RegExp]"]=g[o]=g["[object String]"]=g["[object WeakMap]"]=!1;var c="object"==typeof e&&e&&e.Object===Object&&e,u="object"==typeof self&&self&&self.Object===Object&&self,l=c||u||Function("return this")(),I=t&&!t.nodeType&&t,C=I&&"object"==typeof A&&A&&!A.nodeType&&A,h=C&&C.exports===I,f=h&&c.process,d=function(){try{return f&&f.binding&&f.binding("util")}catch(e){}}(),B=d&&d.isTypedArray;function p(e,t){for(var A=-1,n=null==e?0:e.length;++Aa))return!1;var g=i.get(e);if(g&&i.get(t))return g==t;var c=-1,u=!0,l=2&A?new re:void 0;for(i.set(e,t),i.set(t,e);++c-1},Ae.prototype.set=function(e,t){var A=this.__data__,n=ae(A,e);return n<0?(++this.size,A.push([e,t])):A[n][1]=t,this},ne.prototype.clear=function(){this.size=0,this.__data__={hash:new te,map:new(Y||Ae),string:new te}},ne.prototype.delete=function(e){var t=he(this,e).delete(e);return this.size-=t?1:0,t},ne.prototype.get=function(e){return he(this,e).get(e)},ne.prototype.has=function(e){return he(this,e).has(e)},ne.prototype.set=function(e,t){var A=he(this,e),n=A.size;return A.set(e,t),this.size+=A.size==n?0:1,this},re.prototype.add=re.prototype.push=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},re.prototype.has=function(e){return this.__data__.has(e)},ie.prototype.clear=function(){this.__data__=new Ae,this.size=0},ie.prototype.delete=function(e){var t=this.__data__,A=t.delete(e);return this.size=t.size,A},ie.prototype.get=function(e){return this.__data__.get(e)},ie.prototype.has=function(e){return this.__data__.has(e)},ie.prototype.set=function(e,t){var A=this.__data__;if(A instanceof Ae){var n=A.__data__;if(!Y||n.length<199)return n.push([e,t]),this.size=++A.size,this;A=this.__data__=new ne(n)}return A.set(e,t),this.size=A.size,this};var de=L?function(e){return null==e?[]:(e=Object(e),function(e,t){for(var A=-1,n=null==e?0:e.length,r=0,i=[];++A-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}function Se(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Fe(e){return null!=e&&"object"==typeof e}var Re=B?function(e){return function(t){return e(t)}}(B):function(e){return Fe(e)&&we(e.length)&&!!g[se(e)]};function De(e){return null!=(t=e)&&we(t.length)&&!be(t)?oe(e):le(e);var t}A.exports=function(e,t){return ce(e,t)}}).call(this,A(86),A(155)(e))},function(e,t,A){"use strict";function n(e){return(n="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"===typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.matchesSelector=u,t.matchesSelectorAndParentsTo=function(e,t,A){var n=e;do{if(u(n,t))return!0;if(n===A)return!1;n=n.parentNode}while(n);return!1},t.addEvent=function(e,t,A,n){if(!e)return;var r=s({capture:!0},n);e.addEventListener?e.addEventListener(t,A,r):e.attachEvent?e.attachEvent("on"+t,A):e["on"+t]=A},t.removeEvent=function(e,t,A,n){if(!e)return;var r=s({capture:!0},n);e.removeEventListener?e.removeEventListener(t,A,r):e.detachEvent?e.detachEvent("on"+t,A):e["on"+t]=null},t.outerHeight=function(e){var t=e.clientHeight,A=e.ownerDocument.defaultView.getComputedStyle(e);return t+=(0,r.int)(A.borderTopWidth),t+=(0,r.int)(A.borderBottomWidth)},t.outerWidth=function(e){var t=e.clientWidth,A=e.ownerDocument.defaultView.getComputedStyle(e);return t+=(0,r.int)(A.borderLeftWidth),t+=(0,r.int)(A.borderRightWidth)},t.innerHeight=function(e){var t=e.clientHeight,A=e.ownerDocument.defaultView.getComputedStyle(e);return t-=(0,r.int)(A.paddingTop),t-=(0,r.int)(A.paddingBottom)},t.innerWidth=function(e){var t=e.clientWidth,A=e.ownerDocument.defaultView.getComputedStyle(e);return t-=(0,r.int)(A.paddingLeft),t-=(0,r.int)(A.paddingRight)},t.offsetXYFromParent=function(e,t,A){var n=t===t.ownerDocument.body?{left:0,top:0}:t.getBoundingClientRect(),r=(e.clientX+t.scrollLeft-n.left)/A,i=(e.clientY+t.scrollTop-n.top)/A;return{x:r,y:i}},t.createCSSTransform=function(e,t){var A=l(e,t,"px");return g({},(0,i.browserPrefixToKey)("transform",i.default),A)},t.createSVGTransform=function(e,t){return l(e,t,"")},t.getTranslation=l,t.getTouch=function(e,t){return e.targetTouches&&(0,r.findInArray)(e.targetTouches,(function(e){return t===e.identifier}))||e.changedTouches&&(0,r.findInArray)(e.changedTouches,(function(e){return t===e.identifier}))},t.getTouchIdentifier=function(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier},t.addUserSelectStyles=function(e){if(!e)return;var t=e.getElementById("react-draggable-style-el");t||((t=e.createElement("style")).type="text/css",t.id="react-draggable-style-el",t.innerHTML=".react-draggable-transparent-selection *::-moz-selection {all: inherit;}\n",t.innerHTML+=".react-draggable-transparent-selection *::selection {all: inherit;}\n",e.getElementsByTagName("head")[0].appendChild(t));e.body&&I(e.body,"react-draggable-transparent-selection")},t.removeUserSelectStyles=function(e){if(!e)return;try{if(e.body&&C(e.body,"react-draggable-transparent-selection"),e.selection)e.selection.empty();else{var t=(e.defaultView||window).getSelection();t&&"Caret"!==t.type&&t.removeAllRanges()}}catch(A){}},t.addClassName=I,t.removeClassName=C;var r=A(352),i=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==n(e)&&"function"!==typeof e)return{default:e};var t=o();if(t&&t.has(e))return t.get(e);var A={},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)){var a=r?Object.getOwnPropertyDescriptor(e,i):null;a&&(a.get||a.set)?Object.defineProperty(A,i,a):A[i]=e[i]}A.default=e,t&&t.set(e,A);return A}(A(804));function o(){if("function"!==typeof WeakMap)return null;var e=new WeakMap;return o=function(){return e},e}function a(e,t){var A=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),A.push.apply(A,n)}return A}function s(e){for(var t=1;t=0)return!0;return!1};var r=n(A(251))}).call(this,A(90))},function(e,t,A){"use strict";A.d(t,"a",(function(){return s}));var n=A(3),r=A.n(n),i=A(12),o=A(228),a=A(194);function s(e){return g.apply(this,arguments)}function g(){return(g=Object(i.a)(r.a.mark((function e(t){var A,n,i,s,g,c,u,l;return r.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:A=[],n=!0,i=!1,e.prev=3,g=Object(o.a)(t);case 5:return e.next=7,g.next();case 7:return c=e.sent,n=c.done,e.next=11,c.value;case 11:if(u=e.sent,n){e.next=18;break}l=u,A.push(l);case 15:n=!0,e.next=5;break;case 18:e.next=24;break;case 20:e.prev=20,e.t0=e.catch(3),i=!0,s=e.t0;case 24:if(e.prev=24,e.prev=25,n||null==g.return){e.next=29;break}return e.next=29,g.return();case 29:if(e.prev=29,!i){e.next=32;break}throw s;case 32:return e.finish(29);case 33:return e.finish(24);case 34:return e.abrupt("return",a.b.apply(void 0,A));case 35:case"end":return e.stop()}}),e,null,[[3,20,24,34],[25,,29,33]])})))).apply(this,arguments)}},function(e,t,A){var n=A(585);e.exports=function(e,t,A){"__proto__"==t&&n?n(e,t,{configurable:!0,enumerable:!0,value:A,writable:!0}):e[t]=A}},function(e,t,A){var n=A(551)(Object.getPrototypeOf,Object);e.exports=n},function(e,t,A){var n=A(546);e.exports=function(e){var t=new e.constructor(e.byteLength);return new n(t).set(new n(e)),t}},function(e,t,A){"use strict";function n(e){return function(){return null}}A.d(t,"a",(function(){return n}))},function(e,t,A){"use strict";function n(e,t,A,n,r){return null}A.d(t,"a",(function(){return n}))},function(e,t,A){var n=A(358),r=A(911),i=A(913);e.exports=function(e,t){return i(r(e,t,n),e+"")}},function(e,t,A){var n=A(248),r=A(154);e.exports=function(e){return r(e)&&n(e)}},function(e,t){e.exports=function(e,t){for(var A=-1,n=null==e?0:e.length,r=Array(n);++A0?n:A)(e)}},function(e,t,A){var n=A(477)("keys"),r=A(362);e.exports=function(e){return n[e]||(n[e]=r(e))}},function(e,t,A){var n=A(191),r=A(190),i=r["__core-js_shared__"]||(r["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:n.version,mode:A(361)?"pure":"global",copyright:"\xa9 2019 Denis Pushkarev (zloirock.ru)"})},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,A){var n=A(474);e.exports=function(e){return Object(n(e))}},function(e,t){e.exports={}},function(e,t,A){var n=A(302),r=A(940),i=A(478),o=A(476)("IE_PROTO"),a=function(){},s=function(){var e,t=A(596)("iframe"),n=i.length;for(t.style.display="none",A(941).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("', pos);\n children = [S.slice(start, pos)];\n pos += 9;\n } else if (tagName == \"style\") {\n var start = pos + 1;\n pos = S.indexOf('', pos);\n children = [S.slice(start, pos)];\n pos += 8;\n } else if (NoChildNodes.indexOf(tagName) === -1) {\n pos++;\n children = parseChildren(tagName);\n } else {\n pos++;\n }\n } else {\n pos++;\n }\n return {\n tagName,\n attributes,\n children,\n };\n }\n\n /**\n * is parsing a string, that starts with a char and with the same usually ' or \"\n */\n\n function parseString() {\n var startChar = S[pos];\n var startpos = pos + 1;\n pos = S.indexOf(startChar, startpos);\n return S.slice(startpos, pos);\n }\n\n /**\n *\n */\n function findElements() {\n var r = new RegExp('\\\\s' + options.attrName + '\\\\s*=[\\'\"]' + options.attrValue + '[\\'\"]').exec(S);\n if (r) {\n return r.index;\n } else {\n return -1;\n }\n }\n\n var out = null;\n if (options.attrValue !== undefined) {\n options.attrName = options.attrName || 'id';\n var out = [];\n\n while ((pos = findElements()) !== -1) {\n pos = S.lastIndexOf('<', pos);\n if (pos !== -1) {\n out.push(parseNode());\n }\n S = S.substr(pos);\n pos = 0;\n }\n } else if (options.parseNode) {\n out = parseNode();\n } else {\n out = parseChildren('');\n }\n\n if (options.filter) {\n out = filter(out, options.filter);\n }\n\n if (options.simplify) {\n return simplify(Array.isArray(out) ? out : [out]);\n }\n\n if (options.setPos) {\n out.pos = pos;\n }\n\n return out;\n}\n\n/**\n * transform the DomObject to an object that is like the object of PHP`s simple_xmp_load_*() methods.\n * this format helps you to write that is more likely to keep your program working, even if there a small changes in the XML schema.\n * be aware, that it is not possible to reproduce the original xml from a simplified version, because the order of elements is not saved.\n * therefore your program will be more flexible and easier to read.\n *\n * @param {tNode[]} children the childrenList\n */\nfunction simplify(children) {\n var out = {};\n if (!children.length) {\n return '';\n }\n\n if (children.length === 1 && typeof children[0] == 'string') {\n return children[0];\n }\n // map each object\n children.forEach(function(child) {\n if (typeof child !== 'object') {\n return;\n }\n if (!out[child.tagName])\n out[child.tagName] = [];\n var kids = simplify(child.children);\n out[child.tagName].push(kids);\n if (Object.keys(child.attributes).length && typeof kids !== 'string') {\n kids._attributes = child.attributes;\n }\n });\n\n for (var i in out) {\n if (out[i].length == 1) {\n out[i] = out[i][0];\n }\n }\n\n return out;\n}\n\n/**\n * similar to simplify, but lost less\n *\n * @param {tNode[]} children the childrenList\n */\nfunction simplifyLostLess(children, parentAttributes = {}) {\n var out = {};\n if (!children.length) {\n return out;\n }\n\n if (children.length === 1 && typeof children[0] == 'string') {\n return Object.keys(parentAttributes).length ? {\n _attributes: parentAttributes,\n value: children[0]\n } : children[0];\n }\n // map each object\n children.forEach(function(child) {\n if (typeof child !== 'object') {\n return;\n }\n if (!out[child.tagName])\n out[child.tagName] = [];\n var kids = simplifyLostLess(child.children || [], child.attributes);\n out[child.tagName].push(kids);\n if (Object.keys(child.attributes).length) {\n kids._attributes = child.attributes;\n }\n });\n\n return out;\n}\n/**\n * behaves the same way as Array.filter, if the filter method return true, the element is in the resultList\n * @params children{Array} the children of a node\n * @param f{function} the filter method\n */\nfunction filter(children, f, dept = 0, path = '') {\n var out = [];\n children.forEach(function(child, i) {\n if (typeof(child) === 'object' && f(child, i, dept, path)) out.push(child);\n if (child.children) {\n var kids = filter(child.children, f, dept + 1, (path ? path + '.' : '') + i + '.' + child.tagName);\n out = out.concat(kids);\n }\n });\n return out;\n}\n/**\n * stringify a previously parsed string object.\n * this is useful,\n * 1. to remove whitespace\n * 2. to recreate xml data, with some changed data.\n * @param {tNode} O the object to Stringify\n */\nfunction stringify(O) {\n var out = '';\n\n function writeChildren(O) {\n if (O) {\n for (var i = 0; i < O.length; i++) {\n if (typeof O[i] == 'string') {\n out += O[i].trim();\n } else {\n writeNode(O[i]);\n }\n }\n }\n }\n\n function writeNode(N) {\n out += \"<\" + N.tagName;\n for (var i in N.attributes) {\n if (N.attributes[i] === null) {\n out += ' ' + i;\n } else if (N.attributes[i].indexOf('\"') === -1) {\n out += ' ' + i + '=\"' + N.attributes[i].trim() + '\"';\n } else {\n out += ' ' + i + \"='\" + N.attributes[i].trim() + \"'\";\n }\n }\n if (N.tagName[0] === '?') {\n out += '?>';\n return;\n }\n out += '>';\n writeChildren(N.children);\n out += '';\n }\n writeChildren(O);\n\n return out;\n}\n\n/**\n * use this method to read the text content, of some node.\n * It is great if you have mixed content like:\n * this text has some big text and a
link\n * @return {string}\n */\nfunction toContentString(tDom) {\n if (Array.isArray(tDom)) {\n var out = '';\n tDom.forEach(function(e) {\n out += ' ' + toContentString(e);\n out = out.trim();\n });\n return out;\n } else if (typeof tDom === 'object') {\n return toContentString(tDom.children)\n } else {\n return ' ' + tDom;\n }\n}\nfunction getElementById(S, id, simplified) {\n var out = parse(S, {\n attrValue: id\n });\n return simplified ? tXml.simplify(out) : out[0];\n}\nfunction getElementsByClassName(S, classname, simplified) {\n const out = parse(S, {\n attrName: 'class',\n attrValue: '[a-zA-Z0-9- ]*' + classname + '[a-zA-Z0-9- ]*'\n });\n return simplified ? tXml.simplify(out) : out;\n}\n\nexport { filter, getElementById, getElementsByClassName, parse, simplify, simplifyLostLess, stringify, toContentString };\n","export const fieldTagNames = {\n // TIFF Baseline\n 0x013B: 'Artist',\n 0x0102: 'BitsPerSample',\n 0x0109: 'CellLength',\n 0x0108: 'CellWidth',\n 0x0140: 'ColorMap',\n 0x0103: 'Compression',\n 0x8298: 'Copyright',\n 0x0132: 'DateTime',\n 0x0152: 'ExtraSamples',\n 0x010A: 'FillOrder',\n 0x0121: 'FreeByteCounts',\n 0x0120: 'FreeOffsets',\n 0x0123: 'GrayResponseCurve',\n 0x0122: 'GrayResponseUnit',\n 0x013C: 'HostComputer',\n 0x010E: 'ImageDescription',\n 0x0101: 'ImageLength',\n 0x0100: 'ImageWidth',\n 0x010F: 'Make',\n 0x0119: 'MaxSampleValue',\n 0x0118: 'MinSampleValue',\n 0x0110: 'Model',\n 0x00FE: 'NewSubfileType',\n 0x0112: 'Orientation',\n 0x0106: 'PhotometricInterpretation',\n 0x011C: 'PlanarConfiguration',\n 0x0128: 'ResolutionUnit',\n 0x0116: 'RowsPerStrip',\n 0x0115: 'SamplesPerPixel',\n 0x0131: 'Software',\n 0x0117: 'StripByteCounts',\n 0x0111: 'StripOffsets',\n 0x00FF: 'SubfileType',\n 0x0107: 'Threshholding',\n 0x011A: 'XResolution',\n 0x011B: 'YResolution',\n\n // TIFF Extended\n 0x0146: 'BadFaxLines',\n 0x0147: 'CleanFaxData',\n 0x0157: 'ClipPath',\n 0x0148: 'ConsecutiveBadFaxLines',\n 0x01B1: 'Decode',\n 0x01B2: 'DefaultImageColor',\n 0x010D: 'DocumentName',\n 0x0150: 'DotRange',\n 0x0141: 'HalftoneHints',\n 0x015A: 'Indexed',\n 0x015B: 'JPEGTables',\n 0x011D: 'PageName',\n 0x0129: 'PageNumber',\n 0x013D: 'Predictor',\n 0x013F: 'PrimaryChromaticities',\n 0x0214: 'ReferenceBlackWhite',\n 0x0153: 'SampleFormat',\n 0x0154: 'SMinSampleValue',\n 0x0155: 'SMaxSampleValue',\n 0x022F: 'StripRowCounts',\n 0x014A: 'SubIFDs',\n 0x0124: 'T4Options',\n 0x0125: 'T6Options',\n 0x0145: 'TileByteCounts',\n 0x0143: 'TileLength',\n 0x0144: 'TileOffsets',\n 0x0142: 'TileWidth',\n 0x012D: 'TransferFunction',\n 0x013E: 'WhitePoint',\n 0x0158: 'XClipPathUnits',\n 0x011E: 'XPosition',\n 0x0211: 'YCbCrCoefficients',\n 0x0213: 'YCbCrPositioning',\n 0x0212: 'YCbCrSubSampling',\n 0x0159: 'YClipPathUnits',\n 0x011F: 'YPosition',\n\n // EXIF\n 0x9202: 'ApertureValue',\n 0xA001: 'ColorSpace',\n 0x9004: 'DateTimeDigitized',\n 0x9003: 'DateTimeOriginal',\n 0x8769: 'Exif IFD',\n 0x9000: 'ExifVersion',\n 0x829A: 'ExposureTime',\n 0xA300: 'FileSource',\n 0x9209: 'Flash',\n 0xA000: 'FlashpixVersion',\n 0x829D: 'FNumber',\n 0xA420: 'ImageUniqueID',\n 0x9208: 'LightSource',\n 0x927C: 'MakerNote',\n 0x9201: 'ShutterSpeedValue',\n 0x9286: 'UserComment',\n\n // IPTC\n 0x83BB: 'IPTC',\n\n // ICC\n 0x8773: 'ICC Profile',\n\n // XMP\n 0x02BC: 'XMP',\n\n // GDAL\n 0xA480: 'GDAL_METADATA',\n 0xA481: 'GDAL_NODATA',\n\n // Photoshop\n 0x8649: 'Photoshop',\n\n // GeoTiff\n 0x830E: 'ModelPixelScale',\n 0x8482: 'ModelTiepoint',\n 0x85D8: 'ModelTransformation',\n 0x87AF: 'GeoKeyDirectory',\n 0x87B0: 'GeoDoubleParams',\n 0x87B1: 'GeoAsciiParams',\n\n // LERC\n 0xC5F2: 'LercParameters',\n};\n\nexport const fieldTags = {};\nfor (const key in fieldTagNames) {\n if (fieldTagNames.hasOwnProperty(key)) {\n fieldTags[fieldTagNames[key]] = parseInt(key, 10);\n }\n}\n\nexport const fieldTagTypes = {\n 256: 'SHORT',\n 257: 'SHORT',\n 258: 'SHORT',\n 259: 'SHORT',\n 262: 'SHORT',\n 273: 'LONG',\n 274: 'SHORT',\n 277: 'SHORT',\n 278: 'LONG',\n 279: 'LONG',\n 282: 'RATIONAL',\n 283: 'RATIONAL',\n 284: 'SHORT',\n 286: 'SHORT',\n 287: 'RATIONAL',\n 296: 'SHORT',\n 305: 'ASCII',\n 306: 'ASCII',\n 338: 'SHORT',\n 339: 'SHORT',\n 513: 'LONG',\n 514: 'LONG',\n 1024: 'SHORT',\n 1025: 'SHORT',\n 2048: 'SHORT',\n 2049: 'ASCII',\n 33550: 'DOUBLE',\n 33922: 'DOUBLE',\n 34665: 'LONG',\n 34735: 'SHORT',\n 34737: 'ASCII',\n 42113: 'ASCII',\n};\n\nexport const arrayFields = [\n fieldTags.BitsPerSample,\n fieldTags.ExtraSamples,\n fieldTags.SampleFormat,\n fieldTags.StripByteCounts,\n fieldTags.StripOffsets,\n fieldTags.StripRowCounts,\n fieldTags.TileByteCounts,\n fieldTags.TileOffsets,\n fieldTags.SubIFDs,\n];\n\nexport const fieldTypeNames = {\n 0x0001: 'BYTE',\n 0x0002: 'ASCII',\n 0x0003: 'SHORT',\n 0x0004: 'LONG',\n 0x0005: 'RATIONAL',\n 0x0006: 'SBYTE',\n 0x0007: 'UNDEFINED',\n 0x0008: 'SSHORT',\n 0x0009: 'SLONG',\n 0x000A: 'SRATIONAL',\n 0x000B: 'FLOAT',\n 0x000C: 'DOUBLE',\n // IFD offset, suggested by https://owl.phy.queensu.ca/~phil/exiftool/standards.html\n 0x000D: 'IFD',\n // introduced by BigTIFF\n 0x0010: 'LONG8',\n 0x0011: 'SLONG8',\n 0x0012: 'IFD8',\n};\n\nexport const fieldTypes = {};\nfor (const key in fieldTypeNames) {\n if (fieldTypeNames.hasOwnProperty(key)) {\n fieldTypes[fieldTypeNames[key]] = parseInt(key, 10);\n }\n}\n\nexport const photometricInterpretations = {\n WhiteIsZero: 0,\n BlackIsZero: 1,\n RGB: 2,\n Palette: 3,\n TransparencyMask: 4,\n CMYK: 5,\n YCbCr: 6,\n\n CIELab: 8,\n ICCLab: 9,\n};\n\nexport const ExtraSamplesValues = {\n Unspecified: 0,\n Assocalpha: 1,\n Unassalpha: 2,\n};\n\nexport const LercParameters = {\n Version: 0,\n AddCompression: 1,\n};\n\nexport const LercAddCompression = {\n None: 0,\n Deflate: 1,\n};\n\n\nexport const geoKeyNames = {\n 1024: 'GTModelTypeGeoKey',\n 1025: 'GTRasterTypeGeoKey',\n 1026: 'GTCitationGeoKey',\n 2048: 'GeographicTypeGeoKey',\n 2049: 'GeogCitationGeoKey',\n 2050: 'GeogGeodeticDatumGeoKey',\n 2051: 'GeogPrimeMeridianGeoKey',\n 2052: 'GeogLinearUnitsGeoKey',\n 2053: 'GeogLinearUnitSizeGeoKey',\n 2054: 'GeogAngularUnitsGeoKey',\n 2055: 'GeogAngularUnitSizeGeoKey',\n 2056: 'GeogEllipsoidGeoKey',\n 2057: 'GeogSemiMajorAxisGeoKey',\n 2058: 'GeogSemiMinorAxisGeoKey',\n 2059: 'GeogInvFlatteningGeoKey',\n 2060: 'GeogAzimuthUnitsGeoKey',\n 2061: 'GeogPrimeMeridianLongGeoKey',\n 2062: 'GeogTOWGS84GeoKey',\n 3072: 'ProjectedCSTypeGeoKey',\n 3073: 'PCSCitationGeoKey',\n 3074: 'ProjectionGeoKey',\n 3075: 'ProjCoordTransGeoKey',\n 3076: 'ProjLinearUnitsGeoKey',\n 3077: 'ProjLinearUnitSizeGeoKey',\n 3078: 'ProjStdParallel1GeoKey',\n 3079: 'ProjStdParallel2GeoKey',\n 3080: 'ProjNatOriginLongGeoKey',\n 3081: 'ProjNatOriginLatGeoKey',\n 3082: 'ProjFalseEastingGeoKey',\n 3083: 'ProjFalseNorthingGeoKey',\n 3084: 'ProjFalseOriginLongGeoKey',\n 3085: 'ProjFalseOriginLatGeoKey',\n 3086: 'ProjFalseOriginEastingGeoKey',\n 3087: 'ProjFalseOriginNorthingGeoKey',\n 3088: 'ProjCenterLongGeoKey',\n 3089: 'ProjCenterLatGeoKey',\n 3090: 'ProjCenterEastingGeoKey',\n 3091: 'ProjCenterNorthingGeoKey',\n 3092: 'ProjScaleAtNatOriginGeoKey',\n 3093: 'ProjScaleAtCenterGeoKey',\n 3094: 'ProjAzimuthAngleGeoKey',\n 3095: 'ProjStraightVertPoleLongGeoKey',\n 3096: 'ProjRectifiedGridAngleGeoKey',\n 4096: 'VerticalCSTypeGeoKey',\n 4097: 'VerticalCitationGeoKey',\n 4098: 'VerticalDatumGeoKey',\n 4099: 'VerticalUnitsGeoKey',\n};\n\nexport const geoKeys = {};\nfor (const key in geoKeyNames) {\n if (geoKeyNames.hasOwnProperty(key)) {\n geoKeys[geoKeyNames[key]] = parseInt(key, 10);\n }\n}\n","export function fromWhiteIsZero(raster, max) {\n const { width, height } = raster;\n const rgbRaster = new Uint8Array(width * height * 3);\n let value;\n for (let i = 0, j = 0; i < raster.length; ++i, j += 3) {\n value = 256 - (raster[i] / max * 256);\n rgbRaster[j] = value;\n rgbRaster[j + 1] = value;\n rgbRaster[j + 2] = value;\n }\n return rgbRaster;\n}\n\nexport function fromBlackIsZero(raster, max) {\n const { width, height } = raster;\n const rgbRaster = new Uint8Array(width * height * 3);\n let value;\n for (let i = 0, j = 0; i < raster.length; ++i, j += 3) {\n value = raster[i] / max * 256;\n rgbRaster[j] = value;\n rgbRaster[j + 1] = value;\n rgbRaster[j + 2] = value;\n }\n return rgbRaster;\n}\n\nexport function fromPalette(raster, colorMap) {\n const { width, height } = raster;\n const rgbRaster = new Uint8Array(width * height * 3);\n const greenOffset = colorMap.length / 3;\n const blueOffset = colorMap.length / 3 * 2;\n for (let i = 0, j = 0; i < raster.length; ++i, j += 3) {\n const mapIndex = raster[i];\n rgbRaster[j] = colorMap[mapIndex] / 65536 * 256;\n rgbRaster[j + 1] = colorMap[mapIndex + greenOffset] / 65536 * 256;\n rgbRaster[j + 2] = colorMap[mapIndex + blueOffset] / 65536 * 256;\n }\n return rgbRaster;\n}\n\nexport function fromCMYK(cmykRaster) {\n const { width, height } = cmykRaster;\n const rgbRaster = new Uint8Array(width * height * 3);\n for (let i = 0, j = 0; i < cmykRaster.length; i += 4, j += 3) {\n const c = cmykRaster[i];\n const m = cmykRaster[i + 1];\n const y = cmykRaster[i + 2];\n const k = cmykRaster[i + 3];\n\n rgbRaster[j] = 255 * ((255 - c) / 256) * ((255 - k) / 256);\n rgbRaster[j + 1] = 255 * ((255 - m) / 256) * ((255 - k) / 256);\n rgbRaster[j + 2] = 255 * ((255 - y) / 256) * ((255 - k) / 256);\n }\n return rgbRaster;\n}\n\nexport function fromYCbCr(yCbCrRaster) {\n const { width, height } = yCbCrRaster;\n const rgbRaster = new Uint8ClampedArray(width * height * 3);\n for (let i = 0, j = 0; i < yCbCrRaster.length; i += 3, j += 3) {\n const y = yCbCrRaster[i];\n const cb = yCbCrRaster[i + 1];\n const cr = yCbCrRaster[i + 2];\n\n rgbRaster[j] = (y + (1.40200 * (cr - 0x80)));\n rgbRaster[j + 1] = (y - (0.34414 * (cb - 0x80)) - (0.71414 * (cr - 0x80)));\n rgbRaster[j + 2] = (y + (1.77200 * (cb - 0x80)));\n }\n return rgbRaster;\n}\n\nconst Xn = 0.95047;\nconst Yn = 1.00000;\nconst Zn = 1.08883;\n\n// from https://github.com/antimatter15/rgb-lab/blob/master/color.js\n\nexport function fromCIELab(cieLabRaster) {\n const { width, height } = cieLabRaster;\n const rgbRaster = new Uint8Array(width * height * 3);\n\n for (let i = 0, j = 0; i < cieLabRaster.length; i += 3, j += 3) {\n const L = cieLabRaster[i + 0];\n const a_ = cieLabRaster[i + 1] << 24 >> 24; // conversion from uint8 to int8\n const b_ = cieLabRaster[i + 2] << 24 >> 24; // same\n\n let y = (L + 16) / 116;\n let x = (a_ / 500) + y;\n let z = y - (b_ / 200);\n let r;\n let g;\n let b;\n\n x = Xn * ((x * x * x > 0.008856) ? x * x * x : (x - (16 / 116)) / 7.787);\n y = Yn * ((y * y * y > 0.008856) ? y * y * y : (y - (16 / 116)) / 7.787);\n z = Zn * ((z * z * z > 0.008856) ? z * z * z : (z - (16 / 116)) / 7.787);\n\n r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);\n g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);\n b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);\n\n r = (r > 0.0031308) ? ((1.055 * (r ** (1 / 2.4))) - 0.055) : 12.92 * r;\n g = (g > 0.0031308) ? ((1.055 * (g ** (1 / 2.4))) - 0.055) : 12.92 * g;\n b = (b > 0.0031308) ? ((1.055 * (b ** (1 / 2.4))) - 0.055) : 12.92 * b;\n\n rgbRaster[j] = Math.max(0, Math.min(1, r)) * 255;\n rgbRaster[j + 1] = Math.max(0, Math.min(1, g)) * 255;\n rgbRaster[j + 2] = Math.max(0, Math.min(1, b)) * 255;\n }\n return rgbRaster;\n}\n","\nfunction decodeRowAcc(row, stride) {\n let length = row.length - stride;\n let offset = 0;\n do {\n for (let i = stride; i > 0; i--) {\n row[offset + stride] += row[offset];\n offset++;\n }\n\n length -= stride;\n } while (length > 0);\n}\n\nfunction decodeRowFloatingPoint(row, stride, bytesPerSample) {\n let index = 0;\n let count = row.length;\n const wc = count / bytesPerSample;\n\n while (count > stride) {\n for (let i = stride; i > 0; --i) {\n row[index + stride] += row[index];\n ++index;\n }\n count -= stride;\n }\n\n const copy = row.slice();\n for (let i = 0; i < wc; ++i) {\n for (let b = 0; b < bytesPerSample; ++b) {\n row[(bytesPerSample * i) + b] = copy[((bytesPerSample - b - 1) * wc) + i];\n }\n }\n}\n\nexport function applyPredictor(block, predictor, width, height, bitsPerSample,\n planarConfiguration) {\n if (!predictor || predictor === 1) {\n return block;\n }\n\n for (let i = 0; i < bitsPerSample.length; ++i) {\n if (bitsPerSample[i] % 8 !== 0) {\n throw new Error('When decoding with predictor, only multiple of 8 bits are supported.');\n }\n if (bitsPerSample[i] !== bitsPerSample[0]) {\n throw new Error('When decoding with predictor, all samples must have the same size.');\n }\n }\n\n const bytesPerSample = bitsPerSample[0] / 8;\n const stride = planarConfiguration === 2 ? 1 : bitsPerSample.length;\n\n for (let i = 0; i < height; ++i) {\n // Last strip will be truncated if height % stripHeight != 0\n if (i * stride * width * bytesPerSample >= block.byteLength) {\n break;\n }\n let row;\n if (predictor === 2) { // horizontal prediction\n switch (bitsPerSample[0]) {\n case 8:\n row = new Uint8Array(\n block, i * stride * width * bytesPerSample, stride * width * bytesPerSample,\n );\n break;\n case 16:\n row = new Uint16Array(\n block, i * stride * width * bytesPerSample, stride * width * bytesPerSample / 2,\n );\n break;\n case 32:\n row = new Uint32Array(\n block, i * stride * width * bytesPerSample, stride * width * bytesPerSample / 4,\n );\n break;\n default:\n throw new Error(`Predictor 2 not allowed with ${bitsPerSample[0]} bits per sample.`);\n }\n decodeRowAcc(row, stride, bytesPerSample);\n } else if (predictor === 3) { // horizontal floating point\n row = new Uint8Array(\n block, i * stride * width * bytesPerSample, stride * width * bytesPerSample,\n );\n decodeRowFloatingPoint(row, stride, bytesPerSample);\n }\n }\n return block;\n}\n","let A,I=null;function g(){return null!==I&&I.buffer===A.memory.buffer||(I=new Uint8Array(A.memory.buffer)),I}let B=0;let Q=null;function C(){return null!==Q&&Q.buffer===A.memory.buffer||(Q=new Int32Array(A.memory.buffer)),Q}async function E(I){void 0===I&&(I=\"\".replace(/\\.js$/,\"_bg.wasm\"));(\"string\"==typeof I||\"function\"==typeof Request&&I instanceof Request||\"function\"==typeof URL&&I instanceof URL)&&(I=fetch(I));const{instance:g,module:B}=await async function(A,I){if(\"function\"==typeof Response&&A instanceof Response){if(\"function\"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(A,I)}catch(I){if(\"application/wasm\"==A.headers.get(\"Content-Type\"))throw I;console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\",I)}const g=await A.arrayBuffer();return await WebAssembly.instantiate(g,I)}{const g=await WebAssembly.instantiate(A,I);return g instanceof WebAssembly.Instance?{instance:g,module:A}:g}}(await I,{});return A=g.exports,E.__wbindgen_wasm_module=B,A}var D=Object.freeze({__proto__:null,decompress:function(I,Q){try{const F=A.__wbindgen_add_to_stack_pointer(-16);var E=function(A,I){const Q=I(1*A.length);return g().set(A,Q/1),B=A.length,Q}(I,A.__wbindgen_malloc),D=B;A.decompress(F,E,D,Q);var i=C()[F/4+0],w=C()[F/4+1],G=(o=i,N=w,g().subarray(o/1,o/1+N)).slice();return A.__wbindgen_free(i,1*w),G}finally{A.__wbindgen_add_to_stack_pointer(16)}var o,N},default:E});const i=[62,0,0,0,63,52,53,54,55,56,57,58,59,60,61,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];function w(A){return i[A-43]}const G=function(A){let I,g=A.endsWith(\"==\")?2:A.endsWith(\"=\")?1:0,B=A.length,Q=new Uint8Array(B/4*3);for(let g=0,C=0;g>16,Q[C+1]=I>>8&255,Q[C+2]=255&I;return Q.subarray(0,Q.length-g)}(\"AGFzbQEAAAABWQ5gAn9/AX9gA39/fwF/YAJ/fwBgAX8AYAN/f38AYAF/AX9gBH9/f38AYAR/f39/AX9gBn9/f39/fwBgAX8BfmAAAGAFf39/f38AYAV/f39/fwF/YAJ+fwF/A21sBQgICwMBAgUMAQABAAIABQACAgYGDQYDAgACAAAEBAQCAgYGAAYBBgIHAwQDBAQDAwADBQMDBAQEBAQCAgAHAAQAAgMBAgcFBAIDAQUCAgIDAgIDAwcCAQAABAIACgAAAQAFAgADBQkJCQMCBAUBcAErKwUDAQARBgkBfwFBgIDAAAsHXwUGbWVtb3J5AgAKZGVjb21wcmVzcwAnH19fd2JpbmRnZW5fYWRkX3RvX3N0YWNrX3BvaW50ZXIAYhFfX3diaW5kZ2VuX21hbGxvYwBMD19fd2JpbmRnZW5fZnJlZQBWCTABAEEBCypqJDUCZmVDNQFmZUNha2pXDD1pVBohSVtTaGdfXDEOXlhqaQscQWAbP2QKsugBbNMqAgh/AX4CQAJAAkACQCAAQfUBTwRAIABBzf97Tw0CIABBC2oiAEF4cSEGQZCnwAAoAgAiCEUNAUEAIAZrIQQCQAJAAn9BACAAQQh2IgBFDQAaQR8gBkH///8HSw0AGiAGQQYgAGciAGtBH3F2QQFxIABBAXRrQT5qCyIHQQJ0QZypwABqKAIAIgAEQ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AIABBIGogBjYCACAAQRxqIAc2AgAgAEEYakEANgIAIABBFGogBDYCACAAQQk6AAogAEGAAjsBQiAAQYECOwFEIABBggI7AUAgAEH/AzsBCCABQTBqJAALxwICBX8BfiMAQRBrIgMkACAALQALIQIgA0IANwMIIAEoAgAhBQJAAkAgAAJ/IAEoAgQiBEHAACACayIGQfgBcUEDdiICSQRAIARBCU8NAiADQQhqIAUgBBBLGiABQQA2AgQgAUGIg8AANgIAIARBA3QMAQsgBkH/AXFByABPDQIgA0EIaiAFIAIQSxogASAEIAJrNgIEIAEgAiAFajYCACAGQfgBcQsgAC0ACyIBajoACyAAIAApAwAgAykDCCIHQjiGIAdCKIZCgICAgICAwP8Ag4QgB0IYhkKAgICAgOA/gyAHQgiGQoCAgIDwH4OEhCAHQgiIQoCAgPgPgyAHQhiIQoCA/AeDhCAHQiiIQoD+A4MgB0I4iISEhCABQT9xrYiENwMAIANBEGokAA8LIARBCEHYhcAAEDcACyACQQhByIXAABA3AAuqAgEDfyMAQYABayIEJAACQAJAAn8CQCABKAIAIgNBEHFFBEAgACgCACECIANBIHENASACrSABEBUMAgsgACgCACECQQAhAANAIAAgBGpB/wBqIAJBD3EiA0EwciADQdcAaiADQQpJGzoAACAAQX9qIQAgAkEEdiICDQALIABBgAFqIgJBgQFPDQIgAUGkjsAAQQIgACAEakGAAWpBACAAaxAIDAELQQAhAANAIAAgBGpB/wBqIAJBD3EiA0EwciADQTdqIANBCkkbOgAAIABBf2ohACACQQR2IgINAAsgAEGAAWoiAkGBAU8NAiABQaSOwABBAiAAIARqQYABakEAIABrEAgLIARBgAFqJAAPCyACQYABQZSOwAAQOQALIAJBgAFBlI7AABA5AAuxAgEEfyMAQUBqIgIkACABKAIEIgNFBEAgAUEEaiEDIAEoAgAhBCACQQA2AiAgAkIBNwMYIAIgAkEYajYCJCACQThqIARBEGopAgA3AwAgAkEwaiAEQQhqKQIANwMAIAIgBCkCADcDKCACQSRqQdiJwAAgAkEoahAJGiACQRBqIgQgAigC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2AgggAyACQQhqEAkNACAAQQRqIAEQGSACQSBqJAAPCyACQSBqJABBAQswAQF/AkACQEGAwABBAhBZIgENAQwAC0GAwABBAhBjAAsgACABNgIAIABBgCA2AgQLewECfwJAAkAgACgCBCIBBEAgACgCDCICIAFPDQEgACgCACIBIAJqIAEtAAA6AAAgAEEANgIIIAAgACgCDEEBajYCDCAAKAIERQ0CIAAoAgAtAAAPC0EAQQBBiIbAABA2AAsgAiABQZiGwAAQNgALQQBBAEGohsAAEDYAC2gBAn8gACAALQBGIgFBAWoiAjoACiAAQQEgAUEPcXRBAmoiATsBQCAAQX8gAkEPcXRBf3M7AQggAEEYaigCACABQf//A3EiAU8EQCAAIAE2AhgLIABBJGooAgAgAU8EQCAAIAE2AiQLC1ABAX8gAEEUaigCACIBRSABQQJ0RXJFBEAgACgCEBAECyAAQSBqKAIAIgFFIAFBAXRFckUEQCAAKAIcEAQLIABBLGooAgAEQCAAKAIoEAQLC2wBAX8jAEEwayIDJAAgAyABNgIEIAMgADYCACADQRxqQQI2AgAgA0EsakEcNgIAIANCAjcCDCADQYCNwAA2AgggA0EcNgIkIAMgA0EgajYCGCADIAM2AiggAyADQQRqNgIgIANBCGogAhBRAAtsAQF/IwBBMGsiAyQAIAMgATYCBCADIAA2AgAgA0EcakECNgIAIANBLGpBHDYCACADQgI3AgwgA0HMkcAANgIIIANBHDYCJCADIANBIGo2AhggAyADQQRqNgIoIAMgAzYCICADQQhqIAIQUQALbAEBfyMAQTBrIgMkACADIAE2AgQgAyAANgIAIANBHGpBAjYCACADQSxqQRw2AgAgA0ICNwIMIANBgJLAADYCCCADQRw2AiQgAyADQSBqNgIYIAMgA0EEajYCKCADIAM2AiAgA0EIaiACEFEAC2wBAX8jAEEwayIDJAAgAyABNgIEIAMgADYCACADQRxqQQI2AgAgA0EsakEcNgIAIANCAjcCDCADQayRwAA2AgggA0EcNgIkIAMgA0EgajYCGCADIANBBGo2AiggAyADNgIgIANBCGogAhBRAAtcAQF/IwBBEGsiAyQAAkAgACgCBCABayACTwRAIANBADYCAAwBCyADIAAgASACEBYgAygCAEEBRw0AIANBCGooAgAiAARAIAMoAgQgABBjAAsQXQALIANBEGokAAtaAQF/IwBBEGsiAiQAAkAgACgCBCABa0EBTwRAIAJBADYCAAwBCyACIAAgARAeIAIoAgBBAUcNACACQQhqKAIAIgAEQCACKAIEIAAQYwALEF0ACyACQRBqJAALWgEBfyMAQRBrIgIkAAJAIAAoAgQgAWtBAU8EQCACQQA2AgAMAQsgAiAAIAEQHSACKAIAQQFHDQAgAkEIaigCACIABEAgAigCBCAAEGMACxBdAAsgAkEQaiQAC1kBAX8jAEEgayICJAAgAiAAKAIANgIEIAJBGGogAUEQaikCADcDACACQRBqIAFBCGopAgA3AwAgAiABKQIANwMIIAJBBGpB2InAACACQQhqEAkgAkEgaiQAC0YAAkBBCCACSQRAAn9BCCACSQRAIAIgAxAQDAELIAMQAAsiAg0BQQAPCyAAIAMQCg8LIAIgACADIAEgASADSxsQSyAAEAQLWQEBfyMAQSBrIgIkACACIAAoAgA2AgQgAkEYaiABQRBqKQIANwMAIAJBEGogAUEIaikCADcDACACIAEpAgA3AwggAkEEakHwj8AAIAJBCGoQCSACQSBqJAALWQACQAJAAkAgAUF/SgRAAkAgAgRAIAENAQwECyABRQ0DIAFBARBZIgINBAwCCyABEEciAkUNAQwDCxBdAAsgAUEBEGMAC0EBIQILIAAgATYCBCAAIAI2AgALVgEBfyMAQSBrIgIkACACIAA2AgQgAkEYaiABQRBqKQIANwMAIAJBEGogAUEIaikCADcDACACIAEpAgA3AwggAkEEakHwj8AAIAJBCGoQCSACQSBqJAALWQEDfwJAIAEoAgwiAiABKAIIIgNPBEAgASgCBCIEIAJJDQEgASgCACEBIAAgAiADazYCBCAAIAEgA2o2AgAPCyADIAJB2IbAABA4AAsgAiAEQdiGwAAQNwALVQEBfyAAQRBqIAAtAEYQDSAAQQA6AEcgAEEAOwE4IABBMGpCADcDACAAQQA6AAsgAEIANwMAIAAgAC0ARkEBaiI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gECAQMBBQIHAgsCHAI5AgEBAgQIAQkBCgIdAUgBBAECAwEBCAFRAQIHDAhiAQIJCwZKAhsBAQEBATcOAQUBAgULASQJAWYEAQYBAgICGQIEAxAEDQECAgYBDwEAAwADHQMdAh4CQAIBBwgBAgsJAS0DdwIiAXYDBAIJAQYD2wICAToBAQcBAQEBAggGCgIBMBE/BDAHAQEFASgJDAIgBAICAQM4AQECAwEBAzoIAgKYAwENAQcEAQYBAwLGOgEFAAHDIQADjQFgIAAGaQIABAEKIAJQAgABAwEEARkCBQGXAhoSDQEmCBkLLgMwAQIEAgInAUMGAgICAgwBCAEvATMBAQMCAgUCAQEqAggB7gECAQQBAAEAEBAQAAIAAeIBlQUAAwECBQQoAwQBpQIABAACmQuwATYPOAMxBAICRQMkBQEIPgEMAjQJCgQCAV8DAgEBAgYBoAEDCBUCOQIBAQEBFgEOBwMFwwgCAwEBFwFRAQIGAQECAQECAQLrAQIEBgIBAhsCVQgCAQECagEBAQIGAQFlAwIEAQUACQEC9QEKAgEBBAGQBAICBAEgCigGAgQIAQkGAgMuDQECAAcBBgEBUhYCBwECAQJ6BgMBAQIBBwEBSAIDAQEBAAIABTsHAAE/BFEBAAIAAQEDBAUICAIHHgSUAwA3BDIIAQ4BFgUBDwAHARECBwECAQUABwAEAAdtBwBggPAATGF5b3V0RXJycHJpdmF0ZQB7CXByb2R1Y2VycwIIbGFuZ3VhZ2UBBFJ1c3QADHByb2Nlc3NlZC1ieQMFcnVzdGMdMS40OS4wIChlMTg4NGE4ZTMgMjAyMC0xMi0yOSkGd2FscnVzBjAuMTguMAx3YXNtLWJpbmRnZW4SMC4yLjcwIChiNjM1NWMyNzAp\");let o;async function N(A,I){o||(o=await(async()=>(await E(G),D))());const g=o.decompress(A,I);if(0===g.length)throw Error(\"Failed to decode with LZW decoder.\");return g}export{N as decompress};\n","import { applyPredictor } from '../predictor';\n\nexport default class BaseDecoder {\n async decode(fileDirectory, buffer) {\n const decoded = await this.decodeBlock(buffer);\n const predictor = fileDirectory.Predictor || 1;\n if (predictor !== 1) {\n const isTiled = !fileDirectory.StripOffsets;\n const tileWidth = isTiled ? fileDirectory.TileWidth : fileDirectory.ImageWidth;\n const tileHeight = isTiled ? fileDirectory.TileLength : (\n fileDirectory.RowsPerStrip || fileDirectory.ImageLength\n );\n return applyPredictor(\n decoded, predictor, tileWidth, tileHeight, fileDirectory.BitsPerSample,\n fileDirectory.PlanarConfiguration,\n );\n }\n return decoded;\n }\n}\n","import BaseDecoder from './basedecoder';\n\n\nexport default class RawDecoder extends BaseDecoder {\n decodeBlock(buffer) {\n return buffer;\n }\n}\n","import { decompress } from 'lzw-tiff-decoder';\n\nimport BaseDecoder from './basedecoder';\n\nexport default class LZWDecoder extends BaseDecoder {\n constructor(fileDirectory) {\n super();\n const width = fileDirectory.TileWidth || fileDirectory.ImageWidth;\n const height = fileDirectory.TileLength || fileDirectory.ImageLength;\n const nbytes = fileDirectory.BitsPerSample[0] / 8;\n this.maxUncompressedSize = width * height * nbytes;\n }\n\n async decodeBlock(buffer) {\n const bytes = new Uint8Array(buffer);\n const decoded = await decompress(bytes, this.maxUncompressedSize);\n return decoded.buffer;\n }\n}\n\n","import BaseDecoder from './basedecoder';\n\n/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /\n/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */\n/*\n Copyright 2011 notmasteryet\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// - The JPEG specification can be found in the ITU CCITT Recommendation T.81\n// (www.w3.org/Graphics/JPEG/itu-t81.pdf)\n// - The JFIF specification can be found in the JPEG File Interchange Format\n// (www.w3.org/Graphics/JPEG/jfif3.pdf)\n// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters\n// in PostScript Level 2, Technical Note #5116\n// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)\n\n\nconst dctZigZag = new Int32Array([\n 0,\n 1, 8,\n 16, 9, 2,\n 3, 10, 17, 24,\n 32, 25, 18, 11, 4,\n 5, 12, 19, 26, 33, 40,\n 48, 41, 34, 27, 20, 13, 6,\n 7, 14, 21, 28, 35, 42, 49, 56,\n 57, 50, 43, 36, 29, 22, 15,\n 23, 30, 37, 44, 51, 58,\n 59, 52, 45, 38, 31,\n 39, 46, 53, 60,\n 61, 54, 47,\n 55, 62,\n 63,\n]);\n\nconst dctCos1 = 4017; // cos(pi/16)\nconst dctSin1 = 799; // sin(pi/16)\nconst dctCos3 = 3406; // cos(3*pi/16)\nconst dctSin3 = 2276; // sin(3*pi/16)\nconst dctCos6 = 1567; // cos(6*pi/16)\nconst dctSin6 = 3784; // sin(6*pi/16)\nconst dctSqrt2 = 5793; // sqrt(2)\nconst dctSqrt1d2 = 2896;// sqrt(2) / 2\n\nfunction buildHuffmanTable(codeLengths, values) {\n let k = 0;\n const code = [];\n let length = 16;\n while (length > 0 && !codeLengths[length - 1]) {\n --length;\n }\n code.push({ children: [], index: 0 });\n\n let p = code[0];\n let q;\n for (let i = 0; i < length; i++) {\n for (let j = 0; j < codeLengths[i]; j++) {\n p = code.pop();\n p.children[p.index] = values[k];\n while (p.index > 0) {\n p = code.pop();\n }\n p.index++;\n code.push(p);\n while (code.length <= i) {\n code.push(q = { children: [], index: 0 });\n p.children[p.index] = q.children;\n p = q;\n }\n k++;\n }\n if (i + 1 < length) {\n // p here points to last code\n code.push(q = { children: [], index: 0 });\n p.children[p.index] = q.children;\n p = q;\n }\n }\n return code[0].children;\n}\n\nfunction decodeScan(data, initialOffset,\n frame, components, resetInterval,\n spectralStart, spectralEnd,\n successivePrev, successive) {\n const { mcusPerLine, progressive } = frame;\n\n const startOffset = initialOffset;\n let offset = initialOffset;\n let bitsData = 0;\n let bitsCount = 0;\n function readBit() {\n if (bitsCount > 0) {\n bitsCount--;\n return (bitsData >> bitsCount) & 1;\n }\n bitsData = data[offset++];\n if (bitsData === 0xFF) {\n const nextByte = data[offset++];\n if (nextByte) {\n throw new Error(`unexpected marker: ${((bitsData << 8) | nextByte).toString(16)}`);\n }\n // unstuff 0\n }\n bitsCount = 7;\n return bitsData >>> 7;\n }\n function decodeHuffman(tree) {\n let node = tree;\n let bit;\n while ((bit = readBit()) !== null) { // eslint-disable-line no-cond-assign\n node = node[bit];\n if (typeof node === 'number') {\n return node;\n }\n if (typeof node !== 'object') {\n throw new Error('invalid huffman sequence');\n }\n }\n return null;\n }\n function receive(initialLength) {\n let length = initialLength;\n let n = 0;\n while (length > 0) {\n const bit = readBit();\n if (bit === null) {\n return undefined;\n }\n n = (n << 1) | bit;\n --length;\n }\n return n;\n }\n function receiveAndExtend(length) {\n const n = receive(length);\n if (n >= 1 << (length - 1)) {\n return n;\n }\n return n + (-1 << length) + 1;\n }\n function decodeBaseline(component, zz) {\n const t = decodeHuffman(component.huffmanTableDC);\n const diff = t === 0 ? 0 : receiveAndExtend(t);\n component.pred += diff;\n zz[0] = component.pred;\n let k = 1;\n while (k < 64) {\n const rs = decodeHuffman(component.huffmanTableAC);\n const s = rs & 15;\n const r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n break;\n }\n k += 16;\n } else {\n k += r;\n const z = dctZigZag[k];\n zz[z] = receiveAndExtend(s);\n k++;\n }\n }\n }\n function decodeDCFirst(component, zz) {\n const t = decodeHuffman(component.huffmanTableDC);\n const diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);\n component.pred += diff;\n zz[0] = component.pred;\n }\n function decodeDCSuccessive(component, zz) {\n zz[0] |= readBit() << successive;\n }\n let eobrun = 0;\n function decodeACFirst(component, zz) {\n if (eobrun > 0) {\n eobrun--;\n return;\n }\n let k = spectralStart;\n const e = spectralEnd;\n while (k <= e) {\n const rs = decodeHuffman(component.huffmanTableAC);\n const s = rs & 15;\n const r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r) - 1;\n break;\n }\n k += 16;\n } else {\n k += r;\n const z = dctZigZag[k];\n zz[z] = receiveAndExtend(s) * (1 << successive);\n k++;\n }\n }\n }\n let successiveACState = 0;\n let successiveACNextValue;\n function decodeACSuccessive(component, zz) {\n let k = spectralStart;\n const e = spectralEnd;\n let r = 0;\n while (k <= e) {\n const z = dctZigZag[k];\n const direction = zz[z] < 0 ? -1 : 1;\n switch (successiveACState) {\n case 0: { // initial state\n const rs = decodeHuffman(component.huffmanTableAC);\n const s = rs & 15;\n r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r);\n successiveACState = 4;\n } else {\n r = 16;\n successiveACState = 1;\n }\n } else {\n if (s !== 1) {\n throw new Error('invalid ACn encoding');\n }\n successiveACNextValue = receiveAndExtend(s);\n successiveACState = r ? 2 : 3;\n }\n continue; // eslint-disable-line no-continue\n }\n case 1: // skipping r zero items\n case 2:\n if (zz[z]) {\n zz[z] += (readBit() << successive) * direction;\n } else {\n r--;\n if (r === 0) {\n successiveACState = successiveACState === 2 ? 3 : 0;\n }\n }\n break;\n case 3: // set value for a zero item\n if (zz[z]) {\n zz[z] += (readBit() << successive) * direction;\n } else {\n zz[z] = successiveACNextValue << successive;\n successiveACState = 0;\n }\n break;\n case 4: // eob\n if (zz[z]) {\n zz[z] += (readBit() << successive) * direction;\n }\n break;\n default:\n break;\n }\n k++;\n }\n if (successiveACState === 4) {\n eobrun--;\n if (eobrun === 0) {\n successiveACState = 0;\n }\n }\n }\n function decodeMcu(component, decodeFunction, mcu, row, col) {\n const mcuRow = (mcu / mcusPerLine) | 0;\n const mcuCol = mcu % mcusPerLine;\n const blockRow = (mcuRow * component.v) + row;\n const blockCol = (mcuCol * component.h) + col;\n decodeFunction(component, component.blocks[blockRow][blockCol]);\n }\n function decodeBlock(component, decodeFunction, mcu) {\n const blockRow = (mcu / component.blocksPerLine) | 0;\n const blockCol = mcu % component.blocksPerLine;\n decodeFunction(component, component.blocks[blockRow][blockCol]);\n }\n\n const componentsLength = components.length;\n let component;\n let i;\n let j;\n let k;\n let n;\n let decodeFn;\n if (progressive) {\n if (spectralStart === 0) {\n decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;\n } else {\n decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;\n }\n } else {\n decodeFn = decodeBaseline;\n }\n\n let mcu = 0;\n let marker;\n let mcuExpected;\n if (componentsLength === 1) {\n mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;\n } else {\n mcuExpected = mcusPerLine * frame.mcusPerColumn;\n }\n\n const usedResetInterval = resetInterval || mcuExpected;\n\n while (mcu < mcuExpected) {\n // reset interval stuff\n for (i = 0; i < componentsLength; i++) {\n components[i].pred = 0;\n }\n eobrun = 0;\n\n if (componentsLength === 1) {\n component = components[0];\n for (n = 0; n < usedResetInterval; n++) {\n decodeBlock(component, decodeFn, mcu);\n mcu++;\n }\n } else {\n for (n = 0; n < usedResetInterval; n++) {\n for (i = 0; i < componentsLength; i++) {\n component = components[i];\n const { h, v } = component;\n for (j = 0; j < v; j++) {\n for (k = 0; k < h; k++) {\n decodeMcu(component, decodeFn, mcu, j, k);\n }\n }\n }\n mcu++;\n\n // If we've reached our expected MCU's, stop decoding\n if (mcu === mcuExpected) {\n break;\n }\n }\n }\n\n // find marker\n bitsCount = 0;\n marker = (data[offset] << 8) | data[offset + 1];\n if (marker < 0xFF00) {\n throw new Error('marker was not found');\n }\n\n if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx\n offset += 2;\n } else {\n break;\n }\n }\n\n return offset - startOffset;\n}\n\nfunction buildComponentData(frame, component) {\n const lines = [];\n const { blocksPerLine, blocksPerColumn } = component;\n const samplesPerLine = blocksPerLine << 3;\n const R = new Int32Array(64);\n const r = new Uint8Array(64);\n\n // A port of poppler's IDCT method which in turn is taken from:\n // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,\n // \"Practical Fast 1-D DCT Algorithms with 11 Multiplications\",\n // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,\n // 988-991.\n function quantizeAndInverse(zz, dataOut, dataIn) {\n const qt = component.quantizationTable;\n let v0;\n let v1;\n let v2;\n let v3;\n let v4;\n let v5;\n let v6;\n let v7;\n let t;\n const p = dataIn;\n let i;\n\n // dequant\n for (i = 0; i < 64; i++) {\n p[i] = zz[i] * qt[i];\n }\n\n // inverse DCT on rows\n for (i = 0; i < 8; ++i) {\n const row = 8 * i;\n\n // check for all-zero AC coefficients\n if (p[1 + row] === 0 && p[2 + row] === 0 && p[3 + row] === 0\n && p[4 + row] === 0 && p[5 + row] === 0 && p[6 + row] === 0\n && p[7 + row] === 0) {\n t = ((dctSqrt2 * p[0 + row]) + 512) >> 10;\n p[0 + row] = t;\n p[1 + row] = t;\n p[2 + row] = t;\n p[3 + row] = t;\n p[4 + row] = t;\n p[5 + row] = t;\n p[6 + row] = t;\n p[7 + row] = t;\n continue; // eslint-disable-line no-continue\n }\n\n // stage 4\n v0 = ((dctSqrt2 * p[0 + row]) + 128) >> 8;\n v1 = ((dctSqrt2 * p[4 + row]) + 128) >> 8;\n v2 = p[2 + row];\n v3 = p[6 + row];\n v4 = ((dctSqrt1d2 * (p[1 + row] - p[7 + row])) + 128) >> 8;\n v7 = ((dctSqrt1d2 * (p[1 + row] + p[7 + row])) + 128) >> 8;\n v5 = p[3 + row] << 4;\n v6 = p[5 + row] << 4;\n\n // stage 3\n t = (v0 - v1 + 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = ((v2 * dctSin6) + (v3 * dctCos6) + 128) >> 8;\n v2 = ((v2 * dctCos6) - (v3 * dctSin6) + 128) >> 8;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = ((v4 * dctSin3) + (v7 * dctCos3) + 2048) >> 12;\n v4 = ((v4 * dctCos3) - (v7 * dctSin3) + 2048) >> 12;\n v7 = t;\n t = ((v5 * dctSin1) + (v6 * dctCos1) + 2048) >> 12;\n v5 = ((v5 * dctCos1) - (v6 * dctSin1) + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[0 + row] = v0 + v7;\n p[7 + row] = v0 - v7;\n p[1 + row] = v1 + v6;\n p[6 + row] = v1 - v6;\n p[2 + row] = v2 + v5;\n p[5 + row] = v2 - v5;\n p[3 + row] = v3 + v4;\n p[4 + row] = v3 - v4;\n }\n\n // inverse DCT on columns\n for (i = 0; i < 8; ++i) {\n const col = i;\n\n // check for all-zero AC coefficients\n if (p[(1 * 8) + col] === 0 && p[(2 * 8) + col] === 0 && p[(3 * 8) + col] === 0\n && p[(4 * 8) + col] === 0 && p[(5 * 8) + col] === 0 && p[(6 * 8) + col] === 0\n && p[(7 * 8) + col] === 0) {\n t = ((dctSqrt2 * dataIn[i + 0]) + 8192) >> 14;\n p[(0 * 8) + col] = t;\n p[(1 * 8) + col] = t;\n p[(2 * 8) + col] = t;\n p[(3 * 8) + col] = t;\n p[(4 * 8) + col] = t;\n p[(5 * 8) + col] = t;\n p[(6 * 8) + col] = t;\n p[(7 * 8) + col] = t;\n continue; // eslint-disable-line no-continue\n }\n\n // stage 4\n v0 = ((dctSqrt2 * p[(0 * 8) + col]) + 2048) >> 12;\n v1 = ((dctSqrt2 * p[(4 * 8) + col]) + 2048) >> 12;\n v2 = p[(2 * 8) + col];\n v3 = p[(6 * 8) + col];\n v4 = ((dctSqrt1d2 * (p[(1 * 8) + col] - p[(7 * 8) + col])) + 2048) >> 12;\n v7 = ((dctSqrt1d2 * (p[(1 * 8) + col] + p[(7 * 8) + col])) + 2048) >> 12;\n v5 = p[(3 * 8) + col];\n v6 = p[(5 * 8) + col];\n\n // stage 3\n t = (v0 - v1 + 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = ((v2 * dctSin6) + (v3 * dctCos6) + 2048) >> 12;\n v2 = ((v2 * dctCos6) - (v3 * dctSin6) + 2048) >> 12;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = ((v4 * dctSin3) + (v7 * dctCos3) + 2048) >> 12;\n v4 = ((v4 * dctCos3) - (v7 * dctSin3) + 2048) >> 12;\n v7 = t;\n t = ((v5 * dctSin1) + (v6 * dctCos1) + 2048) >> 12;\n v5 = ((v5 * dctCos1) - (v6 * dctSin1) + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[(0 * 8) + col] = v0 + v7;\n p[(7 * 8) + col] = v0 - v7;\n p[(1 * 8) + col] = v1 + v6;\n p[(6 * 8) + col] = v1 - v6;\n p[(2 * 8) + col] = v2 + v5;\n p[(5 * 8) + col] = v2 - v5;\n p[(3 * 8) + col] = v3 + v4;\n p[(4 * 8) + col] = v3 - v4;\n }\n\n // convert to 8-bit integers\n for (i = 0; i < 64; ++i) {\n const sample = 128 + ((p[i] + 8) >> 4);\n if (sample < 0) {\n dataOut[i] = 0;\n } else if (sample > 0XFF) {\n dataOut[i] = 0xFF;\n } else {\n dataOut[i] = sample;\n }\n }\n }\n\n for (let blockRow = 0; blockRow < blocksPerColumn; blockRow++) {\n const scanLine = blockRow << 3;\n for (let i = 0; i < 8; i++) {\n lines.push(new Uint8Array(samplesPerLine));\n }\n for (let blockCol = 0; blockCol < blocksPerLine; blockCol++) {\n quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);\n\n let offset = 0;\n const sample = blockCol << 3;\n for (let j = 0; j < 8; j++) {\n const line = lines[scanLine + j];\n for (let i = 0; i < 8; i++) {\n line[sample + i] = r[offset++];\n }\n }\n }\n }\n return lines;\n}\n\nclass JpegStreamReader {\n constructor() {\n this.jfif = null;\n this.adobe = null;\n\n this.quantizationTables = [];\n this.huffmanTablesAC = [];\n this.huffmanTablesDC = [];\n this.resetFrames();\n }\n\n resetFrames() {\n this.frames = [];\n }\n\n parse(data) {\n let offset = 0;\n // const { length } = data;\n function readUint16() {\n const value = (data[offset] << 8) | data[offset + 1];\n offset += 2;\n return value;\n }\n function readDataBlock() {\n const length = readUint16();\n const array = data.subarray(offset, offset + length - 2);\n offset += array.length;\n return array;\n }\n function prepareComponents(frame) {\n let maxH = 0;\n let maxV = 0;\n let component;\n let componentId;\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n if (maxH < component.h) {\n maxH = component.h;\n }\n if (maxV < component.v) {\n maxV = component.v;\n }\n }\n }\n const mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);\n const mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n const blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);\n const blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);\n const blocksPerLineForMcu = mcusPerLine * component.h;\n const blocksPerColumnForMcu = mcusPerColumn * component.v;\n const blocks = [];\n for (let i = 0; i < blocksPerColumnForMcu; i++) {\n const row = [];\n for (let j = 0; j < blocksPerLineForMcu; j++) {\n row.push(new Int32Array(64));\n }\n blocks.push(row);\n }\n component.blocksPerLine = blocksPerLine;\n component.blocksPerColumn = blocksPerColumn;\n component.blocks = blocks;\n }\n }\n frame.maxH = maxH;\n frame.maxV = maxV;\n frame.mcusPerLine = mcusPerLine;\n frame.mcusPerColumn = mcusPerColumn;\n }\n\n let fileMarker = readUint16();\n if (fileMarker !== 0xFFD8) { // SOI (Start of Image)\n throw new Error('SOI not found');\n }\n\n fileMarker = readUint16();\n while (fileMarker !== 0xFFD9) { // EOI (End of image)\n switch (fileMarker) {\n case 0xFF00: break;\n case 0xFFE0: // APP0 (Application Specific)\n case 0xFFE1: // APP1\n case 0xFFE2: // APP2\n case 0xFFE3: // APP3\n case 0xFFE4: // APP4\n case 0xFFE5: // APP5\n case 0xFFE6: // APP6\n case 0xFFE7: // APP7\n case 0xFFE8: // APP8\n case 0xFFE9: // APP9\n case 0xFFEA: // APP10\n case 0xFFEB: // APP11\n case 0xFFEC: // APP12\n case 0xFFED: // APP13\n case 0xFFEE: // APP14\n case 0xFFEF: // APP15\n case 0xFFFE: { // COM (Comment)\n const appData = readDataBlock();\n\n if (fileMarker === 0xFFE0) {\n if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49\n && appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\\x00'\n this.jfif = {\n version: { major: appData[5], minor: appData[6] },\n densityUnits: appData[7],\n xDensity: (appData[8] << 8) | appData[9],\n yDensity: (appData[10] << 8) | appData[11],\n thumbWidth: appData[12],\n thumbHeight: appData[13],\n thumbData: appData.subarray(14, 14 + (3 * appData[12] * appData[13])),\n };\n }\n }\n // TODO APP1 - Exif\n if (fileMarker === 0xFFEE) {\n if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F\n && appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\\x00'\n this.adobe = {\n version: appData[6],\n flags0: (appData[7] << 8) | appData[8],\n flags1: (appData[9] << 8) | appData[10],\n transformCode: appData[11],\n };\n }\n }\n break;\n }\n\n case 0xFFDB: { // DQT (Define Quantization Tables)\n const quantizationTablesLength = readUint16();\n const quantizationTablesEnd = quantizationTablesLength + offset - 2;\n while (offset < quantizationTablesEnd) {\n const quantizationTableSpec = data[offset++];\n const tableData = new Int32Array(64);\n if ((quantizationTableSpec >> 4) === 0) { // 8 bit values\n for (let j = 0; j < 64; j++) {\n const z = dctZigZag[j];\n tableData[z] = data[offset++];\n }\n } else if ((quantizationTableSpec >> 4) === 1) { // 16 bit\n for (let j = 0; j < 64; j++) {\n const z = dctZigZag[j];\n tableData[z] = readUint16();\n }\n } else {\n throw new Error('DQT: invalid table spec');\n }\n this.quantizationTables[quantizationTableSpec & 15] = tableData;\n }\n break;\n }\n\n case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)\n case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)\n case 0xFFC2: { // SOF2 (Start of Frame, Progressive DCT)\n readUint16(); // skip data length\n const frame = {\n extended: (fileMarker === 0xFFC1),\n progressive: (fileMarker === 0xFFC2),\n precision: data[offset++],\n scanLines: readUint16(),\n samplesPerLine: readUint16(),\n components: {},\n componentsOrder: [],\n };\n\n const componentsCount = data[offset++];\n let componentId;\n // let maxH = 0;\n // let maxV = 0;\n for (let i = 0; i < componentsCount; i++) {\n componentId = data[offset];\n const h = data[offset + 1] >> 4;\n const v = data[offset + 1] & 15;\n const qId = data[offset + 2];\n frame.componentsOrder.push(componentId);\n frame.components[componentId] = {\n h,\n v,\n quantizationIdx: qId,\n };\n offset += 3;\n }\n prepareComponents(frame);\n this.frames.push(frame);\n break;\n }\n\n case 0xFFC4: { // DHT (Define Huffman Tables)\n const huffmanLength = readUint16();\n for (let i = 2; i < huffmanLength;) {\n const huffmanTableSpec = data[offset++];\n const codeLengths = new Uint8Array(16);\n let codeLengthSum = 0;\n for (let j = 0; j < 16; j++, offset++) {\n codeLengths[j] = data[offset];\n codeLengthSum += codeLengths[j];\n }\n const huffmanValues = new Uint8Array(codeLengthSum);\n for (let j = 0; j < codeLengthSum; j++, offset++) {\n huffmanValues[j] = data[offset];\n }\n i += 17 + codeLengthSum;\n\n if ((huffmanTableSpec >> 4) === 0) {\n this.huffmanTablesDC[huffmanTableSpec & 15] = buildHuffmanTable(\n codeLengths, huffmanValues,\n );\n } else {\n this.huffmanTablesAC[huffmanTableSpec & 15] = buildHuffmanTable(\n codeLengths, huffmanValues,\n );\n }\n }\n break;\n }\n\n case 0xFFDD: // DRI (Define Restart Interval)\n readUint16(); // skip data length\n this.resetInterval = readUint16();\n break;\n\n case 0xFFDA: { // SOS (Start of Scan)\n readUint16(); // skip length\n const selectorsCount = data[offset++];\n const components = [];\n const frame = this.frames[0];\n for (let i = 0; i < selectorsCount; i++) {\n const component = frame.components[data[offset++]];\n const tableSpec = data[offset++];\n component.huffmanTableDC = this.huffmanTablesDC[tableSpec >> 4];\n component.huffmanTableAC = this.huffmanTablesAC[tableSpec & 15];\n components.push(component);\n }\n const spectralStart = data[offset++];\n const spectralEnd = data[offset++];\n const successiveApproximation = data[offset++];\n const processed = decodeScan(data, offset,\n frame, components, this.resetInterval,\n spectralStart, spectralEnd,\n successiveApproximation >> 4, successiveApproximation & 15);\n offset += processed;\n break;\n }\n\n case 0xFFFF: // Fill bytes\n if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.\n offset--;\n }\n break;\n\n default:\n if (data[offset - 3] === 0xFF\n && data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {\n // could be incorrect encoding -- last 0xFF byte of the previous\n // block was eaten by the encoder\n offset -= 3;\n break;\n }\n throw new Error(`unknown JPEG marker ${fileMarker.toString(16)}`);\n }\n fileMarker = readUint16();\n }\n }\n\n getResult() {\n const { frames } = this;\n if (this.frames.length === 0) {\n throw new Error('no frames were decoded');\n } else if (this.frames.length > 1) {\n console.warn('more than one frame is not supported');\n }\n\n // set each frame's components quantization table\n for (let i = 0; i < this.frames.length; i++) {\n const cp = this.frames[i].components;\n for (const j of Object.keys(cp)) {\n cp[j].quantizationTable = this.quantizationTables[cp[j].quantizationIdx];\n delete cp[j].quantizationIdx;\n }\n }\n\n const frame = frames[0];\n const { components, componentsOrder } = frame;\n const outComponents = [];\n const width = frame.samplesPerLine;\n const height = frame.scanLines;\n\n for (let i = 0; i < componentsOrder.length; i++) {\n const component = components[componentsOrder[i]];\n outComponents.push({\n lines: buildComponentData(frame, component),\n scaleX: component.h / frame.maxH,\n scaleY: component.v / frame.maxV,\n });\n }\n\n const out = new Uint8Array(width * height * outComponents.length);\n let oi = 0;\n for (let y = 0; y < height; ++y) {\n for (let x = 0; x < width; ++x) {\n for (let i = 0; i < outComponents.length; ++i) {\n const component = outComponents[i];\n out[oi] = component.lines[0 | y * component.scaleY][0 | x * component.scaleX];\n ++oi;\n }\n }\n }\n return out;\n }\n}\n\nexport default class JpegDecoder extends BaseDecoder {\n constructor(fileDirectory) {\n super();\n this.reader = new JpegStreamReader();\n if (fileDirectory.JPEGTables) {\n this.reader.parse(fileDirectory.JPEGTables);\n }\n }\n\n decodeBlock(buffer) {\n this.reader.resetFrames();\n this.reader.parse(new Uint8Array(buffer));\n return this.reader.getResult().buffer;\n }\n}\n","\n/*! pako 2.0.4 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED$1 = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN$1 = 2;\n\n/*============================================================================*/\n\n\nfunction zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES$1 = 30;\n/* number of distance codes */\n\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\n\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES$1 + 2) * 2);\nzero$1(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES$1 * 2);\nzero$1(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero$1(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);\nzero$1(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES$1);\nzero$1(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES$1);\nzero$1(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) =>\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) =>\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS$1; bits++) {\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES$1 - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES$1; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES$1 + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES$1; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nconst copy_block = (s, buf, len, header) =>\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n// while (len--) {\n// put_byte(s, *buf++);\n// }\n s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending);\n s.pending += len;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) =>\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let lx = 0; /* running index in l_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) =>\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE$1;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) =>\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let black_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS$1; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init$1 = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block$1 = (s, buf, stored_len, last) =>\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align$1 = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nconst _tr_flush_block$1 = (s, buf, stored_len, last) =>\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN$1) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block$1(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally$1 = (s, dist, lc) =>\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //let out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n\n//#ifdef TRUNCATE_BLOCK\n// /* Try to guess if it is profitable to stop the current block here */\n// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n// /* Compute an upper bound for the compressed length */\n// out_length = s.last_lit*8;\n// in_length = s.strstart - s.block_start;\n//\n// for (dcode = 0; dcode < D_CODES; dcode++) {\n// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n// }\n// out_length >>>= 3;\n// //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n// // s->last_lit, in_length, out_length,\n// // 100L - out_length*100L/in_length));\n// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n// return true;\n// }\n// }\n//#endif\n\n return (s.last_lit === s.lit_bufsize - 1);\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n};\n\nvar _tr_init_1 = _tr_init$1;\nvar _tr_stored_block_1 = _tr_stored_block$1;\nvar _tr_flush_block_1 = _tr_flush_block$1;\nvar _tr_tally_1 = _tr_tally$1;\nvar _tr_align_1 = _tr_align$1;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants$2 = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_UNKNOWN,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants$2;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42;\nconst EXTRA_STATE = 69;\nconst NAME_STATE = 73;\nconst COMMENT_STATE = 91;\nconst HCRC_STATE = 103;\nconst BUSY_STATE = 113;\nconst FINISH_STATE = 666;\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n let max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (;;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n// s.block_start >= s.w_size)) {\n// throw new Error(\"slide too late\");\n// }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n// if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n const max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n};\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED$2; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\nconst deflateResetKeep = (strm) => {\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH$2;\n _tr_init(s);\n return Z_OK$3;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK$3) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$2; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR$2; }\n strm.state.gzhead = head;\n return Z_OK$3;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR$2;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION$1) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);\n};\n\n\nconst deflate$2 = (strm, flush) => {\n\n let beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK$1 || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH$3)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);\n }\n\n s.strm = strm; /* just in case */\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n//#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n//#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK$3;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH$3) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {\n let bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK$3;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align(s);\n }\n else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH$1) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK$3;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH$3) { return Z_OK$3; }\n if (s.wrap <= 0) { return Z_STREAM_END$3; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR$2;\n }\n\n const status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR$2;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK$3;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2$1 = deflate$2;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1$2 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2$1,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {\n return new TextEncoder().encode(str);\n }\n\n let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n const len = max || buf.length;\n\n if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {\n return new TextDecoder().decode(buf.subarray(0, max));\n }\n\n let i, out;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate$1(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1$2.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1$2.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1$2.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1$2.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$2) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1$2.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$2;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$2) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate$1(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip$1(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_2 = deflate$1;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar constants$1 = constants$2;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD$1 = 30; /* got a data error -- remain here until reset */\nconst TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE$1;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n let base_index = 0;\n// let shoextra; /* extra bits table to use */\n let end; /* use base and extra for symbol > end */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n let extra_index = 0;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES$1 || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES$1) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS$1) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,\n Z_DEFLATED\n} = constants$2;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 1; /* i: waiting for magic header */\nconst FLAGS = 2; /* i: waiting for method and flags (gzip) */\nconst TIME = 3; /* i: waiting for modification time (gzip) */\nconst OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 5; /* i: waiting for extra length (gzip) */\nconst EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nconst NAME = 7; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 8; /* i: waiting for end of comment (gzip) */\nconst HCRC = 9; /* i: waiting for header crc (gzip) */\nconst DICTID = 10; /* i: waiting for dictionary check value */\nconst DICT = 11; /* waiting for inflateSetDictionary() call */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 14; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 17; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 18; /* i: waiting for code length code lengths */\nconst CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 20; /* i: same as LEN below, but only first time in */\nconst LEN = 21; /* i: waiting for length/lit/eob code */\nconst LENEXT = 22; /* i: waiting for length extra bits */\nconst DIST = 23; /* i: waiting for distance code */\nconst DISTEXT = 24; /* i: waiting for distance extra bits */\nconst MATCH = 25; /* o: waiting for output space to copy string */\nconst LIT = 26; /* o: waiting for output space to write literal */\nconst CHECK = 27; /* i: waiting for 32-bit check value */\nconst LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 29; /* finished check, done -- remain here until reset */\nconst BAD = 30; /* got a data error -- remain here until reset */\nconst MEM = 31; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateResetKeep = (strm) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$1;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$1) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate$2 = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$1;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT$1;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$1;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR$1;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH$1))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$1;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$1;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR$1;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$1;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2$1 = inflate$2;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\n*/\n\nvar inflate_1$2 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2$1,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate$1(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1$2.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1$2.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;\n\n // Convert data if needed\n if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1$2.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT && dictionary) {\n status = inflate_1$2.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK) {\n status = inflate_1$2.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR) {\n // Replace code with more verbose\n status = Z_NEED_DICT;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1$2.inflateReset(strm);\n status = inflate_1$2.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR:\n case Z_DATA_ERROR:\n case Z_NEED_DICT:\n case Z_MEM_ERROR:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END) {\n status = inflate_1$2.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err) {\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate$1(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1$1 = Inflate$1;\nvar inflate_2 = inflate$1;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip$1 = inflate$1;\nvar constants = constants$2;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1$1,\n\tinflate: inflate_2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip$1,\n\tconstants: constants\n};\n\nconst { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;\n\nconst { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;\n\n\n\nvar Deflate_1 = Deflate;\nvar deflate_1 = deflate;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar Inflate_1 = Inflate;\nvar inflate_1 = inflate;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip_1 = ungzip;\nvar constants_1 = constants$2;\n\nvar pako = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tInflate: Inflate_1,\n\tinflate: inflate_1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nexport { Deflate_1 as Deflate, Inflate_1 as Inflate, constants_1 as constants, pako as default, deflate_1 as deflate, deflateRaw_1 as deflateRaw, gzip_1 as gzip, inflate_1 as inflate, inflateRaw_1 as inflateRaw, ungzip_1 as ungzip };\n","import { inflate } from 'pako';\nimport BaseDecoder from './basedecoder';\n\nexport default class DeflateDecoder extends BaseDecoder {\n decodeBlock(buffer) {\n return inflate(new Uint8Array(buffer)).buffer;\n }\n}\n","import BaseDecoder from './basedecoder';\n\n\nexport default class PackbitsDecoder extends BaseDecoder {\n decodeBlock(buffer) {\n const dataView = new DataView(buffer);\n const out = [];\n\n for (let i = 0; i < buffer.byteLength; ++i) {\n let header = dataView.getInt8(i);\n if (header < 0) {\n const next = dataView.getUint8(i + 1);\n header = -header;\n for (let j = 0; j <= header; ++j) {\n out.push(next);\n }\n i += 1;\n } else {\n for (let j = 0; j <= header; ++j) {\n out.push(dataView.getUint8(i + j + 1));\n }\n i += header + 1;\n }\n }\n return new Uint8Array(out).buffer;\n }\n}\n","import { inflate } from 'pako';\nimport Lerc from 'lerc';\nimport BaseDecoder from './basedecoder';\nimport { LercParameters, LercAddCompression } from '../globals';\n\nexport default class LercDecoder extends BaseDecoder {\n constructor(fileDirectory) {\n super();\n\n this.planarConfiguration = typeof fileDirectory.PlanarConfiguration !== 'undefined' ? fileDirectory.PlanarConfiguration : 1;\n this.samplesPerPixel = typeof fileDirectory.SamplesPerPixel !== 'undefined' ? fileDirectory.SamplesPerPixel : 1;\n\n this.addCompression = fileDirectory.LercParameters[LercParameters.AddCompression];\n }\n\n interleavePixels(bandInterleavedData) {\n const pixelInterleavedData = new bandInterleavedData.constructor(bandInterleavedData.length);\n const lengthPerSample = bandInterleavedData.length / this.samplesPerPixel;\n for (let i = 0; i < lengthPerSample; i++) {\n for (let j = 0; j < this.samplesPerPixel; j++) {\n pixelInterleavedData[i * this.samplesPerPixel + j] = bandInterleavedData[i + j * lengthPerSample];\n }\n }\n return pixelInterleavedData;\n }\n\n decodeBlock(buffer) {\n switch (this.addCompression) {\n case LercAddCompression.None:\n break;\n case LercAddCompression.Deflate:\n buffer = inflate(new Uint8Array(buffer)).buffer;\n break;\n default:\n throw new Error(`Unsupported LERC additional compression method identifier: ${this.addCompression}`);\n }\n\n const lercResult = Lerc.decode(buffer);\n const lercData = lercResult.pixels[0]; // always band-interleaved\n const decodedData = this.planarConfiguration === 1 ? this.interleavePixels(lercData) : lercData; // transform to pixel-interleaved if expected\n return decodedData.buffer;\n }\n}\n","import RawDecoder from './raw';\nimport LZWDecoder from './lzw';\nimport JpegDecoder from './jpeg';\nimport DeflateDecoder from './deflate';\nimport PackbitsDecoder from './packbits';\nimport LercDecoder from './lerc';\n\nexport function getDecoder(fileDirectory) {\n switch (fileDirectory.Compression) {\n case undefined:\n case 1: // no compression\n return new RawDecoder();\n case 5: // LZW\n return new LZWDecoder(fileDirectory);\n case 6: // JPEG\n throw new Error('old style JPEG compression is not supported.');\n case 7: // JPEG\n return new JpegDecoder(fileDirectory);\n case 8: // Deflate as recognized by Adobe\n case 32946: // Deflate GDAL default\n return new DeflateDecoder();\n case 32773: // packbits\n return new PackbitsDecoder();\n case 34887: // LERC\n return new LercDecoder(fileDirectory);\n default:\n throw new Error(`Unknown compression method identifier: ${fileDirectory.Compression}`);\n }\n}\n","/**\n * @module resample\n */\n\nfunction copyNewSize(array, width, height, samplesPerPixel = 1) {\n return new (Object.getPrototypeOf(array).constructor)(width * height * samplesPerPixel);\n}\n\n/**\n * Resample the input arrays using nearest neighbor value selection.\n * @param {TypedArray[]} valueArrays The input arrays to resample\n * @param {number} inWidth The width of the input rasters\n * @param {number} inHeight The height of the input rasters\n * @param {number} outWidth The desired width of the output rasters\n * @param {number} outHeight The desired height of the output rasters\n * @returns {TypedArray[]} The resampled rasters\n */\nexport function resampleNearest(valueArrays, inWidth, inHeight, outWidth, outHeight) {\n const relX = inWidth / outWidth;\n const relY = inHeight / outHeight;\n return valueArrays.map((array) => {\n const newArray = copyNewSize(array, outWidth, outHeight);\n for (let y = 0; y < outHeight; ++y) {\n const cy = Math.min(Math.round(relY * y), inHeight - 1);\n for (let x = 0; x < outWidth; ++x) {\n const cx = Math.min(Math.round(relX * x), inWidth - 1);\n const value = array[(cy * inWidth) + cx];\n newArray[(y * outWidth) + x] = value;\n }\n }\n return newArray;\n });\n}\n\n// simple linear interpolation, code from:\n// https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support\nfunction lerp(v0, v1, t) {\n return ((1 - t) * v0) + (t * v1);\n}\n\n/**\n * Resample the input arrays using bilinear interpolation.\n * @param {TypedArray[]} valueArrays The input arrays to resample\n * @param {number} inWidth The width of the input rasters\n * @param {number} inHeight The height of the input rasters\n * @param {number} outWidth The desired width of the output rasters\n * @param {number} outHeight The desired height of the output rasters\n * @returns {TypedArray[]} The resampled rasters\n */\nexport function resampleBilinear(valueArrays, inWidth, inHeight, outWidth, outHeight) {\n const relX = inWidth / outWidth;\n const relY = inHeight / outHeight;\n\n return valueArrays.map((array) => {\n const newArray = copyNewSize(array, outWidth, outHeight);\n for (let y = 0; y < outHeight; ++y) {\n const rawY = relY * y;\n\n const yl = Math.floor(rawY);\n const yh = Math.min(Math.ceil(rawY), (inHeight - 1));\n\n for (let x = 0; x < outWidth; ++x) {\n const rawX = relX * x;\n const tx = rawX % 1;\n\n const xl = Math.floor(rawX);\n const xh = Math.min(Math.ceil(rawX), (inWidth - 1));\n\n const ll = array[(yl * inWidth) + xl];\n const hl = array[(yl * inWidth) + xh];\n const lh = array[(yh * inWidth) + xl];\n const hh = array[(yh * inWidth) + xh];\n\n const value = lerp(\n lerp(ll, hl, tx),\n lerp(lh, hh, tx),\n rawY % 1,\n );\n newArray[(y * outWidth) + x] = value;\n }\n }\n return newArray;\n });\n}\n\n/**\n * Resample the input arrays using the selected resampling method.\n * @param {TypedArray[]} valueArrays The input arrays to resample\n * @param {number} inWidth The width of the input rasters\n * @param {number} inHeight The height of the input rasters\n * @param {number} outWidth The desired width of the output rasters\n * @param {number} outHeight The desired height of the output rasters\n * @param {string} [method = 'nearest'] The desired resampling method\n * @returns {TypedArray[]} The resampled rasters\n */\nexport function resample(valueArrays, inWidth, inHeight, outWidth, outHeight, method = 'nearest') {\n switch (method.toLowerCase()) {\n case 'nearest':\n return resampleNearest(valueArrays, inWidth, inHeight, outWidth, outHeight);\n case 'bilinear':\n case 'linear':\n return resampleBilinear(valueArrays, inWidth, inHeight, outWidth, outHeight);\n default:\n throw new Error(`Unsupported resampling method: '${method}'`);\n }\n}\n\n/**\n * Resample the pixel interleaved input array using nearest neighbor value selection.\n * @param {TypedArray} valueArrays The input arrays to resample\n * @param {number} inWidth The width of the input rasters\n * @param {number} inHeight The height of the input rasters\n * @param {number} outWidth The desired width of the output rasters\n * @param {number} outHeight The desired height of the output rasters\n * @param {number} samples The number of samples per pixel for pixel\n * interleaved data\n * @returns {TypedArray} The resampled raster\n */\nexport function resampleNearestInterleaved(\n valueArray, inWidth, inHeight, outWidth, outHeight, samples) {\n const relX = inWidth / outWidth;\n const relY = inHeight / outHeight;\n\n const newArray = copyNewSize(valueArray, outWidth, outHeight, samples);\n for (let y = 0; y < outHeight; ++y) {\n const cy = Math.min(Math.round(relY * y), inHeight - 1);\n for (let x = 0; x < outWidth; ++x) {\n const cx = Math.min(Math.round(relX * x), inWidth - 1);\n for (let i = 0; i < samples; ++i) {\n const value = valueArray[(cy * inWidth * samples) + (cx * samples) + i];\n newArray[(y * outWidth * samples) + (x * samples) + i] = value;\n }\n }\n }\n return newArray;\n}\n\n/**\n * Resample the pixel interleaved input array using bilinear interpolation.\n * @param {TypedArray} valueArrays The input arrays to resample\n * @param {number} inWidth The width of the input rasters\n * @param {number} inHeight The height of the input rasters\n * @param {number} outWidth The desired width of the output rasters\n * @param {number} outHeight The desired height of the output rasters\n * @param {number} samples The number of samples per pixel for pixel\n * interleaved data\n * @returns {TypedArray} The resampled raster\n */\nexport function resampleBilinearInterleaved(\n valueArray, inWidth, inHeight, outWidth, outHeight, samples) {\n const relX = inWidth / outWidth;\n const relY = inHeight / outHeight;\n const newArray = copyNewSize(valueArray, outWidth, outHeight, samples);\n for (let y = 0; y < outHeight; ++y) {\n const rawY = relY * y;\n\n const yl = Math.floor(rawY);\n const yh = Math.min(Math.ceil(rawY), (inHeight - 1));\n\n for (let x = 0; x < outWidth; ++x) {\n const rawX = relX * x;\n const tx = rawX % 1;\n\n const xl = Math.floor(rawX);\n const xh = Math.min(Math.ceil(rawX), (inWidth - 1));\n\n for (let i = 0; i < samples; ++i) {\n const ll = valueArray[(yl * inWidth * samples) + (xl * samples) + i];\n const hl = valueArray[(yl * inWidth * samples) + (xh * samples) + i];\n const lh = valueArray[(yh * inWidth * samples) + (xl * samples) + i];\n const hh = valueArray[(yh * inWidth * samples) + (xh * samples) + i];\n\n const value = lerp(\n lerp(ll, hl, tx),\n lerp(lh, hh, tx),\n rawY % 1,\n );\n newArray[(y * outWidth * samples) + (x * samples) + i] = value;\n }\n }\n }\n return newArray;\n}\n\n/**\n * Resample the pixel interleaved input array using the selected resampling method.\n * @param {TypedArray} valueArray The input array to resample\n * @param {number} inWidth The width of the input rasters\n * @param {number} inHeight The height of the input rasters\n * @param {number} outWidth The desired width of the output rasters\n * @param {number} outHeight The desired height of the output rasters\n * @param {number} samples The number of samples per pixel for pixel\n * interleaved data\n * @param {string} [method = 'nearest'] The desired resampling method\n * @returns {TypedArray} The resampled rasters\n */\nexport function resampleInterleaved(valueArray, inWidth, inHeight, outWidth, outHeight, samples, method = 'nearest') {\n switch (method.toLowerCase()) {\n case 'nearest':\n return resampleNearestInterleaved(\n valueArray, inWidth, inHeight, outWidth, outHeight, samples,\n );\n case 'bilinear':\n case 'linear':\n return resampleBilinearInterleaved(\n valueArray, inWidth, inHeight, outWidth, outHeight, samples,\n );\n default:\n throw new Error(`Unsupported resampling method: '${method}'`);\n }\n}\n","/* eslint max-len: [\"error\", { \"code\": 120 }] */\n\nimport { getFloat16 } from '@petamoriken/float16';\nimport { parse } from 'txml/txml';\n\nimport { photometricInterpretations, ExtraSamplesValues } from './globals';\nimport { fromWhiteIsZero, fromBlackIsZero, fromPalette, fromCMYK, fromYCbCr, fromCIELab } from './rgb';\nimport { getDecoder } from './compression';\nimport { resample, resampleInterleaved } from './resample';\n\nfunction sum(array, start, end) {\n let s = 0;\n for (let i = start; i < end; ++i) {\n s += array[i];\n }\n return s;\n}\n\nfunction arrayForType(format, bitsPerSample, size) {\n switch (format) {\n case 1: // unsigned integer data\n if (bitsPerSample <= 8) {\n return new Uint8Array(size);\n } else if (bitsPerSample <= 16) {\n return new Uint16Array(size);\n } else if (bitsPerSample <= 32) {\n return new Uint32Array(size);\n }\n break;\n case 2: // twos complement signed integer data\n if (bitsPerSample === 8) {\n return new Int8Array(size);\n } else if (bitsPerSample === 16) {\n return new Int16Array(size);\n } else if (bitsPerSample === 32) {\n return new Int32Array(size);\n }\n break;\n case 3: // floating point data\n switch (bitsPerSample) {\n case 16:\n case 32:\n return new Float32Array(size);\n case 64:\n return new Float64Array(size);\n default:\n break;\n }\n break;\n default:\n break;\n }\n throw Error('Unsupported data format/bitsPerSample');\n}\n\nfunction needsNormalization(format, bitsPerSample) {\n if ((format === 1 || format === 2) && bitsPerSample <= 32 && bitsPerSample % 8 === 0) {\n return false;\n } else if (format === 3 && (bitsPerSample === 16 || bitsPerSample === 32 || bitsPerSample === 64)) {\n return false;\n }\n return true;\n}\n\nfunction normalizeArray(inBuffer, format, planarConfiguration, samplesPerPixel, bitsPerSample, tileWidth, tileHeight) {\n // const inByteArray = new Uint8Array(inBuffer);\n const view = new DataView(inBuffer);\n const outSize = planarConfiguration === 2\n ? tileHeight * tileWidth\n : tileHeight * tileWidth * samplesPerPixel;\n const samplesToTransfer = planarConfiguration === 2\n ? 1 : samplesPerPixel;\n const outArray = arrayForType(format, bitsPerSample, outSize);\n // let pixel = 0;\n\n const bitMask = parseInt('1'.repeat(bitsPerSample), 2);\n\n if (format === 1) { // unsigned integer\n // translation of https://github.com/OSGeo/gdal/blob/master/gdal/frmts/gtiff/geotiff.cpp#L7337\n let pixelBitSkip;\n // let sampleBitOffset = 0;\n if (planarConfiguration === 1) {\n pixelBitSkip = samplesPerPixel * bitsPerSample;\n // sampleBitOffset = (samplesPerPixel - 1) * bitsPerSample;\n } else {\n pixelBitSkip = bitsPerSample;\n }\n\n // Bits per line rounds up to next byte boundary.\n let bitsPerLine = tileWidth * pixelBitSkip;\n if ((bitsPerLine & 7) !== 0) {\n bitsPerLine = (bitsPerLine + 7) & (~7);\n }\n\n for (let y = 0; y < tileHeight; ++y) {\n const lineBitOffset = y * bitsPerLine;\n for (let x = 0; x < tileWidth; ++x) {\n const pixelBitOffset = lineBitOffset + (x * samplesToTransfer * bitsPerSample);\n for (let i = 0; i < samplesToTransfer; ++i) {\n const bitOffset = pixelBitOffset + (i * bitsPerSample);\n const outIndex = (((y * tileWidth) + x) * samplesToTransfer) + i;\n\n const byteOffset = Math.floor(bitOffset / 8);\n const innerBitOffset = bitOffset % 8;\n if (innerBitOffset + bitsPerSample <= 8) {\n outArray[outIndex] = (view.getUint8(byteOffset) >> (8 - bitsPerSample) - innerBitOffset) & bitMask;\n } else if (innerBitOffset + bitsPerSample <= 16) {\n outArray[outIndex] = (view.getUint16(byteOffset) >> (16 - bitsPerSample) - innerBitOffset) & bitMask;\n } else if (innerBitOffset + bitsPerSample <= 24) {\n const raw = (view.getUint16(byteOffset) << 8) | (view.getUint8(byteOffset + 2));\n outArray[outIndex] = (raw >> (24 - bitsPerSample) - innerBitOffset) & bitMask;\n } else {\n outArray[outIndex] = (view.getUint32(byteOffset) >> (32 - bitsPerSample) - innerBitOffset) & bitMask;\n }\n\n\n // let outWord = 0;\n // for (let bit = 0; bit < bitsPerSample; ++bit) {\n // if (inByteArray[bitOffset >> 3]\n // & (0x80 >> (bitOffset & 7))) {\n // outWord |= (1 << (bitsPerSample - 1 - bit));\n // }\n // ++bitOffset;\n // }\n\n // outArray[outIndex] = outWord;\n // outArray[pixel] = outWord;\n // pixel += 1;\n }\n // bitOffset = bitOffset + pixelBitSkip - bitsPerSample;\n }\n }\n } else if (format === 3) { // floating point\n // Float16 is handled elsewhere\n // normalize 16/24 bit floats to 32 bit floats in the array\n // console.time();\n // if (bitsPerSample === 16) {\n // for (let byte = 0, outIndex = 0; byte < inBuffer.byteLength; byte += 2, ++outIndex) {\n // outArray[outIndex] = getFloat16(view, byte);\n // }\n // }\n // console.timeEnd()\n }\n\n return outArray.buffer;\n}\n\n/**\n * GeoTIFF sub-file image.\n */\nclass GeoTIFFImage {\n /**\n * @constructor\n * @param {Object} fileDirectory The parsed file directory\n * @param {Object} geoKeys The parsed geo-keys\n * @param {DataView} dataView The DataView for the underlying file.\n * @param {Boolean} littleEndian Whether the file is encoded in little or big endian\n * @param {Boolean} cache Whether or not decoded tiles shall be cached\n * @param {Source} source The datasource to read from\n */\n constructor(fileDirectory, geoKeys, dataView, littleEndian, cache, source) {\n this.fileDirectory = fileDirectory;\n this.geoKeys = geoKeys;\n this.dataView = dataView;\n this.littleEndian = littleEndian;\n this.tiles = cache ? {} : null;\n this.isTiled = !fileDirectory.StripOffsets;\n const planarConfiguration = fileDirectory.PlanarConfiguration;\n this.planarConfiguration = (typeof planarConfiguration === 'undefined') ? 1 : planarConfiguration;\n if (this.planarConfiguration !== 1 && this.planarConfiguration !== 2) {\n throw new Error('Invalid planar configuration.');\n }\n\n this.source = source;\n }\n\n /**\n * Returns the associated parsed file directory.\n * @returns {Object} the parsed file directory\n */\n getFileDirectory() {\n return this.fileDirectory;\n }\n\n /**\n * Returns the associated parsed geo keys.\n * @returns {Object} the parsed geo keys\n */\n getGeoKeys() {\n return this.geoKeys;\n }\n\n /**\n * Returns the width of the image.\n * @returns {Number} the width of the image\n */\n getWidth() {\n return this.fileDirectory.ImageWidth;\n }\n\n /**\n * Returns the height of the image.\n * @returns {Number} the height of the image\n */\n getHeight() {\n return this.fileDirectory.ImageLength;\n }\n\n /**\n * Returns the number of samples per pixel.\n * @returns {Number} the number of samples per pixel\n */\n getSamplesPerPixel() {\n return typeof this.fileDirectory.SamplesPerPixel !== 'undefined'\n ? this.fileDirectory.SamplesPerPixel : 1;\n }\n\n /**\n * Returns the width of each tile.\n * @returns {Number} the width of each tile\n */\n getTileWidth() {\n return this.isTiled ? this.fileDirectory.TileWidth : this.getWidth();\n }\n\n /**\n * Returns the height of each tile.\n * @returns {Number} the height of each tile\n */\n getTileHeight() {\n if (this.isTiled) {\n return this.fileDirectory.TileLength;\n }\n if (typeof this.fileDirectory.RowsPerStrip !== 'undefined') {\n return Math.min(this.fileDirectory.RowsPerStrip, this.getHeight());\n }\n return this.getHeight();\n }\n\n getBlockWidth() {\n return this.getTileWidth();\n }\n\n getBlockHeight(y) {\n if (this.isTiled || (y + 1) * this.getTileHeight() <= this.getHeight()) {\n return this.getTileHeight();\n } else {\n return this.getHeight() - (y * this.getTileHeight());\n }\n }\n\n /**\n * Calculates the number of bytes for each pixel across all samples. Only full\n * bytes are supported, an exception is thrown when this is not the case.\n * @returns {Number} the bytes per pixel\n */\n getBytesPerPixel() {\n let bytes = 0;\n for (let i = 0; i < this.fileDirectory.BitsPerSample.length; ++i) {\n bytes += this.getSampleByteSize(i);\n }\n return bytes;\n }\n\n getSampleByteSize(i) {\n if (i >= this.fileDirectory.BitsPerSample.length) {\n throw new RangeError(`Sample index ${i} is out of range.`);\n }\n return Math.ceil(this.fileDirectory.BitsPerSample[i] / 8);\n }\n\n getReaderForSample(sampleIndex) {\n const format = this.fileDirectory.SampleFormat\n ? this.fileDirectory.SampleFormat[sampleIndex] : 1;\n const bitsPerSample = this.fileDirectory.BitsPerSample[sampleIndex];\n switch (format) {\n case 1: // unsigned integer data\n if (bitsPerSample <= 8) {\n return DataView.prototype.getUint8;\n } else if (bitsPerSample <= 16) {\n return DataView.prototype.getUint16;\n } else if (bitsPerSample <= 32) {\n return DataView.prototype.getUint32;\n }\n break;\n case 2: // twos complement signed integer data\n if (bitsPerSample <= 8) {\n return DataView.prototype.getInt8;\n } else if (bitsPerSample <= 16) {\n return DataView.prototype.getInt16;\n } else if (bitsPerSample <= 32) {\n return DataView.prototype.getInt32;\n }\n break;\n case 3:\n switch (bitsPerSample) {\n case 16:\n return function (offset, littleEndian) {\n return getFloat16(this, offset, littleEndian);\n };\n case 32:\n return DataView.prototype.getFloat32;\n case 64:\n return DataView.prototype.getFloat64;\n default:\n break;\n }\n break;\n default:\n break;\n }\n throw Error('Unsupported data format/bitsPerSample');\n }\n\n getSampleFormat(sampleIndex = 0) {\n return this.fileDirectory.SampleFormat\n ? this.fileDirectory.SampleFormat[sampleIndex] : 1;\n }\n\n getBitsPerSample(sampleIndex = 0) {\n return this.fileDirectory.BitsPerSample[sampleIndex];\n }\n\n getArrayForSample(sampleIndex, size) {\n const format = this.getSampleFormat(sampleIndex);\n const bitsPerSample = this.getBitsPerSample(sampleIndex);\n return arrayForType(format, bitsPerSample, size);\n }\n\n /**\n * Returns the decoded strip or tile.\n * @param {Number} x the strip or tile x-offset\n * @param {Number} y the tile y-offset (0 for stripped images)\n * @param {Number} sample the sample to get for separated samples\n * @param {Pool|AbstractDecoder} poolOrDecoder the decoder or decoder pool\n * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @returns {Promise.}\n */\n async getTileOrStrip(x, y, sample, poolOrDecoder, signal) {\n const numTilesPerRow = Math.ceil(this.getWidth() / this.getTileWidth());\n const numTilesPerCol = Math.ceil(this.getHeight() / this.getTileHeight());\n let index;\n const { tiles } = this;\n if (this.planarConfiguration === 1) {\n index = (y * numTilesPerRow) + x;\n } else if (this.planarConfiguration === 2) {\n index = (sample * numTilesPerRow * numTilesPerCol) + (y * numTilesPerRow) + x;\n }\n\n let offset;\n let byteCount;\n if (this.isTiled) {\n offset = this.fileDirectory.TileOffsets[index];\n byteCount = this.fileDirectory.TileByteCounts[index];\n } else {\n offset = this.fileDirectory.StripOffsets[index];\n byteCount = this.fileDirectory.StripByteCounts[index];\n }\n const slice = (await this.source.fetch([{ offset, length: byteCount }], signal))[0];\n\n let request;\n if (tiles === null || !tiles[index]) {\n // resolve each request by potentially applying array normalization\n request = (async () => {\n let data = await poolOrDecoder.decode(this.fileDirectory, slice);\n const sampleFormat = this.getSampleFormat();\n const bitsPerSample = this.getBitsPerSample();\n if (needsNormalization(sampleFormat, bitsPerSample)) {\n data = normalizeArray(\n data,\n sampleFormat,\n this.planarConfiguration,\n this.getSamplesPerPixel(),\n bitsPerSample,\n this.getTileWidth(),\n this.getBlockHeight(y),\n );\n }\n return data;\n })();\n\n // set the cache\n if (tiles !== null) {\n tiles[index] = request;\n }\n } else {\n // get from the cache\n request = tiles[index];\n }\n\n // cache the tile request\n return { x, y, sample, data: await request };\n }\n\n /**\n * Internal read function.\n * @private\n * @param {Array} imageWindow The image window in pixel coordinates\n * @param {Array} samples The selected samples (0-based indices)\n * @param {TypedArray[]|TypedArray} valueArrays The array(s) to write into\n * @param {Boolean} interleave Whether or not to write in an interleaved manner\n * @param {Pool|AbstractDecoder} poolOrDecoder the decoder or decoder pool\n * @param {number} width the width of window to be read into\n * @param {number} height the height of window to be read into\n * @param {number} resampleMethod the resampling method to be used when interpolating\n * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @returns {Promise|Promise}\n */\n async _readRaster(imageWindow, samples, valueArrays, interleave, poolOrDecoder, width, height, resampleMethod, signal) {\n const tileWidth = this.getTileWidth();\n const tileHeight = this.getTileHeight();\n\n const minXTile = Math.max(Math.floor(imageWindow[0] / tileWidth), 0);\n const maxXTile = Math.min(\n Math.ceil(imageWindow[2] / tileWidth),\n Math.ceil(this.getWidth() / this.getTileWidth()),\n );\n const minYTile = Math.max(Math.floor(imageWindow[1] / tileHeight), 0);\n const maxYTile = Math.min(\n Math.ceil(imageWindow[3] / tileHeight),\n Math.ceil(this.getHeight() / this.getTileHeight()),\n );\n const windowWidth = imageWindow[2] - imageWindow[0];\n\n let bytesPerPixel = this.getBytesPerPixel();\n\n const srcSampleOffsets = [];\n const sampleReaders = [];\n for (let i = 0; i < samples.length; ++i) {\n if (this.planarConfiguration === 1) {\n srcSampleOffsets.push(sum(this.fileDirectory.BitsPerSample, 0, samples[i]) / 8);\n } else {\n srcSampleOffsets.push(0);\n }\n sampleReaders.push(this.getReaderForSample(samples[i]));\n }\n\n const promises = [];\n const { littleEndian } = this;\n\n for (let yTile = minYTile; yTile < maxYTile; ++yTile) {\n for (let xTile = minXTile; xTile < maxXTile; ++xTile) {\n for (let sampleIndex = 0; sampleIndex < samples.length; ++sampleIndex) {\n const si = sampleIndex;\n const sample = samples[sampleIndex];\n if (this.planarConfiguration === 2) {\n bytesPerPixel = this.getSampleByteSize(sampleIndex);\n }\n const promise = this.getTileOrStrip(xTile, yTile, sample, poolOrDecoder, signal).then((tile) => {\n const buffer = tile.data;\n const dataView = new DataView(buffer);\n const blockHeight = this.getBlockHeight(tile.y);\n const firstLine = tile.y * tileHeight;\n const firstCol = tile.x * tileWidth;\n const lastLine = firstLine + blockHeight;\n const lastCol = (tile.x + 1) * tileWidth;\n const reader = sampleReaders[si];\n\n const ymax = Math.min(blockHeight, blockHeight - (lastLine - imageWindow[3]));\n const xmax = Math.min(tileWidth, tileWidth - (lastCol - imageWindow[2]));\n\n for (let y = Math.max(0, imageWindow[1] - firstLine); y < ymax; ++y) {\n for (let x = Math.max(0, imageWindow[0] - firstCol); x < xmax; ++x) {\n const pixelOffset = ((y * tileWidth) + x) * bytesPerPixel;\n const value = reader.call(\n dataView, pixelOffset + srcSampleOffsets[si], littleEndian,\n );\n let windowCoordinate;\n if (interleave) {\n windowCoordinate = ((y + firstLine - imageWindow[1]) * windowWidth * samples.length)\n + ((x + firstCol - imageWindow[0]) * samples.length)\n + si;\n valueArrays[windowCoordinate] = value;\n } else {\n windowCoordinate = (\n (y + firstLine - imageWindow[1]) * windowWidth\n ) + x + firstCol - imageWindow[0];\n valueArrays[si][windowCoordinate] = value;\n }\n }\n }\n });\n promises.push(promise);\n }\n }\n }\n await Promise.all(promises);\n\n if ((width && (imageWindow[2] - imageWindow[0]) !== width)\n || (height && (imageWindow[3] - imageWindow[1]) !== height)) {\n let resampled;\n if (interleave) {\n resampled = resampleInterleaved(\n valueArrays,\n imageWindow[2] - imageWindow[0],\n imageWindow[3] - imageWindow[1],\n width, height,\n samples.length,\n resampleMethod,\n );\n } else {\n resampled = resample(\n valueArrays,\n imageWindow[2] - imageWindow[0],\n imageWindow[3] - imageWindow[1],\n width, height,\n resampleMethod,\n );\n }\n resampled.width = width;\n resampled.height = height;\n return resampled;\n }\n\n valueArrays.width = width || imageWindow[2] - imageWindow[0];\n valueArrays.height = height || imageWindow[3] - imageWindow[1];\n\n return valueArrays;\n }\n\n /**\n * Reads raster data from the image. This function reads all selected samples\n * into separate arrays of the correct type for that sample or into a single\n * combined array when `interleave` is set. When provided, only a subset\n * of the raster is read for each sample.\n *\n * @param {Object} [options={}] optional parameters\n * @param {Array} [options.window=whole image] the subset to read data from.\n * @param {Array} [options.samples=all samples] the selection of samples to read from.\n * @param {Boolean} [options.interleave=false] whether the data shall be read\n * in one single array or separate\n * arrays.\n * @param {Number} [options.pool=null] The optional decoder pool to use.\n * @param {number} [options.width] The desired width of the output. When the width is\n * not the same as the images, resampling will be\n * performed.\n * @param {number} [options.height] The desired height of the output. When the width\n * is not the same as the images, resampling will\n * be performed.\n * @param {string} [options.resampleMethod='nearest'] The desired resampling method.\n * @param {number|number[]} [options.fillValue] The value to use for parts of the image\n * outside of the images extent. When\n * multiple samples are requested, an\n * array of fill values can be passed.\n * @param {AbortSignal} [options.signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @returns {Promise.<(TypedArray|TypedArray[])>} the decoded arrays as a promise\n */\n async readRasters({\n window: wnd, samples = [], interleave, pool = null,\n width, height, resampleMethod, fillValue, signal,\n } = {}) {\n const imageWindow = wnd || [0, 0, this.getWidth(), this.getHeight()];\n\n // check parameters\n if (imageWindow[0] > imageWindow[2] || imageWindow[1] > imageWindow[3]) {\n throw new Error('Invalid subsets');\n }\n\n const imageWindowWidth = imageWindow[2] - imageWindow[0];\n const imageWindowHeight = imageWindow[3] - imageWindow[1];\n const numPixels = imageWindowWidth * imageWindowHeight;\n const samplesPerPixel = this.getSamplesPerPixel();\n\n if (!samples || !samples.length) {\n for (let i = 0; i < samplesPerPixel; ++i) {\n samples.push(i);\n }\n } else {\n for (let i = 0; i < samples.length; ++i) {\n if (samples[i] >= samplesPerPixel) {\n return Promise.reject(new RangeError(`Invalid sample index '${samples[i]}'.`));\n }\n }\n }\n let valueArrays;\n if (interleave) {\n const format = this.fileDirectory.SampleFormat\n ? Math.max.apply(null, this.fileDirectory.SampleFormat) : 1;\n const bitsPerSample = Math.max.apply(null, this.fileDirectory.BitsPerSample);\n valueArrays = arrayForType(format, bitsPerSample, numPixels * samples.length);\n if (fillValue) {\n valueArrays.fill(fillValue);\n }\n } else {\n valueArrays = [];\n for (let i = 0; i < samples.length; ++i) {\n const valueArray = this.getArrayForSample(samples[i], numPixels);\n if (Array.isArray(fillValue) && i < fillValue.length) {\n valueArray.fill(fillValue[i]);\n } else if (fillValue && !Array.isArray(fillValue)) {\n valueArray.fill(fillValue);\n }\n valueArrays.push(valueArray);\n }\n }\n\n const poolOrDecoder = pool || getDecoder(this.fileDirectory);\n\n const result = await this._readRaster(\n imageWindow, samples, valueArrays, interleave, poolOrDecoder, width, height, resampleMethod, signal,\n );\n return result;\n }\n\n /**\n * Reads raster data from the image as RGB. The result is always an\n * interleaved typed array.\n * Colorspaces other than RGB will be transformed to RGB, color maps expanded.\n * When no other method is applicable, the first sample is used to produce a\n * greayscale image.\n * When provided, only a subset of the raster is read for each sample.\n *\n * @param {Object} [options] optional parameters\n * @param {Array} [options.window=whole image] the subset to read data from.\n * @param {Number} [options.pool=null] The optional decoder pool to use.\n * @param {number} [options.width] The desired width of the output. When the width is no the\n * same as the images, resampling will be performed.\n * @param {number} [options.height] The desired height of the output. When the width is no the\n * same as the images, resampling will be performed.\n * @param {string} [options.resampleMethod='nearest'] The desired resampling method.\n * @param {bool} [options.enableAlpha=false] Enable reading alpha channel if present.\n * @param {AbortSignal} [options.signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @returns {Promise.} the RGB array as a Promise\n */\n async readRGB({ window, pool = null, width, height, resampleMethod, enableAlpha = false, signal } = {}) {\n const imageWindow = window || [0, 0, this.getWidth(), this.getHeight()];\n\n // check parameters\n if (imageWindow[0] > imageWindow[2] || imageWindow[1] > imageWindow[3]) {\n throw new Error('Invalid subsets');\n }\n\n const pi = this.fileDirectory.PhotometricInterpretation;\n\n if (pi === photometricInterpretations.RGB) {\n let s = [0, 1, 2];\n if ((!(this.fileDirectory.ExtraSamples === ExtraSamplesValues.Unspecified)) && enableAlpha) {\n s = [];\n for (let i = 0; i < this.fileDirectory.BitsPerSample.length; i += 1) {\n s.push(i);\n }\n }\n return this.readRasters({\n window,\n interleave: true,\n samples: s,\n pool,\n width,\n height,\n resampleMethod,\n signal,\n });\n }\n\n let samples;\n switch (pi) {\n case photometricInterpretations.WhiteIsZero:\n case photometricInterpretations.BlackIsZero:\n case photometricInterpretations.Palette:\n samples = [0];\n break;\n case photometricInterpretations.CMYK:\n samples = [0, 1, 2, 3];\n break;\n case photometricInterpretations.YCbCr:\n case photometricInterpretations.CIELab:\n samples = [0, 1, 2];\n break;\n default:\n throw new Error('Invalid or unsupported photometric interpretation.');\n }\n\n const subOptions = {\n window: imageWindow,\n interleave: true,\n samples,\n pool,\n width,\n height,\n resampleMethod,\n signal,\n };\n const { fileDirectory } = this;\n const raster = await this.readRasters(subOptions);\n\n const max = 2 ** this.fileDirectory.BitsPerSample[0];\n let data;\n switch (pi) {\n case photometricInterpretations.WhiteIsZero:\n data = fromWhiteIsZero(raster, max);\n break;\n case photometricInterpretations.BlackIsZero:\n data = fromBlackIsZero(raster, max);\n break;\n case photometricInterpretations.Palette:\n data = fromPalette(raster, fileDirectory.ColorMap);\n break;\n case photometricInterpretations.CMYK:\n data = fromCMYK(raster);\n break;\n case photometricInterpretations.YCbCr:\n data = fromYCbCr(raster);\n break;\n case photometricInterpretations.CIELab:\n data = fromCIELab(raster);\n break;\n default:\n throw new Error('Unsupported photometric interpretation.');\n }\n data.width = raster.width;\n data.height = raster.height;\n return data;\n }\n\n /**\n * Returns an array of tiepoints.\n * @returns {Object[]}\n */\n getTiePoints() {\n if (!this.fileDirectory.ModelTiepoint) {\n return [];\n }\n\n const tiePoints = [];\n for (let i = 0; i < this.fileDirectory.ModelTiepoint.length; i += 6) {\n tiePoints.push({\n i: this.fileDirectory.ModelTiepoint[i],\n j: this.fileDirectory.ModelTiepoint[i + 1],\n k: this.fileDirectory.ModelTiepoint[i + 2],\n x: this.fileDirectory.ModelTiepoint[i + 3],\n y: this.fileDirectory.ModelTiepoint[i + 4],\n z: this.fileDirectory.ModelTiepoint[i + 5],\n });\n }\n return tiePoints;\n }\n\n /**\n * Returns the parsed GDAL metadata items.\n *\n * If sample is passed to null, dataset-level metadata will be returned.\n * Otherwise only metadata specific to the provided sample will be returned.\n *\n * @param {Number} [sample=null] The sample index.\n * @returns {Object}\n */\n getGDALMetadata(sample = null) {\n const metadata = {};\n if (!this.fileDirectory.GDAL_METADATA) {\n return null;\n }\n const string = this.fileDirectory.GDAL_METADATA;\n const xmlDom = parse(string.substring(0, string.length - 1));\n\n if (!xmlDom[0].tagName) {\n throw new Error('Failed to parse GDAL metadata XML.');\n }\n\n const root = xmlDom[0];\n if (root.tagName !== 'GDALMetadata') {\n throw new Error('Unexpected GDAL metadata XML tag.');\n }\n\n let items = root.children\n .filter((child) => child.tagName === 'Item');\n\n if (sample !== null) {\n items = items.filter((item) => Number(item.attributes.sample) === sample);\n }\n\n for (let i = 0; i < items.length; ++i) {\n const item = items[i];\n metadata[item.attributes.name] = item.children[0];\n }\n return metadata;\n }\n\n /**\n * Returns the GDAL nodata value\n * @returns {Number} or null\n */\n getGDALNoData() {\n if (!this.fileDirectory.GDAL_NODATA) {\n return null;\n }\n const string = this.fileDirectory.GDAL_NODATA;\n return Number(string.substring(0, string.length - 1));\n }\n\n /**\n * Returns the image origin as a XYZ-vector. When the image has no affine\n * transformation, then an exception is thrown.\n * @returns {Array} The origin as a vector\n */\n getOrigin() {\n const tiePoints = this.fileDirectory.ModelTiepoint;\n const modelTransformation = this.fileDirectory.ModelTransformation;\n if (tiePoints && tiePoints.length === 6) {\n return [\n tiePoints[3],\n tiePoints[4],\n tiePoints[5],\n ];\n }\n if (modelTransformation) {\n return [\n modelTransformation[3],\n modelTransformation[7],\n modelTransformation[11],\n ];\n }\n throw new Error('The image does not have an affine transformation.');\n }\n\n /**\n * Returns the image resolution as a XYZ-vector. When the image has no affine\n * transformation, then an exception is thrown.\n * @param {GeoTIFFImage} [referenceImage=null] A reference image to calculate the resolution from\n * in cases when the current image does not have the\n * required tags on its own.\n * @returns {Array} The resolution as a vector\n */\n getResolution(referenceImage = null) {\n const modelPixelScale = this.fileDirectory.ModelPixelScale;\n const modelTransformation = this.fileDirectory.ModelTransformation;\n\n if (modelPixelScale) {\n return [\n modelPixelScale[0],\n -modelPixelScale[1],\n modelPixelScale[2],\n ];\n }\n if (modelTransformation) {\n return [\n modelTransformation[0],\n modelTransformation[5],\n modelTransformation[10],\n ];\n }\n\n if (referenceImage) {\n const [refResX, refResY, refResZ] = referenceImage.getResolution();\n return [\n refResX * referenceImage.getWidth() / this.getWidth(),\n refResY * referenceImage.getHeight() / this.getHeight(),\n refResZ * referenceImage.getWidth() / this.getWidth(),\n ];\n }\n\n throw new Error('The image does not have an affine transformation.');\n }\n\n /**\n * Returns whether or not the pixels of the image depict an area (or point).\n * @returns {Boolean} Whether the pixels are a point\n */\n pixelIsArea() {\n return this.geoKeys.GTRasterTypeGeoKey === 1;\n }\n\n /**\n * Returns the image bounding box as an array of 4 values: min-x, min-y,\n * max-x and max-y. When the image has no affine transformation, then an\n * exception is thrown.\n * @returns {Array} The bounding box\n */\n getBoundingBox() {\n const origin = this.getOrigin();\n const resolution = this.getResolution();\n\n const x1 = origin[0];\n const y1 = origin[1];\n\n const x2 = x1 + (resolution[0] * this.getWidth());\n const y2 = y1 + (resolution[1] * this.getHeight());\n\n return [\n Math.min(x1, x2),\n Math.min(y1, y2),\n Math.max(x1, x2),\n Math.max(y1, y2),\n ];\n }\n}\n\nexport default GeoTIFFImage;\n","import { getFloat16 } from '@petamoriken/float16';\n\nexport default class DataView64 {\n constructor(arrayBuffer) {\n this._dataView = new DataView(arrayBuffer);\n }\n\n get buffer() {\n return this._dataView.buffer;\n }\n\n getUint64(offset, littleEndian) {\n const left = this.getUint32(offset, littleEndian);\n const right = this.getUint32(offset + 4, littleEndian);\n let combined;\n if (littleEndian) {\n combined = left + 2 ** 32 * right;\n if (!Number.isSafeInteger(combined)) {\n throw new Error(\n `${combined} exceeds MAX_SAFE_INTEGER. Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues`\n );\n }\n return combined;\n }\n combined = 2 ** 32 * left + right;\n if (!Number.isSafeInteger(combined)) {\n throw new Error(\n `${combined} exceeds MAX_SAFE_INTEGER. Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues`\n );\n }\n\n return combined;\n }\n\n // adapted from https://stackoverflow.com/a/55338384/8060591\n getInt64(offset, littleEndian) {\n let value = 0;\n const isNegative =\n (this._dataView.getUint8(offset + (littleEndian ? 7 : 0)) & 0x80) > 0;\n let carrying = true;\n for (let i = 0; i < 8; i++) {\n let byte = this._dataView.getUint8(offset + (littleEndian ? i : 7 - i));\n if (isNegative) {\n if (carrying) {\n if (byte !== 0x00) {\n byte = ~(byte - 1) & 0xff;\n carrying = false;\n }\n } else {\n byte = ~byte & 0xff;\n }\n }\n value += byte * 256 ** i;\n }\n if (isNegative) {\n value = -value;\n }\n return value;\n }\n\n getUint8(offset, littleEndian) {\n return this._dataView.getUint8(offset, littleEndian);\n }\n\n getInt8(offset, littleEndian) {\n return this._dataView.getInt8(offset, littleEndian);\n }\n\n getUint16(offset, littleEndian) {\n return this._dataView.getUint16(offset, littleEndian);\n }\n\n getInt16(offset, littleEndian) {\n return this._dataView.getInt16(offset, littleEndian);\n }\n\n getUint32(offset, littleEndian) {\n return this._dataView.getUint32(offset, littleEndian);\n }\n\n getInt32(offset, littleEndian) {\n return this._dataView.getInt32(offset, littleEndian);\n }\n\n getFloat16(offset, littleEndian) {\n return getFloat16(this._dataView, littleEndian);\n }\n\n getFloat32(offset, littleEndian) {\n return this._dataView.getFloat32(offset, littleEndian);\n }\n\n getFloat64(offset, littleEndian) {\n return this._dataView.getFloat64(offset, littleEndian);\n }\n}\n","export default class DataSlice {\n constructor(arrayBuffer, sliceOffset, littleEndian, bigTiff) {\n this._dataView = new DataView(arrayBuffer);\n this._sliceOffset = sliceOffset;\n this._littleEndian = littleEndian;\n this._bigTiff = bigTiff;\n }\n\n get sliceOffset() {\n return this._sliceOffset;\n }\n\n get sliceTop() {\n return this._sliceOffset + this.buffer.byteLength;\n }\n\n get littleEndian() {\n return this._littleEndian;\n }\n\n get bigTiff() {\n return this._bigTiff;\n }\n\n get buffer() {\n return this._dataView.buffer;\n }\n\n covers(offset, length) {\n return this.sliceOffset <= offset && this.sliceTop >= offset + length;\n }\n\n readUint8(offset) {\n return this._dataView.getUint8(\n offset - this._sliceOffset, this._littleEndian,\n );\n }\n\n readInt8(offset) {\n return this._dataView.getInt8(\n offset - this._sliceOffset, this._littleEndian,\n );\n }\n\n readUint16(offset) {\n return this._dataView.getUint16(\n offset - this._sliceOffset, this._littleEndian,\n );\n }\n\n readInt16(offset) {\n return this._dataView.getInt16(\n offset - this._sliceOffset, this._littleEndian,\n );\n }\n\n readUint32(offset) {\n return this._dataView.getUint32(\n offset - this._sliceOffset, this._littleEndian,\n );\n }\n\n readInt32(offset) {\n return this._dataView.getInt32(\n offset - this._sliceOffset, this._littleEndian,\n );\n }\n\n readFloat32(offset) {\n return this._dataView.getFloat32(\n offset - this._sliceOffset, this._littleEndian,\n );\n }\n\n readFloat64(offset) {\n return this._dataView.getFloat64(\n offset - this._sliceOffset, this._littleEndian,\n );\n }\n\n readUint64(offset) {\n const left = this.readUint32(offset);\n const right = this.readUint32(offset + 4);\n let combined;\n if (this._littleEndian) {\n combined = left + 2 ** 32 * right;\n if (!Number.isSafeInteger(combined)) {\n throw new Error(\n `${combined} exceeds MAX_SAFE_INTEGER. Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues`,\n );\n }\n return combined;\n }\n combined = 2 ** 32 * left + right;\n if (!Number.isSafeInteger(combined)) {\n throw new Error(\n `${combined} exceeds MAX_SAFE_INTEGER. Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues`,\n );\n }\n\n return combined;\n }\n\n // adapted from https://stackoverflow.com/a/55338384/8060591\n readInt64(offset) {\n let value = 0;\n const isNegative =\n (this._dataView.getUint8(offset + (this._littleEndian ? 7 : 0)) & 0x80) >\n 0;\n let carrying = true;\n for (let i = 0; i < 8; i++) {\n let byte = this._dataView.getUint8(\n offset + (this._littleEndian ? i : 7 - i)\n );\n if (isNegative) {\n if (carrying) {\n if (byte !== 0x00) {\n byte = ~(byte - 1) & 0xff;\n carrying = false;\n }\n } else {\n byte = ~byte & 0xff;\n }\n }\n value += byte * 256 ** i;\n }\n if (isNegative) {\n value = -value;\n }\n return value\n }\n\n readOffset(offset) {\n if (this._bigTiff) {\n return this.readUint64(offset);\n }\n return this.readUint32(offset);\n }\n}\n","\nconst CRLFCRLF = '\\r\\n\\r\\n';\n\n/*\n * Shim for 'Object.fromEntries'\n */\nfunction itemsToObject(items) {\n if (typeof Object.fromEntries !== 'undefined') {\n return Object.fromEntries(items);\n }\n const obj = {};\n for (const [key, value] of items) {\n obj[key.toLowerCase()] = value;\n }\n return obj;\n}\n\n/**\n * Parse HTTP headers from a given string.\n * @param {String} text the text to parse the headers from\n * @returns {Object} the parsed headers with lowercase keys\n */\nfunction parseHeaders(text) {\n const items = text\n .split('\\r\\n')\n .map(line => {\n const kv = line.split(':').map(str => str.trim());\n kv[0] = kv[0].toLowerCase();\n return kv\n });\n\n return itemsToObject(items);\n}\n\n/**\n * Parse a 'Content-Type' header value to the content-type and parameters\n * @param {String} rawContentType the raw string to parse from\n * @returns {Object} the parsed content type with the fields: type and params\n */\nexport function parseContentType(rawContentType) {\n const [type, ...rawParams] = rawContentType.split(';').map((s) => s.trim());\n const paramsItems = rawParams.map((param) => param.split('='));\n return { type, params: itemsToObject(paramsItems) };\n}\n\n/**\n * Parse a 'Content-Range' header value to its start, end, and total parts\n * @param {String} rawContentRange the raw string to parse from\n * @returns {Object} the parsed parts\n */\nexport function parseContentRange(rawContentRange) {\n let start;\n let end;\n let total;\n\n if (rawContentRange) {\n [, start, end, total] = rawContentRange.match(/bytes (\\d+)-(\\d+)\\/(\\d+)/);\n start = parseInt(start, 10);\n end = parseInt(end, 10);\n total = parseInt(total, 10);\n }\n\n return { start, end, total };\n}\n\n/**\n * Parses a list of byteranges from the given 'multipart/byteranges' HTTP response.\n * Each item in the list has the following properties:\n * - headers: the HTTP headers\n * - data: the sliced ArrayBuffer for that specific part\n * - offset: the offset of the byterange within its originating file\n * - length: the length of the byterange\n * @param {ArrayBuffer} responseArrayBuffer the response to be parsed and split\n * @param {String} boundary the boundary string used to split the sections\n * @returns {Object[]} the parsed byteranges\n */\nexport function parseByteRanges(responseArrayBuffer, boundary) {\n let offset = null;\n const decoder = new TextDecoder('ascii');\n const out = [];\n\n const startBoundary = `--${boundary}`;\n const endBoundary = `${startBoundary}--`;\n\n // search for the initial boundary, may be offset by some bytes\n // TODO: more efficient to check for `--` in bytes directly\n for (let i = 0; i < 10; ++i) {\n const text = decoder.decode(\n new Uint8Array(responseArrayBuffer, i, startBoundary.length)\n );\n if (text === startBoundary) {\n offset = i;\n }\n }\n\n if (offset === null) {\n throw new Error(\"Could not find initial boundary\");\n }\n\n while (offset < responseArrayBuffer.byteLength) {\n const text = decoder.decode(\n new Uint8Array(responseArrayBuffer, offset,\n Math.min(startBoundary.length + 1024, responseArrayBuffer.byteLength - offset),\n ),\n );\n\n // break if we arrived at the end\n if (text.length === 0 || text.startsWith(endBoundary)) {\n break;\n }\n\n // assert that we are actually dealing with a byterange and are at the correct offset\n if (!text.startsWith(startBoundary)) {\n throw new Error('Part does not start with boundary');\n }\n\n // get a substring from where we read the headers\n const innerText = text.substr(startBoundary.length + 2);\n\n if (innerText.length === 0) {\n break;\n }\n\n // find the double linebreak that denotes the end of the headers\n const endOfHeaders = innerText.indexOf(CRLFCRLF);\n\n // parse the headers to get the content range size\n const headers = parseHeaders(innerText.substr(0, endOfHeaders));\n const { start, end, total } = parseContentRange(headers['content-range']);\n\n // calculate the length of the slice and the next offset\n const startOfData = offset + startBoundary.length + endOfHeaders + CRLFCRLF.length;\n const length = parseInt(end, 10) + 1 - parseInt(start, 10);\n out.push({\n headers,\n data: responseArrayBuffer.slice(startOfData, startOfData + length),\n offset: start,\n length,\n fileSize: total,\n });\n\n offset = startOfData + length + 4;\n }\n\n return out;\n}\n","import LRUCache from 'lru-cache';\nimport { BaseSource } from './basesource';\nimport { AbortError, AggregateError, wait, zip } from '../utils';\n\nclass Block {\n /**\n *\n * @param {number} offset\n * @param {number} length\n * @param {ArrayBuffer} [data]\n */\n constructor(offset, length, data = null) {\n this.offset = offset;\n this.length = length;\n this.data = data;\n }\n\n /**\n * @returns {number} the top byte border\n */\n get top() {\n return this.offset + this.length;\n }\n}\n\n\nclass BlockGroup {\n /**\n *\n * @param {number} offset\n * @param {number} length\n * @param {number[]} blockIds\n */\n constructor(offset, length, blockIds) {\n this.offset = offset;\n this.length = length;\n this.blockIds = blockIds;\n }\n}\n\n\nexport class BlockedSource extends BaseSource {\n /**\n *\n * @param {Source} source The underlying source that shall be blocked and cached\n * @param {object} options\n */\n constructor(source, { blockSize = 65536, cacheSize = 100 } = {}) {\n super();\n this.source = source;\n this.blockSize = blockSize;\n\n this.blockCache = new LRUCache({ max: cacheSize });\n\n // mapping blockId -> Block instance\n this.blockRequests = new Map();\n\n // set of blockIds missing for the current requests\n this.blockIdsToFetch = new Set();\n\n this.abortedBlockIds = new Set();\n }\n\n get fileSize() {\n return this.source.fileSize;\n }\n\n /**\n *\n * @param {basesource/Slice[]} slices\n */\n async fetch(slices, signal) {\n const blockRequests = [];\n const missingBlockIds = [];\n const allBlockIds = []\n\n for (const { offset, length } of slices) {\n let top = offset + length;\n\n const { fileSize } = this;\n if (fileSize !== null) {\n top = Math.min(top, fileSize);\n }\n\n const firstBlockOffset = Math.floor(offset / this.blockSize) * this.blockSize;\n\n for (let current = firstBlockOffset; current < top; current += this.blockSize) {\n const blockId = Math.floor(current / this.blockSize);\n if (!this.blockCache.has(blockId) && !this.blockRequests.has(blockId)) {\n this.blockIdsToFetch.add(blockId);\n missingBlockIds.push(blockId);\n }\n if (this.blockRequests.has(blockId)) {\n blockRequests.push(this.blockRequests.get(blockId));\n }\n allBlockIds.push(blockId);\n }\n }\n\n // allow additional block requests to accumulate\n await wait();\n this.fetchBlocks(signal);\n\n // Gather all of the new requests that this fetch call is contributing to `fetch`.\n const missingRequests = [];\n for (const blockId of missingBlockIds) {\n // The requested missing block could already be in the cache\n // instead of having its request still be outstanding.\n if (this.blockRequests.has(blockId)) {\n missingRequests.push(this.blockRequests.get(blockId));\n }\n }\n\n // Actually await all pending requests that are needed for this `fetch`.\n await Promise.allSettled(blockRequests.values());\n await Promise.allSettled(missingRequests.values());\n\n // Perform retries if a block was interrupted by a previous signal\n const abortedBlockRequests = [];\n const abortedBlockIds = allBlockIds\n .filter(id => this.abortedBlockIds.has(id) || !this.blockCache.has(id));\n abortedBlockIds.forEach(id => this.blockIdsToFetch.add(id));\n // start the retry of some blocks if required\n if (abortedBlockIds.length > 0 && signal && !signal.aborted) {\n this.fetchBlocks(null);\n for (const blockId of abortedBlockIds) {\n const block = this.blockRequests.get(blockId);\n if (!block) {\n throw new Error(`Block ${blockId} is not in the block requests`);\n }\n abortedBlockRequests.push(block);\n }\n await Promise.allSettled(Array.from(abortedBlockRequests.values()));\n }\n\n // throw an abort error\n if (signal && signal.aborted) {\n throw new AbortError('Request was aborted');\n }\n\n const blocks = allBlockIds.map((id) => this.blockCache.get(id));\n const failedBlocks = blocks.filter((i) => !i);\n if (failedBlocks.length) {\n throw new AggregateError(failedBlocks, 'Request failed');\n }\n\n // create a final Map, with all required blocks for this request to satisfy\n const requiredBlocks = new Map(zip(allBlockIds, blocks));\n\n // TODO: satisfy each slice\n return this.readSliceData(slices, requiredBlocks);\n }\n\n /**\n *\n * @param {AbortSignal} signal\n */\n fetchBlocks(signal) {\n // check if we still need to\n if (this.blockIdsToFetch.size > 0) {\n const groups = this.groupBlocks(this.blockIdsToFetch);\n\n // start requesting slices of data\n const groupRequests = this.source.fetch(groups, signal);\n\n for (let groupIndex = 0; groupIndex < groups.length; ++groupIndex) {\n const group = groups[groupIndex];\n\n for (const blockId of group.blockIds) {\n // make an async IIFE for each block\n this.blockRequests.set(blockId, (async () => {\n try {\n const response = (await groupRequests)[groupIndex];\n const blockOffset = blockId * this.blockSize;\n const o = blockOffset - response.offset;\n const t = Math.min(o + this.blockSize, response.data.byteLength);\n const data = response.data.slice(o, t);\n const block = new Block(\n blockOffset,\n data.byteLength,\n data,\n blockId,\n );\n this.blockCache.set(blockId, block);\n this.abortedBlockIds.delete(blockId);\n } catch (err) {\n if (err.name === 'AbortError') {\n // store the signal here, we need it to determine later if an\n // error was caused by this signal\n err.signal = signal;\n this.blockCache.del(blockId);\n this.abortedBlockIds.add(blockId);\n } else {\n throw err;\n }\n } finally {\n this.blockRequests.delete(blockId);\n }\n })());\n }\n }\n this.blockIdsToFetch.clear();\n }\n }\n\n /**\n *\n * @param {Set} blockIds\n * @returns {BlockGroup[]}\n */\n groupBlocks(blockIds) {\n const sortedBlockIds = Array.from(blockIds).sort((a, b) => a - b);\n if (sortedBlockIds.length === 0) {\n return [];\n }\n let current = [];\n let lastBlockId = null;\n const groups = [];\n\n for (const blockId of sortedBlockIds) {\n if (lastBlockId === null || lastBlockId + 1 === blockId) {\n current.push(blockId);\n lastBlockId = blockId;\n } else {\n groups.push(new BlockGroup(\n current[0] * this.blockSize,\n current.length * this.blockSize,\n current,\n ));\n current = [blockId];\n lastBlockId = blockId;\n }\n }\n\n groups.push(new BlockGroup(\n current[0] * this.blockSize,\n current.length * this.blockSize,\n current,\n ));\n\n return groups;\n }\n\n /**\n *\n * @param {Slice[]} slices\n * @param {Map} blocks\n */\n readSliceData(slices, blocks) {\n return slices.map((slice) => {\n const top = slice.offset + slice.length;\n const blockIdLow = Math.floor(slice.offset / this.blockSize);\n const blockIdHigh = Math.floor((slice.offset + slice.length) / this.blockSize);\n const sliceData = new ArrayBuffer(slice.length);\n const sliceView = new Uint8Array(sliceData);\n\n for (let blockId = blockIdLow; blockId <= blockIdHigh; ++blockId) {\n const block = blocks.get(blockId);\n const delta = block.offset - slice.offset;\n const topDelta = block.top - top;\n let blockInnerOffset = 0;\n let rangeInnerOffset = 0;\n let usedBlockLength;\n\n if (delta < 0) {\n blockInnerOffset = -delta;\n } else if (delta > 0) {\n rangeInnerOffset = delta;\n }\n\n if (topDelta < 0) {\n usedBlockLength = block.length - blockInnerOffset;\n } else {\n usedBlockLength = top - block.offset - blockInnerOffset;\n }\n\n const blockView = new Uint8Array(block.data, blockInnerOffset, usedBlockLength);\n sliceView.set(blockView, rangeInnerOffset);\n }\n\n return sliceData;\n });\n }\n}\n","import { BaseClient, BaseResponse } from './base';\n\n\nclass FetchResponse extends BaseResponse {\n /**\n * BaseResponse facade for fetch API Response\n * @param {Response} response\n */\n constructor(response) {\n super();\n this.response = response;\n }\n\n get status() {\n return this.response.status;\n }\n\n getHeader(name) {\n return this.response.headers.get(name);\n }\n\n async getData() {\n const data = this.response.arrayBuffer\n ? await this.response.arrayBuffer()\n : (await this.response.buffer()).buffer;\n return data;\n }\n}\n\nexport class FetchClient extends BaseClient {\n constructor(url, credentials) {\n super(url);\n this.credentials = credentials;\n }\n\n async request({ headers, credentials, signal } = {}) {\n const response = await fetch(this.url, {\n headers, credentials, signal,\n });\n return new FetchResponse(response);\n }\n}\n","import { BaseClient, BaseResponse } from './base';\nimport { AbortError } from '../../utils';\n\n\nclass XHRResponse extends BaseResponse {\n /**\n * BaseResponse facade for XMLHttpRequest\n * @param {XMLHttpRequest} xhr\n * @param {ArrayBuffer} data\n */\n constructor(xhr, data) {\n super();\n this.xhr = xhr;\n this.data = data;\n }\n\n get status() {\n return this.xhr.status;\n }\n\n getHeader(name) {\n return this.xhr.getResponseHeader(name);\n }\n\n async getData() {\n return this.data;\n }\n}\n\nexport class XHRClient extends BaseClient {\n constructRequest(headers, signal) {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open('GET', this.url);\n xhr.responseType = 'arraybuffer';\n for (const [key, value] of Object.entries(headers)) {\n xhr.setRequestHeader(key, value);\n }\n\n // hook signals\n xhr.onload = () => {\n const data = xhr.response;\n resolve(new XHRResponse(xhr, data));\n };\n xhr.onerror = reject;\n xhr.onabort = () => reject(new AbortError('Request aborted'));\n xhr.send();\n\n if (signal) {\n if (signal.aborted) {\n xhr.abort();\n }\n signal.addEventListener('abort', () => xhr.abort());\n }\n });\n }\n\n async request({ headers, signal } = {}) {\n const response = await this.constructRequest(headers, signal);\n return response;\n }\n}\n","import { parseByteRanges, parseContentRange, parseContentType } from './httputils';\nimport { BaseSource } from './basesource';\nimport { BlockedSource } from './blockedsource';\n\nimport { FetchClient } from './client/fetch';\nimport { XHRClient } from './client/xhr';\nimport { HttpClient } from './client/http';\n\n\nclass RemoteSource extends BaseSource {\n /**\n *\n * @param {BaseClient} client\n * @param {object} headers\n * @param {numbers} maxRanges\n * @param {boolean} allowFullFile\n */\n constructor(client, headers, maxRanges, allowFullFile) {\n super();\n this.client = client;\n this.headers = headers;\n this.maxRanges = maxRanges;\n this.allowFullFile = allowFullFile;\n this._fileSize = null;\n }\n\n /**\n *\n * @param {Slice[]} slices\n */\n async fetch(slices, signal) {\n // if we allow multi-ranges, split the incoming request into that many sub-requests\n // and join them afterwards\n if (this.maxRanges >= slices.length) {\n return this.fetchSlices(slices, signal);\n } else if (this.maxRanges > 0 && slices.length > 1) {\n // TODO: split into multiple multi-range requests\n\n // const subSlicesRequests = [];\n // for (let i = 0; i < slices.length; i += this.maxRanges) {\n // subSlicesRequests.push(\n // this.fetchSlices(slices.slice(i, i + this.maxRanges), signal),\n // );\n // }\n // return (await Promise.all(subSlicesRequests)).flat();\n }\n\n // otherwise make a single request for each slice\n return await Promise.all(\n slices.map((slice) => this.fetchSlice(slice, signal)),\n );\n }\n\n async fetchSlices(slices, signal) {\n const response = await this.client.request({\n headers: {\n ...this.headers,\n Range: `bytes=${slices\n .map(({ offset, length }) => `${offset}-${offset + length}`)\n .join(',')\n }`,\n },\n signal,\n });\n\n if (!response.ok) {\n throw new Error('Error fetching data.');\n } else if (response.status === 206) {\n const { type, params } = parseContentType(response.getHeader('content-type'));\n if (type === 'multipart/byteranges') {\n const byteRanges = parseByteRanges(await response.getData(), params.boundary);\n this._fileSize = byteRanges[0].fileSize || null;\n return byteRanges;\n }\n\n const data = await response.getData();\n\n const { start, end, total } = parseContentRange(response.getHeader('content-range'));\n this._fileSize = total || null;\n const first = [{\n data,\n offset: start,\n length: end - start,\n }];\n\n if (slices.length > 1) {\n // we requested more than one slice, but got only the first\n // unfortunately, some HTTP Servers don't support multi-ranges\n // and return onyl the first\n\n // get the rest of the slices and fetch them iteratetively\n const others = await Promise.all(slices.slice(1).map((slice) => this.fetchSlice(slice, signal)));\n return first.concat(others);\n }\n return first;\n } else {\n if (!this.allowFullFile) {\n throw new Error('Server responded with full file');\n }\n const data = await response.getData();\n this._fileSize = data.byteLength;\n return [{\n data,\n offset: 0,\n length: data.byteLength,\n }];\n }\n }\n\n async fetchSlice(slice, signal) {\n const { offset, length } = slice;\n const response = await this.client.request({\n headers: {\n ...this.headers,\n Range: `bytes=${offset}-${offset + length}`,\n },\n signal,\n });\n\n // check the response was okay and if the server actually understands range requests\n if (!response.ok) {\n throw new Error('Error fetching data.');\n } else if (response.status === 206) {\n const data = await response.getData();\n\n const { total } = parseContentRange(response.getHeader('content-range'));\n this._fileSize = total || null;\n return {\n data,\n offset,\n length,\n };\n } else {\n if (!this.allowFullFile) {\n throw new Error('Server responded with full file');\n }\n\n const data = await response.getData();\n\n this._fileSize = data.byteLength;\n return {\n data,\n offset: 0,\n length: data.byteLength,\n };\n }\n }\n\n get fileSize() {\n return this._fileSize;\n }\n}\n\n\nfunction maybeWrapInBlockedSource(source, { blockSize, cacheSize }) {\n if (blockSize === null) {\n return source;\n }\n return new BlockedSource(source, { blockSize, cacheSize });\n}\n\nexport function makeFetchSource(url, { headers = {}, credentials, maxRanges = 0, allowFullFile = false, ...blockOptions } = {}) {\n const client = new FetchClient(url, credentials);\n const source = new RemoteSource(client, headers, maxRanges, allowFullFile);\n return maybeWrapInBlockedSource(source, blockOptions);\n}\n\nexport function makeXHRSource(url, { headers = {}, maxRanges = 0, allowFullFile = false, ...blockOptions } = {}) {\n const client = new XHRClient(url);\n const source = new RemoteSource(client, headers, maxRanges, allowFullFile);\n return maybeWrapInBlockedSource(source, blockOptions);\n}\n\nexport function makeHttpSource(url, { headers = {}, maxRanges = 0, allowFullFile = false, ...blockOptions } = {}) {\n const client = new HttpClient(url);\n const source = new RemoteSource(client, headers, maxRanges, allowFullFile);\n return maybeWrapInBlockedSource(source, blockOptions);\n}\n\n/**\n *\n * @param {string} url\n * @param {object} options\n */\nexport function makeRemoteSource(url, { forceXHR = false, ...clientOptions } = {}) {\n\n if (typeof fetch === 'function' && !forceXHR) {\n return makeFetchSource(url, clientOptions);\n }\n if (typeof XMLHttpRequest !== 'undefined') {\n return makeXHRSource(url, clientOptions);\n }\n return makeHttpSource(url, clientOptions);\n}\n","import { BaseSource } from './basesource';\nimport { AbortError } from '../utils';\n\n\nclass ArrayBufferSource extends BaseSource {\n constructor(arrayBuffer) {\n super();\n this.arrayBuffer = arrayBuffer;\n }\n\n fetchSlice(slice, signal) {\n if (signal && signal.aborted) {\n throw new AbortError('Request aborted');\n }\n return this.arrayBuffer.slice(slice.offset, slice.offset + slice.length);\n }\n}\n\nexport function makeBufferSource(arrayBuffer) {\n return new ArrayBufferSource(arrayBuffer);\n}\n","import { BaseSource } from './basesource';\n\n\nclass FileReaderSource extends BaseSource {\n constructor(file) {\n super();\n this.file = file;\n }\n\n async fetchSlice(slice, signal) {\n return new Promise((resolve, reject) => {\n const blob = this.file.slice(slice.offset, slice.offset + slice.length);\n const reader = new FileReader();\n reader.onload = (event) => resolve(event.target.result);\n reader.onerror = reject;\n reader.onabort = reject;\n reader.readAsArrayBuffer(blob);\n\n if (signal) {\n signal.addEventListener('abort', () => reader.abort());\n }\n });\n }\n}\n\n/**\n * Create a new source from a given file/blob.\n * @param {Blob} file The file or blob to read from.\n * @returns The constructed source\n */\nexport function makeFileReaderSource(file) {\n return new FileReaderSource(file);\n}\n","/*\n Some parts of this file are based on UTIF.js,\n which was released under the MIT License.\n You can view that here:\n https://github.com/photopea/UTIF.js/blob/master/LICENSE\n*/\nimport { fieldTagNames, fieldTagTypes, fieldTypeNames, geoKeyNames } from './globals';\nimport { assign, endsWith, forEach, invert, times } from './utils';\n\nconst tagName2Code = invert(fieldTagNames);\nconst geoKeyName2Code = invert(geoKeyNames);\nconst name2code = {};\nassign(name2code, tagName2Code);\nassign(name2code, geoKeyName2Code);\nconst typeName2byte = invert(fieldTypeNames);\n\n// config variables\nconst numBytesInIfd = 1000;\n\nconst _binBE = {\n nextZero: (data, o) => {\n let oincr = o;\n while (data[oincr] !== 0) {\n oincr++;\n }\n return oincr;\n },\n readUshort: (buff, p) => {\n return (buff[p] << 8) | buff[p + 1];\n },\n readShort: (buff, p) => {\n const a = _binBE.ui8;\n a[0] = buff[p + 1];\n a[1] = buff[p + 0];\n return _binBE.i16[0];\n },\n readInt: (buff, p) => {\n const a = _binBE.ui8;\n a[0] = buff[p + 3];\n a[1] = buff[p + 2];\n a[2] = buff[p + 1];\n a[3] = buff[p + 0];\n return _binBE.i32[0];\n },\n readUint: (buff, p) => {\n const a = _binBE.ui8;\n a[0] = buff[p + 3];\n a[1] = buff[p + 2];\n a[2] = buff[p + 1];\n a[3] = buff[p + 0];\n return _binBE.ui32[0];\n },\n readASCII: (buff, p, l) => {\n return l.map((i) => String.fromCharCode(buff[p + i])).join('');\n },\n readFloat: (buff, p) => {\n const a = _binBE.ui8;\n times(4, (i) => {\n a[i] = buff[p + 3 - i];\n });\n return _binBE.fl32[0];\n },\n readDouble: (buff, p) => {\n const a = _binBE.ui8;\n times(8, (i) => {\n a[i] = buff[p + 7 - i];\n });\n return _binBE.fl64[0];\n },\n writeUshort: (buff, p, n) => {\n buff[p] = (n >> 8) & 255;\n buff[p + 1] = n & 255;\n },\n writeUint: (buff, p, n) => {\n buff[p] = (n >> 24) & 255;\n buff[p + 1] = (n >> 16) & 255;\n buff[p + 2] = (n >> 8) & 255;\n buff[p + 3] = (n >> 0) & 255;\n },\n writeASCII: (buff, p, s) => {\n times(s.length, (i) => {\n buff[p + i] = s.charCodeAt(i);\n });\n },\n ui8: new Uint8Array(8),\n};\n\n_binBE.fl64 = new Float64Array(_binBE.ui8.buffer);\n\n_binBE.writeDouble = (buff, p, n) => {\n _binBE.fl64[0] = n;\n times(8, (i) => {\n buff[p + i] = _binBE.ui8[7 - i];\n });\n};\n\n\nconst _writeIFD = (bin, data, _offset, ifd) => {\n let offset = _offset;\n\n const keys = Object.keys(ifd).filter((key) => {\n return key !== undefined && key !== null && key !== 'undefined';\n });\n\n bin.writeUshort(data, offset, keys.length);\n offset += 2;\n\n let eoff = offset + (12 * keys.length) + 4;\n\n for (const key of keys) {\n let tag = null;\n if (typeof key === 'number') {\n tag = key;\n } else if (typeof key === 'string') {\n tag = parseInt(key, 10);\n }\n\n const typeName = fieldTagTypes[tag];\n const typeNum = typeName2byte[typeName];\n\n if (typeName == null || typeName === undefined || typeof typeName === 'undefined') {\n throw new Error(`unknown type of tag: ${tag}`);\n }\n\n let val = ifd[key];\n\n if (typeof val === 'undefined') {\n throw new Error(`failed to get value for key ${key}`);\n }\n\n // ASCIIZ format with trailing 0 character\n // http://www.fileformat.info/format/tiff/corion.htm\n // https://stackoverflow.com/questions/7783044/whats-the-difference-between-asciiz-vs-ascii\n if (typeName === 'ASCII' && typeof val === 'string' && endsWith(val, '\\u0000') === false) {\n val += '\\u0000';\n }\n\n const num = val.length;\n\n bin.writeUshort(data, offset, tag);\n offset += 2;\n\n bin.writeUshort(data, offset, typeNum);\n offset += 2;\n\n bin.writeUint(data, offset, num);\n offset += 4;\n\n let dlen = [-1, 1, 1, 2, 4, 8, 0, 0, 0, 0, 0, 0, 8][typeNum] * num;\n let toff = offset;\n\n if (dlen > 4) {\n bin.writeUint(data, offset, eoff);\n toff = eoff;\n }\n\n if (typeName === 'ASCII') {\n bin.writeASCII(data, toff, val);\n } else if (typeName === 'SHORT') {\n times(num, (i) => {\n bin.writeUshort(data, toff + (2 * i), val[i]);\n });\n } else if (typeName === 'LONG') {\n times(num, (i) => {\n bin.writeUint(data, toff + (4 * i), val[i]);\n });\n } else if (typeName === 'RATIONAL') {\n times(num, (i) => {\n bin.writeUint(data, toff + (8 * i), Math.round(val[i] * 10000));\n bin.writeUint(data, toff + (8 * i) + 4, 10000);\n });\n } else if (typeName === 'DOUBLE') {\n times(num, (i) => {\n bin.writeDouble(data, toff + (8 * i), val[i]);\n });\n }\n\n if (dlen > 4) {\n dlen += (dlen & 1);\n eoff += dlen;\n }\n\n offset += 4;\n }\n\n return [offset, eoff];\n};\n\nconst encodeIfds = (ifds) => {\n const data = new Uint8Array(numBytesInIfd);\n let offset = 4;\n const bin = _binBE;\n\n // set big-endian byte-order\n // https://en.wikipedia.org/wiki/TIFF#Byte_order\n data[0] = 77;\n data[1] = 77;\n\n // set format-version number\n // https://en.wikipedia.org/wiki/TIFF#Byte_order\n data[3] = 42;\n\n let ifdo = 8;\n\n bin.writeUint(data, offset, ifdo);\n\n offset += 4;\n\n ifds.forEach((ifd, i) => {\n const noffs = _writeIFD(bin, data, ifdo, ifd);\n ifdo = noffs[1];\n if (i < ifds.length - 1) {\n bin.writeUint(data, noffs[0], ifdo);\n }\n });\n\n if (data.slice) {\n return data.slice(0, ifdo).buffer;\n }\n\n // node hasn't implemented slice on Uint8Array yet\n const result = new Uint8Array(ifdo);\n for (let i = 0; i < ifdo; i++) {\n result[i] = data[i];\n }\n return result.buffer;\n};\n\nconst encodeImage = (values, width, height, metadata) => {\n if (height === undefined || height === null) {\n throw new Error(`you passed into encodeImage a width of type ${height}`);\n }\n\n if (width === undefined || width === null) {\n throw new Error(`you passed into encodeImage a width of type ${width}`);\n }\n\n const ifd = {\n 256: [width], // ImageWidth\n 257: [height], // ImageLength\n 273: [numBytesInIfd], // strips offset\n 278: [height], // RowsPerStrip\n 305: 'geotiff.js', // no array for ASCII(Z)\n };\n\n if (metadata) {\n for (const i in metadata) {\n if (metadata.hasOwnProperty(i)) {\n ifd[i] = metadata[i];\n }\n }\n }\n\n const prfx = new Uint8Array(encodeIfds([ifd]));\n\n const img = new Uint8Array(values);\n\n const samplesPerPixel = ifd[277];\n\n const data = new Uint8Array(numBytesInIfd + (width * height * samplesPerPixel));\n times(prfx.length, (i) => {\n data[i] = prfx[i];\n });\n forEach(img, (value, i) => {\n data[numBytesInIfd + i] = value;\n });\n\n return data.buffer;\n};\n\nconst convertToTids = (input) => {\n const result = {};\n for (const key in input) {\n if (key !== 'StripOffsets') {\n if (!name2code[key]) {\n console.error(key, 'not in name2code:', Object.keys(name2code));\n }\n result[name2code[key]] = input[key];\n }\n }\n return result;\n};\n\nconst toArray = (input) => {\n if (Array.isArray(input)) {\n return input;\n }\n return [input];\n};\n\nconst metadataDefaults = [\n ['Compression', 1], // no compression\n ['PlanarConfiguration', 1],\n ['XPosition', 0],\n ['YPosition', 0],\n ['ResolutionUnit', 1], // Code 1 for actual pixel count or 2 for pixels per inch.\n ['ExtraSamples', 0], // should this be an array??\n ['GeoAsciiParams', 'WGS 84\\u0000'],\n ['ModelTiepoint', [0, 0, 0, -180, 90, 0]], // raster fits whole globe\n ['GTModelTypeGeoKey', 2],\n ['GTRasterTypeGeoKey', 1],\n ['GeographicTypeGeoKey', 4326],\n ['GeogCitationGeoKey', 'WGS 84'],\n];\n\nexport function writeGeotiff(data, metadata) {\n const isFlattened = typeof data[0] === 'number';\n\n let height;\n let numBands;\n let width;\n let flattenedValues;\n\n if (isFlattened) {\n height = metadata.height || metadata.ImageLength;\n width = metadata.width || metadata.ImageWidth;\n numBands = data.length / (height * width);\n flattenedValues = data;\n } else {\n numBands = data.length;\n height = data[0].length;\n width = data[0][0].length;\n flattenedValues = [];\n times(height, (rowIndex) => {\n times(width, (columnIndex) => {\n times(numBands, (bandIndex) => {\n flattenedValues.push(data[bandIndex][rowIndex][columnIndex]);\n });\n });\n });\n }\n\n metadata.ImageLength = height;\n delete metadata.height;\n metadata.ImageWidth = width;\n delete metadata.width;\n\n // consult https://www.loc.gov/preservation/digital/formats/content/tiff_tags.shtml\n\n if (!metadata.BitsPerSample) {\n metadata.BitsPerSample = times(numBands, () => 8);\n }\n\n metadataDefaults.forEach((tag) => {\n const key = tag[0];\n if (!metadata[key]) {\n const value = tag[1];\n metadata[key] = value;\n }\n });\n\n // The color space of the image data.\n // 1=black is zero and 2=RGB.\n if (!metadata.PhotometricInterpretation) {\n metadata.PhotometricInterpretation = metadata.BitsPerSample.length === 3 ? 2 : 1;\n }\n\n // The number of components per pixel.\n if (!metadata.SamplesPerPixel) {\n metadata.SamplesPerPixel = [numBands];\n }\n\n if (!metadata.StripByteCounts) {\n // we are only writing one strip\n metadata.StripByteCounts = [numBands * height * width];\n }\n\n if (!metadata.ModelPixelScale) {\n // assumes raster takes up exactly the whole globe\n metadata.ModelPixelScale = [360 / width, 180 / height, 0];\n }\n\n if (!metadata.SampleFormat) {\n metadata.SampleFormat = times(numBands, () => 1);\n }\n\n\n const geoKeys = Object.keys(metadata)\n .filter((key) => endsWith(key, 'GeoKey'))\n .sort((a, b) => name2code[a] - name2code[b]);\n\n if (!metadata.GeoKeyDirectory) {\n const NumberOfKeys = geoKeys.length;\n\n const GeoKeyDirectory = [1, 1, 0, NumberOfKeys];\n geoKeys.forEach((geoKey) => {\n const KeyID = Number(name2code[geoKey]);\n GeoKeyDirectory.push(KeyID);\n\n let Count;\n let TIFFTagLocation;\n let valueOffset;\n if (fieldTagTypes[KeyID] === 'SHORT') {\n Count = 1;\n TIFFTagLocation = 0;\n valueOffset = metadata[geoKey];\n } else if (geoKey === 'GeogCitationGeoKey') {\n Count = metadata.GeoAsciiParams.length;\n TIFFTagLocation = Number(name2code.GeoAsciiParams);\n valueOffset = 0;\n } else {\n console.log(`[geotiff.js] couldn't get TIFFTagLocation for ${geoKey}`);\n }\n GeoKeyDirectory.push(TIFFTagLocation);\n GeoKeyDirectory.push(Count);\n GeoKeyDirectory.push(valueOffset);\n });\n metadata.GeoKeyDirectory = GeoKeyDirectory;\n }\n\n // delete GeoKeys from metadata, because stored in GeoKeyDirectory tag\n for (const geoKey in geoKeys) {\n if (geoKeys.hasOwnProperty(geoKey)) {\n delete metadata[geoKey];\n }\n }\n\n [\n 'Compression',\n 'ExtraSamples',\n 'GeographicTypeGeoKey',\n 'GTModelTypeGeoKey',\n 'GTRasterTypeGeoKey',\n 'ImageLength', // synonym of ImageHeight\n 'ImageWidth',\n 'PhotometricInterpretation',\n 'PlanarConfiguration',\n 'ResolutionUnit',\n 'SamplesPerPixel',\n 'XPosition',\n 'YPosition',\n ].forEach((name) => {\n if (metadata[name]) {\n metadata[name] = toArray(metadata[name]);\n }\n });\n\n\n const encodedMetadata = convertToTids(metadata);\n\n const outputImage = encodeImage(flattenedValues, width, height, encodedMetadata);\n\n return outputImage;\n}\n","import GeoTIFFImage from './geotiffimage';\nimport DataView64 from './dataview64';\nimport DataSlice from './dataslice';\nimport Pool from './pool';\n\nimport { makeRemoteSource } from './source/remote';\nimport { makeBufferSource } from './source/arraybuffer';\nimport { makeFileReaderSource } from './source/filereader';\nimport { makeFileSource } from './source/file';\n\nimport { fieldTypes, fieldTagNames, arrayFields, geoKeyNames } from './globals';\nimport { writeGeotiff } from './geotiffwriter';\nimport * as globals from './globals';\nimport * as rgb from './rgb';\nimport { getDecoder } from './compression';\nimport { setLogger } from './logging';\n\nexport { globals };\nexport { rgb };\nexport { getDecoder };\nexport { setLogger };\n\nfunction getFieldTypeLength(fieldType) {\n switch (fieldType) {\n case fieldTypes.BYTE: case fieldTypes.ASCII: case fieldTypes.SBYTE: case fieldTypes.UNDEFINED:\n return 1;\n case fieldTypes.SHORT: case fieldTypes.SSHORT:\n return 2;\n case fieldTypes.LONG: case fieldTypes.SLONG: case fieldTypes.FLOAT: case fieldTypes.IFD:\n return 4;\n case fieldTypes.RATIONAL: case fieldTypes.SRATIONAL: case fieldTypes.DOUBLE:\n case fieldTypes.LONG8: case fieldTypes.SLONG8: case fieldTypes.IFD8:\n return 8;\n default:\n throw new RangeError(`Invalid field type: ${fieldType}`);\n }\n}\n\nfunction parseGeoKeyDirectory(fileDirectory) {\n const rawGeoKeyDirectory = fileDirectory.GeoKeyDirectory;\n if (!rawGeoKeyDirectory) {\n return null;\n }\n\n const geoKeyDirectory = {};\n for (let i = 4; i <= rawGeoKeyDirectory[3] * 4; i += 4) {\n const key = geoKeyNames[rawGeoKeyDirectory[i]];\n const location = (rawGeoKeyDirectory[i + 1])\n ? (fieldTagNames[rawGeoKeyDirectory[i + 1]]) : null;\n const count = rawGeoKeyDirectory[i + 2];\n const offset = rawGeoKeyDirectory[i + 3];\n\n let value = null;\n if (!location) {\n value = offset;\n } else {\n value = fileDirectory[location];\n if (typeof value === 'undefined' || value === null) {\n throw new Error(`Could not get value of geoKey '${key}'.`);\n } else if (typeof value === 'string') {\n value = value.substring(offset, offset + count - 1);\n } else if (value.subarray) {\n value = value.subarray(offset, offset + count);\n if (count === 1) {\n value = value[0];\n }\n }\n }\n geoKeyDirectory[key] = value;\n }\n return geoKeyDirectory;\n}\n\nfunction getValues(dataSlice, fieldType, count, offset) {\n let values = null;\n let readMethod = null;\n const fieldTypeLength = getFieldTypeLength(fieldType);\n\n switch (fieldType) {\n case fieldTypes.BYTE: case fieldTypes.ASCII: case fieldTypes.UNDEFINED:\n values = new Uint8Array(count); readMethod = dataSlice.readUint8;\n break;\n case fieldTypes.SBYTE:\n values = new Int8Array(count); readMethod = dataSlice.readInt8;\n break;\n case fieldTypes.SHORT:\n values = new Uint16Array(count); readMethod = dataSlice.readUint16;\n break;\n case fieldTypes.SSHORT:\n values = new Int16Array(count); readMethod = dataSlice.readInt16;\n break;\n case fieldTypes.LONG: case fieldTypes.IFD:\n values = new Uint32Array(count); readMethod = dataSlice.readUint32;\n break;\n case fieldTypes.SLONG:\n values = new Int32Array(count); readMethod = dataSlice.readInt32;\n break;\n case fieldTypes.LONG8: case fieldTypes.IFD8:\n values = new Array(count); readMethod = dataSlice.readUint64;\n break;\n case fieldTypes.SLONG8:\n values = new Array(count); readMethod = dataSlice.readInt64;\n break;\n case fieldTypes.RATIONAL:\n values = new Uint32Array(count * 2); readMethod = dataSlice.readUint32;\n break;\n case fieldTypes.SRATIONAL:\n values = new Int32Array(count * 2); readMethod = dataSlice.readInt32;\n break;\n case fieldTypes.FLOAT:\n values = new Float32Array(count); readMethod = dataSlice.readFloat32;\n break;\n case fieldTypes.DOUBLE:\n values = new Float64Array(count); readMethod = dataSlice.readFloat64;\n break;\n default:\n throw new RangeError(`Invalid field type: ${fieldType}`);\n }\n\n // normal fields\n if (!(fieldType === fieldTypes.RATIONAL || fieldType === fieldTypes.SRATIONAL)) {\n for (let i = 0; i < count; ++i) {\n values[i] = readMethod.call(\n dataSlice, offset + (i * fieldTypeLength),\n );\n }\n } else { // RATIONAL or SRATIONAL\n for (let i = 0; i < count; i += 2) {\n values[i] = readMethod.call(\n dataSlice, offset + (i * fieldTypeLength),\n );\n values[i + 1] = readMethod.call(\n dataSlice, offset + ((i * fieldTypeLength) + 4),\n );\n }\n }\n\n if (fieldType === fieldTypes.ASCII) {\n return new TextDecoder('utf-8').decode(values);\n }\n return values;\n}\n\n/**\n * Data class to store the parsed file directory, geo key directory and\n * offset to the next IFD\n */\nclass ImageFileDirectory {\n constructor(fileDirectory, geoKeyDirectory, nextIFDByteOffset) {\n this.fileDirectory = fileDirectory;\n this.geoKeyDirectory = geoKeyDirectory;\n this.nextIFDByteOffset = nextIFDByteOffset;\n }\n}\n\n/**\n * Error class for cases when an IFD index was requested, that does not exist\n * in the file.\n */\nclass GeoTIFFImageIndexError extends Error {\n constructor(index) {\n super(`No image at index ${index}`);\n this.index = index;\n }\n}\n\n\nclass GeoTIFFBase {\n /**\n * (experimental) Reads raster data from the best fitting image. This function uses\n * the image with the lowest resolution that is still a higher resolution than the\n * requested resolution.\n * When specified, the `bbox` option is translated to the `window` option and the\n * `resX` and `resY` to `width` and `height` respectively.\n * Then, the [readRasters]{@link GeoTIFFImage#readRasters} method of the selected\n * image is called and the result returned.\n * @see GeoTIFFImage.readRasters\n * @param {Object} [options={}] optional parameters\n * @param {Array} [options.window=whole image] the subset to read data from.\n * @param {Array} [options.bbox=whole image] the subset to read data from in\n * geographical coordinates.\n * @param {Array} [options.samples=all samples] the selection of samples to read from.\n * @param {Boolean} [options.interleave=false] whether the data shall be read\n * in one single array or separate\n * arrays.\n * @param {Number} [options.pool=null] The optional decoder pool to use.\n * @param {Number} [options.width] The desired width of the output. When the width is not the\n * same as the images, resampling will be performed.\n * @param {Number} [options.height] The desired height of the output. When the width is not the\n * same as the images, resampling will be performed.\n * @param {String} [options.resampleMethod='nearest'] The desired resampling method.\n * @param {AbortSignal} [options.signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @param {Number|Number[]} [options.fillValue] The value to use for parts of the image\n * outside of the images extent. When multiple\n * samples are requested, an array of fill values\n * can be passed.\n * @returns {Promise.<(TypedArray|TypedArray[])>} the decoded arrays as a promise\n */\n async readRasters(options = {}) {\n const { window: imageWindow, width, height } = options;\n let { resX, resY, bbox } = options;\n\n const firstImage = await this.getImage();\n let usedImage = firstImage;\n const imageCount = await this.getImageCount();\n const imgBBox = firstImage.getBoundingBox();\n\n if (imageWindow && bbox) {\n throw new Error('Both \"bbox\" and \"window\" passed.');\n }\n\n // if width/height is passed, transform it to resolution\n if (width || height) {\n // if we have an image window (pixel coordinates), transform it to a BBox\n // using the origin/resolution of the first image.\n if (imageWindow) {\n const [oX, oY] = firstImage.getOrigin();\n const [rX, rY] = firstImage.getResolution();\n\n bbox = [\n oX + (imageWindow[0] * rX),\n oY + (imageWindow[1] * rY),\n oX + (imageWindow[2] * rX),\n oY + (imageWindow[3] * rY),\n ];\n }\n\n // if we have a bbox (or calculated one)\n\n const usedBBox = bbox || imgBBox;\n\n if (width) {\n if (resX) {\n throw new Error('Both width and resX passed');\n }\n resX = (usedBBox[2] - usedBBox[0]) / width;\n }\n if (height) {\n if (resY) {\n throw new Error('Both width and resY passed');\n }\n resY = (usedBBox[3] - usedBBox[1]) / height;\n }\n }\n\n // if resolution is set or calculated, try to get the image with the worst acceptable resolution\n if (resX || resY) {\n const allImages = [];\n for (let i = 0; i < imageCount; ++i) {\n const image = await this.getImage(i);\n const { SubfileType: subfileType, NewSubfileType: newSubfileType } = image.fileDirectory;\n if (i === 0 || subfileType === 2 || newSubfileType & 1) {\n allImages.push(image);\n }\n }\n\n allImages.sort((a, b) => a.getWidth() - b.getWidth());\n for (let i = 0; i < allImages.length; ++i) {\n const image = allImages[i];\n const imgResX = (imgBBox[2] - imgBBox[0]) / image.getWidth();\n const imgResY = (imgBBox[3] - imgBBox[1]) / image.getHeight();\n\n usedImage = image;\n if ((resX && resX > imgResX) || (resY && resY > imgResY)) {\n break;\n }\n }\n }\n\n let wnd = imageWindow;\n if (bbox) {\n const [oX, oY] = firstImage.getOrigin();\n const [imageResX, imageResY] = usedImage.getResolution(firstImage);\n\n wnd = [\n Math.round((bbox[0] - oX) / imageResX),\n Math.round((bbox[1] - oY) / imageResY),\n Math.round((bbox[2] - oX) / imageResX),\n Math.round((bbox[3] - oY) / imageResY),\n ];\n wnd = [\n Math.min(wnd[0], wnd[2]),\n Math.min(wnd[1], wnd[3]),\n Math.max(wnd[0], wnd[2]),\n Math.max(wnd[1], wnd[3]),\n ];\n }\n\n return usedImage.readRasters({ ...options, window: wnd });\n }\n}\n\n\n/**\n * The abstraction for a whole GeoTIFF file.\n * @augments GeoTIFFBase\n */\nclass GeoTIFF extends GeoTIFFBase {\n /**\n * @constructor\n * @param {Source} source The datasource to read from.\n * @param {Boolean} littleEndian Whether the image uses little endian.\n * @param {Boolean} bigTiff Whether the image uses bigTIFF conventions.\n * @param {Number} firstIFDOffset The numeric byte-offset from the start of the image\n * to the first IFD.\n * @param {Object} [options] further options.\n * @param {Boolean} [options.cache=false] whether or not decoded tiles shall be cached.\n */\n constructor(source, littleEndian, bigTiff, firstIFDOffset, options = {}) {\n super();\n this.source = source;\n this.littleEndian = littleEndian;\n this.bigTiff = bigTiff;\n this.firstIFDOffset = firstIFDOffset;\n this.cache = options.cache || false;\n this.ifdRequests = [];\n this.ghostValues = null;\n }\n\n async getSlice(offset, size) {\n const fallbackSize = this.bigTiff ? 4048 : 1024;\n return new DataSlice(\n (await this.source.fetch([{\n offset,\n length: typeof size !== 'undefined' ? size : fallbackSize,\n }]))[0],\n offset,\n this.littleEndian,\n this.bigTiff,\n );\n }\n\n /**\n * Instructs to parse an image file directory at the given file offset.\n * As there is no way to ensure that a location is indeed the start of an IFD,\n * this function must be called with caution (e.g only using the IFD offsets from\n * the headers or other IFDs).\n * @param {number} offset the offset to parse the IFD at\n * @returns {ImageFileDirectory} the parsed IFD\n */\n async parseFileDirectoryAt(offset) {\n const entrySize = this.bigTiff ? 20 : 12;\n const offsetSize = this.bigTiff ? 8 : 2;\n\n let dataSlice = await this.getSlice(offset);\n const numDirEntries = this.bigTiff ?\n dataSlice.readUint64(offset) :\n dataSlice.readUint16(offset);\n\n // if the slice does not cover the whole IFD, request a bigger slice, where the\n // whole IFD fits: num of entries + n x tag length + offset to next IFD\n const byteSize = (numDirEntries * entrySize) + (this.bigTiff ? 16 : 6);\n if (!dataSlice.covers(offset, byteSize)) {\n dataSlice = await this.getSlice(offset, byteSize);\n }\n\n const fileDirectory = {};\n\n // loop over the IFD and create a file directory object\n let i = offset + (this.bigTiff ? 8 : 2);\n for (let entryCount = 0; entryCount < numDirEntries; i += entrySize, ++entryCount) {\n const fieldTag = dataSlice.readUint16(i);\n const fieldType = dataSlice.readUint16(i + 2);\n const typeCount = this.bigTiff ?\n dataSlice.readUint64(i + 4) :\n dataSlice.readUint32(i + 4);\n\n let fieldValues;\n let value;\n const fieldTypeLength = getFieldTypeLength(fieldType);\n const valueOffset = i + (this.bigTiff ? 12 : 8);\n\n // check whether the value is directly encoded in the tag or refers to a\n // different external byte range\n if (fieldTypeLength * typeCount <= (this.bigTiff ? 8 : 4)) {\n fieldValues = getValues(dataSlice, fieldType, typeCount, valueOffset);\n } else {\n // resolve the reference to the actual byte range\n const actualOffset = dataSlice.readOffset(valueOffset);\n const length = getFieldTypeLength(fieldType) * typeCount;\n\n // check, whether we actually cover the referenced byte range; if not,\n // request a new slice of bytes to read from it\n if (dataSlice.covers(actualOffset, length)) {\n fieldValues = getValues(dataSlice, fieldType, typeCount, actualOffset);\n } else {\n const fieldDataSlice = await this.getSlice(actualOffset, length);\n fieldValues = getValues(fieldDataSlice, fieldType, typeCount, actualOffset);\n }\n }\n\n // unpack single values from the array\n if (typeCount === 1 && arrayFields.indexOf(fieldTag) === -1 &&\n !(fieldType === fieldTypes.RATIONAL || fieldType === fieldTypes.SRATIONAL)) {\n value = fieldValues[0];\n } else {\n value = fieldValues;\n }\n\n // write the tags value to the file directly\n fileDirectory[fieldTagNames[fieldTag]] = value;\n }\n const geoKeyDirectory = parseGeoKeyDirectory(fileDirectory);\n const nextIFDByteOffset = dataSlice.readOffset(\n offset + offsetSize + (entrySize * numDirEntries),\n );\n\n return new ImageFileDirectory(\n fileDirectory,\n geoKeyDirectory,\n nextIFDByteOffset,\n );\n }\n\n async requestIFD(index) {\n // see if we already have that IFD index requested.\n if (this.ifdRequests[index]) {\n // attach to an already requested IFD\n return this.ifdRequests[index];\n } else if (index === 0) {\n // special case for index 0\n this.ifdRequests[index] = this.parseFileDirectoryAt(this.firstIFDOffset);\n return this.ifdRequests[index];\n } else if (!this.ifdRequests[index - 1]) {\n // if the previous IFD was not yet loaded, load that one first\n // this is the recursive call.\n try {\n this.ifdRequests[index - 1] = this.requestIFD(index - 1);\n } catch (e) {\n // if the previous one already was an index error, rethrow\n // with the current index\n if (e instanceof GeoTIFFImageIndexError) {\n throw new GeoTIFFImageIndexError(index);\n }\n // rethrow anything else\n throw e;\n }\n }\n // if the previous IFD was loaded, we can finally fetch the one we are interested in.\n // we need to wrap this in an IIFE, otherwise this.ifdRequests[index] would be delayed\n this.ifdRequests[index] = (async () => {\n const previousIfd = await this.ifdRequests[index - 1];\n if (previousIfd.nextIFDByteOffset === 0) {\n throw new GeoTIFFImageIndexError(index);\n }\n return this.parseFileDirectoryAt(previousIfd.nextIFDByteOffset);\n })();\n return this.ifdRequests[index];\n }\n\n /**\n * Get the n-th internal subfile of an image. By default, the first is returned.\n *\n * @param {Number} [index=0] the index of the image to return.\n * @returns {GeoTIFFImage} the image at the given index\n */\n async getImage(index = 0) {\n const ifd = await this.requestIFD(index);\n return new GeoTIFFImage(\n ifd.fileDirectory, ifd.geoKeyDirectory,\n this.dataView, this.littleEndian, this.cache, this.source,\n );\n }\n\n /**\n * Returns the count of the internal subfiles.\n *\n * @returns {Number} the number of internal subfile images\n */\n async getImageCount() {\n let index = 0;\n // loop until we run out of IFDs\n let hasNext = true;\n while (hasNext) {\n try {\n await this.requestIFD(index);\n ++index;\n } catch (e) {\n if (e instanceof GeoTIFFImageIndexError) {\n hasNext = false;\n } else {\n throw e;\n }\n }\n }\n return index;\n }\n\n /**\n * Get the values of the COG ghost area as a parsed map.\n * See https://gdal.org/drivers/raster/cog.html#header-ghost-area for reference\n * @returns {Object} the parsed ghost area or null, if no such area was found\n */\n async getGhostValues() {\n const offset = this.bigTiff ? 16 : 8;\n if (this.ghostValues) {\n return this.ghostValues;\n }\n const detectionString = 'GDAL_STRUCTURAL_METADATA_SIZE=';\n const heuristicAreaSize = detectionString.length + 100;\n let slice = await this.getSlice(offset, heuristicAreaSize);\n if (detectionString === getValues(slice, fieldTypes.ASCII, detectionString.length, offset)) {\n const valuesString = getValues(slice, fieldTypes.ASCII, heuristicAreaSize, offset);\n const firstLine = valuesString.split('\\n')[0];\n const metadataSize = Number(firstLine.split('=')[1].split(' ')[0]) + firstLine.length;\n if (metadataSize > heuristicAreaSize) {\n slice = await this.getSlice(offset, metadataSize);\n }\n const fullString = getValues(slice, fieldTypes.ASCII, metadataSize, offset);\n this.ghostValues = {};\n fullString\n .split('\\n')\n .filter(line => line.length > 0)\n .map(line => line.split('='))\n .forEach(([key, value]) => {\n this.ghostValues[key] = value;\n });\n }\n return this.ghostValues;\n }\n\n /**\n * Parse a (Geo)TIFF file from the given source.\n *\n * @param {source~Source} source The source of data to parse from.\n * @param {object} options Additional options.\n * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n */\n static async fromSource(source, options, signal) {\n const headerData = (await source.fetch([{ offset: 0, length: 1024 }], signal))[0];\n const dataView = new DataView64(headerData);\n\n const BOM = dataView.getUint16(0, 0);\n let littleEndian;\n if (BOM === 0x4949) {\n littleEndian = true;\n } else if (BOM === 0x4D4D) {\n littleEndian = false;\n } else {\n throw new TypeError('Invalid byte order value.');\n }\n\n const magicNumber = dataView.getUint16(2, littleEndian);\n let bigTiff;\n if (magicNumber === 42) {\n bigTiff = false;\n } else if (magicNumber === 43) {\n bigTiff = true;\n const offsetByteSize = dataView.getUint16(4, littleEndian);\n if (offsetByteSize !== 8) {\n throw new Error('Unsupported offset byte-size.');\n }\n } else {\n throw new TypeError('Invalid magic number.');\n }\n\n const firstIFDOffset = bigTiff\n ? dataView.getUint64(8, littleEndian)\n : dataView.getUint32(4, littleEndian);\n return new GeoTIFF(source, littleEndian, bigTiff, firstIFDOffset, options);\n }\n\n /**\n * Closes the underlying file buffer\n * N.B. After the GeoTIFF has been completely processed it needs\n * to be closed but only if it has been constructed from a file.\n */\n close() {\n if (typeof this.source.close === 'function') {\n return this.source.close();\n }\n return false;\n }\n}\n\nexport { GeoTIFF };\nexport default GeoTIFF;\n\n/**\n * Wrapper for GeoTIFF files that have external overviews.\n * @augments GeoTIFFBase\n */\nclass MultiGeoTIFF extends GeoTIFFBase {\n /**\n * Construct a new MultiGeoTIFF from a main and several overview files.\n * @param {GeoTIFF} mainFile The main GeoTIFF file.\n * @param {GeoTIFF[]} overviewFiles An array of overview files.\n */\n constructor(mainFile, overviewFiles) {\n super();\n this.mainFile = mainFile;\n this.overviewFiles = overviewFiles;\n this.imageFiles = [mainFile].concat(overviewFiles);\n\n this.fileDirectoriesPerFile = null;\n this.fileDirectoriesPerFileParsing = null;\n this.imageCount = null;\n }\n\n async parseFileDirectoriesPerFile() {\n const requests = [this.mainFile.parseFileDirectoryAt(this.mainFile.firstIFDOffset)]\n .concat(this.overviewFiles.map((file) => file.parseFileDirectoryAt(file.firstIFDOffset)));\n\n this.fileDirectoriesPerFile = await Promise.all(requests);\n return this.fileDirectoriesPerFile;\n }\n\n /**\n * Get the n-th internal subfile of an image. By default, the first is returned.\n *\n * @param {Number} [index=0] the index of the image to return.\n * @returns {GeoTIFFImage} the image at the given index\n */\n async getImage(index = 0) {\n await this.getImageCount();\n await this.parseFileDirectoriesPerFile();\n let visited = 0;\n let relativeIndex = 0;\n for (let i = 0; i < this.imageFiles.length; i++) {\n const imageFile = this.imageFiles[i];\n for (let ii = 0; ii < this.imageCounts[i]; ii++) {\n if (index === visited) {\n const ifd = await imageFile.requestIFD(relativeIndex);\n return new GeoTIFFImage(\n ifd.fileDirectory, ifd.geoKeyDirectory,\n imageFile.dataView, imageFile.littleEndian, imageFile.cache, imageFile.source,\n );\n }\n visited++;\n relativeIndex++;\n }\n relativeIndex = 0;\n }\n\n throw new RangeError('Invalid image index');\n }\n\n /**\n * Returns the count of the internal subfiles.\n *\n * @returns {Number} the number of internal subfile images\n */\n async getImageCount() {\n if (this.imageCount !== null) {\n return this.imageCount;\n }\n const requests = [this.mainFile.getImageCount()]\n .concat(this.overviewFiles.map((file) => file.getImageCount()));\n this.imageCounts = await Promise.all(requests);\n this.imageCount = this.imageCounts.reduce((count, ifds) => count + ifds, 0);\n return this.imageCount;\n }\n}\n\nexport { MultiGeoTIFF };\n\n/**\n * Creates a new GeoTIFF from a remote URL.\n * @param {string} url The URL to access the image from\n * @param {object} [options] Additional options to pass to the source.\n * See {@link makeRemoteSource} for details.\n * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @returns {Promise.} The resulting GeoTIFF file.\n */\nexport async function fromUrl(url, options = {}, signal) {\n return GeoTIFF.fromSource(makeRemoteSource(url, options), signal);\n}\n\n/**\n * Construct a new GeoTIFF from an\n * [ArrayBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer}.\n * @param {ArrayBuffer} arrayBuffer The data to read the file from.\n * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @returns {Promise.} The resulting GeoTIFF file.\n */\nexport async function fromArrayBuffer(arrayBuffer, signal) {\n return GeoTIFF.fromSource(makeBufferSource(arrayBuffer), signal);\n}\n\n/**\n * Construct a GeoTIFF from a local file path. This uses the node\n * [filesystem API]{@link https://nodejs.org/api/fs.html} and is\n * not available on browsers.\n *\n * N.B. After the GeoTIFF has been completely processed it needs\n * to be closed but only if it has been constructed from a file.\n * @param {string} path The file path to read from.\n * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @returns {Promise.} The resulting GeoTIFF file.\n */\nexport async function fromFile(path, signal) {\n return GeoTIFF.fromSource(makeFileSource(path), signal);\n}\n\n/**\n * Construct a GeoTIFF from an HTML\n * [Blob]{@link https://developer.mozilla.org/en-US/docs/Web/API/Blob} or\n * [File]{@link https://developer.mozilla.org/en-US/docs/Web/API/File}\n * object.\n * @param {Blob|File} blob The Blob or File object to read from.\n * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @returns {Promise.} The resulting GeoTIFF file.\n */\nexport async function fromBlob(blob, signal) {\n return GeoTIFF.fromSource(makeFileReaderSource(blob), signal);\n}\n\n/**\n * Construct a MultiGeoTIFF from the given URLs.\n * @param {string} mainUrl The URL for the main file.\n * @param {string[]} overviewUrls An array of URLs for the overview images.\n * @param {object} [options] Additional options to pass to the source.\n * See [makeRemoteSource]{@link module:source.makeRemoteSource}\n * for details.\n * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is\n * to be aborted\n * @returns {Promise.} The resulting MultiGeoTIFF file.\n */\nexport async function fromUrls(mainUrl, overviewUrls = [], options = {}, signal) {\n const mainFile = await GeoTIFF.fromSource(makeRemoteSource(mainUrl, options), signal);\n const overviewFiles = await Promise.all(\n overviewUrls.map((url) => GeoTIFF.fromSource(makeRemoteSource(url, options))),\n );\n\n return new MultiGeoTIFF(mainFile, overviewFiles);\n}\n\n/**\n * Main creating function for GeoTIFF files.\n * @param {(Array)} array of pixel values\n * @returns {metadata} metadata\n */\nexport async function writeArrayBuffer(values, metadata) {\n return writeGeotiff(values, metadata);\n}\n\nexport { Pool };\n","import { COORDINATE_SYSTEM, Layer, project32, picking, CompositeLayer, LayerExtension, OrthographicView, Controller, OrbitView } from '@deck.gl/core';\nimport { Matrix4 } from 'math.gl';\nimport GL from '@luma.gl/constants';\nimport { TileLayer } from '@deck.gl/geo-layers';\nimport { Model, Geometry, Texture2D, isWebGL2, Texture3D } from '@luma.gl/core';\nimport { ProgramManager } from '@luma.gl/engine';\nimport { hasFeature, FEATURES } from '@luma.gl/webgl';\nimport { BitmapLayer as BitmapLayer$1, PolygonLayer, LineLayer, TextLayer } from '@deck.gl/layers';\nimport quickselect from 'quickselect';\nimport { Plane } from '@math.gl/culling';\nimport { PureComponent, useMemo } from 'react';\nimport DeckGL from '@deck.gl/react';\nimport equal from 'fast-deep-equal';\nimport { jsxDEV } from 'react/jsx-dev-runtime';\nimport { fromUrl, fromBlob } from 'geotiff';\nimport parser from 'fast-xml-parser';\nimport { KeyError, openGroup, BoundsCheckError, slice, HTTPStore } from 'zarr';\n\nvar fs$6 = \"#define SHADER_NAME xr-layer-fragment-shader\\nprecision highp float;precision highp int;precision highp SAMPLER_TYPE;\\n#define GLSLIFY 1\\nuniform SAMPLER_TYPE channel0;uniform SAMPLER_TYPE channel1;uniform SAMPLER_TYPE channel2;uniform SAMPLER_TYPE channel3;uniform SAMPLER_TYPE channel4;uniform SAMPLER_TYPE channel5;in vec2 vTexCoord;uniform vec2 contrastLimits[6];void main(){float intensity0=float(texture(channel0,vTexCoord).r);DECKGL_PROCESS_INTENSITY(intensity0,contrastLimits[0],0);float intensity1=float(texture(channel1,vTexCoord).r);DECKGL_PROCESS_INTENSITY(intensity1,contrastLimits[1],1);float intensity2=float(texture(channel2,vTexCoord).r);DECKGL_PROCESS_INTENSITY(intensity2,contrastLimits[2],2);float intensity3=float(texture(channel3,vTexCoord).r);DECKGL_PROCESS_INTENSITY(intensity3,contrastLimits[3],3);float intensity4=float(texture(channel4,vTexCoord).r);DECKGL_PROCESS_INTENSITY(intensity4,contrastLimits[4],4);float intensity5=float(texture(channel5,vTexCoord).r);DECKGL_PROCESS_INTENSITY(intensity5,contrastLimits[5],5);DECKGL_MUTATE_COLOR(gl_FragColor,intensity0,intensity1,intensity2,intensity3,intensity4,intensity5,vTexCoord);geometry.uv=vTexCoord;DECKGL_FILTER_COLOR(gl_FragColor,geometry);}\"; // eslint-disable-line\n\nvar vs$1 = \"#define GLSLIFY 1\\n#define SHADER_NAME xr-layer-vertex-shader\\nattribute vec2 texCoords;attribute vec3 positions;attribute vec3 positions64Low;attribute vec3 instancePickingColors;varying vec2 vTexCoord;void main(void){geometry.worldPosition=positions;geometry.uv=texCoords;geometry.pickingColor=instancePickingColors;gl_Position=project_position_to_clipspace(positions,positions64Low,vec3(0.),geometry.position);DECKGL_FILTER_GL_POSITION(gl_Position,geometry);vTexCoord=texCoords;vec4 color=vec4(0.);DECKGL_FILTER_COLOR(color,geometry);}\"; // eslint-disable-line\n\nvar fs$5 = \"#define GLSLIFY 1\\nfloat apply_contrast_limits(float intensity,vec2 contrastLimits){return max(0.,(intensity-contrastLimits[0])/max(0.0005,(contrastLimits[1]-contrastLimits[0])));}\"; // eslint-disable-line\n\nvar channels$1 = {\n name: 'channel-intensity-module',\n defines: {\n SAMPLER_TYPE: 'usampler2D',\n COLORMAP_FUNCTION: ''\n },\n fs: fs$5\n};\n\nconst MAX_COLOR_INTENSITY = 255;\nconst DEFAULT_COLOR_OFF = [0, 0, 0];\nconst MAX_CHANNELS = 6;\nconst DEFAULT_FONT_FAMILY = \"-apple-system, 'Helvetica Neue', Arial, sans-serif\";\nconst DTYPE_VALUES = {\n Uint8: {\n format: GL.R8UI,\n dataFormat: GL.RED_INTEGER,\n type: GL.UNSIGNED_BYTE,\n max: 2 ** 8 - 1,\n sampler: \"usampler2D\"\n },\n Uint16: {\n format: GL.R16UI,\n dataFormat: GL.RED_INTEGER,\n type: GL.UNSIGNED_SHORT,\n max: 2 ** 16 - 1,\n sampler: \"usampler2D\"\n },\n Uint32: {\n format: GL.R32UI,\n dataFormat: GL.RED_INTEGER,\n type: GL.UNSIGNED_INT,\n max: 2 ** 32 - 1,\n sampler: \"usampler2D\"\n },\n Float32: {\n format: GL.R32F,\n dataFormat: GL.RED,\n type: GL.FLOAT,\n max: 3.4 * 10 ** 38,\n sampler: \"sampler2D\"\n },\n Int8: {\n format: GL.R8I,\n dataFormat: GL.RED_INTEGER,\n type: GL.BYTE,\n max: 2 ** (8 - 1) - 1,\n sampler: \"isampler2D\"\n },\n Int16: {\n format: GL.R16I,\n dataFormat: GL.RED_INTEGER,\n type: GL.SHORT,\n max: 2 ** (16 - 1) - 1,\n sampler: \"isampler2D\"\n },\n Int32: {\n format: GL.R32I,\n dataFormat: GL.RED_INTEGER,\n type: GL.INT,\n max: 2 ** (32 - 1) - 1,\n sampler: \"isampler2D\"\n },\n Float64: {\n format: GL.R32F,\n dataFormat: GL.RED,\n type: GL.FLOAT,\n max: 3.4 * 10 ** 38,\n sampler: \"sampler2D\",\n cast: (data) => new Float32Array(data)\n }\n};\nconst COLORMAPS = [\"jet\", \"hsv\", \"hot\", \"cool\", \"spring\", \"summer\", \"autumn\", \"winter\", \"bone\", \"copper\", \"greys\", \"yignbu\", \"greens\", \"yiorrd\", \"bluered\", \"rdbu\", \"picnic\", \"rainbow\", \"portland\", \"blackbody\", \"earth\", \"electric\", \"alpha\", \"viridis\", \"inferno\", \"magma\", \"plasma\", \"warm\", \"rainbow-soft\", \"bathymetry\", \"cdom\", \"chlorophyll\", \"density\", \"freesurface-blue\", \"freesurface-red\", \"oxygen\", \"par\", \"phase\", \"salinity\", \"temperature\", \"turbidity\", \"velocity-blue\", \"velocity-green\", \"cubehelix\"];\nvar RENDERING_MODES;\n(function(RENDERING_MODES2) {\n RENDERING_MODES2[\"MAX_INTENSITY_PROJECTION\"] = \"Maximum Intensity Projection\";\n RENDERING_MODES2[\"MIN_INTENSITY_PROJECTION\"] = \"Minimum Intensity Projection\";\n RENDERING_MODES2[\"ADDITIVE\"] = \"Additive\";\n})(RENDERING_MODES || (RENDERING_MODES = {}));\n\nfunction range(len) {\n return [...Array(len).keys()];\n}\nfunction padWithDefault(arr, defaultValue, padWidth) {\n for (let i = 0; i < padWidth; i += 1) {\n arr.push(defaultValue);\n }\n\n return arr;\n}\n/**\n * (Safely) get GL values for associated dtype.\n * @param {keyof typeof import('../constants').DTYPE_VALUES} dtype\n */\n\nfunction getDtypeValues(dtype) {\n const values = DTYPE_VALUES[dtype];\n\n if (!values) {\n const valid = Object.keys(DTYPE_VALUES);\n throw Error(`Dtype not supported, got ${dtype}. Must be one of ${valid}.`);\n }\n\n return values;\n}\nfunction padContrastLimits({\n contrastLimits = [],\n channelsVisible,\n domain,\n dtype\n}) {\n const maxSliderValue = domain && domain[1] || getDtypeValues(dtype).max;\n const newContrastLimits = contrastLimits.map((slider, i) => channelsVisible[i] ? slider : [maxSliderValue, maxSliderValue]); // Need to pad contrastLimits and colors with default values (required by shader)\n\n const padSize = MAX_CHANNELS - newContrastLimits.length;\n\n if (padSize < 0) {\n throw Error(`${newContrastLimits.lengths} channels passed in, but only 6 are allowed.`);\n }\n\n const paddedContrastLimits = padWithDefault(newContrastLimits, [maxSliderValue, maxSliderValue], padSize).reduce((acc, val) => acc.concat(val), []);\n return paddedContrastLimits;\n}\n/**\n * Get physical size scaling Matrix4\n * @param {Object} loader PixelSource\n */\n\nfunction getPhysicalSizeScalingMatrix(loader) {\n const {\n x,\n y,\n z\n } = loader?.meta?.physicalSizes ?? {};\n\n if (x?.size && y?.size && z?.size) {\n const min = Math.min(z.size, x.size, y.size);\n const ratio = [x.size / min, y.size / min, z.size / min];\n return new Matrix4().scale(ratio);\n }\n\n return new Matrix4().identity();\n}\n\n/* eslint-disable prefer-destructuring */\nconst coreShaderModule = {\n fs: fs$6,\n vs: vs$1\n};\n\nfunction validateWebGL2Filter(gl, interpolation) {\n const canShowFloat = hasFeature(gl, FEATURES.TEXTURE_FLOAT);\n const canShowLinear = hasFeature(gl, FEATURES.TEXTURE_FILTER_LINEAR_FLOAT);\n\n if (!canShowFloat) {\n throw new Error('WebGL1 context does not support floating point textures. Unable to display raster data.');\n }\n\n if (!canShowLinear && interpolation === GL.LINEAR) {\n console.warn('LINEAR filtering not supported in WebGL1 context. Falling back to NEAREST.');\n return GL.NEAREST;\n }\n\n return interpolation;\n}\n\nfunction getRenderingAttrs$1(dtype, gl, interpolation) {\n if (!isWebGL2(gl)) {\n return {\n format: GL.LUMINANCE,\n dataFormat: GL.LUMINANCE,\n type: GL.FLOAT,\n sampler: 'sampler2D',\n shaderModule: coreShaderModule,\n filter: validateWebGL2Filter(gl, interpolation),\n cast: data => new Float32Array(data)\n };\n } // Linear filtering only works when the data type is cast to Float32.\n\n\n const isLinear = interpolation === GL.LINEAR; // Need to add es version tag so that shaders work in WebGL2 since the tag is needed for using usampler2d with WebGL2.\n // Very cursed!\n\n const upgradedShaderModule = { ...coreShaderModule\n };\n const version300str = '#version 300 es\\n';\n upgradedShaderModule.fs = version300str.concat(upgradedShaderModule.fs);\n upgradedShaderModule.vs = version300str.concat(upgradedShaderModule.vs);\n const values = getDtypeValues(isLinear ? 'Float32' : dtype);\n return { ...values,\n shaderModule: upgradedShaderModule,\n filter: interpolation,\n cast: isLinear ? data => new Float32Array(data) : data => data\n };\n}\n\nconst defaultProps$b = {\n pickable: {\n type: 'boolean',\n value: true,\n compare: true\n },\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n channelData: {\n type: 'object',\n value: {},\n compare: true\n },\n bounds: {\n type: 'array',\n value: [0, 0, 1, 1],\n compare: true\n },\n contrastLimits: {\n type: 'array',\n value: [],\n compare: true\n },\n channelsVisible: {\n type: 'array',\n value: [],\n compare: true\n },\n dtype: {\n type: 'string',\n value: 'Uint16',\n compare: true\n },\n interpolation: {\n type: 'number',\n value: GL.NEAREST,\n compare: true\n }\n};\n/**\n * @typedef LayerProps\n * @type {object}\n * @property {Array.>} contrastLimits List of [begin, end] values to control each channel's ramp function.\n * @property {Array.} channelsVisible List of boolean values for each channel for whether or not it is visible.\n * @property {string} dtype Dtype for the layer.\n * @property {Array.=} domain Override for the possible max/min values (i.e something different than 65535 for uint16/'[]) }}\n * @ignore\n */\n\nconst XRLayer = class extends Layer {\n /**\n * This function replaces `usampler` with `sampler` if the data is not an unsigned integer\n * and adds a standard ramp function default for DECKGL_PROCESS_INTENSITY.\n */\n getShaders() {\n const {\n dtype,\n interpolation\n } = this.props;\n const {\n shaderModule,\n sampler\n } = getRenderingAttrs$1(dtype, this.context.gl, interpolation);\n\n const extensionDefinesDeckglProcessIntensity = this._isHookDefinedByExtensions('fs:DECKGL_PROCESS_INTENSITY');\n\n const newChannelsModule = { ...channels$1,\n inject: {}\n };\n\n if (!extensionDefinesDeckglProcessIntensity) {\n newChannelsModule.inject['fs:DECKGL_PROCESS_INTENSITY'] = `\n intensity = apply_contrast_limits(intensity, contrastLimits);\n `;\n }\n\n return super.getShaders({ ...shaderModule,\n defines: {\n SAMPLER_TYPE: sampler\n },\n modules: [project32, picking, newChannelsModule]\n });\n }\n\n _isHookDefinedByExtensions(hookName) {\n const {\n extensions\n } = this.props;\n return extensions?.some(e => {\n const shaders = e.getShaders();\n const {\n inject = {},\n modules = []\n } = shaders;\n const definesInjection = inject[hookName];\n const moduleDefinesInjection = modules.some(m => m?.inject[hookName]);\n return definesInjection || moduleDefinesInjection;\n });\n }\n /**\n * This function initializes the internal state.\n */\n\n\n initializeState() {\n const {\n gl\n } = this.context; // This tells WebGL how to read row data from the texture. For example, the default here is 4 (i.e for RGBA, one byte per channel) so\n // each row of data is expected to be a multiple of 4. This setting (i.e 1) allows us to have non-multiple-of-4 row sizes. For example, for 2 byte (16 bit data),\n // we could use 2 as the value and it would still work, but 1 also works fine (and is more flexible for 8 bit - 1 byte - textures as well).\n // https://stackoverflow.com/questions/42789896/webgl-error-arraybuffer-not-big-enough-for-request-in-case-of-gl-luminance\n\n gl.pixelStorei(GL.UNPACK_ALIGNMENT, 1);\n gl.pixelStorei(GL.PACK_ALIGNMENT, 1);\n const attributeManager = this.getAttributeManager();\n attributeManager.add({\n positions: {\n size: 3,\n type: GL.DOUBLE,\n fp64: this.use64bitPositions(),\n update: this.calculatePositions,\n noAlloc: true\n }\n });\n this.setState({\n numInstances: 1,\n positions: new Float64Array(12)\n });\n const programManager = ProgramManager.getDefaultProgramManager(gl);\n const mutateStr = 'fs:DECKGL_MUTATE_COLOR(inout vec4 rgba, float intensity0, float intensity1, float intensity2, float intensity3, float intensity4, float intensity5, vec2 vTexCoord)';\n const processStr = `fs:DECKGL_PROCESS_INTENSITY(inout float intensity, vec2 contrastLimits, int channelIndex)`; // Only initialize shader hook functions _once globally_\n // Since the program manager is shared across all layers, but many layers\n // might be created, this solves the performance issue of always adding new\n // hook functions.\n // See https://github.com/kylebarron/deck.gl-raster/blob/2eb91626f0836558f0be4cd201ea18980d7f7f2d/src/deckgl/raster-layer/raster-layer.js#L21-L40\n\n if (!programManager._hookFunctions.includes(mutateStr)) {\n programManager.addShaderHook(mutateStr);\n }\n\n if (!programManager._hookFunctions.includes(processStr)) {\n programManager.addShaderHook(processStr);\n }\n }\n /**\n * This function finalizes state by clearing all textures from the WebGL context\n */\n\n\n finalizeState() {\n super.finalizeState();\n\n if (this.state.textures) {\n Object.values(this.state.textures).forEach(tex => tex && tex.delete());\n }\n }\n /**\n * This function updates state by retriggering model creation (shader compilation and attribute binding)\n * and loading any textures that need be loading.\n */\n\n\n updateState({\n props,\n oldProps,\n changeFlags,\n ...rest\n }) {\n super.updateState({\n props,\n oldProps,\n changeFlags,\n ...rest\n }); // setup model first\n\n if (changeFlags.extensionsChanged || props.interpolation !== oldProps.interpolation) {\n const {\n gl\n } = this.context;\n\n if (this.state.model) {\n this.state.model.delete();\n }\n\n this.setState({\n model: this._getModel(gl)\n });\n this.getAttributeManager().invalidateAll();\n }\n\n if (props.channelData !== oldProps.channelData && props.channelData?.data !== oldProps.channelData?.data || props.interpolation !== oldProps.interpolation) {\n this.loadChannelTextures(props.channelData);\n }\n\n const attributeManager = this.getAttributeManager();\n\n if (props.bounds !== oldProps.bounds) {\n attributeManager.invalidate('positions');\n }\n }\n /**\n * This function creates the luma.gl model.\n */\n\n\n _getModel(gl) {\n if (!gl) {\n return null;\n }\n /*\n 0,0 --- 1,0\n | |\n 0,1 --- 1,1\n */\n\n\n return new Model(gl, { ...this.getShaders(),\n id: this.props.id,\n geometry: new Geometry({\n drawMode: GL.TRIANGLE_FAN,\n vertexCount: 4,\n attributes: {\n texCoords: new Float32Array([0, 1, 0, 0, 1, 0, 1, 1])\n }\n }),\n isInstanced: false\n });\n }\n /**\n * This function generates view positions for use as a vec3 in the shader\n */\n\n\n calculatePositions(attributes) {\n const {\n positions\n } = this.state;\n const {\n bounds\n } = this.props; // bounds as [minX, minY, maxX, maxY]\n\n /*\n (minX0, maxY3) ---- (maxX2, maxY3)\n | |\n | |\n | |\n (minX0, minY1) ---- (maxX2, minY1)\n */\n\n positions[0] = bounds[0];\n positions[1] = bounds[1];\n positions[2] = 0;\n positions[3] = bounds[0];\n positions[4] = bounds[3];\n positions[5] = 0;\n positions[6] = bounds[2];\n positions[7] = bounds[3];\n positions[8] = 0;\n positions[9] = bounds[2];\n positions[10] = bounds[1];\n positions[11] = 0; // eslint-disable-next-line no-param-reassign\n\n attributes.value = positions;\n }\n /**\n * This function runs the shaders and draws to the canvas\n */\n\n\n draw({\n uniforms\n }) {\n const {\n textures,\n model\n } = this.state;\n\n if (textures && model) {\n const {\n contrastLimits,\n domain,\n dtype,\n channelsVisible\n } = this.props; // Check number of textures not null.\n\n const numTextures = Object.values(textures).filter(t => t).length; // Slider values and color values can come in before textures since their data is async.\n // Thus we pad based on the number of textures bound.\n\n const paddedContrastLimits = padContrastLimits({\n contrastLimits: contrastLimits.slice(0, numTextures),\n channelsVisible: channelsVisible.slice(0, numTextures),\n domain,\n dtype\n });\n model.setUniforms({ ...uniforms,\n contrastLimits: paddedContrastLimits,\n ...textures\n }).draw();\n }\n }\n /**\n * This function loads all channel textures from incoming resolved promises/data from the loaders by calling `dataToTexture`\n */\n\n\n loadChannelTextures(channelData) {\n const textures = {\n channel0: null,\n channel1: null,\n channel2: null,\n channel3: null,\n channel4: null,\n channel5: null\n };\n\n if (this.state.textures) {\n Object.values(this.state.textures).forEach(tex => tex && tex.delete());\n }\n\n if (channelData && Object.keys(channelData).length > 0 && channelData.data) {\n channelData.data.forEach((d, i) => {\n textures[`channel${i}`] = this.dataToTexture(d, channelData.width, channelData.height);\n }, this);\n this.setState({\n textures\n });\n }\n }\n /**\n * This function creates textures from the data\n */\n\n\n dataToTexture(data, width, height) {\n const {\n interpolation\n } = this.props;\n const attrs = getRenderingAttrs$1(this.props.dtype, this.context.gl, interpolation);\n return new Texture2D(this.context.gl, {\n width,\n height,\n data: attrs.cast?.(data) ?? data,\n // we don't want or need mimaps\n mipmaps: false,\n parameters: {\n // NEAREST for integer data\n [GL.TEXTURE_MIN_FILTER]: attrs.filter,\n [GL.TEXTURE_MAG_FILTER]: attrs.filter,\n // CLAMP_TO_EDGE to remove tile artifacts\n [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE,\n [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE\n },\n format: attrs.format,\n dataFormat: attrs.dataFormat,\n type: attrs.type\n });\n }\n\n};\nXRLayer.layerName = 'XRLayer';\nXRLayer.defaultProps = defaultProps$b;\n\n// eslint-disable-next-line max-classes-per-file\nconst PHOTOMETRIC_INTERPRETATIONS = {\n WhiteIsZero: 0,\n BlackIsZero: 1,\n RGB: 2,\n Palette: 3,\n TransparencyMask: 4,\n CMYK: 5,\n YCbCr: 6,\n CIELab: 8,\n ICCLab: 9\n};\nconst defaultProps$a = { ...BitmapLayer$1.defaultProps,\n pickable: {\n type: 'boolean',\n value: true,\n compare: true\n },\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN\n};\n\nconst getPhotometricInterpretationShader = (photometricInterpretation, transparentColorInHook) => {\n const useTransparentColor = transparentColorInHook ? 'true' : 'false';\n const transparentColorVector = `vec3(${(transparentColorInHook || [0, 0, 0]).map(i => String(i / 255)).join(',')})`;\n\n switch (photometricInterpretation) {\n case PHOTOMETRIC_INTERPRETATIONS.RGB:\n return `color[3] = (${useTransparentColor} && (color.rgb == ${transparentColorVector})) ? 0.0 : color.a;`;\n\n case PHOTOMETRIC_INTERPRETATIONS.WhiteIsZero:\n return `\\\n float value = 1.0 - (color.r / 256.0);\n color = vec4(value, value, value, (${useTransparentColor} && vec3(value, value, value) == ${transparentColorVector}) ? 0.0 : color.a);\n `;\n\n case PHOTOMETRIC_INTERPRETATIONS.BlackIsZero:\n return `\\\n float value = (color.r / 256.0);\n color = vec4(value, value, value, (${useTransparentColor} && vec3(value, value, value) == ${transparentColorVector}) ? 0.0 : color.a);\n `;\n\n case PHOTOMETRIC_INTERPRETATIONS.YCbCr:\n // We need to use an epsilon because the conversion to RGB is not perfect.\n return `\\\n float y = color[0];\n float cb = color[1];\n float cr = color[2];\n color[0] = (y + (1.40200 * (cr - .5)));\n color[1] = (y - (0.34414 * (cb - .5)) - (0.71414 * (cr - .5)));\n color[2] = (y + (1.77200 * (cb - .5)));\n color[3] = (${useTransparentColor} && distance(color.rgb, ${transparentColorVector}) < 0.01) ? 0.0 : color.a;\n `;\n\n default:\n console.error('Unsupported photometric interpretation or none provided. No transformation will be done to image data');\n return '';\n }\n};\n\nconst getTransparentColor = photometricInterpretation => {\n switch (photometricInterpretation) {\n case PHOTOMETRIC_INTERPRETATIONS.RGB:\n return [0, 0, 0, 0];\n\n case PHOTOMETRIC_INTERPRETATIONS.WhiteIsZero:\n return [255, 255, 255, 0];\n\n case PHOTOMETRIC_INTERPRETATIONS.BlackIsZero:\n return [0, 0, 0, 0];\n\n case PHOTOMETRIC_INTERPRETATIONS.YCbCr:\n return [16, 128, 128, 0];\n\n default:\n console.error('Unsupported photometric interpretation or none provided. No transformation will be done to image data');\n return [0, 0, 0, 0];\n }\n};\n\nclass BitmapLayerWrapper extends BitmapLayer$1 {\n _getModel(gl) {\n const {\n photometricInterpretation,\n transparentColorInHook\n } = this.props; // This is a port to the GPU of a subset of https://github.com/geotiffjs/geotiff.js/blob/master/src/rgb.js\n // Safari was too slow doing this off of the GPU and it is noticably faster on other browsers as well.\n\n const photometricInterpretationShader = getPhotometricInterpretationShader(photometricInterpretation, transparentColorInHook);\n\n if (!gl) {\n return null;\n }\n /*\n 0,0 --- 1,0\n | |\n 0,1 --- 1,1\n */\n\n\n return new Model(gl, { ...this.getShaders(),\n id: this.props.id,\n geometry: new Geometry({\n drawMode: GL.TRIANGLES,\n vertexCount: 6\n }),\n isInstanced: false,\n inject: {\n 'fs:DECKGL_FILTER_COLOR': photometricInterpretationShader\n }\n });\n }\n\n}\n/**\n * @typedef LayerProps\n * @type {object}\n * @property {number=} opacity Opacity of the layer.\n * @property {function=} onClick Hook function from deck.gl to handle clicked-on objects.\n * @property {Object=} modelMatrix Math.gl Matrix4 object containing an affine transformation to be applied to the image.\n * @property {number=} photometricInterpretation One of WhiteIsZero BlackIsZero YCbCr or RGB (default)\n * @property {Array.=} transparentColor An RGB (0-255 range) color to be considered \"transparent\" if provided.\n * In other words, any fragment shader output equal transparentColor (before applying opacity) will have opacity 0.\n * This parameter only needs to be a truthy value when using colormaps because each colormap has its own transparent color that is calculated on the shader.\n * Thus setting this to a truthy value (with a colormap set) indicates that the shader should make that color transparent.\n * @property {String=} id Unique identifier for this layer.\n */\n\n/**\n * @type {{ new (...props: import('../types').Viv[]) }}\n * @ignore\n */\n\n\nconst BitmapLayer = class extends CompositeLayer {\n initializeState(args) {\n const {\n gl\n } = this.context; // This tells WebGL how to read row data from the texture. For example, the default here is 4 (i.e for RGBA, one byte per channel) so\n // each row of data is expected to be a multiple of 4. This setting (i.e 1) allows us to have non-multiple-of-4 row sizes. For example, for 2 byte (16 bit data),\n // we could use 2 as the value and it would still work, but 1 also works fine (and is more flexible for 8 bit - 1 byte - textures as well).\n // https://stackoverflow.com/questions/42789896/webgl-error-arraybuffer-not-big-enough-for-request-in-case-of-gl-luminance\n // This needs to be called here and not in the BitmapLayerWrapper because the `image` prop is converted to a texture outside of the layer, as controlled by the `image` type.\n // See: https://github.com/visgl/deck.gl/pull/5197\n\n gl.pixelStorei(GL.UNPACK_ALIGNMENT, 1);\n gl.pixelStorei(GL.PACK_ALIGNMENT, 1);\n super.initializeState(args);\n }\n\n renderLayers() {\n const {\n photometricInterpretation,\n transparentColor: transparentColorInHook\n } = this.props;\n const transparentColor = getTransparentColor(photometricInterpretation);\n return new BitmapLayerWrapper(this.props, {\n // transparentColor is a prop applied to the original image data by deck.gl's\n // BitmapLayer and needs to be in the original colorspace. It is used to determine\n // what color is \"transparent\" in the original color space (i.e what shows when opacity is 0).\n transparentColor,\n // This is our transparentColor props which needs to be applied in the hook that converts to the RGB space.\n transparentColorInHook,\n id: `${this.props.id}-wrapped`\n });\n }\n\n};\nBitmapLayer.layerName = 'BitmapLayer'; // From https://github.com/geotiffjs/geotiff.js/blob/8ef472f41b51d18074aece2300b6a8ad91a21ae1/src/globals.js#L202-L213\n\nBitmapLayer.PHOTOMETRIC_INTERPRETATIONS = PHOTOMETRIC_INTERPRETATIONS;\nBitmapLayer.defaultProps = { ...defaultProps$a,\n // We don't want this layer to bind the texture so the type should not be `image`.\n image: {\n type: 'object',\n value: {},\n compare: true\n },\n transparentColor: {\n type: 'array',\n value: [0, 0, 0],\n compare: true\n },\n photometricInterpretation: {\n type: 'number',\n value: 2,\n compare: true\n }\n};\nBitmapLayerWrapper.defaultProps = defaultProps$a;\nBitmapLayerWrapper.layerName = 'BitmapLayerWrapper';\n\nfunction getChannelStats(arr) {\n let len = arr.length;\n let min = Infinity;\n let max = -Infinity;\n let total = 0;\n while (len--) {\n if (arr[len] < min) {\n min = arr[len];\n }\n if (arr[len] > max) {\n max = arr[len];\n }\n total += arr[len];\n }\n const mean = total / arr.length;\n len = arr.length;\n let sumSquared = 0;\n while (len--) {\n sumSquared += (arr[len] - mean) ** 2;\n }\n const sd = (sumSquared / arr.length) ** 0.5;\n const mid = Math.floor(arr.length / 2);\n const firstQuartileLocation = Math.floor(arr.length / 4);\n const thirdQuartileLocation = 3 * Math.floor(arr.length / 4);\n quickselect(arr, mid);\n const median = arr[mid];\n quickselect(arr, firstQuartileLocation, 0, mid);\n const q1 = arr[firstQuartileLocation];\n quickselect(arr, thirdQuartileLocation, mid, arr.length - 1);\n const q3 = arr[thirdQuartileLocation];\n const cutoffArr = arr.filter((i) => i > 0);\n const cutoffPercentile = 5e-4;\n const topCutoffLocation = Math.floor(cutoffArr.length * (1 - cutoffPercentile));\n const bottomCutoffLocation = Math.floor(cutoffArr.length * cutoffPercentile);\n quickselect(cutoffArr, topCutoffLocation);\n quickselect(cutoffArr, bottomCutoffLocation, 0, topCutoffLocation);\n const contrastLimits = [cutoffArr[bottomCutoffLocation] || 0, cutoffArr[topCutoffLocation] || 0];\n return {\n mean,\n sd,\n q1,\n q3,\n median,\n domain: [min, max],\n contrastLimits\n };\n}\nfunction ensureArray(x) {\n return Array.isArray(x) ? x : [x];\n}\nfunction intToRgba(int) {\n if (!Number.isInteger(int)) {\n throw Error(\"Not an integer.\");\n }\n const buffer = new ArrayBuffer(4);\n const view = new DataView(buffer);\n view.setInt32(0, int, false);\n const bytes = new Uint8Array(buffer);\n return Array.from(bytes);\n}\nfunction isInterleaved(shape) {\n const lastDimSize = shape[shape.length - 1];\n return lastDimSize === 3 || lastDimSize === 4;\n}\nfunction getLabels(dimOrder) {\n return dimOrder.toLowerCase().split(\"\").reverse();\n}\nfunction getDims(labels) {\n const lookup = new Map(labels.map((name, i) => [name, i]));\n if (lookup.size !== labels.length) {\n throw Error(\"Labels must be unique, found duplicated label.\");\n }\n return (name) => {\n const index = lookup.get(name);\n if (index === void 0) {\n throw Error(\"Invalid dimension.\");\n }\n return index;\n };\n}\nfunction getImageSize(source) {\n const interleaved = isInterleaved(source.shape);\n const [height, width] = source.shape.slice(interleaved ? -3 : -2);\n return {\n height,\n width\n };\n}\nfunction prevPowerOf2(x) {\n return 2 ** Math.floor(Math.log2(x));\n}\nconst SIGNAL_ABORTED = \"__vivSignalAborted\";\n\nfunction renderSubLayers(props) {\n const {\n bbox: {\n left,\n top,\n right,\n bottom\n },\n x,\n y,\n z\n } = props.tile;\n const {\n data,\n id,\n loader,\n maxZoom\n } = props; // Only render in positive coorinate system\n\n if ([left, bottom, right, top].some(v => v < 0) || !data) {\n return null;\n }\n\n const base = loader[0];\n const {\n height,\n width\n } = getImageSize(base); // Tiles are exactly fitted to have height and width such that their bounds match that of the actual image (not some padded version).\n // Thus the right/bottom given by deck.gl are incorrect since they assume tiles are of uniform sizes, which is not the case for us.\n\n const bounds = [left, data.height < base.tileSize ? height : bottom, data.width < base.tileSize ? width : right, top];\n\n if (isInterleaved(base.shape)) {\n const {\n photometricInterpretation = 2\n } = base.meta;\n return new BitmapLayer(props, {\n image: data,\n photometricInterpretation,\n // Shared props with XRLayer:\n bounds,\n id: `tile-sub-layer-${bounds}-${id}`,\n tileId: {\n x,\n y,\n z\n }\n });\n }\n\n return new XRLayer(props, {\n channelData: data,\n // Uncomment to help debugging - shades the tile being hovered over.\n // autoHighlight: true,\n // highlightColor: [80, 80, 80, 50],\n // Shared props with BitmapLayer:\n bounds,\n id: `tile-sub-layer-${bounds}-${id}`,\n tileId: {\n x,\n y,\n z\n },\n // The auto setting is NEAREST at the highest resolution but LINEAR otherwise.\n interpolation: z === maxZoom ? GL.NEAREST : GL.LINEAR\n });\n}\n\nconst defaultProps$9 = {\n pickable: {\n type: 'boolean',\n value: true,\n compare: true\n },\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n contrastLimits: {\n type: 'array',\n value: [],\n compare: true\n },\n channelsVisible: {\n type: 'array',\n value: [],\n compare: true\n },\n renderSubLayers: {\n type: 'function',\n value: renderSubLayers,\n compare: false\n },\n dtype: {\n type: 'string',\n value: 'Uint16',\n compare: true\n },\n domain: {\n type: 'array',\n value: [],\n compare: true\n },\n viewportId: {\n type: 'string',\n value: '',\n compare: true\n },\n interpolation: {\n type: 'number',\n value: null,\n compare: true\n }\n};\n/**\n * This layer serves as a proxy of sorts to the rendering done in renderSubLayers, reacting to viewport changes in a custom manner.\n */\n\nclass MultiscaleImageLayerBase extends TileLayer {\n /**\n * This function allows us to controls which viewport gets to update the Tileset2D.\n * This is a uniquely TileLayer issue since it updates based on viewport updates thanks\n * to its ability to handle zoom-pan loading. Essentially, with a picture-in-picture,\n * this prevents it from detecting the update of some other viewport that is unwanted.\n */\n _updateTileset() {\n if (!this.props.viewportId) {\n super._updateTileset();\n }\n\n if (this.props.viewportId && this.context.viewport.id === this.props.viewportId || // I don't know why, but DeckGL doesn't recognize multiple views on the first pass\n // so we force update on the first pass by checking if there is a viewport in the tileset.\n !this.state.tileset._viewport) {\n super._updateTileset();\n }\n }\n\n}\nMultiscaleImageLayerBase.layerName = 'MultiscaleImageLayerBase';\nMultiscaleImageLayerBase.defaultProps = defaultProps$9;\n\nvar fs$4 = \"#define GLSLIFY 1\\nuniform float majorLensAxis;uniform float minorLensAxis;uniform vec2 lensCenter;uniform bool lensEnabled;uniform int lensSelection;uniform vec3 lensBorderColor;uniform float lensBorderRadius;uniform vec3 colors[6];bool frag_in_lens_bounds(vec2 vTexCoord){return pow((lensCenter.x-vTexCoord.x)/majorLensAxis,2.)+pow((lensCenter.y-vTexCoord.y)/minorLensAxis,2.)<(1.-lensBorderRadius);}bool frag_on_lens_bounds(vec2 vTexCoord){float ellipseDistance=pow((lensCenter.x-vTexCoord.x)/majorLensAxis,2.)+pow((lensCenter.y-vTexCoord.y)/minorLensAxis,2.);return ellipseDistance<=1.&&ellipseDistance>=(1.-lensBorderRadius);}float get_use_color_float(vec2 vTexCoord,int channelIndex){bool isFragInLensBounds=frag_in_lens_bounds(vTexCoord);bool inLensAndUseLens=lensEnabled&&isFragInLensBounds;return float(int((inLensAndUseLens&&channelIndex==lensSelection)||(!inLensAndUseLens)));}void mutate_color(inout vec3 rgb,float intensity0,float intensity1,float intensity2,float intensity3,float intensity4,float intensity5,vec2 vTexCoord){float useColorValue=0.;useColorValue=get_use_color_float(vTexCoord,0);rgb+=max(0.,min(1.,intensity0))*max(vec3(colors[0]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,1);rgb+=max(0.,min(1.,intensity1))*max(vec3(colors[1]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,2);rgb+=max(0.,min(1.,intensity2))*max(vec3(colors[2]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,3);rgb+=max(0.,min(1.,intensity3))*max(vec3(colors[3]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,4);rgb+=max(0.,min(1.,intensity4))*max(vec3(colors[4]),(1.-useColorValue)*vec3(1.,1.,1.));useColorValue=get_use_color_float(vTexCoord,5);rgb+=max(0.,min(1.,intensity5))*max(vec3(colors[5]),(1.-useColorValue)*vec3(1.,1.,1.));}\"; // eslint-disable-line\n\nvar lens = {\n name: 'lens-module',\n fs: fs$4,\n inject: {\n 'fs:DECKGL_MUTATE_COLOR': `\n vec3 rgb = rgba.rgb;\n mutate_color(rgb, intensity0, intensity1, intensity2, intensity3, intensity4, intensity5, vTexCoord);\n rgba = vec4(rgb, 1.);\n `,\n 'fs:#main-end': `\n bool isFragOnLensBounds = frag_on_lens_bounds(vTexCoord);\n gl_FragColor = (lensEnabled && isFragOnLensBounds) ? vec4(lensBorderColor, 1.) : gl_FragColor;\n `\n }\n};\n\nconst COLOR_PALETTE = [[0, 0, 255], // blue\n[0, 255, 0], // green\n[255, 0, 255], // magenta\n[255, 255, 0], // yellow\n[255, 128, 0], // orange\n[0, 255, 255], // cyan\n[255, 255, 255], // white\n[255, 0, 0] // red\n];\nfunction getDefaultPalette(n) {\n if (n > COLOR_PALETTE.length) {\n throw new Error('Too many colors');\n }\n\n return COLOR_PALETTE.slice(0, n);\n}\nfunction padColors({\n colors,\n channelsVisible\n}) {\n const newColors = colors.map((color, i) => channelsVisible[i] ? color.map(c => c / MAX_COLOR_INTENSITY) : DEFAULT_COLOR_OFF);\n const padSize = MAX_CHANNELS - newColors.length;\n const paddedColors = padWithDefault(newColors, DEFAULT_COLOR_OFF, padSize).reduce((acc, val) => acc.concat(val), []);\n return paddedColors;\n}\n\nconst defaultProps$8 = {\n lensEnabled: {\n type: 'boolean',\n value: false,\n compare: true\n },\n lensSelection: {\n type: 'number',\n value: 0,\n compare: true\n },\n lensRadius: {\n type: 'number',\n value: 100,\n compare: true\n },\n lensBorderColor: {\n type: 'array',\n value: [255, 255, 255],\n compare: true\n },\n lensBorderRadius: {\n type: 'number',\n value: 0.02,\n compare: true\n },\n colors: {\n type: 'array',\n value: null,\n compare: true\n }\n};\n/**\n * This deck.gl extension allows for a lens that selectively shows one channel in its chosen color and then the others in white.\n * @typedef LayerProps\n * @type {Object}\n * @property {boolean=} lensEnabled Whether or not to use the lens.\n * @property {number=} lensSelection Numeric index of the channel to be focused on by the lens.\n * @property {number=} lensRadius Pixel radius of the lens (default: 100).\n * @property {Array.=} lensBorderColor RGB color of the border of the lens (default [255, 255, 255]).\n * @property {number=} lensBorderRadius Percentage of the radius of the lens for a border (default 0.02).\n * @property {Array>=} colors Color palette to pseudo-color channels as.\n * */\n\nconst LensExtension = class extends LayerExtension {\n getShaders() {\n return { ...super.getShaders(),\n modules: [lens]\n };\n }\n\n initializeState() {\n const layer = this.getCurrentLayer(); // No need to run this on layers that don't have a `draw` call.\n\n if (layer.isComposite) {\n return;\n }\n\n const onMouseMove = () => {\n const {\n viewportId\n } = layer.props;\n const {\n lensRadius = defaultProps$8.lensRadius.value\n } = this.props; // If there is no viewportId, don't try to do anything.\n\n if (!viewportId) {\n layer.setState({\n unprojectLensBounds: [0, 0, 0, 0]\n });\n return;\n }\n\n const {\n mousePosition\n } = layer.context;\n const layerView = layer.context.deck.viewManager.views.filter(view => view.id === viewportId)[0];\n const viewState = layer.context.deck.viewManager.viewState[viewportId];\n const viewport = layerView.makeViewport({ ...viewState,\n viewState\n }); // If the mouse is in the viewport and the mousePosition exists, set\n // the state with the bounding box of the circle that will render as a lens.\n\n if (mousePosition && viewport.containsPixel(mousePosition)) {\n const offsetMousePosition = {\n x: mousePosition.x - viewport.x,\n y: mousePosition.y - viewport.y\n };\n const mousePositionBounds = [// left\n [offsetMousePosition.x - lensRadius, offsetMousePosition.y], // bottom\n [offsetMousePosition.x, offsetMousePosition.y + lensRadius], // right\n [offsetMousePosition.x + lensRadius, offsetMousePosition.y], // top\n [offsetMousePosition.x, offsetMousePosition.y - lensRadius]]; // Unproject from screen to world coordinates.\n\n const unprojectLensBounds = mousePositionBounds.map((bounds, i) => viewport.unproject(bounds)[i % 2]);\n layer.setState({\n unprojectLensBounds\n });\n } else {\n layer.setState({\n unprojectLensBounds: [0, 0, 0, 0]\n });\n }\n };\n\n if (this.context.deck) {\n this.context.deck.eventManager.on({\n pointermove: onMouseMove,\n pointerleave: onMouseMove,\n wheel: onMouseMove\n });\n }\n\n this.setState({\n onMouseMove,\n unprojectLensBounds: [0, 0, 0, 0]\n });\n }\n\n draw() {\n const {\n unprojectLensBounds = [0, 0, 0, 0]\n } = this.state;\n const {\n bounds,\n lensEnabled = defaultProps$8.lensEnabled.value,\n lensSelection = defaultProps$8.lensSelection.value,\n lensBorderColor = defaultProps$8.lensBorderColor.value,\n lensBorderRadius = defaultProps$8.lensBorderRadius.value,\n colors,\n channelsVisible\n } = this.props; // Creating a unit-square scaled intersection box for rendering the lens.\n // It is ok if these coordinates are outside the unit square since\n // we check membership in or out of the lens on the fragment shader.\n\n const [leftMouseBound, bottomMouseBound, rightMouseBound, topMouseBound] = unprojectLensBounds;\n const [left, bottom, right, top] = bounds;\n const leftMouseBoundScaled = (leftMouseBound - left) / (right - left);\n const bottomMouseBoundScaled = (bottomMouseBound - top) / (bottom - top);\n const rightMouseBoundScaled = (rightMouseBound - left) / (right - left);\n const topMouseBoundScaled = (topMouseBound - top) / (bottom - top);\n const paddedColors = padColors({\n channelsVisible: channelsVisible || this.selections.map(() => true),\n colors: colors || getDefaultPalette(this.props.selections.length)\n });\n const uniforms = {\n majorLensAxis: (rightMouseBoundScaled - leftMouseBoundScaled) / 2,\n minorLensAxis: (bottomMouseBoundScaled - topMouseBoundScaled) / 2,\n lensCenter: [(rightMouseBoundScaled + leftMouseBoundScaled) / 2, (bottomMouseBoundScaled + topMouseBoundScaled) / 2],\n lensEnabled,\n lensSelection,\n lensBorderColor,\n lensBorderRadius,\n colors: paddedColors\n }; // eslint-disable-next-line no-unused-expressions\n\n this.state.model?.setUniforms(uniforms);\n }\n\n finalizeState() {\n // Remove event listeners\n if (this.context.deck) {\n this.context.deck.eventManager.off({\n pointermove: this.state?.onMouseMove,\n pointerleave: this.state?.onMouseMove,\n wheel: this.state?.onMouseMove\n });\n }\n }\n\n};\nLensExtension.extensionName = 'LensExtension';\nLensExtension.defaultProps = defaultProps$8;\n\nvar fs$3 = \"#define GLSLIFY 1\\nvec4 apply_transparent_color_1540259130(vec3 color,vec3 transparentColor,bool useTransparentColor,float opacity){return vec4(color,(color==transparentColor&&useTransparentColor)? 0. : opacity);}uniform vec3 transparentColor;uniform bool useTransparentColor;uniform float opacity;uniform vec3 colors[6];void mutate_color(inout vec3 rgb,float intensity0,float intensity1,float intensity2,float intensity3,float intensity4,float intensity5){rgb+=max(0.0,min(1.0,intensity0))*vec3(colors[0]);rgb+=max(0.0,min(1.0,intensity1))*vec3(colors[1]);rgb+=max(0.0,min(1.0,intensity2))*vec3(colors[2]);rgb+=max(0.0,min(1.0,intensity3))*vec3(colors[3]);rgb+=max(0.0,min(1.0,intensity4))*vec3(colors[4]);rgb+=max(0.0,min(1.0,intensity5))*vec3(colors[5]);}vec4 apply_opacity(vec3 rgb){return vec4(apply_transparent_color_1540259130(rgb,transparentColor,useTransparentColor,opacity));}\"; // eslint-disable-line\n\nvar colorPalette = {\n name: 'color-palette-module',\n fs: fs$3,\n inject: {\n 'fs:DECKGL_MUTATE_COLOR': `\n vec3 rgb = rgba.rgb;\n mutate_color(rgb, intensity0, intensity1, intensity2, intensity3, intensity4, intensity5);\n rgba = apply_opacity(rgb);\n `\n }\n};\n\nconst defaultProps$7 = {\n colors: {\n type: 'array',\n value: null,\n compare: true\n },\n opacity: {\n type: 'number',\n value: 1.0,\n compare: true\n },\n transparentColor: {\n type: 'array',\n value: null,\n compare: true\n },\n useTransparentColor: {\n type: 'boolean',\n value: false,\n compare: true\n }\n};\n/**\n * This deck.gl extension allows for a color palette to be used for pseudo-coloring channels.\n * @typedef LayerProps\n * @type {object}\n * @property {Array>=} colors Array of colors to map channels to (RGB).\n * @property {number=} opacity Opacity of the layer.\n * @property {Array.=} transparentColor An RGB (0-255 range) color to be considered \"transparent\" if provided.\n * In other words, any fragment shader output equal transparentColor (before applying opacity) will have opacity 0.\n * @property {Boolean=} useTransparentColor Whether or not to use the value provided to transparentColor.\n * */\n\nconst ColorPaletteExtension = class extends LayerExtension {\n getShaders() {\n return { ...super.getShaders(),\n modules: [colorPalette]\n };\n }\n\n draw() {\n const {\n colors,\n channelsVisible,\n opacity = defaultProps$7.opacity.value,\n transparentColor = defaultProps$7.transparentColor.value,\n useTransparentColor = defaultProps$7.useTransparentColor.value\n } = this.props;\n const paddedColors = padColors({\n channelsVisible: channelsVisible || this.selections.map(() => true),\n colors: colors || getDefaultPalette(this.props.selections.length)\n });\n const uniforms = {\n colors: paddedColors,\n opacity,\n transparentColor: (transparentColor || [0, 0, 0]).map(i => i / 255),\n useTransparentColor: Boolean(useTransparentColor)\n }; // eslint-disable-next-line no-unused-expressions\n\n this.state.model?.setUniforms(uniforms);\n }\n\n};\nColorPaletteExtension.extensionName = 'ColorPaletteExtension';\nColorPaletteExtension.defaultProps = defaultProps$7;\n\nvar fs$2 = \"#define GLSLIFY 1\\nvec4 jet(float x_17){const float e0=0.0;const vec4 v0=vec4(0,0,0.5137254901960784,1);const float e1=0.125;const vec4 v1=vec4(0,0.23529411764705882,0.6666666666666666,1);const float e2=0.375;const vec4 v2=vec4(0.0196078431372549,1,1,1);const float e3=0.625;const vec4 v3=vec4(1,1,0,1);const float e4=0.875;const vec4 v4=vec4(0.9803921568627451,0,0,1);const float e5=1.0;const vec4 v5=vec4(0.5019607843137255,0,0,1);float a0=smoothstep(e0,e1,x_17);float a1=smoothstep(e1,e2,x_17);float a2=smoothstep(e2,e3,x_17);float a3=smoothstep(e3,e4,x_17);float a4=smoothstep(e4,e5,x_17);return max(mix(v0,v1,a0)*step(e0,x_17)*step(x_17,e1),max(mix(v1,v2,a1)*step(e1,x_17)*step(x_17,e2),max(mix(v2,v3,a2)*step(e2,x_17)*step(x_17,e3),max(mix(v3,v4,a3)*step(e3,x_17)*step(x_17,e4),mix(v4,v5,a4)*step(e4,x_17)*step(x_17,e5)))));}vec4 hsv(float x_18){const float e0=0.0;const vec4 v0=vec4(1,0,0,1);const float e1=0.169;const vec4 v1=vec4(0.9921568627450981,1,0.00784313725490196,1);const float e2=0.173;const vec4 v2=vec4(0.9686274509803922,1,0.00784313725490196,1);const float e3=0.337;const vec4 v3=vec4(0,0.9882352941176471,0.01568627450980392,1);const float e4=0.341;const vec4 v4=vec4(0,0.9882352941176471,0.0392156862745098,1);const float e5=0.506;const vec4 v5=vec4(0.00392156862745098,0.9764705882352941,1,1);const float e6=0.671;const vec4 v6=vec4(0.00784313725490196,0,0.9921568627450981,1);const float e7=0.675;const vec4 v7=vec4(0.03137254901960784,0,0.9921568627450981,1);const float e8=0.839;const vec4 v8=vec4(1,0,0.984313725490196,1);const float e9=0.843;const vec4 v9=vec4(1,0,0.9607843137254902,1);const float e10=1.0;const vec4 v10=vec4(1,0,0.023529411764705882,1);float a0=smoothstep(e0,e1,x_18);float a1=smoothstep(e1,e2,x_18);float a2=smoothstep(e2,e3,x_18);float a3=smoothstep(e3,e4,x_18);float a4=smoothstep(e4,e5,x_18);float a5=smoothstep(e5,e6,x_18);float a6=smoothstep(e6,e7,x_18);float a7=smoothstep(e7,e8,x_18);float a8=smoothstep(e8,e9,x_18);float a9=smoothstep(e9,e10,x_18);return max(mix(v0,v1,a0)*step(e0,x_18)*step(x_18,e1),max(mix(v1,v2,a1)*step(e1,x_18)*step(x_18,e2),max(mix(v2,v3,a2)*step(e2,x_18)*step(x_18,e3),max(mix(v3,v4,a3)*step(e3,x_18)*step(x_18,e4),max(mix(v4,v5,a4)*step(e4,x_18)*step(x_18,e5),max(mix(v5,v6,a5)*step(e5,x_18)*step(x_18,e6),max(mix(v6,v7,a6)*step(e6,x_18)*step(x_18,e7),max(mix(v7,v8,a7)*step(e7,x_18)*step(x_18,e8),max(mix(v8,v9,a8)*step(e8,x_18)*step(x_18,e9),mix(v9,v10,a9)*step(e9,x_18)*step(x_18,e10))))))))));}vec4 hot(float x_13){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.3;const vec4 v1=vec4(0.9019607843137255,0,0,1);const float e2=0.6;const vec4 v2=vec4(1,0.8235294117647058,0,1);const float e3=1.0;const vec4 v3=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_13);float a1=smoothstep(e1,e2,x_13);float a2=smoothstep(e2,e3,x_13);return max(mix(v0,v1,a0)*step(e0,x_13)*step(x_13,e1),max(mix(v1,v2,a1)*step(e1,x_13)*step(x_13,e2),mix(v2,v3,a2)*step(e2,x_13)*step(x_13,e3)));}vec4 cool(float x_24){const float e0=0.0;const vec4 v0=vec4(0.49019607843137253,0,0.7019607843137254,1);const float e1=0.13;const vec4 v1=vec4(0.4549019607843137,0,0.8549019607843137,1);const float e2=0.25;const vec4 v2=vec4(0.3843137254901961,0.2901960784313726,0.9294117647058824,1);const float e3=0.38;const vec4 v3=vec4(0.26666666666666666,0.5725490196078431,0.9058823529411765,1);const float e4=0.5;const vec4 v4=vec4(0,0.8,0.7725490196078432,1);const float e5=0.63;const vec4 v5=vec4(0,0.9686274509803922,0.5725490196078431,1);const float e6=0.75;const vec4 v6=vec4(0,1,0.34509803921568627,1);const float e7=0.88;const vec4 v7=vec4(0.1568627450980392,1,0.03137254901960784,1);const float e8=1.0;const vec4 v8=vec4(0.5764705882352941,1,0,1);float a0=smoothstep(e0,e1,x_24);float a1=smoothstep(e1,e2,x_24);float a2=smoothstep(e2,e3,x_24);float a3=smoothstep(e3,e4,x_24);float a4=smoothstep(e4,e5,x_24);float a5=smoothstep(e5,e6,x_24);float a6=smoothstep(e6,e7,x_24);float a7=smoothstep(e7,e8,x_24);return max(mix(v0,v1,a0)*step(e0,x_24)*step(x_24,e1),max(mix(v1,v2,a1)*step(e1,x_24)*step(x_24,e2),max(mix(v2,v3,a2)*step(e2,x_24)*step(x_24,e3),max(mix(v3,v4,a3)*step(e3,x_24)*step(x_24,e4),max(mix(v4,v5,a4)*step(e4,x_24)*step(x_24,e5),max(mix(v5,v6,a5)*step(e5,x_24)*step(x_24,e6),max(mix(v6,v7,a6)*step(e6,x_24)*step(x_24,e7),mix(v7,v8,a7)*step(e7,x_24)*step(x_24,e8))))))));}vec4 spring(float x_5){const float e0=0.0;const vec4 v0=vec4(1,0,1,1);const float e1=1.0;const vec4 v1=vec4(1,1,0,1);float a0=smoothstep(e0,e1,x_5);return mix(v0,v1,a0)*step(e0,x_5)*step(x_5,e1);}vec4 summer(float x_12){const float e0=0.0;const vec4 v0=vec4(0,0.5019607843137255,0.4,1);const float e1=1.0;const vec4 v1=vec4(1,1,0.4,1);float a0=smoothstep(e0,e1,x_12);return mix(v0,v1,a0)*step(e0,x_12)*step(x_12,e1);}vec4 autumn(float x_25){const float e0=0.0;const vec4 v0=vec4(1,0,0,1);const float e1=1.0;const vec4 v1=vec4(1,1,0,1);float a0=smoothstep(e0,e1,x_25);return mix(v0,v1,a0)*step(e0,x_25)*step(x_25,e1);}vec4 winter(float x_16){const float e0=0.0;const vec4 v0=vec4(0,0,1,1);const float e1=1.0;const vec4 v1=vec4(0,1,0.5019607843137255,1);float a0=smoothstep(e0,e1,x_16);return mix(v0,v1,a0)*step(e0,x_16)*step(x_16,e1);}vec4 bone(float x_15){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.376;const vec4 v1=vec4(0.32941176470588235,0.32941176470588235,0.4549019607843137,1);const float e2=0.753;const vec4 v2=vec4(0.6627450980392157,0.7843137254901961,0.7843137254901961,1);const float e3=1.0;const vec4 v3=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_15);float a1=smoothstep(e1,e2,x_15);float a2=smoothstep(e2,e3,x_15);return max(mix(v0,v1,a0)*step(e0,x_15)*step(x_15,e1),max(mix(v1,v2,a1)*step(e1,x_15)*step(x_15,e2),mix(v2,v3,a2)*step(e2,x_15)*step(x_15,e3)));}vec4 copper(float x_10){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.804;const vec4 v1=vec4(1,0.6274509803921569,0.4,1);const float e2=1.0;const vec4 v2=vec4(1,0.7803921568627451,0.4980392156862745,1);float a0=smoothstep(e0,e1,x_10);float a1=smoothstep(e1,e2,x_10);return max(mix(v0,v1,a0)*step(e0,x_10)*step(x_10,e1),mix(v1,v2,a1)*step(e1,x_10)*step(x_10,e2));}vec4 greys(float x_4){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=1.0;const vec4 v1=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_4);return mix(v0,v1,a0)*step(e0,x_4)*step(x_4,e1);}vec4 yignbu(float x_32){const float e0=0.0;const vec4 v0=vec4(0.03137254901960784,0.11372549019607843,0.34509803921568627,1);const float e1=0.125;const vec4 v1=vec4(0.1450980392156863,0.20392156862745098,0.5803921568627451,1);const float e2=0.25;const vec4 v2=vec4(0.13333333333333333,0.3686274509803922,0.6588235294117647,1);const float e3=0.375;const vec4 v3=vec4(0.11372549019607843,0.5686274509803921,0.7529411764705882,1);const float e4=0.5;const vec4 v4=vec4(0.2549019607843137,0.7137254901960784,0.7686274509803922,1);const float e5=0.625;const vec4 v5=vec4(0.4980392156862745,0.803921568627451,0.7333333333333333,1);const float e6=0.75;const vec4 v6=vec4(0.7803921568627451,0.9137254901960784,0.7058823529411765,1);const float e7=0.875;const vec4 v7=vec4(0.9294117647058824,0.9725490196078431,0.8509803921568627,1);const float e8=1.0;const vec4 v8=vec4(1,1,0.8509803921568627,1);float a0=smoothstep(e0,e1,x_32);float a1=smoothstep(e1,e2,x_32);float a2=smoothstep(e2,e3,x_32);float a3=smoothstep(e3,e4,x_32);float a4=smoothstep(e4,e5,x_32);float a5=smoothstep(e5,e6,x_32);float a6=smoothstep(e6,e7,x_32);float a7=smoothstep(e7,e8,x_32);return max(mix(v0,v1,a0)*step(e0,x_32)*step(x_32,e1),max(mix(v1,v2,a1)*step(e1,x_32)*step(x_32,e2),max(mix(v2,v3,a2)*step(e2,x_32)*step(x_32,e3),max(mix(v3,v4,a3)*step(e3,x_32)*step(x_32,e4),max(mix(v4,v5,a4)*step(e4,x_32)*step(x_32,e5),max(mix(v5,v6,a5)*step(e5,x_32)*step(x_32,e6),max(mix(v6,v7,a6)*step(e6,x_32)*step(x_32,e7),mix(v7,v8,a7)*step(e7,x_32)*step(x_32,e8))))))));}vec4 greens(float x_34){const float e0=0.0;const vec4 v0=vec4(0,0.26666666666666666,0.10588235294117647,1);const float e1=0.125;const vec4 v1=vec4(0,0.42745098039215684,0.17254901960784313,1);const float e2=0.25;const vec4 v2=vec4(0.13725490196078433,0.5450980392156862,0.27058823529411763,1);const float e3=0.375;const vec4 v3=vec4(0.2549019607843137,0.6705882352941176,0.36470588235294116,1);const float e4=0.5;const vec4 v4=vec4(0.4549019607843137,0.7686274509803922,0.4627450980392157,1);const float e5=0.625;const vec4 v5=vec4(0.6313725490196078,0.8509803921568627,0.6078431372549019,1);const float e6=0.75;const vec4 v6=vec4(0.7803921568627451,0.9137254901960784,0.7529411764705882,1);const float e7=0.875;const vec4 v7=vec4(0.8980392156862745,0.9607843137254902,0.8784313725490196,1);const float e8=1.0;const vec4 v8=vec4(0.9686274509803922,0.9882352941176471,0.9607843137254902,1);float a0=smoothstep(e0,e1,x_34);float a1=smoothstep(e1,e2,x_34);float a2=smoothstep(e2,e3,x_34);float a3=smoothstep(e3,e4,x_34);float a4=smoothstep(e4,e5,x_34);float a5=smoothstep(e5,e6,x_34);float a6=smoothstep(e6,e7,x_34);float a7=smoothstep(e7,e8,x_34);return max(mix(v0,v1,a0)*step(e0,x_34)*step(x_34,e1),max(mix(v1,v2,a1)*step(e1,x_34)*step(x_34,e2),max(mix(v2,v3,a2)*step(e2,x_34)*step(x_34,e3),max(mix(v3,v4,a3)*step(e3,x_34)*step(x_34,e4),max(mix(v4,v5,a4)*step(e4,x_34)*step(x_34,e5),max(mix(v5,v6,a5)*step(e5,x_34)*step(x_34,e6),max(mix(v6,v7,a6)*step(e6,x_34)*step(x_34,e7),mix(v7,v8,a7)*step(e7,x_34)*step(x_34,e8))))))));}vec4 yiorrd(float x_41){const float e0=0.0;const vec4 v0=vec4(0.5019607843137255,0,0.14901960784313725,1);const float e1=0.125;const vec4 v1=vec4(0.7411764705882353,0,0.14901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.8901960784313725,0.10196078431372549,0.10980392156862745,1);const float e3=0.375;const vec4 v3=vec4(0.9882352941176471,0.3058823529411765,0.16470588235294117,1);const float e4=0.5;const vec4 v4=vec4(0.9921568627450981,0.5529411764705883,0.23529411764705882,1);const float e5=0.625;const vec4 v5=vec4(0.996078431372549,0.6980392156862745,0.2980392156862745,1);const float e6=0.75;const vec4 v6=vec4(0.996078431372549,0.8509803921568627,0.4627450980392157,1);const float e7=0.875;const vec4 v7=vec4(1,0.9294117647058824,0.6274509803921569,1);const float e8=1.0;const vec4 v8=vec4(1,1,0.8,1);float a0=smoothstep(e0,e1,x_41);float a1=smoothstep(e1,e2,x_41);float a2=smoothstep(e2,e3,x_41);float a3=smoothstep(e3,e4,x_41);float a4=smoothstep(e4,e5,x_41);float a5=smoothstep(e5,e6,x_41);float a6=smoothstep(e6,e7,x_41);float a7=smoothstep(e7,e8,x_41);return max(mix(v0,v1,a0)*step(e0,x_41)*step(x_41,e1),max(mix(v1,v2,a1)*step(e1,x_41)*step(x_41,e2),max(mix(v2,v3,a2)*step(e2,x_41)*step(x_41,e3),max(mix(v3,v4,a3)*step(e3,x_41)*step(x_41,e4),max(mix(v4,v5,a4)*step(e4,x_41)*step(x_41,e5),max(mix(v5,v6,a5)*step(e5,x_41)*step(x_41,e6),max(mix(v6,v7,a6)*step(e6,x_41)*step(x_41,e7),mix(v7,v8,a7)*step(e7,x_41)*step(x_41,e8))))))));}vec4 bluered(float x_23){const float e0=0.0;const vec4 v0=vec4(0,0,1,1);const float e1=1.0;const vec4 v1=vec4(1,0,0,1);float a0=smoothstep(e0,e1,x_23);return mix(v0,v1,a0)*step(e0,x_23)*step(x_23,e1);}vec4 rdbu(float x_1){const float e0=0.0;const vec4 v0=vec4(0.0196078431372549,0.0392156862745098,0.6745098039215687,1);const float e1=0.35;const vec4 v1=vec4(0.41568627450980394,0.5372549019607843,0.9686274509803922,1);const float e2=0.5;const vec4 v2=vec4(0.7450980392156863,0.7450980392156863,0.7450980392156863,1);const float e3=0.6;const vec4 v3=vec4(0.8627450980392157,0.6666666666666666,0.5176470588235295,1);const float e4=0.7;const vec4 v4=vec4(0.9019607843137255,0.5686274509803921,0.35294117647058826,1);const float e5=1.0;const vec4 v5=vec4(0.6980392156862745,0.0392156862745098,0.10980392156862745,1);float a0=smoothstep(e0,e1,x_1);float a1=smoothstep(e1,e2,x_1);float a2=smoothstep(e2,e3,x_1);float a3=smoothstep(e3,e4,x_1);float a4=smoothstep(e4,e5,x_1);return max(mix(v0,v1,a0)*step(e0,x_1)*step(x_1,e1),max(mix(v1,v2,a1)*step(e1,x_1)*step(x_1,e2),max(mix(v2,v3,a2)*step(e2,x_1)*step(x_1,e3),max(mix(v3,v4,a3)*step(e3,x_1)*step(x_1,e4),mix(v4,v5,a4)*step(e4,x_1)*step(x_1,e5)))));}vec4 picnic(float x_42){const float e0=0.0;const vec4 v0=vec4(0,0,1,1);const float e1=0.1;const vec4 v1=vec4(0.2,0.6,1,1);const float e2=0.2;const vec4 v2=vec4(0.4,0.8,1,1);const float e3=0.3;const vec4 v3=vec4(0.6,0.8,1,1);const float e4=0.4;const vec4 v4=vec4(0.8,0.8,1,1);const float e5=0.5;const vec4 v5=vec4(1,1,1,1);const float e6=0.6;const vec4 v6=vec4(1,0.8,1,1);const float e7=0.7;const vec4 v7=vec4(1,0.6,1,1);const float e8=0.8;const vec4 v8=vec4(1,0.4,0.8,1);const float e9=0.9;const vec4 v9=vec4(1,0.4,0.4,1);const float e10=1.0;const vec4 v10=vec4(1,0,0,1);float a0=smoothstep(e0,e1,x_42);float a1=smoothstep(e1,e2,x_42);float a2=smoothstep(e2,e3,x_42);float a3=smoothstep(e3,e4,x_42);float a4=smoothstep(e4,e5,x_42);float a5=smoothstep(e5,e6,x_42);float a6=smoothstep(e6,e7,x_42);float a7=smoothstep(e7,e8,x_42);float a8=smoothstep(e8,e9,x_42);float a9=smoothstep(e9,e10,x_42);return max(mix(v0,v1,a0)*step(e0,x_42)*step(x_42,e1),max(mix(v1,v2,a1)*step(e1,x_42)*step(x_42,e2),max(mix(v2,v3,a2)*step(e2,x_42)*step(x_42,e3),max(mix(v3,v4,a3)*step(e3,x_42)*step(x_42,e4),max(mix(v4,v5,a4)*step(e4,x_42)*step(x_42,e5),max(mix(v5,v6,a5)*step(e5,x_42)*step(x_42,e6),max(mix(v6,v7,a6)*step(e6,x_42)*step(x_42,e7),max(mix(v7,v8,a7)*step(e7,x_42)*step(x_42,e8),max(mix(v8,v9,a8)*step(e8,x_42)*step(x_42,e9),mix(v9,v10,a9)*step(e9,x_42)*step(x_42,e10))))))))));}vec4 rainbow(float x_31){const float e0=0.0;const vec4 v0=vec4(0.5882352941176471,0,0.35294117647058826,1);const float e1=0.125;const vec4 v1=vec4(0,0,0.7843137254901961,1);const float e2=0.25;const vec4 v2=vec4(0,0.09803921568627451,1,1);const float e3=0.375;const vec4 v3=vec4(0,0.596078431372549,1,1);const float e4=0.5;const vec4 v4=vec4(0.17254901960784313,1,0.5882352941176471,1);const float e5=0.625;const vec4 v5=vec4(0.592156862745098,1,0,1);const float e6=0.75;const vec4 v6=vec4(1,0.9176470588235294,0,1);const float e7=0.875;const vec4 v7=vec4(1,0.43529411764705883,0,1);const float e8=1.0;const vec4 v8=vec4(1,0,0,1);float a0=smoothstep(e0,e1,x_31);float a1=smoothstep(e1,e2,x_31);float a2=smoothstep(e2,e3,x_31);float a3=smoothstep(e3,e4,x_31);float a4=smoothstep(e4,e5,x_31);float a5=smoothstep(e5,e6,x_31);float a6=smoothstep(e6,e7,x_31);float a7=smoothstep(e7,e8,x_31);return max(mix(v0,v1,a0)*step(e0,x_31)*step(x_31,e1),max(mix(v1,v2,a1)*step(e1,x_31)*step(x_31,e2),max(mix(v2,v3,a2)*step(e2,x_31)*step(x_31,e3),max(mix(v3,v4,a3)*step(e3,x_31)*step(x_31,e4),max(mix(v4,v5,a4)*step(e4,x_31)*step(x_31,e5),max(mix(v5,v6,a5)*step(e5,x_31)*step(x_31,e6),max(mix(v6,v7,a6)*step(e6,x_31)*step(x_31,e7),mix(v7,v8,a7)*step(e7,x_31)*step(x_31,e8))))))));}vec4 portland(float x_21){const float e0=0.0;const vec4 v0=vec4(0.047058823529411764,0.2,0.5137254901960784,1);const float e1=0.25;const vec4 v1=vec4(0.0392156862745098,0.5333333333333333,0.7294117647058823,1);const float e2=0.5;const vec4 v2=vec4(0.9490196078431372,0.8274509803921568,0.2196078431372549,1);const float e3=0.75;const vec4 v3=vec4(0.9490196078431372,0.5607843137254902,0.2196078431372549,1);const float e4=1.0;const vec4 v4=vec4(0.8509803921568627,0.11764705882352941,0.11764705882352941,1);float a0=smoothstep(e0,e1,x_21);float a1=smoothstep(e1,e2,x_21);float a2=smoothstep(e2,e3,x_21);float a3=smoothstep(e3,e4,x_21);return max(mix(v0,v1,a0)*step(e0,x_21)*step(x_21,e1),max(mix(v1,v2,a1)*step(e1,x_21)*step(x_21,e2),max(mix(v2,v3,a2)*step(e2,x_21)*step(x_21,e3),mix(v3,v4,a3)*step(e3,x_21)*step(x_21,e4))));}vec4 blackbody(float x_38){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.2;const vec4 v1=vec4(0.9019607843137255,0,0,1);const float e2=0.4;const vec4 v2=vec4(0.9019607843137255,0.8235294117647058,0,1);const float e3=0.7;const vec4 v3=vec4(1,1,1,1);const float e4=1.0;const vec4 v4=vec4(0.6274509803921569,0.7843137254901961,1,1);float a0=smoothstep(e0,e1,x_38);float a1=smoothstep(e1,e2,x_38);float a2=smoothstep(e2,e3,x_38);float a3=smoothstep(e3,e4,x_38);return max(mix(v0,v1,a0)*step(e0,x_38)*step(x_38,e1),max(mix(v1,v2,a1)*step(e1,x_38)*step(x_38,e2),max(mix(v2,v3,a2)*step(e2,x_38)*step(x_38,e3),mix(v3,v4,a3)*step(e3,x_38)*step(x_38,e4))));}vec4 earth(float x_29){const float e0=0.0;const vec4 v0=vec4(0,0,0.5098039215686274,1);const float e1=0.1;const vec4 v1=vec4(0,0.7058823529411765,0.7058823529411765,1);const float e2=0.2;const vec4 v2=vec4(0.1568627450980392,0.8235294117647058,0.1568627450980392,1);const float e3=0.4;const vec4 v3=vec4(0.9019607843137255,0.9019607843137255,0.19607843137254902,1);const float e4=0.6;const vec4 v4=vec4(0.47058823529411764,0.27450980392156865,0.0784313725490196,1);const float e5=1.0;const vec4 v5=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_29);float a1=smoothstep(e1,e2,x_29);float a2=smoothstep(e2,e3,x_29);float a3=smoothstep(e3,e4,x_29);float a4=smoothstep(e4,e5,x_29);return max(mix(v0,v1,a0)*step(e0,x_29)*step(x_29,e1),max(mix(v1,v2,a1)*step(e1,x_29)*step(x_29,e2),max(mix(v2,v3,a2)*step(e2,x_29)*step(x_29,e3),max(mix(v3,v4,a3)*step(e3,x_29)*step(x_29,e4),mix(v4,v5,a4)*step(e4,x_29)*step(x_29,e5)))));}vec4 electric(float x_9){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.15;const vec4 v1=vec4(0.11764705882352941,0,0.39215686274509803,1);const float e2=0.4;const vec4 v2=vec4(0.47058823529411764,0,0.39215686274509803,1);const float e3=0.6;const vec4 v3=vec4(0.6274509803921569,0.35294117647058826,0,1);const float e4=0.8;const vec4 v4=vec4(0.9019607843137255,0.7843137254901961,0,1);const float e5=1.0;const vec4 v5=vec4(1,0.9803921568627451,0.8627450980392157,1);float a0=smoothstep(e0,e1,x_9);float a1=smoothstep(e1,e2,x_9);float a2=smoothstep(e2,e3,x_9);float a3=smoothstep(e3,e4,x_9);float a4=smoothstep(e4,e5,x_9);return max(mix(v0,v1,a0)*step(e0,x_9)*step(x_9,e1),max(mix(v1,v2,a1)*step(e1,x_9)*step(x_9,e2),max(mix(v2,v3,a2)*step(e2,x_9)*step(x_9,e3),max(mix(v3,v4,a3)*step(e3,x_9)*step(x_9,e4),mix(v4,v5,a4)*step(e4,x_9)*step(x_9,e5)))));}vec4 alpha(float x_0){const float e0=0.0;const vec4 v0=vec4(1,1,1,0);const float e1=1.0;const vec4 v1=vec4(1,1,1,1);float a0=smoothstep(e0,e1,x_0);return mix(v0,v1,a0)*step(e0,x_0)*step(x_0,e1);}vec4 viridis(float x_22){const float e0=0.0;const vec4 v0=vec4(0.26666666666666666,0.00392156862745098,0.32941176470588235,1);const float e1=0.13;const vec4 v1=vec4(0.2784313725490196,0.17254901960784313,0.47843137254901963,1);const float e2=0.25;const vec4 v2=vec4(0.23137254901960785,0.3176470588235294,0.5450980392156862,1);const float e3=0.38;const vec4 v3=vec4(0.17254901960784313,0.44313725490196076,0.5568627450980392,1);const float e4=0.5;const vec4 v4=vec4(0.12941176470588237,0.5647058823529412,0.5529411764705883,1);const float e5=0.63;const vec4 v5=vec4(0.15294117647058825,0.6784313725490196,0.5058823529411764,1);const float e6=0.75;const vec4 v6=vec4(0.3607843137254902,0.7843137254901961,0.38823529411764707,1);const float e7=0.88;const vec4 v7=vec4(0.6666666666666666,0.8627450980392157,0.19607843137254902,1);const float e8=1.0;const vec4 v8=vec4(0.9921568627450981,0.9058823529411765,0.1450980392156863,1);float a0=smoothstep(e0,e1,x_22);float a1=smoothstep(e1,e2,x_22);float a2=smoothstep(e2,e3,x_22);float a3=smoothstep(e3,e4,x_22);float a4=smoothstep(e4,e5,x_22);float a5=smoothstep(e5,e6,x_22);float a6=smoothstep(e6,e7,x_22);float a7=smoothstep(e7,e8,x_22);return max(mix(v0,v1,a0)*step(e0,x_22)*step(x_22,e1),max(mix(v1,v2,a1)*step(e1,x_22)*step(x_22,e2),max(mix(v2,v3,a2)*step(e2,x_22)*step(x_22,e3),max(mix(v3,v4,a3)*step(e3,x_22)*step(x_22,e4),max(mix(v4,v5,a4)*step(e4,x_22)*step(x_22,e5),max(mix(v5,v6,a5)*step(e5,x_22)*step(x_22,e6),max(mix(v6,v7,a6)*step(e6,x_22)*step(x_22,e7),mix(v7,v8,a7)*step(e7,x_22)*step(x_22,e8))))))));}vec4 inferno(float x_30){const float e0=0.0;const vec4 v0=vec4(0,0,0.01568627450980392,1);const float e1=0.13;const vec4 v1=vec4(0.12156862745098039,0.047058823529411764,0.2823529411764706,1);const float e2=0.25;const vec4 v2=vec4(0.3333333333333333,0.058823529411764705,0.42745098039215684,1);const float e3=0.38;const vec4 v3=vec4(0.5333333333333333,0.13333333333333333,0.41568627450980394,1);const float e4=0.5;const vec4 v4=vec4(0.7294117647058823,0.21176470588235294,0.3333333333333333,1);const float e5=0.63;const vec4 v5=vec4(0.8901960784313725,0.34901960784313724,0.2,1);const float e6=0.75;const vec4 v6=vec4(0.9764705882352941,0.5490196078431373,0.0392156862745098,1);const float e7=0.88;const vec4 v7=vec4(0.9764705882352941,0.788235294117647,0.19607843137254902,1);const float e8=1.0;const vec4 v8=vec4(0.9882352941176471,1,0.6431372549019608,1);float a0=smoothstep(e0,e1,x_30);float a1=smoothstep(e1,e2,x_30);float a2=smoothstep(e2,e3,x_30);float a3=smoothstep(e3,e4,x_30);float a4=smoothstep(e4,e5,x_30);float a5=smoothstep(e5,e6,x_30);float a6=smoothstep(e6,e7,x_30);float a7=smoothstep(e7,e8,x_30);return max(mix(v0,v1,a0)*step(e0,x_30)*step(x_30,e1),max(mix(v1,v2,a1)*step(e1,x_30)*step(x_30,e2),max(mix(v2,v3,a2)*step(e2,x_30)*step(x_30,e3),max(mix(v3,v4,a3)*step(e3,x_30)*step(x_30,e4),max(mix(v4,v5,a4)*step(e4,x_30)*step(x_30,e5),max(mix(v5,v6,a5)*step(e5,x_30)*step(x_30,e6),max(mix(v6,v7,a6)*step(e6,x_30)*step(x_30,e7),mix(v7,v8,a7)*step(e7,x_30)*step(x_30,e8))))))));}vec4 magma(float x_33){const float e0=0.0;const vec4 v0=vec4(0,0,0.01568627450980392,1);const float e1=0.13;const vec4 v1=vec4(0.10980392156862745,0.06274509803921569,0.26666666666666666,1);const float e2=0.25;const vec4 v2=vec4(0.30980392156862746,0.07058823529411765,0.4823529411764706,1);const float e3=0.38;const vec4 v3=vec4(0.5058823529411764,0.1450980392156863,0.5058823529411764,1);const float e4=0.5;const vec4 v4=vec4(0.7098039215686275,0.21176470588235294,0.47843137254901963,1);const float e5=0.63;const vec4 v5=vec4(0.8980392156862745,0.3137254901960784,0.39215686274509803,1);const float e6=0.75;const vec4 v6=vec4(0.984313725490196,0.5294117647058824,0.3803921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.996078431372549,0.7607843137254902,0.5294117647058824,1);const float e8=1.0;const vec4 v8=vec4(0.9882352941176471,0.9921568627450981,0.7490196078431373,1);float a0=smoothstep(e0,e1,x_33);float a1=smoothstep(e1,e2,x_33);float a2=smoothstep(e2,e3,x_33);float a3=smoothstep(e3,e4,x_33);float a4=smoothstep(e4,e5,x_33);float a5=smoothstep(e5,e6,x_33);float a6=smoothstep(e6,e7,x_33);float a7=smoothstep(e7,e8,x_33);return max(mix(v0,v1,a0)*step(e0,x_33)*step(x_33,e1),max(mix(v1,v2,a1)*step(e1,x_33)*step(x_33,e2),max(mix(v2,v3,a2)*step(e2,x_33)*step(x_33,e3),max(mix(v3,v4,a3)*step(e3,x_33)*step(x_33,e4),max(mix(v4,v5,a4)*step(e4,x_33)*step(x_33,e5),max(mix(v5,v6,a5)*step(e5,x_33)*step(x_33,e6),max(mix(v6,v7,a6)*step(e6,x_33)*step(x_33,e7),mix(v7,v8,a7)*step(e7,x_33)*step(x_33,e8))))))));}vec4 plasma(float x_3){const float e0=0.0;const vec4 v0=vec4(0.050980392156862744,0.03137254901960784,0.5294117647058824,1);const float e1=0.13;const vec4 v1=vec4(0.29411764705882354,0.011764705882352941,0.6313725490196078,1);const float e2=0.25;const vec4 v2=vec4(0.49019607843137253,0.011764705882352941,0.6588235294117647,1);const float e3=0.38;const vec4 v3=vec4(0.6588235294117647,0.13333333333333333,0.5882352941176471,1);const float e4=0.5;const vec4 v4=vec4(0.796078431372549,0.27450980392156865,0.4745098039215686,1);const float e5=0.63;const vec4 v5=vec4(0.8980392156862745,0.4196078431372549,0.36470588235294116,1);const float e6=0.75;const vec4 v6=vec4(0.9725490196078431,0.5803921568627451,0.2549019607843137,1);const float e7=0.88;const vec4 v7=vec4(0.9921568627450981,0.7647058823529411,0.1568627450980392,1);const float e8=1.0;const vec4 v8=vec4(0.9411764705882353,0.9764705882352941,0.12941176470588237,1);float a0=smoothstep(e0,e1,x_3);float a1=smoothstep(e1,e2,x_3);float a2=smoothstep(e2,e3,x_3);float a3=smoothstep(e3,e4,x_3);float a4=smoothstep(e4,e5,x_3);float a5=smoothstep(e5,e6,x_3);float a6=smoothstep(e6,e7,x_3);float a7=smoothstep(e7,e8,x_3);return max(mix(v0,v1,a0)*step(e0,x_3)*step(x_3,e1),max(mix(v1,v2,a1)*step(e1,x_3)*step(x_3,e2),max(mix(v2,v3,a2)*step(e2,x_3)*step(x_3,e3),max(mix(v3,v4,a3)*step(e3,x_3)*step(x_3,e4),max(mix(v4,v5,a4)*step(e4,x_3)*step(x_3,e5),max(mix(v5,v6,a5)*step(e5,x_3)*step(x_3,e6),max(mix(v6,v7,a6)*step(e6,x_3)*step(x_3,e7),mix(v7,v8,a7)*step(e7,x_3)*step(x_3,e8))))))));}vec4 warm(float x_43){const float e0=0.0;const vec4 v0=vec4(0.49019607843137253,0,0.7019607843137254,1);const float e1=0.13;const vec4 v1=vec4(0.6745098039215687,0,0.7333333333333333,1);const float e2=0.25;const vec4 v2=vec4(0.8588235294117647,0,0.6666666666666666,1);const float e3=0.38;const vec4 v3=vec4(1,0,0.5098039215686274,1);const float e4=0.5;const vec4 v4=vec4(1,0.24705882352941178,0.2901960784313726,1);const float e5=0.63;const vec4 v5=vec4(1,0.4823529411764706,0,1);const float e6=0.75;const vec4 v6=vec4(0.9176470588235294,0.6901960784313725,0,1);const float e7=0.88;const vec4 v7=vec4(0.7450980392156863,0.8941176470588236,0,1);const float e8=1.0;const vec4 v8=vec4(0.5764705882352941,1,0,1);float a0=smoothstep(e0,e1,x_43);float a1=smoothstep(e1,e2,x_43);float a2=smoothstep(e2,e3,x_43);float a3=smoothstep(e3,e4,x_43);float a4=smoothstep(e4,e5,x_43);float a5=smoothstep(e5,e6,x_43);float a6=smoothstep(e6,e7,x_43);float a7=smoothstep(e7,e8,x_43);return max(mix(v0,v1,a0)*step(e0,x_43)*step(x_43,e1),max(mix(v1,v2,a1)*step(e1,x_43)*step(x_43,e2),max(mix(v2,v3,a2)*step(e2,x_43)*step(x_43,e3),max(mix(v3,v4,a3)*step(e3,x_43)*step(x_43,e4),max(mix(v4,v5,a4)*step(e4,x_43)*step(x_43,e5),max(mix(v5,v6,a5)*step(e5,x_43)*step(x_43,e6),max(mix(v6,v7,a6)*step(e6,x_43)*step(x_43,e7),mix(v7,v8,a7)*step(e7,x_43)*step(x_43,e8))))))));}vec4 rainbow_soft_1310269270(float x_14){const float e0=0.0;const vec4 v0=vec4(0.49019607843137253,0,0.7019607843137254,1);const float e1=0.1;const vec4 v1=vec4(0.7803921568627451,0,0.7058823529411765,1);const float e2=0.2;const vec4 v2=vec4(1,0,0.4745098039215686,1);const float e3=0.3;const vec4 v3=vec4(1,0.4235294117647059,0,1);const float e4=0.4;const vec4 v4=vec4(0.8705882352941177,0.7607843137254902,0,1);const float e5=0.5;const vec4 v5=vec4(0.5882352941176471,1,0,1);const float e6=0.6;const vec4 v6=vec4(0,1,0.21568627450980393,1);const float e7=0.7;const vec4 v7=vec4(0,0.9647058823529412,0.5882352941176471,1);const float e8=0.8;const vec4 v8=vec4(0.19607843137254902,0.6549019607843137,0.8705882352941177,1);const float e9=0.9;const vec4 v9=vec4(0.403921568627451,0.2,0.9215686274509803,1);const float e10=1.0;const vec4 v10=vec4(0.48627450980392156,0,0.7294117647058823,1);float a0=smoothstep(e0,e1,x_14);float a1=smoothstep(e1,e2,x_14);float a2=smoothstep(e2,e3,x_14);float a3=smoothstep(e3,e4,x_14);float a4=smoothstep(e4,e5,x_14);float a5=smoothstep(e5,e6,x_14);float a6=smoothstep(e6,e7,x_14);float a7=smoothstep(e7,e8,x_14);float a8=smoothstep(e8,e9,x_14);float a9=smoothstep(e9,e10,x_14);return max(mix(v0,v1,a0)*step(e0,x_14)*step(x_14,e1),max(mix(v1,v2,a1)*step(e1,x_14)*step(x_14,e2),max(mix(v2,v3,a2)*step(e2,x_14)*step(x_14,e3),max(mix(v3,v4,a3)*step(e3,x_14)*step(x_14,e4),max(mix(v4,v5,a4)*step(e4,x_14)*step(x_14,e5),max(mix(v5,v6,a5)*step(e5,x_14)*step(x_14,e6),max(mix(v6,v7,a6)*step(e6,x_14)*step(x_14,e7),max(mix(v7,v8,a7)*step(e7,x_14)*step(x_14,e8),max(mix(v8,v9,a8)*step(e8,x_14)*step(x_14,e9),mix(v9,v10,a9)*step(e9,x_14)*step(x_14,e10))))))))));}vec4 bathymetry(float x_36){const float e0=0.0;const vec4 v0=vec4(0.1568627450980392,0.10196078431372549,0.17254901960784313,1);const float e1=0.13;const vec4 v1=vec4(0.23137254901960785,0.19215686274509805,0.35294117647058826,1);const float e2=0.25;const vec4 v2=vec4(0.25098039215686274,0.2980392156862745,0.5450980392156862,1);const float e3=0.38;const vec4 v3=vec4(0.24705882352941178,0.43137254901960786,0.592156862745098,1);const float e4=0.5;const vec4 v4=vec4(0.2823529411764706,0.5568627450980392,0.6196078431372549,1);const float e5=0.63;const vec4 v5=vec4(0.3333333333333333,0.6823529411764706,0.6392156862745098,1);const float e6=0.75;const vec4 v6=vec4(0.47058823529411764,0.807843137254902,0.6392156862745098,1);const float e7=0.88;const vec4 v7=vec4(0.7333333333333333,0.9019607843137255,0.6745098039215687,1);const float e8=1.0;const vec4 v8=vec4(0.9921568627450981,0.996078431372549,0.8,1);float a0=smoothstep(e0,e1,x_36);float a1=smoothstep(e1,e2,x_36);float a2=smoothstep(e2,e3,x_36);float a3=smoothstep(e3,e4,x_36);float a4=smoothstep(e4,e5,x_36);float a5=smoothstep(e5,e6,x_36);float a6=smoothstep(e6,e7,x_36);float a7=smoothstep(e7,e8,x_36);return max(mix(v0,v1,a0)*step(e0,x_36)*step(x_36,e1),max(mix(v1,v2,a1)*step(e1,x_36)*step(x_36,e2),max(mix(v2,v3,a2)*step(e2,x_36)*step(x_36,e3),max(mix(v3,v4,a3)*step(e3,x_36)*step(x_36,e4),max(mix(v4,v5,a4)*step(e4,x_36)*step(x_36,e5),max(mix(v5,v6,a5)*step(e5,x_36)*step(x_36,e6),max(mix(v6,v7,a6)*step(e6,x_36)*step(x_36,e7),mix(v7,v8,a7)*step(e7,x_36)*step(x_36,e8))))))));}vec4 cdom(float x_7){const float e0=0.0;const vec4 v0=vec4(0.1843137254901961,0.058823529411764705,0.24313725490196078,1);const float e1=0.13;const vec4 v1=vec4(0.3411764705882353,0.09019607843137255,0.33725490196078434,1);const float e2=0.25;const vec4 v2=vec4(0.5098039215686274,0.10980392156862745,0.38823529411764707,1);const float e3=0.38;const vec4 v3=vec4(0.6705882352941176,0.1607843137254902,0.3764705882352941,1);const float e4=0.5;const vec4 v4=vec4(0.807843137254902,0.2627450980392157,0.33725490196078434,1);const float e5=0.63;const vec4 v5=vec4(0.9019607843137255,0.41568627450980394,0.32941176470588235,1);const float e6=0.75;const vec4 v6=vec4(0.9490196078431372,0.5843137254901961,0.403921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.9764705882352941,0.7568627450980392,0.5294117647058824,1);const float e8=1.0;const vec4 v8=vec4(0.996078431372549,0.9294117647058824,0.6901960784313725,1);float a0=smoothstep(e0,e1,x_7);float a1=smoothstep(e1,e2,x_7);float a2=smoothstep(e2,e3,x_7);float a3=smoothstep(e3,e4,x_7);float a4=smoothstep(e4,e5,x_7);float a5=smoothstep(e5,e6,x_7);float a6=smoothstep(e6,e7,x_7);float a7=smoothstep(e7,e8,x_7);return max(mix(v0,v1,a0)*step(e0,x_7)*step(x_7,e1),max(mix(v1,v2,a1)*step(e1,x_7)*step(x_7,e2),max(mix(v2,v3,a2)*step(e2,x_7)*step(x_7,e3),max(mix(v3,v4,a3)*step(e3,x_7)*step(x_7,e4),max(mix(v4,v5,a4)*step(e4,x_7)*step(x_7,e5),max(mix(v5,v6,a5)*step(e5,x_7)*step(x_7,e6),max(mix(v6,v7,a6)*step(e6,x_7)*step(x_7,e7),mix(v7,v8,a7)*step(e7,x_7)*step(x_7,e8))))))));}vec4 chlorophyll(float x_6){const float e0=0.0;const vec4 v0=vec4(0.07058823529411765,0.1411764705882353,0.0784313725490196,1);const float e1=0.13;const vec4 v1=vec4(0.09803921568627451,0.24705882352941178,0.1607843137254902,1);const float e2=0.25;const vec4 v2=vec4(0.09411764705882353,0.3568627450980392,0.23137254901960785,1);const float e3=0.38;const vec4 v3=vec4(0.050980392156862744,0.4666666666666667,0.2823529411764706,1);const float e4=0.5;const vec4 v4=vec4(0.07058823529411765,0.5803921568627451,0.3137254901960784,1);const float e5=0.63;const vec4 v5=vec4(0.3137254901960784,0.6784313725490196,0.34901960784313724,1);const float e6=0.75;const vec4 v6=vec4(0.5176470588235295,0.7686274509803922,0.47843137254901963,1);const float e7=0.88;const vec4 v7=vec4(0.6862745098039216,0.8666666666666667,0.6352941176470588,1);const float e8=1.0;const vec4 v8=vec4(0.8431372549019608,0.9764705882352941,0.8156862745098039,1);float a0=smoothstep(e0,e1,x_6);float a1=smoothstep(e1,e2,x_6);float a2=smoothstep(e2,e3,x_6);float a3=smoothstep(e3,e4,x_6);float a4=smoothstep(e4,e5,x_6);float a5=smoothstep(e5,e6,x_6);float a6=smoothstep(e6,e7,x_6);float a7=smoothstep(e7,e8,x_6);return max(mix(v0,v1,a0)*step(e0,x_6)*step(x_6,e1),max(mix(v1,v2,a1)*step(e1,x_6)*step(x_6,e2),max(mix(v2,v3,a2)*step(e2,x_6)*step(x_6,e3),max(mix(v3,v4,a3)*step(e3,x_6)*step(x_6,e4),max(mix(v4,v5,a4)*step(e4,x_6)*step(x_6,e5),max(mix(v5,v6,a5)*step(e5,x_6)*step(x_6,e6),max(mix(v6,v7,a6)*step(e6,x_6)*step(x_6,e7),mix(v7,v8,a7)*step(e7,x_6)*step(x_6,e8))))))));}vec4 density(float x_19){const float e0=0.0;const vec4 v0=vec4(0.21176470588235294,0.054901960784313725,0.1411764705882353,1);const float e1=0.13;const vec4 v1=vec4(0.34901960784313724,0.09019607843137255,0.3137254901960784,1);const float e2=0.25;const vec4 v2=vec4(0.43137254901960786,0.17647058823529413,0.5176470588235295,1);const float e3=0.38;const vec4 v3=vec4(0.47058823529411764,0.30196078431372547,0.6980392156862745,1);const float e4=0.5;const vec4 v4=vec4(0.47058823529411764,0.44313725490196076,0.8352941176470589,1);const float e5=0.63;const vec4 v5=vec4(0.45098039215686275,0.592156862745098,0.8941176470588236,1);const float e6=0.75;const vec4 v6=vec4(0.5254901960784314,0.7254901960784313,0.8901960784313725,1);const float e7=0.88;const vec4 v7=vec4(0.6941176470588235,0.8392156862745098,0.8901960784313725,1);const float e8=1.0;const vec4 v8=vec4(0.9019607843137255,0.9450980392156862,0.9450980392156862,1);float a0=smoothstep(e0,e1,x_19);float a1=smoothstep(e1,e2,x_19);float a2=smoothstep(e2,e3,x_19);float a3=smoothstep(e3,e4,x_19);float a4=smoothstep(e4,e5,x_19);float a5=smoothstep(e5,e6,x_19);float a6=smoothstep(e6,e7,x_19);float a7=smoothstep(e7,e8,x_19);return max(mix(v0,v1,a0)*step(e0,x_19)*step(x_19,e1),max(mix(v1,v2,a1)*step(e1,x_19)*step(x_19,e2),max(mix(v2,v3,a2)*step(e2,x_19)*step(x_19,e3),max(mix(v3,v4,a3)*step(e3,x_19)*step(x_19,e4),max(mix(v4,v5,a4)*step(e4,x_19)*step(x_19,e5),max(mix(v5,v6,a5)*step(e5,x_19)*step(x_19,e6),max(mix(v6,v7,a6)*step(e6,x_19)*step(x_19,e7),mix(v7,v8,a7)*step(e7,x_19)*step(x_19,e8))))))));}vec4 freesurface_blue_3154355989(float x_35){const float e0=0.0;const vec4 v0=vec4(0.11764705882352941,0.01568627450980392,0.43137254901960786,1);const float e1=0.13;const vec4 v1=vec4(0.1843137254901961,0.054901960784313725,0.6901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.1607843137254902,0.17647058823529413,0.9254901960784314,1);const float e3=0.38;const vec4 v3=vec4(0.09803921568627451,0.38823529411764707,0.8313725490196079,1);const float e4=0.5;const vec4 v4=vec4(0.26666666666666666,0.5137254901960784,0.7843137254901961,1);const float e5=0.63;const vec4 v5=vec4(0.4470588235294118,0.611764705882353,0.7725490196078432,1);const float e6=0.75;const vec4 v6=vec4(0.615686274509804,0.7098039215686275,0.796078431372549,1);const float e7=0.88;const vec4 v7=vec4(0.7843137254901961,0.8156862745098039,0.8470588235294118,1);const float e8=1.0;const vec4 v8=vec4(0.9450980392156862,0.9294117647058824,0.9254901960784314,1);float a0=smoothstep(e0,e1,x_35);float a1=smoothstep(e1,e2,x_35);float a2=smoothstep(e2,e3,x_35);float a3=smoothstep(e3,e4,x_35);float a4=smoothstep(e4,e5,x_35);float a5=smoothstep(e5,e6,x_35);float a6=smoothstep(e6,e7,x_35);float a7=smoothstep(e7,e8,x_35);return max(mix(v0,v1,a0)*step(e0,x_35)*step(x_35,e1),max(mix(v1,v2,a1)*step(e1,x_35)*step(x_35,e2),max(mix(v2,v3,a2)*step(e2,x_35)*step(x_35,e3),max(mix(v3,v4,a3)*step(e3,x_35)*step(x_35,e4),max(mix(v4,v5,a4)*step(e4,x_35)*step(x_35,e5),max(mix(v5,v6,a5)*step(e5,x_35)*step(x_35,e6),max(mix(v6,v7,a6)*step(e6,x_35)*step(x_35,e7),mix(v7,v8,a7)*step(e7,x_35)*step(x_35,e8))))))));}vec4 freesurface_red_1679163293(float x_20){const float e0=0.0;const vec4 v0=vec4(0.23529411764705882,0.03529411764705882,0.07058823529411765,1);const float e1=0.13;const vec4 v1=vec4(0.39215686274509803,0.06666666666666667,0.10588235294117647,1);const float e2=0.25;const vec4 v2=vec4(0.5568627450980392,0.0784313725490196,0.11372549019607843,1);const float e3=0.38;const vec4 v3=vec4(0.6941176470588235,0.16862745098039217,0.10588235294117647,1);const float e4=0.5;const vec4 v4=vec4(0.7529411764705882,0.3411764705882353,0.24705882352941178,1);const float e5=0.63;const vec4 v5=vec4(0.803921568627451,0.49019607843137253,0.4117647058823529,1);const float e6=0.75;const vec4 v6=vec4(0.8470588235294118,0.6352941176470588,0.5803921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.8901960784313725,0.7803921568627451,0.7568627450980392,1);const float e8=1.0;const vec4 v8=vec4(0.9450980392156862,0.9294117647058824,0.9254901960784314,1);float a0=smoothstep(e0,e1,x_20);float a1=smoothstep(e1,e2,x_20);float a2=smoothstep(e2,e3,x_20);float a3=smoothstep(e3,e4,x_20);float a4=smoothstep(e4,e5,x_20);float a5=smoothstep(e5,e6,x_20);float a6=smoothstep(e6,e7,x_20);float a7=smoothstep(e7,e8,x_20);return max(mix(v0,v1,a0)*step(e0,x_20)*step(x_20,e1),max(mix(v1,v2,a1)*step(e1,x_20)*step(x_20,e2),max(mix(v2,v3,a2)*step(e2,x_20)*step(x_20,e3),max(mix(v3,v4,a3)*step(e3,x_20)*step(x_20,e4),max(mix(v4,v5,a4)*step(e4,x_20)*step(x_20,e5),max(mix(v5,v6,a5)*step(e5,x_20)*step(x_20,e6),max(mix(v6,v7,a6)*step(e6,x_20)*step(x_20,e7),mix(v7,v8,a7)*step(e7,x_20)*step(x_20,e8))))))));}vec4 oxygen(float x_11){const float e0=0.0;const vec4 v0=vec4(0.25098039215686274,0.0196078431372549,0.0196078431372549,1);const float e1=0.13;const vec4 v1=vec4(0.41568627450980394,0.023529411764705882,0.058823529411764705,1);const float e2=0.25;const vec4 v2=vec4(0.5647058823529412,0.10196078431372549,0.027450980392156862,1);const float e3=0.38;const vec4 v3=vec4(0.6588235294117647,0.25098039215686274,0.011764705882352941,1);const float e4=0.5;const vec4 v4=vec4(0.7372549019607844,0.39215686274509803,0.01568627450980392,1);const float e5=0.63;const vec4 v5=vec4(0.807843137254902,0.5333333333333333,0.043137254901960784,1);const float e6=0.75;const vec4 v6=vec4(0.8627450980392157,0.6823529411764706,0.09803921568627451,1);const float e7=0.88;const vec4 v7=vec4(0.9058823529411765,0.8431372549019608,0.17254901960784313,1);const float e8=1.0;const vec4 v8=vec4(0.9725490196078431,0.996078431372549,0.4117647058823529,1);float a0=smoothstep(e0,e1,x_11);float a1=smoothstep(e1,e2,x_11);float a2=smoothstep(e2,e3,x_11);float a3=smoothstep(e3,e4,x_11);float a4=smoothstep(e4,e5,x_11);float a5=smoothstep(e5,e6,x_11);float a6=smoothstep(e6,e7,x_11);float a7=smoothstep(e7,e8,x_11);return max(mix(v0,v1,a0)*step(e0,x_11)*step(x_11,e1),max(mix(v1,v2,a1)*step(e1,x_11)*step(x_11,e2),max(mix(v2,v3,a2)*step(e2,x_11)*step(x_11,e3),max(mix(v3,v4,a3)*step(e3,x_11)*step(x_11,e4),max(mix(v4,v5,a4)*step(e4,x_11)*step(x_11,e5),max(mix(v5,v6,a5)*step(e5,x_11)*step(x_11,e6),max(mix(v6,v7,a6)*step(e6,x_11)*step(x_11,e7),mix(v7,v8,a7)*step(e7,x_11)*step(x_11,e8))))))));}vec4 par(float x_28){const float e0=0.0;const vec4 v0=vec4(0.2,0.0784313725490196,0.09411764705882353,1);const float e1=0.13;const vec4 v1=vec4(0.35294117647058826,0.12549019607843137,0.13725490196078433,1);const float e2=0.25;const vec4 v2=vec4(0.5058823529411764,0.17254901960784313,0.13333333333333333,1);const float e3=0.38;const vec4 v3=vec4(0.6235294117647059,0.26666666666666666,0.09803921568627451,1);const float e4=0.5;const vec4 v4=vec4(0.7137254901960784,0.38823529411764707,0.07450980392156863,1);const float e5=0.63;const vec4 v5=vec4(0.7803921568627451,0.5254901960784314,0.08627450980392157,1);const float e6=0.75;const vec4 v6=vec4(0.8313725490196079,0.6705882352941176,0.13725490196078433,1);const float e7=0.88;const vec4 v7=vec4(0.8666666666666667,0.8235294117647058,0.21176470588235294,1);const float e8=1.0;const vec4 v8=vec4(0.8823529411764706,0.9921568627450981,0.29411764705882354,1);float a0=smoothstep(e0,e1,x_28);float a1=smoothstep(e1,e2,x_28);float a2=smoothstep(e2,e3,x_28);float a3=smoothstep(e3,e4,x_28);float a4=smoothstep(e4,e5,x_28);float a5=smoothstep(e5,e6,x_28);float a6=smoothstep(e6,e7,x_28);float a7=smoothstep(e7,e8,x_28);return max(mix(v0,v1,a0)*step(e0,x_28)*step(x_28,e1),max(mix(v1,v2,a1)*step(e1,x_28)*step(x_28,e2),max(mix(v2,v3,a2)*step(e2,x_28)*step(x_28,e3),max(mix(v3,v4,a3)*step(e3,x_28)*step(x_28,e4),max(mix(v4,v5,a4)*step(e4,x_28)*step(x_28,e5),max(mix(v5,v6,a5)*step(e5,x_28)*step(x_28,e6),max(mix(v6,v7,a6)*step(e6,x_28)*step(x_28,e7),mix(v7,v8,a7)*step(e7,x_28)*step(x_28,e8))))))));}vec4 phase(float x_39){const float e0=0.0;const vec4 v0=vec4(0.5686274509803921,0.4117647058823529,0.07058823529411765,1);const float e1=0.13;const vec4 v1=vec4(0.7215686274509804,0.2784313725490196,0.14901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.7294117647058823,0.22745098039215686,0.45098039215686275,1);const float e3=0.38;const vec4 v3=vec4(0.6274509803921569,0.2784313725490196,0.7254901960784313,1);const float e4=0.5;const vec4 v4=vec4(0.43137254901960786,0.3803921568627451,0.8549019607843137,1);const float e5=0.63;const vec4 v5=vec4(0.19607843137254902,0.4823529411764706,0.6431372549019608,1);const float e6=0.75;const vec4 v6=vec4(0.12156862745098039,0.5137254901960784,0.43137254901960786,1);const float e7=0.88;const vec4 v7=vec4(0.30196078431372547,0.5058823529411764,0.13333333333333333,1);const float e8=1.0;const vec4 v8=vec4(0.5686274509803921,0.4117647058823529,0.07058823529411765,1);float a0=smoothstep(e0,e1,x_39);float a1=smoothstep(e1,e2,x_39);float a2=smoothstep(e2,e3,x_39);float a3=smoothstep(e3,e4,x_39);float a4=smoothstep(e4,e5,x_39);float a5=smoothstep(e5,e6,x_39);float a6=smoothstep(e6,e7,x_39);float a7=smoothstep(e7,e8,x_39);return max(mix(v0,v1,a0)*step(e0,x_39)*step(x_39,e1),max(mix(v1,v2,a1)*step(e1,x_39)*step(x_39,e2),max(mix(v2,v3,a2)*step(e2,x_39)*step(x_39,e3),max(mix(v3,v4,a3)*step(e3,x_39)*step(x_39,e4),max(mix(v4,v5,a4)*step(e4,x_39)*step(x_39,e5),max(mix(v5,v6,a5)*step(e5,x_39)*step(x_39,e6),max(mix(v6,v7,a6)*step(e6,x_39)*step(x_39,e7),mix(v7,v8,a7)*step(e7,x_39)*step(x_39,e8))))))));}vec4 salinity(float x_26){const float e0=0.0;const vec4 v0=vec4(0.16470588235294117,0.09411764705882353,0.4235294117647059,1);const float e1=0.13;const vec4 v1=vec4(0.12941176470588237,0.19607843137254902,0.6352941176470588,1);const float e2=0.25;const vec4 v2=vec4(0.058823529411764705,0.35294117647058826,0.5686274509803921,1);const float e3=0.38;const vec4 v3=vec4(0.1568627450980392,0.4627450980392157,0.5372549019607843,1);const float e4=0.5;const vec4 v4=vec4(0.23137254901960785,0.5725490196078431,0.5294117647058824,1);const float e5=0.63;const vec4 v5=vec4(0.30980392156862746,0.6862745098039216,0.49411764705882355,1);const float e6=0.75;const vec4 v6=vec4(0.47058823529411764,0.796078431372549,0.40784313725490196,1);const float e7=0.88;const vec4 v7=vec4(0.7568627450980392,0.8666666666666667,0.39215686274509803,1);const float e8=1.0;const vec4 v8=vec4(0.9921568627450981,0.9372549019607843,0.6039215686274509,1);float a0=smoothstep(e0,e1,x_26);float a1=smoothstep(e1,e2,x_26);float a2=smoothstep(e2,e3,x_26);float a3=smoothstep(e3,e4,x_26);float a4=smoothstep(e4,e5,x_26);float a5=smoothstep(e5,e6,x_26);float a6=smoothstep(e6,e7,x_26);float a7=smoothstep(e7,e8,x_26);return max(mix(v0,v1,a0)*step(e0,x_26)*step(x_26,e1),max(mix(v1,v2,a1)*step(e1,x_26)*step(x_26,e2),max(mix(v2,v3,a2)*step(e2,x_26)*step(x_26,e3),max(mix(v3,v4,a3)*step(e3,x_26)*step(x_26,e4),max(mix(v4,v5,a4)*step(e4,x_26)*step(x_26,e5),max(mix(v5,v6,a5)*step(e5,x_26)*step(x_26,e6),max(mix(v6,v7,a6)*step(e6,x_26)*step(x_26,e7),mix(v7,v8,a7)*step(e7,x_26)*step(x_26,e8))))))));}vec4 temperature(float x_8){const float e0=0.0;const vec4 v0=vec4(0.01568627450980392,0.13725490196078433,0.2,1);const float e1=0.13;const vec4 v1=vec4(0.09019607843137255,0.2,0.47843137254901963,1);const float e2=0.25;const vec4 v2=vec4(0.3333333333333333,0.23137254901960785,0.615686274509804,1);const float e3=0.38;const vec4 v3=vec4(0.5058823529411764,0.30980392156862746,0.5607843137254902,1);const float e4=0.5;const vec4 v4=vec4(0.6862745098039216,0.37254901960784315,0.5098039215686274,1);const float e5=0.63;const vec4 v5=vec4(0.8705882352941177,0.4392156862745098,0.396078431372549,1);const float e6=0.75;const vec4 v6=vec4(0.9764705882352941,0.5725490196078431,0.25882352941176473,1);const float e7=0.88;const vec4 v7=vec4(0.9764705882352941,0.7686274509803922,0.2549019607843137,1);const float e8=1.0;const vec4 v8=vec4(0.9098039215686274,0.9803921568627451,0.3568627450980392,1);float a0=smoothstep(e0,e1,x_8);float a1=smoothstep(e1,e2,x_8);float a2=smoothstep(e2,e3,x_8);float a3=smoothstep(e3,e4,x_8);float a4=smoothstep(e4,e5,x_8);float a5=smoothstep(e5,e6,x_8);float a6=smoothstep(e6,e7,x_8);float a7=smoothstep(e7,e8,x_8);return max(mix(v0,v1,a0)*step(e0,x_8)*step(x_8,e1),max(mix(v1,v2,a1)*step(e1,x_8)*step(x_8,e2),max(mix(v2,v3,a2)*step(e2,x_8)*step(x_8,e3),max(mix(v3,v4,a3)*step(e3,x_8)*step(x_8,e4),max(mix(v4,v5,a4)*step(e4,x_8)*step(x_8,e5),max(mix(v5,v6,a5)*step(e5,x_8)*step(x_8,e6),max(mix(v6,v7,a6)*step(e6,x_8)*step(x_8,e7),mix(v7,v8,a7)*step(e7,x_8)*step(x_8,e8))))))));}vec4 turbidity(float x_40){const float e0=0.0;const vec4 v0=vec4(0.13333333333333333,0.12156862745098039,0.10588235294117647,1);const float e1=0.13;const vec4 v1=vec4(0.2549019607843137,0.19607843137254902,0.1607843137254902,1);const float e2=0.25;const vec4 v2=vec4(0.3843137254901961,0.27058823529411763,0.20392156862745098,1);const float e3=0.38;const vec4 v3=vec4(0.5137254901960784,0.34901960784313724,0.2235294117647059,1);const float e4=0.5;const vec4 v4=vec4(0.6313725490196078,0.4392156862745098,0.23137254901960785,1);const float e5=0.63;const vec4 v5=vec4(0.7254901960784313,0.5490196078431373,0.25882352941176473,1);const float e6=0.75;const vec4 v6=vec4(0.792156862745098,0.6823529411764706,0.34509803921568627,1);const float e7=0.88;const vec4 v7=vec4(0.8470588235294118,0.8196078431372549,0.49411764705882355,1);const float e8=1.0;const vec4 v8=vec4(0.9137254901960784,0.9647058823529412,0.6705882352941176,1);float a0=smoothstep(e0,e1,x_40);float a1=smoothstep(e1,e2,x_40);float a2=smoothstep(e2,e3,x_40);float a3=smoothstep(e3,e4,x_40);float a4=smoothstep(e4,e5,x_40);float a5=smoothstep(e5,e6,x_40);float a6=smoothstep(e6,e7,x_40);float a7=smoothstep(e7,e8,x_40);return max(mix(v0,v1,a0)*step(e0,x_40)*step(x_40,e1),max(mix(v1,v2,a1)*step(e1,x_40)*step(x_40,e2),max(mix(v2,v3,a2)*step(e2,x_40)*step(x_40,e3),max(mix(v3,v4,a3)*step(e3,x_40)*step(x_40,e4),max(mix(v4,v5,a4)*step(e4,x_40)*step(x_40,e5),max(mix(v5,v6,a5)*step(e5,x_40)*step(x_40,e6),max(mix(v6,v7,a6)*step(e6,x_40)*step(x_40,e7),mix(v7,v8,a7)*step(e7,x_40)*step(x_40,e8))))))));}vec4 velocity_blue_297387650(float x_2){const float e0=0.0;const vec4 v0=vec4(0.06666666666666667,0.12549019607843137,0.25098039215686274,1);const float e1=0.13;const vec4 v1=vec4(0.13725490196078433,0.20392156862745098,0.4549019607843137,1);const float e2=0.25;const vec4 v2=vec4(0.11372549019607843,0.3176470588235294,0.611764705882353,1);const float e3=0.38;const vec4 v3=vec4(0.12156862745098039,0.44313725490196076,0.6352941176470588,1);const float e4=0.5;const vec4 v4=vec4(0.19607843137254902,0.5647058823529412,0.6627450980392157,1);const float e5=0.63;const vec4 v5=vec4(0.3411764705882353,0.6784313725490196,0.6901960784313725,1);const float e6=0.75;const vec4 v6=vec4(0.5843137254901961,0.7686274509803922,0.7411764705882353,1);const float e7=0.88;const vec4 v7=vec4(0.796078431372549,0.8666666666666667,0.8274509803921568,1);const float e8=1.0;const vec4 v8=vec4(0.996078431372549,0.984313725490196,0.9019607843137255,1);float a0=smoothstep(e0,e1,x_2);float a1=smoothstep(e1,e2,x_2);float a2=smoothstep(e2,e3,x_2);float a3=smoothstep(e3,e4,x_2);float a4=smoothstep(e4,e5,x_2);float a5=smoothstep(e5,e6,x_2);float a6=smoothstep(e6,e7,x_2);float a7=smoothstep(e7,e8,x_2);return max(mix(v0,v1,a0)*step(e0,x_2)*step(x_2,e1),max(mix(v1,v2,a1)*step(e1,x_2)*step(x_2,e2),max(mix(v2,v3,a2)*step(e2,x_2)*step(x_2,e3),max(mix(v3,v4,a3)*step(e3,x_2)*step(x_2,e4),max(mix(v4,v5,a4)*step(e4,x_2)*step(x_2,e5),max(mix(v5,v6,a5)*step(e5,x_2)*step(x_2,e6),max(mix(v6,v7,a6)*step(e6,x_2)*step(x_2,e7),mix(v7,v8,a7)*step(e7,x_2)*step(x_2,e8))))))));}vec4 velocity_green_2558432129(float x_27){const float e0=0.0;const vec4 v0=vec4(0.09019607843137255,0.13725490196078433,0.07450980392156863,1);const float e1=0.13;const vec4 v1=vec4(0.09411764705882353,0.25098039215686274,0.14901960784313725,1);const float e2=0.25;const vec4 v2=vec4(0.043137254901960784,0.37254901960784315,0.17647058823529413,1);const float e3=0.38;const vec4 v3=vec4(0.15294117647058825,0.4823529411764706,0.13725490196078433,1);const float e4=0.5;const vec4 v4=vec4(0.37254901960784315,0.5725490196078431,0.047058823529411764,1);const float e5=0.63;const vec4 v5=vec4(0.596078431372549,0.6470588235294118,0.07058823529411765,1);const float e6=0.75;const vec4 v6=vec4(0.788235294117647,0.7294117647058823,0.27058823529411763,1);const float e7=0.88;const vec4 v7=vec4(0.9137254901960784,0.8470588235294118,0.5372549019607843,1);const float e8=1.0;const vec4 v8=vec4(1,0.9921568627450981,0.803921568627451,1);float a0=smoothstep(e0,e1,x_27);float a1=smoothstep(e1,e2,x_27);float a2=smoothstep(e2,e3,x_27);float a3=smoothstep(e3,e4,x_27);float a4=smoothstep(e4,e5,x_27);float a5=smoothstep(e5,e6,x_27);float a6=smoothstep(e6,e7,x_27);float a7=smoothstep(e7,e8,x_27);return max(mix(v0,v1,a0)*step(e0,x_27)*step(x_27,e1),max(mix(v1,v2,a1)*step(e1,x_27)*step(x_27,e2),max(mix(v2,v3,a2)*step(e2,x_27)*step(x_27,e3),max(mix(v3,v4,a3)*step(e3,x_27)*step(x_27,e4),max(mix(v4,v5,a4)*step(e4,x_27)*step(x_27,e5),max(mix(v5,v6,a5)*step(e5,x_27)*step(x_27,e6),max(mix(v6,v7,a6)*step(e6,x_27)*step(x_27,e7),mix(v7,v8,a7)*step(e7,x_27)*step(x_27,e8))))))));}vec4 cubehelix(float x_37){const float e0=0.0;const vec4 v0=vec4(0,0,0,1);const float e1=0.07;const vec4 v1=vec4(0.08627450980392157,0.0196078431372549,0.23137254901960785,1);const float e2=0.13;const vec4 v2=vec4(0.23529411764705882,0.01568627450980392,0.4117647058823529,1);const float e3=0.2;const vec4 v3=vec4(0.42745098039215684,0.00392156862745098,0.5294117647058824,1);const float e4=0.27;const vec4 v4=vec4(0.6313725490196078,0,0.5764705882352941,1);const float e5=0.33;const vec4 v5=vec4(0.8235294117647058,0.00784313725490196,0.5568627450980392,1);const float e6=0.4;const vec4 v6=vec4(0.984313725490196,0.043137254901960784,0.4823529411764706,1);const float e7=0.47;const vec4 v7=vec4(1,0.11372549019607843,0.3803921568627451,1);const float e8=0.53;const vec4 v8=vec4(1,0.21176470588235294,0.27058823529411763,1);const float e9=0.6;const vec4 v9=vec4(1,0.3333333333333333,0.1803921568627451,1);const float e10=0.67;const vec4 v10=vec4(1,0.47058823529411764,0.13333333333333333,1);const float e11=0.73;const vec4 v11=vec4(1,0.615686274509804,0.1450980392156863,1);const float e12=0.8;const vec4 v12=vec4(0.9450980392156862,0.7490196078431373,0.2235294117647059,1);const float e13=0.87;const vec4 v13=vec4(0.8784313725490196,0.8627450980392157,0.36470588235294116,1);const float e14=0.93;const vec4 v14=vec4(0.8549019607843137,0.9450980392156862,0.5568627450980392,1);const float e15=1.0;const vec4 v15=vec4(0.8901960784313725,0.9921568627450981,0.7764705882352941,1);float a0=smoothstep(e0,e1,x_37);float a1=smoothstep(e1,e2,x_37);float a2=smoothstep(e2,e3,x_37);float a3=smoothstep(e3,e4,x_37);float a4=smoothstep(e4,e5,x_37);float a5=smoothstep(e5,e6,x_37);float a6=smoothstep(e6,e7,x_37);float a7=smoothstep(e7,e8,x_37);float a8=smoothstep(e8,e9,x_37);float a9=smoothstep(e9,e10,x_37);float a10=smoothstep(e10,e11,x_37);float a11=smoothstep(e11,e12,x_37);float a12=smoothstep(e12,e13,x_37);float a13=smoothstep(e13,e14,x_37);float a14=smoothstep(e14,e15,x_37);return max(mix(v0,v1,a0)*step(e0,x_37)*step(x_37,e1),max(mix(v1,v2,a1)*step(e1,x_37)*step(x_37,e2),max(mix(v2,v3,a2)*step(e2,x_37)*step(x_37,e3),max(mix(v3,v4,a3)*step(e3,x_37)*step(x_37,e4),max(mix(v4,v5,a4)*step(e4,x_37)*step(x_37,e5),max(mix(v5,v6,a5)*step(e5,x_37)*step(x_37,e6),max(mix(v6,v7,a6)*step(e6,x_37)*step(x_37,e7),max(mix(v7,v8,a7)*step(e7,x_37)*step(x_37,e8),max(mix(v8,v9,a8)*step(e8,x_37)*step(x_37,e9),max(mix(v9,v10,a9)*step(e9,x_37)*step(x_37,e10),max(mix(v10,v11,a10)*step(e10,x_37)*step(x_37,e11),max(mix(v11,v12,a11)*step(e11,x_37)*step(x_37,e12),max(mix(v12,v13,a12)*step(e12,x_37)*step(x_37,e13),max(mix(v13,v14,a13)*step(e13,x_37)*step(x_37,e14),mix(v14,v15,a14)*step(e14,x_37)*step(x_37,e15)))))))))))))));}vec4 apply_transparent_color_452471729(vec3 color,vec3 transparentColor,bool useTransparentColor,float opacity){return vec4(color,(color==transparentColor&&useTransparentColor)? 0. : opacity);}uniform float opacity;uniform bool useTransparentColor;vec4 colormap(float intensity){return vec4(apply_transparent_color_452471729(COLORMAP_FUNCTION(min(1.,intensity)).xyz,COLORMAP_FUNCTION(0.).xyz,useTransparentColor,opacity));}\"; // eslint-disable-line\n\nvar additiveColormap = {\n name: 'additive-colormap',\n fs: fs$2,\n inject: {\n 'fs:DECKGL_MUTATE_COLOR': `\n float intensityCombo = 0.;\n intensityCombo += max(0.,intensity0);\n intensityCombo += max(0.,intensity1);\n intensityCombo += max(0.,intensity2);\n intensityCombo += max(0.,intensity3);\n intensityCombo += max(0.,intensity4);\n intensityCombo += max(0.,intensity5);\n rgba = colormap(intensityCombo);\n`\n }\n};\n\nconst defaultProps$6 = {\n colormap: {\n type: 'string',\n value: 'viridis',\n compare: true\n },\n opacity: {\n type: 'number',\n value: 1.0,\n compare: true\n },\n useTransparentColor: {\n type: 'boolean',\n value: false,\n compare: true\n }\n};\n/**\n * This deck.gl extension allows for a color palette to be used for pseudo-coloring channels.\n * @typedef LayerProps\n * @type {object}\n * @property {number=} opacity Opacity of the layer.\n * @property {string=} colormap String indicating a colormap (default: ''). The full list of options is here: https://github.com/glslify/glsl-colormap#glsl-colormap\n * @property {boolean=} useTransparentColor Indicates whether the shader should make the output of colormap_function(0) color transparent\n * */\n\nconst AdditiveColormapExtension = class extends LayerExtension {\n getShaders() {\n return {\n defines: {\n COLORMAP_FUNCTION: this?.props?.colormap || defaultProps$6.colormap.value\n },\n modules: [additiveColormap]\n };\n }\n\n updateState({\n props,\n oldProps,\n changeFlags,\n ...rest\n }) {\n super.updateState({\n props,\n oldProps,\n changeFlags,\n ...rest\n });\n\n if (props.colormap !== oldProps.colormap) {\n const {\n gl\n } = this.context;\n\n if (this.state.model) {\n this.state.model.delete();\n this.setState({\n model: this._getModel(gl)\n });\n }\n }\n }\n\n draw() {\n const {\n useTransparentColor = defaultProps$6.useTransparentColor.value,\n opacity = defaultProps$6.opacity.value\n } = this.props;\n const uniforms = {\n opacity,\n useTransparentColor\n }; // eslint-disable-next-line no-unused-expressions\n\n this.state.model?.setUniforms(uniforms);\n }\n\n};\nAdditiveColormapExtension.extensionName = 'AdditiveColormapExtension';\nAdditiveColormapExtension.defaultProps = defaultProps$6;\n\nconst defaultProps$5 = {\n pickable: {\n type: 'boolean',\n value: true,\n compare: true\n },\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n contrastLimits: {\n type: 'array',\n value: [],\n compare: true\n },\n channelsVisible: {\n type: 'array',\n value: [],\n compare: true\n },\n selections: {\n type: 'array',\n value: [],\n compare: true\n },\n domain: {\n type: 'array',\n value: [],\n compare: true\n },\n viewportId: {\n type: 'string',\n value: '',\n compare: true\n },\n loader: {\n type: 'object',\n value: {\n getRaster: async () => ({\n data: [],\n height: 0,\n width: 0\n }),\n dtype: 'Uint16'\n },\n compare: true\n },\n onClick: {\n type: 'function',\n value: null,\n compare: true\n },\n onViewportLoad: {\n type: 'function',\n value: null,\n compare: true\n },\n interpolation: {\n type: 'number',\n value: GL.NEAREST,\n compare: true\n },\n extensions: {\n type: 'array',\n value: [new ColorPaletteExtension()],\n compare: true\n }\n};\n/**\n * @typedef LayerProps\n * @type {Object}\n * @property {Array.>} contrastLimits List of [begin, end] values to control each channel's ramp function.\n * @property {Array.} channelsVisible List of boolean values for each channel for whether or not it is visible.\n * @property {Object} loader PixelSource. Represents an N-dimensional image.\n * @property {Array} selections Selection to be used for fetching data.\n * @property {Array.>=} domain Override for the possible max/min values (i.e something different than 65535 for uint16/'(...props: import('../types').Viv[]) }}\n * @ignore\n */\n\nconst ImageLayer = class extends CompositeLayer {\n finalizeState() {\n this.state.abortController.abort();\n }\n\n updateState({\n props,\n oldProps\n }) {\n const loaderChanged = props.loader !== oldProps.loader;\n const selectionsChanged = props.selections !== oldProps.selections;\n\n if (loaderChanged || selectionsChanged) {\n // Only fetch new data to render if loader has changed\n const {\n loader,\n selections = [],\n onViewportLoad\n } = this.props;\n const abortController = new AbortController();\n this.setState({\n abortController\n });\n const {\n signal\n } = abortController;\n\n const getRaster = selection => loader.getRaster({\n selection,\n signal\n });\n\n const dataPromises = selections.map(getRaster);\n Promise.all(dataPromises).then(rasters => {\n const raster = {\n data: rasters.map(d => d.data),\n width: rasters[0].width,\n height: rasters[0].height\n };\n\n if (isInterleaved(loader.shape)) {\n // data is for BitmapLayer and needs to be of form { data: Uint8Array, width, height };\n // eslint-disable-next-line prefer-destructuring\n raster.data = raster.data[0];\n\n if (raster.data.length === raster.width * raster.height * 3) {\n // data is RGB (not RGBA) and need to update texture formats\n raster.format = GL.RGB;\n raster.dataFormat = GL.RGB;\n }\n }\n\n if (onViewportLoad) {\n onViewportLoad(raster);\n }\n\n this.setState({ ...raster\n });\n }).catch(e => {\n if (e !== SIGNAL_ABORTED) {\n throw e; // re-throws error if not our signal\n }\n });\n }\n } // eslint-disable-next-line class-methods-use-this\n\n\n getPickingInfo({\n info,\n sourceLayer\n }) {\n // eslint-disable-next-line no-param-reassign\n info.sourceLayer = sourceLayer; // eslint-disable-next-line no-param-reassign\n\n info.tile = sourceLayer.props.tile;\n return info;\n }\n\n renderLayers() {\n const {\n loader,\n id\n } = this.props;\n const {\n dtype\n } = loader;\n const {\n width,\n height,\n data\n } = this.state;\n if (!(width && height)) return null;\n const bounds = [0, height, width, 0];\n\n if (isInterleaved(loader.shape)) {\n const {\n photometricInterpretation = 2\n } = loader.meta;\n return new BitmapLayer(this.props, {\n image: this.state,\n photometricInterpretation,\n // Shared props with XRLayer:\n bounds,\n id: `image-sub-layer-${bounds}-${id}`\n });\n }\n\n return new XRLayer(this.props, {\n channelData: {\n data,\n height,\n width\n },\n // Shared props with BitmapLayer:\n bounds,\n id: `image-sub-layer-${bounds}-${id}`,\n dtype\n });\n }\n\n};\nImageLayer.layerName = 'ImageLayer';\nImageLayer.defaultProps = defaultProps$5;\n\nconst defaultProps$4 = {\n pickable: {\n type: 'boolean',\n value: true,\n compare: true\n },\n onHover: {\n type: 'function',\n value: null,\n compare: false\n },\n contrastLimits: {\n type: 'array',\n value: [],\n compare: true\n },\n channelsVisible: {\n type: 'array',\n value: [],\n compare: true\n },\n domain: {\n type: 'array',\n value: [],\n compare: true\n },\n viewportId: {\n type: 'string',\n value: '',\n compare: true\n },\n maxRequests: {\n type: 'number',\n value: 10,\n compare: true\n },\n onClick: {\n type: 'function',\n value: null,\n compare: true\n },\n refinementStrategy: {\n type: 'string',\n value: null,\n compare: true\n },\n excludeBackground: {\n type: 'boolean',\n value: false,\n compare: true\n },\n extensions: {\n type: 'array',\n value: [new ColorPaletteExtension()],\n compare: true\n }\n};\n/**\n * @typedef LayerProps\n * @type {object}\n * @property {Array.>} contrastLimits List of [begin, end] values to control each channel's ramp function.\n * @property {Array.} channelsVisible List of boolean values for each channel for whether or not it is visible.\n * @property {Array} loader Image pyramid. PixelSource[], where each PixelSource is decreasing in shape.\n * @property {Array} selections Selection to be used for fetching data.\n * @property {Array.>=} domain Override for the possible max/min values (i.e something different than 65535 for uint16/'(...props: import('../../types').Viv[]) }}\n * @ignore\n */\n\nconst MultiscaleImageLayer = class extends CompositeLayer {\n renderLayers() {\n const {\n loader,\n selections,\n opacity,\n viewportId,\n onTileError,\n onHover,\n id,\n onClick,\n modelMatrix,\n excludeBackground,\n refinementStrategy\n } = this.props; // Get properties from highest resolution\n\n const {\n tileSize,\n dtype\n } = loader[0]; // This is basically to invert:\n // https://github.com/visgl/deck.gl/pull/4616/files#diff-4d6a2e500c0e79e12e562c4f1217dc80R128\n // The z level can be wrong for showing the correct scales because of the calculation deck.gl does\n // so we need to invert it for fetching tiles and minZoom/maxZoom.\n\n const getTileData = async ({\n x,\n y,\n z,\n signal\n }) => {\n // Early return if no selections\n if (!selections || selections.length === 0) {\n return null;\n } // I don't fully undertstand why this works, but I have a sense.\n // It's basically to cancel out:\n // https://github.com/visgl/deck.gl/pull/4616/files#diff-4d6a2e500c0e79e12e562c4f1217dc80R128,\n // which felt odd to me to beign with.\n // The image-tile example works without, this but I have a feeling there is something\n // going on with our pyramids and/or rendering that is different.\n\n\n const resolution = Math.round(-z);\n\n const getTile = selection => {\n const config = {\n x,\n y,\n selection,\n signal\n };\n return loader[resolution].getTile(config);\n };\n\n try {\n /*\n * Try to request the tile data. The pixels sources can throw\n * special SIGNAL_ABORTED string that we pick up in the catch\n * block to return null to deck.gl.\n *\n * This means that our pixels sources _always_ have the same\n * return type, and optional throw for performance.\n */\n const tiles = await Promise.all(selections.map(getTile));\n const tile = {\n data: tiles.map(d => d.data),\n width: tiles[0].width,\n height: tiles[0].height\n };\n\n if (isInterleaved(loader[resolution].shape)) {\n // eslint-disable-next-line prefer-destructuring\n tile.data = tile.data[0];\n\n if (tile.data.length === tile.width * tile.height * 3) {\n tile.format = GL.RGB;\n tile.dataFormat = GL.RGB; // is this not properly inferred?\n } // can just return early, no need to check for webgl2\n\n\n return tile;\n }\n\n return tile;\n } catch (err) {\n /*\n * Signal is aborted. We handle the custom value thrown\n * by our pixel sources here and return falsy to deck.gl.\n */\n if (err === SIGNAL_ABORTED) {\n return null;\n } // We should propagate all other thrown values/errors\n\n\n throw err;\n }\n };\n\n const {\n height,\n width\n } = getImageSize(loader[0]);\n const tiledLayer = new MultiscaleImageLayerBase(this.props, {\n id: `Tiled-Image-${id}`,\n getTileData,\n dtype,\n tileSize,\n // If you scale a matrix up or down, that is like zooming in or out. zoomOffset controls\n // how the zoom level you fetch tiles at is offset, allowing us to fetch higher resolution tiles\n // while at a lower \"absolute\" zoom level. If you didn't use this prop, an image that is scaled\n // up would always look \"low resolution\" no matter the level of the image pyramid you are looking at.\n zoomOffset: Math.round(Math.log2(modelMatrix ? modelMatrix.getScale()[0] : 1)),\n extent: [0, 0, width, height],\n // See the above note within for why the use of zoomOffset and the rounding necessary.\n minZoom: Math.round(-(loader.length - 1)),\n maxZoom: 0,\n // We want a no-overlap caching strategy with an opacity < 1 to prevent\n // multiple rendered sublayers (some of which have been cached) from overlapping\n refinementStrategy: refinementStrategy || (opacity === 1 ? 'best-available' : 'no-overlap'),\n // TileLayer checks `changeFlags.updateTriggersChanged.getTileData` to see if tile cache\n // needs to be re-created. We want to trigger this behavior if the loader changes.\n // https://github.com/uber/deck.gl/blob/3f67ea6dfd09a4d74122f93903cb6b819dd88d52/modules/geo-layers/src/tile-layer/tile-layer.js#L50\n updateTriggers: {\n getTileData: [loader, selections]\n },\n onTileError: onTileError || loader[0].onTileError\n }); // This gives us a background image and also solves the current\n // minZoom funny business. We don't use it for the background if we have an opacity\n // paramteter set to anything but 1, but we always use it for situations where\n // we are zoomed out too far.\n\n const lowestResolution = loader[loader.length - 1];\n const implementsGetRaster = typeof lowestResolution.getRaster === 'function';\n const layerModelMatrix = modelMatrix ? modelMatrix.clone() : new Matrix4();\n const baseLayer = implementsGetRaster && !excludeBackground && new ImageLayer(this.props, {\n id: `Background-Image-${id}`,\n loader: lowestResolution,\n modelMatrix: layerModelMatrix.scale(2 ** (loader.length - 1)),\n visible: !viewportId || this.context.viewport.id === viewportId,\n onHover,\n onClick,\n // Background image is nicest when LINEAR in my opinion.\n interpolation: GL.LINEAR,\n onViewportLoad: null\n });\n const layers = [baseLayer, tiledLayer];\n return layers;\n }\n\n};\nMultiscaleImageLayer.layerName = 'MultiscaleImageLayer';\nMultiscaleImageLayer.defaultProps = defaultProps$4;\n\nconst defaultProps$3 = {\n pickable: {\n type: 'boolean',\n value: true,\n compare: true\n },\n loader: {\n type: 'object',\n value: {\n getRaster: async () => ({\n data: [],\n height: 0,\n width: 0\n }),\n getRasterSize: () => ({\n height: 0,\n width: 0\n }),\n dtype: '>} contrastLimits List of [begin, end] values to control each channel's ramp function.\n * @property {Array.>} colors List of [r, g, b] values for each channel.\n * @property {Array.} channelsVisible List of boolean values for each channel for whether or not it is visible.\n * @property {Array} loader PixelSource[]. Assumes multiscale if loader.length > 1.\n * @property {Array} selections Selection to be used for fetching data.\n * @property {number=} opacity Opacity of the layer.\n * @property {string=} colormap String indicating a colormap (default: ''). The full list of options is here: https://github.com/glslify/glsl-colormap#glsl-colormap\n * @property {Array.>=} domain Override for the possible max/min values (i.e something different than 65535 for uint16/'=} boundingBoxColor [r, g, b] color of the bounding box (default: [255, 0, 0]).\n * @property {number=} boundingBoxOutlineWidth Width of the bounding box in px (default: 1).\n * @property {Array.=} viewportOutlineColor [r, g, b] color of the outline (default: [255, 190, 0]).\n * @property {number=} viewportOutlineWidth Viewport outline width in px (default: 2).\n * @property {String=} id Unique identifier for this layer.\n */\n\n/**\n * @type {{ new (...props: import('../types').Viv[]) }}\n * @ignore\n */\n\nconst OverviewLayer = class extends CompositeLayer {\n renderLayers() {\n const {\n loader,\n id,\n zoom,\n boundingBox,\n boundingBoxColor,\n boundingBoxOutlineWidth,\n viewportOutlineColor,\n viewportOutlineWidth,\n overviewScale\n } = this.props;\n const {\n width,\n height\n } = getImageSize(loader[0]);\n const z = loader.length - 1;\n const lowestResolution = loader[z];\n const overview = new ImageLayer(this.props, {\n id: `viewport-${id}`,\n modelMatrix: new Matrix4().scale(2 ** z * overviewScale),\n loader: lowestResolution\n });\n const boundingBoxOutline = new PolygonLayer({\n id: `bounding-box-overview-${id}`,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [boundingBox],\n getPolygon: f => f,\n filled: false,\n stroked: true,\n getLineColor: boundingBoxColor,\n getLineWidth: boundingBoxOutlineWidth * 2 ** zoom\n });\n const viewportOutline = new PolygonLayer({\n id: `viewport-outline-${id}`,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [[[0, 0], [width * overviewScale, 0], [width * overviewScale, height * overviewScale], [0, height * overviewScale]]],\n getPolygon: f => f,\n filled: false,\n stroked: true,\n getLineColor: viewportOutlineColor,\n getLineWidth: viewportOutlineWidth * 2 ** zoom\n });\n const layers = [overview, boundingBoxOutline, viewportOutline];\n return layers;\n }\n\n};\nOverviewLayer.layerName = 'OverviewLayer';\nOverviewLayer.defaultProps = defaultProps$3;\n\nfunction getVivId(id) {\n return `-#${id}#`;\n}\n/**\n * Create a boudning box from a viewport based on passed-in viewState.\n * @param {viewState} Object The viewState for a certain viewport.\n * @returns {View} The DeckGL View for this viewport.\n */\n\nfunction makeBoundingBox(viewState) {\n const viewport = new OrthographicView().makeViewport({\n // From the current `detail` viewState, we need its projection matrix (actually the inverse).\n viewState,\n height: viewState.height,\n width: viewState.width\n }); // Use the inverse of the projection matrix to map screen to the view space.\n\n return [viewport.unproject([0, 0]), viewport.unproject([viewport.width, 0]), viewport.unproject([viewport.width, viewport.height]), viewport.unproject([0, viewport.height])];\n}\n/**\n * Create an initial view state that centers the image in the viewport at the zoom level that fills the dimensions in `viewSize`.\n * @param {Object} loader (PixelSource[] | PixelSource)\n * @param {Object} viewSize { height, width } object giving dimensions of the viewport for deducing the right zoom level to center the image.\n * @param {Object=} zoomBackOff A positive number which controls how far zoomed out the view state is from filling the entire viewport (default is 0 so the image fully fills the view).\n * SideBySideViewer and PictureInPictureViewer use .5 when setting viewState automatically in their default behavior, so the viewport is slightly zoomed out from the image\n * filling the whole screen. 1 unit of zoomBackOff (so a passed-in value of 1) corresponds to a 2x zooming out.\n * @param {Boolean=} use3d Whether or not to return a view state that can be used with the 3d viewer\n * @param {Boolean=} modelMatrix If using a transformation matrix, passing it in here will allow this function to properly center the volume.\n * @returns {Object} A default initial view state that centers the image within the view: { target: [x, y, 0], zoom: -zoom }.\n */\n\nfunction getDefaultInitialViewState(loader, viewSize, zoomBackOff = 0, use3d = false, modelMatrix) {\n const source = Array.isArray(loader) ? loader[0] : loader;\n const {\n width,\n height\n } = getImageSize(source);\n const depth = source.shape[source.labels.indexOf('z')];\n const zoom = Math.log2(Math.min(viewSize.width / width, viewSize.height / height)) - zoomBackOff;\n const physicalSizeScalingMatrix = getPhysicalSizeScalingMatrix(source);\n const loaderInitialViewState = {\n target: (modelMatrix || new Matrix4()).transformPoint((use3d ? physicalSizeScalingMatrix : new Matrix4()).transformPoint([width / 2, height / 2, use3d ? depth / 2 : 0])),\n zoom\n };\n return loaderInitialViewState;\n}\n/**\n * Creates the layers for viewing an image in detail.\n * @param {String} id The identifier of the view.\n * @param {Object} props The layer properties.\n * @returns {Array} An array of layers.\n */\n\nfunction getImageLayer(id, props) {\n const {\n loader\n } = props; // Grab name of PixelSource if a class instance (works for Tiff & Zarr).\n\n const sourceName = loader[0]?.constructor?.name; // Create at least one layer even without selections so that the tests pass.\n\n const Layer = loader.length > 1 ? MultiscaleImageLayer : ImageLayer;\n const layerLoader = loader.length > 1 ? loader : loader[0];\n return new Layer({ ...props,\n id: `${sourceName}${getVivId(id)}`,\n viewportId: id,\n loader: layerLoader\n });\n}\n\nfunction getPosition(boundingBox, position, length) {\n const viewLength = boundingBox[2][0] - boundingBox[0][0];\n\n switch (position) {\n case 'bottom-right':\n {\n const yCoord = boundingBox[2][1] - (boundingBox[2][1] - boundingBox[0][1]) * length;\n const xLeftCoord = boundingBox[2][0] - viewLength * length;\n return [yCoord, xLeftCoord];\n }\n\n case 'top-right':\n {\n const yCoord = (boundingBox[2][1] - boundingBox[0][1]) * length;\n const xLeftCoord = boundingBox[2][0] - viewLength * length;\n return [yCoord, xLeftCoord];\n }\n\n case 'top-left':\n {\n const yCoord = (boundingBox[2][1] - boundingBox[0][1]) * length;\n const xLeftCoord = viewLength * length;\n return [yCoord, xLeftCoord];\n }\n\n case 'bottom-left':\n {\n const yCoord = boundingBox[2][1] - (boundingBox[2][1] - boundingBox[0][1]) * length;\n const xLeftCoord = viewLength * length;\n return [yCoord, xLeftCoord];\n }\n\n default:\n {\n throw new Error(`Position ${position} not found`);\n }\n }\n}\n\nconst defaultProps$2 = {\n pickable: {\n type: 'boolean',\n value: true,\n compare: true\n },\n viewState: {\n type: 'object',\n value: {\n zoom: 0,\n target: [0, 0, 0]\n },\n compare: true\n },\n unit: {\n type: 'string',\n value: '',\n compare: true\n },\n size: {\n type: 'number',\n value: 1,\n compare: true\n },\n position: {\n type: 'string',\n value: 'bottom-right',\n compare: true\n },\n length: {\n type: 'number',\n value: 0.085,\n compare: true\n }\n};\n/**\n * @typedef LayerProps\n * @type {Object}\n * @property {String} unit Physical unit size per pixel at full resolution.\n * @property {Number} size Physical size of a pixel.\n * @property {Object} viewState The current viewState for the desired view. We cannot internally use this.context.viewport because it is one frame behind:\n * https://github.com/visgl/deck.gl/issues/4504\n * @property {Array=} boundingBox Boudning box of the view in which this should render.\n * @property {string=} id Id from the parent layer.\n * @property {number=} length Value from 0 to 1 representing the portion of the view to be used for the length part of the scale bar.\n */\n\n/**\n * @type {{ new(...props: LayerProps[]) }}\n * @ignore\n */\n\nconst ScaleBarLayer = class extends CompositeLayer {\n renderLayers() {\n const {\n id,\n unit,\n size,\n position,\n viewState,\n length\n } = this.props;\n const boundingBox = makeBoundingBox(viewState);\n const {\n zoom\n } = viewState;\n const viewLength = boundingBox[2][0] - boundingBox[0][0];\n const barLength = viewLength * 0.05; // This is a good heuristic for stopping the bar tick marks from getting too small\n // and/or the text squishing up into the bar.\n\n const barHeight = Math.max(2 ** (-zoom + 1.5), (boundingBox[2][1] - boundingBox[0][1]) * 0.007);\n const numUnits = barLength * size;\n const [yCoord, xLeftCoord] = getPosition(boundingBox, position, length);\n const lengthBar = new LineLayer({\n id: `scale-bar-length-${id}`,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [[[xLeftCoord, yCoord], [xLeftCoord + barLength, yCoord]]],\n getSourcePosition: d => d[0],\n getTargetPosition: d => d[1],\n getWidth: 2,\n getColor: [220, 220, 220]\n });\n const tickBoundsLeft = new LineLayer({\n id: `scale-bar-height-left-${id}`,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [[[xLeftCoord, yCoord - barHeight], [xLeftCoord, yCoord + barHeight]]],\n getSourcePosition: d => d[0],\n getTargetPosition: d => d[1],\n getWidth: 2,\n getColor: [220, 220, 220]\n });\n const tickBoundsRight = new LineLayer({\n id: `scale-bar-height-right-${id}`,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [[[xLeftCoord + barLength, yCoord - barHeight], [xLeftCoord + barLength, yCoord + barHeight]]],\n getSourcePosition: d => d[0],\n getTargetPosition: d => d[1],\n getWidth: 2,\n getColor: [220, 220, 220]\n });\n const textLayer = new TextLayer({\n id: `units-label-layer-${id}`,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [{\n text: String(numUnits).slice(0, 5).replace(/\\.$/, '') + unit,\n position: [xLeftCoord + barLength * 0.5, yCoord + barHeight * 4]\n }],\n getColor: [220, 220, 220, 255],\n getSize: 12,\n fontFamily: DEFAULT_FONT_FAMILY,\n sizeUnits: 'meters',\n sizeScale: 2 ** -zoom,\n characterSet: [...unit.split(''), ...range(10).map(i => String(i)), '.']\n });\n return [lengthBar, tickBoundsLeft, tickBoundsRight, textLayer];\n }\n\n};\nScaleBarLayer.layerName = 'ScaleBarLayer';\nScaleBarLayer.defaultProps = defaultProps$2;\n\nvar vs = \"#version 300 es\\n#define GLSLIFY 1\\n#define SHADER_NAME xr-layer-vertex-shader\\nin vec3 positions;uniform vec3 eye_pos;uniform mat4 proj;uniform mat4 model;uniform mat4 view;uniform mat4 scale;uniform mat4 resolution;out vec3 vray_dir;flat out vec3 transformed_eye;void main(){gl_Position=proj*view*model*scale*resolution*vec4(positions,1.);/*This first diagram is a skewed volume(i.e a \\\"shear\\\" model matrix applied)top down with the eye marked as #,all in world space^___|__\\\\|\\\\\\\\|\\\\|____|||\\n#\\nThis next diagram shows the volume after the inverse model matrix has placed it back in model coordinates,but the eye still in world space.^___|___|||||||__|__||||\\n#\\nFinally,we apply the inverse model matrix transformation to the eye as well to bring it too into world space.Notice that the ray here matches the \\\"voxels\\\" through which the first ray also passes,as desired.^____/__|/||/||/____|///\\n#\\n*/transformed_eye=(inverse(resolution)*inverse(scale)*inverse(model)*(vec4(eye_pos,1.))).xyz;vray_dir=positions-transformed_eye;}\"; // eslint-disable-line\n\nvar fs$1 = \"#version 300 es\\nprecision highp int;precision highp float;precision highp SAMPLER_TYPE;\\n#define GLSLIFY 1\\nuniform highp SAMPLER_TYPE volume0;uniform highp SAMPLER_TYPE volume1;uniform highp SAMPLER_TYPE volume2;uniform highp SAMPLER_TYPE volume3;uniform highp SAMPLER_TYPE volume4;uniform highp SAMPLER_TYPE volume5;uniform vec3 scaledDimensions;uniform mat4 scale;uniform vec3 normals[NUM_PLANES];uniform float distances[NUM_PLANES];uniform vec3 colors[6];uniform vec2 xSlice;uniform vec2 ySlice;uniform vec2 zSlice;uniform vec2 contrastLimits[6];in vec3 vray_dir;flat in vec3 transformed_eye;out vec4 color;vec2 intersect_box(vec3 orig,vec3 dir){vec3 box_min=vec3(xSlice[0],ySlice[0],zSlice[0]);vec3 box_max=vec3(xSlice[1],ySlice[1],zSlice[1]);vec3 inv_dir=1./dir;vec3 tmin_tmp=(box_min-orig)*inv_dir;vec3 tmax_tmp=(box_max-orig)*inv_dir;vec3 tmin=min(tmin_tmp,tmax_tmp);vec3 tmax=max(tmin_tmp,tmax_tmp);float t0=max(tmin.x,max(tmin.y,tmin.z));float t1=min(tmax.x,min(tmax.y,tmax.z));vec2 val=vec2(t0,t1);return val;}float linear_to_srgb(float x){if(x<=0.0031308f){return 12.92f*x;}return 1.055f*pow(x,1.f/2.4f)-0.055f;}float wang_hash(int seed){seed=(seed ^ 61)^(seed>>16);seed*=9;seed=seed ^(seed>>4);seed*=0x27d4eb2d;seed=seed ^(seed>>15);return float(seed % 2147483647)/float(2147483647);}void main(void){vec3 ray_dir=normalize(vray_dir);vec2 t_hit=intersect_box(transformed_eye,ray_dir);if(t_hit.x>t_hit.y){discard;}t_hit.x=max(t_hit.x,0.);vec3 dt_vec=1./(scale*vec4(abs(ray_dir),1.)).xyz;float dt=1.*min(dt_vec.x,min(dt_vec.y,dt_vec.z));float offset=wang_hash(int(gl_FragCoord.x+640.*gl_FragCoord.y));vec3 p=transformed_eye+(t_hit.x+offset*dt)*ray_dir;_BEFORE_RENDERfor(float t=t_hit.x;t maxVals[i]) {\n maxVals[i] = intensityArray[i];\n }\n }\n `,\n _AFTER_RENDER: `\\\n vec3 rgbCombo = vec3(0.0);\n for(int i = 0; i < 6; i++) {\n rgbCombo += max(0.0, min(1.0, maxVals[i])) * vec3(colors[i]);\n }\n color = vec4(rgbCombo, 1.0);\n `\n },\n [RENDERING_MODES.MIN_INTENSITY_PROJECTION]: {\n _BEFORE_RENDER: `\\\n float minVals[6] = float[6](1. / 0., 1. / 0., 1. / 0., 1. / 0., 1. / 0., 1. / 0.);\n `,\n _RENDER: `\\\n \n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n\n for(int i = 0; i < 6; i++) {\n if(intensityArray[i] < minVals[i]) {\n minVals[i] = intensityArray[i];\n }\n }\n `,\n _AFTER_RENDER: `\\\n vec3 rgbCombo = vec3(0.0);\n for(int i = 0; i < 6; i++) {\n rgbCombo += max(0.0, min(1.0, minVals[i])) * vec3(colors[i]);\n }\n color = vec4(rgbCombo, 1.0);\n `\n },\n [RENDERING_MODES.ADDITIVE]: {\n _BEFORE_RENDER: ``,\n _RENDER: `\\\n vec3 rgbCombo = vec3(0.0);\n vec3 hsvCombo = vec3(0.0);\n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n float total = 0.0;\n for(int i = 0; i < 6; i++) {\n float intensityValue = intensityArray[i];\n rgbCombo += max(0.0, min(1.0, intensityValue)) * colors[i];\n total += intensityValue;\n }\n // Do not go past 1 in opacity.\n total = min(total, 1.0);\n vec4 val_color = vec4(rgbCombo, total);\n // Opacity correction\n val_color.a = 1.0 - pow(1.0 - val_color.a, 1.0);\n color.rgb += (1.0 - color.a) * val_color.a * val_color.rgb;\n color.a += (1.0 - color.a) * val_color.a;\n if (color.a >= 0.95) {\n break;\n }\n `,\n _AFTER_RENDER: ``\n }\n};\nconst RENDERING_MODES_COLORMAP = {\n [RENDERING_MODES.MAX_INTENSITY_PROJECTION]: {\n _BEFORE_RENDER: `\\\n float maxVals[6] = float[6](-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);\n `,\n _RENDER: `\\\n \n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n\n for(int i = 0; i < 6; i++) {\n if(intensityArray[i] > maxVals[i]) {\n maxVals[i] = intensityArray[i];\n }\n }\n `,\n _AFTER_RENDER: `\\\n float total = 0.0;\n for(int i = 0; i < 6; i++) {\n total += maxVals[i];\n }\n // Do not go past 1 in opacity/colormap value.\n total = min(total, 1.0);\n color = colormap(total, total);\n `\n },\n [RENDERING_MODES.MIN_INTENSITY_PROJECTION]: {\n _BEFORE_RENDER: `\\\n float minVals[6] = float[6](1. / 0., 1. / 0., 1. / 0., 1. / 0., 1. / 0., 1. / 0.);\n `,\n _RENDER: `\\\n \n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n\n for(int i = 0; i < 6; i++) {\n if(intensityArray[i] < minVals[i]) {\n minVals[i] = intensityArray[i];\n }\n }\n `,\n _AFTER_RENDER: `\\\n float total = 0.0;\n for(int i = 0; i < 6; i++) {\n total += minVals[i];\n }\n // Do not go past 1 in opacity/colormap value.\n total = min(total, 1.0);\n color = colormap(total, total);\n `\n },\n [RENDERING_MODES.ADDITIVE]: {\n _BEFORE_RENDER: ``,\n _RENDER: `\\\n float intensityArray[6] = float[6](intensityValue0, intensityValue1, intensityValue2, intensityValue3, intensityValue4, intensityValue5);\n\t\tfloat total = 0.0;\n\n\t\tfor(int i = 0; i < 6; i++) {\n\t\t\ttotal += intensityArray[i];\n\t\t}\n\t\t// Do not go past 1 in opacity/colormap value.\n\t\ttotal = min(total, 1.0);\n\n\t\tvec4 val_color = colormap(total, total);\n\n\t\t// Opacity correction\n\t\tval_color.a = 1.0 - pow(1.0 - val_color.a, 1.0);\n\t\tcolor.rgb += (1.0 - color.a) * val_color.a * val_color.rgb;\n\t\tcolor.a += (1.0 - color.a) * val_color.a;\n\t\tif (color.a >= 0.95) {\n\t\t\tbreak;\n\t\t}\n p += ray_dir * dt;\n `,\n _AFTER_RENDER: ``\n }\n};\n\n/* This is largely an adaptation of Will Usher's excellent blog post/code:\nhttps://github.com/Twinklebear/webgl-volume-raycaster\nWithout his app, this would have been exponentially more difficult to do, so we thank him dearly.\n\nThe major changes are:\n\n- Code has been adapted to the luma.gl/deck.gl framework instead of more-or-less pure WebGL.\n\n- We use a coordinate system that will allow overlays/other figures on our vertex shader/javascript via the `uniform mat4 scale` that matches raw pixel size multiplied by\nthe ratio of physical sizes (if present) to the world space, just like our 2D layers. Will implements everything in a unit cube (I think?) centered at the origin.\n\n- We use an OrbitView which is a similar camera to what Will has, but stops gimbal lock from happening\nby stopping full rotations whereas Will implements a camera that allows for full rotations without gimbal lock via quaternions.\nWe have an open issue for implementing this deck.gl: https://github.com/visgl/deck.gl/issues/5364\n\n- We have a multi-channel use case and have a few tweaks in the fragment shader to handle that.\n\n- We convert all of our data to Float32Array so we can use LINEAR sampling while also maintaing the dynamic range and integrity of the data.\n\n- Will uses a colormap via a sampled texture, which is a very good idea, but not something we are geared up for in 2D, so not something we will do in 3D either: \nhttps://github.com/visgl/luma.gl/issues/1415\n\n- We allow for multiple rendering settings (Max/Min Int. Proj., Additive, etc.)\n\n- We allow for arbtirary affine transformations via deck.gl's modelMatrix prop and have updated the vertex shader accordingly.\nMore information about that is detailed in the comments there.\n*/\n\nconst CUBE_STRIP = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0];\nconst NUM_PLANES_DEFAULT = 1;\nconst defaultProps$1 = {\n pickable: false,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n channelData: {\n type: 'object',\n value: {},\n compare: true\n },\n colors: {\n type: 'array',\n value: [],\n compare: true\n },\n contrastLimits: {\n type: 'array',\n value: [],\n compare: true\n },\n dtype: {\n type: 'string',\n value: 'Uint8',\n compare: true\n },\n colormap: {\n type: 'string',\n value: '',\n compare: true\n },\n xSlice: {\n type: 'array',\n value: null,\n compare: true\n },\n ySlice: {\n type: 'array',\n value: null,\n compare: true\n },\n zSlice: {\n type: 'array',\n value: null,\n compare: true\n },\n clippingPlanes: {\n type: 'array',\n value: [],\n compare: true\n },\n renderingMode: {\n type: 'string',\n value: RENDERING_MODES.ADDITIVE,\n compare: true\n },\n resolutionMatrix: {\n type: 'object',\n value: new Matrix4(),\n compare: true\n }\n};\n\nfunction getRenderingAttrs() {\n const values = getDtypeValues('Float32');\n return { ...values,\n sampler: values.sampler.replace('2D', '3D'),\n cast: data => new Float32Array(data)\n };\n}\n\nfunction removeExtraColormapFunctionsFromShader(colormap) {\n // Always include viridis so shaders compile,\n // but otherwise we discard all other colormaps via a regex.\n // With all the colormaps, the shaders were too large\n // and crashed our computers when we loaded volumes too large.\n const discardColormaps = COLORMAPS.filter(i => i !== (colormap || 'viridis')).map(i => i.replace(/-/g, '_'));\n const discardRegex = new RegExp(`vec4 (${discardColormaps.join('(_([0-9]*))?|')})\\\\(float x_[0-9]+\\\\){([^}]+)}`, 'g');\n const channelsModules = { ...channels,\n fs: channels.fs.replace(discardRegex, ''),\n defines: {\n COLORMAP_FUNCTION: colormap || 'viridis'\n }\n };\n return channelsModules;\n}\n/**\n * @typedef LayerProps\n * @type {Object}\n * @property {Array.>} contrastLimits List of [begin, end] values to control each channel's ramp function.\n * @property {Array.>} colors List of [r, g, b] values for each channel.\n * @property {Array.} channelsVisible List of boolean values for each channel for whether or not it is visible.\n * @property {string} dtype Dtype for the layer.\n * @property {string=} colormap String indicating a colormap (default: ''). The full list of options is here: https://github.com/glslify/glsl-colormap#glsl-colormap\n * @property {Array.>=} domain Override for the possible max/min values (i.e something different than 65535 for uint16/'=} xSlice 0-width (physical coordinates) interval on which to slice the volume.\n * @property {Array.=} ySlice 0-height (physical coordinates) interval on which to slice the volume.\n * @property {Array.=} zSlice 0-depth (physical coordinates) interval on which to slice the volume.\n * @property {Array.=} clippingPlanes List of math.gl [Plane](https://math.gl/modules/culling/docs/api-reference/plane) objects.\n * @property {Object=} resolutionMatrix Matrix for scaling the volume based on the (downsampled) resolution being displayed.\n */\n\n/**\n * @type {{ new (...props: import('../../../types').Viv[]) }}\n * @ignore\n */\n\n\nconst XR3DLayer = class extends Layer {\n initializeState() {\n const {\n gl\n } = this.context; // This tells WebGL how to read row data from the texture. For example, the default here is 4 (i.e for RGBA, one byte per channel) so\n // each row of data is expected to be a multiple of 4. This setting (i.e 1) allows us to have non-multiple-of-4 row sizes. For example, for 2 byte (16 bit data),\n // we could use 2 as the value and it would still work, but 1 also works fine (and is more flexible for 8 bit - 1 byte - textures as well).\n // https://stackoverflow.com/questions/42789896/webgl-error-arraybuffer-not-big-enough-for-request-in-case-of-gl-luminance\n\n gl.pixelStorei(GL.UNPACK_ALIGNMENT, 1);\n gl.pixelStorei(GL.PACK_ALIGNMENT, 1);\n const programManager = ProgramManager.getDefaultProgramManager(gl);\n const processStr = `fs:DECKGL_PROCESS_INTENSITY(inout float intensity, vec2 contrastLimits, int channelIndex)`;\n\n if (!programManager._hookFunctions.includes(processStr)) {\n programManager.addShaderHook(processStr);\n }\n }\n\n _isHookDefinedByExtensions(hookName) {\n const {\n extensions\n } = this.props;\n return extensions?.some(e => {\n const shaders = e.getShaders();\n const {\n inject = {},\n modules = []\n } = shaders;\n const definesInjection = inject[hookName];\n const moduleDefinesInjection = modules.some(m => m?.inject[hookName]);\n return definesInjection || moduleDefinesInjection;\n });\n }\n /**\n * This function compiles the shaders and the projection module.\n */\n\n\n getShaders() {\n const {\n colormap,\n renderingMode,\n clippingPlanes\n } = this.props;\n const {\n sampler\n } = getRenderingAttrs();\n const {\n _BEFORE_RENDER,\n _RENDER,\n _AFTER_RENDER\n } = colormap ? RENDERING_MODES_COLORMAP[renderingMode] : RENDERING_MODES_BLEND[renderingMode];\n const channelsModules = removeExtraColormapFunctionsFromShader(colormap);\n\n const extensionDefinesDeckglProcessIntensity = this._isHookDefinedByExtensions('fs:DECKGL_PROCESS_INTENSITY');\n\n const newChannelsModule = { ...channelsModules,\n inject: {}\n };\n\n if (!extensionDefinesDeckglProcessIntensity) {\n newChannelsModule.inject['fs:DECKGL_PROCESS_INTENSITY'] = `\n intensity = apply_contrast_limits(intensity, contrastLimits);\n `;\n }\n\n return super.getShaders({\n vs,\n fs: fs$1.replace('_BEFORE_RENDER', _BEFORE_RENDER).replace('_RENDER', _RENDER).replace('_AFTER_RENDER', _AFTER_RENDER),\n defines: {\n SAMPLER_TYPE: sampler,\n COLORMAP_FUNCTION: colormap || 'viridis',\n NUM_PLANES: String(clippingPlanes.length || NUM_PLANES_DEFAULT)\n },\n modules: [newChannelsModule]\n });\n }\n /**\n * This function finalizes state by clearing all textures from the WebGL context\n */\n\n\n finalizeState() {\n super.finalizeState();\n\n if (this.state.textures) {\n Object.values(this.state.textures).forEach(tex => tex && tex.delete());\n }\n }\n /**\n * This function updates state by retriggering model creation (shader compilation and attribute binding)\n * and loading any textures that need be loading.\n */\n\n\n updateState({\n props,\n oldProps,\n changeFlags\n }) {\n // setup model first\n if (changeFlags.extensionsChanged || props.colormap !== oldProps.colormap || props.renderingMode !== oldProps.renderingMode || props.clippingPlanes.length !== oldProps.clippingPlanes.length) {\n const {\n gl\n } = this.context;\n\n if (this.state.model) {\n this.state.model.delete();\n }\n\n this.setState({\n model: this._getModel(gl)\n });\n }\n\n if (props.channelData && props?.channelData?.data !== oldProps?.channelData?.data) {\n this.loadTexture(props.channelData);\n }\n }\n /**\n * This function creates the luma.gl model.\n */\n\n\n _getModel(gl) {\n if (!gl) {\n return null;\n }\n\n return new Model(gl, { ...this.getShaders(),\n geometry: new Geometry({\n drawMode: gl.TRIANGLE_STRIP,\n attributes: {\n positions: new Float32Array(CUBE_STRIP)\n }\n })\n });\n }\n /**\n * This function runs the shaders and draws to the canvas\n */\n\n\n draw({\n uniforms\n }) {\n const {\n textures,\n model,\n scaleMatrix\n } = this.state;\n const {\n contrastLimits,\n colors,\n xSlice,\n ySlice,\n zSlice,\n modelMatrix,\n channelsVisible,\n domain,\n dtype,\n clippingPlanes,\n resolutionMatrix\n } = this.props;\n const {\n viewMatrix,\n viewMatrixInverse,\n projectionMatrix\n } = this.context.viewport;\n\n if (textures && model && scaleMatrix) {\n const paddedContrastLimits = padContrastLimits({\n contrastLimits,\n channelsVisible,\n domain,\n dtype\n });\n const paddedColors = padColors({\n colors,\n channelsVisible\n });\n const invertedScaleMatrix = scaleMatrix.clone().invert();\n const invertedResolutionMatrix = resolutionMatrix.clone().invert();\n const paddedClippingPlanes = padWithDefault(clippingPlanes.map(p => p.clone().transform(invertedScaleMatrix).transform(invertedResolutionMatrix)), new Plane([1, 0, 0]), clippingPlanes.length || NUM_PLANES_DEFAULT); // Need to flatten for shaders.\n\n const normals = paddedClippingPlanes.map(plane => plane.normal).flat();\n const distances = paddedClippingPlanes.map(plane => plane.distance);\n model.setUniforms({ ...uniforms,\n ...textures,\n contrastLimits: paddedContrastLimits,\n colors: paddedColors,\n xSlice: new Float32Array(xSlice ? xSlice.map(i => i / scaleMatrix[0] / resolutionMatrix[0]) : [0, 1]),\n ySlice: new Float32Array(ySlice ? ySlice.map(i => i / scaleMatrix[5] / resolutionMatrix[5]) : [0, 1]),\n zSlice: new Float32Array(zSlice ? zSlice.map(i => i / scaleMatrix[10] / resolutionMatrix[10]) : [0, 1]),\n eye_pos: new Float32Array([viewMatrixInverse[12], viewMatrixInverse[13], viewMatrixInverse[14]]),\n view: viewMatrix,\n proj: projectionMatrix,\n scale: scaleMatrix,\n resolution: resolutionMatrix,\n model: modelMatrix || new Matrix4(),\n normals,\n distances\n }).draw();\n }\n }\n /**\n * This function loads all textures from incoming resolved promises/data from the loaders by calling `dataToTexture`\n */\n\n\n loadTexture(channelData) {\n const textures = {\n volume0: null,\n volume1: null,\n volume2: null,\n volume3: null,\n volume4: null,\n volume5: null\n };\n\n if (this.state.textures) {\n Object.values(this.state.textures).forEach(tex => tex && tex.delete());\n }\n\n if (channelData && Object.keys(channelData).length > 0 && channelData.data) {\n const {\n height,\n width,\n depth\n } = channelData;\n channelData.data.forEach((d, i) => {\n textures[`volume${i}`] = this.dataToTexture(d, width, height, depth);\n }, this);\n this.setState({\n textures,\n scaleMatrix: new Matrix4().scale(this.props.physicalSizeScalingMatrix.transformPoint([width, height, depth]))\n });\n }\n }\n /**\n * This function creates textures from the data\n */\n\n\n dataToTexture(data, width, height, depth) {\n const attrs = getRenderingAttrs();\n const texture = new Texture3D(this.context.gl, {\n width,\n height,\n depth,\n data: attrs.cast?.(data) ?? data,\n // ? Seems to be a luma.gl bug. Looks like Texture2D is wrong or this is but these are flipped somewhere.\n format: attrs.dataFormat,\n dataFormat: attrs.format,\n type: attrs.type,\n mipmaps: false,\n parameters: {\n [GL.TEXTURE_MIN_FILTER]: GL.LINEAR,\n [GL.TEXTURE_MAG_FILTER]: GL.LINEAR,\n [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE,\n [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE,\n [GL.TEXTURE_WRAP_R]: GL.CLAMP_TO_EDGE\n }\n });\n return texture;\n }\n\n};\nXR3DLayer.layerName = 'XR3DLayer';\nXR3DLayer.defaultProps = defaultProps$1;\n\n/* global globalThis */\n/**\n * Creates a single continguous TypedArray that can visualized as a volume in 3D space where the y-axis going up is positive,\n * the x-axis going right is positive, and the z-axis coming out of the screen is positive.\n * To do this, and keep the orientation, we must anti-diagonally transpose each slice of raster data so that the (0, 0) data point is transformed\n * to the top right. If you start the camera looking at the 0th slice (or rotate from looking at the final slice) in 3D, this becomes more apparent.\n * Of note here is that in 2D rendering, the y-axis is positive in the downward direction.\n *\n * @param {object} props\n * @param {object} props.source PixelSource\n * @param {object} props.selection A single selection for the PixelSource\n * @param {object} props.onUpdate A callback for progress that is called twice during the loading of each plane, once when the promsie resolves and once when it is loaded into the final contiguous buffer.\n * @param {object} props.downsampleDepth This is the number by which to downsample on the z direction, usually `2 ** resolution` where `resolution` is that of the `PixelSource` in the image pyramid.\n * The idea here is to get every `downsampleDepth` raster slice so that proper scaling is maintained (just liek a 2D image pyramid).\n * @return {TypedArray}\n * @ignore\n */\n\nasync function getVolume({\n source,\n selection,\n onUpdate = () => {},\n downsampleDepth = 1,\n signal\n}) {\n const {\n shape,\n labels,\n dtype\n } = source;\n const {\n height,\n width\n } = getImageSize(source);\n const depth = shape[labels.indexOf('z')];\n const depthDownsampled = Math.max(1, Math.floor(depth / downsampleDepth));\n const rasterSize = height * width;\n const name = `${dtype}Array`;\n const TypedArray = globalThis[name];\n const volumeData = new TypedArray(rasterSize * depthDownsampled);\n await Promise.all(new Array(depthDownsampled).fill(0).map(async (_, z) => {\n const depthSelection = { ...selection,\n z: z * downsampleDepth\n };\n const {\n data: rasterData\n } = await source.getRaster({\n selection: depthSelection,\n signal\n });\n let r = 0;\n onUpdate(); // For now this process fills in each raster plane anti-diagonally transposed.\n // This is to ensure that the image looks right in three dimensional space.\n\n while (r < rasterSize) {\n const volIndex = z * rasterSize + (rasterSize - r - 1);\n const rasterIndex = (width - r - 1) % width + width * Math.floor(r / width);\n volumeData[volIndex] = rasterData[rasterIndex];\n r += 1;\n }\n\n onUpdate();\n }));\n return {\n data: volumeData,\n height,\n width,\n depth: depthDownsampled\n };\n}\nconst getTextLayer = (text, viewport, id) => {\n return new TextLayer({\n id: `text-${id}`,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [{\n text,\n position: viewport.position\n }],\n getColor: [220, 220, 220, 255],\n getSize: 25,\n sizeUnits: 'meters',\n sizeScale: 2 ** -viewport.zoom,\n fontFamily: 'Helvetica'\n });\n};\n\nconst defaultProps = {\n pickable: false,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n contrastLimits: {\n type: 'array',\n value: [],\n compare: true\n },\n channelsVisible: {\n type: 'array',\n value: [],\n compare: true\n },\n colors: {\n type: 'array',\n value: [],\n compare: true\n },\n colormap: {\n type: 'string',\n value: '',\n compare: true\n },\n selections: {\n type: 'array',\n value: [],\n compare: true\n },\n resolution: {\n type: 'number',\n value: 0,\n compare: true\n },\n domain: {\n type: 'array',\n value: [],\n compare: true\n },\n loader: {\n type: 'object',\n value: [{\n getRaster: async () => ({\n data: [],\n height: 0,\n width: 0\n }),\n dtype: 'Uint16',\n shape: [1],\n labels: ['z']\n }],\n compare: true\n },\n xSlice: {\n type: 'array',\n value: null,\n compare: true\n },\n ySlice: {\n type: 'array',\n value: null,\n compare: true\n },\n zSlice: {\n type: 'array',\n value: null,\n compare: true\n },\n clippingPlanes: {\n type: 'array',\n value: [],\n compare: true\n },\n renderingMode: {\n type: 'string',\n value: RENDERING_MODES.MAX_INTENSITY_PROJECTION,\n compare: true\n },\n onUpdate: {\n type: 'function',\n value: () => {},\n compare: true\n },\n useProgressIndicator: {\n type: 'boolean',\n value: true,\n compare: true\n },\n useWebGL1Warning: {\n type: 'boolean',\n value: true,\n compare: true\n }\n};\n/**\n * @typedef LayerProps\n * @type {Object}\n * @property {Array.>} contrastLimits List of [begin, end] values to control each channel's ramp function.\n * @property {Array.>} colors List of [r, g, b] values for each channel.\n * @property {Array.} channelsVisible List of boolean values for each channel for whether or not it is visible.\n * @property {Array} loader PixelSource[]. Represents an N-dimensional image.\n * @property {Array} selections Selection to be used for fetching data.\n * @property {string=} colormap String indicating a colormap (default: ''). The full list of options is here: https://github.com/glslify/glsl-colormap#glsl-colormap\n * @property {Array.>=} domain Override for the possible max/min values (i.e something different than 65535 for uint16/'=} xSlice 0-width (physical coordinates) interval on which to slice the volume.\n * @property {Array.=} ySlice 0-height (physical coordinates) interval on which to slice the volume.\n * @property {Array.=} zSlice 0-depth (physical coordinates) interval on which to slice the volume.\n * @property {function=} onViewportLoad Function that gets called when the data in the viewport loads.\n * @property {Array.=} clippingPlanes List of math.gl [Plane](https://math.gl/modules/culling/docs/api-reference/plane) objects.\n * @property {boolean=} useProgressIndicator Whether or not to use the default progress text + indicator (default is true)\n * @property {boolean=} useWebGL1Warning Whether or not to use the default WebGL1 warning (default is true)\n * @property {function=} onUpdate A callback to be used for getting updates of the progress, ({ progress }) => {}\n */\n\n/**\n * @type {{ new (...props: import('../../types').Viv[]) }}\n * @ignore\n */\n\nconst VolumeLayer = class extends CompositeLayer {\n clearState() {\n this.setState({\n height: null,\n width: null,\n depth: null,\n data: null,\n physicalSizeScalingMatrix: null,\n resolutionMatrix: null,\n progress: 0,\n abortController: null\n });\n }\n\n finalizeState() {\n this.state.abortController.abort();\n }\n\n updateState({\n oldProps,\n props\n }) {\n const loaderChanged = props.loader !== oldProps.loader;\n const resolutionChanged = props.resolution !== oldProps.resolution;\n const selectionsChanged = props.selections !== oldProps.selections; // Only fetch new data to render if loader has changed\n\n if (resolutionChanged) {\n // Clear last volume.\n this.clearState();\n }\n\n if (loaderChanged || selectionsChanged || resolutionChanged) {\n const {\n loader,\n selections = [],\n resolution,\n onViewportLoad\n } = this.props;\n const source = loader[resolution];\n let progress = 0;\n const totalRequests = // eslint-disable-next-line no-bitwise\n (source.shape[source.labels.indexOf('z')] >> resolution) * selections.length;\n\n const onUpdate = () => {\n progress += 0.5 / totalRequests;\n\n if (this.props.onUpdate) {\n this.props.onUpdate({\n progress\n });\n }\n\n this.setState({\n progress\n });\n };\n\n const abortController = new AbortController();\n this.setState({\n abortController\n });\n const {\n signal\n } = abortController;\n const volumePromises = selections.map(selection => getVolume({\n selection,\n source,\n onUpdate,\n downsampleDepth: 2 ** resolution,\n signal\n }));\n const physicalSizeScalingMatrix = getPhysicalSizeScalingMatrix(loader[resolution]);\n Promise.all(volumePromises).then(volumes => {\n if (onViewportLoad) {\n onViewportLoad(volumes);\n }\n\n const volume = {\n data: volumes.map(d => d.data),\n width: volumes[0].width,\n height: volumes[0].height,\n depth: volumes[0].depth\n };\n this.setState({ ...volume,\n physicalSizeScalingMatrix,\n resolutionMatrix: new Matrix4().scale(2 ** resolution)\n });\n });\n }\n }\n\n renderLayers() {\n const {\n loader,\n id,\n resolution,\n useProgressIndicator,\n useWebGL1Warning\n } = this.props;\n const {\n dtype\n } = loader[resolution];\n const {\n data,\n width,\n height,\n depth,\n progress,\n physicalSizeScalingMatrix,\n resolutionMatrix\n } = this.state;\n const {\n gl\n } = this.context;\n\n if (!isWebGL2(gl) && useWebGL1Warning) {\n const {\n viewport\n } = this.context;\n return getTextLayer(['Volume rendering is only available on browsers that support WebGL2. If you', 'are using Safari, you can turn on WebGL2 by navigating in the top menubar', 'to check Develop > Experimental Features > WebGL 2.0 and then refreshing', 'the page.'].join('\\n'), viewport, id);\n }\n\n if (!(width && height) && useProgressIndicator) {\n const {\n viewport\n } = this.context;\n return getTextLayer(`Loading Volume ${String((progress || 0) * 100).slice(0, 5)}%...`, viewport, id);\n }\n\n return new XR3DLayer(this.props, {\n channelData: {\n data,\n width,\n height,\n depth\n },\n id: `XR3DLayer-${0}-${height}-${width}-${0}-${resolution}-${id}`,\n physicalSizeScalingMatrix,\n parameters: {\n [GL.CULL_FACE]: true,\n [GL.CULL_FACE_MODE]: GL.FRONT,\n [GL.DEPTH_TEST]: false,\n blendFunc: [GL.SRC_ALPHA, GL.ONE],\n blend: true\n },\n resolutionMatrix,\n dtype\n });\n }\n\n};\nVolumeLayer.layerName = 'VolumeLayer';\nVolumeLayer.defaultProps = defaultProps;\n\nvar _jsxFileName$3 = \"/Users/ilangold/Projects/Gehlenborg/viv/src/viewers/VivViewer.jsx\";\nconst areViewStatesEqual = (viewState, otherViewState) => {\n return otherViewState === viewState || viewState?.zoom === otherViewState?.zoom && viewState?.rotationX === otherViewState?.rotationX && viewState?.rotationOrbit === otherViewState?.rotationOrbit && equal(viewState?.target, otherViewState?.target);\n};\nclass VivViewerWrapper extends PureComponent {\n constructor(props) {\n super(props);\n this.state = {\n viewStates: {}\n };\n const {\n viewStates\n } = this.state;\n const {\n views,\n viewStates: initialViewStates\n } = this.props;\n views.forEach((view) => {\n viewStates[view.id] = view.filterViewState({\n viewState: initialViewStates.find((v) => v.id === view.id)\n });\n });\n this._onViewStateChange = this._onViewStateChange.bind(this);\n this.layerFilter = this.layerFilter.bind(this);\n this.onHover = this.onHover.bind(this);\n }\n layerFilter({\n layer,\n viewport\n }) {\n return layer.id.includes(getVivId(viewport.id));\n }\n _onViewStateChange({\n viewId,\n viewState,\n interactionState,\n oldViewState\n }) {\n const {\n views,\n onViewStateChange\n } = this.props;\n viewState = onViewStateChange && onViewStateChange({\n viewId,\n viewState,\n interactionState,\n oldViewState\n }) || viewState;\n this.setState((prevState) => {\n const viewStates = {};\n views.forEach((view) => {\n const currentViewState = prevState.viewStates[view.id];\n viewStates[view.id] = view.filterViewState({\n viewState: {\n ...viewState,\n id: viewId\n },\n oldViewState,\n currentViewState\n });\n });\n return {\n viewStates\n };\n });\n return viewState;\n }\n componentDidUpdate(prevProps) {\n const {\n props\n } = this;\n const {\n views\n } = props;\n const viewStates = {\n ...this.state.viewStates\n };\n let anyChanged = false;\n views.forEach((view) => {\n const currViewState = props.viewStates?.find((viewState) => viewState.id === view.id);\n if (!currViewState) {\n return;\n }\n const prevViewState = prevProps.viewStates?.find((viewState) => viewState.id === view.id);\n if (areViewStatesEqual(currViewState, prevViewState)) {\n return;\n }\n anyChanged = true;\n const {\n height,\n width\n } = view;\n viewStates[view.id] = view.filterViewState({\n viewState: {\n ...currViewState,\n height,\n width,\n id: view.id\n }\n });\n });\n if (anyChanged) {\n this.setState({\n viewStates\n });\n }\n }\n static getDerivedStateFromProps(props, prevState) {\n const {\n views,\n viewStates: viewStatesProps\n } = props;\n if (views.some((view) => !prevState.viewStates[view.id] || view.height !== prevState.viewStates[view.id].height || view.width !== prevState.viewStates[view.id].width)) {\n const viewStates = {};\n views.forEach((view) => {\n const {\n height,\n width\n } = view;\n const currentViewState = prevState.viewStates[view.id];\n viewStates[view.id] = view.filterViewState({\n viewState: {\n ...currentViewState || viewStatesProps.find((v) => v.id === view.id),\n height,\n width,\n id: view.id\n }\n });\n });\n return {\n viewStates\n };\n }\n return prevState;\n }\n onHover(info, event) {\n const {\n tile,\n coordinate,\n sourceLayer: layer\n } = info;\n const {\n onHover,\n hoverHooks\n } = this.props;\n if (onHover) {\n onHover(info, event);\n }\n if (!hoverHooks || !coordinate || !layer) {\n return null;\n }\n const {\n handleValue = () => {\n },\n handleCoordnate = () => {\n }\n } = hoverHooks;\n let hoverData;\n if (layer.id.includes(\"Tiled\")) {\n if (!tile?.content) {\n return null;\n }\n const {\n content,\n bbox,\n z\n } = tile;\n if (!content.data || !bbox) {\n return null;\n }\n const {\n data,\n width,\n height\n } = content;\n const {\n left,\n right,\n top,\n bottom\n } = bbox;\n const bounds = [left, data.height < layer.tileSize ? height : bottom, data.width < layer.tileSize ? width : right, top];\n if (!data) {\n return null;\n }\n const layerZoomScale = Math.max(1, 2 ** Math.round(-z));\n const dataCoords = [Math.floor((coordinate[0] - bounds[0]) / layerZoomScale), Math.floor((coordinate[1] - bounds[3]) / layerZoomScale)];\n const coords = dataCoords[1] * width + dataCoords[0];\n hoverData = data.map((d) => d[coords]);\n } else {\n const {\n channelData\n } = layer.props;\n if (!channelData) {\n return null;\n }\n const {\n data,\n width,\n height\n } = channelData;\n if (!data || !width || !height) {\n return null;\n }\n const bounds = [0, height, width, 0];\n const {\n zoom\n } = layer.context.viewport;\n const layerZoomScale = Math.max(1, 2 ** Math.floor(-zoom));\n const dataCoords = [Math.floor((coordinate[0] - bounds[0]) / layerZoomScale), Math.floor((coordinate[1] - bounds[3]) / layerZoomScale)];\n const coords = dataCoords[1] * width + dataCoords[0];\n hoverData = data.map((d) => d[coords]);\n }\n handleValue(hoverData);\n handleCoordnate(coordinate);\n }\n _renderLayers() {\n const {\n onHover\n } = this;\n const {\n viewStates\n } = this.state;\n const {\n views,\n layerProps\n } = this.props;\n return views.map((view, i) => view.getLayers({\n viewStates,\n props: {\n ...layerProps[i],\n onHover\n }\n }));\n }\n render() {\n const {\n views,\n randomize,\n useDevicePixels = true,\n deckProps\n } = this.props;\n const {\n viewStates\n } = this.state;\n const deckGLViews = views.map((view) => view.getDeckGlView());\n if (randomize) {\n const random = Math.random();\n const holdFirstElement = deckGLViews[0];\n const randomWieghted = random * 1.49;\n const randomizedIndex = Math.round(randomWieghted * (views.length - 1));\n deckGLViews[0] = deckGLViews[randomizedIndex];\n deckGLViews[randomizedIndex] = holdFirstElement;\n }\n return /* @__PURE__ */ jsxDEV(DeckGL, {\n ...deckProps ?? {},\n layerFilter: this.layerFilter,\n layers: this._renderLayers(),\n onViewStateChange: this._onViewStateChange,\n views: deckGLViews,\n viewState: viewStates,\n useDevicePixels,\n getCursor: ({\n isDragging\n }) => {\n return isDragging ? \"grabbing\" : \"crosshair\";\n }\n }, void 0, false, {\n fileName: _jsxFileName$3,\n lineNumber: 301,\n columnNumber: 7\n }, this);\n }\n}\nconst VivViewer = (props) => /* @__PURE__ */ jsxDEV(VivViewerWrapper, {\n ...props\n}, void 0, false, {\n fileName: _jsxFileName$3,\n lineNumber: 333,\n columnNumber: 28\n}, undefined);\n\n/**\n * This class generates a layer and a view for use in the VivViewer\n * @param {Object} args\n * @param {string} args.id id for this VivView.\n * @param {Object} args.height Width of the view.\n * @param {Object} args.width Height of the view.\n * @param {string} args.id Id for the current view\n * @param {number=} args.x X (top-left) location on the screen for the current view\n * @param {number=} args.y Y (top-left) location on the screen for the current view\n */\n\nclass VivView {\n constructor({\n id,\n x = 0,\n y = 0,\n height,\n width\n }) {\n this.width = width;\n this.height = height;\n this.id = id;\n this.x = x;\n this.y = y;\n }\n /**\n * Create a DeckGL view based on this class.\n * @returns {View} The DeckGL View for this class.\n */\n\n\n getDeckGlView() {\n return new OrthographicView({\n controller: true,\n id: this.id,\n height: this.height,\n width: this.width,\n x: this.x,\n y: this.y\n });\n }\n /**\n * Create a viewState for this class, checking the id to make sure this class and veiwState match.\n * @param {Object} args\n * @param {object} [args.viewState] incoming ViewState object from deck.gl update.\n * @param {object} [args.oldViewState] old ViewState object from deck.gl.\n * @param {object} [args.currentViewState] current ViewState object in react state.\n * @returns {?object} ViewState for this class (or null by default if the ids do not match).\n */\n\n\n filterViewState({\n viewState\n }) {\n const {\n id,\n height,\n width\n } = this;\n return viewState.id === id ? {\n height,\n width,\n ...viewState\n } : null;\n }\n /**\n * Create a layer for this instance.\n * @param {Object} args\n * @param {Object} args.viewStates ViewStates for all current views.\n * @param {Object} args.props Props for this instance.\n * @returns {Layer} Instance of a layer.\n */\n // eslint-disable-next-line class-methods-use-this,no-unused-vars\n\n\n getLayers({\n viewStates,\n props\n }) {}\n\n}\n\n/* eslint-disable max-classes-per-file */\nconst OVERVIEW_VIEW_ID = 'overview';\n\nclass OverviewState {}\n\nclass OverviewController extends Controller {\n constructor(props) {\n super(OverviewState, props);\n this.events = ['click'];\n }\n\n handleEvent(event) {\n if (event.type !== 'click') {\n return;\n }\n\n let [x, y] = this.getCenter(event);\n const {\n width,\n height,\n zoom,\n scale\n } = this.controllerStateProps;\n\n if (x < 0 || y < 0 || x > width || y > height) {\n return;\n }\n\n const scaleFactor = 1 / (2 ** zoom * scale);\n x *= scaleFactor;\n y *= scaleFactor;\n\n if (this.onViewStateChange) {\n this.onViewStateChange({\n viewState: {\n target: [x, y, 0]\n }\n });\n }\n }\n\n}\n/**\n * This class generates a OverviewLayer and a view for use in the VivViewer as an overview to a Detailview (they must be used in conjection).\n * From the base class VivView, only the initialViewState argument is used. This class uses private methods to position its x and y from the\n * additional arguments:\n * @param {Object} args\n * @param {Object} args.id for thie VivView\n * @param {Object} args.loader PixelSource[], where each PixelSource is decreasing in shape. If length == 1, not multiscale.\n * @param {number} args.detailHeight Height of the detail view.\n * @param {number} args.detailWidth Width of the detail view.\n * @param {number} [args.scale] Scale of this viewport relative to the detail. Default is .2.\n * @param {number} [args.margin] Margin to be offset from the the corner of the other viewport. Default is 25.\n * @param {string} [args.position] Location of the viewport - one of \"bottom-right\", \"top-right\", \"top-left\", \"bottom-left.\" Default is 'bottom-right'.\n * @param {number} [args.minimumWidth] Absolute lower bound for how small the viewport should scale. Default is 150.\n * @param {number} [args.maximumWidth] Absolute upper bound for how large the viewport should scale. Default is 350.\n * @param {number} [args.minimumHeight] Absolute lower bound for how small the viewport should scale. Default is 150.\n * @param {number} [args.maximumHeight] Absolute upper bound for how large the viewport should scale. Default is 350.\n * @param {Boolean} [args.clickCenter] Click to center the default view. Default is true.\n * */\n\n\nclass OverviewView extends VivView {\n constructor({\n id,\n loader,\n detailHeight,\n detailWidth,\n scale = 0.2,\n margin = 25,\n position = 'bottom-right',\n minimumWidth = 150,\n maximumWidth = 350,\n minimumHeight = 150,\n maximumHeight = 350,\n clickCenter = true\n }) {\n super({\n id\n });\n this.margin = margin;\n this.loader = loader;\n this.position = position;\n this.detailHeight = detailHeight;\n this.detailWidth = detailWidth;\n\n this._setHeightWidthScale({\n detailWidth,\n detailHeight,\n scale,\n minimumWidth,\n maximumWidth,\n minimumHeight,\n maximumHeight\n });\n\n this._setXY();\n\n this.clickCenter = clickCenter;\n }\n /**\n * Set the image-pixel scale and height and width based on detail view.\n */\n\n\n _setHeightWidthScale({\n detailWidth,\n detailHeight,\n scale,\n minimumWidth,\n maximumWidth,\n minimumHeight,\n maximumHeight\n }) {\n const numLevels = this.loader.length;\n const {\n width: rasterWidth,\n height: rasterHeight\n } = getImageSize(this.loader[0]);\n this._imageWidth = rasterWidth;\n this._imageHeight = rasterHeight;\n\n if (rasterWidth > rasterHeight) {\n const heightWidthRatio = rasterHeight / rasterWidth;\n this.width = Math.min(maximumWidth, Math.max(detailWidth * scale, minimumWidth));\n this.height = this.width * heightWidthRatio;\n this.scale = 2 ** (numLevels - 1) / rasterWidth * this.width;\n } else {\n const widthHeightRatio = rasterWidth / rasterHeight;\n this.height = Math.min(maximumHeight, Math.max(detailHeight * scale, minimumHeight));\n this.width = this.height * widthHeightRatio;\n this.scale = 2 ** (numLevels - 1) / rasterHeight * this.height;\n }\n }\n /**\n * Set the x and y (top left corner) of this overview relative to the detail.\n */\n\n\n _setXY() {\n const {\n height,\n width,\n margin,\n position,\n detailWidth,\n detailHeight\n } = this;\n\n switch (position) {\n case 'bottom-right':\n {\n this.x = detailWidth - width - margin;\n this.y = detailHeight - height - margin;\n break;\n }\n\n case 'top-right':\n {\n this.x = detailWidth - width - margin;\n this.y = margin;\n break;\n }\n\n case 'top-left':\n {\n this.x = margin;\n this.y = margin;\n break;\n }\n\n case 'bottom-left':\n {\n this.x = margin;\n this.y = detailHeight - height - margin;\n break;\n }\n\n default:\n {\n throw new Error(`overviewLocation prop needs to be one of ['bottom-right', 'top-right', 'top-left', 'bottom-left']`);\n }\n }\n }\n\n getDeckGlView() {\n const {\n scale,\n clickCenter\n } = this;\n const controller = clickCenter && {\n type: OverviewController,\n scale\n };\n return new OrthographicView({\n controller,\n id: this.id,\n height: this.height,\n width: this.width,\n x: this.x,\n y: this.y,\n clear: true\n });\n }\n\n filterViewState({\n viewState\n }) {\n // Scale the view as the overviewScale changes with screen resizing - basically, do not react to any view state changes.\n const {\n _imageWidth,\n _imageHeight,\n scale\n } = this;\n return { ...viewState,\n height: this.height,\n width: this.width,\n id: this.id,\n target: [_imageWidth * scale / 2, _imageHeight * scale / 2, 0],\n zoom: -(this.loader.length - 1)\n };\n }\n\n getLayers({\n viewStates,\n props\n }) {\n const {\n detail,\n overview\n } = viewStates;\n\n if (!detail) {\n throw new Error('Overview requires a viewState with id detail');\n } // Scale the bounding box.\n\n\n const boundingBox = makeBoundingBox(detail).map(coords => coords.map(e => e * this.scale));\n const overviewLayer = new OverviewLayer(props, {\n id: getVivId(this.id),\n boundingBox,\n overviewScale: this.scale,\n zoom: -overview.zoom\n });\n return [overviewLayer];\n }\n\n}\n\nconst DETAIL_VIEW_ID = 'detail';\n/**\n * This class generates a MultiscaleImageLayer and a view for use in the VivViewer as a detailed view.\n * It takes the same arguments for its constructor as its base class VivView.\n * */\n\nclass DetailView extends VivView {\n getLayers({\n props,\n viewStates\n }) {\n const {\n loader\n } = props;\n const {\n id,\n height,\n width\n } = this;\n const layerViewState = viewStates[id];\n const layers = [getImageLayer(id, props)]; // Inspect the first pixel source for physical sizes\n\n if (loader[0]?.meta?.physicalSizes?.x) {\n const {\n size,\n unit\n } = loader[0].meta.physicalSizes.x;\n layers.push(new ScaleBarLayer({\n id: getVivId(id),\n loader,\n unit,\n size,\n viewState: { ...layerViewState,\n height,\n width\n }\n }));\n }\n\n return layers;\n }\n\n filterViewState({\n viewState,\n currentViewState\n }) {\n if (viewState.id === OVERVIEW_VIEW_ID) {\n const {\n target\n } = viewState;\n\n if (target) {\n return { ...currentViewState,\n target\n };\n }\n }\n\n return super.filterViewState({\n viewState\n });\n }\n\n}\n\n/**\n * This class generates a MultiscaleImageLayer and a view for use in the SideBySideViewer.\n * It is linked with its other views as controlled by `linkedIds`, `zoomLock`, and `panLock` parameters.\n * It takes the same arguments for its constructor as its base class VivView plus the following:\n * @param {Object} args\n * @param {Array} args.linkedIds Ids of the other views to which this could be locked via zoom/pan.\n * @param {Boolean} args.panLock Whether or not we lock pan.\n * @param {Boolean} args.zoomLock Whether or not we lock zoom.\n * @param {Array=} args.viewportOutlineColor Outline color of the border (default [255, 255, 255])\n * @param {number=} args.viewportOutlineWidth Default outline width (default 10)\n * @param {number=} args.x X (top-left) location on the screen for the current view\n * @param {number=} args.y Y (top-left) location on the screen for the current view\n * @param {number} args.height Width of the view.\n * @param {number} args.width Height of the view.\n * @param {string} args.id id of the View\n * */\n\nclass SideBySideView extends VivView {\n constructor({\n id,\n x = 0,\n y = 0,\n height,\n width,\n linkedIds = [],\n panLock = true,\n zoomLock = true,\n viewportOutlineColor = [255, 255, 255],\n viewportOutlineWidth = 10\n }) {\n super({\n id,\n x,\n y,\n height,\n width\n });\n this.linkedIds = linkedIds;\n this.panLock = panLock;\n this.zoomLock = zoomLock;\n this.viewportOutlineColor = viewportOutlineColor;\n this.viewportOutlineWidth = viewportOutlineWidth;\n }\n\n filterViewState({\n viewState,\n oldViewState,\n currentViewState\n }) {\n const {\n id: viewStateId\n } = viewState;\n const {\n id,\n linkedIds,\n panLock,\n zoomLock\n } = this;\n\n if (oldViewState && linkedIds.indexOf(viewStateId) !== -1 && (zoomLock || panLock)) {\n const thisViewState = {\n height: currentViewState.height,\n width: currentViewState.width,\n target: [],\n zoom: null\n };\n const [currentX, currentY] = currentViewState.target;\n\n if (zoomLock) {\n const dZoom = viewState.zoom - oldViewState.zoom;\n thisViewState.zoom = currentViewState.zoom + dZoom;\n } else {\n thisViewState.zoom = currentViewState.zoom;\n }\n\n if (panLock) {\n const [oldX, oldY] = oldViewState.target;\n const [newX, newY] = viewState.target;\n const dx = newX - oldX;\n const dy = newY - oldY;\n thisViewState.target.push(currentX + dx);\n thisViewState.target.push(currentY + dy);\n } else {\n thisViewState.target.push(currentX);\n thisViewState.target.push(currentY);\n }\n\n return {\n id,\n target: thisViewState.target,\n zoom: thisViewState.zoom,\n height: thisViewState.height,\n width: thisViewState.width\n };\n }\n\n return viewState.id === id ? {\n id,\n target: viewState.target,\n zoom: viewState.zoom,\n height: viewState.height,\n width: viewState.width\n } : {\n id,\n target: currentViewState.target,\n zoom: currentViewState.zoom,\n height: currentViewState.height,\n width: currentViewState.width\n };\n }\n\n getLayers({\n props,\n viewStates\n }) {\n const {\n loader\n } = props;\n const {\n id,\n viewportOutlineColor,\n viewportOutlineWidth,\n height,\n width\n } = this;\n const layerViewState = viewStates[id];\n const boundingBox = makeBoundingBox({ ...layerViewState,\n height,\n width\n });\n const layers = [getImageLayer(id, props)];\n const border = new PolygonLayer({\n id: `viewport-outline-${getVivId(id)}`,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [boundingBox],\n getPolygon: f => f,\n filled: false,\n stroked: true,\n getLineColor: viewportOutlineColor,\n getLineWidth: viewportOutlineWidth * 2 ** -layerViewState.zoom\n });\n layers.push(border);\n\n if (loader[0]?.meta?.physicalSizes?.x) {\n const {\n size,\n unit\n } = loader[0].meta.physicalSizes.x;\n layers.push(new ScaleBarLayer({\n id: getVivId(id),\n loader,\n unit,\n size,\n viewState: { ...layerViewState,\n height,\n width\n }\n }));\n }\n\n return layers;\n }\n\n}\n\n/**\n * This class generates a VolumeLayer and a view for use in the VivViewer as volumetric rendering.\n * @param {Object} args\n * @param {Array} args.target Centered target for the camera (used if useFixedAxis is true)\n * @param {Boolean} args.useFixedAxis Whether or not to fix the axis of the camera.\n * */\n\nclass VolumeView extends VivView {\n constructor({\n target,\n useFixedAxis,\n ...args\n }) {\n super(args);\n this.target = target;\n this.useFixedAxis = useFixedAxis;\n }\n\n getDeckGlView() {\n const {\n height,\n width,\n id,\n x,\n y\n } = this;\n return new OrbitView({\n id,\n controller: true,\n height,\n width,\n x,\n y,\n orbitAxis: 'Y'\n });\n }\n\n filterViewState({\n viewState\n }) {\n const {\n id,\n target,\n useFixedAxis\n } = this;\n return viewState.id === id ? { ...viewState,\n // fix the center of the camera if desired\n target: useFixedAxis ? target : viewState.target\n } : null;\n }\n\n getLayers({\n props\n }) {\n const {\n loader\n } = props;\n const {\n id\n } = this;\n const layers = [new VolumeLayer(props, {\n id: `${loader.type}${getVivId(id)}`\n })];\n return layers;\n }\n\n}\n\nvar _jsxFileName$2 = \"/Users/ilangold/Projects/Gehlenborg/viv/src/viewers/PictureInPictureViewer.jsx\";\nconst PictureInPictureViewer = (props) => {\n const {\n loader,\n contrastLimits,\n colors,\n channelsVisible,\n viewStates: viewStatesProp,\n colormap,\n overview,\n overviewOn,\n selections,\n hoverHooks = {\n handleValue: () => {\n },\n handleCoordinate: () => {\n }\n },\n height,\n width,\n lensEnabled = false,\n lensSelection = 0,\n lensRadius = 100,\n lensBorderColor = [255, 255, 255],\n lensBorderRadius = 0.02,\n clickCenter = true,\n transparentColor,\n onViewStateChange,\n onHover,\n onViewportLoad,\n extensions = [new ColorPaletteExtension()],\n deckProps\n } = props;\n const detailViewState = viewStatesProp?.find((v) => v.id === DETAIL_VIEW_ID);\n const baseViewState = useMemo(() => {\n return detailViewState || getDefaultInitialViewState(loader, {\n height,\n width\n }, 0.5);\n }, [loader, detailViewState]);\n const detailView = new DetailView({\n id: DETAIL_VIEW_ID,\n height,\n width\n });\n const layerConfig = {\n loader,\n contrastLimits,\n colors,\n channelsVisible,\n selections,\n onViewportLoad,\n colormap,\n lensEnabled,\n lensSelection,\n lensRadius,\n lensBorderColor,\n lensBorderRadius,\n extensions,\n transparentColor\n };\n const views = [detailView];\n const layerProps = [layerConfig];\n const viewStates = [{\n ...baseViewState,\n id: DETAIL_VIEW_ID\n }];\n if (overviewOn && loader) {\n const overviewViewState = viewStatesProp?.find((v) => v.id === OVERVIEW_VIEW_ID) || {\n ...baseViewState,\n id: OVERVIEW_VIEW_ID\n };\n const overviewView = new OverviewView({\n id: OVERVIEW_VIEW_ID,\n loader,\n detailHeight: height,\n detailWidth: width,\n clickCenter,\n ...overview\n });\n views.push(overviewView);\n layerProps.push({\n ...layerConfig,\n lensEnabled: false\n });\n viewStates.push(overviewViewState);\n }\n if (!loader)\n return null;\n return /* @__PURE__ */ jsxDEV(VivViewer, {\n layerProps,\n views,\n viewStates,\n hoverHooks,\n onViewStateChange,\n onHover,\n deckProps\n }, void 0, false, {\n fileName: _jsxFileName$2,\n lineNumber: 127,\n columnNumber: 5\n }, undefined);\n};\n\nvar _jsxFileName$1 = \"/Users/ilangold/Projects/Gehlenborg/viv/src/viewers/SideBySideViewer.jsx\";\nconst SideBySideViewer = (props) => {\n const {\n loader,\n contrastLimits,\n colors,\n channelsVisible,\n viewStates: viewStatesProp,\n colormap,\n panLock,\n selections,\n zoomLock,\n height,\n width,\n lensEnabled = false,\n lensSelection = 0,\n lensRadius = 100,\n lensBorderColor = [255, 255, 255],\n lensBorderRadius = 0.02,\n transparentColor,\n onViewStateChange,\n onHover,\n onViewportLoad,\n extensions = [new ColorPaletteExtension()],\n deckProps\n } = props;\n const leftViewState = viewStatesProp?.find((v) => v.id === \"left\");\n const rightViewState = viewStatesProp?.find((v) => v.id === \"right\");\n const viewStates = useMemo(() => {\n if (leftViewState && rightViewState) {\n return viewStatesProp;\n }\n const defaultViewState = getDefaultInitialViewState(loader, {\n height,\n width: width / 2\n }, 0.5);\n return [leftViewState || {\n ...defaultViewState,\n id: \"left\"\n }, rightViewState || {\n ...defaultViewState,\n id: \"right\"\n }];\n }, [loader, leftViewState, rightViewState]);\n const detailViewLeft = new SideBySideView({\n id: \"left\",\n linkedIds: [\"right\"],\n panLock,\n zoomLock,\n height,\n width: width / 2\n });\n const detailViewRight = new SideBySideView({\n id: \"right\",\n x: width / 2,\n linkedIds: [\"left\"],\n panLock,\n zoomLock,\n height,\n width: width / 2\n });\n const layerConfig = {\n loader,\n contrastLimits,\n colors,\n channelsVisible,\n selections,\n onViewportLoad,\n colormap,\n lensEnabled,\n lensSelection,\n lensRadius,\n lensBorderColor,\n lensBorderRadius,\n extensions,\n transparentColor\n };\n const views = [detailViewRight, detailViewLeft];\n const layerProps = [layerConfig, layerConfig];\n return loader ? /* @__PURE__ */ jsxDEV(VivViewer, {\n layerProps,\n views,\n randomize: true,\n onViewStateChange,\n onHover,\n viewStates,\n deckProps\n }, void 0, false, {\n fileName: _jsxFileName$1,\n lineNumber: 115,\n columnNumber: 5\n }, undefined) : null;\n};\n\nvar _jsxFileName = \"/Users/ilangold/Projects/Gehlenborg/viv/src/viewers/VolumeViewer.jsx\";\nconst VolumeViewer = (props) => {\n const {\n loader,\n contrastLimits,\n colors,\n channelsVisible,\n selections,\n colormap,\n resolution = Math.max(0, loader.length - 1),\n modelMatrix,\n onViewStateChange,\n renderingMode = RENDERING_MODES.ADDITIVE,\n xSlice = null,\n ySlice = null,\n zSlice = null,\n onViewportLoad,\n height: screenHeight,\n width: screenWidth,\n viewStates: viewStatesProp,\n clippingPlanes = [],\n useFixedAxis = true\n } = props;\n const volumeViewState = viewStatesProp?.find((state) => state?.id === \"3d\");\n const initialViewState = useMemo(() => {\n if (volumeViewState) {\n return volumeViewState;\n }\n const viewState = getDefaultInitialViewState(loader, {\n height: screenHeight,\n width: screenWidth\n }, 1, true, modelMatrix);\n return {\n ...viewState,\n rotationX: 0,\n rotationOrbit: 0\n };\n }, [loader, resolution, modelMatrix]);\n const viewStates = [volumeViewState || {\n ...initialViewState,\n id: \"3d\"\n }];\n const volumeView = new VolumeView({\n id: \"3d\",\n target: viewStates[0].target,\n useFixedAxis\n });\n const layerConfig = {\n loader,\n contrastLimits,\n colors,\n channelsVisible,\n selections,\n colormap,\n xSlice,\n ySlice,\n zSlice,\n resolution,\n renderingMode,\n modelMatrix,\n onViewportLoad: () => setTimeout(onViewportLoad, 0),\n clippingPlanes\n };\n const views = [volumeView];\n const layerProps = [layerConfig];\n return loader ? /* @__PURE__ */ jsxDEV(VivViewer, {\n layerProps,\n views,\n viewStates,\n onViewStateChange,\n useDevicePixels: false\n }, void 0, false, {\n fileName: _jsxFileName,\n lineNumber: 100,\n columnNumber: 5\n }, undefined) : null;\n};\n\nconst VIV_PROXY_KEY = \"__viv\";\nconst OFFSETS_PROXY_KEY = `${VIV_PROXY_KEY}-offsets`;\nfunction checkProxies(tiff) {\n if (!isProxy(tiff, OFFSETS_PROXY_KEY)) {\n console.warn(\"GeoTIFF source is missing offsets proxy.\");\n }\n}\nfunction isProxy(tiff, proxyFlag) {\n return tiff[proxyFlag];\n}\nfunction createOffsetsProxy(tiff, offsets) {\n const get = (target, key) => {\n if (key === \"getImage\") {\n return (index) => {\n if (!(index in target.ifdRequests) && index in offsets) {\n const offset = offsets[index];\n target.ifdRequests[index] = target.parseFileDirectoryAt(offset);\n }\n return target.getImage(index);\n };\n }\n if (key === OFFSETS_PROXY_KEY) {\n return true;\n }\n return Reflect.get(target, key);\n };\n return new Proxy(tiff, {\n get\n });\n}\n\nconst encodedJs = \"KGZ1bmN0aW9uICgpIHsKICAndXNlIHN0cmljdCc7CgogIGZ1bmN0aW9uIGRlY29kZVJvd0FjYyhyb3csIHN0cmlkZSkgewogICAgbGV0IGxlbmd0aCA9IHJvdy5sZW5ndGggLSBzdHJpZGU7CiAgICBsZXQgb2Zmc2V0ID0gMDsKICAgIGRvIHsKICAgICAgZm9yIChsZXQgaSA9I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gPSBuZXcgVWludDhBcnJheSgKICAgICAgICAgICAgICBibG9jaywgaSAqIHN0cmlkZSAqIHdpZHRoICogYnl0ZXNQZXJTYW1wbGUsIHN0cmlkZSAqIHdpZHRoICogYnl0ZXNQZXJTYW1wbGUsCiAgICAgICAgICAgICk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgY2FzZSAxNjoKICAgICAgICAgICAgcm93ID0gbmV3IFVpbnQxNkFycmF5KAogICAgICAgICAgICAgIGJsb2NrLCBpICogc3RyaWRlICogd2lkdGggKiBieXRlc1BlclNhbXBsZSwgc3RyaWRlICogd2lkdGggKiBieXRlc1BlclNhbXBsZSAvIDIsCiAgICAgICAgICAgICk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgY2FzZSAzMjoKICAgICAgICAgICAgcm93ID0gbmV3IFVpbnQzMkFycmF5KAogICAgICAgICAgICAgIGJsb2NrLCBpICogc3RyaWRlICogd2lkdGggKiBieXRlc1BlclNhbXBsZSwgc3RyaWRlICogd2lkdGggKiBieXRlc1BlclNhbXBsZSAvIDQsCiAgICAgICAgICAgICk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBQcmVkaWN0b3IgMiBub3QgYWxsb3dlZCB3aXRoICR7Yml0c1BlclNhbXBsZVswXX0gYml0cyBwZXIgc2FtcGxlLmApOwogICAgICAgIH0KICAgICAgICBkZWNvZGVSb3dBY2Mocm93LCBzdHJpZGUpOwogICAgICB9IGVsc2UgaWYgKHByZWRpY3RvciA9PT0gMykgeyAvLyBob3Jpem9udGFsIGZsb2F0aW5nIHBvaW50CiAgICAgICAgcm93ID0gbmV3IFVpbnQ4QXJyYXkoCiAgICAgICAgICBibG9jaywgaSAqIHN0cmlkZSAqIHdpZHRoICogYnl0ZXNQZXJTYW1wbGUsIHN0cmlkZSAqIHdpZHRoICogYnl0ZXNQZXJTYW1wbGUsCiAgICAgICAgKTsK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ICBmdW5jdGlvbiByZWFkQml0KCkgewogICAgICBpZiAoYml0c0NvdW50ID4gMCkgewogICAgICAgIGJpdHNDb3VudC0tOwogICAgICAgIHJldHVybiAoYml0c0RhdGEgPj4gYml0c0NvdW50KSAmIDE7CiAgICAgIH0KICAgICAgYml0c0RhdGEgPSBkYXRhW29mZnNldCsrXTsKICAgICAgaWYgKGJpdHNEYXRhID09PSAweEZGKSB7CiAgICAgICAgY29uc3QgbmV4dEJ5dGUgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICBpZiAobmV4dEJ5dGUpIHsKICAgICAgICAgIHRocm93IG5ldyBFcnJvcihgdW5leHBlY3RlZCBtYXJrZXI6ICR7KChiaXRzRGF0YSA8PCA4KSB8IG5leHRCeXRlKS50b1N0cmluZygxNil9YCk7CiAgICAgICAgfQogICAgICAgIC8vIHVuc3R1ZmYgMAogICAgICB9CiAgICAgIGJpdHNDb3VudCA9IDc7CiAgICAgIHJldHVybiBiaXRzRGF0YSA+Pj4gNzsKICAgIH0KICAgIGZ1bmN0aW9uIGRlY29kZUh1ZmZtYW4odHJlZSkgewogICAgICBsZXQgbm9kZSA9IHRyZWU7CiAgICAgIGxldCBiaXQ7CiAgICAgIHdoaWxlICgoYml0ID0gcmVhZEJpdCgpKSAhPT0gbnVsbCkgeyAvLyBlc2xpbnQtZGlzYWJsZS1saW5lIG5vLWNvbmQtYXNzaWduCiAgICAgICAgbm9kZSA9IG5vZGVbYml0XTsKICAgICAgICBpZiAodHlwZW9mIG5vZGUgPT09ICdudW1iZXInKSB7CiAgICAgICAgICByZXR1cm4gbm9kZTsKICAgICAgICB9CiAgICAgICAgaWYgKHR5cGVvZiBub2RlICE9PSAnb2JqZWN0JykgewogICAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdpbnZhbGlkIGh1ZmZtYW4gc2VxdWVuY2UnKTsKICAgICAgICB9CiAgICAgIH0KICAgICAgcmV0dXJuIG51bGw7CiAgICB9CiAgICBmdW5jdGlvbiByZWNlaXZlKGluaXRpYWxMZW5ndGgpIHsKICAgICAgbGV0IGxlbmd0aCA9IGluaXRpYWxMZW5ndGg7CiAgICAgIGxldCBuID0gMDsKICAgICAgd2hpbGUgKGxlbmd0aCA+IDApIHsKICAgICAgICBjb25zdCBiaXQgPSByZWFkQml0KCk7CiAgICAgICAgaWYgKGJpdCA9PT0gbnVsbCkgewogICAgICAgICAgcmV0dXJuIHVuZGVmaW5lZDsKICAgICAgICB9CiAgICAgICAgbiA9IChuIDw8IDEpIHwgYml0OwogICAgICAgIC0tbGVuZ3RoOwogICAgICB9CiAgICAgIHJldHVybiBuOwogICAgfQogICAgZnVuY3Rpb24gcmVjZWl2ZUFuZEV4dGVuZChsZW5ndGgpIHsKICAgICAgY29uc3QgbiA9IHJlY2VpdmUobGVuZ3RoKTsKICAgICAgaWYgKG4gPj0gMSA8PCAobGVuZ3RoIC0gMSkpIHsKICAgICAgICByZXR1cm4gbjsKICAgICAgfQogICAgICByZXR1cm4gbiArICgtMSA8PCBsZW5ndGgpICsgMTsKICAgIH0KICAgIGZ1bmN0aW9uIGRlY29kZUJhc2VsaW5lKGNvbXBvbmVudCwgenopIHsKICAgICAgY29uc3QgdCA9IGRlY29kZUh1ZmZtYW4oY29tcG9uZW50Lmh1ZmZtYW5UYWJsZURDKTsKICAgICAgY29uc3QgZGlmZiA9IHQgPT09IDAgPyAwIDogcmVjZWl2ZUFuZEV4dGVuZCh0KTsKICAgICAgY29tcG9uZW50LnByZWQgKz0gZGlmZjsKICAgICAgenpbMF0gPSBjb21wb25lbnQucHJlZDsKICAgICAgbGV0IGsgPSAxOwogICAgICB3aGlsZSAoayA8IDY0KSB7CiAgICAgICAgY29uc3QgcnMgPSBkZWNvZGVIdWZmbWFuKGNvbXBvbmVudC5odWZmbWFuVGFibGVBQyk7CiAgICAgICAgY29uc3QgcyA9IHJzICYgMTU7CiAgICAgICAgY29uc3QgciA9IHJzID4+IDQ7CiAgICAgICAgaWYgKHMgPT09IDApIHsKICAgICAgICAgIGlmIChyIDwgMTUpIHsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICBrICs9IDE2OwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICBrICs9IHI7CiAgICAgICAgICBjb25zdCB6ID0gZGN0WmlnWmFnW2tdOwogICAgICAgICAgenpbel0gPSByZWNlaXZlQW5kRXh0ZW5kKHMpOwogICAgICAgICAgaysrOwogICAgICAgIH0KICAgICAgfQogICAgfQogICAgZnVuY3Rpb24gZGVjb2RlRENGaXJzdChjb21wb25lbnQsIHp6KSB7CiAgICAgIGNvbnN0IHQgPSBkZWNvZGVIdWZmbWFuKGNvbXBvbmVudC5odWZmbWFuVGFibGVEQyk7CiAgICAgIGNvbnN0IGRpZmYgPSB0ID09PSAwID8gMCA6IChyZWNlaXZlQW5kRXh0ZW5kKHQpIDw8IHN1Y2Nlc3NpdmUpOwogICAgICBjb21wb25lbnQucHJlZCArPSBkaWZmOwogICAgICB6elswXSA9IGNvbXBvbmVudC5wcmVkOwogICAgfQogICAgZnVuY3Rpb24gZGVjb2RlRENTdWNjZXNzaXZlKGNvbXBvbmVudCwgenopIHsKICAgICAgenpbMF0gfD0gcmVhZEJpdCgpIDw8IHN1Y2Nlc3NpdmU7CiAgICB9CiAgICBsZXQgZW9icnVuID0gMDsKICAgIGZ1bmN0aW9uIGRlY29kZUFDRmlyc3QoY29tcG9uZW50LCB6eikgewogICAgICBpZiAoZW9icnVuID4gMCkgewogICAgICAgIGVvYnJ1bi0tOwogICAgICAgIHJldHVybjsKICAgICAgfQogICAgICBsZXQgayA9IHNwZWN0cmFsU3RhcnQ7CiAgICAgIGNvbnN0IGUgPSBzcGVjdHJhbEVuZDsKICAgICAgd2hpbGUgKGsgPD0gZSkgewogICAgICAgIGNvbnN0IHJzID0gZGVjb2RlSHVmZm1hbihjb21wb25lbnQuaHVmZm1hblRhYmxlQUMpOwogICAgICAgIGNvbnN0IHMgPSBycyAmIDE1OwogICAgICAgIGNvbnN0IHIgPSBycyA+PiA0OwogICAgICAgIGlmIChzID09PSAwKSB7CiAgICAgICAgICBpZiAociA8IDE1KSB7CiAgICAgICAgICAgIGVvYnJ1biA9IHJlY2VpdmUocikgKyAoMSA8PCByKSAtIDE7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgayArPSAxNjsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgayArPSByOwogICAgICAgICAgY29uc3QgeiA9IGRjdFppZ1phZ1trXTsKICAgICAgICAgIHp6W3pdID0gcmVjZWl2ZUFuZEV4dGVuZChzKSAqICgxIDw8IHN1Y2Nlc3NpdmUpOwogICAgICAgICAgaysrOwogICAgICAgIH0KICAgICAgfQogICAgfQogICAgbGV0IHN1Y2Nlc3NpdmVBQ1N0YXRlID0gMDsKICAgIGxldCBzdWNjZXNzaXZlQUNOZXh0VmFsdWU7CiAgICBmdW5jdGlvbiBkZWNvZGVBQ1N1Y2Nlc3NpdmUoY29tcG9uZW50LCB6eikgewogICAgICBsZXQgayA9IHNwZWN0cmFsU3RhcnQ7CiAgICAgIGNvbnN0IGUgPSBzcGVjdHJhbEVuZDsKICAgICAgbGV0IHIgPSAwOwogICAgICB3aGlsZSAoayA8PSBlKSB7CiAgICAgICAgY29uc3QgeiA9IGRjdFppZ1phZ1trXTsKICAgICAgICBjb25zdCBkaXJlY3Rpb24gPSB6elt6XSA8IDAgPyAtMSA6IDE7CiAgICAgICAgc3dpdGNoIChzdWNjZXNzaXZlQUNTdGF0ZSkgewogICAgICAgICAgY2FzZSAwOiB7IC8vIGluaXRpYWwgc3RhdGUKICAgICAgICAgICAgY29uc3QgcnMgPSBkZWNvZGVIdWZmbWFuKGNvbXBvbmVudC5odWZmbWFuVGFibGVBQyk7CiAgICAgICAgICAgIGNvbnN0IHMgPSBycyAmIDE1OwogICAgICAgICAgICByID0gcnMgPj4gNDsKICAgICAgICAgICAgaWYgKHMgPT09IDApIHsKICAgICAgICAgICAgICBpZiAociA8IDE1KSB7CiAgICAgICAgICAgICAgICBlb2JydW4gPSByZWNlaXZlKHIpICsgKDEgPDwgcik7CiAgICAgICAgICAgICAgICBzdWNjZXNzaXZlQUNTdGF0ZSA9IDQ7CiAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgIHIgPSAxNjsKICAgICAgICAgICAgICAgIHN1Y2Nlc3NpdmVBQ1N0YXRlID0gMTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgaWYgKHMgIT09IDEpIHsKICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcignaW52YWxpZCBBQ24gZW5jb2RpbmcnKTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgc3VjY2Vzc2l2ZUFDTmV4dFZhbHVlID0gcmVjZWl2ZUFuZEV4dGVuZChzKTsKICAgICAgICAgICAgICBzdWNjZXNzaXZlQUNTdGF0ZSA9IHIgPyAyIDogMzsKICAgICAgICAgICAgfQogICAgICAgICAgICBjb250aW51ZTsgLy8gZXNsaW50LWRpc2FibGUtbGluZSBuby1jb250aW51ZQogICAgICAgICAgfQogICAgICAgICAgY2FzZSAxOiAvLyBza2lwcGluZyByIHplcm8gaXRlbXMKICAgICAgICAgIGNhc2UgMjoKICAgICAgICAgICAgaWYgKHp6W3pdKSB7CiAgICAgICAgICAgICAgenpbel0gKz0gKHJlYWRCaXQoKSA8PCBzdWNjZXNzaXZlKSAqIGRpcmVjdGlvbjsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICByLS07CiAgICAgICAgICAgICAgaWYgKHIgPT09IDApIHsKICAgICAgICAgICAgICAgIHN1Y2Nlc3NpdmVBQ1N0YXRlID0gc3VjY2Vzc2l2ZUFDU3RhdGUgPT09IDIgPyAzIDogMDsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICBjYXNlIDM6IC8vIHNldCB2YWx1ZSBmb3IgYSB6ZXJvIGl0ZW0KICAgICAgICAgICAgaWYgKHp6W3pdKSB7CiAgICAgICAgICAgICAgenpbel0gKz0gKHJlYWRCaXQoKSA8PCBzdWNjZXNzaXZlKSAqIGRpcmVjdGlvbjsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICB6elt6XSA9IHN1Y2Nlc3NpdmVBQ05leHRWYWx1ZSA8PCBzdWNjZXNzaXZlOwogICAgICAgICAgICAgIHN1Y2Nlc3NpdmVBQ1N0YXRlID0gMDsKICAgICAgICAgICAgfQogICAgICAgICAgICBicmVhazsKICAgICAgICAgIGNhc2UgNDogLy8gZW9iCiAgICAgICAgICAgIGlmICh6elt6XSkgewogICAgICAgICAgICAgIHp6W3pdICs9IChyZWFkQml0KCkgPDwgc3VjY2Vzc2l2ZSkgKiBkaXJlY3Rpb247CiAgICAgICAgICAgIH0KICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfQogICAgICAgIGsrKzsKICAgICAgfQogICAgICBpZiAoc3VjY2Vzc2l2ZUFDU3RhdGUgPT09IDQpIHsKICAgICAgICBlb2JydW4tLTsKICAgICAgICBpZiAoZW9icnVuID09PSAwKSB7CiAgICAgICAgICBzdWNjZXNzaXZlQUNTdGF0ZSA9IDA7CiAgICAgICAgfQogICAgICB9CiAgICB9CiAgICBmdW5jdGlvbiBkZWNvZGVNY3UoY29tcG9uZW50LCBkZWNvZGVGdW5jdGlvbiwgbWN1LCByb3csIGNvbCkgewogICAgICBjb25zdCBtY3VSb3cgPSAobWN1IC8gbWN1c1BlckxpbmUpIHwgMDsKICAgICAgY29uc3QgbWN1Q29sID0gbWN1ICUgbWN1c1BlckxpbmU7CiAgICAgIGNvbnN0IGJsb2NrUm93ID0gKG1jdVJvdyAqIGNvbXBvbmVudC52KSArIHJvdzsKICAgICAgY29uc3QgYmxvY2tDb2wgPSAobWN1Q29sICogY29tcG9uZW50LmgpICsgY29sOwogICAgICBkZWNvZGVGdW5jdGlvbihjb21wb25lbnQsIGNvbXBvbmVudC5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MaW5lICogY29tcG9uZW50c1swXS5ibG9ja3NQZXJDb2x1bW47CiAgICB9IGVsc2UgewogICAgICBtY3VFeHBlY3RlZCA9IG1jdXNQZXJMaW5lICogZnJhbWUubWN1c1BlckNvbHVtbjsKICAgIH0KCiAgICBjb25zdCB1c2VkUmVzZXRJbnRlcnZhbCA9IHJlc2V0SW50ZXJ2YWwgfHwgbWN1RXhwZWN0ZWQ7CgogICAgd2hpbGUgKG1jdSA8IG1jdUV4cGVjdGVkKSB7CiAgICAgIC8vIHJlc2V0IGludGVydmFsIHN0dWZmCiAgICAgIGZvciAoaSA9IDA7IGkgPCBjb21wb25lbnRzTGVuZ3RoOyBpKyspIHsKICAgICAgICBjb21wb25lbnRzW2ldLnByZWQgPSAwOwogICAgICB9CiAgICAgIGVvYnJ1biA9IDA7CgogICAgICBpZiAoY29tcG9uZW50c0xlbmd0aCA9PT0gMSkgewogICAgICAgIGNvbXBvbmVudCA9IGNvbXBvbmVudHNbMF07CiAgICAgICAgZm9yIChuID0gMDsgbiA8IHVzZWRSZXNldEludGVydmFsOyBuKyspIHsKICAgICAgICAgIGRlY29kZUJsb2NrKGNvbXBvbmVudCwgZGVjb2RlRm4sIG1jdSk7CiAgICAgICAgICBtY3UrKzsKICAgICAgICB9CiAgICAgIH0gZWxzZSB7CiAgICAgICAgZm9yIChuID0gMDsgbiA8IHVzZWRSZXNldEludGVydmFsOyBuKyspIHsKICAgICAgICAgIGZvciAoaSA9IDA7IGkgPCBjb21wb25lbnRzTGVuZ3RoOyBpKyspIHsKICAgICAgICAgICAgY29tcG9uZW50ID0gY29tcG9uZW50c1tpXTsKICAgICAgICAgICAgY29uc3QgeyBoLCB2IH0gPSBjb21wb25lbnQ7CiAgICAgICAgICAgIGZvciAoaiA9IDA7IGogPCB2OyBqKyspIHsKICAgICAgICAgICAgICBmb3IgKGsgPSAwOyBrIDwgaDsgaysrKSB7CiAgICAgICAgICAgICAgICBkZWNvZGVNY3UoY29tcG9uZW50LCBkZWNvZGVGbiwgbWN1LCBqLCBrKTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIG1jdSsrOwoKICAgICAgICAgIC8vIElmIHdlJ3ZlIHJlYWNoZWQgb3VyIGV4cGVjdGVkIE1DVSdzLCBzdG9wIGRlY29kaW5nCiAgICAgICAgICBpZiAobWN1ID09PSBtY3VFeHBlY3RlZCkgewogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgIH0KCiAgICAgIC8vIGZpbmQgbWFya2VyCiAgICAgIGJpdHNDb3VudCA9IDA7CiAgICAgIG1hcmtlciA9IChkYXRhW29mZnNldF0gPDwgOCkgfCBkYXRhW29mZnNldCArIDFdOwogICAgICBpZiAobWFya2VyIDwgMHhGRjAwKSB7CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdtYXJrZXIgd2FzIG5vdCBmb3VuZCcpOwogICAgICB9CgogICAgICBpZiAobWFya2VyID49IDB4RkZEMCAmJiBtYXJrZXIgPD0gMHhGRkQ3KSB7IC8vIFJTVHgKICAgICAgICBvZmZzZXQgKz0gMjsKICAgICAgfSBlbHNlIHsKICAgICAgICBicmVhazsKICAgICAgfQogICAgfQoKICAgIHJldHVybiBvZmZzZXQgLSBzdGFydE9mZnNldDsKICB9CgogIGZ1bmN0aW9uIGJ1aWxkQ29tcG9uZW50RGF0YShmcmFtZSwgY29tcG9uZW50KSB7CiAgICBjb25zdCBsaW5lcyA9IFtdOwogICAgY29uc3QgeyBibG9ja3NQZXJMaW5lLCBibG9ja3NQZXJDb2x1bW4gfSA9IGNvbXBvbmVudDsKICAgIGNvbnN0IHNhbXBsZXNQZXJMaW5lID0gYmxvY2tzUGVyTGluZSA8PCAzOwogICAgY29uc3QgUiA9IG5ldyBJbnQzMkFycmF5KDY0KTsKICAgIGNvbnN0IHIgPSBuZXcgVWludDhBcnJheSg2NCk7CgogICAgLy8gQSBwb3J0IG9mIHBvcHBsZXIncyBJRENUIG1ldGhvZCB3aGljaCBpbiB0dXJuIGlzIHRha2VuIGZyb206CiAgICAvLyAgIENocmlzdG9waCBMb2VmZmxlciwgQWRyaWFhbiBMaWd0ZW5iZXJnLCBHZW9yZ2UgUy4gTW9zY2h5dHosCiAgICAvLyAgICJQcmFjdGljYWwgRmFzdCAxLUQgRENUIEFsZ29yaXRobXMgd2l0aCAxMSBNdWx0aXBsaWNhdGlvbnMiLAogICAgLy8gICBJRUVFIEludGwuIENvbmYuIG9uIEFjb3VzdGljcywgU3BlZWNoICYgU2lnbmFsIFByb2Nlc3NpbmcsIDE5ODksCiAgICAvLyAgIDk4OC05OTEuCiAgICBmdW5jdGlvbiBxdWFudGl6ZUFuZEludmVyc2UoenosIGRhdGFPdXQsIGRhdGFJbikgewogICAgICBjb25zdCBxdCA9IGNvbXBvbmVudC5xdWFudGl6YXRpb25UYWJsZTsKICAgICAgbGV0IHYwOwogICAgICBsZXQgdjE7CiAgICAgIGxldCB2MjsKICAgICAgbGV0IHYzOwogICAgICBsZXQgdjQ7CiAgICAgIGxldCB2NTsKICAgICAgbGV0IHY2OwogICAgICBsZXQgdjc7CiAgICAgIGxldCB0OwogICAgICBjb25zdCBwID0gZGF0YUluOwogICAgICBsZXQgaTsKCiAgICAgIC8vIGRlcXVhbnQKICAgICAgZm9yIChpID0gMDsgaSA8IDY0OyBpKyspIHsKICAgICAgICBwW2ldID0genpbaV0gKiBxdFtpXTsKICAgICAgfQoKICAgICAgLy8gaW52ZXJzZSBEQ1Qgb24gcm93cwogICAgICBmb3IgKGkgPSAwOyBpIDwgODsgKytpKSB7CiAgICAgICAgY29uc3Qgcm93ID0gOCAqIGk7CgogICAgICAgIC8vIGNoZWNrIGZvciBhbGwtemVybyBBQyBjb2VmZmljaWVudHMKICAgICAgICBpZiAocFsxICsgcm93XSA9PT0gMCAmJiBwWzIgKyByb3ddID09PSAwICYmIHBbMyArIHJvd10gPT09IDAKICAgICAgICAgICYmIHBbNCArIHJvd10gPT09IDAgJiYgcFs1ICsgcm93XSA9PT0gMCAmJiBwWzYgKyByb3ddID09PSAwCiAgICAgICAgICAmJiBwWzcgKyByb3ddID09PSAwKSB7CiAgICAgICAgICB0ID0gKChkY3RTcXJ0MiAqIHBbMCArIHJvd10pICsgNTEyKSA+PiAxMDsKICAgICAgICAgIHBbMCArIHJvd10gPSB0OwogICAgICAgICAgcFsxICsgcm93XSA9IHQ7CiAgICAgICAgICBwWzIgKyByb3ddID0gdDsKICAgICAgICAgIHBbMyArIHJvd10gPSB0OwogICAgICAgICAgcFs0ICsgcm93XSA9IHQ7CiAgICAgICAgICBwWzUgKyByb3ddID0gdDsKICAgICAgICAgIHBbNiArIHJvd10gPSB0OwogICAgICAgICAgcFs3ICsgcm93XSA9IHQ7CiAgICAgICAgICBjb250aW51ZTsgLy8gZXNsaW50LWRpc2FibGUtbGluZSBuby1jb250aW51ZQogICAgICAgIH0KCiAgICAgICAgLy8gc3RhZ2UgNAogICAgICAgIHYwID0gKChkY3RTcXJ0MiAqIHBbMCArIHJvd10pICsgMTI4KSA+PiA4OwogICAgICAgIHYxID0gKChkY3RTcXJ0MiAqIHBbNCArIHJvd10pICsgMTI4KSA+PiA4OwogICAgICAgIHYyID0gcFsyICsgcm93XTsKICAgICAgICB2MyA9IHBbNiArIHJvd107CiAgICAgICAgdjQgPSAoKGRjdFNxcnQxZDIgKiAocFsxICsgcm93XSAtIHBbNyArIHJvd10pKSArIDEyOCkgPj4gODsKICAgICAgICB2NyA9ICgoZGN0U3FydDFkMiAqIChwWzEgKyByb3ddICsgcFs3ICsgcm93XSkpICsgMTI4KSA+PiA4OwogICAgICAgIHY1ID0gcFszICsgcm93XSA8PCA0OwogICAgICAgIHY2ID0gcFs1ICsgcm93XSA8PCA0OwoKICAgICAgICAvLyBzdGFnZSAzCiAgICAgICAgdCA9ICh2MCAtIHYxICsgMSkgPj4gMTsKICAgICAgICB2MCA9ICh2MCArIHYxICsgMSkgPj4gMTsKICAgICAgICB2MSA9IHQ7CiAgICAgICAgdCA9ICgodjIgKiBkY3RTaW42KSArICh2MyAqIGRjdENvczYpICsgMTI4KSA+PiA4OwogICAgICAgIHYyID0gKCh2MiAqIGRjdENvczYpIC0gKHYzICogZGN0U2luNikgKyAxMjgpID4+IDg7CiAgICAgICAgdjMgPSB0OwogICAgICAgIHQgPSAodjQgLSB2NiArIDEpID4+IDE7CiAgICAgICAgdjQgPSAodjQgKyB2NiArIDEpID4+IDE7CiAgICAgICAgdjYgPSB0OwogICAgICAgIHQgPSAodjcgKyB2NSArIDEpID4+IDE7CiAgICAgICAgdjUgPSAodjcgLSB2NSArIDEpID4+IDE7CiAgICAgICAgdjcgPSB0OwoKICAgICAgICAvLyBzdGFnZSAyCiAgICAgICAgdCA9ICh2MCAtIHYzICsgMSkgPj4gMTsKICAgICAgICB2MCA9ICh2MCArIHYzICsgMSkgPj4gMTsKICAgICAgICB2MyA9IHQ7CiAgICAgICAgdCA9ICh2MSAtIHYyICsgMSkgPj4gMTsKICAgICAgICB2MSA9ICh2MSArIHYyICsgMSkgPj4gMTsKICAgICAgICB2MiA9IHQ7CiAgICAgICAgdCA9ICgodjQgKiBkY3RTaW4zKSArICh2NyAqIGRjdENvczMpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjQgPSAoKHY0ICogZGN0Q29zMykgLSAodjcgKiBkY3RTaW4zKSArIDIwNDgpID4+IDEyOwogICAgICAgIHY3ID0gdDsKICAgICAgICB0ID0gKCh2NSAqIGRjdFNpbjEpICsgKHY2ICogZGN0Q29zMSkgKyAyMDQ4KSA+PiAxMjsKICAgICAgICB2NSA9ICgodjUgKiBkY3RDb3MxKSAtICh2NiAqIGRjdFNpbjEpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjYgPSB0OwoKICAgICAgICAvLyBzdGFnZSAxCiAgICAgICAgcFswICsgcm93XSA9IHYwICsgdjc7CiAgICAgICAgcFs3ICsgcm93XSA9IHYwIC0gdjc7CiAgICAgICAgcFsxICsgcm93XSA9IHYxICsgdjY7CiAgICAgICAgcFs2ICsgcm93XSA9IHYxIC0gdjY7CiAgICAgICAgcFsyICsgcm93XSA9IHYyICsgdjU7CiAgICAgICAgcFs1ICsgcm93XSA9IHYyIC0gdjU7CiAgICAgICAgcFszICsgcm93XSA9IHYzICsgdjQ7CiAgICAgICAgcFs0ICsgcm93XSA9IHYzIC0gdjQ7CiAgICAgIH0KCiAgICAgIC8vIGludmVyc2UgRENUIG9uIGNvbHVtbnMKICAgICAgZm9yIChpID0gMDsgaSA8IDg7ICsraSkgewogICAgICAgIGNvbnN0IGNvbCA9IGk7CgogICAgICAgIC8vIGNoZWNrIGZvciBhbGwtemVybyBBQyBjb2VmZmljaWVudHMKICAgICAgICBpZiAocFsoMSAqIDgpICsgY29sXSA9PT0gMCAmJiBwWygyICogOCkgKyBjb2xdID09PSAwICYmIHBbKDMgKiA4KSArIGNvbF0gPT09IDAKICAgICAgICAgICYmIHBbKDQgKiA4KSArIGNvbF0gPT09IDAgJiYgcFsoNSAqIDgpICsgY29sXSA9PT0gMCAmJiBwWyg2ICogOCkgKyBjb2xdID09PSAwCiAgICAgICAgICAmJiBwWyg3ICogOCkgKyBjb2xdID09PSAwKSB7CiAgICAgICAgICB0ID0gKChkY3RTcXJ0MiAqIGRhdGFJbltpICsgMF0pICsgODE5MikgPj4gMTQ7CiAgICAgICAgICBwWygwICogOCkgKyBjb2xdID0gdDsKICAgICAgICAgIHBbKDEgKiA4KSArIGNvbF0gPSB0OwogICAgICAgICAgcFsoMiAqIDgpICsgY29sXSA9IHQ7CiAgICAgICAgICBwWygzICogOCkgKyBjb2xdID0gdDsKICAgICAgICAgIHBbKDQgKiA4KSArIGNvbF0gPSB0OwogICAgICAgICAgcFsoNSAqIDgpICsgY29sXSA9IHQ7CiAgICAgICAgICBwWyg2ICogOCkgKyBjb2xdID0gdDsKICAgICAgICAgIHBbKDcgKiA4KSArIGNvbF0gPSB0OwogICAgICAgICAgY29udGludWU7IC8vIGVzbGludC1kaXNhYmxlLWxpbmUgbm8tY29udGludWUKICAgICAgICB9CgogICAgICAgIC8vIHN0YWdlIDQKICAgICAgICB2MCA9ICgoZGN0U3FydDIgKiBwWygwICogOCkgKyBjb2xdKSArIDIwNDgpID4+IDEyOwogICAgICAgIHYxID0gKChkY3RTcXJ0MiAqIHBbKDQgKiA4KSArIGNvbF0pICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjIgPSBwWygyICogOCkgKyBjb2xdOwogICAgICAgIHYzID0gcFsoNiAqIDgpICsgY29sXTsKICAgICAgICB2NCA9ICgoZGN0U3FydDFkMiAqIChwWygxICogOCkgKyBjb2xdIC0gcFsoNyAqIDgpICsgY29sXSkpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjcgPSAoKGRjdFNxcnQxZDIgKiAocFsoMSAqIDgpICsgY29sXSArIHBbKDcgKiA4KSArIGNvbF0pKSArIDIwNDgpID4+IDEyOwogICAgICAgIHY1ID0gcFsoMyAqIDgpICsgY29sXTsKICAgICAgICB2NiA9IHBbKDUgKiA4KSArIGNvbF07CgogICAgICAgIC8vIHN0YWdlIDMKICAgICAgICB0ID0gKHYwIC0gdjEgKyAxKSA+PiAxOwogICAgICAgIHYwID0gKHYwICsgdjEgKyAxKSA+PiAxOwogICAgICAgIHYxID0gdDsKICAgICAgICB0ID0gKCh2MiAqIGRjdFNpbjYpICsgKHYzICogZGN0Q29zNikgKyAyMDQ4KSA+PiAxMjsKICAgICAgICB2MiA9ICgodjIgKiBkY3RDb3M2KSAtICh2MyAqIGRjdFNpbjYpICsgMjA0OCkgPj4gMTI7CiAgICAgICAgdjMgPSB0OwogICAgICAgIHQgPSAodjQgLSB2NiArIDEpID4+IDE7CiAgICAgICAgdjQgPSAodjQgKyB2NiArIDEpID4+IDE7CiAgICAgICAgdjYgPSB0OwogICAgICAgIHQgPSAodjcgKyB2NSArIDEpID4+IDE7CiAgICAgICAgdjUgPSAodjcgLSB2NSArIDEpID4+IDE7CiAgICAgICAgdjcgPSB0OwoKICAgICAgICAvLyBzdGFnZS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bGUgPSAxMjggKyAoKHBbaV0gKyA4KSA+PiA0KTsKICAgICAgICBpZiAoc2FtcGxlIDwgMCkgewogICAgICAgICAgZGF0YU91dFtpXSA9IDA7CiAgICAgICAgfSBlbHNlIGlmIChzYW1wbGUgPiAwWEZGKSB7CiAgICAgICAgICBkYXRhT3V0W2ldID0gMHhGRjsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgZGF0YU91dFtpXSA9IHNhbXBsZTsKICAgICAgICB9CiAgICAgIH0KICAgIH0KCiAgICBmb3IgKGxldCBibG9ja1JvdyA9IDA7IGJsb2NrUm93IDwgYmxvY2tzUGVyQ29sdW1uOyBibG9ja1JvdysrKSB7CiAgICAgIGNvbnN0IHNjYW5MaW5lID0gYmxvY2tSb3cgPDwgMzsKICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCA4OyBpKyspIHsKICAgICAgICBsaW5lcy5wdXNoKG5ldyBVaW50OEFycmF5KHNhbXBsZXNQZXJMaW5lKSk7CiAgICAgIH0KICAgICAgZm9yIChsZXQgYmxvY2tDb2wgPSAwOyBibG9ja0NvbCA8IGJsb2Nrc1BlckxpbmU7IGJsb2NrQ29sKyspIHsKICAgICAgICBxdWFudGl6ZUFuZEludmVyc2UoY29tcG9uZW50LmJsb2Nrc1tibG9ja1Jvd11bYmxvY2tDb2xdLCByLCBSKTsKCiAgICAgICAgbGV0IG9mZnNldCA9IDA7CiAgICAgICAgY29uc3Qgc2FtcGxlID0gYmxvY2tDb2wgPDwgMzsKICAgICAgICBmb3IgKGxldCBqID0gMDsgaiA8IDg7IGorKykgewogICAgICAgICAgY29uc3QgbGluZSA9IGxpbmVzW3NjYW5MaW5lICsgal07CiAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IDg7IGkrKykgewogICAgICAgICAgICBsaW5lW3NhbXBsZSArIGldID0gcltvZmZzZXQrK107CiAgICAgICAgICB9CiAgICAgICAgfQogICAgICB9CiAgICB9CiAgICByZXR1cm4gbGluZXM7CiAgfQoKICBjbGFzcyBKcGVnU3RyZWFtUmVhZGVyIHsKICAgIGNvbnN0cnVjdG9yKCkgewogICAgICB0aGlzLmpmaWYgPSBudWxsOwogICAgICB0aGlzLmFkb2JlID0gbnVsbDsKCiAgICAgIHRoaXMucXVhbnRpemF0aW9uVGFibGVzID0gW107CiAgICAgIHRoaXMuaHVmZm1hblRhYmxlc0FDID0gW107CiAgICAgIHRoaXMuaHVmZm1hblRhYmxlc0RDID0gW107CiAgICAgIHRoaXMucmVzZXRGcmFtZXMoKTsKICAgIH0KCiAgICByZXNldEZyYW1lcygpIHsKICAgICAgdGhpcy5mcmFtZXMgPSBbXTsKICAgIH0KCiAgICBwYXJzZShkYXRhKSB7CiAgICAgIGxldCBvZmZzZXQgPSAwOwogICAgICAvLyBjb25zdCB7IGxlbmd0aCB9ID0gZGF0YTsKICAgICAgZnVuY3Rpb24gcmVhZFVpbnQxNigpIHsKICAgICAgICBjb25zdCB2YWx1ZSA9IChkYXRhW29mZnNldF0gPDwgOCkgfCBkYXRhW29mZnNldCArIDFdOwogICAgICAgIG9mZnNldCArPSAyOwogICAgICAgIHJldHVybiB2YWx1ZTsKICAgICAgfQogICAgICBmdW5jdGlvbiByZWFkRGF0YUJsb2NrKCkgewogICAgICAgIGNvbnN0IGxlbmd0aCA9IHJlYWRVaW50MTYoKTsKICAgICAgICBjb25zdCBhcnJheSA9IGRhdGEuc3ViYXJyYXkob2Zmc2V0LCBvZmZzZXQgKyBsZW5ndGggLSAyKTsKICAgICAgICBvZmZzZXQgKz0gYXJyYXkubGVuZ3RoOwogICAgICAgIHJldHVybiBhcnJheTsKICAgICAgfQogICAgICBmdW5jdGlvbiBwcmVwYXJlQ29tcG9uZW50cyhmcmFtZSkgewogICAgICAgIGxldCBtYXhIID0gMDsKICAgICAgICBsZXQgbWF4ViA9IDA7CiAgICAgICAgbGV0IGNvbXBvbmVudDsKICAgICAgICBsZXQgY29tcG9uZW50SWQ7CiAgICAgICAgZm9yIChjb21wb25lbnRJZCBpbiBmcmFtZS5jb21wb25lbnRzKSB7CiAgICAgICAgICBpZiAoZnJhbWUuY29tcG9uZW50cy5oYXNPd25Qcm9wZXJ0eShjb21wb25lbnRJZCkpIHsKICAgICAgICAgICAgY29tcG9uZW50ID0gZnJhbWUuY29tcG9uZW50c1tjb21wb25lbnRJZF07CiAgICAgICAgICAgIGlmIChtYXhIIDwgY29tcG9uZW50LmgpIHsKICAgICAgICAgICAgICBtYXhIID0gY29tcG9uZW50Lmg7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKG1heFYgPCBjb21wb25lbnQudikgewogICAgICAgICAgICAgIG1heFYgPSBjb21wb25lbnQudjsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBjb25zdCBtY3VzUGVyTGluZSA9IE1hdGguY2VpbChmcmFtZS5zYW1wbGVzUGVyTGluZSAvIDggLyBtYXhIKTsKICAgICAgICBjb25zdCBtY3VzUGVyQ29sdW1uID0gTWF0aC5jZWlsKGZyYW1lLnNjYW5MaW5lcyAvIDggLyBtYXhWKTsKICAgICAgICBmb3IgKGNvbXBvbmVudElkIGluIGZyYW1lLmNvbXBvbmVudHMpIHsKICAgICAgICAgIGlmIChmcmFtZS5jb21wb25lbnRzLmhhc093blByb3BlcnR5KGNvbXBvbmVudElkKSkgewogICAgICAgICAgICBjb21wb25lbnQgPSBmcmFtZS5jb21wb25lbnRzW2NvbXBvbmVudElkXTsKICAgICAgICAgICAgY29uc3QgYmxvY2tzUGVyTGluZSA9IE1hdGguY2VpbChNYXRoLmNlaWwoZnJhbWUuc2FtcGxlc1BlckxpbmUgLyA4KSAqIGNvbXBvbmVudC5oIC8gbWF4SCk7CiAgICAgICAgICAgIGNvbnN0IGJsb2Nrc1BlckNvbHVtbiA9IE1hdGguY2VpbChNYXRoLmNlaWwoZnJhbWUuc2NhbkxpbmVzIC8gOCkgKiBjb21wb25lbnQudiAvIG1heFYpOwogICAgICAgICAgICBjb25zdCBibG9ja3NQZXJMaW5lRm9yTWN1ID0gbWN1c1BlckxpbmUgKiBjb21wb25lbnQuaDsKICAgICAgICAgICAgY29uc3QgYmxvY2tzUGVyQ29sdW1uRm9yTWN1ID0gbWN1c1BlckNvbHVtbiAqIGNvbXBvbmVudC52OwogICAgICAgICAgICBjb25zdCBibG9ja3MgPSBbXTsKICAgICAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBibG9ja3NQZXJDb2x1bW5Gb3JNY3U7IGkrKykgewogICAgICAgICAgICAgIGNvbnN0IHJvdyA9IFtdOwogICAgICAgICAgICAgIGZvciAobGV0IGogPSAwOyBqIDwgYmxvY2tzUGVyTGluZUZvck1jdTsgaisrKSB7CiAgICAgICAgICAgICAgICByb3cucHVzaChuZXcgSW50MzJBcnJheSg2NCkpOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBibG9ja3MucHVzaChyb3cpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvbXBvbmVudC5ibG9ja3NQZXJMaW5lID0gYmxvY2tzUGVyTGluZTsKICAgICAgICAgICAgY29tcG9uZW50LmJsb2Nrc1BlckNvbHVtbiA9IGJsb2Nrc1BlckNvbHVtbjsKICAgICAgICAgICAgY29tcG9uZW50LmJsb2NrcyA9IGJsb2NrczsKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgICAgZnJhbWUubWF4SCA9IG1heEg7CiAgICAgICAgZnJhbWUubWF4ViA9IG1heFY7CiAgICAgICAgZnJhbWUubWN1c1BlckxpbmUgPSBtY3VzUGVyTGluZTsKICAgICAgICBmcmFtZS5tY3VzUGVyQ29sdW1uID0gbWN1c1BlckNvbHVtbjsKICAgICAgfQoKICAgICAgbGV0IGZpbGVNYXJrZXIgPSByZWFkVWludDE2KCk7CiAgICAgIGlmIChmaWxlTWFya2VyICE9PSAweEZGRDgpIHsgLy8gU09JIChTdGFydCBvZiBJbWFnZSkKICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ1NPSSBub3QgZm91bmQnKTsKICAgICAgfQoKICAgICAgZmlsZU1hcmtlciA9IHJlYWRVaW50MTYoKTsKICAgICAgd2hpbGUgKGZpbGVNYXJrZXIgIT09IDB4RkZEOSkgeyAvLyBFT0kgKEVuZCBvZiBpbWFnZSkKICAgICAgICBzd2l0Y2ggKGZpbGVNYXJrZXIpIHsKICAgICAgICAgIGNhc2UgMHhGRjAwOiBicmVhazsKICAgICAgICAgIGNhc2UgMHhGRkUwOiAvLyBBUFAwIChBcHBsaWNhdGlvbiBTcGVjaWZpYykKICAgICAgICAgIGNhc2UgMHhGRkUxOiAvLyBBUFAxCiAgICAgICAgICBjYXNlIDB4RkZFMjogLy8gQVBQMgogICAgICAgICAgY2FzZSAweEZGRTM6IC8vIEFQUDMKICAgICAgICAgIGNhc2UgMHhGRkU0OiAvLyBBUFA0CiAgICAgICAgICBjYXNlIDB4RkZFNTogLy8gQVBQNQogICAgICAgICAgY2FzZSAweEZGRTY6IC8vIEFQUDYKICAgICAgICAgIGNhc2UgMHhGRkU3OiAvLyBBUFA3CiAgICAgICAgICBjYXNlIDB4RkZFODogLy8gQVBQOAogICAgICAgICAgY2FzZSAweEZGRTk6IC8vIEFQUDkKICAgICAgICAgIGNhc2UgMHhGRkVBOiAvLyBBUFAxMAogICAgICAgICAgY2FzZSAweEZGRUI6IC8vIEFQUDExCiAgICAgICAgICBjYXNlIDB4RkZFQzogLy8gQVBQMTIKICAgICAgICAgIGNhc2UgMHhGRkVEOiAvLyBBUFAxMwogICAgICAgICAgY2FzZSAweEZGRUU6IC8vIEFQUDE0CiAgICAgICAgICBjYXNlIDB4RkZFRjogLy8gQVBQMTUKICAgICAgICAgIGNhc2UgMHhGRkZFOiB7IC8vIENPTSAoQ29tbWVudCkKICAgICAgICAgICAgY29uc3QgYXBwRGF0YSA9IHJlYWREYXRhQmxvY2soKTsKCiAgICAgICAgICAgIGlmIChmaWxlTWFya2VyID09PSAweEZGRTApIHsKICAgICAgICAgICAgICBpZiAoYXBwRGF0YVswXSA9PT0gMHg0QSAmJiBhcHBEYXRhWzFdID09PSAweDQ2ICYmIGFwcERhdGFbMl0gPT09IDB4NDkKICAgICAgICAgICAgICAgICYmIGFwcERhdGFbM10gPT09IDB4NDYgJiYgYXBwRGF0YVs0XSA9PT0gMCkgeyAvLyAnSkZJRlx4MDAnCiAgICAgICAgICAgICAgICB0aGlzLmpmaWYgPSB7CiAgICAgICAgICAgICAgICAgIHZlcnNpb246IHsgbWFqb3I6IGFwcERhdGFbNV0sIG1pbm9yOiBhcHBEYXRhWzZdIH0sCiAgICAgICAgICAgICAgICAgIGRlbnNpdHlVbml0czogYXBwRGF0YVs3XSwKICAgICAgICAgICAgICAgICAgeERlbnNpdHk6IChhcHBEYXRhWzhdIDw8IDgpIHwgYXBwRGF0YVs5XSwKICAgICAgICAgICAgICAgICAgeURlbnNpdHk6IChhcHBEYXRhWzEwXSA8PCA4KSB8IGFwcERhdGFbMTFdLAogICAgICAgICAgICAgICAgICB0aHVtYldpZHRoOiBhcHBEYXRhWzEyXSwKICAgICAgICAgICAgICAgICAgdGh1bWJIZWlnaHQ6IGFwcERhdGFbMTNdLAogICAgICAgICAgICAgICAgICB0aHVtYkRhdGE6IGFwcERhdGEuc3ViYXJyYXkoMTQsIDE0ICsgKDMgKiBhcHBEYXRhWzEyXSAqIGFwcERhdGFbMTNdKSksCiAgICAgICAgICAgICAgICB9OwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICAvLyBUT0RPIEFQUDEgLSBFeGlmCiAgICAgICAgICAgIGlmIChmaWxlTWFya2VyID09PSAweEZGRUUpIHsKICAgICAgICAgICAgICBpZiAoYXBwRGF0YVswXSA9PT0gMHg0MSAmJiBhcHBEYXRhWzFdID09PSAweDY0ICYmIGFwcERhdGFbMl0gPT09IDB4NkYKICAgICAgICAgICAgICAgICYmIGFwcERhdGFbM10gPT09IDB4NjIgJiYgYXBwRGF0YVs0XSA9PT0gMHg2NSAmJiBhcHBEYXRhWzVdID09PSAwKSB7IC8vICdBZG9iZVx4MDAnCiAgICAgICAgICAgICAgICB0aGlzLmFkb2JlID0gewogICAgICAgICAgICAgICAgICB2ZXJzaW9uOiBhcHBEYXRhWzZdLAogICAgICAgICAgICAgICAgICBmbGFnczA6IChhcHBEYXRhWzddIDw8IDgpIHwgYXBwRGF0YVs4XSwKICAgICAgICAgICAgICAgICAgZmxhZ3MxOiAoYXBwRGF0YVs5XSA8PCA4KSB8IGFwcERhdGFbMTBdLAogICAgICAgICAgICAgICAgICB0cmFuc2Zvcm1Db2RlOiBhcHBEYXRhWzExXSwKICAgICAgICAgICAgICAgIH07CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQoKICAgICAgICAgIGNhc2UgMHhGRkRCOiB7IC8vIERRVCAoRGVmaW5lIFF1YW50aXphdGlvbiBUYWJsZXMpCiAgICAgICAgICAgIGNvbnN0IHF1YW50aXphdGlvblRhYmxlc0xlbmd0aCA9IHJlYWRVaW50MTYoKTsKICAgICAgICAgICAgY29uc3QgcXVhbnRpemF0aW9uVGFibGVzRW5kID0gcXVhbnRpemF0aW9uVGFibGVzTGVuZ3RoICsgb2Zmc2V0IC0gMjsKICAgICAgICAgICAgd2hpbGUgKG9mZnNldCA8IHF1YW50aXphdGlvblRhYmxlc0VuZCkgewogICAgICAgICAgICAgIGNvbnN0IHF1YW50aXphdGlvblRhYmxlU3BlYyA9IGRhdGFbb2Zmc2V0KytdOwogICAgICAgICAgICAgIGNvbnN0IHRhYmxlRGF0YSA9IG5ldyBJbnQzMkFycmF5KDY0KTsKICAgICAgICAgICAgICBpZiAoKHF1YW50aXphdGlvblRhYmxlU3BlYyA+PiA0KSA9PT0gMCkgeyAvLyA4IGJpdCB2YWx1ZXMKICAgICAgICAgICAgICAgIGZvciAobGV0IGogPSAwOyBqIDwgNjQ7IGorKykgewogICAgICAgICAgICAgICAgICBjb25zdCB6ID0gZGN0WmlnWmFnW2pdOwogICAgICAgICAgICAgICAgICB0YWJsZURhdGFbel0gPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9IGVsc2UgaWYgKChxdWFudGl6YXRpb25UYWJsZVNwZWMgPj4gNCkgPT09IDEpIHsgLy8gMTYgYml0CiAgICAgICAgICAgICAgICBmb3IgKGxldCBqID0gMDsgaiA8IDY0OyBqKyspIHsKICAgICAgICAgICAgICAgICAgY29uc3QgeiA9IGRjdFppZ1phZ1tqXTsKICAgICAgICAgICAgICAgICAgdGFibGVEYXRhW3pdID0gcmVhZFVpbnQxNigpOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0RRVDogaW52YWxpZCB0YWJsZSBzcGVjJyk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIHRoaXMucXVhbnRpemF0aW9uVGFibGVzW3F1YW50aXphdGlvblRhYmxlU3BlYyAmIDE1XSA9IHRhYmxlRGF0YTsKICAgICAgICAgICAgfQogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KCiAgICAgICAgICBjYXNlIDB4RkZDMDogLy8gU09GMCAoU3RhcnQgb2YgRnJhbWUsIEJhc2VsaW5lIERDVCkKICAgICAgICAgIGNhc2UgMHhGRkMxOiAvLyBTT0YxIChTdGFydCBvZiBGcmFtZSwgRXh0ZW5kZWQgRENUKQogICAgICAgICAgY2FzZSAweEZGQzI6IHsgLy8gU09GMiAoU3RhcnQgb2YgRnJhbWUsIFByb2dyZXNzaXZlIERDVCkKICAgICAgICAgICAgcmVhZFVpbnQxNigpOyAvLyBza2lwIGRhdGEgbGVuZ3RoCiAgICAgICAgICAgIGNvbnN0IGZyYW1lID0gewogICAgICAgICAgICAgIGV4dGVuZGVkOiAoZmlsZU1hcmtlciA9PT0gMHhGRkMxKSwKICAgICAgICAgICAgICBwcm9ncmVzc2l2ZTogKGZpbGVNYXJrZXIgPT09IDB4RkZDMiksCiAgICAgICAgICAgICAgcHJlY2lzaW9uOiBkYXRhW29mZnNldCsrXSwKICAgICAgICAgICAgICBzY2FuTGluZXM6IHJlYWRVaW50MTYoKSwKICAgICAgICAgICAgICBzYW1wbGVzUGVyTGluZTogcmVhZFVpbnQxNigpLAogICAgICAgICAgICAgIGNvbXBvbmVudHM6IHt9LAogICAgICAgICAgICAgIGNvbXBvbmVudHNPcmRlcjogW10sCiAgICAgICAgICAgIH07CgogICAgICAgICAgICBjb25zdCBjb21wb25lbnRzQ291bnQgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgbGV0IGNvbXBvbmVudElkOwogICAgICAgICAgICAvLyBsZXQgbWF4SCA9IDA7CiAgICAgICAgICAgIC8vIGxldCBtYXhWID0gMDsKICAgICAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBjb21wb25lbnRzQ291bnQ7IGkrKykgewogICAgICAgICAgICAgIGNvbXBvbmVudElkID0gZGF0YVtvZmZzZXRdOwogICAgICAgICAgICAgIGNvbnN0IGggPSBkYXRhW29mZnNldCArIDFdID4+IDQ7CiAgICAgICAgICAgICAgY29uc3QgdiA9IGRhdGFbb2Zmc2V0ICsgMV0gJiAxNTsKICAgICAgICAgICAgICBjb25zdCBxSWQgPSBkYXRhW29mZnNldCArIDJdOwogICAgICAgICAgICAgIGZyYW1lLmNvbXBvbmVudHNPcmRlci5wdXNoKGNvbXBvbmVudElkKTsKICAgICAgICAgICAgICBmcmFtZS5jb21wb25lbnRzW2NvbXBvbmVudElkXSA9IHsKICAgICAgICAgICAgICAgIGgsCiAgICAgICAgICAgICAgICB2LAogICAgICAgICAgICAgICAgcXVhbnRpemF0aW9uSWR4OiBxSWQsCiAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICBvZmZzZXQgKz0gMzsKICAgICAgICAgICAgfQogICAgICAgICAgICBwcmVwYXJlQ29tcG9uZW50cyhmcmFtZSk7CiAgICAgICAgICAgIHRoaXMuZnJhbWVzLnB1c2goZnJhbWUpOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KCiAgICAgICAgICBjYXNlIDB4RkZDNDogeyAvLyBESFQgKERlZmluZSBIdWZmbWFuIFRhYmxlcykKICAgICAgICAgICAgY29uc3QgaHVmZm1hbkxlbmd0aCA9IHJlYWRVaW50MTYoKTsKICAgICAgICAgICAgZm9yIChsZXQgaSA9IDI7IGkgPCBodWZmbWFuTGVuZ3RoOykgewogICAgICAgICAgICAgIGNvbnN0IGh1ZmZtYW5UYWJsZVNwZWMgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgICBjb25zdCBjb2RlTGVuZ3RocyA9IG5ldyBVaW50OEFycmF5KDE2KTsKICAgICAgICAgICAgICBsZXQgY29kZUxlbmd0aFN1bSA9IDA7CiAgICAgICAgICAgICAgZm9yIChsZXQgaiA9IDA7IGogPCAxNjsgaisrLCBvZmZzZXQrKykgewogICAgICAgICAgICAgICAgY29kZUxlbmd0aHNbal0gPSBkYXRhW29mZnNldF07CiAgICAgICAgICAgICAgICBjb2RlTGVuZ3RoU3VtICs9IGNvZGVMZW5ndGhzW2pdOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBjb25zdCBodWZmbWFuVmFsdWVzID0gbmV3IFVpbnQ4QXJyYXkoY29kZUxlbmd0aFN1bSk7CiAgICAgICAgICAgICAgZm9yIChsZXQgaiA9IDA7IGogPCBjb2RlTGVuZ3RoU3VtOyBqKyssIG9mZnNldCsrKSB7CiAgICAgICAgICAgICAgICBodWZmbWFuVmFsdWVzW2pdID0gZGF0YVtvZmZzZXRdOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBpICs9IDE3ICsgY29kZUxlbmd0aFN1bTsKCiAgICAgICAgICAgICAgaWYgKChodWZmbWFuVGFibGVTcGVjID4+IDQpID09PSAwKSB7CiAgICAgICAgICAgICAgICB0aGlzLmh1ZmZtYW5UYWJsZXNEQ1todWZmbWFuVGFibGVTcGVjICYgMTVdID0gYnVpbGRIdWZmbWFuVGFibGUoCiAgICAgICAgICAgICAgICAgIGNvZGVMZW5ndGhzLCBodWZmbWFuVmFsdWVzLAogICAgICAgICAgICAgICAgKTsKICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgdGhpcy5odWZmbWFuVGFibGVzQUNbaHVmZm1hblRhYmxlU3BlYyAmIDE1XSA9IGJ1aWxkSHVmZm1hblRhYmxlKAogICAgICAgICAgICAgICAgICBjb2RlTGVuZ3RocywgaHVmZm1hblZhbHVlcywKICAgICAgICAgICAgICAgICk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQoKICAgICAgICAgIGNhc2UgMHhGRkREOiAvLyBEUkkgKERlZmluZSBSZXN0YXJ0IEludGVydmFsKQogICAgICAgICAgICByZWFkVWludDE2KCk7IC8vIHNraXAgZGF0YSBsZW5ndGgKICAgICAgICAgICAgdGhpcy5yZXNldEludGVydmFsID0gcmVhZFVpbnQxNigpOwogICAgICAgICAgICBicmVhazsKCiAgICAgICAgICBjYXNlIDB4RkZEQTogeyAvLyBTT1MgKFN0YXJ0IG9mIFNjYW4pCiAgICAgICAgICAgIHJlYWRVaW50MTYoKTsgLy8gc2tpcCBsZW5ndGgKICAgICAgICAgICAgY29uc3Qgc2VsZWN0b3JzQ291bnQgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgY29uc3QgY29tcG9uZW50cyA9IFtdOwogICAgICAgICAgICBjb25zdCBmcmFtZSA9IHRoaXMuZnJhbWVzWzBdOwogICAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IHNlbGVjdG9yc0NvdW50OyBpKyspIHsKICAgICAgICAgICAgICBjb25zdCBjb21wb25lbnQgPSBmcmFtZS5jb21wb25lbnRzW2RhdGFbb2Zmc2V0KytdXTsKICAgICAgICAgICAgICBjb25zdCB0YWJsZVNwZWMgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgICBjb21wb25lbnQuaHVmZm1hblRhYmxlREMgPSB0aGlzLmh1ZmZtYW5UYWJsZXNEQ1t0YWJsZVNwZWMgPj4gNF07CiAgICAgICAgICAgICAgY29tcG9uZW50Lmh1ZmZtYW5UYWJsZUFDID0gdGhpcy5odWZmbWFuVGFibGVzQUNbdGFibGVTcGVjICYgMTVdOwogICAgICAgICAgICAgIGNvbXBvbmVudHMucHVzaChjb21wb25lbnQpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvbnN0IHNwZWN0cmFsU3RhcnQgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgY29uc3Qgc3BlY3RyYWxFbmQgPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgY29uc3Qgc3VjY2Vzc2l2ZUFwcHJveGltYXRpb24gPSBkYXRhW29mZnNldCsrXTsKICAgICAgICAgICAgY29uc3QgcHJvY2Vzc2VkID0gZGVjb2RlU2NhbihkYXRhLCBvZmZzZXQsCiAgICAgICAgICAgICAgZnJhbWUsIGNvbXBvbmVudHMsIHRoaXMucmVzZXRJbnRlcnZhbCwKICAgICAgICAgICAgICBzcGVjdHJhbFN0YXJ0LCBzcGVjdHJhbEVuZCwKICAgICAgICAgICAgICBzdWNjZXNzaXZlQXBwcm94aW1hdGlvbiA+PiA0LCBzdWNjZXNzaXZlQXBwcm94aW1hdGlvbiAmIDE1KTsKICAgICAgICAgICAgb2Zmc2V0ICs9IHByb2Nlc3NlZDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CgogICAgICAgICAgY2FzZSAweEZGRkY6IC8vIEZpbGwgYnl0ZXMKICAgICAgICAgICAgaWYgKGRhdGFbb2Zmc2V0XSAhPT0gMHhGRikgeyAvLyBBdm9pZCBza2lwcGluZyBhIHZhbGlkIG1hcmtlci4KICAgICAgICAgICAgICBvZmZzZXQtLTsKICAgICAgICAgICAgfQogICAgICAgICAgICBicmVhazsKCiAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICBpZiAoZGF0YVtvZmZzZXQgLSAzXSA9PT0gMHh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0LmtleXMoY3ApKSB7CiAgICAgICAgICBjcFtqXS5xdWFudGl6YXRpb25UYWJsZSA9IHRoaXMucXVhbnRpemF0aW9uVGFibGVzW2NwW2pdLnF1YW50aXphdGlvbklkeF07CiAgICAgICAgICBkZWxldGUgY3Bbal0ucXVhbnRpemF0aW9uSWR4OwogICAgICAgIH0KICAgICAgfQoKICAgICAgY29uc3QgZnJhbWUgPSBmcmFtZXNbMF07CiAgICAgIGNvbnN0IHsgY29tcG9uZW50cywgY29tcG9uZW50c09yZGVyIH0gPSBmcmFtZTsKICAgICAgY29uc3Qgb3V0Q29tcG9uZW50cyA9IFtdOwogICAgICBjb25zdCB3aWR0aCA9IGZyYW1lLnNhbXBsZXNQZXJMaW5lOwogICAgICBjb25zdCBoZWlnaHQgPSBmcmFtZS5zY2FuTGluZXM7CgogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IGNvbXBvbmVudHNPcmRlci5sZW5ndGg7IGkrKykgewogICAgICAgIGNvbnN0IGNvbXBvbmVudCA9IGNvbXBvbmVudHNbY29tcG9uZW50c09yZGVyW2ldXTsKICAgICAgICBvdXRDb21wb25lbnRzLnB1c2goewogICAgICAgICAgbGluZXM6IGJ1aWxkQ29tcG9uZW50RGF0YShmcmFtZSwgY29tcG9uZW50KSwKICAgICAgICAgIHNjYWxlWDogY29tcG9uZW50LmggLyBmcmFtZS5tYXhILAogICAgICAgICAgc2NhbGVZOiBjb21wb25lbnQudiAvIGZyYW1lLm1heFYsCiAgICAgICAgfSk7CiAgICAgIH0KCiAgICAgIGNvbnN0IG91dCA9IG5ldyBVaW50OEFycmF5KHdpZHRoICogaGVpZ2h0ICogb3V0Q29tcG9uZW50cy5sZW5ndGgpOwogICAgICBsZXQgb2kgPSAwOwogICAgICBmb3IgKGxldCB5ID0gMDsgeSA8IGhlaWdodDsgKyt5KSB7CiAgICAgICAgZm9yIChsZXQgeCA9IDA7IHggPCB3aWR0aDsgKyt4KSB7CiAgICAgICAgICBmb3IgKGxldCBpID0g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2FyZS4KICAvLyAzLiBUaGlzIG5vdGljZSBtYXkgbm90IGJlIHJlbW92ZWQgb3IgYWx0ZXJlZCBmcm9tIGFueSBzb3VyY2UgZGlzdHJpYnV0aW9uLgoKICAvKiBlc2xpbnQtZGlzYWJsZSBzcGFjZS11bmFyeS1vcHMgKi8KCiAgLyogUHVibGljIGNvbnN0YW50cyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09Ki8KICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwoKCiAgLy9jb25zdCBaX0ZJTFRFUkVEICAgICAgICAgID0gMTsKICAvL2NvbnN0IFpfSFVGRk1BTl9PTkxZICAgICAgPSAyOwogIC8vY29uc3QgWl9STEUgICAgICAgICAgICAgICA9IDM7CiAgY29uc3QgWl9GSVhFRCQxICAgICAgICAgICAgICAgPSA0OwogIC8vY29uc3QgWl9ERUZBVUxUX1NUUkFURUdZICA9IDA7CgogIC8qIFBvc3NpYmxlIHZhbHVlcyBvZiB0aGUgZGF0YV90eXBlIGZpZWxkICh0aG91Z2ggc2VlIGluZmxhdGUoKSkgKi8KICBjb25zdCBaX0JJTkFSWSAgICAgICAgICAgICAgPSAwOwogIGNvbnN0IFpfVEVYVCAgICAgICAgICAgICAgICA9IDE7CiAgLy9jb25zdCBaX0FTQ0lJICAgICAgICAgICAgID0gMTsgLy8gPSBaX1RFWFQKICBjb25zdCBaX1VOS05PV04kMSAgICAgICAgICAgICA9IDI7CgogIC8qPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSovCgoKICBmdW5jdGlvbiB6ZXJvJDEoYnVmKSB7IGxldCBsZW4gPSBidWYubGVuZ3RoOyB3aGlsZSAoLS1sZW4gPj0gMCkgeyBidWZbbGVuXSA9IDA7IH0gfQoKIC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pZCArPSBsZW5ndGggLSBCdWZfc2l6ZTsKICAgIH0gZWxzZSB7CiAgICAgIHMuYmlfYnVmIHw9ICh2YWx1ZSA8PCBzLmJpX3ZhbGlkKSAmIDB4ZmZmZjsKICAgICAgcy5iaV92YWxpZCArPSBsZW5ndGg7CiAgICB9CiAgfTsKCgogIGNvbnN0IHNlbmRfY29kZSA9IChzLCBjLCB0cmVlKSA9PiB7CgogICAgc2VuZF9iaXRzKHMsIHRyZWVbYyAqIDJdLyouQ29kZSovLCB0cmVlW2MgKiAyICsgMV0vKi5MZW4qLyk7CiAgfTsKCgogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQogICAqIFJldmVyc2UgdGhlIGZpcnN0IGxlbiBiaXRzIG9mIGEgY29kZSwgdXNpbmcgc3RyYWlnaHRmb3J3YXJkIGNvZGUgKGEgZmFzdGVyCiAgICogbWV0aG9kIHdvdWxkIHVzZSBhIHRhYmxlKQogICAqIElOIGFzc2VydGlvbjogMSA8PSBsZW4gPD0gMTUKICAgKi8KICBjb25zdCBiaV9yZXZlcnNlID0gKGNvZGUsIGxlbikgPT4gewoKICAgIGxldCByZXMgPSAwOwogICAgZG8gewogICAgICByZXMgfD0gY29kZSAmIDE7CiAgICAgIGNvZGUgPj4+PSAxOwogICAgICByZXMgPDw9IDE7CiAgICB9IHdoaWxlICgtLWxlbiA+IDApOwogICAgcmV0dXJuIHJlcyA+Pj4gMTsKICB9OwoKCiAgLyogPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09CiAgICogRmx1c2ggdGhlIGJpdCBidWZmZXIsIGtlZXBpbmcgYXQgbW9zdCA3IGJpdHMgaW4gaXQuCiAgICovCiAgY29uc3QgYmlfZmx1c2ggPSAocykgPT4gewoKICAgIGlmIChzLmJpX3ZhbGlkID09PSAxNikgewogICAgICBw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G9wdGltYWwgYml0IGxlbmd0aHMgKHdoaWNoIG1heQogICAgICogb3ZlcmZsb3cgaW4gdGhlIGNhc2Ugb2YgdGhlIGJpdCBsZW5ndGggdHJlZSkuCiAgICAgKi8KICAgIHRyZWVbcy5oZWFwW3MuaGVhcF9tYXhdICogMiArIDFdLyouTGVuKi8gPSAwOyAvKiByb290IG9mIHRoZSBoZWFwICovCgogICAgZm9yIChoID0gcy5oZWFwX21heCArIDE7IGggPCBIRUFQX1NJWkUkMTsgaCsrKSB7CiAgICAgIG4gPSBzLmhlYXBbaF07CiAgICAgIGJpdHMgPSB0cmVlW3RyZWVbbiAqIDIgKyAxXS8qLkRhZCovICogMiArIDFdLyouTGVuKi8gKyAxOwogICAgICBpZiAoYml0cyA+IG1heF9sZW5ndGgpIHsKICAgICAgICBiaXRzID0gbWF4X2xlbmd0aDsKICAgICAgICBvdmVyZmxvdysrOwogICAgICB9CiAgICAgIHRyZWVbbiAqIDIgKyAxXS8qLkxlbiovID0gYml0czsKICAgICAgLyogV2Ugb3ZlcndyaXRlIHRyZWVbbl0uRGFkIHdoaWNoIGlzIG5vIGxvbmdlciBuZWVkZWQgKi8KCiAgICAgIGlmIChuID4gbWF4X2NvZGUpIHsgY29udGludWU7IH0gLyogbm90IGEgbGVhZiBub2RlICovCgogICAgICBzLmJsX2NvdW50W2JpdHNdKys7CiAgICAgIHhiaXRzID0gMDsKICAgICAgaWYgKG4gPj0gYmFzZSkgewogICAgICAgIHhiaXRzID0gZXh0cmFbbiAtIGJhc2VdOwogICAgICB9CiAgICAgIGYgPSB0cmVlW24gKiAyXS8qLkZyZXEqLzsKICAgICAgcy5vcHRfbGVuICs9IGYgKiAoYml0cyArIHhiaXRzKTsKICAgICAgaWYgKGhhc19zdHJlZSkgewogICAgICAgIHMuc3RhdGljX2xlbiArPSBmICogKHN0cmVlW24gKiAyICsgMV0vKi5MZW4qLyArIHhiaXRzKTsKICAgICAgfQogICAgfQogICAgaWYgKG92ZXJmbG93ID09PSAw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gd3Jvbmcgb25lcy4gVGhpcyBpZGVhIGlzIHRha2VuCiAgICAgKiBmcm9tICdhcicgd3JpdHRlbiBieSBIYXJ1aGlrbyBPa3VtdXJhLikKICAgICAqLwogICAgZm9yIChiaXRzID0gbWF4X2xlbmd0aDsgYml0cyAhPT0gMDsgYml0cy0tKSB7CiAgICAgIG4gPSBzLmJsX2NvdW50W2JpdHNdOwogICAgICB3aGlsZSAobiAhPT0gMCkgewogICAgICAgIG0gPSBzLmhlYXBbLS1oXTsKICAgICAgICBpZiAobSA+IG1heF9jb2RlKSB7IGNvbnRpbnVlOyB9CiAgICAgICAgaWYgKHRyZWVbbSAqIDIgKyAxXS8qLkxlbiovICE9PSBiaXRzKSB7CiAgICAgICAgICAvLyBUcmFjZSgoc3RkZXJyLCJjb2RlICVkIGJpdHMgJWQtPiVkXG4iLCBtLCB0cmVlW21dLkxlbiwgYml0cykpOwogICAgICAgICAgcy5vcHRfbGVuICs9IChiaXRzIC0gdHJlZVttICogMiArIDFdLyouTGVuKi8pICogdHJlZVttICogMl0vKi5GcmVxKi87CiAgICAgICAgICB0cmVlW20gKiAyICsgMV0vKi5MZW4qLyA9IGJpdHM7CiAgICAgICAgfQogICAgICAgIG4tLTsKICAgICAgfQogICAgfQogIH07CgoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBHZW5lcmF0ZSB0aGUgY29kZXMgZm9yIGEgZ2l2ZW4gdHJlZSBhbmQgYml0IGNvdW50cyAod2hpY2ggbmVlZCBub3QgYmUKICAgKiBvcHRpbWFsKS4KICAgKiBJTiBhc3NlcnRpb246IHRoZSBhcnJheSBibF9jb3VudCBjb250YWlucyB0aGUgYml0IGxlbmd0aCBzdGF0aXN0aWNzIGZvcgogICAqIHRoZSBnaXZlbiB0cmVlIGFuZCB0aGUgZmllbGQgbGVuIGlzIHNldCBmb3IgYWxsIHRyZWUgZWxlbW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MTsKICAgIH0KICAgIC8qIENoZWNrIHRoYXQgdGhlIGJpdCBjb3VudHMgaW4gYmxfY291bnQgYXJlIGNvbnNpc3RlbnQuIFRoZSBsYXN0IGNvZGUKICAgICAqIG11c3QgYmUgYWxsIG9uZXMuCiAgICAgKi8KICAgIC8vQXNzZXJ0IChjb2RlICsgYmxfY291bnRbTUFYX0JJVFNdLTEgPT0gKDE8PE1BWF9CSVRTKS0xLAogICAgLy8gICAgICAgICJpbmNvbnNpc3RlbnQgYml0IGNvdW50cyIpOwogICAgLy9UcmFjZXYoKHN0ZGVyciwiXG5nZW5fY29kZXM6IG1heF9jb2RlICVkICIsIG1heF9jb2RlKSk7CgogICAgZm9yIChuID0gMDsgIG4gPD0gbWF4X2NvZGU7IG4rKykgewogICAgICBsZXQgbGVuID0gdHJlZVtuICogMiArIDFdLyouTGVuKi87CiAgICAgIGlmIChsZW4gPT09IDApIHsgY29udGludWU7IH0KICAgICAgLyogTm93IHJldmVyc2UgdGhlIGJpdHMgKi8KICAgICAgdHJlZVtuICogMl0vKi5Db2RlKi8gPSBiaV9yZXZlcnNlKG5leHRfY29kZVtsZW5dKyssIGxlbik7CgogICAgICAvL1RyYWNlY3YodHJlZSAhPSBzdGF0aWNfbHRyZWUsIChzdGRlcnIsIlxubiAlM2QgJWMgbCAlMmQgYyAlNHggKCV4KSAiLAogICAgICAvLyAgICAgbiwgKGlzZ3JhcGgobikgPyBuIDogJyAnKSwgbGVuLCB0cmVlW25dLkNvZGUsIG5leHRfY29kZVtsZW5dLTEpKTsKICAgIH0KICB9OwoKCiAgLyogPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09CiAgICogSW5pdGlhbGl6ZSB0aGUgdmFyaW91cyAnY29uc3RhbnQnIHRhYmxlcy4KICAgKi8KICBjb25zdCB0cl9zdGF0aWNfaW5pdCA9ICgpID0+IHsKCiAgICBsZXQgbjsgICAgICAgIC8qIG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pc3RhbmNlcyBhcmUgZGl2aWRlZCBieSAxMjggKi8KICAgIGZvciAoOyBjb2RlIDwgRF9DT0RFUyQxOyBjb2RlKyspIHsKICAgICAgYmFzZV9kaXN0W2NvZGVdID0gZGlzdCA8PCA3OwogICAgICBmb3IgKG4gPSAwOyBuIDwgKDEgPDwgKGV4dHJhX2RiaXRzW2NvZGVdIC0gNykpOyBuKyspIHsKICAgICAgICBfZGlzdF9jb2RlWzI1NiArIGRpc3QrK10gPSBjb2RlOwogICAgICB9CiAgICB9CiAgICAvL0Fzc2VydCAoZGlzdCA9PSAyNTYsICJ0cl9zdGF0aWNfaW5pdDogMjU2K2Rpc3QgIT0gNTEyIik7CgogICAgLyogQ29uc3RydWN0IHRoZSBjb2RlcyBvZiB0aGUgc3RhdGljIGxpdGVyYWwgdHJlZSAqLwogICAgZm9yIChiaXRzID0gMDsgYml0cyA8PSBNQVhfQklUUyQxOyBiaXRzKyspIHsKICAgICAgYmxfY291bnRbYml0c10gPSAwOwogICAgfQoKICAgIG4gPSAwOwogICAgd2hpbGUgKG4gPD0gMTQzKSB7CiAgICAgIHN0YXRpY19sdHJlZVtuICogMiArIDFdLyouTGVuKi8gPSA4OwogICAgICBuKys7CiAgICAgIGJsX2NvdW50WzhdKys7CiAgICB9CiAgICB3aGlsZSAobiA8PSAyNTUpIHsKICAgICAgc3RhdGljX2x0cmVlW24gKiAyICsgMV0vKi5MZW4qLyA9IDk7CiAgICAgIG4rKzsKICAgICAgYmxfY291bnRbOV0rKzsKICAgIH0KICAgIHdoaWxlIChuIDw9IDI3OSkgewogICAgICBzdGF0aWNfbHRyZWVbbiAqIDIgKyAxXS8qLkxlbiovID0gNzsKICAgICAgbisrOwogICAgICBibF9jb3VudFs3XSsrOwogICAgfQogICAgd2hpbGUgKG4gPD0gMjg3KSB7CiAgICAgIHN0YXRpY19sdHJlZVtuICogMiArIDFdLyouTGVuKi8gPSA4OwogICAgICBuKys7CiAgICAgIGJsX2NvdW50WzhdKys7CiAgICB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iA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBJbml0aWFsaXplIGEgbmV3IGJsb2NrLgogICAqLwogIGNvbnN0IGluaXRfYmxvY2sgPSAocykgPT4gewoKICAgIGxldCBuOyAvKiBpdGVyYXRlcyBvdmVyIHRyZWUgZWxlbWVudHMgKi8KCiAgICAvKiBJbml0aWFsaXplIHRoZSB0cmVlcy4gKi8KICAgIGZvciAobiA9IDA7IG4gPCBMX0NPREVTJDE7ICBuKyspIHsgcy5keW5fbHRyZWVbbiAqIDJdLyouRnJlcSovID0gMDsgfQogICAgZm9yIChuID0gMDsgbiA8IERfQ09ERVMkMTsgIG4rKykgeyBzLmR5bl9kdHJlZVtuICogMl0vKi5GcmVxKi8gPSAwOyB9CiAgICBmb3IgKG4gPSAwOyBuIDwgQkxfQ09ERVMkMTsgbisrKSB7IHMuYmxfdHJlZVtuICogMl0vKi5GcmVxKi8gPSAwOyB9CgogICAgcy5keW5fbHRyZWVbRU5EX0JMT0NLICogMl0vKi5GcmVxKi8gPSAxOwogICAgcy5vcHRfbGVuID0gcy5zdGF0aWNfbGVuID0gMDsKICAgIHMubGFzdF9saXQgPSBzLm1hdGNoZXMgPSAwOwogIH07CgoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBGbHVzaCB0aGUgYml0IGJ1ZmZlciBhbmQgYWxpZ24gdGhlIG91dHB1dCBvbiBhIGJ5dGUgYm91bmRhcnkKICAgKi8KICBjb25zdCBiaV93aW5kdXAgPSAocykgPT4KICB7CiAgICBpZiAocy5iaV92YWxpZCA+IDgpIHsKICAgICAgcHV0X3Nob3J0KHMsIHMuYmlfYnVmKTsKICAgIH0gZWxzZSBpZiAocy5iaV92YWxpZCA+IDApIHsKICAgICAgLy9wdXRfYnl0ZShzLCAoQnl0ZSlzLT5iaV9idWYpOwogICAgICBzLnBlbmRpbmdfYnVmW3MucGVuZGluZysrXSA9IHMuYmlfYnVmOwogICAgfQogICAgcy5iaV9idWYgPSAwOwogICAgcy5iaV92YWxpZCA9IDA7CiAgfTsKCiAgLyogPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09CiAgICogQ29weSBhIHN0b3JlZCBibG9jaywgc3RvcmluZyBmaXJzdCB0aGUgbGVuZ3RoIGFuZCBpdHMKICAgKiBvbmUncyBjb21wbGVtZW50IGlmIHJlcXVlc3RlZC4KICAgKi8KICBjb25zdCBjb3B5X2Jsb2NrID0gKHMsIGJ1ZiwgbGVuLCBoZWFkZXIpID0+CiAgLy9EZWZsYXRlU3RhdGUgKnM7CiAgLy9jaGFyZiAgICAqYnVmOyAgICAvKiB0aGUgaW5wdXQgZGF0YSAqLwogIC8vdW5zaWduZWQgbGVuOyAgICAgLyogaXRzIGxlbmd0aCAqLwogIC8vaW50ICAgICAgaGVhZGVyOyAgLyogdHJ1ZSBpZiBibG9jayBoZWFkZXIgbXVzdCBiZSB3cml0dGVuICovCiAgewogICAgYmlfd2luZHVwKHMpOyAgICAgICAgLyogYWxpZ24gb24gYnl0ZSBib3VuZGFyeSAqLwoKICAgIGlmIChoZWFkZXIpIHsKICAgICAgcHV0X3Nob3J0KHMsIGxlbik7CiAgICAgIHB1dF9zaG9ydChzLCB+bGVuKTsKICAgIH0KICAvLyAgd2hpbGUgKGxlbi0tKSB7CiAgLy8gICAgcHV0X2J5dGUocywgKmJ1ZisrKTsKICAvLyAgfQogICAgcy5wZW5kaW5nX2J1Zi5zZXQocy53aW5kb3cuc3ViYXJyYXkoYnVmLCBidWYgKyBsZW4pLCBzLnBlbmRpbmcpOwogICAgcy5wZW5kaW5nICs9IGxlbjsKICB9OwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT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C8qIHRoZSB0cmVlIHRvIHJlc3RvcmUgKi8KICAvLyAgICBpbnQgazsgICAgICAgICAgICAgICAvKiBub2RlIHRvIG1vdmUgZG93biAqLwogIHsKICAgIGNvbnN0IHYgPSBzLmhlYXBba107CiAgICBsZXQgaiA9IGsgPDwgMTsgIC8qIGxlZnQgc29uIG9mIGsgKi8KICAgIHdoaWxlIChqIDw9IHMuaGVhcF9sZW4pIHsKICAgICAgLyogU2V0IGogdG8gdGhlIHNtYWxsZXN0IG9mIHRoZSB0d28gc29uczogKi8KICAgICAgaWYgKGogPCBzLmhlYXBfbGVuICYmCiAgICAgICAgc21hbGxlcih0cmVlLCBzLmhlYXBbaiArIDFdLCBzLmhlYXBbal0sIHMuZGVwdGgpKSB7CiAgICAgICAgaisrOwogICAgICB9CiAgICAgIC8qIEV4aXQgaWYgdiBpcyBzbWFsbGVyIHRoYW4gYm90aCBzb25zICovCiAgICAgIGlmIChzbWFsbGVyKHRyZWUsIHYsIHMuaGVhcFtqXSwgcy5kZXB0aCkpIHsgYnJlYWs7IH0KCiAgICAgIC8qIEV4Y2hhbmdlIHYgd2l0aCB0aGUgc21hbGxlc3Qgc29uICovCiAgICAgIHMuaGVhcFtrXSA9IHMuaGVhcFtqXTsKICAgICAgayA9IGo7CgogICAgICAvKiBBbmQgY29udGludWUgZG93biB0aGUgdHJlZSwgc2V0dGluZyBqIHRvIHRoZSBsZWZ0IHNvbiBvZiBrICovCiAgICAgIGogPDw9IDE7CiAgICB9CiAgICBzLmhlYXBba10gPSB2OwogIH07CgoKICAvLyBpbmxpbmVkIG1hbnVhbGx5CiAgLy8gY29uc3QgU01BTExFU1QgPSAxOwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBTZW5kIHRoZSBibG9jayBkYXRhIGNvbXByZXNzZWQgdXNpbmcgdGhlIGdpdmVuIEh1ZmZtYW4gdHJlZXMKICA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l9jb3VudCkgewogICAgICAgIHMuYmxfdHJlZVtjdXJsZW4gKiAyXS8qLkZyZXEqLyArPSBjb3VudDsKCiAgICAgIH0gZWxzZSBpZiAoY3VybGVuICE9PSAwKSB7CgogICAgICAgIGlmIChjdXJsZW4gIT09IHByZXZsZW4pIHsgcy5ibF90cmVlW2N1cmxlbiAqIDJdLyouRnJlcSovKys7IH0KICAgICAgICBzLmJsX3RyZWVbUkVQXzNfNiAqIDJdLyouRnJlcSovKys7CgogICAgICB9IGVsc2UgaWYgKGNvdW50IDw9IDEwKSB7CiAgICAgICAgcy5ibF90cmVlW1JFUFpfM18xMCAqIDJdLyouRnJlcSovKys7CgogICAgICB9IGVsc2UgewogICAgICAgIHMuYmxfdHJlZVtSRVBaXzExXzEzOCAqIDJdLyouRnJlcSovKys7CiAgICAgIH0KCiAgICAgIGNvdW50ID0gMDsKICAgICAgcHJldmxlbiA9IGN1cmxlbjsKCiAgICAgIGlmIChuZXh0bGVuID09PSAwKSB7CiAgICAgICAgbWF4X2NvdW50ID0gMTM4OwogICAgICAgIG1pbl9jb3VudCA9IDM7CgogICAgICB9IGVsc2UgaWYgKGN1cmxlbiA9PT0gbmV4dGxlbikgewogICAgICAgIG1heF9jb3VudCA9IDY7CiAgICAgICAgbWluX2NvdW50ID0gMzsKCiAgICAgIH0gZWxzZSB7CiAgICAgICAgbWF4X2NvdW50ID0gNzsKICAgICAgICBtaW5fY291bnQgPSA0OwogICAgICB9CiAgICB9CiAgfTsKCgogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQogICAqIFNlbmQgYSBsaXRlcmFsIG9yIGRpc3RhbmNlIHRyZWUgaW4gY29tcHJlc3NlZCBmb3JtLCB1c2luZyB0aGUgY29kZXMgaW4KICAgKiBibF90cmVlLgogICAqLwogIGNvbnN0IHNlbmRfdHJlZSA9IChzLCB0cmVlLCBtYXhfY29kZSkgPT4KICAvLy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biovOwoKICAgICAgaWYgKCsrY291bnQgPCBtYXhfY291bnQgJiYgY3VybGVuID09PSBuZXh0bGVuKSB7CiAgICAgICAgY29udGludWU7CgogICAgICB9IGVsc2UgaWYgKGNvdW50IDwgbWluX2NvdW50KSB7CiAgICAgICAgZG8geyBzZW5kX2NvZGUocywgY3VybGVuLCBzLmJsX3RyZWUpOyB9IHdoaWxlICgtLWNvdW50ICE9PSAwKTsKCiAgICAgIH0gZWxzZSBpZiAoY3VybGVuICE9PSAwKSB7CiAgICAgICAgaWYgKGN1cmxlbiAhPT0gcHJldmxlbikgewogICAgICAgICAgc2VuZF9jb2RlKHMsIGN1cmxlbiwgcy5ibF90cmVlKTsKICAgICAgICAgIGNvdW50LS07CiAgICAgICAgfQogICAgICAgIC8vQXNzZXJ0KGNvdW50ID49IDMgJiYgY291bnQgPD0gNiwgIiAzXzY/Iik7CiAgICAgICAgc2VuZF9jb2RlKHMsIFJFUF8zXzYsIHMuYmxfdHJlZSk7CiAgICAgICAgc2VuZF9iaXRzKHMsIGNvdW50IC0gMywgMik7CgogICAgICB9IGVsc2UgaWYgKGNvdW50IDw9IDEwKSB7CiAgICAgICAgc2VuZF9jb2RlKHMsIFJFUFpfM18xMCwgcy5ibF90cmVlKTsKICAgICAgICBzZW5kX2JpdHMocywgY291bnQgLSAzLCAzKTsKCiAgICAgIH0gZWxzZSB7CiAgICAgICAgc2VuZF9jb2RlKHMsIFJFUFpfMTFfMTM4LCBzLmJsX3RyZWUpOwogICAgICAgIHNlbmRfYml0cyhzLCBjb3VudCAtIDExLCA3KTsKICAgICAgfQoKICAgICAgY291bnQgPSAwOwogICAgICBwcmV2bGVuID0gY3VybGVuOwogICAgICBpZiAobmV4dGxlbiA9PT0gMCkgewogICAgICAgIG1heF9jb3VudCA9IDEzODsKICAgICAgICBtaW5fY291bnQgPSAzOwoKICAgICAgfSBlbHNlIGlmIChjdXJsZW4gPT09IG5leHRsZW4pIHsKICAgICAgICBtYXhfY291bnQgPSA2OwogIC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qIDJdLyouRnJlcSovICE9PSAwIHx8IHMuZHluX2x0cmVlWzEwICogMl0vKi5GcmVxKi8gIT09IDAgfHwKICAgICAgICBzLmR5bl9sdHJlZVsxMyAqIDJdLyouRnJlcSovICE9PSAwKSB7CiAgICAgIHJldHVybiBaX1RFWFQ7CiAgICB9CiAgICBmb3IgKG4gPSAzMjsgbiA8IExJVEVSQUxTJDE7IG4rKykgewogICAgICBpZiAocy5keW5fbHRyZWVbbiAqIDJdLyouRnJlcSovICE9PSAwKSB7CiAgICAgICAgcmV0dXJuIFpfVEVYVDsKICAgICAgfQogICAgfQoKICAgIC8qIFRoZXJlIGFyZSBubyAiYmxhY2stbGlzdGVkIiBvciAid2hpdGUtbGlzdGVkIiBieXRlczoKICAgICAqIHRoaXMgc3RyZWFtIGVpdGhlciBpcyBlbXB0eSBvciBoYXMgdG9sZXJhdGVkICgiZ3JheS1saXN0ZWQiKSBieXRlcyBvbmx5LgogICAgICovCiAgICByZXR1cm4gWl9CSU5BUlk7CiAgfTsKCgogIGxldCBzdGF0aWNfaW5pdF9kb25lID0gZmFsc2U7CgogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQogICAqIEluaXRpYWxpemUgdGhlIHRyZWUgZGF0YSBzdHJ1Y3R1cmVzIGZvciBhIG5ldyB6bGliIHN0cmVhbS4KICAgKi8KICBjb25zdCBfdHJfaW5pdCQxID0gKHMpID0+CiAgewoKICAgIGlmICghc3RhdGljX2luaXRfZG9uZSkgewogICAgICB0cl9zdGF0aWNfaW5pdCgpOwogICAgICBzdGF0aWNfaW5pdF9kb25lID0gdHJ1ZTsKICAgIH0KCiAgICBzLmxfZGVzYyAgPSBuZXcgVHJlZURlc2Mocy5keW5fbHRyZWUsIHN0YXRpY19sX2Rlc2MpOwogICAgcy5kX2Rlc2MgID0gbmV3IFRyZWVEZXNjKHMuZHluX2R0cmVlLCBzdGF0aWNfZF9k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y8gICBhcHByZWNpYXRlZCBidXQgaXMgbm90IHJlcXVpcmVkLgogIC8vIDIuIEFsdGVyZWQgc291cmNlIHZlcnNpb25zIG11c3QgYmUgcGxhaW5seSBtYXJrZWQgYXMgc3VjaCwgYW5kIG11c3Qgbm90IGJlCiAgLy8gICBtaXNyZXByZXNlbnRlZCBhcyBiZWluZyB0aGUgb3JpZ2luYWwgc29mdHdhcmUuCiAgLy8gMy4gVGhpcyBub3RpY2UgbWF5IG5vdCBiZSByZW1vdmVkIG9yIGFsdGVyZWQgZnJvbSBhbnkgc291cmNlIGRpc3RyaWJ1dGlvbi4KCiAgdmFyIG1lc3NhZ2VzID0gewogICAgMjogICAgICAnbmVlZCBkaWN0aW9uYXJ5JywgICAgIC8qIFpfTkVFRF9ESUNUICAgICAgIDIgICovCiAgICAxOiAgICAgICdzdHJlYW0gZW5kJywgICAgICAgICAgLyogWl9TVFJFQU1fRU5EICAgICAgMSAgKi8KICAgIDA6ICAgICAgJycsICAgICAgICAgICAgICAgICAgICAvKiBaX09LICAgICAgICAgICAgICAwICAqLwogICAgJy0xJzogICAnZmlsZSBlcnJvcicsICAgICAgICAgIC8qIFpfRVJSTk8gICAgICAgICAoLTEpICovCiAgICAnLTInOiAgICdzdHJlYW0gZXJyb3InLCAgICAgICAgLyogWl9TVFJFQU1fRVJST1IgICgtMikgKi8KICAgICctMyc6ICAgJ2RhdGEgZXJyb3InLCAgICAgICAgICAvKiBaX0RBVEFfRVJST1IgICAgKC0zKSAqLwogICAgJy00JzogICAnaW5zdWZmaWNpZW50IG1lbW9yeScsIC8qIFpfTUVNX0VSUk9SICAgICAoLTQpICovCiAgICAnLTUnOiAgICdidWZmZXIgZXJyb3InLCAgICAgICAgLyogWl9CVUZfRVJST1IgICAgICgtNSkgKi8KICAgICctNic6ICAgJ2luY29tcGF0aWJsZSB2ZXJzaW9uJyAvKiBaX1ZFUlNJT05fRVJST1IgKC02KSAqLwogIH07CgogIC8vIChDKSAxOTk1LTIwMTMgSmV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gICAgICAtNSwKICAgIC8vWl9WRVJTSU9OX0VSUk9SOiAtNiwKCiAgICAvKiBjb21wcmVzc2lvbiBsZXZlbHMgKi8KICAgIFpfTk9fQ09NUFJFU1NJT046ICAgICAgICAgMCwKICAgIFpfQkVTVF9TUEVFRDogICAgICAgICAgICAgMSwKICAgIFpfQkVTVF9DT01QUkVTU0lPTjogICAgICAgOSwKICAgIFpfREVGQVVMVF9DT01QUkVTU0lPTjogICAtMSwKCgogICAgWl9GSUxURVJFRDogICAgICAgICAgICAgICAxLAogICAgWl9IVUZGTUFOX09OTFk6ICAgICAgICAgICAyLAogICAgWl9STEU6ICAgICAgICAgICAgICAgICAgICAzLAogICAgWl9GSVhFRDogICAgICAgICAgICAgICAgICA0LAogICAgWl9ERUZBVUxUX1NUUkFURUdZOiAgICAgICAwLAoKICAgIC8qIFBvc3NpYmxlIHZhbHVlcyBvZiB0aGUgZGF0YV90eXBlIGZpZWxkICh0aG91Z2ggc2VlIGluZmxhdGUoKSkgKi8KICAgIFpfQklOQVJZOiAgICAgICAgICAgICAgICAgMCwKICAgIFpfVEVYVDogICAgICAgICAgICAgICAgICAgMSwKICAgIC8vWl9BU0NJSTogICAgICAgICAgICAgICAgMSwgLy8gPSBaX1RFWFQgKGRlcHJlY2F0ZWQpCiAgICBaX1VOS05PV046ICAgICAgICAgICAgICAgIDIsCgogICAgLyogVGhlIGRlZmxhdGUgY29tcHJlc3Npb24gbWV0aG9kICovCiAgICBaX0RFRkxBVEVEOiAgICAgICAgICAgICAgIDgKICAgIC8vWl9OVUxMOiAgICAgICAgICAgICAgICAgbnVsbCAvLyBVc2UgLTEgb3IgbnVsbCBpbmxpbmUsIGRlcGVuZGluZyBvbiB2YXIgdHlwZQogIH07CgogIC8vIChDKSAxOTk1LTIwMTMgSmVhbi1sb3VwIEdhaWxseSBhbmQgTWFyayBBZGxlcgogIC8vIChDKSAyMDE0LTIwMTcgVml0YWx5IFB1enJpbiBhbmQgQW5kcmV5IFR1cGl0c2luCi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X3BlbmRpbmcgPSAoc3RybSkgPT4gewogICAgY29uc3QgcyA9IHN0cm0uc3RhdGU7CgogICAgLy9fdHJfZmx1c2hfYml0cyhzKTsKICAgIGxldCBsZW4gPSBzLnBlbmRpbmc7CiAgICBpZiAobGVuID4gc3RybS5hdmFpbF9vdXQpIHsKICAgICAgbGVuID0gc3RybS5hdmFpbF9vdXQ7CiAgICB9CiAgICBpZiAobGVuID09PSAwKSB7IHJldHVybjsgfQoKICAgIHN0cm0ub3V0cHV0LnNldChzLnBlbmRpbmdfYnVmLnN1YmFycmF5KHMucGVuZGluZ19vdXQsIHMucGVuZGluZ19vdXQgKyBsZW4pLCBzdHJtLm5leHRfb3V0KTsKICAgIHN0cm0ubmV4dF9vdXQgKz0gbGVuOwogICAgcy5wZW5kaW5nX291dCArPSBsZW47CiAgICBzdHJtLnRvdGFsX291dCArPSBsZW47CiAgICBzdHJtLmF2YWlsX291dCAtPSBsZW47CiAgICBzLnBlbmRpbmcgLT0gbGVuOwogICAgaWYgKHMucGVuZGluZyA9PT0gMCkgewogICAgICBzLnBlbmRpbmdfb3V0ID0gMDsKICAgIH0KICB9OwoKCiAgY29uc3QgZmx1c2hfYmxvY2tfb25seSA9IChzLCBsYXN0KSA9PiB7CiAgICBfdHJfZmx1c2hfYmxvY2socywgKHMuYmxvY2tfc3RhcnQgPj0gMCA/IHMuYmxvY2tfc3RhcnQgOiAtMSksIHMuc3Ryc3RhcnQgLSBzLmJsb2NrX3N0YXJ0LCBsYXN0KTsKICAgIHMuYmxvY2tfc3RhcnQgPSBzLnN0cnN0YXJ0OwogICAgZmx1c2hfcGVuZGluZyhzLnN0cm0pOwogIH07CgoKICBjb25zdCBwdXRfYnl0ZSA9IChzLCBiKSA9PiB7CiAgICBzLnBlbmRpbmdfYnVmW3MucGVuZGluZysrXSA9IGI7CiAgfTsKCgogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09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ICB9IHdoaWxlIChfd2luWysrc2Nhbl0gPT09IF93aW5bKyttYXRjaF0gJiYgX3dpblsrK3NjYW5dID09PSBfd2luWysrbWF0Y2hdICYmCiAgICAgICAgICAgICAgIF93aW5bKytzY2FuXSA9PT0gX3dpblsrK21hdGNoXSAmJiBfd2luWysrc2Nhbl0gPT09IF93aW5bKyttYXRjaF0gJiYKICAgICAgICAgICAgICAgX3dpblsrK3NjYW5dID09PSBfd2luWysrbWF0Y2hdICYmIF93aW5bKytzY2FuXSA9PT0gX3dpblsrK21hdGNoXSAmJgogICAgICAgICAgICAgICBfd2luWysrc2Nhbl0gPT09IF93aW5bKyttYXRjaF0gJiYgX3dpblsrK3NjYW5dID09PSBfd2luWysrbWF0Y2hdICYmCiAgICAgICAgICAgICAgIHNjYW4gPCBzdHJlbmQpOwoKICAgICAgLy8gQXNzZXJ0KHNjYW4gPD0gcy0+d2luZG93Kyh1bnNpZ25lZCkocy0+d2luZG93X3NpemUtMSksICJ3aWxkIHNjYW4iKTsKCiAgICAgIGxlbiA9IE1BWF9NQVRDSCAtIChzdHJlbmQgLSBzY2FuKTsKICAgICAgc2NhbiA9IHN0cmVuZCAtIE1BWF9NQVRDSDsKCiAgICAgIGlmIChsZW4gPiBiZXN0X2xlbikgewogICAgICAgIHMubWF0Y2hfc3RhcnQgPSBjdXJfbWF0Y2g7CiAgICAgICAgYmVzdF9sZW4gPSBsZW47CiAgICAgICAgaWYgKGxlbiA+PSBuaWNlX21hdGNoKSB7CiAgICAgICAgICBicmVhazsKICAgICAgICB9CiAgICAgICAgc2Nhbl9lbmQxICA9IF93aW5bc2NhbiArIGJlc3RfbGVuIC0gMV07CiAgICAgICAgc2Nhbl9lbmQgICA9IF93aW5bc2NhbiArIGJlc3RfbGVuXTsKICAgICAgfQogICAgfSB3aGlsZSAoKGN1cl9tYXRjaCA9IHByZXZbY3VyX21hdGNoICYgd21hc2tdKSA+IGxpbWl0ICYmIC0tY2hhaW5fbGVuZ3RoICE9PSAwKTsK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2NrIGJlbG93IG5vdCBuZWVkZWQKICAgICAgLyogRGVhbCB3aXRoICFAIyQlIDY0SyBsaW1pdDogKi8KICAgICAgLy9pZiAoc2l6ZW9mKGludCkgPD0gMikgewogICAgICAvLyAgICBpZiAobW9yZSA9PSAwICYmIHMtPnN0cnN0YXJ0ID09IDAgJiYgcy0+bG9va2FoZWFkID09IDApIHsKICAgICAgLy8gICAgICAgIG1vcmUgPSB3c2l6ZTsKICAgICAgLy8KICAgICAgLy8gIH0gZWxzZSBpZiAobW9yZSA9PSAodW5zaWduZWQpKC0xKSkgewogICAgICAvLyAgICAgICAgLyogVmVyeSB1bmxpa2VseSwgYnV0IHBvc3NpYmxlIG9uIDE2IGJpdCBtYWNoaW5lIGlmCiAgICAgIC8vICAgICAgICAgKiBzdHJzdGFydCA9PSAwICYmIGxvb2thaGVhZCA9PSAxIChpbnB1dCBkb25lIGEgYnl0ZSBhdCB0aW1lKQogICAgICAvLyAgICAgICAgICovCiAgICAgIC8vICAgICAgICBtb3JlLS07CiAgICAgIC8vICAgIH0KICAgICAgLy99CgoKICAgICAgLyogSWYgdGhlIHdpbmRvdyBpcyBhbG1vc3QgZnVsbCBhbmQgdGhlcmUgaXMgaW5zdWZmaWNpZW50IGxvb2thaGVhZCwKICAgICAgICogbW92ZSB0aGUgdXBwZXIgaGFsZiB0byB0aGUgbG93ZXIgb25lIHRvIG1ha2Ugcm9vbSBpbiB0aGUgdXBwZXIgaGFsZi4KICAgICAgICovCiAgICAgIGlmIChzLnN0cnN0YXJ0ID49IF93X3NpemUgKyAoX3dfc2l6ZSAtIE1JTl9MT09LQUhFQUQpKSB7CgogICAgICAgIHMud2luZG93LnNldChzLndpbmRvdy5zdWJhcnJheShfd19zaXplLCBfd19zaXplICsgX3dfc2l6ZSksIDApOwogICAgICAgIHMubWF0Y2hfc3RhcnQgLT0gX3dfc2l6ZTsKICAgICAgICBzLnN0cnN0YXJ0IC09IF93X3NpemU7CiAgICAgICAgLyogd2Ugbm93IGhhdm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gICAgICAgfSB3aGlsZSAoLS1uKTsKCiAgICAgICAgbW9yZSArPSBfd19zaXplOwogICAgICB9CiAgICAgIGlmIChzLnN0cm0uYXZhaWxfaW4gPT09IDApIHsKICAgICAgICBicmVhazsKICAgICAgfQoKICAgICAgLyogSWYgdGhlcmUgd2FzIG5vIHNsaWRpbmc6CiAgICAgICAqICAgIHN0cnN0YXJ0IDw9IFdTSVpFK01BWF9ESVNULTEgJiYgbG9va2FoZWFkIDw9IE1JTl9MT09LQUhFQUQgLSAxICYmCiAgICAgICAqICAgIG1vcmUgPT0gd2luZG93X3NpemUgLSBsb29rYWhlYWQgLSBzdHJzdGFydAogICAgICAgKiA9PiBtb3JlID49IHdpbmRvd19zaXplIC0gKE1JTl9MT09LQUhFQUQtMSArIFdTSVpFICsgTUFYX0RJU1QtMSkKICAgICAgICogPT4gbW9yZSA+PSB3aW5kb3dfc2l6ZSAtIDIqV1NJWkUgKyAyCiAgICAgICAqIEluIHRoZSBCSUdfTUVNIG9yIE1NQVAgY2FzZSAobm90IHlldCBzdXBwb3J0ZWQpLAogICAgICAgKiAgIHdpbmRvd19zaXplID09IGlucHV0X3NpemUgKyBNSU5fTE9PS0FIRUFEICAmJgogICAgICAgKiAgIHN0cnN0YXJ0ICsgcy0+bG9va2FoZWFkIDw9IGlucHV0X3NpemUgPT4gbW9yZSA+PSBNSU5fTE9PS0FIRUFELgogICAgICAgKiBPdGhlcndpc2UsIHdpbmRvd19zaXplID09IDIqV1NJWkUgc28gbW9yZSA+PSAyLgogICAgICAgKiBJZiB0aGVyZSB3YXMgc2xpZGluZywgbW9yZSA+PSBXU0laRS4gU28gaW4gYWxsIGNhc2VzLCBtb3JlID49IDIuCiAgICAgICAqLwogICAgICAvL0Fzc2VydChtb3JlID49IDIsICJtb3JlIDwgMiIpOwogICAgICBuID0gcmVhZF9idWYocy5zdHJtLCBzLndpbmRvdywgcy5zdHJzdGFydCArIHMubG9va2FoZWFkLCBtb3JlKTsKICAgICAgcy5sb29rYWhlYWQgKz0gbjsKCiAgICAgIC8qIEluaXRpYWxpemUgdGhlIGhhc2ggdmFsdWUgbm93IHRoYXQgd2UgaGF2ZSBzb21lIGlucHV0OiAqLwogICAgICBpZiAocy5sb29rYWhlYWQgKyBzLmluc2VydCA+PSBNSU5fTUFUQ0gpIHsKICAgICAgICBzdHIgPSBzLnN0cnN0YXJ0IC0gcy5pbnNlcnQ7CiAgICAgICAgcy5pbnNfaCA9IHMud2luZG93W3N0cl07CgogICAgICAgIC8qIFVQREFURV9IQVNIKHMsIHMtPmluc19oLCBzLT53aW5kb3dbc3RyICsgMV0pOyAqLwogICAgICAgIHMuaW5zX2ggPSBIQVNIKHMsIHMuaW5zX2gsIHMud2luZG93W3N0ciArIDFdKTsKICAvLyNpZiBNSU5fTUFUQ0ggIT0gMwogIC8vICAgICAgICBDYWxsIHVwZGF0ZV9oYXNoKCkgTUlOX01BVENILTMgbW9yZSB0aW1lcwogIC8vI2VuZGlmCiAgICAgICAgd2hpbGUgKHMuaW5zZXJ0KSB7CiAgICAgICAgICAvKiBVUERBVEVfSEFTSChzLCBzLT5pbnNfaCwgcy0+d2luZG93W3N0ciArIE1JTl9NQVRDSC0xXSk7ICovCiAgICAgICAgICBzLmluc19oID0gSEFTSChzLCBzLmluc19oLCBzLndpbmRvd1tzdHIgKyBNSU5fTUFUQ0ggLSAxXSk7CgogICAgICAgICAgcy5wcmV2W3N0ciAmIHMud19tYXNrXSA9IHMuaGVhZFtzLmluc19oXTsKICAgICAgICAgIHMuaGVhZFtzLmluc19oXSA9IHN0cjsKICAgICAgICAgIHN0cisrOwogICAgICAgICAgcy5pbnNlcnQtLTsKICAgICAgICAgIGlmIChzLmxvb2thaGVhZCArIHMuaW5zZXJ0IDwgTUlOX01BVENIKSB7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgIH0KICAgICAgfQogICAgICAvKiBJZiB0aGUgd2hvbGUgaW5wdXQgaGFzIGxlc3MgdGhhbiBNSU5fTUFUQ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lYWRlcjoKICAgICAqLwogICAgbGV0IG1heF9ibG9ja19zaXplID0gMHhmZmZmOwoKICAgIGlmIChtYXhfYmxvY2tfc2l6ZSA+IHMucGVuZGluZ19idWZfc2l6ZSAtIDUpIHsKICAgICAgbWF4X2Jsb2NrX3NpemUgPSBzLnBlbmRpbmdfYnVmX3NpemUgLSA1OwogICAgfQoKICAgIC8qIENvcHkgYXMgbXVjaCBhcyBwb3NzaWJsZSBmcm9tIGlucHV0IHRvIG91dHB1dDogKi8KICAgIGZvciAoOzspIHsKICAgICAgLyogRmlsbCB0aGUgd2luZG93IGFzIG11Y2ggYXMgcG9zc2libGU6ICovCiAgICAgIGlmIChzLmxvb2thaGVhZCA8PSAxKSB7CgogICAgICAgIC8vQXNzZXJ0KHMtPnN0cnN0YXJ0IDwgcy0+d19zaXplK01BWF9ESVNUKHMpIHx8CiAgICAgICAgLy8gIHMtPmJsb2NrX3N0YXJ0ID49IChsb25nKXMtPndfc2l6ZSwgInNsaWRlIHRvbyBsYXRlIik7CiAgLy8gICAgICBpZiAoIShzLnN0cnN0YXJ0IDwgcy53X3NpemUgKyAocy53X3NpemUgLSBNSU5fTE9PS0FIRUFEKSB8fAogIC8vICAgICAgICBzLmJsb2NrX3N0YXJ0ID49IHMud19zaXplKSkgewogIC8vICAgICAgICB0aHJvdyAgbmV3IEVycm9yKCJzbGlkZSB0b28gbGF0ZSIpOwogIC8vICAgICAgfQoKICAgICAgICBmaWxsX3dpbmRvdyhzKTsKICAgICAgICBpZiAocy5sb29rYWhlYWQgPT09IDAgJiYgZmx1c2ggPT09IFpfTk9fRkxVU0gkMikgewogICAgICAgICAgcmV0dXJuIEJTX05FRURfTU9SRTsKICAgICAgICB9CgogICAgICAgIGlmIChzLmxvb2thaGVhZCA9PT0gMCkgewogICAgICAgICAgYnJlYWs7CiAgICAgICAgfQogICAgICAgIC8qIGZsdXNoIHRoZSBjdXJyZW50IGJsb2NrICovCiAgICAgIH0KICAgICAgLy9Bc3NlcnQocy0+Y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KHMud19zaXplIC0gTUlOX0xPT0tBSEVBRCkpIHsKICAgICAgICAvKioqIEZMVVNIX0JMT0NLKHMsIDApOyAqKiovCiAgICAgICAgZmx1c2hfYmxvY2tfb25seShzLCBmYWxzZSk7CiAgICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICAgIHJldHVybiBCU19ORUVEX01PUkU7CiAgICAgICAgfQogICAgICAgIC8qKiovCiAgICAgIH0KICAgIH0KCiAgICBzLmluc2VydCA9IDA7CgogICAgaWYgKGZsdXNoID09PSBaX0ZJTklTSCQzKSB7CiAgICAgIC8qKiogRkxVU0hfQkxPQ0socywgMSk7ICoqKi8KICAgICAgZmx1c2hfYmxvY2tfb25seShzLCB0cnVlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfRklOSVNIX1NUQVJURUQ7CiAgICAgIH0KICAgICAgLyoqKi8KICAgICAgcmV0dXJuIEJTX0ZJTklTSF9ET05FOwogICAgfQoKICAgIGlmIChzLnN0cnN0YXJ0ID4gcy5ibG9ja19zdGFydCkgewogICAgICAvKioqIEZMVVNIX0JMT0NLKHMsIDApOyAqKiovCiAgICAgIGZsdXNoX2Jsb2NrX29ubHkocywgZmFsc2UpOwogICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgIHJldHVybiBCU19ORUVEX01PUkU7CiAgICAgIH0KICAgICAgLyoqKi8KICAgIH0KCiAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogIH07CgogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PQogICAqIENvbXByZXNzIGFzIG11Y2ggYXMgcG9zc2libGUgZnJvbSB0aGUgaW5wdXQgc3RyZWFtLCByZXR1cm4gdGhlIGN1cnJlbnQKICAgKiBibG9jayBzdGF0ZS4KICAgKiBUaGlzIGZ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ogICAgICAgICAqLwogICAgICAgIGlmIChzLm1hdGNoX2xlbmd0aCA8PSBzLm1heF9sYXp5X21hdGNoLyptYXhfaW5zZXJ0X2xlbmd0aCovICYmIHMubG9va2FoZWFkID49IE1JTl9NQVRDSCkgewogICAgICAgICAgcy5tYXRjaF9sZW5ndGgtLTsgLyogc3RyaW5nIGF0IHN0cnN0YXJ0IGFscmVhZHkgaW4gdGFibGUgKi8KICAgICAgICAgIGRvIHsKICAgICAgICAgICAgcy5zdHJzdGFydCsrOwogICAgICAgICAgICAvKioqIElOU0VSVF9TVFJJTkcocywgcy5zdHJzdGFydCwgaGFzaF9oZWFkKTsgKioqLwogICAgICAgICAgICBzLmluc19oID0gSEFTSChzLCBzLmluc19oLCBzLndpbmRvd1tzLnN0cnN0YXJ0ICsgTUlOX01BVENIIC0gMV0pOwogICAgICAgICAgICBoYXNoX2hlYWQgPSBzLnByZXZbcy5zdHJzdGFydCAmIHMud19tYXNrXSA9IHMuaGVhZFtzLmluc19oXTsKICAgICAgICAgICAgcy5oZWFkW3MuaW5zX2hdID0gcy5zdHJzdGFydDsKICAgICAgICAgICAgLyoqKi8KICAgICAgICAgICAgLyogc3Ryc3RhcnQgbmV2ZXIgZXhjZWVkcyBXU0laRS1NQVhfTUFUQ0gsIHNvIHRoZXJlIGFyZQogICAgICAgICAgICAgKiBhbHdheXMgTUlOX01BVENIIGJ5dGVzIGFoZWFkLgogICAgICAgICAgICAgKi8KICAgICAgICAgIH0gd2hpbGUgKC0tcy5tYXRjaF9sZW5ndGggIT09IDApOwogICAgICAgICAgcy5zdHJzdGFydCsrOwogICAgICAgIH0gZWxzZQogICAgICAgIHsKICAgICAgICAgIHMuc3Ryc3RhcnQgKz0gcy5tYXRjaF9sZW5ndGg7CiAgICAgICAgICBzLm1hdGNoX2xlbmd0aCA9IDA7CiAgICAgICAgICBzLmluc19oID0gcy53aW5kb3dbcy5zdHJzdGFydF07CiAgICAgICAgICAvKiBVUERBVEVfSEFTSChzLCBzLmluc19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KICAgICAgfQogICAgfQogICAgcy5pbnNlcnQgPSAoKHMuc3Ryc3RhcnQgPCAoTUlOX01BVENIIC0gMSkpID8gcy5zdHJzdGFydCA6IE1JTl9NQVRDSCAtIDEpOwogICAgaWYgKGZsdXNoID09PSBaX0ZJTklTSCQzKSB7CiAgICAgIC8qKiogRkxVU0hfQkxPQ0socywgMSk7ICoqKi8KICAgICAgZmx1c2hfYmxvY2tfb25seShzLCB0cnVlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfRklOSVNIX1NUQVJURUQ7CiAgICAgIH0KICAgICAgLyoqKi8KICAgICAgcmV0dXJuIEJTX0ZJTklTSF9ET05FOwogICAgfQogICAgaWYgKHMubGFzdF9saXQpIHsKICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAwKTsgKioqLwogICAgICBmbHVzaF9ibG9ja19vbmx5KHMsIGZhbHNlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogICAgICB9CiAgICAgIC8qKiovCiAgICB9CiAgICByZXR1cm4gQlNfQkxPQ0tfRE9ORTsKICB9OwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBTYW1lIGFzIGFib3ZlLCBidXQgYWNoaWV2ZXMgYmV0dGVyIGNvbXByZXNzaW9uLiBXZSB1c2UgYSBsYXp5CiAgICogZXZhbHVhdGlvbiBmb3IgbWF0Y2hlczogYSBtYXRjaCBpcyBmaW5hbGx5IGFkb3B0ZWQgb25seSBpZiB0aGVyZSBpcwogICAqIG5vIGJldHRlciBtYXRjaCBhdCB0aGUgbmV4dCB3aW5kb3cgcG9zaXRpb24uCiAgICovCiAgY29uc3QgZGVmbGF0ZV9zbG93ID0gKHMsIGZsdXNoKSA9PiB7Cg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AgICAvKioqIF90cl90YWxseV9saXQocywgcy53aW5kb3dbcy5zdHJzdGFydC0xXSwgYmZsdXNoKTsgKioqLwogICAgICAgIGJmbHVzaCA9IF90cl90YWxseShzLCAwLCBzLndpbmRvd1tzLnN0cnN0YXJ0IC0gMV0pOwoKICAgICAgICBpZiAoYmZsdXNoKSB7CiAgICAgICAgICAvKioqIEZMVVNIX0JMT0NLX09OTFkocywgMCkgKioqLwogICAgICAgICAgZmx1c2hfYmxvY2tfb25seShzLCBmYWxzZSk7CiAgICAgICAgICAvKioqLwogICAgICAgIH0KICAgICAgICBzLnN0cnN0YXJ0Kys7CiAgICAgICAgcy5sb29rYWhlYWQtLTsKICAgICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgICAgcmV0dXJuIEJTX05FRURfTU9SRTsKICAgICAgICB9CiAgICAgIH0gZWxzZSB7CiAgICAgICAgLyogVGhlcmUgaXMgbm8gcHJldmlvdXMgbWF0Y2ggdG8gY29tcGFyZSB3aXRoLCB3YWl0IGZvcgogICAgICAgICAqIHRoZSBuZXh0IHN0ZXAgdG8gZGVjaWRlLgogICAgICAgICAqLwogICAgICAgIHMubWF0Y2hfYXZhaWxhYmxlID0gMTsKICAgICAgICBzLnN0cnN0YXJ0Kys7CiAgICAgICAgcy5sb29rYWhlYWQtLTsKICAgICAgfQogICAgfQogICAgLy9Bc3NlcnQgKGZsdXNoICE9IFpfTk9fRkxVU0gsICJubyBmbHVzaD8iKTsKICAgIGlmIChzLm1hdGNoX2F2YWlsYWJsZSkgewogICAgICAvL1RyYWNldnYoKHN0ZGVyciwiJWMiLCBzLT53aW5kb3dbcy0+c3Ryc3RhcnQtMV0pKTsKICAgICAgLyoqKiBfdHJfdGFsbHlfbGl0KHMsIHMud2luZG93W3Muc3Ryc3RhcnQtMV0sIGJmbHVzaCk7ICoqKi8KICAgICAgYmZsdXNoID0gX3RyX3RhbGx5KHMsIDAsIHMud2luZG93W3Muc3Ryc3RhcnQgLSAxXSk7CgogICAgICBzLm1hdGNoX2F2YWlsYWJsZSA9IDA7CiAgICB9CiAgICBzLmluc2VydCA9IHMuc3Ryc3RhcnQgPCBNSU5fTUFUQ0ggLSAxID8gcy5zdHJzdGFydCA6IE1JTl9NQVRDSCAtIDE7CiAgICBpZiAoZmx1c2ggPT09IFpfRklOSVNIJDMpIHsKICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAxKTsgKioqLwogICAgICBmbHVzaF9ibG9ja19vbmx5KHMsIHRydWUpOwogICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgIHJldHVybiBCU19GSU5JU0hfU1RBUlRFRDsKICAgICAgfQogICAgICAvKioqLwogICAgICByZXR1cm4gQlNfRklOSVNIX0RPTkU7CiAgICB9CiAgICBpZiAocy5sYXN0X2xpdCkgewogICAgICAvKioqIEZMVVNIX0JMT0NLKHMsIDApOyAqKiovCiAgICAgIGZsdXNoX2Jsb2NrX29ubHkocywgZmFsc2UpOwogICAgICBpZiAocy5zdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgIHJldHVybiBCU19ORUVEX01PUkU7CiAgICAgIH0KICAgICAgLyoqKi8KICAgIH0KCiAgICByZXR1cm4gQlNfQkxPQ0tfRE9ORTsKICB9OwoKCiAgLyogPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09CiAgICogRm9yIFpfUkxFLCBzaW1wbHkgbG9vayBmb3IgcnVucyBvZiBieXRlcywgZ2VuZXJhdGUgbWF0Y2hlcyBvbmx5IG9mIGRpc3RhbmNlCiAgICogb25lLiAgRG8gbm90IG1haW50YWluIGEgaGFzaCB0YWJsZS4gIChJdCB3aWxsIGJlIHJlZ2VuZXJhdGVkIGlmIHRoaXMgcnVuIG9mCiAgICogZGVmbGF0ZSBzd2l0Y2hlcyBhd2F5IGZyb20gWl9STEUuKQogICAqLwogIGNvbnN0IGRlZmxh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YWQgPj0gTUlOX01BVENIICYmIHMuc3Ryc3RhcnQgPiAwKSB7CiAgICAgICAgc2NhbiA9IHMuc3Ryc3RhcnQgLSAxOwogICAgICAgIHByZXYgPSBfd2luW3NjYW5dOwogICAgICAgIGlmIChwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmIHByZXYgPT09IF93aW5bKytzY2FuXSkgewogICAgICAgICAgc3RyZW5kID0gcy5zdHJzdGFydCArIE1BWF9NQVRDSDsKICAgICAgICAgIGRvIHsKICAgICAgICAgICAgLypqc2hpbnQgbm9lbXB0eTpmYWxzZSovCiAgICAgICAgICB9IHdoaWxlIChwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmCiAgICAgICAgICAgICAgICAgICBwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmCiAgICAgICAgICAgICAgICAgICBwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmCiAgICAgICAgICAgICAgICAgICBwcmV2ID09PSBfd2luWysrc2Nhbl0gJiYgcHJldiA9PT0gX3dpblsrK3NjYW5dICYmCiAgICAgICAgICAgICAgICAgICBzY2FuIDwgc3RyZW5kKTsKICAgICAgICAgIHMubWF0Y2hfbGVuZ3RoID0gTUFYX01BVENIIC0gKHN0cmVuZCAtIHNjYW4pOwogICAgICAgICAgaWYgKHMubWF0Y2hfbGVuZ3RoID4gcy5sb29rYWhlYWQpIHsKICAgICAgICAgICAgcy5tYXRjaF9sZW5ndGggPSBzLmxvb2thaGVhZDsKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgICAgLy9Bc3NlcnQoc2NhbiA8PSBzLT53aW5kb3crKHVJbnQpKHMtPndpbmRvd19zaXplLTEpLCAid2lsZCBzY2FuIik7CiAgICAgIH0KCiAgICAgIC8qIEVtaXQgbWF0Y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WlsX291dCA9PT0gMCkgewogICAgICAgICAgcmV0dXJuIEJTX05FRURfTU9SRTsKICAgICAgICB9CiAgICAgICAgLyoqKi8KICAgICAgfQogICAgfQogICAgcy5pbnNlcnQgPSAwOwogICAgaWYgKGZsdXNoID09PSBaX0ZJTklTSCQzKSB7CiAgICAgIC8qKiogRkxVU0hfQkxPQ0socywgMSk7ICoqKi8KICAgICAgZmx1c2hfYmxvY2tfb25seShzLCB0cnVlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfRklOSVNIX1NUQVJURUQ7CiAgICAgIH0KICAgICAgLyoqKi8KICAgICAgcmV0dXJuIEJTX0ZJTklTSF9ET05FOwogICAgfQogICAgaWYgKHMubGFzdF9saXQpIHsKICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAwKTsgKioqLwogICAgICBmbHVzaF9ibG9ja19vbmx5KHMsIGZhbHNlKTsKICAgICAgaWYgKHMuc3RybS5hdmFpbF9vdXQgPT09IDApIHsKICAgICAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogICAgICB9CiAgICAgIC8qKiovCiAgICB9CiAgICByZXR1cm4gQlNfQkxPQ0tfRE9ORTsKICB9OwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0KICAgKiBGb3IgWl9IVUZGTUFOX09OTFksIGRvIG5vdCBsb29rIGZvciBtYXRjaGVzLiAgRG8gbm90IG1haW50YWluIGEgaGFzaCB0YWJsZS4KICAgKiAoSXQgd2lsbCBiZSByZWdlbmVyYXRlZCBpZiB0aGlzIHJ1biBvZiBkZWZsYXRlIHN3aXRjaGVzIGF3YXkgZnJvbSBIdWZmbWFuLikKICAgKi8KICBjb25zdCBkZWZsYXRlX2h1ZmYgPSAocywgZmx1c2gpID0+IHsKCiAgICBsZXQgYmZsdXNoOyAgICAgICAgICAgICAvKiBzZXQgaWYgY3VycmVudCBibG9jayBtdXN0IGJlIGZsdXNoZWQgKi8KCiAgICBmb3IgKDs7KSB7CiAgICAgIC8qIE1ha2Ugc3VyZSB0aGF0IHdlIGhhdmUgYSBsaXRlcmFsIHRvIHdyaXRlLiAqLwogICAgICBpZiAocy5sb29rYWhlYWQgPT09IDApIHsKICAgICAgICBmaWxsX3dpbmRvdyhzKTsKICAgICAgICBpZiAocy5sb29rYWhlYWQgPT09IDApIHsKICAgICAgICAgIGlmIChmbHVzaCA9PT0gWl9OT19GTFVTSCQyKSB7CiAgICAgICAgICAgIHJldHVybiBCU19ORUVEX01PUkU7CiAgICAgICAgICB9CiAgICAgICAgICBicmVhazsgICAgICAvKiBmbHVzaCB0aGUgY3VycmVudCBibG9jayAqLwogICAgICAgIH0KICAgICAgfQoKICAgICAgLyogT3V0cHV0IGEgbGl0ZXJhbCBieXRlICovCiAgICAgIHMubWF0Y2hfbGVuZ3RoID0gMDsKICAgICAgLy9UcmFjZXZ2KChzdGRlcnIsIiVjIiwgcy0+d2luZG93W3MtPnN0cnN0YXJ0XSkpOwogICAgICAvKioqIF90cl90YWxseV9saXQocywgcy53aW5kb3dbcy5zdHJzdGFydF0sIGJmbHVzaCk7ICoqKi8KICAgICAgYmZsdXNoID0gX3RyX3RhbGx5KHMsIDAsIHMud2luZG93W3Muc3Ryc3RhcnRdKTsKICAgICAgcy5sb29rYWhlYWQtLTsKICAgICAgcy5zdHJzdGFydCsrOwogICAgICBpZiAoYmZsdXNoKSB7CiAgICAgICAgLyoqKiBGTFVTSF9CTE9DSyhzLCAwKTsgKioqLwogICAgICAgIGZsdXNoX2Jsb2NrX29ubHkocywgZmFsc2UpOwogICAgICAgIGlmIChzLnN0cm0uYXZhaWxfb3V0ID09PSAwKSB7CiAgICAgICAgICByZXR1cm4gQlNfTkVFRF9NT1JFOwogICAgICAgIH0KICAgICAgICAvKioqLwogICAgICB9CiAgICB9CiAgICBzLmluc2VydCA9IDA7CiAgICBpZiAoZmx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KTsKICAgICAgICAgIHB1dF9ieXRlKHMsIDApOwogICAgICAgICAgcHV0X2J5dGUocywgMCk7CiAgICAgICAgICBwdXRfYnl0ZShzLCAwKTsKICAgICAgICAgIHB1dF9ieXRlKHMsIDApOwogICAgICAgICAgcHV0X2J5dGUocywgcy5sZXZlbCA9PT0gOSA/IDIgOgogICAgICAgICAgICAgICAgICAgICAgKHMuc3RyYXRlZ3kgPj0gWl9IVUZGTUFOX09OTFkgfHwgcy5sZXZlbCA8IDIgPwogICAgICAgICAgICAgICAgICAgICAgIDQgOiAwKSk7CiAgICAgICAgICBwdXRfYnl0ZShzLCBPU19DT0RFKTsKICAgICAgICAgIHMuc3RhdHVzID0gQlVTWV9TVEFURTsKICAgICAgICB9CiAgICAgICAgZWxzZSB7CiAgICAgICAgICBwdXRfYnl0ZShzLCAocy5nemhlYWQudGV4dCA/IDEgOiAwKSArCiAgICAgICAgICAgICAgICAgICAgICAocy5nemhlYWQuaGNyYyA/IDIgOiAwKSArCiAgICAgICAgICAgICAgICAgICAgICAoIXMuZ3poZWFkLmV4dHJhID8gMCA6IDQpICsKICAgICAgICAgICAgICAgICAgICAgICghcy5nemhlYWQubmFtZSA/IDAgOiA4KSArCiAgICAgICAgICAgICAgICAgICAgICAoIXMuZ3poZWFkLmNvbW1lbnQgPyAwIDogMTYpCiAgICAgICAgICApOwogICAgICAgICAgcHV0X2J5dGUocywgcy5nemhlYWQudGltZSAmIDB4ZmYpOwogICAgICAgICAgcHV0X2J5dGUocywgKHMuZ3poZWFkLnRpbWUgPj4gOCkgJiAweGZmKTsKICAgICAgICAgIHB1dF9ieXRlKHMsIChzLmd6aGVhZC50aW1lID4+IDE2KSAmIDB4ZmYpOwogICAgICAgICAgcHV0X2J5dGUocywgKHMuZ3poZWFkLnRpbWUgPj4gMjQpICYgMHhmZik7CiAgICAgICAgICBwdXRfYnl0ZShzLCBzLmxldmVsID09PSA5ID8gMiA6CiAgICAgICAgICAgICAgICAgICAgICAocy5zdHJhdGVneSA+PSBaX0hVRkZNQU5fT05MWSB8fCBzLmxldmVsIDwgMiA/CiAgICAgICAgICAgICAgICAgICAgICAgNCA6IDApKTsKICAgICAgICAgIHB1dF9ieXRlKHMsIHMuZ3poZWFkLm9zICYgMHhmZik7CiAgICAgICAgICBpZiAocy5nemhlYWQuZXh0cmEgJiYgcy5nemhlYWQuZXh0cmEubGVuZ3RoKSB7CiAgICAgICAgICAgIHB1dF9ieXRlKHMsIHMuZ3poZWFkLmV4dHJhLmxlbmd0aCAmIDB4ZmYpOwogICAgICAgICAgICBwdXRfYnl0ZShzLCAocy5nemhlYWQuZXh0cmEubGVuZ3RoID4+IDgpICYgMHhmZik7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAocy5nemhlYWQuaGNyYykgewogICAgICAgICAgICBzdHJtLmFkbGVyID0gY3JjMzJfMShzdHJtLmFkbGVyLCBzLnBlbmRpbmdfYnVmLCBzLnBlbmRpbmcsIDApOwogICAgICAgICAgfQogICAgICAgICAgcy5nemluZGV4ID0gMDsKICAgICAgICAgIHMuc3RhdHVzID0gRVhUUkFfU1RBVEU7CiAgICAgICAgfQogICAgICB9CiAgICAgIGVsc2UgLy8gREVGTEFURSBoZWFkZXIKICAgICAgewogICAgICAgIGxldCBoZWFkZXIgPSAoWl9ERUZMQVRFRCQyICsgKChzLndfYml0cyAtIDgpIDw8IDQpKSA8PCA4OwogICAgICAgIGxldCBsZXZlbF9mbGFncyA9IC0xOwoKICAgICAgICBpZiAocy5zdHJhdGVneSA+PSBaX0hVRkZNQU5fT05MWSB8fCBzLmxldmVsIDwgMikgewogICAgICAgICAgbGV2ZWxfZmxhZ3MgPSAwOwogICAgICAgIH0gZWxzZSBpZiAocy5sZXZlbCA8IDYpIHsKICAgICAgICAgIGxldmVsX2ZsYWdzID0gMTsKICAgICAgICB9IGVsc2UgaWYgKHMubGV2ZWwgPT09IDYpIHsKICAgICAgICAgIGxldmVsX2ZsYWdzID0gMjsKICAgICAgICB9IGVsc2UgewogICAgICAgIC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YWRsZXIsIHMucGVuZGluZ19idWYsIHMucGVuZGluZyAtIGJlZywgYmVnKTsKICAgICAgICAgICAgfQogICAgICAgICAgICBmbHVzaF9wZW5kaW5nKHN0cm0pOwogICAgICAgICAgICBiZWcgPSBzLnBlbmRpbmc7CiAgICAgICAgICAgIGlmIChzLnBlbmRpbmcgPT09IHMucGVuZGluZ19idWZfc2l6ZSkgewogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICBwdXRfYnl0ZShzLCBzLmd6aGVhZC5leHRyYVtzLmd6aW5kZXhdICYgMHhmZik7CiAgICAgICAgICBzLmd6aW5kZXgrKzsKICAgICAgICB9CiAgICAgICAgaWYgKHMuZ3poZWFkLmhjcmMgJiYgcy5wZW5kaW5nID4gYmVnKSB7CiAgICAgICAgICBzdHJtLmFkbGVyID0gY3JjMzJfMShzdHJtLmFkbGVyLCBzLnBlbmRpbmdfYnVmLCBzLnBlbmRpbmcgLSBiZWcsIGJlZyk7CiAgICAgICAgfQogICAgICAgIGlmIChzLmd6aW5kZXggPT09IHMuZ3poZWFkLmV4dHJhLmxlbmd0aCkgewogICAgICAgICAgcy5nemluZGV4ID0gMDsKICAgICAgICAgIHMuc3RhdHVzID0gTkFNRV9TVEFURTsKICAgICAgICB9CiAgICAgIH0KICAgICAgZWxzZSB7CiAgICAgICAgcy5zdGF0dXMgPSBOQU1FX1NUQVRFOwogICAgICB9CiAgICB9CiAgICBpZiAocy5zdGF0dXMgPT09IE5BTUVfU1RBVEUpIHsKICAgICAgaWYgKHMuZ3poZWFkLm5hbWUvKiAhPSBaX05VTEwqLykgewogICAgICAgIGJlZyA9IHMucGVuZGluZzsgIC8qIHN0YXJ0IG9mIGJ5dGVzIHRvIHVwZGF0ZSBjcmMgKi8KICAgICAgICAvL2ludCB2YWw7CgogICAgICAgIGRvIHsKICAgICAgICAgIGlmIChzLnBlbmRpbmcgPT09IHMucGVuZGluZ19idWZfc2l6ZSkgewogICAgICAgICAgICBpZiAocy5nemhlYWQuaGNyYyAmJiBzLnBlbmRpbmcgPiBiZWcpIHsKICAgICAgICAgICAgICBzdHJtLmFkbGVyID0gY3JjMzJfMShzdHJtLmFkbGVyLCBzLnBlbmRpbmdfYnVmLCBzLnBlbmRpbmcgLSBiZWcsIGJlZyk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZmx1c2hfcGVuZGluZyhzdHJtKTsKICAgICAgICAgICAgYmVnID0gcy5wZW5kaW5nOwogICAgICAgICAgICBpZiAocy5wZW5kaW5nID09PSBzLnBlbmRpbmdfYnVmX3NpemUpIHsKICAgICAgICAgICAgICB2YWwgPSAxOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICAvLyBKUyBzcGVjaWZpYzogbGl0dGxlIG1hZ2ljIHRvIGFkZCB6ZXJvIHRlcm1pbmF0b3IgdG8gZW5kIG9mIHN0cmluZwogICAgICAgICAgaWYgKHMuZ3ppbmRleCA8IHMuZ3poZWFkLm5hbWUubGVuZ3RoKSB7CiAgICAgICAgICAgIHZhbCA9IHMuZ3poZWFkLm5hbWUuY2hhckNvZGVBdChzLmd6aW5kZXgrKykgJiAweGZmOwogICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgdmFsID0gMDsKICAgICAgICAgIH0KICAgICAgICAgIHB1dF9ieXRlKHMsIHZhbCk7CiAgICAgICAgfSB3aGlsZSAodmFsICE9PSAwKTsKCiAgICAgICAgaWYgKHMuZ3poZWFkLmhjcmMgJiYgcy5wZW5kaW5nID4gYmVnKSB7CiAgICAgICAgICBzdHJtLmFkbGVyID0gY3JjMzJfMShzdHJtLmFkbGVyLCBzLnBlbmRpbmdfYnVmLCBzLnBlbmRpbmcgLSBiZWcsIGJlZyk7CiAgICAgICAgfQogICAgICAgIGlmICh2YWwgPT09IDApIHsKICAgICAgICAgIHMuZ3ppbmRleCA9IDA7CiAgICAgICAgICBzLnN0YXR1cyA9IENPTU1FTlRfU1RBVEU7CiAgICAgICAgfQogICAgICB9CiAgICAgIGVsc2UgewogICAgICAgIHMuc3RhdHVzID0gQ09NTUVOVF9TVEFURTsKICAgICAgfQogICAgfQogICAgaWYgKHMuc3RhdHVzID09PSBDT01NRU5UX1NUQVRFKSB7CiAgICAgIGlmIChzLmd6aGVhZC5jb21tZW50LyogIT0gWl9OVUxMKi8pIHsKICAgICAgICBiZWcgPSBzLnBlbmRpbmc7ICAvKiBzdGFydCBvZiBieXRlcyB0byB1cGRhdGUgY3JjICovCiAgICAgICAgLy9pbnQgdmFsOwoKICAgICAgICBkbyB7CiAgICAgICAgICBpZiAocy5wZW5kaW5nID09PSBzLnBlbmRpbmdfYnVmX3NpemUpIHsKICAgICAgICAgICAgaWYgKHMuZ3poZWFkLmhjcmMgJiYgcy5wZW5kaW5nID4gYmVnKSB7CiAgICAgICAgICAgICAgc3RybS5hZGxlciA9IGNyYzMyXzEoc3RybS5hZGxlciwgcy5wZW5kaW5nX2J1Ziwgcy5wZW5kaW5nIC0gYmVnLCBiZWcpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGZsdXNoX3BlbmRpbmcoc3RybSk7CiAgICAgICAgICAgIGJlZyA9IHMucGVuZGluZzsKICAgICAgICAgICAgaWYgKHMucGVuZGluZyA9PT0gcy5wZW5kaW5nX2J1Zl9zaXplKSB7CiAgICAgICAgICAgICAgdmFsID0gMTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgICAgLy8gSlMgc3BlY2lmaWM6IGxpdHRsZSBtYWdpYyB0byBhZGQgemVybyB0ZXJtaW5hdG9yIHRvIGVuZCBvZiBzdHJpbmcKICAgICAgICAgIGlmIChzLmd6aW5kZXggPCBzLmd6aGVhZC5jb21tZW50Lmxlbmd0aCkgewogICAgICAgICAgICB2YWwgPSBzLmd6aGVhZC5jb21tZW50LmNoYXJDb2RlQXQocy5nemluZGV4KyspICYgMHhmZjsKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIHZhbCA9IDA7CiAgICAgICAgICB9CiAgICAgICAgICBwdXRfYnl0ZShzLCB2YWwpOwogICAgICAgIH0gd2hpbGUgKHZhbCAhPT0gMCk7CgogICAgICAgIGlmIChzLmd6aGVhZC5oY3JjICYmIHMucGVuZGluZyA+IGJlZykgewogICAgICAgICAgc3RybS5hZGxlciA9IGNyYzMyXzEoc3RybS5hZGxlciwgcy5wZW5kaW5nX2J1Ziwgcy5wZW5kaW5nIC0gYmVnLCBiZWcpOwogICAgICAgIH0KICAgICAgICBpZiAodmFsID09PSAwKSB7CiAgICAgICAgICBzLnN0YXR1cyA9IEhDUkNfU1RBVEU7CiAgICAgICAgfQogICAgICB9CiAgICAgIGVsc2UgewogICAgICAgIHMuc3RhdHVzID0gSENSQ19TVEFURTsKICAgICAgfQogICAgfQogICAgaWYgKHMuc3RhdHVzID09PSBIQ1JDX1NUQVRFKSB7CiAgICAgIGlmIChzLmd6aGVhZC5oY3JjKSB7CiAgICAgICAgaWYgKHMucGVuZGluZyArIDIgPiBzLnBlbmRpbmdfYnVmX3NpemUpIHsKICAgICAgICAgIGZsdXNoX3BlbmRpbmcoc3RybSk7CiAgICAgICAgfQogICAgICAgIGlmIChzLnBlbmRpbmcgKyAyIDw9IHMucGVuZGluZ19idWZfc2l6ZSkgewogICAgICAgICAgcHV0X2J5dGUocywgc3RybS5hZGxlciAmIDB4ZmYpOwogICAgICAgICAgcHV0X2J5dGUocywgKHN0cm0uYWRsZXIgPj4gOCkgJiAweGZmKTsKICAgICAgICAgIHN0cm0uYWRsZXIgPSAwOyAvL2NyYzMyKDBMLCBaX05VTEwsIDApOwogICAgICAgICAgcy5zdGF0dXMgPSBCVVNZX1NUQVRFOwogICAgICAgIH0KICAgICAgfQogICAgICBlbHNlIHsKICAgICAgICBzLnN0YXR1cyA9IEJVU1lfU1RBVEU7CiAgICAgIH0KICAgIH0KICAvLyNlbmRpZgoKICAgIC8qIEZsdXNoIGFzIG11Y2ggc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gICAgICAgICAgKi8KICAgICAgICAgIGlmIChmbHVzaCA9PT0gWl9GVUxMX0ZMVVNIJDEpIHsKICAgICAgICAgICAgLyoqKiBDTEVBUl9IQVNIKHMpOyAqKiovICAgICAgICAgICAgIC8qIGZvcmdldCBoaXN0b3J5ICovCiAgICAgICAgICAgIHplcm8ocy5oZWFkKTsgLy8gRmlsbCB3aXRoIE5JTCAoPSAwKTsKCiAgICAgICAgICAgIGlmIChzLmxvb2thaGVhZCA9PT0gMCkgewogICAgICAgICAgICAgIHMuc3Ryc3RhcnQgPSAwOwogICAgICAgICAgICAgIHMuYmxvY2tfc3RhcnQgPSAwOwogICAgICAgICAgICAgIHMuaW5zZXJ0ID0gMDsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBmbHVzaF9wZW5kaW5nKHN0cm0pOwogICAgICAgIGlmIChzdHJtLmF2YWlsX291dCA9PT0gMCkgewogICAgICAgICAgcy5sYXN0X2ZsdXNoID0gLTE7IC8qIGF2b2lkIEJVRl9FUlJPUiBhdCBuZXh0IGNhbGwsIHNlZSBhYm92ZSAqLwogICAgICAgICAgcmV0dXJuIFpfT0skMzsKICAgICAgICB9CiAgICAgIH0KICAgIH0KICAgIC8vQXNzZXJ0KHN0cm0tPmF2YWlsX291dCA+IDAsICJidWcyIik7CiAgICAvL2lmIChzdHJtLmF2YWlsX291dCA8PSAwKSB7IHRocm93IG5ldyBFcnJvcigiYnVnMiIpO30KCiAgICBpZiAoZmx1c2ggIT09IFpfRklOSVNIJDMpIHsgcmV0dXJuIFpfT0skMzsgfQogICAgaWYgKHMud3JhcCA8PSAwKSB7IHJldHVybiBaX1NUUkVBTV9FTkQkMzsgfQoKICAgIC8qIFdyaXRlIHRoZSB0cmFpbGVyICovCiAgICBpZiAocy53cmFwID09PSAyKSB7CiAgICAgIHB1dF9ieXRlKHMsIHN0cm0uYWRsZXIgJiAweGZmKTsKICAgICAgcHV0X2J5dGUocywgKHN0cm0uYWRsZXIgPj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G1fcG9zID0gMDsgaSA8IGJ1Zl9sZW47IG1fcG9zKyspIHsKICAgICAgYyA9IHN0ci5jaGFyQ29kZUF0KG1fcG9zKTsKICAgICAgaWYgKChjICYgMHhmYzAwKSA9PT0gMHhkODAwICYmIChtX3BvcyArIDEgPCBzdHJfbGVuKSkgewogICAgICAgIGMyID0gc3RyLmNoYXJDb2RlQXQobV9wb3MgKyAxKTsKICAgICAgICBpZiAoKGMyICYgMHhmYzAwKSA9PT0gMHhkYzAwKSB7CiAgICAgICAgICBjID0gMHgxMDAwMCArICgoYyAtIDB4ZDgwMCkgPDwgMTApICsgKGMyIC0gMHhkYzAwKTsKICAgICAgICAgIG1fcG9zKys7CiAgICAgICAgfQogICAgICB9CiAgICAgIGlmIChjIDwgMHg4MCkgewogICAgICAgIC8qIG9uZSBieXRlICovCiAgICAgICAgYnVmW2krK10gPSBjOwogICAgICB9IGVsc2UgaWYgKGMgPCAweDgwMCkgewogICAgICAgIC8qIHR3byBieXRlcyAqLwogICAgICAgIGJ1ZltpKytdID0gMHhDMCB8IChjID4+PiA2KTsKICAgICAgICBidWZbaSsrXSA9IDB4ODAgfCAoYyAmIDB4M2YpOwogICAgICB9IGVsc2UgaWYgKGMgPCAweDEwMDAwKSB7CiAgICAgICAgLyogdGhyZWUgYnl0ZXMgKi8KICAgICAgICBidWZbaSsrXSA9IDB4RTAgfCAoYyA+Pj4gMTIpOwogICAgICAgIGJ1ZltpKytdID0gMHg4MCB8IChjID4+PiA2ICYgMHgzZik7CiAgICAgICAgYnVmW2krK10gPSAweDgwIHwgKGMgJiAweDNmKTsKICAgICAgfSBlbHNlIHsKICAgICAgICAvKiBmb3VyIGJ5dGVzICovCiAgICAgICAgYnVmW2krK10gPSAweGYwIHwgKGMgPj4+IDE4KTsKICAgICAgICBidWZbaSsrXSA9IDB4ODAgfCAoYyA+Pj4gMTIgJiAweDNmKTsKICAgICAgICBidWZbaSsrXSA9IDB4ODAgfCAoYyA+Pj4gNiAmIDB4M2YpOwog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PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSovCgogIGNvbnN0IHsKICAgIFpfTk9fRkxVU0g6IFpfTk9fRkxVU0gkMSwgWl9TWU5DX0ZMVVNILCBaX0ZVTExfRkxVU0gsIFpfRklOSVNIOiBaX0ZJTklTSCQyLAogICAgWl9PSzogWl9PSyQyLCBaX1NUUkVBTV9FTkQ6IFpfU1RSRUFNX0VORCQyLAogICAgWl9ERUZBVUxUX0NPTVBSRVNTSU9OLAogICAgWl9ERUZBVUxUX1NUUkFURUdZLAogICAgWl9ERUZMQVRFRDogWl9ERUZMQVRFRCQxCiAgfSA9IGNvbnN0YW50cyQyOwoKICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwoKCiAgLyoqCiAgICogY2xhc3MgRGVmbGF0ZQogICAqCiAgICogR2VuZXJpYyBKUy1zdHlsZSB3cmFwcGVyIGZvciB6bGliIGNhbGxzLiBJZiB5b3UgZG9uJ3QgbmVlZAogICAqIHN0cmVhbWluZyBiZWhhdmlvdXIgLSB1c2UgbW9yZSBzaW1wbGUgZnVuY3Rpb25zOiBbW2RlZmxhdGVdXSwKICAgKiBbW2RlZmxhdGVSYXddXSBhbmQgW1tnemlwXV0uCiAgICoqLwoKICAvKiBpbnRlcm5hbAogICAqIERlZmxhdGUuY2h1bmtzIC0+IEFycmF5CiAgICoKICAgKiBDaHVua3Mgb2Ygb3V0cHV0IGRhdGEsIGlmIFtbRGVmbGF0ZSNvbkRhdGFdXSBub3Qgb3ZlcnJpZGRlbi4KICAgKiovCgogIC8qKgogICAqIERlZmxhdGUucmVzdWx0IC0+IFVpbnQ4QXJyYXkKICAgKgogICAqIENvbXByZXNzZWQgcmVzdWx0LCBnZW5lcmF0ZW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ovCiAgLy8jZW5kaWYKICAgIGxldCB3c2l6ZTsgICAgICAgICAgICAgICAgICAvKiB3aW5kb3cgc2l6ZSBvciB6ZXJvIGlmIG5vdCB1c2luZyB3aW5kb3cgKi8KICAgIGxldCB3aGF2ZTsgICAgICAgICAgICAgICAgICAvKiB2YWxpZCBieXRlcyBpbiB0aGUgd2luZG93ICovCiAgICBsZXQgd25leHQ7ICAgICAgICAgICAgICAgICAgLyogd2luZG93IHdyaXRlIGluZGV4ICovCiAgICAvLyBVc2UgYHNfd2luZG93YCBpbnN0ZWFkIGB3aW5kb3dgLCBhdm9pZCBjb25mbGljdCB3aXRoIGluc3RydW1lbnRhdGlvbiB0b29scwogICAgbGV0IHNfd2luZG93OyAgICAgICAgICAgICAgIC8qIGFsbG9jYXRlZCBzbGlkaW5nIHdpbmRvdywgaWYgd3NpemUgIT0gMCAqLwogICAgbGV0IGhvbGQ7ICAgICAgICAgICAgICAgICAgIC8qIGxvY2FsIHN0cm0uaG9sZCAqLwogICAgbGV0IGJpdHM7ICAgICAgICAgICAgICAgICAgIC8qIGxvY2FsIHN0cm0uYml0cyAqLwogICAgbGV0IGxjb2RlOyAgICAgICAgICAgICAgICAgIC8qIGxvY2FsIHN0cm0ubGVuY29kZSAqLwogICAgbGV0IGRjb2RlOyAgICAgICAgICAgICAgICAgIC8qIGxvY2FsIHN0cm0uZGlzdGNvZGUgKi8KICAgIGxldCBsbWFzazsgICAgICAgICAgICAgICAgICAvKiBtYXNrIGZvciBmaXJzdCBsZXZlbCBvZiBsZW5ndGggY29kZXMgKi8KICAgIGxldCBkbWFzazsgICAgICAgICAgICAgICAgICAvKiBtYXNrIGZvciBmaXJzdCBsZXZlbCBvZiBkaXN0YW5jZSBjb2RlcyAqLwogICAgbGV0IGhlcmU7ICAgICAgICAgICAgICAgICAgIC8qIHJldHJpZXZlZCB0YWJsZSBlbnRyeSAqLwogICAgbGV0IG9wOyAgICAgICAgICAgICAgICAgICAgIC8qIGNvZGUgYml0cywgb3Bl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BzdGF0ZS53aW5kb3c7CiAgICBob2xkID0gc3RhdGUuaG9sZDsKICAgIGJpdHMgPSBzdGF0ZS5iaXRzOwogICAgbGNvZGUgPSBzdGF0ZS5sZW5jb2RlOwogICAgZGNvZGUgPSBzdGF0ZS5kaXN0Y29kZTsKICAgIGxtYXNrID0gKDEgPDwgc3RhdGUubGVuYml0cykgLSAxOwogICAgZG1hc2sgPSAoMSA8PCBzdGF0ZS5kaXN0Yml0cykgLSAxOwoKCiAgICAvKiBkZWNvZGUgbGl0ZXJhbHMgYW5kIGxlbmd0aC9kaXN0YW5jZXMgdW50aWwgZW5kLW9mLWJsb2NrIG9yIG5vdCBlbm91Z2gKICAgICAgIGlucHV0IGRhdGEgb3Igb3V0cHV0IHNwYWNlICovCgogICAgdG9wOgogICAgZG8gewogICAgICBpZiAoYml0cyA8IDE1KSB7CiAgICAgICAgaG9sZCArPSBpbnB1dFtfaW4rK10gPDwgYml0czsKICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgaG9sZCArPSBpbnB1dFtfaW4rK10gPDwgYml0czsKICAgICAgICBiaXRzICs9IDg7CiAgICAgIH0KCiAgICAgIGhlcmUgPSBsY29kZVtob2xkICYgbG1hc2tdOwoKICAgICAgZG9sZW46CiAgICAgIGZvciAoOzspIHsgLy8gR290byBlbXVsYXRpb24KICAgICAgICBvcCA9IGhlcmUgPj4+IDI0LypoZXJlLmJpdHMqLzsKICAgICAgICBob2xkID4+Pj0gb3A7CiAgICAgICAgYml0cyAtPSBvcDsKICAgICAgICBvcCA9IChoZXJlID4+PiAxNikgJiAweGZmLypoZXJlLm9wKi87CiAgICAgICAgaWYgKG9wID09PSAwKSB7ICAgICAgICAgICAgICAgICAgICAgICAgICAvKiBsaXRlcmFsICovCiAgICAgICAgICAvL1RyYWNldnYoKHN0ZGVyciwgaGVyZS52YWwgPj0gMHgyMCAmJiBoZXJlLnZhbCA8IDB4N2YgPwogICAgICAgICAgLy8gICAgICAgICJpbmZsYXRlOiAgICAgICAgIGxpdGVyYWwgJyVjJ1xuIiA6CiAgICAgICAgICAvLyAgICAgICAgImluZmxhdGU6ICAgICAgICAgbGl0ZXJhbCAweCUwMnhcbiIsIGhlcmUudmFsKSk7CiAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IGhlcmUgJiAweGZmZmYvKmhlcmUudmFsKi87CiAgICAgICAgfQogICAgICAgIGVsc2UgaWYgKG9wICYgMTYpIHsgICAgICAgICAgICAgICAgICAgICAvKiBsZW5ndGggYmFzZSAqLwogICAgICAgICAgbGVuID0gaGVyZSAmIDB4ZmZmZi8qaGVyZS52YWwqLzsKICAgICAgICAgIG9wICY9IDE1OyAgICAgICAgICAgICAgICAgICAgICAgICAgIC8qIG51bWJlciBvZiBleHRyYSBiaXRzICovCiAgICAgICAgICBpZiAob3ApIHsKICAgICAgICAgICAgaWYgKGJpdHMgPCBvcCkgewogICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbX2luKytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICB9CiAgICAgICAgICAgIGxlbiArPSBob2xkICYgKCgxIDw8IG9wKSAtIDEpOwogICAgICAgICAgICBob2xkID4+Pj0gb3A7CiAgICAgICAgICAgIGJpdHMgLT0gb3A7CiAgICAgICAgICB9CiAgICAgICAgICAvL1RyYWNldnYoKHN0ZGVyciwgImluZmxhdGU6ICAgICAgICAgbGVuZ3RoICV1XG4iLCBsZW4pKTsKICAgICAgICAgIGlmIChiaXRzIDwgMTUpIHsKICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtfaW4rK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICBob2xkICs9IGlucHV0W19pbisrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICB9CiAgICAgICAgICBoZXJlID0gZGNvZGVbaG9sZCAmIGRtYXNrXTsKCiAgICAgICAgICBkb2Rpc3Q6CiAgICAgICAgICBmb3IgKDs7KSB7IC8vIGdvdG8gZW11bGF0aW9uCiAgICAgICAgICAgIG9wID0gaGVyZSA+Pj4gMjQvKmhlcmUuYml0cyovOwogICAgICAgICAgICBob2xkID4+Pj0gb3A7CiAgICAgICAgICAgIGJpdHMgLT0gb3A7CiAgICAgICAgICAgIG9wID0gKGhlcmUgPj4+IDE2KSAmIDB4ZmYvKmhlcmUub3AqLzsKCiAgICAgICAgICAgIGlmIChvcCAmIDE2KSB7ICAgICAgICAgICAgICAgICAgICAgIC8qIGRpc3RhbmNlIGJhc2UgKi8KICAgICAgICAgICAgICBkaXN0ID0gaGVyZSAmIDB4ZmZmZi8qaGVyZS52YWwqLzsKICAgICAgICAgICAgICBvcCAmPSAxNTsgICAgICAgICAgICAgICAgICAgICAgIC8qIG51bWJlciBvZiBleHRyYSBiaXRzICovCiAgICAgICAgICAgICAgaWYgKGJpdHMgPCBvcCkgewogICAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtfaW4rK10gPDwgYml0czsKICAgICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgICAgIGlmIChiaXRzIDwgb3ApIHsKICAgICAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtfaW4rK10gPDwgYml0czsKICAgICAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBkaXN0ICs9IGhvbGQgJiAoKDEgPDwgb3ApIC0gMSk7CiAgLy8jaWZkZWYgSU5GTEFURV9TVFJJQ1QKICAgICAgICAgICAgICBpZiAoZGlzdCA+IGRtYXgpIHsKICAgICAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgZGlzdGFuY2UgdG9vIGZhciBiYWNrJzsKICAgICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQkMTsKICAgICAgICAgICAgICAgIGJyZWFrIHRvcDsKICAgICAgICAgICAgICB9CiAgLy8jZW5kaWYKICAgICAgICAgICAgICBob2xkID4+Pj0gb3A7CiAgICAgICAgICAgICAgYml0cyAtPSBvcDsKICAgICAgICAgICAgICAvL1RyYWNldnYoKHN0ZGVyciwgImluZmxhdGU6ICAgICAgICAgZGlzdGFuY2UgJXVcbiIsIGRpc3QpKTsKICAgICAgICAgICAgICBvcCA9IF9vdXQgLSBiZWc7ICAgICAgICAgICAgICAgIC8qIG1heCBkaXN0YW5jZSBpbiBvdXRwdXQgKi8KICAgICAgICAgICAgICBpZiAoZGlzdCA+IG9wKSB7ICAgICAgICAgICAgICAgIC8qIHNlZSBpZiBjb3B5IGZyb20gd2luZG93ICovCiAgICAgICAgICAgICAgICBvcCA9IGRpc3QgLSBvcDsgICAgICAgICAgICAgICAvKiBkaXN0YW5jZSBiYWNrIGluIHdpbmRvdyAqLwogICAgICAgICAgICAgICAgaWYgKG9wID4gd2hhdmUpIHsKICAgICAgICAgICAgICAgICAgaWYgKHN0YXRlLnNhbmUpIHsKICAgICAgICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGRpc3RhbmNlIHRvbyBmYXIgYmFjayc7CiAgICAgICAgICAgICAgICAgICAgc3RhdGUubW9kZSA9IEJBRCQxOwogICAgICAgICAgICAgICAgICAgIGJyZWFrIHRvcDsKICAgICAgICAgICAgICAgICAgfQoKICAvLyAoISkgVGhpcyBibG9jayBpcyBkaXNhYmxlZCBpbiB6bGliIGRlZmF1bHRzLAogIC8vIGRvbid0IGVuYWJsZSBpdCBmb3IgYmluYXJ5IGNvbXBhdGliaWxpdHkKICAvLyNpZmRlZiBJTkZMQVRFX0FMTE9XX0lOVkFMSURfRElTVEFOQ0VfVE9PRkFSX0FSUlIKICAvLyAgICAgICAgICAgICAgICBpZiAobGVuIDw9IG9wIC0gd2hhdmUpIHsKICAvLyAgICAgICAgICAgICAgICAgIGRvIHsKICAvLyAgICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSAwOwogIC8vICAgICAgICAgICAgICAgICAgfSB3aGlsZSAoLS1sZW4pOwogIC8vICAgICAgICAgICAgICAgICAgY29udGludWUgdG9wOwogIC8vICAgICAgICAgICAgICAgIH0KICAvLyAgICAgICAgICAgICAgICBsZW4gLT0gb3AgLSB3aGF2ZTsKICAvLyAgICAgICAgICAgICAgICBkbyB7CiAgLy8gICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IDA7CiAgLy8gICAgICAgICAgICAgICAgfSB3aGlsZSAoLS1vcCA+IHdoYXZlKTsKICAvLyAgICAgICAgICAgICAgICBpZiAob3AgPT09IDApIHsKICAvLyAgICAgICAgICAgICAgICAgIGZyb20gPSBfb3V0IC0gZGlzdDsKICAvLyAgICAgICAgICAgICAgICAgIGRvIHsKICAvLyAgICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAvLyAgICAgICAgICAgICAgICAgIH0gd2hpbGUgKC0tbGVuKTsKICAvLyAgICAgICAgICAgICAgICAgIGNvbnRpbnVlIHRvcDsKICAvLyAgICAgICAgICAgICAgICB9CiAgLy8jZW5kaWYKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGZyb20gPSAwOyAvLyB3aW5kb3cgaW5kZXgKICAgICAgICAgICAgICAgIGZyb21fc291cmNlID0gc193aW5kb3c7CiAgICAgICAgICAgICAgICBpZiAod25leHQgPT09IDApIHsgICAgICAgICAgIC8qIHZlcnkgY29tbW9uIGNhc2UgKi8KICAgICAgICAgICAgICAgICAgZnJvbSArPSB3c2l6ZSAtIG9wOwogICAgICAgICAgICAgICAgICBpZiAob3AgPCBsZW4pIHsgICAgICAgICAvKiBzb21lIGZyb20gd2luZG93ICovCiAgICAgICAgICAgICAgICAgICAgbGVuIC09IG9wOwogICAgICAgICAgICAgICAgICAgIGRvIHsKICAgICAgICAgICAgICAgICAgICAgIG91dHB1dFtfb3V0KytdID0gc193aW5kb3dbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgICB9IHdoaWxlICgtLW9wKTsKICAgICAgICAgICAgICAgICAgICBmcm9tID0gX291dCAtIGRpc3Q7ICAvKiByZXN0IGZyb20gb3V0cHV0ICovCiAgICAgICAgICAgICAgICAgICAgZnJvbV9zb3VyY2UgPSBvdXRwdXQ7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGVsc2UgaWYgKHduZXh0IDwgb3ApIHsgICAgICAvKiB3cmFwIGFyb3VuZCB3aW5kb3cgKi8KICAgICAgICAgICAgICAgICAgZnJvbSArPSB3c2l6ZSArIHduZXh0IC0gb3A7CiAgICAgICAgICAgICAgICAgIG9wIC09IHduZXh0OwogICAgICAgICAgICAgICAgICBpZiAob3AgPCBsZW4pIHsgICAgICAgICAvKiBzb21lIGZyb20gZW5kIG9mIHdpbmRvdyAqLwogICAgICAgICAgICAgICAgICAgIGxlbiAtPSBvcDsKICAgICAgICAgICAgICAgICAgICBkbyB7CiAgICAgICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IHNfd2luZG93W2Zyb20rK107CiAgICAgICAgICAgICAgICAgICAgfSB3aGlsZSAoLS1vcCk7CiAgICAgICAgICAgICAgICAgICAgZnJvbSA9IDA7CiAgICAgICAgICAgICAgICAgICAgaWYgKHduZXh0IDwgbGVuKSB7ICAvKiBzb21lIGZyb20gc3RhcnQgb2Ygd2luZG93ICovCiAgICAgICAgICAgICAgICAgICAgICBvcCA9IHduZXh0OwogICAgICAgICAgICAgICAgICAgICAgbGVuIC09IG9wOwogICAgICAgICAgICAgICAgICAgICAgZG8gewogICAgICAgICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IHNfd2luZG93W2Zyb20rK107CiAgICAgICAgICAgICAgICAgICAgICB9IHdoaWxlICgtLW9wKTsKICAgICAgICAgICAgICAgICAgICAgIGZyb20gPSBfb3V0IC0gZGlzdDsgICAgICAvKiByZXN0IGZyb20gb3V0cHV0ICovCiAgICAgICAgICAgICAgICAgICAgICBmcm9tX3NvdXJjZSA9IG91dHB1dDsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGVsc2UgeyAgICAgICAgICAgICAgICAgICAgICAvKiBjb250aWd1b3VzIGluIHdpbmRvdyAqLwogICAgICAgICAgICAgICAgICBmcm9tICs9IHduZXh0IC0gb3A7CiAgICAgICAgICAgICAgICAgIGlmIChvcCA8IGxlbikgeyAgICAgICAgIC8qIHNvbWUgZnJvbSB3aW5kb3cgKi8KICAgICAgICAgICAgICAgICAgICBsZW4gLT0gb3A7CiAgICAgICAgICAgICAgICAgICAgZG8gewogICAgICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBzX3dpbmRvd1tmcm9tKytdOwogICAgICAgICAgICAgICAgICAgIH0gd2hpbGUgKC0tb3ApOwogICAgICAgICAgICAgICAgICAgIGZyb20gPSBfb3V0IC0gZGlzdDsgIC8qIHJlc3QgZnJvbSBvdXRwdXQgKi8KICAgICAgICAgICAgICAgICAgICBmcm9tX3NvdXJjZSA9IG91dHB1dDsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgd2hpbGUgKGxlbiA+IDIpIHsKICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBmcm9tX3NvdXJjZVtmcm9tKytdOwogICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IGZyb21fc291cmNlW2Zyb20rK107CiAgICAgICAgICAgICAgICAgIG91dHB1dFtfb3V0KytdID0gZnJvbV9zb3VyY2VbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgbGVuIC09IDM7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBpZiAobGVuKSB7CiAgICAgICAgICAgICAgICAgIG91dHB1dFtfb3V0KytdID0gZnJvbV9zb3VyY2VbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgaWYgKGxlbiA+IDEpIHsKICAgICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IGZyb21fc291cmNlW2Zyb20rK107CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICBmcm9tID0gX291dCAtIGRpc3Q7ICAgICAgICAgIC8qIGNvcHkgZGlyZWN0IGZyb20gb3V0cHV0ICovCiAgICAgICAgICAgICAgICBkbyB7ICAgICAgICAgICAgICAgICAgICAgICAgLyogbWluaW11bSBsZW5ndGggaXMgdGhyZWUgKi8KICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgbGVuIC09IDM7CiAgICAgICAgICAgICAgICB9IHdoaWxlIChsZW4gPiAyKTsKICAgICAgICAgICAgICAgIGlmIChsZW4pIHsKICAgICAgICAgICAgICAgICAgb3V0cHV0W19vdXQrK10gPSBvdXRwdXRbZnJvbSsrXTsKICAgICAgICAgICAgICAgICAgaWYgKGxlbiA+IDEpIHsKICAgICAgICAgICAgICAgICAgICBvdXRwdXRbX291dCsrXSA9IG91dHB1dFtmcm9tKytdOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgaWYgKChvcCAmIDY0KSA9PT0gMCkgeyAgICAgICAgICAvKiAybmQgbGV2ZWwgZGlzdGFuY2UgY29kZSAqLwogICAgICAgICAgICAgIGhlcmUgPSBkY29kZVsoaGVyZSAmIDB4ZmZmZikvKmhlcmUudmFsKi8gKyAoaG9sZCAmICgoMSA8PCBvcCkgLSAxKSldOwogICAgICAgICAgICAgIGNvbnRpbnVlIGRvZGlzdDsKICAgICAgICAgICAgfQogICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGRpc3RhbmNlIGNvZGUnOwogICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQkMTsKICAgICAgICAgICAgICBicmVhayB0b3A7CiAgICAgICAgICAgIH0KCiAgICAgICAgICAgIGJyZWFrOyAvLyBuZWVkIHRvIGVtdWxhdGUgZ290byB2aWEgImNvbnRpbnVlIgogICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBlbHNlIGlmICgob3AgJiA2NCkgPT09IDApIHsgICAgICAgICAgICAgIC8qIDJuZCBsZXZlbCBsZW5ndGggY29kZSAqLwogICAgICAgICAgaGVyZSA9IGxjb2RlWyhoZXJlICYgMHhmZmZmKS8qaGVyZS52YWwqLyArIChob2xkICYgKCgxIDw8IG9wKSAtIDEpKV07CiAgICAgICAgICBjb250aW51ZSBkb2xlbjsKICAgICAgICB9CiAgICAgICAgZWxzZSBpZiAob3AgJiAzMikgeyAgICAgICAgICAgICAgICAgICAgIC8qIGVuZC1vZi1ibG9jayAqLwogICAgICAgICAgLy9UcmFjZXZ2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgICAgIGVuZCBvZiBibG9ja1xuIikpOwogICAgICAgICAgc3RhdGUubW9kZSA9IFRZUEUkMTsKICAgICAgICAgIGJyZWFrIHRvcDsKICAgICAgICB9CiAgICAgICAgZWxzZSB7CiAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGxpdGVyYWwvbGVuZ3RoIGNvZGUnOwogICAgICAgICAgc3RhdGUubW9kZSA9IEJBRCQxOwogICAgICAgICAgYnJlYWsgdG9wOwogICAgICAgIH0KCiAgICAgICAgYnJlYWs7IC8vIG5lZWQgdG8gZW11bGF0ZSBnb3RvIHZpYSAiY29udGludWUiCiAgICAgIH0KICAgIH0gd2hpbGUgKF9pbiA8IGxhc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AyMiwgMjIsCiAgICAyMywgMjMsIDI0LCAyNCwgMjUsIDI1LCAyNiwgMjYsIDI3LCAyNywKICAgIDI4LCAyOCwgMjksIDI5LCA2NCwgNjQKICBdKTsKCiAgY29uc3QgaW5mbGF0ZV90YWJsZSA9ICh0eXBlLCBsZW5zLCBsZW5zX2luZGV4LCBjb2RlcywgdGFibGUsIHRhYmxlX2luZGV4LCB3b3JrLCBvcHRzKSA9PgogIHsKICAgIGNvbnN0IGJpdHMgPSBvcHRzLmJpdHM7CiAgICAgICAgLy9oZXJlID0gb3B0cy5oZXJlOyAvKiB0YWJsZSBlbnRyeSBmb3IgZHVwbGljYXRpb24gKi8KCiAgICBsZXQgbGVuID0gMDsgICAgICAgICAgICAgICAvKiBhIGNvZGUncyBsZW5ndGggaW4gYml0cyAqLwogICAgbGV0IHN5bSA9IDA7ICAgICAgICAgICAgICAgLyogaW5kZXggb2YgY29kZSBzeW1ib2xzICovCiAgICBsZXQgbWluID0gMCwgbWF4ID0gMDsgICAgICAgICAgLyogbWluaW11bSBhbmQgbWF4aW11bSBjb2RlIGxlbmd0aHMgKi8KICAgIGxldCByb290ID0gMDsgICAgICAgICAgICAgIC8qIG51bWJlciBvZiBpbmRleCBiaXRzIGZvciByb290IHRhYmxlICovCiAgICBsZXQgY3VyciA9IDA7ICAgICAgICAgICAgICAvKiBudW1iZXIgb2YgaW5kZXggYml0cyBmb3IgY3VycmVudCB0YWJsZSAqLwogICAgbGV0IGRyb3AgPSAwOyAgICAgICAgICAgICAgLyogY29kZSBiaXRzIHRvIGRyb3AgZm9yIHN1Yi10YWJsZSAqLwogICAgbGV0IGxlZnQgPSAwOyAgICAgICAgICAgICAgICAgICAvKiBudW1iZXIgb2YgcHJlZml4IGNvZGVzIGF2YWlsYWJsZSAqLwogICAgbGV0IHVzZWQgPSAwOyAgICAgICAgICAgICAgLyogY29kZSBlbnRyaWVzIGluIHRhYmxlIHVzZWQgKi8KICAgIGxldCBodWZmID0gMDsgICAgICAgICAgICA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SB7ICAgICAgICAgICAgICAgICAgICAvKiBESVNUUyAqLwogICAgICBiYXNlID0gZGJhc2U7CiAgICAgIGV4dHJhID0gZGV4dDsKICAgICAgZW5kID0gLTE7CiAgICB9CgogICAgLyogaW5pdGlhbGl6ZSBvcHRzIGZvciBsb29wICovCiAgICBodWZmID0gMDsgICAgICAgICAgICAgICAgICAgLyogc3RhcnRpbmcgY29kZSAqLwogICAgc3ltID0gMDsgICAgICAgICAgICAgICAgICAgIC8qIHN0YXJ0aW5nIGNvZGUgc3ltYm9sICovCiAgICBsZW4gPSBtaW47ICAgICAgICAgICAgICAgICAgLyogc3RhcnRpbmcgY29kZSBsZW5ndGggKi8KICAgIG5leHQgPSB0YWJsZV9pbmRleDsgICAgICAgICAgICAgIC8qIGN1cnJlbnQgdGFibGUgdG8gZmlsbCBpbiAqLwogICAgY3VyciA9IHJvb3Q7ICAgICAgICAgICAgICAgIC8qIGN1cnJlbnQgdGFibGUgaW5kZXggYml0cyAqLwogICAgZHJvcCA9IDA7ICAgICAgICAgICAgICAgICAgIC8qIGN1cnJlbnQgYml0cyB0byBkcm9wIGZyb20gY29kZSBmb3IgaW5kZXggKi8KICAgIGxvdyA9IC0xOyAgICAgICAgICAgICAgICAgICAvKiB0cmlnZ2VyIG5ldyBzdWItdGFibGUgd2hlbiBsZW4gPiByb290ICovCiAgICB1c2VkID0gMSA8PCByb290OyAgICAgICAgICAvKiB1c2Ugcm9vdCB0YWJsZSBlbnRyaWVzICovCiAgICBtYXNrID0gdXNlZCAtIDE7ICAgICAgICAgICAgLyogbWFzayBmb3IgY29tcGFyaW5nIGxvdyAqLwoKICAgIC8qIGNoZWNrIGF2YWlsYWJsZSB0YWJsZSBzcGFjZSAqLwogICAgaWYgKCh0eXBlID09PSBMRU5TJDEgJiYgdXNlZCA+IEVOT1VHSF9MRU5TJDEpIHx8CiAgICAgICh0eXBlID09PSBESVNUUyQxICYmIHVzZWQgPiBFTk9VR0hfRElTVFMkMSkpIHsKICAgICAgcmV0dXJuIDE7CiAgICB9CgogICAgLyogcHJvY2VzcyBhbGwgY29kZXMgYW5kIG1ha2UgdGFibGUgZW50cmllcyAqLwogICAgZm9yICg7OykgewogICAgICAvKiBjcmVhdGUgdGFibGUgZW50cnkgKi8KICAgICAgaGVyZV9iaXRzID0gbGVuIC0gZHJvcDsKICAgICAgaWYgKHdvcmtbc3ltXSA8IGVuZCkgewogICAgICAgIGhlcmVfb3AgPSAwOwogICAgICAgIGhlcmVfdmFsID0gd29ya1tzeW1dOwogICAgICB9CiAgICAgIGVsc2UgaWYgKHdvcmtbc3ltXSA+IGVuZCkgewogICAgICAgIGhlcmVfb3AgPSBleHRyYVtleHRyYV9pbmRleCArIHdvcmtbc3ltXV07CiAgICAgICAgaGVyZV92YWwgPSBiYXNlW2Jhc2VfaW5kZXggKyB3b3JrW3N5bV1dOwogICAgICB9CiAgICAgIGVsc2UgewogICAgICAgIGhlcmVfb3AgPSAzMiArIDY0OyAgICAgICAgIC8qIGVuZCBvZiBibG9jayAqLwogICAgICAgIGhlcmVfdmFsID0gMDsKICAgICAgfQoKICAgICAgLyogcmVwbGljYXRlIGZvciB0aG9zZSBpbmRpY2VzIHdpdGggbG93IGxlbiBiaXRzIGVxdWFsIHRvIGh1ZmYgKi8KICAgICAgaW5jciA9IDEgPDwgKGxlbiAtIGRyb3ApOwogICAgICBmaWxsID0gMSA8PCBjdXJyOwogICAgICBtaW4gPSBmaWxsOyAgICAgICAgICAgICAgICAgLyogc2F2ZSBvZmZzZXQgdG8gbmV4dCB0YWJsZSAqLwogICAgICBkbyB7CiAgICAgICAgZmlsbCAtPSBpbmNyOwogICAgICAgIHRhYmxlW25leHQgKyAoaHVmZiA+PiBkcm9wKSArIGZpbGxdID0gKGhlcmVfYml0cyA8PCAyNCkgfCAoaGVyZV9vcCA8PCAxNikgfCBoZXJlX3ZhbCB8MDsKICAgICAgfSB3aGlsZSAoZmlsbCAhPT0gMCk7CgogICAgICAvKiBiYWNrd2FyZHMgaW5jcmVtZW50IHRoZSBsZW4tYml0IGNvZGUgaHVmZiAqLwogICAgICBpbmNyID0gMSA8PCAobGVuIC0gMSk7CiAgICAgIHdoaWxlIChodWZmICYgaW5jcikgewogICAgICAgIGluY3IgPj49IDE7CiAgICAgIH0KICAgICAgaWYgKGluY3IgIT09IDApIHsKICAgICAgICBodWZmICY9IGluY3IgLSAxOwogICAgICAgIGh1ZmYgKz0gaW5jcjsKICAgICAgfSBlbHNlIHsKICAgICAgICBodWZmID0gMDsKICAgICAgfQoKICAgICAgLyogZ28gdG8gbmV4dCBzeW1ib2wsIHVwZGF0ZSBjb3VudCwgbGVuICovCiAgICAgIHN5bSsrOwogICAgICBpZiAoLS1jb3VudFtsZW5dID09PSAwKSB7CiAgICAgICAgaWYgKGxlbiA9PT0gbWF4KSB7IGJyZWFrOyB9CiAgICAgICAgbGVuID0gbGVuc1tsZW5zX2luZGV4ICsgd29ya1tzeW1dXTsKICAgICAgfQoKICAgICAgLyogY3JlYXRlIG5ldyBzdWItdGFibGUgaWYgbmVlZGVkICovCiAgICAgIGlmIChsZW4gPiByb290ICYmIChodWZmICYgbWFzaykgIT09IGxvdykgewogICAgICAgIC8qIGlmIGZpcnN0IHRpbWUsIHRyYW5zaXRpb24gdG8gc3ViLXRhYmxlcyAqLwogICAgICAgIGlmIChkcm9wID09PSAwKSB7CiAgICAgICAgICBkcm9wID0gcm9vdDsKICAgICAgICB9CgogICAgICAgIC8qIGluY3JlbWVudCBwYXN0IGxhc3QgdGFibGUgKi8KICAgICAgICBuZXh0ICs9IG1pbjsgICAgICAgICAgICAvKiBoZXJlIG1pbiBpcyAxIDw8IGN1cnIgKi8KCiAgICAgICAgLyogZGV0ZXJtaW5lIGxlbmd0aCBvZiBuZXh0IHRhYmxlICovCiAgICAgICAgY3VyciA9IGxlbiAtIGRyb3A7CiAgICAgICAgbGVmdCA9IDEgPDwgY3VycjsKICAgICAgICB3aGlsZSAoY3VyciArIGRyb3AgPCBtYXgpIHsKICAgICAgICAgIGxlZnQgLT0gY291bnRbY3VyciArIGRyb3BdOwogICAgICAgICAgaWYgKGxlZnQgPD0gMCkgeyBicmVhazsgfQogICAgICAgICAgY3VycisrOwogICAgICAgICAgbGVmdCA8PD0gMTsKICAgICAgICB9CgogICAgICAgIC8qIGNoZWNrIGZvciBlbm91Z2ggc3BhY2UgKi8KICAgICAgICB1c2VkICs9IDEgPDwgY3VycjsKICAgICAgICBpZiAoKHR5cGUgPT09IExFTlMkMSAmJiB1c2VkID4gRU5PVUdIX0xFTlMkMSkgfHwKICAgICAgICAgICh0eXBlID09PSBESVNUUyQxICYmIHVzZWQgPiBFTk9VR0hfRElTVFMkMSkpIHsKICAgICAgICAgIHJldHVybiAxOwogICAgICAgIH0KCiAgICAgICAgLyogcG9pbnQgZW50cnkgaW4gcm9vdCB0YWJsZSB0byBzdWItdGFibGUgKi8KICAgICAgICBsb3cgPSBodWZmICYgbWFzazsKICAgICAgICAvKnRhYmxlLm9wW2xvd10gPSBjdXJyOwogICAgICAgIHRhYmxlLmJpdHNbbG93XSA9IHJvb3Q7CiAgICAgICAgdGFibGUudmFsW2xvd10gPSBuZXh0IC0gb3B0cy50YWJsZV9pbmRleDsqLwogICAgICAgIHRhYmxlW2xvd10gPSAocm9vdCA8PCAyNCkgfCAoY3VyciA8PCAxNikgfCAobmV4dCAtIHRhYmxlX2luZGV4KSB8MDsKICAgICAgfQogICAgfQoKICAgIC8qIGZpbGwgaW4gcmVtYWluaW5nIHRhYmxlIGVudHJ5IGlmIGNvZGUgaXMgaW5jb21wbGV0ZSAoZ3VhcmFudGVlZCB0byBoYXZlCiAgICAgYXQgbW9zdCBvbmUgcmVtYWluaW5nIGVudHJ5LCBzaW5jZSBpZiB0aGUgY29kZSBpcyBpbmNvbXBsZXRlLCB0aGUKICAgICBtYXhpbXVtIGNvZGUgbGVuZ3RoIHRoYXQgd2FzIGFsbG93ZWQgdG8gZ2V0IHRoaXMgZmFyIGlzIG9uZSBiaXQpICovCiAgICBpZiAoaHVmZiAhPT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PSzogWl9PSyQxLCBaX1NUUkVBTV9FTkQ6IFpfU1RSRUFNX0VORCQxLCBaX05FRURfRElDVDogWl9ORUVEX0RJQ1QkMSwgWl9TVFJFQU1fRVJST1I6IFpfU1RSRUFNX0VSUk9SJDEsIFpfREFUQV9FUlJPUjogWl9EQVRBX0VSUk9SJDEsIFpfTUVNX0VSUk9SOiBaX01FTV9FUlJPUiQxLCBaX0JVRl9FUlJPUiwKICAgIFpfREVGTEFURUQKICB9ID0gY29uc3RhbnRzJDI7CgoKICAvKiBTVEFURVMgPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwogIC8qID09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSovCgoKICBjb25zdCAgICBIRUFEID0gMTsgICAgICAgLyogaTogd2FpdGluZyBmb3IgbWFnaWMgaGVhZGVyICovCiAgY29uc3QgICAgRkxBR1MgPSAyOyAgICAgIC8qIGk6IHdhaXRpbmcgZm9yIG1ldGhvZCBhbmQgZmxhZ3MgKGd6aXApICovCiAgY29uc3QgICAgVElNRSA9IDM7ICAgICAgIC8qIGk6IHdhaXRpbmcgZm9yIG1vZGlmaWNhdGlvbiB0aW1lIChnemlwKSAqLwogIGNvbnN0ICAgIE9TID0gNDsgICAgICAgICAvKiBpOiB3YWl0aW5nIGZvciBleHRyYSBmbGFncyBhbmQgb3BlcmF0aW5nIHN5c3RlbSAoZ3ppcCkgKi8KICBjb25zdCAgICBFWExFTiA9IDU7ICAgICAgLyogaTogd2FpdGluZyBmb3IgZXh0cmEgbGVuZ3RoIChnemlwKSAqLwogIGNvbnN0ICAgIEVYVFJBID0gNjsgICAgICAvKiBpOiB3YWl0aW5nIGZvciBleHRyYSBieXRlcyAoZ3ppcCkgKi8KICBjb25zdCAgICBOQU1FID0gNzsgICAgICAgLyogaTogd2FpdGluZyBmb3IgZW5kI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DsgICAgICAgICAgICAgLyogdmFsaWQgYnl0ZXMgaW4gdGhlIHdpbmRvdyAqLwogICAgdGhpcy53bmV4dCA9IDA7ICAgICAgICAgICAgIC8qIHdpbmRvdyB3cml0ZSBpbmRleCAqLwogICAgdGhpcy53aW5kb3cgPSBudWxsOyAgICAgICAgIC8qIGFsbG9jYXRlZCBzbGlkaW5nIHdpbmRvdywgaWYgbmVlZGVkICovCgogICAgLyogYml0IGFjY3VtdWxhdG9yICovCiAgICB0aGlzLmhvbGQgPSAwOyAgICAgICAgICAgICAgLyogaW5wdXQgYml0IGFjY3VtdWxhdG9yICovCiAgICB0aGlzLmJpdHMgPSAwOyAgICAgICAgICAgICAgLyogbnVtYmVyIG9mIGJpdHMgaW4gImluIiAqLwoKICAgIC8qIGZvciBzdHJpbmcgYW5kIHN0b3JlZCBibG9jayBjb3B5aW5nICovCiAgICB0aGlzLmxlbmd0aCA9IDA7ICAgICAgICAgICAgLyogbGl0ZXJhbCBvciBsZW5ndGggb2YgZGF0YSB0byBjb3B5ICovCiAgICB0aGlzLm9mZnNldCA9IDA7ICAgICAgICAgICAgLyogZGlzdGFuY2UgYmFjayB0byBjb3B5IHN0cmluZyBmcm9tICovCgogICAgLyogZm9yIHRhYmxlIGFuZCBjb2RlIGRlY29kaW5nICovCiAgICB0aGlzLmV4dHJhID0gMDsgICAgICAgICAgICAgLyogZXh0cmEgYml0cyBuZWVkZWQgKi8KCiAgICAvKiBmaXhlZCBhbmQgZHluYW1pYyBjb2RlIHRhYmxlcyAqLwogICAgdGhpcy5sZW5jb2RlID0gbnVsbDsgICAgICAgICAgLyogc3RhcnRpbmcgdGFibGUgZm9yIGxlbmd0aC9saXRlcmFsIGNvZGVzICovCiAgICB0aGlzLmRpc3Rjb2RlID0gbnVsbDsgICAgICAgICAvKiBzdGFydGluZyB0YWJsZSBmb3IgZGlzdGFuY2UgY29kZXMgKi8KICAgIHRoaXMubGVuYml0cyA9IDA7ICAgICAgICAgICAvKiBpbmRleCBiaX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CByZXF1ZXN0IGZyb20gd2luZG93Qml0cyBwYXJhbWV0ZXIgKi8KICAgIGlmICh3aW5kb3dCaXRzIDwgMCkgewogICAgICB3cmFwID0gMDsKICAgICAgd2luZG93Qml0cyA9IC13aW5kb3dCaXRzOwogICAgfQogICAgZWxzZSB7CiAgICAgIHdyYXAgPSAod2luZG93Qml0cyA+PiA0KSArIDE7CiAgICAgIGlmICh3aW5kb3dCaXRzIDwgNDgpIHsKICAgICAgICB3aW5kb3dCaXRzICY9IDE1OwogICAgICB9CiAgICB9CgogICAgLyogc2V0IG51bWJlciBvZiB3aW5kb3cgYml0cywgZnJlZSB3aW5kb3cgaWYgZGlmZmVyZW50ICovCiAgICBpZiAod2luZG93Qml0cyAmJiAod2luZG93Qml0cyA8IDggfHwgd2luZG93Qml0cyA+IDE1KSkgewogICAgICByZXR1cm4gWl9TVFJFQU1fRVJST1IkMTsKICAgIH0KICAgIGlmIChzdGF0ZS53aW5kb3cgIT09IG51bGwgJiYgc3RhdGUud2JpdHMgIT09IHdpbmRvd0JpdHMpIHsKICAgICAgc3RhdGUud2luZG93ID0gbnVsbDsKICAgIH0KCiAgICAvKiB1cGRhdGUgc3RhdGUgYW5kIHJlc2V0IHRoZSByZXN0IG9mIGl0ICovCiAgICBzdGF0ZS53cmFwID0gd3JhcDsKICAgIHN0YXRlLndiaXRzID0gd2luZG93Qml0czsKICAgIHJldHVybiBpbmZsYXRlUmVzZXQoc3RybSk7CiAgfTsKCgogIGNvbnN0IGluZmxhdGVJbml0MiA9IChzdHJtLCB3aW5kb3dCaXRzKSA9PiB7CgogICAgaWYgKCFzdHJtKSB7IHJldHVybiBaX1NUUkVBTV9FUlJPUiQxOyB9CiAgICAvL3N0cm0ubXNnID0gWl9OVUxMOyAgICAgICAgICAgICAgICAgLyogaW4gY2FzZSB3ZSByZXR1cm4gYW4gZXJyb3IgKi8KCiAgICBjb25zdCBzdGF0ZSA9IG5ldyBJbmZsYXRlU3RhdGUoKTsKCiAgICAvL2lmI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uZXh0OyAgICAgICAgICAgICAgICAgICAvKiBuZXh0IGlucHV0IElOREVYICovCiAgICBsZXQgcHV0OyAgICAgICAgICAgICAgICAgICAgLyogbmV4dCBvdXRwdXQgSU5ERVggKi8KICAgIGxldCBoYXZlLCBsZWZ0OyAgICAgICAgICAgICAvKiBhdmFpbGFibGUgaW5wdXQgYW5kIG91dHB1dCAqLwogICAgbGV0IGhvbGQ7ICAgICAgICAgICAgICAgICAgIC8qIGJpdCBidWZmZXIgKi8KICAgIGxldCBiaXRzOyAgICAgICAgICAgICAgICAgICAvKiBiaXRzIGluIGJpdCBidWZmZXIgKi8KICAgIGxldCBfaW4sIF9vdXQ7ICAgICAgICAgICAgICAvKiBzYXZlIHN0YXJ0aW5nIGF2YWlsYWJsZSBpbnB1dCBhbmQgb3V0cHV0ICovCiAgICBsZXQgY29weTsgICAgICAgICAgICAgICAgICAgLyogbnVtYmVyIG9mIHN0b3JlZCBvciBtYXRjaCBieXRlcyB0byBjb3B5ICovCiAgICBsZXQgZnJvbTsgICAgICAgICAgICAgICAgICAgLyogd2hlcmUgdG8gY29weSBtYXRjaCBieXRlcyBmcm9tICovCiAgICBsZXQgZnJvbV9zb3VyY2U7CiAgICBsZXQgaGVyZSA9IDA7ICAgICAgICAgICAgICAgLyogY3VycmVudCBkZWNvZGluZyB0YWJsZSBlbnRyeSAqLwogICAgbGV0IGhlcmVfYml0cywgaGVyZV9vcCwgaGVyZV92YWw7IC8vIHBha2VkICJoZXJlIiBkZW5vcm1hbGl6ZWQgKEpTIHNwZWNpZmljKQogICAgLy9sZXQgbGFzdDsgICAgICAgICAgICAgICAgICAgLyogcGFyZW50IHRhYmxlIGVudHJ5ICovCiAgICBsZXQgbGFzdF9iaXRzLCBsYXN0X29wLCBsYXN0X3ZhbDsgLy8gcGFrZWQgImxhc3QiIGRlbm9ybWFsaXplZCAoSlMgc3BlY2lmaWMpCiAgICBsZXQgbGVuOyAgICAgICAgICAgICAgICAgICAgLyogbGVuZ3RoIHRvI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XRlLmJpdHM7CiAgICAvLy0tLQoKICAgIF9pbiA9IGhhdmU7CiAgICBfb3V0ID0gbGVmdDsKICAgIHJldCA9IFpfT0skMTsKCiAgICBpbmZfbGVhdmU6IC8vIGdvdG8gZW11bGF0aW9uCiAgICBmb3IgKDs7KSB7CiAgICAgIHN3aXRjaCAoc3RhdGUubW9kZSkgewogICAgICAgIGNhc2UgSEVBRDoKICAgICAgICAgIGlmIChzdGF0ZS53cmFwID09PSAwKSB7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBUWVBFRE87CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgLy89PT0gTkVFREJJVFMoMTYpOwogICAgICAgICAgd2hpbGUgKGJpdHMgPCAxNikgewogICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgfQogICAgICAgICAgLy89PT0vLwogICAgICAgICAgaWYgKChzdGF0ZS53cmFwICYgMikgJiYgaG9sZCA9PT0gMHg4YjFmKSB7ICAvKiBnemlwIGhlYWRlciAqLwogICAgICAgICAgICBzdGF0ZS5jaGVjayA9IDAvKmNyYzMyKDBMLCBaX05VTEwsIDApKi87CiAgICAgICAgICAgIC8vPT09IENSQzIoc3RhdGUuY2hlY2ssIGhvbGQpOwogICAgICAgICAgICBoYnVmWzBdID0gaG9sZCAmIDB4ZmY7CiAgICAgICAgICAgIGhidWZbMV0gPSAoaG9sZCA+Pj4gOCkgJiAweGZmOwogICAgICAgICAgICBzdGF0ZS5jaGVjayA9IGNyYzMyXzEoc3RhdGUuY2hlY2ssIGhidWYsIDIsIDApOwogICAgICAgICAgICAvLz09PS8vCgogICAgICAgICAgICAvLz09PSBJTklUQklUUygpOwogICAgICAgICAgICBob2xkID0gMDsKICAgICAgICAgICAgYml0cyA9IDA7CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgc3RhdGUubW9kZSA9IEZMQUdTOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIHN0YXRlLmZsYWdzID0gMDsgICAgICAgICAgIC8qIGV4cGVjdCB6bGliIGhlYWRlciAqLwogICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC5kb25lID0gZmFsc2U7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAoIShzdGF0ZS53cmFwICYgMSkgfHwgICAvKiBjaGVjayBpZiB6bGliIGhlYWRlciBhbGxvd2VkICovCiAgICAgICAgICAgICgoKGhvbGQgJiAweGZmKS8qQklUUyg4KSovIDw8IDgpICsgKGhvbGQgPj4gOCkpICUgMzEpIHsKICAgICAgICAgICAgc3RybS5tc2cgPSAnaW5jb3JyZWN0IGhlYWRlciBjaGVjayc7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgaWYgKChob2xkICYgMHgwZikvKkJJVFMoNCkqLyAhPT0gWl9ERUZMQVRFRCkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICd1bmtub3duIGNvbXByZXNzaW9uIG1ldGhvZCc7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgLy8tLS0gRFJPUEJJVFMoNCkgLS0tLy8KICAgICAgICAgIGhvbGQgPj4+PSA0OwogICAgICAgICAgYml0cyAtPSA0OwogICAgICAgICAgLy8tLS0vLwogICAgICAgICAgbGVuID0gKGhvbGQgJiAweDBmKS8qQklUUyg0KSovICsgODsKICAgICAgICAgIGlmIChzdGF0ZS53Yml0cyA9PT0gMCkgewogICAgICAgICAgICBzdGF0ZS53Yml0cyA9IGxlbjsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgaWYgKGxlbiA+IHN0YXRlLndiaXRzKSB7CiAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgd2luZG93IHNpemUnOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KCiAgICAgICAgICAvLyAhISEgcGFrbyBwYXRjaC4gRm9yY2UgdXNlIGBvcHRpb25zLndpbmRvd0JpdHNgIGlmIHBhc3NlZC4KICAgICAgICAgIC8vIFJlcXVpcmVkIHRvIGFsd2F5cyB1c2UgbWF4IHdpbmRvdyBzaXplIGJ5IGRlZmF1bHQuCiAgICAgICAgICBzdGF0ZS5kbWF4ID0gMSA8PCBzdGF0ZS53Yml0czsKICAgICAgICAgIC8vc3RhdGUuZG1heCA9IDEgPDwgbGVuOwoKICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgIHpsaWIgaGVhZGVyIG9rXG4iKSk7CiAgICAgICAgICBzdHJtLmFkbGVyID0gc3RhdGUuY2hlY2sgPSAxLyphZGxlcjMyKDBMLCBaX05VTEwsIDApKi87CiAgICAgICAgICBzdGF0ZS5tb2RlID0gaG9sZCAmIDB4MjAwID8gRElDVElEIDogVFlQRTsKICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICBob2xkID0gMDsKICAgICAgICAgIGJpdHMgPSAwOwogICAgICAgICAgLy89PT0vLwogICAgICAgICAgYnJlYWs7CiAgICAgICAgY2FzZSBGTEFHUzoKICAgICAgICAgIC8vPT09IE5FRURCSVRTKDE2KTsgKi8KICAgICAgICAgIHdoaWxlIChiaXRzIDwgMTYpIHsKICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgIH0KICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgIHN0YXRlLmZsYWdzID0gaG9sZDsKICAgICAgICAgIGlmICgoc3RhdGUuZmxhZ3MgJiAweGZmKSAhPT0gWl9ERUZMQVRFRCkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICd1bmtub3duIGNvbXByZXNzaW9uIG1ldGhvZCc7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgaWYgKHN0YXRlLmZsYWdzICYgMHhlMDAwKSB7CiAgICAgICAgICAgIHN0cm0ubXNnID0gJ3Vua25vd24gaGVhZGVyIGZsYWdzIHNldCc7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC50ZXh0ID0gKChob2xkID4+IDgpICYgMSk7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAoc3RhdGUuZmxhZ3MgJiAweDAyMDApIHsKICAgICAgICAgICAgLy89PT0gQ1JDMihzdGF0ZS5jaGVjaywgaG9sZCk7CiAgICAgICAgICAgIGhidWZbMF0gPSBob2xkICYgMHhmZjsKICAgICAgICAgICAgaGJ1ZlsxXSA9IChob2xkID4+PiA4KSAmIDB4ZmY7CiAgICAgICAgICAgIHN0YXRlLmNoZWNrID0gY3JjMzJfMShzdGF0ZS5jaGVjaywgaGJ1ZiwgMiwgMCk7CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgIH0KICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICBob2xkID0gMDsKICAgICAgICAgIGJpdHMgPSAwOwogICAgICAgICAgLy89PT0vLwogICAgICAgICAgc3RhdGUubW9kZSA9IFRJTUU7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBUSU1FOgogICAgICAgICAgLy89PT0gTkVFREJJVFMoMzIpOyAqLwogICAgICAgICAgd2hpbGUgKGJpdHMgPCAzMikgewogICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgfQogICAgICAgICAgLy89PT0vLwogICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC50aW1lID0gaG9sZDsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDIwMCkgewogICAgICAgICAgICAvLz09PSBDUkM0KHN0YXRlLmNoZWNrLCBob2xkKQogICAgICAgICAgICBoYnVmWzBdID0gaG9sZCAmIDB4ZmY7CiAgICAgICAgICAgIGhidWZbMV0gPSAoaG9sZCA+Pj4gOCkgJiAweGZmOwogICAgICAgICAgICBoYnVmWzJdID0gKGhvbGQgPj4+IDE2KSAmIDB4ZmY7CiAgICAgICAgICAgIGhidWZbM10gPSAoaG9sZCA+Pj4gMjQpICYgMHhmZjsKICAgICAgICAgICAgc3RhdGUuY2hlY2sgPSBjcmMzMl8xKHN0YXRlLmNoZWNrLCBoYnVmLCA0LCAwKTsKICAgICAgICAgICAgLy89PT0KICAgICAgICAgIH0KICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICBob2xkID0gMDsKICAgICAgICAgIGJpdHMgPSAwOwogICAgICAgICAgLy89PT0vLwogICAgICAgICAgc3RhdGUubW9kZSA9IE9TOwogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgT1M6CiAgICAgICAgICAvLz09PSBORUVEQklUUygxNik7ICovCiAgICAgICAgICB3aGlsZSAoYml0cyA8IDE2KSB7CiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICB9CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBpZiAoc3RhdGUuaGVhZCkgewogICAgICAgICAgICBzdGF0ZS5oZWFkLnhmbGFncyA9IChob2xkICYgMHhmZik7CiAgICAgICAgICAgIHN0YXRlLmhlYWQub3MgPSAoaG9sZCA+PiA4KTsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDIwMCkgewogICAgICAgICAgICAvLz09PSBDUkMyKHN0YXRlLmNoZWNrLCBob2xkKTsKICAgICAgICAgICAgaGJ1ZlswXSA9IGhvbGQgJiAweGZmOwogICAgICAgICAgICBoYnVmWzFdID0gKGhvbGQgPj4+IDgpICYgMHhmZjsKICAgICAgICAgICAgc3RhdGUuY2hlY2sgPSBjcmMzMl8xKHN0YXRlLmNoZWNrLCBoYnVmLCAyLCAwKTsKICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgfQogICAgICAgICAgLy89PT0gSU5JVEJJVFMoKTsKICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgYml0cyA9IDA7CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBzdGF0ZS5tb2RlID0gRVhMRU47CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBFWExFTjoKICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDQwMCkgewogICAgICAgICAgICAvLz09PSBORUVEQklUUygxNik7ICovCiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgMTYpIHsKICAgICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgc3RhdGUubGVuZ3RoID0gaG9sZDsKICAgICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgICBzdGF0ZS5oZWFkLmV4dHJhX2xlbiA9IGhvbGQ7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKHN0YXRlLmZsYWdzICYgMHgwMjAwKSB7CiAgICAgICAgICAgICAgLy89PT0gQ1JDMihzdGF0ZS5jaGVjaywgaG9sZCk7CiAgICAgICAgICAgICAgaGJ1ZlswXSA9IGhvbGQgJiAweGZmOwogICAgICAgICAgICAgIGhidWZbMV0gPSAoaG9sZCA+Pj4gOCkgJiAweGZmOwogICAgICAgICAgICAgIHN0YXRlLmNoZWNrID0gY3JjMzJfMShzdGF0ZS5jaGVjaywgaGJ1ZiwgMiwgMCk7CiAgICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgICBiaXRzID0gMDsKICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgfQogICAgICAgICAgZWxzZSBpZiAoc3RhdGUuaGVhZCkgewogICAgICAgICAgICBzdGF0ZS5oZWFkLmV4dHJhID0gbnVsbC8qWl9OVUxMKi87CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5tb2RlID0gRVhUUkE7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBFWFRSQToKICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDQwMCkgewogICAgICAgICAgICBjb3B5ID0gc3RhdGUubGVuZ3RoOwogICAgICAgICAgICBpZiAoY29weSA+IGhhdmUpIHsgY29weSA9IGhhdmU7IH0KICAgICAgICAgICAgaWYgKGNvcHkpIHsKICAgICAgICAgICAgICBpZiAoc3RhdGUuaGVhZCkgewogICAgICAgICAgICAgICAgbGVuID0gc3RhdGUuaGVhZC5leHRyYV9sZW4gLSBzdGF0ZS5sZW5ndGg7CiAgICAgICAgICAgICAgICBpZiAoIXN0YXRlLmhlYWQuZXh0cmEpIHsKICAgICAgICAgICAgICAgICAgLy8gVXNlIHVudHlwZWQgYXJyYXkgZm9yIG1vcmUgY29udmVuaWVudCBwcm9jZXNzaW5nIGxhdGVyCiAgICAgICAgICAgICAgICAgIHN0YXRlLmhlYWQuZXh0cmEgPSBuZXcgVWludDhBcnJheShzdGF0ZS5oZWFkLmV4dHJhX2xlbik7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICBzdGF0ZS5oZWFkLmV4dHJhLnNldCgKICAgICAgICAgICAgICAgICAgaW5wdXQuc3ViYXJyYXkoCiAgICAgICAgICAgICAgICAgICAgbmV4dCwKICAgICAgICAgICAgICAgICAgICAvLyBleHRyYSBmaWVsZCBpcyBsaW1pdGVkIHRvIDY1NTM2IGJ5dGVzCiAgICAgICAgICAgICAgICAgICAgLy8gLSBubyBuZWVkIGZvciBhZGRpdGlvbmFsIHNpemUgY2hlY2sKICAgICAgICAgICAgICAgICAgICBuZXh0ICsgY29weQogICAgICAgICAgICAgICAgICApLAogICAgICAgICAgICAgICAgICAvKmxlbiArIGNvcHkgPiBzdGF0ZS5oZWFkLmV4dHJhX21heCAtIGxlbiA/IHN0YXRlLmhlYWQuZXh0cmFfbWF4IDogY29weSwqLwogICAgICAgICAgICAgICAgICBsZW4KICAgICAgICAgICAgICAgICk7CiAgICAgICAgICAgICAgICAvL3ptZW1jcHkoc3RhdGUuaGVhZC5leHRyYSArIGxlbiwgbmV4dCwKICAgICAgICAgICAgICAgIC8vICAgICAgICBsZW4gKyBjb3B5ID4gc3RhdGUuaGVhZC5leHRyYV9tYXggPwogICAgICAgICAgICAgICAgLy8gICAgICAgIHN0YXRlLmhlYWQuZXh0cmFfbWF4IC0gbGVuIDogY29weSk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDIwMCkgewogICAgICAgICAgICAgICAgc3RhdGUuY2hlY2sgPSBjcmMzMl8xKHN0YXRlLmNoZWNrLCBpbnB1dCwgY29weSwgbmV4dCk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGhhdmUgLT0gY29weTsKICAgICAgICAgICAgICBuZXh0ICs9IGNvcHk7CiAgICAgICAgICAgICAgc3RhdGUubGVuZ3RoIC09IGNvcHk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKHN0YXRlLmxlbmd0aCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgIH0KICAgICAgICAgIHN0YXRlLmxlbmd0aCA9IDA7CiAgICAgICAgICBzdGF0ZS5tb2RlID0gTkFNRTsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIE5BTUU6CiAgICAgICAgICBpZiAoc3RhdGUuZmxhZ3MgJiAweDA4MDApIHsKICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgIGNvcHkgPSAwOwogICAgICAgICAgICBkbyB7CiAgICAgICAgICAgICAgLy8gVE9ETzogMiBvciAxIGJ5dGVzPwogICAgICAgICAgICAgIGxlbiA9IGlucHV0W25leHQgKyBjb3B5KytdOwogICAgICAgICAgICAgIC8qIHVzZSBjb25zdGFudCBsaW1pdCBiZWNhdXNlIGluIGpzIHdlIHNob3VsZCBub3QgcHJlYWxsb2NhdGUgbWVtb3J5ICovCiAgICAgICAgICAgICAgaWYgKHN0YXRlLmhlYWQgJiYgbGVuICYmCiAgICAgICAgICAgICAgICAgIChzdGF0ZS5sZW5ndGggPCA2NTUzNiAvKnN0YXRlLmhlYWQubmFtZV9tYXgqLykpIHsKICAgICAgICAgICAgICAgIHN0YXRlLmhlYWQubmFtZSArPSBTdHJpbmcuZnJvbUNoYXJDb2RlKGxlbik7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9IHdoaWxlIChsZW4gJiYgY29weSA8IGhhdmUpOwoKICAgICAgICAgICAgaWYgKHN0YXRlLmZsYWdzICYgMHgwMjAwKSB7CiAgICAgICAgICAgICAgc3RhdGUuY2hlY2sgPSBjcmMzMl8xKHN0YXRlLmNoZWNrLCBpbnB1dCwgY29weSwgbmV4dCk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaGF2ZSAtPSBjb3B5OwogICAgICAgICAgICBuZXh0ICs9IGNvcHk7CiAgICAgICAgICAgIGlmIChsZW4pIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIGlmIChzdGF0ZS5oZWFkKSB7CiAgICAgICAgICAgIHN0YXRlLmhlYWQubmFtZSA9IG51bGw7CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5sZW5ndGggPSAwOwogICAgICAgICAgc3RhdGUubW9kZSA9IENPTU1FTlQ7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBDT01NRU5UOgogICAgICAgICAgaWYgKHN0YXRlLmZsYWdzICYgMHgxMDAwKSB7CiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBjb3B5ID0gMDsKICAgICAgICAgICAgZG8gewogICAgICAgICAgICAgIGxlbiA9IGlucHV0W25leHQgKyBjb3B5KytdOwogICAgICAgICAgICAgIC8qIHVzZSBjb25zdGFudCBsaW1pdCBiZWNhdXNlIGluIGpzIHdlIHNob3VsZCBub3QgcHJlYWxsb2NhdGUgbWVtb3J5ICovCiAgICAgICAgICAgICAgaWYgKHN0YXRlLmhlYWQgJiYgbGVuICYmCiAgICAgICAgICAgICAgICAgIChzdGF0ZS5sZW5ndGggPCA2NTUzNiAvKnN0YXRlLmhlYWQuY29tbV9tYXgqLykpIHsKICAgICAgICAgICAgICAgIHN0YXRlLmhlYWQuY29tbWVudCArPSBTdHJpbmcuZnJvbUNoYXJDb2RlKGxlbik7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9IHdoaWxlIChsZW4gJiYgY29weSA8IGhhdmUpOwogICAgICAgICAgICBpZiAoc3RhdGUuZmxhZ3MgJiAweDAyMDApIHsKICAgICAgICAgICAgICBzdGF0ZS5jaGVjayA9IGNyYzMyXzEoc3RhdGUuY2hlY2ssIGlucHV0LCBjb3B5LCBuZXh0KTsKICAgICAgICAgICAgfQogICAgICAgICAgICBoYXZlIC09IGNvcHk7CiAgICAgICAgICAgIG5leHQgKz0gY29weTsKICAgICAgICAgICAgaWYgKGxlbikgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC5jb21tZW50ID0gbnVsbDsKICAgICAgICAgIH0KICAgICAgICAgIHN0YXRlLm1vZGUgPSBIQ1JDOwogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgSENSQzoKICAgICAgICAgIGlmIChzdGF0ZS5mbGFncyAmIDB4MDIwMCkgewogICAgICAgICAgICAvLz09PSBORUVEQklUUygxNik7ICovCiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgMTYpIHsKICAgICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgaWYgKGhvbGQgIT09IChzdGF0ZS5jaGVjayAmIDB4ZmZmZikpIHsKICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdoZWFkZXIgY3JjIG1pc21hdGNoJzsKICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgICBiaXRzID0gMDsKICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgfQogICAgICAgICAgaWYgKHN0YXRlLmhlYWQpIHsKICAgICAgICAgICAgc3RhdGUuaGVhZC5oY3JjID0gKChzdGF0ZS5mbGFncyA+PiA5KSAmIDEpOwogICAgICAgICAgICBzdGF0ZS5oZWFkLmRvbmUgPSB0cnVlOwogICAgICAgICAgfQogICAgICAgICAgc3RybS5hZGxlciA9IHN0YXRlLmNoZWNrID0gMDsKICAgICAgICAgIHN0YXRlLm1vZGUgPSBUWVBFOwogICAgICAgICAgYnJlYWs7CiAgICAgICAgY2FzZSBESUNUSUQ6CiAgICAgICAgICAvLz09PSBORUVEQklUUygzMik7ICovCiAgICAgICAgICB3aGlsZSAoYml0cyA8IDMyKSB7CiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICB9CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBzdHJtLmFkbGVyID0gc3RhdGUuY2hlY2sgPSB6c3dhcDMyKGhvbGQpOwogICAgICAgICAgLy89PT0gSU5JVEJJVFMoKTsKICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgYml0cyA9IDA7CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBzdGF0ZS5tb2RlID0gRElDVDsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIERJQ1Q6CiAgICAgICAgICBpZiAoc3RhdGUuaGF2ZWRpY3QgPT09IDApIHsKICAgICAgICAgICAgLy8tLS0gUkVTVE9SRSgpIC0tLQogICAgICAgICAgICBzdHJtLm5leHRfb3V0ID0gcHV0OwogICAgICAgICAgICBzdHJtLmF2YWlsX291dCA9IGxlZnQ7CiAgICAgICAgICAgIHN0cm0ubmV4dF9pbiA9IG5leHQ7CiAgICAgICAgICAgIHN0cm0uYXZhaWxfaW4gPSBoYXZlOwogICAgICAgICAgICBzdGF0ZS5ob2xkID0gaG9sZDsKICAgICAgICAgICAgc3RhdGUuYml0cyA9IGJpdHM7CiAgICAgICAgICAgIC8vLS0tCiAgICAgICAgICAgIHJldHVybiBaX05FRURfRElDVCQxOwogICAgICAgICAgfQogICAgICAgICAgc3RybS5hZGxlciA9IHN0YXRlLmNoZWNrID0gMS8qYWRsZXIzMigwTCwgWl9OVUxMLCAwKSovOwogICAgICAgICAgc3RhdGUubW9kZSA9IFRZUEU7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBUWVBFOgogICAgICAgICAgaWYgKGZsdXNoID09PSBaX0JMT0NLIHx8IGZsdXNoID09PSBaX1RSRUVTKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgVFlQRURPOgogICAgICAgICAgaWYgKHN0YXRlLmxhc3QpIHsKICAgICAgICAgICAgLy8tLS0gQllURUJJVFMoKSAtLS0vLwogICAgICAgICAgICBob2xkID4+Pj0gYml0cyAmIDc7CiAgICAgICAgICAgIGJpdHMgLT0gYml0cyAmIDc7CiAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgICAgc3RhdGUubW9kZSA9IENIRUNLOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIC8vPT09IE5FRURCSVRTKDMpOyAqLwogICAgICAgICAgd2hpbGUgKGJpdHMgPCAzKSB7CiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICB9CiAgICAgICAgICAvLz09PS8vCiAgICAgICAgICBzdGF0ZS5sYXN0ID0gKGhvbGQgJiAweDAxKS8qQklUUygxKSovOwogICAgICAgICAgLy8tLS0gRFJPUEJJVFMoMSkgLS0tLy8KICAgICAgICAgIGhvbGQgPj4+PSAxOwogICAgICAgICAgYml0cyAtPSAxOwogICAgICAgICAgLy8tLS0vLwoKICAgICAgICAgIHN3aXRjaCAoKGhvbGQgJiAweDAzKS8qQklUUygyKSovKSB7CiAgICAgICAgICAgIGNhc2UgMDogICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8qIHN0b3JlZCBibG9jayAqLwogICAgICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgc3RvcmVkIGJsb2NrJXNcbiIsCiAgICAgICAgICAgICAgLy8gICAgICAgIHN0YXRlLmxhc3QgPyAiIChsYXN0KSIgOiAiIikpOwogICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBTVE9SRUQ7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8qIGZpeGVkIGJsb2NrICovCiAgICAgICAgICAgICAgZml4ZWR0YWJsZXMoc3RhdGUpOwogICAgICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgZml4ZWQgY29kZXMgYmxvY2slc1xuIiwKICAgICAgICAgICAgICAvLyAgICAgICAgc3RhdGUubGFzdCA/ICIgKGxhc3QpIiA6ICIiKSk7CiAgICAgICAgICAgICAgc3RhdGUubW9kZSA9IExFTl87ICAgICAgICAgICAgIC8qIGRlY29kZSBjb2RlcyAqLwogICAgICAgICAgICAgIGlmIChmbHVzaCA9PT0gWl9UUkVFUykgewogICAgICAgICAgICAgICAgLy8tLS0gRFJPUEJJVFMoMikgLS0tLy8KICAgICAgICAgICAgICAgIGhvbGQgPj4+PSAyOwogICAgICAgICAgICAgICAgYml0cyAtPSAyOwogICAgICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICAgICAgYnJlYWsgaW5mX2xlYXZlOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAyOiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLyogZHluYW1pYyBibG9jayAqLwogICAgICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgZHluYW1pYyBjb2RlcyBibG9jayVzXG4iLAogICAgICAgICAgICAgIC8vICAgICAgICBzdGF0ZS5sYXN0ID8gIiAobGFzdCkiIDogIiIpKTsKICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gVEFCTEU7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMzoKICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGJsb2NrIHR5cGUnOwogICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICB9CiAgICAgICAgICAvLy0tLSBEUk9QQklUUygyKSAtLS0vLwogICAgICAgICAgaG9sZCA+Pj49IDI7CiAgICAgICAgICBiaXRzIC09IDI7CiAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICBicmVhazsKICAgICAgICBjYXNlIFNUT1JFRDoKICAgICAgICAgIC8vLS0tIEJZVEVCSVRTKCkgLS0tLy8gLyogZ28gdG8gYnl0ZSBib3VuZGFyeSAqLwogICAgICAgICAgaG9sZCA+Pj49IGJpdHMgJiA3OwogICAgICAgICAgYml0cyAtPSBiaXRzICYgNzsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIC8vPT09IE5FRURCSVRTKDMyKTsgKi8KICAgICAgICAgIHdoaWxlIChiaXRzIDwgMzIpIHsKICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgIH0KICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgIGlmICgoaG9sZCAmIDB4ZmZmZikgIT09ICgoaG9sZCA+Pj4gMTYpIF4gMHhmZmZmKSkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIHN0b3JlZCBibG9jayBsZW5ndGhzJzsKICAgICAgICAgICAgc3RhdGUubW9kZSA9IEJBRDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5sZW5ndGggPSBob2xkICYgMHhmZmZmOwogICAgICAgICAgLy9UcmFjZXYoKHN0ZGVyciwgImluZmxhdGU6ICAgICAgIHN0b3JlZCBsZW5ndGggJXVcbiIsCiAgICAgICAgICAvLyAgICAgICAgc3RhdGUubGVuZ3RoKSk7CiAgICAgICAgICAvLz09PSBJTklUQklUUygpOwogICAgICAgICAgaG9sZCA9IDA7CiAgICAgICAgICBiaXRzID0gMDsKICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgIHN0YXRlLm1vZGUgPSBDT1BZXzsKICAgICAgICAgIGlmIChmbHVzaCA9PT0gWl9UUkVFUykgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIENPUFlfOgogICAgICAgICAgc3RhdGUubW9kZSA9IENPUFk7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBDT1BZOgogICAgICAgICAgY29weSA9IHN0YXRlLmxlbmd0aDsKICAgICAgICAgIGlmIChjb3B5KSB7CiAgICAgICAgICAgIGlmIChjb3B5ID4gaGF2ZSkgeyBjb3B5ID0gaGF2ZTsgfQogICAgICAgICAgICBpZiAoY29weSA+IGxlZnQpIHsgY29weSA9IGxlZnQ7IH0KICAgICAgICAgICAgaWYgKGNvcHkgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgIC8vLS0tIHptZW1jcHkocHV0LCBuZXh0LCBjb3B5KTsgLS0tCiAgICAgICAgICAgIG91dHB1dC5zZXQoaW5wdXQuc3ViYXJyYXkobmV4dCwgbmV4dCArIGNvcHkpLCBwdXQpOwogICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgIGhhdmUgLT0gY29weTsKICAgICAgICAgICAgbmV4dCArPSBjb3B5OwogICAgICAgICAgICBsZWZ0IC09IGNvcHk7CiAgICAgICAgICAgIHB1dCArPSBjb3B5OwogICAgICAgICAgICBzdGF0ZS5sZW5ndGggLT0gY29weTsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICAvL1RyYWNldigoc3RkZXJyLCAiaW5mbGF0ZTogICAgICAgc3RvcmVkIGVuZFxuIikpOwogICAgICAgICAgc3RhdGUubW9kZSA9IFRZUEU7CiAgICAgICAgICBicmVhazsKICAgICAgICBjYXNlIFRBQkxFOgogICAgICAgICAgLy89PT0gTkVFREJJVFMoMTQpOyAqLwogICAgICAgICAgd2hpbGUgKGJpdHMgPCAxNCkgewogICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgfQogICAgICAgICAgLy89PT0vLwogICAgICAgICAgc3RhdGUubmxlbiA9IChob2xkICYgMHgxZikvKkJJVFMoNSkqLyArIDI1NzsKICAgICAgICAgIC8vLS0tIERST1BCSVRTKDUpIC0tLS8vCiAgICAgICAgICBob2xkID4+Pj0gNTsKICAgICAgICAgIGJpdHMgLT0gNTsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIHN0YXRlLm5kaXN0ID0gKGhvbGQgJiAweDFmKS8qQklUUyg1KSovICsgMTsKICAgICAgICAgIC8vLS0tIERST1BCSVRTKDUpIC0tLS8vCiAgICAgICAgICBob2xkID4+Pj0gNTsKICAgICAgICAgIGJpdHMgLT0gNTsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIHN0YXRlLm5jb2RlID0gKGhvbGQgJiAweDBmKS8qQklUUyg0KSovICsgNDsKICAgICAgICAgIC8vLS0tIERST1BCSVRTKDQpIC0tLS8vCiAgICAgICAgICBob2xkID4+Pj0gNDsKICAgICAgICAgIGJpdHMgLT0gNDsKICAgICAgICAgIC8vLS0tLy8KICAvLyNpZm5kZWYgUEtaSVBfQlVHX1dPUktBUk9VTkQKICAgICAgICAgIGlmIChzdGF0ZS5ubGVuID4gMjg2IHx8IHN0YXRlLm5kaXN0ID4gMzApIHsKICAgICAgICAgICAgc3RybS5tc2cgPSAndG9vIG1hbnkgbGVuZ3RoIG9yIGRpc3RhbmNlIHN5bWJvbHMnOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAvLyNlbmRpZgogICAgICAgICAgLy9UcmFjZXYoKHN0ZGVyciwgImluZmxhdGU6ICAgICAgIHRhYmxlIHNpemVzIG9rXG4iKSk7CiAgICAgICAgICBzdGF0ZS5oYXZlID0gMDsKICAgICAgICAgIHN0YXRlLm1vZGUgPSBMRU5MRU5TOwogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgTEVOTEVOUzoKICAgICAgICAgIHdoaWxlIChzdGF0ZS5oYXZlIDwgc3RhdGUubmNvZGUpIHsKICAgICAgICAgICAgLy89PT0gTkVFREJJVFMoMyk7CiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgMykgewogICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgICBzdGF0ZS5sZW5zW29yZGVyW3N0YXRlLmhhdmUrK11dID0gKGhvbGQgJiAweDA3KTsvL0JJVFMoMyk7CiAgICAgICAgICAgIC8vLS0tIERST1BCSVRTKDMpIC0tLS8vCiAgICAgICAgICAgIGhvbGQgPj4+PSAzOwogICAgICAgICAgICBiaXRzIC09IDM7CiAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIH0KICAgICAgICAgIHdoaWxlIChzdGF0ZS5oYXZlIDwgMTkpIHsKICAgICAgICAgICAgc3RhdGUubGVuc1tvcmRlcltzdGF0ZS5oYXZlKytdXSA9IDA7CiAgICAgICAgICB9CiAgICAgICAgICAvLyBXZSBoYXZlIHNlcGFyYXRlIHRhYmxlcyAmIG5vIHBvaW50ZXJzLiAyIGNvbW1lbnRlZCBsaW5lcyBiZWxvdyBub3QgbmVlZGVkLgogICAgICAgICAgLy9zdGF0ZS5uZXh0ID0gc3RhdGUuY29kZXM7CiAgICAgICAgICAvL3N0YXRlLmxlbmNvZGUgPSBzdGF0ZS5uZXh0OwogICAgICAgICAgLy8gU3dpdGNoIHRvIHVzZSBkeW5hbWljIHRhYmxlCiAgICAgICAgICBzdGF0ZS5sZW5jb2RlID0gc3RhdGUubGVuZHluOwogICAgICAgICAgc3RhdGUubGVuYml0cyA9IDc7CgogICAgICAgICAgb3B0cyA9IHsgYml0czogc3RhdGUubGVuYml0cyB9OwogICAgICAgICAgcmV0ID0gaW5mdHJlZXMoQ09ERVMsIHN0YXRlLmxlbnMsIDAsIDE5LCBzdGF0ZS5sZW5jb2RlLCAwLCBzdGF0ZS53b3JrLCBvcHRzKTsKICAgICAgICAgIHN0YXRlLmxlbmJpdHMgPSBvcHRzLmJpdHM7CgogICAgICAgICAgaWYgKHJldCkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGNvZGUgbGVuZ3RocyBzZXQnOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgICBjb2RlIGxlbmd0aHMgb2tcbiIpKTsKICAgICAgICAgIHN0YXRlLmhhdmUgPSAwOwogICAgICAgICAgc3RhdGUubW9kZSA9IENPREVMRU5TOwogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgQ09ERUxFTlM6CiAgICAgICAgICB3aGlsZSAoc3RhdGUuaGF2ZSA8IHN0YXRlLm5sZW4gKyBzdGF0ZS5uZGlzdCkgewogICAgICAgICAgICBmb3IgKDs7KSB7CiAgICAgICAgICAgICAgaGVyZSA9IHN0YXRlLmxlbmNvZGVbaG9sZCAmICgoMSA8PCBzdGF0ZS5sZW5iaXRzKSAtIDEpXTsvKkJJVFMoc3RhdGUubGVuYml0cykqLwogICAgICAgICAgICAgIGhlcmVfYml0cyA9IGhlcmUgPj4+IDI0OwogICAgICAgICAgICAgIGhlcmVfb3AgPSAoaGVyZSA+Pj4gMTYpICYgMHhmZjsKICAgICAgICAgICAgICBoZXJlX3ZhbCA9IGhlcmUgJiAweGZmZmY7CgogICAgICAgICAgICAgIGlmICgoaGVyZV9iaXRzKSA8PSBiaXRzKSB7IGJyZWFrOyB9CiAgICAgICAgICAgICAgLy8tLS0gUFVMTEJZVEUoKSAtLS0vLwogICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmIChoZXJlX3ZhbCA8IDE2KSB7CiAgICAgICAgICAgICAgLy8tLS0gRFJPUEJJVFMoaGVyZS5iaXRzKSAtLS0vLwogICAgICAgICAgICAgIGhvbGQgPj4+PSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgYml0cyAtPSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICAgIHN0YXRlLmxlbnNbc3RhdGUuaGF2ZSsrXSA9IGhlcmVfdmFsOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIGlmIChoZXJlX3ZhbCA9PT0gMTYpIHsKICAgICAgICAgICAgICAgIC8vPT09IE5FRURCSVRTKGhlcmUuYml0cyArIDIpOwogICAgICAgICAgICAgICAgbiA9IGhlcmVfYml0cyArIDI7CiAgICAgICAgICAgICAgICB3aGlsZSAoYml0cyA8IG4pIHsKICAgICAgICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICAgICAgaG9sZCArPSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgICAgIC8vLS0tIERST1BCSVRTKGhlcmUuYml0cykgLS0tLy8KICAgICAgICAgICAgICAgIGhvbGQgPj4+PSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgICBiaXRzIC09IGhlcmVfYml0czsKICAgICAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgICAgICAgIGlmIChzdGF0ZS5oYXZlID09PSAwKSB7CiAgICAgICAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgYml0IGxlbmd0aCByZXBlYXQnOwogICAgICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGxlbiA9IHN0YXRlLmxlbnNbc3RhdGUuaGF2ZSAtIDFdOwogICAgICAgICAgICAgICAgY29weSA9IDMgKyAoaG9sZCAmIDB4MDMpOy8vQklUUygyKTsKICAgICAgICAgICAgICAgIC8vLS0tIERST1BCSVRTKDIpIC0tLS8vCiAgICAgICAgICAgICAgICBob2xkID4+Pj0gMjsKICAgICAgICAgICAgICAgIGJpdHMgLT0gMjsKICAgICAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSBpZiAoaGVyZV92YWwgPT09IDE3KSB7CiAgICAgICAgICAgICAgICAvLz09PSBORUVEQklUUyhoZXJlLmJpdHMgKyAzKTsKICAgICAgICAgICAgICAgIG4gPSBoZXJlX2JpdHMgKyAzOwogICAgICAgICAgICAgICAgd2hpbGUgKGJpdHMgPCBuKSB7CiAgICAgICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAvLz09PS8vCiAgICAgICAgICAgICAgICAvLy0tLSBEUk9QQklUUyhoZXJlLmJpdHMpIC0tLS8vCiAgICAgICAgICAgICAgICBob2xkID4+Pj0gaGVyZV9iaXRzOwogICAgICAgICAgICAgICAgYml0cyAtPSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgICAgICBsZW4gPSAwOwogICAgICAgICAgICAgICAgY29weSA9IDMgKyAoaG9sZCAmIDB4MDcpOy8vQklUUygzKTsKICAgICAgICAgICAgICAgIC8vLS0tIERST1BCSVRTKDMpIC0tLS8vCiAgICAgICAgICAgICAgICBob2xkID4+Pj0gMzsKICAgICAgICAgICAgICAgIGJpdHMgLT0gMzsKICAgICAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAvLz09PSBORUVEQklUUyhoZXJlLmJpdHMgKyA3KTsKICAgICAgICAgICAgICAgIG4gPSBoZXJlX2JpdHMgKyA3OwogICAgICAgICAgICAgICAgd2hpbGUgKGJpdHMgPCBuKSB7CiAgICAgICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAvLz09PS8vCiAgICAgICAgICAgICAgICAvLy0tLSBEUk9QQklUUyhoZXJlLmJpdHMpIC0tLS8vCiAgICAgICAgICAgICAgICBob2xkID4+Pj0gaGVyZV9iaXRzOwogICAgICAgICAgICAgICAgYml0cyAtPSBoZXJlX2JpdHM7CiAgICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgICAgICBsZW4gPSAwOwogICAgICAgICAgICAgICAgY29weSA9IDExICsgKGhvbGQgJiAweDdmKTsvL0JJVFMoNyk7CiAgICAgICAgICAgICAgICAvLy0tLSBEUk9QQklUUyg3KSAtLS0vLwogICAgICAgICAgICAgICAgaG9sZCA+Pj49IDc7CiAgICAgICAgICAgICAgICBiaXRzIC09IDc7CiAgICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGlmIChzdGF0ZS5oYXZlICsgY29weSA+IHN0YXRlLm5sZW4gKyBzdGF0ZS5uZGlzdCkgewogICAgICAgICAgICAgICAgc3RybS5tc2cgPSAnaW52YWxpZCBiaXQgbGVuZ3RoIHJlcGVhdCc7CiAgICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIHdoaWxlIChjb3B5LS0pIHsKICAgICAgICAgICAgICAgIHN0YXRlLmxlbnNbc3RhdGUuaGF2ZSsrXSA9IGxlbjsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KCiAgICAgICAgICAvKiBoYW5kbGUgZXJyb3IgYnJlYWtzIGluIHdoaWxlICovCiAgICAgICAgICBpZiAoc3RhdGUubW9kZSA9PT0gQkFEKSB7IGJyZWFrOyB9CgogICAgICAgICAgLyogY2hlY2sgZm9yIGVuZC1vZi1ibG9jayBjb2RlIChiZXR0ZXIgaGF2ZSBvbmUpICovCiAgICAgICAgICBpZiAoc3RhdGUubGVuc1syNTZdID09PSAwKSB7CiAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgY29kZSAtLSBtaXNzaW5nIGVuZC1vZi1ibG9jayc7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQoKICAgICAgICAgIC8qIGJ1aWxkIGNvZGUgdGFibGVzIC0tIG5vdGU6IGRvIG5vdCBjaGFuZ2UgdGhlIGxlbmJpdHMgb3IgZGlzdGJpdHMKICAgICAgICAgICAgIHZhbHVlcyBoZXJlICg5IGFuZCA2KSB3aXRob3V0IHJlYWRpbmcgdGhlIGNvbW1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nRyZWVzKERJU1RTLCBzdGF0ZS5sZW5zLCBzdGF0ZS5ubGVuLCBzdGF0ZS5uZGlzdCwgc3RhdGUuZGlzdGNvZGUsIDAsIHN0YXRlLndvcmssIG9wdHMpOwogICAgICAgICAgLy8gV2UgaGF2ZSBzZXBhcmF0ZSB0YWJsZXMgJiBubyBwb2ludGVycy4gMiBjb21tZW50ZWQgbGluZXMgYmVsb3cgbm90IG5lZWRlZC4KICAgICAgICAgIC8vIHN0YXRlLm5leHRfaW5kZXggPSBvcHRzLnRhYmxlX2luZGV4OwogICAgICAgICAgc3RhdGUuZGlzdGJpdHMgPSBvcHRzLmJpdHM7CiAgICAgICAgICAvLyBzdGF0ZS5kaXN0Y29kZSA9IHN0YXRlLm5leHQ7CgogICAgICAgICAgaWYgKHJldCkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGRpc3RhbmNlcyBzZXQnOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICdpbmZsYXRlOiAgICAgICBjb2RlcyBva1xuJykpOwogICAgICAgICAgc3RhdGUubW9kZSA9IExFTl87CiAgICAgICAgICBpZiAoZmx1c2ggPT09IFpfVFJFRVMpIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBMRU5fOgogICAgICAgICAgc3RhdGUubW9kZSA9IExFTjsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIExFTjoKICAgICAgICAgIGlmIChoYXZlID49IDYgJiYgbGVmdCA+PSAyNTgpIHsKICAgICAgICAgICAgLy8tLS0gUkVTVE9SRSgpIC0tLQogICAgICAgICAgICBzdHJtLm5leHRfb3V0ID0gcHV0OwogICAgICAgICAgICBzdHJtLmF2YWlsX291dCA9IGxlZnQ7CiAgICAgICAgICAgIHN0cm0ubmV4dF9pbiA9IG5leHQ7CiAgICAgICAgICAgIHN0cm0uYXZhaWxfaW4gPSBoYXZlOwogICAgICAgICAgICBzdGF0ZS5ob2xkID0gaG9sZDsKICAgICAgICAgICAgc3RhdGUuYml0cyA9IGJpdHM7CiAgICAgICAgICAgIC8vLS0tCiAgICAgICAgICAgIGluZmZhc3Qoc3RybSwgX291dCk7CiAgICAgICAgICAgIC8vLS0tIExPQUQoKSAtLS0KICAgICAgICAgICAgcHV0ID0gc3RybS5uZXh0X291dDsKICAgICAgICAgICAgb3V0cHV0ID0gc3RybS5vdXRwdXQ7CiAgICAgICAgICAgIGxlZnQgPSBzdHJtLmF2YWlsX291dDsKICAgICAgICAgICAgbmV4dCA9IHN0cm0ubmV4dF9pbjsKICAgICAgICAgICAgaW5wdXQgPSBzdHJtLmlucHV0OwogICAgICAgICAgICBoYXZlID0gc3RybS5hdmFpbF9pbjsKICAgICAgICAgICAgaG9sZCA9IHN0YXRlLmhvbGQ7CiAgICAgICAgICAgIGJpdHMgPSBzdGF0ZS5iaXRzOwogICAgICAgICAgICAvLy0tLQoKICAgICAgICAgICAgaWYgKHN0YXRlLm1vZGUgPT09IFRZUEUpIHsKICAgICAgICAgICAgICBzdGF0ZS5iYWNrID0gLTE7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5iYWNrID0gMDsKICAgICAgICAgIGZvciAoOzspIHsKICAgICAgICAgICAgaGVyZSA9IHN0YXRlLmxlbmNvZGVbaG9sZCAmICgoMSA8PCBzdGF0ZS5sZW5iaXRzKSAtIDEpXTsgIC8qQklUUyhzdGF0ZS5sZW5iaXRzKSovCiAgICAgICAgICAgIGhlcmVfYml0cyA9IGhlcmUgPj4+IDI0OwogICAgICAgICAgICBoZXJlX29wID0gKGhlcmUgPj4+IDE2KSAmIDB4ZmY7CiAgICAgICAgICAgIGhlcmVfdmFsID0gaGVyZSAmIDB4ZmZmZjsKCiAgICAgICAgICAgIGlmIChoZXJlX2JpdHMgPD0gYml0cykgeyBicmVhazsgfQogICAgICAgICAgICAvLy0tLSBQVUxMQllURSgpIC0tLS8vCiAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIH0KICAgICAgICAgIGlmIChoZXJlX29wICYmIChoZXJlX29wICYgMHhmMCkgPT09IDApIHsKICAgICAgICAgICAgbGFzdF9iaXRzID0gaGVyZV9iaXRzOwogICAgICAgICAgICBsYXN0X29wID0gaGVyZV9vcDsKICAgICAgICAgICAgbGFzdF92YWwgPSBoZXJlX3ZhbDsKICAgICAgICAgICAgZm9yICg7OykgewogICAgICAgICAgICAgIGhlcmUgPSBzdGF0ZS5sZW5jb2RlW2xhc3RfdmFsICsKICAgICAgICAgICAgICAgICAgICAgICgoaG9sZCAmICgoMSA8PCAobGFzdF9iaXRzICsgbGFzdF9vcCkpIC0gMSkpLypCSVRTKGxhc3QuYml0cyArIGxhc3Qub3ApKi8gPj4gbGFzdF9iaXRzKV07CiAgICAgICAgICAgICAgaGVyZV9iaXRzID0gaGVyZSA+Pj4gMjQ7CiAgICAgICAgICAgICAgaGVyZV9vcCA9IChoZXJlID4+PiAxNikgJiAweGZmOwogICAgICAgICAgICAgIGhlcmVfdmFsID0gaGVyZSAmIDB4ZmZmZjsKCiAgICAgICAgICAgICAgaWYgKChsYXN0X2JpdHMgKyBoZXJlX2JpdHMpIDw9IGJpdHMpIHsgYnJlYWs7IH0KICAgICAgICAgICAgICAvLy0tLSBQVUxMQllURSgpIC0tLS8vCiAgICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8tLS0gRFJPUEJJVFMobGFzdC5iaXRzKSAtLS0vLwogICAgICAgICAgICBob2xkID4+Pj0gbGFzdF9iaXRzOwogICAgICAgICAgICBiaXRzIC09IGxhc3RfYml0czsKICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICBzdGF0ZS5iYWNrICs9IGxhc3RfYml0czsKICAgICAgICAgIH0KICAgICAgICAgIC8vLS0tIERST1BCSVRTKGhlcmUuYml0cykgLS0tLy8KICAgICAgICAgIGhvbGQgPj4+PSBoZXJlX2JpdHM7CiAgICAgICAgICBiaXRzIC09IGhlcmVfYml0czsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIHN0YXRlLmJhY2sgKz0gaGVyZV9iaXRzOwogICAgICAgICAgc3RhdGUubGVuZ3RoID0gaGVyZV92YWw7CiAgICAgICAgICBpZiAoaGVyZV9vcCA9PT0gMCkgewogICAgICAgICAgICAvL1RyYWNldnYoKHN0ZGVyciwgaGVyZS52YWwgPj0gMHgyMCAmJiBoZXJlLnZhbCA8IDB4N2YgPwogICAgICAgICAgICAvLyAgICAgICAgImluZmxhdGU6ICAgICAgICAgbGl0ZXJhbCAnJWMnXG4iIDoKICAgICAgICAgICAgLy8gICAgICAgICJpbmZsYXRlOiAgICAgICAgIGxpdGVyYWwgMHglMDJ4XG4iLCBoZXJlLnZhbCkpOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gTElUOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChoZXJlX29wICYgMzIpIHsKICAgICAgICAgICAgLy9UcmFjZXZ2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgICAgIGVuZCBvZiBibG9ja1xuIikpOwogICAgICAgICAgICBzdGF0ZS5iYWNrID0gLTE7CiAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBUWVBFOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChoZXJlX29wICYgNjQpIHsKICAgICAgICAgICAgc3RybS5tc2cgPSAnaW52YWxpZCBsaXRlcmFsL2xlbmd0aCBjb2RlJzsKICAgICAgICAgICAgc3RhdGUubW9kZSA9IEJBRDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgICAgICAgICBzdGF0ZS5leHRyYSA9IGhlcmVfb3AgJiAxNTsKICAgICAgICAgIHN0YXRlLm1vZGUgPSBMRU5FWFQ7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBMRU5FWFQ6CiAgICAgICAgICBpZiAoc3RhdGUuZXh0cmEpIHsKICAgICAgICAgICAgLy89PT0gTkVFREJJVFMoc3RhdGUuZXh0cmEpOwogICAgICAgICAgICBuID0gc3RhdGUuZXh0cmE7CiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgbikgewogICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgICBzdGF0ZS5sZW5ndGggKz0gaG9sZCAmICgoMSA8PCBzdGF0ZS5leHRyYSkgLSAxKS8qQklUUyhzdGF0ZS5leHRyYSkqLzsKICAgICAgICAgICAgLy8tLS0gRFJPUEJJVFMoc3RhdGUuZXh0cmEpIC0tLS8vCiAgICAgICAgICAgIGhvbGQgPj4+PSBzdGF0ZS5leHRyYTsKICAgICAgICAgICAgYml0cyAtPSBzdGF0ZS5leHRyYTsKICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICBzdGF0ZS5iYWNrICs9IHN0YXRlLmV4dHJhOwogICAgICAgICAgfQogICAgICAgICAgLy9UcmFjZXZ2KChzdGRlcnIsICJpbmZsYXRlOiAgICAgICAgIGxlbmd0aCAldVxuIiwgc3RhdGUubGVuZ3RoKSk7CiAgICAgICAgICBzdGF0ZS53YXMgPSBzdGF0ZS5sZW5ndGg7CiAgICAgICAgICBzdGF0ZS5tb2RlID0gRElTVDsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIERJU1Q6CiAgICAgICAgICBmb3IgKDs7KSB7CiAgICAgICAgICAgIGhlcmUgPSBzdGF0ZS5kaXN0Y29kZVtob2xkICYgKCgxIDw8IHN0YXRlLmRpc3RiaXRzKSAtIDEpXTsvKkJJVFMoc3RhdGUuZGlzdGJpdHMpKi8KICAgICAgICAgICAgaGVyZV9iaXRzID0gaGVyZSA+Pj4gMjQ7CiAgICAgICAgICAgIGhlcmVfb3AgPSAoaGVyZSA+Pj4gMTYpICYgMHhmZjsKICAgICAgICAgICAgaGVyZV92YWwgPSBoZXJlICYgMHhmZmZmOwoKICAgICAgICAgICAgaWYgKChoZXJlX2JpdHMpIDw9IGJpdHMpIHsgYnJlYWs7IH0KICAgICAgICAgICAgLy8tLS0gUFVMTEJZVEUoKSAtLS0vLwogICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICB9CiAgICAgICAgICBpZiAoKGhlcmVfb3AgJiAweGYwKSA9PT0gMCkgewogICAgICAgICAgICBsYXN0X2JpdHMgPSBoZXJlX2JpdHM7CiAgICAgICAgICAgIGxhc3Rfb3AgPSBoZXJlX29wOwogICAgICAgICAgICBsYXN0X3ZhbCA9IGhlcmVfdmFsOwogICAgICAgICAgICBmb3IgKDs7KSB7CiAgICAgICAgICAgICAgaGVyZSA9IHN0YXRlLmRpc3Rjb2RlW2xhc3RfdmFsICsKICAgICAgICAgICAgICAgICAgICAgICgoaG9sZCAmICgoMSA8PCAobGFzdF9iaXRzICsgbGFzdF9vcCkpIC0gMSkpLypCSVRTKGxhc3QuYml0cyArIGxhc3Qub3ApKi8gPj4gbGFzdF9iaXRzKV07CiAgICAgICAgICAgICAgaGVyZV9iaXRzID0gaGVyZSA+Pj4gMjQ7CiAgICAgICAgICAgICAgaGVyZV9vcCA9IChoZXJlID4+PiAxNikgJiAweGZmOwogICAgICAgICAgICAgIGhlcmVfdmFsID0gaGVyZSAmIDB4ZmZmZjsKCiAgICAgICAgICAgICAgaWYgKChsYXN0X2JpdHMgKyBoZXJlX2JpdHMpIDw9IGJpdHMpIHsgYnJlYWs7IH0KICAgICAgICAgICAgICAvLy0tLSBQVUxMQllURSgpIC0tLS8vCiAgICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy8tLS0gRFJPUEJJVFMobGFzdC5iaXRzKSAtLS0vLwogICAgICAgICAgICBob2xkID4+Pj0gbGFzdF9iaXRzOwogICAgICAgICAgICBiaXRzIC09IGxhc3RfYml0czsKICAgICAgICAgICAgLy8tLS0vLwogICAgICAgICAgICBzdGF0ZS5iYWNrICs9IGxhc3RfYml0czsKICAgICAgICAgIH0KICAgICAgICAgIC8vLS0tIERST1BCSVRTKGhlcmUuYml0cykgLS0tLy8KICAgICAgICAgIGhvbGQgPj4+PSBoZXJlX2JpdHM7CiAgICAgICAgICBiaXRzIC09IGhlcmVfYml0czsKICAgICAgICAgIC8vLS0tLy8KICAgICAgICAgIHN0YXRlLmJhY2sgKz0gaGVyZV9iaXRzOwogICAgICAgICAgaWYgKGhlcmVfb3AgJiA2NCkgewogICAgICAgICAgICBzdHJtLm1zZyA9ICdpbnZhbGlkIGRpc3RhbmNlIGNvZGUnOwogICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICBicmVhazsKICAgICAgICAgIH0KICAgICAgICAgIHN0YXRlLm9mZnNldCA9IGhlcmVfdmFsOwogICAgICAgICAgc3RhdGUuZXh0cmEgPSAoaGVyZV9vcCkgJiAxNTsKICAgICAgICAgIHN0YXRlLm1vZGUgPSBESVNURVhUOwogICAgICAgICAgLyogZmFsbHMgdGhyb3VnaCAqLwogICAgICAgIGNhc2UgRElTVEVYVDoKICAgICAgICAgIGlmIChzdGF0ZS5leHRyYSkgewogICAgICAgICAgICAvLz09PSBORUVEQklUUyhzdGF0ZS5leHRyYSk7CiAgICAgICAgICAgIG4gPSBzdGF0ZS5leHRyYTsKICAgICAgICAgICAgd2hpbGUgKGJpdHMgPCBuKSB7CiAgICAgICAgICAgICAgaWYgKGhhdmUgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICAgICAgaGF2ZS0tOwogICAgICAgICAgICAgIGhvbGQgKz0gaW5wdXRbbmV4dCsrXSA8PCBiaXRzOwogICAgICAgICAgICAgIGJpdHMgKz0gODsKICAgICAgICAgICAgfQogICAgICAgICAgICAvLz09PS8vCiAgICAgICAgICAgIHN0YXRlLm9mZnNldCArPSBob2xkICYgKCgxIDw8IHN0YXRlLmV4dHJhKSAtIDEpLypCSVRTKHN0YXRlLmV4dHJhKSovOwogICAgICAgICAgICAvLy0tLSBEUk9QQklUUyhzdGF0ZS5leHRyYSkgLS0tLy8KICAgICAgICAgICAgaG9sZCA+Pj49IHN0YXRlLmV4dHJhOwogICAgICAgICAgICBiaXRzIC09IHN0YXRlLmV4dHJhOwogICAgICAgICAgICAvLy0tLS8vCiAgICAgICAgICAgIHN0YXRlLmJhY2sgKz0gc3RhdGUuZXh0cmE7CiAgICAgICAgICB9CiAgLy8jaWZkZWYgSU5GTEFURV9TVFJJQ1QKICAgICAgICAgIGlmIChzdGF0ZS5vZmZzZXQgPiBzdGF0ZS5kbWF4KSB7CiAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgZGlzdGFuY2UgdG9vIGZhciBiYWNrJzsKICAgICAgICAgICAgc3RhdGUubW9kZSA9IEJBRDsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICB9CiAgLy8jZW5kaWYKICAgICAgICAgIC8vVHJhY2V2digoc3RkZXJyLCAiaW5mbGF0ZTogICAgICAgICBkaXN0YW5jZSAldVxuIiwgc3RhdGUub2Zmc2V0KSk7CiAgICAgICAgICBzdGF0ZS5tb2RlID0gTUFUQ0g7CiAgICAgICAgICAvKiBmYWxscyB0aHJvdWdoICovCiAgICAgICAgY2FzZSBNQVRDSDoKICAgICAgICAgIGlmIChsZWZ0ID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgY29weSA9IF9vdXQgLSBsZWZ0OwogICAgICAgICAgaWYgKHN0YXRlLm9mZnNldCA+IGNvcHkpIHsgICAgICAgICAvKiBjb3B5IGZyb20gd2luZG93ICovCiAgICAgICAgICAgIGNvcHkgPSBzdGF0ZS5vZmZzZXQgLSBjb3B5OwogICAgICAgICAgICBpZiAoY29weSA+IHN0YXRlLndoYXZlKSB7CiAgICAgICAgICAgICAgaWYgKHN0YXRlLnNhbmUpIHsKICAgICAgICAgICAgICAgIHN0cm0ubXNnID0gJ2ludmFsaWQgZGlzdGFuY2UgdG9vIGZhciBiYWNrJzsKICAgICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgICB9CiAgLy8gKCEpIFRoaXMgYmxvY2sgaXMgZGlzYWJsZWQgaW4gemxpYiBkZWZhdWx0cywKICAvLyBkb24ndCBlbmFibGUgaXQgZm9yIGJpbmFyeSBjb21wYXRpYmlsaXR5CiAgLy8jaWZkZWYgSU5GTEFURV9BTExPV19JTlZBTElEX0RJU1RBTkNFX1RPT0ZBUl9BUlJSCiAgLy8gICAgICAgICAgVHJhY2UoKHN0ZGVyciwgImluZmxhdGUuYyB0b28gZmFyXG4iKSk7CiAgLy8gICAgICAgICAgY29weSAtPSBzdGF0ZS53aGF2ZTsKICAvLyAgICAgICAgICBpZiAoY29weSA+IHN0YXRlLmxlbmd0aCkgeyBjb3B5ID0gc3RhdGUubGVuZ3RoOyB9CiAgLy8gICAgICAgICAgaWYgKGNvcHkgPiBsZWZ0KSB7IGNvcHkgPSBsZWZ0OyB9CiAgLy8gICAgICAgICAgbGVmdCAtPSBjb3B5OwogIC8vICAgICAgICAgIHN0YXRlLmxlbmd0aCAtPSBjb3B5OwogIC8vICAgICAgICAgIGRvIHsKICAvLyAgICAgICAgICAgIG91dHB1dFtwdXQrK10gPSAwOwogIC8vICAgICAgICAgIH0gd2hpbGUgKC0tY29weSk7CiAgLy8gICAgICAgICAgaWYgKHN0YXRlLmxlbmd0aCA9PT0gMCkgeyBzdGF0ZS5tb2RlID0gTEVOOyB9CiAgLy8gICAgICAgICAgYnJlYWs7CiAgLy8jZW5kaWYKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiAoY29weSA+IHN0YXRlLnduZXh0KSB7CiAgICAgICAgICAgICAgY29weSAtPSBzdGF0ZS53bmV4dDsKICAgICAgICAgICAgICBmcm9tID0gc3RhdGUud3NpemUgLSBjb3B5OwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIGZyb20gPSBzdGF0ZS53bmV4dCAtIGNvcHk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGNvcHkgPiBzdGF0ZS5sZW5ndGgpIHsgY29weSA9IHN0YXRlLmxlbmd0aDsgfQogICAgICAgICAgICBmcm9tX3NvdXJjZSA9IHN0YXRlLndpbmRvdzsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgeyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8qIGNvcHkgZnJvbSBvdXRwdXQgKi8KICAgICAgICAgICAgZnJvbV9zb3VyY2UgPSBvdXRwdXQ7CiAgICAgICAgICAgIGZyb20gPSBwdXQgLSBzdGF0ZS5vZmZzZXQ7CiAgICAgICAgICAgIGNvcHkgPSBzdGF0ZS5sZW5ndGg7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAoY29weSA+IGxlZnQpIHsgY29weSA9IGxlZnQ7IH0KICAgICAgICAgIGxlZnQgLT0gY29weTsKICAgICAgICAgIHN0YXRlLmxlbmd0aCAtPSBjb3B5OwogICAgICAgICAgZG8gewogICAgICAgICAgICBvdXRwdXRbcHV0KytdID0gZnJvbV9zb3VyY2VbZnJvbSsrXTsKICAgICAgICAgIH0gd2hpbGUgKC0tY29weSk7CiAgICAgICAgICBpZiAoc3RhdGUubGVuZ3RoID09PSAwKSB7IHN0YXRlLm1vZGUgPSBMRU47IH0KICAgICAgICAgIGJyZWFrOwogICAgICAgIGNhc2UgTElUOgogICAgICAgICAgaWYgKGxlZnQgPT09IDApIHsgYnJlYWsgaW5mX2xlYXZlOyB9CiAgICAgICAgICBvdXRwdXRbcHV0KytdID0gc3RhdGUubGVuZ3RoOwogICAgICAgICAgbGVmdC0tOwogICAgICAgICAgc3RhdGUubW9kZSA9IExFTjsKICAgICAgICAgIGJyZWFrOwogICAgICAgIGNhc2UgQ0hFQ0s6CiAgICAgICAgICBpZiAoc3RhdGUud3JhcCkgewogICAgICAgICAgICAvLz09PSBORUVEQklUUygzMik7CiAgICAgICAgICAgIHdoaWxlIChiaXRzIDwgMzIpIHsKICAgICAgICAgICAgICBpZiAoaGF2ZSA9PT0gMCkgeyBicmVhayBpbmZfbGVhdmU7IH0KICAgICAgICAgICAgICBoYXZlLS07CiAgICAgICAgICAgICAgLy8gVXNlICd8JyBpbnN0ZWFkIG9mICcrJyB0byBtYWtlIHN1cmUgdGhhdCByZXN1bHQgaXMgc2lnbmVkCiAgICAgICAgICAgICAgaG9sZCB8PSBpbnB1dFtuZXh0KytdIDw8IGJpdHM7CiAgICAgICAgICAgICAgYml0cyArPSA4OwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09Ly8KICAgICAgICAgICAgX291dCAtPSBsZWZ0OwogICAgICAgICAgICBzdHJtLnRvdGFsX291dCArPSBfb3V0OwogICAgICAgICAgICBzdGF0ZS50b3RhbCArPSBfb3V0OwogICAgICAgICAgICBpZiAoX291dCkgewogICAgICAgICAgICAgIHN0cm0uYWRsZXIgPSBzdGF0ZS5jaGVjayA9CiAgICAgICAgICAgICAgICAgIC8qVVBEQVRFKHN0YXRlLmNoZWNrLCBwdXQgLSBfb3V0LCBfb3V0KTsqLwogICAgICAgICAgICAgICAgICAoc3RhdGUuZmxhZ3MgPyBjcmMzMl8xKHN0YXRlLmNoZWNrLCBvdXRwdXQsIF9vdXQsIHB1dCAtIF9vdXQpIDogYWRsZXIzMl8xKHN0YXRlLmNoZWNrLCBvdXRwdXQsIF9vdXQsIHB1dCAtIF9vdXQpKTsKCiAgICAgICAgICAgIH0KICAgICAgICAgICAgX291dCA9IGxlZnQ7CiAgICAgICAgICAgIC8vIE5COiBjcmMzMiBzdG9yZWQgYXMgc2lnbmVkIDMyLWJpdCBpbnQsIHpzd2FwMzIgcmV0dXJucyBzaWduZWQgdG9vCiAgICAgICAgICAgIGlmICgoc3RhdGUuZmxhZ3MgPyBob2xkIDogenN3YXAzMihob2xkKSkgIT09IHN0YXRlLmNoZWNrKSB7CiAgICAgICAgICAgICAgc3RybS5tc2cgPSAnaW5jb3JyZWN0IGRhdGEgY2hlY2snOwogICAgICAgICAgICAgIHN0YXRlLm1vZGUgPSBCQUQ7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy89PT0gSU5JVEJJVFMoKTsKICAgICAgICAgICAgaG9sZCA9IDA7CiAgICAgICAgICAgIGJpdHMgPSAwOwogICAgICAgICAgICAvLz09PS8vCiAgICAgICAgICAgIC8vVHJhY2V2KChzdGRlcnIsICJpbmZsYXRlOiAgIGNoZWNrIG1hdGNoZXMgdHJhaWxlclxuIikpOwogICAgICAgICAgfQogICAgICAgICAgc3RhdGUubW9kZSA9IExFTkdUSDsKICAgICAgICAgIC8qIGZhbGxzIHRocm91Z2ggKi8KICAgICAgICBjYXNlIExFTkdUSDoKICAgICAgICAgIGlmIChzdGF0ZS53cmFwICYmIHN0YXRlLmZsYWdzKSB7CiAgICAgICAgICAgIC8vPT09IE5FRURCSVRTKDMyKTsKICAgICAgICAgICAgd2hpbGUgKGJpdHMgPCAzMikgewogICAgICAgICAgICAgIGlmIChoYXZlID09PSAwKSB7IGJyZWFrIGluZl9sZWF2ZTsgfQogICAgICAgICAgICAgIGhhdmUtLTsKICAgICAgICAgICAgICBob2xkICs9IGlucHV0W25leHQrK10gPDwgYml0czsKICAgICAgICAgICAgICBiaXRzICs9IDg7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgICBpZiAoaG9sZCAhPT0gKHN0YXRlLnRvdGFsICYgMHhmZmZmZmZmZikpIHsKICAgICAgICAgICAgICBzdHJtLm1zZyA9ICdpbmNvcnJlY3QgbGVuZ3RoIGNoZWNrJzsKICAgICAgICAgICAgICBzdGF0ZS5tb2RlID0gQkFEOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vPT09IElOSVRCSVRTKCk7CiAgICAgICAgICAgIGhvbGQgPSAwOwogICAgICAgICAgICBiaXRzID0gMDsKICAgICAgICAgICAgLy89PT0vLwogICAgICAgICAgICAvL1RyYWNldigoc3RkZXJyLCAiaW5mbGF0ZTogICBsZW5ndGggbWF0Y2hlcyB0cmFpbGVyXG4iKSk7CiAgICAgICAgICB9CiA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aXMubmFtZSAgICAgICA9ICcnOwogICAgLyogc3BhY2UgYXQgbmFtZSAob25seSB3aGVuIHJlYWRpbmcgaGVhZGVyKSAqLwogICAgLy8gdGhpcy5uYW1lX21heCAgID0gMDsKICAgIC8qIHBvaW50ZXIgdG8gemVyby10ZXJtaW5hdGVkIGNvbW1lbnQgb3IgWl9OVUxMICovCiAgICB0aGlzLmNvbW1lbnQgICAgPSAnJzsKICAgIC8qIHNwYWNlIGF0IGNvbW1lbnQgKG9ubHkgd2hlbiByZWFkaW5nIGhlYWRlcikgKi8KICAgIC8vIHRoaXMuY29tbV9tYXggICA9IDA7CiAgICAvKiB0cnVlIGlmIHRoZXJlIHdhcyBvciB3aWxsIGJlIGEgaGVhZGVyIGNyYyAqLwogICAgdGhpcy5oY3JjICAgICAgID0gMDsKICAgIC8qIHRydWUgd2hlbiBkb25lIHJlYWRpbmcgZ3ppcCBoZWFkZXIgKG5vdCB1c2VkIHdoZW4gd3JpdGluZyBhIGd6aXAgZmlsZSkgKi8KICAgIHRoaXMuZG9uZSAgICAgICA9IGZhbHNlOwogIH0KCiAgdmFyIGd6aGVhZGVyID0gR1poZWFkZXI7CgogIGNvbnN0IHRvU3RyaW5nID0gT2JqZWN0LnByb3RvdHlwZS50b1N0cmluZzsKCiAgLyogUHVibGljIGNvbnN0YW50cyA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09Ki8KICAvKiA9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0qLwoKICBjb25zdCB7CiAgICBaX05PX0ZMVVNILCBaX0ZJTklTSCwKICAgIFpfT0ssIFpfU1RSRUFNX0VORCwgWl9ORUVEX0RJQ1QsIFpfU1RSRUFNX0VSUk9SLCBaX0RBVEFfRVJST1IsIFpfTUVNX0VSUk9SCiAgfSA9IGNvbnN0YW50cyQyOwoKICAvKiA9PT09PT09PT09PT09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2tCaXRzZXQpIHsKICAgICAgICAgIHJlc3VsdE1hc2sgPSBuZXcgVWludDhBcnJheShkYXRhLndpZHRoICogZGF0YS5oZWlnaHQpOwogICAgICAgIH0KICAgICAgICB2YXIgYmxvY2tEYXRhQnVmZmVyID0gbmV3IEZsb2F0MzJBcnJheShibG9ja1dpZHRoICogYmxvY2tIZWlnaHQpOwoKICAgICAgICB2YXIgeHgsIHl5OwogICAgICAgIGZvciAodmFyIHkgPSAwOyB5IDw9IG51bVk7IHkrKykgewogICAgICAgICAgdmFyIHRoaXNCbG9ja0hlaWdodCA9ICh5ICE9PSBudW1ZKSA/IGJsb2NrSGVpZ2h0IDogKGRhdGEuaGVpZ2h0ICUgbnVtWSk7CiAgICAgICAgICBpZiAodGhpc0Jsb2NrSGVpZ2h0ID09PSAwKSB7CiAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgfQogICAgICAgICAgZm9yICh2YXIgeCA9IDA7IHggPD0gbnVtWDsgeCsrKSB7CiAgICAgICAgICAgIHZhciB0aGlzQmxvY2tXaWR0aCA9ICh4ICE9PSBudW1YKSA/IGJsb2NrV2lkdGggOiAoZGF0YS53aWR0aCAlIG51bVgpOwogICAgICAgICAgICBpZiAodGhpc0Jsb2NrV2lkdGggPT09IDApIHsKICAgICAgICAgICAgICBjb250aW51ZTsKICAgICAgICAgICAgfQoKICAgICAgICAgICAgdmFyIG91dFB0ciA9IHkgKiBkYXRhLndpZHRoICogYmxvY2tIZWlnaHQgKyB4ICogYmxvY2tXaWR0aDsKICAgICAgICAgICAgdmFyIG91dFN0cmlkZSA9IGRhdGEud2lkdGggLSB0aGlzQmxvY2tXaWR0aDsKCiAgICAgICAgICAgIHZhciBibG9jayA9IGRhdGEucGl4ZWxzLmJsb2Nrc1tibG9ja0lkeF07CgogICAgICAgICAgICB2YXIgYmxvY2tEYXRhLCBibG9ja1B0ciwgY29uc3RWYWx1ZTsKICAgICAgICAgICAgaWYgKGJsb2NrLmVuY29kaW5nIDwgMikgewogICAgICAgICAgICAgIC8vIGJsb2NrIGlzIGVpdGhlciB1bmNvbXByZXNzZWQgb3IgYml0LXN0dWZmZWQgKGVuY29kaW5ncyAwIGFuZCAxKQogICAgICAgICAgICAgIGlmIChibG9jay5lbmNvZGluZyA9PT0gMCkgewogICAgICAgICAgICAgICAgLy8gYmxvY2sgaXMgdW5jb21wcmVzc2VkCiAgICAgICAgICAgICAgICBibG9ja0RhdGEgPSBibG9jay5yYXdEYXRhOwogICAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgICAvLyBibG9jayBpcyBiaXQtc3R1ZmZlZAogICAgICAgICAgICAgICAgdW5zdHVmZihibG9jay5zdHVmZmVkRGF0YSwgYmxvY2suYml0c1BlclBpeGVsLCBibG9jay5udW1WYWxpZFBpeGVscywgYmxvY2sub2Zmc2V0LCBzY2FsZSwgYmxvY2tEYXRhQnVmZmVyLCBkYXRhLnBpeGVscy5tYXhWYWx1ZSk7CiAgICAgICAgICAgICAgICBibG9ja0RhdGEgPSBibG9ja0RhdGFCdWZmZXI7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGJsb2NrUHRyID0gMDsKICAgICAgICAgICAgfQogICAgICAgICAgICBlbHNlIGlmIChibG9jay5lbmNvZGluZyA9PT0gMikgewogICAgICAgICAgICAgIC8vIGJsb2NrIGlzIGFsbCAwCiAgICAgICAgICAgICAgY29uc3RWYWx1ZSA9IDA7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgLy8gYmxvY2sgaGFzIGNvbnN0YW50IHZhbHVlIChlbmNvZGluZyA9PT0gMykKICAgICAgICAgICAgICBjb25zdFZhbHVlID0gYmxvY2sub2Zmc2V0OwogICAgICAgICAgICB9CgogICAgICAgICAgICB2YXIgbWFza0J5dGU7CiAgICAgICAgICAgIGlmIChtYXNrQml0c2V0KSB7CiAgICAgICAgICAgICAgZm9yICh5eSA9IDA7IHl5IDwgdGhpc0Jsb2NrSGVpZ2h0OyB5eSsrKSB7CiAgICAgICAgICAgICAgICBpZiAob3V0UHRyICYgNykgewogICAgICAgICAgICAgICAgICAvLwogICAgICAgICAgICAgICAgICBtYXNrQnl0ZSA9IG1hc2tCaXRzZXRbb3V0UHRyID4+IDNdOwogICAgICAgICAgICAgICAgICBtYXNrQnl0ZSA8PD0gb3V0UHRyICYgNzsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGZvciAoeHggPSAwOyB4eCA8IHRoaXNCbG9ja1dpZHRoOyB4eCsrKSB7CiAgICAgICAgICAgICAgICAgIGlmICghKG91dFB0ciAmIDcpKSB7CiAgICAgICAgICAgICAgICAgICAgLy8gcmVhZCBuZXh0IGJ5dGUgZnJvbSBtYXNrCiAgICAgICAgICAgICAgICAgICAgbWFza0J5dGUgPSBtYXNrQml0c2V0W291dFB0ciA+PiAzXTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBpZiAobWFza0J5dGUgJiAxMjgpIHsKICAgICAgICAgICAgICAgICAgICAvLyBwaXhlbCBkYXRhIHByZXNlbnQKICAgICAgICAgICAgICAgICAgICBpZiAocmVzdWx0TWFzaykgewogICAgICAgICAgICAgICAgICAgICAgcmVzdWx0TWFza1tvdXRQdHJdID0gMTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgY3VycmVudFZhbHVlID0gKGJsb2NrLmVuY29kaW5nIDwgMikgPyBibG9ja0RhdGFbYmxvY2tQdHIrK10gOiBjb25zdFZhbHVlOwogICAgICAgICAgICAgICAgICAgIG1pblZhbHVlID0gbWluVmFsdWUgPiBjdXJyZW50VmFsdWUgPyBjdXJyZW50VmFsdWUgOiBtaW5WYWx1ZTsKICAgICAgICAgICAgICAgICAgICByZXN1bHRQaXhlbHNbb3V0UHRyKytdID0gY3VycmVudFZhbHVlOwogICAgICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgICAgIC8vIHBpeGVsIGRhdGEgbm90IHByZXNlbnQKICAgICAgICAgICAgICAgICAgICBpZiAocmVzdWx0TWFzaykgewogICAgICAgICAgICAgICAgICAgICAgcmVzdWx0TWFza1tvdXRQdHJdID0gMDsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgcmVzdWx0UGl4ZWxzW291dFB0cisrXSA9IG5vRGF0YVZhbHVlOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIG1hc2tCeXRlIDw8PSAxOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgICAgLy8gbWFzayBub3QgcHJlc2VudCwgc2ltcGx5IGNvcHkgYmxvY2sgb3ZlcgogICAgICAgICAgICAgIGlmIChibG9jay5lbmNvZGluZyA8IDIpIHsKICAgICAgICAgICAgICAgIC8vIGR1cGxpY2F0aW5nIHRoaXMgY29kZSBibG9jayBmb3IgcGVyZm9ybWFuY2UgcmVhc29ucwogICAgICAgICAgICAgICAgLy8gYmxvY2tEYXRhIGNhc2U6CiAgICAgICAgICAgICAgICBmb3IgKHl5ID0gMDsgeXkgPCB0aGlzQmxvY2tIZWlnaHQ7IHl5KyspIHsKICAgICAgICAgICAgICAgICAgZm9yICh4eCA9IDA7IHh4IDwgdGhpc0Jsb2NrV2lkdGg7IHh4KyspIHsKICAgICAgICAgICAgICAgICAgICBjdXJyZW50VmFsdWUgPSBibG9ja0RhdGFbYmxvY2tQdHIrK107CiAgICAgICAgICAgICAgICAgICAgbWluVmFsdWUgPSBtaW5WYWx1ZSA+IGN1cnJlbnRWYWx1ZSA/IGN1cnJlbnRWYWx1ZSA6IG1pblZhbHVlOwogICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHIrK10gPSBjdXJyZW50VmFsdWU7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAvLyBjb25zdFZhbHVlIGNhc2U6CiAgICAgICAgICAgICAgICBtaW5WYWx1ZSA9IG1pblZhbHVlID4gY29uc3RWYWx1ZSA/IGNvbnN0VmFsdWUgOiBtaW5WYWx1ZTsKICAgICAgICAgICAgICAgIGZvciAoeXkgPSAwOyB5eSA8IHRoaXNCbG9ja0hlaWdodDsgeXkrKykgewogICAgICAgICAgICAgICAgICBmb3IgKHh4ID0gMDsgeHggPCB0aGlzQmxvY2tXaWR0aDsgeHgrKykgewogICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHIrK10gPSBjb25zdFZhbHVlOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIG91dFB0ciArPSBvdXRTdHJpZGU7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmICgoYmxvY2suZW5jb2RpbmcgPT09IDEpICYmIChibG9ja1B0ciAhPT0gYmxvY2subnVtVmFsaWRQaXhlbHMpKSB7CiAgICAgICAgICAgICAgdGhyb3cgIkJsb2NrIGFuZCBNYXNrIGRvIG5vdCBtYXRjaCI7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgYmxvY2tJZHgrKzsKICAgICAgICAgIH0KICAgICAgICB9CgogICAgICAgIHJldHVybiB7CiAgICAgICAgICByZXN1bHRQaXhlbHM6IHJlc3VsdFBpeGVscywKICAgICAgICAgIHJlc3VsdE1hc2s6IHJlc3VsdE1hc2ssCiAgICAgICAgICBtaW5WYWx1ZTogbWluVmFsdWUKICAgICAgICB9OwogICAgICB9OwoKICAgICAgdmFyIGZvcm1hdEZpbGVJbmZvID0gZnVuY3Rpb24oZGF0YSkgewogICAgICAgIHJldHVybiB7CiAgICAgICAgICAiZmlsZUlkZW50aWZpZXJTdHJpbmciOiBkYXRhLmZpbGVJZGVudGlmaWVyU3RyaW5nLAogICAgICAgICAgImZpbGVWZXJzaW9uIjogZGF0YS5maWxlVmVyc2lvbiwKICAgICAgICAgICJpbWFnZVR5cGUiOiBkYXRhLmltYWdlVHlwZSwKICAgICAgICAgICJoZWlnaHQiOiBkYXRhLmhlaWdodCwKICAgICAgICAgICJ3aWR0aCI6IGRhdGEud2lkdGgsCiAgICAgICAgICAibWF4WkVycm9yIjogZGF0YS5tYXhaRXJyb3IsCiAgICAgICAgICAiZW9mT2Zmc2V0IjogZGF0YS5lb2ZPZmZzZXQsCiAgICAgICAgICAibWFzayI6IGRhdGEubWFzayA/IHsKICAgICAgICAgICAgIm51bUJsb2Nrc1giOiBkYXRhLm1hc2subnVtQmxvY2tzWCwKICAgICAgICAgICAgIm51bUJsb2Nrc1kiOiBkYXRhLm1hc2subnVtQmxvY2tzWSwKICAgICAgICAgICAgIm51bUJ5dGVzIjogZGF0YS5tYXNrLm51bUJ5dGVzLAogICAgICAgICAgICAibWF4VmFsdWUiOiBkYXRhLm1hc2subWF4VmFsdWUKICAgICAgICAgIH0gOiBudWxsLAogICAgICAgICAgInBpeGVscyI6IHsKICAgICAgICAgICAgIm51bUJsb2Nrc1giOiBkYXRhLnBpeGVscy5udW1CbG9ja3NYLAogICAgICAgICAgICAibnVtQmxvY2tzWSI6IGRhdGEucGl4ZWxzLm51bUJsb2Nrc1ksCiAgICAgICAgICAgICJudW1CeXRlcyI6IGRhdGEucGl4ZWxzLm51bUJ5dGVzLAogICAgICAgICAgICAibWF4VmFsdWUiOiBkYXRhLnBpeGVscy5tYXhWYWx1ZSwKICAgICAgICAgICAgIm5vRGF0YVZhbHVlIjogZGF0YS5ub0RhdGFWYWx1ZQogICAgICAgICAgfQogICAgICAgIH07CiAgICAgIH07CgogICAgICB2YXIgY29tcHV0ZVVzZWRCaXREZXB0aHMgPSBmdW5jdGlvbihkYXRhKSB7CiAgICAgICAgdmFyIG51bUJsb2NrcyA9IGRhdGEucGl4ZWxzLm51bUJsb2Nrc1ggKiBkYXRhLnBpeGVscy5udW1CbG9ja3NZOwogICAgICAgIHZhciBiaXREZXB0aHMgPSB7fTsKICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IG51bUJsb2NrczsgaSsrKSB7CiAgICAgICAgICB2YXIgYmxvY2sgPSBkYXRhLnBpeGVscy5ibG9ja3NbaV07CiAgICAgICAgICBpZiAoYmxvY2suZW5jb2RpbmcgPT09IDApIHsKICAgICAgICAgICAgYml0RGVwdGhzLmZsb2F0MzIgPSB0cnVlOwogICAgICAgICAgfSBlbHNlIGlmIChibG9jay5lbmNvZGluZyA9PT0gMSkgewogICAgICAgICAgICBiaXREZXB0aHNbYmxvY2suYml0c1BlclBpeGVsXSA9IHRydWU7CiAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICBiaXREZXB0aHNbMF0gPSB0cnVlOwogICAgICAgICAgfQogICAgICAgIH0KCiAgICAgICAgcmV0dXJuIE9iamVjdC5rZXlzKGJpdERlcHRocyk7CiAgICAgIH07CgogICAgICB2YXIgcGFyc2UgPSBmdW5jdGlvbihpbnB1dCwgZnAsIHNraXBNYXNrKSB7CiAgICAgICAgdmFyIGRhdGEgPSB7fTsKCiAgICAgICAgLy8gRmlsZSBoZWFkZXIKICAgICAgICB2YXIgZmlsZUlkVmlldyA9IG5ldyBVaW50OEFycmF5KGlucHV0LCBmcCwgMTApOwogICAgICAgIGRhdGEuZmlsZUlkZW50aWZpZXJTdHJpbmcgPSBTdHJpbmcuZnJvbUNoYXJDb2RlLmFwcGx5KG51bGwsIGZpbGVJZFZpZXcpOwogICAgICAgIGlmIChkYXRhLmZpbGVJZGVudGlmaWVyU3RyaW5nLnRyaW0oKSAhPT0gIkNudFpJbWFnZSIpIHsKICAgICAgICAgIHRocm93ICJVbmV4cGVjdGVkIGZpbGUgaWRlbnRpZmllciBzdHJpbmc6ICIgKyBkYXRhLmZpbGVJZGVudGlmaWVyU3RyaW5nOwogICAgICAgIH0KICAgICAgICBmcCArPSAxMDsKICAgICAgICB2YXIgdmlldyA9IG5ldyBEYXRhVmlldyhpbnB1dCwgZnAsIDI0KTsKICAgICAgICBkYXRhLmZpbGVWZXJzaW9uID0gdmlldy5nZXRJbnQzMigwLCB0cnVlKTsKICAgICAgICBkYXRhLmltYWdlVHlwZSA9IHZpZXcuZ2V0SW50MzIoNCwgdHJ1ZSk7CiAgICAgICAgZGF0YS5oZWlnaHQgPSB2aWV3LmdldFVpbnQzMig4LCB0cnVlKTsKICAgICAgICBkYXRhLndpZHRoID0gdmlldy5nZXRVaW50MzIoMTIsIHRydWUpOwogICAgICAgIGRhdGEubWF4WkVycm9yID0gdmlldy5nZXRGbG9hdDY0KDE2LCB0cnVlKTsKICAgICAgICBmcCArPSAyNDsKCiAgICAgICAgLy8gTWFzayBIZWFkZXIKICAgICAgICBpZiAoIXNraXBNYXNrKSB7CiAgICAgICAgICB2aWV3ID0gbmV3IERhdGFWaWV3KGlucHV0LCBmcCwgMTYpOwogICAgICAgICAgZGF0YS5tYXNrID0ge307CiAgICAgICAgICBkYXRhLm1hc2subnVtQmxvY2tzWSA9IHZpZXcuZ2V0VWludDMyKDAsIHRydWUpOwogICAgICAgICAgZGF0YS5tYXNrLm51bUJsb2Nrc1ggPSB2aWV3LmdldFVpbnQzMig0LCB0cnVlKTsKICAgICAgICAgIGRhdGEubWFzay5udW1CeXRlcyA9IHZpZXcuZ2V0VWludDMyKDgsIHRydWUpOwogICAgICAgICAgZGF0YS5tYXNrLm1heFZhbHVlID0gdmlldy5nZXRGbG9hdDMyKDEyLCB0cnVlKTsKICAgICAgICAgIGZwICs9IDE2OwoKICAgICAgICAgIC8vIE1hc2sgRGF0YQogICAgICAgICAgaWYgKGRhdGEubWFzay5udW1CeXRlcyA+IDApIHsKICAgICAgICAgICAgdmFyIGJpdHNldCA9IG5ldyBVaW50OEFycmF5KE1hdGguY2VpbChkYXRhLndpZHRoICogZGF0YS5oZWlnaHQgLyA4KSk7CiAgICAgICAgICAgIHZpZXcgPSBuZXcgRGF0YVZpZXcoaW5wdXQsIGZwLCBkYXRhLm1hc2subnVtQnl0ZXMpOwogICAgICAgICAgICB2YXIgY250ID0gdmlldy5nZXRJbnQxNigwLCB0cnVlKTsKICAgICAgICAgICAgdmFyIGlwID0gMiwgb3AgPSAwOwogICAgICAgICAgICBkbyB7CiAgICAgICAgICAgICAgaWYgKGNudCA+IDApIHsKICAgICAgICAgICAgICAgIHdoaWxlIChjbnQtLSkgeyBiaXRzZXRbb3ArK10gPSB2aWV3LmdldFVpbnQ4KGlwKyspOyB9CiAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgIHZhciB2YWwgPSB2aWV3LmdldFVpbnQ4KGlwKyspOwogICAgICAgICAgICAgICAgY250ID0gLWNudDsKICAgICAgICAgICAgICAgIHdoaWxlIChjbnQtLSkgeyBiaXRzZXRbb3ArK10gPSB2YWw7IH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgY250ID0gdmlldy5nZXRJbnQxNihpcCwgdHJ1ZSk7CiAgICAgICAgICAgICAgaXAgKz0gMjsKICAgICAgICAgICAgfSB3aGlsZSAoaXAgPCBkYXRhLm1hc2subnVtQnl0ZXMpOwogICAgICAgICAgICBpZiAoKGNudCAhPT0gLTMyNzY4KSB8fCAob3AgPCBiaXRzZXQubGVuZ3RoKSkgewogICAgICAgICAgICAgIHRocm93ICJVbmV4cGVjdGVkIGVuZCBvZiBtYXNrIFJMRSBlbmNvZGluZyI7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZGF0YS5tYXNrLmJpdHNldCA9IGJpdHNldDsKICAgICAgICAgICAgZnAgKz0gZGF0YS5tYXNrLm51bUJ5dGVzOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSBpZiAoKGRhdGEubWFzay5udW1CeXRlcyB8IGRhdGEubWFzay5udW1CbG9ja3NZIHwgZGF0YS5tYXNrLm1heFZhbHVlKSA9PT0gMCkgeyAgLy8gU3B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lIG51bWJlciBvZiBibG9ja3MuCiAgICAgICAgdmFyIGFjdHVhbE51bUJsb2Nrc1ggPSBudW1CbG9ja3NYICsgKChkYXRhLndpZHRoICUgbnVtQmxvY2tzWCkgPiAwID8gMSA6IDApOwogICAgICAgIHZhciBhY3R1YWxOdW1CbG9ja3NZID0gbnVtQmxvY2tzWSArICgoZGF0YS5oZWlnaHQgJSBudW1CbG9ja3NZKSA+IDAgPyAxIDogMCk7CiAgICAgICAgZGF0YS5waXhlbHMuYmxvY2tzID0gbmV3IEFycmF5KGFjdHVhbE51bUJsb2Nrc1ggKiBhY3R1YWxOdW1CbG9ja3NZKTsKICAgICAgICB2YXIgYmxvY2tJID0gMDsKICAgICAgICBmb3IgKHZhciBibG9ja1kgPSAwOyBibG9ja1kgPCBhY3R1YWxOdW1CbG9ja3NZOyBibG9ja1krKykgewogICAgICAgICAgZm9yICh2YXIgYmxvY2tYID0gMDsgYmxvY2tYIDwgYWN0dWFsTnVtQmxvY2tzWDsgYmxvY2tYKyspIHsKCiAgICAgICAgICAgIC8vIEJsb2NrCiAgICAgICAgICAgIHZhciBzaXplID0gMDsKICAgICAgICAgICAgdmFyIGJ5dGVzTGVmdCA9IGlucHV0LmJ5dGVMZW5ndGggLSBmcDsKICAgICAgICAgICAgdmlldyA9IG5ldyBEYXRhVmlldyhpbnB1dCwgZnAsIE1hdGgubWluKDEwLCBieXRlc0xlZnQpKTsKICAgICAgICAgICAgdmFyIGJsb2NrID0ge307CiAgICAgICAgICAgIGRhdGEucGl4ZWxzLmJsb2Nrc1tibG9ja0krK10gPSBibG9jazsKICAgICAgICAgICAgdmFyIGhlYWRlckJ5dGUgPSB2aWV3LmdldFVpbnQ4KDApOyBzaXplKys7CiAgICAgICAgICAgIGJsb2NrLmVuY29kaW5nID0gaGVhZGVyQnl0ZSAmIDYzOwogICAgICAgICAgICBpZiAoYmxvY2suZW5jb2RpbmcgPiAzKSB7CiAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgYmxvY2sgZW5jb2RpbmcgKCIgKyBibG9jay5lbmNvZGluZyArICIpIjsKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiAoYmxvY2suZW5jb2RpbmcgPT09IDIpIHsKICAgICAgICAgICAgICBmcCsrOwogICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmICgoaGVhZGVyQnl0ZSAhPT0gMCkgJiYgKGhlYWRlckJ5dGUgIT09IDIpKSB7CiAgICAgICAgICAgICAgaGVhZGVyQnl0ZSA+Pj0gNjsKICAgICAgICAgICAgICBibG9jay5vZmZzZXRUeXBlID0gaGVhZGVyQnl0ZTsKICAgICAgICAgICAgICBpZiAoaGVhZGVyQnl0ZSA9PT0gMikgewogICAgICAgICAgICAgICAgYmxvY2sub2Zmc2V0ID0gdmlldy5nZXRJbnQ4KDEpOyBzaXplKys7CiAgICAgICAgICAgICAgfSBlbHNlIGlmIChoZWFkZXJCeXRlID09PSAxKSB7CiAgICAgICAgICAgICAgICBibG9jay5vZmZzZXQgPSB2aWV3LmdldEludDE2KDEsIHRydWUpOyBzaXplICs9IDI7CiAgICAgICAgICAgICAgfSBlbHNlIGlmIChoZWFkZXJCeXRlID09PSAwKSB7CiAgICAgICAgICAgICAgICBibG9jay5vZmZzZXQgPSB2aWV3LmdldEZsb2F0MzIoMSwgdHJ1ZSk7IHNpemUgKz0gNDsKICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgYmxvY2sgb2Zmc2V0IHR5cGUiOwogICAgICAgICAgICAgIH0KCiAgICAgICAgICAgICAgaWYgKGJsb2NrLmVuY29kaW5nID09PSAxKSB7CiAgICAgICAgICAgICAgICBoZWFkZXJCeXRlID0gdmlldy5nZXRVaW50OChzaXplKTsgc2l6ZSsrOwogICAgICAgICAgICAgICAgYmxvY2suYml0c1BlclBpeGVsID0gaGVhZGVyQnl0ZSAmIDYzOwogICAgICAgICAgICAgICAgaGVhZGVyQnl0ZSA+Pj0gNjsKICAgICAgICAgICAgICAgIGJsb2NrLm51bVZhbGlkUGl4ZWxzVHlwZSA9IGhlYWRlckJ5dGU7CiAgICAgICAgICAgICAgICBpZiAoaGVhZGVyQnl0ZSA9PT0gMikgewogICAgICAgICAgICAgICAgICBibG9jay5udW1WYWxpZFBpeGVscyA9IHZpZXcuZ2V0VWludDgoc2l6ZSk7IHNpemUrKzsKICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAoaGVhZGVyQnl0ZSA9PT0gMSkgewogICAgICAgICAgICAgICAgICBibG9jay5udW1WYWxpZFBpeGVscyA9IHZpZXcuZ2V0VWludDE2KHNpemUsIHRydWUpOyBzaXplICs9IDI7CiAgICAgICAgICAgICAgICB9IGVsc2UgaWYgKGhlYWRlckJ5dGUgPT09IDApIHsKICAgICAgICAgICAgICAgICAgYmxvY2subnVtVmFsaWRQaXhlbHMgPSB2aWV3LmdldFVpbnQzMihzaXplLCB0cnVlKTsgc2l6ZSArPSA0OwogICAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgdmFsaWQgcGl4ZWwgY291bnQgdHlwZSI7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGZwICs9IHNpemU7CgogICAgICAgICAgICBpZiAoYmxvY2suZW5jb2RpbmcgPT09IDMpIHsKICAgICAgICAgICAgICBjb250aW51ZTsKICAgICAgICAgICAgfQoKICAgICAgICAgICAgdmFyIGFycmF5QnVmLCBzdG9yZTg7CiAgICAgICAgICAgIGlmIChibG9jay5lbmNvZGluZyA9PT0gMCkgewogICAgICAgICAgICAgIHZhciBudW1QaXhlbHMgPSAoZGF0YS5waXhlbHMubnVtQnl0ZXMgLSAxKSAvIDQ7CiAgICAgICAgICAgICAgaWYgKG51bVBpeGVscyAhPT0gTWF0aC5mbG9vcihudW1QaXhlbHMpKSB7CiAgICAgICAgICAgICAgICB0aHJvdyAidW5jb21wcmVzc2VkIGJsb2NrIGhhcyBpbnZhbGlkIGxlbmd0aCI7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGFycmF5QnVmID0gbmV3IEFycmF5QnVmZmVyKG51bVBpeGVscyAqIDQpOwogICAgICAgICAgICAgIHN0b3JlOCA9IG5ldyBVaW50OEFycmF5KGFycmF5QnVmKTsKICAgICAgICAgICAgICBzdG9yZTguc2V0KG5ldyBVaW50OEFycmF5KGlucHV0LCBmcCwgbnVtUGl4ZWxzICogNCkpOwogICAgICAgICAgICAgIHZhciByYXdEYXRhID0gbmV3IEZsb2F0MzJBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgICAgYmxvY2sucmF3RGF0YSA9IHJhd0RhdGE7CiAgICAgICAgICAgICAgZnAgKz0gbnVtUGl4ZWxzICogNDsKICAgICAgICAgICAgfSBlbHNlIGlmIChibG9jay5lbmNvZGluZyA9PT0gMSkgewogICAgICAgICAgICAgIHZhciBkYXRhQnl0ZXMgPSBNYXRoLmNlaWwoYmxvY2subnVtVmFsaWRQaXhlbHMgKiBibG9jay5iaXRzUGVyUGl4ZWwgLyA4KTsKICAgICAgICAgICAgICB2YXIgZGF0YVdvcmRzID0gTWF0aC5jZWlsKGRhdGFCeXRlcyAvIDQpOwogICAgICAgICAgICAgIGFycmF5QnVmID0gbmV3IEFycmF5QnVmZmVyKGRhdGFXb3JkcyAqIDQpOwogICAgICAgICAgICAgIHN0b3JlOCA9IG5ldyBVaW50OEFycmF5KGFycmF5QnVmKTsKICAgICAgICAgICAgICBzdG9yZTguc2V0KG5ldyBVaW50OEFycmF5KGlucHV0LCBmcCwgZGF0YUJ5dGVzKSk7CiAgICAgICAgICAgICAgYmxvY2suc3R1ZmZlZERhdGEgPSBuZXcgVWludDMyQXJyYXkoYXJyYXlCdWYpOwogICAgICAgICAgICAgIGZwICs9IGRhdGFCeXRlczsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBkYXRh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ICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgdmFyIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJpdHNMZWZ0KTsKICAgICAgICAgICAgbiA9ICgoYnVmZmVyICYgYml0TWFzaykgPDwgbWlzc2luZ0JpdHMpICYgYml0TWFzazsKICAgICAgICAgICAgYnVmZmVyID0gc3JjW2krK107CiAgICAgICAgICAgIGJpdHNMZWZ0ID0gMzIgLSBtaXNzaW5nQml0czsKICAgICAgICAgICAgbiArPSAoYnVmZmVyID4+PiBiaXRzTGVmdCk7CiAgICAgICAgICB9CiAgICAgICAgICAvL3BpeGVsIHZhbHVlcyBtYXkgZXhjZWVkIG1heCBkdWUgdG8gcXVhbnRpemF0aW9uCiAgICAgICAgICBkZXN0W29dID0gbiA8IG5tYXggPyBvZmZzZXQgKyBuICogc2NhbGUgOiBtYXhWYWx1ZTsKICAgICAgICB9CiAgICAgICAgcmV0dXJuIGRlc3Q7CiAgICAgIH07CgogICAgICByZXR1cm4gQ250WkltYWdlOwogICAgfSkoKTsKCiAgICAvL3ZlcnNpb24gMi4gU3VwcG9ydHMgMi4xLCAyLjIsIDIuMwogICAgdmFyIExlcmMyRGVjb2RlID0gKGZ1bmN0aW9uKCkgewogICAgICAvLyBOb3RlOiBjdXJyZW50bHksIHRoaXMgbW9kdWxlIG9ubHkgaGFzIGFuIGltcGxlbWVudGF0aW9uIGZvciBkZWNvZGluZyBMRVJDIGRhdGEsIG5vdCBlbmNvZGluZy4gVGhlIG5hbWUgb2YKICAgICAgLy8gdGhlIGNsYXNzIHdhcyBjaG9zZW4gdG8gYmUgZnV0dXJlIHByb29mLCBmb2xsb3dpbmcgTGVyY0RlY29kZS4KCiAgICAgIC8qKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKgogICAgICAqIHByaXZhdGUgc3RhdGljIGNsYXNzIGJpdHN1dGZmZXIgdXNlZCBieSBMZXJjMkRlY29kZQogICAgICAqKioqKioqKioqKioqKioq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ApIHsKICAgICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMjsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgICAgbiA9IChidWZmZXIgPj4+IChiaXRzTGVmdCAtIGJpdHNQZXJQaXhlbCkpICYgYml0TWFzazsKICAgICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICBtaXNzaW5nQml0cyA9IChiaXRzUGVyUGl4ZWwgLSBiaXRzTGVmdCk7CiAgICAgICAgICAgICAgICBuID0gKChidWZmZXIgJiBiaXRNYXNrKSA8PCBtaXNzaW5nQml0cykgJiBiaXRNYXNrOwogICAgICAgICAgICAgICAgYnVmZmVyID0gc3JjW2krK107CiAgICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyIC0gbWlzc2luZ0JpdHM7CiAgICAgICAgICAgICAgICBuICs9IChidWZmZXIgPj4+IGJpdHNMZWZ0KTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZGVzdFtvXSA9IGx1dEFycltuXTsvL29mZnNldCArIGx1dEFycltuXSAqIHNjYWxlOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgbm1heCA9IE1hdGguY2VpbCgobWF4VmFsdWUgLSBvZmZzZXQpIC8gc2NhbGUpOwogICAgICAgICAgICBmb3IgKG8gPSAwOyBvIDwgbnVtUGl4ZWxzOyBvKyspIHsKICAgICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMjsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgICAgbiA9IChidWZmZXIgPj4+IChiaXRzTGVmdCAtIGJpdHNQZXJQaXhlbCkpICYgYml0TWFzazsKICAgICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICBtaXNzaW5nQml0cyA9IChiaXRzUGVyUGl4ZWwgLSBiaXRzTGVmdCk7CiAgICAgICAgICAgICAgICBuID0gKChidWZmZXIgJiBiaXRNYXNrKSA8PCBtaXNzaW5nQml0cykgJiBiaXRNYXNrOwogICAgICAgICAgICAgICAgYnVmZmVyID0gc3JjW2krK107CiAgICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyIC0gbWlzc2luZ0JpdHM7CiAgICAgICAgICAgICAgICBuICs9IChidWZmZXIgPj4+IGJpdHNMZWZ0KTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgLy9waXhlbCB2YWx1ZXMgbWF5IGV4Y2VlZCBtYXggZHVlIHRvIHF1YW50aXphdGlvbgogICAgICAgICAgICAgIGRlc3Rbb10gPSBuIDwgbm1heCA/IG9mZnNldCArIG4gKiBzY2FsZSA6IG1heFZhbHVlOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgfSwKCiAgICAgICAgdW5zdHVmZkxVVDogZnVuY3Rpb24oc3JjLCBiaXRzUGVyUGl4ZWwsIG51bVBpeGVscywgb2Zmc2V0LCBzY2FsZSwgbWF4VmFsdWUpIHsKICAgICAgICAgIHZhciBiaXRNYXNrID0gKDEgPDwgYml0c1BlclBpeGVsKSAtIDE7CiAgICAgICAgICB2YXIgaSA9IDAsIG8gPSAwLCBtaXNzaW5nQml0cyA9IDAsIGJpdHNMZWZ0ID0gMCwgbiA9IDA7CiAgICAgICAgICB2YXIgYnVmZmVyOwogICAgICAgICAgdmFyIGRlc3QgPSBbXTsKCiAgICAgICAgICAvLyBnZXQgcmlkIG9mIHRyYWlsaW5nIGJ5dGVzIHRoYXQgYXJlIGFscmVhZHkgcGFydCBvZiBuZXh0IGJsb2NrCiAgICAgICAgICB2YXIgbnVtSW52YWxpZFRhaWxCeXRlcyA9IHNyYy5sZW5ndGggKiA0IC0gTWF0aC5jZWlsKGJpdHNQZXJQaXhlbCAqIG51bVBpeGVscyAvIDgpOwogICAgICAgICAgc3JjW3NyYy5sZW5ndGggLSAxXSA8PD0gOCAqIG51bUludmFsaWRUYWlsQnl0ZXM7CgogICAgICAgICAgdmFyIG5tYXggPSBNYXRoLmNlaWwoKG1heFZhbHVlIC0gb2Zmc2V0KSAvIHNjYWxlKTsKICAgICAgICAgIGZvciAobyA9IDA7IG8gPCBudW1QaXhlbHM7IG8rKykgewogICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGlmIChiaXRzTGVmdCA+PSBiaXRzUGVyUGl4ZWwpIHsKICAgICAgICAgICAgICBuID0gKGJ1ZmZlciA+Pj4gKGJpdHNMZWZ0IC0gYml0c1BlclBpeGVsKSkgJiBiaXRNYXNrOwogICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICBtaXNzaW5nQml0cyA9IChiaXRzUGVyUGl4ZWwgLSBiaXRzTGVmdCk7CiAgICAgICAgICAgICAgbiA9ICgoYnVmZmVyICYgYml0TWFzaykgPDwgbWlzc2luZ0JpdHMpICYgYml0TWFzazsKICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyIC0gbWlzc2luZ0JpdHM7CiAgICAgICAgICAgICAgbiArPSAoYnVmZmVyID4+PiBiaXRzTGVmdCk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgLy9kZXN0LnB1c2gobik7CiAgICAgICAgICAgIGRlc3Rbb10gPSBuIDwgbm1heCA/IG9mZnNldCArIG4gKiBzY2FsZSA6IG1heFZhbHVlOwogICAgICAgICAgfQogICAgICAgICAgZGVzdC51bnNoaWZ0KG9mZnNldCk7Ly8xc3Qgb25lCiAgICAgICAgICByZXR1cm4gZGVzdDsKICAgICAgICB9LAoKICAgICAgICB1bnN0dWZmMjogZnVuY3Rpb24oc3JjLCBkZXN0LCBiaXRzUGVyUGl4ZWwsIG51bVBpeGVscywgbHV0QXJyLCBvZmZzZXQsIHNjYWxlLCBtYXhWYWx1ZSkgewogICAgICAgICAgdmFyIGJpdE1hc2sgPSAoMSA8PCBiaXRzUGVyUGl4ZWwpIC0gMTsKICAgICAgICAgIHZhciBpID0gMCwgbzsKICAgICAgICAgIHZhciBiaXRzTGVmdCA9IDAsIGJpdFBvcyA9IDA7CiAgICAgICAgICB2YXIgbiwgYnVmZmVyLCBtaXNzaW5nQml0czsKICAgICAgICAgIGlmIChsdXRBcnIpIHsKICAgICAgICAgICAgZm9yIChvID0gMDsgbyA8IG51bVBpeGVsczsgbysrKSB7CiAgICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID09PSAwKSB7CiAgICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICAgIGJpdHNMZWZ0ID0gMzI7CiAgICAgICAgICAgICAgICBiaXRQb3MgPSAwOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBpZiAoYml0c0xlZnQgPj0gYml0c1BlclBpeGVsKSB7CiAgICAgICAgICAgICAgICBuID0gKChidWZmZXIgPj4+IGJpdFBvcykgJiBiaXRNYXNrKTsKICAgICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICAgIGJpdFBvcyArPSBiaXRzUGVyUGl4ZWw7CiAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJpdHNMZWZ0KTsKICAgICAgICAgICAgICAgIG4gPSAoYnVmZmVyID4+PiBiaXRQb3MpICYgYml0TWFzazsKICAgICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMiAtIG1pc3NpbmdCaXRzOwogICAgICAgICAgICAgICAgbiB8PSAoYnVmZmVyICYgKCgxIDw8IG1pc3NpbmdCaXRzKSAtIDEpKSA8PCAoYml0c1BlclBpeGVsIC0gbWlzc2luZ0JpdHMpOwogICAgICAgICAgICAgICAgYml0UG9zID0gbWlzc2luZ0JpdHM7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGRlc3Rbb10gPSBsdXRBcnJbbl07CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgewogICAgICAgICAgICB2YXIgbm1heCA9IE1hdGguY2VpbCgobWF4VmFsdWUgLSBvZmZzZXQpIC8gc2NhbGUpOwogICAgICAgICAgICBmb3IgKG8gPSAwOyBvIDwgbnVtUGl4ZWxzOyBvKyspIHsKICAgICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMjsKICAgICAgICAgICAgICAgIGJpdFBvcyA9IDA7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGlmIChiaXRzTGVmdCA+PSBiaXRzUGVyUGl4ZWwpIHsKICAgICAgICAgICAgICAgIC8vbm8gdW5zaWduZWQgbGVmdCBzaGlmdAogICAgICAgICAgICAgICAgbiA9ICgoYnVmZmVyID4+PiBiaXRQb3MpICYgYml0TWFzayk7CiAgICAgICAgICAgICAgICBiaXRzTGVmdCAtPSBiaXRzUGVyUGl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uID0gMCwgYml0UG9zID0gMDsKICAgICAgICAgIHZhciBidWZmZXI7CiAgICAgICAgICB2YXIgZGVzdCA9IFtdOwogICAgICAgICAgdmFyIG5tYXggPSBNYXRoLmNlaWwoKG1heFZhbHVlIC0gb2Zmc2V0KSAvIHNjYWxlKTsKICAgICAgICAgIGZvciAobyA9IDA7IG8gPCBudW1QaXhlbHM7IG8rKykgewogICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyOwogICAgICAgICAgICAgIGJpdFBvcyA9IDA7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgIC8vbm8gdW5zaWduZWQgbGVmdCBzaGlmdAogICAgICAgICAgICAgIG4gPSAoKGJ1ZmZlciA+Pj4gYml0UG9zKSAmIGJpdE1hc2spOwogICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICBiaXRQb3MgKz0gYml0c1BlclBpeGVsOwogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJpdHNMZWZ0KTsKICAgICAgICAgICAgICBuID0gKGJ1ZmZlciA+Pj4gYml0UG9zKSAmIGJpdE1hc2s7Ly8oKGJ1ZmZlciAmIGJpdE1hc2spIDw8IG1pc3NpbmdCaXRzKSAmIGJpdE1hc2s7CiAgICAgICAgICAgICAgYnVmZmVyID0gc3JjW2krK107CiAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMiAtIG1pc3NpbmdCaXRzOwogICAgICAgICAgICAgIG4gfD0gKGJ1ZmZlciAmICgoMSA8PCBtaXNzaW5nQml0cykgLSAxKSkgPDwgKGJpdHNQZXJQaXhlbCAtIG1pc3NpbmdCaXRzKTsKICAgICAgICAgICAgICBiaXRQb3MgPSBtaXNzaW5nQml0czsKICAgICAgICAgICAgfQogICAgICAgICAgICAvL2Rlc3QucHVzaChuKTsKICAgICAgICAgICAgZGVzdFtvXSA9IG4gPCBubWF4ID8gb2Zmc2V0ICsgbiAqIHNjYWxlIDogbWF4VmFsdWU7CiAgICAgICAgICB9CiAgICAgICAgICBkZXN0LnVuc2hpZnQob2Zmc2V0KTsKICAgICAgICAgIHJldHVybiBkZXN0OwogICAgICAgIH0sCgogICAgICAgIG9yaWdpbmFsVW5zdHVmZjogZnVuY3Rpb24oc3JjLCBkZXN0LCBiaXRzUGVyUGl4ZWwsIG51bVBpeGVscykgewogICAgICAgICAgdmFyIGJpdE1hc2sgPSAoMSA8PCBiaXRzUGVyUGl4ZWwpIC0gMTsKICAgICAgICAgIHZhciBpID0gMCwgbzsKICAgICAgICAgIHZhciBiaXRzTGVmdCA9IDA7CiAgICAgICAgICB2YXIgbiwgYnVmZmVyLCBtaXNzaW5nQml0czsKCiAgICAgICAgICAvLyBnZXQgcmlkIG9mIHRyYWlsaW5nIGJ5dGVzIHRoYXQgYXJlIGFscmVhZHkgcGFydCBvZiBuZXh0IGJsb2NrCiAgICAgICAgICB2YXIgbnVtSW52YWxpZFRhaWxCeXRlcyA9IHNyYy5sZW5ndGggKiA0IC0gTWF0aC5jZWlsKGJpdHNQZXJQaXhlbCAqIG51bVBpeGVscyAvIDgpOwogICAgICAgICAgc3JjW3NyYy5sZW5ndGggLSAxXSA8PD0gOCAqIG51bUludmFsaWRUYWlsQnl0ZXM7CgogICAgICAgICAgZm9yIChvID0gMDsgbyA8IG51bVBpeGVsczsgbysrKSB7CiAgICAgICAgICAgIGlmIChiaXRzTGVmdCA9PT0gMCkgewogICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgIGJpdHNMZWZ0ID0gMzI7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgIG4gPSAoYnVmZmVyID4+PiAoYml0c0xlZnQgLSBiaXRzUGVyUGl4ZWwpKSAmIGJpdE1hc2s7CiAgICAgICAgICAgICAgYml0c0xlZnQgLT0gYml0c1BlclBpeGVsOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJpdHNMZWZ0KTsKICAgICAgICAgICAgICBuID0gKChidWZmZXIgJiBiaXRNYXNrKSA8PCBtaXNzaW5nQml0cykgJiBiaXRNYXNrOwogICAgICAgICAgICAgIGJ1ZmZlciA9IHNyY1tpKytdOwogICAgICAgICAgICAgIGJpdHNMZWZ0ID0gMzIgLSBtaXNzaW5nQml0czsKICAgICAgICAgICAgICBuICs9IChidWZmZXIgPj4+IGJpdHNMZWZ0KTsKICAgICAgICAgICAgfQogICAgICAgICAgICBkZXN0W29dID0gbjsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiBkZXN0OwogICAgICAgIH0sCgogICAgICAgIG9yaWdpbmFsVW5zdHVmZjI6IGZ1bmN0aW9uKHNyYywgZGVzdCwgYml0c1BlclBpeGVsLCBudW1QaXhlbHMpIHsKICAgICAgICAgIHZhciBiaXRNYXNrID0gKDEgPDwgYml0c1BlclBpeGVsKSAtIDE7CiAgICAgICAgICB2YXIgaSA9IDAsIG87CiAgICAgICAgICB2YXIgYml0c0xlZnQgPSAwLCBiaXRQb3MgPSAwOwogICAgICAgICAgdmFyIG4sIGJ1ZmZlciwgbWlzc2luZ0JpdHM7CiAgICAgICAgICAvL21pY3JvLW9wdGltaXphdGlvbnMKICAgICAgICAgIGZvciAobyA9IDA7IG8gPCBudW1QaXhlbHM7IG8rKykgewogICAgICAgICAgICBpZiAoYml0c0xlZnQgPT09IDApIHsKICAgICAgICAgICAgICBidWZmZXIgPSBzcmNbaSsrXTsKICAgICAgICAgICAgICBiaXRzTGVmdCA9IDMyOwogICAgICAgICAgICAgIGJpdFBvcyA9IDA7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGJpdHNMZWZ0ID49IGJpdHNQZXJQaXhlbCkgewogICAgICAgICAgICAgIC8vbm8gdW5zaWduZWQgbGVmdCBzaGlmdAogICAgICAgICAgICAgIG4gPSAoKGJ1ZmZlciA+Pj4gYml0UG9zKSAmIGJpdE1hc2spOwogICAgICAgICAgICAgIGJpdHNMZWZ0IC09IGJpdHNQZXJQaXhlbDsKICAgICAgICAgICAgICBiaXRQb3MgKz0gYml0c1BlclBpeGVsOwogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgIG1pc3NpbmdCaXRzID0gKGJpdHNQZXJQaXhlbCAtIGJpdHNMZWZ0KTsKICAgICAgICAgICAgICBuID0gKGJ1ZmZlciA+Pj4gYml0UG9zKSAmIGJpdE1hc2s7Ly8oKGJ1ZmZlciAmIGJpdE1hc2spIDw8IG1pc3NpbmdCaXRzKSAmIGJpdE1hc2s7CiAgICAgICAgICAgICAgYnVmZmVyID0gc3JjW2krK107CiAgICAgICAgICAgICAgYml0c0xlZnQgPSAzMiAtIG1pc3NpbmdCaXRzOwogICAgICAgICAgICAgIG4gfD0gKGJ1ZmZlciAmICgoMSA8PCBtaXNzaW5nQml0cykgLSAxKSkgPDwgKGJpdHNQZXJQaXhlbCAtIG1pc3NpbmdCaXRzKTsKICAgICAgICAgICAgICBiaXRQb3MgPSBtaXNzaW5nQml0czsKICAgICAgICAgICAgfQogICAgICAgICAgICBkZXN0W29dID0gbjsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiBkZXN0OwogICAgICAgIH0KICAgICAgfTsKCiAgICAgIC8qKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKgogICAgICAqcHJpdmF0ZSBzdGF0aWMgY2xhc3MgdXNlZCBieSBMZXJjMkRlY29kZQogICAgICAqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgIHZhciBMZXJjMkhlbHBlcnMgPSB7CiAgICAgICAgSFVGRk1BTl9MVVRfQklUU19NQVg6IDEyLCAvL3VzZSAyXjEyIGx1dCwgdHJlYXQgaXQgbGlrZSBjb25zdGFudAogICAgICAgIGNvbXB1dGVDaGVja3N1bUZsZXRjaGVyMzI6IGZ1bmN0aW9uKGlucHV0KSB7CgogICAgICAgICAgdmFyIHN1bTEgPSAweGZmZmYsIHN1bTIgPSAweGZmZmY7CiAgICAgICAgICB2YXIgbGVuID0gaW5wdXQubGVuZ3RoOwogICAgICAgICAgdmFyIHdvcmRzID0gTWF0aC5mbG9vcihsZW4gLyAyKTsKICAgICAgICAgIHZhciBpID0gMDsKICAgICAgICAgIHdoaWxlICh3b3JkcykgewogICAgICAgICAgICB2YXIgdGxlbiA9ICh3b3JkcyA+PSAzNTkpID8gMzU5IDogd29yZHM7CiAgICAgICAgICAgIHdvcmRzIC09IHRsZW47CiAgICAgICAgICAgIGRvIHsKICAgICAgICAgICAgICBzdW0xICs9IChpbnB1dFtpKytdIDw8IDgpOwogICAgICAgICAgICAgIHN1bTIgKz0gc3VtMSArPSBpbnB1dFtpKytdOwogICAgICAgICAgICB9IHdoaWxlICgtLXRsZW4pOwoKICAgICAgICAgICAgc3VtMSA9IChzdW0xICYgMHhmZmZmKSArIChzdW0xID4+PiAxNik7CiAgICAgICAgICAgIHN1bTIgPSAoc3VtMiAmIDB4ZmZmZikgKyAoc3VtMiA+Pj4gMTYpOwogICAgICAgICAgfQoKICAgICAgICAgIC8vIGFkZCB0aGUgc3RyYWdnbGVyIGJ5dGUgaWYgaXQgZXhpc3RzCiAgICAgICAgICBpZiAobGVuICYgMSkgewogICAgICAgICAgICBzdW0yICs9IHN1bTEgKz0gKGlucHV0W2ldIDw8IDgpOwogICAgICAgICAgfQogICAgICAgICAgLy8gc2Vjb25kIHJlZHVjdGlvbiBzdGVwIHRvIHJlZHVjZSBzdW1zIHRvIDE2IGJpdHMKICAgICAgICAgIHN1bTE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m8uY2hlY2tzdW0gPSB2aWV3LmdldFVpbnQzMig0LCB0cnVlKTsgLy9ucm93cwogICAgICAgICAgICBwdHIgKz0gNDsKICAgICAgICAgIH0KCiAgICAgICAgICAvL2tleXMgc3RhcnQgZnJvbSBoZXJlCiAgICAgICAgICB2aWV3ID0gbmV3IERhdGFWaWV3KGlucHV0LCBwdHIsIDEyKTsKICAgICAgICAgIGhlYWRlckluZm8uaGVpZ2h0ID0gdmlldy5nZXRVaW50MzIoMCwgdHJ1ZSk7IC8vbnJvd3MKICAgICAgICAgIGhlYWRlckluZm8ud2lkdGggPSB2aWV3LmdldFVpbnQzMig0LCB0cnVlKTsgLy9uY29scwogICAgICAgICAgcHRyICs9IDg7CiAgICAgICAgICBpZiAoZmlsZVZlcnNpb24gPj0gNCkgewogICAgICAgICAgICBoZWFkZXJJbmZvLm51bURpbXMgPSB2aWV3LmdldFVpbnQzMig4LCB0cnVlKTsKICAgICAgICAgICAgcHRyICs9IDQ7CiAgICAgICAgICB9CiAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgaGVhZGVySW5mby5udW1EaW1zID0gMTsKICAgICAgICAgIH0KCiAgICAgICAgICB2aWV3ID0gbmV3IERhdGFWaWV3KGlucHV0LCBwdHIsIDQwKTsKICAgICAgICAgIGhlYWRlckluZm8ubnVtVmFsaWRQaXhlbCA9IHZpZXcuZ2V0VWludDMyKDAsIHRydWUpOwogICAgICAgICAgaGVhZGVySW5mby5taWNyb0Jsb2NrU2l6ZSA9IHZpZXcuZ2V0SW50MzIoNCwgdHJ1ZSk7CiAgICAgICAgICBoZWFkZXJJbmZvLmJsb2JTaXplID0gdmlldy5nZXRJbnQzMig4LCB0cnVlKTsKICAgICAgICAgIGhlYWRlckluZm8uaW1hZ2VUeXBlID0gdmlldy5nZXRJbnQzMigxMiwgdHJ1ZSk7CgogICAgICAgICAgaGVhZGVySW5mby5tYXhaRXJyb3IgPSB2aWV3LmdldEZsb2F0NjQoMTYsIHRydWUpOwogICAgICAgIC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hZ2VUeXBlKTsKICAgICAgICAgIHZhciBtaW5WYWx1ZXMgPSB0aGlzLnJlYWRTdWJBcnJheShpbnB1dCwgZGF0YS5wdHIsIE91dFBpeGVsVHlwZUFycmF5LCByYW5nZUJ5dGVzKTsKICAgICAgICAgIHZhciBtYXhWYWx1ZXMgPSB0aGlzLnJlYWRTdWJBcnJheShpbnB1dCwgZGF0YS5wdHIgKyByYW5nZUJ5dGVzLCBPdXRQaXhlbFR5cGVBcnJheSwgcmFuZ2VCeXRlcyk7CiAgICAgICAgICBkYXRhLnB0ciArPSAoMiAqIHJhbmdlQnl0ZXMpOwogICAgICAgICAgdmFyIGksIGVxdWFsID0gdHJ1ZTsKICAgICAgICAgIGZvciAoaSA9IDA7IGkgPCBoZWFkZXJJbmZvLm51bURpbXM7IGkrKykgewogICAgICAgICAgICBpZiAobWluVmFsdWVzW2ldICE9PSBtYXhWYWx1ZXNbaV0pIHsKICAgICAgICAgICAgICBlcXVhbCA9IGZhbHNlOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICBoZWFkZXJJbmZvLm1pblZhbHVlcyA9IG1pblZhbHVlczsKICAgICAgICAgIGhlYWRlckluZm8ubWF4VmFsdWVzID0gbWF4VmFsdWVzOwogICAgICAgICAgcmV0dXJuIGVxdWFsOwogICAgICAgIH0sCgogICAgICAgIHJlYWRTdWJBcnJheTogZnVuY3Rpb24oaW5wdXQsIHB0ciwgT3V0UGl4ZWxUeXBlQXJyYXksIG51bUJ5dGVzKSB7CiAgICAgICAgICB2YXIgcmF3RGF0YTsKICAgICAgICAgIGlmIChPdXRQaXhlbFR5cGVBcnJheSA9PT0gVWludDhBcnJheSkgewogICAgICAgICAgICByYXdEYXRhID0gbmV3IFVpbnQ4QXJyYXkoaW5wdXQsIHB0ciwgbnVtQnl0ZXMpOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgIHZhciBhcnJheUJ1ZiA9IG5ldyBBcnJheUJ1ZmZlcihudW1CeXRlcyk7CiAgICAgICAgICAgIHZhciBzdG9yZTggPSBuZXcgVWludDhBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgIHN0b3JlOC5zZXQobmV3IFVpbnQ4QXJyYXkoaW5wdXQsIHB0ciwgbnVtQnl0ZXMpKTsKICAgICAgICAgICAgcmF3RGF0YSA9IG5ldyBPdXRQaXhlbFR5cGVBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm4gcmF3RGF0YTsKICAgICAgICB9LAoKICAgICAgICByZWFkTWFzazogZnVuY3Rpb24oaW5wdXQsIGRhdGEpIHsKICAgICAgICAgIHZhciBwdHIgPSBkYXRhLnB0cjsKICAgICAgICAgIHZhciBoZWFkZXJJbmZvID0gZGF0YS5oZWFkZXJJbmZvOwogICAgICAgICAgdmFyIG51bVBpeGVscyA9IGhlYWRlckluZm8ud2lkdGggKiBoZWFkZXJJbmZvLmhlaWdodDsKICAgICAgICAgIHZhciBudW1WYWxpZFBpeGVsID0gaGVhZGVySW5mby5udW1WYWxpZFBpeGVsOwoKICAgICAgICAgIHZhciB2aWV3ID0gbmV3IERhdGFWaWV3KGlucHV0LCBwdHIsIDQpOwogICAgICAgICAgdmFyIG1hc2sgPSB7fTsKICAgICAgICAgIG1hc2subnVtQnl0ZXMgPSB2aWV3LmdldFVpbnQzMigwLCB0cnVlKTsKICAgICAgICAgIHB0ciArPSA0OwoKICAgICAgICAgIC8vIE1hc2sgRGF0YQogICAgICAgICAgaWYgKCgwID09PSBudW1WYWxpZFBpeGVsIHx8IG51bVBpeGVscyA9PT0gbnVtVmFsaWRQaXhlbCkgJiYgMCAhPT0gbWFzay5udW1CeXRlcykgewogICAgICAgICAgICB0aHJvdyAoImludmFsaWQgbWFzayIpOwogICAgICAgICAgfQogICAgICAgICAgdmFyIGJpdHNldCwgcmVzdWx0TWFzazsKICAgICAgICAgIGlmIChudW1WYWxpZFBpeGVsID09PSAwKSB7CiAgICAgICAgICAgIGJpdHNldCA9IG5ldyBVaW50OEFycmF5KE1hdGguY2VpbChudW1QaXhlbHMgLyA4KSk7CiAgICAgICAgICAgIG1hc2suYml0c2V0ID0gYml0c2V0OwogICAgICAgICAgICByZXN1bHRNYXNrID0gbmV3IFVpbnQ4QXJyYXkobnVtUGl4ZWxzKTsKICAgICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0TWFzayA9IHJlc3VsdE1hc2s7CiAgICAgICAgICAgIHB0ciArPSBtYXNrLm51bUJ5dGVzOwogICAgICAgICAgfS8vID8/Pz8/IGVsc2UgaWYgKGRhdGEubWFzay5udW1CeXRlcyA+IDAgJiYgZGF0YS5tYXNrLm51bUJ5dGVzPCBkYXRhLm51bVZhbGlkUGl4ZWwpIHsKICAgICAgICAgIGVsc2UgaWYgKG1hc2subnVtQnl0ZXMgPiAwKSB7CiAgICAgICAgICAgIGJpdHNldCA9IG5ldyBVaW50OEFycmF5KE1hdGguY2VpbChudW1QaXhlbHMgLyA4KSk7CiAgICAgICAgICAgIHZpZXcgPSBuZXcgRGF0YVZpZXcoaW5wdXQsIHB0ciwgbWFzay5udW1CeXRlcyk7CiAgICAgICAgICAgIHZhciBjbnQgPSB2aWV3LmdldEludDE2KDAsIHRydWUpOwogICAgICAgICAgICB2YXIgaXAgPSAyLCBvcCA9IDAsIHZhbCA9IDA7CiAgICAgICAgICAgIGRvIHsKICAgICAgICAgICAgICBpZiAoY250ID4gMCkgewogICAgICAgICAgICAgICAgd2hpbGUgKGNudC0tKSB7IGJpdHNldFtvcCsrXSA9IHZpZXcuZ2V0VWludDgoaXArKyk7IH0KICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgdmFsID0gdmlldy5nZXRVaW50OChpcCsrKTsKICAgICAgICAgICAgICAgIGNudCA9IC1jbnQ7CiAgICAgICAgICAgICAgICB3aGlsZSAoY250LS0pIHsgYml0c2V0W29wKytdID0gdmFsOyB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGNudCA9IHZpZXcuZ2V0SW50MTYoaXAsIHRydWUpOwogICAgICAgICAgICAgIGlwICs9IDI7CiAgICAgICAgICAgIH0gd2hpbGUgKGlwIDwgbWFzay5udW1CeXRlcyk7CiAgICAgICAgICAgIGlmICgoY250ICE9PSAtMzI3NjgpIHx8IChvcCA8IGJpdHNldC5sZW5ndGgpKSB7CiAgICAgICAgICAgICAgdGhyb3cgIlVuZXhwZWN0ZWQgZW5kIG9mIG1hc2sgUkxFIGVuY29kaW5nIjsKICAgICAgICAgICAgfQoKICAgICAgICAgICAgcmVzdWx0TWFzayA9IG5ldyBVaW50OEFycmF5KG51bVBpeGVscyk7CiAgICAgICAgICAgIHZhciBtYiA9IDAsIGsgPSAwOwoKICAgICAgICAgICAgZm9yIChrID0gMDsgayA8IG51bVBpeGVsczsgaysrKSB7CiAgICAgICAgICAgICAgaWYgKGsgJiA3KSB7CiAgICAgICAgICAgICAgICBtYiA9IGJpdHNldFtrID4+IDNdOwogICAgICAgICAgICAgICAgbWIgPDw9IGsgJiA3OwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIG1iID0gYml0c2V0W2sgPj4gM107CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGlmIChtYiAmIDEyOCkgewogICAgICAgICAgICAgICAgcmVzdWx0TWFza1trXSA9IDE7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdE1hc2sgPSByZXN1bHRNYXNrOwoKICAgICAgICAgICAgbWFzay5iaXRzZXQgPSBiaXRzZXQ7CiAgICAgICAgICAgIHB0ciArPSBtYXNrLm51bUJ5dGVzOwogICAgICAgICAgfQogICAgICAgICAgZGF0YS5wdHIgPSBwdHI7CiAgICAgICAgICBkYXRhLm1hc2sgPSBtYXNrOwogICAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgICAgfSwKCiAgICAgICAgcmVhZERhdGFPbmVTd2VlcDogZnVuY3Rpb24oaW5wdXQsIGRhdGEsIE91dFBpeGVsVHlwZUFycmF5KSB7CiAgICAgICAgICB2YXIgcHRyID0gZGF0YS5wdHI7CiAgICAgICAgICB2YXIgaGVhZGVySW5mbyA9IGRhdGEuaGVhZGVySW5mbzsKICAgICAgICAgIHZhciBudW1EaW1zID0gaGVhZGVySW5mby5udW1EaW1zOwogICAgICAgICAgdmFyIG51bVBpeGVscyA9IGhlYWRlckluZm8ud2lkdGggKiBoZWFkZXJJbmZvLmhlaWdodDsKICAgICAgICAgIHZhciBpbWFnZVR5cGUgPSBoZWFkZXJJbmZvLmltYWdlVHlwZTsKICAgICAgICAgIHZhciBudW1CeXRlcyA9IGhlYWRlckluZm8ubnVtVmFsaWRQaXhlbCAqIExlcmMySGVscGVycy5nZXREYXRhVHlwZVNpemUoaW1hZ2VUeXBlKSAqIG51bURpbXM7CiAgICAgICAgICAvL2RhdGEucGl4ZWxzLm51bUJ5dGVzID0gbnVtQnl0ZXM7CiAgICAgICAgICB2YXIgcmF3RGF0YTsKICAgICAgICAgIHZhciBtYXNrID0gZGF0YS5waXhlbHMucmVzdWx0TWFzazsKICAgICAgICAgIGlmIChPdXRQaXhlbFR5cGVBcnJheSA9PT0gVWludDhBcnJheSkgewogICAgICAgICAgICByYXdEYXRhID0gbmV3IFVpbnQ4QXJyYXkoaW5wdXQsIHB0ciwgbnVtQnl0ZXMpOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgIHZhciBhcnJheUJ1ZiA9IG5ldyBBcnJheUJ1ZmZlcihudW1CeXRlcyk7CiAgICAgICAgICAgIHZhciBzdG9yZTggPSBuZXcgVWludDhBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgIHN0b3JlOC5zZXQobmV3IFVpbnQ4QXJyYXkoaW5wdXQsIHB0ciwgbnVtQnl0ZXMpKTsKICAgICAgICAgICAgcmF3RGF0YSA9IG5ldyBPdXRQaXhlbFR5cGVBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICB9CiAgICAgICAgICBpZiAocmF3RGF0YS5sZW5ndGggPT09IG51bVBpeGVscyAqIG51bURpbXMpIHsKICAgICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0UGl4ZWxzID0gcmF3RGF0YTsKICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgIC8vbWFzawogICAgICAgICAgewogICAgICAgICAgICBkYXRhLnBpeGVscy5yZXN1bHRQaXhlbHMgPSBuZXcgT3V0UGl4ZWxUeXBlQXJyYXkobnVtUGl4ZWxzICogbnVtRGltcyk7CiAgICAgICAgICAgIHZhciB6ID0gMCwgayA9IDAsIGkgPSAwLCBuU3RhcnQgPSAwOwogICAgICAgICAgICBpZiAobnVtRGltcyA+IDEpIHsKICAgICAgICAgICAgICBmb3IgKGk9MDsgaSA8IG51bURpbXM7IGkrKykgewogICAgICAgICAgICAgICAgblN0YXJ0ID0gaSAqIG51bVBpeGVsczsKICAgICAgICAgICAgICAgIGZvciAoayA9IDA7IGsgPCBudW1QaXhlbHM7IGsrKykgewogICAgICAgICAgICAgICAgICBpZiAobWFza1trXSkgewogICAgICAgICAgICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdFBpeGVsc1tuU3RhcnQgKyBrXSA9IHJhd0RhdGFbeisrXTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICBmb3IgKGsgPSAwOyBrIDwgbnVtUGl4ZWxzOyBrKyspIHsKICAgICAgICAgICAgICAgIGlmIChtYXNrW2tdKSB7CiAgICAgICAgICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdFBpeGVsc1trXSA9IHJhd0RhdGFbeisrXTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIHB0ciArPSBudW1CeXRlczsKICAgICAgICAgIGRhdGEucHRyID0gcHRyOyAgICAgICAvL3JldHVybiBkYXRhOwogICAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgICAgfSwKCiAgICAgICAgcmVhZEh1ZmZtYW5UcmVlOiBmdW5jdGlvbihpbnB1dCwgZGF0YSkgewogICAgICAgICAgdmFyIEJJVFNfTUFYID0gdGhpcy5IVUZGTUFOX0xVVF9CSVRTX01BWDsgLy84IGlzIHNsb3cgZm9yIHRoZSBsYXJnZSB0ZXN0IGltYWdlCiAgICAgICAgICAvL3ZhciBzaXplX21heCA9IDEgPDwgQklUU19NQVg7CiAgICAgICAgICAvKiAqKioqKioqKioqKioqKioqKioqKioqKioKICAgICAgICAgICAqIHJlYWRpbmcgY29kZSB0YWJsZQogICAgICAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgICAgICB2YXIgdmlldyA9IG5ldyBEYXRhVmlldyhpbnB1dCwgZGF0YS5wdHIsIDE2KTsKICAgICAgICAgIGRhdGEucHRyICs9IDE2OwogICAgICAgICAgdmFyIHZlcnNpb24gPSB2aWV3LmdldEludDMyKDAsIHRydWUpOwogICAgICAgICAgaWYgKHZlcnNpb24gPCAyKSB7CiAgICAgICAgICAgIHRocm93ICJ1bnN1cHBvcnRlZCBIdWZmbWFuIHZlcnNpb24iOwogICAgICAgICAgfQogICAgICAgICAgdmFyIHNpemUgPSB2aWV3LmdldEludDMyKDQsIHRydWUpOwogICAgICAgICAgdmFyIGkwID0gdmlldy5nZXRJbnQzMig4LCB0cnVlKTsKICAgICAgICAgIHZhciBpMSA9IHZpZXcuZ2V0SW50MzIoMTIsIHRydWUpOwogICAgICAgICAgaWYgKGkwID49IGkxKSB7CiAgICAgICAgICAgIHJldHVybiBmYWxzZTsKICAgICAgICAgIH0KICAgICAgICAgIHZhciBibG9ja0RhdGFCdWZmZXIgPSBuZXcgVWludDMyQXJyYXkoaTEgLSBpMCk7CiAgICAgICAgICBMZXJjMkhlbHBlcnMuZG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Y29kZVRhYmxlW2pdLmZpcnN0OwogICAgICAgICAgICBpZiAobGVuID4gMCkgewogICAgICAgICAgICAgIGNvZGVUYWJsZVtqXS5zZWNvbmQgPSAod29yZCA8PCBiaXRQb3MpID4+PiAoMzIgLSBsZW4pOwoKICAgICAgICAgICAgICBpZiAoMzIgLSBiaXRQb3MgPj0gbGVuKSB7CiAgICAgICAgICAgICAgICBiaXRQb3MgKz0gbGVuOwogICAgICAgICAgICAgICAgaWYgKGJpdFBvcyA9PT0gMzIpIHsKICAgICAgICAgICAgICAgICAgYml0UG9zID0gMDsKICAgICAgICAgICAgICAgICAgc3JjUHRyKys7CiAgICAgICAgICAgICAgICAgIHdvcmQgPSBzdHVmZmVkRGF0YVtzcmNQdHJdOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIGJpdFBvcyArPSBsZW4gLSAzMjsKICAgICAgICAgICAgICAgIHNyY1B0cisrOwogICAgICAgICAgICAgICAgd29yZCA9IHN0dWZmZWREYXRhW3NyY1B0cl07CiAgICAgICAgICAgICAgICBjb2RlVGFibGVbal0uc2Vjb25kIHw9IHdvcmQgPj4+ICgzMiAtIGJpdFBvcyk7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CgogICAgICAgICAgLy9maW5pc2hlZCByZWFkaW5nIGNvZGUgdGFibGUKCiAgICAgICAgICAvKiAqKioqKioqKioqKioqKioqKioqKioqKioKICAgICAgICAgICAqIGJ1aWxkaW5nIGx1dAogICAgICAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgICAgICB2YXIgbnVtQml0c0xVVCA9IDAsIG51bUJpdHNMVVRRaWNrID0gMDsKICAgICAgICAgIHZhciB0cmVlID0gbmV3IFRyZWVOb2RlKCk7CiAgICAgICAgICBmb3IgKGkgPSAwOyBpIDwgY29kZVRhYmxlLmxlbmd0aDsgaSsrKSB7CiAgICAgICAgICAgIGlmIChjb2RlVGFibGVbaV0gIT09IHVuZGVmaW5lZCkgewogICAgICAgICAgICAgIG51bUJpdHNMVVQgPSBNYXRoLm1heChudW1CaXRzTFVULCBjb2RlVGFibGVbaV0uZmlyc3QpOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICBpZiAobnVtQml0c0xVVCA+PSBCSVRTX01BWCkgewogICAgICAgICAgICBudW1CaXRzTFVUUWljayA9IEJJVFNfTUFYOwogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgIG51bUJpdHNMVVRRaWNrID0gbnVtQml0c0xVVDsKICAgICAgICAgIH0KICAgICAgICAgIGlmIChudW1CaXRzTFVUID49IDMwKSB7CiAgICAgICAgICAgIGNvbnNvbGUubG9nKCJXQVJuaW5nLCBsYXJnZSBOVU0gTFVUIEJJVFMgSVMgIiArIG51bUJpdHNMVVQpOwogICAgICAgICAgfQogICAgICAgICAgdmFyIGRlY29kZUx1dCA9IFtdLCBlbnRyeSwgY29kZSwgbnVtRW50cmllcywgamosIGN1cnJlbnRCaXQsIG5vZGU7CiAgICAgICAgICBmb3IgKGkgPSBpMDsgaSA8IGkxOyBpKyspIHsKICAgICAgICAgICAgaiA9IGkgLSAoaSA8IHNpemUgPyAwIDogc2l6ZSk7Ly93cmFwIGFyb3VuZAogICAgICAgICAgICBsZW4gPSBjb2RlVGFibGVbal0uZmlyc3Q7CiAgICAgICAgICAgIGlmIChsZW4gPiAwKSB7CiAgICAgICAgICAgICAgZW50cnkgPSBbbGVuLCBqXTsKICAgICAgICAgICAgICBpZiAobGVuIDw9IG51bUJpdHNMVVRRaWNrKSB7CiAgICAgICAgICAgICAgICBjb2RlID0gY29kZVRhYmxlW2pdLnNlY29uZCA8PCAobnVtQml0c0xVVFFpY2sgLSBsZW4pOwogICAgICAgICAgICAgICAgbnVtRW50cmllcyA9IDEgPDwgKG51bUJpdHNMVVRRaWNrIC0gbGVuKTsKICAgICAgICAgICAgICAgIGZvciAoayA9IDA7IGsgPCBudW1FbnRyaWVzOyBrKyspIHsKICAgICAgICAgICAgICAgICAgZGVjb2RlTHV0W2NvZGUgfCBrXSA9IGVudHJ5OwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIC8vYnVpbGQgdHJlZQogICAgICAgICAgICAgICAgY29kZSA9IGNvZGVUYWJsZVtqXS5zZWNvbmQ7CiAgICAgICAgICAgICAgICBub2RlID0gdHJlZTsKICAgICAgICAgICAgICAgIGZvciAoamogPSBsZW4gLSAxOyBqaiA+PSAwOyBqai0tKSB7CiAgICAgICAgICAgICAgICAgIGN1cnJlbnRCaXQgPSBjb2RlID4+PiBqaiAmIDE7IC8vbm8gbGVmdCBzaGlmdCBhcyBsZW5ndGggY291bGQgYmUgMzAsMzEKICAgICAgICAgICAgICAgICAgaWYgKGN1cnJlbnRCaXQpIHsKICAgICAgICAgICAgICAgICAgICBpZiAoIW5vZGUucmlnaHQpIHsKICAgICAgICAgICAgICAgICAgICAgIG5vZGUucmlnaHQgPSBuZXcgVHJlZU5vZGUoKTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgbm9kZSA9IG5vZGUucmlnaHQ7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgaWYgKCFub2RlLmxlZnQpIHsKICAgICAgICAgICAgICAgICAgICAgIG5vZGUubGVmdCA9IG5ldyBUcmVlTm9kZSgpOwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICBub2RlID0gbm9kZS5sZWZ0OwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIGlmIChqaiA9PT0gMCAmJiAhbm9kZS52YWwpIHsKICAgICAgICAgICAgICAgICAgICBub2RlLnZhbCA9IGVudHJ5WzFdOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm4gewogICAgICAgICAgICBkZWNvZGVMdXQ6IGRlY29kZUx1dCwKICAgICAgICAgICAgbnVtQml0c0xVVFFpY2s6IG51bUJpdHNMVVRRaWNrLAogICAgICAgICAgICBudW1CaXRzTFVUOiBudW1CaXRzTFVULAogICAgICAgICAgICB0cmVlOiB0cmVlLAogICAgICAgICAgICBzdHVmZmVkRGF0YTogc3R1ZmZlZERhdGEsCiAgICAgICAgICAgIHNyY1B0cjogc3JjUHRyLAogICAgICAgICAgICBiaXRQb3M6IGJpdFBvcwogICAgICAgICAgfTsKICAgICAgICB9LAoKICAgICAgICByZWFkSHVmZm1hbjogZnVuY3Rpb24oaW5wdXQsIGRhdGEsIE91dFBpeGVsVHlwZUFycmF5KSB7CiAgICAgICAgICB2YXIgaGVhZGVySW5mbyA9IGRhdGEuaGVhZGVySW5mbzsKICAgICAgICAgIHZhciBudW1EaW1zID0gaGVhZGVySW5mby5udW1EaW1zOwogICAgICAgICAgdmFyIGhlaWdodCA9IGRhdGEuaGVhZGVySW5mby5oZWlnaHQ7CiAgICAgICAgICB2YXIgd2lkdGggPSBkYXRhLmhlYWRlckluZm8ud2lkdGg7CiAgICAgICAgICB2YXIgbnVtUGl4ZWxzID0gd2lkdGggKiBoZWlnaHQ7CiAgICAgICAgICAvL3ZhciBzaXplX21heCA9IDEgPDwgQklUU19NQVg7CiAgICAgICAgICAvKiAqKioqKioqKioqKioqKioqKioqKioqKioKICAgICAgICAgICAqIHJlYWRpbmcgaHVmZm1hbiBzdHJ1Y3R1cmUgaW5mbwogICAgICAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgICAgICB2YXIgaHVmZm1hbkluZm8gPSB0aGlzLnJlYWRIdWZmbWFuVHJlZShpbnB1dCwgZGF0YSk7CiAgICAgICAgICB2YXIgZGVjb2RlTHV0ID0gaHVmZm1hbkluZm8uZGVjb2RlTHV0OwogICAgICAgICAgdmFyIHRyZWUgPSBodWZmbWFuSW5mby50cmVlOwogICAgICAgICAgLy9zdHVmZmVkRGF0YSBpbmNsdWRlcyBodWZmbWFuIGhlYWRlcnMKICAgICAgICAgIHZhciBzdHVmZmVkRGF0YSA9IGh1ZmZtYW5JbmZvLnN0dWZmZWREYXRhOwogICAgICAgICAgdmFyIHNyY1B0ciA9IGh1ZmZtYW5JbmZvLnNyY1B0cjsKICAgICAgICAgIHZhciBiaXRQb3MgPSBodWZmbWFuSW5mby5iaXRQb3M7CiAgICAgICAgICB2YXIgbnVtQml0c0xVVFFpY2sgPSBodWZmbWFuSW5mby5udW1CaXRzTFVUUWljazsKICAgICAgICAgIHZhciBudW1CaXRzTFVUID0gaHVmZm1hbkluZm8ubnVtQml0c0xVVDsKICAgICAgICAgIHZhciBvZmZzZXQgPSBkYXRhLmhlYWRlckluZm8uaW1hZ2VUeXBlID09PSAwID8gMTI4IDogMDsKICAgICAgICAgIC8qKioqKioqKioqKioqKioqKioqKioqKioqCiAgICAgICAgICAqICBkZWNvZGUKICAgICAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKioqKi8KICAgICAgICAgIHZhciBub2RlLCB2YWwsIGRlbHRhLCBtYXNrID0gZGF0YS5waXhlbHMucmVzdWx0TWFzaywgdmFsVG1wLCB2YWxUbXBRdWljaywgY3VycmVudEJpdDsKICAgICAgICAgIHZhciBpLCBqLCBrLCBpaTsKICAgICAgICAgIHZhciBwcmV2VmFsID0gMDsKICAgICAgICAgIGlmIChiaXRQb3MgPiAwKSB7CiAgICAgICAgICAgIHNyY1B0cisrOwogICAgICAgICAgICBiaXRQb3MgPSAwOwogICAgICAgICAgfQogICAgICAgICAgdmFyIHdvcmQgPSBzdHVmZmVkRGF0YVtzcmNQdHJdOwogICAgICAgICAgdmFyIGRlbHRhRW5jb2RlID0gZGF0YS5lbmNvZGVNb2RlID09PSAxOwogICAgICAgICAgdmFyIHJlc3VsdFBpeGVsc0FsbERpbSA9IG5ldyBPdXRQaXhlbFR5cGVBcnJheShudW1QaXhlbHMgKiBudW1EaW1zKTsKICAgICAgICAgIHZhciByZXN1bHRQaXhlbHMgPSByZXN1bHRQaXhlbHNBbGxEaW07CiAgICAgICAgICB2YXIgaURpbTsKICAgICAgICAgIGZvciAoaURpbSA9IDA7IGlEaW0gPCBoZWFkZXJJbmZvLm51bURpbXM7IGlEaW0rKykgewogICAgICAgICAgICBpZiAobnVtRGltcyA+IDEpIHsKICAgICAgICAgICAgICAvL2dldCB0aGUgbWVtIGJsb2NrIG9mIGN1cnJlbnQgZGltZW5zaW9uCiAgICAgICAgICAgICAgcmVzdWx0UGl4ZWxzID0gbmV3IE91dFBpeGVsVHlwZUFycmF5KHJlc3VsdFBpeGVsc0FsbERpbS5idWZmZXIsIG51bVBpeGVscyAqIGlEaW0sIG51bVBpeGVscyk7CiAgICAgICAgICAgICAgcHJldlZhbCA9IDA7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgaWYgKGRhdGEuaGVhZGVySW5mby5udW1WYWxpZFBpeGVsID09PSB3aWR0aCAqIGhlaWdodCkgeyAvL2FsbCB2YWxpZAogICAgICAgICAgICAgIGZvciAoayA9IDAsIGkgPSAwOyBpIDwgaGVpZ2h0OyBpKyspIHsKICAgICAgICAgICAgICAgIGZvciAoaiA9IDA7IGogPCB3aWR0aDsgaisrLCBrKyspIHsKICAgICAgICAgICAgICAgICAgdmFsID0gMDsKICAgICAgICAgICAgICAgICAgdmFsVG1wID0gKHdvcmQgPDwgYml0UG9zKSA+Pj4gKDMyIC0gbnVtQml0c0xVVFFpY2spOwogICAgICAgICAgICAgICAgICB2YWxUbXBRdWljayA9IHZhbFRtcDsvLyA+Pj4gZGVsdGFCaXRzOwogICAgICAgICAgICAgICAgICBpZiAoMzIgLSBiaXRQb3MgPCBudW1CaXRzTFVUUWljaykgewogICAgICAgICAgICAgICAgICAgIHZhbFRtcCB8PSAoKHN0dWZmZWREYXRhW3NyY1B0ciArIDFdKSA+Pj4gKDY0IC0gYml0UG9zIC0gbnVtQml0c0xVVFFpY2spKTsKICAgICAgICAgICAgICAgICAgICB2YWxUbXBRdWljayA9IHZhbFRtcDsvLyA+Pj4gZGVsdGFCaXRzOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIGlmIChkZWNvZGVMdXRbdmFsVG1wUXVpY2tdKSAgICAvLyBpZiB0aGVyZSwgbW92ZSB0aGUgY29ycmVjdCBudW1iZXIgb2YgYml0cyBhbmQgZG9uZQogICAgICAgICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAgICAgdmFsID0gZGVjb2RlTHV0W3ZhbFRtcFF1aWNrXVsxXTsKICAgICAgICAgICAgICAgICAgICBiaXRQb3MgKz0gZGVjb2RlTHV0W3ZhbFRtcFF1aWNrXVswXTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICB2YWxUbXAgPSAod29yZCA8PCBiaXRQb3MpID4+PiAoMzIgLSBudW1CaXRzTFVUKTsKICAgICAgICAgICAgICAgICAgICB2YWxUbXBRdWljayA9IHZhbFRtcDsvLyA+Pj4gZGVsdGFCaXRzOwogICAgICAgICAgICAgICAgICAgIGlmICgzMiAtIGJpdFBvcyA8IG51bUJpdHNMVVQpIHsKICAgICAgICAgICAgICAgICAgICAgIHZhbFRtcCB8PSAoKHN0dWZmZWREYXRhW3NyY1B0ciArIDFdKSA+Pj4gKDY0IC0gYml0UG9zIC0gbnVtQml0c0xVVCkpOwogICAgICAgICAgICAgICAgICAgICAgdmFsVG1wUXVpY2sgPSB2YWxUbXA7Ly8gPj4+IGRlbHRhQml0czsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgbm9kZSA9IHRyZWU7CiAgICAgICAgICAgICAgICAgICAgZm9yIChpaSA9IDA7IGlpIDwgbnVtQml0c0xVVDsgaWkrKykgewogICAgICAgICAgICAgICAgICAgICAgY3VycmVudEJpdCA9IHZhbFRtcCA+Pj4gKG51bUJpdHNMVVQgLSBpaSAtIDEpICYgMTsKICAgICAgICAgICAgICAgICAgICAgIG5vZGUgPSBjdXJyZW50Qml0ID8gbm9kZS5yaWdodCA6IG5vZGUubGVmdDsKICAgICAgICAgICAgICAgICAgICAgIGlmICghKG5vZGUubGVmdCB8fCBub2RlLnJpZ2h0KSkgewogICAgICAgICAgICAgICAgICAgICAgICB2YWwgPSBub2RlLnZhbDsKICAgICAgICAgICAgICAgICAgICAgICAgYml0UG9zID0gYml0UG9zICsgaWkgKyAxOwogICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KCiAgICAgICAgICAgICAgICAgIGlmIChiaXRQb3MgPj0gMzIpIHsKICAgICAgICAgICAgICAgICAgICBiaXRQb3MgLT0gMzI7CiAgICAgICAgICAgICAgICAgICAgc3JjUHRyKys7CiAgICAgICAgICAgICAgICAgICAgd29yZCA9IHN0dWZmZWREYXRhW3NyY1B0cl07CiAgICAgICAgICAgICAgICAgIH0KCiAgICAgICAgICAgICAgICAgIGRlbHRhID0gdmFsIC0gb2Zmc2V0OwogICAgICAgICAgICAgICAgICBpZiAoZGVsdGFFbmNvZGUpIHsKICAgICAgICAgICAgICAgICAgICBpZiAoaiA+IDApIHsKICAgICAgICAgICAgICAgICAgICAgIGRlbHRhICs9IHByZXZWYWw7ICAgIC8vIHVzZSBvdmVyZmxvdwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICBlbHNlIGlmIChpID4gMCkgewogICAgICAgICAgICAgICAgICAgICAgZGVsdGEgKz0gcmVzdWx0UGl4ZWxzW2sgLSB3aWR0aF07CiAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgICAgICAgZGVsdGEgKz0gcHJldlZhbDsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgZGVsdGEgJj0gMHhGRjsgLy9vdmVyZmxvdwogICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1trXSA9IGRlbHRhOy8vb3ZlcmZsb3cKICAgICAgICAgICAgICAgICAgICBwcmV2VmFsID0gZGVsdGE7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgcmVzdWx0UGl4ZWxzW2tdID0gZGVsdGE7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZSB7IC8vbm90IGFsbCB2YWxpZCwgdXNlIG1hc2sKICAgICAgICAgICAgICBmb3IgKGsgPSAwLCBpID0gMDsgaSA8IGhlaWdodDsgaSsrKSB7CiAgICAgICAgICAgICAgICBmb3IgKGogPSAwOyBqIDwgd2lkdGg7IGorKywgaysrKSB7CiAgICAgICAgICAgICAgICAgIGlmIChtYXNrW2tdKSB7CiAgICAgICAgICAgICAgICAgICAgdmFsID0gMDsKICAgICAgICAgICAgICAgICAgICB2YWxUbXAgPSAod29yZCA8PCBiaXRQb3MpID4+PiAoMzIgLSBudW1CaXRzTFVUUWljayk7CiAgICAgICAgICAgICAgICAgICAgdmFsVG1wUXVpY2sgPSB2YWxUbXA7Ly8gPj4+IGRlbHRhQml0czsKICAgICAgICAgICAgICAgICAgICBpZiAoMzIgLSBiaXRQb3MgPCBudW1CaXRzTFVUUWljaykgewogICAgICAgICAgICAgICAgICAgICAgdmFsVG1wIHw9ICgoc3R1ZmZlZERhdGFbc3JjUHRyICsgMV0pID4+PiAoNjQgLSBiaXRQb3MgLSBudW1CaXRzTFVUUWljaykpOwogICAgICAgICAgICAgICAgICAgICAgdmFsVG1wUXVpY2sgPSB2YWxUbXA7Ly8gPj4+IGRlbHRhQml0czsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgaWYgKGRlY29kZUx1dFt2YWxUbXBRdWlja10pICAgIC8vIGlmIHRoZXJlLCBtb3ZlIHRoZSBjb3JyZWN0IG51bWJlciBvZiBiaXRzIGFuZCBkb25lCiAgICAgICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgICAgdmFsID0gZGVjb2RlTHV0W3ZhbFRtcFF1aWNrXVsxXTsKICAgICAgICAgICAgICAgICAgICAgIGJpdFBvcyArPSBkZWNvZGVMdXRbdmFsVG1wUXVpY2tdWzBdOwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICAgIHZhbFRtcCA9ICh3b3JkIDw8IGJpdFBvcykgPj4+ICgzMiAtIG51bUJpdHNMVVQpOwogICAgICAgICAgICAgICAgICAgICAgdmFsVG1wUXVpY2sgPSB2YWxUbXA7Ly8gPj4+IGRlbHRhQml0czsKICAgICAgICAgICAgICAgICAgICAgIGlmICgzMiAtIGJpdFBvcyA8IG51bUJpdHNMVVQpIHsKICAgICAgICAgICAgICAgICAgICAgICAgdmFsVG1wIHw9ICgoc3R1ZmZlZERhdGFbc3JjUHRyICsgMV0pID4+PiAoNjQgLSBiaXRQb3MgLSBudW1CaXRzTFVUKSk7CiAgICAgICAgICAgICAgICAgICAgICAgIHZhbFRtcFF1aWNrID0gdmFsVG1wOy8vID4+PiBkZWx0YUJpdHM7CiAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICBub2RlID0gdHJlZTsKICAgICAgICAgICAgICAgICAgICAgIGZvciAoaWkgPSAwOyBpaSA8IG51bUJpdHNMVVQ7IGlpKyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgY3VycmVudEJpdCA9IHZhbFRtcCA+Pj4gKG51bUJpdHNMVVQgLSBpaSAtIDEpICYgMTsKICAgICAgICAgICAgICAgICAgICAgICAgbm9kZSA9IGN1cnJlbnRCaXQgPyBub2RlLnJpZ2h0IDogbm9kZS5sZWZ0OwogICAgICAgICAgICAgICAgICAgICAgICBpZiAoIShub2RlLmxlZnQgfHwgbm9kZS5yaWdodCkpIHsKICAgICAgICAgICAgICAgICAgICAgICAgICB2YWwgPSBub2RlLnZhbDsKICAgICAgICAgICAgICAgICAgICAgICAgICBiaXRQb3MgPSBiaXRQb3MgKyBpaSArIDE7CiAgICAgICAgICAgICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICB9CgogICAgICAgICAgICAgICAgICAgIGlmIChiaXRQb3MgPj0gMzIpIHsKICAgICAgICAgICAgICAgICAgICAgIGJpdFBvcyAtPSAzMjsKICAgICAgICAgICAgICAgICAgICAgIHNyY1B0cisrOwogICAgICAgICAgICAgICAgICAgICAgd29yZCA9IHN0dWZmZWREYXRhW3NyY1B0cl07CiAgICAgICAgICAgICAgICAgICAgfQoKICAgICAgICAgICAgICAgICAgICBkZWx0YSA9IHZhbCAtIG9mZnNldDsKICAgICAgICAgICAgICAgICAgICBpZiAoZGVsdGFFbmNvZGUpIHsKICAgICAgICAgICAgICAgICAgICAgIGlmIChqID4gMCAmJiBtYXNrW2sgLSAxXSkgewogICAgICAgICAgICAgICAgICAgICAgICBkZWx0YSArPSBwcmV2VmFsOyAgICAvLyB1c2Ugb3ZlcmZsb3cKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgIGVsc2UgaWYgKGkgPiAwICYmIG1hc2tbayAtIHdpZHRoXSkgewogICAgICAgICAgICAgICAgICAgICAgICBkZWx0YSArPSByZXN1bHRQaXhlbHNbayAtIHdpZHRoXTsKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgICAgICAgICBkZWx0YSArPSBwcmV2VmFsOwogICAgICAgICAgICAgICAgICAgICAgfQoKICAgICAgICAgICAgICAgICAgICAgIGRlbHRhICY9IDB4RkY7IC8vb3ZlcmZsb3cKICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1trXSA9IGRlbHRhOy8vb3ZlcmZsb3cKICAgICAgICAgICAgICAgICAgICAgIHByZXZWYWwgPSBkZWx0YTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgICByZXN1bHRQaXhlbHNba10gPSBkZWx0YTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZGF0YS5wdHIgPSBkYXRhLnB0ciArIChzcmNQdHIgKyAxKSAqIDQgKyAoYml0UG9zID4gMCA/IDQgOiAwKTsKICAgICAgICAgIH0KICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdFBpeGVscyA9IHJlc3VsdFBpeGVsc0FsbERpbTsKICAgICAgICB9LAoKICAgICAgICBkZWNvZGVCaXRzOiBmdW5jdGlvbihpbnB1dCwgZGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBvZmZzZXQsIGlEaW0pIHsKICAgICAgICAgIHsKICAgICAgICAgICAgLy9iaXRzdHVmZiBlbmNvZGluZyBpcyAzCiAgICAgICAgICAgIHZhciBoZWFkZXJJbmZvID0gZGF0YS5oZWFkZXJJbmZvOwogICAgICAgICAgICB2YXIgZmlsZVZlcnNpb24gPSBoZWFkZXJJbmZvLmZpbGVWZXJzaW9uOwogICAgICAgICAgICAvL3ZhciBibG9jayA9IHt9OwogICAgICAgICAgICB2YXIgYmxvY2tQdHIgPSAwOwogICAgICAgICAgICB2YXIgdmlldyA9IG5ldyBEYXRhVmlldyhpbnB1dCwgZGF0YS5wdHIsIDUpOy8vdG8gZG8KICAgICAgICAgICAgdmFyIGhlYWRlckJ5dGUgPSB2aWV3LmdldFVpbnQ4KDApOwogICAgICAgICAgICBibG9ja1B0cisrOwogICAgICAgICAgICB2YXIgYml0czY3ID0gaGVhZGVyQnl0ZSA+PiA2OwogICAgICAgICAgICB2YXIgbiA9IChiaXRzNjcgPT09IDApID8gNCA6IDMgLSBiaXRzNjc7CiAgICAgICAgICAgIHZhciBkb0x1dCA9IChoZWFkZXJCeXRlICYgMzIpID4gMCA/IHRydWUgOiBmYWxzZTsvLzV0aCBiaXQKICAgICAgICAgICAgdmFyIG51bUJpdHMgPSBoZWFkZXJCeXRlICYgMzE7CiAgICAgICAgICAgIHZhciBudW1FbGVtZW50cyA9IDA7CiAgICAgICAgICAgIGlmIChuID09PSAxKSB7CiAgICAgICAgICAgICAgbnVtRWxlbWVudHMgPSB2aWV3LmdldFVpbnQ4KGJsb2NrUHRyKTsgYmxvY2tQdHIrKzsKICAgICAgICAgICAgfSBlbHNlIGlmIChuID09PSAyKSB7CiAgICAgICAgICAgICAgbnVtRWxlbWVudHMgPSB2aWV3LmdldFVpbnQxNihibG9ja1B0ciwgdHJ1ZSk7IGJsb2NrUHRyICs9IDI7CiAgICAgICAgICAgIH0gZWxzZSBpZiAobiA9PT0gNCkgewogICAgICAgICAgICAgIG51bUVsZW1lbnRzID0gdmlldy5nZXRVaW50MzIoYmxvY2tQdHIsIHRydWUpOyBibG9ja1B0ciArPSA0OwogICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgIHRocm93ICJJbnZhbGlkIHZhbGlkIHBpeGVsIGNvdW50IHR5cGUiOwogICAgICAgICAgICB9CiAgICAgICAgICAgIC8vZml4OiBodWZmbWFuIGNvZGVzIGFyZSBiaXQgc3R1ZmZlZCwgYnV0IG5vdCBib3VuZCBieSBkYXRhJ3MgbWF4IHZhbHVlLCBzbyBuZWVkIHRvIHVzZSBvcmlnaW5hbFVuc3R1ZmYKICAgICAgICAgICAgLy9vZmZzZXQgPSBvZmZzZXQgfHwgMDsKICAgICAgICAgICAgdmFyIHNjYWxlID0gMiAqIGhlYWRlckluZm8ubWF4WkVycm9yOwogICAgICAgICAgICB2YXIgc3R1ZmZlZERhdGEsIGFycmF5QnVmLCBzdG9yZTgsIGRhdGFCeXRlcywgZGF0YVdvcmRzOwogICAgICAgICAgICB2YXIgbHV0QXJyLCBsdXREYXRhLCBsdXRCeXRlcywgYml0c1BlclBpeGVsOwogICAgICAgICAgICB2YXIgek1heCA9IGhlYWRlckluZm8ubnVtRGltcyA+IDEgPyBoZWFkZXJJbmZvLm1heFZhbHVlc1tpRGltXSA6IGhlYWRlckluZm8uek1heDsKICAgICAgICAgICAgaWYgKGRvTHV0KSB7CiAgICAgICAgICAgICAgZGF0YS5jb3VudGVyLmx1dCsrOwogICAgICAgICAgICAgIGx1dEJ5dGVzID0gdmlldy5nZXRVaW50OChibG9ja1B0cik7CiAgICAgICAgICAgICAgYmxvY2tQdHIrKzsKICAgICAgICAgICAgICBkYXRhQnl0ZXMgPSBNYXRoLmNlaWwoKGx1dEJ5dGVzIC0gMSkgKiBudW1CaXRzIC8gOCk7CiAgICAgICAgICAgICAgZGF0YVdvcmRzID0gTWF0aC5jZWlsKGRhdGFCeXRlcyAvIDQpOwogICAgICAgICAgICAgIGFycmF5QnVmID0gbmV3IEFycmF5QnVmZmVyKGRhdGFXb3JkcyAqIDQpOwogICAgICAgICAgICAgIHN0b3JlOCA9IG5ldyBVaW50OEFycmF5KGFycmF5QnVmKTsKCiAgICAgICAgICAgICAgZGF0YS5wdHIgKz0gYmxvY2tQdHI7CiAgICAgICAgICAgICAgc3RvcmU4LnNldChuZXcgVWludDhBcnJheShpbnB1dCwgZGF0YS5wdHIsIGRhdGFCeXRlcykpOwoKICAgICAgICAgICAgICBsdXREYXRhID0gbmV3IFVpbnQzMkFycmF5KGFycmF5QnVmKTsKICAgICAgICAgICAgICBkYXRhLnB0ciArPSBkYXRhQnl0ZXM7CgogICAgICAgICAgICAgIGJpdHNQZXJQaXhlbCA9IDA7CiAgICAgICAgICAgICAgd2hpbGUgKChsdXRCeXRlcyAtIDEpID4+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ml0U3R1ZmZlci51bnN0dWZmMihibG9jaywgYmxvY2tEYXRhQnVmZmVyLCBoZWFkZXJJbmZvLnpNYXgpOwogICAgICAgICAgICAgICAgQml0U3R1ZmZlci51bnN0dWZmMihzdHVmZmVkRGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBiaXRzUGVyUGl4ZWwsIG51bUVsZW1lbnRzLCBsdXRBcnIpOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIEJpdFN0dWZmZXIudW5zdHVmZihzdHVmZmVkRGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBiaXRzUGVyUGl4ZWwsIG51bUVsZW1lbnRzLCBsdXRBcnIpOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAvL2NvbnNvbGUuZGVidWcoImJpdHN0dWZmZXIiKTsKICAgICAgICAgICAgICBkYXRhLmNvdW50ZXIuYml0c3R1ZmZlcisrOwogICAgICAgICAgICAgIGJpdHNQZXJQaXhlbCA9IG51bUJpdHM7CiAgICAgICAgICAgICAgZGF0YS5wdHIgKz0gYmxvY2tQdHI7CiAgICAgICAgICAgICAgaWYgKGJpdHNQZXJQaXhlbCA+IDApIHsKICAgICAgICAgICAgICAgIGRhdGFCeXRlcyA9IE1hdGguY2VpbChudW1FbGVtZW50cyAqIGJpdHNQZXJQaXhlbCAvIDgpOwogICAgICAgICAgICAgICAgZGF0YVdvcmRzID0gTWF0aC5jZWlsKGRhdGFCeXRlcyAvIDQpOwogICAgICAgICAgICAgICAgYXJyYXlCdWYgPSBuZXcgQXJyYXlCdWZmZXIoZGF0YVdvcmRzICogNCk7CiAgICAgICAgICAgICAgICBzdG9yZTggPSBuZXcgVWludDhBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgICAgICBzdG9yZTguc2V0KG5ldyBVaW50OEFycmF5KGlucHV0LCBkYXRhLnB0ciwgZGF0YUJ5dGVzKSk7CiAgICAgICAgICAgICAgICBzdHVmZmVkRGF0YSA9IG5ldyBVaW50MzJBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgICAgICBkYXRhLnB0ciArPSBkYXRhQnl0ZXM7CiAgICAgICAgICAgICAgICBpZiAoZmlsZVZlcnNpb24gPj0gMykgewogICAgICAgICAgICAgICAgICBpZiAob2Zmc2V0ID09IG51bGwpIHsKICAgICAgICAgICAgICAgICAgICBCaXRTdHVmZmVyLm9yaWdpbmFsVW5zdHVmZjIoc3R1ZmZlZERhdGEsIGJsb2NrRGF0YUJ1ZmZlciwgYml0c1BlclBpeGVsLCBudW1FbGVtZW50cyk7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgQml0U3R1ZmZlci51bnN0dWZmMihzdHVmZmVkRGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBiaXRzUGVyUGl4ZWwsIG51bUVsZW1lbnRzLCBmYWxzZSwgb2Zmc2V0LCBzY2FsZSwgek1heCk7CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgICBpZiAob2Zmc2V0ID09IG51bGwpIHsKICAgICAgICAgICAgICAgICAgICBCaXRTdHVmZmVyLm9yaWdpbmFsVW5zdHVmZihzdHVmZmVkRGF0YSwgYmxvY2tEYXRhQnVmZmVyLCBiaXRzUGVyUGl4ZWwsIG51bUVsZW1lbnRzKTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICBCaXRTdHVmZmVyLnVuc3R1ZmYoc3R1ZmZlZERhdGEsIGJsb2NrRGF0YUJ1ZmZlciwgYml0c1BlclBpeGVsLCBudW1FbGVtZW50cywgZmFsc2UsIG9mZnNldCwgc2NhbGUsIHpNYXgpOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgIC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iArIGJsb2NrWSArICIgeCIgKyBibG9ja1gpOwogICAgICAgICAgICAgIHRoaXNCbG9ja1dpZHRoID0gKGJsb2NrWCAhPT0gbnVtQmxvY2tzWCAtIDEpID8gbWljcm9CbG9ja1NpemUgOiBsYXN0QmxvY2tXaWR0aDsKCiAgICAgICAgICAgICAgb3V0UHRyID0gYmxvY2tZICogd2lkdGggKiBtaWNyb0Jsb2NrU2l6ZSArIGJsb2NrWCAqIG1pY3JvQmxvY2tTaXplOwogICAgICAgICAgICAgIG91dFN0cmlkZSA9IHdpZHRoIC0gdGhpc0Jsb2NrV2lkdGg7CgoKICAgICAgICAgICAgICBmb3IgKGlEaW0gPSAwOyBpRGltIDwgbnVtRGltczsgaURpbSsrKSB7CiAgICAgICAgICAgICAgICBpZiAobnVtRGltcyA+IDEpIHsKICAgICAgICAgICAgICAgICAgcmVzdWx0UGl4ZWxzID0gbmV3IE91dFBpeGVsVHlwZUFycmF5KGRhdGEucGl4ZWxzLnJlc3VsdFBpeGVscy5idWZmZXIsIHdpZHRoICogaGVpZ2h0ICogaURpbSAqIGRhdGFUeXBlU2l6ZSwgd2lkdGggKiBoZWlnaHQpOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgYnl0ZXNMZWZ0ID0gaW5wdXQuYnl0ZUxlbmd0aCAtIGRhdGEucHRyOwogICAgICAgICAgICAgICAgdmlldyA9IG5ldyBEYXRhVmlldyhpbnB1dCwgZGF0YS5wdHIsIE1hdGgubWluKDEwLCBieXRlc0xlZnQpKTsKICAgICAgICAgICAgICAgIGJsb2NrID0ge307CiAgICAgICAgICAgICAgICBibG9ja1B0ciA9IDA7CiAgICAgICAgICAgICAgICBoZWFkZXJCeXRlID0gdmlldy5nZXRVaW50OCgwKTsKICAgICAgICAgICAgICAgIGJsb2NrUHRyKys7CiAgICAgICAgICAgICAgICBiaXRzNjcgPSAoaGVhZGVyQnl0ZSA+PiA2KSAmIDB4RkY7CiAgICAgICAgICAgICAgICB0ZXN0Q29kZSA9IChoZWFkZXJCeXRlID4+IDIpICYgMTU7ICAgIC8vIHVzZSBiaXRzIDIzNDUgZm9yIGludGVncml0eSBjaGVjawogICAgICAgICAgICAgICAgaWYgKHRlc3RDb2RlICE9PSAoKChibG9ja1ggKiBtaWNyb0Jsb2NrU2l6ZSkgPj4gMykgJiAxNSkpIHsKICAgICAgICAgICAgICAgICAgdGhyb3cgImludGVncml0eSBpc3N1ZSI7CiAgICAgICAgICAgICAgICAgIC8vcmV0dXJuIGZhbHNlOwogICAgICAgICAgICAgICAgfQoKICAgICAgICAgICAgICAgIGJsb2NrRW5jb2RpbmcgPSBoZWFkZXJCeXRlICYgMzsKICAgICAgICAgICAgICAgIGlmIChibG9ja0VuY29kaW5nID4gMykgewogICAgICAgICAgICAgICAgICBkYXRhLnB0ciArPSBibG9ja1B0cjsKICAgICAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgYmxvY2sgZW5jb2RpbmcgKCIgKyBibG9ja0VuY29kaW5nICsgIikiOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZWxzZSBpZiAoYmxvY2tFbmNvZGluZyA9PT0gMikgeyAvL2NvbnN0YW50IDAKICAgICAgICAgICAgICAgICAgZGF0YS5jb3VudGVyLmNvbnN0YW50Kys7CiAgICAgICAgICAgICAgICAgIGRhdGEucHRyICs9IGJsb2NrUHRyOwogICAgICAgICAgICAgICAgICBjb250aW51ZTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGVsc2UgaWYgKGJsb2NrRW5jb2RpbmcgPT09IDApIHsgIC8vdW5jb21wcmVzc2VkCiAgICAgICAgICAgICAgICAgIGRhdGEuY291bnRlci51bmNvbXByZXNzZWQrKzsKICAgICAgICAgICAgICAgICAgZGF0YS5wdHIgKz0gYmxvY2tQdHI7CiAgICAgICAgICAgICAgICAgIG51bUJ5dGVzID0gdGhpc0Jsb2NrSGVpZ2h0ICogdGhpc0Jsb2NrV2lkdGggKiBkYXRhVHlwZVNpemU7CiAgICAgICAgICAgICAgICAgIGJ5dGVzbGVmdCA9IGlucHV0LmJ5dGVMZW5ndGggLSBkYXRhLnB0cjsKICAgICAgICAgICAgICAgICAgbnVtQnl0ZXMgPSBudW1CeXRlcyA8IGJ5dGVzbGVmdCA/IG51bUJ5dGVzIDogYnl0ZXNsZWZ0OwogICAgICAgICAgICAgICAgICAvL2JpdCBhbGlnbm1lbnQKICAgICAgICAgICAgICAgICAgYXJyYXlCdWYgPSBuZXcgQXJyYXlCdWZmZXIoKG51bUJ5dGVzICUgZGF0YVR5cGVTaXplKSA9PT0gMCA/IG51bUJ5dGVzIDogKG51bUJ5dGVzICsgZGF0YVR5cGVTaXplIC0gbnVtQnl0ZXMgJSBkYXRhVHlwZVNpemUpKTsKICAgICAgICAgICAgICAgICAgc3RvcmU4ID0gbmV3IFVpbnQ4QXJyYXkoYXJyYXlCdWYpOwogICAgICAgICAgICAgICAgICBzdG9yZTguc2V0KG5ldyBVaW50OEFycmF5KGlucHV0LCBkYXRhLnB0ciwgbnVtQnl0ZXMpKTsKICAgICAgICAgICAgICAgICAgcmF3RGF0YSA9IG5ldyBPdXRQaXhlbFR5cGVBcnJheShhcnJheUJ1Zik7CiAgICAgICAgICAgICAgICAgIHogPSAwOwogICAgICAgICAgICAgICAgICBpZiAobWFzaykgewogICAgICAgICAgICAgICAgICAgIGZvciAocm93ID0gMDsgcm93IDwgdGhpc0Jsb2NrSGVpZ2h0OyByb3crKykgewogICAgICAgICAgICAgICAgICAgICAgZm9yIChjb2wgPSAwOyBjb2wgPCB0aGlzQmxvY2tXaWR0aDsgY29sKyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgaWYgKG1hc2tbb3V0UHRyXSkgewogICAgICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHJdID0gcmF3RGF0YVt6KytdOwogICAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICAgIG91dFB0cisrOwogICAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7Ly9hbGwgdmFsaWQKICAgICAgICAgICAgICAgICAgICBmb3IgKHJvdyA9IDA7IHJvdyA8IHRoaXNCbG9ja0hlaWdodDsgcm93KyspIHsKICAgICAgICAgICAgICAgICAgICAgIGZvciAoY29sID0gMDsgY29sIDwgdGhpc0Jsb2NrV2lkdGg7IGNvbCsrKSB7CiAgICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHIrK10gPSByYXdEYXRhW3orK107CiAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICBvdXRQdHIgKz0gb3V0U3RyaWRlOwogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBkYXRhLnB0ciArPSB6ICogZGF0YVR5cGVTaXplOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZWxzZSB7IC8vMSBvciAzCiAgICAgICAgICAgICAgICAgIG9mZnNldFR5cGUgPSBMZXJjMkhlbHBlcnMuZ2V0RGF0YVR5cGVVc2VkKGltYWdlVHlwZSwgYml0czY3KTsKICAgICAgICAgICAgICAgICAgb2Zmc2V0ID0gTGVyYzJIZWxwZXJzLmdldE9uZVBpeGVsKGJsb2NrLCBibG9ja1B0ciwgb2Zmc2V0VHlwZSwgdmlldyk7CiAgICAgICAgICAgICAgICAgIGJsb2NrUHRyICs9IExlcmMySGVscGVycy5nZXREYXRhVHlwZVNpemUob2Zmc2V0VHlwZSk7CiAgICAgICAgICAgICAgICAgIGlmIChibG9ja0VuY29kaW5nID09PSAzKSAvL2NvbnN0YW50IG9mZnNldCB2YWx1ZQogICAgICAgICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAgICAgZGF0YS5wdHIgKz0gYmxvY2tQdHI7CiAgICAgICAgICAgICAgICAgICAgZGF0YS5jb3VudGVyLmNvbnN0YW50b2Zmc2V0Kys7CiAgICAgICAgICAgICAgICAgICAgLy95b3UgY2FuIGRlbGV0ZSB0aGUgZm9sbG93aW5nIHJlc3VsdE1hc2sgY2FzZSBpbiBmYXZvciBvZiBwZXJmb3JtYW5jZSBiZWNhdXNlIHZhbCBpcyBjb25zdGFudCBhbmQgdXNlcnMgdXNlIG5vZGF0YSBtYXNrLCBvdGhlcndpc2Ugbm9kYXRhdmFsdWUgcG9zdCBwcm9jZXNzaW5nIGhhbmRsZXMgaXQgdG9vLgogICAgICAgICAgICAgICAgICAgIC8vd2hpbGUgdGhlIGFib3ZlIHN0YXRlbWVudCBpcyB0cnVlLCB3ZSdyZSBub3QgZG9pbmcgaXQgYXMgd2Ugd2FudCB0byBrZWVwIGludmFsaWQgcGl4ZWwgdmFsdWUgYXQgMCByYXRoZXIgdGhhbiBhcmJpdHJhcnkgdmFsdWVzCiAgICAgICAgICAgICAgICAgICAgaWYgKG1hc2spIHsKICAgICAgICAgICAgICAgICAgICAgIGZvciAocm93ID0gMDsgcm93IDwgdGhpc0Jsb2NrSGVpZ2h0OyByb3crKykgewogICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGNvbCA9IDA7IGNvbCA8IHRoaXNCbG9ja1dpZHRoOyBjb2wrKykgewogICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChtYXNrW291dFB0cl0pIHsKICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHJdID0gb2Zmc2V0OwogICAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgICAgICBvdXRQdHIrKzsKICAgICAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgICAgICBvdXRQdHIgKz0gb3V0U3RyaWRlOwogICAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICAgIGZvciAocm93ID0gMDsgcm93IDwgdGhpc0Jsb2NrSGVpZ2h0OyByb3crKykgewogICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGNvbCA9IDA7IGNvbCA8IHRoaXNCbG9ja1dpZHRoOyBjb2wrKykgewogICAgICAgICAgICAgICAgICAgICAgICAgIHJlc3VsdFBpeGVsc1tvdXRQdHIrK10gPSBvZmZzZXQ7CiAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgZWxzZSB7IC8vYml0c3R1ZmYgZW5jb2RpbmcgaXMgMwogICAgICAgICAgICAgICAgICAgIGRhdGEucHRyICs9IGJsb2NrUHRyOwogICAgICAgICAgICAgICAgICAgIC8vaGVhdnkgbGlmdGluZwogICAgICAgICAgICAgICAgICAgIExlcmMySGVscGVycy5kZWNvZGVCaXRzKGlucHV0LCBkYXRhLCBibG9ja0RhdGFCdWZmZXIsIG9mZnNldCwgaURpbSk7CiAgICAgICAgICAgICAgICAgICAgYmxvY2tQdHIgPSAwOwogICAgICAgICAgICAgICAgICAgIGlmIChtYXNrKSB7CiAgICAgICAgICAgICAgICAgICAgICBmb3IgKHJvdyA9IDA7IHJvdyA8IHRoaXNCbG9ja0hlaWdodDsgcm93KyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgZm9yIChjb2wgPSAwOyBjb2wgPCB0aGlzQmxvY2tXaWR0aDsgY29sKyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgICBpZiAobWFza1tvdXRQdHJdKSB7CiAgICAgICAgICAgICAgICAgICAgICAgICAgICByZXN1bHRQaXhlbHNbb3V0UHRyXSA9IGJsb2NrRGF0YUJ1ZmZlcltibG9ja1B0cisrXTsKICAgICAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICAgICAgb3V0UHRyKys7CiAgICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICAgICAgb3V0UHRyICs9IG91dFN0cmlkZTsKICAgICAgICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgICAgICAgICBmb3IgKHJvdyA9IDA7IHJvdyA8IHRoaXNCbG9ja0hlaWdodDsgcm93KyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgZm9yIChjb2wgPSAwOyBjb2wgPCB0aGlzQmxvY2tXaWR0aDsgY29sKyspIHsKICAgICAgICAgICAgICAgICAgICAgICAgICByZXN1bHRQaXhlbHNbb3V0UHRyKytdID0gYmxvY2tEYXRhQnVmZmVyW2Jsb2NrUHRyKytdOwogICAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICAgIG91dFB0ciArPSBvdXRTdHJpZGU7CiAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgfSwKCiAgICAgICAgLyoqKioqKioqKioqKioqKioqCiAgICAgICAgKiAgcHJpdmF0ZSBtZXRob2RzIChoZWxwZXIgbWV0aG9kcykKICAgICAgICAqKioqKioqKioqKioqKioqKi8KCiAgICAgICAgZm9ybWF0RmlsZUluZm86IGZ1bmN0aW9uKGRhdGEpIHsKICAgICAgICAgIHJldHVybiB7CiAgICAgICAgICAgICJmaWxlSWRlbnRpZmllclN0cmluZyI6IGRhdGEuaGVhZGVySW5mby5maWxlSWRlbnRpZmllclN0cmluZywKICAgICAgICAgICAgImZpbGVWZXJzaW9uIjogZGF0YS5oZWFkZXJJbmZvLmZpbGVWZXJzaW9uLAogICAgICAgICAgICAiaW1hZ2VUeXBlIjogZGF0YS5oZWFkZXJJbmZvLmltYWdlVHlwZSwKICAgICAgICAgICAgImhlaWdodCI6IGRhdGEuaGVhZGVySW5mby5oZWlnaHQsCiAgICAgICAgICAgICJ3aWR0aCI6IGRhdGEuaGVhZGVySW5mby53aWR0aCwKICAgICAgICAgICAgIm51bVZhbGlkUGl4ZWwiOiBkYXRhLmhlYWRlckluZm8ubnVtVmFsaWRQaXhlbCwKICAgICAgICAgICAgIm1pY3JvQmxvY2tTaXplIjogZGF0YS5oZWFkZXJJbmZvLm1pY3JvQmxvY2tTaXplLAogICAgICAgICAgICAiYmxvYlNpemUiOiBkYXRhLmhlYWRlckluZm8uYmxvYlNpemUsCiAgICAgICAgICAgICJtYXhaRXJyb3IiOiBkYXRhLmhlYWRlckluZm8ubWF4WkVycm9yLAogICAgICAgICAgICAicGl4ZWxUeXBlIjogTGVyYzJIZWxwZXJzLmdldFBpeGVsVHlwZShkYXRhLmhlYWRlckluZm8uaW1hZ2VUeXBlKSwKICAgICAgICAgICAgImVvZk9mZnNldCI6IGRhdGEuZW9mT2Zmc2V0LAogICAgICAgICAgICAibWFzayI6IGRhdGEubWFzayA/IHsKICAgICAgICAgICAgICAibnVtQnl0ZXMiOiBkYXRhLm1hc2subnVtQnl0ZXMKICAgICAgICAgICAgfSA6IG51bGwsCiAgICAgICAgICAgICJwaXhlbHMiOiB7CiAgICAgICAgICAgICAgIm51bUJsb2Nrc1giOiBkYXRhLnBpeGVscy5udW1CbG9ja3NYLAogICAgICAgICAgICAgICJudW1CbG9ja3NZIjogZGF0YS5waXhlbHMubnVtQmxvY2tzWSwKICAgICAgICAgICAgICAvLyJudW1CeXRlcyI6IGRhdGEucGl4ZWxzLm51bUJ5dGVzLAogICAgICAgICAgICAgICJtYXhWYWx1ZSI6IGRhdGEuaGVhZGVySW5mby56TWF4LAogICAgICAgICAgICAgICJtaW5WYWx1ZSI6IGRhdGEuaGVhZGVySW5mby56TWluLAogICAgICAgICAgICAgICJub0RhdGFWYWx1ZSI6IGRhdGEubm9EYXRhVmFsdWUKICAgICAgICAgICAgfQogICAgICAgICAgfTsKICAgICAgICB9LAoKICAgICAgICBjb25zdHJ1Y3RDb25zdGFudFN1cmZhY2U6IGZ1bmN0aW9uKGRhdGEpIHsKICAgICAgICAgIHZhciB2YWwgPSBkYXRhLmhlYWRlckluZm8uek1heDsKICAgICAgICAgIHZhciBudW1EaW1zID0gIGRhdGEuaGVhZGVySW5mby5udW1EaW1zOwogICAgICAgICAgdmFyIG51bVBpeGVscyA9IGRhdGEuaGVhZGVySW5mby5oZWlnaHQgKiBkYXRhLmhlYWRlckluZm8ud2lkdGg7CiAgICAgICAgICB2YXIgbnVtUGl4ZWxBbGxEaW1zID0gbnVtUGl4ZWxzICogbnVtRGltczsKICAgICAgICAgIHZhciBpPTAsIGsgPSAwLCBuU3RhcnQ9MDsKICAgICAgICAgIHZhciBtYXNrID0gZGF0YS5waXhlbHMucmVzdWx0TWFzazsKICAgICAgICAgIGlmIChtYXNrKSB7CiAgICAgICAgICAgIGlmIChudW1EaW1zID4gMSkgewogICAgICAgICAgICAgIGZvciAoaT0wOyBpIDwgbnVtRGltczsgaSsrKSB7CiAgICAgICAgICAgICAgICBuU3RhcnQgPSBpICogbnVtUGl4ZWxzOwogICAgICAgICAgICAgICAgZm9yIChrID0gMDsgayA8IG51bVBpeGVsczsgaysrKSB7CiAgICAgICAgICAgICAgICAgIGlmIChtYXNrW2tdKSB7CiAgICAgICAgICAgICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0UGl4ZWxzW25TdGFydCArIGtdID0gdmFsOwogICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgIGZvciAoayA9IDA7IGsgPCBudW1QaXhlbHM7IGsrKykgewogICAgICAgICAgICAgICAgaWYgKG1hc2tba10pIHsKICAgICAgICAgICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0UGl4ZWxzW2tdID0gdmFsOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgIGlmIChkYXRhLnBpeGVscy5yZXN1bHRQaXhlbHMuZmlsbCkgewogICAgICAgICAgICAgIGRhdGEucGl4ZWxzLnJlc3VsdFBpeGVscy5maWxsKHZhbCk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgZm9yIChrID0gMDsgayA8IG51bVBpeGVsQWxsRGltczsgaysrKSB7CiAgICAgICAgICAgICAgICBkYXRhLnBpeGVscy5yZXN1bHRQaXhlbHNba10gPSB2YWw7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm47CiAgICAgICAgfSwKCiAgICAgICAgZ2V0RGF0YVR5cGVBcnJheTogZnVuY3Rpb24odCkgewogICAgICAgICAgdmFyIHRwOwogICAgICAgICAgc3dpdGNoICh0KSB7CiAgICAgICAgICAgIGNhc2UgMDogLy9jaGFyCiAgICAgICAgICAgICAgdHAgPSBJbnQ4QXJyYXk7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlCiAgICAgICAgICAgICAgdHAgPSBVaW50OEFycmF5OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDI6IC8vc2hvcnQKICAgICAgICAgICAgICB0cCA9IEludDE2QXJyYXk7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMzogLy91c2hvcnQKICAgICAgICAgICAgICB0cCA9IFVpbnQxNkFycmF5OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDQ6CiAgICAgICAgICAgICAgdHAgPSBJbnQzMkFycmF5OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDU6CiAgICAgICAgICAgICAgdHAgPSBVaW50MzJBcnJheTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA2OgogICAgICAgICAgICAgIHRwID0gRmxvYXQzMkFycmF5OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDc6CiAgICAgICAgICAgICAgdHAgPSBGbG9hdDY0QXJyYXk7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgdHAgPSBGbG9hdDMyQXJyYXk7CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm4gdHA7CiAgICAgICAgfSwKCiAgICAgICAgZ2V0UGl4ZWxUeXBlOiBmdW5jdGlvbih0KSB7CiAgICAgICAgICB2YXIgdHA7CiAgICAgICAgICBzd2l0Y2ggKHQpIHsKICAgICAgICAgICAgY2FzZSAwOiAvL2NoYXIKICAgICAgICAgICAgICB0cCA9ICJTOCI7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlCiAgICAgICAgICAgICAgdHAgPSAiVTgiOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDI6IC8vc2hvcnQKICAgICAgICAgICAgICB0cCA9ICJTMTYiOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDM6IC8vdXNob3J0CiAgICAgICAgICAgICAgdHAgPSAiVTE2IjsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA0OgogICAgICAgICAgICAgIHRwID0gIlMzMiI7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNToKICAgICAgICAgICAgICB0cCA9ICJVMzIiOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDY6CiAgICAgICAgICAgICAgdHAgPSAiRjMyIjsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA3OgogICAgICAgICAgICAgIHRwID0gIkY2NCI7IC8vbm90IHN1cHBvcnRlZAogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgIHRwID0gIkYzMiI7CiAgICAgICAgICB9CiAgICAgICAgICByZXR1cm4gdHA7CiAgICAgICAgfSwKCiAgICAgICAgaXNWYWxpZFBpeGVsVmFsdWU6IGZ1bmN0aW9uKHQsIHZhbCkgewogICAgICAgICAgaWYgKHZhbCA9PSBudWxsKSB7CiAgICAgICAgICAgIHJldHVybiBmYWxzZTsKICAgICAgICAgIH0KICAgICAgICAgIHZhciBpc1ZhbGlkOwogICAgICAgICAgc3dpdGNoICh0KSB7CiAgICAgICAgICAgIGNhc2UgMDogLy9jaGFyCiAgICAgICAgICAgICAgaXNWYWxpZCA9IHZhbCA+PSAtMTI4ICYmIHZhbCA8PSAxMjc7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlICAodW5zaWduZWQgY2hhcikKICAgICAgICAgICAgICBpc1ZhbGlkID0gdmFsID49IDAgJiYgdmFsIDw9IDI1NTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAyOiAvL3Nob3J0CiAgICAgICAgICAgICAgaXNWYWxpZCA9IHZhbCA+PSAtMzI3NjggJiYgdmFsIDw9IDMyNzY3OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDM6IC8vdXNob3J0CiAgICAgICAgICAgICAgaXNWYWxpZCA9IHZhbCA+PSAwICYmIHZhbCA8PSA2NTUzNjsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA0OiAvL2ludCAzMgogICAgICAgICAgICAgIGlzVmFsaWQgPSB2YWwgPj0gLTIxNDc0ODM2NDggJiYgdmFsIDw9IDIxNDc0ODM2NDc7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNTogLy91aW5pdCAzMgogICAgICAgICAgICAgIGlzVmFsaWQgPSB2YWwgPj0gMCAmJiB2YWwgPD0gNDI5NDk2NzI5NjsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA2OgogICAgICAgICAgICAgIGlzVmFsaWQgPSB2YWwgPj0gLTMuNDAyNzk5OTM4NzkwMTQ4NGUrMzggJiYgdmFsIDw9IDMuNDAyNzk5OTM4NzkwMTQ4NGUrMzg7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNzoKICAgICAgICAgICAgICBpc1ZhbGlkID0gdmFsID49IDVlLTMyNCAmJiB2YWwgPD0gMS43OTc2OTMxMzQ4NjIzMTU3ZSszMDg7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgaXNWYWxpZCA9IGZhbHNlOwogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuIGlzVmFsaWQ7CiAgICAgICAgfSwKCiAgICAgICAgZ2V0RGF0YVR5cGVTaXplOiBmdW5jdGlvbih0KSB7CiAgICAgICAgICB2YXIgcyA9IDA7CiAgICAgICAgICBzd2l0Y2ggKHQpIHsKICAgICAgICAgICAgY2FzZSAwOiAvL3VieXRlCiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlCiAgICAgICAgICAgICAgcyA9IDE7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMjogLy9zaG9ydAogICAgICAgICAgICBjYXNlIDM6IC8vdXNob3J0CiAgICAgICAgICAgICAgcyA9IDI7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNDoKICAgICAgICAgICAgY2FzZSA1OgogICAgICAgICAgICBjYXNlIDY6CiAgICAgICAgICAgICAgcyA9IDQ7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNzoKICAgICAgICAgICAgICBzID0gODsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgZGVmYXVsdDoKICAgICAgICAgICAgICBzID0gdDsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiBzOwogICAgICAgIH0sCgogICAgICAgIGdldERhdGFUeXBlVXNlZDogZnVuY3Rpb24oZHQsIHRjKSB7CiAgICAgICAgICB2YXIgdCA9IGR0OwogICAgICAgICAgc3dpdGNoIChkdCkgewogICAgICAgICAgICBjYXNlIDI6IC8vc2hvcnQKICAgICAgICAgICAgY2FzZSA0OiAvL2xvbmcKICAgICAgICAgICAgICB0ID0gZHQgLSB0YzsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAzOiAvL3VzaG9ydAogICAgICAgICAgICBjYXNlIDU6IC8vdWxvbmcKICAgICAgICAgICAgICB0ID0gZHQgLSAyICogdGM7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNjogLy9mbG9hdAogICAgICAgICAgICAgIGlmICgwID09PSB0YykgewogICAgICAgICAgICAgICAgdCA9IGR0OwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIGlmICgxID09PSB0YykgewogICAgICAgICAgICAgICAgdCA9IDI7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgdCA9IDE7Ly9ieXRlCiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDc6IC8vZG91YmxlCiAgICAgICAgICAgICAgaWYgKDAgPT09IHRjKSB7CiAgICAgICAgICAgICAgICB0ID0gZHQ7CiAgICAgICAgICAgICAgfQogICAgICAgICAgICAgIGVsc2UgewogICAgICAgICAgICAgICAgdCA9IGR0IC0gMiAqIHRjICsgMTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgdCA9IGR0OwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQogICAgICAgICAgcmV0dXJuIHQ7CiAgICAgICAgfSwKCiAgICAgICAgZ2V0T25lUGl4ZWw6IGZ1bmN0aW9uKGJsb2NrLCBibG9ja1B0ciwgb2Zmc2V0VHlwZSwgdmlldykgewogICAgICAgICAgdmFyIHRlbXAgPSAwOwogICAgICAgICAgc3dpdGNoIChvZmZzZXRUeXBlKSB7CiAgICAgICAgICAgIGNhc2UgMDogLy9jaGFyCiAgICAgICAgICAgICAgdGVtcCA9IHZpZXcuZ2V0SW50OChibG9ja1B0cik7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgMTogLy9ieXRlCiAgICAgICAgICAgICAgdGVtcCA9IHZpZXcuZ2V0VWludDgoYmxvY2tQdHIpOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDI6CiAgICAgICAgICAgICAgdGVtcCA9IHZpZXcuZ2V0SW50MTYoYmxvY2tQdHIsIHRydWUpOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBjYXNlIDM6CiAgICAgICAgICAgICAgdGVtcCA9IHZpZXcuZ2V0VWludDE2KGJsb2NrUHRyLCB0cnVlKTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA0OgogICAgICAgICAgICAgIHRlbXAgPSB2aWV3LmdldEludDMyKGJsb2NrUHRyLCB0cnVlKTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA1OgogICAgICAgICAgICAgIHRlbXAgPSB2aWV3LmdldFVJbnQzMihibG9ja1B0ciwgdHJ1ZSk7CiAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgNjoKICAgICAgICAgICAgICB0ZW1wID0gdmlldy5nZXRGbG9hdDMyKGJsb2NrUHRyLCB0cnVlKTsKICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSA3OgogICAgICAgICAgICAgIC8vdGVtcCA9IHZpZXcuZ2V0RmxvYXQ2NChibG9ja1B0ciwgdHJ1ZSk7CiAgICAgICAgICAgICAgLy9ibG9ja1B0ciArPSA4OwogICAgICAgICAgICAgIC8vbGVyYzIgZW5jb2RpbmcgZG9lc250IGhhbmRsZSBmbG9hdCA2NCwgZm9yY2UgdG8gZmxvYXQzMj8/PwogICAgICAgICAgICAgIHRlbXAgPSB2aWV3LmdldEZsb2F0NjQoYmxvY2tQdHIsIHRydWUpOwogICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICAgIHRocm93ICgidGhlIGRlY29kZXIgZG9lcyBub3QgdW5kZXJzdGFuZCB0aGlzIHBpeGVsIHR5cGUiKTsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiB0ZW1wOwogICAgICAgIH0KICAgICAgfTsKCiAgICAgIC8qKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioKICAgICAgKnByaXZhdGUgY2xhc3MgZm9yIGEgdHJlZSBub2RlLiBIdWZmbWFuIGNvZGUgaXMgaW4gTGVyYzJIZWxwZXJzCiAgICAgICoqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKiovCiAgICAgIHZhciBUcmVlTm9kZSA9IGZ1bmN0aW9uKHZhbCwgbGVmdCwgcmlnaHQpIHsKICAgICAgICB0aGlzLnZhbCA9IHZhbDsKICAgICAgICB0aGlzLmxlZnQgPSBsZWZ0OwogICAgICAgIHRoaXMucmlnaHQgPSByaWdodDsKICAgICAgfTsKCiAgICAgIHZhciBMZXJjMkRlY29kZSA9IHsKICAgICAgICAvKgogICAgICAgICogKioqKioqKipyZW1vdmVkIG9wdGlvbnMgY29tcGFyZWQgdG8gTEVSQzEuIFdlIGNhbiBicmluZyBzb21lIG9mIHRoZW0gYmFjayBpZiBuZWVkZWQuCiAgICAgICAgICogcmVtb3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pbmcgKGxlc3MgZWZmaWNpZW50KQogICAgICAgICAqIHJlbW92ZWQgY29tcHV0ZVVzZWRCaXREZXB0aHMuCiAgICAgICAgICoKICAgICAgICAgKgogICAgICAgICAqIHJlc3BvbnNlIGNoYW5nZXMgY29tcGFyZWQgdG8gTEVSQzEKICAgICAgICAgKiAxLiBlbmNvZGVkTWFza0RhdGEgaXMgbm90IGF2YWlsYWJsZQogICAgICAgICAqIDIuIG5vRGF0YVZhbHVlIGlzIG9wdGlvbmFsIChyZXR1cm5zIG9ubHkgaWYgdXNlcidzIG5vRGF0YVZhbHVlIGlzIHdpdGggaW4gdGhlIHZhbGlkIGRhdGEgdHlwZSByYW5nZSkKICAgICAgICAgKiAzLiBtYXNrRGF0YSBpcyBhbHdheXMgYXZhaWxhYmxlCiAgICAgICAgKi8KICAgICAgICAvKioqKioqKioqKioqKioqKioKICAgICAgICAqICBwdWJsaWMgcHJvcGVydGllcwogICAgICAgICoqKioqKioqKioqKioqKioqKi8KICAgICAgICAvL0hVRkZNQU5fTFVUX0JJVFNfTUFYOiAxMiwgLy91c2UgMl4xMiBsdXQsIG5vdCBjb25maWd1cmFibGUKCiAgICAgICAgLyoqKioqKioqKioqKioqKioqCiAgICAgICAgKiAgcHVibGljIG1ldGhvZHMKICAgICAgICAqKioqKioqKioqKioqKioqKi8KCiAgICAgICAgLyoqCiAgICAgICAgICogRGVjb2RlIGEgTEVSQzIgYnl0ZSBzdHJlYW0gYW5kIHJldHVybiBhbiBvYmplY3QgY29udGFpbmluZyB0aGUgcGl4ZWwgZGF0YSBhbmQgb3B0aW9uYWwgbWV0YWRhdGEuCiAgICAgICAgICoKICAgICAgICAgKiBAcGFyYW0ge0FycmF5QnVmZmVyfSBpbnB1dCBUaGUgTEVSQyBpbnB1dCBieXRlIHN0cmVhbQogICAgICAgICAqIEBwYXJhbSB7b2JqZWN0fSBbb3B0aW9uc10gb3B0aW9ucyBEZWNvZGluZyBvcHRpb25zCiAgICAgICAgICogQHBhcmFtIH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FkZXJJbmZvOwogICAgICAgICAgdmFyIGZpbGVWZXJzaW9uID0gaGVhZGVySW5mby5maWxlVmVyc2lvbjsKICAgICAgICAgIHZhciBPdXRQaXhlbFR5cGVBcnJheSA9IExlcmMySGVscGVycy5nZXREYXRhVHlwZUFycmF5KGhlYWRlckluZm8uaW1hZ2VUeXBlKTsKCiAgICAgICAgICAvLyBNYXNrIEhlYWRlcgogICAgICAgICAgTGVyYzJIZWxwZXJzLnJlYWRNYXNrKGlucHV0LCBkYXRhKTsKICAgICAgICAgIGlmIChoZWFkZXJJbmZvLm51bVZhbGlkUGl4ZWwgIT09IGhlYWRlckluZm8ud2lkdGggKiBoZWFkZXJJbmZvLmhlaWdodCAmJiAhZGF0YS5waXhlbHMucmVzdWx0TWFzaykgewogICAgICAgICAgICBkYXRhLnBpeGVscy5yZXN1bHRNYXNrID0gb3B0aW9ucy5tYXNrRGF0YTsKICAgICAgICAgIH0KCiAgICAgICAgICB2YXIgbnVtUGl4ZWxzID0gaGVhZGVySW5mby53aWR0aCAqIGhlYWRlckluZm8uaGVpZ2h0OwogICAgICAgICAgZGF0YS5waXhlbHMucmVzdWx0UGl4ZWxzID0gbmV3IE91dFBpeGVsVHlwZUFycmF5KG51bVBpeGVscyAqIGhlYWRlckluZm8ubnVtRGltcyk7CgogICAgICAgICAgZGF0YS5jb3VudGVyID0gewogICAgICAgICAgICBvbmVzd2VlcDogMCwKICAgICAgICAgICAgdW5jb21wcmVzc2VkOiAwLAogICAgICAgICAgICBsdXQ6IDAsCiAgICAgICAgICAgIGJpdHN0dWZmZXI6IDAsCiAgICAgICAgICAgIGNvbnN0YW50OiAwLAogICAgICAgICAgICBjb25zdGFudG9mZnNldDogMAogICAgICAgICAgfTsKICAgICAgICAgIGlmIChoZWFkZXJJbmZvLm51bVZhbGlkUGl4ZWwgIT09IDApIHsKICAgICAgICAgICAgLy9ub3QgdGVzdGVkCiAgICAgICAgICAgIGlmIChoZWFkZXJJbmZvLnpNYXggPT09IGhlYWRlckluZm8uek1pbikgLy9jb25zdGFudCBzdXJmYWNlCiAgICAgICAgICAgIHsKICAgICAgICAgICAgICBMZXJjMkhlbHBlcnMuY29uc3RydWN0Q29uc3RhbnRTdXJmYWNlKGRhdGEpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgaWYgKGZpbGVWZXJzaW9uID49IDQgJiYgTGVyYzJIZWxwZXJzLmNoZWNrTWluTWF4UmFuZ2VzKGlucHV0LCBkYXRhKSkgewogICAgICAgICAgICAgIExlcmMySGVscGVycy5jb25zdHJ1Y3RDb25zdGFudFN1cmZhY2UoZGF0YSk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZSB7CiAgICAgICAgICAgICAgdmFyIHZpZXcgPSBuZXcgRGF0YVZpZXcoaW5wdXQsIGRhdGEucHRyLCAyKTsKICAgICAgICAgICAgICB2YXIgYlJlYWREYXRhT25lU3dlZXAgPSB2aWV3LmdldFVpbnQ4KDApOwogICAgICAgICAgICAgIGRhdGEucHRyKys7CiAgICAgICAgICAgICAgaWYgKGJSZWFkRGF0YU9uZVN3ZWVwKSB7CiAgICAgICAgICAgICAgICAvL2NvbnNvbGUuZGVidWcoIk9uZVN3ZWVwIik7CiAgICAgICAgICAgICAgICBMZXJjMkhlbHBlcnMucmVhZERhdGFPbmVTd2VlcChpbnB1dCwgZGF0YSwgT3V0UGl4ZWxUeXBlQXJyYXkpOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgIC8vbGVyYzIuMTogLy9iaXRzdHVmZmluZyArIGx1dAogICAgICAgICAgICAgICAgLy9sZXJjMi4yOiAvL2JpdHN0dWZmaW5nICsgbHV0ICsgaHVmZm1hbgogICAgICAgICAgICAgICAgLy9sZXJjMi4zOiBuZXcgYml0c3R1ZmZlcgogICAgICAgICAgICAgICAgaWYgKGZpbGVWZXJzaW9uID4gMSAmJiBoZWFkZXJJbmZvLmltYWdlVHlwZSA8PSAxICYmIE1hdGguYWJzKGhlYWRlckluZm8ubWF4WkVycm9yIC0gMC41KSA8IDAuMDAwMDEpIHsKICAgICAgICAgICAgICAgICAgLy90aGlzIGlzIDIueCBwbHVzIDggYml0ICh1bnNpZ25lZCBhbmQgc2lnbmVkKSBkYXRhLCBwb3NzaWJsaXR5IG9mIEh1ZmZtYW4KICAgICAgICAgICAgICAgICAgdmFyIGZsYWdIdWZmbWFuID0gdmlldy5nZXRVaW50OCgxKTsKICAgICAgICAgICAgICAgICAgZGF0YS5wdHIrKzsKICAgICAgICAgICAgICAgICAgZGF0YS5lbmNvZGVNb2RlID0gZmxhZ0h1ZmZtYW47CiAgICAgICAgICAgICAgICAgIGlmIChmbGFnSHVmZm1hbiA+IDIgfHwgKGZpbGVWZXJzaW9uIDwgNCAmJiBmbGFnSHVmZm1hbiA+IDEpKSB7CiAgICAgICAgICAgICAgICAgICAgdGhyb3cgIkludmFsaWQgSHVmZm1hbiBmbGFnICIgKyBmbGFnSHVmZm1hbjsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBpZiAoZmxhZ0h1ZmZtYW4pIHsvLzEgLSBkZWx0YSBIdWZmbWFuLCAyIC0gSHVmZm1hbgogICAgICAgICAgICAgICAgICAgIC8vY29uc29sZS5sb2coIkh1ZmZtYW4iKTsKICAgICAgICAgICAgICAgICAgICBMZXJjMkhlbHBlcnMucmVhZEh1ZmZtYW4oaW5wdXQsIGRhdGEsIE91dFBpeGVsVHlwZUFycmF5KTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgICBlbHNlIHsKICAgICAgICAgICAgICAgICAgICAvL2NvbnNvbGUubG9nKCJUaWxlcyIpOwogICAgICAgICAgICAgICAgICAgIExlcmMySGVscGVycy5yZWFkVGlsZXMoaW5wdXQsIGRhdGEsIE91dFBpeGVsVHlwZUFycmF5KTsKICAgICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZWxzZSB7IC8vbGVyYzIueCBub24tOCBiaXQgZGF0YQogICAgICAgICAgICAgICAgICAvL2NvbnNvbGUubG9nKCJUaWxlcyIpOwogICAgICAgICAgICAgICAgICBMZXJjMkhlbHBlcnMucmVhZFRpbGVzKGlucHV0LCBkYXRhLCBPdXRQaXhlbFR5cGVBcnJheSk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgfQogICAgICAgICAgICB9CiAgICAgICAgICB9CgogICAgICAgICAgZGF0YS5lb2ZPZmZzZXQgPSBkYXRhLnB0cjsKICAgICAgICAgIHZhciBkaWZmOwogICAgICAgICAgaWYgKG9wdGlvbnMuaW5wdXRPZmZzZXQpIHsKICAgICAgICAgICAgZGlmZiA9IGRhdGEuaGVhZGVySW5mby5ibG9iU2l6ZSArIG9wdGlvbnMuaW5wdXRPZmZzZXQgLSBkYXRhLnB0cjsKICAgICAgICAgICAgaWYgKE1hdGguYWJzKGRpZmYpID49IDEpIHsKICAgICAgICAgICAgICAvL2NvbnNvbGUuZGVidWcoImluY29ycmVjdCBlb2Y6IGRhdGFwdHIgIiArIGRhdGEucHRyICsgIiBvZmZzZXQgIiArIG9wdGlvbnMuaW5wdXRPZmZzZXQgKyAiIGJsb2JzaXplICIgKyBkYXRhLmhlYWRlckluZm8uYmxvYlNpemUgKyAiIGRpZmY6ICIgKyBkaWZmKTsKICAgICAgICAgICAgICBkYXRhLmVvZk9mZnNldCA9IG9wdGlvbnMuaW5wdXRPZmZzZXQgKyBkYXRhLmhlYWRlckluZm8uYmxvYlNpemU7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICAgIGVsc2UgewogICAgICAgICAgICBkaWZmID0gZGF0YS5oZWFkZXJJbmZvLmJsb2JTaXplIC0gZGF0YS5wdHI7CiAgICAgICAgICAgIGlmIChNYXRoLmFicyhkaWZmKSA+PSAxKSB7CiAgICAgICAgICAgICAgLy9jb25zb2xlLmRlYnVnKCJpbmNvcnJlY3QgZmlyc3QgYmFuZCBlb2Y6IGRhdGFwdHIgIiArIGRhdGEucHRyICsgIiBibG9ic2l6ZSAiICsgZGF0YS5oZWFkZXJJbmZvLmJsb2JTaXplICsgIiBkaWZmOiAiICsgZGlmZik7CiAgICAgICAgICAgICAgZGF0YS5lb2ZPZmZzZXQgPSBkYXRhLmhlYWRlckluZm8uYmxvYlNpemU7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KCiAgICAgICAgICB2YXIgcmVzdWx0ID0gewogICAgICAgICAgICB3aWR0aDogaGVhZGVySW5mby53aWR0aCwKICAgICAgICAgICAgaGVpZ2h0OiBoZWFkZXJJbmZvLmhlaWdodCwKICAgICAgICAgICAgcGl4ZWxEYXRhOiBkYXRhLnBpeGVscy5yZXN1bHRQaXhlbHMsCiAgICAgICAgICAgIG1pblZhbHVlOiBoZWFkZXJJbmZvLnpNaW4sCiAgICAgICAgICAgIG1heFZhbHVlOiBoZWFkZXJJbmZvLnpNYXgsCiAgICAgICAgICAgIHZhbGlkUGl4ZWxDb3VudDogaGVhZGVySW5mby5udW1WYWxpZFBpeGVsLAogICAgICAgICAgICBkaW1Db3VudDogaGVhZGVySW5mby5udW1EaW1zLAogICAgICAgICAgICBkaW1TdGF0czogewogICAgICAgICAgICAgIG1pblZhbHVlczogaGVhZGVySW5mby5taW5WYWx1ZXMsCiAgICAgICAgICAgICAgbWF4VmFsdWVzOiBoZWFkZXJJbmZvLm1heFZhbHVlcwogICAgICAgICAgICB9LAogICAgICAgICAgICBtYXNrRGF0YTogZGF0YS5waXhlbHMucmVzdWx0TWFzawogICAgICAgICAgICAvL25vRGF0YVZhbHVlOiBub0RhdGFWYWx1ZQogICAgICAgICAgfTsKCiAgICAgICAgICAvL3dlIHNob3VsZCByZW1vdmUgdGhpcyBpZiB0aGVyZSdzIG5vIGV4aXN0aW5nIGNsaWVudAogICAgICAgICAgLy9vcHRpb25hbCBub0RhdGFWYWx1ZSBwcm9jZXNzaW5nLCBpdCdzIHVzZXIncyByZXNwb25zaWJsaXR5CiAgICAgICAgICBpZiAoZGF0YS5waXhlbHMucmVzdWx0TWFzayAmJiBMZXJjMkhlbHBlcnMuaXNWYWxpZFBpeGVsVmFsdWUoaGVhZGVySW5mby5pbWFnZVR5cGUsIG5vRGF0YVZhbHVlKSkgewogICAgICAgICAgICB2YXIgbWFzayA9IGRhdGEucGl4ZWxzLnJlc3VsdE1hc2s7CiAgICAgICAgICAgIGZvciAoaSA9IDA7IGkgPCBudW1QaXhlbHM7IGkrKykgewogICAgICAgICAgICAgIGlmICghbWFza1tpXSkgewogICAgICAgICAgICAgICAgcmVzdWx0LnBpeGVsRGF0YVtpXSA9IG5vRGF0YVZhbHVlOwogICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgICAgICByZXN1bHQubm9EYXRhVmFsdWUgPSBub0RhdGFWYWx1ZTsKICAgICAgICAgIH0KICAgICAgICAgIGRhdGEubm9EYXRhVmFsdWUgPSBub0RhdGFWYWx1ZTsKICAgICAgICAgIGlmIChvcHRpb25zLnJldHVybkZpbGVJbmZvKSB7CiAgICAgICAgICAgIHJlc3VsdC5maWxlSW5mbyA9IExlcmMySGVscGVycy5mb3JtYXRGaWxlSW5mbyhkYXRhKTsKICAgICAgICAgIH0KICAgICAgICAgIHJldHVybiByZXN1bHQ7CiAgICAgICAgfSwKCiAgICAgICAgZ2V0QmFuZENvdW50OiBmdW5jdGlvbigvKmJ5dGUgYXJyYXkqLyBpbnB1dCkgewogICAgICAgICAgdmFyIGNvdW50ID0gMDsKICAgICAgICAgIHZhciBpID0gMDsKICAgICAgICAgIHZhciB0ZW1wID0ge307CiAgICAgICAgICB0ZW1wLnB0ciA9IDA7CiAgICAgICAgICB0ZW1wLnBpeGVscyA9IHt9OwogICAgICAgICAgd2hpbGUgKGkgPCBpbnB1dC5ieXRlTGVuZ3RoIC0gNTgpIHsKICAgICAgICAgICAgTGVyYzJIZWxwZXJzLnJlYWRIZWFkZXJJbmZvKGlucHV0LCB0ZW1wKTsKICAgICAgICAgICAgaSArPSB0ZW1wLmhlYWRlckluZm8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LmZpbGVJbmZvLm1hc2subnVtQnl0ZXMgPiAwKSB7CiAgICAgICAgICAgIGJhbmRNYXNrcy5wdXNoKHJlc3VsdC5tYXNrRGF0YSk7CiAgICAgICAgICB9CgogICAgICAgICAgaVBsYW5lKys7CiAgICAgICAgICBkZWNvZGVkUGl4ZWxCbG9jay5waXhlbHMucHVzaChyZXN1bHQucGl4ZWxEYXRhKTsKICAgICAgICAgIGRlY29kZWRQaXhlbEJsb2NrLnN0YXRpc3RpY3MucHVzaCh7CiAgICAgICAgICAgIG1pblZhbHVlOiByZXN1bHQubWluVmFsdWUsCiAgICAgICAgICAgIG1heFZhbHVlOiByZXN1bHQubWF4VmFsdWUsCiAgICAgICAgICAgIG5vRGF0YVZhbHVlOiByZXN1bHQubm9EYXRhVmFsdWUsCiAgICAgICAgICAgIGRpbVN0YXRzOiByZXN1bHQuZGltU3RhdHMKICAgICAgICAgIH0pOwogICAgICAgIH0KICAgICAgICB2YXIgaSwgaiwgbnVtUGl4ZWxzOwogICAgICAgIGlmIChtYWpvclZlcnNpb24gPiAxICYmIGJhbmRNYXNrcy5sZW5ndGggPiAxKSB7CiAgICAgICAgICBudW1QaXhlbHMgPSBkZWNvZGVkUGl4ZWxCbG9jay53aWR0aCAqIGRlY29kZWRQaXhlbEJsb2NrLmhlaWdodDsKICAgICAgICAgIGRlY29kZWRQaXhlbEJsb2NrLmJhbmRNYXNrcyA9IGJhbmRNYXNrczsKICAgICAgICAgIG1hc2tEYXRhID0gbmV3IFVpbnQ4QXJyYXkobnVtUGl4ZWxzKTsKICAgICAgICAgIG1hc2tEYXRhLnNldChiYW5kTWFza3NbMF0pOwogICAgICAgICAgZm9yIChpID0gMTsgaSA8IGJhbmRNYXNrcy5sZW5ndGg7IGkrKykgewogICAgICAgICAgICBiYW5kTWFzayA9IGJhbmRNYXNrc1tpXTsKICAgICAgICAgICAgZm9yIChqID0gMDsgaiA8IG51bVBpeGVsczsgaisrKSB7CiAgICAgICAgICAgICAgbWFza0RhdGF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gfQogIH0KCiAgYXN5bmMgZnVuY3Rpb24gZGVjb2RlKGZpbGVEaXJlY3RvcnksIGJ1ZmZlcikgewogICAgY29uc3QgZGVjb2RlciA9IGdldERlY29kZXIoZmlsZURpcmVjdG9yeSk7CiAgICBjb25zdCByZXN1bHQgPSBhd2FpdCBkZWNvZGVyLmRlY29kZShmaWxlRGlyZWN0b3J5LCBidWZmZXIpOwogICAgc2VsZi5wb3N0TWVzc2FnZShyZXN1bHQsIFtyZXN1bHRdKTsKICB9CiAgaWYgKHR5cGVvZiBzZWxmICE9PSAidW5kZWZpbmVkIikgewogICAgc2VsZi5hZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIiwgKGV2ZW50KSA9PiB7CiAgICAgIGNvbnN0IFtuYW1lLCAuLi5hcmdzXSA9IGV2ZW50LmRhdGE7CiAgICAgIHN3aXRjaCAobmFtZSkgewogICAgICAgIGNhc2UgImRlY29kZSI6CiAgICAgICAgICBkZWNvZGUoYXJnc1swXSwgYXJnc1sxXSk7CiAgICAgICAgICBicmVhazsKICAgICAgfQogICAgfSk7CiAgfQoKfSkoKTsK\";\n const blob = typeof window !== \"undefined\" && window.Blob && new Blob([atob(encodedJs)], { type: \"text/javascript;charset=utf-8\" });\n function WorkerWrapper() {\n const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);\n try {\n return objURL ? new Worker(objURL) : new Worker(\"data:application/javascript;base64,\" + encodedJs, {type: \"module\"});\n } finally {\n objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);\n }\n }\n\nconst defaultPoolSize = globalThis?.navigator?.hardwareConcurrency ?? 4;\nclass Pool {\n workers;\n idleWorkers;\n waitQueue;\n decoder;\n constructor(size = defaultPoolSize) {\n this.workers = [];\n this.idleWorkers = [];\n this.waitQueue = [];\n this.decoder = null;\n for (let i = 0; i < size; ++i) {\n const w = new WorkerWrapper();\n this.workers.push(w);\n this.idleWorkers.push(w);\n }\n }\n async decode(fileDirectory, buffer) {\n const currentWorker = await this.waitForWorker();\n return new Promise((resolve, reject) => {\n currentWorker.onmessage = (event) => {\n this.finishTask(currentWorker);\n resolve(event.data);\n };\n currentWorker.onerror = (error) => {\n this.finishTask(currentWorker);\n reject(error);\n };\n currentWorker.postMessage([\"decode\", fileDirectory, buffer], [buffer]);\n });\n }\n async waitForWorker() {\n const idleWorker = this.idleWorkers.pop();\n if (idleWorker) {\n return idleWorker;\n }\n const waiter = {};\n const promise = new Promise((resolve) => {\n waiter.resolve = resolve;\n });\n this.waitQueue.push(waiter);\n return promise;\n }\n async finishTask(currentWorker) {\n const waiter = this.waitQueue.pop();\n if (waiter) {\n waiter.resolve(currentWorker);\n } else {\n this.idleWorkers.push(currentWorker);\n }\n }\n destroy() {\n for (let i = 0; i < this.workers.length; ++i) {\n this.workers[i].terminate();\n }\n }\n}\n\nconst PARSER_OPTIONS = {\n attributeNamePrefix: \"\",\n attrNodeName: \"attr\",\n parseNodeValue: true,\n parseAttributeValue: true,\n ignoreAttributes: false\n};\nconst parse = (str) => parser.parse(str, PARSER_OPTIONS);\nfunction fromString(str) {\n const res = parse(str);\n if (!res.OME) {\n throw Error(\"Failed to parse OME-XML metadata.\");\n }\n return ensureArray(res.OME.Image).map((img) => {\n const Channels = ensureArray(img.Pixels.Channel).map((c) => {\n if (\"Color\" in c.attr) {\n return {\n ...c.attr,\n Color: intToRgba(c.attr.Color)\n };\n }\n return {\n ...c.attr\n };\n });\n const {\n AquisitionDate = \"\",\n Description = \"\"\n } = img;\n const image = {\n ...img.attr,\n AquisitionDate,\n Description,\n Pixels: {\n ...img.Pixels.attr,\n Channels\n }\n };\n return {\n ...image,\n format() {\n const {\n Pixels\n } = image;\n const sizes = [\"X\", \"Y\", \"Z\"].map((name) => {\n const size = Pixels[`PhysicalSize${name}`];\n const unit = Pixels[`PhysicalSize${name}Unit`];\n return size && unit ? `${size} ${unit}` : \"-\";\n }).join(\" x \");\n return {\n \"Acquisition Date\": image.AquisitionDate,\n \"Dimensions (XY)\": `${Pixels.SizeX} x ${Pixels.SizeY}`,\n \"Pixels Type\": Pixels.Type,\n \"Pixels Size (XYZ)\": sizes,\n \"Z-sections/Timepoints\": `${Pixels.SizeZ} x ${Pixels.SizeT}`,\n Channels: Pixels.SizeC\n };\n }\n };\n });\n}\n\nclass TiffPixelSource {\n constructor(indexer, dtype, tileSize, shape, labels, meta, pool) {\n this.dtype = dtype;\n this.tileSize = tileSize;\n this.shape = shape;\n this.labels = labels;\n this.meta = meta;\n this.pool = pool;\n this._indexer = indexer;\n }\n _indexer;\n async getRaster({\n selection,\n signal\n }) {\n const image = await this._indexer(selection);\n return this._readRasters(image, {\n signal\n });\n }\n async getTile({\n x,\n y,\n selection,\n signal\n }) {\n const {\n height,\n width\n } = this._getTileExtent(x, y);\n const x0 = x * this.tileSize;\n const y0 = y * this.tileSize;\n const window = [x0, y0, x0 + width, y0 + height];\n const image = await this._indexer(selection);\n return this._readRasters(image, {\n window,\n width,\n height,\n signal\n });\n }\n async _readRasters(image, props) {\n const interleave = isInterleaved(this.shape);\n const raster = await image.readRasters({\n interleave,\n ...props,\n pool: this.pool\n });\n if (props?.signal?.aborted) {\n throw SIGNAL_ABORTED;\n }\n const data = interleave ? raster : raster[0];\n return {\n data,\n width: raster.width,\n height: raster.height\n };\n }\n _getTileExtent(x, y) {\n const {\n height: zoomLevelHeight,\n width: zoomLevelWidth\n } = getImageSize(this);\n let height = this.tileSize;\n let width = this.tileSize;\n const maxXTileCoord = Math.floor(zoomLevelWidth / this.tileSize);\n const maxYTileCoord = Math.floor(zoomLevelHeight / this.tileSize);\n if (x === maxXTileCoord) {\n width = zoomLevelWidth % this.tileSize;\n }\n if (y === maxYTileCoord) {\n height = zoomLevelHeight % this.tileSize;\n }\n return {\n height,\n width\n };\n }\n onTileError(err) {\n console.error(err);\n }\n}\n\nfunction getOmeLegacyIndexer(tiff, rootMeta) {\n const imgMeta = rootMeta[0];\n const {\n SizeT,\n SizeC,\n SizeZ\n } = imgMeta.Pixels;\n const ifdIndexer = getOmeIFDIndexer(imgMeta);\n return (sel, pyramidLevel) => {\n const index = ifdIndexer(sel);\n const pyramidIndex = pyramidLevel * SizeZ * SizeT * SizeC;\n return tiff.getImage(index + pyramidIndex);\n };\n}\nfunction getOmeSubIFDIndexer(tiff, rootMeta) {\n const imgMeta = rootMeta[0];\n const ifdIndexer = getOmeIFDIndexer(imgMeta);\n const ifdCache = new Map();\n return async (sel, pyramidLevel) => {\n const index = ifdIndexer(sel);\n const baseImage = await tiff.getImage(index);\n if (pyramidLevel === 0) {\n return baseImage;\n }\n const {\n SubIFDs\n } = baseImage.fileDirectory;\n if (!SubIFDs) {\n throw Error(\"Indexing Error: OME-TIFF is missing SubIFDs.\");\n }\n const key = `${sel.t}-${sel.c}-${sel.z}-${pyramidLevel}`;\n if (!ifdCache.has(key)) {\n const subIfdOffset = SubIFDs[pyramidLevel - 1];\n ifdCache.set(key, tiff.parseFileDirectoryAt(subIfdOffset));\n }\n const ifd = await ifdCache.get(key);\n return new baseImage.constructor(ifd.fileDirectory, ifd.geoKeyDirectory, tiff.dataView, tiff.littleEndian, tiff.cache, tiff.source);\n };\n}\nfunction getOmeIFDIndexer(imgMeta) {\n const {\n SizeC,\n SizeZ,\n SizeT,\n DimensionOrder\n } = imgMeta.Pixels;\n switch (DimensionOrder) {\n case \"XYZCT\": {\n return ({\n t,\n c,\n z\n }) => t * SizeZ * SizeC + c * SizeZ + z;\n }\n case \"XYZTC\": {\n return ({\n t,\n c,\n z\n }) => c * SizeZ * SizeT + t * SizeZ + z;\n }\n case \"XYCTZ\": {\n return ({\n t,\n c,\n z\n }) => z * SizeC * SizeT + t * SizeC + c;\n }\n case \"XYCZT\": {\n return ({\n t,\n c,\n z\n }) => t * SizeC * SizeZ + z * SizeC + c;\n }\n case \"XYTCZ\": {\n return ({\n t,\n c,\n z\n }) => z * SizeT * SizeC + c * SizeT + t;\n }\n case \"XYTZC\": {\n return ({\n t,\n c,\n z\n }) => c * SizeT * SizeZ + z * SizeT + t;\n }\n default: {\n throw new Error(`Invalid OME-XML DimensionOrder, got ${DimensionOrder}.`);\n }\n }\n}\n\nconst DTYPE_LOOKUP$1 = {\n uint8: \"Uint8\",\n uint16: \"Uint16\",\n uint32: \"Uint32\",\n float: \"Float32\",\n double: \"Float64\",\n int8: \"Int8\",\n int16: \"Int16\",\n int32: \"Int32\"\n};\nfunction getOmePixelSourceMeta({\n Pixels\n}) {\n const labels = getLabels(Pixels.DimensionOrder);\n const dims = getDims(labels);\n const shape = Array(labels.length).fill(0);\n shape[dims(\"t\")] = Pixels.SizeT;\n shape[dims(\"c\")] = Pixels.SizeC;\n shape[dims(\"z\")] = Pixels.SizeZ;\n if (Pixels.Interleaved) {\n labels.push(\"_c\");\n shape.push(3);\n }\n const getShape = (level) => {\n const s = [...shape];\n s[dims(\"x\")] = Pixels.SizeX >> level;\n s[dims(\"y\")] = Pixels.SizeY >> level;\n return s;\n };\n if (!(Pixels.Type in DTYPE_LOOKUP$1)) {\n throw Error(`Pixel type ${Pixels.Type} not supported.`);\n }\n const dtype = DTYPE_LOOKUP$1[Pixels.Type];\n if (Pixels.PhysicalSizeX && Pixels.PhysicalSizeY) {\n const physicalSizes = {\n x: {\n size: Pixels.PhysicalSizeX,\n unit: Pixels.PhysicalSizeXUnit\n },\n y: {\n size: Pixels.PhysicalSizeY,\n unit: Pixels.PhysicalSizeYUnit\n }\n };\n if (Pixels.PhysicalSizeZ) {\n physicalSizes.z = {\n size: Pixels.PhysicalSizeZ,\n unit: Pixels.PhysicalSizeZUnit\n };\n }\n return {\n labels,\n getShape,\n physicalSizes,\n dtype\n };\n }\n return {\n labels,\n getShape,\n dtype\n };\n}\nfunction guessTileSize$1(image) {\n const tileWidth = image.getTileWidth();\n const tileHeight = image.getTileHeight();\n const size = Math.min(tileWidth, tileHeight);\n return prevPowerOf2(size);\n}\n\nasync function load$2(tiff, pool) {\n const firstImage = await tiff.getImage(0);\n const {\n ImageDescription,\n SubIFDs,\n PhotometricInterpretation: photometricInterpretation\n } = firstImage.fileDirectory;\n const omexml = fromString(ImageDescription);\n let levels;\n let pyramidIndexer;\n if (SubIFDs) {\n levels = SubIFDs.length + 1;\n pyramidIndexer = getOmeSubIFDIndexer(tiff, omexml);\n } else {\n levels = omexml.length;\n pyramidIndexer = getOmeLegacyIndexer(tiff, omexml);\n }\n const imgMeta = omexml[0];\n const {\n labels,\n getShape,\n physicalSizes,\n dtype\n } = getOmePixelSourceMeta(imgMeta);\n const tileSize = guessTileSize$1(firstImage);\n const meta = {\n photometricInterpretation,\n physicalSizes\n };\n const data = Array.from({\n length: levels\n }).map((_, resolution) => {\n const shape = getShape(resolution);\n const indexer = (sel) => pyramidIndexer(sel, resolution);\n const source = new TiffPixelSource(indexer, dtype, tileSize, shape, labels, meta, pool);\n return source;\n });\n return {\n data,\n metadata: imgMeta\n };\n}\n\nasync function loadOmeTiff(source, opts = {}) {\n const {\n headers,\n offsets,\n pool = true\n } = opts;\n let tiff;\n if (typeof source === \"string\") {\n tiff = await fromUrl(source, {\n ...headers,\n cacheSize: Infinity\n });\n } else {\n tiff = await fromBlob(source);\n }\n if (offsets) {\n tiff = createOffsetsProxy(tiff, offsets);\n }\n checkProxies(tiff);\n return pool ? load$2(tiff, new Pool()) : load$2(tiff);\n}\n\nfunction joinUrlParts(...args) {\n return args.map((part, i) => {\n if (i === 0)\n return part.trim().replace(/[/]*$/g, \"\");\n return part.trim().replace(/(^[/]*|[/]*$)/g, \"\");\n }).filter((x) => x.length).join(\"/\");\n}\nclass ReadOnlyStore {\n async keys() {\n return [];\n }\n async deleteItem() {\n return false;\n }\n async setItem() {\n console.warn(\"Cannot write to read-only store.\");\n return false;\n }\n}\nclass FileStore extends ReadOnlyStore {\n _map;\n _rootPrefix;\n constructor(fileMap, rootPrefix = \"\") {\n super();\n this._map = fileMap;\n this._rootPrefix = rootPrefix;\n }\n _key(key) {\n return joinUrlParts(this._rootPrefix, key);\n }\n async getItem(key) {\n const file = this._map.get(this._key(key));\n if (!file) {\n throw new KeyError(key);\n }\n const buffer = await file.arrayBuffer();\n return buffer;\n }\n async containsItem(key) {\n const path = this._key(key);\n return this._map.has(path);\n }\n}\n\nfunction isOmeZarr(dataShape, Pixels) {\n const {\n SizeT,\n SizeC,\n SizeZ,\n SizeY,\n SizeX\n } = Pixels;\n const omeZarrShape = [SizeT, SizeC, SizeZ, SizeY, SizeX];\n return dataShape.every((size, i) => omeZarrShape[i] === size);\n}\nfunction guessBioformatsLabels({\n shape\n}, {\n Pixels\n}) {\n if (isOmeZarr(shape, Pixels)) {\n return getLabels(\"XYZCT\");\n }\n const labels = getLabels(Pixels.DimensionOrder);\n labels.forEach((lower, i) => {\n const label = lower.toUpperCase();\n const xmlSize = Pixels[`Size${label}`];\n if (!xmlSize) {\n throw Error(`Dimension ${label} is invalid for OME-XML.`);\n }\n if (shape[i] !== xmlSize) {\n throw Error(\"Dimension mismatch between zarr source and OME-XML.\");\n }\n });\n return labels;\n}\nfunction getRootPrefix(files, rootName) {\n const first = files.find((f) => f.path.indexOf(rootName) > 0);\n if (!first) {\n throw Error(\"Could not find root in store.\");\n }\n const prefixLength = first.path.indexOf(rootName) + rootName.length;\n return first.path.slice(0, prefixLength);\n}\nasync function loadMultiscales(store, path = \"\") {\n const grp = await openGroup(store, path);\n const rootAttrs = await grp.attrs.asObject();\n let paths = [\"0\"];\n let labels = [\"t\", \"c\", \"z\", \"y\", \"x\"];\n if (\"multiscales\" in rootAttrs) {\n const {\n datasets,\n axes\n } = rootAttrs.multiscales[0];\n paths = datasets.map((d) => d.path);\n if (axes) {\n labels = axes;\n }\n }\n const data = paths.map((path2) => grp.getItem(path2));\n return {\n data: await Promise.all(data),\n rootAttrs,\n labels\n };\n}\nfunction guessTileSize(arr) {\n const interleaved = isInterleaved(arr.shape);\n const [yChunk, xChunk] = arr.chunks.slice(interleaved ? -3 : -2);\n const size = Math.min(yChunk, xChunk);\n return prevPowerOf2(size);\n}\n\nfunction getIndexer(labels) {\n const size = labels.length;\n const dims = getDims(labels);\n return (sel) => {\n if (Array.isArray(sel)) {\n return [...sel];\n }\n const selection = Array(size).fill(0);\n for (const [key, value] of Object.entries(sel)) {\n selection[dims(key)] = value;\n }\n return selection;\n };\n}\n\nconst DTYPE_LOOKUP = {\n u1: \"Uint8\",\n u2: \"Uint16\",\n u4: \"Uint32\",\n f4: \"Float32\",\n f8: \"Float64\",\n i1: \"Int8\",\n i2: \"Int16\",\n i4: \"Int32\"\n};\nclass ZarrPixelSource {\n constructor(data, labels, tileSize) {\n this.labels = labels;\n this.tileSize = tileSize;\n this._indexer = getIndexer(labels);\n this._data = data;\n const xChunkSize = data.chunks[this._xIndex];\n const yChunkSize = data.chunks[this._xIndex - 1];\n this._readChunks = tileSize === xChunkSize && tileSize === yChunkSize;\n }\n _data;\n _indexer;\n _readChunks;\n get shape() {\n return this._data.shape;\n }\n get dtype() {\n const suffix = this._data.dtype.slice(1);\n if (!(suffix in DTYPE_LOOKUP)) {\n throw Error(`Zarr dtype not supported, got ${suffix}.`);\n }\n return DTYPE_LOOKUP[suffix];\n }\n get _xIndex() {\n const interleave = isInterleaved(this._data.shape);\n return this._data.shape.length - (interleave ? 2 : 1);\n }\n _chunkIndex(selection, x, y) {\n const sel = this._indexer(selection);\n sel[this._xIndex] = x;\n sel[this._xIndex - 1] = y;\n return sel;\n }\n _getSlices(x, y) {\n const {\n height,\n width\n } = getImageSize(this);\n const [xStart, xStop] = [x * this.tileSize, Math.min((x + 1) * this.tileSize, width)];\n const [yStart, yStop] = [y * this.tileSize, Math.min((y + 1) * this.tileSize, height)];\n if (xStart === xStop || yStart === yStop) {\n throw new BoundsCheckError(\"Tile slice is zero-sized.\");\n }\n return [slice(xStart, xStop), slice(yStart, yStop)];\n }\n async getRaster({\n selection\n }) {\n const sel = this._chunkIndex(selection, null, null);\n const {\n data,\n shape\n } = await this._data.getRaw(sel);\n const [height, width] = shape;\n return {\n data,\n width,\n height\n };\n }\n async getTile(props) {\n const {\n x,\n y,\n selection,\n signal\n } = props;\n let res;\n if (this._readChunks) {\n const sel = this._chunkIndex(selection, x, y);\n res = await this._data.getRawChunk(sel, {\n storeOptions: {\n signal\n }\n });\n } else {\n const [xSlice, ySlice] = this._getSlices(x, y);\n const sel = this._chunkIndex(selection, xSlice, ySlice);\n res = await this._data.getRaw(sel);\n }\n const {\n data,\n shape: [height, width]\n } = res;\n return {\n data,\n width,\n height\n };\n }\n onTileError(err) {\n if (!(err instanceof BoundsCheckError)) {\n throw err;\n }\n }\n}\n\nasync function load$1(root, xmlSource) {\n if (typeof xmlSource !== \"string\") {\n xmlSource = await xmlSource.text();\n }\n const imgMeta = fromString(xmlSource)[0];\n const {\n data\n } = await loadMultiscales(root, \"0\");\n const labels = guessBioformatsLabels(data[0], imgMeta);\n const tileSize = guessTileSize(data[0]);\n const pyramid = data.map((arr) => new ZarrPixelSource(arr, labels, tileSize));\n return {\n data: pyramid,\n metadata: imgMeta\n };\n}\n\nasync function load(store) {\n const {\n data,\n rootAttrs,\n labels\n } = await loadMultiscales(store);\n const tileSize = guessTileSize(data[0]);\n const pyramid = data.map((arr) => new ZarrPixelSource(arr, labels, tileSize));\n return {\n data: pyramid,\n metadata: rootAttrs\n };\n}\n\nasync function loadBioformatsZarr(source, options = {}) {\n const METADATA = \"METADATA.ome.xml\";\n const ZARR_DIR = \"data.zarr\";\n if (typeof source === \"string\") {\n const url = source.endsWith(\"/\") ? source.slice(0, -1) : source;\n const store2 = new HTTPStore(url + \"/\" + ZARR_DIR, options);\n const xmlSource = await fetch(url + \"/\" + METADATA, options.fetchOptions);\n return load$1(store2, xmlSource);\n }\n const fMap = new Map();\n let xmlFile;\n for (const file of source) {\n if (file.name === METADATA) {\n xmlFile = file;\n } else {\n fMap.set(file.path, file);\n }\n }\n if (!xmlFile) {\n throw Error(\"No OME-XML metadata found for store.\");\n }\n const store = new FileStore(fMap, getRootPrefix(source, ZARR_DIR));\n return load$1(store, xmlFile);\n}\nasync function loadOmeZarr(source, options = {}) {\n const store = new HTTPStore(source, options);\n if (options?.type !== \"multiscales\") {\n throw Error(\"Only multiscale OME-Zarr is supported.\");\n }\n return load(store);\n}\n\nexport { AdditiveColormapExtension, BitmapLayer, COLORMAPS, ColorPaletteExtension, DETAIL_VIEW_ID, DTYPE_VALUES, DetailView, ImageLayer, LensExtension, MAX_CHANNELS, MultiscaleImageLayer, OVERVIEW_VIEW_ID, OverviewLayer, OverviewView, PictureInPictureViewer, RENDERING_MODES, ScaleBarLayer, SideBySideView, SideBySideViewer, TiffPixelSource, VivView, VivViewer, VolumeLayer, VolumeView, VolumeViewer, XR3DLayer, XRLayer, ZarrPixelSource, getChannelStats, getDefaultInitialViewState, loadBioformatsZarr, loadOmeTiff, loadOmeZarr };\n","import getPrototypeOf from \"./getPrototypeOf\";\nimport setPrototypeOf from \"./setPrototypeOf\";\nimport isNativeFunction from \"./isNativeFunction\";\nimport construct from \"./construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}","import type {Readable} from 'stream';\n\n/** A DOM or Node readable stream */\nexport type ReadableStreamType = ReadableStream | Readable;\n\nconst isBoolean: (x: any) => boolean = (x) => typeof x === 'boolean';\nconst isFunction: (x: any) => boolean = (x) => typeof x === 'function';\n\nexport const isObject: (x: any) => boolean = (x) => x !== null && typeof x === 'object';\nexport const isPureObject: (x: any) => boolean = (x) =>\n isObject(x) && x.constructor === {}.constructor;\nexport const isPromise: (x: any) => boolean = (x) => isObject(x) && isFunction(x.then);\n\nexport const isIterable: (x: any) => boolean = (x) => x && typeof x[Symbol.iterator] === 'function';\nexport const isAsyncIterable: (x: any) => boolean = (x) =>\n x && typeof x[Symbol.asyncIterator] === 'function';\nexport const isIterator: (x: any) => boolean = (x) => x && isFunction(x.next);\n\nexport const isResponse: (x: any) => boolean = (x) =>\n (typeof Response !== 'undefined' && x instanceof Response) ||\n (x && x.arrayBuffer && x.text && x.json);\n\nexport const isFile: (x: any) => boolean = (x) => typeof File !== 'undefined' && x instanceof File;\nexport const isBlob: (x: any) => boolean = (x) => typeof Blob !== 'undefined' && x instanceof Blob;\n\nexport const isWritableDOMStream: (x: any) => boolean = (x) =>\n isObject(x) && isFunction(x.abort) && isFunction(x.getWriter);\n\nexport const isReadableDOMStream: (x: any) => boolean = (x) =>\n (typeof ReadableStream !== 'undefined' && x instanceof ReadableStream) ||\n (isObject(x) && isFunction(x.tee) && isFunction(x.cancel) && isFunction(x.getReader));\n// Not implemented in Firefox: && isFunction(x.pipeTo)\n\n/** Check for Node.js `Buffer` without triggering bundler to include buffer polyfill */\nexport const isBuffer: (x: any) => boolean = (x) => x && typeof x === 'object' && x.isBuffer;\n\nexport const isWritableNodeStream: (x: any) => boolean = (x) =>\n isObject(x) && isFunction(x.end) && isFunction(x.write) && isBoolean(x.writable);\nexport const isReadableNodeStream: (x: any) => boolean = (x) =>\n isObject(x) && isFunction(x.read) && isFunction(x.pipe) && isBoolean(x.readable);\nexport const isReadableStream: (x: any) => boolean = (x) =>\n isReadableDOMStream(x) || isReadableNodeStream(x);\nexport const isWritableStream: (x: any) => boolean = (x) =>\n isWritableDOMStream(x) || isWritableNodeStream(x);\n","import * as glMatrix from \"./common.js\";\n/**\r\n * 4 Dimensional Vector\r\n * @module vec4\r\n */\n\n/**\r\n * Creates a new, empty vec4\r\n *\r\n * @returns {vec4} a new 4D vector\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n }\n\n return out;\n}\n/**\r\n * Creates a new vec4 initialized with values from an existing vector\r\n *\r\n * @param {vec4} a vector to clone\r\n * @returns {vec4} a new 4D vector\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\r\n * Creates a new vec4 initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {vec4} a new 4D vector\r\n */\n\nexport function fromValues(x, y, z, w) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\r\n * Copy the values from one vec4 to another\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the source vector\r\n * @returns {vec4} out\r\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\r\n * Set the components of a vec4 to the given values\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {vec4} out\r\n */\n\nexport function set(out, x, y, z, w) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\r\n * Adds two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n/**\r\n * Multiplies two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n out[3] = a[3] * b[3];\n return out;\n}\n/**\r\n * Divides two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n out[3] = a[3] / b[3];\n return out;\n}\n/**\r\n * Math.ceil the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to ceil\r\n * @returns {vec4} out\r\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n out[3] = Math.ceil(a[3]);\n return out;\n}\n/**\r\n * Math.floor the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to floor\r\n * @returns {vec4} out\r\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n out[3] = Math.floor(a[3]);\n return out;\n}\n/**\r\n * Returns the minimum of two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n out[3] = Math.min(a[3], b[3]);\n return out;\n}\n/**\r\n * Returns the maximum of two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n out[3] = Math.max(a[3], b[3]);\n return out;\n}\n/**\r\n * Math.round the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to round\r\n * @returns {vec4} out\r\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n out[3] = Math.round(a[3]);\n return out;\n}\n/**\r\n * Scales a vec4 by a scalar number\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec4} out\r\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n/**\r\n * Adds two vec4's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec4} out\r\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n/**\r\n * Calculates the euclidian distance between two vec4's\r\n *\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {Number} distance between a and b\r\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\r\n * Calculates the squared euclidian distance between two vec4's\r\n *\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {Number} squared distance between a and b\r\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\r\n * Calculates the length of a vec4\r\n *\r\n * @param {vec4} a vector to calculate length of\r\n * @returns {Number} length of a\r\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\r\n * Calculates the squared length of a vec4\r\n *\r\n * @param {vec4} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\r\n * Negates the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to negate\r\n * @returns {vec4} out\r\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = -a[3];\n return out;\n}\n/**\r\n * Returns the inverse of the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to invert\r\n * @returns {vec4} out\r\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n out[3] = 1.0 / a[3];\n return out;\n}\n/**\r\n * Normalize a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to normalize\r\n * @returns {vec4} out\r\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n var len = x * x + y * y + z * z + w * w;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = x * len;\n out[1] = y * len;\n out[2] = z * len;\n out[3] = w * len;\n return out;\n}\n/**\r\n * Calculates the dot product of two vec4's\r\n *\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {Number} dot product of a and b\r\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n/**\r\n * Returns the cross-product of three vectors in a 4-dimensional space\r\n *\r\n * @param {vec4} result the receiving vector\r\n * @param {vec4} U the first vector\r\n * @param {vec4} V the second vector\r\n * @param {vec4} W the third vector\r\n * @returns {vec4} result\r\n */\n\nexport function cross(out, u, v, w) {\n var A = v[0] * w[1] - v[1] * w[0],\n B = v[0] * w[2] - v[2] * w[0],\n C = v[0] * w[3] - v[3] * w[0],\n D = v[1] * w[2] - v[2] * w[1],\n E = v[1] * w[3] - v[3] * w[1],\n F = v[2] * w[3] - v[3] * w[2];\n var G = u[0];\n var H = u[1];\n var I = u[2];\n var J = u[3];\n out[0] = H * F - I * E + J * D;\n out[1] = -(G * F) + I * C - J * B;\n out[2] = G * E - H * C + J * A;\n out[3] = -(G * D) + H * B - I * A;\n return out;\n}\n/**\r\n * Performs a linear interpolation between two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec4} out\r\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n var aw = a[3];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n out[3] = aw + t * (b[3] - aw);\n return out;\n}\n/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\r\n * @returns {vec4} out\r\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a\n // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n // http://projecteuclid.org/euclid.aoms/1177692644;\n\n var v1, v2, v3, v4;\n var s1, s2;\n\n do {\n v1 = glMatrix.RANDOM() * 2 - 1;\n v2 = glMatrix.RANDOM() * 2 - 1;\n s1 = v1 * v1 + v2 * v2;\n } while (s1 >= 1);\n\n do {\n v3 = glMatrix.RANDOM() * 2 - 1;\n v4 = glMatrix.RANDOM() * 2 - 1;\n s2 = v3 * v3 + v4 * v4;\n } while (s2 >= 1);\n\n var d = Math.sqrt((1 - s1) / s2);\n out[0] = scale * v1;\n out[1] = scale * v2;\n out[2] = scale * v3 * d;\n out[3] = scale * v4 * d;\n return out;\n}\n/**\r\n * Transforms the vec4 with a mat4.\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the vector to transform\r\n * @param {mat4} m matrix to transform with\r\n * @returns {vec4} out\r\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n return out;\n}\n/**\r\n * Transforms the vec4 with a quat\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the vector to transform\r\n * @param {quat} q quaternion to transform with\r\n * @returns {vec4} out\r\n */\n\nexport function transformQuat(out, a, q) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3]; // calculate quat * vec\n\n var ix = qw * x + qy * z - qz * y;\n var iy = qw * y + qz * x - qx * z;\n var iz = qw * z + qx * y - qy * x;\n var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat\n\n out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n out[3] = a[3];\n return out;\n}\n/**\r\n * Set the components of a vec4 to zero\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @returns {vec4} out\r\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n return out;\n}\n/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {vec4} a vector to represent as a string\r\n * @returns {String} string representation of the vector\r\n */\n\nexport function str(a) {\n return \"vec4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\r\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {vec4} a The first vector.\r\n * @param {vec4} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {vec4} a The first vector.\r\n * @param {vec4} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n/**\r\n * Alias for {@link vec4.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec4.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec4.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec4.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec4.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec4.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec4.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec4s.\r\n *\r\n * @param {Array} a the array of vectors to iterate over\r\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\r\n * @param {Number} offset Number of elements to skip at the beginning of the array\r\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\r\n * @param {Function} fn Function to call for each vector in the array\r\n * @param {Object} [arg] additional argument to pass to fn\r\n * @returns {Array} a\r\n * @function\r\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 4;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n vec[3] = a[i + 3];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n a[i + 3] = vec[3];\n }\n\n return a;\n };\n}();","export function assign(target, source) {\n for (const key in source) {\n if (source.hasOwnProperty(key)) {\n target[key] = source[key];\n }\n }\n}\n\nexport function chunk(iterable, length) {\n const results = [];\n const lengthOfIterable = iterable.length;\n for (let i = 0; i < lengthOfIterable; i += length) {\n const chunked = [];\n for (let ci = i; ci < i + length; ci++) {\n chunked.push(iterable[ci]);\n }\n results.push(chunked);\n }\n return results;\n}\n\nexport function endsWith(string, expectedEnding) {\n if (string.length < expectedEnding.length) {\n return false;\n }\n const actualEnding = string.substr(string.length - expectedEnding.length);\n return actualEnding === expectedEnding;\n}\n\nexport function forEach(iterable, func) {\n const { length } = iterable;\n for (let i = 0; i < length; i++) {\n func(iterable[i], i);\n }\n}\n\nexport function invert(oldObj) {\n const newObj = {};\n for (const key in oldObj) {\n if (oldObj.hasOwnProperty(key)) {\n const value = oldObj[key];\n newObj[value] = key;\n }\n }\n return newObj;\n}\n\nexport function range(n) {\n const results = [];\n for (let i = 0; i < n; i++) {\n results.push(i);\n }\n return results;\n}\n\nexport function times(numTimes, func) {\n const results = [];\n for (let i = 0; i < numTimes; i++) {\n results.push(func(i));\n }\n return results;\n}\n\nexport function toArray(iterable) {\n const results = [];\n const { length } = iterable;\n for (let i = 0; i < length; i++) {\n results.push(iterable[i]);\n }\n return results;\n}\n\nexport function toArrayRecursively(input) {\n if (input.length) {\n return toArray(input).map(toArrayRecursively);\n }\n return input;\n}\n\n// copied from https://github.com/academia-de-codigo/parse-content-range-header/blob/master/index.js\nexport function parseContentRange(headerValue) {\n if (!headerValue) {\n return null;\n }\n\n if (typeof headerValue !== 'string') {\n throw new Error('invalid argument');\n }\n\n const parseInt = (number) => Number.parseInt(number, 10);\n\n // Check for presence of unit\n let matches = headerValue.match(/^(\\w*) /);\n const unit = matches && matches[1];\n\n // check for start-end/size header format\n matches = headerValue.match(/(\\d+)-(\\d+)\\/(\\d+|\\*)/);\n if (matches) {\n return {\n unit,\n first: parseInt(matches[1]),\n last: parseInt(matches[2]),\n length: matches[3] === '*' ? null : parseInt(matches[3]),\n };\n }\n\n // check for size header format\n matches = headerValue.match(/(\\d+|\\*)/);\n if (matches) {\n return {\n unit,\n first: null,\n last: null,\n length: matches[1] === '*' ? null : parseInt(matches[1]),\n };\n }\n\n return null;\n}\n\n\n/*\n * Promisified wrapper around 'setTimeout' to allow 'await'\n */\nexport async function wait(milliseconds) {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nexport function zip(a, b) {\n const A = Array.isArray(a) ? a : Array.from(a);\n const B = Array.isArray(b) ? b : Array.from(b);\n return A.map((k, i) => [k, B[i]]);\n}\n\n\n// Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error\nexport class AbortError extends Error {\n constructor(params) {\n // Pass remaining arguments (including vendor specific ones) to parent constructor\n super(params);\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, AbortError);\n }\n\n this.name = 'AbortError';\n }\n}\n\nexport class CustomAggregateError extends Error {\n constructor(errors, message) {\n super(message);\n this.errors = errors;\n this.message = message;\n this.name = 'AggregateError';\n }\n}\n\nexport const AggregateError = CustomAggregateError;\n","import * as glMatrix from \"./common.js\";\n/**\r\n * 3x3 Matrix\r\n * @module mat3\r\n */\n\n/**\r\n * Creates a new identity mat3\r\n *\r\n * @returns {mat3} a new 3x3 matrix\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(9);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n }\n\n out[0] = 1;\n out[4] = 1;\n out[8] = 1;\n return out;\n}\n/**\r\n * Copies the upper-left 3x3 values into the given mat3.\r\n *\r\n * @param {mat3} out the receiving 3x3 matrix\r\n * @param {mat4} a the source 4x4 matrix\r\n * @returns {mat3} out\r\n */\n\nexport function fromMat4(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[4];\n out[4] = a[5];\n out[5] = a[6];\n out[6] = a[8];\n out[7] = a[9];\n out[8] = a[10];\n return out;\n}\n/**\r\n * Creates a new mat3 initialized with values from an existing matrix\r\n *\r\n * @param {mat3} a matrix to clone\r\n * @returns {mat3} a new 3x3 matrix\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\r\n * Copy the values from one mat3 to another\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\r\n * Create a new mat3 with the given values\r\n *\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\r\n * @returns {mat3} A new mat3\r\n */\n\nexport function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\r\n * Set the components of a mat3 to the given values\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\r\n * @returns {mat3} out\r\n */\n\nexport function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\r\n * Set a mat3 to the identity matrix\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @returns {mat3} out\r\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\r\n * Transpose the values of a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a12 = a[5];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a01;\n out[5] = a[7];\n out[6] = a02;\n out[7] = a12;\n } else {\n out[0] = a[0];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a[1];\n out[4] = a[4];\n out[5] = a[7];\n out[6] = a[2];\n out[7] = a[5];\n out[8] = a[8];\n }\n\n return out;\n}\n/**\r\n * Inverts a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b01 = a22 * a11 - a12 * a21;\n var b11 = -a22 * a10 + a12 * a20;\n var b21 = a21 * a10 - a11 * a20; // Calculate the determinant\n\n var det = a00 * b01 + a01 * b11 + a02 * b21;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = b01 * det;\n out[1] = (-a22 * a01 + a02 * a21) * det;\n out[2] = (a12 * a01 - a02 * a11) * det;\n out[3] = b11 * det;\n out[4] = (a22 * a00 - a02 * a20) * det;\n out[5] = (-a12 * a00 + a02 * a10) * det;\n out[6] = b21 * det;\n out[7] = (-a21 * a00 + a01 * a20) * det;\n out[8] = (a11 * a00 - a01 * a10) * det;\n return out;\n}\n/**\r\n * Calculates the adjugate of a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n out[0] = a11 * a22 - a12 * a21;\n out[1] = a02 * a21 - a01 * a22;\n out[2] = a01 * a12 - a02 * a11;\n out[3] = a12 * a20 - a10 * a22;\n out[4] = a00 * a22 - a02 * a20;\n out[5] = a02 * a10 - a00 * a12;\n out[6] = a10 * a21 - a11 * a20;\n out[7] = a01 * a20 - a00 * a21;\n out[8] = a00 * a11 - a01 * a10;\n return out;\n}\n/**\r\n * Calculates the determinant of a mat3\r\n *\r\n * @param {mat3} a the source matrix\r\n * @returns {Number} determinant of a\r\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);\n}\n/**\r\n * Multiplies two mat3's\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @returns {mat3} out\r\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b00 = b[0],\n b01 = b[1],\n b02 = b[2];\n var b10 = b[3],\n b11 = b[4],\n b12 = b[5];\n var b20 = b[6],\n b21 = b[7],\n b22 = b[8];\n out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n return out;\n}\n/**\r\n * Translate a mat3 by the given vector\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to translate\r\n * @param {vec2} v vector to translate by\r\n * @returns {mat3} out\r\n */\n\nexport function translate(out, a, v) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n x = v[0],\n y = v[1];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a10;\n out[4] = a11;\n out[5] = a12;\n out[6] = x * a00 + y * a10 + a20;\n out[7] = x * a01 + y * a11 + a21;\n out[8] = x * a02 + y * a12 + a22;\n return out;\n}\n/**\r\n * Rotates a mat3 by the given angle\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat3} out\r\n */\n\nexport function rotate(out, a, rad) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c * a00 + s * a10;\n out[1] = c * a01 + s * a11;\n out[2] = c * a02 + s * a12;\n out[3] = c * a10 - s * a00;\n out[4] = c * a11 - s * a01;\n out[5] = c * a12 - s * a02;\n out[6] = a20;\n out[7] = a21;\n out[8] = a22;\n return out;\n}\n/**\r\n * Scales the mat3 by the dimensions in the given vec2\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to rotate\r\n * @param {vec2} v the vec2 to scale the matrix by\r\n * @returns {mat3} out\r\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1];\n out[0] = x * a[0];\n out[1] = x * a[1];\n out[2] = x * a[2];\n out[3] = y * a[3];\n out[4] = y * a[4];\n out[5] = y * a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\r\n * Creates a matrix from a vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.translate(dest, dest, vec);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {vec2} v Translation vector\r\n * @returns {mat3} out\r\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = v[0];\n out[7] = v[1];\n out[8] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a given angle\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.rotate(dest, dest, rad);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat3} out\r\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = -s;\n out[4] = c;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a vector scaling\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.scale(dest, dest, vec);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {vec2} v Scaling vector\r\n * @returns {mat3} out\r\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = v[1];\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\r\n * Copies the values from a mat2d into a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat2d} a the matrix to copy\r\n * @returns {mat3} out\r\n **/\n\nexport function fromMat2d(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = 0;\n out[3] = a[2];\n out[4] = a[3];\n out[5] = 0;\n out[6] = a[4];\n out[7] = a[5];\n out[8] = 1;\n return out;\n}\n/**\r\n * Calculates a 3x3 matrix from the given quaternion\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {quat} q Quaternion to create matrix from\r\n *\r\n * @returns {mat3} out\r\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[3] = yx - wz;\n out[6] = zx + wy;\n out[1] = yx + wz;\n out[4] = 1 - xx - zz;\n out[7] = zy - wx;\n out[2] = zx - wy;\n out[5] = zy + wx;\n out[8] = 1 - xx - yy;\n return out;\n}\n/**\r\n * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {mat4} a Mat4 to derive the normal matrix from\r\n *\r\n * @returns {mat3} out\r\n */\n\nexport function normalFromMat4(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n return out;\n}\n/**\r\n * Generates a 2D projection matrix with the given bounds\r\n *\r\n * @param {mat3} out mat3 frustum matrix will be written into\r\n * @param {number} width Width of your gl context\r\n * @param {number} height Height of gl context\r\n * @returns {mat3} out\r\n */\n\nexport function projection(out, width, height) {\n out[0] = 2 / width;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = -2 / height;\n out[5] = 0;\n out[6] = -1;\n out[7] = 1;\n out[8] = 1;\n return out;\n}\n/**\r\n * Returns a string representation of a mat3\r\n *\r\n * @param {mat3} a matrix to represent as a string\r\n * @returns {String} string representation of the matrix\r\n */\n\nexport function str(a) {\n return \"mat3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \")\";\n}\n/**\r\n * Returns Frobenius norm of a mat3\r\n *\r\n * @param {mat3} a the matrix to calculate Frobenius norm of\r\n * @returns {Number} Frobenius norm\r\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);\n}\n/**\r\n * Adds two mat3's\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @returns {mat3} out\r\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n return out;\n}\n/**\r\n * Subtracts matrix b from matrix a\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @returns {mat3} out\r\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n return out;\n}\n/**\r\n * Multiply each element of the matrix by a scalar.\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to scale\r\n * @param {Number} b amount to scale the matrix's elements by\r\n * @returns {mat3} out\r\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n return out;\n}\n/**\r\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\r\n *\r\n * @param {mat3} out the receiving vector\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @param {Number} scale the amount to scale b's elements by before adding\r\n * @returns {mat3} out\r\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n return out;\n}\n/**\r\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {mat3} a The first matrix.\r\n * @param {mat3} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8];\n}\n/**\r\n * Returns whether or not the matrices have approximately the same elements in the same position.\r\n *\r\n * @param {mat3} a The first matrix.\r\n * @param {mat3} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3],\n a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7],\n a8 = a[8];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));\n}\n/**\r\n * Alias for {@link mat3.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link mat3.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @module helpers\n */\n/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n *\n * @memberof helpers\n * @type {number}\n */\nexports.earthRadius = 6371008.8;\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n *\n * @memberof helpers\n * @type {Object}\n */\nexports.factors = {\n centimeters: exports.earthRadius * 100,\n centimetres: exports.earthRadius * 100,\n degrees: exports.earthRadius / 111325,\n feet: exports.earthRadius * 3.28084,\n inches: exports.earthRadius * 39.370,\n kilometers: exports.earthRadius / 1000,\n kilometres: exports.earthRadius / 1000,\n meters: exports.earthRadius,\n metres: exports.earthRadius,\n miles: exports.earthRadius / 1609.344,\n millimeters: exports.earthRadius * 1000,\n millimetres: exports.earthRadius * 1000,\n nauticalmiles: exports.earthRadius / 1852,\n radians: 1,\n yards: exports.earthRadius / 1.0936,\n};\n/**\n * Units of measurement factors based on 1 meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexports.unitsFactors = {\n centimeters: 100,\n centimetres: 100,\n degrees: 1 / 111325,\n feet: 3.28084,\n inches: 39.370,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n meters: 1,\n metres: 1,\n miles: 1 / 1609.344,\n millimeters: 1000,\n millimetres: 1000,\n nauticalmiles: 1 / 1852,\n radians: 1 / exports.earthRadius,\n yards: 1 / 1.0936,\n};\n/**\n * Area of measurement factors based on 1 square meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexports.areaFactors = {\n acres: 0.000247105,\n centimeters: 10000,\n centimetres: 10000,\n feet: 10.763910417,\n inches: 1550.003100006,\n kilometers: 0.000001,\n kilometres: 0.000001,\n meters: 1,\n metres: 1,\n miles: 3.86e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geom, properties, options) {\n if (options === void 0) { options = {}; }\n var feat = { type: \"Feature\" };\n if (options.id === 0 || options.id) {\n feat.id = options.id;\n }\n if (options.bbox) {\n feat.bbox = options.bbox;\n }\n feat.properties = properties || {};\n feat.geometry = geom;\n return feat;\n}\nexports.feature = feature;\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = \"Point\";\n * var coordinates = [110, 50];\n * var geometry = turf.geometry(type, coordinates);\n * // => geometry\n */\nfunction geometry(type, coordinates, options) {\n if (options === void 0) { options = {}; }\n switch (type) {\n case \"Point\": return point(coordinates).geometry;\n case \"LineString\": return lineString(coordinates).geometry;\n case \"Polygon\": return polygon(coordinates).geometry;\n case \"MultiPoint\": return multiPoint(coordinates).geometry;\n case \"MultiLineString\": return multiLineString(coordinates).geometry;\n case \"MultiPolygon\": return multiPolygon(coordinates).geometry;\n default: throw new Error(type + \" is invalid\");\n }\n}\nexports.geometry = geometry;\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"Point\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\nexports.point = point;\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\nexports.points = points;\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {\n var ring = coordinates_1[_i];\n if (ring.length < 4) {\n throw new Error(\"Each LinearRing of a Polygon must have 4 or more Positions.\");\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n }\n }\n var geom = {\n type: \"Polygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\nexports.polygon = polygon;\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\nexports.polygons = polygons;\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n var geom = {\n type: \"LineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\nexports.lineString = lineString;\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\nexports.lineStrings = lineStrings;\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n if (options === void 0) { options = {}; }\n var fc = { type: \"FeatureCollection\" };\n if (options.id) {\n fc.id = options.id;\n }\n if (options.bbox) {\n fc.bbox = options.bbox;\n }\n fc.features = features;\n return fc;\n}\nexports.featureCollection = featureCollection;\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiLineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\nexports.multiLineString = multiLineString;\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPoint\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\nexports.multiPoint = multiPoint;\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPolygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\nexports.multiPolygon = multiPolygon;\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = turf.geometry(\"Point\", [100, 0]);\n * var line = turf.geometry(\"LineString\", [[101, 0], [102, 1]]);\n * var collection = turf.geometryCollection([pt, line]);\n *\n * // => collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"GeometryCollection\",\n geometries: geometries,\n };\n return feature(geom, properties, options);\n}\nexports.geometryCollection = geometryCollection;\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (precision === void 0) { precision = 0; }\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\nexports.round = round;\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, or kilometers inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = exports.factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return radians * factor;\n}\nexports.radiansToLength = radiansToLength;\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, or kilometers inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = exports.factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return distance / factor;\n}\nexports.lengthToRadians = lengthToRadians;\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, or kilometers inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\nexports.lengthToDegrees = lengthToDegrees;\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n var angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\nexports.bearingToAzimuth = bearingToAzimuth;\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\nexports.radiansToDegrees = radiansToDegrees;\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\nexports.degreesToRadians = degreesToRadians;\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] of the length\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"kilometers\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(length >= 0)) {\n throw new Error(\"length must be a positive number\");\n }\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);\n}\nexports.convertLength = convertLength;\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {Units} [originalUnit=\"meters\"] of the distance\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"meters\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n var startFactor = exports.areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n var finalFactor = exports.areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n return (area / startFactor) * finalFactor;\n}\nexports.convertArea = convertArea;\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num) && !/^\\s*$/.test(num);\n}\nexports.isNumber = isNumber;\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\nexports.isObject = isObject;\n/**\n * Validate BBox\n *\n * @private\n * @param {Array} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) {\n throw new Error(\"bbox is required\");\n }\n if (!Array.isArray(bbox)) {\n throw new Error(\"bbox must be an Array\");\n }\n if (bbox.length !== 4 && bbox.length !== 6) {\n throw new Error(\"bbox must be an Array of 4 or 6 numbers\");\n }\n bbox.forEach(function (num) {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\nexports.validateBBox = validateBBox;\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) {\n throw new Error(\"id is required\");\n }\n if ([\"string\", \"number\"].indexOf(typeof id) === -1) {\n throw new Error(\"id must be a number or a string\");\n }\n}\nexports.validateId = validateId;\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error(\"method has been renamed to `radiansToDegrees`\");\n}\nexports.radians2degrees = radians2degrees;\nfunction degrees2radians() {\n throw new Error(\"method has been renamed to `degreesToRadians`\");\n}\nexports.degrees2radians = degrees2radians;\nfunction distanceToDegrees() {\n throw new Error(\"method has been renamed to `lengthToDegrees`\");\n}\nexports.distanceToDegrees = distanceToDegrees;\nfunction distanceToRadians() {\n throw new Error(\"method has been renamed to `lengthToRadians`\");\n}\nexports.distanceToRadians = distanceToRadians;\nfunction radiansToDistance() {\n throw new Error(\"method has been renamed to `radiansToLength`\");\n}\nexports.radiansToDistance = radiansToDistance;\nfunction bearingToAngle() {\n throw new Error(\"method has been renamed to `bearingToAzimuth`\");\n}\nexports.bearingToAngle = bearingToAngle;\nfunction convertDistance() {\n throw new Error(\"method has been renamed to `convertLength`\");\n}\nexports.convertDistance = convertDistance;\n","import { formatMuiErrorMessage as _formatMuiErrorMessage } from \"@material-ui/utils\";\n\n/* eslint-disable no-use-before-define */\n\n/**\n * Returns a number whose value is limited to the given range.\n *\n * @param {number} value The value to be clamped\n * @param {number} min The lower boundary of the output range\n * @param {number} max The upper boundary of the output range\n * @returns {number} A number in the range [min, max]\n */\nfunction clamp(value) {\n var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (value < min || value > max) {\n console.error(\"Material-UI: The value provided \".concat(value, \" is out of range [\").concat(min, \", \").concat(max, \"].\"));\n }\n }\n\n return Math.min(Math.max(min, value), max);\n}\n/**\n * Converts a color from CSS hex format to CSS rgb format.\n *\n * @param {string} color - Hex color, i.e. #nnn or #nnnnnn\n * @returns {string} A CSS rgb color string\n */\n\n\nexport function hexToRgb(color) {\n color = color.substr(1);\n var re = new RegExp(\".{1,\".concat(color.length >= 6 ? 2 : 1, \"}\"), 'g');\n var colors = color.match(re);\n\n if (colors && colors[0].length === 1) {\n colors = colors.map(function (n) {\n return n + n;\n });\n }\n\n return colors ? \"rgb\".concat(colors.length === 4 ? 'a' : '', \"(\").concat(colors.map(function (n, index) {\n return index < 3 ? parseInt(n, 16) : Math.round(parseInt(n, 16) / 255 * 1000) / 1000;\n }).join(', '), \")\") : '';\n}\n\nfunction intToHex(int) {\n var hex = int.toString(16);\n return hex.length === 1 ? \"0\".concat(hex) : hex;\n}\n/**\n * Converts a color from CSS rgb format to CSS hex format.\n *\n * @param {string} color - RGB color, i.e. rgb(n, n, n)\n * @returns {string} A CSS rgb color string, i.e. #nnnnnn\n */\n\n\nexport function rgbToHex(color) {\n // Idempotent\n if (color.indexOf('#') === 0) {\n return color;\n }\n\n var _decomposeColor = decomposeColor(color),\n values = _decomposeColor.values;\n\n return \"#\".concat(values.map(function (n) {\n return intToHex(n);\n }).join(''));\n}\n/**\n * Converts a color from hsl format to rgb format.\n *\n * @param {string} color - HSL color values\n * @returns {string} rgb color values\n */\n\nexport function hslToRgb(color) {\n color = decomposeColor(color);\n var _color = color,\n values = _color.values;\n var h = values[0];\n var s = values[1] / 100;\n var l = values[2] / 100;\n var a = s * Math.min(l, 1 - l);\n\n var f = function f(n) {\n var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12;\n return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n };\n\n var type = 'rgb';\n var rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];\n\n if (color.type === 'hsla') {\n type += 'a';\n rgb.push(values[3]);\n }\n\n return recomposeColor({\n type: type,\n values: rgb\n });\n}\n/**\n * Returns an object with the type and values of a color.\n *\n * Note: Does not support rgb % values.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {object} - A MUI color object: {type: string, values: number[]}\n */\n\nexport function decomposeColor(color) {\n // Idempotent\n if (color.type) {\n return color;\n }\n\n if (color.charAt(0) === '#') {\n return decomposeColor(hexToRgb(color));\n }\n\n var marker = color.indexOf('(');\n var type = color.substring(0, marker);\n\n if (['rgb', 'rgba', 'hsl', 'hsla'].indexOf(type) === -1) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: Unsupported `\".concat(color, \"` color.\\nWe support the following formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla().\") : _formatMuiErrorMessage(3, color));\n }\n\n var values = color.substring(marker + 1, color.length - 1).split(',');\n values = values.map(function (value) {\n return parseFloat(value);\n });\n return {\n type: type,\n values: values\n };\n}\n/**\n * Converts a color object with type and values to a string.\n *\n * @param {object} color - Decomposed color\n * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'\n * @param {array} color.values - [n,n,n] or [n,n,n,n]\n * @returns {string} A CSS color string\n */\n\nexport function recomposeColor(color) {\n var type = color.type;\n var values = color.values;\n\n if (type.indexOf('rgb') !== -1) {\n // Only convert the first 3 values to int (i.e. not alpha)\n values = values.map(function (n, i) {\n return i < 3 ? parseInt(n, 10) : n;\n });\n } else if (type.indexOf('hsl') !== -1) {\n values[1] = \"\".concat(values[1], \"%\");\n values[2] = \"\".concat(values[2], \"%\");\n }\n\n return \"\".concat(type, \"(\").concat(values.join(', '), \")\");\n}\n/**\n * Calculates the contrast ratio between two colors.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} A contrast ratio value in the range 0 - 21.\n */\n\nexport function getContrastRatio(foreground, background) {\n var lumA = getLuminance(foreground);\n var lumB = getLuminance(background);\n return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n}\n/**\n * The relative brightness of any point in a color space,\n * normalized to 0 for darkest black and 1 for lightest white.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} The relative brightness of the color in the range 0 - 1\n */\n\nexport function getLuminance(color) {\n color = decomposeColor(color);\n var rgb = color.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : color.values;\n rgb = rgb.map(function (val) {\n val /= 255; // normalized\n\n return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);\n }); // Truncate at 3 digits\n\n return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3));\n}\n/**\n * Darken or lighten a color, depending on its luminance.\n * Light colors are darkened, dark colors are lightened.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient=0.15 - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function emphasize(color) {\n var coefficient = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.15;\n return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);\n}\nvar warnedOnce = false;\n/**\n * Set the absolute transparency of a color.\n * Any existing alpha values are overwritten.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} value - value to set the alpha channel to in the range 0 -1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n *\n * @deprecated\n * Use `import { alpha } from '@material-ui/core/styles'` instead.\n */\n\nexport function fade(color, value) {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnedOnce) {\n warnedOnce = true;\n console.error(['Material-UI: The `fade` color utility was renamed to `alpha` to better describe its functionality.', '', \"You should use `import { alpha } from '@material-ui/core/styles'`\"].join('\\n'));\n }\n }\n\n return alpha(color, value);\n}\n/**\n * Set the absolute transparency of a color.\n * Any existing alpha value is overwritten.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} value - value to set the alpha channel to in the range 0-1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function alpha(color, value) {\n color = decomposeColor(color);\n value = clamp(value);\n\n if (color.type === 'rgb' || color.type === 'hsl') {\n color.type += 'a';\n }\n\n color.values[3] = value;\n return recomposeColor(color);\n}\n/**\n * Darkens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function darken(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] *= 1 - coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] *= 1 - coefficient;\n }\n }\n\n return recomposeColor(color);\n}\n/**\n * Lightens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function lighten(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] += (100 - color.values[2]) * coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] += (255 - color.values[i]) * coefficient;\n }\n }\n\n return recomposeColor(color);\n}","/*!\n Copyright (c) 2017 Jed Watson.\n Licensed under the MIT License (MIT), see\n http://jedwatson.github.io/classnames\n*/\n/* global define */\n\n(function () {\n\t'use strict';\n\n\tvar hasOwn = {}.hasOwnProperty;\n\n\tfunction classNames () {\n\t\tvar classes = [];\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\tvar arg = arguments[i];\n\t\t\tif (!arg) continue;\n\n\t\t\tvar argType = typeof arg;\n\n\t\t\tif (argType === 'string' || argType === 'number') {\n\t\t\t\tclasses.push(arg);\n\t\t\t} else if (Array.isArray(arg) && arg.length) {\n\t\t\t\tvar inner = classNames.apply(null, arg);\n\t\t\t\tif (inner) {\n\t\t\t\t\tclasses.push(inner);\n\t\t\t\t}\n\t\t\t} else if (argType === 'object') {\n\t\t\t\tfor (var key in arg) {\n\t\t\t\t\tif (hasOwn.call(arg, key) && arg[key]) {\n\t\t\t\t\t\tclasses.push(key);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn classes.join(' ');\n\t}\n\n\tif (typeof module !== 'undefined' && module.exports) {\n\t\tclassNames.default = classNames;\n\t\tmodule.exports = classNames;\n\t} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {\n\t\t// register as 'classnames', consistent with npm package name\n\t\tdefine('classnames', [], function () {\n\t\t\treturn classNames;\n\t\t});\n\t} else {\n\t\twindow.classNames = classNames;\n\t}\n}());\n","// This file enables: import 'probe.gl/bench'.\n// Note: Must be published using package.json \"files\" field\nmodule.exports = require('./dist/es5/env');\n","var _typeof = require(\"../helpers/typeof\");\n\nvar assertThisInitialized = require(\"./assertThisInitialized\");\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n }\n\n return assertThisInitialized(self);\n}\n\nmodule.exports = _possibleConstructorReturn;","function _getPrototypeOf(o) {\n module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}\n\nmodule.exports = _getPrototypeOf;","var setPrototypeOf = require(\"./setPrototypeOf\");\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}\n\nmodule.exports = _inherits;","import * as React from 'react';\nvar useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n/**\n * https://github.com/facebook/react/issues/14099#issuecomment-440013892\n *\n * @param {function} fn\n */\n\nexport default function useEventCallback(fn) {\n var ref = React.useRef(fn);\n useEnhancedEffect(function () {\n ref.current = fn;\n });\n return React.useCallback(function () {\n return (0, ref.current).apply(void 0, arguments);\n }, []);\n}","import * as glMatrix from \"./common.js\";\n/**\r\n * 3 Dimensional Vector\r\n * @module vec3\r\n */\n\n/**\r\n * Creates a new, empty vec3\r\n *\r\n * @returns {vec3} a new 3D vector\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(3);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n return out;\n}\n/**\r\n * Creates a new vec3 initialized with values from an existing vector\r\n *\r\n * @param {ReadonlyVec3} a vector to clone\r\n * @returns {vec3} a new 3D vector\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\r\n * Calculates the length of a vec3\r\n *\r\n * @param {ReadonlyVec3} a vector to calculate length of\r\n * @returns {Number} length of a\r\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return Math.hypot(x, y, z);\n}\n/**\r\n * Creates a new vec3 initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @returns {vec3} a new 3D vector\r\n */\n\nexport function fromValues(x, y, z) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\r\n * Copy the values from one vec3 to another\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the source vector\r\n * @returns {vec3} out\r\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\r\n * Set the components of a vec3 to the given values\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @returns {vec3} out\r\n */\n\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\r\n * Adds two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n return out;\n}\n/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n return out;\n}\n/**\r\n * Multiplies two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n return out;\n}\n/**\r\n * Divides two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n return out;\n}\n/**\r\n * Math.ceil the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a vector to ceil\r\n * @returns {vec3} out\r\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n return out;\n}\n/**\r\n * Math.floor the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a vector to floor\r\n * @returns {vec3} out\r\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n return out;\n}\n/**\r\n * Returns the minimum of two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n return out;\n}\n/**\r\n * Returns the maximum of two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n return out;\n}\n/**\r\n * Math.round the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a vector to round\r\n * @returns {vec3} out\r\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n return out;\n}\n/**\r\n * Scales a vec3 by a scalar number\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec3} out\r\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n return out;\n}\n/**\r\n * Adds two vec3's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec3} out\r\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n return out;\n}\n/**\r\n * Calculates the euclidian distance between two vec3's\r\n *\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {Number} distance between a and b\r\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return Math.hypot(x, y, z);\n}\n/**\r\n * Calculates the squared euclidian distance between two vec3's\r\n *\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {Number} squared distance between a and b\r\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return x * x + y * y + z * z;\n}\n/**\r\n * Calculates the squared length of a vec3\r\n *\r\n * @param {ReadonlyVec3} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return x * x + y * y + z * z;\n}\n/**\r\n * Negates the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a vector to negate\r\n * @returns {vec3} out\r\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n return out;\n}\n/**\r\n * Returns the inverse of the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a vector to invert\r\n * @returns {vec3} out\r\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n return out;\n}\n/**\r\n * Normalize a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a vector to normalize\r\n * @returns {vec3} out\r\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var len = x * x + y * y + z * z;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n/**\r\n * Calculates the dot product of two vec3's\r\n *\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {Number} dot product of a and b\r\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n/**\r\n * Computes the cross product of two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function cross(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2];\n var bx = b[0],\n by = b[1],\n bz = b[2];\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n/**\r\n * Performs a linear interpolation between two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec3} out\r\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n/**\r\n * Performs a hermite interpolation with two control points\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @param {ReadonlyVec3} c the third operand\r\n * @param {ReadonlyVec3} d the fourth operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec3} out\r\n */\n\nexport function hermite(out, a, b, c, d, t) {\n var factorTimes2 = t * t;\n var factor1 = factorTimes2 * (2 * t - 3) + 1;\n var factor2 = factorTimes2 * (t - 2) + t;\n var factor3 = factorTimes2 * (t - 1);\n var factor4 = factorTimes2 * (3 - 2 * t);\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\r\n * Performs a bezier interpolation with two control points\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the first operand\r\n * @param {ReadonlyVec3} b the second operand\r\n * @param {ReadonlyVec3} c the third operand\r\n * @param {ReadonlyVec3} d the fourth operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec3} out\r\n */\n\nexport function bezier(out, a, b, c, d, t) {\n var inverseFactor = 1 - t;\n var inverseFactorTimesTwo = inverseFactor * inverseFactor;\n var factorTimes2 = t * t;\n var factor1 = inverseFactorTimesTwo * inverseFactor;\n var factor2 = 3 * t * inverseFactorTimesTwo;\n var factor3 = 3 * factorTimes2 * inverseFactor;\n var factor4 = factorTimes2 * t;\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\r\n * @returns {vec3} out\r\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n var z = glMatrix.RANDOM() * 2.0 - 1.0;\n var zScale = Math.sqrt(1.0 - z * z) * scale;\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n/**\r\n * Transforms the vec3 with a mat4.\r\n * 4th vector component is implicitly '1'\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the vector to transform\r\n * @param {ReadonlyMat4} m matrix to transform with\r\n * @returns {vec3} out\r\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n/**\r\n * Transforms the vec3 with a mat3.\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the vector to transform\r\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\r\n * @returns {vec3} out\r\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n/**\r\n * Transforms the vec3 with a quat\r\n * Can also be used for dual quaternions. (Multiply it with the real part)\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec3} a the vector to transform\r\n * @param {ReadonlyQuat} q quaternion to transform with\r\n * @returns {vec3} out\r\n */\n\nexport function transformQuat(out, a, q) {\n // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3];\n var x = a[0],\n y = a[1],\n z = a[2]; // var qvec = [qx, qy, qz];\n // var uv = vec3.cross([], qvec, a);\n\n var uvx = qy * z - qz * y,\n uvy = qz * x - qx * z,\n uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);\n\n var uuvx = qy * uvz - qz * uvy,\n uuvy = qz * uvx - qx * uvz,\n uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);\n\n var w2 = qw * 2;\n uvx *= w2;\n uvy *= w2;\n uvz *= w2; // vec3.scale(uuv, uuv, 2);\n\n uuvx *= 2;\n uuvy *= 2;\n uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));\n\n out[0] = x + uvx + uuvx;\n out[1] = y + uvy + uuvy;\n out[2] = z + uvz + uuvz;\n return out;\n}\n/**\r\n * Rotate a 3D vector around the x-axis\r\n * @param {vec3} out The receiving vec3\r\n * @param {ReadonlyVec3} a The vec3 point to rotate\r\n * @param {ReadonlyVec3} b The origin of the rotation\r\n * @param {Number} rad The angle of rotation in radians\r\n * @returns {vec3} out\r\n */\n\nexport function rotateX(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\r\n * Rotate a 3D vector around the y-axis\r\n * @param {vec3} out The receiving vec3\r\n * @param {ReadonlyVec3} a The vec3 point to rotate\r\n * @param {ReadonlyVec3} b The origin of the rotation\r\n * @param {Number} rad The angle of rotation in radians\r\n * @returns {vec3} out\r\n */\n\nexport function rotateY(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\r\n * Rotate a 3D vector around the z-axis\r\n * @param {vec3} out The receiving vec3\r\n * @param {ReadonlyVec3} a The vec3 point to rotate\r\n * @param {ReadonlyVec3} b The origin of the rotation\r\n * @param {Number} rad The angle of rotation in radians\r\n * @returns {vec3} out\r\n */\n\nexport function rotateZ(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2]; //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\r\n * Get the angle between two 3D vectors\r\n * @param {ReadonlyVec3} a The first operand\r\n * @param {ReadonlyVec3} b The second operand\r\n * @returns {Number} The angle in radians\r\n */\n\nexport function angle(a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n bx = b[0],\n by = b[1],\n bz = b[2],\n mag1 = Math.sqrt(ax * ax + ay * ay + az * az),\n mag2 = Math.sqrt(bx * bx + by * by + bz * bz),\n mag = mag1 * mag2,\n cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\r\n * Set the components of a vec3 to zero\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @returns {vec3} out\r\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {ReadonlyVec3} a vector to represent as a string\r\n * @returns {String} string representation of the vector\r\n */\n\nexport function str(a) {\n return \"vec3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \")\";\n}\n/**\r\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {ReadonlyVec3} a The first vector.\r\n * @param {ReadonlyVec3} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {ReadonlyVec3} a The first vector.\r\n * @param {ReadonlyVec3} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));\n}\n/**\r\n * Alias for {@link vec3.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec3.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec3.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec3.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec3.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec3.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec3.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec3s.\r\n *\r\n * @param {Array} a the array of vectors to iterate over\r\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\r\n * @param {Number} offset Number of elements to skip at the beginning of the array\r\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\r\n * @param {Function} fn Function to call for each vector in the array\r\n * @param {Object} [arg] additional argument to pass to fn\r\n * @returns {Array} a\r\n * @function\r\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 3;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n\n return a;\n };\n}();","export default function ownerDocument(node) {\n return node && node.ownerDocument || document;\n}","import * as glMatrix from \"./common.js\";\n/**\r\n * 2 Dimensional Vector\r\n * @module vec2\r\n */\n\n/**\r\n * Creates a new, empty vec2\r\n *\r\n * @returns {vec2} a new 2D vector\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(2);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n }\n\n return out;\n}\n/**\r\n * Creates a new vec2 initialized with values from an existing vector\r\n *\r\n * @param {vec2} a vector to clone\r\n * @returns {vec2} a new 2D vector\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\r\n * Creates a new vec2 initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @returns {vec2} a new 2D vector\r\n */\n\nexport function fromValues(x, y) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\r\n * Copy the values from one vec2 to another\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the source vector\r\n * @returns {vec2} out\r\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\r\n * Set the components of a vec2 to the given values\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @returns {vec2} out\r\n */\n\nexport function set(out, x, y) {\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\r\n * Adds two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n return out;\n}\n/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n return out;\n}\n/**\r\n * Multiplies two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n return out;\n}\n/**\r\n * Divides two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n return out;\n}\n/**\r\n * Math.ceil the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to ceil\r\n * @returns {vec2} out\r\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n return out;\n}\n/**\r\n * Math.floor the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to floor\r\n * @returns {vec2} out\r\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n return out;\n}\n/**\r\n * Returns the minimum of two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n return out;\n}\n/**\r\n * Returns the maximum of two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n return out;\n}\n/**\r\n * Math.round the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to round\r\n * @returns {vec2} out\r\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n return out;\n}\n/**\r\n * Scales a vec2 by a scalar number\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec2} out\r\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n return out;\n}\n/**\r\n * Adds two vec2's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec2} out\r\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n return out;\n}\n/**\r\n * Calculates the euclidian distance between two vec2's\r\n *\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {Number} distance between a and b\r\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0],\n y = b[1] - a[1];\n return Math.hypot(x, y);\n}\n/**\r\n * Calculates the squared euclidian distance between two vec2's\r\n *\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {Number} squared distance between a and b\r\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0],\n y = b[1] - a[1];\n return x * x + y * y;\n}\n/**\r\n * Calculates the length of a vec2\r\n *\r\n * @param {vec2} a vector to calculate length of\r\n * @returns {Number} length of a\r\n */\n\nexport function length(a) {\n var x = a[0],\n y = a[1];\n return Math.hypot(x, y);\n}\n/**\r\n * Calculates the squared length of a vec2\r\n *\r\n * @param {vec2} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\n */\n\nexport function squaredLength(a) {\n var x = a[0],\n y = a[1];\n return x * x + y * y;\n}\n/**\r\n * Negates the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to negate\r\n * @returns {vec2} out\r\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n return out;\n}\n/**\r\n * Returns the inverse of the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to invert\r\n * @returns {vec2} out\r\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n return out;\n}\n/**\r\n * Normalize a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to normalize\r\n * @returns {vec2} out\r\n */\n\nexport function normalize(out, a) {\n var x = a[0],\n y = a[1];\n var len = x * x + y * y;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n return out;\n}\n/**\r\n * Calculates the dot product of two vec2's\r\n *\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {Number} dot product of a and b\r\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1];\n}\n/**\r\n * Computes the cross product of two vec2's\r\n * Note that the cross product must by definition produce a 3D vector\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function cross(out, a, b) {\n var z = a[0] * b[1] - a[1] * b[0];\n out[0] = out[1] = 0;\n out[2] = z;\n return out;\n}\n/**\r\n * Performs a linear interpolation between two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec2} out\r\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0],\n ay = a[1];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n return out;\n}\n/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\r\n * @returns {vec2} out\r\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n out[0] = Math.cos(r) * scale;\n out[1] = Math.sin(r) * scale;\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to transform\r\n * @param {mat2} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat2(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat2d\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to transform\r\n * @param {mat2d} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat2d(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y + m[4];\n out[1] = m[1] * x + m[3] * y + m[5];\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat3\r\n * 3rd vector component is implicitly '1'\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to transform\r\n * @param {mat3} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[3] * y + m[6];\n out[1] = m[1] * x + m[4] * y + m[7];\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat4\r\n * 3rd vector component is implicitly '0'\r\n * 4th vector component is implicitly '1'\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to transform\r\n * @param {mat4} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0];\n var y = a[1];\n out[0] = m[0] * x + m[4] * y + m[12];\n out[1] = m[1] * x + m[5] * y + m[13];\n return out;\n}\n/**\r\n * Rotate a 2D vector\r\n * @param {vec2} out The receiving vec2\r\n * @param {vec2} a The vec2 point to rotate\r\n * @param {vec2} b The origin of the rotation\r\n * @param {Number} rad The angle of rotation in radians\r\n * @returns {vec2} out\r\n */\n\nexport function rotate(out, a, b, rad) {\n //Translate point to the origin\n var p0 = a[0] - b[0],\n p1 = a[1] - b[1],\n sinC = Math.sin(rad),\n cosC = Math.cos(rad); //perform rotation and translate to correct position\n\n out[0] = p0 * cosC - p1 * sinC + b[0];\n out[1] = p0 * sinC + p1 * cosC + b[1];\n return out;\n}\n/**\r\n * Get the angle between two 2D vectors\r\n * @param {vec2} a The first operand\r\n * @param {vec2} b The second operand\r\n * @returns {Number} The angle in radians\r\n */\n\nexport function angle(a, b) {\n var x1 = a[0],\n y1 = a[1],\n x2 = b[0],\n y2 = b[1],\n // mag is the product of the magnitudes of a and b\n mag = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2),\n // mag &&.. short circuits if mag == 0\n cosine = mag && (x1 * x2 + y1 * y2) / mag; // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1\n\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\r\n * Set the components of a vec2 to zero\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @returns {vec2} out\r\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n return out;\n}\n/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {vec2} a vector to represent as a string\r\n * @returns {String} string representation of the vector\r\n */\n\nexport function str(a) {\n return \"vec2(\" + a[0] + \", \" + a[1] + \")\";\n}\n/**\r\n * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)\r\n *\r\n * @param {vec2} a The first vector.\r\n * @param {vec2} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1];\n}\n/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {vec2} a The first vector.\r\n * @param {vec2} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1];\n var b0 = b[0],\n b1 = b[1];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1));\n}\n/**\r\n * Alias for {@link vec2.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec2.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec2.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec2.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec2.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec2.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec2.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec2s.\r\n *\r\n * @param {Array} a the array of vectors to iterate over\r\n * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed\r\n * @param {Number} offset Number of elements to skip at the beginning of the array\r\n * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array\r\n * @param {Function} fn Function to call for each vector in the array\r\n * @param {Object} [arg] additional argument to pass to fn\r\n * @returns {Array} a\r\n * @function\r\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 2;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n }\n\n return a;\n };\n}();","/*! pako 2.0.3 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN = 2;\n\n/*============================================================================*/\n\n\nfunction zero(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES = 30;\n/* number of distance codes */\n\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) =>\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) =>\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nconst copy_block = (s, buf, len, header) =>\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n// while (len--) {\n// put_byte(s, *buf++);\n// }\n s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending);\n s.pending += len;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) =>\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let lx = 0; /* running index in l_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) =>\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) =>\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let black_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block = (s, buf, stored_len, last) =>\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nconst _tr_flush_block = (s, buf, stored_len, last) =>\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally = (s, dist, lc) =>\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //let out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n\n//#ifdef TRUNCATE_BLOCK\n// /* Try to guess if it is profitable to stop the current block here */\n// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n// /* Compute an upper bound for the compressed length */\n// out_length = s.last_lit*8;\n// in_length = s.strstart - s.block_start;\n//\n// for (dcode = 0; dcode < D_CODES; dcode++) {\n// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n// }\n// out_length >>>= 3;\n// //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n// // s->last_lit, in_length, out_length,\n// // 100L - out_length*100L/in_length));\n// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n// return true;\n// }\n// }\n//#endif\n\n return (s.last_lit === s.lit_bufsize - 1);\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n};\n\nvar _tr_init_1 = _tr_init;\nvar _tr_stored_block_1 = _tr_stored_block;\nvar _tr_flush_block_1 = _tr_flush_block;\nvar _tr_tally_1 = _tr_tally;\nvar _tr_align_1 = _tr_align;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init: _tr_init$1, _tr_stored_block: _tr_stored_block$1, _tr_flush_block: _tr_flush_block$1, _tr_tally: _tr_tally$1, _tr_align: _tr_align$1 } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_FULL_FLUSH, Z_FINISH, Z_BLOCK,\n Z_OK, Z_STREAM_END, Z_STREAM_ERROR, Z_DATA_ERROR, Z_BUF_ERROR,\n Z_DEFAULT_COMPRESSION,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED: Z_FIXED$1, Z_DEFAULT_STRATEGY,\n Z_UNKNOWN: Z_UNKNOWN$1,\n Z_DEFLATED\n} = constants;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES$1 = 30;\n/* number of distance codes */\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42;\nconst EXTRA_STATE = 69;\nconst NAME_STATE = 73;\nconst COMMENT_STATE = 91;\nconst HCRC_STATE = 103;\nconst BUSY_STATE = 113;\nconst FINISH_STATE = 666;\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero$1 = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block$1(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH$1;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH$1 - (strend - scan);\n scan = strend - MAX_MATCH$1;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH$1) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH$1 - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH$1) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n let max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (;;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n// s.block_start >= s.w_size)) {\n// throw new Error(\"slide too late\");\n// }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n// if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n const max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n};\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH$1) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH$1) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally$1(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH$1) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH$1 - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH$1 - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH$1;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally$1(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH$1 - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH$1) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH$1;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH$1 - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH$1) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally$1(s, 1, s.match_length - MIN_MATCH$1);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero$1(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH$1 - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE$1 * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES$1 + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES$1 + 1) * 2);\n zero$1(this.dyn_ltree);\n zero$1(this.dyn_dtree);\n zero$1(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */\n zero$1(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];\n zero$1(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\nconst deflateResetKeep = (strm) => {\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN$1;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n _tr_init$1(s);\n return Z_OK;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED$1) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n};\n\n\nconst deflate = (strm, flush) => {\n\n let beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n//#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n//#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n let bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align$1(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block$1(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero$1(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n const status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero$1(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH$1) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH$1 - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH$1 - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH$1 - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH$1 - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2 = deflate;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n let i, out;\n const len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$1,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION$1,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY$1\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$1) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$1) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$1 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH$1) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$1) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$1;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$1) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1 = Deflate;\nvar deflate_2$1 = deflate$1;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar constants$1 = constants;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_2$1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD = 30; /* got a data error -- remain here until reset */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n let base_index = 0;\n// let shoextra; /* extra bits table to use */\n let end; /* use base and extra for symbol > end */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n let extra_index = 0;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$2, Z_BLOCK: Z_BLOCK$1, Z_TREES,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2, Z_NEED_DICT, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 1; /* i: waiting for magic header */\nconst FLAGS = 2; /* i: waiting for method and flags (gzip) */\nconst TIME = 3; /* i: waiting for modification time (gzip) */\nconst OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 5; /* i: waiting for extra length (gzip) */\nconst EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nconst NAME = 7; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 8; /* i: waiting for end of comment (gzip) */\nconst HCRC = 9; /* i: waiting for header crc (gzip) */\nconst DICTID = 10; /* i: waiting for dictionary check value */\nconst DICT = 11; /* waiting for inflateSetDictionary() call */\nconst TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 14; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 17; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 18; /* i: waiting for code length code lengths */\nconst CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 20; /* i: same as LEN below, but only first time in */\nconst LEN = 21; /* i: waiting for length/lit/eob code */\nconst LENEXT = 22; /* i: waiting for length extra bits */\nconst DIST = 23; /* i: waiting for distance code */\nconst DISTEXT = 24; /* i: waiting for distance extra bits */\nconst MATCH = 25; /* o: waiting for output space to copy string */\nconst LIT = 26; /* o: waiting for output space to write literal */\nconst CHECK = 27; /* i: waiting for 32-bit check value */\nconst LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 29; /* finished check, done -- remain here until reset */\nconst BAD$1 = 30; /* got a data error -- remain here until reset */\nconst MEM = 31; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS$1;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateResetKeep = (strm) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS$1);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS$1);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$2;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$2) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$2;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD$1;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED$2) {\n strm.msg = 'unknown compression method';\n state.mode = BAD$1;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD$1;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE$1;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED$2) {\n strm.msg = 'unknown compression method';\n state.mode = BAD$1;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD$1;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE$1;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE$1;\n /* falls through */\n case TYPE$1:\n if (flush === Z_BLOCK$1 || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD$1;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD$1;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE$1;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD$1;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD$1;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD$1;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD$1;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD$1) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD$1;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD$1;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD$1;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE$1) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE$1;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$2;\n break inf_leave;\n case BAD$1:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&\n (state.mode < CHECK || flush !== Z_FINISH$2))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE$1 ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$2) && ret === Z_OK$2) {\n ret = Z_BUF_ERROR$1;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$2;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$2;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$2;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2 = inflate;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\n*/\n\nvar inflate_1 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_FINISH: Z_FINISH$3,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_MEM_ERROR: Z_MEM_ERROR$1\n} = constants;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK$3) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK$3) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$3 : Z_NO_FLUSH$2;\n\n // Convert data if needed\n if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT$1 && dictionary) {\n status = inflate_1.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK$3) {\n status = inflate_1.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR$2) {\n // Replace code with more verbose\n status = Z_NEED_DICT$1;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END$3 &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1.inflateReset(strm);\n status = inflate_1.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR$2:\n case Z_DATA_ERROR$2:\n case Z_NEED_DICT$1:\n case Z_MEM_ERROR$1:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END$3) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK$3 && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END$3) {\n status = inflate_1.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$3) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1 = Inflate;\nvar inflate_2$1 = inflate$1;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip = inflate$1;\nvar constants$2 = constants;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1,\n\tinflate: inflate_2$1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip,\n\tconstants: constants$2\n};\n\nconst { Deflate: Deflate$1, deflate: deflate$2, deflateRaw: deflateRaw$1, gzip: gzip$1 } = deflate_1$1;\n\nconst { Inflate: Inflate$1, inflate: inflate$2, inflateRaw: inflateRaw$1, ungzip: ungzip$1 } = inflate_1$1;\n\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_1$2 = deflate$2;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar Inflate_1$1 = Inflate$1;\nvar inflate_1$2 = inflate$2;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip_1 = ungzip$1;\nvar constants_1 = constants;\n\nvar pako = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_1$2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tInflate: Inflate_1$1,\n\tinflate: inflate_1$2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nexport { pako as p };\n","import { p as pako } from './pako.esm-ef1fc3f4.mjs';\n\nclass GZip {\n constructor(level = 1) {\n if (level < 0 || level > 9) {\n throw new Error('Invalid gzip compression level, it should be between 0 and 9');\n }\n this.level = level;\n }\n static fromConfig({ level }) {\n return new GZip(level);\n }\n encode(data) {\n const gzipped = pako.gzip(data, { level: this.level });\n return gzipped;\n }\n decode(data, out) {\n const uncompressed = pako.ungzip(data);\n if (out !== undefined) {\n out.set(uncompressed);\n return out;\n }\n return uncompressed;\n }\n}\nGZip.codecId = 'gzip';\n\nexport default GZip;\n","import { p as pako } from './pako.esm-ef1fc3f4.mjs';\n\nclass Zlib {\n constructor(level = 1) {\n if (level < -1 || level > 9) {\n throw new Error('Invalid zlib compression level, it should be between -1 and 9');\n }\n this.level = level;\n }\n static fromConfig({ level }) {\n return new Zlib(level);\n }\n encode(data) {\n const gzipped = pako.deflate(data, { level: this.level });\n return gzipped;\n }\n decode(data, out) {\n const uncompressed = pako.inflate(data);\n if (out !== undefined) {\n out.set(uncompressed);\n return out;\n }\n return uncompressed;\n }\n}\nZlib.codecId = 'zlib';\n\nexport default Zlib;\n","const IS_NODE = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;\n// This is for the \"binary\" loader (custom code is ~2x faster than \"atob\")\n// from: https://github.com/evanw/esbuild/blob/150a01844d47127c007c2b1973158d69c560ca21/internal/runtime/runtime.go#L185\nlet __toBinary = IS_NODE\n ? (base64) => new Uint8Array(Buffer.from(base64, 'base64'))\n : /* @__PURE__ */ (() => {\n var table = new Uint8Array(128);\n for (var i = 0; i < 64; i++)\n table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;\n return (base64) => {\n var n = base64.length;\n // @ts-ignore\n var bytes = new Uint8Array((((n - (base64[n - 1] == '=') - (base64[n - 2] == '=')) * 3) / 4) | 0);\n for (var i = 0, j = 0; i < n;) {\n var c0 = table[base64.charCodeAt(i++)], c1 = table[base64.charCodeAt(i++)];\n var c2 = table[base64.charCodeAt(i++)], c3 = table[base64.charCodeAt(i++)];\n bytes[j++] = (c0 << 2) | (c1 >> 4);\n bytes[j++] = (c1 << 4) | (c2 >> 2);\n bytes[j++] = (c2 << 6) | c3;\n }\n return bytes;\n };\n })();\nfunction initEmscriptenModule(moduleFactory, src) {\n const wasmBinary = __toBinary(src);\n return moduleFactory({ noInitialRun: true, wasmBinary });\n}\n\nexport { initEmscriptenModule as i };\n","import { i as initEmscriptenModule } from './utils-6b0080f1.mjs';\n\nvar blosc_codec = (function() {\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\n \n return (\nfunction(blosc_codec) {\n blosc_codec = blosc_codec || {};\n\n\nvar f;f||(f=typeof blosc_codec !== 'undefined' ? blosc_codec : {});var aa,ba;f.ready=new Promise(function(a,b){aa=a;ba=b;});var r={},t;for(t in f)f.hasOwnProperty(t)&&(r[t]=f[t]);var ca=\"./this.program\",da=f.print||console.log.bind(console),u=f.printErr||console.warn.bind(console);for(t in r)r.hasOwnProperty(t)&&(f[t]=r[t]);r=null;f.thisProgram&&(ca=f.thisProgram);var v;f.wasmBinary&&(v=f.wasmBinary);var noExitRuntime;f.noExitRuntime&&(noExitRuntime=f.noExitRuntime);\n\"object\"!==typeof WebAssembly&&w(\"no native wasm support detected\");var y,ea=!1,fa=\"undefined\"!==typeof TextDecoder?new TextDecoder(\"utf8\"):void 0;\nfunction ha(a,b,c){var d=b+c;for(c=b;a[c]&&!(c>=d);)++c;if(16e?d+=String.fromCharCode(e):(e-=65536,d+=String.fromCharCode(55296|e>>10,56320|e&1023));}}else d+=String.fromCharCode(e);}return d}\nfunction ia(a,b,c){var d=z;if(0=g){var k=a.charCodeAt(++e);g=65536+((g&1023)<<10)|k&1023;}if(127>=g){if(b>=c)break;d[b++]=g;}else {if(2047>=g){if(b+1>=c)break;d[b++]=192|g>>6;}else {if(65535>=g){if(b+2>=c)break;d[b++]=224|g>>12;}else {if(b+3>=c)break;d[b++]=240|g>>18;d[b++]=128|g>>12&63;}d[b++]=128|g>>6&63;}d[b++]=128|g&63;}}d[b]=0;}}var ja=\"undefined\"!==typeof TextDecoder?new TextDecoder(\"utf-16le\"):void 0;\nfunction ka(a,b){var c=a>>1;for(var d=c+b/2;!(c>=d)&&A[c];)++c;c<<=1;if(32>1];if(0==e||c==b/2)return d;++c;d+=String.fromCharCode(e);}}function la(a,b,c){void 0===c&&(c=2147483647);if(2>c)return 0;c-=2;var d=b;c=c<2*a.length?c/2:a.length;for(var e=0;e>1]=a.charCodeAt(e),b+=2;C[b>>1]=0;return b-d}function ma(a){return 2*a.length}\nfunction na(a,b){for(var c=0,d=\"\";!(c>=b/4);){var e=D[a+4*c>>2];if(0==e)break;++c;65536<=e?(e-=65536,d+=String.fromCharCode(55296|e>>10,56320|e&1023)):d+=String.fromCharCode(e);}return d}function oa(a,b,c){void 0===c&&(c=2147483647);if(4>c)return 0;var d=b;c=d+c-4;for(var e=0;e=g){var k=a.charCodeAt(++e);g=65536+((g&1023)<<10)|k&1023;}D[b>>2]=g;b+=4;if(b+4>c)break}D[b>>2]=0;return b-d}\nfunction pa(a){for(var b=0,c=0;c=d&&++c;b+=4;}return b}var E,F,z,C,A,D,G,qa,ra;function sa(a){E=a;f.HEAP8=F=new Int8Array(a);f.HEAP16=C=new Int16Array(a);f.HEAP32=D=new Int32Array(a);f.HEAPU8=z=new Uint8Array(a);f.HEAPU16=A=new Uint16Array(a);f.HEAPU32=G=new Uint32Array(a);f.HEAPF32=qa=new Float32Array(a);f.HEAPF64=ra=new Float64Array(a);}var ta=f.INITIAL_MEMORY||16777216;f.wasmMemory?y=f.wasmMemory:y=new WebAssembly.Memory({initial:ta/65536,maximum:32768});\ny&&(E=y.buffer);ta=E.byteLength;sa(E);var I,ua=[],va=[],wa=[],xa=[];function ya(){var a=f.preRun.shift();ua.unshift(a);}var J=0,K=null;f.preloadedImages={};f.preloadedAudios={};function w(a){if(f.onAbort)f.onAbort(a);u(a);ea=!0;a=new WebAssembly.RuntimeError(\"abort(\"+a+\"). Build with -s ASSERTIONS=1 for more info.\");ba(a);throw a;}function Aa(a){var b=L;return String.prototype.startsWith?b.startsWith(a):0===b.indexOf(a)}function Ba(){return Aa(\"data:application/octet-stream;base64,\")}\nvar L=\"blosc_codec.wasm\";if(!Ba()){var Ca=L;L=f.locateFile?f.locateFile(Ca,\"\"):\"\"+Ca;}function Da(){try{if(v)return new Uint8Array(v);throw \"both async and sync fetching of the wasm failed\";}catch(a){w(a);}}function N(a){for(;0>2]=b;};this.X=function(b){D[this.N+0>>2]=b;};this.Y=function(){D[this.N+4>>2]=0;};this.W=function(){F[this.N+12>>0]=0;};this.Z=function(){F[this.N+13>>0]=0;};this.V=function(b,c){this.$(b);this.X(c);this.Y();this.W();this.Z();};}function Fa(a){switch(a){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(\"Unknown type size: \"+a);}}var Ga=void 0;\nfunction P(a){for(var b=\"\";z[a];)b+=Ga[z[a++]];return b}var Q={},R={},S={};function Ha(a){if(void 0===a)return \"_unknown\";a=a.replace(/[^a-zA-Z0-9_]/g,\"$\");var b=a.charCodeAt(0);return 48<=b&&57>=b?\"_\"+a:a}function Ia(a,b){a=Ha(a);return (new Function(\"body\",\"return function \"+a+'() {\\n \"use strict\"; return body.apply(this, arguments);\\n};\\n'))(b)}\nfunction Ja(a){var b=Error,c=Ia(a,function(d){this.name=a;this.message=d;d=Error(d).stack;void 0!==d&&(this.stack=this.toString()+\"\\n\"+d.replace(/^Error(:[^\\n]*)?\\n/,\"\"));});c.prototype=Object.create(b.prototype);c.prototype.constructor=c;c.prototype.toString=function(){return void 0===this.message?this.name:this.name+\": \"+this.message};return c}var Ka=void 0;function T(a){throw new Ka(a);}var La=void 0;\nfunction Ma(a,b){function c(h){h=b(h);if(h.length!==d.length)throw new La(\"Mismatched type converter count\");for(var l=0;l>2])}function Ta(a){if(null===a)return \"null\";var b=typeof a;return \"object\"===b||\"array\"===b||\"function\"===b?a.toString():\"\"+a}\nfunction Ua(a,b){switch(b){case 2:return function(c){return this.fromWireType(qa[c>>2])};case 3:return function(c){return this.fromWireType(ra[c>>3])};default:throw new TypeError(\"Unknown float type: \"+a);}}function Va(a){var b=Function;if(!(b instanceof Function))throw new TypeError(\"new_ called with constructor type \"+typeof b+\" which is not a function\");var c=Ia(b.name||\"unknownFunctionName\",function(){});c.prototype=b.prototype;c=new c;a=b.apply(c,a);return a instanceof Object?a:c}\nfunction Wa(a){for(;a.length;){var b=a.pop();a.pop()(b);}}function Xa(a,b){var c=f;if(void 0===c[a].L){var d=c[a];c[a]=function(){c[a].L.hasOwnProperty(arguments.length)||T(\"Function '\"+b+\"' called with an invalid number of arguments (\"+arguments.length+\") - expects one of (\"+c[a].L+\")!\");return c[a].L[arguments.length].apply(this,arguments)};c[a].L=[];c[a].L[d.S]=d;}}\nfunction Ya(a,b,c){f.hasOwnProperty(a)?((void 0===c||void 0!==f[a].L&&void 0!==f[a].L[c])&&T(\"Cannot register public name '\"+a+\"' twice\"),Xa(a,a),f.hasOwnProperty(c)&&T(\"Cannot register multiple overloads of a function with the same number of arguments (\"+c+\")!\"),f[a].L[c]=b):(f[a]=b,void 0!==c&&(f[a].ba=c));}function Za(a,b){for(var c=[],d=0;d>2)+d]);return c}\nfunction $a(a,b){0<=a.indexOf(\"j\")||w(\"Assertion failed: getDynCaller should only be called with i64 sigs\");var c=[];return function(){c.length=arguments.length;for(var d=0;d>1]}:function(d){return A[d>>1]};case 2:return c?function(d){return D[d>>2]}:function(d){return G[d>>2]};default:throw new TypeError(\"Unknown integer type: \"+a);}}var gb={};\nfunction hb(){if(!ib){var a={USER:\"web_user\",LOGNAME:\"web_user\",PATH:\"/\",PWD:\"/\",HOME:\"/home/web_user\",LANG:(\"object\"===typeof navigator&&navigator.languages&&navigator.languages[0]||\"C\").replace(\"-\",\"_\")+\".UTF-8\",_:ca||\"./this.program\"},b;for(b in gb)a[b]=gb[b];var c=[];for(b in a)c.push(b+\"=\"+a[b]);ib=c;}return ib}for(var ib,jb=[null,[],[]],kb=Array(256),X=0;256>X;++X)kb[X]=String.fromCharCode(X);Ga=kb;Ka=f.BindingError=Ja(\"BindingError\");La=f.InternalError=Ja(\"InternalError\");\nf.count_emval_handles=function(){for(var a=0,b=5;b>g])},M:null});},y:function(a,b){b=P(b);U(a,{name:b,fromWireType:function(c){var d=\nV[c].value;Qa(c);return d},toWireType:function(c,d){return Ra(d)},argPackAdvance:8,readValueFromPointer:Sa,M:null});},h:function(a,b,c){c=Fa(c);b=P(b);U(a,{name:b,fromWireType:function(d){return d},toWireType:function(d,e){if(\"number\"!==typeof e&&\"boolean\"!==typeof e)throw new TypeError('Cannot convert \"'+Ta(e)+'\" to '+this.name);return e},argPackAdvance:8,readValueFromPointer:Ua(b,c),M:null});},e:function(a,b,c,d,e,g){var k=Za(b,c);a=P(a);e=ab(d,e);Ya(a,function(){eb(\"Cannot call \"+a+\" due to unbound types\",\nk);},b-1);Ma(k,function(h){var l=a,n=a;h=[h[0],null].concat(h.slice(1));var p=e,q=h.length;2>q&&T(\"argTypes array size mismatch! Must at least get return value and 'this' types!\");for(var x=null!==h[1]&&!1,B=!1,m=1;m>>h};}var l=-1!=b.indexOf(\"unsigned\");U(a,{name:b,fromWireType:g,toWireType:function(n,p){if(\"number\"!==typeof p&&\"boolean\"!==typeof p)throw new TypeError('Cannot convert \"'+Ta(p)+'\" to '+this.name);if(pe)throw new TypeError('Passing a number \"'+Ta(p)+'\" from JS side to C/C++ side to an argument of type \"'+b+'\", which is outside the valid range ['+d+\", \"+e+\"]!\");return l?p>>>0:p|0},argPackAdvance:8,readValueFromPointer:fb(b,\nk,0!==d),M:null});},b:function(a,b,c){function d(g){g>>=2;var k=G;return new e(E,k[g+1],k[g])}var e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][b];c=P(c);U(a,{name:c,fromWireType:d,argPackAdvance:8,readValueFromPointer:d},{U:!0});},i:function(a,b){b=P(b);var c=\"std::string\"===b;U(a,{name:b,fromWireType:function(d){var e=G[d>>2];if(c)for(var g=d+4,k=0;k<=e;++k){var h=d+4+k;if(k==e||0==z[h]){g=g?ha(z,g,h-g):\"\";if(void 0===l)var l=g;else l+=String.fromCharCode(0),\nl+=g;g=h+1;}}else {l=Array(e);for(k=0;k=q&&(q=65536+((q&1023)<<10)|e.charCodeAt(++p)&1023);127>=q?++n:n=2047>=q?n+\n2:65535>=q?n+3:n+4;}return n}:function(){return e.length})(),h=Y(4+k+1);G[h>>2]=k;if(c&&g)ia(e,h+4,k+1);else if(g)for(g=0;g>2],p=k(),q,x=l+4,B=0;B<=n;++B){var m=l+4+B*b;if(B==n||0==p[m>>h])x=d(x,m-x),void 0===q?q=x:(q+=String.fromCharCode(0),q+=x),x=m+b;}W(l);return q},toWireType:function(l,n){\"string\"!==typeof n&&T(\"Cannot pass non-string to C++ string type \"+c);var p=g(n),q=Y(4+p+b);G[q>>2]=p>>h;e(n,q+4,p+b);null!==l&&l.push(W,q);return q},argPackAdvance:8,readValueFromPointer:Sa,M:function(l){W(l);}});},A:function(a,b){b=P(b);U(a,{aa:!0,name:b,argPackAdvance:0,fromWireType:function(){},\ntoWireType:function(){}});},n:Qa,x:function(a){4>>=0;var b=z.length;if(2147483648=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);d=Math.max(16777216,a,d);0>>16);sa(y.buffer);\nvar e=1;break a}catch(g){}e=void 0;}if(e)return !0}return !1},u:function(a,b){var c=0;hb().forEach(function(d,e){var g=b+c;e=D[a+4*e>>2]=g;for(g=0;g>0]=d.charCodeAt(g);F[e>>0]=0;c+=d.length+1;});return 0},v:function(a,b){var c=hb();D[a>>2]=c.length;var d=0;c.forEach(function(e){d+=e.length+1;});D[b>>2]=d;return 0},w:function(){return 0},q:function(){},g:function(a,b,c,d){for(var e=0,g=0;g>2],h=D[b+(8*g+4)>>2],l=0;l>2]=e;return 0},a:y,l:function(){return 0},k:function(){return 0},j:function(){},B:function(){return 6},m:function(){},f:function(){}};\n(function(){function a(e){f.asm=e.exports;I=f.asm.D;J--;f.monitorRunDependencies&&f.monitorRunDependencies(J);0==J&&(K&&(e=K,K=null,e()));}function b(e){a(e.instance);}function c(e){return Promise.resolve().then(Da).then(function(g){return WebAssembly.instantiate(g,d)}).then(e,function(g){u(\"failed to asynchronously prepare wasm: \"+g);w(g);})}var d={a:mb};J++;f.monitorRunDependencies&&f.monitorRunDependencies(J);if(f.instantiateWasm)try{return f.instantiateWasm(d,\na)}catch(e){return u(\"Module.instantiateWasm callback failed with error: \"+e),!1}(function(){return v||\"function\"!==typeof WebAssembly.instantiateStreaming||Ba()||Aa(\"file://\")||\"function\"!==typeof fetch?c(b):fetch(L,{credentials:\"same-origin\"}).then(function(e){return WebAssembly.instantiateStreaming(e,d).then(b,function(g){u(\"wasm streaming compile failed: \"+g);u(\"falling back to ArrayBuffer instantiation\");return c(b)})})})().catch(ba);return {}})();\nvar lb=f.___wasm_call_ctors=function(){return (lb=f.___wasm_call_ctors=f.asm.E).apply(null,arguments)},Y=f._malloc=function(){return (Y=f._malloc=f.asm.F).apply(null,arguments)},W=f._free=function(){return (W=f._free=f.asm.G).apply(null,arguments)},db=f.___getTypeName=function(){return (db=f.___getTypeName=f.asm.H).apply(null,arguments)};f.___embind_register_native_and_builtin_types=function(){return (f.___embind_register_native_and_builtin_types=f.asm.I).apply(null,arguments)};\nf.dynCall_jiiiii=function(){return (f.dynCall_jiiiii=f.asm.J).apply(null,arguments)};f.dynCall_jiji=function(){return (f.dynCall_jiji=f.asm.K).apply(null,arguments)};var Z;K=function nb(){Z||ob();Z||(K=nb);};\nfunction ob(){function a(){if(!Z&&(Z=!0,f.calledRun=!0,!ea)){N(va);N(wa);aa(f);if(f.onRuntimeInitialized)f.onRuntimeInitialized();if(f.postRun)for(\"function\"==typeof f.postRun&&(f.postRun=[f.postRun]);f.postRun.length;){var b=f.postRun.shift();xa.unshift(b);}N(xa);}}if(!(0 9) {\n throw new Error(`Invalid compression level: '${clevel}'. It should be between 0 and 9`);\n }\n if (!COMPRESSORS.has(cname)) {\n throw new Error(`Invalid compressor '${cname}'. Valid compressors include\n 'blosclz', 'lz4', 'lz4hc','snappy', 'zlib', 'zstd'.`);\n }\n if (shuffle < -1 || shuffle > 2) {\n throw new Error(`Invalid shuffle ${shuffle}. Must be one of 0 (NOSHUFFLE),\n 1 (SHUFFLE), 2 (BITSHUFFLE), -1 (AUTOSHUFFLE).`);\n }\n this.blocksize = blocksize;\n this.clevel = clevel;\n this.cname = cname;\n this.shuffle = shuffle;\n }\n static fromConfig(config) {\n const { blocksize, clevel, cname, shuffle } = config;\n return new Blosc(clevel, cname, shuffle, blocksize);\n }\n async encode(data) {\n if (!emscriptenModule) {\n emscriptenModule = initEmscriptenModule(blosc_codec, wasmSrc);\n }\n const module = await emscriptenModule;\n const view = module.compress(data, this.cname, this.clevel, this.shuffle, this.blocksize);\n const result = new Uint8Array(view); // Copy view and free wasm memory\n module.free_result();\n return result;\n }\n async decode(data, out) {\n if (!emscriptenModule) {\n emscriptenModule = initEmscriptenModule(blosc_codec, wasmSrc);\n }\n const module = await emscriptenModule;\n const view = module.decompress(data);\n const result = new Uint8Array(view); // Copy view and free wasm memory\n module.free_result();\n if (out !== undefined) {\n out.set(result);\n return out;\n }\n return result;\n }\n}\nBlosc.codecId = 'blosc';\nBlosc.COMPRESSORS = [...COMPRESSORS];\nBlosc.NOSHUFFLE = BloscShuffle.NOSHUFFLE;\nBlosc.SHUFFLE = BloscShuffle.SHUFFLE;\nBlosc.BITSHUFFLE = BloscShuffle.BITSHUFFLE;\nBlosc.AUTOSHUFFLE = BloscShuffle.AUTOSHUFFLE;\n\nexport default Blosc;\n","import { Zlib, GZip, Blosc } from 'numcodecs';\nimport { addCodec } from './zarr-core';\n\naddCodec(Zlib.codecId, () => Zlib);\naddCodec(GZip.codecId, () => GZip);\naddCodec(Blosc.codecId, () => Blosc);\n\nexport * from './zarr-core';\n","import {assert} from './assert';\n\nconst ERR_CONTEXT = 'Invalid WebGLRenderingContext';\nexport const ERR_WEBGL = ERR_CONTEXT;\nexport const ERR_WEBGL2 = 'Requires WebGL2';\n\nexport function isWebGL(gl) {\n if (typeof WebGLRenderingContext !== 'undefined' && gl instanceof WebGLRenderingContext) {\n return true;\n }\n if (typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) {\n return true;\n }\n // Look for debug contexts, headless gl etc\n return Boolean(gl && Number.isFinite(gl._version));\n}\n\nexport function isWebGL2(gl) {\n if (typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) {\n return true;\n }\n // Look for debug contexts, headless gl etc\n return Boolean(gl && gl._version === 2);\n}\n\nexport function getWebGL2Context(gl) {\n return isWebGL2(gl) ? gl : null;\n}\n\nexport function assertWebGLContext(gl) {\n assert(isWebGL(gl), ERR_CONTEXT);\n return gl;\n}\n\nexport function assertWebGL2Context(gl) {\n assert(isWebGL2(gl), ERR_WEBGL2);\n return gl;\n}\n","import arrayWithHoles from \"./arrayWithHoles\";\nimport iterableToArray from \"./iterableToArray\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray\";\nimport nonIterableRest from \"./nonIterableRest\";\nexport default function _toArray(arr) {\n return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();\n}","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _Alpha = require('./Alpha');\n\nObject.defineProperty(exports, 'Alpha', {\n enumerable: true,\n get: function get() {\n return _interopRequireDefault(_Alpha).default;\n }\n});\n\nvar _Checkboard = require('./Checkboard');\n\nObject.defineProperty(exports, 'Checkboard', {\n enumerable: true,\n get: function get() {\n return _interopRequireDefault(_Checkboard).default;\n }\n});\n\nvar _EditableInput = require('./EditableInput');\n\nObject.defineProperty(exports, 'EditableInput', {\n enumerable: true,\n get: function get() {\n return _interopRequireDefault(_EditableInput).default;\n }\n});\n\nvar _Hue = require('./Hue');\n\nObject.defineProperty(exports, 'Hue', {\n enumerable: true,\n get: function get() {\n return _interopRequireDefault(_Hue).default;\n }\n});\n\nvar _Raised = require('./Raised');\n\nObject.defineProperty(exports, 'Raised', {\n enumerable: true,\n get: function get() {\n return _interopRequireDefault(_Raised).default;\n }\n});\n\nvar _Saturation = require('./Saturation');\n\nObject.defineProperty(exports, 'Saturation', {\n enumerable: true,\n get: function get() {\n return _interopRequireDefault(_Saturation).default;\n }\n});\n\nvar _ColorWrap = require('./ColorWrap');\n\nObject.defineProperty(exports, 'ColorWrap', {\n enumerable: true,\n get: function get() {\n return _interopRequireDefault(_ColorWrap).default;\n }\n});\n\nvar _Swatch = require('./Swatch');\n\nObject.defineProperty(exports, 'Swatch', {\n enumerable: true,\n get: function get() {\n return _interopRequireDefault(_Swatch).default;\n }\n});\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {CubeGeometry} from '@luma.gl/core';\nimport {UNIT} from '@deck.gl/core';\nimport ColumnLayer from './column-layer';\n\nconst defaultProps = {\n cellSize: {type: 'number', min: 0, value: 1000},\n offset: {type: 'array', min: 0, value: [1, 1]}\n};\n\nexport default class GridCellLayer extends ColumnLayer {\n getGeometry(diskResolution) {\n return new CubeGeometry();\n }\n\n draw({uniforms}) {\n const {elevationScale, extruded, offset, coverage, cellSize, angle, radiusUnits} = this.props;\n this.state.model\n .setUniforms(uniforms)\n .setUniforms({\n radius: cellSize / 2,\n radiusUnits: UNIT[radiusUnits],\n angle,\n offset,\n extruded,\n coverage,\n elevationScale,\n edgeDistance: 1,\n isWireframe: false\n })\n .draw();\n }\n}\n\nGridCellLayer.layerName = 'GridCellLayer';\nGridCellLayer.defaultProps = defaultProps;\n","// Beginning of a minimal implementation of the Node.js path API, that doesn't pull in big polyfills.\n\n/**\n * Replacement for Node.js path.dirname\n * @param url\n */\nexport function dirname(url: string): string {\n const slashIndex = url && url.lastIndexOf('/');\n return slashIndex >= 0 ? url.substr(0, slashIndex as number) : '';\n}\n\n/**\n * Replacement for Node.js path.join\n * @param parts\n */\nexport function join(...parts: string[]): string {\n const separator = '/';\n parts = parts.map((part, index) => {\n if (index) {\n part = part.replace(new RegExp(`^${separator}`), '');\n }\n if (index !== parts.length - 1) {\n part = part.replace(new RegExp(`${separator}$`), '');\n }\n return part;\n });\n return parts.join(separator);\n}\n","import pkg from '../package.json';\nexport const version = pkg.version;\nexport { compile } from './compile/compile';\nexport { normalize } from './normalize';\nexport * from './util';\n//# sourceMappingURL=index.js.map","import deckLog from '../utils/log';\nimport {getLoggers} from './loggers';\n\n/* debug utility */\n\nlet loggers = {};\n\n// Conditionally load default loggers in development mode\n// eslint-disable-next-line\nif (process.env.NODE_ENV !== 'production') {\n loggers = getLoggers(deckLog);\n}\n\nexport function register(handlers) {\n loggers = handlers;\n}\n\nexport default function debug(eventType) {\n if (deckLog.level > 0 && loggers[eventType]) {\n // Not using ...args to defeat perf hit from array construction\n loggers[eventType].call(...arguments);\n }\n}\n","export const LIFECYCLE = {\n NO_STATE: 'Awaiting state',\n MATCHED: 'Matched. State transferred from previous layer',\n INITIALIZED: 'Initialized',\n AWAITING_GC: 'Discarded. Awaiting garbage collection',\n AWAITING_FINALIZATION: 'No longer matched. Awaiting garbage collection',\n FINALIZED: 'Finalized! Awaiting garbage collection'\n};\n\n/* Secret props keys */\n// Symbols are non-enumerable by default, does not show in for...in or Object.keys\n// but are copied with Object.assign ¯\\_(ツ)_/¯\n// Supported everywhere except IE11, can be polyfilled with core-js\nexport const PROP_SYMBOLS = {\n COMPONENT: Symbol.for('component'),\n ASYNC_DEFAULTS: Symbol.for('asyncPropDefaults'),\n ASYNC_ORIGINAL: Symbol.for('asyncPropOriginal'),\n ASYNC_RESOLVED: Symbol.for('asyncPropResolved')\n};\n","import turfUnion from '@turf/union';\nimport turfDifference from '@turf/difference';\nimport turfIntersect from '@turf/intersect';\nimport rewind from '@turf/rewind';\n\nimport {\n EditAction,\n ClickEvent,\n PointerMoveEvent,\n StartDraggingEvent,\n StopDraggingEvent,\n DraggingEvent,\n Pick,\n Tooltip,\n ModeProps,\n GuideFeatureCollection,\n TentativeFeature,\n} from '../types';\nimport { FeatureCollection, Feature, Polygon, Geometry, Position } from '../geojson-types';\nimport { getPickedEditHandles, getNonGuidePicks } from '../utils';\nimport { EditMode } from './edit-mode';\nimport { ImmutableFeatureCollection } from './immutable-feature-collection';\n\nexport type GeoJsonEditAction = EditAction;\n\nconst DEFAULT_GUIDES: GuideFeatureCollection = {\n type: 'FeatureCollection',\n features: [],\n};\nconst DEFAULT_TOOLTIPS: Tooltip[] = [];\n\n// Main interface for `EditMode`s that edit GeoJSON\nexport type GeoJsonEditModeType = EditMode;\n\nexport interface GeoJsonEditModeConstructor {\n new (): GeoJsonEditModeType;\n}\n\nexport class GeoJsonEditMode implements EditMode {\n _clickSequence: Position[] = [];\n\n getGuides(props: ModeProps): GuideFeatureCollection {\n return DEFAULT_GUIDES;\n }\n\n getTooltips(props: ModeProps): Tooltip[] {\n return DEFAULT_TOOLTIPS;\n }\n\n getSelectedFeature(props: ModeProps): Feature | null | undefined {\n if (props.selectedIndexes.length === 1) {\n return props.data.features[props.selectedIndexes[0]];\n }\n return null;\n }\n\n getSelectedGeometry(props: ModeProps): Geometry | null | undefined {\n const feature = this.getSelectedFeature(props);\n if (feature) {\n return feature.geometry;\n }\n return null;\n }\n\n getSelectedFeaturesAsFeatureCollection(props: ModeProps): FeatureCollection {\n const { features } = props.data;\n const selectedFeatures = props.selectedIndexes.map((selectedIndex) => features[selectedIndex]);\n return {\n type: 'FeatureCollection',\n features: selectedFeatures,\n };\n }\n\n getClickSequence(): Position[] {\n return this._clickSequence;\n }\n\n addClickSequence({ mapCoords }: ClickEvent): void {\n this._clickSequence.push(mapCoords);\n }\n\n resetClickSequence(): void {\n this._clickSequence = [];\n }\n\n getTentativeGuide(props: ModeProps): TentativeFeature | null | undefined {\n const guides = this.getGuides(props);\n\n // @ts-ignore\n return guides.features.find((f) => f.properties && f.properties.guideType === 'tentative');\n }\n\n isSelectionPicked(picks: Pick[], props: ModeProps): boolean {\n if (!picks.length) return false;\n const pickedFeatures = getNonGuidePicks(picks).map(({ index }) => index);\n const pickedHandles = getPickedEditHandles(picks).map(\n ({ properties }) => properties.featureIndex\n );\n const pickedIndexes = new Set([...pickedFeatures, ...pickedHandles]);\n return props.selectedIndexes.some((index) => pickedIndexes.has(index));\n }\n\n rewindPolygon(feature: Feature): Feature {\n const { geometry } = feature;\n\n const isPolygonal = geometry.type === 'Polygon' || geometry.type === 'MultiPolygon';\n if (isPolygonal) {\n // @ts-ignore\n return rewind(feature);\n }\n\n return feature;\n }\n\n getAddFeatureAction(\n featureOrGeometry: Geometry | Feature,\n features: FeatureCollection\n ): GeoJsonEditAction {\n // Unsure why flow can't deal with Geometry type, but there I fixed it\n const featureOrGeometryAsAny: any = featureOrGeometry;\n\n const feature: any =\n featureOrGeometryAsAny.type === 'Feature'\n ? featureOrGeometryAsAny\n : {\n type: 'Feature',\n properties: {},\n geometry: featureOrGeometryAsAny,\n };\n\n const rewindFeature = this.rewindPolygon(feature);\n const updatedData = new ImmutableFeatureCollection(features)\n .addFeature(rewindFeature)\n .getObject();\n\n return {\n updatedData,\n editType: 'addFeature',\n editContext: {\n featureIndexes: [updatedData.features.length - 1],\n },\n };\n }\n\n getAddManyFeaturesAction(\n { features: featuresToAdd }: FeatureCollection,\n features: FeatureCollection\n ): GeoJsonEditAction {\n let updatedData = new ImmutableFeatureCollection(features);\n const initialIndex = updatedData.getObject().features.length;\n const updatedIndexes = [];\n for (const feature of featuresToAdd) {\n const { properties, geometry } = feature;\n const geometryAsAny: any = geometry;\n updatedData = updatedData.addFeature({\n type: 'Feature',\n properties,\n geometry: geometryAsAny,\n });\n updatedIndexes.push(initialIndex + updatedIndexes.length);\n }\n\n return {\n updatedData: updatedData.getObject(),\n editType: 'addFeature',\n editContext: {\n featureIndexes: updatedIndexes,\n },\n };\n }\n\n getAddFeatureOrBooleanPolygonAction(\n featureOrGeometry: Polygon | Feature,\n props: ModeProps\n ): GeoJsonEditAction | null | undefined {\n const featureOrGeometryAsAny: any = featureOrGeometry;\n\n const selectedFeature = this.getSelectedFeature(props);\n const { modeConfig } = props;\n if (modeConfig && modeConfig.booleanOperation) {\n if (\n !selectedFeature ||\n (selectedFeature.geometry.type !== 'Polygon' &&\n selectedFeature.geometry.type !== 'MultiPolygon')\n ) {\n // eslint-disable-next-line no-console,no-undef\n console.warn(\n 'booleanOperation only supported for single Polygon or MultiPolygon selection'\n );\n return null;\n }\n\n const feature =\n featureOrGeometryAsAny.type === 'Feature'\n ? featureOrGeometryAsAny\n : {\n type: 'Feature',\n geometry: featureOrGeometryAsAny,\n };\n\n let updatedGeometry;\n if (modeConfig.booleanOperation === 'union') {\n updatedGeometry = turfUnion(selectedFeature, feature);\n } else if (modeConfig.booleanOperation === 'difference') {\n // @ts-ignore\n updatedGeometry = turfDifference(selectedFeature, feature);\n } else if (modeConfig.booleanOperation === 'intersection') {\n // @ts-ignore\n updatedGeometry = turfIntersect(selectedFeature, feature);\n } else {\n // eslint-disable-next-line no-console,no-undef\n console.warn(`Invalid booleanOperation ${modeConfig.booleanOperation}`);\n return null;\n }\n\n if (!updatedGeometry) {\n // eslint-disable-next-line no-console,no-undef\n console.warn('Canceling edit. Boolean operation erased entire polygon.');\n return null;\n }\n\n const featureIndex = props.selectedIndexes[0];\n\n const updatedData = new ImmutableFeatureCollection(props.data)\n .replaceGeometry(featureIndex, updatedGeometry.geometry)\n .getObject();\n\n const editAction: GeoJsonEditAction = {\n updatedData,\n editType: 'unionGeometry',\n editContext: {\n featureIndexes: [featureIndex],\n },\n };\n\n return editAction;\n }\n return this.getAddFeatureAction(featureOrGeometry, props.data);\n }\n\n createTentativeFeature(props: ModeProps): TentativeFeature {\n return null;\n }\n\n handleClick(event: ClickEvent, props: ModeProps): void {}\n handlePointerMove(event: PointerMoveEvent, props: ModeProps): void {\n const tentativeFeature = this.createTentativeFeature(props);\n if (tentativeFeature) {\n props.onEdit({\n updatedData: props.data,\n editType: 'updateTentativeFeature',\n editContext: {\n feature: tentativeFeature,\n },\n });\n }\n }\n handleStartDragging(event: StartDraggingEvent, props: ModeProps): void {}\n handleStopDragging(event: StopDraggingEvent, props: ModeProps): void {}\n handleDragging(event: DraggingEvent, props: ModeProps): void {}\n\n handleKeyUp(event: KeyboardEvent, props: ModeProps): void {\n if (event.key === 'Escape') {\n this.resetClickSequence();\n props.onEdit({\n // Because the new drawing feature is dropped, so the data will keep as the same.\n updatedData: props.data,\n editType: 'cancelFeature',\n editContext: {},\n });\n }\n }\n}\n\nexport function getIntermediatePosition(position1: Position, position2: Position): Position {\n const intermediatePosition = [\n (position1[0] + position2[0]) / 2.0,\n (position1[1] + position2[1]) / 2.0,\n ];\n // @ts-ignore\n return intermediatePosition;\n}\n","import GL from '@luma.gl/constants';\nimport Resource from './resource';\nimport Accessor from './accessor';\nimport {getGLTypeFromTypedArray, getTypedArrayFromGLType} from '../webgl-utils/typed-array-utils';\nimport {assertWebGL2Context, log} from '@luma.gl/gltools';\nimport {assert} from '../utils/assert';\nimport {checkProps} from '../utils/check-props';\n\nconst DEBUG_DATA_LENGTH = 10;\n\n// Shared prop checks for constructor and setProps\nconst DEPRECATED_PROPS = {\n offset: 'accessor.offset',\n stride: 'accessor.stride',\n type: 'accessor.type',\n size: 'accessor.size',\n divisor: 'accessor.divisor',\n normalized: 'accessor.normalized',\n integer: 'accessor.integer',\n instanced: 'accessor.divisor',\n isInstanced: 'accessor.divisor'\n};\n\n// Prop checks for constructor\nconst PROP_CHECKS_INITIALIZE = {\n removedProps: {},\n replacedProps: {\n bytes: 'byteLength'\n },\n // new Buffer() with individual accessor props is still used in apps, emit warnings\n deprecatedProps: DEPRECATED_PROPS\n};\n\n// Prop checks for setProps\nconst PROP_CHECKS_SET_PROPS = {\n // Buffer.setProps() with individual accessor props is rare => emit errors\n removedProps: DEPRECATED_PROPS\n};\n\nexport default class Buffer extends Resource {\n constructor(gl, props = {}) {\n super(gl, props);\n\n this.stubRemovedMethods('Buffer', 'v6.0', ['layout', 'setLayout', 'getIndexedParameter']);\n // this.stubRemovedMethods('Buffer', 'v7.0', ['updateAccessor']);\n\n // In WebGL1, need to make sure we use GL.ELEMENT_ARRAY_BUFFER when initializing element buffers\n // otherwise buffer type will lock to generic (non-element) buffer\n // In WebGL2, we can use GL.COPY_READ_BUFFER which avoids locking the type here\n this.target = props.target || (this.gl.webgl2 ? GL.COPY_READ_BUFFER : GL.ARRAY_BUFFER);\n\n this.initialize(props);\n\n Object.seal(this);\n }\n\n // returns number of elements in the buffer (assuming that the full buffer is used)\n getElementCount(accessor = this.accessor) {\n return Math.round(this.byteLength / Accessor.getBytesPerElement(accessor));\n }\n\n // returns number of vertices in the buffer (assuming that the full buffer is used)\n getVertexCount(accessor = this.accessor) {\n return Math.round(this.byteLength / Accessor.getBytesPerVertex(accessor));\n }\n\n // Creates and initializes the buffer object's data store.\n // Signature: `new Buffer(gl, {data: new Float32Array(...)})`\n // Signature: `new Buffer(gl, new Float32Array(...))`\n // Signature: `new Buffer(gl, 100)`\n initialize(props = {}) {\n // Signature `new Buffer(gl, new Float32Array(...)`\n if (ArrayBuffer.isView(props)) {\n props = {data: props};\n }\n\n // Signature: `new Buffer(gl, 100)`\n if (Number.isFinite(props)) {\n props = {byteLength: props};\n }\n\n props = checkProps('Buffer', props, PROP_CHECKS_INITIALIZE);\n\n // Initialize member fields\n this.usage = props.usage || GL.STATIC_DRAW;\n this.debugData = null;\n\n // Deprecated: Merge main props and accessor\n this.setAccessor(Object.assign({}, props, props.accessor));\n\n // Set data: (re)initializes the buffer\n if (props.data) {\n this._setData(props.data, props.offset, props.byteLength);\n } else {\n this._setByteLength(props.byteLength || 0);\n }\n\n return this;\n }\n\n setProps(props) {\n props = checkProps('Buffer', props, PROP_CHECKS_SET_PROPS);\n\n if ('accessor' in props) {\n this.setAccessor(props.accessor);\n }\n\n return this;\n }\n\n // Optionally stores an accessor with the buffer, makes it easier to use it as an attribute later\n // {type, size = 1, offset = 0, stride = 0, normalized = false, integer = false, divisor = 0}\n setAccessor(accessor) {\n // NOTE: From luma.gl v7.0, Accessors have an optional `buffer `field\n // (mainly to support \"interleaving\")\n // To avoid confusion, ensure `buffer.accessor` does not have a `buffer.accessor.buffer` field:\n accessor = Object.assign({}, accessor);\n delete accessor.buffer;\n\n // This new statement ensures that an \"accessor object\" is re-packaged as an Accessor instance\n this.accessor = new Accessor(accessor);\n return this;\n }\n\n // Allocate a bigger GPU buffer (if the current buffer is not big enough).\n // If a reallocation is triggered it clears the buffer\n // Returns:\n // `true`: buffer was reallocated, data was cleared\n // `false`: buffer was big enough, data is intact\n reallocate(byteLength) {\n if (byteLength > this.byteLength) {\n this._setByteLength(byteLength);\n return true;\n }\n this.bytesUsed = byteLength;\n return false;\n }\n\n // Update with new data. Reinitializes the buffer\n setData(props) {\n return this.initialize(props);\n }\n\n // Updates a subset of a buffer object's data store.\n // Data (Typed Array or ArrayBuffer), length is inferred unless provided\n // Offset into buffer\n // WebGL2 only: Offset into srcData\n // WebGL2 only: Number of bytes to be copied\n subData(props) {\n // Signature: buffer.subData(new Float32Array([...]))\n if (ArrayBuffer.isView(props)) {\n props = {data: props};\n }\n\n const {data, offset = 0, srcOffset = 0} = props;\n const byteLength = props.byteLength || props.length;\n\n assert(data);\n\n // Create the buffer - binding it here for the first time locks the type\n // In WebGL2, use GL.COPY_WRITE_BUFFER to avoid locking the type\n const target = this.gl.webgl2 ? GL.COPY_WRITE_BUFFER : this.target;\n this.gl.bindBuffer(target, this.handle);\n // WebGL2: subData supports additional srcOffset and length parameters\n if (srcOffset !== 0 || byteLength !== undefined) {\n assertWebGL2Context(this.gl);\n this.gl.bufferSubData(this.target, offset, data, srcOffset, byteLength);\n } else {\n this.gl.bufferSubData(target, offset, data);\n }\n this.gl.bindBuffer(target, null);\n\n // TODO - update local `data` if offsets are right\n this.debugData = null;\n\n this._inferType(data);\n\n return this;\n }\n\n // WEBGL2 ONLY: Copies part of the data of another buffer into this buffer\n copyData({sourceBuffer, readOffset = 0, writeOffset = 0, size}) {\n const {gl} = this;\n assertWebGL2Context(gl);\n\n // Use GL.COPY_READ_BUFFER+GL.COPY_WRITE_BUFFER avoid disturbing other targets and locking type\n gl.bindBuffer(GL.COPY_READ_BUFFER, sourceBuffer.handle);\n gl.bindBuffer(GL.COPY_WRITE_BUFFER, this.handle);\n gl.copyBufferSubData(GL.COPY_READ_BUFFER, GL.COPY_WRITE_BUFFER, readOffset, writeOffset, size);\n gl.bindBuffer(GL.COPY_READ_BUFFER, null);\n gl.bindBuffer(GL.COPY_WRITE_BUFFER, null);\n\n // TODO - update local `data` if offsets are 0\n this.debugData = null;\n\n return this;\n }\n\n // WEBGL2 ONLY: Reads data from buffer into an ArrayBufferView or SharedArrayBuffer.\n getData({dstData = null, srcByteOffset = 0, dstOffset = 0, length = 0} = {}) {\n assertWebGL2Context(this.gl);\n\n const ArrayType = getTypedArrayFromGLType(this.accessor.type || GL.FLOAT, {clamped: false});\n const sourceAvailableElementCount = this._getAvailableElementCount(srcByteOffset);\n\n const dstElementOffset = dstOffset;\n\n let dstAvailableElementCount;\n let dstElementCount;\n if (dstData) {\n dstElementCount = dstData.length;\n dstAvailableElementCount = dstElementCount - dstElementOffset;\n } else {\n // Allocate ArrayBufferView with enough size to copy all eligible data.\n dstAvailableElementCount = Math.min(\n sourceAvailableElementCount,\n length || sourceAvailableElementCount\n );\n dstElementCount = dstElementOffset + dstAvailableElementCount;\n }\n\n const copyElementCount = Math.min(sourceAvailableElementCount, dstAvailableElementCount);\n length = length || copyElementCount;\n assert(length <= copyElementCount);\n dstData = dstData || new ArrayType(dstElementCount);\n\n // Use GL.COPY_READ_BUFFER to avoid disturbing other targets and locking type\n this.gl.bindBuffer(GL.COPY_READ_BUFFER, this.handle);\n this.gl.getBufferSubData(GL.COPY_READ_BUFFER, srcByteOffset, dstData, dstOffset, length);\n this.gl.bindBuffer(GL.COPY_READ_BUFFER, null);\n\n // TODO - update local `data` if offsets are 0\n return dstData;\n }\n\n /**\n * Binds a buffer to a given binding point (target).\n * GL.TRANSFORM_FEEDBACK_BUFFER and GL.UNIFORM_BUFFER take an index, and optionally a range.\n * - GL.TRANSFORM_FEEDBACK_BUFFER and GL.UNIFORM_BUFFER need an index to affect state\n * - GL.UNIFORM_BUFFER: `offset` must be aligned to GL.UNIFORM_BUFFER_OFFSET_ALIGNMENT.\n * - GL.UNIFORM_BUFFER: `size` must be a minimum of GL.UNIFORM_BLOCK_SIZE_DATA.\n */\n bind({\n target = this.target, // target for the bind operation\n index = this.accessor && this.accessor.index, // index = index of target (indexed bind point)\n offset = 0,\n size\n } = {}) {\n // NOTE: While GL.TRANSFORM_FEEDBACK_BUFFER and GL.UNIFORM_BUFFER could\n // be used as direct binding points, they will not affect transform feedback or\n // uniform buffer state. Instead indexed bindings need to be made.\n if (target === GL.UNIFORM_BUFFER || target === GL.TRANSFORM_FEEDBACK_BUFFER) {\n if (size !== undefined) {\n this.gl.bindBufferRange(target, index, this.handle, offset, size);\n } else {\n assert(offset === 0); // Make sure offset wasn't supplied\n this.gl.bindBufferBase(target, index, this.handle);\n }\n } else {\n this.gl.bindBuffer(target, this.handle);\n }\n\n return this;\n }\n\n unbind({target = this.target, index = this.accessor && this.accessor.index} = {}) {\n const isIndexedBuffer = target === GL.UNIFORM_BUFFER || target === GL.TRANSFORM_FEEDBACK_BUFFER;\n if (isIndexedBuffer) {\n this.gl.bindBufferBase(target, index, null);\n } else {\n this.gl.bindBuffer(target, null);\n }\n return this;\n }\n\n // PROTECTED METHODS (INTENDED FOR USE BY OTHER FRAMEWORK CODE ONLY)\n\n // Returns a short initial data array\n getDebugData() {\n if (!this.debugData) {\n this.debugData = this.getData({length: Math.min(DEBUG_DATA_LENGTH, this.byteLength)});\n return {data: this.debugData, changed: true};\n }\n return {data: this.debugData, changed: false};\n }\n\n invalidateDebugData() {\n this.debugData = null;\n }\n\n // PRIVATE METHODS\n\n // Allocate a new buffer and initialize to contents of typed array\n _setData(data, offset = 0, byteLength = data.byteLength + offset) {\n assert(ArrayBuffer.isView(data));\n\n this._trackDeallocatedMemory();\n\n const target = this._getTarget();\n this.gl.bindBuffer(target, this.handle);\n this.gl.bufferData(target, byteLength, this.usage);\n this.gl.bufferSubData(target, offset, data);\n this.gl.bindBuffer(target, null);\n\n this.debugData = data.slice(0, DEBUG_DATA_LENGTH);\n this.bytesUsed = byteLength;\n\n this._trackAllocatedMemory(byteLength);\n\n // infer GL type from supplied typed array\n const type = getGLTypeFromTypedArray(data);\n assert(type);\n this.setAccessor(new Accessor(this.accessor, {type}));\n return this;\n }\n\n // Allocate a GPU buffer of specified size.\n _setByteLength(byteLength, usage = this.usage) {\n assert(byteLength >= 0);\n\n this._trackDeallocatedMemory();\n\n // Workaround needed for Safari (#291):\n // gl.bufferData with size equal to 0 crashes. Instead create zero sized array.\n let data = byteLength;\n if (byteLength === 0) {\n data = new Float32Array(0);\n }\n\n const target = this._getTarget();\n this.gl.bindBuffer(target, this.handle);\n this.gl.bufferData(target, data, usage);\n this.gl.bindBuffer(target, null);\n\n this.usage = usage;\n this.debugData = null;\n this.bytesUsed = byteLength;\n\n this._trackAllocatedMemory(byteLength);\n\n return this;\n }\n\n // Binding a buffer for the first time locks the type\n // In WebGL2, use GL.COPY_WRITE_BUFFER to avoid locking the type\n _getTarget() {\n return this.gl.webgl2 ? GL.COPY_WRITE_BUFFER : this.target;\n }\n\n _getAvailableElementCount(srcByteOffset) {\n const ArrayType = getTypedArrayFromGLType(this.accessor.type || GL.FLOAT, {clamped: false});\n const sourceElementOffset = srcByteOffset / ArrayType.BYTES_PER_ELEMENT;\n return this.getElementCount() - sourceElementOffset;\n }\n\n // Automatically infers type from typed array passed to setData\n // Note: No longer that useful, since type is now autodeduced from the compiled shaders\n _inferType(data) {\n if (!this.accessor.type) {\n this.setAccessor(new Accessor(this.accessor, {type: getGLTypeFromTypedArray(data)}));\n }\n }\n\n // RESOURCE METHODS\n\n _createHandle() {\n return this.gl.createBuffer();\n }\n\n _deleteHandle() {\n this.gl.deleteBuffer(this.handle);\n this._trackDeallocatedMemory();\n }\n\n _getParameter(pname) {\n this.gl.bindBuffer(this.target, this.handle);\n const value = this.gl.getBufferParameter(this.target, pname);\n this.gl.bindBuffer(this.target, null);\n return value;\n }\n\n // DEPRECATIONS - v7.0\n get type() {\n log.deprecated('Buffer.type', 'Buffer.accessor.type')();\n return this.accessor.type;\n }\n\n get bytes() {\n log.deprecated('Buffer.bytes', 'Buffer.byteLength')();\n return this.byteLength;\n }\n\n // DEPRECATIONS - v6.0\n // Deprecated in v6.x, but not warnings not properly implemented\n setByteLength(byteLength) {\n log.deprecated('setByteLength', 'reallocate')();\n return this.reallocate(byteLength);\n }\n\n // Deprecated in v6.x, but not warnings not properly implemented\n updateAccessor(opts) {\n log.deprecated('updateAccessor(...)', 'setAccessor(new Accessor(buffer.accessor, ...)')();\n this.accessor = new Accessor(this.accessor, opts);\n return this;\n }\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Hammer from './utils/hammer';\n\n// This module contains constants that must be conditionally required\n// due to `window`/`document` references downstream.\nexport const RECOGNIZERS = Hammer\n ? [\n [Hammer.Pan, {event: 'tripan', pointers: 3, threshold: 0, enable: false}],\n [Hammer.Rotate, {enable: false}],\n [Hammer.Pinch, {enable: false}],\n [Hammer.Swipe, {enable: false}],\n [Hammer.Pan, {threshold: 0, enable: false}],\n [Hammer.Press, {enable: false}],\n [Hammer.Tap, {event: 'doubletap', taps: 2, enable: false}],\n // TODO - rename to 'tap' and 'singletap' in the next major release\n [Hammer.Tap, {event: 'anytap', enable: false}],\n [Hammer.Tap, {enable: false}]\n ]\n : null;\n\n// Recognize the following gestures even if a given recognizer succeeds\nexport const RECOGNIZER_COMPATIBLE_MAP = {\n tripan: ['rotate', 'pinch', 'pan'],\n rotate: ['pinch'],\n pinch: ['pan'],\n pan: ['press', 'doubletap', 'anytap', 'tap'],\n doubletap: ['anytap'],\n anytap: ['tap']\n};\n\n// Recognize the folling gestures only if a given recognizer fails\nexport const RECOGNIZER_FALLBACK_MAP = {\n doubletap: ['tap']\n};\n\n/**\n * Only one set of basic input events will be fired by Hammer.js:\n * either pointer, touch, or mouse, depending on system support.\n * In order to enable an application to be agnostic of system support,\n * alias basic input events into \"classes\" of events: down, move, and up.\n * See `_onBasicInput()` for usage of these aliases.\n */\nexport const BASIC_EVENT_ALIASES = {\n pointerdown: 'pointerdown',\n pointermove: 'pointermove',\n pointerup: 'pointerup',\n touchstart: 'pointerdown',\n touchmove: 'pointermove',\n touchend: 'pointerup',\n mousedown: 'pointerdown',\n mousemove: 'pointermove',\n mouseup: 'pointerup'\n};\n\nexport const INPUT_EVENT_TYPES = {\n KEY_EVENTS: ['keydown', 'keyup'],\n MOUSE_EVENTS: ['mousedown', 'mousemove', 'mouseup', 'mouseover', 'mouseout', 'mouseleave'],\n WHEEL_EVENTS: [\n // Chrome, Safari\n 'wheel',\n // IE\n 'mousewheel'\n ]\n};\n\n/**\n * \"Gestural\" events are those that have semantic meaning beyond the basic input event,\n * e.g. a click or tap is a sequence of `down` and `up` events with no `move` event in between.\n * Hammer.js handles these with its Recognizer system;\n * this block maps event names to the Recognizers required to detect the events.\n */\nexport const EVENT_RECOGNIZER_MAP = {\n tap: 'tap',\n anytap: 'anytap',\n doubletap: 'doubletap',\n press: 'press',\n pinch: 'pinch',\n pinchin: 'pinch',\n pinchout: 'pinch',\n pinchstart: 'pinch',\n pinchmove: 'pinch',\n pinchend: 'pinch',\n pinchcancel: 'pinch',\n rotate: 'rotate',\n rotatestart: 'rotate',\n rotatemove: 'rotate',\n rotateend: 'rotate',\n rotatecancel: 'rotate',\n tripan: 'tripan',\n tripanstart: 'tripan',\n tripanmove: 'tripan',\n tripanup: 'tripan',\n tripandown: 'tripan',\n tripanleft: 'tripan',\n tripanright: 'tripan',\n tripanend: 'tripan',\n tripancancel: 'tripan',\n pan: 'pan',\n panstart: 'pan',\n panmove: 'pan',\n panup: 'pan',\n pandown: 'pan',\n panleft: 'pan',\n panright: 'pan',\n panend: 'pan',\n pancancel: 'pan',\n swipe: 'swipe',\n swipeleft: 'swipe',\n swiperight: 'swipe',\n swipeup: 'swipe',\n swipedown: 'swipe'\n};\n\n/**\n * Map gestural events typically provided by browsers\n * that are not reported in 'hammer.input' events\n * to corresponding Hammer.js gestures.\n */\nexport const GESTURE_EVENT_ALIASES = {\n click: 'tap',\n anyclick: 'anytap',\n dblclick: 'doubletap',\n mousedown: 'pointerdown',\n mousemove: 'pointermove',\n mouseup: 'pointerup',\n mouseover: 'pointerover',\n mouseout: 'pointerout',\n mouseleave: 'pointerleave'\n};\n","export default function assert(condition, message) {\n if (!condition) {\n throw new Error(`math.gl assertion ${message}`);\n }\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {config, formatValue, equals, isArray} from '../../lib/common';\nimport assert from '../../lib/assert';\n\nexport default class MathArray extends Array {\n // Defined by derived class\n get ELEMENTS() {\n assert(false);\n return 0;\n }\n\n clone() {\n // @ts-ignore error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.\n return new this.constructor().copy(this);\n }\n\n from(arrayOrObject) {\n // @ts-ignore error TS2339: Property 'copy' does not exist on type 'MathArray'.\n return Array.isArray(arrayOrObject) ? this.copy(arrayOrObject) : this.fromObject(arrayOrObject);\n }\n\n fromArray(array, offset = 0) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = array[i + offset];\n }\n return this.check();\n }\n\n to(arrayOrObject) {\n if (arrayOrObject === this) {\n return this;\n }\n // @ts-ignore error TS2339: Property 'toObject' does not exist on type 'MathArray'.\n return isArray(arrayOrObject) ? this.toArray(arrayOrObject) : this.toObject(arrayOrObject);\n }\n\n toTarget(target) {\n return target ? this.to(target) : this;\n }\n\n toArray(array = [], offset = 0) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n array[offset + i] = this[i];\n }\n return array;\n }\n\n toFloat32Array() {\n return new Float32Array(this);\n }\n\n toString() {\n return this.formatString(config);\n }\n\n formatString(opts) {\n let string = '';\n for (let i = 0; i < this.ELEMENTS; ++i) {\n string += (i > 0 ? ', ' : '') + formatValue(this[i], opts);\n }\n return `${opts.printTypes ? this.constructor.name : ''}[${string}]`;\n }\n\n equals(array) {\n if (!array || this.length !== array.length) {\n return false;\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n if (!equals(this[i], array[i])) {\n return false;\n }\n }\n return true;\n }\n\n exactEquals(array) {\n if (!array || this.length !== array.length) {\n return false;\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n if (this[i] !== array[i]) {\n return false;\n }\n }\n return true;\n }\n\n // Modifiers\n\n negate() {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = -this[i];\n }\n return this.check();\n }\n\n lerp(a, b, t) {\n if (t === undefined) {\n t = b;\n b = a;\n a = this; // eslint-disable-line\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n const ai = a[i];\n this[i] = ai + t * (b[i] - ai);\n }\n return this.check();\n }\n\n min(vector) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.min(vector[i], this[i]);\n }\n return this.check();\n }\n\n max(vector) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.max(vector[i], this[i]);\n }\n return this.check();\n }\n\n clamp(minVector, maxVector) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.min(Math.max(this[i], minVector[i]), maxVector[i]);\n }\n return this.check();\n }\n\n add(...vectors) {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] += vector[i];\n }\n }\n return this.check();\n }\n\n subtract(...vectors) {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] -= vector[i];\n }\n }\n return this.check();\n }\n\n scale(scale) {\n if (Array.isArray(scale)) {\n // @ts-ignore error TS2339: Property 'multiply' does not exist on type 'MathArray'.\n return this.multiply(scale);\n }\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= scale;\n }\n return this.check();\n }\n\n // three.js compatibility\n\n sub(a) {\n return this.subtract(a);\n }\n\n setScalar(a) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = a;\n }\n return this.check();\n }\n\n addScalar(a) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] += a;\n }\n return this.check();\n }\n\n subScalar(a) {\n return this.addScalar(-a);\n }\n\n multiplyScalar(scalar) {\n // Multiplies all elements\n // `Matrix4.scale` only scales its 3x3 \"minor\"\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= scalar;\n }\n return this.check();\n }\n\n divideScalar(a) {\n return this.scale(1 / a);\n }\n\n clampScalar(min, max) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] = Math.min(Math.max(this[i], min), max);\n }\n return this.check();\n }\n\n // Cesium compatibility\n\n multiplyByScalar(scalar) {\n return this.scale(scalar);\n }\n\n // THREE.js compatibility\n get elements() {\n return this;\n }\n\n // Debug checks\n\n check() {\n if (config.debug && !this.validate()) {\n throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);\n }\n return this;\n }\n\n validate() {\n let valid = this.length === this.ELEMENTS;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n valid = valid && Number.isFinite(this[i]);\n }\n return valid;\n }\n}\n","import MathArray from './math-array';\nimport {checkNumber} from '../../lib/validators';\nimport assert from '../../lib/assert';\n\nexport default class Vector extends MathArray {\n get ELEMENTS() {\n assert(false);\n return 0;\n }\n\n // VIRTUAL METHODS\n copy(vector) {\n assert(false);\n return this;\n }\n\n // ACCESSORS\n\n get x() {\n return this[0];\n }\n set x(value) {\n this[0] = checkNumber(value);\n }\n\n get y() {\n return this[1];\n }\n set y(value) {\n this[1] = checkNumber(value);\n }\n\n // NOTE: `length` is a reserved word for Arrays, so we can't use `v.length()`\n // Offer `len` and `magnitude`\n len() {\n return Math.sqrt(this.lengthSquared());\n }\n\n magnitude() {\n return this.len();\n }\n\n lengthSquared() {\n let length = 0;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n length += this[i] * this[i];\n }\n return length;\n }\n\n magnitudeSquared() {\n return this.lengthSquared();\n }\n\n distance(mathArray) {\n return Math.sqrt(this.distanceSquared(mathArray));\n }\n\n distanceSquared(mathArray) {\n let length = 0;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n const dist = this[i] - mathArray[i];\n length += dist * dist;\n }\n return checkNumber(length);\n }\n\n dot(mathArray) {\n let product = 0;\n for (let i = 0; i < this.ELEMENTS; ++i) {\n product += this[i] * mathArray[i];\n }\n return checkNumber(product);\n }\n\n // MODIFIERS\n\n normalize() {\n const length = this.magnitude();\n if (length !== 0) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] /= length;\n }\n }\n return this.check();\n }\n\n // negate() {\n // for (let i = 0; i < this.ELEMENTS; ++i) {\n // this[i] = -this[i];\n // }\n // return this.check();\n // }\n\n // inverse() {\n // for (let i = 0; i < this.ELEMENTS; ++i) {\n // this[i] = 1 / this[i];\n // }\n // return this.check();\n // }\n\n multiply(...vectors) {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] *= vector[i];\n }\n }\n return this.check();\n }\n\n divide(...vectors) {\n for (const vector of vectors) {\n for (let i = 0; i < this.ELEMENTS; ++i) {\n this[i] /= vector[i];\n }\n }\n return this.check();\n }\n\n // THREE.js compatibility\n lengthSq() {\n return this.lengthSquared();\n }\n\n distanceTo(vector) {\n return this.distance(vector);\n }\n\n distanceToSquared(vector) {\n return this.distanceSquared(vector);\n }\n\n getComponent(i) {\n assert(i >= 0 && i < this.ELEMENTS, 'index is out of range');\n return checkNumber(this[i]);\n }\n\n setComponent(i, value) {\n assert(i >= 0 && i < this.ELEMENTS, 'index is out of range');\n this[i] = value;\n return this.check();\n }\n\n addVectors(a, b) {\n return this.copy(a).add(b);\n }\n\n subVectors(a, b) {\n return this.copy(a).subtract(b);\n }\n\n multiplyVectors(a, b) {\n return this.copy(a).multiply(b);\n }\n\n addScaledVector(a, b) {\n // @ts-ignore error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.\n return this.add(new this.constructor(a).multiplyScalar(b));\n }\n}\n","/* eslint-disable camelcase */\n// vec2 additions\n\nexport function vec2_transformMat4AsVector(out, a, m) {\n const x = a[0];\n const y = a[1];\n const w = m[3] * x + m[7] * y || 1.0;\n out[0] = (m[0] * x + m[4] * y) / w;\n out[1] = (m[1] * x + m[5] * y) / w;\n return out;\n}\n\n// vec3 additions\n\n// Transform as vector, only uses 3x3 minor matrix\nexport function vec3_transformMat4AsVector(out, a, m) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n const w = m[3] * x + m[7] * y + m[11] * z || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z) / w;\n return out;\n}\n\nexport function vec3_transformMat2(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n out[2] = a[2];\n return out;\n}\n\n// vec4 additions\n\nexport function vec4_transformMat2(out, a, m) {\n const x = a[0];\n const y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n\nexport function vec4_transformMat3(out, a, m) {\n const x = a[0];\n const y = a[1];\n const z = a[2];\n out[0] = m[0] * x + m[3] * y + m[6] * z;\n out[1] = m[1] * x + m[4] * y + m[7] * z;\n out[2] = m[2] * x + m[5] * y + m[8] * z;\n out[3] = a[3];\n return out;\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Vector from './base/vector';\nimport {config, isArray} from '../lib/common';\nimport {checkNumber} from '../lib/validators';\n\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as vec3 from 'gl-matrix/vec3';\n// eslint-disable-next-line camelcase\nimport {vec3_transformMat2, vec3_transformMat4AsVector} from '../lib/gl-matrix-extras';\n\nconst ORIGIN = [0, 0, 0];\nconst constants = {};\n\nexport default class Vector3 extends Vector {\n static get ZERO() {\n return (constants.ZERO = constants.ZERO || Object.freeze(new Vector3(0, 0, 0, 0)));\n }\n\n /**\n * @class\n * @param {Number | [Number, Number, Number]} x\n * @param {Number} y - rotation around X (latitude)\n * @param {Number} z - rotation around X (latitude)\n */\n constructor(x = 0, y = 0, z = 0) {\n // PERF NOTE: initialize elements as double precision numbers\n super(-0, -0, -0);\n if (arguments.length === 1 && isArray(x)) {\n this.copy(x);\n } else {\n // this.set(x, y, z);\n if (config.debug) {\n checkNumber(x);\n checkNumber(y);\n checkNumber(z);\n }\n // @ts-ignore TS2412: Property '0' of type 'number | [number, number, number]' is not assignable to numeric index type 'number'\n this[0] = x;\n this[1] = y;\n this[2] = z;\n }\n }\n\n set(x, y, z) {\n this[0] = x;\n this[1] = y;\n this[2] = z;\n return this.check();\n }\n\n copy(array) {\n this[0] = array[0];\n this[1] = array[1];\n this[2] = array[2];\n return this.check();\n }\n\n fromObject(object) {\n if (config.debug) {\n checkNumber(object.x);\n checkNumber(object.y);\n checkNumber(object.z);\n }\n this[0] = object.x;\n this[1] = object.y;\n this[2] = object.z;\n return this.check();\n }\n\n toObject(object) {\n object.x = this[0];\n object.y = this[1];\n object.z = this[2];\n return object;\n }\n\n // Getters/setters\n /* eslint-disable no-multi-spaces, brace-style, no-return-assign */\n get ELEMENTS() {\n return 3;\n }\n\n // x,y inherited from Vector\n\n get z() {\n return this[2];\n }\n set z(value) {\n this[2] = checkNumber(value);\n }\n /* eslint-enable no-multi-spaces, brace-style, no-return-assign */\n\n angle(vector) {\n return vec3.angle(this, vector);\n }\n\n // MODIFIERS\n\n cross(vector) {\n vec3.cross(this, this, vector);\n return this.check();\n }\n\n rotateX({radians, origin = ORIGIN}) {\n vec3.rotateX(this, this, origin, radians);\n return this.check();\n }\n\n rotateY({radians, origin = ORIGIN}) {\n vec3.rotateY(this, this, origin, radians);\n return this.check();\n }\n\n rotateZ({radians, origin = ORIGIN}) {\n vec3.rotateZ(this, this, origin, radians);\n return this.check();\n }\n\n // Transforms\n\n // transforms as point (4th component is implicitly 1)\n transform(matrix4) {\n return this.transformAsPoint(matrix4);\n }\n\n // transforms as point (4th component is implicitly 1)\n transformAsPoint(matrix4) {\n vec3.transformMat4(this, this, matrix4);\n return this.check();\n }\n\n // transforms as vector (4th component is implicitly 0, ignores translation. slightly faster)\n transformAsVector(matrix4) {\n vec3_transformMat4AsVector(this, this, matrix4);\n return this.check();\n }\n\n transformByMatrix3(matrix3) {\n vec3.transformMat3(this, this, matrix3);\n return this.check();\n }\n\n transformByMatrix2(matrix2) {\n vec3_transformMat2(this, this, matrix2);\n return this.check();\n }\n\n transformByQuaternion(quaternion) {\n vec3.transformQuat(this, this, quaternion);\n return this.check();\n }\n}\n","import {Vector3} from '@math.gl/core';\nimport {INTERSECTION} from '../../constants';\n\nconst scratchVector = new Vector3();\nconst scratchNormal = new Vector3();\n\nexport default class AxisAlignedBoundingBox {\n constructor(minimum = [0, 0, 0], maximum = [0, 0, 0], center = null) {\n // If center was not defined, compute it.\n center = center || scratchVector.copy(minimum).add(maximum).scale(0.5);\n this.center = new Vector3(center);\n this.halfDiagonal = new Vector3(maximum).subtract(this.center);\n\n /**\n * The minimum point defining the bounding box.\n * @type {Vector3}\n * @default {@link 0, 0, 0}\n */\n this.minimum = new Vector3(minimum);\n\n /**\n * The maximum point defining the bounding box.\n * @type {Vector3}\n * @default {@link 0, 0, 0}\n */\n this.maximum = new Vector3(maximum);\n }\n\n /**\n * Duplicates a AxisAlignedBoundingBox instance.\n *\n * @returns {AxisAlignedBoundingBox} A new AxisAlignedBoundingBox instance.\n */\n clone() {\n return new AxisAlignedBoundingBox(this.minimum, this.maximum, this.center);\n }\n\n /**\n * Compares the provided AxisAlignedBoundingBox componentwise and returns\n * true if they are equal, false otherwise.\n *\n * @param {AxisAlignedBoundingBox} [right] The second AxisAlignedBoundingBox to compare with.\n * @returns {Boolean} true if left and right are equal, false otherwise.\n */\n equals(right) {\n return (\n this === right ||\n (Boolean(right) && this.minimum.equals(right.minimum) && this.maximum.equals(right.maximum))\n );\n }\n\n transform(transformation) {\n this.center.transformAsPoint(transformation);\n // TODO - this.halfDiagonal.transformAsVector(transformation);\n this.halfDiagonal.transform(transformation);\n this.minimum.transform(transformation);\n this.maximum.transform(transformation);\n return this;\n }\n\n /**\n * Determines which side of a plane a box is located.\n */\n intersectPlane(plane) {\n const {halfDiagonal} = this;\n const normal = scratchNormal.from(plane.normal);\n const e =\n halfDiagonal.x * Math.abs(normal.x) +\n halfDiagonal.y * Math.abs(normal.y) +\n halfDiagonal.z * Math.abs(normal.z);\n const s = this.center.dot(normal) + plane.distance; // signed distance from center\n\n if (s - e > 0) {\n return INTERSECTION.INSIDE;\n }\n\n if (s + e < 0) {\n // Not in front because normals point inward\n return INTERSECTION.OUTSIDE;\n }\n\n return INTERSECTION.INTERSECTING;\n }\n\n // Computes the estimated distance from the closest point on a bounding box to a point.\n distanceTo(point) {\n return Math.sqrt(this.distanceSquaredTo(point));\n }\n\n // Computes the estimated distance squared from the closest point on a bounding box to a point.\n // A simplified version of OrientedBoundingBox.distanceSquaredTo\n distanceSquaredTo(point) {\n const offset = scratchVector.from(point).subtract(this.center);\n const {halfDiagonal} = this;\n\n let distanceSquared = 0.0;\n let d;\n\n d = Math.abs(offset.x) - halfDiagonal.x;\n if (d > 0) {\n distanceSquared += d * d;\n }\n\n d = Math.abs(offset.y) - halfDiagonal.y;\n if (d > 0) {\n distanceSquared += d * d;\n }\n\n d = Math.abs(offset.z) - halfDiagonal.z;\n if (d > 0) {\n distanceSquared += d * d;\n }\n\n return distanceSquared;\n }\n}\n","// This file is derived from the Cesium math library under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {Vector3} from '@math.gl/core';\nimport * as mat4 from 'gl-matrix/mat4';\nimport {INTERSECTION} from '../../constants';\n\n// import Rectangle from './rectangle';\n\n// const defaultProjection = new GeographicProjection();\n// const fromRectangle2DLowerLeft = new Vector3();\n// const fromRectangle2DUpperRight = new Vector3();\n// const fromRectangle2DSouthwest = new Cartographic();\n// const fromRectangle2DNortheast = new Cartographic();\n\n// const fromRectangle3DScratch = [];\n\nconst scratchVector = new Vector3();\nconst scratchVector2 = new Vector3();\n\nexport default class BoundingSphere {\n constructor(center = [0, 0, 0], radius = 0.0) {\n this.radius = -0;\n this.center = new Vector3();\n this.fromCenterRadius(center, radius);\n }\n\n fromCenterRadius(center, radius) {\n this.center.from(center);\n this.radius = radius;\n return this;\n }\n\n fromCornerPoints(corner, oppositeCorner) {\n oppositeCorner = scratchVector.from(oppositeCorner);\n this.center = new Vector3().from(corner).add(oppositeCorner).scale(0.5);\n this.radius = this.center.distance(oppositeCorner);\n return this;\n }\n\n equals(right) {\n return (\n this === right ||\n (Boolean(right) && this.center.equals(right.center) && this.radius === right.radius)\n );\n }\n\n clone() {\n return new BoundingSphere(this.center, this.radius);\n }\n\n union(boundingSphere) {\n const leftCenter = this.center;\n const leftRadius = this.radius;\n const rightCenter = boundingSphere.center;\n const rightRadius = boundingSphere.radius;\n\n const toRightCenter = scratchVector.copy(rightCenter).subtract(leftCenter);\n const centerSeparation = toRightCenter.magnitude();\n\n if (leftRadius >= centerSeparation + rightRadius) {\n // Left sphere wins.\n return this.clone();\n }\n\n if (rightRadius >= centerSeparation + leftRadius) {\n // Right sphere wins.\n return boundingSphere.clone();\n }\n\n // There are two tangent points, one on far side of each sphere.\n const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;\n\n // Compute the center point halfway between the two tangent points.\n scratchVector2\n .copy(toRightCenter)\n .scale((-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation)\n .add(leftCenter);\n\n this.center.copy(scratchVector2);\n this.radius = halfDistanceBetweenTangentPoints;\n\n return this;\n }\n\n expand(point) {\n point = scratchVector.from(point);\n const radius = point.subtract(this.center).magnitude();\n if (radius > this.radius) {\n this.radius = radius;\n }\n return this;\n }\n\n transform(transform) {\n this.center.transform(transform);\n const scale = mat4.getScaling(scratchVector, transform);\n this.radius = Math.max(scale[0], Math.max(scale[1], scale[2])) * this.radius;\n return this;\n }\n\n // Computes the estimated distance squared from the closest point on a bounding sphere to a point.\n distanceSquaredTo(point) {\n const d = this.distanceTo(point);\n return d * d;\n }\n\n distanceTo(point) {\n point = scratchVector.from(point);\n const delta = point.subtract(this.center);\n return Math.max(0, delta.len() - this.radius);\n }\n\n // Determines which side of a plane a sphere is located.\n intersectPlane(plane) {\n const center = this.center;\n const radius = this.radius;\n const normal = plane.normal;\n const distanceToPlane = normal.dot(center) + plane.distance;\n\n // The center point is negative side of the plane normal\n if (distanceToPlane < -radius) {\n return INTERSECTION.OUTSIDE;\n }\n // The center point is positive side of the plane, but radius extends beyond it; partial overlap\n if (distanceToPlane < radius) {\n return INTERSECTION.INTERSECTING;\n }\n // The center point and radius is positive side of the plane\n return INTERSECTION.INSIDE;\n }\n}\n","import MathArray from './math-array';\nimport {checkNumber} from '../../lib/validators';\nimport {config} from '../../lib/common';\nimport assert from '../../lib/assert';\n\nexport default class Matrix extends MathArray {\n // Defined by derived class\n get ELEMENTS() {\n assert(false);\n return 0;\n }\n\n get RANK() {\n assert(false);\n return 0;\n }\n\n // fromObject(object) {\n // const array = object.elements;\n // return this.fromRowMajor(array);\n // }\n\n // toObject(object) {\n // const array = object.elements;\n // this.toRowMajor(array);\n // return object;\n // }\n\n toString() {\n let string = '[';\n if (config.printRowMajor) {\n string += 'row-major:';\n for (let row = 0; row < this.RANK; ++row) {\n for (let col = 0; col < this.RANK; ++col) {\n string += ` ${this[col * this.RANK + row]}`;\n }\n }\n } else {\n string += 'column-major:';\n for (let i = 0; i < this.ELEMENTS; ++i) {\n string += ` ${this[i]}`;\n }\n }\n string += ']';\n return string;\n }\n\n getElementIndex(row, col) {\n return col * this.RANK + row;\n }\n\n // By default assumes row major indices\n getElement(row, col) {\n return this[col * this.RANK + row];\n }\n\n // By default assumes row major indices\n setElement(row, col, value) {\n this[col * this.RANK + row] = checkNumber(value);\n return this;\n }\n\n getColumn(columnIndex, result = new Array(this.RANK).fill(-0)) {\n const firstIndex = columnIndex * this.RANK;\n for (let i = 0; i < this.RANK; ++i) {\n result[i] = this[firstIndex + i];\n }\n return result;\n }\n\n setColumn(columnIndex, columnVector) {\n const firstIndex = columnIndex * this.RANK;\n for (let i = 0; i < this.RANK; ++i) {\n this[firstIndex + i] = columnVector[i];\n }\n return this;\n }\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport Matrix from './base/matrix';\nimport {checkVector, deprecated} from '../lib/validators';\n// eslint-disable-next-line camelcase\nimport {vec4_transformMat3} from '../lib/gl-matrix-extras';\n\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as mat3 from 'gl-matrix/mat3';\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as vec2 from 'gl-matrix/vec2';\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as vec3 from 'gl-matrix/vec3';\n\nconst IDENTITY = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1]);\nconst ZERO = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0]);\n\nconst INDICES = Object.freeze({\n COL0ROW0: 0,\n COL0ROW1: 1,\n COL0ROW2: 2,\n COL1ROW0: 3,\n COL1ROW1: 4,\n COL1ROW2: 5,\n COL2ROW0: 6,\n COL2ROW1: 7,\n COL2ROW2: 8\n});\n\nconst constants = {};\n\nexport default class Matrix3 extends Matrix {\n static get IDENTITY() {\n constants.IDENTITY = constants.IDENTITY || Object.freeze(new Matrix3(IDENTITY));\n return constants.IDENTITY;\n }\n\n static get ZERO() {\n constants.ZERO = constants.ZERO || Object.freeze(new Matrix3(ZERO));\n return constants.ZERO;\n }\n\n get ELEMENTS() {\n return 9;\n }\n\n get RANK() {\n return 3;\n }\n\n get INDICES() {\n return INDICES;\n }\n\n constructor(array) {\n // PERF NOTE: initialize elements as double precision numbers\n super(-0, -0, -0, -0, -0, -0, -0, -0, -0);\n if (arguments.length === 1 && Array.isArray(array)) {\n this.copy(array);\n } else {\n this.identity();\n }\n }\n\n copy(array) {\n this[0] = array[0];\n this[1] = array[1];\n this[2] = array[2];\n this[3] = array[3];\n this[4] = array[4];\n this[5] = array[5];\n this[6] = array[6];\n this[7] = array[7];\n this[8] = array[8];\n return this.check();\n }\n\n // accepts column major order, stores in column major order\n // eslint-disable-next-line max-params\n set(m00, m10, m20, m01, m11, m21, m02, m12, m22) {\n this[0] = m00;\n this[1] = m10;\n this[2] = m20;\n this[3] = m01;\n this[4] = m11;\n this[5] = m21;\n this[6] = m02;\n this[7] = m12;\n this[8] = m22;\n return this.check();\n }\n\n // accepts row major order, stores as column major\n // eslint-disable-next-line max-params\n setRowMajor(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n this[0] = m00;\n this[1] = m10;\n this[2] = m20;\n this[3] = m01;\n this[4] = m11;\n this[5] = m21;\n this[6] = m02;\n this[7] = m12;\n this[8] = m22;\n return this.check();\n }\n\n // Accessors\n\n determinant() {\n return mat3.determinant(this);\n }\n\n // Constructors\n\n identity() {\n return this.copy(IDENTITY);\n }\n\n // Calculates a 3x3 matrix from the given quaternion\n // q quat Quaternion to create matrix from\n fromQuaternion(q) {\n mat3.fromQuat(this, q);\n return this.check();\n }\n\n // Modifiers\n\n transpose() {\n mat3.transpose(this, this);\n return this.check();\n }\n\n invert() {\n mat3.invert(this, this);\n return this.check();\n }\n\n // Operations\n\n multiplyLeft(a) {\n mat3.multiply(this, a, this);\n return this.check();\n }\n\n multiplyRight(a) {\n mat3.multiply(this, this, a);\n return this.check();\n }\n\n rotate(radians) {\n mat3.rotate(this, this, radians);\n return this.check();\n }\n\n scale(factor) {\n if (Array.isArray(factor)) {\n mat3.scale(this, this, factor);\n } else {\n mat3.scale(this, this, [factor, factor, factor]);\n }\n\n return this.check();\n }\n\n translate(vec) {\n mat3.translate(this, this, vec);\n return this.check();\n }\n\n // Transforms\n\n transform(vector, result) {\n switch (vector.length) {\n case 2:\n result = vec2.transformMat3(result || [-0, -0], vector, this);\n break;\n case 3:\n result = vec3.transformMat3(result || [-0, -0, -0], vector, this);\n break;\n case 4:\n result = vec4_transformMat3(result || [-0, -0, -0, -0], vector, this);\n break;\n default:\n throw new Error('Illegal vector');\n }\n checkVector(result, vector.length);\n return result;\n }\n\n // DEPRECATED IN 3.0\n\n transformVector(vector, result) {\n deprecated('Matrix3.transformVector');\n return this.transform(vector, result);\n }\n\n transformVector2(vector, result) {\n deprecated('Matrix3.transformVector');\n return this.transform(vector, result);\n }\n\n transformVector3(vector, result) {\n deprecated('Matrix3.transformVector');\n return this.transform(vector, result);\n }\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport MathArray from './base/math-array';\nimport {checkNumber, checkVector} from '../lib/validators';\nimport assert from '../lib/assert';\n\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as quat from 'gl-matrix/quat';\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as vec4 from 'gl-matrix/vec4';\n\nconst IDENTITY_QUATERNION = [0, 0, 0, 1];\n\nexport default class Quaternion extends MathArray {\n constructor(x = 0, y = 0, z = 0, w = 1) {\n // PERF NOTE: initialize elements as double precision numbers\n super(-0, -0, -0, -0);\n // eslint-disable-next-line prefer-rest-params\n if (Array.isArray(x) && arguments.length === 1) {\n this.copy(x);\n } else {\n this.set(x, y, z, w);\n }\n }\n\n copy(array) {\n this[0] = array[0];\n this[1] = array[1];\n this[2] = array[2];\n this[3] = array[3];\n return this.check();\n }\n\n set(x, y, z, w) {\n this[0] = x;\n this[1] = y;\n this[2] = z;\n this[3] = w;\n return this.check();\n }\n\n // Creates a quaternion from the given 3x3 rotation matrix.\n // NOTE: The resultant quaternion is not normalized, so you should\n // be sure to renormalize the quaternion yourself where necessary.\n fromMatrix3(m) {\n quat.fromMat3(this, m);\n return this.check();\n }\n\n // Set a quat to the identity quaternion\n identity() {\n quat.identity(this);\n return this.check();\n }\n\n fromAxisRotation(axis, rad) {\n quat.setAxisAngle(this, axis, rad);\n return this.check();\n }\n\n // Set the components of a quat to the given values\n // set(i, j, k, l) {\n // quat.set(this, i, j, k, l);\n // return this.check();\n // }\n\n // Sets a quat from the given angle and rotation axis, then returns it.\n setAxisAngle(axis, rad) {\n return this.fromAxisRotation(axis, rad);\n }\n\n // Getters/setters\n /* eslint-disable no-multi-spaces, brace-style, no-return-assign */\n get ELEMENTS() {\n return 4;\n }\n\n get x() {\n return this[0];\n }\n\n set x(value) {\n this[0] = checkNumber(value);\n }\n\n get y() {\n return this[1];\n }\n\n set y(value) {\n this[1] = checkNumber(value);\n }\n\n get z() {\n return this[2];\n }\n\n set z(value) {\n this[2] = checkNumber(value);\n }\n\n get w() {\n return this[3];\n }\n\n set w(value) {\n this[3] = checkNumber(value);\n }\n\n /* eslint-enable no-multi-spaces, brace-style, no-return-assign */\n\n // Calculates the length of a quat\n len() {\n return quat.length(this);\n }\n\n // Calculates the squared length of a quat\n lengthSquared() {\n return quat.squaredLength(this);\n }\n\n // Calculates the dot product of two quat's\n // @return {Number}\n dot(a, b) {\n if (b !== undefined) {\n throw new Error('Quaternion.dot only takes one argument');\n }\n return quat.dot(this, a);\n }\n\n // Gets the rotation axis and angle for a given quaternion.\n // If a quaternion is created with setAxisAngle, this method will\n // return the same values as providied in the original parameter\n // list OR functionally equivalent values.\n // Example: The quaternion formed by axis [0, 0, 1] and angle -90\n // is the same as the quaternion formed by [0, 0, 1] and 270.\n // This method favors the latter.\n // @return {{[x,y,z], Number}}\n // getAxisAngle() {\n // const axis = [];\n // const angle = quat.getAxisAngle(axis, this);\n // return {axis, angle};\n // }\n\n // MODIFIERS\n\n // Sets a quaternion to represent the shortest rotation from one vector\n // to another. Both vectors are assumed to be unit length.\n rotationTo(vectorA, vectorB) {\n quat.rotationTo(this, vectorA, vectorB);\n return this.check();\n }\n\n // Sets the specified quaternion with values corresponding to the given axes.\n // Each axis is a vec3 and is expected to be unit length and perpendicular\n // to all other specified axes.\n // setAxes() {\n // Number\n // }\n\n // Performs a spherical linear interpolation with two control points\n // sqlerp() {\n // Number;\n // }\n\n // Adds two quat's\n add(a, b) {\n if (b !== undefined) {\n throw new Error('Quaternion.add only takes one argument');\n }\n quat.add(this, this, a);\n return this.check();\n }\n\n // Calculates the W component of a quat from the X, Y, and Z components.\n // Any existing W component will be ignored.\n calculateW() {\n quat.calculateW(this, this);\n return this.check();\n }\n\n // Calculates the conjugate of a quat If the quaternion is normalized,\n // this function is faster than quat.inverse and produces the same result.\n conjugate() {\n quat.conjugate(this, this);\n return this.check();\n }\n\n // Calculates the inverse of a quat\n invert() {\n quat.invert(this, this);\n return this.check();\n }\n\n // Performs a linear interpolation between two quat's\n lerp(a, b, t) {\n quat.lerp(this, a, b, t);\n return this.check();\n }\n\n // Multiplies two quat's\n multiplyRight(a, b) {\n assert(!b); // Quaternion.multiply only takes one argument\n quat.multiply(this, this, a);\n return this.check();\n }\n\n multiplyLeft(a, b) {\n assert(!b); // Quaternion.multiply only takes one argument\n quat.multiply(this, a, this);\n return this.check();\n }\n\n // Normalize a quat\n normalize() {\n // Handle 0 case\n const length = this.len();\n const l = length > 0 ? 1 / length : 0;\n this[0] = this[0] * l;\n this[1] = this[1] * l;\n this[2] = this[2] * l;\n this[3] = this[3] * l;\n // Set to [0, 0, 0, 1] if length is 0\n if (length === 0) {\n this[3] = 1;\n }\n return this.check();\n }\n\n // Rotates a quaternion by the given angle about the X axis\n rotateX(rad) {\n quat.rotateX(this, this, rad);\n return this.check();\n }\n\n // Rotates a quaternion by the given angle about the Y axis\n rotateY(rad) {\n quat.rotateY(this, this, rad);\n return this.check();\n }\n\n // Rotates a quaternion by the given angle about the Z axis\n rotateZ(rad) {\n quat.rotateZ(this, this, rad);\n return this.check();\n }\n\n // Scales a quat by a scalar number\n scale(b) {\n quat.scale(this, this, b);\n return this.check();\n }\n\n // Performs a spherical linear interpolation between two quat\n slerp(start, target, ratio) {\n // eslint-disable-next-line prefer-rest-params\n switch (arguments.length) {\n case 1: // Deprecated signature ({start, target, ratio})\n // eslint-disable-next-line prefer-rest-params\n ({start = IDENTITY_QUATERNION, target, ratio} = arguments[0]);\n break;\n case 2: // THREE.js compatibility signature (target, ration)\n // eslint-disable-next-line prefer-rest-params\n [target, ratio] = arguments;\n start = this; // eslint-disable-line\n break;\n default: // Default signature: (start, target, ratio)\n }\n quat.slerp(this, start, target, ratio);\n return this.check();\n }\n\n transformVector4(vector, result = vector) {\n vec4.transformQuat(result, vector, this);\n return checkVector(result, 4);\n }\n\n // THREE.js Math API compatibility\n lengthSq() {\n return this.lengthSquared();\n }\n\n setFromAxisAngle(axis, rad) {\n return this.setAxisAngle(axis, rad);\n }\n\n premultiply(a, b) {\n return this.multiplyLeft(a, b);\n }\n\n multiply(a, b) {\n return this.multiplyRight(a, b);\n }\n}\n","// This file is derived from the Cesium math library under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {Vector3, Matrix3, Quaternion} from '@math.gl/core';\nimport BoundingSphere from './bounding-sphere';\nimport {INTERSECTION} from '../../constants';\n\nconst scratchVector3 = new Vector3();\nconst scratchOffset = new Vector3();\nconst scratchVectorU = new Vector3();\nconst scratchVectorV = new Vector3();\nconst scratchVectorW = new Vector3();\nconst scratchCorner = new Vector3();\nconst scratchToCenter = new Vector3();\n\nconst MATRIX3 = {\n COLUMN0ROW0: 0,\n COLUMN0ROW1: 1,\n COLUMN0ROW2: 2,\n COLUMN1ROW0: 3,\n COLUMN1ROW1: 4,\n COLUMN1ROW2: 5,\n COLUMN2ROW0: 6,\n COLUMN2ROW1: 7,\n COLUMN2ROW2: 8\n};\n\nexport default class OrientedBoundingBox {\n constructor(center = [0, 0, 0], halfAxes = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {\n this.center = new Vector3().from(center);\n this.halfAxes = new Matrix3(halfAxes);\n }\n\n get halfSize() {\n const xAxis = this.halfAxes.getColumn(0);\n const yAxis = this.halfAxes.getColumn(1);\n const zAxis = this.halfAxes.getColumn(2);\n return [new Vector3(xAxis).len(), new Vector3(yAxis).len(), new Vector3(zAxis).len()];\n }\n\n get quaternion() {\n const xAxis = this.halfAxes.getColumn(0);\n const yAxis = this.halfAxes.getColumn(1);\n const zAxis = this.halfAxes.getColumn(2);\n const normXAxis = new Vector3(xAxis).normalize();\n const normYAxis = new Vector3(yAxis).normalize();\n const normZAxis = new Vector3(zAxis).normalize();\n return new Quaternion().fromMatrix3(new Matrix3([...normXAxis, ...normYAxis, ...normZAxis]));\n }\n\n fromCenterHalfSizeQuaternion(center, halfSize, quaternion) {\n const quaternionObject = new Quaternion(quaternion);\n const directionsMatrix = new Matrix3().fromQuaternion(quaternionObject);\n directionsMatrix[0] = directionsMatrix[0] * halfSize[0];\n directionsMatrix[1] = directionsMatrix[1] * halfSize[0];\n directionsMatrix[2] = directionsMatrix[2] * halfSize[0];\n directionsMatrix[3] = directionsMatrix[3] * halfSize[1];\n directionsMatrix[4] = directionsMatrix[4] * halfSize[1];\n directionsMatrix[5] = directionsMatrix[5] * halfSize[1];\n directionsMatrix[6] = directionsMatrix[6] * halfSize[2];\n directionsMatrix[7] = directionsMatrix[7] * halfSize[2];\n directionsMatrix[8] = directionsMatrix[8] * halfSize[2];\n this.center = new Vector3().from(center);\n this.halfAxes = directionsMatrix;\n return this;\n }\n\n clone() {\n return new OrientedBoundingBox(this.center, this.halfAxes);\n }\n\n equals(right) {\n return (\n this === right ||\n (Boolean(right) && this.center.equals(right.center) && this.halfAxes.equals(right.halfAxes))\n );\n }\n\n getBoundingSphere(result = new BoundingSphere()) {\n const halfAxes = this.halfAxes;\n const u = halfAxes.getColumn(0, scratchVectorU);\n const v = halfAxes.getColumn(1, scratchVectorV);\n const w = halfAxes.getColumn(2, scratchVectorW);\n\n // Calculate \"corner\" vector\n const cornerVector = scratchVector3.copy(u).add(v).add(w);\n\n result.center.copy(this.center);\n result.radius = cornerVector.magnitude();\n\n return result;\n }\n\n intersectPlane(plane) {\n const center = this.center;\n const normal = plane.normal;\n const halfAxes = this.halfAxes;\n\n const normalX = normal.x;\n const normalY = normal.y;\n const normalZ = normal.z;\n\n // Plane is used as if it is its normal; the first three components are assumed to be normalized\n const radEffective =\n Math.abs(\n normalX * halfAxes[MATRIX3.COLUMN0ROW0] +\n normalY * halfAxes[MATRIX3.COLUMN0ROW1] +\n normalZ * halfAxes[MATRIX3.COLUMN0ROW2]\n ) +\n Math.abs(\n normalX * halfAxes[MATRIX3.COLUMN1ROW0] +\n normalY * halfAxes[MATRIX3.COLUMN1ROW1] +\n normalZ * halfAxes[MATRIX3.COLUMN1ROW2]\n ) +\n Math.abs(\n normalX * halfAxes[MATRIX3.COLUMN2ROW0] +\n normalY * halfAxes[MATRIX3.COLUMN2ROW1] +\n normalZ * halfAxes[MATRIX3.COLUMN2ROW2]\n );\n const distanceToPlane = normal.dot(center) + plane.distance;\n\n if (distanceToPlane <= -radEffective) {\n // The entire box is on the negative side of the plane normal\n return INTERSECTION.OUTSIDE;\n } else if (distanceToPlane >= radEffective) {\n // The entire box is on the positive side of the plane normal\n return INTERSECTION.INSIDE;\n }\n return INTERSECTION.INTERSECTING;\n }\n\n distanceTo(point) {\n return Math.sqrt(this.distanceSquaredTo(point));\n }\n\n distanceSquaredTo(point) {\n // Computes the estimated distance squared from the\n // closest point on a bounding box to a point.\n // See Geometric Tools for Computer Graphics 10.4.2\n const offset = scratchOffset.from(point).subtract(this.center);\n\n const halfAxes = this.halfAxes;\n const u = halfAxes.getColumn(0, scratchVectorU);\n const v = halfAxes.getColumn(1, scratchVectorV);\n const w = halfAxes.getColumn(2, scratchVectorW);\n\n const uHalf = u.magnitude();\n const vHalf = v.magnitude();\n const wHalf = w.magnitude();\n\n u.normalize();\n v.normalize();\n w.normalize();\n\n let distanceSquared = 0.0;\n let d;\n\n d = Math.abs(offset.dot(u)) - uHalf;\n if (d > 0) {\n distanceSquared += d * d;\n }\n\n d = Math.abs(offset.dot(v)) - vHalf;\n if (d > 0) {\n distanceSquared += d * d;\n }\n\n d = Math.abs(offset.dot(w)) - wHalf;\n if (d > 0) {\n distanceSquared += d * d;\n }\n\n return distanceSquared;\n }\n\n // eslint-disable-next-line max-statements\n computePlaneDistances(position, direction, result = [-0, -0]) {\n let minDist = Number.POSITIVE_INFINITY;\n let maxDist = Number.NEGATIVE_INFINITY;\n\n const center = this.center;\n const halfAxes = this.halfAxes;\n\n const u = halfAxes.getColumn(0, scratchVectorU);\n const v = halfAxes.getColumn(1, scratchVectorV);\n const w = halfAxes.getColumn(2, scratchVectorW);\n\n // project first corner\n const corner = scratchCorner.copy(u).add(v).add(w).add(center);\n\n const toCenter = scratchToCenter.copy(corner).subtract(position);\n let mag = direction.dot(toCenter);\n\n minDist = Math.min(mag, minDist);\n maxDist = Math.max(mag, maxDist);\n\n // project second corner\n corner.copy(center).add(u).add(v).subtract(w);\n\n toCenter.copy(corner).subtract(position);\n mag = direction.dot(toCenter);\n\n minDist = Math.min(mag, minDist);\n maxDist = Math.max(mag, maxDist);\n\n // project third corner\n corner.copy(center).add(u).subtract(v).add(w);\n\n toCenter.copy(corner).subtract(position);\n mag = direction.dot(toCenter);\n\n minDist = Math.min(mag, minDist);\n maxDist = Math.max(mag, maxDist);\n\n // project fourth corner\n corner.copy(center).add(u).subtract(v).subtract(w);\n\n toCenter.copy(corner).subtract(position);\n mag = direction.dot(toCenter);\n\n minDist = Math.min(mag, minDist);\n maxDist = Math.max(mag, maxDist);\n\n // project fifth corner\n center.copy(corner).subtract(u).add(v).add(w);\n\n toCenter.copy(corner).subtract(position);\n mag = direction.dot(toCenter);\n\n minDist = Math.min(mag, minDist);\n maxDist = Math.max(mag, maxDist);\n\n // project sixth corner\n center.copy(corner).subtract(u).add(v).subtract(w);\n\n toCenter.copy(corner).subtract(position);\n mag = direction.dot(toCenter);\n\n minDist = Math.min(mag, minDist);\n maxDist = Math.max(mag, maxDist);\n\n // project seventh corner\n center.copy(corner).subtract(u).subtract(v).add(w);\n\n toCenter.copy(corner).subtract(position);\n mag = direction.dot(toCenter);\n\n minDist = Math.min(mag, minDist);\n maxDist = Math.max(mag, maxDist);\n\n // project eighth corner\n center.copy(corner).subtract(u).subtract(v).subtract(w);\n\n toCenter.copy(corner).subtract(position);\n mag = direction.dot(toCenter);\n\n minDist = Math.min(mag, minDist);\n maxDist = Math.max(mag, maxDist);\n\n result[0] = minDist;\n result[1] = maxDist;\n return result;\n }\n\n transform(transformation) {\n this.center.transformAsPoint(transformation);\n\n const xAxis = this.halfAxes.getColumn(0, scratchVectorU);\n xAxis.transformAsPoint(transformation);\n\n const yAxis = this.halfAxes.getColumn(1, scratchVectorV);\n yAxis.transformAsPoint(transformation);\n\n const zAxis = this.halfAxes.getColumn(2, scratchVectorW);\n zAxis.transformAsPoint(transformation);\n\n this.halfAxes = new Matrix3([...xAxis, ...yAxis, ...zAxis]);\n return this;\n }\n\n getTransform() {\n // const modelMatrix = Matrix4.fromRotationTranslation(this.boundingVolume.halfAxes, this.boundingVolume.center);\n // return modelMatrix;\n throw new Error('not implemented');\n }\n}\n","// This file is derived from the Cesium math library under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\n/* eslint-disable */\nimport {Vector3, equals, assert} from '@math.gl/core';\n\nconst scratchPosition = new Vector3();\nconst scratchNormal = new Vector3();\n\n// A plane in Hessian Normal Form\nexport default class Plane {\n constructor(normal = [0, 0, 1], distance = 0) {\n this.normal = new Vector3();\n this.distance = -0;\n this.fromNormalDistance(normal, distance);\n }\n\n fromNormalDistance(normal, distance) {\n assert(Number.isFinite(distance));\n this.normal.from(normal).normalize();\n this.distance = distance;\n return this;\n }\n\n // Creates a plane from a normal and a point on the plane.\n fromPointNormal(point, normal) {\n point = scratchPosition.from(point);\n this.normal.from(normal).normalize();\n const distance = -this.normal.dot(point);\n this.distance = distance;\n\n return this;\n }\n\n // Creates a plane from the general equation\n fromCoefficients(a, b, c, d) {\n this.normal.set(a, b, c);\n assert(equals(this.normal.len(), 1));\n this.distance = d;\n return this;\n }\n\n // Duplicates a Plane instance.\n clone(plane) {\n return new Plane(this.normal, this.distance);\n }\n\n // Compares the provided Planes by normal and distance\n equals(right) {\n return equals(this.distance, right.distance) && equals(this.normal, right.normal);\n }\n\n // Computes the signed shortest distance of a point to a plane.\n // The sign of the distance determines which side of the plane the point is on.\n getPointDistance(point) {\n return this.normal.dot(point) + this.distance;\n }\n\n // Transforms the plane by the given transformation matrix.\n transform(matrix4) {\n const normal = scratchNormal.copy(this.normal).transformAsVector(matrix4).normalize();\n const point = this.normal.scale(-this.distance).transform(matrix4);\n return this.fromPointNormal(point, normal);\n }\n\n // Projects a point onto the plane.\n projectPointOntoPlane(point, result = [0, 0, 0]) {\n point = scratchPosition.from(point);\n // projectedPoint = point - (normal.point + scale) * normal\n const pointDistance = this.getPointDistance(point);\n const scaledNormal = scratchNormal.copy(this.normal).scale(pointDistance);\n\n return point.subtract(scaledNormal).to(result);\n }\n}\n","// This file is derived from the Cesium math library under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\n/* eslint-disable */\nimport {Vector3, Vector4, assert} from '@math.gl/core';\nimport {INTERSECTION} from '../constants';\nimport Plane from './plane';\n\n// X, Y, Z Unit vectors\nconst faces = [new Vector3([1, 0, 0]), new Vector3([0, 1, 0]), new Vector3([0, 0, 1])];\n\nconst scratchPlaneCenter = new Vector3();\nconst scratchPlaneNormal = new Vector3();\nconst scratchPlane = new Plane(new Vector3(1.0, 0.0, 0.0), 0.0);\n\n// A culling volume defined by planes.\nexport default class CullingVolume {\n // For plane masks (as used in {@link CullingVolume#computeVisibilityWithPlaneMask}), this special value\n // represents the case where the object bounding volume is entirely outside the culling volume.\n static get MASK_OUTSIDE() {\n return 0xffffffff;\n }\n\n // For plane masks (as used in {@link CullingVolume.prototype.computeVisibilityWithPlaneMask}), this value\n // represents the case where the object bounding volume is entirely inside the culling volume.\n static get MASK_INSIDE() {\n return 0x00000000;\n }\n\n // For plane masks (as used in {@link CullingVolume.prototype.computeVisibilityWithPlaneMask}), this value\n // represents the case where the object bounding volume (may) intersect all planes of the culling volume.\n static get MASK_INDETERMINATE() {\n return 0x7fffffff;\n }\n\n constructor(planes = []) {\n // {Cartesian4[]} [planes] An array of clipping planes.\n this.planes = planes;\n assert(this.planes.every((plane) => plane instanceof Plane));\n }\n\n // Constructs a culling volume from a bounding sphere. Creates six planes that create a box containing the sphere.\n // The planes are aligned to the x, y, and z axes in world coordinates.\n fromBoundingSphere(boundingSphere) {\n this.planes.length = 2 * faces.length;\n\n const center = boundingSphere.center;\n const radius = boundingSphere.radius;\n\n let planeIndex = 0;\n\n for (const faceNormal of faces) {\n let plane0 = this.planes[planeIndex];\n let plane1 = this.planes[planeIndex + 1];\n\n if (!plane0) {\n plane0 = this.planes[planeIndex] = new Plane();\n }\n if (!plane1) {\n plane1 = this.planes[planeIndex + 1] = new Plane();\n }\n\n const plane0Center = scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);\n const plane0Distance = -faceNormal.dot(plane0Center);\n\n plane0.fromPointNormal(plane0Center, faceNormal);\n\n const plane1Center = scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);\n\n const negatedFaceNormal = scratchPlaneNormal.copy(faceNormal).negate();\n\n const plane1Distance = -negatedFaceNormal.dot(plane1Center);\n\n plane1.fromPointNormal(plane1Center, negatedFaceNormal);\n\n planeIndex += 2;\n }\n\n return this;\n }\n\n // Determines whether a bounding volume intersects the culling volume.\n computeVisibility(boundingVolume) {\n assert(boundingVolume);\n // const planes = this.planes;\n let intersect = INTERSECTION.INSIDE;\n for (const plane of this.planes) {\n const result = boundingVolume.intersectPlane(plane);\n switch (result) {\n case INTERSECTION.OUTSIDE:\n // We are done\n return INTERSECTION.OUTSIDE;\n\n case INTERSECTION.INTERSECTING:\n // If no other intersection is outside, return INTERSECTING\n intersect = INTERSECTION.INTERSECTING;\n break;\n\n default:\n }\n }\n\n return intersect;\n }\n\n // Determines whether a bounding volume intersects the culling volume.\n /*\n * @param {Number} parentPlaneMask A bit mask from the boundingVolume's parent's check against the same culling\n * volume, such that if (planeMask & (1 << planeIndex) === 0), for k < 31, then\n * the parent (and therefore this) volume is completely inside plane[planeIndex]\n * and that plane check can be skipped.\n */\n computeVisibilityWithPlaneMask(boundingVolume, parentPlaneMask) {\n assert(boundingVolume, 'boundingVolume is required.');\n assert(Number.isFinite(parentPlaneMask), 'parentPlaneMask is required.');\n\n if (\n parentPlaneMask === CullingVolume.MASK_OUTSIDE ||\n parentPlaneMask === CullingVolume.MASK_INSIDE\n ) {\n // parent is completely outside or completely inside, so this child is as well.\n return parentPlaneMask;\n }\n\n // Start with MASK_INSIDE (all zeros) so that after the loop, the return value can be compared with MASK_INSIDE.\n // (Because if there are fewer than 31 planes, the upper bits wont be changed.)\n let mask = CullingVolume.MASK_INSIDE;\n\n const planes = this.planes;\n for (let k = 0; k < this.planes.length; ++k) {\n // For k greater than 31 (since 31 is the maximum number of INSIDE/INTERSECTING bits we can store), skip the optimization.\n const flag = k < 31 ? 1 << k : 0;\n if (k < 31 && (parentPlaneMask & flag) === 0) {\n // boundingVolume is known to be INSIDE this plane.\n continue;\n }\n\n const plane = planes[k];\n const result = boundingVolume.intersectPlane(plane);\n if (result === INTERSECTION.OUTSIDE) {\n return CullingVolume.MASK_OUTSIDE;\n } else if (result === INTERSECTION.INTERSECTING) {\n mask |= flag;\n }\n }\n\n return mask;\n }\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {checkVector, deprecated} from '../lib/validators';\nimport Matrix from './base/matrix';\n// eslint-disable-next-line camelcase\nimport {vec2_transformMat4AsVector, vec3_transformMat4AsVector} from '../lib/gl-matrix-extras';\n\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as mat4 from 'gl-matrix/mat4';\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as vec2 from 'gl-matrix/vec2';\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as vec3 from 'gl-matrix/vec3';\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as vec4 from 'gl-matrix/vec4';\n\nconst IDENTITY = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);\nconst ZERO = Object.freeze([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);\n\nconst INDICES = Object.freeze({\n COL0ROW0: 0,\n COL0ROW1: 1,\n COL0ROW2: 2,\n COL0ROW3: 3,\n COL1ROW0: 4,\n COL1ROW1: 5,\n COL1ROW2: 6,\n COL1ROW3: 7,\n COL2ROW0: 8,\n COL2ROW1: 9,\n COL2ROW2: 10,\n COL2ROW3: 11,\n COL3ROW0: 12,\n COL3ROW1: 13,\n COL3ROW2: 14,\n COL3ROW3: 15\n});\n\nconst constants = {};\n\nexport default class Matrix4 extends Matrix {\n static get IDENTITY() {\n constants.IDENTITY = constants.IDENTITY || Object.freeze(new Matrix4(IDENTITY));\n return constants.IDENTITY;\n }\n\n static get ZERO() {\n constants.ZERO = constants.ZERO || Object.freeze(new Matrix4(ZERO));\n return constants.ZERO;\n }\n\n get INDICES() {\n return INDICES;\n }\n\n get ELEMENTS() {\n return 16;\n }\n\n get RANK() {\n return 4;\n }\n\n constructor(array) {\n // PERF NOTE: initialize elements as double precision numbers\n super(-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0);\n if (arguments.length === 1 && Array.isArray(array)) {\n this.copy(array);\n } else {\n this.identity();\n }\n }\n\n copy(array) {\n this[0] = array[0];\n this[1] = array[1];\n this[2] = array[2];\n this[3] = array[3];\n this[4] = array[4];\n this[5] = array[5];\n this[6] = array[6];\n this[7] = array[7];\n this[8] = array[8];\n this[9] = array[9];\n this[10] = array[10];\n this[11] = array[11];\n this[12] = array[12];\n this[13] = array[13];\n this[14] = array[14];\n this[15] = array[15];\n return this.check();\n }\n\n // eslint-disable-next-line max-params\n set(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33) {\n this[0] = m00;\n this[1] = m10;\n this[2] = m20;\n this[3] = m30;\n this[4] = m01;\n this[5] = m11;\n this[6] = m21;\n this[7] = m31;\n this[8] = m02;\n this[9] = m12;\n this[10] = m22;\n this[11] = m32;\n this[12] = m03;\n this[13] = m13;\n this[14] = m23;\n this[15] = m33;\n return this.check();\n }\n\n // accepts row major order, stores as column major\n // eslint-disable-next-line max-params\n setRowMajor(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n this[0] = m00;\n this[1] = m10;\n this[2] = m20;\n this[3] = m30;\n this[4] = m01;\n this[5] = m11;\n this[6] = m21;\n this[7] = m31;\n this[8] = m02;\n this[9] = m12;\n this[10] = m22;\n this[11] = m32;\n this[12] = m03;\n this[13] = m13;\n this[14] = m23;\n this[15] = m33;\n return this.check();\n }\n\n toRowMajor(result) {\n result[0] = this[0];\n result[1] = this[4];\n result[2] = this[8];\n result[3] = this[12];\n result[4] = this[1];\n result[5] = this[5];\n result[6] = this[9];\n result[7] = this[13];\n result[8] = this[2];\n result[9] = this[6];\n result[10] = this[10];\n result[11] = this[14];\n result[12] = this[3];\n result[13] = this[7];\n result[14] = this[11];\n result[15] = this[15];\n return result;\n }\n\n // Constructors\n\n identity() {\n return this.copy(IDENTITY);\n }\n\n // Calculates a 4x4 matrix from the given quaternion\n // q quat Quaternion to create matrix from\n fromQuaternion(q) {\n mat4.fromQuat(this, q);\n return this.check();\n }\n\n // Generates a frustum matrix with the given bounds\n // left Number Left bound of the frustum\n // right Number Right bound of the frustum\n // bottom Number Bottom bound of the frustum\n // top Number Top bound of the frustum\n // near Number Near bound of the frustum\n // far Number Far bound of the frustum\n frustum({left, right, bottom, top, near, far}) {\n if (far === Infinity) {\n Matrix4._computeInfinitePerspectiveOffCenter(this, left, right, bottom, top, near);\n } else {\n mat4.frustum(this, left, right, bottom, top, near, far);\n }\n return this.check();\n }\n\n // eslint-disable-next-line max-params\n static _computeInfinitePerspectiveOffCenter(result, left, right, bottom, top, near) {\n const column0Row0 = (2.0 * near) / (right - left);\n const column1Row1 = (2.0 * near) / (top - bottom);\n const column2Row0 = (right + left) / (right - left);\n const column2Row1 = (top + bottom) / (top - bottom);\n const column2Row2 = -1.0;\n const column2Row3 = -1.0;\n const column3Row2 = -2.0 * near;\n\n result[0] = column0Row0;\n result[1] = 0.0;\n result[2] = 0.0;\n result[3] = 0.0;\n result[4] = 0.0;\n result[5] = column1Row1;\n result[6] = 0.0;\n result[7] = 0.0;\n result[8] = column2Row0;\n result[9] = column2Row1;\n result[10] = column2Row2;\n result[11] = column2Row3;\n result[12] = 0.0;\n result[13] = 0.0;\n result[14] = column3Row2;\n result[15] = 0.0;\n return result;\n }\n\n // Generates a look-at matrix with the given eye position, focal point,\n // and up axis\n // eye vec3 Position of the viewer\n // center vec3 Point the viewer is looking at\n // up vec3 vec3 pointing up\n lookAt(eye, center, up) {\n // Signature: lookAt({eye, center = [0, 0, 0], up = [0, 1, 0]}))\n if (arguments.length === 1) {\n ({eye, center, up} = eye);\n }\n\n center = center || [0, 0, 0];\n up = up || [0, 1, 0];\n\n mat4.lookAt(this, eye, center, up);\n return this.check();\n }\n\n // Generates a orthogonal projection matrix with the given bounds\n // from \"traditional\" view space parameters\n // left number Left bound of the frustum\n // right number Right bound of the frustum\n // bottom number Bottom bound of the frustum\n // top number Top bound of the frustum\n // near number Near bound of the frustum\n // far number Far bound of the frustum\n ortho({left, right, bottom, top, near = 0.1, far = 500}) {\n mat4.ortho(this, left, right, bottom, top, near, far);\n return this.check();\n }\n\n // Generates an orthogonal projection matrix with the same parameters\n // as a perspective matrix (plus focalDistance)\n // fovy number Vertical field of view in radians\n // aspect number Aspect ratio. typically viewport width/height\n // focalDistance distance in the view frustum used for extent calculations\n // near number Near bound of the frustum\n // far number Far bound of the frustum\n orthographic({\n fovy = (45 * Math.PI) / 180,\n aspect = 1,\n focalDistance = 1,\n near = 0.1,\n far = 500\n }) {\n if (fovy > Math.PI * 2) {\n throw Error('radians');\n }\n const halfY = fovy / 2;\n const top = focalDistance * Math.tan(halfY); // focus_plane is the distance from the camera\n const right = top * aspect;\n\n return new Matrix4().ortho({\n left: -right,\n right,\n bottom: -top,\n top,\n near,\n far\n });\n }\n\n // Generates a perspective projection matrix with the given bounds\n // fovy number Vertical field of view in radians\n // aspect number Aspect ratio. typically viewport width/height\n // near number Near bound of the frustum\n // far number Far bound of the frustum\n perspective({\n fovy = undefined,\n fov = (45 * Math.PI) / 180, // DEPRECATED\n aspect = 1,\n near = 0.1,\n far = 500\n } = {}) {\n fovy = fovy || fov;\n if (fovy > Math.PI * 2) {\n throw Error('radians');\n }\n mat4.perspective(this, fovy, aspect, near, far);\n return this.check();\n }\n\n // Accessors\n\n determinant() {\n return mat4.determinant(this);\n }\n\n // Extracts the non-uniform scale assuming the matrix is an affine transformation.\n // The scales are the \"lengths\" of the column vectors in the upper-left 3x3 matrix.\n getScale(result = [-0, -0, -0]) {\n // explicit is faster than hypot...\n result[0] = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);\n result[1] = Math.sqrt(this[4] * this[4] + this[5] * this[5] + this[6] * this[6]);\n result[2] = Math.sqrt(this[8] * this[8] + this[9] * this[9] + this[10] * this[10]);\n // result[0] = Math.hypot(this[0], this[1], this[2]);\n // result[1] = Math.hypot(this[4], this[5], this[6]);\n // result[2] = Math.hypot(this[8], this[9], this[10]);\n return result;\n }\n\n // Gets the translation portion, assuming the matrix is a affine transformation matrix.\n getTranslation(result = [-0, -0, -0]) {\n result[0] = this[12];\n result[1] = this[13];\n result[2] = this[14];\n return result;\n }\n\n // Gets upper left 3x3 pure rotation matrix (non-scaling), assume affine transformation matrix\n getRotation(\n result = [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0],\n scaleResult = null\n ) {\n const scale = this.getScale(scaleResult || [-0, -0, -0]);\n\n const inverseScale0 = 1 / scale[0];\n const inverseScale1 = 1 / scale[1];\n const inverseScale2 = 1 / scale[2];\n\n result[0] = this[0] * inverseScale0;\n result[1] = this[1] * inverseScale1;\n result[2] = this[2] * inverseScale2;\n result[3] = 0;\n result[4] = this[4] * inverseScale0;\n result[5] = this[5] * inverseScale1;\n result[6] = this[6] * inverseScale2;\n result[7] = 0;\n result[8] = this[8] * inverseScale0;\n result[9] = this[9] * inverseScale1;\n result[10] = this[10] * inverseScale2;\n result[11] = 0;\n result[12] = 0;\n result[13] = 0;\n result[14] = 0;\n result[15] = 1;\n return result;\n }\n\n getRotationMatrix3(result = [-0, -0, -0, -0, -0, -0, -0, -0, -0], scaleResult = null) {\n const scale = this.getScale(scaleResult || [-0, -0, -0]);\n\n const inverseScale0 = 1 / scale[0];\n const inverseScale1 = 1 / scale[1];\n const inverseScale2 = 1 / scale[2];\n\n result[0] = this[0] * inverseScale0;\n result[1] = this[1] * inverseScale1;\n result[2] = this[2] * inverseScale2;\n result[3] = this[4] * inverseScale0;\n result[4] = this[5] * inverseScale1;\n result[5] = this[6] * inverseScale2;\n result[6] = this[8] * inverseScale0;\n result[7] = this[9] * inverseScale1;\n result[8] = this[10] * inverseScale2;\n return result;\n }\n\n // Modifiers\n\n transpose() {\n mat4.transpose(this, this);\n return this.check();\n }\n\n invert() {\n mat4.invert(this, this);\n return this.check();\n }\n\n // Operations\n\n multiplyLeft(a) {\n mat4.multiply(this, a, this);\n return this.check();\n }\n\n multiplyRight(a) {\n mat4.multiply(this, this, a);\n return this.check();\n }\n\n // Rotates a matrix by the given angle around the X axis\n rotateX(radians) {\n mat4.rotateX(this, this, radians);\n // mat4.rotate(this, this, radians, [1, 0, 0]);\n return this.check();\n }\n\n // Rotates a matrix by the given angle around the Y axis.\n rotateY(radians) {\n mat4.rotateY(this, this, radians);\n // mat4.rotate(this, this, radians, [0, 1, 0]);\n return this.check();\n }\n\n // Rotates a matrix by the given angle around the Z axis.\n rotateZ(radians) {\n mat4.rotateZ(this, this, radians);\n // mat4.rotate(this, this, radians, [0, 0, 1]);\n return this.check();\n }\n\n rotateXYZ([rx, ry, rz]) {\n return this.rotateX(rx).rotateY(ry).rotateZ(rz);\n }\n\n rotateAxis(radians, axis) {\n mat4.rotate(this, this, radians, axis);\n return this.check();\n }\n\n scale(factor) {\n if (Array.isArray(factor)) {\n mat4.scale(this, this, factor);\n } else {\n mat4.scale(this, this, [factor, factor, factor]);\n }\n\n return this.check();\n }\n\n translate(vec) {\n mat4.translate(this, this, vec);\n return this.check();\n }\n\n // Transforms\n\n // Transforms any 2, 3 or 4 element vector. 2 and 3 elements are treated as points\n transform(vector, result) {\n if (vector.length === 4) {\n result = vec4.transformMat4(result || [-0, -0, -0, -0], vector, this);\n checkVector(result, 4);\n return result;\n }\n return this.transformAsPoint(vector, result);\n }\n\n // Transforms any 2 or 3 element array as point (w implicitly 1)\n transformAsPoint(vector, result) {\n const {length} = vector;\n switch (length) {\n case 2:\n result = vec2.transformMat4(result || [-0, -0], vector, this);\n break;\n case 3:\n result = vec3.transformMat4(result || [-0, -0, -0], vector, this);\n break;\n default:\n throw new Error('Illegal vector');\n }\n checkVector(result, vector.length);\n return result;\n }\n\n // Transforms any 2 or 3 element array as vector (w implicitly 0)\n transformAsVector(vector, result) {\n switch (vector.length) {\n case 2:\n result = vec2_transformMat4AsVector(result || [-0, -0], vector, this);\n break;\n case 3:\n result = vec3_transformMat4AsVector(result || [-0, -0, -0], vector, this);\n break;\n default:\n throw new Error('Illegal vector');\n }\n checkVector(result, vector.length);\n return result;\n }\n\n // three.js math API compatibility\n makeRotationX(radians) {\n return this.identity().rotateX(radians);\n }\n\n makeTranslation(x, y, z) {\n return this.identity().translate([x, y, z]);\n }\n\n // DEPRECATED in 3.0\n\n transformPoint(vector, result) {\n deprecated('Matrix4.transformPoint', '3.0');\n return this.transformAsPoint(vector, result);\n }\n\n transformVector(vector, result) {\n deprecated('Matrix4.transformVector', '3.0');\n return this.transformAsPoint(vector, result);\n }\n\n transformDirection(vector, result) {\n deprecated('Matrix4.transformDirection', '3.0');\n return this.transformAsVector(vector, result);\n }\n}\n","// This file is derived from the Cesium math library under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\n// Note: This class is still an experimental export, mainly used by other test cases\n// - It has not been fully adapted to math.gl conventions\n// - Documentation has not been ported\n\n// @ts-nocheck\n\nimport {Vector3, Matrix4, assert} from '@math.gl/core';\nimport CullingVolume from './culling-volume';\nimport Plane from './plane';\n\nconst scratchPlaneUpVector = new Vector3();\nconst scratchPlaneRightVector = new Vector3();\nconst scratchPlaneNearCenter = new Vector3();\nconst scratchPlaneFarCenter = new Vector3();\nconst scratchPlaneNormal = new Vector3();\n\nexport default class PerspectiveOffCenterFrustum {\n /**\n * The viewing frustum is defined by 6 planes.\n * Each plane is represented by a {@link Vector4} object, where the x, y, and z components\n * define the unit vector normal to the plane, and the w component is the distance of the\n * plane from the origin/camera position.\n *\n * @alias PerspectiveOffCenterFrustum\n * @constructor\n *\n * @param {Object} [options] An object with the following properties:\n * @param {Number} [options.left] The left clipping plane distance.\n * @param {Number} [options.right] The right clipping plane distance.\n * @param {Number} [options.top] The top clipping plane distance.\n * @param {Number} [options.bottom] The bottom clipping plane distance.\n * @param {Number} [options.near=1.0] The near clipping plane distance.\n * @param {Number} [options.far=500000000.0] The far clipping plane distance.\n *\n * @example\n * const frustum = new PerspectiveOffCenterFrustum({\n * left : -1.0,\n * right : 1.0,\n * top : 1.0,\n * bottom : -1.0,\n * near : 1.0,\n * far : 100.0\n * });\n *\n * @see PerspectiveFrustum\n */\n constructor(options = {}) {\n options = {near: 1.0, far: 500000000.0, ...options};\n\n /**\n * Defines the left clipping plane.\n * @type {Number}\n * @default undefined\n */\n this.left = options.left;\n this._left = undefined;\n\n /**\n * Defines the right clipping plane.\n * @type {Number}\n * @default undefined\n */\n this.right = options.right;\n this._right = undefined;\n\n /**\n * Defines the top clipping plane.\n * @type {Number}\n * @default undefined\n */\n this.top = options.top;\n this._top = undefined;\n\n /**\n * Defines the bottom clipping plane.\n * @type {Number}\n * @default undefined\n */\n this.bottom = options.bottom;\n this._bottom = undefined;\n\n /**\n * The distance of the near plane.\n * @type {Number}\n * @default 1.0\n */\n this.near = options.near;\n this._near = this.near;\n\n /**\n * The distance of the far plane.\n * @type {Number}\n * @default 500000000.0\n */\n this.far = options.far;\n this._far = this.far;\n\n this._cullingVolume = new CullingVolume([\n new Plane(),\n new Plane(),\n new Plane(),\n new Plane(),\n new Plane(),\n new Plane()\n ]);\n this._perspectiveMatrix = new Matrix4();\n this._infinitePerspective = new Matrix4();\n }\n\n /**\n * Returns a duplicate of a PerspectiveOffCenterFrustum instance.\n * @returns {PerspectiveOffCenterFrustum} A new PerspectiveFrustum instance.\n * */\n clone() {\n return new PerspectiveOffCenterFrustum({\n right: this.right,\n left: this.left,\n top: this.top,\n bottom: this.bottom,\n near: this.near,\n far: this.far\n });\n }\n\n /**\n * Compares the provided PerspectiveOffCenterFrustum componentwise and returns\n * true if they are equal, false otherwise.\n *\n * @param {PerspectiveOffCenterFrustum} [other] The right hand side PerspectiveOffCenterFrustum.\n * @returns {Boolean} true if they are equal, false otherwise.\n */\n equals(other) {\n return (\n other &&\n other instanceof PerspectiveOffCenterFrustum &&\n this.right === other.right &&\n this.left === other.left &&\n this.top === other.top &&\n this.bottom === other.bottom &&\n this.near === other.near &&\n this.far === other.far\n );\n }\n\n /**\n * Gets the perspective projection matrix computed from the view frustum.\n * @memberof PerspectiveOffCenterFrustum.prototype\n * @type {Matrix4}\n * @readonly\n *\n * @see PerspectiveOffCenterFrustum#infiniteProjectionMatrix\n */\n get projectionMatrix() {\n update(this);\n return this._perspectiveMatrix;\n }\n\n /**\n * Gets the perspective projection matrix computed from the view frustum with an infinite far plane.\n * @memberof PerspectiveOffCenterFrustum.prototype\n * @type {Matrix4}\n * @readonly\n *\n * @see PerspectiveOffCenterFrustum#projectionMatrix\n */\n get infiniteProjectionMatrix() {\n update(this);\n return this._infinitePerspective;\n }\n\n /**\n * Creates a culling volume for this frustum.\n *\n * @param {Vector3} position The eye position.\n * @param {Vector3} direction The view direction.\n * @param {Vector3} up The up direction.\n * @returns {CullingVolume} A culling volume at the given position and orientation.\n *\n * @example\n * // Check if a bounding volume intersects the frustum.\n * const cullingVolume = frustum.computeCullingVolume(cameraPosition, cameraDirection, cameraUp);\n * const intersect = cullingVolume.computeVisibility(boundingVolume);\n */\n // eslint-disable-next-line complexity, max-statements\n computeCullingVolume(position, direction, up) {\n assert(position, 'position is required.');\n assert(direction, 'direction is required.');\n assert(up, 'up is required.');\n\n const planes = this._cullingVolume.planes;\n\n up = scratchPlaneUpVector.copy(up).normalize();\n const right = scratchPlaneRightVector.copy(direction).cross(up).normalize();\n\n const nearCenter = scratchPlaneNearCenter\n .copy(direction)\n .multiplyByScalar(this.near)\n .add(position);\n\n const farCenter = scratchPlaneFarCenter\n .copy(direction)\n .multiplyByScalar(this.far)\n .add(position);\n\n let normal = scratchPlaneNormal;\n\n // Left plane computation\n normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);\n\n planes[0].fromPointNormal(position, normal);\n\n // Right plane computation\n normal\n .copy(right)\n .multiplyByScalar(this.right)\n .add(nearCenter)\n .subtract(position)\n .cross(up)\n .negate();\n\n planes[1].fromPointNormal(position, normal);\n\n // Bottom plane computation\n normal\n .copy(up)\n .multiplyByScalar(this.bottom)\n .add(nearCenter)\n .subtract(position)\n .cross(right)\n .negate();\n\n planes[2].fromPointNormal(position, normal);\n\n // Top plane computation\n normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);\n\n planes[3].fromPointNormal(position, normal);\n\n normal = new Vector3().copy(direction);\n\n // Near plane computation\n planes[4].fromPointNormal(nearCenter, normal);\n\n // Far plane computation\n normal.negate();\n\n planes[5].fromPointNormal(farCenter, normal);\n\n return this._cullingVolume;\n }\n\n /**\n * Returns the pixel's width and height in meters.\n *\n * @param {Number} drawingBufferWidth The width of the drawing buffer.\n * @param {Number} drawingBufferHeight The height of the drawing buffer.\n * @param {Number} distance The distance to the near plane in meters.\n * @param {Vector2} result The object onto which to store the result.\n * @returns {Vector2} The modified result parameter or a new instance of {@link Vector2} with the pixel's width and height in the x and y properties, respectively.\n *\n * @exception {DeveloperError} drawingBufferWidth must be greater than zero.\n * @exception {DeveloperError} drawingBufferHeight must be greater than zero.\n *\n * @example\n * // Example 1\n * // Get the width and height of a pixel.\n * const pixelSize = camera.frustum.getPixelDimensions(scene.drawingBufferWidth, scene.drawingBufferHeight, 1.0, new Vector2());\n *\n * @example\n * // Example 2\n * // Get the width and height of a pixel if the near plane was set to 'distance'.\n * // For example, get the size of a pixel of an image on a billboard.\n * const position = camera.position;\n * const direction = camera.direction;\n * const toCenter = Vector3.subtract(primitive.boundingVolume.center, position, new Vector3()); // vector from camera to a primitive\n * const toCenterProj = Vector3.multiplyByScalar(direction, Vector3.dot(direction, toCenter), new Vector3()); // project vector onto camera direction vector\n * const distance = Vector3.magnitude(toCenterProj);\n * const pixelSize = camera.frustum.getPixelDimensions(scene.drawingBufferWidth, scene.drawingBufferHeight, distance, new Vector2());\n */\n getPixelDimensions(drawingBufferWidth, drawingBufferHeight, distance, result) {\n update(this);\n\n assert(Number.isFinite(drawingBufferWidth) && Number.isFinite(drawingBufferHeight));\n // 'Both drawingBufferWidth and drawingBufferHeight are required.'\n assert(drawingBufferWidth > 0);\n // 'drawingBufferWidth must be greater than zero.'\n assert(drawingBufferHeight > 0);\n // 'drawingBufferHeight must be greater than zero.'\n assert(distance > 0);\n // 'distance is required.');\n assert(result);\n // 'A result object is required.');\n\n const inverseNear = 1.0 / this.near;\n let tanTheta = this.top * inverseNear;\n const pixelHeight = (2.0 * distance * tanTheta) / drawingBufferHeight;\n tanTheta = this.right * inverseNear;\n const pixelWidth = (2.0 * distance * tanTheta) / drawingBufferWidth;\n\n result.x = pixelWidth;\n result.y = pixelHeight;\n return result;\n }\n}\n\n// eslint-disable-next-line complexity, max-statements\nfunction update(frustum) {\n assert(\n Number.isFinite(frustum.right) &&\n Number.isFinite(frustum.left) &&\n Number.isFinite(frustum.top) &&\n Number.isFinite(frustum.bottom) &&\n Number.isFinite(frustum.near) &&\n Number.isFinite(frustum.far)\n );\n // throw new DeveloperError('right, left, top, bottom, near, or far parameters are not set.');\n\n const {top, bottom, right, left, near, far} = frustum;\n\n if (\n top !== frustum._top ||\n bottom !== frustum._bottom ||\n left !== frustum._left ||\n right !== frustum._right ||\n near !== frustum._near ||\n far !== frustum._far\n ) {\n assert(\n frustum.near > 0 && frustum.near < frustum.far,\n 'near must be greater than zero and less than far.'\n );\n\n frustum._left = left;\n frustum._right = right;\n frustum._top = top;\n frustum._bottom = bottom;\n frustum._near = near;\n frustum._far = far;\n frustum._perspectiveMatrix = new Matrix4().frustum({\n left,\n right,\n bottom,\n top,\n near,\n far\n });\n frustum._infinitePerspective = new Matrix4().frustum({\n left,\n right,\n bottom,\n top,\n near,\n far: Infinity\n });\n }\n}\n","// This file is derived from the Cesium math library under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {Vector3} from '@math.gl/core';\nimport BoundingSphere from '../bounding-volumes/bounding-sphere';\n\n/* eslint-disable */\nconst fromPointsXMin = new Vector3();\nconst fromPointsYMin = new Vector3();\nconst fromPointsZMin = new Vector3();\nconst fromPointsXMax = new Vector3();\nconst fromPointsYMax = new Vector3();\nconst fromPointsZMax = new Vector3();\nconst fromPointsCurrentPos = new Vector3();\nconst fromPointsScratch = new Vector3();\nconst fromPointsRitterCenter = new Vector3();\nconst fromPointsMinBoxPt = new Vector3();\nconst fromPointsMaxBoxPt = new Vector3();\nconst fromPointsNaiveCenterScratch = new Vector3();\nconst volumeConstant = (4.0 / 3.0) * Math.PI;\n\nexport default function makeBoundingSphereFromPoints(positions, result = new BoundingSphere()) {\n if (!positions || positions.length === 0) {\n return result.fromCenterRadius([0, 0, 0], 0);\n }\n\n const currentPos = fromPointsCurrentPos.copy(positions[0]);\n\n const xMin = fromPointsXMin.copy(currentPos);\n const yMin = fromPointsYMin.copy(currentPos);\n const zMin = fromPointsZMin.copy(currentPos);\n\n const xMax = fromPointsXMax.copy(currentPos);\n const yMax = fromPointsYMax.copy(currentPos);\n const zMax = fromPointsZMax.copy(currentPos);\n\n for (const position of positions) {\n currentPos.copy(position);\n\n const x = currentPos.x;\n const y = currentPos.y;\n const z = currentPos.z;\n\n // Store points containing the the smallest and largest components\n if (x < xMin.x) {\n xMin.copy(currentPos);\n }\n\n if (x > xMax.x) {\n xMax.copy(currentPos);\n }\n\n if (y < yMin.y) {\n yMin.copy(currentPos);\n }\n\n if (y > yMax.y) {\n yMax.copy(currentPos);\n }\n\n if (z < zMin.z) {\n zMin.copy(currentPos);\n }\n\n if (z > zMax.z) {\n zMax.copy(currentPos);\n }\n }\n\n // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).\n const xSpan = fromPointsScratch.copy(xMax).subtract(xMin).magnitudeSquared();\n const ySpan = fromPointsScratch.copy(yMax).subtract(yMin).magnitudeSquared();\n const zSpan = fromPointsScratch.copy(zMax).subtract(zMin).magnitudeSquared();\n\n // Set the diameter endpoints to the largest span.\n let diameter1 = xMin;\n let diameter2 = xMax;\n let maxSpan = xSpan;\n if (ySpan > maxSpan) {\n maxSpan = ySpan;\n diameter1 = yMin;\n diameter2 = yMax;\n }\n if (zSpan > maxSpan) {\n maxSpan = zSpan;\n diameter1 = zMin;\n diameter2 = zMax;\n }\n\n // Calculate the center of the initial sphere found by Ritter's algorithm\n const ritterCenter = fromPointsRitterCenter;\n ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;\n ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;\n ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;\n\n // Calculate the radius of the initial sphere found by Ritter's algorithm\n let radiusSquared = fromPointsScratch.copy(diameter2).subtract(ritterCenter).magnitudeSquared();\n let ritterRadius = Math.sqrt(radiusSquared);\n\n // Find the center of the sphere found using the Naive method.\n const minBoxPt = fromPointsMinBoxPt;\n minBoxPt.x = xMin.x;\n minBoxPt.y = yMin.y;\n minBoxPt.z = zMin.z;\n\n const maxBoxPt = fromPointsMaxBoxPt;\n maxBoxPt.x = xMax.x;\n maxBoxPt.y = yMax.y;\n maxBoxPt.z = zMax.z;\n\n const naiveCenter = fromPointsNaiveCenterScratch\n .copy(minBoxPt)\n .add(maxBoxPt)\n .multiplyByScalar(0.5);\n\n // Begin 2nd pass to find naive radius and modify the ritter sphere.\n let naiveRadius = 0;\n for (const position of positions) {\n currentPos.copy(position);\n\n // Find the furthest point from the naive center to calculate the naive radius.\n const r = fromPointsScratch.copy(currentPos).subtract(naiveCenter).magnitude();\n if (r > naiveRadius) {\n naiveRadius = r;\n }\n\n // Make adjustments to the Ritter Sphere to include all points.\n const oldCenterToPointSquared = fromPointsScratch\n .copy(currentPos)\n .subtract(ritterCenter)\n .magnitudeSquared();\n\n if (oldCenterToPointSquared > radiusSquared) {\n const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);\n // Calculate new radius to include the point that lies outside\n ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;\n radiusSquared = ritterRadius * ritterRadius;\n // Calculate center of new Ritter sphere\n const oldToNew = oldCenterToPoint - ritterRadius;\n ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;\n ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;\n ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;\n }\n }\n\n if (ritterRadius < naiveRadius) {\n ritterCenter.to(result.center);\n // @ts-ignore TS2540: Cannot assign to 'radius' because it is a read-only property.\n result.radius = ritterRadius;\n } else {\n naiveCenter.to(result.center);\n // @ts-ignore TS2540: Cannot assign to 'radius' because it is a read-only property.\n result.radius = naiveRadius;\n }\n\n return result;\n}\n","// NOTE: Added to make Cesium-derived test cases work\n// TODO: Determine if/how to keep\nexport default {\n EPSILON1: 1e-1,\n EPSILON2: 1e-2,\n EPSILON3: 1e-3,\n EPSILON4: 1e-4,\n EPSILON5: 1e-5,\n EPSILON6: 1e-6,\n EPSILON7: 1e-7,\n EPSILON8: 1e-8,\n EPSILON9: 1e-9,\n EPSILON10: 1e-10,\n EPSILON11: 1e-11,\n EPSILON12: 1e-12,\n EPSILON13: 1e-13,\n EPSILON14: 1e-14,\n EPSILON15: 1e-15,\n EPSILON16: 1e-16,\n EPSILON17: 1e-17,\n EPSILON18: 1e-18,\n EPSILON19: 1e-19,\n EPSILON20: 1e-20,\n\n PI_OVER_TWO: Math.PI / 2,\n PI_OVER_FOUR: Math.PI / 4,\n PI_OVER_SIX: Math.PI / 6,\n\n TWO_PI: Math.PI * 2\n};\n","// This file is derived from the Cesium math library under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {Matrix3, _MathUtils} from '@math.gl/core';\n\nconst scratchMatrix = new Matrix3();\nconst scratchUnitary = new Matrix3();\nconst scratchDiagonal = new Matrix3();\n\nconst jMatrix = new Matrix3();\nconst jMatrixTranspose = new Matrix3();\n\nexport default function computeEigenDecomposition(matrix, result = {}) {\n const EIGEN_TOLERANCE = _MathUtils.EPSILON20;\n const EIGEN_MAX_SWEEPS = 10;\n\n let count = 0;\n let sweep = 0;\n\n const unitaryMatrix = scratchUnitary;\n const diagonalMatrix = scratchDiagonal;\n\n unitaryMatrix.identity();\n diagonalMatrix.copy(matrix);\n\n const epsilon = EIGEN_TOLERANCE * computeFrobeniusNorm(diagonalMatrix);\n\n while (sweep < EIGEN_MAX_SWEEPS && offDiagonalFrobeniusNorm(diagonalMatrix) > epsilon) {\n shurDecomposition(diagonalMatrix, jMatrix);\n\n jMatrixTranspose.copy(jMatrix).transpose();\n\n diagonalMatrix.multiplyRight(jMatrix);\n diagonalMatrix.multiplyLeft(jMatrixTranspose);\n unitaryMatrix.multiplyRight(jMatrix);\n\n if (++count > 2) {\n ++sweep;\n count = 0;\n }\n }\n\n result.unitary = unitaryMatrix.toTarget(result.unitary);\n result.diagonal = diagonalMatrix.toTarget(result.diagonal);\n\n return result;\n}\n\nfunction computeFrobeniusNorm(matrix) {\n let norm = 0.0;\n for (let i = 0; i < 9; ++i) {\n const temp = matrix[i];\n norm += temp * temp;\n }\n return Math.sqrt(norm);\n}\n\nconst rowVal = [1, 0, 0];\nconst colVal = [2, 2, 1];\n\n// Computes the \"off-diagonal\" Frobenius norm.\n// Assumes matrix is symmetric.\nfunction offDiagonalFrobeniusNorm(matrix) {\n let norm = 0.0;\n for (let i = 0; i < 3; ++i) {\n const temp = matrix[scratchMatrix.getElementIndex(colVal[i], rowVal[i])];\n norm += 2.0 * temp * temp;\n }\n return Math.sqrt(norm);\n}\n\n// The routine takes a matrix, which is assumed to be symmetric, and\n// finds the largest off-diagonal term, and then creates\n// a matrix (result) which can be used to help reduce it\n//\n// This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,\n// section 8.4.2 The 2by2 Symmetric Schur Decomposition.\n//\n// eslint-disable-next-line max-statements\nfunction shurDecomposition(matrix, result) {\n const tolerance = _MathUtils.EPSILON15;\n\n let maxDiagonal = 0.0;\n let rotAxis = 1;\n\n // find pivot (rotAxis) based on max diagonal of matrix\n for (let i = 0; i < 3; ++i) {\n const temp = Math.abs(matrix[scratchMatrix.getElementIndex(colVal[i], rowVal[i])]);\n if (temp > maxDiagonal) {\n rotAxis = i;\n maxDiagonal = temp;\n }\n }\n\n const p = rowVal[rotAxis];\n const q = colVal[rotAxis];\n\n let c = 1.0;\n let s = 0.0;\n\n if (Math.abs(matrix[scratchMatrix.getElementIndex(q, p)]) > tolerance) {\n const qq = matrix[scratchMatrix.getElementIndex(q, q)];\n const pp = matrix[scratchMatrix.getElementIndex(p, p)];\n const qp = matrix[scratchMatrix.getElementIndex(q, p)];\n\n const tau = (qq - pp) / 2.0 / qp;\n let t;\n\n if (tau < 0.0) {\n t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));\n } else {\n t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));\n }\n\n c = 1.0 / Math.sqrt(1.0 + t * t);\n s = t * c;\n }\n\n // Copy into result\n Matrix3.IDENTITY.to(result);\n result[scratchMatrix.getElementIndex(p, p)] = result[scratchMatrix.getElementIndex(q, q)] = c;\n result[scratchMatrix.getElementIndex(q, p)] = s;\n result[scratchMatrix.getElementIndex(p, q)] = -s;\n\n return result;\n}\n","// This file is derived from the Cesium math library under Apache 2 license\n// See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md\n\nimport {Vector3, Matrix3} from '@math.gl/core';\nimport computeEigenDecomposition from './compute-eigen-decomposition';\nimport OrientedBoundingBox from '../bounding-volumes/oriented-bounding-box';\nimport AxisAlignedBoundingBox from '../bounding-volumes/axis-aligned-bounding-box';\n\nconst scratchVector2 = new Vector3();\n\nconst scratchVector3 = new Vector3();\n\nconst scratchVector4 = new Vector3();\n\nconst scratchVector5 = new Vector3();\n\nconst scratchVector6 = new Vector3();\n\nconst scratchCovarianceResult = new Matrix3();\n\nconst scratchEigenResult = {\n diagonal: new Matrix3(),\n unitary: new Matrix3()\n};\n\n/* eslint-disable max-statements */\nexport function makeOrientedBoundingBoxFromPoints(positions, result = new OrientedBoundingBox()) {\n if (!positions || positions.length === 0) {\n result.halfAxes = new Matrix3([0, 0, 0, 0, 0, 0, 0, 0, 0]);\n result.center = new Vector3();\n return result;\n }\n\n const length = positions.length;\n const meanPoint = new Vector3(0, 0, 0);\n for (const position of positions) {\n meanPoint.add(position);\n }\n const invLength = 1.0 / length;\n meanPoint.multiplyByScalar(invLength);\n\n let exx = 0.0;\n let exy = 0.0;\n let exz = 0.0;\n let eyy = 0.0;\n let eyz = 0.0;\n let ezz = 0.0;\n\n for (const position of positions) {\n const p = scratchVector2.copy(position).subtract(meanPoint);\n exx += p.x * p.x;\n exy += p.x * p.y;\n exz += p.x * p.z;\n eyy += p.y * p.y;\n eyz += p.y * p.z;\n ezz += p.z * p.z;\n }\n\n exx *= invLength;\n exy *= invLength;\n exz *= invLength;\n eyy *= invLength;\n eyz *= invLength;\n ezz *= invLength;\n\n const covarianceMatrix = scratchCovarianceResult;\n covarianceMatrix[0] = exx;\n covarianceMatrix[1] = exy;\n covarianceMatrix[2] = exz;\n covarianceMatrix[3] = exy;\n covarianceMatrix[4] = eyy;\n covarianceMatrix[5] = eyz;\n covarianceMatrix[6] = exz;\n covarianceMatrix[7] = eyz;\n covarianceMatrix[8] = ezz;\n\n const {unitary} = computeEigenDecomposition(covarianceMatrix, scratchEigenResult);\n const rotation = result.halfAxes.copy(unitary);\n\n let v1 = rotation.getColumn(0, scratchVector4);\n let v2 = rotation.getColumn(1, scratchVector5);\n let v3 = rotation.getColumn(2, scratchVector6);\n\n let u1 = -Number.MAX_VALUE;\n let u2 = -Number.MAX_VALUE;\n let u3 = -Number.MAX_VALUE;\n let l1 = Number.MAX_VALUE;\n let l2 = Number.MAX_VALUE;\n let l3 = Number.MAX_VALUE;\n\n for (const position of positions) {\n scratchVector2.copy(position);\n\n u1 = Math.max(scratchVector2.dot(v1), u1);\n u2 = Math.max(scratchVector2.dot(v2), u2);\n u3 = Math.max(scratchVector2.dot(v3), u3);\n\n l1 = Math.min(scratchVector2.dot(v1), l1);\n l2 = Math.min(scratchVector2.dot(v2), l2);\n l3 = Math.min(scratchVector2.dot(v3), l3);\n }\n\n v1 = v1.multiplyByScalar(0.5 * (l1 + u1));\n v2 = v2.multiplyByScalar(0.5 * (l2 + u2));\n v3 = v3.multiplyByScalar(0.5 * (l3 + u3));\n\n result.center.copy(v1).add(v2).add(v3);\n\n const scale = scratchVector3.set(u1 - l1, u2 - l2, u3 - l3).multiplyByScalar(0.5);\n const scaleMatrix = new Matrix3([scale[0], 0, 0, 0, scale[1], 0, 0, 0, scale[2]]);\n result.halfAxes.multiplyRight(scaleMatrix);\n\n return result;\n}\n\nexport function makeAxisAlignedBoundingBoxFromPoints(\n positions,\n result = new AxisAlignedBoundingBox()\n) {\n if (!positions || positions.length === 0) {\n result.minimum.set(0, 0, 0);\n result.maximum.set(0, 0, 0);\n result.center.set(0, 0, 0);\n result.halfDiagonal.set(0, 0, 0);\n return result;\n }\n\n let minimumX = positions[0][0];\n let minimumY = positions[0][1];\n let minimumZ = positions[0][2];\n\n let maximumX = positions[0][0];\n let maximumY = positions[0][1];\n let maximumZ = positions[0][2];\n\n for (const p of positions) {\n const x = p[0];\n const y = p[1];\n const z = p[2];\n\n minimumX = Math.min(x, minimumX);\n maximumX = Math.max(x, maximumX);\n minimumY = Math.min(y, minimumY);\n maximumY = Math.max(y, maximumY);\n minimumZ = Math.min(z, minimumZ);\n maximumZ = Math.max(z, maximumZ);\n }\n\n result.minimum.set(minimumX, minimumY, minimumZ);\n result.maximum.set(maximumX, maximumY, maximumZ);\n result.center.copy(result.minimum).add(result.maximum).scale(0.5);\n result.halfDiagonal.copy(result.maximum).subtract(result.center);\n\n return result;\n}\n","var createRange = require('./_createRange');\n\n/**\n * Creates an array of numbers (positive and/or negative) progressing from\n * `start` up to, but not including, `end`. A step of `-1` is used if a negative\n * `start` is specified without an `end` or `step`. If `end` is not specified,\n * it's set to `start` with `start` then set to `0`.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @param {number} [step=1] The value to increment or decrement by.\n * @returns {Array} Returns the range of numbers.\n * @see _.inRange, _.rangeRight\n * @example\n *\n * _.range(4);\n * // => [0, 1, 2, 3]\n *\n * _.range(-4);\n * // => [0, -1, -2, -3]\n *\n * _.range(1, 5);\n * // => [1, 2, 3, 4]\n *\n * _.range(0, 20, 5);\n * // => [0, 5, 10, 15]\n *\n * _.range(0, -4, -1);\n * // => [0, -1, -2, -3]\n *\n * _.range(1, 4, 0);\n * // => [1, 1, 1]\n *\n * _.range(0);\n * // => []\n */\nvar range = createRange();\n\nmodule.exports = range;\n","import objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose\";\nexport default function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n}","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}","// Extensions to math.gl library. Intended to be folded back.\nimport typedArrayManager from './typed-array-manager';\nimport {Vector3} from 'math.gl';\n\n// Helper, avoids low-precision 32 bit matrices from gl-matrix mat4.create()\nexport function createMat4() {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n}\n\nexport function mod(value, divisor) {\n const modulus = value % divisor;\n return modulus < 0 ? divisor + modulus : modulus;\n}\n\n// Extract camera vectors (move to math library?)\nexport function getCameraPosition(viewMatrixInverse) {\n // Read the translation from the inverse view matrix\n return [viewMatrixInverse[12], viewMatrixInverse[13], viewMatrixInverse[14]];\n}\n\n// https://www.gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf\nexport function getFrustumPlanes(viewProjectionMatrix) {\n const planes = {};\n\n planes.left = getFrustumPlane(\n viewProjectionMatrix[3] + viewProjectionMatrix[0],\n viewProjectionMatrix[7] + viewProjectionMatrix[4],\n viewProjectionMatrix[11] + viewProjectionMatrix[8],\n viewProjectionMatrix[15] + viewProjectionMatrix[12]\n );\n planes.right = getFrustumPlane(\n viewProjectionMatrix[3] - viewProjectionMatrix[0],\n viewProjectionMatrix[7] - viewProjectionMatrix[4],\n viewProjectionMatrix[11] - viewProjectionMatrix[8],\n viewProjectionMatrix[15] - viewProjectionMatrix[12]\n );\n planes.bottom = getFrustumPlane(\n viewProjectionMatrix[3] + viewProjectionMatrix[1],\n viewProjectionMatrix[7] + viewProjectionMatrix[5],\n viewProjectionMatrix[11] + viewProjectionMatrix[9],\n viewProjectionMatrix[15] + viewProjectionMatrix[13]\n );\n planes.top = getFrustumPlane(\n viewProjectionMatrix[3] - viewProjectionMatrix[1],\n viewProjectionMatrix[7] - viewProjectionMatrix[5],\n viewProjectionMatrix[11] - viewProjectionMatrix[9],\n viewProjectionMatrix[15] - viewProjectionMatrix[13]\n );\n planes.near = getFrustumPlane(\n viewProjectionMatrix[3] + viewProjectionMatrix[2],\n viewProjectionMatrix[7] + viewProjectionMatrix[6],\n viewProjectionMatrix[11] + viewProjectionMatrix[10],\n viewProjectionMatrix[15] + viewProjectionMatrix[14]\n );\n planes.far = getFrustumPlane(\n viewProjectionMatrix[3] - viewProjectionMatrix[2],\n viewProjectionMatrix[7] - viewProjectionMatrix[6],\n viewProjectionMatrix[11] - viewProjectionMatrix[10],\n viewProjectionMatrix[15] - viewProjectionMatrix[14]\n );\n\n return planes;\n}\n\nconst scratchVector = new Vector3();\n\nfunction getFrustumPlane(a, b, c, d) {\n scratchVector.set(a, b, c);\n const L = scratchVector.len();\n return {distance: d / L, normal: new Vector3(-a / L, -b / L, -c / L)};\n}\n\n/**\n * Calculate the low part of a WebGL 64 bit float\n * @param x {number} - the input float number\n * @returns {number} - the lower 32 bit of the number\n */\nexport function fp64LowPart(x) {\n return x - Math.fround(x);\n}\n\nlet scratchArray;\n\n/**\n * Split a Float64Array into a double-length Float32Array\n * @param typedArray {Float64Array}\n * @param size {Number} - per attribute size\n * @param [startIndex] {Number} - start index in the source array\n * @param [endIndex] {Number} - end index in the source array\n * @returns {Float32Array} - high part, low part for each attribute:\n [1xHi, 1yHi, 1zHi, 1xLow, 1yLow, 1zLow, 2xHi, ...]\n */\nexport function toDoublePrecisionArray(typedArray, {size = 1, startIndex = 0, endIndex}) {\n if (!Number.isFinite(endIndex)) {\n endIndex = typedArray.length;\n }\n const count = (endIndex - startIndex) / size;\n scratchArray = typedArrayManager.allocate(scratchArray, count, {\n type: Float32Array,\n size: size * 2\n });\n\n let sourceIndex = startIndex;\n let targetIndex = 0;\n while (sourceIndex < endIndex) {\n for (let j = 0; j < size; j++) {\n const value = typedArray[sourceIndex++];\n scratchArray[targetIndex + j] = value;\n scratchArray[targetIndex + j + size] = fp64LowPart(value);\n }\n targetIndex += size * 2;\n }\n\n return scratchArray.subarray(0, count * size * 2);\n}\n","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","var baseClamp = require('./_baseClamp'),\n toNumber = require('./toNumber');\n\n/**\n * Clamps `number` within the inclusive `lower` and `upper` bounds.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Number\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n * @example\n *\n * _.clamp(-10, -5, 5);\n * // => -5\n *\n * _.clamp(10, -5, 5);\n * // => 5\n */\nfunction clamp(number, lower, upper) {\n if (upper === undefined) {\n upper = lower;\n lower = undefined;\n }\n if (upper !== undefined) {\n upper = toNumber(upper);\n upper = upper === upper ? upper : 0;\n }\n if (lower !== undefined) {\n lower = toNumber(lower);\n lower = lower === lower ? lower : 0;\n }\n return baseClamp(toNumber(number), lower, upper);\n}\n\nmodule.exports = clamp;\n","/* eslint-disable max-statements, max-depth, complexity, no-unused-expressions */\n\nimport {equals} from '@math.gl/core';\n\n/** @type {typeof import('./polygon-utils').WINDING} */\nexport const WINDING = {\n CLOCKWISE: 1,\n COUNTER_CLOCKWISE: -1\n};\n\n/** @type {typeof import('./polygon-utils').modifyPolygonWindingDirection} */\nexport function modifyPolygonWindingDirection(points, direction, options = {}) {\n const windingDirection = getPolygonWindingDirection(points, options);\n if (windingDirection !== direction) {\n reversePolygon(points, options);\n return true;\n }\n return false;\n}\n\n/** @type {typeof import('./polygon-utils').getPolygonWindingDirection} */\nexport function getPolygonWindingDirection(points, options = {}) {\n return Math.sign(getPolygonSignedArea(points, options));\n}\n\n/** @type {typeof import('./polygon-utils').getPolygonSignedArea} */\nexport function getPolygonSignedArea(points, options = {}) {\n // https://en.wikipedia.org/wiki/Shoelace_formula\n const {start = 0, end = points.length} = options;\n const dim = options.size || 2;\n let area = 0;\n for (let i = start, j = end - dim; i < end; i += dim) {\n area += (points[i] - points[j]) * (points[i + 1] + points[j + 1]);\n j = i;\n }\n return area / 2;\n}\n\n/** @type {typeof import('./polygon-utils').forEachSegmentInPolygon} */\nexport function forEachSegmentInPolygon(points, visitor, options = {}) {\n const {start = 0, end = points.length, size = 2, isClosed} = options;\n\n const numPoints = (end - start) / size;\n for (let i = 0; i < numPoints - 1; ++i) {\n visitor(\n points[start + i * size],\n points[start + i * size + 1],\n points[start + (i + 1) * size],\n points[start + (i + 1) * size + 1],\n i,\n i + 1\n );\n }\n\n const endPointIndex = start + (numPoints - 1) * size;\n const isClosedEx =\n isClosed ||\n (equals(points[start], points[endPointIndex]) &&\n equals(points[start + 1], points[endPointIndex + 1]));\n\n if (!isClosedEx) {\n visitor(\n points[endPointIndex],\n points[endPointIndex + 1],\n points[start],\n points[start + 1],\n numPoints - 1,\n 0\n );\n }\n}\n\nfunction reversePolygon(points, options) {\n const {start = 0, end = points.length, size = 2} = options;\n\n const numPoints = (end - start) / size;\n const numSwaps = Math.floor(numPoints / 2);\n for (let i = 0; i < numSwaps; ++i) {\n const b1 = start + i * size;\n const b2 = start + (numPoints - 1 - i) * size;\n for (let j = 0; j < size; ++j) {\n const tmp = points[b1 + j];\n points[b1 + j] = points[b2 + j];\n points[b2 + j] = tmp;\n }\n }\n}\n\n/** @type {typeof import('./polygon-utils').modifyPolygonWindingDirectionPoints} */\nexport function modifyPolygonWindingDirectionPoints(points, direction, options = {}) {\n const currentDirection = getPolygonWindingDirectionPoints(points, options);\n if (currentDirection !== direction) {\n points.reverse();\n return true;\n }\n return false;\n}\n\n/** @type {typeof import('./polygon-utils').getPolygonWindingDirectionPoints} */\nexport function getPolygonWindingDirectionPoints(points, options = {}) {\n return Math.sign(getPolygonSignedAreaPoints(points, options));\n}\n\n/** @type {typeof import('./polygon-utils').getPolygonSignedAreaPoints} */\nexport function getPolygonSignedAreaPoints(points, options = {}) {\n // https://en.wikipedia.org/wiki/Shoelace_formula\n const {start = 0, end = points.length} = options;\n let area = 0;\n for (let i = start, j = end - 1; i < end; ++i) {\n area += (points[i][0] - points[j][0]) * (points[i][1] + points[j][1]);\n j = i;\n }\n return area / 2;\n}\n\n/** @type {typeof import('./polygon-utils').forEachSegmentInPolygonPoints} */\nexport function forEachSegmentInPolygonPoints(points, visitor, options = {}) {\n const {start = 0, end = points.length, isClosed} = options;\n for (let i = start; i < end - 1; ++i) {\n visitor(points[i], points[i + 1], i, i + 1);\n }\n\n const isClosedEx = isClosed || equals(points[end - 1], points[0]);\n if (!isClosedEx) {\n visitor(points[end - 1], points[0], end - 1, 0);\n }\n}\n","/*\n Adapted from https://github.com/mapbox/earcut to allow passing in\n of outline and hole areas using the `areas` parameter. As the\n areas are calcuted as part of classifying the polygon rings\n we can pass them in again to avoid recomputation\n\n ISC License\n\n Copyright (c) 2016, Mapbox\n\n Permission to use, copy, modify, and/or distribute this software for any purpose\n with or without fee is hereby granted, provided that the above copyright notice\n and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n THIS SOFTWARE.\n\n */\n\n/* eslint-disable complexity, max-params, max-statements, max-depth, no-continue, no-shadow */\n\nimport {getPolygonSignedArea} from './polygon-utils';\n\nexport function earcut(data, holeIndices, dim, areas) {\n dim = dim || 2;\n\n const hasHoles = holeIndices && holeIndices.length;\n const outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n let outerNode = linkedList(data, 0, outerLen, dim, true, areas && areas[0]);\n const triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n let invSize;\n let maxX;\n let maxY;\n let minX;\n let minY;\n let x;\n let y;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim, areas);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = maxX = data[0];\n minY = maxY = data[1];\n\n for (let i = dim; i < outerLen; i += dim) {\n x = data[i];\n y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 1 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise, area) {\n let i;\n let last;\n if (area === undefined) {\n area = getPolygonSignedArea(data, {start, end, size: dim});\n }\n\n // Note that the signed area calculation in math.gl\n // has the opposite sign to that which was originally\n // present in earcut, thus the `< 0` is reversed\n if (clockwise === area < 0) {\n for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);\n } else {\n for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n let p = start;\n let again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n let stop = ear;\n let prev;\n let next;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n prev = ear.prev;\n next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n // cut off the triangle\n triangles.push(prev.i / dim);\n triangles.push(ear.i / dim);\n triangles.push(next.i / dim);\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles, dim);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n const a = ear.prev;\n const b = ear;\n const c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n let p = ear.next.next;\n\n while (p !== ear.prev) {\n if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0)\n return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n const a = ear.prev;\n const b = ear;\n const c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // triangle bbox; min & max are calculated like this for speed\n const minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : b.x < c.x ? b.x : c.x;\n const minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : b.y < c.y ? b.y : c.y;\n const maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : b.x > c.x ? b.x : c.x;\n const maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : b.y > c.y ? b.y : c.y;\n\n // z-order range for the current triangle bbox;\n const minZ = zOrder(minTX, minTY, minX, minY, invSize);\n const maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);\n\n let p = ear.prevZ;\n let n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (\n p !== ear.prev &&\n p !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0\n )\n return false;\n p = p.prevZ;\n\n if (\n n !== ear.prev &&\n n !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&\n area(n.prev, n, n.next) >= 0\n )\n return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (\n p !== ear.prev &&\n p !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0\n )\n return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (\n n !== ear.prev &&\n n !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&\n area(n.prev, n, n.next) >= 0\n )\n return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles, dim) {\n let p = start;\n do {\n const a = p.prev;\n const b = p.next.next;\n\n if (\n !equals(a, b) &&\n intersects(a, p, p.next, b) &&\n locallyInside(a, b) &&\n locallyInside(b, a)\n ) {\n triangles.push(a.i / dim);\n triangles.push(p.i / dim);\n triangles.push(b.i / dim);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n let a = start;\n do {\n let b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n let c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize);\n earcutLinked(c, triangles, dim, minX, minY, invSize);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim, areas) {\n const queue = [];\n let i;\n let len;\n let start;\n let end;\n let list;\n\n for (i = 0, len = holeIndices.length; i < len; i++) {\n start = holeIndices[i] * dim;\n end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n list = linkedList(data, start, end, dim, false, areas && areas[i + 1]);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareX);\n\n // process holes from left to right\n for (i = 0; i < queue.length; i++) {\n eliminateHole(queue[i], outerNode);\n outerNode = filterPoints(outerNode, outerNode.next);\n }\n\n return outerNode;\n}\n\nfunction compareX(a, b) {\n return a.x - b.x;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and and link it\nfunction eliminateHole(hole, outerNode) {\n outerNode = findHoleBridge(hole, outerNode);\n if (outerNode) {\n const b = splitPolygon(outerNode, hole);\n\n // filter collinear points around the cuts\n filterPoints(outerNode, outerNode.next);\n filterPoints(b, b.next);\n }\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n let p = outerNode;\n const hx = hole.x;\n const hy = hole.y;\n let qx = -Infinity;\n let m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n do {\n if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n const x = p.x + ((hy - p.y) * (p.next.x - p.x)) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n if (x === hx) {\n if (hy === p.y) return p;\n if (hy === p.next.y) return p.next;\n }\n m = p.x < p.next.x ? p : p.next;\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n const stop = m;\n const mx = m.x;\n const my = m.y;\n let tanMin = Infinity;\n let tan;\n\n p = m;\n\n do {\n if (\n hx >= p.x &&\n p.x >= mx &&\n hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)\n ) {\n tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (\n locallyInside(p, hole) &&\n (tan < tanMin ||\n (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))\n ) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n let p = start;\n do {\n if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n let e;\n let i;\n let inSize = 1;\n let numMerges;\n let p;\n let pSize;\n let q;\n let qSize;\n let tail;\n\n do {\n p = list;\n list = null;\n tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n q = p;\n pSize = 0;\n for (i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = 32767 * (x - minX) * invSize;\n y = 32767 * (y - minY) * invSize;\n\n x = (x | (x << 8)) & 0x00ff00ff;\n x = (x | (x << 4)) & 0x0f0f0f0f;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00ff00ff;\n y = (y | (y << 4)) & 0x0f0f0f0f;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n let p = start;\n let leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (\n (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&\n (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&\n (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0\n );\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return (\n a.next.i !== b.i &&\n a.prev.i !== b.i &&\n !intersectsPolygon(a, b) && // dones't intersect other edges\n ((locallyInside(a, b) &&\n locallyInside(b, a) &&\n middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b))) || // does not create opposite-facing sectors\n (equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0))\n ); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n const o1 = sign(area(p1, q1, p2));\n const o2 = sign(area(p1, q1, q2));\n const o3 = sign(area(p2, q2, p1));\n const o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return (\n q.x <= Math.max(p.x, r.x) &&\n q.x >= Math.min(p.x, r.x) &&\n q.y <= Math.max(p.y, r.y) &&\n q.y >= Math.min(p.y, r.y)\n );\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n let p = a;\n do {\n if (\n p.i !== a.i &&\n p.next.i !== a.i &&\n p.i !== b.i &&\n p.next.i !== b.i &&\n intersects(p, p.next, a, b)\n )\n return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0\n ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0\n : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n let p = a;\n let inside = false;\n const px = (a.x + b.x) / 2;\n const py = (a.y + b.y) / 2;\n do {\n if (\n p.y > py !== p.next.y > py &&\n p.next.y !== p.y &&\n px < ((p.next.x - p.x) * (py - p.y)) / (p.next.y - p.y) + p.x\n )\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n const a2 = new Node(a.i, a.x, a.y);\n const b2 = new Node(b.i, b.x, b.y);\n const an = a.next;\n const bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n const p = new Node(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction Node(i, x, y) {\n // vertex index in coordinates array\n this.i = i;\n\n // vertex coordinates\n this.x = x;\n this.y = y;\n\n // previous and next vertex nodes in a polygon ring\n this.prev = null;\n this.next = null;\n\n // z-order curve value\n this.z = null;\n\n // previous and next nodes in z-order\n this.prevZ = null;\n this.nextZ = null;\n\n // indicates whether this is a steiner point\n this.steiner = false;\n}\n","import {\n setTransitionProperty,\n getTransitionProperty,\n getTransformXY,\n setTransformXY,\n getTransformName,\n} from './propertyUtils';\n\nconst RE_NUM = /[\\-+]?(?:\\d*\\.|)\\d+(?:[eE][\\-+]?\\d+|)/.source;\n\nlet getComputedStyleX;\n\n// https://stackoverflow.com/a/3485654/3040605\nfunction forceRelayout(elem) {\n const originalStyle = elem.style.display;\n elem.style.display = 'none';\n elem.offsetHeight; // eslint-disable-line\n elem.style.display = originalStyle;\n}\n\nfunction css(el, name, v) {\n let value = v;\n if (typeof name === 'object') {\n for (const i in name) {\n if (name.hasOwnProperty(i)) {\n css(el, i, name[i]);\n }\n }\n return undefined;\n }\n if (typeof value !== 'undefined') {\n if (typeof value === 'number') {\n value = `${value}px`;\n }\n el.style[name] = value;\n return undefined;\n }\n return getComputedStyleX(el, name);\n}\n\nfunction getClientPosition(elem) {\n let box;\n let x;\n let y;\n const doc = elem.ownerDocument;\n const body = doc.body;\n const docElem = doc && doc.documentElement;\n // 根据 GBS 最新数据,A-Grade Browsers 都已支持 getBoundingClientRect 方法,不用再考虑传统的实现方式\n box = elem.getBoundingClientRect();\n\n // 注:jQuery 还考虑减去 docElem.clientLeft/clientTop\n // 但测试发现,这样反而会导致当 html 和 body 有边距/边框样式时,获取的值不正确\n // 此外,ie6 会忽略 html 的 margin 值,幸运地是没有谁会去设置 html 的 margin\n\n x = box.left;\n y = box.top;\n\n // In IE, most of the time, 2 extra pixels are added to the top and left\n // due to the implicit 2-pixel inset border. In IE6/7 quirks mode and\n // IE6 standards mode, this border can be overridden by setting the\n // document element's border to zero -- thus, we cannot rely on the\n // offset always being 2 pixels.\n\n // In quirks mode, the offset can be determined by querying the body's\n // clientLeft/clientTop, but in standards mode, it is found by querying\n // the document element's clientLeft/clientTop. Since we already called\n // getClientBoundingRect we have already forced a reflow, so it is not\n // too expensive just to query them all.\n\n // ie 下应该减去窗口的边框吧,毕竟默认 absolute 都是相对窗口定位的\n // 窗口边框标准是设 documentElement ,quirks 时设置 body\n // 最好禁止在 body 和 html 上边框 ,但 ie < 9 html 默认有 2px ,减去\n // 但是非 ie 不可能设置窗口边框,body html 也不是窗口 ,ie 可以通过 html,body 设置\n // 标准 ie 下 docElem.clientTop 就是 border-top\n // ie7 html 即窗口边框改变不了。永远为 2\n // 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框,即使设了 border-top 也为 0\n\n x -= docElem.clientLeft || body.clientLeft || 0;\n y -= docElem.clientTop || body.clientTop || 0;\n\n return {\n left: x,\n top: y,\n };\n}\n\nfunction getScroll(w, top) {\n let ret = w[`page${top ? 'Y' : 'X'}Offset`];\n const method = `scroll${top ? 'Top' : 'Left'}`;\n if (typeof ret !== 'number') {\n const d = w.document;\n // ie6,7,8 standard mode\n ret = d.documentElement[method];\n if (typeof ret !== 'number') {\n // quirks mode\n ret = d.body[method];\n }\n }\n return ret;\n}\n\nfunction getScrollLeft(w) {\n return getScroll(w);\n}\n\nfunction getScrollTop(w) {\n return getScroll(w, true);\n}\n\nfunction getOffset(el) {\n const pos = getClientPosition(el);\n const doc = el.ownerDocument;\n const w = doc.defaultView || doc.parentWindow;\n pos.left += getScrollLeft(w);\n pos.top += getScrollTop(w);\n return pos;\n}\n\n/**\n * A crude way of determining if an object is a window\n * @member util\n */\nfunction isWindow(obj) {\n // must use == for ie8\n /* eslint eqeqeq:0 */\n return obj !== null && obj !== undefined && obj == obj.window;\n}\n\nfunction getDocument(node) {\n if (isWindow(node)) {\n return node.document;\n }\n if (node.nodeType === 9) {\n return node;\n }\n return node.ownerDocument;\n}\n\nfunction _getComputedStyle(elem, name, cs) {\n let computedStyle = cs;\n let val = '';\n const d = getDocument(elem);\n computedStyle = computedStyle || d.defaultView.getComputedStyle(elem, null);\n\n // https://github.com/kissyteam/kissy/issues/61\n if (computedStyle) {\n val = computedStyle.getPropertyValue(name) || computedStyle[name];\n }\n\n return val;\n}\n\nconst _RE_NUM_NO_PX = new RegExp(`^(${RE_NUM})(?!px)[a-z%]+$`, 'i');\nconst RE_POS = /^(top|right|bottom|left)$/;\nconst CURRENT_STYLE = 'currentStyle';\nconst RUNTIME_STYLE = 'runtimeStyle';\nconst LEFT = 'left';\nconst PX = 'px';\n\nfunction _getComputedStyleIE(elem, name) {\n // currentStyle maybe null\n // http://msdn.microsoft.com/en-us/library/ms535231.aspx\n let ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name];\n\n // 当 width/height 设置为百分比时,通过 pixelLeft 方式转换的 width/height 值\n // 一开始就处理了! CUSTOM_STYLE.height,CUSTOM_STYLE.width ,cssHook 解决@2011-08-19\n // 在 ie 下不对,需要直接用 offset 方式\n // borderWidth 等值也有问题,但考虑到 borderWidth 设为百分比的概率很小,这里就不考虑了\n\n // From the awesome hack by Dean Edwards\n // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291\n // If we're not dealing with a regular pixel number\n // but a number that has a weird ending, we need to convert it to pixels\n // exclude left right for relativity\n if (_RE_NUM_NO_PX.test(ret) && !RE_POS.test(name)) {\n // Remember the original values\n const style = elem.style;\n const left = style[LEFT];\n const rsLeft = elem[RUNTIME_STYLE][LEFT];\n\n // prevent flashing of content\n elem[RUNTIME_STYLE][LEFT] = elem[CURRENT_STYLE][LEFT];\n\n // Put in the new values to get a computed value out\n style[LEFT] = name === 'fontSize' ? '1em' : ret || 0;\n ret = style.pixelLeft + PX;\n\n // Revert the changed values\n style[LEFT] = left;\n\n elem[RUNTIME_STYLE][LEFT] = rsLeft;\n }\n return ret === '' ? 'auto' : ret;\n}\n\nif (typeof window !== 'undefined') {\n getComputedStyleX = window.getComputedStyle\n ? _getComputedStyle\n : _getComputedStyleIE;\n}\n\nfunction getOffsetDirection(dir, option) {\n if (dir === 'left') {\n return option.useCssRight ? 'right' : dir;\n }\n return option.useCssBottom ? 'bottom' : dir;\n}\n\nfunction oppositeOffsetDirection(dir) {\n if (dir === 'left') {\n return 'right';\n } else if (dir === 'right') {\n return 'left';\n } else if (dir === 'top') {\n return 'bottom';\n } else if (dir === 'bottom') {\n return 'top';\n }\n}\n\n// 设置 elem 相对 elem.ownerDocument 的坐标\nfunction setLeftTop(elem, offset, option) {\n // set position first, in-case top/left are set even on static elem\n if (css(elem, 'position') === 'static') {\n elem.style.position = 'relative';\n }\n let presetH = -999;\n let presetV = -999;\n const horizontalProperty = getOffsetDirection('left', option);\n const verticalProperty = getOffsetDirection('top', option);\n const oppositeHorizontalProperty = oppositeOffsetDirection(\n horizontalProperty,\n );\n const oppositeVerticalProperty = oppositeOffsetDirection(verticalProperty);\n\n if (horizontalProperty !== 'left') {\n presetH = 999;\n }\n\n if (verticalProperty !== 'top') {\n presetV = 999;\n }\n let originalTransition = '';\n const originalOffset = getOffset(elem);\n if ('left' in offset || 'top' in offset) {\n originalTransition = getTransitionProperty(elem) || '';\n setTransitionProperty(elem, 'none');\n }\n if ('left' in offset) {\n elem.style[oppositeHorizontalProperty] = '';\n elem.style[horizontalProperty] = `${presetH}px`;\n }\n if ('top' in offset) {\n elem.style[oppositeVerticalProperty] = '';\n elem.style[verticalProperty] = `${presetV}px`;\n }\n // force relayout\n forceRelayout(elem);\n const old = getOffset(elem);\n const originalStyle = {};\n for (const key in offset) {\n if (offset.hasOwnProperty(key)) {\n const dir = getOffsetDirection(key, option);\n const preset = key === 'left' ? presetH : presetV;\n const off = originalOffset[key] - old[key];\n if (dir === key) {\n originalStyle[dir] = preset + off;\n } else {\n originalStyle[dir] = preset - off;\n }\n }\n }\n css(elem, originalStyle);\n // force relayout\n forceRelayout(elem);\n if ('left' in offset || 'top' in offset) {\n setTransitionProperty(elem, originalTransition);\n }\n const ret = {};\n for (const key in offset) {\n if (offset.hasOwnProperty(key)) {\n const dir = getOffsetDirection(key, option);\n const off = offset[key] - originalOffset[key];\n if (key === dir) {\n ret[dir] = originalStyle[dir] + off;\n } else {\n ret[dir] = originalStyle[dir] - off;\n }\n }\n }\n css(elem, ret);\n}\n\nfunction setTransform(elem, offset) {\n const originalOffset = getOffset(elem);\n const originalXY = getTransformXY(elem);\n const resultXY = { x: originalXY.x, y: originalXY.y };\n if ('left' in offset) {\n resultXY.x = originalXY.x + offset.left - originalOffset.left;\n }\n if ('top' in offset) {\n resultXY.y = originalXY.y + offset.top - originalOffset.top;\n }\n setTransformXY(elem, resultXY);\n}\n\nfunction setOffset(elem, offset, option) {\n if (option.ignoreShake) {\n const oriOffset = getOffset(elem);\n\n const oLeft = oriOffset.left.toFixed(0);\n const oTop = oriOffset.top.toFixed(0);\n const tLeft = offset.left.toFixed(0);\n const tTop = offset.top.toFixed(0);\n\n if (oLeft === tLeft && oTop === tTop) {\n return;\n }\n }\n\n if (option.useCssRight || option.useCssBottom) {\n setLeftTop(elem, offset, option);\n } else if (\n option.useCssTransform &&\n getTransformName() in document.body.style\n ) {\n setTransform(elem, offset, option);\n } else {\n setLeftTop(elem, offset, option);\n }\n}\n\nfunction each(arr, fn) {\n for (let i = 0; i < arr.length; i++) {\n fn(arr[i]);\n }\n}\n\nfunction isBorderBoxFn(elem) {\n return getComputedStyleX(elem, 'boxSizing') === 'border-box';\n}\n\nconst BOX_MODELS = ['margin', 'border', 'padding'];\nconst CONTENT_INDEX = -1;\nconst PADDING_INDEX = 2;\nconst BORDER_INDEX = 1;\nconst MARGIN_INDEX = 0;\n\nfunction swap(elem, options, callback) {\n const old = {};\n const style = elem.style;\n let name;\n\n // Remember the old values, and insert the new ones\n for (name in options) {\n if (options.hasOwnProperty(name)) {\n old[name] = style[name];\n style[name] = options[name];\n }\n }\n\n callback.call(elem);\n\n // Revert the old values\n for (name in options) {\n if (options.hasOwnProperty(name)) {\n style[name] = old[name];\n }\n }\n}\n\nfunction getPBMWidth(elem, props, which) {\n let value = 0;\n let prop;\n let j;\n let i;\n for (j = 0; j < props.length; j++) {\n prop = props[j];\n if (prop) {\n for (i = 0; i < which.length; i++) {\n let cssProp;\n if (prop === 'border') {\n cssProp = `${prop}${which[i]}Width`;\n } else {\n cssProp = prop + which[i];\n }\n value += parseFloat(getComputedStyleX(elem, cssProp)) || 0;\n }\n }\n }\n return value;\n}\n\nconst domUtils = {\n getParent(element) {\n let parent = element;\n do {\n if (parent.nodeType === 11 && parent.host) {\n parent = parent.host;\n } else {\n parent = parent.parentNode;\n }\n } while (parent && parent.nodeType !== 1 && parent.nodeType !== 9);\n return parent;\n },\n};\n\neach(['Width', 'Height'], name => {\n domUtils[`doc${name}`] = refWin => {\n const d = refWin.document;\n return Math.max(\n // firefox chrome documentElement.scrollHeight< body.scrollHeight\n // ie standard mode : documentElement.scrollHeight> body.scrollHeight\n d.documentElement[`scroll${name}`],\n // quirks : documentElement.scrollHeight 最大等于可视窗口多一点?\n d.body[`scroll${name}`],\n domUtils[`viewport${name}`](d),\n );\n };\n\n domUtils[`viewport${name}`] = win => {\n // pc browser includes scrollbar in window.innerWidth\n const prop = `client${name}`;\n const doc = win.document;\n const body = doc.body;\n const documentElement = doc.documentElement;\n const documentElementProp = documentElement[prop];\n // 标准模式取 documentElement\n // backcompat 取 body\n return (\n (doc.compatMode === 'CSS1Compat' && documentElementProp) ||\n (body && body[prop]) ||\n documentElementProp\n );\n };\n});\n\n/*\n 得到元素的大小信息\n @param elem\n @param name\n @param {String} [extra] 'padding' : (css width) + padding\n 'border' : (css width) + padding + border\n 'margin' : (css width) + padding + border + margin\n */\nfunction getWH(elem, name, ex) {\n let extra = ex;\n if (isWindow(elem)) {\n return name === 'width'\n ? domUtils.viewportWidth(elem)\n : domUtils.viewportHeight(elem);\n } else if (elem.nodeType === 9) {\n return name === 'width'\n ? domUtils.docWidth(elem)\n : domUtils.docHeight(elem);\n }\n const which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];\n let borderBoxValue =\n name === 'width'\n ? elem.getBoundingClientRect().width\n : elem.getBoundingClientRect().height;\n const computedStyle = getComputedStyleX(elem);\n const isBorderBox = isBorderBoxFn(elem, computedStyle);\n let cssBoxValue = 0;\n if (\n borderBoxValue === null ||\n borderBoxValue === undefined ||\n borderBoxValue <= 0\n ) {\n borderBoxValue = undefined;\n // Fall back to computed then un computed css if necessary\n cssBoxValue = getComputedStyleX(elem, name);\n if (\n cssBoxValue === null ||\n cssBoxValue === undefined ||\n Number(cssBoxValue) < 0\n ) {\n cssBoxValue = elem.style[name] || 0;\n }\n // Normalize '', auto, and prepare for extra\n cssBoxValue = parseFloat(cssBoxValue) || 0;\n }\n if (extra === undefined) {\n extra = isBorderBox ? BORDER_INDEX : CONTENT_INDEX;\n }\n const borderBoxValueOrIsBorderBox =\n borderBoxValue !== undefined || isBorderBox;\n const val = borderBoxValue || cssBoxValue;\n if (extra === CONTENT_INDEX) {\n if (borderBoxValueOrIsBorderBox) {\n return (\n val - getPBMWidth(elem, ['border', 'padding'], which, computedStyle)\n );\n }\n return cssBoxValue;\n } else if (borderBoxValueOrIsBorderBox) {\n if (extra === BORDER_INDEX) {\n return val;\n }\n return (\n val +\n (extra === PADDING_INDEX\n ? -getPBMWidth(elem, ['border'], which, computedStyle)\n : getPBMWidth(elem, ['margin'], which, computedStyle))\n );\n }\n return (\n cssBoxValue +\n getPBMWidth(elem, BOX_MODELS.slice(extra), which, computedStyle)\n );\n}\n\nconst cssShow = {\n position: 'absolute',\n visibility: 'hidden',\n display: 'block',\n};\n\n// fix #119 : https://github.com/kissyteam/kissy/issues/119\nfunction getWHIgnoreDisplay(...args) {\n let val;\n const elem = args[0];\n // in case elem is window\n // elem.offsetWidth === undefined\n if (elem.offsetWidth !== 0) {\n val = getWH.apply(undefined, args);\n } else {\n swap(elem, cssShow, () => {\n val = getWH.apply(undefined, args);\n });\n }\n return val;\n}\n\neach(['width', 'height'], name => {\n const first = name.charAt(0).toUpperCase() + name.slice(1);\n domUtils[`outer${first}`] = (el, includeMargin) => {\n return (\n el &&\n getWHIgnoreDisplay(el, name, includeMargin ? MARGIN_INDEX : BORDER_INDEX)\n );\n };\n const which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];\n\n domUtils[name] = (elem, v) => {\n let val = v;\n if (val !== undefined) {\n if (elem) {\n const computedStyle = getComputedStyleX(elem);\n const isBorderBox = isBorderBoxFn(elem);\n if (isBorderBox) {\n val += getPBMWidth(elem, ['padding', 'border'], which, computedStyle);\n }\n return css(elem, name, val);\n }\n return undefined;\n }\n return elem && getWHIgnoreDisplay(elem, name, CONTENT_INDEX);\n };\n});\n\nfunction mix(to, from) {\n for (const i in from) {\n if (from.hasOwnProperty(i)) {\n to[i] = from[i];\n }\n }\n return to;\n}\n\nconst utils = {\n getWindow(node) {\n if (node && node.document && node.setTimeout) {\n return node;\n }\n const doc = node.ownerDocument || node;\n return doc.defaultView || doc.parentWindow;\n },\n getDocument,\n offset(el, value, option) {\n if (typeof value !== 'undefined') {\n setOffset(el, value, option || {});\n } else {\n return getOffset(el);\n }\n },\n isWindow,\n each,\n css,\n clone(obj) {\n let i;\n const ret = {};\n for (i in obj) {\n if (obj.hasOwnProperty(i)) {\n ret[i] = obj[i];\n }\n }\n const overflow = obj.overflow;\n if (overflow) {\n for (i in obj) {\n if (obj.hasOwnProperty(i)) {\n ret.overflow[i] = obj.overflow[i];\n }\n }\n }\n return ret;\n },\n mix,\n getWindowScrollLeft(w) {\n return getScrollLeft(w);\n },\n getWindowScrollTop(w) {\n return getScrollTop(w);\n },\n merge(...args) {\n const ret = {};\n for (let i = 0; i < args.length; i++) {\n utils.mix(ret, args[i]);\n }\n return ret;\n },\n viewportWidth: 0,\n viewportHeight: 0,\n};\n\nmix(utils, domUtils);\n\nexport default utils;\n","/*\n Adapted from https://github.com/mapbox/lineclip to work with flat arrays\n and 3d positions\n\n ISC License\n\n Copyright (c) 2015, Mapbox\n\n Permission to use, copy, modify, and/or distribute this software for any purpose\n with or without fee is hereby granted, provided that the above copyright notice\n and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS\n OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n THIS SOFTWARE.\n\n */\n\n/* eslint-disable max-statements, max-depth */\n\nimport {push, copy, getPointAtIndex} from './utils';\n\n// Cohen-Sutherland line clipping algorithm, adapted to efficiently\n// handle polylines rather than just segments\nexport function clipPolyline(positions, bbox, options = {}) {\n const {size = 2, startIndex = 0, endIndex = positions.length} = options;\n const numPoints = (endIndex - startIndex) / size;\n const result = [];\n let part = [];\n let a;\n let b;\n let codeA = -1;\n let codeB;\n let lastCode;\n\n for (let i = 1; i < numPoints; i++) {\n a = getPointAtIndex(positions, i - 1, size, startIndex, a);\n b = getPointAtIndex(positions, i, size, startIndex, b);\n if (codeA < 0) {\n codeA = bitCode(a, bbox);\n }\n codeB = lastCode = bitCode(b, bbox);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (!(codeA | codeB)) {\n // accept\n push(part, a);\n\n if (codeB !== lastCode) {\n // segment went outside\n push(part, b);\n\n if (i < numPoints - 1) {\n // start a new line\n result.push(part);\n part = [];\n }\n } else if (i === numPoints - 1) {\n push(part, b);\n }\n break;\n } else if (codeA & codeB) {\n // trivial reject\n break;\n } else if (codeA) {\n // a outside, intersect with clip edge\n intersect(a, b, codeA, bbox, a);\n codeA = bitCode(a, bbox);\n } else {\n // b outside\n intersect(a, b, codeB, bbox, b);\n codeB = bitCode(b, bbox);\n }\n }\n\n codeA = lastCode;\n }\n\n if (part.length) result.push(part);\n\n return result;\n}\n\n// Sutherland-Hodgeman polygon clipping algorithm\n// polygon must be closed (first vertex == last vertex)\nexport function clipPolygon(positions, bbox, options = {}) {\n const {size = 2, endIndex = positions.length} = options;\n let {startIndex = 0} = options;\n let numPoints = (endIndex - startIndex) / size;\n let result;\n let p;\n let prev;\n let inside;\n let prevInside;\n\n // clip against each side of the clip rectangle\n for (let edge = 1; edge <= 8; edge *= 2) {\n result = [];\n prev = getPointAtIndex(positions, numPoints - 1, size, startIndex, prev);\n prevInside = !(bitCode(prev, bbox) & edge);\n\n for (let i = 0; i < numPoints; i++) {\n p = getPointAtIndex(positions, i, size, startIndex, p);\n inside = !(bitCode(p, bbox) & edge);\n\n // if segment goes through the clip window, add an intersection\n if (inside !== prevInside) push(result, intersect(prev, p, edge, bbox));\n\n if (inside) push(result, p); // add a point if it's inside\n\n copy(prev, p);\n prevInside = inside;\n }\n\n // close loop\n positions = result;\n startIndex = 0;\n numPoints = result.length / size;\n\n if (!numPoints) break;\n }\n\n return result;\n}\n\n// intersect a segment against one of the 4 lines that make up the bbox\n\nexport function intersect(a, b, edge, bbox, out = []) {\n let t;\n // Forces out[snapI] to be on the bbox edge\n // Interpolation introduces precision issue which may cause lineclip to be\n // stuck in an infinite loop\n let snap;\n if (edge & 8) {\n // top\n t = (bbox[3] - a[1]) / (b[1] - a[1]);\n snap = 3;\n } else if (edge & 4) {\n // bottom\n t = (bbox[1] - a[1]) / (b[1] - a[1]);\n snap = 1;\n } else if (edge & 2) {\n // right\n t = (bbox[2] - a[0]) / (b[0] - a[0]);\n snap = 2;\n } else if (edge & 1) {\n // left\n t = (bbox[0] - a[0]) / (b[0] - a[0]);\n snap = 0;\n } else {\n return null;\n }\n for (let i = 0; i < a.length; i++) {\n out[i] = (snap & 1) === i ? bbox[snap] : t * (b[i] - a[i]) + a[i];\n }\n return out;\n}\n\n// bit code reflects the point position relative to the bbox:\n\n// left mid right\n// top 1001 1000 1010\n// mid 0001 0000 0010\n// bottom 0101 0100 0110\n\nexport function bitCode(p, bbox) {\n let code = 0;\n\n if (p[0] < bbox[0]) code |= 1;\n // left\n else if (p[0] > bbox[2]) code |= 2; // right\n\n if (p[1] < bbox[1]) code |= 4;\n // bottom\n else if (p[1] > bbox[3]) code |= 8; // top\n\n return code;\n}\n","/* eslint-disable max-statements, max-depth, complexity, no-unused-expressions */\nimport {bitCode, intersect} from './lineclip';\nimport {getPointAtIndex, copy, push} from './utils';\n\nexport function cutPolylineByGrid(positions, options = {}) {\n const {\n size = 2,\n broken = false,\n gridResolution = 10,\n gridOffset = [0, 0],\n startIndex = 0,\n endIndex = positions.length\n } = options;\n const numPoints = (endIndex - startIndex) / size;\n let part = [];\n const result = [part];\n const a = getPointAtIndex(positions, 0, size, startIndex);\n let b;\n let codeB;\n const cell = getGridCell(a, gridResolution, gridOffset, []);\n const scratchPoint = [];\n push(part, a);\n\n for (let i = 1; i < numPoints; i++) {\n b = getPointAtIndex(positions, i, size, startIndex, b);\n codeB = bitCode(b, cell);\n\n while (codeB) {\n // find the intersection with the current cell\n intersect(a, b, codeB, cell, scratchPoint);\n const codeAlt = bitCode(scratchPoint, cell);\n if (codeAlt) {\n intersect(a, scratchPoint, codeAlt, cell, scratchPoint);\n codeB = codeAlt;\n }\n push(part, scratchPoint);\n // move to the next cell\n copy(a, scratchPoint);\n\n moveToNeighborCell(cell, gridResolution, codeB);\n if (broken && part.length > size) {\n part = [];\n result.push(part);\n push(part, a);\n }\n\n codeB = bitCode(b, cell);\n }\n\n push(part, b);\n copy(a, b);\n }\n\n return broken ? result : result[0];\n}\n\nconst TYPE_INSIDE = 0;\nconst TYPE_BORDER = 1;\n\nfunction concatInPlace(arr1, arr2) {\n for (let i = 0; i < arr2.length; i++) {\n arr1.push(arr2[i]);\n }\n return arr1;\n}\n\nexport function cutPolygonByGrid(positions, holeIndices, options = {}) {\n if (!positions.length) {\n // input is empty\n return [];\n }\n const {size = 2, gridResolution = 10, gridOffset = [0, 0], edgeTypes = false} = options;\n const result = [];\n const queue = [\n {\n pos: positions,\n types: edgeTypes && new Array(positions.length / size).fill(TYPE_BORDER),\n holes: holeIndices || []\n }\n ];\n const bbox = [[], []];\n let cell = [];\n\n // Recursively bisect polygon until every part fit in a single grid cell\n while (queue.length) {\n const {pos, types, holes} = queue.shift();\n\n // Get the bounding box of the outer polygon\n getBoundingBox(pos, size, holes[0] || pos.length, bbox);\n cell = getGridCell(bbox[0], gridResolution, gridOffset, cell);\n const code = bitCode(bbox[1], cell);\n\n if (code) {\n // Split the outer ring at the boundary\n let parts = bisectPolygon(pos, types, size, 0, holes[0] || pos.length, cell, code);\n const polygonLow = {pos: parts[0].pos, types: parts[0].types, holes: []};\n const polygonHigh = {pos: parts[1].pos, types: parts[1].types, holes: []};\n queue.push(polygonLow, polygonHigh);\n\n // Split each hole at the boundary\n for (let i = 0; i < holes.length; i++) {\n parts = bisectPolygon(pos, types, size, holes[i], holes[i + 1] || pos.length, cell, code);\n\n if (parts[0]) {\n polygonLow.holes.push(polygonLow.pos.length);\n polygonLow.pos = concatInPlace(polygonLow.pos, parts[0].pos);\n if (edgeTypes) {\n polygonLow.types = concatInPlace(polygonLow.types, parts[0].types);\n }\n }\n if (parts[1]) {\n polygonHigh.holes.push(polygonHigh.pos.length);\n polygonHigh.pos = concatInPlace(polygonHigh.pos, parts[1].pos);\n if (edgeTypes) {\n polygonHigh.types = concatInPlace(polygonHigh.types, parts[1].types);\n }\n }\n }\n } else {\n // Polygon fits in a single cell, no more processing required\n const polygon = {positions: pos};\n if (edgeTypes) {\n polygon.edgeTypes = types;\n }\n if (holes.length) {\n polygon.holeIndices = holes;\n }\n\n result.push(polygon);\n }\n }\n return result;\n}\n\n// edgeTypes:\n// TYPE_BORDER - edge from the original polygon\n// TYPE_INSIDE - inside the original polygon\n// eslint-disable-next-line max-params\nfunction bisectPolygon(positions, edgeTypes, size, startIndex, endIndex, bbox, edge) {\n const numPoints = (endIndex - startIndex) / size;\n const resultLow = [];\n const resultHigh = [];\n const typesLow = [];\n const typesHigh = [];\n const scratchPoint = [];\n\n let p;\n let side;\n let type;\n const prev = getPointAtIndex(positions, numPoints - 1, size, startIndex);\n let prevSide = Math.sign(edge & 8 ? prev[1] - bbox[3] : prev[0] - bbox[2]);\n let prevType = edgeTypes && edgeTypes[numPoints - 1];\n let lowPointCount = 0;\n let highPointCount = 0;\n\n for (let i = 0; i < numPoints; i++) {\n p = getPointAtIndex(positions, i, size, startIndex, p);\n side = Math.sign(edge & 8 ? p[1] - bbox[3] : p[0] - bbox[2]);\n type = edgeTypes && edgeTypes[startIndex / size + i];\n\n // if segment goes through the boundary, add an intersection\n if (side && prevSide && prevSide !== side) {\n intersect(prev, p, edge, bbox, scratchPoint);\n push(resultLow, scratchPoint) && typesLow.push(prevType);\n push(resultHigh, scratchPoint) && typesHigh.push(prevType);\n }\n\n if (side <= 0) {\n push(resultLow, p) && typesLow.push(type);\n lowPointCount -= side;\n } else if (typesLow.length) {\n typesLow[typesLow.length - 1] = TYPE_INSIDE;\n }\n if (side >= 0) {\n push(resultHigh, p) && typesHigh.push(type);\n highPointCount += side;\n } else if (typesHigh.length) {\n typesHigh[typesHigh.length - 1] = TYPE_INSIDE;\n }\n\n copy(prev, p);\n prevSide = side;\n prevType = type;\n }\n\n return [\n lowPointCount ? {pos: resultLow, types: edgeTypes && typesLow} : null,\n highPointCount ? {pos: resultHigh, types: edgeTypes && typesHigh} : null\n ];\n}\n\nfunction getGridCell(p, gridResolution, gridOffset, out) {\n const left = Math.floor((p[0] - gridOffset[0]) / gridResolution) * gridResolution + gridOffset[0];\n const bottom =\n Math.floor((p[1] - gridOffset[1]) / gridResolution) * gridResolution + gridOffset[1];\n out[0] = left;\n out[1] = bottom;\n out[2] = left + gridResolution;\n out[3] = bottom + gridResolution;\n return out;\n}\n\nfunction moveToNeighborCell(cell, gridResolution, edge) {\n if (edge & 8) {\n // top\n cell[1] += gridResolution;\n cell[3] += gridResolution;\n } else if (edge & 4) {\n // bottom\n cell[1] -= gridResolution;\n cell[3] -= gridResolution;\n } else if (edge & 2) {\n // right\n cell[0] += gridResolution;\n cell[2] += gridResolution;\n } else if (edge & 1) {\n // left\n cell[0] -= gridResolution;\n cell[2] -= gridResolution;\n }\n}\n\nfunction getBoundingBox(positions, size, endIndex, out) {\n let minX = Infinity;\n let maxX = -Infinity;\n let minY = Infinity;\n let maxY = -Infinity;\n\n for (let i = 0; i < endIndex; i += size) {\n const x = positions[i];\n const y = positions[i + 1];\n minX = x < minX ? x : minX;\n maxX = x > maxX ? x : maxX;\n minY = y < minY ? y : minY;\n maxY = y > maxY ? y : maxY;\n }\n\n out[0][0] = minX;\n out[0][1] = minY;\n out[1][0] = maxX;\n out[1][1] = maxY;\n return out;\n}\n","import {cutPolylineByGrid, cutPolygonByGrid} from './cut-by-grid';\nimport {getPointAtIndex, push} from './utils';\n\n// https://en.wikipedia.org/wiki/Web_Mercator_projection\nconst DEFAULT_MAX_LATITUDE = 85.051129;\n\n// https://user-images.githubusercontent.com/2059298/78465769-938b7a00-76ae-11ea-9b95-1f4c26425ab9.png\nexport function cutPolylineByMercatorBounds(positions, options = {}) {\n const {size = 2, startIndex = 0, endIndex = positions.length, normalize = true} = options;\n\n // Remap longitudes so that each segment takes the shorter path\n const newPositions = positions.slice(startIndex, endIndex);\n wrapLongitudesForShortestPath(newPositions, size, 0, endIndex - startIndex);\n\n const parts = cutPolylineByGrid(newPositions, {\n size,\n broken: true,\n gridResolution: 360,\n gridOffset: [-180, -180]\n });\n\n if (normalize) {\n // Each part is guaranteed to be in a single copy of the world\n // Map longitudes back to [-180, 180]\n for (const part of parts) {\n shiftLongitudesIntoRange(part, size);\n }\n }\n return parts;\n}\n\n// https://user-images.githubusercontent.com/2059298/78465770-94241080-76ae-11ea-809a-6a8534dac1d9.png\nexport function cutPolygonByMercatorBounds(positions, holeIndices, options = {}) {\n const {size = 2, normalize = true, edgeTypes = false} = options;\n holeIndices = holeIndices || [];\n const newPositions = [];\n const newHoleIndices = [];\n let srcStartIndex = 0;\n let targetIndex = 0;\n\n for (let ringIndex = 0; ringIndex <= holeIndices.length; ringIndex++) {\n // srcStartIndex/srcEndIndex define the ring in the original positions\n const srcEndIndex = holeIndices[ringIndex] || positions.length;\n // targetStartIndex/targetIndex define the ring in newPositions\n const targetStartIndex = targetIndex;\n\n // In case the ring contains a pole (e.g. Antarctica), we'll have to insert vertices\n // The insertion point is defined by the vertex closest to the pole\n // Split the the ring by the insertion point when copying to newPositions\n const splitIndex = findSplitIndex(positions, size, srcStartIndex, srcEndIndex);\n for (let i = splitIndex; i < srcEndIndex; i++) {\n newPositions[targetIndex++] = positions[i];\n }\n for (let i = srcStartIndex; i < splitIndex; i++) {\n newPositions[targetIndex++] = positions[i];\n }\n\n // Remap longitudes so that each segment takes the shorter path\n wrapLongitudesForShortestPath(newPositions, size, targetStartIndex, targetIndex);\n\n // Handle the case when the ring contains a pole\n insertPoleVertices(newPositions, size, targetStartIndex, targetIndex, options.maxLatitude);\n\n srcStartIndex = srcEndIndex;\n newHoleIndices[ringIndex] = targetIndex;\n }\n newHoleIndices.pop();\n\n const parts = cutPolygonByGrid(newPositions, newHoleIndices, {\n size,\n gridResolution: 360,\n gridOffset: [-180, -180],\n edgeTypes\n });\n\n if (normalize) {\n // Each part is guaranteed to be in a single copy of the world\n // Map longitudes back to [-180, 180]\n for (const part of parts) {\n shiftLongitudesIntoRange(part.positions, size);\n }\n }\n return parts;\n}\n\n/* Helpers */\n\n// See comments for insertPoleVertices\nfunction findSplitIndex(positions, size, startIndex, endIndex) {\n let maxLat = -1;\n let pointIndex = -1;\n for (let i = startIndex + 1; i < endIndex; i += size) {\n const lat = Math.abs(positions[i]);\n if (lat > maxLat) {\n maxLat = lat;\n pointIndex = i - 1;\n }\n }\n return pointIndex;\n}\n\n// https://user-images.githubusercontent.com/2059298/78857483-5987e400-79de-11ea-98fc-0631287a8431.png\n//\n// If the polygon contains a pole, to tesselate it correctly, we need to insert the edge\n// of map into the polygon. This requires adding two vertices that represent the pole, by\n// drawing a perpendicular line to the Mercator map edge from a selected vertex on the ring.\n//\n// We select the insertion position carefully so that the inserted line segments do not\n// intersect with the ring itself. This is ensured by findSplitIndex, which returns the\n// vertex closest to the pole.\nfunction insertPoleVertices(\n positions,\n size,\n startIndex,\n endIndex,\n maxLatitude = DEFAULT_MAX_LATITUDE\n) {\n // Check if the ring contains a pole\n const firstLng = positions[startIndex];\n const lastLng = positions[endIndex - size];\n if (Math.abs(firstLng - lastLng) > 180) {\n // The ring does not make a round trip\n // Add the nearest pole to the vertices so that the polygon tesselates correctly\n const p = getPointAtIndex(positions, 0, size, startIndex);\n // Copy the first vertex to the world of the last vertex\n p[0] += Math.round((lastLng - firstLng) / 360) * 360;\n push(positions, p);\n // Project the copied vertex to the edge of the map\n p[1] = Math.sign(p[1]) * maxLatitude;\n push(positions, p);\n // Project the first vertex to the edge of the map\n p[0] = firstLng;\n push(positions, p);\n }\n}\n\nfunction wrapLongitudesForShortestPath(positions, size, startIndex, endIndex) {\n let prevLng = positions[0];\n let lng;\n for (let i = startIndex; i < endIndex; i += size) {\n lng = positions[i];\n const delta = lng - prevLng;\n if (delta > 180 || delta < -180) {\n lng -= Math.round(delta / 360) * 360;\n }\n positions[i] = prevLng = lng;\n }\n}\n\nfunction shiftLongitudesIntoRange(positions, size) {\n let refLng;\n const pointCount = positions.length / size;\n\n // Find a longitude that is not on the edge of a world\n // Which we will use to determine which world copy it is\n for (let i = 0; i < pointCount; i++) {\n refLng = positions[i * size];\n if ((refLng + 180) % 360 !== 0) {\n break;\n }\n }\n\n const delta = -Math.round(refLng / 360) * 360;\n if (delta === 0) {\n return;\n }\n for (let i = 0; i < pointCount; i++) {\n positions[i * size] += delta;\n }\n}\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import setPrototypeOf from \"./setPrototypeOf\";\nimport isNativeReflectConstruct from \"./isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import {isWebGL2, assertWebGLContext} from '@luma.gl/gltools';\nimport {lumaStats} from '../init';\nimport {getKey, getKeyValue} from '../webgl-utils/constants-to-keys';\nimport {assert} from '../utils/assert';\nimport {uid} from '../utils/utils';\nimport {stubRemovedMethods} from '../utils/stub-methods';\n\nconst ERR_RESOURCE_METHOD_UNDEFINED = 'Resource subclass must define virtual methods';\n\n// TODO - Handle context loss\n// function glGetContextLossCount(gl) {\n// return (gl.luma && gl.luma.glCount) || 0;\n// }\n\nexport default class Resource {\n constructor(gl, opts = {}) {\n assertWebGLContext(gl);\n\n const {id, userData = {}} = opts;\n this.gl = gl;\n // @ts-ignore\n this.gl2 = gl;\n // this.ext = polyfillContext(gl);\n this.id = id || uid(this.constructor.name);\n this.userData = userData;\n this._bound = false;\n\n // Set the handle\n // If handle was provided, use it, otherwise create a new handle\n\n // TODO - Stores the handle with context loss information\n // this.glCount = glGetContextLossCount(this.gl);\n\n // Default VertexArray needs to be created with null handle, so compare against undefined\n this._handle = opts.handle;\n if (this._handle === undefined) {\n this._handle = this._createHandle();\n }\n\n // Only meaningful for resources that allocate GPU memory\n this.byteLength = 0;\n\n this._addStats();\n }\n\n toString() {\n return `${this.constructor.name}(${this.id})`;\n }\n\n get handle() {\n // TODO - Add context loss handling\n // Will regenerate and reinitialize the handle if necessary\n // const glCount = glGetContextLossCount(this.gl);\n // if (this.glCount !== glCount) {\n // this._handle = this._createHandle(this.opts);\n // this._glCount = glCount;\n // // Reinitialize object\n // this.initialize(this.opts);\n // }\n return this._handle;\n }\n\n delete({deleteChildren = false} = {}) {\n // Delete this object, and get refs to any children\n // @ts-ignore\n const children = this._handle && this._deleteHandle(this._handle);\n if (this._handle) {\n this._removeStats();\n }\n this._handle = null;\n\n // Optionally, recursively delete the children\n // @ts-ignore\n if (children && deleteChildren) {\n // @ts-ignore\n children.filter(Boolean).forEach(child => child.delete());\n }\n\n return this;\n }\n\n bind(funcOrHandle = this.handle) {\n if (typeof funcOrHandle !== 'function') {\n this._bindHandle(funcOrHandle);\n return this;\n }\n\n let value;\n\n if (!this._bound) {\n this._bindHandle(this.handle);\n this._bound = true;\n\n value = funcOrHandle();\n\n this._bound = false;\n this._bindHandle(null);\n } else {\n value = funcOrHandle();\n }\n\n return value;\n }\n\n unbind() {\n this.bind(null);\n }\n\n /**\n * Query a Resource parameter\n *\n * @param {GLenum} pname\n * @return {GLint|GLfloat|GLenum} param\n */\n getParameter(pname, opts = {}) {\n pname = getKeyValue(this.gl, pname);\n assert(pname);\n\n // @ts-ignore\n const parameters = this.constructor.PARAMETERS || {};\n\n // Use parameter definitions to handle unsupported parameters\n const parameter = parameters[pname];\n if (parameter) {\n const isWebgl2 = isWebGL2(this.gl);\n\n // Check if we can query for this parameter\n const parameterAvailable =\n (!('webgl2' in parameter) || isWebgl2) &&\n (!('extension' in parameter) || this.gl.getExtension(parameter.extension));\n\n if (!parameterAvailable) {\n const webgl1Default = parameter.webgl1;\n const webgl2Default = 'webgl2' in parameter ? parameter.webgl2 : parameter.webgl1;\n const defaultValue = isWebgl2 ? webgl2Default : webgl1Default;\n return defaultValue;\n }\n }\n\n // If unknown parameter - Could be a valid parameter not covered by PARAMS\n // Attempt to query for it and let WebGL report errors\n return this._getParameter(pname, opts);\n }\n\n // Many resources support a getParameter call -\n // getParameters will get all parameters - slow but useful for debugging\n // eslint-disable-next-line complexity\n getParameters(options = {}) {\n const {parameters, keys} = options;\n\n // Get parameter definitions for this Resource\n // @ts-ignore\n const PARAMETERS = this.constructor.PARAMETERS || {};\n\n const isWebgl2 = isWebGL2(this.gl);\n\n const values = {};\n\n // Query all parameters if no list provided\n const parameterKeys = parameters || Object.keys(PARAMETERS);\n\n // WEBGL limits\n for (const pname of parameterKeys) {\n const parameter = PARAMETERS[pname];\n\n // Check if this parameter is available on this platform\n const parameterAvailable =\n parameter &&\n (!('webgl2' in parameter) || isWebgl2) &&\n (!('extension' in parameter) || this.gl.getExtension(parameter.extension));\n\n if (parameterAvailable) {\n const key = keys ? getKey(this.gl, pname) : pname;\n values[key] = this.getParameter(pname, options);\n if (keys && parameter.type === 'GLenum') {\n values[key] = getKey(this.gl, values[key]);\n }\n }\n }\n\n return values;\n }\n\n /**\n * Update a Resource setting\n *\n * @todo - cache parameter to avoid issuing WebGL calls?\n *\n * @param {string} pname - parameter (GL constant, value or key)\n * @param {GLint|GLfloat|GLenum} value\n * @return {Resource} returns self to enable chaining\n */\n setParameter(pname, value) {\n pname = getKeyValue(this.gl, pname);\n assert(pname);\n\n // @ts-ignore\n const parameters = this.constructor.PARAMETERS || {};\n\n const parameter = parameters[pname];\n if (parameter) {\n const isWebgl2 = isWebGL2(this.gl);\n\n // Check if this parameter is available on this platform\n const parameterAvailable =\n (!('webgl2' in parameter) || isWebgl2) &&\n (!('extension' in parameter) || this.gl.getExtension(parameter.extension));\n\n if (!parameterAvailable) {\n throw new Error('Parameter not available on this platform');\n }\n\n // Handle string keys\n if (parameter.type === 'GLenum') {\n value = getKeyValue(value);\n }\n }\n\n // If unknown parameter - Could be a valid parameter not covered by PARAMS\n // attempt to set it and let WebGL report errors\n this._setParameter(pname, value);\n return this;\n }\n\n /*\n * Batch update resource parameters\n * Assumes the subclass supports a setParameter call\n */\n setParameters(parameters) {\n for (const pname in parameters) {\n this.setParameter(pname, parameters[pname]);\n }\n return this;\n }\n\n // Install stubs for removed methods\n stubRemovedMethods(className, version, methodNames) {\n return stubRemovedMethods(this, className, version, methodNames);\n }\n\n // PUBLIC VIRTUAL METHODS\n initialize(opts) {}\n\n // PROTECTED METHODS - These must be overridden by subclass\n _createHandle() {\n throw new Error(ERR_RESOURCE_METHOD_UNDEFINED);\n }\n\n _deleteHandle() {\n throw new Error(ERR_RESOURCE_METHOD_UNDEFINED);\n }\n\n _bindHandle(handle) {\n throw new Error(ERR_RESOURCE_METHOD_UNDEFINED);\n }\n\n _getOptsFromHandle() {\n throw new Error(ERR_RESOURCE_METHOD_UNDEFINED);\n }\n\n /** @returns {number} */\n _getParameter(pname, opts) {\n throw new Error(ERR_RESOURCE_METHOD_UNDEFINED);\n }\n\n _setParameter(pname, value) {\n throw new Error(ERR_RESOURCE_METHOD_UNDEFINED);\n }\n\n // PRIVATE METHODS\n\n _context() {\n this.gl.luma = this.gl.luma || {};\n return this.gl.luma;\n }\n\n _addStats() {\n const name = this.constructor.name;\n const stats = lumaStats.get('Resource Counts');\n\n stats.get('Resources Created').incrementCount();\n stats.get(`${name}s Created`).incrementCount();\n stats.get(`${name}s Active`).incrementCount();\n }\n\n _removeStats() {\n const name = this.constructor.name;\n const stats = lumaStats.get('Resource Counts');\n\n stats.get(`${name}s Active`).decrementCount();\n }\n\n _trackAllocatedMemory(bytes, name = this.constructor.name) {\n const stats = lumaStats.get('Memory Usage');\n\n stats.get('GPU Memory').addCount(bytes);\n stats.get(`${name} Memory`).addCount(bytes);\n this.byteLength = bytes;\n }\n\n _trackDeallocatedMemory(name = this.constructor.name) {\n const stats = lumaStats.get('Memory Usage');\n\n stats.get('GPU Memory').subtractCount(this.byteLength);\n stats.get(`${name} Memory`).subtractCount(this.byteLength);\n this.byteLength = 0;\n }\n}\n","\"use strict\";\n\nexports.__esModule = true;\n\nvar _assign = require(\"../core-js/object/assign\");\n\nvar _assign2 = _interopRequireDefault(_assign);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = _assign2.default || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};","import * as glMatrix from \"./common.js\";\n/**\r\n * 4 Dimensional Vector\r\n * @module vec4\r\n */\n\n/**\r\n * Creates a new, empty vec4\r\n *\r\n * @returns {vec4} a new 4D vector\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n }\n\n return out;\n}\n/**\r\n * Creates a new vec4 initialized with values from an existing vector\r\n *\r\n * @param {ReadonlyVec4} a vector to clone\r\n * @returns {vec4} a new 4D vector\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\r\n * Creates a new vec4 initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {vec4} a new 4D vector\r\n */\n\nexport function fromValues(x, y, z, w) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\r\n * Copy the values from one vec4 to another\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the source vector\r\n * @returns {vec4} out\r\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\r\n * Set the components of a vec4 to the given values\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {vec4} out\r\n */\n\nexport function set(out, x, y, z, w) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\r\n * Adds two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n/**\r\n * Multiplies two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n out[3] = a[3] * b[3];\n return out;\n}\n/**\r\n * Divides two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n out[3] = a[3] / b[3];\n return out;\n}\n/**\r\n * Math.ceil the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a vector to ceil\r\n * @returns {vec4} out\r\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n out[3] = Math.ceil(a[3]);\n return out;\n}\n/**\r\n * Math.floor the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a vector to floor\r\n * @returns {vec4} out\r\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n out[3] = Math.floor(a[3]);\n return out;\n}\n/**\r\n * Returns the minimum of two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n out[3] = Math.min(a[3], b[3]);\n return out;\n}\n/**\r\n * Returns the maximum of two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @returns {vec4} out\r\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n out[3] = Math.max(a[3], b[3]);\n return out;\n}\n/**\r\n * Math.round the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a vector to round\r\n * @returns {vec4} out\r\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n out[3] = Math.round(a[3]);\n return out;\n}\n/**\r\n * Scales a vec4 by a scalar number\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec4} out\r\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n/**\r\n * Adds two vec4's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec4} out\r\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n/**\r\n * Calculates the euclidian distance between two vec4's\r\n *\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @returns {Number} distance between a and b\r\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\r\n * Calculates the squared euclidian distance between two vec4's\r\n *\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @returns {Number} squared distance between a and b\r\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\r\n * Calculates the length of a vec4\r\n *\r\n * @param {ReadonlyVec4} a vector to calculate length of\r\n * @returns {Number} length of a\r\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\r\n * Calculates the squared length of a vec4\r\n *\r\n * @param {ReadonlyVec4} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\r\n * Negates the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a vector to negate\r\n * @returns {vec4} out\r\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = -a[3];\n return out;\n}\n/**\r\n * Returns the inverse of the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a vector to invert\r\n * @returns {vec4} out\r\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n out[3] = 1.0 / a[3];\n return out;\n}\n/**\r\n * Normalize a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a vector to normalize\r\n * @returns {vec4} out\r\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n var len = x * x + y * y + z * z + w * w;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = x * len;\n out[1] = y * len;\n out[2] = z * len;\n out[3] = w * len;\n return out;\n}\n/**\r\n * Calculates the dot product of two vec4's\r\n *\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @returns {Number} dot product of a and b\r\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n/**\r\n * Returns the cross-product of three vectors in a 4-dimensional space\r\n *\r\n * @param {ReadonlyVec4} result the receiving vector\r\n * @param {ReadonlyVec4} U the first vector\r\n * @param {ReadonlyVec4} V the second vector\r\n * @param {ReadonlyVec4} W the third vector\r\n * @returns {vec4} result\r\n */\n\nexport function cross(out, u, v, w) {\n var A = v[0] * w[1] - v[1] * w[0],\n B = v[0] * w[2] - v[2] * w[0],\n C = v[0] * w[3] - v[3] * w[0],\n D = v[1] * w[2] - v[2] * w[1],\n E = v[1] * w[3] - v[3] * w[1],\n F = v[2] * w[3] - v[3] * w[2];\n var G = u[0];\n var H = u[1];\n var I = u[2];\n var J = u[3];\n out[0] = H * F - I * E + J * D;\n out[1] = -(G * F) + I * C - J * B;\n out[2] = G * E - H * C + J * A;\n out[3] = -(G * D) + H * B - I * A;\n return out;\n}\n/**\r\n * Performs a linear interpolation between two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the first operand\r\n * @param {ReadonlyVec4} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec4} out\r\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n var aw = a[3];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n out[3] = aw + t * (b[3] - aw);\n return out;\n}\n/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\r\n * @returns {vec4} out\r\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a\n // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n // http://projecteuclid.org/euclid.aoms/1177692644;\n\n var v1, v2, v3, v4;\n var s1, s2;\n\n do {\n v1 = glMatrix.RANDOM() * 2 - 1;\n v2 = glMatrix.RANDOM() * 2 - 1;\n s1 = v1 * v1 + v2 * v2;\n } while (s1 >= 1);\n\n do {\n v3 = glMatrix.RANDOM() * 2 - 1;\n v4 = glMatrix.RANDOM() * 2 - 1;\n s2 = v3 * v3 + v4 * v4;\n } while (s2 >= 1);\n\n var d = Math.sqrt((1 - s1) / s2);\n out[0] = scale * v1;\n out[1] = scale * v2;\n out[2] = scale * v3 * d;\n out[3] = scale * v4 * d;\n return out;\n}\n/**\r\n * Transforms the vec4 with a mat4.\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the vector to transform\r\n * @param {ReadonlyMat4} m matrix to transform with\r\n * @returns {vec4} out\r\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n return out;\n}\n/**\r\n * Transforms the vec4 with a quat\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {ReadonlyVec4} a the vector to transform\r\n * @param {ReadonlyQuat} q quaternion to transform with\r\n * @returns {vec4} out\r\n */\n\nexport function transformQuat(out, a, q) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3]; // calculate quat * vec\n\n var ix = qw * x + qy * z - qz * y;\n var iy = qw * y + qz * x - qx * z;\n var iz = qw * z + qx * y - qy * x;\n var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat\n\n out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n out[3] = a[3];\n return out;\n}\n/**\r\n * Set the components of a vec4 to zero\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @returns {vec4} out\r\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n return out;\n}\n/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {ReadonlyVec4} a vector to represent as a string\r\n * @returns {String} string representation of the vector\r\n */\n\nexport function str(a) {\n return \"vec4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\r\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {ReadonlyVec4} a The first vector.\r\n * @param {ReadonlyVec4} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {ReadonlyVec4} a The first vector.\r\n * @param {ReadonlyVec4} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n/**\r\n * Alias for {@link vec4.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec4.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec4.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec4.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec4.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec4.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec4.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec4s.\r\n *\r\n * @param {Array} a the array of vectors to iterate over\r\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\r\n * @param {Number} offset Number of elements to skip at the beginning of the array\r\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\r\n * @param {Function} fn Function to call for each vector in the array\r\n * @param {Object} [arg] additional argument to pass to fn\r\n * @returns {Array} a\r\n * @function\r\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 4;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n vec[3] = a[i + 3];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n a[i + 3] = vec[3];\n }\n\n return a;\n };\n}();","function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n \"default\": obj\n };\n}\n\nmodule.exports = _interopRequireDefault;","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport log from '../utils/log';\nimport {createMat4, getCameraPosition, getFrustumPlanes} from '../utils/math-utils';\n\nimport {Matrix4, Vector3, equals} from 'math.gl';\nimport * as mat4 from 'gl-matrix/mat4';\n\nimport {\n getDistanceScales,\n getMeterZoom,\n lngLatToWorld,\n worldToLngLat,\n worldToPixels,\n pixelsToWorld\n} from '@math.gl/web-mercator';\n\nimport {PROJECTION_MODE} from '../lib/constants';\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\nconst IDENTITY = createMat4();\n\nconst ZERO_VECTOR = [0, 0, 0];\n\nconst DEFAULT_ZOOM = 0;\n\nconst DEFAULT_DISTANCE_SCALES = {\n unitsPerMeter: [1, 1, 1],\n metersPerUnit: [1, 1, 1]\n};\n\nexport default class Viewport {\n /**\n * @classdesc\n * Manages coordinate system transformations for deck.gl.\n *\n * Note: The Viewport is immutable in the sense that it only has accessors.\n * A new viewport instance should be created if any parameters have changed.\n */\n constructor(opts = {}) {\n const {\n id = null,\n // Window width/height in pixels (for pixel projection)\n x = 0,\n y = 0,\n width = 1,\n height = 1\n } = opts;\n\n this.id = id || this.constructor.displayName || 'viewport';\n\n this.x = x;\n this.y = y;\n // Silently allow apps to send in w,h = 0,0\n this.width = width || 1;\n this.height = height || 1;\n this._frustumPlanes = {};\n\n this._initViewMatrix(opts);\n this._initProjectionMatrix(opts);\n this._initPixelMatrices();\n\n // Bind methods for easy access\n this.equals = this.equals.bind(this);\n this.project = this.project.bind(this);\n this.unproject = this.unproject.bind(this);\n this.projectPosition = this.projectPosition.bind(this);\n this.unprojectPosition = this.unprojectPosition.bind(this);\n this.projectFlat = this.projectFlat.bind(this);\n this.unprojectFlat = this.unprojectFlat.bind(this);\n }\n\n get metersPerPixel() {\n return this.distanceScales.metersPerUnit[2] / this.scale;\n }\n\n get projectionMode() {\n if (this.isGeospatial) {\n return this.zoom < 12\n ? PROJECTION_MODE.WEB_MERCATOR\n : PROJECTION_MODE.WEB_MERCATOR_AUTO_OFFSET;\n }\n return PROJECTION_MODE.IDENTITY;\n }\n\n // Two viewports are equal if width and height are identical, and if\n // their view and projection matrices are (approximately) equal.\n equals(viewport) {\n if (!(viewport instanceof Viewport)) {\n return false;\n }\n if (this === viewport) {\n return true;\n }\n\n return (\n viewport.width === this.width &&\n viewport.height === this.height &&\n viewport.scale === this.scale &&\n equals(viewport.projectionMatrix, this.projectionMatrix) &&\n equals(viewport.viewMatrix, this.viewMatrix)\n );\n // TODO - check distance scales?\n }\n\n /**\n * Projects xyz (possibly latitude and longitude) to pixel coordinates in window\n * using viewport projection parameters\n * - [longitude, latitude] to [x, y]\n * - [longitude, latitude, Z] => [x, y, z]\n * Note: By default, returns top-left coordinates for canvas/SVG type render\n *\n * @param {Array} lngLatZ - [lng, lat] or [lng, lat, Z]\n * @param {Object} opts - options\n * @param {Object} opts.topLeft=true - Whether projected coords are top left\n * @return {Array} - [x, y] or [x, y, z] in top left coords\n */\n project(xyz, {topLeft = true} = {}) {\n const worldPosition = this.projectPosition(xyz);\n const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix);\n\n const [x, y] = coord;\n const y2 = topLeft ? y : this.height - y;\n return xyz.length === 2 ? [x, y2] : [x, y2, coord[2]];\n }\n\n /**\n * Unproject pixel coordinates on screen onto world coordinates,\n * (possibly [lon, lat]) on map.\n * - [x, y] => [lng, lat]\n * - [x, y, z] => [lng, lat, Z]\n * @param {Array} xyz -\n * @param {Object} opts - options\n * @param {Object} opts.topLeft=true - Whether origin is top left\n * @return {Array|null} - [lng, lat, Z] or [X, Y, Z]\n */\n unproject(xyz, {topLeft = true, targetZ} = {}) {\n const [x, y, z] = xyz;\n\n const y2 = topLeft ? y : this.height - y;\n const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2];\n const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld);\n const [X, Y, Z] = this.unprojectPosition(coord);\n\n if (Number.isFinite(z)) {\n return [X, Y, Z];\n }\n return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y];\n }\n\n // NON_LINEAR PROJECTION HOOKS\n // Used for web meractor projection\n\n projectPosition(xyz) {\n const [X, Y] = this.projectFlat(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2];\n return [X, Y, Z];\n }\n\n unprojectPosition(xyz) {\n const [X, Y] = this.unprojectFlat(xyz);\n const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2];\n return [X, Y, Z];\n }\n\n /**\n * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.\n * Performs the nonlinear part of the web mercator projection.\n * Remaining projection is done with 4x4 matrices which also handles\n * perspective.\n * @param {Array} lngLat - [lng, lat] coordinates\n * Specifies a point on the sphere to project onto the map.\n * @return {Array} [x,y] coordinates.\n */\n projectFlat(xyz) {\n if (this.isGeospatial) {\n return lngLatToWorld(xyz);\n }\n return xyz;\n }\n\n /**\n * Unproject world point [x,y] on map onto {lat, lon} on sphere\n * @param {object|Vector} xy - object with {x,y} members\n * representing point on projected map plane\n * @return {GeoCoordinates} - object with {lat,lon} of point on sphere.\n * Has toArray method if you need a GeoJSON Array.\n * Per cartographic tradition, lat and lon are specified as degrees.\n */\n unprojectFlat(xyz) {\n if (this.isGeospatial) {\n return worldToLngLat(xyz);\n }\n return xyz;\n }\n\n getBounds(options = {}) {\n const unprojectOption = {targetZ: options.z || 0};\n\n const topLeft = this.unproject([0, 0], unprojectOption);\n const topRight = this.unproject([this.width, 0], unprojectOption);\n const bottomLeft = this.unproject([0, this.height], unprojectOption);\n const bottomRight = this.unproject([this.width, this.height], unprojectOption);\n\n return [\n Math.min(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]),\n Math.min(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1]),\n Math.max(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]),\n Math.max(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1])\n ];\n }\n\n getDistanceScales(coordinateOrigin = null) {\n if (coordinateOrigin) {\n return getDistanceScales({\n longitude: coordinateOrigin[0],\n latitude: coordinateOrigin[1],\n highPrecision: true\n });\n }\n return this.distanceScales;\n }\n\n containsPixel({x, y, width = 1, height = 1}) {\n return (\n x < this.x + this.width &&\n this.x < x + width &&\n y < this.y + this.height &&\n this.y < y + height\n );\n }\n\n // Extract frustum planes in common space\n getFrustumPlanes() {\n if (this._frustumPlanes.near) {\n return this._frustumPlanes;\n }\n\n Object.assign(this._frustumPlanes, getFrustumPlanes(this.viewProjectionMatrix));\n\n return this._frustumPlanes;\n }\n\n // EXPERIMENTAL METHODS\n\n /**\n * Needed by panning and linear transition\n * Pan the viewport to place a given world coordinate at screen point [x, y]\n *\n * @param {Array} coords - world coordinates\n * @param {Array} pixel - [x,y] coordinates on screen\n * @return {Object} props of the new viewport\n */\n panByPosition(coords, pixel) {\n return null;\n }\n\n getCameraPosition() {\n return this.cameraPosition;\n }\n\n getCameraDirection() {\n return this.cameraDirection;\n }\n\n getCameraUp() {\n return this.cameraUp;\n }\n\n // INTERNAL METHODS\n\n _createProjectionMatrix({orthographic, fovyRadians, aspect, focalDistance, near, far}) {\n return orthographic\n ? new Matrix4().orthographic({fovy: fovyRadians, aspect, focalDistance, near, far})\n : new Matrix4().perspective({fovy: fovyRadians, aspect, near, far});\n }\n\n /* eslint-disable complexity, max-statements */\n _initViewMatrix(opts) {\n const {\n // view matrix\n viewMatrix = IDENTITY,\n\n longitude = null, // Anchor: lng lat zoom makes viewport work w/ geospatial coordinate systems\n latitude = null,\n zoom = null,\n\n position = null, // Anchor position offset (in meters for geospatial viewports)\n modelMatrix = null, // A model matrix to be applied to position, to match the layer props API\n focalDistance = 1, // Only needed for orthographic views\n\n distanceScales = null\n } = opts;\n\n // Check if we have a geospatial anchor\n this.isGeospatial = Number.isFinite(latitude) && Number.isFinite(longitude);\n\n this.zoom = zoom;\n if (!Number.isFinite(this.zoom)) {\n this.zoom = this.isGeospatial\n ? getMeterZoom({latitude}) + Math.log2(focalDistance)\n : DEFAULT_ZOOM;\n }\n const scale = Math.pow(2, this.zoom);\n this.scale = scale;\n\n // Calculate distance scales if lng/lat/zoom are provided\n this.distanceScales = this.isGeospatial\n ? getDistanceScales({latitude, longitude})\n : distanceScales || DEFAULT_DISTANCE_SCALES;\n\n this.focalDistance = focalDistance;\n\n this.distanceScales.metersPerUnit = new Vector3(this.distanceScales.metersPerUnit);\n this.distanceScales.unitsPerMeter = new Vector3(this.distanceScales.unitsPerMeter);\n\n this.position = ZERO_VECTOR;\n this.meterOffset = ZERO_VECTOR;\n if (position) {\n // Apply model matrix if supplied\n this.position = position;\n this.modelMatrix = modelMatrix;\n this.meterOffset = modelMatrix ? modelMatrix.transformVector(position) : position;\n }\n\n if (this.isGeospatial) {\n // Determine camera center\n this.longitude = longitude;\n this.latitude = latitude;\n this.center = this._getCenterInWorld({longitude, latitude});\n } else {\n this.center = position ? this.projectPosition(position) : [0, 0, 0];\n }\n this.viewMatrixUncentered = viewMatrix;\n // Make a centered version of the matrix for projection modes without an offset\n this.viewMatrix = new Matrix4()\n // Apply the uncentered view matrix\n .multiplyRight(this.viewMatrixUncentered)\n // And center it\n .translate(new Vector3(this.center || ZERO_VECTOR).negate());\n }\n /* eslint-enable complexity, max-statements */\n\n _getCenterInWorld({longitude, latitude}) {\n const {meterOffset, distanceScales} = this;\n\n // Make a centered version of the matrix for projection modes without an offset\n const center = new Vector3(this.projectPosition([longitude, latitude, 0]));\n\n if (meterOffset) {\n const commonPosition = new Vector3(meterOffset)\n // Convert to pixels in current zoom\n .scale(distanceScales.unitsPerMeter);\n center.add(commonPosition);\n }\n\n return center;\n }\n\n _initProjectionMatrix(opts) {\n const {\n // Projection matrix\n projectionMatrix = null,\n\n // Projection matrix parameters, used if projectionMatrix not supplied\n orthographic = false,\n fovyRadians,\n fovy = 75,\n near = 0.1, // Distance of near clipping plane\n far = 1000, // Distance of far clipping plane\n focalDistance = 1\n } = opts;\n\n this.projectionMatrix =\n projectionMatrix ||\n this._createProjectionMatrix({\n orthographic,\n fovyRadians: fovyRadians || fovy * DEGREES_TO_RADIANS,\n aspect: this.width / this.height,\n focalDistance,\n near,\n far\n });\n }\n\n _initPixelMatrices() {\n // Note: As usual, matrix operations should be applied in \"reverse\" order\n // since vectors will be multiplied in from the right during transformation\n const vpm = createMat4();\n mat4.multiply(vpm, vpm, this.projectionMatrix);\n mat4.multiply(vpm, vpm, this.viewMatrix);\n this.viewProjectionMatrix = vpm;\n\n // console.log('VPM', this.viewMatrix, this.projectionMatrix, this.viewProjectionMatrix);\n\n // Calculate inverse view matrix\n this.viewMatrixInverse = mat4.invert([], this.viewMatrix) || this.viewMatrix;\n\n // Decompose camera parameters\n this.cameraPosition = getCameraPosition(this.viewMatrixInverse);\n\n /*\n * Builds matrices that converts preprojected lngLats to screen pixels\n * and vice versa.\n * Note: Currently returns bottom-left coordinates!\n * Note: Starts with the GL projection matrix and adds steps to the\n * scale and translate that matrix onto the window.\n * Note: WebGL controls clip space to screen projection with gl.viewport\n * and does not need this step.\n */\n\n // matrix for conversion from world location to screen (pixel) coordinates\n const viewportMatrix = createMat4(); // matrix from NDC to viewport.\n const pixelProjectionMatrix = createMat4(); // matrix from world space to viewport.\n mat4.scale(viewportMatrix, viewportMatrix, [this.width / 2, -this.height / 2, 1]);\n mat4.translate(viewportMatrix, viewportMatrix, [1, -1, 0]);\n mat4.multiply(pixelProjectionMatrix, viewportMatrix, this.viewProjectionMatrix);\n this.pixelProjectionMatrix = pixelProjectionMatrix;\n this.viewportMatrix = viewportMatrix;\n\n this.pixelUnprojectionMatrix = mat4.invert(createMat4(), this.pixelProjectionMatrix);\n if (!this.pixelUnprojectionMatrix) {\n log.warn('Pixel project matrix not invertible')();\n // throw new Error('Pixel project matrix not invertible');\n }\n }\n}\n\nViewport.displayName = 'Viewport';\n","\"use strict\";\n\nexports.__esModule = true;\n\nvar _defineProperty = require(\"../core-js/object/define-property\");\n\nvar _defineProperty2 = _interopRequireDefault(_defineProperty);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = function (obj, key, value) {\n if (key in obj) {\n (0, _defineProperty2.default)(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n};","import destination from '@turf/destination';\nimport bearing from '@turf/bearing';\nimport pointToLineDistance from '@turf/point-to-line-distance';\nimport { point } from '@turf/helpers';\nimport {\n Position,\n Point,\n LineString,\n FeatureOf,\n FeatureWithProps,\n Viewport,\n} from '@nebula.gl/edit-modes';\nimport WebMercatorViewport from 'viewport-mercator-project';\n\n// TODO edit-modes: delete and use edit-modes/utils instead\n\nexport type NearestPointType = FeatureWithProps;\n\nexport function toDeckColor(\n color?: [number, number, number, number] | number,\n defaultColor: [number, number, number, number] = [255, 0, 0, 255]\n): [number, number, number, number] {\n if (!Array.isArray(color)) {\n return defaultColor;\n }\n return [color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255];\n}\n\n//\n// a GeoJSON helper function that calls the provided function with\n// an argument that is the most deeply-nested array having elements\n// that are arrays of primitives as an argument, e.g.\n//\n// {\n// \"type\": \"MultiPolygon\",\n// \"coordinates\": [\n// [\n// [[30, 20], [45, 40], [10, 40], [30, 20]]\n// ],\n// [\n// [[15, 5], [40, 10], [10, 20], [5, 10], [15, 5]]\n// ]\n// ]\n// }\n//\n// the function would be called on:\n//\n// [[30, 20], [45, 40], [10, 40], [30, 20]]\n//\n// and\n//\n// [[15, 5], [40, 10], [10, 20], [5, 10], [15, 5]]\n//\nexport function recursivelyTraverseNestedArrays(\n array: Array,\n prefix: Array,\n fn: Function\n) {\n if (!Array.isArray(array[0])) {\n return true;\n }\n for (let i = 0; i < array.length; i++) {\n if (recursivelyTraverseNestedArrays(array[i], [...prefix, i], fn)) {\n fn(array, prefix);\n break;\n }\n }\n return false;\n}\n\nexport function generatePointsParallelToLinePoints(\n p1: Position,\n p2: Position,\n groundCoords: Position\n): Position[] {\n const lineString: LineString = {\n type: 'LineString',\n coordinates: [p1, p2],\n };\n const pt = point(groundCoords);\n const ddistance = pointToLineDistance(pt, lineString);\n const lineBearing = bearing(p1, p2);\n\n // Check if current point is to the left or right of line\n // Line from A=(x1,y1) to B=(x2,y2) a point P=(x,y)\n // then (x−x1)(y2−y1)−(y−y1)(x2−x1)\n const isPointToLeftOfLine =\n (groundCoords[0] - p1[0]) * (p2[1] - p1[1]) - (groundCoords[1] - p1[1]) * (p2[0] - p1[0]);\n\n // Bearing to draw perpendicular to the line string\n const orthogonalBearing = isPointToLeftOfLine < 0 ? lineBearing - 90 : lineBearing - 270;\n\n // Get coordinates for the point p3 and p4 which are perpendicular to the lineString\n // Add the distance as the current position moves away from the lineString\n const p3 = destination(p2, ddistance, orthogonalBearing);\n const p4 = destination(p1, ddistance, orthogonalBearing);\n //@ts-ignore\n return [p3.geometry.coordinates, p4.geometry.coordinates];\n}\n\nexport function distance2d(x1: number, y1: number, x2: number, y2: number): number {\n const dx = x1 - x2;\n const dy = y1 - y2;\n return Math.sqrt(dx * dx + dy * dy);\n}\n\nexport function mix(a: number, b: number, ratio: number): number {\n return b * ratio + a * (1 - ratio);\n}\n\nexport function nearestPointOnProjectedLine(\n line: FeatureOf,\n inPoint: FeatureOf,\n viewport: Viewport\n): NearestPointType {\n const wmViewport = new WebMercatorViewport(viewport);\n // Project the line to viewport, then find the nearest point\n const coordinates: Array> = line.geometry.coordinates as any;\n const projectedCoords = coordinates.map(([x, y, z = 0]) => wmViewport.project([x, y, z]));\n //@ts-ignore\n const [x, y] = wmViewport.project(inPoint.geometry.coordinates);\n // console.log('projectedCoords', JSON.stringify(projectedCoords));\n\n let minDistance = Infinity;\n let minPointInfo = {};\n\n projectedCoords.forEach(([x2, y2], index) => {\n if (index === 0) {\n return;\n }\n\n const [x1, y1] = projectedCoords[index - 1];\n\n // line from projectedCoords[index - 1] to projectedCoords[index]\n // convert to Ax + By + C = 0\n const A = y1 - y2;\n const B = x2 - x1;\n const C = x1 * y2 - x2 * y1;\n\n // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line\n const div = A * A + B * B;\n const distance = Math.abs(A * x + B * y + C) / Math.sqrt(div);\n\n // TODO: Check if inside bounds\n\n if (distance < minDistance) {\n minDistance = distance;\n minPointInfo = {\n index,\n x0: (B * (B * x - A * y) - A * C) / div,\n y0: (A * (-B * x + A * y) - B * C) / div,\n };\n }\n });\n //@ts-ignore\n const { index, x0, y0 } = minPointInfo;\n const [x1, y1, z1 = 0] = projectedCoords[index - 1];\n const [x2, y2, z2 = 0] = projectedCoords[index];\n\n // calculate what ratio of the line we are on to find the proper z\n const lineLength = distance2d(x1, y1, x2, y2);\n const startToPointLength = distance2d(x1, y1, x0, y0);\n const ratio = startToPointLength / lineLength;\n const z0 = mix(z1, z2, ratio);\n\n return {\n type: 'Feature',\n geometry: {\n type: 'Point',\n coordinates: wmViewport.unproject([x0, y0, z0]),\n },\n properties: {\n // TODO: calculate the distance in proper units\n dist: minDistance,\n index: index - 1,\n },\n };\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nfunction componentWillMount() {\n // Call this.constructor.gDSFP to support sub-classes.\n var state = this.constructor.getDerivedStateFromProps(this.props, this.state);\n if (state !== null && state !== undefined) {\n this.setState(state);\n }\n}\n\nfunction componentWillReceiveProps(nextProps) {\n // Call this.constructor.gDSFP to support sub-classes.\n // Use the setState() updater to ensure state isn't stale in certain edge cases.\n function updater(prevState) {\n var state = this.constructor.getDerivedStateFromProps(nextProps, prevState);\n return state !== null && state !== undefined ? state : null;\n }\n // Binding \"this\" is important for shallow renderer support.\n this.setState(updater.bind(this));\n}\n\nfunction componentWillUpdate(nextProps, nextState) {\n try {\n var prevProps = this.props;\n var prevState = this.state;\n this.props = nextProps;\n this.state = nextState;\n this.__reactInternalSnapshotFlag = true;\n this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(\n prevProps,\n prevState\n );\n } finally {\n this.props = prevProps;\n this.state = prevState;\n }\n}\n\n// React may warn about cWM/cWRP/cWU methods being deprecated.\n// Add a flag to suppress these warnings for this special case.\ncomponentWillMount.__suppressDeprecationWarning = true;\ncomponentWillReceiveProps.__suppressDeprecationWarning = true;\ncomponentWillUpdate.__suppressDeprecationWarning = true;\n\nfunction polyfill(Component) {\n var prototype = Component.prototype;\n\n if (!prototype || !prototype.isReactComponent) {\n throw new Error('Can only polyfill class components');\n }\n\n if (\n typeof Component.getDerivedStateFromProps !== 'function' &&\n typeof prototype.getSnapshotBeforeUpdate !== 'function'\n ) {\n return Component;\n }\n\n // If new component APIs are defined, \"unsafe\" lifecycles won't be called.\n // Error if any of these lifecycles are present,\n // Because they would work differently between older and newer (16.3+) versions of React.\n var foundWillMountName = null;\n var foundWillReceivePropsName = null;\n var foundWillUpdateName = null;\n if (typeof prototype.componentWillMount === 'function') {\n foundWillMountName = 'componentWillMount';\n } else if (typeof prototype.UNSAFE_componentWillMount === 'function') {\n foundWillMountName = 'UNSAFE_componentWillMount';\n }\n if (typeof prototype.componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'componentWillReceiveProps';\n } else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';\n }\n if (typeof prototype.componentWillUpdate === 'function') {\n foundWillUpdateName = 'componentWillUpdate';\n } else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') {\n foundWillUpdateName = 'UNSAFE_componentWillUpdate';\n }\n if (\n foundWillMountName !== null ||\n foundWillReceivePropsName !== null ||\n foundWillUpdateName !== null\n ) {\n var componentName = Component.displayName || Component.name;\n var newApiName =\n typeof Component.getDerivedStateFromProps === 'function'\n ? 'getDerivedStateFromProps()'\n : 'getSnapshotBeforeUpdate()';\n\n throw Error(\n 'Unsafe legacy lifecycles will not be called for components using new component APIs.\\n\\n' +\n componentName +\n ' uses ' +\n newApiName +\n ' but also contains the following legacy lifecycles:' +\n (foundWillMountName !== null ? '\\n ' + foundWillMountName : '') +\n (foundWillReceivePropsName !== null\n ? '\\n ' + foundWillReceivePropsName\n : '') +\n (foundWillUpdateName !== null ? '\\n ' + foundWillUpdateName : '') +\n '\\n\\nThe above lifecycles should be removed. Learn more about this warning here:\\n' +\n 'https://fb.me/react-async-component-lifecycle-hooks'\n );\n }\n\n // React <= 16.2 does not support static getDerivedStateFromProps.\n // As a workaround, use cWM and cWRP to invoke the new static lifecycle.\n // Newer versions of React will ignore these lifecycles if gDSFP exists.\n if (typeof Component.getDerivedStateFromProps === 'function') {\n prototype.componentWillMount = componentWillMount;\n prototype.componentWillReceiveProps = componentWillReceiveProps;\n }\n\n // React <= 16.2 does not support getSnapshotBeforeUpdate.\n // As a workaround, use cWU to invoke the new lifecycle.\n // Newer versions of React will ignore that lifecycle if gSBU exists.\n if (typeof prototype.getSnapshotBeforeUpdate === 'function') {\n if (typeof prototype.componentDidUpdate !== 'function') {\n throw new Error(\n 'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'\n );\n }\n\n prototype.componentWillUpdate = componentWillUpdate;\n\n var componentDidUpdate = prototype.componentDidUpdate;\n\n prototype.componentDidUpdate = function componentDidUpdatePolyfill(\n prevProps,\n prevState,\n maybeSnapshot\n ) {\n // 16.3+ will not execute our will-update method;\n // It will pass a snapshot value to did-update though.\n // Older versions will require our polyfilled will-update value.\n // We need to handle both cases, but can't just check for the presence of \"maybeSnapshot\",\n // Because for <= 15.x versions this might be a \"prevContext\" object.\n // We also can't just check \"__reactInternalSnapshot\",\n // Because get-snapshot might return a falsy value.\n // So check for the explicit __reactInternalSnapshotFlag flag to determine behavior.\n var snapshot = this.__reactInternalSnapshotFlag\n ? this.__reactInternalSnapshot\n : maybeSnapshot;\n\n componentDidUpdate.call(this, prevProps, prevState, snapshot);\n };\n }\n\n return Component;\n}\n\nexport { polyfill };\n","import arrayWithHoles from \"./arrayWithHoles\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit\";\nimport nonIterableRest from \"./nonIterableRest\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();\n}","export default function _iterableToArrayLimit(arr, i) {\n if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === \"[object Arguments]\")) {\n return;\n }\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}","import _extends from '@babel/runtime/helpers/esm/extends';\nimport isInBrowser from 'is-in-browser';\nimport warning from 'tiny-warning';\nimport _createClass from '@babel/runtime/helpers/esm/createClass';\nimport _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose';\nimport _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized';\nimport _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose';\n\nvar plainObjectConstrurctor = {}.constructor;\nfunction cloneStyle(style) {\n if (style == null || typeof style !== 'object') return style;\n if (Array.isArray(style)) return style.map(cloneStyle);\n if (style.constructor !== plainObjectConstrurctor) return style;\n var newStyle = {};\n\n for (var name in style) {\n newStyle[name] = cloneStyle(style[name]);\n }\n\n return newStyle;\n}\n\n/**\n * Create a rule instance.\n */\n\nfunction createRule(name, decl, options) {\n if (name === void 0) {\n name = 'unnamed';\n }\n\n var jss = options.jss;\n var declCopy = cloneStyle(decl);\n var rule = jss.plugins.onCreateRule(name, declCopy, options);\n if (rule) return rule; // It is an at-rule and it has no instance.\n\n if (name[0] === '@') {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Unknown rule \" + name) : void 0;\n }\n\n return null;\n}\n\nvar join = function join(value, by) {\n var result = '';\n\n for (var i = 0; i < value.length; i++) {\n // Remove !important from the value, it will be readded later.\n if (value[i] === '!important') break;\n if (result) result += by;\n result += value[i];\n }\n\n return result;\n};\n/**\n * Converts JSS array value to a CSS string.\n *\n * `margin: [['5px', '10px']]` > `margin: 5px 10px;`\n * `border: ['1px', '2px']` > `border: 1px, 2px;`\n * `margin: [['5px', '10px'], '!important']` > `margin: 5px 10px !important;`\n * `color: ['red', !important]` > `color: red !important;`\n */\n\n\nvar toCssValue = function toCssValue(value, ignoreImportant) {\n if (ignoreImportant === void 0) {\n ignoreImportant = false;\n }\n\n if (!Array.isArray(value)) return value;\n var cssValue = ''; // Support space separated values via `[['5px', '10px']]`.\n\n if (Array.isArray(value[0])) {\n for (var i = 0; i < value.length; i++) {\n if (value[i] === '!important') break;\n if (cssValue) cssValue += ', ';\n cssValue += join(value[i], ' ');\n }\n } else cssValue = join(value, ', '); // Add !important, because it was ignored.\n\n\n if (!ignoreImportant && value[value.length - 1] === '!important') {\n cssValue += ' !important';\n }\n\n return cssValue;\n};\n\nfunction getWhitespaceSymbols(options) {\n if (options && options.format === false) {\n return {\n linebreak: '',\n space: ''\n };\n }\n\n return {\n linebreak: '\\n',\n space: ' '\n };\n}\n\n/**\n * Indent a string.\n * http://jsperf.com/array-join-vs-for\n */\n\nfunction indentStr(str, indent) {\n var result = '';\n\n for (var index = 0; index < indent; index++) {\n result += ' ';\n }\n\n return result + str;\n}\n/**\n * Converts a Rule to CSS string.\n */\n\n\nfunction toCss(selector, style, options) {\n if (options === void 0) {\n options = {};\n }\n\n var result = '';\n if (!style) return result;\n var _options = options,\n _options$indent = _options.indent,\n indent = _options$indent === void 0 ? 0 : _options$indent;\n var fallbacks = style.fallbacks;\n\n if (options.format === false) {\n indent = -Infinity;\n }\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak,\n space = _getWhitespaceSymbols.space;\n\n if (selector) indent++; // Apply fallbacks first.\n\n if (fallbacks) {\n // Array syntax {fallbacks: [{prop: value}]}\n if (Array.isArray(fallbacks)) {\n for (var index = 0; index < fallbacks.length; index++) {\n var fallback = fallbacks[index];\n\n for (var prop in fallback) {\n var value = fallback[prop];\n\n if (value != null) {\n if (result) result += linebreak;\n result += indentStr(prop + \":\" + space + toCssValue(value) + \";\", indent);\n }\n }\n }\n } else {\n // Object syntax {fallbacks: {prop: value}}\n for (var _prop in fallbacks) {\n var _value = fallbacks[_prop];\n\n if (_value != null) {\n if (result) result += linebreak;\n result += indentStr(_prop + \":\" + space + toCssValue(_value) + \";\", indent);\n }\n }\n }\n }\n\n for (var _prop2 in style) {\n var _value2 = style[_prop2];\n\n if (_value2 != null && _prop2 !== 'fallbacks') {\n if (result) result += linebreak;\n result += indentStr(_prop2 + \":\" + space + toCssValue(_value2) + \";\", indent);\n }\n } // Allow empty style in this case, because properties will be added dynamically.\n\n\n if (!result && !options.allowEmpty) return result; // When rule is being stringified before selector was defined.\n\n if (!selector) return result;\n indent--;\n if (result) result = \"\" + linebreak + result + linebreak;\n return indentStr(\"\" + selector + space + \"{\" + result, indent) + indentStr('}', indent);\n}\n\nvar escapeRegex = /([[\\].#*$><+~=|^:(),\"'`\\s])/g;\nvar nativeEscape = typeof CSS !== 'undefined' && CSS.escape;\nvar escape = (function (str) {\n return nativeEscape ? nativeEscape(str) : str.replace(escapeRegex, '\\\\$1');\n});\n\nvar BaseStyleRule =\n/*#__PURE__*/\nfunction () {\n function BaseStyleRule(key, style, options) {\n this.type = 'style';\n this.isProcessed = false;\n var sheet = options.sheet,\n Renderer = options.Renderer;\n this.key = key;\n this.options = options;\n this.style = style;\n if (sheet) this.renderer = sheet.renderer;else if (Renderer) this.renderer = new Renderer();\n }\n /**\n * Get or set a style property.\n */\n\n\n var _proto = BaseStyleRule.prototype;\n\n _proto.prop = function prop(name, value, options) {\n // It's a getter.\n if (value === undefined) return this.style[name]; // Don't do anything if the value has not changed.\n\n var force = options ? options.force : false;\n if (!force && this.style[name] === value) return this;\n var newValue = value;\n\n if (!options || options.process !== false) {\n newValue = this.options.jss.plugins.onChangeValue(value, name, this);\n }\n\n var isEmpty = newValue == null || newValue === false;\n var isDefined = name in this.style; // Value is empty and wasn't defined before.\n\n if (isEmpty && !isDefined && !force) return this; // We are going to remove this value.\n\n var remove = isEmpty && isDefined;\n if (remove) delete this.style[name];else this.style[name] = newValue; // Renderable is defined if StyleSheet option `link` is true.\n\n if (this.renderable && this.renderer) {\n if (remove) this.renderer.removeProperty(this.renderable, name);else this.renderer.setProperty(this.renderable, name, newValue);\n return this;\n }\n\n var sheet = this.options.sheet;\n\n if (sheet && sheet.attached) {\n process.env.NODE_ENV !== \"production\" ? warning(false, '[JSS] Rule is not linked. Missing sheet option \"link: true\".') : void 0;\n }\n\n return this;\n };\n\n return BaseStyleRule;\n}();\nvar StyleRule =\n/*#__PURE__*/\nfunction (_BaseStyleRule) {\n _inheritsLoose(StyleRule, _BaseStyleRule);\n\n function StyleRule(key, style, options) {\n var _this;\n\n _this = _BaseStyleRule.call(this, key, style, options) || this;\n var selector = options.selector,\n scoped = options.scoped,\n sheet = options.sheet,\n generateId = options.generateId;\n\n if (selector) {\n _this.selectorText = selector;\n } else if (scoped !== false) {\n _this.id = generateId(_assertThisInitialized(_assertThisInitialized(_this)), sheet);\n _this.selectorText = \".\" + escape(_this.id);\n }\n\n return _this;\n }\n /**\n * Set selector string.\n * Attention: use this with caution. Most browsers didn't implement\n * selectorText setter, so this may result in rerendering of entire Style Sheet.\n */\n\n\n var _proto2 = StyleRule.prototype;\n\n /**\n * Apply rule to an element inline.\n */\n _proto2.applyTo = function applyTo(renderable) {\n var renderer = this.renderer;\n\n if (renderer) {\n var json = this.toJSON();\n\n for (var prop in json) {\n renderer.setProperty(renderable, prop, json[prop]);\n }\n }\n\n return this;\n }\n /**\n * Returns JSON representation of the rule.\n * Fallbacks are not supported.\n * Useful for inline styles.\n */\n ;\n\n _proto2.toJSON = function toJSON() {\n var json = {};\n\n for (var prop in this.style) {\n var value = this.style[prop];\n if (typeof value !== 'object') json[prop] = value;else if (Array.isArray(value)) json[prop] = toCssValue(value);\n }\n\n return json;\n }\n /**\n * Generates a CSS string.\n */\n ;\n\n _proto2.toString = function toString(options) {\n var sheet = this.options.sheet;\n var link = sheet ? sheet.options.link : false;\n var opts = link ? _extends({}, options, {\n allowEmpty: true\n }) : options;\n return toCss(this.selectorText, this.style, opts);\n };\n\n _createClass(StyleRule, [{\n key: \"selector\",\n set: function set(selector) {\n if (selector === this.selectorText) return;\n this.selectorText = selector;\n var renderer = this.renderer,\n renderable = this.renderable;\n if (!renderable || !renderer) return;\n var hasChanged = renderer.setSelector(renderable, selector); // If selector setter is not implemented, rerender the rule.\n\n if (!hasChanged) {\n renderer.replaceRule(renderable, this);\n }\n }\n /**\n * Get selector string.\n */\n ,\n get: function get() {\n return this.selectorText;\n }\n }]);\n\n return StyleRule;\n}(BaseStyleRule);\nvar pluginStyleRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n if (key[0] === '@' || options.parent && options.parent.type === 'keyframes') {\n return null;\n }\n\n return new StyleRule(key, style, options);\n }\n};\n\nvar defaultToStringOptions = {\n indent: 1,\n children: true\n};\nvar atRegExp = /@([\\w-]+)/;\n/**\n * Conditional rule for @media, @supports\n */\n\nvar ConditionalRule =\n/*#__PURE__*/\nfunction () {\n function ConditionalRule(key, styles, options) {\n this.type = 'conditional';\n this.isProcessed = false;\n this.key = key;\n var atMatch = key.match(atRegExp);\n this.at = atMatch ? atMatch[1] : 'unknown'; // Key might contain a unique suffix in case the `name` passed by user was duplicate.\n\n this.query = options.name || \"@\" + this.at;\n this.options = options;\n this.rules = new RuleList(_extends({}, options, {\n parent: this\n }));\n\n for (var name in styles) {\n this.rules.add(name, styles[name]);\n }\n\n this.rules.process();\n }\n /**\n * Get a rule.\n */\n\n\n var _proto = ConditionalRule.prototype;\n\n _proto.getRule = function getRule(name) {\n return this.rules.get(name);\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.rules.indexOf(rule);\n }\n /**\n * Create and register rule, run plugins.\n */\n ;\n\n _proto.addRule = function addRule(name, style, options) {\n var rule = this.rules.add(name, style, options);\n if (!rule) return null;\n this.options.jss.plugins.onProcessRule(rule);\n return rule;\n }\n /**\n * Generates a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n if (options === void 0) {\n options = defaultToStringOptions;\n }\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n if (options.indent == null) options.indent = defaultToStringOptions.indent;\n if (options.children == null) options.children = defaultToStringOptions.children;\n\n if (options.children === false) {\n return this.query + \" {}\";\n }\n\n var children = this.rules.toString(options);\n return children ? this.query + \" {\" + linebreak + children + linebreak + \"}\" : '';\n };\n\n return ConditionalRule;\n}();\nvar keyRegExp = /@media|@supports\\s+/;\nvar pluginConditionalRule = {\n onCreateRule: function onCreateRule(key, styles, options) {\n return keyRegExp.test(key) ? new ConditionalRule(key, styles, options) : null;\n }\n};\n\nvar defaultToStringOptions$1 = {\n indent: 1,\n children: true\n};\nvar nameRegExp = /@keyframes\\s+([\\w-]+)/;\n/**\n * Rule for @keyframes\n */\n\nvar KeyframesRule =\n/*#__PURE__*/\nfunction () {\n function KeyframesRule(key, frames, options) {\n this.type = 'keyframes';\n this.at = '@keyframes';\n this.isProcessed = false;\n var nameMatch = key.match(nameRegExp);\n\n if (nameMatch && nameMatch[1]) {\n this.name = nameMatch[1];\n } else {\n this.name = 'noname';\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Bad keyframes name \" + key) : void 0;\n }\n\n this.key = this.type + \"-\" + this.name;\n this.options = options;\n var scoped = options.scoped,\n sheet = options.sheet,\n generateId = options.generateId;\n this.id = scoped === false ? this.name : escape(generateId(this, sheet));\n this.rules = new RuleList(_extends({}, options, {\n parent: this\n }));\n\n for (var name in frames) {\n this.rules.add(name, frames[name], _extends({}, options, {\n parent: this\n }));\n }\n\n this.rules.process();\n }\n /**\n * Generates a CSS string.\n */\n\n\n var _proto = KeyframesRule.prototype;\n\n _proto.toString = function toString(options) {\n if (options === void 0) {\n options = defaultToStringOptions$1;\n }\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n if (options.indent == null) options.indent = defaultToStringOptions$1.indent;\n if (options.children == null) options.children = defaultToStringOptions$1.children;\n\n if (options.children === false) {\n return this.at + \" \" + this.id + \" {}\";\n }\n\n var children = this.rules.toString(options);\n if (children) children = \"\" + linebreak + children + linebreak;\n return this.at + \" \" + this.id + \" {\" + children + \"}\";\n };\n\n return KeyframesRule;\n}();\nvar keyRegExp$1 = /@keyframes\\s+/;\nvar refRegExp = /\\$([\\w-]+)/g;\n\nvar findReferencedKeyframe = function findReferencedKeyframe(val, keyframes) {\n if (typeof val === 'string') {\n return val.replace(refRegExp, function (match, name) {\n if (name in keyframes) {\n return keyframes[name];\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Referenced keyframes rule \\\"\" + name + \"\\\" is not defined.\") : void 0;\n return match;\n });\n }\n\n return val;\n};\n/**\n * Replace the reference for a animation name.\n */\n\n\nvar replaceRef = function replaceRef(style, prop, keyframes) {\n var value = style[prop];\n var refKeyframe = findReferencedKeyframe(value, keyframes);\n\n if (refKeyframe !== value) {\n style[prop] = refKeyframe;\n }\n};\n\nvar pluginKeyframesRule = {\n onCreateRule: function onCreateRule(key, frames, options) {\n return typeof key === 'string' && keyRegExp$1.test(key) ? new KeyframesRule(key, frames, options) : null;\n },\n // Animation name ref replacer.\n onProcessStyle: function onProcessStyle(style, rule, sheet) {\n if (rule.type !== 'style' || !sheet) return style;\n if ('animation-name' in style) replaceRef(style, 'animation-name', sheet.keyframes);\n if ('animation' in style) replaceRef(style, 'animation', sheet.keyframes);\n return style;\n },\n onChangeValue: function onChangeValue(val, prop, rule) {\n var sheet = rule.options.sheet;\n\n if (!sheet) {\n return val;\n }\n\n switch (prop) {\n case 'animation':\n return findReferencedKeyframe(val, sheet.keyframes);\n\n case 'animation-name':\n return findReferencedKeyframe(val, sheet.keyframes);\n\n default:\n return val;\n }\n }\n};\n\nvar KeyframeRule =\n/*#__PURE__*/\nfunction (_BaseStyleRule) {\n _inheritsLoose(KeyframeRule, _BaseStyleRule);\n\n function KeyframeRule() {\n return _BaseStyleRule.apply(this, arguments) || this;\n }\n\n var _proto = KeyframeRule.prototype;\n\n /**\n * Generates a CSS string.\n */\n _proto.toString = function toString(options) {\n var sheet = this.options.sheet;\n var link = sheet ? sheet.options.link : false;\n var opts = link ? _extends({}, options, {\n allowEmpty: true\n }) : options;\n return toCss(this.key, this.style, opts);\n };\n\n return KeyframeRule;\n}(BaseStyleRule);\nvar pluginKeyframeRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n if (options.parent && options.parent.type === 'keyframes') {\n return new KeyframeRule(key, style, options);\n }\n\n return null;\n }\n};\n\nvar FontFaceRule =\n/*#__PURE__*/\nfunction () {\n function FontFaceRule(key, style, options) {\n this.type = 'font-face';\n this.at = '@font-face';\n this.isProcessed = false;\n this.key = key;\n this.style = style;\n this.options = options;\n }\n /**\n * Generates a CSS string.\n */\n\n\n var _proto = FontFaceRule.prototype;\n\n _proto.toString = function toString(options) {\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n if (Array.isArray(this.style)) {\n var str = '';\n\n for (var index = 0; index < this.style.length; index++) {\n str += toCss(this.at, this.style[index]);\n if (this.style[index + 1]) str += linebreak;\n }\n\n return str;\n }\n\n return toCss(this.at, this.style, options);\n };\n\n return FontFaceRule;\n}();\nvar keyRegExp$2 = /@font-face/;\nvar pluginFontFaceRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n return keyRegExp$2.test(key) ? new FontFaceRule(key, style, options) : null;\n }\n};\n\nvar ViewportRule =\n/*#__PURE__*/\nfunction () {\n function ViewportRule(key, style, options) {\n this.type = 'viewport';\n this.at = '@viewport';\n this.isProcessed = false;\n this.key = key;\n this.style = style;\n this.options = options;\n }\n /**\n * Generates a CSS string.\n */\n\n\n var _proto = ViewportRule.prototype;\n\n _proto.toString = function toString(options) {\n return toCss(this.key, this.style, options);\n };\n\n return ViewportRule;\n}();\nvar pluginViewportRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n return key === '@viewport' || key === '@-ms-viewport' ? new ViewportRule(key, style, options) : null;\n }\n};\n\nvar SimpleRule =\n/*#__PURE__*/\nfunction () {\n function SimpleRule(key, value, options) {\n this.type = 'simple';\n this.isProcessed = false;\n this.key = key;\n this.value = value;\n this.options = options;\n }\n /**\n * Generates a CSS string.\n */\n // eslint-disable-next-line no-unused-vars\n\n\n var _proto = SimpleRule.prototype;\n\n _proto.toString = function toString(options) {\n if (Array.isArray(this.value)) {\n var str = '';\n\n for (var index = 0; index < this.value.length; index++) {\n str += this.key + \" \" + this.value[index] + \";\";\n if (this.value[index + 1]) str += '\\n';\n }\n\n return str;\n }\n\n return this.key + \" \" + this.value + \";\";\n };\n\n return SimpleRule;\n}();\nvar keysMap = {\n '@charset': true,\n '@import': true,\n '@namespace': true\n};\nvar pluginSimpleRule = {\n onCreateRule: function onCreateRule(key, value, options) {\n return key in keysMap ? new SimpleRule(key, value, options) : null;\n }\n};\n\nvar plugins = [pluginStyleRule, pluginConditionalRule, pluginKeyframesRule, pluginKeyframeRule, pluginFontFaceRule, pluginViewportRule, pluginSimpleRule];\n\nvar defaultUpdateOptions = {\n process: true\n};\nvar forceUpdateOptions = {\n force: true,\n process: true\n /**\n * Contains rules objects and allows adding/removing etc.\n * Is used for e.g. by `StyleSheet` or `ConditionalRule`.\n */\n\n};\n\nvar RuleList =\n/*#__PURE__*/\nfunction () {\n // Rules registry for access by .get() method.\n // It contains the same rule registered by name and by selector.\n // Original styles object.\n // Used to ensure correct rules order.\n function RuleList(options) {\n this.map = {};\n this.raw = {};\n this.index = [];\n this.counter = 0;\n this.options = options;\n this.classes = options.classes;\n this.keyframes = options.keyframes;\n }\n /**\n * Create and register rule.\n *\n * Will not render after Style Sheet was rendered the first time.\n */\n\n\n var _proto = RuleList.prototype;\n\n _proto.add = function add(name, decl, ruleOptions) {\n var _this$options = this.options,\n parent = _this$options.parent,\n sheet = _this$options.sheet,\n jss = _this$options.jss,\n Renderer = _this$options.Renderer,\n generateId = _this$options.generateId,\n scoped = _this$options.scoped;\n\n var options = _extends({\n classes: this.classes,\n parent: parent,\n sheet: sheet,\n jss: jss,\n Renderer: Renderer,\n generateId: generateId,\n scoped: scoped,\n name: name,\n keyframes: this.keyframes,\n selector: undefined\n }, ruleOptions); // When user uses .createStyleSheet(), duplicate names are not possible, but\n // `sheet.addRule()` opens the door for any duplicate rule name. When this happens\n // we need to make the key unique within this RuleList instance scope.\n\n\n var key = name;\n\n if (name in this.raw) {\n key = name + \"-d\" + this.counter++;\n } // We need to save the original decl before creating the rule\n // because cache plugin needs to use it as a key to return a cached rule.\n\n\n this.raw[key] = decl;\n\n if (key in this.classes) {\n // E.g. rules inside of @media container\n options.selector = \".\" + escape(this.classes[key]);\n }\n\n var rule = createRule(key, decl, options);\n if (!rule) return null;\n this.register(rule);\n var index = options.index === undefined ? this.index.length : options.index;\n this.index.splice(index, 0, rule);\n return rule;\n }\n /**\n * Get a rule.\n */\n ;\n\n _proto.get = function get(name) {\n return this.map[name];\n }\n /**\n * Delete a rule.\n */\n ;\n\n _proto.remove = function remove(rule) {\n this.unregister(rule);\n delete this.raw[rule.key];\n this.index.splice(this.index.indexOf(rule), 1);\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.index.indexOf(rule);\n }\n /**\n * Run `onProcessRule()` plugins on every rule.\n */\n ;\n\n _proto.process = function process() {\n var plugins = this.options.jss.plugins; // We need to clone array because if we modify the index somewhere else during a loop\n // we end up with very hard-to-track-down side effects.\n\n this.index.slice(0).forEach(plugins.onProcessRule, plugins);\n }\n /**\n * Register a rule in `.map`, `.classes` and `.keyframes` maps.\n */\n ;\n\n _proto.register = function register(rule) {\n this.map[rule.key] = rule;\n\n if (rule instanceof StyleRule) {\n this.map[rule.selector] = rule;\n if (rule.id) this.classes[rule.key] = rule.id;\n } else if (rule instanceof KeyframesRule && this.keyframes) {\n this.keyframes[rule.name] = rule.id;\n }\n }\n /**\n * Unregister a rule.\n */\n ;\n\n _proto.unregister = function unregister(rule) {\n delete this.map[rule.key];\n\n if (rule instanceof StyleRule) {\n delete this.map[rule.selector];\n delete this.classes[rule.key];\n } else if (rule instanceof KeyframesRule) {\n delete this.keyframes[rule.name];\n }\n }\n /**\n * Update the function values with a new data.\n */\n ;\n\n _proto.update = function update() {\n var name;\n var data;\n var options;\n\n if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') {\n name = arguments.length <= 0 ? undefined : arguments[0];\n data = arguments.length <= 1 ? undefined : arguments[1];\n options = arguments.length <= 2 ? undefined : arguments[2];\n } else {\n data = arguments.length <= 0 ? undefined : arguments[0];\n options = arguments.length <= 1 ? undefined : arguments[1];\n name = null;\n }\n\n if (name) {\n this.updateOne(this.map[name], data, options);\n } else {\n for (var index = 0; index < this.index.length; index++) {\n this.updateOne(this.index[index], data, options);\n }\n }\n }\n /**\n * Execute plugins, update rule props.\n */\n ;\n\n _proto.updateOne = function updateOne(rule, data, options) {\n if (options === void 0) {\n options = defaultUpdateOptions;\n }\n\n var _this$options2 = this.options,\n plugins = _this$options2.jss.plugins,\n sheet = _this$options2.sheet; // It is a rules container like for e.g. ConditionalRule.\n\n if (rule.rules instanceof RuleList) {\n rule.rules.update(data, options);\n return;\n }\n\n var style = rule.style;\n plugins.onUpdate(data, rule, sheet, options); // We rely on a new `style` ref in case it was mutated during onUpdate hook.\n\n if (options.process && style && style !== rule.style) {\n // We need to run the plugins in case new `style` relies on syntax plugins.\n plugins.onProcessStyle(rule.style, rule, sheet); // Update and add props.\n\n for (var prop in rule.style) {\n var nextValue = rule.style[prop];\n var prevValue = style[prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule.\n // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here.\n\n if (nextValue !== prevValue) {\n rule.prop(prop, nextValue, forceUpdateOptions);\n }\n } // Remove props.\n\n\n for (var _prop in style) {\n var _nextValue = rule.style[_prop];\n var _prevValue = style[_prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule.\n // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here.\n\n if (_nextValue == null && _nextValue !== _prevValue) {\n rule.prop(_prop, null, forceUpdateOptions);\n }\n }\n }\n }\n /**\n * Convert rules to a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n var str = '';\n var sheet = this.options.sheet;\n var link = sheet ? sheet.options.link : false;\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n for (var index = 0; index < this.index.length; index++) {\n var rule = this.index[index];\n var css = rule.toString(options); // No need to render an empty rule.\n\n if (!css && !link) continue;\n if (str) str += linebreak;\n str += css;\n }\n\n return str;\n };\n\n return RuleList;\n}();\n\nvar StyleSheet =\n/*#__PURE__*/\nfunction () {\n function StyleSheet(styles, options) {\n this.attached = false;\n this.deployed = false;\n this.classes = {};\n this.keyframes = {};\n this.options = _extends({}, options, {\n sheet: this,\n parent: this,\n classes: this.classes,\n keyframes: this.keyframes\n });\n\n if (options.Renderer) {\n this.renderer = new options.Renderer(this);\n }\n\n this.rules = new RuleList(this.options);\n\n for (var name in styles) {\n this.rules.add(name, styles[name]);\n }\n\n this.rules.process();\n }\n /**\n * Attach renderable to the render tree.\n */\n\n\n var _proto = StyleSheet.prototype;\n\n _proto.attach = function attach() {\n if (this.attached) return this;\n if (this.renderer) this.renderer.attach();\n this.attached = true; // Order is important, because we can't use insertRule API if style element is not attached.\n\n if (!this.deployed) this.deploy();\n return this;\n }\n /**\n * Remove renderable from render tree.\n */\n ;\n\n _proto.detach = function detach() {\n if (!this.attached) return this;\n if (this.renderer) this.renderer.detach();\n this.attached = false;\n return this;\n }\n /**\n * Add a rule to the current stylesheet.\n * Will insert a rule also after the stylesheet has been rendered first time.\n */\n ;\n\n _proto.addRule = function addRule(name, decl, options) {\n var queue = this.queue; // Plugins can create rules.\n // In order to preserve the right order, we need to queue all `.addRule` calls,\n // which happen after the first `rules.add()` call.\n\n if (this.attached && !queue) this.queue = [];\n var rule = this.rules.add(name, decl, options);\n if (!rule) return null;\n this.options.jss.plugins.onProcessRule(rule);\n\n if (this.attached) {\n if (!this.deployed) return rule; // Don't insert rule directly if there is no stringified version yet.\n // It will be inserted all together when .attach is called.\n\n if (queue) queue.push(rule);else {\n this.insertRule(rule);\n\n if (this.queue) {\n this.queue.forEach(this.insertRule, this);\n this.queue = undefined;\n }\n }\n return rule;\n } // We can't add rules to a detached style node.\n // We will redeploy the sheet once user will attach it.\n\n\n this.deployed = false;\n return rule;\n }\n /**\n * Insert rule into the StyleSheet\n */\n ;\n\n _proto.insertRule = function insertRule(rule) {\n if (this.renderer) {\n this.renderer.insertRule(rule);\n }\n }\n /**\n * Create and add rules.\n * Will render also after Style Sheet was rendered the first time.\n */\n ;\n\n _proto.addRules = function addRules(styles, options) {\n var added = [];\n\n for (var name in styles) {\n var rule = this.addRule(name, styles[name], options);\n if (rule) added.push(rule);\n }\n\n return added;\n }\n /**\n * Get a rule by name.\n */\n ;\n\n _proto.getRule = function getRule(name) {\n return this.rules.get(name);\n }\n /**\n * Delete a rule by name.\n * Returns `true`: if rule has been deleted from the DOM.\n */\n ;\n\n _proto.deleteRule = function deleteRule(name) {\n var rule = typeof name === 'object' ? name : this.rules.get(name);\n\n if (!rule || // Style sheet was created without link: true and attached, in this case we\n // won't be able to remove the CSS rule from the DOM.\n this.attached && !rule.renderable) {\n return false;\n }\n\n this.rules.remove(rule);\n\n if (this.attached && rule.renderable && this.renderer) {\n return this.renderer.deleteRule(rule.renderable);\n }\n\n return true;\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.rules.indexOf(rule);\n }\n /**\n * Deploy pure CSS string to a renderable.\n */\n ;\n\n _proto.deploy = function deploy() {\n if (this.renderer) this.renderer.deploy();\n this.deployed = true;\n return this;\n }\n /**\n * Update the function values with a new data.\n */\n ;\n\n _proto.update = function update() {\n var _this$rules;\n\n (_this$rules = this.rules).update.apply(_this$rules, arguments);\n\n return this;\n }\n /**\n * Updates a single rule.\n */\n ;\n\n _proto.updateOne = function updateOne(rule, data, options) {\n this.rules.updateOne(rule, data, options);\n return this;\n }\n /**\n * Convert rules to a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n return this.rules.toString(options);\n };\n\n return StyleSheet;\n}();\n\nvar PluginsRegistry =\n/*#__PURE__*/\nfunction () {\n function PluginsRegistry() {\n this.plugins = {\n internal: [],\n external: []\n };\n this.registry = {};\n }\n\n var _proto = PluginsRegistry.prototype;\n\n /**\n * Call `onCreateRule` hooks and return an object if returned by a hook.\n */\n _proto.onCreateRule = function onCreateRule(name, decl, options) {\n for (var i = 0; i < this.registry.onCreateRule.length; i++) {\n var rule = this.registry.onCreateRule[i](name, decl, options);\n if (rule) return rule;\n }\n\n return null;\n }\n /**\n * Call `onProcessRule` hooks.\n */\n ;\n\n _proto.onProcessRule = function onProcessRule(rule) {\n if (rule.isProcessed) return;\n var sheet = rule.options.sheet;\n\n for (var i = 0; i < this.registry.onProcessRule.length; i++) {\n this.registry.onProcessRule[i](rule, sheet);\n }\n\n if (rule.style) this.onProcessStyle(rule.style, rule, sheet);\n rule.isProcessed = true;\n }\n /**\n * Call `onProcessStyle` hooks.\n */\n ;\n\n _proto.onProcessStyle = function onProcessStyle(style, rule, sheet) {\n for (var i = 0; i < this.registry.onProcessStyle.length; i++) {\n rule.style = this.registry.onProcessStyle[i](rule.style, rule, sheet);\n }\n }\n /**\n * Call `onProcessSheet` hooks.\n */\n ;\n\n _proto.onProcessSheet = function onProcessSheet(sheet) {\n for (var i = 0; i < this.registry.onProcessSheet.length; i++) {\n this.registry.onProcessSheet[i](sheet);\n }\n }\n /**\n * Call `onUpdate` hooks.\n */\n ;\n\n _proto.onUpdate = function onUpdate(data, rule, sheet, options) {\n for (var i = 0; i < this.registry.onUpdate.length; i++) {\n this.registry.onUpdate[i](data, rule, sheet, options);\n }\n }\n /**\n * Call `onChangeValue` hooks.\n */\n ;\n\n _proto.onChangeValue = function onChangeValue(value, prop, rule) {\n var processedValue = value;\n\n for (var i = 0; i < this.registry.onChangeValue.length; i++) {\n processedValue = this.registry.onChangeValue[i](processedValue, prop, rule);\n }\n\n return processedValue;\n }\n /**\n * Register a plugin.\n */\n ;\n\n _proto.use = function use(newPlugin, options) {\n if (options === void 0) {\n options = {\n queue: 'external'\n };\n }\n\n var plugins = this.plugins[options.queue]; // Avoids applying same plugin twice, at least based on ref.\n\n if (plugins.indexOf(newPlugin) !== -1) {\n return;\n }\n\n plugins.push(newPlugin);\n this.registry = [].concat(this.plugins.external, this.plugins.internal).reduce(function (registry, plugin) {\n for (var name in plugin) {\n if (name in registry) {\n registry[name].push(plugin[name]);\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Unknown hook \\\"\" + name + \"\\\".\") : void 0;\n }\n }\n\n return registry;\n }, {\n onCreateRule: [],\n onProcessRule: [],\n onProcessStyle: [],\n onProcessSheet: [],\n onChangeValue: [],\n onUpdate: []\n });\n };\n\n return PluginsRegistry;\n}();\n\n/**\n * Sheets registry to access all instances in one place.\n */\n\nvar SheetsRegistry =\n/*#__PURE__*/\nfunction () {\n function SheetsRegistry() {\n this.registry = [];\n }\n\n var _proto = SheetsRegistry.prototype;\n\n /**\n * Register a Style Sheet.\n */\n _proto.add = function add(sheet) {\n var registry = this.registry;\n var index = sheet.options.index;\n if (registry.indexOf(sheet) !== -1) return;\n\n if (registry.length === 0 || index >= this.index) {\n registry.push(sheet);\n return;\n } // Find a position.\n\n\n for (var i = 0; i < registry.length; i++) {\n if (registry[i].options.index > index) {\n registry.splice(i, 0, sheet);\n return;\n }\n }\n }\n /**\n * Reset the registry.\n */\n ;\n\n _proto.reset = function reset() {\n this.registry = [];\n }\n /**\n * Remove a Style Sheet.\n */\n ;\n\n _proto.remove = function remove(sheet) {\n var index = this.registry.indexOf(sheet);\n this.registry.splice(index, 1);\n }\n /**\n * Convert all attached sheets to a CSS string.\n */\n ;\n\n _proto.toString = function toString(_temp) {\n var _ref = _temp === void 0 ? {} : _temp,\n attached = _ref.attached,\n options = _objectWithoutPropertiesLoose(_ref, [\"attached\"]);\n\n var _getWhitespaceSymbols = getWhitespaceSymbols(options),\n linebreak = _getWhitespaceSymbols.linebreak;\n\n var css = '';\n\n for (var i = 0; i < this.registry.length; i++) {\n var sheet = this.registry[i];\n\n if (attached != null && sheet.attached !== attached) {\n continue;\n }\n\n if (css) css += linebreak;\n css += sheet.toString(options);\n }\n\n return css;\n };\n\n _createClass(SheetsRegistry, [{\n key: \"index\",\n\n /**\n * Current highest index number.\n */\n get: function get() {\n return this.registry.length === 0 ? 0 : this.registry[this.registry.length - 1].options.index;\n }\n }]);\n\n return SheetsRegistry;\n}();\n\n/**\n * This is a global sheets registry. Only DomRenderer will add sheets to it.\n * On the server one should use an own SheetsRegistry instance and add the\n * sheets to it, because you need to make sure to create a new registry for\n * each request in order to not leak sheets across requests.\n */\n\nvar sheets = new SheetsRegistry();\n\n/* eslint-disable */\n\n/**\n * Now that `globalThis` is available on most platforms\n * (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis#browser_compatibility)\n * we check for `globalThis` first. `globalThis` is necessary for jss\n * to run in Agoric's secure version of JavaScript (SES). Under SES,\n * `globalThis` exists, but `window`, `self`, and `Function('return\n * this')()` are all undefined for security reasons.\n *\n * https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\n */\nvar globalThis$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' && window.Math === Math ? window : typeof self !== 'undefined' && self.Math === Math ? self : Function('return this')();\n\nvar ns = '2f1acc6c3a606b082e5eef5e54414ffb';\nif (globalThis$1[ns] == null) globalThis$1[ns] = 0; // Bundle may contain multiple JSS versions at the same time. In order to identify\n// the current version with just one short number and use it for classes generation\n// we use a counter. Also it is more accurate, because user can manually reevaluate\n// the module.\n\nvar moduleId = globalThis$1[ns]++;\n\nvar maxRules = 1e10;\n/**\n * Returns a function which generates unique class names based on counters.\n * When new generator function is created, rule counter is reseted.\n * We need to reset the rule counter for SSR for each request.\n */\n\nvar createGenerateId = function createGenerateId(options) {\n if (options === void 0) {\n options = {};\n }\n\n var ruleCounter = 0;\n\n var generateId = function generateId(rule, sheet) {\n ruleCounter += 1;\n\n if (ruleCounter > maxRules) {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] You might have a memory leak. Rule counter is at \" + ruleCounter + \".\") : void 0;\n }\n\n var jssId = '';\n var prefix = '';\n\n if (sheet) {\n if (sheet.options.classNamePrefix) {\n prefix = sheet.options.classNamePrefix;\n }\n\n if (sheet.options.jss.id != null) {\n jssId = String(sheet.options.jss.id);\n }\n }\n\n if (options.minify) {\n // Using \"c\" because a number can't be the first char in a class name.\n return \"\" + (prefix || 'c') + moduleId + jssId + ruleCounter;\n }\n\n return prefix + rule.key + \"-\" + moduleId + (jssId ? \"-\" + jssId : '') + \"-\" + ruleCounter;\n };\n\n return generateId;\n};\n\n/**\n * Cache the value from the first time a function is called.\n */\n\nvar memoize = function memoize(fn) {\n var value;\n return function () {\n if (!value) value = fn();\n return value;\n };\n};\n/**\n * Get a style property value.\n */\n\n\nvar getPropertyValue = function getPropertyValue(cssRule, prop) {\n try {\n // Support CSSTOM.\n if (cssRule.attributeStyleMap) {\n return cssRule.attributeStyleMap.get(prop);\n }\n\n return cssRule.style.getPropertyValue(prop);\n } catch (err) {\n // IE may throw if property is unknown.\n return '';\n }\n};\n/**\n * Set a style property.\n */\n\n\nvar setProperty = function setProperty(cssRule, prop, value) {\n try {\n var cssValue = value;\n\n if (Array.isArray(value)) {\n cssValue = toCssValue(value, true);\n\n if (value[value.length - 1] === '!important') {\n cssRule.style.setProperty(prop, cssValue, 'important');\n return true;\n }\n } // Support CSSTOM.\n\n\n if (cssRule.attributeStyleMap) {\n cssRule.attributeStyleMap.set(prop, cssValue);\n } else {\n cssRule.style.setProperty(prop, cssValue);\n }\n } catch (err) {\n // IE may throw if property is unknown.\n return false;\n }\n\n return true;\n};\n/**\n * Remove a style property.\n */\n\n\nvar removeProperty = function removeProperty(cssRule, prop) {\n try {\n // Support CSSTOM.\n if (cssRule.attributeStyleMap) {\n cssRule.attributeStyleMap.delete(prop);\n } else {\n cssRule.style.removeProperty(prop);\n }\n } catch (err) {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] DOMException \\\"\" + err.message + \"\\\" was thrown. Tried to remove property \\\"\" + prop + \"\\\".\") : void 0;\n }\n};\n/**\n * Set the selector.\n */\n\n\nvar setSelector = function setSelector(cssRule, selectorText) {\n cssRule.selectorText = selectorText; // Return false if setter was not successful.\n // Currently works in chrome only.\n\n return cssRule.selectorText === selectorText;\n};\n/**\n * Gets the `head` element upon the first call and caches it.\n * We assume it can't be null.\n */\n\n\nvar getHead = memoize(function () {\n return document.querySelector('head');\n});\n/**\n * Find attached sheet with an index higher than the passed one.\n */\n\nfunction findHigherSheet(registry, options) {\n for (var i = 0; i < registry.length; i++) {\n var sheet = registry[i];\n\n if (sheet.attached && sheet.options.index > options.index && sheet.options.insertionPoint === options.insertionPoint) {\n return sheet;\n }\n }\n\n return null;\n}\n/**\n * Find attached sheet with the highest index.\n */\n\n\nfunction findHighestSheet(registry, options) {\n for (var i = registry.length - 1; i >= 0; i--) {\n var sheet = registry[i];\n\n if (sheet.attached && sheet.options.insertionPoint === options.insertionPoint) {\n return sheet;\n }\n }\n\n return null;\n}\n/**\n * Find a comment with \"jss\" inside.\n */\n\n\nfunction findCommentNode(text) {\n var head = getHead();\n\n for (var i = 0; i < head.childNodes.length; i++) {\n var node = head.childNodes[i];\n\n if (node.nodeType === 8 && node.nodeValue.trim() === text) {\n return node;\n }\n }\n\n return null;\n}\n/**\n * Find a node before which we can insert the sheet.\n */\n\n\nfunction findPrevNode(options) {\n var registry = sheets.registry;\n\n if (registry.length > 0) {\n // Try to insert before the next higher sheet.\n var sheet = findHigherSheet(registry, options);\n\n if (sheet && sheet.renderer) {\n return {\n parent: sheet.renderer.element.parentNode,\n node: sheet.renderer.element\n };\n } // Otherwise insert after the last attached.\n\n\n sheet = findHighestSheet(registry, options);\n\n if (sheet && sheet.renderer) {\n return {\n parent: sheet.renderer.element.parentNode,\n node: sheet.renderer.element.nextSibling\n };\n }\n } // Try to find a comment placeholder if registry is empty.\n\n\n var insertionPoint = options.insertionPoint;\n\n if (insertionPoint && typeof insertionPoint === 'string') {\n var comment = findCommentNode(insertionPoint);\n\n if (comment) {\n return {\n parent: comment.parentNode,\n node: comment.nextSibling\n };\n } // If user specifies an insertion point and it can't be found in the document -\n // bad specificity issues may appear.\n\n\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Insertion point \\\"\" + insertionPoint + \"\\\" not found.\") : void 0;\n }\n\n return false;\n}\n/**\n * Insert style element into the DOM.\n */\n\n\nfunction insertStyle(style, options) {\n var insertionPoint = options.insertionPoint;\n var nextNode = findPrevNode(options);\n\n if (nextNode !== false && nextNode.parent) {\n nextNode.parent.insertBefore(style, nextNode.node);\n return;\n } // Works with iframes and any node types.\n\n\n if (insertionPoint && typeof insertionPoint.nodeType === 'number') {\n var insertionPointElement = insertionPoint;\n var parentNode = insertionPointElement.parentNode;\n if (parentNode) parentNode.insertBefore(style, insertionPointElement.nextSibling);else process.env.NODE_ENV !== \"production\" ? warning(false, '[JSS] Insertion point is not in the DOM.') : void 0;\n return;\n }\n\n getHead().appendChild(style);\n}\n/**\n * Read jss nonce setting from the page if the user has set it.\n */\n\n\nvar getNonce = memoize(function () {\n var node = document.querySelector('meta[property=\"csp-nonce\"]');\n return node ? node.getAttribute('content') : null;\n});\n\nvar _insertRule = function insertRule(container, rule, index) {\n try {\n if ('insertRule' in container) {\n container.insertRule(rule, index);\n } // Keyframes rule.\n else if ('appendRule' in container) {\n container.appendRule(rule);\n }\n } catch (err) {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] \" + err.message) : void 0;\n return false;\n }\n\n return container.cssRules[index];\n};\n\nvar getValidRuleInsertionIndex = function getValidRuleInsertionIndex(container, index) {\n var maxIndex = container.cssRules.length; // In case previous insertion fails, passed index might be wrong\n\n if (index === undefined || index > maxIndex) {\n // eslint-disable-next-line no-param-reassign\n return maxIndex;\n }\n\n return index;\n};\n\nvar createStyle = function createStyle() {\n var el = document.createElement('style'); // Without it, IE will have a broken source order specificity if we\n // insert rules after we insert the style tag.\n // It seems to kick-off the source order specificity algorithm.\n\n el.textContent = '\\n';\n return el;\n};\n\nvar DomRenderer =\n/*#__PURE__*/\nfunction () {\n // Will be empty if link: true option is not set, because\n // it is only for use together with insertRule API.\n function DomRenderer(sheet) {\n this.getPropertyValue = getPropertyValue;\n this.setProperty = setProperty;\n this.removeProperty = removeProperty;\n this.setSelector = setSelector;\n this.hasInsertedRules = false;\n this.cssRules = [];\n // There is no sheet when the renderer is used from a standalone StyleRule.\n if (sheet) sheets.add(sheet);\n this.sheet = sheet;\n\n var _ref = this.sheet ? this.sheet.options : {},\n media = _ref.media,\n meta = _ref.meta,\n element = _ref.element;\n\n this.element = element || createStyle();\n this.element.setAttribute('data-jss', '');\n if (media) this.element.setAttribute('media', media);\n if (meta) this.element.setAttribute('data-meta', meta);\n var nonce = getNonce();\n if (nonce) this.element.setAttribute('nonce', nonce);\n }\n /**\n * Insert style element into render tree.\n */\n\n\n var _proto = DomRenderer.prototype;\n\n _proto.attach = function attach() {\n // In the case the element node is external and it is already in the DOM.\n if (this.element.parentNode || !this.sheet) return;\n insertStyle(this.element, this.sheet.options); // When rules are inserted using `insertRule` API, after `sheet.detach().attach()`\n // most browsers create a new CSSStyleSheet, except of all IEs.\n\n var deployed = Boolean(this.sheet && this.sheet.deployed);\n\n if (this.hasInsertedRules && deployed) {\n this.hasInsertedRules = false;\n this.deploy();\n }\n }\n /**\n * Remove style element from render tree.\n */\n ;\n\n _proto.detach = function detach() {\n if (!this.sheet) return;\n var parentNode = this.element.parentNode;\n if (parentNode) parentNode.removeChild(this.element); // In the most browsers, rules inserted using insertRule() API will be lost when style element is removed.\n // Though IE will keep them and we need a consistent behavior.\n\n if (this.sheet.options.link) {\n this.cssRules = [];\n this.element.textContent = '\\n';\n }\n }\n /**\n * Inject CSS string into element.\n */\n ;\n\n _proto.deploy = function deploy() {\n var sheet = this.sheet;\n if (!sheet) return;\n\n if (sheet.options.link) {\n this.insertRules(sheet.rules);\n return;\n }\n\n this.element.textContent = \"\\n\" + sheet.toString() + \"\\n\";\n }\n /**\n * Insert RuleList into an element.\n */\n ;\n\n _proto.insertRules = function insertRules(rules, nativeParent) {\n for (var i = 0; i < rules.index.length; i++) {\n this.insertRule(rules.index[i], i, nativeParent);\n }\n }\n /**\n * Insert a rule into element.\n */\n ;\n\n _proto.insertRule = function insertRule(rule, index, nativeParent) {\n if (nativeParent === void 0) {\n nativeParent = this.element.sheet;\n }\n\n if (rule.rules) {\n var parent = rule;\n var latestNativeParent = nativeParent;\n\n if (rule.type === 'conditional' || rule.type === 'keyframes') {\n var _insertionIndex = getValidRuleInsertionIndex(nativeParent, index); // We need to render the container without children first.\n\n\n latestNativeParent = _insertRule(nativeParent, parent.toString({\n children: false\n }), _insertionIndex);\n\n if (latestNativeParent === false) {\n return false;\n }\n\n this.refCssRule(rule, _insertionIndex, latestNativeParent);\n }\n\n this.insertRules(parent.rules, latestNativeParent);\n return latestNativeParent;\n }\n\n var ruleStr = rule.toString();\n if (!ruleStr) return false;\n var insertionIndex = getValidRuleInsertionIndex(nativeParent, index);\n\n var nativeRule = _insertRule(nativeParent, ruleStr, insertionIndex);\n\n if (nativeRule === false) {\n return false;\n }\n\n this.hasInsertedRules = true;\n this.refCssRule(rule, insertionIndex, nativeRule);\n return nativeRule;\n };\n\n _proto.refCssRule = function refCssRule(rule, index, cssRule) {\n rule.renderable = cssRule; // We only want to reference the top level rules, deleteRule API doesn't support removing nested rules\n // like rules inside media queries or keyframes\n\n if (rule.options.parent instanceof StyleSheet) {\n this.cssRules[index] = cssRule;\n }\n }\n /**\n * Delete a rule.\n */\n ;\n\n _proto.deleteRule = function deleteRule(cssRule) {\n var sheet = this.element.sheet;\n var index = this.indexOf(cssRule);\n if (index === -1) return false;\n sheet.deleteRule(index);\n this.cssRules.splice(index, 1);\n return true;\n }\n /**\n * Get index of a CSS Rule.\n */\n ;\n\n _proto.indexOf = function indexOf(cssRule) {\n return this.cssRules.indexOf(cssRule);\n }\n /**\n * Generate a new CSS rule and replace the existing one.\n *\n * Only used for some old browsers because they can't set a selector.\n */\n ;\n\n _proto.replaceRule = function replaceRule(cssRule, rule) {\n var index = this.indexOf(cssRule);\n if (index === -1) return false;\n this.element.sheet.deleteRule(index);\n this.cssRules.splice(index, 1);\n return this.insertRule(rule, index);\n }\n /**\n * Get all rules elements.\n */\n ;\n\n _proto.getRules = function getRules() {\n return this.element.sheet.cssRules;\n };\n\n return DomRenderer;\n}();\n\nvar instanceCounter = 0;\n\nvar Jss =\n/*#__PURE__*/\nfunction () {\n function Jss(options) {\n this.id = instanceCounter++;\n this.version = \"10.8.2\";\n this.plugins = new PluginsRegistry();\n this.options = {\n id: {\n minify: false\n },\n createGenerateId: createGenerateId,\n Renderer: isInBrowser ? DomRenderer : null,\n plugins: []\n };\n this.generateId = createGenerateId({\n minify: false\n });\n\n for (var i = 0; i < plugins.length; i++) {\n this.plugins.use(plugins[i], {\n queue: 'internal'\n });\n }\n\n this.setup(options);\n }\n /**\n * Prepares various options, applies plugins.\n * Should not be used twice on the same instance, because there is no plugins\n * deduplication logic.\n */\n\n\n var _proto = Jss.prototype;\n\n _proto.setup = function setup(options) {\n if (options === void 0) {\n options = {};\n }\n\n if (options.createGenerateId) {\n this.options.createGenerateId = options.createGenerateId;\n }\n\n if (options.id) {\n this.options.id = _extends({}, this.options.id, options.id);\n }\n\n if (options.createGenerateId || options.id) {\n this.generateId = this.options.createGenerateId(this.options.id);\n }\n\n if (options.insertionPoint != null) this.options.insertionPoint = options.insertionPoint;\n\n if ('Renderer' in options) {\n this.options.Renderer = options.Renderer;\n } // eslint-disable-next-line prefer-spread\n\n\n if (options.plugins) this.use.apply(this, options.plugins);\n return this;\n }\n /**\n * Create a Style Sheet.\n */\n ;\n\n _proto.createStyleSheet = function createStyleSheet(styles, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n index = _options.index;\n\n if (typeof index !== 'number') {\n index = sheets.index === 0 ? 0 : sheets.index + 1;\n }\n\n var sheet = new StyleSheet(styles, _extends({}, options, {\n jss: this,\n generateId: options.generateId || this.generateId,\n insertionPoint: this.options.insertionPoint,\n Renderer: this.options.Renderer,\n index: index\n }));\n this.plugins.onProcessSheet(sheet);\n return sheet;\n }\n /**\n * Detach the Style Sheet and remove it from the registry.\n */\n ;\n\n _proto.removeStyleSheet = function removeStyleSheet(sheet) {\n sheet.detach();\n sheets.remove(sheet);\n return this;\n }\n /**\n * Create a rule without a Style Sheet.\n * [Deprecated] will be removed in the next major version.\n */\n ;\n\n _proto.createRule = function createRule$1(name, style, options) {\n if (style === void 0) {\n style = {};\n }\n\n if (options === void 0) {\n options = {};\n }\n\n // Enable rule without name for inline styles.\n if (typeof name === 'object') {\n return this.createRule(undefined, name, style);\n }\n\n var ruleOptions = _extends({}, options, {\n name: name,\n jss: this,\n Renderer: this.options.Renderer\n });\n\n if (!ruleOptions.generateId) ruleOptions.generateId = this.generateId;\n if (!ruleOptions.classes) ruleOptions.classes = {};\n if (!ruleOptions.keyframes) ruleOptions.keyframes = {};\n\n var rule = createRule(name, style, ruleOptions);\n\n if (rule) this.plugins.onProcessRule(rule);\n return rule;\n }\n /**\n * Register plugin. Passed function will be invoked with a rule instance.\n */\n ;\n\n _proto.use = function use() {\n var _this = this;\n\n for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {\n plugins[_key] = arguments[_key];\n }\n\n plugins.forEach(function (plugin) {\n _this.plugins.use(plugin);\n });\n return this;\n };\n\n return Jss;\n}();\n\nvar createJss = function createJss(options) {\n return new Jss(options);\n};\n\n/**\n * SheetsManager is like a WeakMap which is designed to count StyleSheet\n * instances and attach/detach automatically.\n * Used in react-jss.\n */\n\nvar SheetsManager =\n/*#__PURE__*/\nfunction () {\n function SheetsManager() {\n this.length = 0;\n this.sheets = new WeakMap();\n }\n\n var _proto = SheetsManager.prototype;\n\n _proto.get = function get(key) {\n var entry = this.sheets.get(key);\n return entry && entry.sheet;\n };\n\n _proto.add = function add(key, sheet) {\n if (this.sheets.has(key)) return;\n this.length++;\n this.sheets.set(key, {\n sheet: sheet,\n refs: 0\n });\n };\n\n _proto.manage = function manage(key) {\n var entry = this.sheets.get(key);\n\n if (entry) {\n if (entry.refs === 0) {\n entry.sheet.attach();\n }\n\n entry.refs++;\n return entry.sheet;\n }\n\n warning(false, \"[JSS] SheetsManager: can't find sheet to manage\");\n return undefined;\n };\n\n _proto.unmanage = function unmanage(key) {\n var entry = this.sheets.get(key);\n\n if (entry) {\n if (entry.refs > 0) {\n entry.refs--;\n if (entry.refs === 0) entry.sheet.detach();\n }\n } else {\n warning(false, \"SheetsManager: can't find sheet to unmanage\");\n }\n };\n\n _createClass(SheetsManager, [{\n key: \"size\",\n get: function get() {\n return this.length;\n }\n }]);\n\n return SheetsManager;\n}();\n\n/**\n* Export a constant indicating if this browser has CSSTOM support.\n* https://developers.google.com/web/updates/2018/03/cssom\n*/\nvar hasCSSTOMSupport = typeof CSS === 'object' && CSS != null && 'number' in CSS;\n\n/**\n * Extracts a styles object with only props that contain function values.\n */\nfunction getDynamicStyles(styles) {\n var to = null;\n\n for (var key in styles) {\n var value = styles[key];\n var type = typeof value;\n\n if (type === 'function') {\n if (!to) to = {};\n to[key] = value;\n } else if (type === 'object' && value !== null && !Array.isArray(value)) {\n var extracted = getDynamicStyles(value);\n\n if (extracted) {\n if (!to) to = {};\n to[key] = extracted;\n }\n }\n }\n\n return to;\n}\n\n/**\n * A better abstraction over CSS.\n *\n * @copyright Oleg Isonen (Slobodskoi) / Isonen 2014-present\n * @website https://github.com/cssinjs/jss\n * @license MIT\n */\nvar index = createJss();\n\nexport default index;\nexport { RuleList, SheetsManager, SheetsRegistry, createJss as create, createGenerateId, createRule, getDynamicStyles, hasCSSTOMSupport, sheets, toCssValue };\n","function _extends() {\n module.exports = _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}\n\nmodule.exports = _extends;","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/*\n * Helper function for padArray\n */\nfunction padArrayChunk({source, target, start = 0, end, size, getData}) {\n end = end || target.length;\n\n const sourceLength = source.length;\n const targetLength = end - start;\n\n if (sourceLength > targetLength) {\n target.set(source.subarray(0, targetLength), start);\n return;\n }\n\n target.set(source, start);\n\n if (!getData) {\n return;\n }\n\n // source is not large enough to fill target space, call `getData` to get filler data\n let i = sourceLength;\n while (i < targetLength) {\n const datum = getData(i, source);\n for (let j = 0; j < size; j++) {\n target[start + i] = datum[j] || 0;\n i++;\n }\n }\n}\n\n/*\n * The padArray function stretches a source array to the size of a target array.\n The arrays can have internal structures (like the attributes of PathLayer and\n SolidPolygonLayer), defined by the optional sourceStartIndices and targetStartIndices parameters.\n If the target array is larger, the getData callback is used to fill in the blanks.\n * @params {TypedArray} source - original data\n * @params {TypedArray} target - output data\n * @params {Number} size - length per datum\n * @params {Function} getData - callback to get new data when source is short\n * @params {Array} [sourceStartIndices] - subdivision of the original data in [object0StartIndex, object1StartIndex, ...]\n * @params {Array} [targetStartIndices] - subdivision of the output data in [object0StartIndex, object1StartIndex, ...]\n */\nexport function padArray({source, target, size, getData, sourceStartIndices, targetStartIndices}) {\n if (!Array.isArray(targetStartIndices)) {\n // Flat arrays\n padArrayChunk({\n source,\n target,\n size,\n getData\n });\n return target;\n }\n\n // Arrays have internal structure\n let sourceIndex = 0;\n let targetIndex = 0;\n const getChunkData = getData && ((i, chunk) => getData(i + targetIndex, chunk));\n\n const n = Math.min(sourceStartIndices.length, targetStartIndices.length);\n\n for (let i = 1; i < n; i++) {\n const nextSourceIndex = sourceStartIndices[i] * size;\n const nextTargetIndex = targetStartIndices[i] * size;\n\n padArrayChunk({\n source: source.subarray(sourceIndex, nextSourceIndex),\n target,\n start: targetIndex,\n end: nextTargetIndex,\n size,\n getData: getChunkData\n });\n\n sourceIndex = nextSourceIndex;\n targetIndex = nextTargetIndex;\n }\n\n if (targetIndex < target.length) {\n padArrayChunk({\n source: [],\n target,\n start: targetIndex,\n size,\n getData: getChunkData\n });\n }\n\n return target;\n}\n","import {padArray} from '../../utils/array-utils';\n\nconst DEFAULT_TRANSITION_SETTINGS = {\n interpolation: {\n duration: 0,\n easing: t => t\n },\n spring: {\n stiffness: 0.05,\n damping: 0.5\n }\n};\n\nexport function normalizeTransitionSettings(userSettings, layerSettings) {\n if (!userSettings) {\n return null;\n }\n if (Number.isFinite(userSettings)) {\n userSettings = {duration: userSettings};\n }\n userSettings.type = userSettings.type || 'interpolation';\n return {\n ...DEFAULT_TRANSITION_SETTINGS[userSettings.type],\n ...layerSettings,\n ...userSettings\n };\n}\n\n// NOTE: NOT COPYING OVER OFFSET OR STRIDE HERE BECAUSE:\n// (1) WE DON'T SUPPORT INTERLEAVED BUFFERS FOR TRANSITIONS\n// (2) BUFFERS WITH OFFSETS ALWAYS CONTAIN VALUES OF THE SAME SIZE\n// (3) THE OPERATIONS IN THE SHADER ARE PER-COMPONENT (addition and scaling)\nexport function getSourceBufferAttribute(gl, attribute) {\n // The Attribute we pass to Transform as a sourceBuffer must have {divisor: 0}\n // so we create a copy of the attribute (with divisor=0) to use when running\n // transform feedback\n const buffer = attribute.getBuffer();\n if (buffer) {\n return [\n attribute.getBuffer(),\n {\n divisor: 0,\n size: attribute.size,\n normalized: attribute.settings.normalized\n }\n ];\n }\n // constant\n // don't pass normalized here because the `value` from a normalized attribute is\n // already normalized\n return attribute.value;\n}\n\nexport function getAttributeTypeFromSize(size) {\n switch (size) {\n case 1:\n return 'float';\n case 2:\n return 'vec2';\n case 3:\n return 'vec3';\n case 4:\n return 'vec4';\n default:\n throw new Error(`No defined attribute type for size \"${size}\"`);\n }\n}\n\nexport function cycleBuffers(buffers) {\n buffers.push(buffers.shift());\n}\n\nexport function getAttributeBufferLength(attribute, numInstances) {\n const {doublePrecision, settings, value, size} = attribute;\n const multiplier = doublePrecision && value instanceof Float64Array ? 2 : 1;\n return (settings.noAlloc ? value.length : numInstances * size) * multiplier;\n}\n\n// This helper is used when transitioning attributes from a set of values in one buffer layout\n// to a set of values in a different buffer layout. (Buffer layouts are used when attribute values\n// within a buffer should be grouped for drawElements, like the Polygon layer.) For example, a\n// buffer layout of [3, 4] might have data [A1, A2, A3, B1, B2, B3, B4]. If it needs to transition\n// to a buffer layout of [4, 2], it should produce a buffer, using the transition setting's `enter`\n// function, that looks like this: [A1, A2, A3, A4 (user `enter` fn), B1, B2, 0]. Note: the final\n// 0 in this buffer is because we never shrink buffers, only grow them, for performance reasons.\nexport function padBuffer({\n buffer,\n numInstances,\n attribute,\n fromLength,\n fromStartIndices,\n getData = x => x\n}) {\n // TODO: move the precisionMultiplier logic to the attribute when retrieving\n // its `size` and `elementOffset`?\n const precisionMultiplier =\n attribute.doublePrecision && attribute.value instanceof Float64Array ? 2 : 1;\n const size = attribute.size * precisionMultiplier;\n const byteOffset = attribute.byteOffset;\n const toStartIndices = attribute.startIndices;\n const hasStartIndices = fromStartIndices && toStartIndices;\n const toLength = getAttributeBufferLength(attribute, numInstances);\n const isConstant = attribute.state.constant;\n\n // check if buffer needs to be padded\n if (!hasStartIndices && fromLength >= toLength) {\n return;\n }\n\n const toData = isConstant\n ? attribute.value\n : attribute.getBuffer().getData({srcByteOffset: byteOffset});\n if (attribute.settings.normalized && !isConstant) {\n const getter = getData;\n getData = (value, chunk) => attribute._normalizeConstant(getter(value, chunk));\n }\n\n const getMissingData = isConstant\n ? (i, chunk) => getData(toData, chunk)\n : (i, chunk) => getData(toData.subarray(i, i + size), chunk);\n\n const source = buffer.getData({length: fromLength});\n const data = new Float32Array(toLength);\n padArray({\n source,\n target: data,\n sourceStartIndices: fromStartIndices,\n targetStartIndices: toStartIndices,\n size,\n getData: getMissingData\n });\n\n // TODO: support offset in buffer.setData?\n if (buffer.byteLength < data.byteLength + byteOffset) {\n buffer.reallocate(data.byteLength + byteOffset);\n }\n buffer.subData({data, offset: byteOffset});\n}\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nvar helpers_1 = require(\"@turf/helpers\");\r\n/**\r\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\r\n *\r\n * @name getCoord\r\n * @param {Array|Geometry|Feature} coord GeoJSON Point or an Array of numbers\r\n * @returns {Array} coordinates\r\n * @example\r\n * var pt = turf.point([10, 10]);\r\n *\r\n * var coord = turf.getCoord(pt);\r\n * //= [10, 10]\r\n */\r\nfunction getCoord(coord) {\r\n if (!coord) {\r\n throw new Error(\"coord is required\");\r\n }\r\n if (!Array.isArray(coord)) {\r\n if (coord.type === \"Feature\" && coord.geometry !== null && coord.geometry.type === \"Point\") {\r\n return coord.geometry.coordinates;\r\n }\r\n if (coord.type === \"Point\") {\r\n return coord.coordinates;\r\n }\r\n }\r\n if (Array.isArray(coord) && coord.length >= 2 && !Array.isArray(coord[0]) && !Array.isArray(coord[1])) {\r\n return coord;\r\n }\r\n throw new Error(\"coord must be GeoJSON Point or an Array of numbers\");\r\n}\r\nexports.getCoord = getCoord;\r\n/**\r\n * Unwrap coordinates from a Feature, Geometry Object or an Array\r\n *\r\n * @name getCoords\r\n * @param {Array|Geometry|Feature} coords Feature, Geometry Object or an Array\r\n * @returns {Array} coordinates\r\n * @example\r\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\r\n *\r\n * var coords = turf.getCoords(poly);\r\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\r\n */\r\nfunction getCoords(coords) {\r\n if (Array.isArray(coords)) {\r\n return coords;\r\n }\r\n // Feature\r\n if (coords.type === \"Feature\") {\r\n if (coords.geometry !== null) {\r\n return coords.geometry.coordinates;\r\n }\r\n }\r\n else {\r\n // Geometry\r\n if (coords.coordinates) {\r\n return coords.coordinates;\r\n }\r\n }\r\n throw new Error(\"coords must be GeoJSON Feature, Geometry Object or an Array\");\r\n}\r\nexports.getCoords = getCoords;\r\n/**\r\n * Checks if coordinates contains a number\r\n *\r\n * @name containsNumber\r\n * @param {Array} coordinates GeoJSON Coordinates\r\n * @returns {boolean} true if Array contains a number\r\n */\r\nfunction containsNumber(coordinates) {\r\n if (coordinates.length > 1 && helpers_1.isNumber(coordinates[0]) && helpers_1.isNumber(coordinates[1])) {\r\n return true;\r\n }\r\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\r\n return containsNumber(coordinates[0]);\r\n }\r\n throw new Error(\"coordinates must only contain numbers\");\r\n}\r\nexports.containsNumber = containsNumber;\r\n/**\r\n * Enforce expectations about types of GeoJSON objects for Turf.\r\n *\r\n * @name geojsonType\r\n * @param {GeoJSON} value any GeoJSON object\r\n * @param {string} type expected GeoJSON type\r\n * @param {string} name name of calling function\r\n * @throws {Error} if value is not the expected type.\r\n */\r\nfunction geojsonType(value, type, name) {\r\n if (!type || !name) {\r\n throw new Error(\"type and name required\");\r\n }\r\n if (!value || value.type !== type) {\r\n throw new Error(\"Invalid input to \" + name + \": must be a \" + type + \", given \" + value.type);\r\n }\r\n}\r\nexports.geojsonType = geojsonType;\r\n/**\r\n * Enforce expectations about types of {@link Feature} inputs for Turf.\r\n * Internally this uses {@link geojsonType} to judge geometry types.\r\n *\r\n * @name featureOf\r\n * @param {Feature} feature a feature with an expected geometry type\r\n * @param {string} type expected GeoJSON type\r\n * @param {string} name name of calling function\r\n * @throws {Error} error if value is not the expected type.\r\n */\r\nfunction featureOf(feature, type, name) {\r\n if (!feature) {\r\n throw new Error(\"No feature passed\");\r\n }\r\n if (!name) {\r\n throw new Error(\".featureOf() requires a name\");\r\n }\r\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\r\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\r\n }\r\n if (!feature.geometry || feature.geometry.type !== type) {\r\n throw new Error(\"Invalid input to \" + name + \": must be a \" + type + \", given \" + feature.geometry.type);\r\n }\r\n}\r\nexports.featureOf = featureOf;\r\n/**\r\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\r\n * Internally this uses {@link geojsonType} to judge geometry types.\r\n *\r\n * @name collectionOf\r\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\r\n * @param {string} type expected GeoJSON type\r\n * @param {string} name name of calling function\r\n * @throws {Error} if value is not the expected type.\r\n */\r\nfunction collectionOf(featureCollection, type, name) {\r\n if (!featureCollection) {\r\n throw new Error(\"No featureCollection passed\");\r\n }\r\n if (!name) {\r\n throw new Error(\".collectionOf() requires a name\");\r\n }\r\n if (!featureCollection || featureCollection.type !== \"FeatureCollection\") {\r\n throw new Error(\"Invalid input to \" + name + \", FeatureCollection required\");\r\n }\r\n for (var _i = 0, _a = featureCollection.features; _i < _a.length; _i++) {\r\n var feature = _a[_i];\r\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\r\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\r\n }\r\n if (!feature.geometry || feature.geometry.type !== type) {\r\n throw new Error(\"Invalid input to \" + name + \": must be a \" + type + \", given \" + feature.geometry.type);\r\n }\r\n }\r\n}\r\nexports.collectionOf = collectionOf;\r\n/**\r\n * Get Geometry from Feature or Geometry Object\r\n *\r\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\r\n * @returns {Geometry|null} GeoJSON Geometry Object\r\n * @throws {Error} if geojson is not a Feature or Geometry Object\r\n * @example\r\n * var point = {\r\n * \"type\": \"Feature\",\r\n * \"properties\": {},\r\n * \"geometry\": {\r\n * \"type\": \"Point\",\r\n * \"coordinates\": [110, 40]\r\n * }\r\n * }\r\n * var geom = turf.getGeom(point)\r\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\r\n */\r\nfunction getGeom(geojson) {\r\n if (geojson.type === \"Feature\") {\r\n return geojson.geometry;\r\n }\r\n return geojson;\r\n}\r\nexports.getGeom = getGeom;\r\n/**\r\n * Get GeoJSON object's type, Geometry type is prioritize.\r\n *\r\n * @param {GeoJSON} geojson GeoJSON object\r\n * @param {string} [name=\"geojson\"] name of the variable to display in error message\r\n * @returns {string} GeoJSON type\r\n * @example\r\n * var point = {\r\n * \"type\": \"Feature\",\r\n * \"properties\": {},\r\n * \"geometry\": {\r\n * \"type\": \"Point\",\r\n * \"coordinates\": [110, 40]\r\n * }\r\n * }\r\n * var geom = turf.getType(point)\r\n * //=\"Point\"\r\n */\r\nfunction getType(geojson, name) {\r\n if (geojson.type === \"FeatureCollection\") {\r\n return \"FeatureCollection\";\r\n }\r\n if (geojson.type === \"GeometryCollection\") {\r\n return \"GeometryCollection\";\r\n }\r\n if (geojson.type === \"Feature\" && geojson.geometry !== null) {\r\n return geojson.geometry.type;\r\n }\r\n return geojson.type;\r\n}\r\nexports.getType = getType;\r\n","const debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return (\n compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n )\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier) {\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier)\n this.inc('pre', identifier)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier)\n }\n this.inc('pre', identifier)\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre':\n if (this.prerelease.length === 0) {\n this.prerelease = [0]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n this.prerelease.push(0)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n if (this.prerelease[0] === identifier) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = [identifier, 0]\n }\n } else {\n this.prerelease = [identifier, 0]\n }\n }\n break\n\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.format()\n this.raw = this.version\n return this\n }\n}\n\nmodule.exports = SemVer\n","var isObject = require('./isObject'),\n now = require('./now'),\n toNumber = require('./toNumber');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\nmodule.exports = debounce;\n","// Returns true if given object is empty, false otherwise.\nexport function isObjectEmpty(object) {\n for (const key in object) {\n return false;\n }\n return true;\n}\n\nexport function deepArrayEqual(x, y) {\n if (x === y) {\n return true;\n }\n const isArrayX = Array.isArray(x) || ArrayBuffer.isView(x);\n const isArrayY = Array.isArray(y) || ArrayBuffer.isView(y);\n if (isArrayX && isArrayY && x.length === y.length) {\n for (let i = 0; i < x.length; ++i) {\n if (x[i] !== y[i]) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n","import {assert} from '../utils/assert';\n\n// Resolve a WebGL enumeration name (returns itself if already a number)\nexport function getKeyValue(gl, name) {\n // If not a string, return (assume number)\n if (typeof name !== 'string') {\n return name;\n }\n\n // If string converts to number, return number\n const number = Number(name);\n if (!isNaN(number)) {\n return number;\n }\n\n // Look up string, after removing any 'GL.' or 'gl.' prefix\n name = name.replace(/^.*\\./, '');\n const value = gl[name];\n assert(value !== undefined, `Accessing undefined constant GL.${name}`);\n return value;\n}\n\nexport function getKey(gl, value) {\n value = Number(value);\n for (const key in gl) {\n if (gl[key] === value) {\n return `GL.${key}`;\n }\n }\n return String(value);\n}\n\nexport function getKeyType(gl, value) {\n assert(value !== undefined, 'undefined key');\n value = Number(value);\n for (const key in gl) {\n if (gl[key] === value) {\n return `GL.${key}`;\n }\n }\n return String(value);\n}\n","/**\n * @license Complex.js v2.0.11 11/02/2016\n *\n * Copyright (c) 2016, Robert Eisele (robert@xarg.org)\n * Dual licensed under the MIT or GPL Version 2 licenses.\n **/\n\n/**\n *\n * This class allows the manipulation of complex numbers.\n * You can pass a complex number in different formats. Either as object, double, string or two integer parameters.\n *\n * Object form\n * { re: , im: }\n * { arg: , abs: }\n * { phi: , r: }\n *\n * Array / Vector form\n * [ real, imaginary ]\n *\n * Double form\n * 99.3 - Single double value\n *\n * String form\n * '23.1337' - Simple real number\n * '15+3i' - a simple complex number\n * '3-i' - a simple complex number\n *\n * Example:\n *\n * var c = new Complex('99.3+8i');\n * c.mul({r: 3, i: 9}).div(4.9).sub(3, 2);\n *\n */\n\n(function(root) {\n\n 'use strict';\n\n var cosh = function(x) {\n return (Math.exp(x) + Math.exp(-x)) * 0.5;\n };\n\n var sinh = function(x) {\n return (Math.exp(x) - Math.exp(-x)) * 0.5;\n };\n\n /**\n * Calculates cos(x) - 1 using Taylor series if x is small.\n *\n * @param {number} x\n * @returns {number} cos(x) - 1\n */\n\n var cosm1 = function(x) {\n var limit = Math.PI/4;\n if (x < -limit || x > limit) {\n return (Math.cos(x) - 1.0);\n }\n\n var xx = x * x;\n return xx *\n (-0.5 + xx *\n (1/24 + xx *\n (-1/720 + xx *\n (1/40320 + xx *\n (-1/3628800 + xx *\n (1/4790014600 + xx *\n (-1/87178291200 + xx *\n (1/20922789888000)\n )\n )\n )\n )\n )\n )\n )\n };\n\n var hypot = function(x, y) {\n\n var a = Math.abs(x);\n var b = Math.abs(y);\n\n if (a < 3000 && b < 3000) {\n return Math.sqrt(a * a + b * b);\n }\n\n if (a < b) {\n a = b;\n b = x / y;\n } else {\n b = y / x;\n }\n return a * Math.sqrt(1 + b * b);\n };\n\n var parser_exit = function() {\n throw SyntaxError('Invalid Param');\n };\n\n /**\n * Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows\n *\n * @param {number} a\n * @param {number} b\n * @returns {number}\n */\n function logHypot(a, b) {\n\n var _a = Math.abs(a);\n var _b = Math.abs(b);\n\n if (a === 0) {\n return Math.log(_b);\n }\n\n if (b === 0) {\n return Math.log(_a);\n }\n\n if (_a < 3000 && _b < 3000) {\n return Math.log(a * a + b * b) * 0.5;\n }\n\n /* I got 4 ideas to compute this property without overflow:\n *\n * Testing 1000000 times with random samples for a,b ∈ [1, 1000000000] against a big decimal library to get an error estimate\n *\n * 1. Only eliminate the square root: (OVERALL ERROR: 3.9122483030951116e-11)\n\n Math.log(a * a + b * b) / 2\n\n *\n *\n * 2. Try to use the non-overflowing pythagoras: (OVERALL ERROR: 8.889760039210159e-10)\n\n var fn = function(a, b) {\n a = Math.abs(a);\n b = Math.abs(b);\n var t = Math.min(a, b);\n a = Math.max(a, b);\n t = t / a;\n\n return Math.log(a) + Math.log(1 + t * t) / 2;\n };\n\n * 3. Abuse the identity cos(atan(y/x) = x / sqrt(x^2+y^2): (OVERALL ERROR: 3.4780178737037204e-10)\n\n Math.log(a / Math.cos(Math.atan2(b, a)))\n\n * 4. Use 3. and apply log rules: (OVERALL ERROR: 1.2014087502620896e-9)\n\n Math.log(a) - Math.log(Math.cos(Math.atan2(b, a)))\n\n */\n\n return Math.log(a / Math.cos(Math.atan2(b, a)));\n }\n\n var parse = function(a, b) {\n\n var z = {'re': 0, 'im': 0};\n\n if (a === undefined || a === null) {\n z['re'] =\n z['im'] = 0;\n } else if (b !== undefined) {\n z['re'] = a;\n z['im'] = b;\n } else\n switch (typeof a) {\n\n case 'object':\n\n if ('im' in a && 're' in a) {\n z['re'] = a['re'];\n z['im'] = a['im'];\n } else if ('abs' in a && 'arg' in a) {\n if (!Number.isFinite(a['abs']) && Number.isFinite(a['arg'])) {\n return Complex['INFINITY'];\n }\n z['re'] = a['abs'] * Math.cos(a['arg']);\n z['im'] = a['abs'] * Math.sin(a['arg']);\n } else if ('r' in a && 'phi' in a) {\n if (!Number.isFinite(a['r']) && Number.isFinite(a['phi'])) {\n return Complex['INFINITY'];\n }\n z['re'] = a['r'] * Math.cos(a['phi']);\n z['im'] = a['r'] * Math.sin(a['phi']);\n } else if (a.length === 2) { // Quick array check\n z['re'] = a[0];\n z['im'] = a[1];\n } else {\n parser_exit();\n }\n break;\n\n case 'string':\n\n z['im'] = /* void */\n z['re'] = 0;\n\n var tokens = a.match(/\\d+\\.?\\d*e[+-]?\\d+|\\d+\\.?\\d*|\\.\\d+|./g);\n var plus = 1;\n var minus = 0;\n\n if (tokens === null) {\n parser_exit();\n }\n\n for (var i = 0; i < tokens.length; i++) {\n\n var c = tokens[i];\n\n if (c === ' ' || c === '\\t' || c === '\\n') {\n /* void */\n } else if (c === '+') {\n plus++;\n } else if (c === '-') {\n minus++;\n } else if (c === 'i' || c === 'I') {\n\n if (plus + minus === 0) {\n parser_exit();\n }\n\n if (tokens[i + 1] !== ' ' && !isNaN(tokens[i + 1])) {\n z['im'] += parseFloat((minus % 2 ? '-' : '') + tokens[i + 1]);\n i++;\n } else {\n z['im'] += parseFloat((minus % 2 ? '-' : '') + '1');\n }\n plus = minus = 0;\n\n } else {\n\n if (plus + minus === 0 || isNaN(c)) {\n parser_exit();\n }\n\n if (tokens[i + 1] === 'i' || tokens[i + 1] === 'I') {\n z['im'] += parseFloat((minus % 2 ? '-' : '') + c);\n i++;\n } else {\n z['re'] += parseFloat((minus % 2 ? '-' : '') + c);\n }\n plus = minus = 0;\n }\n }\n\n // Still something on the stack\n if (plus + minus > 0) {\n parser_exit();\n }\n break;\n\n case 'number':\n z['im'] = 0;\n z['re'] = a;\n break;\n\n default:\n parser_exit();\n }\n\n if (isNaN(z['re']) || isNaN(z['im'])) {\n // If a calculation is NaN, we treat it as NaN and don't throw\n //parser_exit();\n }\n\n return z;\n };\n\n /**\n * @constructor\n * @returns {Complex}\n */\n function Complex(a, b) {\n\n if (!(this instanceof Complex)) {\n return new Complex(a, b);\n }\n\n var z = parse(a, b);\n\n this['re'] = z['re'];\n this['im'] = z['im'];\n }\n\n Complex.prototype = {\n\n 're': 0,\n 'im': 0,\n\n /**\n * Calculates the sign of a complex number, which is a normalized complex\n *\n * @returns {Complex}\n */\n 'sign': function() {\n\n var abs = this['abs']();\n\n return new Complex(\n this['re'] / abs,\n this['im'] / abs);\n },\n\n /**\n * Adds two complex numbers\n *\n * @returns {Complex}\n */\n 'add': function(a, b) {\n\n var z = new Complex(a, b);\n\n // Infinity + Infinity = NaN\n if (this['isInfinite']() && z['isInfinite']()) {\n return Complex['NAN'];\n }\n\n // Infinity + z = Infinity { where z != Infinity }\n if (this['isInfinite']() || z['isInfinite']()) {\n return Complex['INFINITY'];\n }\n\n return new Complex(\n this['re'] + z['re'],\n this['im'] + z['im']);\n },\n\n /**\n * Subtracts two complex numbers\n *\n * @returns {Complex}\n */\n 'sub': function(a, b) {\n\n var z = new Complex(a, b);\n\n // Infinity - Infinity = NaN\n if (this['isInfinite']() && z['isInfinite']()) {\n return Complex['NAN'];\n }\n\n // Infinity - z = Infinity { where z != Infinity }\n if (this['isInfinite']() || z['isInfinite']()) {\n return Complex['INFINITY'];\n }\n\n return new Complex(\n this['re'] - z['re'],\n this['im'] - z['im']);\n },\n\n /**\n * Multiplies two complex numbers\n *\n * @returns {Complex}\n */\n 'mul': function(a, b) {\n\n var z = new Complex(a, b);\n\n // Infinity * 0 = NaN\n if ((this['isInfinite']() && z['isZero']()) || (this['isZero']() && z['isInfinite']())) {\n return Complex['NAN'];\n }\n\n // Infinity * z = Infinity { where z != 0 }\n if (this['isInfinite']() || z['isInfinite']()) {\n return Complex['INFINITY'];\n }\n\n // Short circuit for real values\n if (z['im'] === 0 && this['im'] === 0) {\n return new Complex(this['re'] * z['re'], 0);\n }\n\n return new Complex(\n this['re'] * z['re'] - this['im'] * z['im'],\n this['re'] * z['im'] + this['im'] * z['re']);\n },\n\n /**\n * Divides two complex numbers\n *\n * @returns {Complex}\n */\n 'div': function(a, b) {\n\n var z = new Complex(a, b);\n\n // 0 / 0 = NaN and Infinity / Infinity = NaN\n if ((this['isZero']() && z['isZero']()) || (this['isInfinite']() && z['isInfinite']())) {\n return Complex['NAN'];\n }\n\n // Infinity / 0 = Infinity\n if (this['isInfinite']() || z['isZero']()) {\n return Complex['INFINITY'];\n }\n\n // 0 / Infinity = 0\n if (this['isZero']() || z['isInfinite']()) {\n return Complex['ZERO'];\n }\n\n a = this['re'];\n b = this['im'];\n\n var c = z['re'];\n var d = z['im'];\n var t, x;\n\n if (0 === d) {\n // Divisor is real\n return new Complex(a / c, b / c);\n }\n\n if (Math.abs(c) < Math.abs(d)) {\n\n x = c / d;\n t = c * x + d;\n\n return new Complex(\n (a * x + b) / t,\n (b * x - a) / t);\n\n } else {\n\n x = d / c;\n t = d * x + c;\n\n return new Complex(\n (a + b * x) / t,\n (b - a * x) / t);\n }\n },\n\n /**\n * Calculate the power of two complex numbers\n *\n * @returns {Complex}\n */\n 'pow': function(a, b) {\n\n var z = new Complex(a, b);\n\n a = this['re'];\n b = this['im'];\n\n if (z['isZero']()) {\n return Complex['ONE'];\n }\n\n // If the exponent is real\n if (z['im'] === 0) {\n\n if (b === 0 && a >= 0) {\n\n return new Complex(Math.pow(a, z['re']), 0);\n\n } else if (a === 0) { // If base is fully imaginary\n\n switch ((z['re'] % 4 + 4) % 4) {\n case 0:\n return new Complex(Math.pow(b, z['re']), 0);\n case 1:\n return new Complex(0, Math.pow(b, z['re']));\n case 2:\n return new Complex(-Math.pow(b, z['re']), 0);\n case 3:\n return new Complex(0, -Math.pow(b, z['re']));\n }\n }\n }\n\n /* I couldn't find a good formula, so here is a derivation and optimization\n *\n * z_1^z_2 = (a + bi)^(c + di)\n * = exp((c + di) * log(a + bi)\n * = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a))\n * =>...\n * Re = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * cos(d * log(a^2 + b^2) / 2 + c * atan2(b, a))\n * Im = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * sin(d * log(a^2 + b^2) / 2 + c * atan2(b, a))\n *\n * =>...\n * Re = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * cos(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a))\n * Im = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * sin(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a))\n *\n * =>\n * Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1))\n * Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1))\n *\n */\n\n if (a === 0 && b === 0 && z['re'] > 0 && z['im'] >= 0) {\n return Complex['ZERO'];\n }\n\n var arg = Math.atan2(b, a);\n var loh = logHypot(a, b);\n\n a = Math.exp(z['re'] * loh - z['im'] * arg);\n b = z['im'] * loh + z['re'] * arg;\n return new Complex(\n a * Math.cos(b),\n a * Math.sin(b));\n },\n\n /**\n * Calculate the complex square root\n *\n * @returns {Complex}\n */\n 'sqrt': function() {\n\n var a = this['re'];\n var b = this['im'];\n var r = this['abs']();\n\n var re, im;\n\n if (a >= 0) {\n\n if (b === 0) {\n return new Complex(Math.sqrt(a), 0);\n }\n\n re = 0.5 * Math.sqrt(2.0 * (r + a));\n } else {\n re = Math.abs(b) / Math.sqrt(2 * (r - a));\n }\n\n if (a <= 0) {\n im = 0.5 * Math.sqrt(2.0 * (r - a));\n } else {\n im = Math.abs(b) / Math.sqrt(2 * (r + a));\n }\n\n return new Complex(re, b < 0 ? -im : im);\n },\n\n /**\n * Calculate the complex exponent\n *\n * @returns {Complex}\n */\n 'exp': function() {\n\n var tmp = Math.exp(this['re']);\n\n if (this['im'] === 0) {\n //return new Complex(tmp, 0);\n }\n return new Complex(\n tmp * Math.cos(this['im']),\n tmp * Math.sin(this['im']));\n },\n\n /**\n * Calculate the complex exponent and subtracts one.\n *\n * This may be more accurate than `Complex(x).exp().sub(1)` if\n * `x` is small.\n *\n * @returns {Complex}\n */\n 'expm1': function() {\n\n /**\n * exp(a + i*b) - 1\n = exp(a) * (cos(b) + j*sin(b)) - 1\n = expm1(a)*cos(b) + cosm1(b) + j*exp(a)*sin(b)\n */\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n Math.expm1(a) * Math.cos(b) + cosm1(b),\n Math.exp(a) * Math.sin(b));\n },\n\n /**\n * Calculate the natural log\n *\n * @returns {Complex}\n */\n 'log': function() {\n\n var a = this['re'];\n var b = this['im'];\n\n if (b === 0 && a > 0) {\n //return new Complex(Math.log(a), 0);\n }\n\n return new Complex(\n logHypot(a, b),\n Math.atan2(b, a));\n },\n\n /**\n * Calculate the magnitude of the complex number\n *\n * @returns {number}\n */\n 'abs': function() {\n\n return hypot(this['re'], this['im']);\n },\n\n /**\n * Calculate the angle of the complex number\n *\n * @returns {number}\n */\n 'arg': function() {\n\n return Math.atan2(this['im'], this['re']);\n },\n\n /**\n * Calculate the sine of the complex number\n *\n * @returns {Complex}\n */\n 'sin': function() {\n\n // sin(c) = (e^b - e^(-b)) / (2i)\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n Math.sin(a) * cosh(b),\n Math.cos(a) * sinh(b));\n },\n\n /**\n * Calculate the cosine\n *\n * @returns {Complex}\n */\n 'cos': function() {\n\n // cos(z) = (e^b + e^(-b)) / 2\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n Math.cos(a) * cosh(b),\n -Math.sin(a) * sinh(b));\n },\n\n /**\n * Calculate the tangent\n *\n * @returns {Complex}\n */\n 'tan': function() {\n\n // tan(c) = (e^(ci) - e^(-ci)) / (i(e^(ci) + e^(-ci)))\n\n var a = 2 * this['re'];\n var b = 2 * this['im'];\n var d = Math.cos(a) + cosh(b);\n\n return new Complex(\n Math.sin(a) / d,\n sinh(b) / d);\n },\n\n /**\n * Calculate the cotangent\n *\n * @returns {Complex}\n */\n 'cot': function() {\n\n // cot(c) = i(e^(ci) + e^(-ci)) / (e^(ci) - e^(-ci))\n\n var a = 2 * this['re'];\n var b = 2 * this['im'];\n var d = Math.cos(a) - cosh(b);\n\n return new Complex(\n -Math.sin(a) / d,\n sinh(b) / d);\n },\n\n /**\n * Calculate the secant\n *\n * @returns {Complex}\n */\n 'sec': function() {\n\n // sec(c) = 2 / (e^(ci) + e^(-ci))\n\n var a = this['re'];\n var b = this['im'];\n var d = 0.5 * cosh(2 * b) + 0.5 * Math.cos(2 * a);\n\n return new Complex(\n Math.cos(a) * cosh(b) / d,\n Math.sin(a) * sinh(b) / d);\n },\n\n /**\n * Calculate the cosecans\n *\n * @returns {Complex}\n */\n 'csc': function() {\n\n // csc(c) = 2i / (e^(ci) - e^(-ci))\n\n var a = this['re'];\n var b = this['im'];\n var d = 0.5 * cosh(2 * b) - 0.5 * Math.cos(2 * a);\n\n return new Complex(\n Math.sin(a) * cosh(b) / d,\n -Math.cos(a) * sinh(b) / d);\n },\n\n /**\n * Calculate the complex arcus sinus\n *\n * @returns {Complex}\n */\n 'asin': function() {\n\n // asin(c) = -i * log(ci + sqrt(1 - c^2))\n\n var a = this['re'];\n var b = this['im'];\n\n var t1 = new Complex(\n b * b - a * a + 1,\n -2 * a * b)['sqrt']();\n\n var t2 = new Complex(\n t1['re'] - b,\n t1['im'] + a)['log']();\n\n return new Complex(t2['im'], -t2['re']);\n },\n\n /**\n * Calculate the complex arcus cosinus\n *\n * @returns {Complex}\n */\n 'acos': function() {\n\n // acos(c) = i * log(c - i * sqrt(1 - c^2))\n\n var a = this['re'];\n var b = this['im'];\n\n var t1 = new Complex(\n b * b - a * a + 1,\n -2 * a * b)['sqrt']();\n\n var t2 = new Complex(\n t1['re'] - b,\n t1['im'] + a)['log']();\n\n return new Complex(Math.PI / 2 - t2['im'], t2['re']);\n },\n\n /**\n * Calculate the complex arcus tangent\n *\n * @returns {Complex}\n */\n 'atan': function() {\n\n // atan(c) = i / 2 log((i + x) / (i - x))\n\n var a = this['re'];\n var b = this['im'];\n\n if (a === 0) {\n\n if (b === 1) {\n return new Complex(0, Infinity);\n }\n\n if (b === -1) {\n return new Complex(0, -Infinity);\n }\n }\n\n var d = a * a + (1.0 - b) * (1.0 - b);\n\n var t1 = new Complex(\n (1 - b * b - a * a) / d,\n -2 * a / d).log();\n\n return new Complex(-0.5 * t1['im'], 0.5 * t1['re']);\n },\n\n /**\n * Calculate the complex arcus cotangent\n *\n * @returns {Complex}\n */\n 'acot': function() {\n\n // acot(c) = i / 2 log((c - i) / (c + i))\n\n var a = this['re'];\n var b = this['im'];\n\n if (b === 0) {\n return new Complex(Math.atan2(1, a), 0);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).atan()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).atan();\n },\n\n /**\n * Calculate the complex arcus secant\n *\n * @returns {Complex}\n */\n 'asec': function() {\n\n // asec(c) = -i * log(1 / c + sqrt(1 - i / c^2))\n\n var a = this['re'];\n var b = this['im'];\n\n if (a === 0 && b === 0) {\n return new Complex(0, Infinity);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).acos()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).acos();\n },\n\n /**\n * Calculate the complex arcus cosecans\n *\n * @returns {Complex}\n */\n 'acsc': function() {\n\n // acsc(c) = -i * log(i / c + sqrt(1 - 1 / c^2))\n\n var a = this['re'];\n var b = this['im'];\n\n if (a === 0 && b === 0) {\n return new Complex(Math.PI / 2, Infinity);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).asin()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).asin();\n },\n\n /**\n * Calculate the complex sinh\n *\n * @returns {Complex}\n */\n 'sinh': function() {\n\n // sinh(c) = (e^c - e^-c) / 2\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n sinh(a) * Math.cos(b),\n cosh(a) * Math.sin(b));\n },\n\n /**\n * Calculate the complex cosh\n *\n * @returns {Complex}\n */\n 'cosh': function() {\n\n // cosh(c) = (e^c + e^-c) / 2\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n cosh(a) * Math.cos(b),\n sinh(a) * Math.sin(b));\n },\n\n /**\n * Calculate the complex tanh\n *\n * @returns {Complex}\n */\n 'tanh': function() {\n\n // tanh(c) = (e^c - e^-c) / (e^c + e^-c)\n\n var a = 2 * this['re'];\n var b = 2 * this['im'];\n var d = cosh(a) + Math.cos(b);\n\n return new Complex(\n sinh(a) / d,\n Math.sin(b) / d);\n },\n\n /**\n * Calculate the complex coth\n *\n * @returns {Complex}\n */\n 'coth': function() {\n\n // coth(c) = (e^c + e^-c) / (e^c - e^-c)\n\n var a = 2 * this['re'];\n var b = 2 * this['im'];\n var d = cosh(a) - Math.cos(b);\n\n return new Complex(\n sinh(a) / d,\n -Math.sin(b) / d);\n },\n\n /**\n * Calculate the complex coth\n *\n * @returns {Complex}\n */\n 'csch': function() {\n\n // csch(c) = 2 / (e^c - e^-c)\n\n var a = this['re'];\n var b = this['im'];\n var d = Math.cos(2 * b) - cosh(2 * a);\n\n return new Complex(\n -2 * sinh(a) * Math.cos(b) / d,\n 2 * cosh(a) * Math.sin(b) / d);\n },\n\n /**\n * Calculate the complex sech\n *\n * @returns {Complex}\n */\n 'sech': function() {\n\n // sech(c) = 2 / (e^c + e^-c)\n\n var a = this['re'];\n var b = this['im'];\n var d = Math.cos(2 * b) + cosh(2 * a);\n\n return new Complex(\n 2 * cosh(a) * Math.cos(b) / d,\n -2 * sinh(a) * Math.sin(b) / d);\n },\n\n /**\n * Calculate the complex asinh\n *\n * @returns {Complex}\n */\n 'asinh': function() {\n\n // asinh(c) = log(c + sqrt(c^2 + 1))\n\n var tmp = this['im'];\n this['im'] = -this['re'];\n this['re'] = tmp;\n var res = this['asin']();\n\n this['re'] = -this['im'];\n this['im'] = tmp;\n tmp = res['re'];\n\n res['re'] = -res['im'];\n res['im'] = tmp;\n return res;\n },\n\n /**\n * Calculate the complex asinh\n *\n * @returns {Complex}\n */\n 'acosh': function() {\n\n // acosh(c) = log(c + sqrt(c^2 - 1))\n\n var res = this['acos']();\n if (res['im'] <= 0) {\n var tmp = res['re'];\n res['re'] = -res['im'];\n res['im'] = tmp;\n } else {\n var tmp = res['im'];\n res['im'] = -res['re'];\n res['re'] = tmp;\n }\n return res;\n },\n\n /**\n * Calculate the complex atanh\n *\n * @returns {Complex}\n */\n 'atanh': function() {\n\n // atanh(c) = log((1+c) / (1-c)) / 2\n\n var a = this['re'];\n var b = this['im'];\n\n var noIM = a > 1 && b === 0;\n var oneMinus = 1 - a;\n var onePlus = 1 + a;\n var d = oneMinus * oneMinus + b * b;\n\n var x = (d !== 0)\n ? new Complex(\n (onePlus * oneMinus - b * b) / d,\n (b * oneMinus + onePlus * b) / d)\n : new Complex(\n (a !== -1) ? (a / 0) : 0,\n (b !== 0) ? (b / 0) : 0);\n\n var temp = x['re'];\n x['re'] = logHypot(x['re'], x['im']) / 2;\n x['im'] = Math.atan2(x['im'], temp) / 2;\n if (noIM) {\n x['im'] = -x['im'];\n }\n return x;\n },\n\n /**\n * Calculate the complex acoth\n *\n * @returns {Complex}\n */\n 'acoth': function() {\n\n // acoth(c) = log((c+1) / (c-1)) / 2\n\n var a = this['re'];\n var b = this['im'];\n\n if (a === 0 && b === 0) {\n return new Complex(0, Math.PI / 2);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).atanh()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).atanh();\n },\n\n /**\n * Calculate the complex acsch\n *\n * @returns {Complex}\n */\n 'acsch': function() {\n\n // acsch(c) = log((1+sqrt(1+c^2))/c)\n\n var a = this['re'];\n var b = this['im'];\n\n if (b === 0) {\n\n return new Complex(\n (a !== 0)\n ? Math.log(a + Math.sqrt(a * a + 1))\n : Infinity, 0);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).asinh()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).asinh();\n },\n\n /**\n * Calculate the complex asech\n *\n * @returns {Complex}\n */\n 'asech': function() {\n\n // asech(c) = log((1+sqrt(1-c^2))/c)\n\n var a = this['re'];\n var b = this['im'];\n\n if (this['isZero']()) {\n return Complex['INFINITY'];\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).acosh()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).acosh();\n },\n\n /**\n * Calculate the complex inverse 1/z\n *\n * @returns {Complex}\n */\n 'inverse': function() {\n\n // 1 / 0 = Infinity and 1 / Infinity = 0\n if (this['isZero']()) {\n return Complex['INFINITY'];\n }\n\n if (this['isInfinite']()) {\n return Complex['ZERO'];\n }\n\n var a = this['re'];\n var b = this['im'];\n\n var d = a * a + b * b;\n\n return new Complex(a / d, -b / d);\n },\n\n /**\n * Returns the complex conjugate\n *\n * @returns {Complex}\n */\n 'conjugate': function() {\n\n return new Complex(this['re'], -this['im']);\n },\n\n /**\n * Gets the negated complex number\n *\n * @returns {Complex}\n */\n 'neg': function() {\n\n return new Complex(-this['re'], -this['im']);\n },\n\n /**\n * Ceils the actual complex number\n *\n * @returns {Complex}\n */\n 'ceil': function(places) {\n\n places = Math.pow(10, places || 0);\n\n return new Complex(\n Math.ceil(this['re'] * places) / places,\n Math.ceil(this['im'] * places) / places);\n },\n\n /**\n * Floors the actual complex number\n *\n * @returns {Complex}\n */\n 'floor': function(places) {\n\n places = Math.pow(10, places || 0);\n\n return new Complex(\n Math.floor(this['re'] * places) / places,\n Math.floor(this['im'] * places) / places);\n },\n\n /**\n * Ceils the actual complex number\n *\n * @returns {Complex}\n */\n 'round': function(places) {\n\n places = Math.pow(10, places || 0);\n\n return new Complex(\n Math.round(this['re'] * places) / places,\n Math.round(this['im'] * places) / places);\n },\n\n /**\n * Compares two complex numbers\n *\n * **Note:** new Complex(Infinity).equals(Infinity) === false\n *\n * @returns {boolean}\n */\n 'equals': function(a, b) {\n\n var z = new Complex(a, b);\n\n return Math.abs(z['re'] - this['re']) <= Complex['EPSILON'] &&\n Math.abs(z['im'] - this['im']) <= Complex['EPSILON'];\n },\n\n /**\n * Clones the actual object\n *\n * @returns {Complex}\n */\n 'clone': function() {\n\n return new Complex(this['re'], this['im']);\n },\n\n /**\n * Gets a string of the actual complex number\n *\n * @returns {string}\n */\n 'toString': function() {\n\n var a = this['re'];\n var b = this['im'];\n var ret = '';\n\n if (this['isNaN']()) {\n return 'NaN';\n }\n\n if (this['isZero']()) {\n return '0';\n }\n\n if (this['isInfinite']()) {\n return 'Infinity';\n }\n\n if (a !== 0) {\n ret += a;\n }\n\n if (b !== 0) {\n\n if (a !== 0) {\n ret += b < 0 ? ' - ' : ' + ';\n } else if (b < 0) {\n ret += '-';\n }\n\n b = Math.abs(b);\n\n if (1 !== b) {\n ret += b;\n }\n ret += 'i';\n }\n\n if (!ret)\n return '0';\n\n return ret;\n },\n\n /**\n * Returns the actual number as a vector\n *\n * @returns {Array}\n */\n 'toVector': function() {\n\n return [this['re'], this['im']];\n },\n\n /**\n * Returns the actual real value of the current object\n *\n * @returns {number|null}\n */\n 'valueOf': function() {\n\n if (this['im'] === 0) {\n return this['re'];\n }\n return null;\n },\n\n /**\n * Determines whether a complex number is not on the Riemann sphere.\n *\n * @returns {boolean}\n */\n 'isNaN': function() {\n return isNaN(this['re']) || isNaN(this['im']);\n },\n\n /**\n * Determines whether or not a complex number is at the zero pole of the\n * Riemann sphere.\n *\n * @returns {boolean}\n */\n 'isZero': function() {\n return (\n (this['re'] === 0 || this['re'] === -0) &&\n (this['im'] === 0 || this['im'] === -0)\n );\n },\n\n /**\n * Determines whether a complex number is not at the infinity pole of the\n * Riemann sphere.\n *\n * @returns {boolean}\n */\n 'isFinite': function() {\n return isFinite(this['re']) && isFinite(this['im']);\n },\n\n /**\n * Determines whether or not a complex number is at the infinity pole of the\n * Riemann sphere.\n *\n * @returns {boolean}\n */\n 'isInfinite': function() {\n return !(this['isNaN']() || this['isFinite']());\n }\n };\n\n Complex['ZERO'] = new Complex(0, 0);\n Complex['ONE'] = new Complex(1, 0);\n Complex['I'] = new Complex(0, 1);\n Complex['PI'] = new Complex(Math.PI, 0);\n Complex['E'] = new Complex(Math.E, 0);\n Complex['INFINITY'] = new Complex(Infinity, Infinity);\n Complex['NAN'] = new Complex(NaN, NaN);\n Complex['EPSILON'] = 1e-16;\n\n if (typeof define === 'function' && define['amd']) {\n define([], function() {\n return Complex;\n });\n } else if (typeof exports === 'object') {\n Object.defineProperty(exports, \"__esModule\", {'value': true});\n Complex['default'] = Complex;\n Complex['Complex'] = Complex;\n module['exports'] = Complex;\n } else {\n root['Complex'] = Complex;\n }\n\n})(this);\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar invariant_1 = require(\"@turf/invariant\");\nvar helpers_1 = require(\"@turf/helpers\");\n//http://en.wikipedia.org/wiki/Haversine_formula\n//http://www.movable-type.co.uk/scripts/latlong.html\n/**\n * Calculates the distance between two {@link Point|points} in degrees, radians, miles, or kilometers.\n * This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.\n *\n * @name distance\n * @param {Coord} from origin point\n * @param {Coord} to destination point\n * @param {Object} [options={}] Optional parameters\n * @param {string} [options.units='kilometers'] can be degrees, radians, miles, or kilometers\n * @returns {number} distance between the two points\n * @example\n * var from = turf.point([-75.343, 39.984]);\n * var to = turf.point([-75.534, 39.123]);\n * var options = {units: 'miles'};\n *\n * var distance = turf.distance(from, to, options);\n *\n * //addToMap\n * var addToMap = [from, to];\n * from.properties.distance = distance;\n * to.properties.distance = distance;\n */\nfunction distance(from, to, options) {\n if (options === void 0) { options = {}; }\n var coordinates1 = invariant_1.getCoord(from);\n var coordinates2 = invariant_1.getCoord(to);\n var dLat = helpers_1.degreesToRadians((coordinates2[1] - coordinates1[1]));\n var dLon = helpers_1.degreesToRadians((coordinates2[0] - coordinates1[0]));\n var lat1 = helpers_1.degreesToRadians(coordinates1[1]);\n var lat2 = helpers_1.degreesToRadians(coordinates2[1]);\n var a = Math.pow(Math.sin(dLat / 2), 2) +\n Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);\n return helpers_1.radiansToLength(2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)), options.units);\n}\nexports.default = distance;\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { chainPropTypes } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n userSelect: 'none',\n width: '1em',\n height: '1em',\n display: 'inline-block',\n fill: 'currentColor',\n flexShrink: 0,\n fontSize: theme.typography.pxToRem(24),\n transition: theme.transitions.create('fill', {\n duration: theme.transitions.duration.shorter\n })\n },\n\n /* Styles applied to the root element if `color=\"primary\"`. */\n colorPrimary: {\n color: theme.palette.primary.main\n },\n\n /* Styles applied to the root element if `color=\"secondary\"`. */\n colorSecondary: {\n color: theme.palette.secondary.main\n },\n\n /* Styles applied to the root element if `color=\"action\"`. */\n colorAction: {\n color: theme.palette.action.active\n },\n\n /* Styles applied to the root element if `color=\"error\"`. */\n colorError: {\n color: theme.palette.error.main\n },\n\n /* Styles applied to the root element if `color=\"disabled\"`. */\n colorDisabled: {\n color: theme.palette.action.disabled\n },\n\n /* Styles applied to the root element if `fontSize=\"inherit\"`. */\n fontSizeInherit: {\n fontSize: 'inherit'\n },\n\n /* Styles applied to the root element if `fontSize=\"small\"`. */\n fontSizeSmall: {\n fontSize: theme.typography.pxToRem(20)\n },\n\n /* Styles applied to the root element if `fontSize=\"large\"`. */\n fontSizeLarge: {\n fontSize: theme.typography.pxToRem(35)\n }\n };\n};\nvar SvgIcon = /*#__PURE__*/React.forwardRef(function SvgIcon(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'inherit' : _props$color,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'svg' : _props$component,\n _props$fontSize = props.fontSize,\n fontSize = _props$fontSize === void 0 ? 'medium' : _props$fontSize,\n htmlColor = props.htmlColor,\n titleAccess = props.titleAccess,\n _props$viewBox = props.viewBox,\n viewBox = _props$viewBox === void 0 ? '0 0 24 24' : _props$viewBox,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"color\", \"component\", \"fontSize\", \"htmlColor\", \"titleAccess\", \"viewBox\"]);\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className, color !== 'inherit' && classes[\"color\".concat(capitalize(color))], fontSize !== 'default' && fontSize !== 'medium' && classes[\"fontSize\".concat(capitalize(fontSize))]),\n focusable: \"false\",\n viewBox: viewBox,\n color: htmlColor,\n \"aria-hidden\": titleAccess ? undefined : true,\n role: titleAccess ? 'img' : undefined,\n ref: ref\n }, other), children, titleAccess ? /*#__PURE__*/React.createElement(\"title\", null, titleAccess) : null);\n});\nprocess.env.NODE_ENV !== \"production\" ? SvgIcon.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * Node passed into the SVG element.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n * You can use the `htmlColor` prop to apply a color attribute to the SVG element.\n */\n color: PropTypes.oneOf(['action', 'disabled', 'error', 'inherit', 'primary', 'secondary']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * The fontSize applied to the icon. Defaults to 24px, but can be configure to inherit font size.\n */\n fontSize: chainPropTypes(PropTypes.oneOf(['default', 'inherit', 'large', 'medium', 'small']), function (props) {\n var fontSize = props.fontSize;\n\n if (fontSize === 'default') {\n throw new Error('Material-UI: `fontSize=\"default\"` is deprecated. Use `fontSize=\"medium\"` instead.');\n }\n\n return null;\n }),\n\n /**\n * Applies a color attribute to the SVG element.\n */\n htmlColor: PropTypes.string,\n\n /**\n * The shape-rendering attribute. The behavior of the different options is described on the\n * [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering).\n * If you are having issues with blurry icons you should investigate this property.\n */\n shapeRendering: PropTypes.string,\n\n /**\n * Provides a human-readable title for the element that contains it.\n * https://www.w3.org/TR/SVG-access/#Equivalent\n */\n titleAccess: PropTypes.string,\n\n /**\n * Allows you to redefine what the coordinates without units mean inside an SVG element.\n * For example, if the SVG element is 500 (width) by 200 (height),\n * and you pass viewBox=\"0 0 50 20\",\n * this means that the coordinates inside the SVG will go from the top left corner (0,0)\n * to bottom right (50,20) and each unit will be worth 10px.\n */\n viewBox: PropTypes.string\n} : void 0;\nSvgIcon.muiName = 'SvgIcon';\nexport default withStyles(styles, {\n name: 'MuiSvgIcon'\n})(SvgIcon);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport React from 'react';\nimport SvgIcon from '../SvgIcon';\n/**\n * Private module reserved for @material-ui/x packages.\n */\n\nexport default function createSvgIcon(path, displayName) {\n var Component = function Component(props, ref) {\n return /*#__PURE__*/React.createElement(SvgIcon, _extends({\n ref: ref\n }, props), path);\n };\n\n if (process.env.NODE_ENV !== 'production') {\n // Need to set `displayName` on the inner component for React.memo.\n // React prior to 16.14 ignores `displayName` on the wrapper.\n Component.displayName = \"\".concat(displayName, \"Icon\");\n }\n\n Component.muiName = SvgIcon.muiName;\n return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));\n}","import { useTheme as useThemeWithoutDefault } from '@material-ui/styles';\nimport React from 'react';\nimport defaultTheme from './defaultTheme';\nexport default function useTheme() {\n var theme = useThemeWithoutDefault() || defaultTheme;\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(theme);\n }\n\n return theme;\n}","/**\n * Throws an `Error` with the optional `message` if `condition` is falsy\n * @note Replacement for the external assert method to reduce bundle size\n */\nexport function assert(condition: any, message?: string): void {\n if (!condition) {\n throw new Error(message || 'loader assertion failed.');\n }\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nconst EMPTY_ARRAY = [];\nconst placeholderArray = [];\n\n/*\n * Create an Iterable\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols\n * and a \"context\" tracker from the given data\n */\nexport function createIterable(data, startRow = 0, endRow = Infinity) {\n let iterable = EMPTY_ARRAY;\n\n const objectInfo = {\n index: -1,\n data,\n // visitor can optionally utilize this to avoid constructing a new array for every object\n target: []\n };\n\n if (!data) {\n iterable = EMPTY_ARRAY;\n } else if (typeof data[Symbol.iterator] === 'function') {\n // data is already an iterable\n iterable = data;\n } else if (data.length > 0) {\n placeholderArray.length = data.length;\n iterable = placeholderArray;\n }\n\n if (startRow > 0 || Number.isFinite(endRow)) {\n iterable = (Array.isArray(iterable) ? iterable : Array.from(iterable)).slice(startRow, endRow);\n objectInfo.index = startRow - 1;\n }\n\n return {iterable, objectInfo};\n}\n\n/*\n * Returns true if data is an async iterable object\n */\nexport function isAsyncIterable(data) {\n return data && data[Symbol.asyncIterator];\n}\n\n/*\n * Create an accessor function from a flat buffer that yields the value at each object index\n */\nexport function getAccessorFromBuffer(typedArray, {size, stride, offset, startIndices, nested}) {\n const bytesPerElement = typedArray.BYTES_PER_ELEMENT;\n const elementStride = stride ? stride / bytesPerElement : size;\n const elementOffset = offset ? offset / bytesPerElement : 0;\n const vertexCount = Math.floor((typedArray.length - elementOffset) / elementStride);\n\n return (_, {index, target}) => {\n if (!startIndices) {\n const sourceIndex = index * elementStride + elementOffset;\n for (let j = 0; j < size; j++) {\n target[j] = typedArray[sourceIndex + j];\n }\n return target;\n }\n const startIndex = startIndices[index];\n const endIndex = startIndices[index + 1] || vertexCount;\n let result;\n\n if (nested) {\n result = new Array(endIndex - startIndex);\n for (let i = startIndex; i < endIndex; i++) {\n const sourceIndex = i * elementStride + elementOffset;\n target = new Array(size);\n for (let j = 0; j < size; j++) {\n target[j] = typedArray[sourceIndex + j];\n }\n result[i - startIndex] = target;\n }\n } else if (elementStride === size) {\n result = typedArray.subarray(\n startIndex * size + elementOffset,\n endIndex * size + elementOffset\n );\n } else {\n result = new typedArray.constructor((endIndex - startIndex) * size);\n let targetIndex = 0;\n for (let i = startIndex; i < endIndex; i++) {\n const sourceIndex = i * elementStride + elementOffset;\n for (let j = 0; j < size; j++) {\n result[targetIndex++] = typedArray[sourceIndex + j];\n }\n }\n }\n\n return result;\n };\n}\n","var t0 = new Date,\n t1 = new Date;\n\nexport default function newInterval(floori, offseti, count, field) {\n\n function interval(date) {\n return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date;\n }\n\n interval.floor = function(date) {\n return floori(date = new Date(+date)), date;\n };\n\n interval.ceil = function(date) {\n return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;\n };\n\n interval.round = function(date) {\n var d0 = interval(date),\n d1 = interval.ceil(date);\n return date - d0 < d1 - date ? d0 : d1;\n };\n\n interval.offset = function(date, step) {\n return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;\n };\n\n interval.range = function(start, stop, step) {\n var range = [], previous;\n start = interval.ceil(start);\n step = step == null ? 1 : Math.floor(step);\n if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date\n do range.push(previous = new Date(+start)), offseti(start, step), floori(start);\n while (previous < start && start < stop);\n return range;\n };\n\n interval.filter = function(test) {\n return newInterval(function(date) {\n if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);\n }, function(date, step) {\n if (date >= date) {\n if (step < 0) while (++step <= 0) {\n while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty\n } else while (--step >= 0) {\n while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty\n }\n }\n });\n };\n\n if (count) {\n interval.count = function(start, end) {\n t0.setTime(+start), t1.setTime(+end);\n floori(t0), floori(t1);\n return Math.floor(count(t0, t1));\n };\n\n interval.every = function(step) {\n step = Math.floor(step);\n return !isFinite(step) || !(step > 0) ? null\n : !(step > 1) ? interval\n : interval.filter(field\n ? function(d) { return field(d) % step === 0; }\n : function(d) { return interval.count(0, d) % step === 0; });\n };\n }\n\n return interval;\n}\n","import GL from '@luma.gl/constants';\n\nconst ERR_TYPE_DEDUCTION = 'Failed to deduce GL constant from typed array';\n\n// Converts TYPED ARRAYS to corresponding GL constant\n// Used to auto deduce gl parameter types\nexport function getGLTypeFromTypedArray(arrayOrType) {\n // If typed array, look up constructor\n const type = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;\n switch (type) {\n case Float32Array:\n return GL.FLOAT;\n case Uint16Array:\n return GL.UNSIGNED_SHORT;\n case Uint32Array:\n return GL.UNSIGNED_INT;\n case Uint8Array:\n return GL.UNSIGNED_BYTE;\n case Uint8ClampedArray:\n return GL.UNSIGNED_BYTE;\n case Int8Array:\n return GL.BYTE;\n case Int16Array:\n return GL.SHORT;\n case Int32Array:\n return GL.INT;\n default:\n throw new Error(ERR_TYPE_DEDUCTION);\n }\n}\n\n// Converts GL constant to corresponding TYPED ARRAY\n// Used to auto deduce gl parameter types\n\n/* eslint-disable complexity */\nexport function getTypedArrayFromGLType(glType, {clamped = true} = {}) {\n // Sorted in some order of likelihood to reduce amount of comparisons\n switch (glType) {\n case GL.FLOAT:\n return Float32Array;\n case GL.UNSIGNED_SHORT:\n case GL.UNSIGNED_SHORT_5_6_5:\n case GL.UNSIGNED_SHORT_4_4_4_4:\n case GL.UNSIGNED_SHORT_5_5_5_1:\n return Uint16Array;\n case GL.UNSIGNED_INT:\n return Uint32Array;\n case GL.UNSIGNED_BYTE:\n return clamped ? Uint8ClampedArray : Uint8Array;\n case GL.BYTE:\n return Int8Array;\n case GL.SHORT:\n return Int16Array;\n case GL.INT:\n return Int32Array;\n default:\n throw new Error('Failed to deduce typed array type from GL constant');\n }\n}\n/* eslint-enable complexity */\n\n// Flip rows (can be used on arrays returned from `Framebuffer.readPixels`)\n// https://stackoverflow.com/questions/41969562/\n// how-can-i-flip-the-result-of-webglrenderingcontext-readpixels\nexport function flipRows({data, width, height, bytesPerPixel = 4, temp}) {\n const bytesPerRow = width * bytesPerPixel;\n\n // make a temp buffer to hold one row\n temp = temp || new Uint8Array(bytesPerRow);\n for (let y = 0; y < height / 2; ++y) {\n const topOffset = y * bytesPerRow;\n const bottomOffset = (height - y - 1) * bytesPerRow;\n // make copy of a row on the top half\n temp.set(data.subarray(topOffset, topOffset + bytesPerRow));\n // copy a row from the bottom half to the top\n data.copyWithin(topOffset, bottomOffset, bottomOffset + bytesPerRow);\n // copy the copy of the top half row to the bottom half\n data.set(temp, bottomOffset);\n }\n}\n\nexport function scalePixels({data, width, height}) {\n const newWidth = Math.round(width / 2);\n const newHeight = Math.round(height / 2);\n const newData = new Uint8Array(newWidth * newHeight * 4);\n for (let y = 0; y < newHeight; y++) {\n for (let x = 0; x < newWidth; x++) {\n for (let c = 0; c < 4; c++) {\n newData[(y * newWidth + x) * 4 + c] = data[(y * 2 * width + x * 2) * 4 + c];\n }\n }\n }\n return {data: newData, width: newWidth, height: newHeight};\n}\n","/* eslint-disable complexity */\nimport {\n CullingVolume,\n Plane,\n AxisAlignedBoundingBox,\n makeOrientedBoundingBoxFromPoints\n} from '@math.gl/culling';\nimport {lngLatToWorld} from '@math.gl/web-mercator';\nimport {osmTile2lngLat} from './utils';\n\nconst TILE_SIZE = 512;\n// number of world copies to check\nconst MAX_MAPS = 3;\n// for calculating bounding volume of a tile in a non-web-mercator viewport\nconst REF_POINTS_5 = [[0.5, 0.5], [0, 0], [0, 1], [1, 0], [1, 1]]; // 4 corners and center\nconst REF_POINTS_9 = REF_POINTS_5.concat([[0, 0.5], [0.5, 0], [1, 0.5], [0.5, 1]]); // 4 corners, center and 4 mid points\nconst REF_POINTS_11 = REF_POINTS_9.concat([[0.25, 0.5], [0.75, 0.5]]); // 2 additional points on equator for top tile\n\nclass OSMNode {\n constructor(x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n get children() {\n if (!this._children) {\n const x = this.x * 2;\n const y = this.y * 2;\n const z = this.z + 1;\n this._children = [\n new OSMNode(x, y, z),\n new OSMNode(x, y + 1, z),\n new OSMNode(x + 1, y, z),\n new OSMNode(x + 1, y + 1, z)\n ];\n }\n return this._children;\n }\n\n update(params) {\n const {viewport, cullingVolume, elevationBounds, minZ, maxZ, bounds, offset, project} = params;\n const boundingVolume = this.getBoundingVolume(elevationBounds, offset, project);\n\n // First, check if this tile is visible\n if (bounds && !this.insideBounds(bounds)) {\n return false;\n }\n\n const isInside = cullingVolume.computeVisibility(boundingVolume);\n if (isInside < 0) {\n return false;\n }\n\n // Avoid loading overlapping tiles - if a descendant is requested, do not request the ancester\n if (!this.childVisible) {\n let {z} = this;\n if (z < maxZ && z >= minZ) {\n // Adjust LOD\n // If the tile is far enough from the camera, accept a lower zoom level\n const distance =\n (boundingVolume.distanceTo(viewport.cameraPosition) * viewport.scale) / viewport.height;\n z += Math.floor(Math.log2(distance));\n }\n if (z >= maxZ) {\n // LOD is acceptable\n this.selected = true;\n return true;\n }\n }\n\n // LOD is not enough, recursively test child tiles\n this.selected = false;\n this.childVisible = true;\n for (const child of this.children) {\n child.update(params);\n }\n return true;\n }\n\n getSelected(result = []) {\n if (this.selected) {\n result.push(this);\n }\n if (this._children) {\n for (const node of this._children) {\n node.getSelected(result);\n }\n }\n return result;\n }\n\n insideBounds([minX, minY, maxX, maxY]) {\n const scale = Math.pow(2, this.z);\n const extent = TILE_SIZE / scale;\n\n return (\n this.x * extent < maxX &&\n this.y * extent < maxY &&\n (this.x + 1) * extent > minX &&\n (this.y + 1) * extent > minY\n );\n }\n\n getBoundingVolume(zRange, worldOffset, project) {\n if (project) {\n // Custom projection\n // Estimate bounding box from sample points\n // At low zoom level we need more samples to calculate the bounding volume correctly\n const refPoints = this.z < 1 ? REF_POINTS_11 : this.z < 2 ? REF_POINTS_9 : REF_POINTS_5;\n\n // Convert from tile-relative coordinates to common space\n const refPointPositions = [];\n for (const p of refPoints) {\n const lngLat = osmTile2lngLat(this.x + p[0], this.y + p[1], this.z);\n lngLat[2] = zRange[0];\n refPointPositions.push(project(lngLat));\n\n if (zRange[0] !== zRange[1]) {\n // Account for the elevation volume\n lngLat[2] = zRange[1];\n refPointPositions.push(project(lngLat));\n }\n }\n\n return makeOrientedBoundingBoxFromPoints(refPointPositions);\n }\n\n // Use WebMercator projection\n const scale = Math.pow(2, this.z);\n const extent = TILE_SIZE / scale;\n const originX = this.x * extent + worldOffset * TILE_SIZE;\n // deck's common space is y-flipped\n const originY = TILE_SIZE - (this.y + 1) * extent;\n\n return new AxisAlignedBoundingBox(\n [originX, originY, zRange[0]],\n [originX + extent, originY + extent, zRange[1]]\n );\n }\n}\n\nexport function getOSMTileIndices(viewport, maxZ, zRange, bounds) {\n const project = viewport.resolution ? viewport.projectPosition : null;\n\n // Get the culling volume of the current camera\n const planes = Object.values(viewport.getFrustumPlanes()).map(\n ({normal, distance}) => new Plane(normal.clone().negate(), distance)\n );\n const cullingVolume = new CullingVolume(planes);\n\n // Project zRange from meters to common space\n const unitsPerMeter = viewport.distanceScales.unitsPerMeter[2];\n const elevationMin = (zRange && zRange[0] * unitsPerMeter) || 0;\n const elevationMax = (zRange && zRange[1] * unitsPerMeter) || 0;\n\n // Always load at the current zoom level if pitch is small\n const minZ = viewport.pitch <= 60 ? maxZ : 0;\n\n // Map extent to OSM position\n if (bounds) {\n const [minLng, minLat, maxLng, maxLat] = bounds;\n const topLeft = lngLatToWorld([minLng, maxLat]);\n const bottomRight = lngLatToWorld([maxLng, minLat]);\n bounds = [topLeft[0], TILE_SIZE - topLeft[1], bottomRight[0], TILE_SIZE - bottomRight[1]];\n }\n\n const root = new OSMNode(0, 0, 0);\n const traversalParams = {\n viewport,\n project,\n cullingVolume,\n elevationBounds: [elevationMin, elevationMax],\n minZ,\n maxZ,\n bounds,\n // num. of worlds from the center. For repeated maps\n offset: 0\n };\n\n root.update(traversalParams);\n\n if (viewport.subViewports && viewport.subViewports.length > 1) {\n // Check worlds in repeated maps\n traversalParams.offset = -1;\n while (root.update(traversalParams)) {\n if (--traversalParams.offset < -MAX_MAPS) {\n break;\n }\n }\n traversalParams.offset = 1;\n while (root.update(traversalParams)) {\n if (++traversalParams.offset > MAX_MAPS) {\n break;\n }\n }\n }\n\n return root.getSelected();\n}\n","import {getOSMTileIndices} from './tile-2d-traversal';\n\nconst TILE_SIZE = 512;\nconst DEFAULT_EXTENT = [-Infinity, -Infinity, Infinity, Infinity];\n\nexport const urlType = {\n type: 'url',\n value: null,\n validate: (value, propType) =>\n (propType.optional && value === null) ||\n typeof value === 'string' ||\n (Array.isArray(value) && value.every(url => typeof url === 'string')),\n equals: (value1, value2) => {\n if (value1 === value2) {\n return true;\n }\n if (!Array.isArray(value1) || !Array.isArray(value2)) {\n return false;\n }\n const len = value1.length;\n if (len !== value2.length) {\n return false;\n }\n for (let i = 0; i < len; i++) {\n if (value1[i] !== value2[i]) {\n return false;\n }\n }\n return true;\n }\n};\n\nfunction transformBox(bbox, modelMatrix) {\n const transformedCoords = [\n // top-left\n modelMatrix.transformPoint([bbox[0], bbox[1]]),\n // top-right\n modelMatrix.transformPoint([bbox[2], bbox[1]]),\n // bottom-left\n modelMatrix.transformPoint([bbox[0], bbox[3]]),\n // bottom-right\n modelMatrix.transformPoint([bbox[2], bbox[3]])\n ];\n const transformedBox = [\n // Minimum x coord\n Math.min(...transformedCoords.map(i => i[0])),\n // Minimum y coord\n Math.min(...transformedCoords.map(i => i[1])),\n // Max x coord\n Math.max(...transformedCoords.map(i => i[0])),\n // Max y coord\n Math.max(...transformedCoords.map(i => i[1]))\n ];\n return transformedBox;\n}\n\nexport function getURLFromTemplate(template, properties) {\n if (!template || !template.length) {\n return null;\n }\n if (Array.isArray(template)) {\n const index = Math.abs(properties.x + properties.y) % template.length;\n template = template[index];\n }\n\n const {x, y, z} = properties;\n return template\n .replace('{x}', x)\n .replace('{y}', y)\n .replace('{z}', z)\n .replace('{-y}', Math.pow(2, z) - y - 1);\n}\n\n/**\n * gets the bounding box of a viewport\n */\nfunction getBoundingBox(viewport, zRange, extent) {\n let bounds;\n if (zRange && zRange.length === 2) {\n const [minZ, maxZ] = zRange;\n const bounds0 = viewport.getBounds({z: minZ});\n const bounds1 = viewport.getBounds({z: maxZ});\n bounds = [\n Math.min(bounds0[0], bounds1[0]),\n Math.min(bounds0[1], bounds1[1]),\n Math.max(bounds0[2], bounds1[2]),\n Math.max(bounds0[3], bounds1[3])\n ];\n } else {\n bounds = viewport.getBounds();\n }\n if (!viewport.isGeospatial) {\n return [\n // Top corner should not be more then bottom corner in either direction\n Math.max(Math.min(bounds[0], extent[2]), extent[0]),\n Math.max(Math.min(bounds[1], extent[3]), extent[1]),\n // Bottom corner should not be less then top corner in either direction\n Math.min(Math.max(bounds[2], extent[0]), extent[2]),\n Math.min(Math.max(bounds[3], extent[1]), extent[3])\n ];\n }\n return [\n Math.max(bounds[0], extent[0]),\n Math.max(bounds[1], extent[1]),\n Math.min(bounds[2], extent[2]),\n Math.min(bounds[3], extent[3])\n ];\n}\n\nfunction getIndexingCoords(bbox, scale, modelMatrixInverse) {\n if (modelMatrixInverse) {\n const transformedTileIndex = transformBox(bbox, modelMatrixInverse).map(\n i => (i * scale) / TILE_SIZE\n );\n return transformedTileIndex;\n }\n return bbox.map(i => (i * scale) / TILE_SIZE);\n}\n\nfunction getScale(z, tileSize) {\n return (Math.pow(2, z) * TILE_SIZE) / tileSize;\n}\n\n// https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2\nexport function osmTile2lngLat(x, y, z) {\n const scale = getScale(z, TILE_SIZE);\n const lng = (x / scale) * 360 - 180;\n const n = Math.PI - (2 * Math.PI * y) / scale;\n const lat = (180 / Math.PI) * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));\n return [lng, lat];\n}\n\nfunction tile2XY(x, y, z, tileSize) {\n const scale = getScale(z, tileSize);\n return [(x / scale) * TILE_SIZE, (y / scale) * TILE_SIZE];\n}\nexport function tileToBoundingBox(viewport, x, y, z, tileSize = TILE_SIZE) {\n if (viewport.isGeospatial) {\n const [west, north] = osmTile2lngLat(x, y, z);\n const [east, south] = osmTile2lngLat(x + 1, y + 1, z);\n return {west, north, east, south};\n }\n const [left, top] = tile2XY(x, y, z, tileSize);\n const [right, bottom] = tile2XY(x + 1, y + 1, z, tileSize);\n return {left, top, right, bottom};\n}\n\nfunction getIdentityTileIndices(viewport, z, tileSize, extent, modelMatrixInverse) {\n const bbox = getBoundingBox(viewport, null, extent);\n const scale = getScale(z, tileSize);\n const [minX, minY, maxX, maxY] = getIndexingCoords(bbox, scale, modelMatrixInverse);\n const indices = [];\n\n /*\n | TILE | TILE | TILE |\n |(minX) |(maxX)\n */\n for (let x = Math.floor(minX); x < maxX; x++) {\n for (let y = Math.floor(minY); y < maxY; y++) {\n indices.push({x, y, z});\n }\n }\n return indices;\n}\n\n/**\n * Returns all tile indices in the current viewport. If the current zoom level is smaller\n * than minZoom, return an empty array. If the current zoom level is greater than maxZoom,\n * return tiles that are on maxZoom.\n */\n// eslint-disable-next-line complexity\nexport function getTileIndices({\n viewport,\n maxZoom,\n minZoom,\n zRange,\n extent,\n tileSize = TILE_SIZE,\n modelMatrix,\n modelMatrixInverse,\n zoomOffset = 0\n}) {\n let z = viewport.isGeospatial\n ? Math.round(viewport.zoom + Math.log2(TILE_SIZE / tileSize)) + zoomOffset\n : Math.ceil(viewport.zoom) + zoomOffset;\n if (Number.isFinite(minZoom) && z < minZoom) {\n if (!extent) {\n return [];\n }\n z = minZoom;\n }\n if (Number.isFinite(maxZoom) && z > maxZoom) {\n z = maxZoom;\n }\n let transformedExtent = extent;\n if (modelMatrix && modelMatrixInverse && extent && !viewport.isGeospatial) {\n transformedExtent = transformBox(extent, modelMatrix);\n }\n return viewport.isGeospatial\n ? getOSMTileIndices(viewport, z, zRange, extent)\n : getIdentityTileIndices(\n viewport,\n z,\n tileSize,\n transformedExtent || DEFAULT_EXTENT,\n modelMatrixInverse\n );\n}\n\n/**\n * Returns true if s is a valid URL template\n */\nexport function isURLTemplate(s) {\n return /(?=.*{z})(?=.*{x})(?=.*({y}|{-y}))/.test(s);\n}\n","'use strict';\n\nvar compileSchema = require('./compile')\n , resolve = require('./compile/resolve')\n , Cache = require('./cache')\n , SchemaObject = require('./compile/schema_obj')\n , stableStringify = require('fast-json-stable-stringify')\n , formats = require('./compile/formats')\n , rules = require('./compile/rules')\n , $dataMetaSchema = require('./data')\n , util = require('./compile/util');\n\nmodule.exports = Ajv;\n\nAjv.prototype.validate = validate;\nAjv.prototype.compile = compile;\nAjv.prototype.addSchema = addSchema;\nAjv.prototype.addMetaSchema = addMetaSchema;\nAjv.prototype.validateSchema = validateSchema;\nAjv.prototype.getSchema = getSchema;\nAjv.prototype.removeSchema = removeSchema;\nAjv.prototype.addFormat = addFormat;\nAjv.prototype.errorsText = errorsText;\n\nAjv.prototype._addSchema = _addSchema;\nAjv.prototype._compile = _compile;\n\nAjv.prototype.compileAsync = require('./compile/async');\nvar customKeyword = require('./keyword');\nAjv.prototype.addKeyword = customKeyword.add;\nAjv.prototype.getKeyword = customKeyword.get;\nAjv.prototype.removeKeyword = customKeyword.remove;\nAjv.prototype.validateKeyword = customKeyword.validate;\n\nvar errorClasses = require('./compile/error_classes');\nAjv.ValidationError = errorClasses.Validation;\nAjv.MissingRefError = errorClasses.MissingRef;\nAjv.$dataMetaSchema = $dataMetaSchema;\n\nvar META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';\n\nvar META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];\nvar META_SUPPORT_DATA = ['/properties'];\n\n/**\n * Creates validator instance.\n * Usage: `Ajv(opts)`\n * @param {Object} opts optional options\n * @return {Object} ajv instance\n */\nfunction Ajv(opts) {\n if (!(this instanceof Ajv)) return new Ajv(opts);\n opts = this._opts = util.copy(opts) || {};\n setLogger(this);\n this._schemas = {};\n this._refs = {};\n this._fragments = {};\n this._formats = formats(opts.format);\n\n this._cache = opts.cache || new Cache;\n this._loadingSchemas = {};\n this._compilations = [];\n this.RULES = rules();\n this._getId = chooseGetId(opts);\n\n opts.loopRequired = opts.loopRequired || Infinity;\n if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;\n if (opts.serialize === undefined) opts.serialize = stableStringify;\n this._metaOpts = getMetaSchemaOptions(this);\n\n if (opts.formats) addInitialFormats(this);\n if (opts.keywords) addInitialKeywords(this);\n addDefaultMetaSchema(this);\n if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);\n if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});\n addInitialSchemas(this);\n}\n\n\n\n/**\n * Validate data using schema\n * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.\n * @this Ajv\n * @param {String|Object} schemaKeyRef key, ref or schema object\n * @param {Any} data to be validated\n * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).\n */\nfunction validate(schemaKeyRef, data) {\n var v;\n if (typeof schemaKeyRef == 'string') {\n v = this.getSchema(schemaKeyRef);\n if (!v) throw new Error('no schema with key or ref \"' + schemaKeyRef + '\"');\n } else {\n var schemaObj = this._addSchema(schemaKeyRef);\n v = schemaObj.validate || this._compile(schemaObj);\n }\n\n var valid = v(data);\n if (v.$async !== true) this.errors = v.errors;\n return valid;\n}\n\n\n/**\n * Create validating function for passed schema.\n * @this Ajv\n * @param {Object} schema schema object\n * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.\n * @return {Function} validating function\n */\nfunction compile(schema, _meta) {\n var schemaObj = this._addSchema(schema, undefined, _meta);\n return schemaObj.validate || this._compile(schemaObj);\n}\n\n\n/**\n * Adds schema to the instance.\n * @this Ajv\n * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.\n * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.\n * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n * @return {Ajv} this for method chaining\n */\nfunction addSchema(schema, key, _skipValidation, _meta) {\n if (Array.isArray(schema)){\n for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used.\n * @param {Object} options optional options with properties `separator` and `dataVar`.\n * @return {String} human readable string with all errors descriptions\n */\nfunction errorsText(errors, options) {\n errors = errors || this.errors;\n if (!errors) return 'No errors';\n options = options || {};\n var separator = options.separator === undefined ? ', ' : options.separator;\n var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;\n\n var text = '';\n for (var i=0; i>2];var end=ret+size+15&-16;if(end>_emscripten_get_heap_size()){abort()}HEAP32[DYNAMICTOP_PTR>>2]=end;return ret}function getNativeTypeSize(type){switch(type){case\"i1\":case\"i8\":return 1;case\"i16\":return 2;case\"i32\":return 4;case\"i64\":return 8;case\"float\":return 4;case\"double\":return 8;default:{if(type[type.length-1]===\"*\"){return 4}else if(type[0]===\"i\"){var bits=parseInt(type.substr(1));assert(bits%8===0,\"getNativeTypeSize invalid bits \"+bits+\", type \"+type);return bits/8}else{return 0}}}}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}var jsCallStartIndex=1;var functionPointers=new Array(0);var funcWrappers={};function dynCall(sig,ptr,args){if(args&&args.length){return Module[\"dynCall_\"+sig].apply(null,[ptr].concat(args))}else{return Module[\"dynCall_\"+sig].call(null,ptr)}}var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var getTempRet0=function(){return tempRet0};var GLOBAL_BASE=8;var wasmBinary;if(Module[\"wasmBinary\"])wasmBinary=Module[\"wasmBinary\"];var noExitRuntime;if(Module[\"noExitRuntime\"])noExitRuntime=Module[\"noExitRuntime\"];function setValue(ptr,value,type,noSafe){type=type||\"i8\";if(type.charAt(type.length-1)===\"*\")type=\"i32\";switch(type){case\"i1\":HEAP8[ptr>>0]=value;break;case\"i8\":HEAP8[ptr>>0]=value;break;case\"i16\":HEAP16[ptr>>1]=value;break;case\"i32\":HEAP32[ptr>>2]=value;break;case\"i64\":tempI64=[value>>>0,(tempDouble=value,+Math_abs(tempDouble)>=+1?tempDouble>+0?(Math_min(+Math_floor(tempDouble/+4294967296),+4294967295)|0)>>>0:~~+Math_ceil((tempDouble-+(~~tempDouble>>>0))/+4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case\"float\":HEAPF32[ptr>>2]=value;break;case\"double\":HEAPF64[ptr>>3]=value;break;default:abort(\"invalid type for setValue: \"+type)}}function getValue(ptr,type,noSafe){type=type||\"i8\";if(type.charAt(type.length-1)===\"*\")type=\"i32\";switch(type){case\"i1\":return HEAP8[ptr>>0];case\"i8\":return HEAP8[ptr>>0];case\"i16\":return HEAP16[ptr>>1];case\"i32\":return HEAP32[ptr>>2];case\"i64\":return HEAP32[ptr>>2];case\"float\":return HEAPF32[ptr>>2];case\"double\":return HEAPF64[ptr>>3];default:abort(\"invalid type for getValue: \"+type)}return null}var ABORT=false;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort(\"Assertion failed: \"+text)}}function getCFunc(ident){var func=Module[\"_\"+ident];assert(func,\"Cannot call unknown function \"+ident+\", make sure it is exported\");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={\"string\":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},\"array\":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType===\"string\")return UTF8ToString(ret);if(returnType===\"boolean\")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i=endIdx))++endPtr;if(endPtr-idx>16&&u8Array.subarray&&UTF8Decoder){return UTF8Decoder.decode(u8Array.subarray(idx,endPtr))}else{var str=\"\";while(idx>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):\"\"}function stringToUTF8Array(str,outU8Array,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;outU8Array[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;outU8Array[outIdx++]=192|u>>6;outU8Array[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;outU8Array[outIdx++]=224|u>>12;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;outU8Array[outIdx++]=240|u>>18;outU8Array[outIdx++]=128|u>>12&63;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}}outU8Array[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}var UTF16Decoder=typeof TextDecoder!==\"undefined\"?new TextDecoder(\"utf-16le\"):undefined;function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module[\"HEAP8\"]=HEAP8=new Int8Array(buf);Module[\"HEAP16\"]=HEAP16=new Int16Array(buf);Module[\"HEAP32\"]=HEAP32=new Int32Array(buf);Module[\"HEAPU8\"]=HEAPU8=new Uint8Array(buf);Module[\"HEAPU16\"]=HEAPU16=new Uint16Array(buf);Module[\"HEAPU32\"]=HEAPU32=new Uint32Array(buf);Module[\"HEAPF32\"]=HEAPF32=new Float32Array(buf);Module[\"HEAPF64\"]=HEAPF64=new Float64Array(buf)}var STACK_BASE=24048,DYNAMIC_BASE=5266928,DYNAMICTOP_PTR=24016;var INITIAL_TOTAL_MEMORY=Module[\"TOTAL_MEMORY\"]||33554432;if(Module[\"buffer\"]){buffer=Module[\"buffer\"]}else{buffer=new ArrayBuffer(INITIAL_TOTAL_MEMORY)}INITIAL_TOTAL_MEMORY=buffer.byteLength;updateGlobalBufferAndViews(buffer);HEAP32[DYNAMICTOP_PTR>>2]=DYNAMIC_BASE;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback==\"function\"){callback();continue}var func=callback.func;if(typeof func===\"number\"){if(callback.arg===undefined){Module[\"dynCall_v\"](func)}else{Module[\"dynCall_vi\"](func,callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module[\"preRun\"]){if(typeof Module[\"preRun\"]==\"function\")Module[\"preRun\"]=[Module[\"preRun\"]];while(Module[\"preRun\"].length){addOnPreRun(Module[\"preRun\"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module[\"postRun\"]){if(typeof Module[\"postRun\"]==\"function\")Module[\"postRun\"]=[Module[\"postRun\"]];while(Module[\"postRun\"].length){addOnPostRun(Module[\"postRun\"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var Math_abs=Math.abs;var Math_ceil=Math.ceil;var Math_floor=Math.floor;var Math_min=Math.min;var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module[\"preloadedImages\"]={};Module[\"preloadedAudios\"]={};var memoryInitializer=null;var dataURIPrefix=\"data:application/octet-stream;base64,\";function isDataURI(filename){return String.prototype.startsWith?filename.startsWith(dataURIPrefix):filename.indexOf(dataURIPrefix)===0}var tempDouble;var tempI64;memoryInitializer=\"data:application/octet-stream;base64,AAAAAAAAAAACAAAAAwAAAAEAAAAFAAAABAAAAAYAAAAAAAAAAAAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAYAAAABAAAABAAAAAMAAAAGAAAABQAAAAIAAAAAAAAAAgAAAAMAAAABAAAABAAAAAYAAAAAAAAABQAAAAMAAAAGAAAABAAAAAUAAAAAAAAAAQAAAAIAAAAEAAAABQAAAAYAAAAAAAAAAgAAAAMAAAABAAAABQAAAAIAAAAAAAAAAQAAAAMAAAAGAAAABAAAAAYAAAAAAAAABQAAAAIAAAABAAAABAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAgAAAAMAAAAAAAAAAAAAAAIAAAAAAAAAAQAAAAMAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAABgAAAAAAAAAFAAAAAAAAAAAAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAIAAAAAAAAABgAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAEAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAACAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAwAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAQAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAFAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABgAAAAAAAAABAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAA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I4VQLT3ik5FcA5Angi7LOZd+z+NNVzDy5gXQBXdvVTFUA1AYNMgOeYe+T8+qHXGCwkXQKQTOKwa5AJA8gFVoEMW0T+FwzJyttIRQAEAAAD/////BwAAAP////8xAAAA/////1cBAAD/////YQkAAP////+nQQAA/////5HLAQD/////95AMAP/////B9lcAAAAAAAAAAAAAAAAAAgAAAP////8OAAAA/////2IAAAD/////rgIAAP/////CEgAA/////06DAAD/////IpcDAP/////uIRkA/////4LtrwAAAAAAAAAAAAAAAAAAAAAAAgAAAP//////////AQAAAAMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////////////////////wEAAAAAAAAAAgAAAP///////////////wMAAAD//////////////////////////////////////////////////////////wIAAAD//////////wEAAAAAAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA/////////////////////wEAAAD///////////////8CAAAA////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAA////////////////AgAAAAEAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AQAAAAIAAAD///////////////8AAAAA/////////////////////wMAAAD///////////////////////////////8CAAAA////////////////AQAAAP////////////////////8AAAAA/////////////////////wMAAAD/////////////////////////////////////////////////////AwAAAP////////////////////8AAAAAAQAAAP//////////AgAAAP//////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAP///////////////wIAAAAAAAAAAQAAAP//////////////////////////////////////////////////////////////////////////AwAAAAEAAAD//////////wIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAgAAAAAAAAACAAAAAQAAAAEAAAACAAAAAgAAAAAAAAAFAAAABQAAAAAAAAACAAAAAgAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAABAAAAAgAAAAIAAAACAAAAAAAAAAUAAAAGAAAAAAAAAAIAAAACAAAAAwAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAAAAAAAAgAAAAEAAAADAAAAAgAAAAIAAAAAAAAABQAAAAcAAAAAAAAAAgAAAAIAAAADAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAgAAAAAAAAACAAAAAQAAAAQAAAACAAAAAgAAAAAAAAAFAAAACAAAAAAAAAACAAAAAgAAAAMAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAACAAAAAAAAAAIAAAABAAAAAAAAAAIAAAACAAAAAAAAAAUAAAAJAAAAAAAAAAIAAAACAAAAAwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAIAAAACAAAAAAAAAAMAAAAOAAAAAgAAAAAAAAACAAAAAwAAAAAAAAAAAAAAAgAAAAIAAAADAAAABgAAAAAAAAAAAAAAAAAAAAAAAAALAAAAAgAAAAIAAAAAAAAAAwAAAAoAAAACAAAAAAAAAAIAAAADAAAAAQAAAAAAAAACAAAAAgAAAAMAAAAHAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAACAAAAAgAAAAAAAAADAAAACwAAAAIAAAAAAAAAAgAAAAMAAAACAAAAAAAAAAIAAAACAAAAAwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAADQAAAAIAAAACAAAAAAAAAAMAAAAMAAAAAgAAAAAAAAAC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O1AB/AWSJgT1kDfUWNCNLDAQNk+5C33OqlAchWL34QSk0DKvtDIrNV8QNF0G3kFzGVASSeWhBl6UED+/0mNGuk4QGjA/dm/1CJALPLPMql6DEDSHoDrwpP1P2jouzWST+A/egAAAAAAAABKAwAAAAAAAPoWAAAAAAAAyqAAAAAAAAB6ZQQAAAAAAErGHgAAAAAA+mvXAAAAAADK8+MFAAAAAHqqOykAAAAASqmhIAEAAAD6oGvkBwAAAMpm8T43AAAAes+ZuIIBAABKrDQMkwoAAPq1cFUFSgAAyvkUViUGAgAAAAAAAwAAAAYAAAACAAAABQAAAAEAAAAEAAAAAAAAAAAAAAAFAAAAAwAAAAEAAAAGAAAABAAAAAIAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAP////////////////////////////////////8AAAAA/////wAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAP////8AAAAAAAAAAAEAAAABAAAAAAAAAAAAAAD/////AAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAA/////wUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////AAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/////////////////////////////////////wAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAUAAA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ZW9Cb3VuZGFyeQBwb2x5Z29uLT5uZXh0ID09IE5VTEwAbGlua2VkR2VvLmMAYWRkTmV3TGlua2VkUG9seWdvbgBuZXh0ICE9IE5VTEwAbG9vcCAhPSBOVUxMAGFkZE5ld0xpbmtlZExvb3AAcG9seWdvbi0+Zmlyc3QgPT0gTlVMTABhZGRMaW5rZWRMb29wAGNvb3JkICE9IE5VTEwAYWRkTGlua2VkQ29vcmQAbG9vcC0+Zmlyc3QgPT0gTlVMTABpbm5lckxvb3BzICE9IE5VTEwAbm9ybWFsaXplTXVsdGlQb2x5Z29uAGJib3hlcyAhPSBOVUxMAGNhbmRpZGF0ZXMgIT0gTlVMTABmaW5kUG9seWdvbkZvckhvbGUAY2FuZGlkYXRlQkJveGVzICE9IE5VTEwAcmV2RGlyICE9IElOVkFMSURfRElHSVQAbG9jYWxpai5jAGgzVG9Mb2NhbElqawBiYXNlQ2VsbCAhPSBvcmlnaW5CYXNlQ2VsbAAhKG9yaWdpbk9uUGVudCAmJiBpbmRleE9uUGVudCkAcGVudGFnb25Sb3RhdGlvbnMgPj0gMABkaXJlY3Rpb25Sb3RhdGlvbnMgPj0gMABiYXNlQ2VsbCA9PSBvcmlnaW5CYXNlQ2VsbABiYXNlQ2VsbCAhPSBJTlZBTElEX0JBU0VfQ0VMTABsb2NhbElqa1RvSDMAIV9pc0Jhc2VDZWxsUGVudGFnb24oYmFzZUNlbGwpAGJhc2VDZWxsUm90YXRpb25zID49IDAAd2l0aGluUGVudGFnb25Sb3RhdGlvbnMgPj0gMABncmFwaC0+YnVja2V0cyAhPSBOVUxMAHZlcnRleEdyYXBoLmMAaW5pdFZlcnRleEdyYXBoAG5vZGUgIT0gTlVMTABhZGRWZXJ0ZXhOb2Rl\";var tempDoublePtr=24032;function demangle(func){return func}function demangleAll(text){var regex=/\\b__Z[\\w\\d_]+/g;return text.replace(regex,function(x){var y=demangle(x);return x===y?x:y+\" [\"+x+\"]\"})}function jsStackTrace(){var err=new Error;if(!err.stack){try{throw new Error(0)}catch(e){err=e}if(!err.stack){return\"(no stack trace available)\"}}return err.stack.toString()}function stackTrace(){var js=jsStackTrace();if(Module[\"extraStackTrace\"])js+=\"\\n\"+Module[\"extraStackTrace\"]();return demangleAll(js)}function ___assert_fail(condition,filename,line,func){abort(\"Assertion failed: \"+UTF8ToString(condition)+\", at: \"+[filename?UTF8ToString(filename):\"unknown filename\",line,func?UTF8ToString(func):\"unknown function\"])}function _emscripten_get_heap_size(){return HEAP8.length}function _emscripten_memcpy_big(dest,src,num){HEAPU8.set(HEAPU8.subarray(src,src+num),dest)}function ___setErrNo(value){if(Module[\"___errno_location\"])HEAP32[Module[\"___errno_location\"]()>>2]=value;return value}function abortOnCannotGrowMemory(requestedSize){abort(\"OOM\")}function emscripten_realloc_buffer(size){try{var newBuffer=new ArrayBuffer(size);if(newBuffer.byteLength!=size)return;new Int8Array(newBuffer).set(HEAP8);_emscripten_replace_memory(newBuffer);updateGlobalBufferAndViews(newBuffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=_emscripten_get_heap_size();var PAGE_MULTIPLE=16777216;var LIMIT=2147483648-PAGE_MULTIPLE;if(requestedSize>LIMIT){return false}var MIN_TOTAL_MEMORY=16777216;var newSize=Math.max(oldSize,MIN_TOTAL_MEMORY);while(newSize255){if(ASSERTIONS){assert(false,\"Character code \"+chr+\" (\"+String.fromCharCode(chr)+\") at offset \"+i+\" not in 0x00-0xFF.\")}chr&=255}ret.push(String.fromCharCode(chr))}return ret.join(\"\")}var decodeBase64=typeof atob===\"function\"?atob:function(input){var keyStr=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";var output=\"\";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\\+\\/\\=]/g,\"\");do{enc1=keyStr.indexOf(input.charAt(i++));enc2=keyStr.indexOf(input.charAt(i++));enc3=keyStr.indexOf(input.charAt(i++));enc4=keyStr.indexOf(input.charAt(i++));chr1=enc1<<2|enc2>>4;chr2=(enc2&15)<<4|enc3>>2;chr3=(enc3&3)<<6|enc4;output=output+String.fromCharCode(chr1);if(enc3!==64){output=output+String.fromCharCode(chr2)}if(enc4!==64){output=output+String.fromCharCode(chr3)}}while(i>2]=a;b[g+4>>2]=c;g=(f|0)!=0;if(g)b[f>>2]=0;if(Eb(a,c)|0){n=1;S=o;return n|0}b[n>>2]=0;a:do if((d|0)>=1)if(g){k=0;l=1;m=1;h=0;g=a;while(1){if(!(h|k)){g=da(g,c,4,n)|0;c=G()|0;if((g|0)==0&(c|0)==0){g=2;break a}if(Eb(g,c)|0){g=1;break a}}g=da(g,c,b[16+(k<<2)>>2]|0,n)|0;c=G()|0;if((g|0)==0&(c|0)==0){g=2;break a}a=e+(m<<3)|0;b[a>>2]=g;b[a+4>>2]=c;b[f+(m<<2)>>2]=l;h=h+1|0;a=(h|0)==(l|0);i=k+1|0;j=(i|0)==6;if(Eb(g,c)|0){g=1;break a}l=l+(j&a&1)|0;if((l|0)>(d|0)){g=0;break}else{k=a?(j?0:i):k;m=m+1|0;h=a?0:h}}}else{k=0;l=1;m=1;h=0;g=a;while(1){if(!(h|k)){g=da(g,c,4,n)|0;c=G()|0;if((g|0)==0&(c|0)==0){g=2;break a}if(Eb(g,c)|0){g=1;break a}}g=da(g,c,b[16+(k<<2)>>2]|0,n)|0;c=G()|0;if((g|0)==0&(c|0)==0){g=2;break a}a=e+(m<<3)|0;b[a>>2]=g;b[a+4>>2]=c;h=h+1|0;a=(h|0)==(l|0);i=k+1|0;j=(i|0)==6;if(Eb(g,c)|0){g=1;break a}l=l+(j&a&1)|0;if((l|0)>(d|0)){g=0;break}else{k=a?(j?0:i):k;m=m+1|0;h=a?0:h}}}else g=0;while(0);n=g;S=o;return n|0}function ca(a,c,d,e,f,g,h){a=a|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var i=0,j=0,k=0,l=0,m=0,n=0,o=0;m=S;S=S+16|0;l=m;if((a|0)==0&(c|0)==0){S=m;return}i=ad(a|0,c|0,g|0,((g|0)<0)<<31>>31|0)|0;G()|0;j=e+(i<<3)|0;n=j;o=b[n>>2]|0;n=b[n+4>>2]|0;k=(o|0)==(a|0)&(n|0)==(c|0);if(!((o|0)==0&(n|0)==0|k))do{i=(i+1|0)%(g|0)|0;j=e+(i<<3)|0;o=j;n=b[o>>2]|0;o=b[o+4>>2]|0;k=(n|0)==(a|0)&(o|0)==(c|0)}while(!((n|0)==0&(o|0)==0|k));i=f+(i<<2)|0;if(k?(b[i>>2]|0)<=(h|0):0){S=m;return}o=j;b[o>>2]=a;b[o+4>>2]=c;b[i>>2]=h;if((h|0)>=(d|0)){S=m;return}o=h+1|0;b[l>>2]=0;n=da(a,c,2,l)|0;ca(n,G()|0,d,e,f,g,o);b[l>>2]=0;n=da(a,c,3,l)|0;ca(n,G()|0,d,e,f,g,o);b[l>>2]=0;n=da(a,c,1,l)|0;ca(n,G()|0,d,e,f,g,o);b[l>>2]=0;n=da(a,c,5,l)|0;ca(n,G()|0,d,e,f,g,o);b[l>>2]=0;n=da(a,c,4,l)|0;ca(n,G()|0,d,e,f,g,o);b[l>>2]=0;n=da(a,c,6,l)|0;ca(n,G()|0,d,e,f,g,o);S=m;return}function da(a,c,d,e){a=a|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0;if((b[e>>2]|0)>0){f=0;do{d=Pa(d)|0;f=f+1|0}while((f|0)<(b[e>>2]|0))}i=bd(a|0,c|0,45)|0;G()|0;j=i&127;g=Kb(a,c)|0;f=bd(a|0,c|0,52)|0;G()|0;f=f&15;a:do if(!f)h=6;else while(1){m=(15-f|0)*3|0;n=bd(a|0,c|0,m|0)|0;G()|0;n=n&7;o=(Qb(f)|0)==0;f=f+-1|0;l=cd(7,0,m|0)|0;c=c&~(G()|0);m=cd(b[(o?464:48)+(n*28|0)+(d<<2)>>2]|0,0,m|0)|0;k=G()|0;d=b[(o?672:256)+(n*28|0)+(d<<2)>>2]|0;a=m|a&~l;c=k|c;if(!d){d=0;break a}if(!f){h=6;break}}while(0);if((h|0)==6){o=b[880+(j*28|0)+(d<<2)>>2]|0;n=cd(o|0,0,45)|0;a=n|a;c=G()|0|c&-1040385;d=b[4304+(j*28|0)+(d<<2)>>2]|0;if((o&127|0)==127){o=cd(b[880+(j*28|0)+20>>2]|0,0,45)|0;c=G()|0|c&-1040385;d=b[4304+(j*28|0)+20>>2]|0;a=Mb(o|a,c)|0;c=G()|0;b[e>>2]=(b[e>>2]|0)+1}}h=bd(a|0,c|0,45)|0;G()|0;h=h&127;b:do if(!(la(h)|0)){if((d|0)>0){f=0;do{a=Mb(a,c)|0;c=G()|0;f=f+1|0}while((f|0)!=(d|0))}}else{c:do if((Kb(a,c)|0)==1){if((j|0)!=(h|0))if(ra(h,b[7728+(j*28|0)>>2]|0)|0){a=Ob(a,c)|0;g=1;c=G()|0;break}else{a=Mb(a,c)|0;g=1;c=G()|0;break}switch(g|0){case 5:{a=Ob(a,c)|0;c=G()|0;b[e>>2]=(b[e>>2]|0)+5;g=0;break c}case 3:{a=Mb(a,c)|0;c=G()|0;b[e>>2]=(b[e>>2]|0)+1;g=0;break c}default:{n=0;o=0;F(n|0);return o|0}}}else g=0;while(0);if((d|0)>0){f=0;do{a=Lb(a,c)|0;c=G()|0;f=f+1|0}while((f|0)!=(d|0))}if((j|0)!=(h|0)){if(!(ma(h)|0)){if((g|0)!=0|(Kb(a,c)|0)!=5)break;b[e>>2]=(b[e>>2]|0)+1;break}switch(i&127){case 8:case 118:break b;default:{}}if((Kb(a,c)|0)!=3)b[e>>2]=(b[e>>2]|0)+1}}while(0);b[e>>2]=((b[e>>2]|0)+d|0)%6|0;n=c;o=a;F(n|0);return o|0}function ea(a,c,d,e){a=a|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0;m=S;S=S+16|0;l=m;if(!d){l=e;b[l>>2]=a;b[l+4>>2]=c;l=0;S=m;return l|0}b[l>>2]=0;a:do if(!(Eb(a,c)|0)){g=(d|0)>0;if(g){f=0;k=a;do{k=da(k,c,4,l)|0;c=G()|0;if((k|0)==0&(c|0)==0){a=2;break a}f=f+1|0;if(Eb(k,c)|0){a=1;break a}}while((f|0)<(d|0));j=e;b[j>>2]=k;b[j+4>>2]=c;j=d+-1|0;if(g){g=0;h=1;f=k;a=c;do{f=da(f,a,2,l)|0;a=G()|0;if((f|0)==0&(a|0)==0){a=2;break a}i=e+(h<<3)|0;b[i>>2]=f;b[i+4>>2]=a;h=h+1|0;if(Eb(f,a)|0){a=1;break a}g=g+1|0}while((g|0)<(d|0));i=0;g=h;do{f=da(f,a,3,l)|0;a=G()|0;if((f|0)==0&(a|0)==0){a=2;break a}h=e+(g<<3)|0;b[h>>2]=f;b[h+4>>2]=a;g=g+1|0;if(Eb(f,a)|0){a=1;break a}i=i+1|0}while((i|0)<(d|0));h=0;do{f=da(f,a,1,l)|0;a=G()|0;if((f|0)==0&(a|0)==0){a=2;break a}i=e+(g<<3)|0;b[i>>2]=f;b[i+4>>2]=a;g=g+1|0;if(Eb(f,a)|0){a=1;break a}h=h+1|0}while((h|0)<(d|0));h=0;do{f=da(f,a,5,l)|0;a=G()|0;if((f|0)==0&(a|0)==0){a=2;break a}i=e+(g<<3)|0;b[i>>2]=f;b[i+4>>2]=a;g=g+1|0;if(Eb(f,a)|0){a=1;break a}h=h+1|0}while((h|0)<(d|0));h=0;do{f=da(f,a,4,l)|0;a=G()|0;if((f|0)==0&(a|0)==0){a=2;break a}i=e+(g<<3)|0;b[i>>2]=f;b[i+4>>2]=a;g=g+1|0;if(Eb(f,a)|0){a=1;break a}h=h+1|0}while((h|0)<(d|0));h=0;while(1){f=da(f,a,6,l)|0;a=G()|0;if((f|0)==0&(a|0)==0){a=2;break a}if((h|0)!=(j|0)){i=e+(g<<3)|0;b[i>>2]=f;b[i+4>>2]=a;if(!(Eb(f,a)|0))g=g+1|0;else{a=1;break a}}h=h+1|0;if((h|0)>=(d|0)){h=k;g=c;break}}}else{h=k;f=k;g=c;a=c}}else{h=e;b[h>>2]=a;b[h+4>>2]=c;h=a;f=a;g=c;a=c}a=((h|0)!=(f|0)|(g|0)!=(a|0))&1}else a=1;while(0);l=a;S=m;return l|0}function fa(a,c){a=a|0;c=c|0;var d=0,e=0,f=0,g=0,h=0,i=0;g=S;S=S+48|0;f=g+8|0;e=g;i=a;h=b[i+4>>2]|0;d=e;b[d>>2]=b[i>>2];b[d+4>>2]=h;uc(e,f);f=ya(f,c)|0;c=b[e>>2]|0;e=b[a+8>>2]|0;if((e|0)<=0){i=c;h=(f|0)<(i|0);i=h?i:f;i=i+12|0;S=g;return i|0}d=b[a+12>>2]|0;a=0;do{c=(b[d+(a<<3)>>2]|0)+c|0;a=a+1|0}while((a|0)<(e|0));i=(f|0)<(c|0);i=i?c:f;i=i+12|0;S=g;return i|0}function ga(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0;i=S;S=S+48|0;e=i+8|0;f=i;if(!(ha(a,c,d)|0)){S=i;return}j=a;g=b[j+4>>2]|0;h=f;b[h>>2]=b[j>>2];b[h+4>>2]=g;uc(f,e);h=ya(e,c)|0;c=b[f>>2]|0;g=b[a+8>>2]|0;if((g|0)>0){f=b[a+12>>2]|0;e=0;do{c=(b[f+(e<<3)>>2]|0)+c|0;e=e+1|0}while((e|0)!=(g|0))}c=(h|0)<(c|0)?c:h;if((c|0)<=-12){S=i;return}j=c+11|0;gd(d|0,0,(((j|0)>0?j:0)<<3)+8|0)|0;S=i;return}function ha(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,I=0,J=0;J=S;S=S+112|0;D=J+80|0;j=J+72|0;E=J;F=J+56|0;k=a+8|0;I=Vc((b[k>>2]<<5)+32|0)|0;if(!I)H(22848,22448,800,22456);vc(a,I);g=a;e=b[g+4>>2]|0;i=j;b[i>>2]=b[g>>2];b[i+4>>2]=e;uc(j,D);i=ya(D,c)|0;e=b[j>>2]|0;g=b[k>>2]|0;if((g|0)>0){h=b[a+12>>2]|0;f=0;do{e=(b[h+(f<<3)>>2]|0)+e|0;f=f+1|0}while((f|0)!=(g|0))}i=(i|0)<(e|0)?e:i;C=i+12|0;f=Xc(C,8)|0;l=Xc(C,8)|0;b[D>>2]=0;A=a;B=b[A+4>>2]|0;e=j;b[e>>2]=b[A>>2];b[e+4>>2]=B;e=ia(j,C,c,D,f,l)|0;if(e|0){Wc(f);Wc(l);Wc(I);I=e;S=J;return I|0}a:do if((b[k>>2]|0)>0){g=a+12|0;e=0;while(1){h=ia((b[g>>2]|0)+(e<<3)|0,C,c,D,f,l)|0;e=e+1|0;if(h|0)break;if((e|0)>=(b[k>>2]|0))break a}Wc(f);Wc(l);Wc(I);I=h;S=J;return I|0}while(0);if((i|0)>-12)gd(l|0,0,((C|0)>1?C:1)<<3|0)|0;b:do if((b[D>>2]|0)>0){B=((C|0)<0)<<31>>31;v=f;w=l;x=f;y=f;z=l;A=f;e=f;r=f;s=l;t=l;u=l;f=l;c:while(1){q=b[D>>2]|0;o=0;p=0;g=0;while(1){h=E;i=h+56|0;do{b[h>>2]=0;h=h+4|0}while((h|0)<(i|0));c=v+(o<<3)|0;j=b[c>>2]|0;c=b[c+4>>2]|0;if(ba(j,c,1,E,0)|0){h=E;i=h+56|0;do{b[h>>2]=0;h=h+4|0}while((h|0)<(i|0));h=Xc(7,4)|0;if(h|0){ca(j,c,1,E,h,7,0);Wc(h)}}n=0;do{m=E+(n<<3)|0;l=b[m>>2]|0;m=b[m+4>>2]|0;d:do if(!((l|0)==0&(m|0)==0)){j=ad(l|0,m|0,C|0,B|0)|0;G()|0;h=d+(j<<3)|0;i=h;c=b[i>>2]|0;i=b[i+4>>2]|0;if(!((c|0)==0&(i|0)==0)){k=0;while(1){if((k|0)>(C|0))break c;if((c|0)==(l|0)&(i|0)==(m|0))break d;j=(j+1|0)%(C|0)|0;h=d+(j<<3)|0;i=h;c=b[i>>2]|0;i=b[i+4>>2]|0;if((c|0)==0&(i|0)==0)break;else k=k+1|0}}if(!((l|0)==0&(m|0)==0)){Ub(l,m,F);if(wc(a,I,F)|0){k=h;b[k>>2]=l;b[k+4>>2]=m;k=w+(g<<3)|0;b[k>>2]=l;b[k+4>>2]=m;g=g+1|0}}}while(0);n=n+1|0}while(n>>>0<7);p=p+1|0;if((p|0)>=(q|0))break;else o=o+1|0}if((q|0)>0)gd(x|0,0,q<<3|0)|0;b[D>>2]=g;if((g|0)>0){l=f;m=u;n=A;o=t;p=s;q=w;f=r;u=e;t=y;s=x;r=l;e=m;A=z;z=n;y=o;x=p;w=v;v=q}else break b}Wc(y);Wc(z);Wc(I);I=-1;S=J;return I|0}else e=l;while(0);Wc(I);Wc(f);Wc(e);I=0;S=J;return I|0}function ia(a,c,d,f,g,h){a=a|0;c=c|0;d=d|0;f=f|0;g=g|0;h=h|0;var i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0.0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0.0,E=0.0;C=S;S=S+48|0;y=C+32|0;z=C+16|0;A=C;i=b[a>>2]|0;if((i|0)<=0){B=0;S=C;return B|0}t=a+4|0;u=y+8|0;v=z+8|0;w=A+8|0;x=((c|0)<0)<<31>>31;s=0;a:while(1){j=b[t>>2]|0;q=j+(s<<4)|0;b[y>>2]=b[q>>2];b[y+4>>2]=b[q+4>>2];b[y+8>>2]=b[q+8>>2];b[y+12>>2]=b[q+12>>2];if((s|0)==(i+-1|0)){b[z>>2]=b[j>>2];b[z+4>>2]=b[j+4>>2];b[z+8>>2]=b[j+8>>2];b[z+12>>2]=b[j+12>>2]}else{q=j+(s+1<<4)|0;b[z>>2]=b[q>>2];b[z+4>>2]=b[q+4>>2];b[z+8>>2]=b[q+8>>2];b[z+12>>2]=b[q+12>>2]}q=za(y,z,d)|0;b:do if((q|0)>0){r=+(q|0);p=0;c:while(1){E=+(q-p|0);D=+(p|0);e[A>>3]=+e[y>>3]*E/r+ +e[z>>3]*D/r;e[w>>3]=+e[u>>3]*E/r+ +e[v>>3]*D/r;n=Rb(A,d)|0;o=G()|0;j=ad(n|0,o|0,c|0,x|0)|0;G()|0;i=h+(j<<3)|0;k=i;l=b[k>>2]|0;k=b[k+4>>2]|0;d:do if((l|0)==0&(k|0)==0)B=14;else{m=0;while(1){if((m|0)>(c|0)){i=1;break d}if((l|0)==(n|0)&(k|0)==(o|0)){i=7;break d}j=(j+1|0)%(c|0)|0;i=h+(j<<3)|0;k=i;l=b[k>>2]|0;k=b[k+4>>2]|0;if((l|0)==0&(k|0)==0){B=14;break}else m=m+1|0}}while(0);if((B|0)==14){B=0;if((n|0)==0&(o|0)==0)i=7;else{b[i>>2]=n;b[i+4>>2]=o;i=b[f>>2]|0;m=g+(i<<3)|0;b[m>>2]=n;b[m+4>>2]=o;b[f>>2]=i+1;i=0}}switch(i&7){case 7:case 0:break;default:break c}p=p+1|0;if((q|0)<=(p|0)){B=8;break b}}if(i|0){i=-1;B=20;break a}}else B=8;while(0);if((B|0)==8)B=0;s=s+1|0;i=b[a>>2]|0;if((s|0)>=(i|0)){i=0;B=20;break}}if((B|0)==20){S=C;return i|0}return 0}function ja(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0;k=S;S=S+176|0;j=k;if((c|0)<1){Lc(d,0,0);S=k;return}h=a;h=bd(b[h>>2]|0,b[h+4>>2]|0,52)|0;G()|0;Lc(d,(c|0)>6?c:6,h&15);h=0;do{e=a+(h<<3)|0;Vb(b[e>>2]|0,b[e+4>>2]|0,j);e=b[j>>2]|0;if((e|0)>0){i=0;do{g=j+8+(i<<4)|0;i=i+1|0;e=j+8+(((i|0)%(e|0)|0)<<4)|0;f=Qc(d,e,g)|0;if(!f)Pc(d,g,e)|0;else Oc(d,f)|0;e=b[j>>2]|0}while((i|0)<(e|0))}h=h+1|0}while((h|0)!=(c|0));S=k;return}function ka(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0;g=S;S=S+32|0;e=g;f=g+16|0;ja(a,c,f);b[d>>2]=0;b[d+4>>2]=0;b[d+8>>2]=0;a=Nc(f)|0;if(!a){jc(d)|0;Mc(f);S=g;return}do{c=gc(d)|0;do{hc(c,a)|0;h=a+16|0;b[e>>2]=b[h>>2];b[e+4>>2]=b[h+4>>2];b[e+8>>2]=b[h+8>>2];b[e+12>>2]=b[h+12>>2];Oc(f,a)|0;a=Rc(f,e)|0}while((a|0)!=0);a=Nc(f)|0}while((a|0)!=0);jc(d)|0;Mc(f);S=g;return}function la(a){a=a|0;return b[7728+(a*28|0)+16>>2]|0}function ma(a){a=a|0;return (a|0)==4|(a|0)==117|0}function na(a){a=a|0;return b[11152+((b[a>>2]|0)*216|0)+((b[a+4>>2]|0)*72|0)+((b[a+8>>2]|0)*24|0)+(b[a+12>>2]<<3)>>2]|0}function oa(a){a=a|0;return b[11152+((b[a>>2]|0)*216|0)+((b[a+4>>2]|0)*72|0)+((b[a+8>>2]|0)*24|0)+(b[a+12>>2]<<3)+4>>2]|0}function pa(a,c){a=a|0;c=c|0;a=7728+(a*28|0)|0;b[c>>2]=b[a>>2];b[c+4>>2]=b[a+4>>2];b[c+8>>2]=b[a+8>>2];b[c+12>>2]=b[a+12>>2];return}function qa(a,c){a=a|0;c=c|0;var d=0,e=0;if(c>>>0>20){c=-1;return c|0}do if((b[11152+(c*216|0)>>2]|0)!=(a|0))if((b[11152+(c*216|0)+8>>2]|0)!=(a|0))if((b[11152+(c*216|0)+16>>2]|0)!=(a|0))if((b[11152+(c*216|0)+24>>2]|0)!=(a|0))if((b[11152+(c*216|0)+32>>2]|0)!=(a|0))if((b[11152+(c*216|0)+40>>2]|0)!=(a|0))if((b[11152+(c*216|0)+48>>2]|0)!=(a|0))if((b[11152+(c*216|0)+56>>2]|0)!=(a|0))if((b[11152+(c*216|0)+64>>2]|0)!=(a|0))if((b[11152+(c*216|0)+72>>2]|0)!=(a|0))if((b[11152+(c*216|0)+80>>2]|0)!=(a|0))if((b[11152+(c*216|0)+88>>2]|0)!=(a|0))if((b[11152+(c*216|0)+96>>2]|0)!=(a|0))if((b[11152+(c*216|0)+104>>2]|0)!=(a|0))if((b[11152+(c*216|0)+112>>2]|0)!=(a|0))if((b[11152+(c*216|0)+120>>2]|0)!=(a|0))if((b[11152+(c*216|0)+128>>2]|0)!=(a|0))if((b[11152+(c*216|0)+136>>2]|0)==(a|0)){a=2;d=1;e=2}else{if((b[11152+(c*216|0)+144>>2]|0)==(a|0)){a=0;d=2;e=0;break}if((b[11152+(c*216|0)+152>>2]|0)==(a|0)){a=0;d=2;e=1;break}if((b[11152+(c*216|0)+160>>2]|0)==(a|0)){a=0;d=2;e=2;break}if((b[11152+(c*216|0)+168>>2]|0)==(a|0)){a=1;d=2;e=0;break}if((b[11152+(c*216|0)+176>>2]|0)==(a|0)){a=1;d=2;e=1;break}if((b[11152+(c*216|0)+184>>2]|0)==(a|0)){a=1;d=2;e=2;break}if((b[11152+(c*216|0)+192>>2]|0)==(a|0)){a=2;d=2;e=0;break}if((b[11152+(c*216|0)+200>>2]|0)==(a|0)){a=2;d=2;e=1;break}if((b[11152+(c*216|0)+208>>2]|0)==(a|0)){a=2;d=2;e=2;break}else a=-1;return a|0}else{a=2;d=1;e=1}else{a=2;d=1;e=0}else{a=1;d=1;e=2}else{a=1;d=1;e=1}else{a=1;d=1;e=0}else{a=0;d=1;e=2}else{a=0;d=1;e=1}else{a=0;d=1;e=0}else{a=2;d=0;e=2}else{a=2;d=0;e=1}else{a=2;d=0;e=0}else{a=1;d=0;e=2}else{a=1;d=0;e=1}else{a=1;d=0;e=0}else{a=0;d=0;e=2}else{a=0;d=0;e=1}else{a=0;d=0;e=0}while(0);c=b[11152+(c*216|0)+(d*72|0)+(a*24|0)+(e<<3)+4>>2]|0;return c|0}function ra(a,c){a=a|0;c=c|0;if((b[7728+(a*28|0)+20>>2]|0)==(c|0)){c=1;return c|0}c=(b[7728+(a*28|0)+24>>2]|0)==(c|0);return c|0}function sa(a,c){a=a|0;c=c|0;return b[880+(a*28|0)+(c<<2)>>2]|0}function ta(a,c){a=a|0;c=c|0;if((b[880+(a*28|0)>>2]|0)==(c|0)){c=0;return c|0}if((b[880+(a*28|0)+4>>2]|0)==(c|0)){c=1;return c|0}if((b[880+(a*28|0)+8>>2]|0)==(c|0)){c=2;return c|0}if((b[880+(a*28|0)+12>>2]|0)==(c|0)){c=3;return c|0}if((b[880+(a*28|0)+16>>2]|0)==(c|0)){c=4;return c|0}if((b[880+(a*28|0)+20>>2]|0)==(c|0)){c=5;return c|0}else return ((b[880+(a*28|0)+24>>2]|0)==(c|0)?6:7)|0;return 0}function ua(){return 122}function va(a){a=a|0;var c=0,d=0,e=0;c=0;do{cd(c|0,0,45)|0;e=G()|0|134225919;d=a+(c<<3)|0;b[d>>2]=-1;b[d+4>>2]=e;c=c+1|0}while((c|0)!=122);return}function wa(a){a=a|0;return +e[a+16>>3]<+e[a+24>>3]|0}function xa(a,b){a=a|0;b=b|0;var c=0.0,d=0.0,f=0.0;c=+e[b>>3];if(!(c>=+e[a+8>>3])){b=0;return b|0}if(!(c<=+e[a>>3])){b=0;return b|0}d=+e[a+16>>3];c=+e[a+24>>3];f=+e[b+8>>3];b=f>=c;a=f<=d&1;if(d>2]=0;h=h+4|0}while((h|0)<(j|0));Zb(c,g);h=g;j=b[h>>2]|0;h=b[h+4>>2]|0;Ub(j,h,d);Vb(j,h,f);k=+jb(d,f+8|0);e[d>>3]=+e[a>>3];h=d+8|0;e[h>>3]=+e[a+16>>3];e[f>>3]=+e[a+8>>3];j=f+8|0;e[j>>3]=+e[a+24>>3];l=+jb(d,f);j=~~+A(+(l*l/+dd(+(+q(+((+e[h>>3]-+e[j>>3])/(+e[d>>3]-+e[f>>3])))),3.0)/(k*(k*2.59807621135)*.8)));S=i;return ((j|0)==0?1:j)|0}function za(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0.0;i=S;S=S+288|0;e=i+264|0;f=i+96|0;g=i;h=g;j=h+96|0;do{b[h>>2]=0;h=h+4|0}while((h|0)<(j|0));Zb(d,g);j=g;h=b[j>>2]|0;j=b[j+4>>2]|0;Ub(h,j,e);Vb(h,j,f);k=+jb(e,f+8|0);j=~~+A(+(+jb(a,c)/(k*2.0)));S=i;return ((j|0)==0?1:j)|0}function Aa(a,c,d,e){a=a|0;c=c|0;d=d|0;e=e|0;b[a>>2]=c;b[a+4>>2]=d;b[a+8>>2]=e;return}function Ba(a,c){a=a|0;c=c|0;var d=0,f=0,g=0,h=0,i=0.0,j=0.0,k=0.0,l=0.0,m=0,n=0,o=0.0;n=c+8|0;b[n>>2]=0;k=+e[a>>3];i=+q(+k);l=+e[a+8>>3];j=+q(+l)/.8660254037844386;i=i+j*.5;d=~~i;a=~~j;i=i-+(d|0);j=j-+(a|0);do if(i<.5)if(i<.3333333333333333){b[c>>2]=d;if(j<(i+1.0)*.5){b[c+4>>2]=a;break}else{a=a+1|0;b[c+4>>2]=a;break}}else{o=1.0-i;a=(!(j>2]=a;if(o<=j&j>2]=d;break}else{b[c>>2]=d;break}}else{if(!(i<.6666666666666666)){d=d+1|0;b[c>>2]=d;if(j>2]=a;break}else{a=a+1|0;b[c+4>>2]=a;break}}if(j<1.0-i){b[c+4>>2]=a;if(i*2.0+-1.0>2]=d;break}}else{a=a+1|0;b[c+4>>2]=a}d=d+1|0;b[c>>2]=d}while(0);do if(k<0.0)if(!(a&1)){m=(a|0)/2|0;m=Zc(d|0,((d|0)<0)<<31>>31|0,m|0,((m|0)<0)<<31>>31|0)|0;d=~~(+(d|0)-(+(m>>>0)+4294967296.0*+(G()|0))*2.0);b[c>>2]=d;break}else{m=(a+1|0)/2|0;m=Zc(d|0,((d|0)<0)<<31>>31|0,m|0,((m|0)<0)<<31>>31|0)|0;d=~~(+(d|0)-((+(m>>>0)+4294967296.0*+(G()|0))*2.0+1.0));b[c>>2]=d;break}while(0);m=c+4|0;if(l<0.0){d=d-((a<<1|1|0)/2|0)|0;b[c>>2]=d;a=0-a|0;b[m>>2]=a}f=a-d|0;if((d|0)<0){g=0-d|0;b[m>>2]=f;b[n>>2]=g;b[c>>2]=0;a=f;d=0}else g=0;if((a|0)<0){d=d-a|0;b[c>>2]=d;g=g-a|0;b[n>>2]=g;b[m>>2]=0;a=0}h=d-g|0;f=a-g|0;if((g|0)<0){b[c>>2]=h;b[m>>2]=f;b[n>>2]=0;a=f;d=h;g=0}f=(a|0)<(d|0)?a:d;f=(g|0)<(f|0)?g:f;if((f|0)<=0)return;b[c>>2]=d-f;b[m>>2]=a-f;b[n>>2]=g-f;return}function Ca(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0;c=b[a>>2]|0;h=a+4|0;d=b[h>>2]|0;if((c|0)<0){d=d-c|0;b[h>>2]=d;g=a+8|0;b[g>>2]=(b[g>>2]|0)-c;b[a>>2]=0;c=0}if((d|0)<0){c=c-d|0;b[a>>2]=c;g=a+8|0;f=(b[g>>2]|0)-d|0;b[g>>2]=f;b[h>>2]=0;d=0}else{f=a+8|0;g=f;f=b[f>>2]|0}if((f|0)<0){c=c-f|0;b[a>>2]=c;d=d-f|0;b[h>>2]=d;b[g>>2]=0;f=0}e=(d|0)<(c|0)?d:c;e=(f|0)<(e|0)?f:e;if((e|0)<=0)return;b[a>>2]=c-e;b[h>>2]=d-e;b[g>>2]=f-e;return}function Da(a,c){a=a|0;c=c|0;var d=0.0,f=0;f=b[a+8>>2]|0;d=+((b[a+4>>2]|0)-f|0);e[c>>3]=+((b[a>>2]|0)-f|0)-d*.5;e[c+8>>3]=d*.8660254037844386;return}function Ea(a,c,d){a=a|0;c=c|0;d=d|0;b[d>>2]=(b[c>>2]|0)+(b[a>>2]|0);b[d+4>>2]=(b[c+4>>2]|0)+(b[a+4>>2]|0);b[d+8>>2]=(b[c+8>>2]|0)+(b[a+8>>2]|0);return}function Fa(a,c,d){a=a|0;c=c|0;d=d|0;b[d>>2]=(b[a>>2]|0)-(b[c>>2]|0);b[d+4>>2]=(b[a+4>>2]|0)-(b[c+4>>2]|0);b[d+8>>2]=(b[a+8>>2]|0)-(b[c+8>>2]|0);return}function Ga(a,c){a=a|0;c=c|0;var d=0,e=0;d=B(b[a>>2]|0,c)|0;b[a>>2]=d;d=a+4|0;e=B(b[d>>2]|0,c)|0;b[d>>2]=e;a=a+8|0;c=B(b[a>>2]|0,c)|0;b[a>>2]=c;return}function Ha(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;h=b[a>>2]|0;i=(h|0)<0;e=(b[a+4>>2]|0)-(i?h:0)|0;g=(e|0)<0;f=(g?0-e|0:0)+((b[a+8>>2]|0)-(i?h:0))|0;d=(f|0)<0;a=d?0:f;c=(g?0:e)-(d?f:0)|0;f=(i?0:h)-(g?e:0)-(d?f:0)|0;d=(c|0)<(f|0)?c:f;d=(a|0)<(d|0)?a:d;e=(d|0)>0;a=a-(e?d:0)|0;c=c-(e?d:0)|0;a:do switch(f-(e?d:0)|0){case 0:switch(c|0){case 0:{i=(a|0)==0?0:(a|0)==1?1:7;return i|0}case 1:{i=(a|0)==0?2:(a|0)==1?3:7;return i|0}default:break a}case 1:switch(c|0){case 0:{i=(a|0)==0?4:(a|0)==1?5:7;return i|0}case 1:{if(!a)a=6;else break a;return a|0}default:break a}default:{}}while(0);i=7;return i|0}function Ia(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;h=a+8|0;d=b[h>>2]|0;c=(b[a>>2]|0)-d|0;i=a+4|0;d=(b[i>>2]|0)-d|0;e=Uc(+((c*3|0)-d|0)/7.0)|0;b[a>>2]=e;c=Uc(+((d<<1)+c|0)/7.0)|0;b[i>>2]=c;b[h>>2]=0;d=c-e|0;if((e|0)<0){g=0-e|0;b[i>>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0;d=0}g=e-c|0;f=d-c|0;if((c|0)<0){b[a>>2]=g;b[h>>2]=f;b[i>>2]=0;e=g;c=0}else f=d;d=(f|0)<(e|0)?f:e;d=(c|0)<(d|0)?c:d;if((d|0)<=0)return;b[a>>2]=e-d;b[h>>2]=f-d;b[i>>2]=c-d;return}function La(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;f=b[a>>2]|0;h=a+4|0;c=b[h>>2]|0;i=a+8|0;d=b[i>>2]|0;e=(c*3|0)+f|0;f=d+(f*3|0)|0;b[a>>2]=f;b[h>>2]=e;c=(d*3|0)+c|0;b[i>>2]=c;d=e-f|0;if((f|0)<0){c=c-f|0;b[h>>2]=d;b[i>>2]=c;b[a>>2]=0;f=0}else d=e;if((d|0)<0){f=f-d|0;b[a>>2]=f;c=c-d|0;b[i>>2]=c;b[h>>2]=0;d=0}g=f-c|0;e=d-c|0;if((c|0)<0){b[a>>2]=g;b[h>>2]=e;b[i>>2]=0;f=g;c=0}else e=d;d=(e|0)<(f|0)?e:f;d=(c|0)<(d|0)?c:d;if((d|0)<=0)return;b[a>>2]=f-d;b[h>>2]=e-d;b[i>>2]=c-d;return}function Ma(a,c){a=a|0;c=c|0;var d=0,e=0,f=0,g=0,h=0,i=0;if((c+-1|0)>>>0>=6)return;f=(b[15472+(c*12|0)>>2]|0)+(b[a>>2]|0)|0;b[a>>2]=f;i=a+4|0;e=(b[15472+(c*12|0)+4>>2]|0)+(b[i>>2]|0)|0;b[i>>2]=e;h=a+8|0;c=(b[15472+(c*12|0)+8>>2]|0)+(b[h>>2]|0)|0;b[h>>2]=c;d=e-f|0;if((f|0)<0){c=c-f|0;b[i>>2]=d;b[h>>2]=c;b[a>>2]=0;e=0}else{d=e;e=f}if((d|0)<0){e=e-d|0;b[a>>2]=e;c=c-d|0;b[h>>2]=c;b[i>>2]=0;d=0}g=e-c|0;f=d-c|0;if((c|0)<0){b[a>>2]=g;b[i>>2]=f;b[h>>2]=0;e=g;c=0}else f=d;d=(f|0)<(e|0)?f:e;d=(c|0)<(d|0)?c:d;if((d|0)<=0)return;b[a>>2]=e-d;b[i>>2]=f-d;b[h>>2]=c-d;return}function Na(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;f=b[a>>2]|0;h=a+4|0;c=b[h>>2]|0;i=a+8|0;d=b[i>>2]|0;e=c+f|0;f=d+f|0;b[a>>2]=f;b[h>>2]=e;c=d+c|0;b[i>>2]=c;d=e-f|0;if((f|0)<0){c=c-f|0;b[h>>2]=d;b[i>>2]=c;b[a>>2]=0;e=0}else{d=e;e=f}if((d|0)<0){e=e-d|0;b[a>>2]=e;c=c-d|0;b[i>>2]=c;b[h>>2]=0;d=0}g=e-c|0;f=d-c|0;if((c|0)<0){b[a>>2]=g;b[h>>2]=f;b[i>>2]=0;e=g;c=0}else f=d;d=(f|0)<(e|0)?f:e;d=(c|0)<(d|0)?c:d;if((d|0)<=0)return;b[a>>2]=e-d;b[h>>2]=f-d;b[i>>2]=c-d;return}function Oa(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;c=b[a>>2]|0;h=a+4|0;e=b[h>>2]|0;i=a+8|0;d=b[i>>2]|0;f=e+c|0;b[a>>2]=f;e=d+e|0;b[h>>2]=e;c=d+c|0;b[i>>2]=c;d=e-f|0;if((f|0)<0){c=c-f|0;b[h>>2]=d;b[i>>2]=c;b[a>>2]=0;e=0}else{d=e;e=f}if((d|0)<0){e=e-d|0;b[a>>2]=e;c=c-d|0;b[i>>2]=c;b[h>>2]=0;d=0}g=e-c|0;f=d-c|0;if((c|0)<0){b[a>>2]=g;b[h>>2]=f;b[i>>2]=0;e=g;c=0}else f=d;d=(f|0)<(e|0)?f:e;d=(c|0)<(d|0)?c:d;if((d|0)<=0)return;b[a>>2]=e-d;b[h>>2]=f-d;b[i>>2]=c-d;return}function Pa(a){a=a|0;switch(a|0){case 1:{a=5;break}case 5:{a=4;break}case 4:{a=6;break}case 6:{a=2;break}case 2:{a=3;break}case 3:{a=1;break}default:{}}return a|0}function Qa(a){a=a|0;switch(a|0){case 1:{a=3;break}case 3:{a=2;break}case 2:{a=6;break}case 6:{a=4;break}case 4:{a=5;break}case 5:{a=1;break}default:{}}return a|0}function Ra(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;c=b[a>>2]|0;h=a+4|0;d=b[h>>2]|0;i=a+8|0;e=b[i>>2]|0;f=d+(c<<1)|0;b[a>>2]=f;d=e+(d<<1)|0;b[h>>2]=d;c=(e<<1)+c|0;b[i>>2]=c;e=d-f|0;if((f|0)<0){c=c-f|0;b[h>>2]=e;b[i>>2]=c;b[a>>2]=0;d=e;e=0}else e=f;if((d|0)<0){e=e-d|0;b[a>>2]=e;c=c-d|0;b[i>>2]=c;b[h>>2]=0;d=0}g=e-c|0;f=d-c|0;if((c|0)<0){b[a>>2]=g;b[h>>2]=f;b[i>>2]=0;e=g;c=0}else f=d;d=(f|0)<(e|0)?f:e;d=(c|0)<(d|0)?c:d;if((d|0)<=0)return;b[a>>2]=e-d;b[h>>2]=f-d;b[i>>2]=c-d;return}function Sa(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;f=b[a>>2]|0;h=a+4|0;c=b[h>>2]|0;i=a+8|0;d=b[i>>2]|0;e=(c<<1)+f|0;f=d+(f<<1)|0;b[a>>2]=f;b[h>>2]=e;c=(d<<1)+c|0;b[i>>2]=c;d=e-f|0;if((f|0)<0){c=c-f|0;b[h>>2]=d;b[i>>2]=c;b[a>>2]=0;f=0}else d=e;if((d|0)<0){f=f-d|0;b[a>>2]=f;c=c-d|0;b[i>>2]=c;b[h>>2]=0;d=0}g=f-c|0;e=d-c|0;if((c|0)<0){b[a>>2]=g;b[h>>2]=e;b[i>>2]=0;f=g;c=0}else e=d;d=(e|0)<(f|0)?e:f;d=(c|0)<(d|0)?c:d;if((d|0)<=0)return;b[a>>2]=f-d;b[h>>2]=e-d;b[i>>2]=c-d;return}function Ta(a,c){a=a|0;c=c|0;var d=0,e=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2]=0-(a+d);return}function Xa(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;d=b[a>>2]|0;c=0-d|0;b[a>>2]=c;h=a+8|0;b[h>>2]=0;i=a+4|0;e=b[i>>2]|0;f=e+d|0;if((d|0)>0){b[i>>2]=f;b[h>>2]=d;b[a>>2]=0;c=0;e=f}else d=0;if((e|0)<0){g=c-e|0;b[a>>2]=g;d=d-e|0;b[h>>2]=d;b[i>>2]=0;f=g-d|0;c=0-d|0;if((d|0)<0){b[a>>2]=f;b[i>>2]=c;b[h>>2]=0;e=c;d=0}else{e=0;f=g}}else f=c;c=(e|0)<(f|0)?e:f;c=(d|0)<(c|0)?d:c;if((c|0)<=0)return;b[a>>2]=f-c;b[i>>2]=e-c;b[h>>2]=d-c;return}function Ya(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;d=S;S=S+16|0;e=d;Za(a,b,c,e);Ba(e,c+4|0);S=d;return}function Za(a,c,d,f){a=a|0;c=c|0;d=d|0;f=f|0;var g=0.0,h=0,i=0.0,j=0.0,k=0;k=S;S=S+32|0;h=k;Ic(a,h);b[d>>2]=0;g=+Hc(15888,h);i=+Hc(15912,h);if(i>2]=1;g=i}i=+Hc(15936,h);if(i>2]=2;g=i}i=+Hc(15960,h);if(i>2]=3;g=i}i=+Hc(15984,h);if(i>2]=4;g=i}i=+Hc(16008,h);if(i>2]=5;g=i}i=+Hc(16032,h);if(i>2]=6;g=i}i=+Hc(16056,h);if(i>2]=7;g=i}i=+Hc(16080,h);if(i>2]=8;g=i}i=+Hc(16104,h);if(i>2]=9;g=i}i=+Hc(16128,h);if(i>2]=10;g=i}i=+Hc(16152,h);if(i>2]=11;g=i}i=+Hc(16176,h);if(i>2]=12;g=i}i=+Hc(16200,h);if(i>2]=13;g=i}i=+Hc(16224,h);if(i>2]=14;g=i}i=+Hc(16248,h);if(i>2]=15;g=i}i=+Hc(16272,h);if(i>2]=16;g=i}i=+Hc(16296,h);if(i>2]=17;g=i}i=+Hc(16320,h);if(i>2]=18;g=i}i=+Hc(16344,h);if(i>2]=19;g=i}i=+w(+(1.0-g*.5));if(i<1.0e-16){b[f>>2]=0;b[f+4>>2]=0;b[f+8>>2]=0;b[f+12>>2]=0;S=k;return}d=b[d>>2]|0;g=+e[16368+(d*24|0)>>3];g=+gb(g-+gb(+lb(15568+(d<<4)|0,a)));if(!(Qb(c)|0))j=g;else j=+gb(g+-.3334731722518321);g=+v(+i)/.381966011250105;if((c|0)>0){h=0;do{g=g*2.6457513110645907;h=h+1|0}while((h|0)!=(c|0))}i=+t(+j)*g;e[f>>3]=i;j=+u(+j)*g;e[f+8>>3]=j;S=k;return}function _a(a,c,d,f,g){a=a|0;c=c|0;d=d|0;f=f|0;g=g|0;var h=0.0,i=0.0;h=+Ec(a);if(h<1.0e-16){c=15568+(c<<4)|0;b[g>>2]=b[c>>2];b[g+4>>2]=b[c+4>>2];b[g+8>>2]=b[c+8>>2];b[g+12>>2]=b[c+12>>2];return}i=+z(+(+e[a+8>>3]),+(+e[a>>3]));if((d|0)>0){a=0;do{h=h/2.6457513110645907;a=a+1|0}while((a|0)!=(d|0))}if(!f){h=+y(+(h*.381966011250105));if(Qb(d)|0)i=+gb(i+.3334731722518321)}else{h=h/3.0;d=(Qb(d)|0)==0;h=+y(+((d?h:h/2.6457513110645907)*.381966011250105))}mb(15568+(c<<4)|0,+gb(+e[16368+(c*24|0)>>3]-i),h,g);return}function $a(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0;e=S;S=S+16|0;f=e;Da(a+4|0,f);_a(f,b[a>>2]|0,c,0,d);S=e;return}function ab(a,c,d,f,g){a=a|0;c=c|0;d=d|0;f=f|0;g=g|0;var h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,I=0.0,J=0.0;G=S;S=S+272|0;h=G+256|0;u=G+240|0;D=G;E=G+224|0;F=G+208|0;v=G+176|0;w=G+160|0;x=G+192|0;y=G+144|0;z=G+128|0;A=G+112|0;B=G+96|0;C=G+80|0;b[h>>2]=c;b[u>>2]=b[a>>2];b[u+4>>2]=b[a+4>>2];b[u+8>>2]=b[a+8>>2];b[u+12>>2]=b[a+12>>2];bb(u,h,D);b[g>>2]=0;u=f+d+((f|0)==5&1)|0;if((u|0)<=(d|0)){S=G;return}k=b[h>>2]|0;l=E+4|0;m=v+4|0;n=d+5|0;o=16848+(k<<2)|0;p=16928+(k<<2)|0;q=z+8|0;r=A+8|0;s=B+8|0;t=F+4|0;j=d;a:while(1){i=D+(((j|0)%5|0)<<4)|0;b[F>>2]=b[i>>2];b[F+4>>2]=b[i+4>>2];b[F+8>>2]=b[i+8>>2];b[F+12>>2]=b[i+12>>2];do{}while((cb(F,k,0,1)|0)==2);if((j|0)>(d|0)&(Qb(c)|0)!=0){b[v>>2]=b[F>>2];b[v+4>>2]=b[F+4>>2];b[v+8>>2]=b[F+8>>2];b[v+12>>2]=b[F+12>>2];Da(l,w);f=b[v>>2]|0;h=b[17008+(f*80|0)+(b[E>>2]<<2)>>2]|0;b[v>>2]=b[18608+(f*80|0)+(h*20|0)>>2];i=b[18608+(f*80|0)+(h*20|0)+16>>2]|0;if((i|0)>0){a=0;do{Na(m);a=a+1|0}while((a|0)<(i|0))}i=18608+(f*80|0)+(h*20|0)+4|0;b[x>>2]=b[i>>2];b[x+4>>2]=b[i+4>>2];b[x+8>>2]=b[i+8>>2];Ga(x,(b[o>>2]|0)*3|0);Ea(m,x,m);Ca(m);Da(m,y);I=+(b[p>>2]|0);e[z>>3]=I*3.0;e[q>>3]=0.0;J=I*-1.5;e[A>>3]=J;e[r>>3]=I*2.598076211353316;e[B>>3]=J;e[s>>3]=I*-2.598076211353316;switch(b[17008+((b[v>>2]|0)*80|0)+(b[F>>2]<<2)>>2]|0){case 1:{a=A;f=z;break}case 3:{a=B;f=A;break}case 2:{a=z;f=B;break}default:{a=12;break a}}Fc(w,y,f,a,C);_a(C,b[v>>2]|0,k,1,g+8+(b[g>>2]<<4)|0);b[g>>2]=(b[g>>2]|0)+1}if((j|0)<(n|0)){Da(t,v);_a(v,b[F>>2]|0,k,1,g+8+(b[g>>2]<<4)|0);b[g>>2]=(b[g>>2]|0)+1};b[E>>2]=b[F>>2];b[E+4>>2]=b[F+4>>2];b[E+8>>2]=b[F+8>>2];b[E+12>>2]=b[F+12>>2];j=j+1|0;if((j|0)>=(u|0)){a=3;break}}if((a|0)==3){S=G;return}else if((a|0)==12)H(22474,22521,581,22531)}function bb(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0;j=S;S=S+128|0;e=j+64|0;f=j;g=e;h=20208;i=g+60|0;do{b[g>>2]=b[h>>2];g=g+4|0;h=h+4|0}while((g|0)<(i|0));g=f;h=20272;i=g+60|0;do{b[g>>2]=b[h>>2];g=g+4|0;h=h+4|0}while((g|0)<(i|0));i=(Qb(b[c>>2]|0)|0)==0;e=i?e:f;f=a+4|0;Ra(f);Sa(f);if(Qb(b[c>>2]|0)|0){La(f);b[c>>2]=(b[c>>2]|0)+1}b[d>>2]=b[a>>2];c=d+4|0;Ea(f,e,c);Ca(c);b[d+16>>2]=b[a>>2];c=d+20|0;Ea(f,e+12|0,c);Ca(c);b[d+32>>2]=b[a>>2];c=d+36|0;Ea(f,e+24|0,c);Ca(c);b[d+48>>2]=b[a>>2];c=d+52|0;Ea(f,e+36|0,c);Ca(c);b[d+64>>2]=b[a>>2];d=d+68|0;Ea(f,e+48|0,d);Ca(d);S=j;return}function cb(a,c,d,e){a=a|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;p=S;S=S+32|0;n=p+12|0;i=p;o=a+4|0;m=b[16928+(c<<2)>>2]|0;l=(e|0)!=0;m=l?m*3|0:m;f=b[o>>2]|0;k=a+8|0;h=b[k>>2]|0;if(l){g=a+12|0;e=b[g>>2]|0;f=h+f+e|0;if((f|0)==(m|0)){o=1;S=p;return o|0}else j=g}else{j=a+12|0;e=b[j>>2]|0;f=h+f+e|0}if((f|0)<=(m|0)){o=0;S=p;return o|0}do if((e|0)>0){e=b[a>>2]|0;if((h|0)>0){g=18608+(e*80|0)+60|0;e=a;break}e=18608+(e*80|0)+40|0;if(!d){g=e;e=a}else{Aa(n,m,0,0);Fa(o,n,i);Oa(i);Ea(i,n,o);g=e;e=a}}else{g=18608+((b[a>>2]|0)*80|0)+20|0;e=a}while(0);b[e>>2]=b[g>>2];f=g+16|0;if((b[f>>2]|0)>0){e=0;do{Na(o);e=e+1|0}while((e|0)<(b[f>>2]|0))}a=g+4|0;b[n>>2]=b[a>>2];b[n+4>>2]=b[a+4>>2];b[n+8>>2]=b[a+8>>2];c=b[16848+(c<<2)>>2]|0;Ga(n,l?c*3|0:c);Ea(o,n,o);Ca(o);if(l)e=((b[k>>2]|0)+(b[o>>2]|0)+(b[j>>2]|0)|0)==(m|0)?1:2;else e=2;o=e;S=p;return o|0}function db(a,b){a=a|0;b=b|0;var c=0;do c=cb(a,b,0,1)|0;while((c|0)==2);return c|0}function eb(a,c,d,f,g){a=a|0;c=c|0;d=d|0;f=f|0;g=g|0;var h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0.0,D=0.0;B=S;S=S+240|0;h=B+224|0;x=B+208|0;y=B;z=B+192|0;A=B+176|0;s=B+160|0;t=B+144|0;u=B+128|0;v=B+112|0;w=B+96|0;b[h>>2]=c;b[x>>2]=b[a>>2];b[x+4>>2]=b[a+4>>2];b[x+8>>2]=b[a+8>>2];b[x+12>>2]=b[a+12>>2];fb(x,h,y);b[g>>2]=0;r=f+d+((f|0)==6&1)|0;if((r|0)<=(d|0)){S=B;return}k=b[h>>2]|0;l=d+6|0;m=16928+(k<<2)|0;n=t+8|0;o=u+8|0;p=v+8|0;q=z+4|0;i=0;j=d;f=-1;a:while(1){h=(j|0)%6|0;a=y+(h<<4)|0;b[z>>2]=b[a>>2];b[z+4>>2]=b[a+4>>2];b[z+8>>2]=b[a+8>>2];b[z+12>>2]=b[a+12>>2];a=i;i=cb(z,k,0,1)|0;if((j|0)>(d|0)&(Qb(c)|0)!=0?((a|0)!=1?(b[z>>2]|0)!=(f|0):0):0){Da(y+(((h+5|0)%6|0)<<4)+4|0,A);Da(y+(h<<4)+4|0,s);C=+(b[m>>2]|0);e[t>>3]=C*3.0;e[n>>3]=0.0;D=C*-1.5;e[u>>3]=D;e[o>>3]=C*2.598076211353316;e[v>>3]=D;e[p>>3]=C*-2.598076211353316;h=b[x>>2]|0;switch(b[17008+(h*80|0)+(((f|0)==(h|0)?b[z>>2]|0:f)<<2)>>2]|0){case 1:{a=u;f=t;break}case 3:{a=v;f=u;break}case 2:{a=t;f=v;break}default:{a=8;break a}}Fc(A,s,f,a,w);if(!(Gc(A,w)|0)?!(Gc(s,w)|0):0){_a(w,b[x>>2]|0,k,1,g+8+(b[g>>2]<<4)|0);b[g>>2]=(b[g>>2]|0)+1}}if((j|0)<(l|0)){Da(q,A);_a(A,b[z>>2]|0,k,1,g+8+(b[g>>2]<<4)|0);b[g>>2]=(b[g>>2]|0)+1}j=j+1|0;if((j|0)>=(r|0)){a=3;break}else f=b[z>>2]|0}if((a|0)==3){S=B;return}else if((a|0)==8)H(22557,22521,746,22602)}function fb(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0;j=S;S=S+160|0;e=j+80|0;f=j;g=e;h=20336;i=g+72|0;do{b[g>>2]=b[h>>2];g=g+4|0;h=h+4|0}while((g|0)<(i|0));g=f;h=20416;i=g+72|0;do{b[g>>2]=b[h>>2];g=g+4|0;h=h+4|0}while((g|0)<(i|0));i=(Qb(b[c>>2]|0)|0)==0;e=i?e:f;f=a+4|0;Ra(f);Sa(f);if(Qb(b[c>>2]|0)|0){La(f);b[c>>2]=(b[c>>2]|0)+1}b[d>>2]=b[a>>2];c=d+4|0;Ea(f,e,c);Ca(c);b[d+16>>2]=b[a>>2];c=d+20|0;Ea(f,e+12|0,c);Ca(c);b[d+32>>2]=b[a>>2];c=d+36|0;Ea(f,e+24|0,c);Ca(c);b[d+48>>2]=b[a>>2];c=d+52|0;Ea(f,e+36|0,c);Ca(c);b[d+64>>2]=b[a>>2];c=d+68|0;Ea(f,e+48|0,c);Ca(c);b[d+80>>2]=b[a>>2];d=d+84|0;Ea(f,e+60|0,d);Ca(d);S=j;return}function gb(a){a=+a;var b=0.0;b=a<0.0?a+6.283185307179586:a;return +(!(a>=6.283185307179586)?b:b+-6.283185307179586)}function hb(a,b){a=a|0;b=b|0;if(!(+q(+(+e[a>>3]-+e[b>>3]))<1.7453292519943298e-11)){b=0;return b|0}b=+q(+(+e[a+8>>3]-+e[b+8>>3]))<1.7453292519943298e-11;return b|0}function ib(a,b){a=a|0;b=b|0;var c=0.0,d=0.0,f=0.0,g=0.0;f=+e[b>>3];d=+e[a>>3];g=+u(+((f-d)*.5));c=+u(+((+e[b+8>>3]-+e[a+8>>3])*.5));c=g*g+c*(+t(+f)*+t(+d)*c);return +(+z(+(+r(+c)),+(+r(+(1.0-c))))*2.0)}function jb(a,b){a=a|0;b=b|0;var c=0.0,d=0.0,f=0.0,g=0.0;f=+e[b>>3];d=+e[a>>3];g=+u(+((f-d)*.5));c=+u(+((+e[b+8>>3]-+e[a+8>>3])*.5));c=g*g+c*(+t(+f)*+t(+d)*c);return +(+z(+(+r(+c)),+(+r(+(1.0-c))))*2.0*6371.007180918475)}function kb(a,b){a=a|0;b=b|0;var c=0.0,d=0.0,f=0.0,g=0.0;f=+e[b>>3];d=+e[a>>3];g=+u(+((f-d)*.5));c=+u(+((+e[b+8>>3]-+e[a+8>>3])*.5));c=g*g+c*(+t(+f)*+t(+d)*c);return +(+z(+(+r(+c)),+(+r(+(1.0-c))))*2.0*6371.007180918475*1.0e3)}function lb(a,b){a=a|0;b=b|0;var c=0.0,d=0.0,f=0.0,g=0.0,h=0.0;g=+e[b>>3];d=+t(+g);f=+e[b+8>>3]-+e[a+8>>3];h=d*+u(+f);c=+e[a>>3];return +(+z(+h,+(+u(+g)*+t(+c)-+t(+f)*(d*+u(+c)))))}function mb(a,c,d,f){a=a|0;c=+c;d=+d;f=f|0;var g=0,h=0.0,i=0.0,j=0.0;if(d<1.0e-16){b[f>>2]=b[a>>2];b[f+4>>2]=b[a+4>>2];b[f+8>>2]=b[a+8>>2];b[f+12>>2]=b[a+12>>2];return}h=c<0.0?c+6.283185307179586:c;h=!(c>=6.283185307179586)?h:h+-6.283185307179586;do if(h<1.0e-16){c=+e[a>>3]+d;e[f>>3]=c;g=f}else{g=+q(+(h+-3.141592653589793))<1.0e-16;c=+e[a>>3];if(g){c=c-d;e[f>>3]=c;g=f;break}i=+t(+d);d=+u(+d);c=i*+u(+c)+ +t(+h)*(d*+t(+c));c=c>1.0?1.0:c;c=+x(+(c<-1.0?-1.0:c));e[f>>3]=c;if(+q(+(c+-1.5707963267948966))<1.0e-16){e[f>>3]=1.5707963267948966;e[f+8>>3]=0.0;return}if(+q(+(c+1.5707963267948966))<1.0e-16){e[f>>3]=-1.5707963267948966;e[f+8>>3]=0.0;return}j=+t(+c);h=d*+u(+h)/j;d=+e[a>>3];c=(i-+u(+c)*+u(+d))/+t(+d)/j;i=h>1.0?1.0:h;c=c>1.0?1.0:c;c=+e[a+8>>3]+ +z(+(i<-1.0?-1.0:i),+(c<-1.0?-1.0:c));if(c>3.141592653589793)do c=c+-6.283185307179586;while(c>3.141592653589793);if(c<-3.141592653589793)do c=c+6.283185307179586;while(c<-3.141592653589793);e[f+8>>3]=c;return}while(0);if(+q(+(c+-1.5707963267948966))<1.0e-16){e[g>>3]=1.5707963267948966;e[f+8>>3]=0.0;return}if(+q(+(c+1.5707963267948966))<1.0e-16){e[g>>3]=-1.5707963267948966;e[f+8>>3]=0.0;return}c=+e[a+8>>3];if(c>3.141592653589793)do c=c+-6.283185307179586;while(c>3.141592653589793);if(c<-3.141592653589793)do c=c+6.283185307179586;while(c<-3.141592653589793);e[f+8>>3]=c;return}function nb(a){a=a|0;return +(+e[20496+(a<<3)>>3])}function ob(a){a=a|0;return +(+e[20624+(a<<3)>>3])}function pb(a){a=a|0;return +(+e[20752+(a<<3)>>3])}function qb(a){a=a|0;return +(+e[20880+(a<<3)>>3])}function rb(a){a=a|0;var c=0;c=21008+(a<<3)|0;a=b[c>>2]|0;F(b[c+4>>2]|0);return a|0}function sb(a,b,c){a=a|0;b=b|0;c=c|0;var d=0.0,f=0.0,g=0.0,h=0.0,i=0.0,j=0.0,k=0.0,l=0.0,m=0.0,n=0.0;n=+e[b>>3];l=+e[a>>3];j=+u(+((n-l)*.5));g=+e[b+8>>3];k=+e[a+8>>3];h=+u(+((g-k)*.5));i=+t(+l);m=+t(+n);h=j*j+h*(m*i*h);h=+z(+(+r(+h)),+(+r(+(1.0-h))))*2.0;j=+e[c>>3];n=+u(+((j-n)*.5));d=+e[c+8>>3];g=+u(+((d-g)*.5));f=+t(+j);g=n*n+g*(m*f*g);g=+z(+(+r(+g)),+(+r(+(1.0-g))))*2.0;j=+u(+((l-j)*.5));d=+u(+((k-d)*.5));d=j*j+d*(i*f*d);d=+z(+(+r(+d)),+(+r(+(1.0-d))))*2.0;f=(h+g+d)*.5;return +(+y(+(+r(+(+v(+(f*.5))*+v(+((f-h)*.5))*+v(+((f-g)*.5))*+v(+((f-d)*.5))))))*4.0)}function tb(a,c){a=a|0;c=c|0;var d=0.0,e=0,f=0,g=0,h=0;g=S;S=S+192|0;e=g+168|0;f=g;Ub(a,c,e);Vb(a,c,f);c=b[f>>2]|0;if((c|0)<=0){d=0.0;S=g;return +d}d=+sb(f+8|0,f+8+(((c|0)!=1&1)<<4)|0,e)+0.0;if((c|0)==1){S=g;return +d}a=1;do{h=a;a=a+1|0;d=d+ +sb(f+8+(h<<4)|0,f+8+(((a|0)%(c|0)|0)<<4)|0,e)}while((a|0)<(c|0));S=g;return +d}function ub(a,c){a=a|0;c=c|0;var d=0.0,e=0,f=0,g=0,h=0;g=S;S=S+192|0;e=g+168|0;f=g;Ub(a,c,e);Vb(a,c,f);c=b[f>>2]|0;if((c|0)>0){d=+sb(f+8|0,f+8+(((c|0)!=1&1)<<4)|0,e)+0.0;if((c|0)!=1){a=1;do{h=a;a=a+1|0;d=d+ +sb(f+8+(h<<4)|0,f+8+(((a|0)%(c|0)|0)<<4)|0,e)}while((a|0)<(c|0))}}else d=0.0;S=g;return +(d*6371.007180918475*6371.007180918475)}function vb(a,c){a=a|0;c=c|0;var d=0.0,e=0,f=0,g=0,h=0;g=S;S=S+192|0;e=g+168|0;f=g;Ub(a,c,e);Vb(a,c,f);c=b[f>>2]|0;if((c|0)>0){d=+sb(f+8|0,f+8+(((c|0)!=1&1)<<4)|0,e)+0.0;if((c|0)!=1){a=1;do{h=a;a=a+1|0;d=d+ +sb(f+8+(h<<4)|0,f+8+(((a|0)%(c|0)|0)<<4)|0,e)}while((a|0)<(c|0))}}else d=0.0;S=g;return +(d*6371.007180918475*6371.007180918475*1.0e3*1.0e3)}function wb(a,c){a=a|0;c=c|0;var d=0.0,f=0.0,g=0.0,h=0,i=0,j=0.0,k=0.0,l=0.0;i=S;S=S+176|0;h=i;fc(a,c,h);a=b[h>>2]|0;if((a|0)<=1){g=0.0;S=i;return +g}c=a+-1|0;a=0;d=0.0;f=+e[h+8>>3];g=+e[h+16>>3];do{a=a+1|0;k=f;f=+e[h+8+(a<<4)>>3];l=+u(+((f-k)*.5));j=g;g=+e[h+8+(a<<4)+8>>3];j=+u(+((g-j)*.5));j=l*l+j*(+t(+f)*+t(+k)*j);d=d+ +z(+(+r(+j)),+(+r(+(1.0-j))))*2.0}while((a|0)<(c|0));S=i;return +d}function xb(a,c){a=a|0;c=c|0;var d=0.0,f=0.0,g=0.0,h=0,i=0,j=0.0,k=0.0,l=0.0;i=S;S=S+176|0;h=i;fc(a,c,h);a=b[h>>2]|0;if((a|0)<=1){g=0.0;S=i;return +g}c=a+-1|0;a=0;d=0.0;f=+e[h+8>>3];g=+e[h+16>>3];do{a=a+1|0;k=f;f=+e[h+8+(a<<4)>>3];l=+u(+((f-k)*.5));j=g;g=+e[h+8+(a<<4)+8>>3];j=+u(+((g-j)*.5));j=l*l+j*(+t(+k)*+t(+f)*j);d=d+ +z(+(+r(+j)),+(+r(+(1.0-j))))*2.0}while((a|0)!=(c|0));l=d*6371.007180918475;S=i;return +l}function yb(a,c){a=a|0;c=c|0;var d=0.0,f=0.0,g=0.0,h=0,i=0,j=0.0,k=0.0,l=0.0;i=S;S=S+176|0;h=i;fc(a,c,h);a=b[h>>2]|0;if((a|0)<=1){g=0.0;S=i;return +g}c=a+-1|0;a=0;d=0.0;f=+e[h+8>>3];g=+e[h+16>>3];do{a=a+1|0;k=f;f=+e[h+8+(a<<4)>>3];l=+u(+((f-k)*.5));j=g;g=+e[h+8+(a<<4)+8>>3];j=+u(+((g-j)*.5));j=l*l+j*(+t(+k)*+t(+f)*j);d=d+ +z(+(+r(+j)),+(+r(+(1.0-j))))*2.0}while((a|0)!=(c|0));l=d*6371.007180918475*1.0e3;S=i;return +l}function zb(a,b){a=a|0;b=b|0;b=bd(a|0,b|0,45)|0;G()|0;return b&127|0}function Ab(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0,g=0,h=0;if(!(0==0&(b&-16777216|0)==134217728)){b=0;return b|0}g=bd(a|0,b|0,45)|0;G()|0;g=g&127;if(g>>>0>121){b=0;return b|0}c=bd(a|0,b|0,52)|0;G()|0;c=c&15;do if(c|0){e=1;d=0;while(1){f=bd(a|0,b|0,(15-e|0)*3|0)|0;G()|0;f=f&7;if((f|0)!=0&(d^1))if((f|0)==1&(la(g)|0)!=0){h=0;d=13;break}else d=1;if((f|0)==7){h=0;d=13;break}if(e>>>0>>0)e=e+1|0;else{d=9;break}}if((d|0)==9){if((c|0)==15)h=1;else break;return h|0}else if((d|0)==13)return h|0}while(0);while(1){h=bd(a|0,b|0,(14-c|0)*3|0)|0;G()|0;if(!((h&7|0)==7&0==0)){h=0;d=13;break}if(c>>>0<14)c=c+1|0;else{h=1;d=13;break}}if((d|0)==13)return h|0;return 0}function Bb(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;d=bd(a|0,b|0,52)|0;G()|0;d=d&15;if((d|0)>=(c|0)){if((d|0)!=(c|0))if(c>>>0<=15){e=cd(c|0,0,52)|0;a=e|a;b=G()|0|b&-15728641;if((d|0)>(c|0))do{e=cd(7,0,(14-c|0)*3|0)|0;c=c+1|0;a=e|a;b=G()|0|b}while((c|0)<(d|0))}else{b=0;a=0}}else{b=0;a=0}F(b|0);return a|0}function Cb(a,b,c){a=a|0;b=b|0;c=c|0;a=bd(a|0,b|0,52)|0;G()|0;a=a&15;if(!((c|0)<16&(a|0)<=(c|0))){c=0;return c|0}c=sc(7,c-a|0)|0;return c|0}function Db(a,c,d,e){a=a|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0;h=bd(a|0,c|0,52)|0;G()|0;h=h&15;if(!((d|0)<16&(h|0)<=(d|0)))return;if((h|0)==(d|0)){d=e;b[d>>2]=a;b[d+4>>2]=c;return}j=sc(7,d-h|0)|0;k=(j|0)/7|0;i=bd(a|0,c|0,45)|0;G()|0;if(!(la(i&127)|0))g=0;else{a:do if(!h)f=0;else{g=1;while(1){f=bd(a|0,c|0,(15-g|0)*3|0)|0;G()|0;f=f&7;if(f|0)break a;if(g>>>0>>0)g=g+1|0;else{f=0;break}}}while(0);g=(f|0)==0}l=cd(h+1|0,0,52)|0;f=G()|0|c&-15728641;i=(14-h|0)*3|0;c=cd(7,0,i|0)|0;c=(l|a)&~c;h=f&~(G()|0);Db(c,h,d,e);f=e+(k<<3)|0;if(!g){l=cd(1,0,i|0)|0;Db(l|c,G()|0|h,d,f);l=f+(k<<3)|0;j=cd(2,0,i|0)|0;Db(j|c,G()|0|h,d,l);l=l+(k<<3)|0;j=cd(3,0,i|0)|0;Db(j|c,G()|0|h,d,l);l=l+(k<<3)|0;j=cd(4,0,i|0)|0;Db(j|c,G()|0|h,d,l);l=l+(k<<3)|0;j=cd(5,0,i|0)|0;Db(j|c,G()|0|h,d,l);j=cd(6,0,i|0)|0;Db(j|c,G()|0|h,d,l+(k<<3)|0);return}g=f+(k<<3)|0;if((j|0)>6){j=f+8|0;l=(g>>>0>j>>>0?g:j)+-1+(0-f)|0;gd(f|0,0,l+8&-8|0)|0;f=j+(l>>>3<<3)|0}l=cd(2,0,i|0)|0;Db(l|c,G()|0|h,d,f);l=f+(k<<3)|0;j=cd(3,0,i|0)|0;Db(j|c,G()|0|h,d,l);l=l+(k<<3)|0;j=cd(4,0,i|0)|0;Db(j|c,G()|0|h,d,l);l=l+(k<<3)|0;j=cd(5,0,i|0)|0;Db(j|c,G()|0|h,d,l);j=cd(6,0,i|0)|0;Db(j|c,G()|0|h,d,l+(k<<3)|0);return}function Eb(a,b){a=a|0;b=b|0;var c=0,d=0,e=0;e=bd(a|0,b|0,45)|0;G()|0;if(!(la(e&127)|0)){e=0;return e|0}e=bd(a|0,b|0,52)|0;G()|0;e=e&15;a:do if(!e)c=0;else{d=1;while(1){c=bd(a|0,b|0,(15-d|0)*3|0)|0;G()|0;c=c&7;if(c|0)break a;if(d>>>0>>0)d=d+1|0;else{c=0;break}}}while(0);e=(c|0)==0&1;return e|0}function Fb(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;d=bd(a|0,b|0,52)|0;G()|0;d=d&15;if((c|0)<16&(d|0)<=(c|0)){if((d|0)!=(c|0)){e=cd(c|0,0,52)|0;a=e|a;b=G()|0|b&-15728641;if((d|0)<(c|0))do{e=cd(7,0,(14-d|0)*3|0)|0;d=d+1|0;a=a&~e;b=b&~(G()|0)}while((d|0)<(c|0))}}else{b=0;a=0}F(b|0);return a|0}function Gb(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0;if(!d){y=0;return y|0}f=a;e=b[f>>2]|0;f=b[f+4>>2]|0;if(0==0&(f&15728640|0)==0){if((d|0)<=0){y=0;return y|0}y=c;b[y>>2]=e;b[y+4>>2]=f;if((d|0)==1){y=0;return y|0}e=1;do{w=a+(e<<3)|0;x=b[w+4>>2]|0;y=c+(e<<3)|0;b[y>>2]=b[w>>2];b[y+4>>2]=x;e=e+1|0}while((e|0)!=(d|0));e=0;return e|0}w=d<<3;x=Vc(w)|0;if(!x){y=-3;return y|0}fd(x|0,a|0,w|0)|0;v=Xc(d,8)|0;if(!v){Wc(x);y=-3;return y|0}e=d;a:while(1){h=x;l=b[h>>2]|0;h=b[h+4>>2]|0;t=bd(l|0,h|0,52)|0;G()|0;t=t&15;u=t+-1|0;s=(e|0)>0;b:do if(s){r=((e|0)<0)<<31>>31;p=cd(u|0,0,52)|0;q=G()|0;if(u>>>0>15){f=0;a=l;d=h;while(1){if(!((a|0)==0&(d|0)==0)){g=bd(a|0,d|0,52)|0;G()|0;g=g&15;i=(g|0)<(u|0);g=(g|0)==(u|0);k=i?0:g?a:0;a=i?0:g?d:0;d=ad(k|0,a|0,e|0,r|0)|0;G()|0;g=v+(d<<3)|0;i=g;j=b[i>>2]|0;i=b[i+4>>2]|0;if((j|0)==0&(i|0)==0)d=k;else{p=0;o=d;n=i;d=k;while(1){if((p|0)>(e|0)){y=41;break a}if((j|0)==(d|0)&(n&-117440513|0)==(a|0)){k=bd(j|0,n|0,56)|0;G()|0;k=k&7;m=k+1|0;q=bd(j|0,n|0,45)|0;G()|0;c:do if(!(la(q&127)|0))i=7;else{j=bd(j|0,n|0,52)|0;G()|0;j=j&15;if(!j){i=6;break}i=1;while(1){q=cd(7,0,(15-i|0)*3|0)|0;if(!((q&d|0)==0&((G()|0)&a|0)==0)){i=7;break c}if(i>>>0>>0)i=i+1|0;else{i=6;break}}}while(0);if((k+2|0)>>>0>i>>>0){y=51;break a}q=cd(m|0,0,56)|0;a=G()|0|a&-117440513;i=g;b[i>>2]=0;b[i+4>>2]=0;i=o;d=q|d}else i=(o+1|0)%(e|0)|0;g=v+(i<<3)|0;n=g;j=b[n>>2]|0;n=b[n+4>>2]|0;if((j|0)==0&(n|0)==0)break;else{p=p+1|0;o=i}}}q=g;b[q>>2]=d;b[q+4>>2]=a}f=f+1|0;if((f|0)>=(e|0))break b;d=x+(f<<3)|0;a=b[d>>2]|0;d=b[d+4>>2]|0}}f=0;a=l;d=h;while(1){if(!((a|0)==0&(d|0)==0)){i=bd(a|0,d|0,52)|0;G()|0;i=i&15;if((i|0)>=(u|0)){if((i|0)!=(u|0)){a=a|p;d=d&-15728641|q;if(i>>>0>=t>>>0){g=u;do{o=cd(7,0,(14-g|0)*3|0)|0;g=g+1|0;a=o|a;d=G()|0|d}while(g>>>0>>0)}}}else{a=0;d=0}i=ad(a|0,d|0,e|0,r|0)|0;G()|0;g=v+(i<<3)|0;j=g;k=b[j>>2]|0;j=b[j+4>>2]|0;if(!((k|0)==0&(j|0)==0)){o=0;while(1){if((o|0)>(e|0)){y=41;break a}if((k|0)==(a|0)&(j&-117440513|0)==(d|0)){m=bd(k|0,j|0,56)|0;G()|0;m=m&7;n=m+1|0;z=bd(k|0,j|0,45)|0;G()|0;d:do if(!(la(z&127)|0))j=7;else{k=bd(k|0,j|0,52)|0;G()|0;k=k&15;if(!k){j=6;break}j=1;while(1){z=cd(7,0,(15-j|0)*3|0)|0;if(!((z&a|0)==0&((G()|0)&d|0)==0)){j=7;break d}if(j>>>0>>0)j=j+1|0;else{j=6;break}}}while(0);if((m+2|0)>>>0>j>>>0){y=51;break a}z=cd(n|0,0,56)|0;d=G()|0|d&-117440513;n=g;b[n>>2]=0;b[n+4>>2]=0;a=z|a}else i=(i+1|0)%(e|0)|0;g=v+(i<<3)|0;j=g;k=b[j>>2]|0;j=b[j+4>>2]|0;if((k|0)==0&(j|0)==0)break;else o=o+1|0}}z=g;b[z>>2]=a;b[z+4>>2]=d}f=f+1|0;if((f|0)>=(e|0))break b;d=x+(f<<3)|0;a=b[d>>2]|0;d=b[d+4>>2]|0}}while(0);if((e+5|0)>>>0<11){y=99;break}q=Xc((e|0)/6|0,8)|0;if(!q){y=58;break}e:do if(s){o=0;n=0;do{i=v+(o<<3)|0;a=i;f=b[a>>2]|0;a=b[a+4>>2]|0;if(!((f|0)==0&(a|0)==0)){j=bd(f|0,a|0,56)|0;G()|0;j=j&7;d=j+1|0;k=a&-117440513;z=bd(f|0,a|0,45)|0;G()|0;f:do if(la(z&127)|0){m=bd(f|0,a|0,52)|0;G()|0;m=m&15;if(m|0){g=1;while(1){z=cd(7,0,(15-g|0)*3|0)|0;if(!((f&z|0)==0&(k&(G()|0)|0)==0))break f;if(g>>>0>>0)g=g+1|0;else break}}a=cd(d|0,0,56)|0;f=a|f;a=G()|0|k;d=i;b[d>>2]=f;b[d+4>>2]=a;d=j+2|0}while(0);if((d|0)==7){z=q+(n<<3)|0;b[z>>2]=f;b[z+4>>2]=a&-117440513;n=n+1|0}}o=o+1|0}while((o|0)!=(e|0));if(s){p=((e|0)<0)<<31>>31;m=cd(u|0,0,52)|0;o=G()|0;if(u>>>0>15){a=0;f=0;while(1){do if(!((l|0)==0&(h|0)==0)){j=bd(l|0,h|0,52)|0;G()|0;j=j&15;g=(j|0)<(u|0);j=(j|0)==(u|0);i=g?0:j?l:0;j=g?0:j?h:0;g=ad(i|0,j|0,e|0,p|0)|0;G()|0;d=0;while(1){if((d|0)>(e|0)){y=98;break a}z=v+(g<<3)|0;k=b[z+4>>2]|0;if((k&-117440513|0)==(j|0)?(b[z>>2]|0)==(i|0):0){y=70;break}g=(g+1|0)%(e|0)|0;z=v+(g<<3)|0;if((b[z>>2]|0)==(i|0)?(b[z+4>>2]|0)==(j|0):0)break;else d=d+1|0}if((y|0)==70?(y=0,0==0&(k&117440512|0)==100663296):0)break;z=c+(f<<3)|0;b[z>>2]=l;b[z+4>>2]=h;f=f+1|0}while(0);a=a+1|0;if((a|0)>=(e|0)){e=n;break e}h=x+(a<<3)|0;l=b[h>>2]|0;h=b[h+4>>2]|0}}a=0;f=0;while(1){do if(!((l|0)==0&(h|0)==0)){j=bd(l|0,h|0,52)|0;G()|0;j=j&15;if((j|0)>=(u|0))if((j|0)!=(u|0)){d=l|m;g=h&-15728641|o;if(j>>>0>>0)j=g;else{i=u;do{z=cd(7,0,(14-i|0)*3|0)|0;i=i+1|0;d=z|d;g=G()|0|g}while(i>>>0>>0);j=g}}else{d=l;j=h}else{d=0;j=0}i=ad(d|0,j|0,e|0,p|0)|0;G()|0;g=0;while(1){if((g|0)>(e|0)){y=98;break a}z=v+(i<<3)|0;k=b[z+4>>2]|0;if((k&-117440513|0)==(j|0)?(b[z>>2]|0)==(d|0):0){y=93;break}i=(i+1|0)%(e|0)|0;z=v+(i<<3)|0;if((b[z>>2]|0)==(d|0)?(b[z+4>>2]|0)==(j|0):0)break;else g=g+1|0}if((y|0)==93?(y=0,0==0&(k&117440512|0)==100663296):0)break;z=c+(f<<3)|0;b[z>>2]=l;b[z+4>>2]=h;f=f+1|0}while(0);a=a+1|0;if((a|0)>=(e|0)){e=n;break e}h=x+(a<<3)|0;l=b[h>>2]|0;h=b[h+4>>2]|0}}else{f=0;e=n}}else{f=0;e=0}while(0);gd(v|0,0,w|0)|0;fd(x|0,q|0,e<<3|0)|0;Wc(q);if(!e)break;else c=c+(f<<3)|0}if((y|0)==41){Wc(x);Wc(v);z=-1;return z|0}else if((y|0)==51){Wc(x);Wc(v);z=-2;return z|0}else if((y|0)==58){Wc(x);Wc(v);z=-3;return z|0}else if((y|0)==98){Wc(q);Wc(x);Wc(v);z=-1;return z|0}else if((y|0)==99)fd(c|0,x|0,e<<3|0)|0;Wc(x);Wc(v);z=0;return z|0}function Hb(a,c,d,e,f){a=a|0;c=c|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0;if((c|0)<=0){f=0;return f|0}if((f|0)>=16){g=0;while(1){l=a+(g<<3)|0;if(!((b[l>>2]|0)==0&(b[l+4>>2]|0)==0)){g=14;break}g=g+1|0;if((g|0)>=(c|0)){h=0;g=16;break}}if((g|0)==14)return ((e|0)>0?-2:-1)|0;else if((g|0)==16)return h|0}g=0;l=0;a:while(1){k=a+(l<<3)|0;i=k;h=b[i>>2]|0;i=b[i+4>>2]|0;do if(!((h|0)==0&(i|0)==0)){if((g|0)>=(e|0)){h=-1;g=16;break a}j=bd(h|0,i|0,52)|0;G()|0;j=j&15;if((j|0)>(f|0)){h=-2;g=16;break a}if((j|0)==(f|0)){k=d+(g<<3)|0;b[k>>2]=h;b[k+4>>2]=i;g=g+1|0;break}h=(sc(7,f-j|0)|0)+g|0;if((h|0)>(e|0)){h=-1;g=16;break a}Db(b[k>>2]|0,b[k+4>>2]|0,f,d+(g<<3)|0);g=h}while(0);l=l+1|0;if((l|0)>=(c|0)){h=0;g=16;break}}if((g|0)==16)return h|0;return 0}function Ib(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0;if((c|0)<=0){d=0;return d|0}if((d|0)>=16){e=0;while(1){h=a+(e<<3)|0;if(!((b[h>>2]|0)==0&(b[h+4>>2]|0)==0)){e=-1;f=13;break}e=e+1|0;if((e|0)>=(c|0)){e=0;f=13;break}}if((f|0)==13)return e|0}e=0;h=0;a:while(1){f=a+(h<<3)|0;g=b[f>>2]|0;f=b[f+4>>2]|0;do if(!((g|0)==0&(f|0)==0)){f=bd(g|0,f|0,52)|0;G()|0;f=f&15;if((f|0)>(d|0)){e=-1;f=13;break a}if((f|0)==(d|0)){e=e+1|0;break}else{e=(sc(7,d-f|0)|0)+e|0;break}}while(0);h=h+1|0;if((h|0)>=(c|0)){f=13;break}}if((f|0)==13)return e|0;return 0}function Jb(a,b){a=a|0;b=b|0;b=bd(a|0,b|0,52)|0;G()|0;return b&1|0}function Kb(a,b){a=a|0;b=b|0;var c=0,d=0,e=0;e=bd(a|0,b|0,52)|0;G()|0;e=e&15;if(!e){e=0;return e|0}d=1;while(1){c=bd(a|0,b|0,(15-d|0)*3|0)|0;G()|0;c=c&7;if(c|0){d=5;break}if(d>>>0>>0)d=d+1|0;else{c=0;d=5;break}}if((d|0)==5)return c|0;return 0}function Lb(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;i=bd(a|0,b|0,52)|0;G()|0;i=i&15;if(!i){h=b;i=a;F(h|0);return i|0}h=1;c=0;while(1){f=(15-h|0)*3|0;d=cd(7,0,f|0)|0;e=G()|0;g=bd(a|0,b|0,f|0)|0;G()|0;f=cd(Pa(g&7)|0,0,f|0)|0;g=G()|0;a=f|a&~d;b=g|b&~e;a:do if(!c)if(!((f&d|0)==0&(g&e|0)==0)){d=bd(a|0,b|0,52)|0;G()|0;d=d&15;if(!d)c=1;else{c=1;b:while(1){g=bd(a|0,b|0,(15-c|0)*3|0)|0;G()|0;switch(g&7){case 1:break b;case 0:break;default:{c=1;break a}}if(c>>>0>>0)c=c+1|0;else{c=1;break a}}c=1;while(1){g=(15-c|0)*3|0;e=bd(a|0,b|0,g|0)|0;G()|0;f=cd(7,0,g|0)|0;b=b&~(G()|0);g=cd(Pa(e&7)|0,0,g|0)|0;a=a&~f|g;b=b|(G()|0);if(c>>>0>>0)c=c+1|0;else{c=1;break}}}}else c=0;while(0);if(h>>>0>>0)h=h+1|0;else break}F(b|0);return a|0}function Mb(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0,g=0;d=bd(a|0,b|0,52)|0;G()|0;d=d&15;if(!d){c=b;d=a;F(c|0);return d|0}c=1;while(1){f=(15-c|0)*3|0;g=bd(a|0,b|0,f|0)|0;G()|0;e=cd(7,0,f|0)|0;b=b&~(G()|0);f=cd(Pa(g&7)|0,0,f|0)|0;a=f|a&~e;b=G()|0|b;if(c>>>0>>0)c=c+1|0;else break}F(b|0);return a|0}function Nb(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0;i=bd(a|0,b|0,52)|0;G()|0;i=i&15;if(!i){h=b;i=a;F(h|0);return i|0}h=1;c=0;while(1){f=(15-h|0)*3|0;d=cd(7,0,f|0)|0;e=G()|0;g=bd(a|0,b|0,f|0)|0;G()|0;f=cd(Qa(g&7)|0,0,f|0)|0;g=G()|0;a=f|a&~d;b=g|b&~e;a:do if(!c)if(!((f&d|0)==0&(g&e|0)==0)){d=bd(a|0,b|0,52)|0;G()|0;d=d&15;if(!d)c=1;else{c=1;b:while(1){g=bd(a|0,b|0,(15-c|0)*3|0)|0;G()|0;switch(g&7){case 1:break b;case 0:break;default:{c=1;break a}}if(c>>>0>>0)c=c+1|0;else{c=1;break a}}c=1;while(1){e=(15-c|0)*3|0;f=cd(7,0,e|0)|0;g=b&~(G()|0);b=bd(a|0,b|0,e|0)|0;G()|0;b=cd(Qa(b&7)|0,0,e|0)|0;a=a&~f|b;b=g|(G()|0);if(c>>>0>>0)c=c+1|0;else{c=1;break}}}}else c=0;while(0);if(h>>>0>>0)h=h+1|0;else break}F(b|0);return a|0}function Ob(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0,g=0;d=bd(a|0,b|0,52)|0;G()|0;d=d&15;if(!d){c=b;d=a;F(c|0);return d|0}c=1;while(1){g=(15-c|0)*3|0;f=cd(7,0,g|0)|0;e=b&~(G()|0);b=bd(a|0,b|0,g|0)|0;G()|0;b=cd(Qa(b&7)|0,0,g|0)|0;a=b|a&~f;b=G()|0|e;if(c>>>0>>0)c=c+1|0;else break}F(b|0);return a|0}function Pb(a,c){a=a|0;c=c|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0;j=S;S=S+64|0;i=j+40|0;e=j+24|0;f=j+12|0;g=j;cd(c|0,0,52)|0;d=G()|0|134225919;if(!c){if((b[a+4>>2]|0)>2){h=0;i=0;F(h|0);S=j;return i|0}if((b[a+8>>2]|0)>2){h=0;i=0;F(h|0);S=j;return i|0}if((b[a+12>>2]|0)>2){h=0;i=0;F(h|0);S=j;return i|0}cd(na(a)|0,0,45)|0;h=G()|0|d;i=-1;F(h|0);S=j;return i|0};b[i>>2]=b[a>>2];b[i+4>>2]=b[a+4>>2];b[i+8>>2]=b[a+8>>2];b[i+12>>2]=b[a+12>>2];h=i+4|0;if((c|0)>0){a=-1;while(1){b[e>>2]=b[h>>2];b[e+4>>2]=b[h+4>>2];b[e+8>>2]=b[h+8>>2];if(!(c&1)){Ja(h);b[f>>2]=b[h>>2];b[f+4>>2]=b[h+4>>2];b[f+8>>2]=b[h+8>>2];La(f)}else{Ia(h);b[f>>2]=b[h>>2];b[f+4>>2]=b[h+4>>2];b[f+8>>2]=b[h+8>>2];Ka(f)}Fa(e,f,g);Ca(g);l=(15-c|0)*3|0;k=cd(7,0,l|0)|0;d=d&~(G()|0);l=cd(Ha(g)|0,0,l|0)|0;a=l|a&~k;d=G()|0|d;if((c|0)>1)c=c+-1|0;else break}}else a=-1;a:do if(((b[h>>2]|0)<=2?(b[i+8>>2]|0)<=2:0)?(b[i+12>>2]|0)<=2:0){e=na(i)|0;c=cd(e|0,0,45)|0;c=c|a;a=G()|0|d&-1040385;g=oa(i)|0;if(!(la(e)|0)){if((g|0)<=0)break;f=0;while(1){e=bd(c|0,a|0,52)|0;G()|0;e=e&15;if(e){d=1;while(1){l=(15-d|0)*3|0;i=bd(c|0,a|0,l|0)|0;G()|0;k=cd(7,0,l|0)|0;a=a&~(G()|0);l=cd(Pa(i&7)|0,0,l|0)|0;c=c&~k|l;a=a|(G()|0);if(d>>>0>>0)d=d+1|0;else break}}f=f+1|0;if((f|0)==(g|0))break a}}f=bd(c|0,a|0,52)|0;G()|0;f=f&15;b:do if(f){d=1;c:while(1){l=bd(c|0,a|0,(15-d|0)*3|0)|0;G()|0;switch(l&7){case 1:break c;case 0:break;default:break b}if(d>>>0>>0)d=d+1|0;else break b}if(ra(e,b[i>>2]|0)|0){d=1;while(1){i=(15-d|0)*3|0;k=cd(7,0,i|0)|0;l=a&~(G()|0);a=bd(c|0,a|0,i|0)|0;G()|0;a=cd(Qa(a&7)|0,0,i|0)|0;c=c&~k|a;a=l|(G()|0);if(d>>>0>>0)d=d+1|0;else break}}else{d=1;while(1){l=(15-d|0)*3|0;i=bd(c|0,a|0,l|0)|0;G()|0;k=cd(7,0,l|0)|0;a=a&~(G()|0);l=cd(Pa(i&7)|0,0,l|0)|0;c=c&~k|l;a=a|(G()|0);if(d>>>0>>0)d=d+1|0;else break}}}while(0);if((g|0)>0){d=0;do{c=Lb(c,a)|0;a=G()|0;d=d+1|0}while((d|0)!=(g|0))}}else{c=0;a=0}while(0);k=a;l=c;F(k|0);S=j;return l|0}function Qb(a){a=a|0;return (a|0)%2|0|0}function Rb(a,c){a=a|0;c=c|0;var d=0,e=0;e=S;S=S+16|0;d=e;if((c>>>0<=15?!(0==0?(b[a+4>>2]&2146435072|0)==2146435072:0):0)?!(0==0?(b[a+8+4>>2]&2146435072|0)==2146435072:0):0){Ya(a,c,d);c=Pb(d,c)|0;a=G()|0}else{a=0;c=0}F(a|0);S=e;return c|0}function Sb(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0;f=d+4|0;g=bd(a|0,c|0,52)|0;G()|0;g=g&15;h=bd(a|0,c|0,45)|0;G()|0;e=(g|0)==0;if(!(la(h&127)|0)){if(e){h=0;return h|0}if((b[f>>2]|0)==0?(b[d+8>>2]|0)==0:0)e=(b[d+12>>2]|0)!=0&1;else e=1}else if(e){h=1;return h|0}else e=1;d=1;while(1){if(!(d&1))La(f);else Ka(f);h=bd(a|0,c|0,(15-d|0)*3|0)|0;G()|0;Ma(f,h&7);if(d>>>0>>0)d=d+1|0;else break}return e|0}function Tb(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0;l=S;S=S+16|0;j=l;k=bd(a|0,c|0,45)|0;G()|0;k=k&127;a:do if((la(k)|0)!=0?(g=bd(a|0,c|0,52)|0,G()|0,g=g&15,(g|0)!=0):0){e=1;b:while(1){i=bd(a|0,c|0,(15-e|0)*3|0)|0;G()|0;switch(i&7){case 5:break b;case 0:break;default:{e=c;break a}}if(e>>>0>>0)e=e+1|0;else{e=c;break a}}f=1;e=c;while(1){c=(15-f|0)*3|0;h=cd(7,0,c|0)|0;i=e&~(G()|0);e=bd(a|0,e|0,c|0)|0;G()|0;e=cd(Qa(e&7)|0,0,c|0)|0;a=a&~h|e;e=i|(G()|0);if(f>>>0>>0)f=f+1|0;else break}}else e=c;while(0);i=7728+(k*28|0)|0;b[d>>2]=b[i>>2];b[d+4>>2]=b[i+4>>2];b[d+8>>2]=b[i+8>>2];b[d+12>>2]=b[i+12>>2];if(!(Sb(a,e,d)|0)){S=l;return}h=d+4|0;b[j>>2]=b[h>>2];b[j+4>>2]=b[h+4>>2];b[j+8>>2]=b[h+8>>2];g=bd(a|0,e|0,52)|0;G()|0;i=g&15;if(!(g&1))g=i;else{La(h);g=i+1|0}if(!(la(k)|0))e=0;else{c:do if(!i)e=0;else{c=1;while(1){f=bd(a|0,e|0,(15-c|0)*3|0)|0;G()|0;f=f&7;if(f|0){e=f;break c}if(c>>>0>>0)c=c+1|0;else{e=0;break}}}while(0);e=(e|0)==4&1}if(!(cb(d,g,e,0)|0)){if((g|0)!=(i|0)){b[h>>2]=b[j>>2];b[h+4>>2]=b[j+4>>2];b[h+8>>2]=b[j+8>>2]}}else{if(la(k)|0)do{}while((cb(d,g,0,0)|0)!=0);if((g|0)!=(i|0))Ja(h)}S=l;return}function Ub(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;d=S;S=S+16|0;e=d;Tb(a,b,e);b=bd(a|0,b|0,52)|0;G()|0;$a(e,b&15,c);S=d;return}function Vb(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0,f=0,g=0,h=0;g=S;S=S+16|0;f=g;Tb(a,b,f);d=bd(a|0,b|0,45)|0;G()|0;d=(la(d&127)|0)==0;e=bd(a|0,b|0,52)|0;G()|0;e=e&15;a:do if(!d){if(e|0){d=1;while(1){h=cd(7,0,(15-d|0)*3|0)|0;if(!((h&a|0)==0&((G()|0)&b|0)==0))break a;if(d>>>0>>0)d=d+1|0;else break}}ab(f,e,0,5,c);S=g;return}while(0);eb(f,e,0,6,c);S=g;return}function Wb(a,b){a=a|0;b=b|0;var c=0,d=0,e=0;d=bd(a|0,b|0,45)|0;G()|0;if(!(la(d&127)|0)){d=2;return d|0}d=bd(a|0,b|0,52)|0;G()|0;d=d&15;if(!d){d=5;return d|0}c=1;while(1){e=cd(7,0,(15-c|0)*3|0)|0;if(!((e&a|0)==0&((G()|0)&b|0)==0)){c=2;a=6;break}if(c>>>0>>0)c=c+1|0;else{c=5;a=6;break}}if((a|0)==6)return c|0;return 0}function Xb(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0;m=S;S=S+128|0;k=m+112|0;g=m+96|0;l=m;f=bd(a|0,c|0,52)|0;G()|0;i=f&15;b[k>>2]=i;h=bd(a|0,c|0,45)|0;G()|0;h=h&127;a:do if(la(h)|0){if(i|0){e=1;while(1){j=cd(7,0,(15-e|0)*3|0)|0;if(!((j&a|0)==0&((G()|0)&c|0)==0)){f=0;break a}if(e>>>0>>0)e=e+1|0;else break}}if(!(f&1)){j=cd(i+1|0,0,52)|0;l=G()|0|c&-15728641;k=cd(7,0,(14-i|0)*3|0)|0;Xb((j|a)&~k,l&~(G()|0),d);S=m;return}else f=1}else f=0;while(0);Tb(a,c,g);if(f){bb(g,k,l);j=5}else{fb(g,k,l);j=6}b:do if(la(h)|0)if(!i)e=20;else{e=1;while(1){h=cd(7,0,(15-e|0)*3|0)|0;if(!((h&a|0)==0&((G()|0)&c|0)==0)){e=8;break b}if(e>>>0>>0)e=e+1|0;else{e=20;break}}}else e=8;while(0);gd(d|0,-1,e|0)|0;if(f){f=0;do{g=l+(f<<4)|0;db(g,b[k>>2]|0)|0;g=b[g>>2]|0;e=0;while(1){h=d+(e<<2)|0;i=b[h>>2]|0;if((i|0)==-1|(i|0)==(g|0))break;else e=e+1|0}b[h>>2]=g;f=f+1|0}while((f|0)!=(j|0))}else{f=0;do{g=l+(f<<4)|0;cb(g,b[k>>2]|0,0,1)|0;g=b[g>>2]|0;e=0;while(1){h=d+(e<<2)|0;i=b[h>>2]|0;if((i|0)==-1|(i|0)==(g|0))break;else e=e+1|0}b[h>>2]=g;f=f+1|0}while((f|0)!=(j|0))}S=m;return}function Yb(){return 12}function Zb(a,c){a=a|0;c=c|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0;cd(a|0,0,52)|0;i=G()|0|134225919;if((a|0)<1){e=0;d=0;do{if(la(e)|0){cd(e|0,0,45)|0;h=i|(G()|0);a=c+(d<<3)|0;b[a>>2]=-1;b[a+4>>2]=h;d=d+1|0}e=e+1|0}while((e|0)!=122);return}h=0;d=0;do{if(la(h)|0){cd(h|0,0,45)|0;e=1;f=-1;g=i|(G()|0);while(1){j=cd(7,0,(15-e|0)*3|0)|0;f=f&~j;g=g&~(G()|0);if((e|0)==(a|0))break;else e=e+1|0}j=c+(d<<3)|0;b[j>>2]=f;b[j+4>>2]=g;d=d+1|0}h=h+1|0}while((h|0)!=122);return}function _b(a,c,d,e){a=a|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0;i=S;S=S+64|0;h=i;if((a|0)==(d|0)&(c|0)==(e|0)|(0!=0|(c&2013265920|0)!=134217728|(0!=0|(e&2013265920|0)!=134217728))){h=0;S=i;return h|0}f=bd(a|0,c|0,52)|0;G()|0;f=f&15;g=bd(d|0,e|0,52)|0;G()|0;if((f|0)!=(g&15|0)){h=0;S=i;return h|0}g=f+-1|0;if(f>>>0>1?(k=Bb(a,c,g)|0,j=G()|0,g=Bb(d,e,g)|0,(k|0)==(g|0)&(j|0)==(G()|0)):0){g=(f^15)*3|0;f=bd(a|0,c|0,g|0)|0;G()|0;f=f&7;g=bd(d|0,e|0,g|0)|0;G()|0;g=g&7;if((f|0)==0|(g|0)==0){k=1;S=i;return k|0}if((b[21136+(f<<2)>>2]|0)==(g|0)){k=1;S=i;return k|0}if((b[21168+(f<<2)>>2]|0)==(g|0)){k=1;S=i;return k|0}}f=h;g=f+56|0;do{b[f>>2]=0;f=f+4|0}while((f|0)<(g|0));$(a,c,1,h);k=h;if(((((!((b[k>>2]|0)==(d|0)?(b[k+4>>2]|0)==(e|0):0)?(k=h+8|0,!((b[k>>2]|0)==(d|0)?(b[k+4>>2]|0)==(e|0):0)):0)?(k=h+16|0,!((b[k>>2]|0)==(d|0)?(b[k+4>>2]|0)==(e|0):0)):0)?(k=h+24|0,!((b[k>>2]|0)==(d|0)?(b[k+4>>2]|0)==(e|0):0)):0)?(k=h+32|0,!((b[k>>2]|0)==(d|0)?(b[k+4>>2]|0)==(e|0):0)):0)?(k=h+40|0,!((b[k>>2]|0)==(d|0)?(b[k+4>>2]|0)==(e|0):0)):0){f=h+48|0;f=((b[f>>2]|0)==(d|0)?(b[f+4>>2]|0)==(e|0):0)&1}else f=1;k=f;S=i;return k|0}function $b(a,c,d,e){a=a|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0;k=S;S=S+16|0;h=k;if(!(_b(a,c,d,e)|0)){i=0;j=0;F(i|0);S=k;return j|0}i=c&-2130706433;f=(Eb(a,c)|0)==0;f=f?1:2;while(1){b[h>>2]=0;l=da(a,c,f,h)|0;g=f+1|0;if((l|0)==(d|0)&(G()|0)==(e|0))break;if(g>>>0<7)f=g;else{f=0;a=0;j=6;break}}if((j|0)==6){F(f|0);S=k;return a|0}l=cd(f|0,0,56)|0;j=i|(G()|0)|268435456;l=a|l;F(j|0);S=k;return l|0}function ac(a,b){a=a|0;b=b|0;var c=0;c=0==0&(b&2013265920|0)==268435456;F((c?b&-2130706433|134217728:0)|0);return (c?a:0)|0}function bc(a,c){a=a|0;c=c|0;var d=0,e=0,f=0;e=S;S=S+16|0;d=e;if(!(0==0&(c&2013265920|0)==268435456)){c=0;d=0;F(c|0);S=e;return d|0}f=bd(a|0,c|0,56)|0;G()|0;b[d>>2]=0;d=da(a,c&-2130706433|134217728,f&7,d)|0;c=G()|0;F(c|0);S=e;return d|0}function cc(a,b){a=a|0;b=b|0;var c=0;if(!(0==0&(b&2013265920|0)==268435456)){c=0;return c|0}c=bd(a|0,b|0,56)|0;G()|0;switch(c&7){case 0:case 7:{c=0;return c|0}default:{}}c=b&-2130706433|134217728;if(0==0&(b&117440512|0)==16777216&(Eb(a,c)|0)!=0){c=0;return c|0}c=Ab(a,c)|0;return c|0}function dc(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0;g=S;S=S+16|0;e=g;h=0==0&(c&2013265920|0)==268435456;f=c&-2130706433|134217728;i=d;b[i>>2]=h?a:0;b[i+4>>2]=h?f:0;if(h){c=bd(a|0,c|0,56)|0;G()|0;b[e>>2]=0;a=da(a,f,c&7,e)|0;c=G()|0}else{a=0;c=0}i=d+8|0;b[i>>2]=a;b[i+4>>2]=c;S=g;return}function ec(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0;f=(Eb(a,c)|0)==0;c=c&-2130706433;e=d;b[e>>2]=f?a:0;b[e+4>>2]=f?c|285212672:0;e=d+8|0;b[e>>2]=a;b[e+4>>2]=c|301989888;e=d+16|0;b[e>>2]=a;b[e+4>>2]=c|318767104;e=d+24|0;b[e>>2]=a;b[e+4>>2]=c|335544320;e=d+32|0;b[e>>2]=a;b[e+4>>2]=c|352321536;d=d+40|0;b[d>>2]=a;b[d+4>>2]=c|369098752;return}function fc(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0;h=S;S=S+16|0;g=h;e=bd(a|0,c|0,56)|0;G()|0;i=0==0&(c&2013265920|0)==268435456;f=i?a:0;a=i?c&-2130706433|134217728:0;c=Kc(f,a,e&7)|0;if((c|0)==-1){b[d>>2]=0;S=h;return}Tb(f,a,g);e=bd(f|0,a|0,52)|0;G()|0;e=e&15;if(!(Eb(f,a)|0))eb(g,e,c,2,d);else ab(g,e,c,2,d);S=h;return}function gc(a){a=a|0;var c=0,d=0,e=0;c=Xc(1,12)|0;if(!c)H(22691,22646,49,22704);d=a+4|0;e=b[d>>2]|0;if(e|0){e=e+8|0;b[e>>2]=c;b[d>>2]=c;return c|0}if(b[a>>2]|0)H(22721,22646,61,22744);e=a;b[e>>2]=c;b[d>>2]=c;return c|0}function hc(a,c){a=a|0;c=c|0;var d=0,e=0;e=Vc(24)|0;if(!e)H(22758,22646,78,22772);b[e>>2]=b[c>>2];b[e+4>>2]=b[c+4>>2];b[e+8>>2]=b[c+8>>2];b[e+12>>2]=b[c+12>>2];b[e+16>>2]=0;c=a+4|0;d=b[c>>2]|0;if(d|0){b[d+16>>2]=e;b[c>>2]=e;return e|0}if(b[a>>2]|0)H(22787,22646,82,22772);b[a>>2]=e;b[c>>2]=e;return e|0}function ic(a){a=a|0;var c=0,d=0,e=0,f=0;if(!a)return;e=1;while(1){c=b[a>>2]|0;if(c|0)do{d=b[c>>2]|0;if(d|0)do{f=d;d=b[d+16>>2]|0;Wc(f)}while((d|0)!=0);f=c;c=b[c+8>>2]|0;Wc(f)}while((c|0)!=0);c=a;a=b[a+8>>2]|0;if(!e)Wc(c);if(!a)break;else e=0}return}function jc(a){a=a|0;var c=0,d=0,f=0,g=0,h=0.0,i=0,j=0.0,k=0.0,l=0,m=0,n=0,o=0,p=0,r=0,s=0.0,t=0.0,u=0.0,v=0.0,w=0.0,x=0.0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,I=0,J=0,K=0;g=a+8|0;if(b[g>>2]|0){K=1;return K|0}f=b[a>>2]|0;if(!f){K=0;return K|0}c=f;d=0;do{d=d+1|0;c=b[c+8>>2]|0}while((c|0)!=0);if(d>>>0<2){K=0;return K|0}I=Vc(d<<2)|0;if(!I)H(22807,22646,317,22826);G=Vc(d<<5)|0;if(!G)H(22848,22646,321,22826);b[a>>2]=0;z=a+4|0;b[z>>2]=0;b[g>>2]=0;d=0;F=0;y=0;n=0;a:while(1){m=b[f>>2]|0;if(m){h=0.0;i=m;do{k=+e[i+8>>3];c=i;i=b[i+16>>2]|0;l=(i|0)==0;g=l?m:i;j=+e[g+8>>3];if(+q(+(k-j))>3.141592653589793){K=14;break}h=h+(j-k)*(+e[c>>3]+ +e[g>>3])}while(!l);if((K|0)==14){K=0;h=0.0;c=m;do{x=+e[c+8>>3];E=c+16|0;D=b[E>>2]|0;D=(D|0)==0?m:D;w=+e[D+8>>3];h=h+(+e[c>>3]+ +e[D>>3])*((w<0.0?w+6.283185307179586:w)-(x<0.0?x+6.283185307179586:x));c=b[((c|0)==0?f:E)>>2]|0}while((c|0)!=0)}if(h>0.0){b[I+(F<<2)>>2]=f;F=F+1|0;g=y;c=n}else K=19}else K=19;if((K|0)==19){K=0;do if(!d)if(!n)if(!(b[a>>2]|0)){g=z;i=a;c=f;d=a;break}else{K=27;break a}else{g=z;i=n+8|0;c=f;d=a;break}else{c=d+8|0;if(b[c>>2]|0){K=21;break a}d=Xc(1,12)|0;if(!d){K=23;break a}b[c>>2]=d;g=d+4|0;i=d;c=n}while(0);b[i>>2]=f;b[g>>2]=f;i=G+(y<<5)|0;l=b[f>>2]|0;if(l){m=G+(y<<5)+8|0;e[m>>3]=1797693134862315708145274.0e284;n=G+(y<<5)+24|0;e[n>>3]=1797693134862315708145274.0e284;e[i>>3]=-1797693134862315708145274.0e284;o=G+(y<<5)+16|0;e[o>>3]=-1797693134862315708145274.0e284;u=1797693134862315708145274.0e284;v=-1797693134862315708145274.0e284;g=0;p=l;k=1797693134862315708145274.0e284;s=1797693134862315708145274.0e284;t=-1797693134862315708145274.0e284;j=-1797693134862315708145274.0e284;while(1){h=+e[p>>3];x=+e[p+8>>3];p=b[p+16>>2]|0;r=(p|0)==0;w=+e[(r?l:p)+8>>3];if(h>3]=h;k=h}if(x>3]=x;s=x}if(h>t)e[i>>3]=h;else h=t;if(x>j){e[o>>3]=x;j=x}u=x>0.0&xv?x:v;g=g|+q(+(x-w))>3.141592653589793;if(r)break;else t=h}if(g){e[o>>3]=v;e[n>>3]=u}}else{b[i>>2]=0;b[i+4>>2]=0;b[i+8>>2]=0;b[i+12>>2]=0;b[i+16>>2]=0;b[i+20>>2]=0;b[i+24>>2]=0;b[i+28>>2]=0}g=y+1|0}E=f+8|0;f=b[E>>2]|0;b[E>>2]=0;if(!f){K=45;break}else{y=g;n=c}}if((K|0)==21)H(22624,22646,35,22658);else if((K|0)==23)H(22678,22646,37,22658);else if((K|0)==27)H(22721,22646,61,22744);else if((K|0)==45){b:do if((F|0)>0){E=(g|0)==0;C=g<<2;D=(a|0)==0;B=0;c=0;while(1){A=b[I+(B<<2)>>2]|0;if(!E){y=Vc(C)|0;if(!y){K=50;break}z=Vc(C)|0;if(!z){K=52;break}c:do if(!D){g=0;d=0;i=a;while(1){f=G+(g<<5)|0;if(kc(b[i>>2]|0,f,b[A>>2]|0)|0){b[y+(d<<2)>>2]=i;b[z+(d<<2)>>2]=f;r=d+1|0}else r=d;i=b[i+8>>2]|0;if(!i)break;else{g=g+1|0;d=r}}if((r|0)>0){f=b[y>>2]|0;if((r|0)==1)d=f;else{o=0;p=-1;d=f;n=f;while(1){l=b[n>>2]|0;f=0;i=0;while(1){g=b[b[y+(i<<2)>>2]>>2]|0;if((g|0)==(l|0))m=f;else m=f+((kc(g,b[z+(i<<2)>>2]|0,b[l>>2]|0)|0)&1)|0;i=i+1|0;if((i|0)==(r|0))break;else f=m}g=(m|0)>(p|0);d=g?n:d;f=o+1|0;if((f|0)==(r|0))break c;o=f;p=g?m:p;n=b[y+(f<<2)>>2]|0}}}else d=0}else d=0;while(0);Wc(y);Wc(z);if(d){g=d+4|0;f=b[g>>2]|0;if(!f){if(b[d>>2]|0){K=70;break}}else d=f+8|0;b[d>>2]=A;b[g>>2]=A}else K=73}else K=73;if((K|0)==73){K=0;c=b[A>>2]|0;if(c|0)do{z=c;c=b[c+16>>2]|0;Wc(z)}while((c|0)!=0);Wc(A);c=2}B=B+1|0;if((B|0)>=(F|0)){J=c;break b}}if((K|0)==50)H(22863,22646,249,22882);else if((K|0)==52)H(22901,22646,252,22882);else if((K|0)==70)H(22721,22646,61,22744)}else J=0;while(0);Wc(I);Wc(G);K=J;return K|0}return 0}function kc(a,c,d){a=a|0;c=c|0;d=d|0;var f=0.0,g=0.0,h=0.0,i=0.0,j=0.0,k=0.0,l=0.0,m=0;if(!(xa(c,d)|0)){a=0;return a|0}c=wa(c)|0;l=+e[d>>3];f=+e[d+8>>3];f=c&f<0.0?f+6.283185307179586:f;a=b[a>>2]|0;if(!a){a=0;return a|0}if(c){c=0;d=a;a:while(1){while(1){i=+e[d>>3];k=+e[d+8>>3];d=d+16|0;m=b[d>>2]|0;m=(m|0)==0?a:m;h=+e[m>>3];g=+e[m+8>>3];if(i>h){j=i;i=k}else{j=h;h=i;i=g;g=k}if(!(lj))break;d=b[d>>2]|0;if(!d){d=22;break a}}k=g<0.0?g+6.283185307179586:g;i=i<0.0?i+6.283185307179586:i;f=i==f|k==f?f+-2.220446049250313e-16:f;k=k+(l-h)/(j-h)*(i-k);if((k<0.0?k+6.283185307179586:k)>f)c=c^1;d=b[d>>2]|0;if(!d){d=22;break}}if((d|0)==22)return c|0}else{c=0;d=a;b:while(1){while(1){i=+e[d>>3];k=+e[d+8>>3];d=d+16|0;m=b[d>>2]|0;m=(m|0)==0?a:m;h=+e[m>>3];g=+e[m+8>>3];if(i>h){j=i;i=k}else{j=h;h=i;i=g;g=k}if(!(lj))break;d=b[d>>2]|0;if(!d){d=22;break b}}f=i==f|g==f?f+-2.220446049250313e-16:f;if(g+(l-h)/(j-h)*(i-g)>f)c=c^1;d=b[d>>2]|0;if(!d){d=22;break}}if((d|0)==22)return c|0}return 0}function lc(c,d,e,f,g){c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;u=S;S=S+32|0;t=u+16|0;s=u;h=bd(c|0,d|0,52)|0;G()|0;h=h&15;p=bd(e|0,f|0,52)|0;G()|0;if((h|0)!=(p&15|0)){t=1;S=u;return t|0}l=bd(c|0,d|0,45)|0;G()|0;l=l&127;m=bd(e|0,f|0,45)|0;G()|0;m=m&127;p=(l|0)!=(m|0);if(p){j=ta(l,m)|0;if((j|0)==7){t=2;S=u;return t|0}k=ta(m,l)|0;if((k|0)==7)H(22925,22949,151,22959);else{q=j;i=k}}else{q=0;i=0}n=la(l)|0;o=la(m)|0;b[t>>2]=0;b[t+4>>2]=0;b[t+8>>2]=0;b[t+12>>2]=0;do if(!q){Sb(e,f,t)|0;if((n|0)!=0&(o|0)!=0){if((m|0)!=(l|0))H(23077,22949,243,22959);i=Kb(c,d)|0;h=Kb(e,f)|0;if(!(a[22032+(i*7|0)+h>>0]|0)){i=b[21200+(i*28|0)+(h<<2)>>2]|0;if((i|0)>0){j=t+4|0;h=0;do{Oa(j);h=h+1|0}while((h|0)!=(i|0));r=50}else r=50}else h=5}else r=50}else{m=b[4304+(l*28|0)+(q<<2)>>2]|0;j=(m|0)>0;if(!o)if(j){l=0;k=e;j=f;do{k=Ob(k,j)|0;j=G()|0;i=Qa(i)|0;l=l+1|0}while((l|0)!=(m|0));m=i;l=k;k=j}else{m=i;l=e;k=f}else if(j){l=0;k=e;j=f;do{k=Nb(k,j)|0;j=G()|0;i=Qa(i)|0;if((i|0)==1)i=Qa(1)|0;l=l+1|0}while((l|0)!=(m|0));m=i;l=k;k=j}else{m=i;l=e;k=f}Sb(l,k,t)|0;if(!p)H(22972,22949,181,22959);j=(n|0)!=0;i=(o|0)!=0;if(j&i)H(22999,22949,182,22959);if(!j)if(i){i=Kb(l,k)|0;if(a[22032+(i*7|0)+m>>0]|0){h=4;break}l=0;k=b[21200+(m*28|0)+(i<<2)>>2]|0;r=26}else i=0;else{i=Kb(c,d)|0;if(a[22032+(i*7|0)+q>>0]|0){h=3;break}k=b[21200+(i*28|0)+(q<<2)>>2]|0;l=k;r=26}if((r|0)==26){if((k|0)<=-1)H(23030,22949,212,22959);if((l|0)<=-1)H(23053,22949,213,22959);if((k|0)>0){j=t+4|0;i=0;do{Oa(j);i=i+1|0}while((i|0)!=(k|0));i=l}else i=l};b[s>>2]=0;b[s+4>>2]=0;b[s+8>>2]=0;Ma(s,q);if(h|0)while(1){if(!(Qb(h)|0))La(s);else Ka(s);if((h|0)>1)h=h+-1|0;else break}if((i|0)>0){h=0;do{Oa(s);h=h+1|0}while((h|0)!=(i|0))}r=t+4|0;Ea(r,s,r);Ca(r);r=50}while(0);if((r|0)==50){h=t+4|0;b[g>>2]=b[h>>2];b[g+4>>2]=b[h+4>>2];b[g+8>>2]=b[h+8>>2];h=0}t=h;S=u;return t|0}function mc(a,c,d,e){a=a|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0;p=S;S=S+48|0;h=p+36|0;i=p+24|0;j=p+12|0;k=p;g=bd(a|0,c|0,52)|0;G()|0;g=g&15;n=bd(a|0,c|0,45)|0;G()|0;n=n&127;l=la(n)|0;cd(g|0,0,52)|0;r=G()|0|134225919;q=e;b[q>>2]=-1;b[q+4>>2]=r;if(!g){if((b[d>>2]|0)>1){r=1;S=p;return r|0}if((b[d+4>>2]|0)>1){r=1;S=p;return r|0}if((b[d+8>>2]|0)>1){r=1;S=p;return r|0}f=sa(n,Ha(d)|0)|0;if((f|0)==127){r=1;S=p;return r|0}o=cd(f|0,0,45)|0;q=G()|0;n=e;q=b[n+4>>2]&-1040385|q;r=e;b[r>>2]=b[n>>2]|o;b[r+4>>2]=q;r=0;S=p;return r|0};b[h>>2]=b[d>>2];b[h+4>>2]=b[d+4>>2];b[h+8>>2]=b[d+8>>2];while(1){b[i>>2]=b[h>>2];b[i+4>>2]=b[h+4>>2];b[i+8>>2]=b[h+8>>2];if(!(Qb(g)|0)){Ja(h);b[j>>2]=b[h>>2];b[j+4>>2]=b[h+4>>2];b[j+8>>2]=b[h+8>>2];La(j)}else{Ia(h);b[j>>2]=b[h>>2];b[j+4>>2]=b[h+4>>2];b[j+8>>2]=b[h+8>>2];Ka(j)}Fa(i,j,k);Ca(k);q=e;s=b[q>>2]|0;q=b[q+4>>2]|0;t=(15-g|0)*3|0;d=cd(7,0,t|0)|0;q=q&~(G()|0);t=cd(Ha(k)|0,0,t|0)|0;q=G()|0|q;r=e;b[r>>2]=t|s&~d;b[r+4>>2]=q;if((g|0)>1)g=g+-1|0;else break}a:do if(((b[h>>2]|0)<=1?(b[h+4>>2]|0)<=1:0)?(b[h+8>>2]|0)<=1:0){g=Ha(h)|0;i=sa(n,g)|0;if((i|0)==127)k=0;else k=la(i)|0;b:do if(!g)if((l|0)!=0&(k|0)!=0){t=Kb(a,c)|0;g=e;g=21408+(t*28|0)+((Kb(b[g>>2]|0,b[g+4>>2]|0)|0)<<2)|0;g=b[g>>2]|0;if((g|0)<=-1)H(23201,22949,433,23134);if(!g){f=i;g=55}else{h=e;f=0;d=b[h>>2]|0;h=b[h+4>>2]|0;do{d=Mb(d,h)|0;h=G()|0;t=e;b[t>>2]=d;b[t+4>>2]=h;f=f+1|0}while((f|0)<(g|0));f=i;g=54}}else{f=i;g=54}else{if(l){h=21408+((Kb(a,c)|0)*28|0)+(g<<2)|0;h=b[h>>2]|0;if((h|0)>0){d=0;do{g=Pa(g)|0;d=d+1|0}while((d|0)!=(h|0))}if((g|0)==1){f=3;break a}d=sa(n,g)|0;if((d|0)==127)H(23104,22949,376,23134);if(!(la(d)|0)){o=h;m=g;f=d}else H(23147,22949,377,23134)}else{o=0;m=g;f=i}j=b[4304+(n*28|0)+(m<<2)>>2]|0;if((j|0)<=-1)H(23178,22949,384,23134);if(!k){if((o|0)<=-1)H(23030,22949,417,23134);if(o|0){h=e;g=0;d=b[h>>2]|0;h=b[h+4>>2]|0;do{d=Mb(d,h)|0;h=G()|0;t=e;b[t>>2]=d;b[t+4>>2]=h;g=g+1|0}while((g|0)<(o|0))}if((j|0)<=0){g=54;break}h=e;g=0;d=b[h>>2]|0;h=b[h+4>>2]|0;while(1){d=Mb(d,h)|0;h=G()|0;t=e;b[t>>2]=d;b[t+4>>2]=h;g=g+1|0;if((g|0)==(j|0)){g=54;break b}}}i=ta(f,n)|0;if((i|0)==7)H(22925,22949,393,23134);g=e;d=b[g>>2]|0;g=b[g+4>>2]|0;if((j|0)>0){h=0;do{d=Mb(d,g)|0;g=G()|0;t=e;b[t>>2]=d;b[t+4>>2]=g;h=h+1|0}while((h|0)!=(j|0))}d=Kb(d,g)|0;t=ma(f)|0;d=b[(t?21824:21616)+(i*28|0)+(d<<2)>>2]|0;if((d|0)<=-1)H(23030,22949,412,23134);if(!d)g=54;else{i=e;g=0;h=b[i>>2]|0;i=b[i+4>>2]|0;do{h=Lb(h,i)|0;i=G()|0;t=e;b[t>>2]=h;b[t+4>>2]=i;g=g+1|0}while((g|0)<(d|0));g=54}}while(0);if((g|0)==54)if(k)g=55;if((g|0)==55){t=e;if((Kb(b[t>>2]|0,b[t+4>>2]|0)|0)==1){f=4;break}}t=e;r=b[t>>2]|0;t=b[t+4>>2]&-1040385;s=cd(f|0,0,45)|0;t=t|(G()|0);f=e;b[f>>2]=r|s;b[f+4>>2]=t;f=0}else f=2;while(0);t=f;S=p;return t|0}function nc(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0,g=0;g=S;S=S+16|0;f=g;a=lc(a,b,c,d,f)|0;if(!a){Ua(f,e);a=0}S=g;return a|0}function oc(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0;e=S;S=S+16|0;f=e;Va(c,f);d=mc(a,b,f,d)|0;S=e;return d|0}function pc(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0,g=0;g=S;S=S+32|0;e=g+12|0;f=g;if((lc(a,b,a,b,e)|0)==0?(lc(a,b,c,d,f)|0)==0:0)a=Ta(e,f)|0;else a=-1;S=g;return a|0}function qc(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0,g=0;g=S;S=S+32|0;e=g+12|0;f=g;if((lc(a,b,a,b,e)|0)==0?(lc(a,b,c,d,f)|0)==0:0)a=Ta(e,f)|0;else a=-1;S=g;return (a>>>31^1)+a|0}function rc(a,c,d,e,f){a=a|0;c=c|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0.0,j=0.0,k=0,l=0,m=0,n=0,o=0.0,p=0.0,r=0.0,s=0,t=0,u=0,v=0,w=0,x=0,y=0.0;x=S;S=S+48|0;g=x+24|0;h=x+12|0;w=x;if((lc(a,c,a,c,g)|0)==0?(lc(a,c,d,e,h)|0)==0:0){v=Ta(g,h)|0;if((v|0)<0){w=v;S=x;return w|0};b[g>>2]=0;b[g+4>>2]=0;b[g+8>>2]=0;b[h>>2]=0;b[h+4>>2]=0;b[h+8>>2]=0;lc(a,c,a,c,g)|0;lc(a,c,d,e,h)|0;Wa(g);Wa(h);if(!v){e=g+4|0;n=g+8|0;s=e;t=n;u=g;d=b[g>>2]|0;e=b[e>>2]|0;g=b[n>>2]|0;p=0.0;r=0.0;o=0.0}else{l=b[g>>2]|0;o=+(v|0);s=g+4|0;m=b[s>>2]|0;t=g+8|0;n=b[t>>2]|0;u=g;d=l;e=m;g=n;p=+((b[h>>2]|0)-l|0)/o;r=+((b[h+4>>2]|0)-m|0)/o;o=+((b[h+8>>2]|0)-n|0)/o}b[w>>2]=d;n=w+4|0;b[n>>2]=e;m=w+8|0;b[m>>2]=g;l=0;while(1){j=+(l|0);y=p*j+ +(d|0);i=r*j+ +(b[s>>2]|0);j=o*j+ +(b[t>>2]|0);e=~~+ed(+y);h=~~+ed(+i);d=~~+ed(+j);y=+q(+(+(e|0)-y));i=+q(+(+(h|0)-i));j=+q(+(+(d|0)-j));do if(!(y>i&y>j)){k=0-e|0;if(i>j){g=k-d|0;break}else{g=h;d=k-h|0;break}}else{e=0-(h+d)|0;g=h}while(0);b[w>>2]=e;b[n>>2]=g;b[m>>2]=d;Xa(w);mc(a,c,w,f+(l<<3)|0)|0;if((l|0)==(v|0))break;l=l+1|0;d=b[u>>2]|0}w=0;S=x;return w|0}w=-1;S=x;return w|0}function sc(a,b){a=a|0;b=b|0;var c=0;if(!b){c=1;return c|0}c=a;a=1;do{a=B((b&1|0)==0?1:c,a)|0;b=b>>1;c=B(c,c)|0}while((b|0)!=0);return a|0}function tc(a,c,d){a=a|0;c=c|0;d=d|0;var f=0.0,g=0.0,h=0.0,i=0.0,j=0.0,k=0.0,l=0,m=0,n=0,o=0.0;if(!(xa(c,d)|0)){n=0;return n|0}c=wa(c)|0;o=+e[d>>3];f=+e[d+8>>3];f=c&f<0.0?f+6.283185307179586:f;n=b[a>>2]|0;if((n|0)<=0){n=0;return n|0}m=b[a+4>>2]|0;if(c){c=0;d=-1;a=0;a:while(1){l=a;while(1){i=+e[m+(l<<4)>>3];k=+e[m+(l<<4)+8>>3];a=(d+2|0)%(n|0)|0;h=+e[m+(a<<4)>>3];g=+e[m+(a<<4)+8>>3];if(i>h){j=i;i=k}else{j=h;h=i;i=g;g=k}if(!(oj))break;d=l+1|0;if((d|0)<(n|0)){a=l;l=d;d=a}else{d=22;break a}}k=g<0.0?g+6.283185307179586:g;i=i<0.0?i+6.283185307179586:i;f=i==f|k==f?f+-2.220446049250313e-16:f;k=k+(o-h)/(j-h)*(i-k);if((k<0.0?k+6.283185307179586:k)>f)c=c^1;a=l+1|0;if((a|0)>=(n|0)){d=22;break}else d=l}if((d|0)==22)return c|0}else{c=0;d=-1;a=0;b:while(1){l=a;while(1){i=+e[m+(l<<4)>>3];k=+e[m+(l<<4)+8>>3];a=(d+2|0)%(n|0)|0;h=+e[m+(a<<4)>>3];g=+e[m+(a<<4)+8>>3];if(i>h){j=i;i=k}else{j=h;h=i;i=g;g=k}if(!(oj))break;d=l+1|0;if((d|0)<(n|0)){a=l;l=d;d=a}else{d=22;break b}}f=i==f|g==f?f+-2.220446049250313e-16:f;if(g+(o-h)/(j-h)*(i-g)>f)c=c^1;a=l+1|0;if((a|0)>=(n|0)){d=22;break}else d=l}if((d|0)==22)return c|0}return 0}function uc(a,c){a=a|0;c=c|0;var d=0.0,f=0.0,g=0.0,h=0.0,i=0.0,j=0.0,k=0.0,l=0.0,m=0.0,n=0,o=0,p=0,r=0,s=0,t=0,u=0,v=0;r=b[a>>2]|0;if(!r){b[c>>2]=0;b[c+4>>2]=0;b[c+8>>2]=0;b[c+12>>2]=0;b[c+16>>2]=0;b[c+20>>2]=0;b[c+24>>2]=0;b[c+28>>2]=0;return}s=c+8|0;e[s>>3]=1797693134862315708145274.0e284;t=c+24|0;e[t>>3]=1797693134862315708145274.0e284;e[c>>3]=-1797693134862315708145274.0e284;u=c+16|0;e[u>>3]=-1797693134862315708145274.0e284;if((r|0)<=0)return;o=b[a+4>>2]|0;l=1797693134862315708145274.0e284;m=-1797693134862315708145274.0e284;n=0;a=-1;h=1797693134862315708145274.0e284;i=1797693134862315708145274.0e284;k=-1797693134862315708145274.0e284;f=-1797693134862315708145274.0e284;p=0;while(1){d=+e[o+(p<<4)>>3];j=+e[o+(p<<4)+8>>3];a=a+2|0;g=+e[o+(((a|0)==(r|0)?0:a)<<4)+8>>3];if(d>3]=d;h=d}if(j>3]=j;i=j}if(d>k)e[c>>3]=d;else d=k;if(j>f){e[u>>3]=j;f=j}l=j>0.0&jm?j:m;n=n|+q(+(j-g))>3.141592653589793;a=p+1|0;if((a|0)==(r|0))break;else{v=p;k=d;p=a;a=v}}if(!n)return;e[u>>3]=m;e[t>>3]=l;return}function vc(a,c){a=a|0;c=c|0;var d=0,f=0,g=0,h=0.0,i=0.0,j=0.0,k=0.0,l=0.0,m=0.0,n=0.0,o=0.0,p=0.0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0;r=b[a>>2]|0;if(r){s=c+8|0;e[s>>3]=1797693134862315708145274.0e284;t=c+24|0;e[t>>3]=1797693134862315708145274.0e284;e[c>>3]=-1797693134862315708145274.0e284;u=c+16|0;e[u>>3]=-1797693134862315708145274.0e284;if((r|0)>0){g=b[a+4>>2]|0;o=1797693134862315708145274.0e284;p=-1797693134862315708145274.0e284;f=0;d=-1;k=1797693134862315708145274.0e284;l=1797693134862315708145274.0e284;n=-1797693134862315708145274.0e284;i=-1797693134862315708145274.0e284;v=0;while(1){h=+e[g+(v<<4)>>3];m=+e[g+(v<<4)+8>>3];z=d+2|0;j=+e[g+(((z|0)==(r|0)?0:z)<<4)+8>>3];if(h>3]=h;k=h}if(m>3]=m;l=m}if(h>n)e[c>>3]=h;else h=n;if(m>i){e[u>>3]=m;i=m}o=m>0.0&mp?m:p;f=f|+q(+(m-j))>3.141592653589793;d=v+1|0;if((d|0)==(r|0))break;else{z=v;n=h;v=d;d=z}}if(f){e[u>>3]=p;e[t>>3]=o}}}else{b[c>>2]=0;b[c+4>>2]=0;b[c+8>>2]=0;b[c+12>>2]=0;b[c+16>>2]=0;b[c+20>>2]=0;b[c+24>>2]=0;b[c+28>>2]=0}z=a+8|0;d=b[z>>2]|0;if((d|0)<=0)return;y=a+12|0;x=0;do{g=b[y>>2]|0;f=x;x=x+1|0;t=c+(x<<5)|0;u=b[g+(f<<3)>>2]|0;if(u){v=c+(x<<5)+8|0;e[v>>3]=1797693134862315708145274.0e284;a=c+(x<<5)+24|0;e[a>>3]=1797693134862315708145274.0e284;e[t>>3]=-1797693134862315708145274.0e284;w=c+(x<<5)+16|0;e[w>>3]=-1797693134862315708145274.0e284;if((u|0)>0){r=b[g+(f<<3)+4>>2]|0;o=1797693134862315708145274.0e284;p=-1797693134862315708145274.0e284;g=0;f=-1;s=0;k=1797693134862315708145274.0e284;l=1797693134862315708145274.0e284;m=-1797693134862315708145274.0e284;i=-1797693134862315708145274.0e284;while(1){h=+e[r+(s<<4)>>3];n=+e[r+(s<<4)+8>>3];f=f+2|0;j=+e[r+(((f|0)==(u|0)?0:f)<<4)+8>>3];if(h>3]=h;k=h}if(n>3]=n;l=n}if(h>m)e[t>>3]=h;else h=m;if(n>i){e[w>>3]=n;i=n}o=n>0.0&np?n:p;g=g|+q(+(n-j))>3.141592653589793;f=s+1|0;if((f|0)==(u|0))break;else{A=s;s=f;m=h;f=A}}if(g){e[w>>3]=p;e[a>>3]=o}}}else{b[t>>2]=0;b[t+4>>2]=0;b[t+8>>2]=0;b[t+12>>2]=0;b[t+16>>2]=0;b[t+20>>2]=0;b[t+24>>2]=0;b[t+28>>2]=0;d=b[z>>2]|0}}while((x|0)<(d|0));return}function wc(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0,g=0;if(!(tc(a,c,d)|0)){f=0;return f|0}f=a+8|0;if((b[f>>2]|0)<=0){f=1;return f|0}e=a+12|0;a=0;while(1){g=a;a=a+1|0;if(tc((b[e>>2]|0)+(g<<3)|0,c+(a<<5)|0,d)|0){a=0;e=6;break}if((a|0)>=(b[f>>2]|0)){a=1;e=6;break}}if((e|0)==6)return a|0;return 0}function xc(){return 8}function yc(){return 16}function zc(){return 168}function Ac(){return 8}function Bc(){return 16}function Cc(){return 12}function Dc(){return 8}function Ec(a){a=a|0;var b=0.0,c=0.0;c=+e[a>>3];b=+e[a+8>>3];return +(+r(+(c*c+b*b)))}function Fc(a,b,c,d,f){a=a|0;b=b|0;c=c|0;d=d|0;f=f|0;var g=0.0,h=0.0,i=0.0,j=0.0,k=0.0,l=0.0,m=0.0,n=0.0;k=+e[a>>3];j=+e[b>>3]-k;i=+e[a+8>>3];h=+e[b+8>>3]-i;m=+e[c>>3];g=+e[d>>3]-m;n=+e[c+8>>3];l=+e[d+8>>3]-n;g=(g*(i-n)-(k-m)*l)/(j*l-h*g);e[f>>3]=k+j*g;e[f+8>>3]=i+h*g;return}function Gc(a,b){a=a|0;b=b|0;if(!(+e[a>>3]==+e[b>>3])){b=0;return b|0}b=+e[a+8>>3]==+e[b+8>>3];return b|0}function Hc(a,b){a=a|0;b=b|0;var c=0.0,d=0.0,f=0.0;f=+e[a>>3]-+e[b>>3];d=+e[a+8>>3]-+e[b+8>>3];c=+e[a+16>>3]-+e[b+16>>3];return +(f*f+d*d+c*c)}function Ic(a,b){a=a|0;b=b|0;var c=0.0,d=0.0,f=0.0;c=+e[a>>3];d=+t(+c);c=+u(+c);e[b+16>>3]=c;c=+e[a+8>>3];f=d*+t(+c);e[b>>3]=f;c=d*+u(+c);e[b+8>>3]=c;return}function Jc(a,c){a=a|0;c=c|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0;k=S;S=S+32|0;f=k+16|0;g=k;Tb(a,c,f);h=zb(a,c)|0;j=Kb(a,c)|0;pa(h,g);c=qa(h,b[f>>2]|0)|0;if(!(la(h)|0)){j=c;S=k;return j|0}do switch(h|0){case 4:{a=0;d=14;break}case 14:{a=1;d=14;break}case 24:{a=2;d=14;break}case 38:{a=3;d=14;break}case 49:{a=4;d=14;break}case 58:{a=5;d=14;break}case 63:{a=6;d=14;break}case 72:{a=7;d=14;break}case 83:{a=8;d=14;break}case 97:{a=9;d=14;break}case 107:{a=10;d=14;break}case 117:{a=11;d=14;break}default:{i=0;e=0}}while(0);if((d|0)==14){i=b[22096+(a*24|0)+8>>2]|0;e=b[22096+(a*24|0)+16>>2]|0}a=b[f>>2]|0;if((a|0)!=(b[g>>2]|0)){h=ma(h)|0;a=b[f>>2]|0;if(h|(a|0)==(e|0))c=(c+1|0)%6|0}if((j|0)==3&(a|0)==(e|0)){j=(c+5|0)%6|0;S=k;return j|0}if(!((j|0)==5&(a|0)==(i|0))){j=c;S=k;return j|0}j=(c+1|0)%6|0;S=k;return j|0}function Kc(a,c,d){a=a|0;c=c|0;d=d|0;var e=0,f=0;e=Eb(a,c)|0;if((d+-1|0)>>>0>5){d=-1;return d|0}f=(e|0)!=0;if((d|0)==1&f){d=-1;return d|0}e=Jc(a,c)|0;if(f){d=(5-e+(b[22384+(d<<2)>>2]|0)|0)%5|0;return d|0}else{d=(6-e+(b[22416+(d<<2)>>2]|0)|0)%6|0;return d|0}return 0}function Lc(a,c,d){a=a|0;c=c|0;d=d|0;var e=0;if((c|0)>0){e=Xc(c,4)|0;b[a>>2]=e;if(!e)H(23230,23253,40,23267)}else b[a>>2]=0;b[a+4>>2]=c;b[a+8>>2]=0;b[a+12>>2]=d;return}function Mc(a){a=a|0;var c=0,d=0,f=0,g=0,h=0,i=0,j=0;g=a+4|0;h=a+12|0;i=a+8|0;a:while(1){d=b[g>>2]|0;c=0;while(1){if((c|0)>=(d|0))break a;f=b[a>>2]|0;j=b[f+(c<<2)>>2]|0;if(!j)c=c+1|0;else break}c=f+(~~(+q(+(+s(10.0,+(+(15-(b[h>>2]|0)|0)))*(+e[j>>3]+ +e[j+8>>3])))%+(d|0))>>>0<<2)|0;d=b[c>>2]|0;b:do if(d|0){f=j+32|0;if((d|0)==(j|0))b[c>>2]=b[f>>2];else{d=d+32|0;c=b[d>>2]|0;if(!c)break;while(1){if((c|0)==(j|0))break;d=c+32|0;c=b[d>>2]|0;if(!c)break b}b[d>>2]=b[f>>2]}Wc(j);b[i>>2]=(b[i>>2]|0)+-1}while(0)}Wc(b[a>>2]|0);return}function Nc(a){a=a|0;var c=0,d=0,e=0;e=b[a+4>>2]|0;d=0;while(1){if((d|0)>=(e|0)){c=0;d=4;break}c=b[(b[a>>2]|0)+(d<<2)>>2]|0;if(!c)d=d+1|0;else{d=4;break}}if((d|0)==4)return c|0;return 0}function Oc(a,c){a=a|0;c=c|0;var d=0,f=0,g=0,h=0;d=~~(+q(+(+s(10.0,+(+(15-(b[a+12>>2]|0)|0)))*(+e[c>>3]+ +e[c+8>>3])))%+(b[a+4>>2]|0))>>>0;d=(b[a>>2]|0)+(d<<2)|0;f=b[d>>2]|0;if(!f){h=1;return h|0}h=c+32|0;do if((f|0)!=(c|0)){d=b[f+32>>2]|0;if(!d){h=1;return h|0}g=d;while(1){if((g|0)==(c|0)){g=8;break}d=b[g+32>>2]|0;if(!d){d=1;g=10;break}else{f=g;g=d}}if((g|0)==8){b[f+32>>2]=b[h>>2];break}else if((g|0)==10)return d|0}else b[d>>2]=b[h>>2];while(0);Wc(c);h=a+8|0;b[h>>2]=(b[h>>2]|0)+-1;h=0;return h|0}function Pc(a,c,d){a=a|0;c=c|0;d=d|0;var f=0,g=0,h=0,i=0;h=Vc(40)|0;if(!h)H(23283,23253,98,23296);b[h>>2]=b[c>>2];b[h+4>>2]=b[c+4>>2];b[h+8>>2]=b[c+8>>2];b[h+12>>2]=b[c+12>>2];g=h+16|0;b[g>>2]=b[d>>2];b[g+4>>2]=b[d+4>>2];b[g+8>>2]=b[d+8>>2];b[g+12>>2]=b[d+12>>2];b[h+32>>2]=0;g=~~(+q(+(+s(10.0,+(+(15-(b[a+12>>2]|0)|0)))*(+e[c>>3]+ +e[c+8>>3])))%+(b[a+4>>2]|0))>>>0;g=(b[a>>2]|0)+(g<<2)|0;f=b[g>>2]|0;do if(!f)b[g>>2]=h;else{while(1){if(hb(f,c)|0?hb(f+16|0,d)|0:0)break;g=b[f+32>>2]|0;f=(g|0)==0?f:g;if(!(b[f+32>>2]|0)){i=10;break}}if((i|0)==10){b[f+32>>2]=h;break}Wc(h);i=f;return i|0}while(0);i=a+8|0;b[i>>2]=(b[i>>2]|0)+1;i=h;return i|0}function Qc(a,c,d){a=a|0;c=c|0;d=d|0;var f=0,g=0;g=~~(+q(+(+s(10.0,+(+(15-(b[a+12>>2]|0)|0)))*(+e[c>>3]+ +e[c+8>>3])))%+(b[a+4>>2]|0))>>>0;g=b[(b[a>>2]|0)+(g<<2)>>2]|0;if(!g){d=0;return d|0}if(!d){a=g;while(1){if(hb(a,c)|0){f=10;break}a=b[a+32>>2]|0;if(!a){a=0;f=10;break}}if((f|0)==10)return a|0}a=g;while(1){if(hb(a,c)|0?hb(a+16|0,d)|0:0){f=10;break}a=b[a+32>>2]|0;if(!a){a=0;f=10;break}}if((f|0)==10)return a|0;return 0}function Rc(a,c){a=a|0;c=c|0;var d=0;d=~~(+q(+(+s(10.0,+(+(15-(b[a+12>>2]|0)|0)))*(+e[c>>3]+ +e[c+8>>3])))%+(b[a+4>>2]|0))>>>0;a=b[(b[a>>2]|0)+(d<<2)>>2]|0;if(!a){d=0;return d|0}while(1){if(hb(a,c)|0){c=5;break}a=b[a+32>>2]|0;if(!a){a=0;c=5;break}}if((c|0)==5)return a|0;return 0}function Sc(){return 23312}function Tc(a){a=+a;return +(+hd(+a))}function Uc(a){a=+a;return ~~+Tc(a)|0}function Vc(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0;w=S;S=S+16|0;n=w;do if(a>>>0<245){k=a>>>0<11?16:a+11&-8;a=k>>>3;m=b[5829]|0;d=m>>>a;if(d&3|0){c=(d&1^1)+a|0;a=23356+(c<<1<<2)|0;d=a+8|0;e=b[d>>2]|0;f=e+8|0;g=b[f>>2]|0;if((g|0)==(a|0))b[5829]=m&~(1<>2]=a;b[d>>2]=g}v=c<<3;b[e+4>>2]=v|3;v=e+v+4|0;b[v>>2]=b[v>>2]|1;v=f;S=w;return v|0}l=b[5831]|0;if(k>>>0>l>>>0){if(d|0){c=2<>>12&16;c=c>>>i;d=c>>>5&8;c=c>>>d;g=c>>>2&4;c=c>>>g;a=c>>>1&2;c=c>>>a;e=c>>>1&1;e=(d|i|g|a|e)+(c>>>e)|0;c=23356+(e<<1<<2)|0;a=c+8|0;g=b[a>>2]|0;i=g+8|0;d=b[i>>2]|0;if((d|0)==(c|0)){a=m&~(1<>2]=c;b[a>>2]=d;a=m}v=e<<3;h=v-k|0;b[g+4>>2]=k|3;f=g+k|0;b[f+4>>2]=h|1;b[g+v>>2]=h;if(l|0){e=b[5834]|0;c=l>>>3;d=23356+(c<<1<<2)|0;c=1<>2]|0}b[a>>2]=e;b[c+12>>2]=e;b[e+8>>2]=c;b[e+12>>2]=d}b[5831]=h;b[5834]=f;v=i;S=w;return v|0}g=b[5830]|0;if(g){d=(g&0-g)+-1|0;f=d>>>12&16;d=d>>>f;e=d>>>5&8;d=d>>>e;h=d>>>2&4;d=d>>>h;i=d>>>1&2;d=d>>>i;j=d>>>1&1;j=b[23620+((e|f|h|i|j)+(d>>>j)<<2)>>2]|0;d=j;i=j;j=(b[j+4>>2]&-8)-k|0;while(1){a=b[d+16>>2]|0;if(!a){a=b[d+20>>2]|0;if(!a)break}h=(b[a+4>>2]&-8)-k|0;f=h>>>0>>0;d=a;i=f?a:i;j=f?h:j}h=i+k|0;if(h>>>0>i>>>0){f=b[i+24>>2]|0;c=b[i+12>>2]|0;do if((c|0)==(i|0)){a=i+20|0;c=b[a>>2]|0;if(!c){a=i+16|0;c=b[a>>2]|0;if(!c){d=0;break}}while(1){e=c+20|0;d=b[e>>2]|0;if(!d){e=c+16|0;d=b[e>>2]|0;if(!d)break;else{c=d;a=e}}else{c=d;a=e}}b[a>>2]=0;d=c}else{d=b[i+8>>2]|0;b[d+12>>2]=c;b[c+8>>2]=d;d=c}while(0);do if(f|0){c=b[i+28>>2]|0;a=23620+(c<<2)|0;if((i|0)==(b[a>>2]|0)){b[a>>2]=d;if(!d){b[5830]=g&~(1<>2]|0)==(i|0)?v:f+20|0)>>2]=d;if(!d)break}b[d+24>>2]=f;c=b[i+16>>2]|0;if(c|0){b[d+16>>2]=c;b[c+24>>2]=d}c=b[i+20>>2]|0;if(c|0){b[d+20>>2]=c;b[c+24>>2]=d}}while(0);if(j>>>0<16){v=j+k|0;b[i+4>>2]=v|3;v=i+v+4|0;b[v>>2]=b[v>>2]|1}else{b[i+4>>2]=k|3;b[h+4>>2]=j|1;b[h+j>>2]=j;if(l|0){e=b[5834]|0;c=l>>>3;d=23356+(c<<1<<2)|0;c=1<>2]|0}b[a>>2]=e;b[c+12>>2]=e;b[e+8>>2]=c;b[e+12>>2]=d}b[5831]=j;b[5834]=h}v=i+8|0;S=w;return v|0}else m=k}else m=k}else m=k}else if(a>>>0<=4294967231){a=a+11|0;k=a&-8;e=b[5830]|0;if(e){f=0-k|0;a=a>>>8;if(a)if(k>>>0>16777215)j=31;else{m=(a+1048320|0)>>>16&8;q=a<>>16&4;q=q<>>16&2;j=14-(i|m|j)+(q<>>15)|0;j=k>>>(j+7|0)&1|j<<1}else j=0;d=b[23620+(j<<2)>>2]|0;a:do if(!d){d=0;a=0;q=61}else{a=0;i=k<<((j|0)==31?0:25-(j>>>1)|0);g=0;while(1){h=(b[d+4>>2]&-8)-k|0;if(h>>>0>>0)if(!h){a=d;f=0;q=65;break a}else{a=d;f=h}q=b[d+20>>2]|0;d=b[d+16+(i>>>31<<2)>>2]|0;g=(q|0)==0|(q|0)==(d|0)?g:q;if(!d){d=g;q=61;break}else i=i<<1}}while(0);if((q|0)==61){if((d|0)==0&(a|0)==0){a=2<>>12&16;m=m>>>h;g=m>>>5&8;m=m>>>g;i=m>>>2&4;m=m>>>i;j=m>>>1&2;m=m>>>j;d=m>>>1&1;a=0;d=b[23620+((g|h|i|j|d)+(m>>>d)<<2)>>2]|0}if(!d){i=a;h=f}else q=65}if((q|0)==65){g=d;while(1){m=(b[g+4>>2]&-8)-k|0;d=m>>>0>>0;f=d?m:f;a=d?g:a;d=b[g+16>>2]|0;if(!d)d=b[g+20>>2]|0;if(!d){i=a;h=f;break}else g=d}}if(((i|0)!=0?h>>>0<((b[5831]|0)-k|0)>>>0:0)?(l=i+k|0,l>>>0>i>>>0):0){g=b[i+24>>2]|0;c=b[i+12>>2]|0;do if((c|0)==(i|0)){a=i+20|0;c=b[a>>2]|0;if(!c){a=i+16|0;c=b[a>>2]|0;if(!c){c=0;break}}while(1){f=c+20|0;d=b[f>>2]|0;if(!d){f=c+16|0;d=b[f>>2]|0;if(!d)break;else{c=d;a=f}}else{c=d;a=f}}b[a>>2]=0}else{v=b[i+8>>2]|0;b[v+12>>2]=c;b[c+8>>2]=v}while(0);do if(g){a=b[i+28>>2]|0;d=23620+(a<<2)|0;if((i|0)==(b[d>>2]|0)){b[d>>2]=c;if(!c){e=e&~(1<>2]|0)==(i|0)?v:g+20|0)>>2]=c;if(!c)break}b[c+24>>2]=g;a=b[i+16>>2]|0;if(a|0){b[c+16>>2]=a;b[a+24>>2]=c}a=b[i+20>>2]|0;if(a){b[c+20>>2]=a;b[a+24>>2]=c}}while(0);b:do if(h>>>0<16){v=h+k|0;b[i+4>>2]=v|3;v=i+v+4|0;b[v>>2]=b[v>>2]|1}else{b[i+4>>2]=k|3;b[l+4>>2]=h|1;b[l+h>>2]=h;c=h>>>3;if(h>>>0<256){d=23356+(c<<1<<2)|0;a=b[5829]|0;c=1<>2]|0}b[a>>2]=l;b[c+12>>2]=l;b[l+8>>2]=c;b[l+12>>2]=d;break}c=h>>>8;if(c)if(h>>>0>16777215)d=31;else{u=(c+1048320|0)>>>16&8;v=c<>>16&4;v=v<>>16&2;d=14-(t|u|d)+(v<>>15)|0;d=h>>>(d+7|0)&1|d<<1}else d=0;c=23620+(d<<2)|0;b[l+28>>2]=d;a=l+16|0;b[a+4>>2]=0;b[a>>2]=0;a=1<>2]=l;b[l+24>>2]=c;b[l+12>>2]=l;b[l+8>>2]=l;break}c=b[c>>2]|0;c:do if((b[c+4>>2]&-8|0)!=(h|0)){e=h<<((d|0)==31?0:25-(d>>>1)|0);while(1){d=c+16+(e>>>31<<2)|0;a=b[d>>2]|0;if(!a)break;if((b[a+4>>2]&-8|0)==(h|0)){c=a;break c}else{e=e<<1;c=a}}b[d>>2]=l;b[l+24>>2]=c;b[l+12>>2]=l;b[l+8>>2]=l;break b}while(0);u=c+8|0;v=b[u>>2]|0;b[v+12>>2]=l;b[u>>2]=l;b[l+8>>2]=v;b[l+12>>2]=c;b[l+24>>2]=0}while(0);v=i+8|0;S=w;return v|0}else m=k}else m=k}else m=-1;while(0);d=b[5831]|0;if(d>>>0>=m>>>0){c=d-m|0;a=b[5834]|0;if(c>>>0>15){v=a+m|0;b[5834]=v;b[5831]=c;b[v+4>>2]=c|1;b[a+d>>2]=c;b[a+4>>2]=m|3}else{b[5831]=0;b[5834]=0;b[a+4>>2]=d|3;v=a+d+4|0;b[v>>2]=b[v>>2]|1}v=a+8|0;S=w;return v|0}h=b[5832]|0;if(h>>>0>m>>>0){t=h-m|0;b[5832]=t;v=b[5835]|0;u=v+m|0;b[5835]=u;b[u+4>>2]=t|1;b[v+4>>2]=m|3;v=v+8|0;S=w;return v|0}if(!(b[5947]|0)){b[5949]=4096;b[5948]=4096;b[5950]=-1;b[5951]=-1;b[5952]=0;b[5940]=0;b[5947]=n&-16^1431655768;a=4096}else a=b[5949]|0;i=m+48|0;j=m+47|0;g=a+j|0;f=0-a|0;k=g&f;if(k>>>0<=m>>>0){v=0;S=w;return v|0}a=b[5939]|0;if(a|0?(l=b[5937]|0,n=l+k|0,n>>>0<=l>>>0|n>>>0>a>>>0):0){v=0;S=w;return v|0}d:do if(!(b[5940]&4)){d=b[5835]|0;e:do if(d){e=23764;while(1){n=b[e>>2]|0;if(n>>>0<=d>>>0?(n+(b[e+4>>2]|0)|0)>>>0>d>>>0:0)break;a=b[e+8>>2]|0;if(!a){q=128;break e}else e=a}c=g-h&f;if(c>>>0<2147483647){a=id(c|0)|0;if((a|0)==((b[e>>2]|0)+(b[e+4>>2]|0)|0)){if((a|0)!=(-1|0)){h=c;g=a;q=145;break d}}else{e=a;q=136}}else c=0}else q=128;while(0);do if((q|0)==128){d=id(0)|0;if((d|0)!=(-1|0)?(c=d,o=b[5948]|0,p=o+-1|0,c=((p&c|0)==0?0:(p+c&0-o)-c|0)+k|0,o=b[5937]|0,p=c+o|0,c>>>0>m>>>0&c>>>0<2147483647):0){n=b[5939]|0;if(n|0?p>>>0<=o>>>0|p>>>0>n>>>0:0){c=0;break}a=id(c|0)|0;if((a|0)==(d|0)){h=c;g=d;q=145;break d}else{e=a;q=136}}else c=0}while(0);do if((q|0)==136){d=0-c|0;if(!(i>>>0>c>>>0&(c>>>0<2147483647&(e|0)!=(-1|0))))if((e|0)==(-1|0)){c=0;break}else{h=c;g=e;q=145;break d}a=b[5949]|0;a=j-c+a&0-a;if(a>>>0>=2147483647){h=c;g=e;q=145;break d}if((id(a|0)|0)==(-1|0)){id(d|0)|0;c=0;break}else{h=a+c|0;g=e;q=145;break d}}while(0);b[5940]=b[5940]|4;q=143}else{c=0;q=143}while(0);if(((q|0)==143?k>>>0<2147483647:0)?(t=id(k|0)|0,p=id(0)|0,r=p-t|0,s=r>>>0>(m+40|0)>>>0,!((t|0)==(-1|0)|s^1|t>>>0

>>0&((t|0)!=(-1|0)&(p|0)!=(-1|0))^1)):0){h=s?r:c;g=t;q=145}if((q|0)==145){c=(b[5937]|0)+h|0;b[5937]=c;if(c>>>0>(b[5938]|0)>>>0)b[5938]=c;j=b[5835]|0;f:do if(j){c=23764;while(1){a=b[c>>2]|0;d=b[c+4>>2]|0;if((g|0)==(a+d|0)){q=154;break}e=b[c+8>>2]|0;if(!e)break;else c=e}if(((q|0)==154?(u=c+4|0,(b[c+12>>2]&8|0)==0):0)?g>>>0>j>>>0&a>>>0<=j>>>0:0){b[u>>2]=d+h;v=(b[5832]|0)+h|0;t=j+8|0;t=(t&7|0)==0?0:0-t&7;u=j+t|0;t=v-t|0;b[5835]=u;b[5832]=t;b[u+4>>2]=t|1;b[j+v+4>>2]=40;b[5836]=b[5951];break}if(g>>>0<(b[5833]|0)>>>0)b[5833]=g;d=g+h|0;c=23764;while(1){if((b[c>>2]|0)==(d|0)){q=162;break}a=b[c+8>>2]|0;if(!a)break;else c=a}if((q|0)==162?(b[c+12>>2]&8|0)==0:0){b[c>>2]=g;l=c+4|0;b[l>>2]=(b[l>>2]|0)+h;l=g+8|0;l=g+((l&7|0)==0?0:0-l&7)|0;c=d+8|0;c=d+((c&7|0)==0?0:0-c&7)|0;k=l+m|0;i=c-l-m|0;b[l+4>>2]=m|3;g:do if((j|0)==(c|0)){v=(b[5832]|0)+i|0;b[5832]=v;b[5835]=k;b[k+4>>2]=v|1}else{if((b[5834]|0)==(c|0)){v=(b[5831]|0)+i|0;b[5831]=v;b[5834]=k;b[k+4>>2]=v|1;b[k+v>>2]=v;break}a=b[c+4>>2]|0;if((a&3|0)==1){h=a&-8;e=a>>>3;h:do if(a>>>0<256){a=b[c+8>>2]|0;d=b[c+12>>2]|0;if((d|0)==(a|0)){b[5829]=b[5829]&~(1<>2]=d;b[d+8>>2]=a;break}}else{g=b[c+24>>2]|0;a=b[c+12>>2]|0;do if((a|0)==(c|0)){d=c+16|0;e=d+4|0;a=b[e>>2]|0;if(!a){a=b[d>>2]|0;if(!a){a=0;break}}else d=e;while(1){f=a+20|0;e=b[f>>2]|0;if(!e){f=a+16|0;e=b[f>>2]|0;if(!e)break;else{a=e;d=f}}else{a=e;d=f}}b[d>>2]=0}else{v=b[c+8>>2]|0;b[v+12>>2]=a;b[a+8>>2]=v}while(0);if(!g)break;d=b[c+28>>2]|0;e=23620+(d<<2)|0;do if((b[e>>2]|0)!=(c|0)){v=g+16|0;b[((b[v>>2]|0)==(c|0)?v:g+20|0)>>2]=a;if(!a)break h}else{b[e>>2]=a;if(a|0)break;b[5830]=b[5830]&~(1<>2]=g;d=c+16|0;e=b[d>>2]|0;if(e|0){b[a+16>>2]=e;b[e+24>>2]=a}d=b[d+4>>2]|0;if(!d)break;b[a+20>>2]=d;b[d+24>>2]=a}while(0);c=c+h|0;f=h+i|0}else f=i;c=c+4|0;b[c>>2]=b[c>>2]&-2;b[k+4>>2]=f|1;b[k+f>>2]=f;c=f>>>3;if(f>>>0<256){d=23356+(c<<1<<2)|0;a=b[5829]|0;c=1<>2]|0}b[a>>2]=k;b[c+12>>2]=k;b[k+8>>2]=c;b[k+12>>2]=d;break}c=f>>>8;do if(!c)e=0;else{if(f>>>0>16777215){e=31;break}u=(c+1048320|0)>>>16&8;v=c<>>16&4;v=v<>>16&2;e=14-(t|u|e)+(v<>>15)|0;e=f>>>(e+7|0)&1|e<<1}while(0);c=23620+(e<<2)|0;b[k+28>>2]=e;a=k+16|0;b[a+4>>2]=0;b[a>>2]=0;a=b[5830]|0;d=1<>2]=k;b[k+24>>2]=c;b[k+12>>2]=k;b[k+8>>2]=k;break}c=b[c>>2]|0;i:do if((b[c+4>>2]&-8|0)!=(f|0)){e=f<<((e|0)==31?0:25-(e>>>1)|0);while(1){d=c+16+(e>>>31<<2)|0;a=b[d>>2]|0;if(!a)break;if((b[a+4>>2]&-8|0)==(f|0)){c=a;break i}else{e=e<<1;c=a}}b[d>>2]=k;b[k+24>>2]=c;b[k+12>>2]=k;b[k+8>>2]=k;break g}while(0);u=c+8|0;v=b[u>>2]|0;b[v+12>>2]=k;b[u>>2]=k;b[k+8>>2]=v;b[k+12>>2]=c;b[k+24>>2]=0}while(0);v=l+8|0;S=w;return v|0}c=23764;while(1){a=b[c>>2]|0;if(a>>>0<=j>>>0?(v=a+(b[c+4>>2]|0)|0,v>>>0>j>>>0):0)break;c=b[c+8>>2]|0}f=v+-47|0;a=f+8|0;a=f+((a&7|0)==0?0:0-a&7)|0;f=j+16|0;a=a>>>0>>0?j:a;c=a+8|0;d=h+-40|0;t=g+8|0;t=(t&7|0)==0?0:0-t&7;u=g+t|0;t=d-t|0;b[5835]=u;b[5832]=t;b[u+4>>2]=t|1;b[g+d+4>>2]=40;b[5836]=b[5951];d=a+4|0;b[d>>2]=27;b[c>>2]=b[5941];b[c+4>>2]=b[5942];b[c+8>>2]=b[5943];b[c+12>>2]=b[5944];b[5941]=g;b[5942]=h;b[5944]=0;b[5943]=c;c=a+24|0;do{u=c;c=c+4|0;b[c>>2]=7}while((u+8|0)>>>0>>0);if((a|0)!=(j|0)){g=a-j|0;b[d>>2]=b[d>>2]&-2;b[j+4>>2]=g|1;b[a>>2]=g;c=g>>>3;if(g>>>0<256){d=23356+(c<<1<<2)|0;a=b[5829]|0;c=1<>2]|0}b[a>>2]=j;b[c+12>>2]=j;b[j+8>>2]=c;b[j+12>>2]=d;break}c=g>>>8;if(c)if(g>>>0>16777215)e=31;else{u=(c+1048320|0)>>>16&8;v=c<>>16&4;v=v<>>16&2;e=14-(t|u|e)+(v<>>15)|0;e=g>>>(e+7|0)&1|e<<1}else e=0;d=23620+(e<<2)|0;b[j+28>>2]=e;b[j+20>>2]=0;b[f>>2]=0;c=b[5830]|0;a=1<>2]=j;b[j+24>>2]=d;b[j+12>>2]=j;b[j+8>>2]=j;break}c=b[d>>2]|0;j:do if((b[c+4>>2]&-8|0)!=(g|0)){e=g<<((e|0)==31?0:25-(e>>>1)|0);while(1){d=c+16+(e>>>31<<2)|0;a=b[d>>2]|0;if(!a)break;if((b[a+4>>2]&-8|0)==(g|0)){c=a;break j}else{e=e<<1;c=a}}b[d>>2]=j;b[j+24>>2]=c;b[j+12>>2]=j;b[j+8>>2]=j;break f}while(0);u=c+8|0;v=b[u>>2]|0;b[v+12>>2]=j;b[u>>2]=j;b[j+8>>2]=v;b[j+12>>2]=c;b[j+24>>2]=0}}else{v=b[5833]|0;if((v|0)==0|g>>>0>>0)b[5833]=g;b[5941]=g;b[5942]=h;b[5944]=0;b[5838]=b[5947];b[5837]=-1;b[5842]=23356;b[5841]=23356;b[5844]=23364;b[5843]=23364;b[5846]=23372;b[5845]=23372;b[5848]=23380;b[5847]=23380;b[5850]=23388;b[5849]=23388;b[5852]=23396;b[5851]=23396;b[5854]=23404;b[5853]=23404;b[5856]=23412;b[5855]=23412;b[5858]=23420;b[5857]=23420;b[5860]=23428;b[5859]=23428;b[5862]=23436;b[5861]=23436;b[5864]=23444;b[5863]=23444;b[5866]=23452;b[5865]=23452;b[5868]=23460;b[5867]=23460;b[5870]=23468;b[5869]=23468;b[5872]=23476;b[5871]=23476;b[5874]=23484;b[5873]=23484;b[5876]=23492;b[5875]=23492;b[5878]=23500;b[5877]=23500;b[5880]=23508;b[5879]=23508;b[5882]=23516;b[5881]=23516;b[5884]=23524;b[5883]=23524;b[5886]=23532;b[5885]=23532;b[5888]=23540;b[5887]=23540;b[5890]=23548;b[5889]=23548;b[5892]=23556;b[5891]=23556;b[5894]=23564;b[5893]=23564;b[5896]=23572;b[5895]=23572;b[5898]=23580;b[5897]=23580;b[5900]=23588;b[5899]=23588;b[5902]=23596;b[5901]=23596;b[5904]=23604;b[5903]=23604;v=h+-40|0;t=g+8|0;t=(t&7|0)==0?0:0-t&7;u=g+t|0;t=v-t|0;b[5835]=u;b[5832]=t;b[u+4>>2]=t|1;b[g+v+4>>2]=40;b[5836]=b[5951]}while(0);c=b[5832]|0;if(c>>>0>m>>>0){t=c-m|0;b[5832]=t;v=b[5835]|0;u=v+m|0;b[5835]=u;b[u+4>>2]=t|1;b[v+4>>2]=m|3;v=v+8|0;S=w;return v|0}}v=Sc()|0;b[v>>2]=12;v=0;S=w;return v|0}function Wc(a){a=a|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0;if(!a)return;d=a+-8|0;f=b[5833]|0;a=b[a+-4>>2]|0;c=a&-8;j=d+c|0;do if(!(a&1)){e=b[d>>2]|0;if(!(a&3))return;h=d+(0-e)|0;g=e+c|0;if(h>>>0>>0)return;if((b[5834]|0)==(h|0)){a=j+4|0;c=b[a>>2]|0;if((c&3|0)!=3){i=h;c=g;break}b[5831]=g;b[a>>2]=c&-2;b[h+4>>2]=g|1;b[h+g>>2]=g;return}d=e>>>3;if(e>>>0<256){a=b[h+8>>2]|0;c=b[h+12>>2]|0;if((c|0)==(a|0)){b[5829]=b[5829]&~(1<>2]=c;b[c+8>>2]=a;i=h;c=g;break}}f=b[h+24>>2]|0;a=b[h+12>>2]|0;do if((a|0)==(h|0)){c=h+16|0;d=c+4|0;a=b[d>>2]|0;if(!a){a=b[c>>2]|0;if(!a){a=0;break}}else c=d;while(1){e=a+20|0;d=b[e>>2]|0;if(!d){e=a+16|0;d=b[e>>2]|0;if(!d)break;else{a=d;c=e}}else{a=d;c=e}}b[c>>2]=0}else{i=b[h+8>>2]|0;b[i+12>>2]=a;b[a+8>>2]=i}while(0);if(f){c=b[h+28>>2]|0;d=23620+(c<<2)|0;if((b[d>>2]|0)==(h|0)){b[d>>2]=a;if(!a){b[5830]=b[5830]&~(1<>2]|0)==(h|0)?i:f+20|0)>>2]=a;if(!a){i=h;c=g;break}}b[a+24>>2]=f;c=h+16|0;d=b[c>>2]|0;if(d|0){b[a+16>>2]=d;b[d+24>>2]=a}c=b[c+4>>2]|0;if(c){b[a+20>>2]=c;b[c+24>>2]=a;i=h;c=g}else{i=h;c=g}}else{i=h;c=g}}else{i=d;h=d}while(0);if(h>>>0>=j>>>0)return;a=j+4|0;e=b[a>>2]|0;if(!(e&1))return;if(!(e&2)){if((b[5835]|0)==(j|0)){j=(b[5832]|0)+c|0;b[5832]=j;b[5835]=i;b[i+4>>2]=j|1;if((i|0)!=(b[5834]|0))return;b[5834]=0;b[5831]=0;return}if((b[5834]|0)==(j|0)){j=(b[5831]|0)+c|0;b[5831]=j;b[5834]=h;b[i+4>>2]=j|1;b[h+j>>2]=j;return}f=(e&-8)+c|0;d=e>>>3;do if(e>>>0<256){c=b[j+8>>2]|0;a=b[j+12>>2]|0;if((a|0)==(c|0)){b[5829]=b[5829]&~(1<>2]=a;b[a+8>>2]=c;break}}else{g=b[j+24>>2]|0;a=b[j+12>>2]|0;do if((a|0)==(j|0)){c=j+16|0;d=c+4|0;a=b[d>>2]|0;if(!a){a=b[c>>2]|0;if(!a){d=0;break}}else c=d;while(1){e=a+20|0;d=b[e>>2]|0;if(!d){e=a+16|0;d=b[e>>2]|0;if(!d)break;else{a=d;c=e}}else{a=d;c=e}}b[c>>2]=0;d=a}else{d=b[j+8>>2]|0;b[d+12>>2]=a;b[a+8>>2]=d;d=a}while(0);if(g|0){a=b[j+28>>2]|0;c=23620+(a<<2)|0;if((b[c>>2]|0)==(j|0)){b[c>>2]=d;if(!d){b[5830]=b[5830]&~(1<>2]|0)==(j|0)?e:g+20|0)>>2]=d;if(!d)break}b[d+24>>2]=g;a=j+16|0;c=b[a>>2]|0;if(c|0){b[d+16>>2]=c;b[c+24>>2]=d}a=b[a+4>>2]|0;if(a|0){b[d+20>>2]=a;b[a+24>>2]=d}}}while(0);b[i+4>>2]=f|1;b[h+f>>2]=f;if((i|0)==(b[5834]|0)){b[5831]=f;return}}else{b[a>>2]=e&-2;b[i+4>>2]=c|1;b[h+c>>2]=c;f=c}a=f>>>3;if(f>>>0<256){d=23356+(a<<1<<2)|0;c=b[5829]|0;a=1<>2]|0}b[c>>2]=i;b[a+12>>2]=i;b[i+8>>2]=a;b[i+12>>2]=d;return}a=f>>>8;if(a)if(f>>>0>16777215)e=31;else{h=(a+1048320|0)>>>16&8;j=a<>>16&4;j=j<>>16&2;e=14-(g|h|e)+(j<>>15)|0;e=f>>>(e+7|0)&1|e<<1}else e=0;a=23620+(e<<2)|0;b[i+28>>2]=e;b[i+20>>2]=0;b[i+16>>2]=0;c=b[5830]|0;d=1<>2]=i;b[i+24>>2]=a;b[i+12>>2]=i;b[i+8>>2]=i}else{a=b[a>>2]|0;b:do if((b[a+4>>2]&-8|0)!=(f|0)){e=f<<((e|0)==31?0:25-(e>>>1)|0);while(1){d=a+16+(e>>>31<<2)|0;c=b[d>>2]|0;if(!c)break;if((b[c+4>>2]&-8|0)==(f|0)){a=c;break b}else{e=e<<1;a=c}}b[d>>2]=i;b[i+24>>2]=a;b[i+12>>2]=i;b[i+8>>2]=i;break a}while(0);h=a+8|0;j=b[h>>2]|0;b[j+12>>2]=i;b[h>>2]=i;b[i+8>>2]=j;b[i+12>>2]=a;b[i+24>>2]=0}while(0);j=(b[5837]|0)+-1|0;b[5837]=j;if(j|0)return;a=23772;while(1){a=b[a>>2]|0;if(!a)break;else a=a+8|0}b[5837]=-1;return}function Xc(a,c){a=a|0;c=c|0;var d=0;if(a){d=B(c,a)|0;if((c|a)>>>0>65535)d=((d>>>0)/(a>>>0)|0|0)==(c|0)?d:-1}else d=0;a=Vc(d)|0;if(!a)return a|0;if(!(b[a+-4>>2]&3))return a|0;gd(a|0,0,d|0)|0;return a|0}function Yc(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;c=a+c>>>0;return (F(b+d+(c>>>0>>0|0)>>>0|0),c|0)|0}function Zc(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;d=b-d-(c>>>0>a>>>0|0)>>>0;return (F(d|0),a-c>>>0|0)|0}function _c(a){a=a|0;return (a?31-(D(a^a-1)|0)|0:32)|0}function $c(a,c,d,e,f){a=a|0;c=c|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;l=a;j=c;k=j;h=d;n=e;i=n;if(!k){g=(f|0)!=0;if(!i){if(g){b[f>>2]=(l>>>0)%(h>>>0);b[f+4>>2]=0}n=0;f=(l>>>0)/(h>>>0)>>>0;return (F(n|0),f)|0}else{if(!g){n=0;f=0;return (F(n|0),f)|0}b[f>>2]=a|0;b[f+4>>2]=c&0;n=0;f=0;return (F(n|0),f)|0}}g=(i|0)==0;do if(h){if(!g){g=(D(i|0)|0)-(D(k|0)|0)|0;if(g>>>0<=31){m=g+1|0;i=31-g|0;c=g-31>>31;h=m;a=l>>>(m>>>0)&c|k<>>(m>>>0)&c;g=0;i=l<>2]=a|0;b[f+4>>2]=j|c&0;n=0;f=0;return (F(n|0),f)|0}g=h-1|0;if(g&h|0){i=(D(h|0)|0)+33-(D(k|0)|0)|0;p=64-i|0;m=32-i|0;j=m>>31;o=i-32|0;c=o>>31;h=i;a=m-1>>31&k>>>(o>>>0)|(k<>>(i>>>0))&c;c=c&k>>>(i>>>0);g=l<>>(o>>>0))&j|l<>31;break}if(f|0){b[f>>2]=g&l;b[f+4>>2]=0}if((h|0)==1){o=j|c&0;p=a|0|0;return (F(o|0),p)|0}else{p=_c(h|0)|0;o=k>>>(p>>>0)|0;p=k<<32-p|l>>>(p>>>0)|0;return (F(o|0),p)|0}}else{if(g){if(f|0){b[f>>2]=(k>>>0)%(h>>>0);b[f+4>>2]=0}o=0;p=(k>>>0)/(h>>>0)>>>0;return (F(o|0),p)|0}if(!l){if(f|0){b[f>>2]=0;b[f+4>>2]=(k>>>0)%(i>>>0)}o=0;p=(k>>>0)/(i>>>0)>>>0;return (F(o|0),p)|0}g=i-1|0;if(!(g&i)){if(f|0){b[f>>2]=a|0;b[f+4>>2]=g&k|c&0}o=0;p=k>>>((_c(i|0)|0)>>>0);return (F(o|0),p)|0}g=(D(i|0)|0)-(D(k|0)|0)|0;if(g>>>0<=30){c=g+1|0;i=31-g|0;h=c;a=k<>>(c>>>0);c=k>>>(c>>>0);g=0;i=l<>2]=a|0;b[f+4>>2]=j|c&0;o=0;p=0;return (F(o|0),p)|0}while(0);if(!h){k=i;j=0;i=0}else{m=d|0|0;l=n|e&0;k=Yc(m|0,l|0,-1,-1)|0;d=G()|0;j=i;i=0;do{e=j;j=g>>>31|j<<1;g=i|g<<1;e=a<<1|e>>>31|0;n=a>>>31|c<<1|0;Zc(k|0,d|0,e|0,n|0)|0;p=G()|0;o=p>>31|((p|0)<0?-1:0)<<1;i=o&1;a=Zc(e|0,n|0,o&m|0,(((p|0)<0?-1:0)>>31|((p|0)<0?-1:0)<<1)&l|0)|0;c=G()|0;h=h-1|0}while((h|0)!=0);k=j;j=0}h=0;if(f|0){b[f>>2]=a;b[f+4>>2]=c}o=(g|0)>>>31|(k|h)<<1|(h<<1|g>>>31)&0|j;p=(g<<1|0>>>31)&-2|i;return (F(o|0),p)|0}function ad(a,c,d,e){a=a|0;c=c|0;d=d|0;e=e|0;var f=0,g=0;g=S;S=S+16|0;f=g|0;$c(a,c,d,e,f)|0;S=g;return (F(b[f+4>>2]|0),b[f>>2]|0)|0}function bd(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){F(b>>>c|0);return a>>>c|(b&(1<>>c-32|0}function cd(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){F(b<>>32-c|0);return a<=0.0?+p(a+.5):+A(a-.5)}function fd(c,d,e){c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0;if((e|0)>=8192){K(c|0,d|0,e|0)|0;return c|0}h=c|0;g=c+e|0;if((c&3)==(d&3)){while(c&3){if(!e)return h|0;a[c>>0]=a[d>>0]|0;c=c+1|0;d=d+1|0;e=e-1|0}e=g&-4|0;f=e-64|0;while((c|0)<=(f|0)){b[c>>2]=b[d>>2];b[c+4>>2]=b[d+4>>2];b[c+8>>2]=b[d+8>>2];b[c+12>>2]=b[d+12>>2];b[c+16>>2]=b[d+16>>2];b[c+20>>2]=b[d+20>>2];b[c+24>>2]=b[d+24>>2];b[c+28>>2]=b[d+28>>2];b[c+32>>2]=b[d+32>>2];b[c+36>>2]=b[d+36>>2];b[c+40>>2]=b[d+40>>2];b[c+44>>2]=b[d+44>>2];b[c+48>>2]=b[d+48>>2];b[c+52>>2]=b[d+52>>2];b[c+56>>2]=b[d+56>>2];b[c+60>>2]=b[d+60>>2];c=c+64|0;d=d+64|0}while((c|0)<(e|0)){b[c>>2]=b[d>>2];c=c+4|0;d=d+4|0}}else{e=g-4|0;while((c|0)<(e|0)){a[c>>0]=a[d>>0]|0;a[c+1>>0]=a[d+1>>0]|0;a[c+2>>0]=a[d+2>>0]|0;a[c+3>>0]=a[d+3>>0]|0;c=c+4|0;d=d+4|0}}while((c|0)<(g|0)){a[c>>0]=a[d>>0]|0;c=c+1|0;d=d+1|0}return h|0}function gd(c,d,e){c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0;h=c+e|0;d=d&255;if((e|0)>=67){while(c&3){a[c>>0]=d;c=c+1|0}f=h&-4|0;i=d|d<<8|d<<16|d<<24;g=f-64|0;while((c|0)<=(g|0)){b[c>>2]=i;b[c+4>>2]=i;b[c+8>>2]=i;b[c+12>>2]=i;b[c+16>>2]=i;b[c+20>>2]=i;b[c+24>>2]=i;b[c+28>>2]=i;b[c+32>>2]=i;b[c+36>>2]=i;b[c+40>>2]=i;b[c+44>>2]=i;b[c+48>>2]=i;b[c+52>>2]=i;b[c+56>>2]=i;b[c+60>>2]=i;c=c+64|0}while((c|0)<(f|0)){b[c>>2]=i;c=c+4|0}}while((c|0)<(h|0)){a[c>>0]=d;c=c+1|0}return h-e|0}function hd(a){a=+a;return a>=0.0?+p(a+.5):+A(a-.5)}function id(a){a=a|0;var c=0,d=0,e=0;e=J()|0;d=b[g>>2]|0;c=d+a|0;if((a|0)>0&(c|0)<(d|0)|(c|0)<0){M(c|0)|0;I(12);return -1}if((c|0)>(e|0))if(!(L(c|0)|0)){I(12);return -1}b[g>>2]=c;return d|0}\n\n// EMSCRIPTEN_END_FUNCS\nreturn{___uremdi3:ad,_bitshift64Lshr:bd,_bitshift64Shl:cd,_calloc:Xc,_cellAreaKm2:ub,_cellAreaM2:vb,_cellAreaRads2:tb,_compact:Gb,_destroyLinkedPolygon:ic,_edgeLengthKm:pb,_edgeLengthM:qb,_emscripten_replace_memory:V,_exactEdgeLengthKm:xb,_exactEdgeLengthM:yb,_exactEdgeLengthRads:wb,_experimentalH3ToLocalIj:nc,_experimentalLocalIjToH3:oc,_free:Wc,_geoToH3:Rb,_getDestinationH3IndexFromUnidirectionalEdge:bc,_getH3IndexesFromUnidirectionalEdge:dc,_getH3UnidirectionalEdge:$b,_getH3UnidirectionalEdgeBoundary:fc,_getH3UnidirectionalEdgesFromHexagon:ec,_getOriginH3IndexFromUnidirectionalEdge:ac,_getPentagonIndexes:Zb,_getRes0Indexes:va,_h3Distance:pc,_h3GetBaseCell:zb,_h3GetFaces:Xb,_h3IndexesAreNeighbors:_b,_h3IsPentagon:Eb,_h3IsResClassIII:Jb,_h3IsValid:Ab,_h3Line:rc,_h3LineSize:qc,_h3SetToLinkedGeo:ka,_h3ToCenterChild:Fb,_h3ToChildren:Db,_h3ToGeo:Ub,_h3ToGeoBoundary:Vb,_h3ToParent:Bb,_h3UnidirectionalEdgeIsValid:cc,_hexAreaKm2:nb,_hexAreaM2:ob,_hexRing:ea,_i64Subtract:Zc,_kRing:$,_kRingDistances:aa,_llvm_minnum_f64:dd,_llvm_round_f64:ed,_malloc:Vc,_maxFaceCount:Wb,_maxH3ToChildrenSize:Cb,_maxKringSize:_,_maxPolyfillSize:fa,_maxUncompactSize:Ib,_memcpy:fd,_memset:gd,_numHexagons:rb,_pentagonIndexCount:Yb,_pointDistKm:jb,_pointDistM:kb,_pointDistRads:ib,_polyfill:ga,_res0IndexCount:ua,_round:hd,_sbrk:id,_sizeOfCoordIJ:Dc,_sizeOfGeoBoundary:zc,_sizeOfGeoCoord:yc,_sizeOfGeoPolygon:Bc,_sizeOfGeofence:Ac,_sizeOfH3Index:xc,_sizeOfLinkedGeoPolygon:Cc,_uncompact:Hb,establishStackSpace:Z,stackAlloc:W,stackRestore:Y,stackSave:X}})\n\n\n// EMSCRIPTEN_END_ASM\n(asmGlobalArg,asmLibraryArg,buffer);var ___uremdi3=Module[\"___uremdi3\"]=asm[\"___uremdi3\"];var _bitshift64Lshr=Module[\"_bitshift64Lshr\"]=asm[\"_bitshift64Lshr\"];var _bitshift64Shl=Module[\"_bitshift64Shl\"]=asm[\"_bitshift64Shl\"];var _calloc=Module[\"_calloc\"]=asm[\"_calloc\"];var _cellAreaKm2=Module[\"_cellAreaKm2\"]=asm[\"_cellAreaKm2\"];var _cellAreaM2=Module[\"_cellAreaM2\"]=asm[\"_cellAreaM2\"];var _cellAreaRads2=Module[\"_cellAreaRads2\"]=asm[\"_cellAreaRads2\"];var _compact=Module[\"_compact\"]=asm[\"_compact\"];var _destroyLinkedPolygon=Module[\"_destroyLinkedPolygon\"]=asm[\"_destroyLinkedPolygon\"];var _edgeLengthKm=Module[\"_edgeLengthKm\"]=asm[\"_edgeLengthKm\"];var _edgeLengthM=Module[\"_edgeLengthM\"]=asm[\"_edgeLengthM\"];var _emscripten_replace_memory=Module[\"_emscripten_replace_memory\"]=asm[\"_emscripten_replace_memory\"];var _exactEdgeLengthKm=Module[\"_exactEdgeLengthKm\"]=asm[\"_exactEdgeLengthKm\"];var _exactEdgeLengthM=Module[\"_exactEdgeLengthM\"]=asm[\"_exactEdgeLengthM\"];var _exactEdgeLengthRads=Module[\"_exactEdgeLengthRads\"]=asm[\"_exactEdgeLengthRads\"];var _experimentalH3ToLocalIj=Module[\"_experimentalH3ToLocalIj\"]=asm[\"_experimentalH3ToLocalIj\"];var _experimentalLocalIjToH3=Module[\"_experimentalLocalIjToH3\"]=asm[\"_experimentalLocalIjToH3\"];var _free=Module[\"_free\"]=asm[\"_free\"];var _geoToH3=Module[\"_geoToH3\"]=asm[\"_geoToH3\"];var _getDestinationH3IndexFromUnidirectionalEdge=Module[\"_getDestinationH3IndexFromUnidirectionalEdge\"]=asm[\"_getDestinationH3IndexFromUnidirectionalEdge\"];var _getH3IndexesFromUnidirectionalEdge=Module[\"_getH3IndexesFromUnidirectionalEdge\"]=asm[\"_getH3IndexesFromUnidirectionalEdge\"];var _getH3UnidirectionalEdge=Module[\"_getH3UnidirectionalEdge\"]=asm[\"_getH3UnidirectionalEdge\"];var _getH3UnidirectionalEdgeBoundary=Module[\"_getH3UnidirectionalEdgeBoundary\"]=asm[\"_getH3UnidirectionalEdgeBoundary\"];var _getH3UnidirectionalEdgesFromHexagon=Module[\"_getH3UnidirectionalEdgesFromHexagon\"]=asm[\"_getH3UnidirectionalEdgesFromHexagon\"];var _getOriginH3IndexFromUnidirectionalEdge=Module[\"_getOriginH3IndexFromUnidirectionalEdge\"]=asm[\"_getOriginH3IndexFromUnidirectionalEdge\"];var _getPentagonIndexes=Module[\"_getPentagonIndexes\"]=asm[\"_getPentagonIndexes\"];var _getRes0Indexes=Module[\"_getRes0Indexes\"]=asm[\"_getRes0Indexes\"];var _h3Distance=Module[\"_h3Distance\"]=asm[\"_h3Distance\"];var _h3GetBaseCell=Module[\"_h3GetBaseCell\"]=asm[\"_h3GetBaseCell\"];var _h3GetFaces=Module[\"_h3GetFaces\"]=asm[\"_h3GetFaces\"];var _h3IndexesAreNeighbors=Module[\"_h3IndexesAreNeighbors\"]=asm[\"_h3IndexesAreNeighbors\"];var _h3IsPentagon=Module[\"_h3IsPentagon\"]=asm[\"_h3IsPentagon\"];var _h3IsResClassIII=Module[\"_h3IsResClassIII\"]=asm[\"_h3IsResClassIII\"];var _h3IsValid=Module[\"_h3IsValid\"]=asm[\"_h3IsValid\"];var _h3Line=Module[\"_h3Line\"]=asm[\"_h3Line\"];var _h3LineSize=Module[\"_h3LineSize\"]=asm[\"_h3LineSize\"];var _h3SetToLinkedGeo=Module[\"_h3SetToLinkedGeo\"]=asm[\"_h3SetToLinkedGeo\"];var _h3ToCenterChild=Module[\"_h3ToCenterChild\"]=asm[\"_h3ToCenterChild\"];var _h3ToChildren=Module[\"_h3ToChildren\"]=asm[\"_h3ToChildren\"];var _h3ToGeo=Module[\"_h3ToGeo\"]=asm[\"_h3ToGeo\"];var _h3ToGeoBoundary=Module[\"_h3ToGeoBoundary\"]=asm[\"_h3ToGeoBoundary\"];var _h3ToParent=Module[\"_h3ToParent\"]=asm[\"_h3ToParent\"];var _h3UnidirectionalEdgeIsValid=Module[\"_h3UnidirectionalEdgeIsValid\"]=asm[\"_h3UnidirectionalEdgeIsValid\"];var _hexAreaKm2=Module[\"_hexAreaKm2\"]=asm[\"_hexAreaKm2\"];var _hexAreaM2=Module[\"_hexAreaM2\"]=asm[\"_hexAreaM2\"];var _hexRing=Module[\"_hexRing\"]=asm[\"_hexRing\"];var _i64Subtract=Module[\"_i64Subtract\"]=asm[\"_i64Subtract\"];var _kRing=Module[\"_kRing\"]=asm[\"_kRing\"];var _kRingDistances=Module[\"_kRingDistances\"]=asm[\"_kRingDistances\"];var _llvm_minnum_f64=Module[\"_llvm_minnum_f64\"]=asm[\"_llvm_minnum_f64\"];var _llvm_round_f64=Module[\"_llvm_round_f64\"]=asm[\"_llvm_round_f64\"];var _malloc=Module[\"_malloc\"]=asm[\"_malloc\"];var _maxFaceCount=Module[\"_maxFaceCount\"]=asm[\"_maxFaceCount\"];var _maxH3ToChildrenSize=Module[\"_maxH3ToChildrenSize\"]=asm[\"_maxH3ToChildrenSize\"];var _maxKringSize=Module[\"_maxKringSize\"]=asm[\"_maxKringSize\"];var _maxPolyfillSize=Module[\"_maxPolyfillSize\"]=asm[\"_maxPolyfillSize\"];var _maxUncompactSize=Module[\"_maxUncompactSize\"]=asm[\"_maxUncompactSize\"];var _memcpy=Module[\"_memcpy\"]=asm[\"_memcpy\"];var _memset=Module[\"_memset\"]=asm[\"_memset\"];var _numHexagons=Module[\"_numHexagons\"]=asm[\"_numHexagons\"];var _pentagonIndexCount=Module[\"_pentagonIndexCount\"]=asm[\"_pentagonIndexCount\"];var _pointDistKm=Module[\"_pointDistKm\"]=asm[\"_pointDistKm\"];var _pointDistM=Module[\"_pointDistM\"]=asm[\"_pointDistM\"];var _pointDistRads=Module[\"_pointDistRads\"]=asm[\"_pointDistRads\"];var _polyfill=Module[\"_polyfill\"]=asm[\"_polyfill\"];var _res0IndexCount=Module[\"_res0IndexCount\"]=asm[\"_res0IndexCount\"];var _round=Module[\"_round\"]=asm[\"_round\"];var _sbrk=Module[\"_sbrk\"]=asm[\"_sbrk\"];var _sizeOfCoordIJ=Module[\"_sizeOfCoordIJ\"]=asm[\"_sizeOfCoordIJ\"];var _sizeOfGeoBoundary=Module[\"_sizeOfGeoBoundary\"]=asm[\"_sizeOfGeoBoundary\"];var _sizeOfGeoCoord=Module[\"_sizeOfGeoCoord\"]=asm[\"_sizeOfGeoCoord\"];var _sizeOfGeoPolygon=Module[\"_sizeOfGeoPolygon\"]=asm[\"_sizeOfGeoPolygon\"];var _sizeOfGeofence=Module[\"_sizeOfGeofence\"]=asm[\"_sizeOfGeofence\"];var _sizeOfH3Index=Module[\"_sizeOfH3Index\"]=asm[\"_sizeOfH3Index\"];var _sizeOfLinkedGeoPolygon=Module[\"_sizeOfLinkedGeoPolygon\"]=asm[\"_sizeOfLinkedGeoPolygon\"];var _uncompact=Module[\"_uncompact\"]=asm[\"_uncompact\"];var establishStackSpace=Module[\"establishStackSpace\"]=asm[\"establishStackSpace\"];var stackAlloc=Module[\"stackAlloc\"]=asm[\"stackAlloc\"];var stackRestore=Module[\"stackRestore\"]=asm[\"stackRestore\"];var stackSave=Module[\"stackSave\"]=asm[\"stackSave\"];Module[\"asm\"]=asm;Module[\"cwrap\"]=cwrap;Module[\"setValue\"]=setValue;Module[\"getValue\"]=getValue;Module[\"getTempRet0\"]=getTempRet0;if(memoryInitializer){if(!isDataURI(memoryInitializer)){memoryInitializer=locateFile(memoryInitializer)}if(ENVIRONMENT_IS_NODE||ENVIRONMENT_IS_SHELL){var data=readBinary(memoryInitializer);HEAPU8.set(data,GLOBAL_BASE)}else{addRunDependency(\"memory initializer\");var applyMemoryInitializer=function(data){if(data.byteLength)data=new Uint8Array(data);HEAPU8.set(data,GLOBAL_BASE);if(Module[\"memoryInitializerRequest\"])delete Module[\"memoryInitializerRequest\"].response;removeRunDependency(\"memory initializer\")};var doBrowserLoad=function(){readAsync(memoryInitializer,applyMemoryInitializer,function(){throw\"could not load memory initializer \"+memoryInitializer})};var memoryInitializerBytes=tryParseAsDataURI(memoryInitializer);if(memoryInitializerBytes){applyMemoryInitializer(memoryInitializerBytes.buffer)}else if(Module[\"memoryInitializerRequest\"]){var useRequest=function(){var request=Module[\"memoryInitializerRequest\"];var response=request.response;if(request.status!==200&&request.status!==0){var data=tryParseAsDataURI(Module[\"memoryInitializerRequestURL\"]);if(data){response=data.buffer}else{console.warn(\"a problem seems to have happened with Module.memoryInitializerRequest, status: \"+request.status+\", retrying \"+memoryInitializer);doBrowserLoad();return}}applyMemoryInitializer(response)};if(Module[\"memoryInitializerRequest\"].response){setTimeout(useRequest,0)}else{Module[\"memoryInitializerRequest\"].addEventListener(\"load\",useRequest)}}else{doBrowserLoad()}}}var calledRun;function ExitStatus(status){this.name=\"ExitStatus\";this.message=\"Program terminated with exit(\"+status+\")\";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0)return;function doRun(){if(calledRun)return;calledRun=true;if(ABORT)return;initRuntime();preMain();if(Module[\"onRuntimeInitialized\"])Module[\"onRuntimeInitialized\"]();postRun()}if(Module[\"setStatus\"]){Module[\"setStatus\"](\"Running...\");setTimeout(function(){setTimeout(function(){Module[\"setStatus\"](\"\")},1);doRun()},1)}else{doRun()}}Module[\"run\"]=run;function abort(what){if(Module[\"onAbort\"]){Module[\"onAbort\"](what)}what+=\"\";out(what);err(what);ABORT=true;EXITSTATUS=1;throw\"abort(\"+what+\"). Build with -s ASSERTIONS=1 for more info.\"}Module[\"abort\"]=abort;if(Module[\"preInit\"]){if(typeof Module[\"preInit\"]==\"function\")Module[\"preInit\"]=[Module[\"preInit\"]];while(Module[\"preInit\"].length>0){Module[\"preInit\"].pop()()}}noExitRuntime=true;run();\n\n\n\n return libh3\n}\n)(typeof libh3 === 'object' ? libh3 : {});\nexport default libh3;","/*\n * Copyright 2018-2019 Uber Technologies, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Define the C bindings for the h3 library\n\n// Add some aliases to make the function definitions more intelligible\nconst NUMBER = 'number';\nconst BOOLEAN = NUMBER;\nconst H3_LOWER = NUMBER;\nconst H3_UPPER = NUMBER;\nconst RESOLUTION = NUMBER;\nconst POINTER = NUMBER;\n\n// Define the bindings to functions in the C lib. Functions are defined as\n// [name, return type, [arg types]]. You must run `npm run build-emscripten`\n// before new functions added here will be available.\nexport default [\n // The size functions are inserted via build/sizes.h\n ['sizeOfH3Index', NUMBER],\n ['sizeOfGeoCoord', NUMBER],\n ['sizeOfGeoBoundary', NUMBER],\n ['sizeOfGeoPolygon', NUMBER],\n ['sizeOfGeofence', NUMBER],\n ['sizeOfLinkedGeoPolygon', NUMBER],\n ['sizeOfCoordIJ', NUMBER],\n // The remaining functions are defined in the core lib in h3Api.h\n ['h3IsValid', BOOLEAN, [H3_LOWER, H3_UPPER]],\n ['geoToH3', H3_LOWER, [NUMBER, NUMBER, RESOLUTION]],\n ['h3ToGeo', null, [H3_LOWER, H3_UPPER, POINTER]],\n ['h3ToGeoBoundary', null, [H3_LOWER, H3_UPPER, POINTER]],\n ['maxKringSize', NUMBER, [NUMBER]],\n ['kRing', null, [H3_LOWER, H3_UPPER, NUMBER, POINTER]],\n ['kRingDistances', null, [H3_LOWER, H3_UPPER, NUMBER, POINTER, POINTER]],\n ['hexRing', null, [H3_LOWER, H3_UPPER, NUMBER, POINTER]],\n ['maxPolyfillSize', NUMBER, [POINTER, RESOLUTION]],\n ['polyfill', null, [POINTER, RESOLUTION, POINTER]],\n ['h3SetToLinkedGeo', null, [POINTER, NUMBER, POINTER]],\n ['destroyLinkedPolygon', null, [POINTER]],\n ['compact', NUMBER, [POINTER, POINTER, NUMBER]],\n ['uncompact', NUMBER, [POINTER, NUMBER, POINTER, NUMBER, RESOLUTION]],\n ['maxUncompactSize', NUMBER, [POINTER, NUMBER, RESOLUTION]],\n ['h3IsPentagon', BOOLEAN, [H3_LOWER, H3_UPPER]],\n ['h3IsResClassIII', BOOLEAN, [H3_LOWER, H3_UPPER]],\n ['h3GetBaseCell', NUMBER, [H3_LOWER, H3_UPPER]],\n ['maxFaceCount', NUMBER, [H3_LOWER, H3_UPPER]],\n ['h3GetFaces', null, [H3_LOWER, H3_UPPER, POINTER]],\n ['h3ToParent', H3_LOWER, [H3_LOWER, H3_UPPER, RESOLUTION]],\n ['h3ToChildren', null, [H3_LOWER, H3_UPPER, RESOLUTION, POINTER]],\n ['h3ToCenterChild', H3_LOWER, [H3_LOWER, H3_UPPER, RESOLUTION]],\n ['maxH3ToChildrenSize', NUMBER, [H3_LOWER, H3_UPPER, RESOLUTION]],\n ['h3IndexesAreNeighbors', BOOLEAN, [H3_LOWER, H3_UPPER, H3_LOWER, H3_UPPER]],\n ['getH3UnidirectionalEdge', H3_LOWER, [H3_LOWER, H3_UPPER, H3_LOWER, H3_UPPER]],\n ['getOriginH3IndexFromUnidirectionalEdge', H3_LOWER, [H3_LOWER, H3_UPPER]],\n ['getDestinationH3IndexFromUnidirectionalEdge', H3_LOWER, [H3_LOWER, H3_UPPER]],\n ['h3UnidirectionalEdgeIsValid', BOOLEAN, [H3_LOWER, H3_UPPER]],\n ['getH3IndexesFromUnidirectionalEdge', null, [H3_LOWER, H3_UPPER, POINTER]],\n ['getH3UnidirectionalEdgesFromHexagon', null, [H3_LOWER, H3_UPPER, POINTER]],\n ['getH3UnidirectionalEdgeBoundary', null, [H3_LOWER, H3_UPPER, POINTER]],\n ['h3Distance', NUMBER, [H3_LOWER, H3_UPPER, H3_LOWER, H3_UPPER]],\n ['h3Line', NUMBER, [H3_LOWER, H3_UPPER, H3_LOWER, H3_UPPER, POINTER]],\n ['h3LineSize', NUMBER, [H3_LOWER, H3_UPPER, H3_LOWER, H3_UPPER]],\n ['experimentalH3ToLocalIj', NUMBER, [H3_LOWER, H3_UPPER, H3_LOWER, H3_UPPER, POINTER]],\n ['experimentalLocalIjToH3', NUMBER, [H3_LOWER, H3_UPPER, POINTER, POINTER]],\n ['hexAreaM2', NUMBER, [RESOLUTION]],\n ['hexAreaKm2', NUMBER, [RESOLUTION]],\n ['edgeLengthM', NUMBER, [RESOLUTION]],\n ['edgeLengthKm', NUMBER, [RESOLUTION]],\n ['pointDistM', NUMBER, [POINTER, POINTER]],\n ['pointDistKm', NUMBER, [POINTER, POINTER]],\n ['pointDistRads', NUMBER, [POINTER, POINTER]],\n ['cellAreaM2', NUMBER, [H3_LOWER, H3_UPPER]],\n ['cellAreaKm2', NUMBER, [H3_LOWER, H3_UPPER]],\n ['cellAreaRads2', NUMBER, [H3_LOWER, H3_UPPER]],\n ['exactEdgeLengthM', NUMBER, [H3_LOWER, H3_UPPER]],\n ['exactEdgeLengthKm', NUMBER, [H3_LOWER, H3_UPPER]],\n ['exactEdgeLengthRads', NUMBER, [H3_LOWER, H3_UPPER]],\n ['numHexagons', NUMBER, [RESOLUTION]],\n ['getRes0Indexes', null, [POINTER]],\n ['res0IndexCount', NUMBER],\n ['getPentagonIndexes', null, [NUMBER, POINTER]],\n ['pentagonIndexCount', NUMBER]\n];\n","/*\n * Copyright 2018-2019 Uber Technologies, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @module h3\n */\n\nimport C from '../out/libh3';\nimport BINDINGS from './bindings';\n\nconst H3 = {};\n\n// Create the bound functions themselves\nBINDINGS.forEach(function bind(def) {\n H3[def[0]] = C.cwrap(...def);\n});\n\n// Alias the hexidecimal base for legibility\nconst BASE_16 = 16;\n\n// ----------------------------------------------------------------------------\n// Byte size imports\n\nconst SZ_INT = 4;\nconst SZ_PTR = 4;\nconst SZ_DBL = 8;\nconst SZ_H3INDEX = H3.sizeOfH3Index();\nconst SZ_GEOCOORD = H3.sizeOfGeoCoord();\nconst SZ_GEOBOUNDARY = H3.sizeOfGeoBoundary();\nconst SZ_GEOPOLYGON = H3.sizeOfGeoPolygon();\nconst SZ_GEOFENCE = H3.sizeOfGeofence();\nconst SZ_LINKED_GEOPOLYGON = H3.sizeOfLinkedGeoPolygon();\nconst SZ_COORDIJ = H3.sizeOfCoordIJ();\n\n// ----------------------------------------------------------------------------\n// Custom types\n\n/**\n * 64-bit hexidecimal string representation of an H3 index\n * @static\n * @typedef {string} H3Index\n */\n\n/**\n * 64-bit hexidecimal string representation of an H3 index,\n * or two 32-bit integers in little endian order in an array.\n * @static\n * @typedef {string | number[]} H3IndexInput\n */\n\n/**\n * Coordinates as an `{i, j}` pair\n * @static\n * @typedef CoordIJ\n * @type {Object}\n * @property {number} i\n * @property {number} j\n */\n\n// ----------------------------------------------------------------------------\n// Unit constants\n\n/**\n * Length/Area units\n * @static\n * @typedef UNITS\n * @type {Object}\n * @property {string} m\n * @property {string} m2\n * @property {string} km\n * @property {string} km2\n * @property {string} rads\n * @property {string} rads2\n */\nexport const UNITS = {\n m: 'm',\n m2: 'm2',\n km: 'km',\n km2: 'km2',\n rads: 'rads',\n rads2: 'rads2'\n};\n\n// ----------------------------------------------------------------------------\n// Utilities and helpers\n\n/**\n * Validate a resolution, throwing an error if invalid\n * @private\n * @param {mixed} res Value to validate\n * @throws {Error} Error if invalid\n */\nfunction validateRes(res) {\n if (typeof res !== 'number' || res < 0 || res > 15 || Math.floor(res) !== res) {\n throw new Error(`Invalid resolution: ${res}`);\n }\n}\n\nconst INVALID_HEXIDECIMAL_CHAR = /[^0-9a-fA-F]/;\n\n/**\n * Convert an H3 index (64-bit hexidecimal string) into a \"split long\" - a pair of 32-bit ints\n * @private\n * @param {H3IndexInput} h3Index H3 index to check\n * @return {number[]} A two-element array with 32 lower bits and 32 upper bits\n */\nfunction h3IndexToSplitLong(h3Index) {\n if (\n Array.isArray(h3Index) &&\n h3Index.length === 2 &&\n Number.isInteger(h3Index[0]) &&\n Number.isInteger(h3Index[1])\n ) {\n return h3Index;\n }\n if (typeof h3Index !== 'string' || INVALID_HEXIDECIMAL_CHAR.test(h3Index)) {\n return [0, 0];\n }\n const upper = parseInt(h3Index.substring(0, h3Index.length - 8), BASE_16);\n const lower = parseInt(h3Index.substring(h3Index.length - 8), BASE_16);\n return [lower, upper];\n}\n\n/**\n * Convert a 32-bit int to a hexdecimal string\n * @private\n * @param {number} num Integer to convert\n * @return {H3Index} Hexidecimal string\n */\nfunction hexFrom32Bit(num) {\n if (num >= 0) {\n return num.toString(BASE_16);\n }\n\n // Handle negative numbers\n num = num & 0x7fffffff;\n let tempStr = zeroPad(8, num.toString(BASE_16));\n const topNum = (parseInt(tempStr[0], BASE_16) + 8).toString(BASE_16);\n tempStr = topNum + tempStr.substring(1);\n return tempStr;\n}\n\n/**\n * Get a H3 index from a split long (pair of 32-bit ints)\n * @private\n * @param {number} lower Lower 32 bits\n * @param {number} upper Upper 32 bits\n * @return {H3Index} H3 index\n */\nfunction splitLongToh3Index(lower, upper) {\n return hexFrom32Bit(upper) + zeroPad(8, hexFrom32Bit(lower));\n}\n\n/**\n * Zero-pad a string to a given length\n * @private\n * @param {number} fullLen Target length\n * @param {string} numStr String to zero-pad\n * @return {string} Zero-padded string\n */\nfunction zeroPad(fullLen, numStr) {\n const numZeroes = fullLen - numStr.length;\n let outStr = '';\n for (let i = 0; i < numZeroes; i++) {\n outStr += '0';\n }\n outStr = outStr + numStr;\n return outStr;\n}\n\n/**\n * Populate a C-appropriate Geofence struct from a polygon array\n * @private\n * @param {Array[]} polygonArray Polygon, as an array of coordinate pairs\n * @param {number} geofence C pointer to a Geofence struct\n * @param {boolean} isGeoJson Whether coordinates are in [lng, lat] order per GeoJSON spec\n * @return {number} C pointer to populated Geofence struct\n */\nfunction polygonArrayToGeofence(polygonArray, geofence, isGeoJson) {\n const numVerts = polygonArray.length;\n const geoCoordArray = C._calloc(numVerts, SZ_GEOCOORD);\n // Support [lng, lat] pairs if GeoJSON is specified\n const latIndex = isGeoJson ? 1 : 0;\n const lngIndex = isGeoJson ? 0 : 1;\n for (let i = 0; i < numVerts * 2; i += 2) {\n C.HEAPF64.set(\n [polygonArray[i / 2][latIndex], polygonArray[i / 2][lngIndex]].map(degsToRads),\n geoCoordArray / SZ_DBL + i\n );\n }\n C.HEAPU32.set([numVerts, geoCoordArray], geofence / SZ_INT);\n return geofence;\n}\n\n/**\n * Create a C-appropriate GeoPolygon struct from an array of polygons\n * @private\n * @param {Array[]} coordinates Array of polygons, each an array of coordinate pairs\n * @param {boolean} isGeoJson Whether coordinates are in [lng, lat] order per GeoJSON spec\n * @return {number} C pointer to populated GeoPolygon struct\n */\nfunction coordinatesToGeoPolygon(coordinates, isGeoJson) {\n // Any loops beyond the first loop are holes\n const numHoles = coordinates.length - 1;\n const geoPolygon = C._calloc(SZ_GEOPOLYGON);\n // Byte positions within the struct\n const geofenceOffset = 0;\n const numHolesOffset = geofenceOffset + SZ_GEOFENCE;\n const holesOffset = numHolesOffset + SZ_INT;\n // geofence is first part of struct\n polygonArrayToGeofence(coordinates[0], geoPolygon + geofenceOffset, isGeoJson);\n let holes;\n if (numHoles > 0) {\n holes = C._calloc(numHoles, SZ_GEOFENCE);\n for (let i = 0; i < numHoles; i++) {\n polygonArrayToGeofence(coordinates[i + 1], holes + SZ_GEOFENCE * i, isGeoJson);\n }\n }\n C.setValue(geoPolygon + numHolesOffset, numHoles, 'i32');\n C.setValue(geoPolygon + holesOffset, holes, 'i32');\n return geoPolygon;\n}\n\n/**\n * Free memory allocated for a GeoPolygon struct. It is an error to access the struct\n * after passing it to this method.\n * @private\n * @return {number} geoPolygon C pointer to populated GeoPolygon struct\n */\nfunction destroyGeoPolygon(geoPolygon) {\n // Byte positions within the struct\n const geofenceOffset = 0;\n const numHolesOffset = geofenceOffset + SZ_GEOFENCE;\n const holesOffset = numHolesOffset + SZ_INT;\n // Free the outer loop\n C._free(C.getValue(geoPolygon + geofenceOffset, 'i8*'));\n // Free the holes, if any\n const numHoles = C.getValue(geoPolygon + numHolesOffset, 'i32');\n for (let i = 0; i < numHoles; i++) {\n C._free(C.getValue(geoPolygon + holesOffset + SZ_GEOFENCE * i, 'i8*'));\n }\n C._free(geoPolygon);\n}\n\n/**\n * Read a long value, returning the lower and upper portions as separate 32-bit integers.\n * Because the upper bits are returned via side effect, the argument to this function is\n * intended to be the invocation that caused the side effect, e.g. readLong(H3.getSomeLong())\n * @private\n * @param {number} invocation Invoked function returning a long value. The actual return\n * value of these functions is a 32-bit integer.\n * @return {number} Long value as a [lower, upper] pair\n */\nfunction readLong(invocation) {\n // Upper 32-bits of the long set via side-effect\n const upper = C.getTempRet0();\n return [invocation, upper];\n}\n\n/**\n * Read an H3 index from a C return value. As with readLong, the argument to this function\n * is intended to be an invocation, e.g. readH3Index(H3.getSomeAddress()), to help ensure that\n * the temp value storing the upper bits of the long is still set.\n * @private\n * @param {number} invocation Invoked function returning a single H3 index\n * @return {H3Index} H3 index, or null if index was invalid\n */\nfunction readH3Index(invocation) {\n const [lower, upper] = readLong(invocation);\n // The lower bits are allowed to be 0s, but if the upper bits are 0\n // this represents an invalid H3 index\n return upper ? splitLongToh3Index(lower, upper) : null;\n}\n\n/**\n * Read an H3 index from a pointer to C memory.\n * @private\n * @param {number} cAddress Pointer to allocated C memory\n * @param {number} offset Offset, in number of H3 indexes, in case we're\n * reading an array\n * @return {H3Index} H3 index, or null if index was invalid\n */\nfunction readH3IndexFromPointer(cAddress, offset = 0) {\n const lower = C.getValue(cAddress + SZ_INT * offset * 2, 'i32');\n const upper = C.getValue(cAddress + SZ_INT * (offset * 2 + 1), 'i32');\n // The lower bits are allowed to be 0s, but if the upper bits are 0\n // this represents an invalid H3 index\n return upper ? splitLongToh3Index(lower, upper) : null;\n}\n\n/**\n * Store an H3 index in C memory. Primarily used as an efficient way to\n * write sets of hexagons.\n * @private\n * @param {H3IndexInput} h3Index H3 index to store\n * @param {number} cAddress Pointer to allocated C memory\n * @param {number} offset Offset, in number of H3 indexes from beginning\n * of the current array\n */\nfunction storeH3Index(h3Index, cAddress, offset) {\n // HEAPU32 is a typed array projection on the index space\n // as unsigned 32-bit integers. This means the index needs\n // to be divided by SZ_INT (4) to access correctly. Also,\n // the H3 index is 64 bits, so we skip by twos as we're writing\n // to 32-bit integers in the proper order.\n C.HEAPU32.set(h3IndexToSplitLong(h3Index), cAddress / SZ_INT + 2 * offset);\n}\n\n/**\n * Read an array of 64-bit H3 indexes from C and convert to a JS array of\n * H3 index strings\n * @private\n * @param {number} cAddress Pointer to C ouput array\n * @param {number} maxCount Max number of hexagons in array. Hexagons with\n * the value 0 will be skipped, so this isn't\n * necessarily the length of the output array.\n * @return {H3Index[]} Array of H3 indexes\n */\nfunction readArrayOfHexagons(cAddress, maxCount) {\n const out = [];\n for (let i = 0; i < maxCount; i++) {\n const h3Index = readH3IndexFromPointer(cAddress, i);\n if (h3Index !== null) {\n out.push(h3Index);\n }\n }\n return out;\n}\n\n/**\n * Store an array of H3 index strings as a C array of 64-bit integers.\n * @private\n * @param {number} cAddress Pointer to C input array\n * @param {H3IndexInput[]} hexagons H3 indexes to pass to the C lib\n */\nfunction storeArrayOfHexagons(cAddress, hexagons) {\n // Assuming the cAddress points to an already appropriately\n // allocated space\n const count = hexagons.length;\n for (let i = 0; i < count; i++) {\n storeH3Index(hexagons[i], cAddress, i);\n }\n}\n\n/**\n * Populate a C-appropriate GeoCoord struct from a [lat, lng] array\n * @private\n * @param {number} lat Coordinate latitude\n * @param {number} lng Coordinate longitude\n * @return {number} C pointer to populated GeoCoord struct\n */\nfunction storeGeoCoord(lat, lng) {\n const geoCoord = C._calloc(1, SZ_GEOCOORD);\n C.HEAPF64.set([lat, lng].map(degsToRads), geoCoord / SZ_DBL);\n return geoCoord;\n}\n\nfunction readSingleCoord(cAddress) {\n return radsToDegs(C.getValue(cAddress, 'double'));\n}\n\n/**\n * Read a GeoCoord from C and return a [lat, lng] pair.\n * @private\n * @param {number} cAddress Pointer to C struct\n * @return {number[]} [lat, lng] pair\n */\nfunction readGeoCoord(cAddress) {\n return [readSingleCoord(cAddress), readSingleCoord(cAddress + SZ_DBL)];\n}\n\n/**\n * Read a GeoCoord from C and return a GeoJSON-style [lng, lat] pair.\n * @private\n * @param {number} cAddress Pointer to C struct\n * @return {number[]} [lng, lat] pair\n */\nfunction readGeoCoordGeoJson(cAddress) {\n return [readSingleCoord(cAddress + SZ_DBL), readSingleCoord(cAddress)];\n}\n\n/**\n * Read the GeoBoundary structure into a list of geo coordinate pairs\n * @private\n * @param {number} geoBoundary C pointer to GeoBoundary struct\n * @param {boolean} geoJsonCoords Whether to provide GeoJSON coordinate order: [lng, lat]\n * @param {boolean} closedLoop Whether to close the loop\n * @return {Array[]} Array of geo coordinate pairs\n */\nfunction readGeoBoundary(geoBoundary, geoJsonCoords, closedLoop) {\n const numVerts = C.getValue(geoBoundary, 'i32');\n // Note that though numVerts is an int, the coordinate doubles have to be\n // aligned to 8 bytes, hence the 8-byte offset here\n const vertsPos = geoBoundary + SZ_DBL;\n const out = [];\n // Support [lng, lat] pairs if GeoJSON is specified\n const readCoord = geoJsonCoords ? readGeoCoordGeoJson : readGeoCoord;\n for (let i = 0; i < numVerts * 2; i += 2) {\n out.push(readCoord(vertsPos + SZ_DBL * i));\n }\n if (closedLoop) {\n // Close loop if GeoJSON is specified\n out.push(out[0]);\n }\n return out;\n}\n\n/**\n * Read the LinkedGeoPolygon structure into a nested array of MultiPolygon coordinates\n * @private\n * @param {number} polygon C pointer to LinkedGeoPolygon struct\n * @param {boolean} formatAsGeoJson Whether to provide GeoJSON output: [lng, lat], closed loops\n * @return {number[][][][]} MultiPolygon-style output.\n */\nfunction readMultiPolygon(polygon, formatAsGeoJson) {\n const output = [];\n const readCoord = formatAsGeoJson ? readGeoCoordGeoJson : readGeoCoord;\n let loops;\n let loop;\n let coords;\n let coord;\n // Loop through the linked structure, building the output\n while (polygon) {\n output.push((loops = []));\n // Follow ->first pointer\n loop = C.getValue(polygon, 'i8*');\n while (loop) {\n loops.push((coords = []));\n // Follow ->first pointer\n coord = C.getValue(loop, 'i8*');\n while (coord) {\n coords.push(readCoord(coord));\n // Follow ->next pointer\n coord = C.getValue(coord + SZ_DBL * 2, 'i8*');\n }\n if (formatAsGeoJson) {\n // Close loop if GeoJSON is requested\n coords.push(coords[0]);\n }\n // Follow ->next pointer\n loop = C.getValue(loop + SZ_PTR * 2, 'i8*');\n }\n // Follow ->next pointer\n polygon = C.getValue(polygon + SZ_PTR * 2, 'i8*');\n }\n return output;\n}\n\n/**\n * Read a CoordIJ from C and return an {i, j} pair.\n * @private\n * @param {number} cAddress Pointer to C struct\n * @return {CoordIJ} {i, j} pair\n */\nfunction readCoordIJ(cAddress) {\n return {\n i: C.getValue(cAddress, 'i32'),\n j: C.getValue(cAddress + SZ_INT, 'i32')\n };\n}\n\n/**\n * Store an {i, j} pair to a C CoordIJ struct.\n * @private\n * @param {number} cAddress Pointer to C struct\n * @return {CoordIJ} {i, j} pair\n */\nfunction storeCoordIJ(cAddress, {i, j}) {\n C.setValue(cAddress, i, 'i32');\n C.setValue(cAddress + SZ_INT, j, 'i32');\n}\n\n/**\n * Read an array of positive integers array from C. Negative\n * values are considered invalid and ignored in output.\n * @private\n * @param {number} cAddress Pointer to C array\n * @param {number} count Length of C array\n * @return {number[]} Javascript integer array\n */\nfunction readArrayOfPositiveIntegers(cAddress, count) {\n const out = [];\n for (let i = 0; i < count; i++) {\n const int = C.getValue(cAddress + SZ_INT * i, 'i32');\n if (int >= 0) {\n out.push(int);\n }\n }\n return out;\n}\n\n// ----------------------------------------------------------------------------\n// Public API functions: Core\n\n/**\n * Whether a given string represents a valid H3 index\n * @static\n * @param {H3IndexInput} h3Index H3 index to check\n * @return {boolean} Whether the index is valid\n */\nexport function h3IsValid(h3Index) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n return Boolean(H3.h3IsValid(lower, upper));\n}\n\n/**\n * Whether the given H3 index is a pentagon\n * @static\n * @param {H3IndexInput} h3Index H3 index to check\n * @return {boolean} isPentagon\n */\nexport function h3IsPentagon(h3Index) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n return Boolean(H3.h3IsPentagon(lower, upper));\n}\n\n/**\n * Whether the given H3 index is in a Class III resolution (rotated versus\n * the icosahedron and subject to shape distortion adding extra points on\n * icosahedron edges, making them not true hexagons).\n * @static\n * @param {H3IndexInput} h3Index H3 index to check\n * @return {boolean} isResClassIII\n */\nexport function h3IsResClassIII(h3Index) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n return Boolean(H3.h3IsResClassIII(lower, upper));\n}\n\n/**\n * Get the number of the base cell for a given H3 index\n * @static\n * @param {H3IndexInput} h3Index H3 index to get the base cell for\n * @return {number} Index of the base cell (0-121)\n */\nexport function h3GetBaseCell(h3Index) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n return H3.h3GetBaseCell(lower, upper);\n}\n\n/**\n * Get the indices of all icosahedron faces intersected by a given H3 index\n * @static\n * @param {H3IndexInput} h3Index H3 index to get faces for\n * @return {number[]} Indices (0-19) of all intersected faces\n */\nexport function h3GetFaces(h3Index) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n const count = H3.maxFaceCount(lower, upper);\n const faces = C._malloc(SZ_INT * count);\n H3.h3GetFaces(lower, upper, faces);\n const out = readArrayOfPositiveIntegers(faces, count);\n C._free(faces);\n return out;\n}\n\n/**\n * Returns the resolution of an H3 index\n * @static\n * @param {H3IndexInput} h3Index H3 index to get resolution\n * @return {number} The number (0-15) resolution, or -1 if invalid\n */\nexport function h3GetResolution(h3Index) {\n if (typeof h3Index !== 'string') {\n return -1;\n }\n return parseInt(h3Index.charAt(1), BASE_16);\n}\n\n/**\n * Get the hexagon containing a lat,lon point\n * @static\n * @param {number} lat Latitude of point\n * @param {number} lng Longtitude of point\n * @param {number} res Resolution of hexagons to return\n * @return {H3Index} H3 index\n */\nexport function geoToH3(lat, lng, res) {\n const latlng = C._malloc(SZ_GEOCOORD);\n // Slightly more efficient way to set the memory\n C.HEAPF64.set([lat, lng].map(degsToRads), latlng / SZ_DBL);\n // Read value as a split long\n const h3Index = readH3Index(H3.geoToH3(latlng, res));\n C._free(latlng);\n return h3Index;\n}\n\n/**\n * Get the lat,lon center of a given hexagon\n * @static\n * @param {H3IndexInput} h3Index H3 index\n * @return {number[]} Point as a [lat, lng] pair\n */\nexport function h3ToGeo(h3Index) {\n const latlng = C._malloc(SZ_GEOCOORD);\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n H3.h3ToGeo(lower, upper, latlng);\n const out = readGeoCoord(latlng);\n C._free(latlng);\n return out;\n}\n\n/**\n * Get the vertices of a given hexagon (or pentagon), as an array of [lat, lng]\n * points. For pentagons and hexagons on the edge of an icosahedron face, this\n * function may return up to 10 vertices.\n * @static\n * @param {H3Index} h3Index H3 index\n * @param {boolean} [formatAsGeoJson] Whether to provide GeoJSON output: [lng, lat], closed loops\n * @return {number[][]} Array of [lat, lng] pairs\n */\nexport function h3ToGeoBoundary(h3Index, formatAsGeoJson) {\n const geoBoundary = C._malloc(SZ_GEOBOUNDARY);\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n H3.h3ToGeoBoundary(lower, upper, geoBoundary);\n const out = readGeoBoundary(geoBoundary, formatAsGeoJson, formatAsGeoJson);\n C._free(geoBoundary);\n return out;\n}\n\n// ----------------------------------------------------------------------------\n// Public API functions: Algorithms\n\n/**\n * Get the parent of the given hexagon at a particular resolution\n * @static\n * @param {H3IndexInput} h3Index H3 index to get parent for\n * @param {number} res Resolution of hexagon to return\n * @return {H3Index} H3 index of parent, or null for invalid input\n */\nexport function h3ToParent(h3Index, res) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n return readH3Index(H3.h3ToParent(lower, upper, res));\n}\n\n/**\n * Get the children/descendents of the given hexagon at a particular resolution\n * @static\n * @param {H3IndexInput} h3Index H3 index to get children for\n * @param {number} res Resolution of hexagons to return\n * @return {H3Index[]} H3 indexes of children, or empty array for invalid input\n */\nexport function h3ToChildren(h3Index, res) {\n // Bad input in this case can potentially result in high computation volume\n // using the current C algorithm. Validate and return an empty array on failure.\n if (!h3IsValid(h3Index)) {\n return [];\n }\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n const maxCount = H3.maxH3ToChildrenSize(lower, upper, res);\n const hexagons = C._calloc(maxCount, SZ_H3INDEX);\n H3.h3ToChildren(lower, upper, res, hexagons);\n const out = readArrayOfHexagons(hexagons, maxCount);\n C._free(hexagons);\n return out;\n}\n\n/**\n * Get the center child of the given hexagon at a particular resolution\n * @static\n * @param {H3IndexInput} h3Index H3 index to get center child for\n * @param {number} res Resolution of hexagon to return\n * @return {H3Index} H3 index of child, or null for invalid input\n */\nexport function h3ToCenterChild(h3Index, res) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n return readH3Index(H3.h3ToCenterChild(lower, upper, res));\n}\n\n/**\n * Get all hexagons in a k-ring around a given center. The order of the hexagons is undefined.\n * @static\n * @param {H3IndexInput} h3Index H3 index of center hexagon\n * @param {number} ringSize Radius of k-ring\n * @return {H3Index[]} H3 indexes for all hexagons in ring\n */\nexport function kRing(h3Index, ringSize) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n const maxCount = H3.maxKringSize(ringSize);\n const hexagons = C._calloc(maxCount, SZ_H3INDEX);\n H3.kRing(lower, upper, ringSize, hexagons);\n const out = readArrayOfHexagons(hexagons, maxCount);\n C._free(hexagons);\n return out;\n}\n\n/**\n * Get all hexagons in a k-ring around a given center, in an array of arrays\n * ordered by distance from the origin. The order of the hexagons within each ring is undefined.\n * @static\n * @param {H3IndexInput} h3Index H3 index of center hexagon\n * @param {number} ringSize Radius of k-ring\n * @return {H3Index[][]} Array of arrays with H3 indexes for all hexagons each ring\n */\nexport function kRingDistances(h3Index, ringSize) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n const maxCount = H3.maxKringSize(ringSize);\n const kRings = C._calloc(maxCount, SZ_H3INDEX);\n const distances = C._calloc(maxCount, SZ_INT);\n H3.kRingDistances(lower, upper, ringSize, kRings, distances);\n // Create an array of empty arrays to hold the output\n const out = [];\n for (let i = 0; i < ringSize + 1; i++) {\n out.push([]);\n }\n // Read the array of hexagons, putting them into the appropriate rings\n for (let i = 0; i < maxCount * 2; i += 2) {\n const hexLower = C.getValue(kRings + SZ_INT * i, 'i32');\n const hexUpper = C.getValue(kRings + SZ_INT * (i + 1), 'i32');\n const index = C.getValue(distances + SZ_INT * (i / 2), 'i32');\n if (hexLower !== 0 || hexUpper !== 0) {\n out[index].push(splitLongToh3Index(hexLower, hexUpper));\n }\n }\n C._free(kRings);\n C._free(distances);\n return out;\n}\n\n/**\n * Get all hexagons in a hollow hexagonal ring centered at origin with sides of a given length.\n * Unlike kRing, this function will throw an error if there is a pentagon anywhere in the ring.\n * @static\n * @param {H3IndexInput} h3Index H3 index of center hexagon\n * @param {number} ringSize Radius of ring\n * @return {H3Index[]} H3 indexes for all hexagons in ring\n * @throws {Error} If the algorithm could not calculate the ring\n */\nexport function hexRing(h3Index, ringSize) {\n const maxCount = ringSize === 0 ? 1 : 6 * ringSize;\n const hexagons = C._calloc(maxCount, SZ_H3INDEX);\n const retVal = H3.hexRing(...h3IndexToSplitLong(h3Index), ringSize, hexagons);\n if (retVal !== 0) {\n C._free(hexagons);\n throw new Error('Failed to get hexRing (encountered a pentagon?)');\n }\n const out = readArrayOfHexagons(hexagons, maxCount);\n C._free(hexagons);\n return out;\n}\n\n/**\n * Get all hexagons with centers contained in a given polygon. The polygon\n * is specified with GeoJson semantics as an array of loops. Each loop is\n * an array of [lat, lng] pairs (or [lng, lat] if isGeoJson is specified).\n * The first loop is the perimeter of the polygon, and subsequent loops are\n * expected to be holes.\n * @static\n * @param {number[][] | number[][][]} coordinates\n * Array of loops, or a single loop\n * @param {number} res Resolution of hexagons to return\n * @param {boolean} [isGeoJson] Whether to expect GeoJson-style [lng, lat]\n * pairs instead of [lat, lng]\n * @return {H3Index[]} H3 indexes for all hexagons in polygon\n */\nexport function polyfill(coordinates, res, isGeoJson) {\n validateRes(res);\n isGeoJson = Boolean(isGeoJson);\n // Guard against empty input\n if (coordinates.length === 0 || coordinates[0].length === 0) {\n return [];\n }\n // Wrap to expected format if a single loop is provided\n if (typeof coordinates[0][0] === 'number') {\n coordinates = [coordinates];\n }\n const geoPolygon = coordinatesToGeoPolygon(coordinates, isGeoJson);\n const arrayLen = H3.maxPolyfillSize(geoPolygon, res);\n const hexagons = C._calloc(arrayLen, SZ_H3INDEX);\n H3.polyfill(geoPolygon, res, hexagons);\n const out = readArrayOfHexagons(hexagons, arrayLen);\n C._free(hexagons);\n destroyGeoPolygon(geoPolygon);\n return out;\n}\n\n/**\n * Get the outlines of a set of H3 hexagons, returned in GeoJSON MultiPolygon\n * format (an array of polygons, each with an array of loops, each an array of\n * coordinates). Coordinates are returned as [lat, lng] pairs unless GeoJSON\n * is requested.\n *\n * It is the responsibility of the caller to ensure that all hexagons in the\n * set have the same resolution and that the set contains no duplicates. Behavior\n * is undefined if duplicates or multiple resolutions are present, and the\n * algorithm may produce unexpected or invalid polygons.\n *\n * @static\n * @param {H3IndexInput[]} h3Indexes H3 indexes to get outlines for\n * @param {boolean} [formatAsGeoJson] Whether to provide GeoJSON output:\n * [lng, lat], closed loops\n * @return {number[][][][]} MultiPolygon-style output.\n */\nexport function h3SetToMultiPolygon(h3Indexes, formatAsGeoJson) {\n // Early exit on empty input\n if (!h3Indexes || !h3Indexes.length) {\n return [];\n }\n // Set up input set\n const indexCount = h3Indexes.length;\n const set = C._calloc(indexCount, SZ_H3INDEX);\n storeArrayOfHexagons(set, h3Indexes);\n // Allocate memory for output linked polygon\n const polygon = C._calloc(SZ_LINKED_GEOPOLYGON);\n // Store a reference to the first polygon - that's the one we need for\n // memory deallocation\n const originalPolygon = polygon;\n H3.h3SetToLinkedGeo(set, indexCount, polygon);\n const multiPolygon = readMultiPolygon(polygon, formatAsGeoJson);\n // Clean up\n H3.destroyLinkedPolygon(originalPolygon);\n C._free(originalPolygon);\n C._free(set);\n return multiPolygon;\n}\n\n/**\n * Compact a set of hexagons of the same resolution into a set of hexagons across\n * multiple levels that represents the same area.\n * @static\n * @param {H3IndexInput[]} h3Set H3 indexes to compact\n * @return {H3Index[]} Compacted H3 indexes\n * @throws {Error} If the input is invalid (e.g. duplicate hexagons)\n */\nexport function compact(h3Set) {\n if (!h3Set || !h3Set.length) {\n return [];\n }\n // Set up input set\n const count = h3Set.length;\n const set = C._calloc(count, SZ_H3INDEX);\n storeArrayOfHexagons(set, h3Set);\n // Allocate memory for compacted hexagons, worst-case is no compaction\n const compactedSet = C._calloc(count, SZ_H3INDEX);\n const retVal = H3.compact(set, compactedSet, count);\n if (retVal !== 0) {\n C._free(set);\n C._free(compactedSet);\n throw new Error('Failed to compact, malformed input data (duplicate hexagons?)');\n }\n const out = readArrayOfHexagons(compactedSet, count);\n C._free(set);\n C._free(compactedSet);\n return out;\n}\n\n/**\n * Uncompact a compacted set of hexagons to hexagons of the same resolution\n * @static\n * @param {H3IndexInput[]} compactedSet H3 indexes to uncompact\n * @param {number} res The resolution to uncompact to\n * @return {H3Index[]} The uncompacted H3 indexes\n * @throws {Error} If the input is invalid (e.g. invalid resolution)\n */\nexport function uncompact(compactedSet, res) {\n validateRes(res);\n if (!compactedSet || !compactedSet.length) {\n return [];\n }\n // Set up input set\n const count = compactedSet.length;\n const set = C._calloc(count, SZ_H3INDEX);\n storeArrayOfHexagons(set, compactedSet);\n // Estimate how many hexagons we need (always overestimates if in error)\n const maxUncompactedNum = H3.maxUncompactSize(set, count, res);\n // Allocate memory for uncompacted hexagons\n const uncompactedSet = C._calloc(maxUncompactedNum, SZ_H3INDEX);\n const retVal = H3.uncompact(set, count, uncompactedSet, maxUncompactedNum, res);\n if (retVal !== 0) {\n C._free(set);\n C._free(uncompactedSet);\n throw new Error('Failed to uncompact (bad resolution?)');\n }\n const out = readArrayOfHexagons(uncompactedSet, maxUncompactedNum);\n C._free(set);\n C._free(uncompactedSet);\n return out;\n}\n\n// ----------------------------------------------------------------------------\n// Public API functions: Unidirectional edges\n\n/**\n * Whether two H3 indexes are neighbors (share an edge)\n * @static\n * @param {H3IndexInput} origin Origin hexagon index\n * @param {H3IndexInput} destination Destination hexagon index\n * @return {boolean} Whether the hexagons share an edge\n */\nexport function h3IndexesAreNeighbors(origin, destination) {\n const [oLower, oUpper] = h3IndexToSplitLong(origin);\n const [dLower, dUpper] = h3IndexToSplitLong(destination);\n return Boolean(H3.h3IndexesAreNeighbors(oLower, oUpper, dLower, dUpper));\n}\n\n/**\n * Get an H3 index representing a unidirectional edge for a given origin and destination\n * @static\n * @param {H3IndexInput} origin Origin hexagon index\n * @param {H3IndexInput} destination Destination hexagon index\n * @return {H3Index} H3 index of the edge, or null if no edge is shared\n */\nexport function getH3UnidirectionalEdge(origin, destination) {\n const [oLower, oUpper] = h3IndexToSplitLong(origin);\n const [dLower, dUpper] = h3IndexToSplitLong(destination);\n return readH3Index(H3.getH3UnidirectionalEdge(oLower, oUpper, dLower, dUpper));\n}\n\n/**\n * Get the origin hexagon from an H3 index representing a unidirectional edge\n * @static\n * @param {H3IndexInput} edgeIndex H3 index of the edge\n * @return {H3Index} H3 index of the edge origin\n */\nexport function getOriginH3IndexFromUnidirectionalEdge(edgeIndex) {\n const [lower, upper] = h3IndexToSplitLong(edgeIndex);\n return readH3Index(H3.getOriginH3IndexFromUnidirectionalEdge(lower, upper));\n}\n\n/**\n * Get the destination hexagon from an H3 index representing a unidirectional edge\n * @static\n * @param {H3IndexInput} edgeIndex H3 index of the edge\n * @return {H3Index} H3 index of the edge destination\n */\nexport function getDestinationH3IndexFromUnidirectionalEdge(edgeIndex) {\n const [lower, upper] = h3IndexToSplitLong(edgeIndex);\n return readH3Index(H3.getDestinationH3IndexFromUnidirectionalEdge(lower, upper));\n}\n\n/**\n * Whether the input is a valid unidirectional edge\n * @static\n * @param {H3IndexInput} edgeIndex H3 index of the edge\n * @return {boolean} Whether the index is valid\n */\nexport function h3UnidirectionalEdgeIsValid(edgeIndex) {\n const [lower, upper] = h3IndexToSplitLong(edgeIndex);\n return Boolean(H3.h3UnidirectionalEdgeIsValid(lower, upper));\n}\n\n/**\n * Get the [origin, destination] pair represented by a unidirectional edge\n * @static\n * @param {H3IndexInput} edgeIndex H3 index of the edge\n * @return {H3Index[]} [origin, destination] pair as H3 indexes\n */\nexport function getH3IndexesFromUnidirectionalEdge(edgeIndex) {\n const [lower, upper] = h3IndexToSplitLong(edgeIndex);\n const count = 2;\n const hexagons = C._calloc(count, SZ_H3INDEX);\n H3.getH3IndexesFromUnidirectionalEdge(lower, upper, hexagons);\n const out = readArrayOfHexagons(hexagons, count);\n C._free(hexagons);\n return out;\n}\n\n/**\n * Get all of the unidirectional edges with the given H3 index as the origin (i.e. an edge to\n * every neighbor)\n * @static\n * @param {H3IndexInput} h3Index H3 index of the origin hexagon\n * @return {H3Index[]} List of unidirectional edges\n */\nexport function getH3UnidirectionalEdgesFromHexagon(h3Index) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n const count = 6;\n const edges = C._calloc(count, SZ_H3INDEX);\n H3.getH3UnidirectionalEdgesFromHexagon(lower, upper, edges);\n const out = readArrayOfHexagons(edges, count);\n C._free(edges);\n return out;\n}\n\n/**\n * Get the vertices of a given edge as an array of [lat, lng] points. Note that for edges that\n * cross the edge of an icosahedron face, this may return 3 coordinates.\n * @static\n * @param {H3IndexInput} edgeIndex H3 index of the edge\n * @param {boolean} [formatAsGeoJson] Whether to provide GeoJSON output: [lng, lat]\n * @return {number[][]} Array of geo coordinate pairs\n */\nexport function getH3UnidirectionalEdgeBoundary(edgeIndex, formatAsGeoJson) {\n const geoBoundary = C._malloc(SZ_GEOBOUNDARY);\n const [lower, upper] = h3IndexToSplitLong(edgeIndex);\n H3.getH3UnidirectionalEdgeBoundary(lower, upper, geoBoundary);\n const out = readGeoBoundary(geoBoundary, formatAsGeoJson);\n C._free(geoBoundary);\n return out;\n}\n\n/**\n * Get the grid distance between two hex indexes. This function may fail\n * to find the distance between two indexes if they are very far apart or\n * on opposite sides of a pentagon.\n * @static\n * @param {H3IndexInput} origin Origin hexagon index\n * @param {H3IndexInput} destination Destination hexagon index\n * @return {number} Distance between hexagons, or a negative\n * number if the distance could not be computed\n */\nexport function h3Distance(origin, destination) {\n const [oLower, oUpper] = h3IndexToSplitLong(origin);\n const [dLower, dUpper] = h3IndexToSplitLong(destination);\n return H3.h3Distance(oLower, oUpper, dLower, dUpper);\n}\n\n/**\n * Given two H3 indexes, return the line of indexes between them (inclusive).\n *\n * This function may fail to find the line between two indexes, for\n * example if they are very far apart. It may also fail when finding\n * distances for indexes on opposite sides of a pentagon.\n *\n * Notes:\n *\n * - The specific output of this function should not be considered stable\n * across library versions. The only guarantees the library provides are\n * that the line length will be `h3Distance(start, end) + 1` and that\n * every index in the line will be a neighbor of the preceding index.\n * - Lines are drawn in grid space, and may not correspond exactly to either\n * Cartesian lines or great arcs.\n *\n * @static\n * @param {H3IndexInput} origin Origin hexagon index\n * @param {H3IndexInput} destination Destination hexagon index\n * @return {H3Index[]} H3 indexes connecting origin and destination\n * @throws {Error} If the line cannot be calculated\n */\nexport function h3Line(origin, destination) {\n const [oLower, oUpper] = h3IndexToSplitLong(origin);\n const [dLower, dUpper] = h3IndexToSplitLong(destination);\n const count = H3.h3LineSize(oLower, oUpper, dLower, dUpper);\n if (count < 0) {\n // We can't get the specific error code here - may be any of\n // the errors possible in experimentalH3ToLocalIj\n throw new Error('Line cannot be calculated');\n }\n const hexagons = C._calloc(count, SZ_H3INDEX);\n H3.h3Line(oLower, oUpper, dLower, dUpper, hexagons);\n const out = readArrayOfHexagons(hexagons, count);\n C._free(hexagons);\n return out;\n}\n\n/**\n * Produces IJ coordinates for an H3 index anchored by an origin.\n *\n * - The coordinate space used by this function may have deleted\n * regions or warping due to pentagonal distortion.\n * - Coordinates are only comparable if they come from the same\n * origin index.\n * - Failure may occur if the index is too far away from the origin\n * or if the index is on the other side of a pentagon.\n * - This function is experimental, and its output is not guaranteed\n * to be compatible across different versions of H3.\n * @static\n * @param {H3IndexInput} origin Origin H3 index\n * @param {H3IndexInput} destination H3 index for which to find relative coordinates\n * @return {CoordIJ} Coordinates as an `{i, j}` pair\n * @throws {Error} If the IJ coordinates cannot be calculated\n */\nexport function experimentalH3ToLocalIj(origin, destination) {\n const ij = C._malloc(SZ_COORDIJ);\n const retVal = H3.experimentalH3ToLocalIj(\n ...h3IndexToSplitLong(origin),\n ...h3IndexToSplitLong(destination),\n ij\n );\n const coords = readCoordIJ(ij);\n C._free(ij);\n // Return the pair, or throw if an error code was returned.\n // Switch statement and error codes cribbed from h3-java's implementation.\n switch (retVal) {\n case 0:\n return coords;\n case 1:\n throw new Error('Incompatible origin and index.');\n case 2:\n default:\n throw new Error(\n 'Local IJ coordinates undefined for this origin and index pair. ' +\n 'The index may be too far from the origin.'\n );\n case 3:\n case 4:\n case 5:\n throw new Error('Encountered possible pentagon distortion');\n }\n}\n\n/**\n * Produces an H3 index for IJ coordinates anchored by an origin.\n *\n * - The coordinate space used by this function may have deleted\n * regions or warping due to pentagonal distortion.\n * - Coordinates are only comparable if they come from the same\n * origin index.\n * - Failure may occur if the index is too far away from the origin\n * or if the index is on the other side of a pentagon.\n * - This function is experimental, and its output is not guaranteed\n * to be compatible across different versions of H3.\n * @static\n * @param {H3IndexInput} origin Origin H3 index\n * @param {CoordIJ} coords Coordinates as an `{i, j}` pair\n * @return {H3Index} H3 index at the relative coordinates\n * @throws {Error} If the H3 index cannot be calculated\n */\nexport function experimentalLocalIjToH3(origin, coords) {\n // Validate input coords\n if (!coords || typeof coords.i !== 'number' || typeof coords.j !== 'number') {\n throw new Error('Coordinates must be provided as an {i, j} object');\n }\n // Allocate memory for the CoordIJ struct and an H3 index to hold the return value\n const ij = C._malloc(SZ_COORDIJ);\n const out = C._malloc(SZ_H3INDEX);\n storeCoordIJ(ij, coords);\n const retVal = H3.experimentalLocalIjToH3(...h3IndexToSplitLong(origin), ij, out);\n const h3Index = readH3IndexFromPointer(out);\n C._free(ij);\n C._free(out);\n if (retVal !== 0) {\n throw new Error(\n 'Index not defined for this origin and IJ coordinates pair. ' +\n 'IJ coordinates may be too far from origin, or ' +\n 'a pentagon distortion was encountered.'\n );\n }\n return h3Index;\n}\n\n// ----------------------------------------------------------------------------\n// Public API functions: Distance/area utilities\n\n/**\n * Great circle distance between two geo points. This is not specific to H3,\n * but is implemented in the library and provided here as a convenience.\n * @static\n * @param {number[]} latlng1 Origin coordinate as [lat, lng]\n * @param {number[]} latlng2 Destination coordinate as [lat, lng]\n * @param {string} unit Distance unit (either UNITS.m or UNITS.km)\n * @return {number} Great circle distance\n * @throws {Error} If the unit is invalid\n */\nexport function pointDist(latlng1, latlng2, unit) {\n const coord1 = storeGeoCoord(latlng1[0], latlng1[1]);\n const coord2 = storeGeoCoord(latlng2[0], latlng2[1]);\n let result;\n switch (unit) {\n case UNITS.m:\n result = H3.pointDistM(coord1, coord2);\n break;\n case UNITS.km:\n result = H3.pointDistKm(coord1, coord2);\n break;\n case UNITS.rads:\n result = H3.pointDistRads(coord1, coord2);\n break;\n default:\n result = null;\n }\n C._free(coord1);\n C._free(coord2);\n if (result === null) {\n throw new Error(`Unknown unit: ${unit}`);\n }\n return result;\n}\n\n/**\n * Exact area of a given cell\n * @static\n * @param {H3Index} h3Index H3 index of the hexagon to measure\n * @param {string} unit Distance unit (either UNITS.m2 or UNITS.km2)\n * @return {number} Cell area\n * @throws {Error} If the unit is invalid\n */\nexport function cellArea(h3Index, unit) {\n const [lower, upper] = h3IndexToSplitLong(h3Index);\n switch (unit) {\n case UNITS.m2:\n return H3.cellAreaM2(lower, upper);\n case UNITS.km2:\n return H3.cellAreaKm2(lower, upper);\n case UNITS.rads2:\n return H3.cellAreaRads2(lower, upper);\n default:\n throw new Error(`Unknown unit: ${unit}`);\n }\n}\n\n/**\n * Exact length of a given unidirectional edge\n * @static\n * @param {H3Index} edge H3 index of the edge to measure\n * @param {string} unit Distance unit (either UNITS.m, UNITS.km, or UNITS.rads)\n * @return {number} Cell area\n * @throws {Error} If the unit is invalid\n */\nexport function exactEdgeLength(edge, unit) {\n const [lower, upper] = h3IndexToSplitLong(edge);\n switch (unit) {\n case UNITS.m:\n return H3.exactEdgeLengthM(lower, upper);\n case UNITS.km:\n return H3.exactEdgeLengthKm(lower, upper);\n case UNITS.rads:\n return H3.exactEdgeLengthRads(lower, upper);\n default:\n throw new Error(`Unknown unit: ${unit}`);\n }\n}\n\n/**\n * Average hexagon area at a given resolution\n * @static\n * @param {number} res Hexagon resolution\n * @param {string} unit Area unit (either UNITS.m2, UNITS.km2, or UNITS.rads2)\n * @return {number} Average area\n * @throws {Error} If the unit is invalid\n */\nexport function hexArea(res, unit) {\n validateRes(res);\n switch (unit) {\n case UNITS.m2:\n return H3.hexAreaM2(res);\n case UNITS.km2:\n return H3.hexAreaKm2(res);\n default:\n throw new Error(`Unknown unit: ${unit}`);\n }\n}\n\n/**\n * Average hexagon edge length at a given resolution\n * @static\n * @param {number} res Hexagon resolution\n * @param {string} unit Distance unit (either UNITS.m, UNITS.km, or UNITS.rads)\n * @return {number} Average edge length\n * @throws {Error} If the unit is invalid\n */\nexport function edgeLength(res, unit) {\n validateRes(res);\n switch (unit) {\n case UNITS.m:\n return H3.edgeLengthM(res);\n case UNITS.km:\n return H3.edgeLengthKm(res);\n default:\n throw new Error(`Unknown unit: ${unit}`);\n }\n}\n\n// ----------------------------------------------------------------------------\n// Public informational utilities\n\n/**\n * The total count of hexagons in the world at a given resolution. Note that above\n * resolution 8 the exact count cannot be represented in a JavaScript 32-bit number,\n * so consumers should use caution when applying further operations to the output.\n * @static\n * @param {number} res Hexagon resolution\n * @return {number} Count\n */\nexport function numHexagons(res) {\n validateRes(res);\n // Get number as a long value\n const [lower, upper] = readLong(H3.numHexagons(res));\n // If we're using <= 32 bits we can use normal JS numbers\n if (!upper) {\n return lower;\n }\n // Above 32 bit, make a JS number that's correct in order of magnitude\n return upper * Math.pow(2, 32) + lower;\n}\n\n/**\n * Get all H3 indexes at resolution 0. As every index at every resolution > 0 is\n * the descendant of a res 0 index, this can be used with h3ToChildren to iterate\n * over H3 indexes at any resolution.\n * @static\n * @return {H3Index[]} All H3 indexes at res 0\n */\nexport function getRes0Indexes() {\n const count = H3.res0IndexCount();\n const hexagons = C._malloc(SZ_H3INDEX * count);\n H3.getRes0Indexes(hexagons);\n const out = readArrayOfHexagons(hexagons, count);\n C._free(hexagons);\n return out;\n}\n\n/**\n * Get the twelve pentagon indexes at a given resolution.\n * @static\n * @param {number} res Hexagon resolution\n * @return {H3Index[]} All H3 pentagon indexes at res\n */\nexport function getPentagonIndexes(res) {\n validateRes(res);\n const count = H3.pentagonIndexCount();\n const hexagons = C._malloc(SZ_H3INDEX * count);\n H3.getPentagonIndexes(res, hexagons);\n const out = readArrayOfHexagons(hexagons, count);\n C._free(hexagons);\n return out;\n}\n\n/**\n * Convert degrees to radians\n * @static\n * @param {number} deg Value in degrees\n * @return {number} Value in radians\n */\nexport function degsToRads(deg) {\n return (deg * Math.PI) / 180;\n}\n\n/**\n * Convert radians to degrees\n * @static\n * @param {number} rad Value in radians\n * @return {number} Value in degrees\n */\nexport function radsToDegs(rad) {\n return (rad * 180) / Math.PI;\n}\n","var baseMerge = require('./_baseMerge'),\n createAssigner = require('./_createAssigner');\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nmodule.exports = merge;\n","import GL from '@luma.gl/constants';\nimport {isWebGL2, assertWebGL2Context, withParameters, log} from '@luma.gl/gltools';\nimport {global} from 'probe.gl/env';\n\nimport Resource from './resource';\nimport Buffer from './buffer';\nimport {\n TEXTURE_FORMATS,\n DATA_FORMAT_CHANNELS,\n TYPE_SIZES,\n isFormatSupported,\n isLinearFilteringSupported\n} from './texture-formats';\nimport {assert} from '../utils/assert';\nimport {uid, isPowerOfTwo} from '../utils/utils';\n\n// Supported min filters for NPOT texture.\nconst NPOT_MIN_FILTERS = [GL.LINEAR, GL.NEAREST];\n\n// Polyfill\n// Note (Tarek): Do we really need to support this API?\nconst WebGLBuffer = global.WebGLBuffer || function WebGLBuffer() {};\n\nexport default class Texture extends Resource {\n static isSupported(gl, opts = {}) {\n const {format, linearFiltering} = opts;\n let supported = true;\n if (format) {\n supported = supported && isFormatSupported(gl, format);\n supported = supported && (!linearFiltering || isLinearFilteringSupported(gl, format));\n }\n return supported;\n }\n\n // target cannot be modified by bind:\n // textures are special because when you first bind them to a target,\n // they get special information. When you first bind a texture as a\n // GL_TEXTURE_2D, you are actually setting special state in the texture.\n // You are saying that this texture is a 2D texture.\n // And it will always be a 2D texture; this state cannot be changed ever.\n // If you have a texture that was first bound as a GL_TEXTURE_2D,\n // you must always bind it as a GL_TEXTURE_2D;\n // attempting to bind it as GL_TEXTURE_1D will give rise to an error\n // (while run-time).\n constructor(gl, props) {\n const {\n id = uid('texture'),\n handle,\n target\n // , magFilter, minFilter, wrapS, wrapT\n } = props;\n\n super(gl, {id, handle});\n\n this.target = target;\n this.textureUnit = undefined;\n\n // Program.draw() checks the loaded flag of all textures to avoid\n // Textures that are still loading from promises\n // Set to true as soon as texture has been initialized with valid data\n this.loaded = false;\n\n this.width = undefined;\n this.height = undefined;\n this.depth = undefined;\n this.format = undefined;\n this.type = undefined;\n this.dataFormat = undefined;\n this.border = undefined;\n this.textureUnit = undefined;\n this.mipmaps = undefined;\n }\n\n toString() {\n return `Texture(${this.id},${this.width}x${this.height})`;\n }\n\n /* eslint-disable max-len, max-statements */\n initialize(props = {}) {\n let data = props.data;\n\n if (data instanceof Promise) {\n data.then(resolvedImageData =>\n this.initialize(\n Object.assign({}, props, {\n pixels: resolvedImageData,\n data: resolvedImageData\n })\n )\n );\n return this;\n }\n const isVideo = typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement;\n // @ts-ignore\n if (isVideo && data.readyState < HTMLVideoElement.HAVE_METADATA) {\n this._video = null; // Declare member before the object is sealed\n data.addEventListener('loadeddata', () => this.initialize(props));\n return this;\n }\n\n const {\n pixels = null,\n format = GL.RGBA,\n border = 0,\n recreate = false,\n parameters = {},\n pixelStore = {},\n textureUnit = undefined\n } = props;\n\n // pixels variable is for API compatibility purpose\n if (!data) {\n // TODO - This looks backwards? Commenting out for now until we decide\n // which prop to use\n // log.deprecated('data', 'pixels')();\n data = pixels;\n }\n\n let {width, height, dataFormat, type, compressed = false, mipmaps = true} = props;\n const {depth = 0} = props;\n\n // Deduce width and height\n ({width, height, compressed, dataFormat, type} = this._deduceParameters({\n format,\n type,\n dataFormat,\n compressed,\n data,\n width,\n height\n }));\n\n // Store opts for accessors\n this.width = width;\n this.height = height;\n this.depth = depth;\n this.format = format;\n this.type = type;\n this.dataFormat = dataFormat;\n this.border = border;\n this.textureUnit = textureUnit;\n\n if (Number.isFinite(this.textureUnit)) {\n this.gl.activeTexture(GL.TEXTURE0 + this.textureUnit);\n this.gl.bindTexture(this.target, this.handle);\n }\n\n if (mipmaps && this._isNPOT()) {\n log.warn(`texture: ${this} is Non-Power-Of-Two, disabling mipmaping`)();\n mipmaps = false;\n\n this._updateForNPOT(parameters);\n }\n\n this.mipmaps = mipmaps;\n\n this.setImageData({\n data,\n width,\n height,\n depth,\n format,\n type,\n dataFormat,\n border,\n mipmaps,\n parameters: pixelStore,\n compressed\n });\n\n if (mipmaps) {\n this.generateMipmap();\n }\n\n // Set texture sampler parameters\n this.setParameters(parameters);\n\n // TODO - Store data to enable auto recreate on context loss\n if (recreate) {\n this.data = data;\n }\n if (isVideo) {\n this._video = {\n video: data,\n parameters,\n // @ts-ignore\n lastTime: data.readyState >= HTMLVideoElement.HAVE_CURRENT_DATA ? data.currentTime : -1\n };\n }\n\n return this;\n }\n\n update() {\n if (this._video) {\n const {video, parameters, lastTime} = this._video;\n // @ts-ignore\n if (lastTime === video.currentTime || video.readyState < HTMLVideoElement.HAVE_CURRENT_DATA) {\n return;\n }\n this.setSubImageData({\n data: video,\n parameters\n });\n if (this.mipmaps) {\n this.generateMipmap();\n }\n this._video.lastTime = video.currentTime;\n }\n }\n\n // If size has changed, reinitializes with current format\n // note clears image and mipmaps\n resize({height, width, mipmaps = false}) {\n if (width !== this.width || height !== this.height) {\n return this.initialize({\n width,\n height,\n format: this.format,\n type: this.type,\n dataFormat: this.dataFormat,\n border: this.border,\n mipmaps\n });\n }\n return this;\n }\n\n // Call to regenerate mipmaps after modifying texture(s)\n generateMipmap(params = {}) {\n if (this._isNPOT()) {\n log.warn(`texture: ${this} is Non-Power-Of-Two, disabling mipmaping`)();\n return this;\n }\n\n this.mipmaps = true;\n\n this.gl.bindTexture(this.target, this.handle);\n withParameters(this.gl, params, () => {\n this.gl.generateMipmap(this.target);\n });\n this.gl.bindTexture(this.target, null);\n return this;\n }\n\n /*\n * Allocates storage\n * @param {*} pixels -\n * null - create empty texture of specified format\n * Typed array - init from image data in typed array\n * Buffer|WebGLBuffer - (WEBGL2) init from image data in WebGLBuffer\n * HTMLImageElement|Image - Inits with content of image. Auto width/height\n * HTMLCanvasElement - Inits with contents of canvas. Auto width/height\n * HTMLVideoElement - Creates video texture. Auto width/height\n *\n * @param {GLint} width -\n * @param {GLint} height -\n * @param {GLint} mipMapLevel -\n * @param {GLenum} format - format of image data.\n * @param {GLenum} type\n * - format of array (autodetect from type) or\n * - (WEBGL2) format of buffer\n * @param {Number} offset - (WEBGL2) offset from start of buffer\n * @param {GLint} border - must be 0.\n * @parameters - temporary settings to be applied, can be used to supply pixel store settings.\n */\n /* eslint-disable max-len, max-statements, complexity */\n setImageData(options) {\n this._trackDeallocatedMemory('Texture');\n\n const {\n target = this.target,\n pixels = null,\n level = 0,\n format = this.format,\n border = this.border,\n offset = 0,\n parameters = {}\n } = options;\n\n let {\n data = null,\n type = this.type,\n width = this.width,\n height = this.height,\n dataFormat = this.dataFormat,\n compressed = false\n } = options;\n\n // pixels variable is for API compatibility purpose\n if (!data) {\n data = pixels;\n }\n\n ({type, dataFormat, compressed, width, height} = this._deduceParameters({\n format,\n type,\n dataFormat,\n compressed,\n data,\n width,\n height\n }));\n\n const {gl} = this;\n gl.bindTexture(this.target, this.handle);\n\n let dataType = null;\n ({data, dataType} = this._getDataType({data, compressed}));\n\n let gl2;\n\n withParameters(this.gl, parameters, () => {\n switch (dataType) {\n case 'null':\n gl.texImage2D(target, level, format, width, height, border, dataFormat, type, data);\n break;\n case 'typed-array':\n // Looks like this assert is not necessary, as offset is ignored under WebGL1\n // assert((offset === 0 || isWebGL2(gl)), 'offset supported in WebGL2 only');\n // @ts-ignore\n gl.texImage2D(\n target,\n level,\n format,\n width,\n height,\n border,\n dataFormat,\n type,\n data,\n // @ts-ignore\n offset\n );\n break;\n case 'buffer':\n // WebGL2 enables creating textures directly from a WebGL buffer\n gl2 = assertWebGL2Context(gl);\n gl2.bindBuffer(GL.PIXEL_UNPACK_BUFFER, data.handle || data);\n gl2.texImage2D(target, level, format, width, height, border, dataFormat, type, offset);\n gl2.bindBuffer(GL.PIXEL_UNPACK_BUFFER, null);\n break;\n case 'browser-object':\n if (isWebGL2(gl)) {\n gl.texImage2D(target, level, format, width, height, border, dataFormat, type, data);\n } else {\n gl.texImage2D(target, level, format, dataFormat, type, data);\n }\n break;\n case 'compressed':\n for (const [levelIndex, levelData] of data.entries()) {\n gl.compressedTexImage2D(\n target,\n levelIndex,\n levelData.format,\n levelData.width,\n levelData.height,\n border,\n levelData.data\n );\n }\n\n break;\n default:\n assert(false, 'Unknown image data type');\n }\n });\n\n if (data && data.byteLength) {\n this._trackAllocatedMemory(data.byteLength, 'Texture');\n } else {\n // NOTE(Tarek): Default to RGBA bytes\n const channels = DATA_FORMAT_CHANNELS[this.dataFormat] || 4;\n const channelSize = TYPE_SIZES[this.type] || 1;\n\n this._trackAllocatedMemory(this.width * this.height * channels * channelSize, 'Texture');\n }\n\n this.loaded = true;\n\n return this;\n }\n /* eslint-enable max-len, max-statements, complexity */\n\n /**\n * Redefines an area of an existing texture\n * Note: does not allocate storage\n */\n /*\n * Redefines an area of an existing texture\n * @param {*} pixels, data -\n * null - create empty texture of specified format\n * Typed array - init from image data in typed array\n * Buffer|WebGLBuffer - (WEBGL2) init from image data in WebGLBuffer\n * HTMLImageElement|Image - Inits with content of image. Auto width/height\n * HTMLCanvasElement - Inits with contents of canvas. Auto width/height\n * HTMLVideoElement - Creates video texture. Auto width/height\n *\n * @param {GLint} x - xOffset from where texture to be updated\n * @param {GLint} y - yOffset from where texture to be updated\n * @param {GLint} width - width of the sub image to be updated\n * @param {GLint} height - height of the sub image to be updated\n * @param {GLint} level - mip level to be updated\n * @param {GLenum} format - internal format of image data.\n * @param {GLenum} type\n * - format of array (autodetect from type) or\n * - (WEBGL2) format of buffer or ArrayBufferView\n * @param {GLenum} dataFormat - format of image data.\n * @param {Number} offset - (WEBGL2) offset from start of buffer\n * @param {GLint} border - must be 0.\n * @parameters - temporary settings to be applied, can be used to supply pixel store settings.\n */\n setSubImageData({\n target = this.target,\n pixels = null,\n data = null,\n x = 0,\n y = 0,\n width = this.width,\n height = this.height,\n level = 0,\n format = this.format,\n type = this.type,\n dataFormat = this.dataFormat,\n compressed = false,\n offset = 0,\n border = this.border,\n parameters = {}\n }) {\n ({type, dataFormat, compressed, width, height} = this._deduceParameters({\n format,\n type,\n dataFormat,\n compressed,\n data,\n width,\n height\n }));\n\n assert(this.depth === 0, 'texSubImage not supported for 3D textures');\n\n // pixels variable is for API compatibility purpose\n if (!data) {\n data = pixels;\n }\n\n // Support ndarrays\n if (data && data.data) {\n const ndarray = data;\n data = ndarray.data;\n width = ndarray.shape[0];\n height = ndarray.shape[1];\n }\n\n // Support buffers\n if (data instanceof Buffer) {\n data = data.handle;\n }\n\n this.gl.bindTexture(this.target, this.handle);\n\n withParameters(this.gl, parameters, () => {\n // TODO - x,y parameters\n if (compressed) {\n this.gl.compressedTexSubImage2D(target, level, x, y, width, height, format, data);\n } else if (data === null) {\n this.gl.texSubImage2D(target, level, x, y, width, height, dataFormat, type, null);\n } else if (ArrayBuffer.isView(data)) {\n // const gl2 = assertWebGL2Context(this.gl);\n // @ts-ignore last offset parameter is ignored under WebGL1\n this.gl.texSubImage2D(target, level, x, y, width, height, dataFormat, type, data, offset);\n } else if (data instanceof WebGLBuffer) {\n // WebGL2 allows us to create texture directly from a WebGL buffer\n const gl2 = assertWebGL2Context(this.gl);\n // This texImage2D signature uses currently bound GL.PIXEL_UNPACK_BUFFER\n gl2.bindBuffer(GL.PIXEL_UNPACK_BUFFER, data);\n gl2.texSubImage2D(target, level, x, y, width, height, dataFormat, type, offset);\n gl2.bindBuffer(GL.PIXEL_UNPACK_BUFFER, null);\n } else if (isWebGL2(this.gl)) {\n // Assume data is a browser supported object (ImageData, Canvas, ...)\n const gl2 = assertWebGL2Context(this.gl);\n gl2.texSubImage2D(target, level, x, y, width, height, dataFormat, type, data);\n } else {\n this.gl.texSubImage2D(target, level, x, y, dataFormat, type, data);\n }\n });\n\n this.gl.bindTexture(this.target, null);\n }\n /* eslint-enable max-len, max-statements, complexity */\n\n /**\n * Defines a two-dimensional texture image or cube-map texture image with\n * pixels from the current framebuffer (rather than from client memory).\n * (gl.copyTexImage2D wrapper)\n *\n * Note that binding a texture into a Framebuffer's color buffer and\n * rendering can be faster.\n */\n copyFramebuffer(opts = {}) {\n log.error(\n 'Texture.copyFramebuffer({...}) is no logner supported, use copyToTexture(source, target, opts})'\n )();\n return null;\n }\n\n getActiveUnit() {\n return this.gl.getParameter(GL.ACTIVE_TEXTURE) - GL.TEXTURE0;\n }\n\n // target cannot be modified by bind:\n // textures are special because when you first bind them to a target,\n // they get special information. When you first bind a texture as a\n // GL_TEXTURE_2D, you are actually setting special state in the texture.\n // You are saying that this texture is a 2D texture.\n // And it will always be a 2D texture; this state cannot be changed ever.\n // If you have a texture that was first bound as a GL_TEXTURE_2D,\n // you must always bind it as a GL_TEXTURE_2D;\n // attempting to bind it as GL_TEXTURE_1D will give rise to an error\n // (while run-time).\n\n bind(textureUnit = this.textureUnit) {\n const {gl} = this;\n\n if (textureUnit !== undefined) {\n this.textureUnit = textureUnit;\n gl.activeTexture(gl.TEXTURE0 + textureUnit);\n }\n\n gl.bindTexture(this.target, this.handle);\n return textureUnit;\n }\n\n unbind(textureUnit = this.textureUnit) {\n const {gl} = this;\n\n if (textureUnit !== undefined) {\n this.textureUnit = textureUnit;\n gl.activeTexture(gl.TEXTURE0 + textureUnit);\n }\n\n gl.bindTexture(this.target, null);\n return textureUnit;\n }\n\n // PRIVATE METHODS\n\n _getDataType({data, compressed = false}) {\n if (compressed) {\n return {data, dataType: 'compressed'};\n }\n if (data === null) {\n return {data, dataType: 'null'};\n }\n if (ArrayBuffer.isView(data)) {\n return {data, dataType: 'typed-array'};\n }\n if (data instanceof Buffer) {\n return {data: data.handle, dataType: 'buffer'};\n }\n if (data instanceof WebGLBuffer) {\n return {data, dataType: 'buffer'};\n }\n // Assume data is a browser supported object (ImageData, Canvas, ...)\n return {data, dataType: 'browser-object'};\n }\n\n /* Copied from texture-2d.js\n // WebGL2\n setPixels(opts = {}) {\n const {\n buffer,\n width = null,\n height = null,\n mipmapLevel = 0,\n format = GL.RGBA,\n type = GL.UNSIGNED_BYTE,\n border = 0\n } = opts;\n\n const {gl} = this;\n\n // This signature of texImage2D uses currently bound GL.PIXEL_UNPACK_BUFFER\n gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, buffer.target);\n // And as always, we must also bind the texture itself\n this.bind();\n\n gl.texImage2D(gl.TEXTURE_2D,\n mipmapLevel, format, width, height, border, format, type, buffer.target);\n\n this.unbind();\n gl.bindBuffer(GL.GL.PIXEL_UNPACK_BUFFER, null);\n return this;\n }\n\n setImageDataFromCompressedBuffer(opts) {\n const {\n buffer,\n // offset = 0,\n width = null,\n height = null,\n mipmapLevel = 0,\n internalFormat = GL.RGBA,\n // format = GL.RGBA,\n // type = GL.UNSIGNED_BYTE,\n border = 0\n } = opts;\n\n const {gl} = this;\n gl.compressedTexImage2D(this.target,\n mipmapLevel, internalFormat, width, height, border, buffer);\n // gl.compressedTexSubImage2D(target,\n // level, xoffset, yoffset, width, height, format, ArrayBufferView? pixels);\n return this;\n }\n\n copySubImage(opts) {\n const {\n // pixels,\n // offset = 0,\n // x,\n // y,\n // width,\n // height,\n // mipmapLevel = 0,\n // internalFormat = GL.RGBA,\n // type = GL.UNSIGNED_BYTE,\n // border = 0\n } = opts;\n\n // if (pixels instanceof ArrayBufferView) {\n // gl.texSubImage2D(target, level, x, y, width, height, format, type, pixels);\n // }\n // gl.texSubImage2D(target, level, x, y, format, type, ? pixels);\n // gl.texSubImage2D(target, level, x, y, format, type, HTMLImageElement pixels);\n // gl.texSubImage2D(target, level, x, y, format, type, HTMLCanvasElement pixels);\n // gl.texSubImage2D(target, level, x, y, format, type, HTMLVideoElement pixels);\n // // Additional signature in a WebGL 2 context:\n // gl.texSubImage2D(target, level, x, y, format, type, GLintptr offset);\n }\n */\n\n // HELPER METHODS\n\n _deduceParameters(opts) {\n const {format, data} = opts;\n let {width, height, dataFormat, type, compressed} = opts;\n\n // Deduce format and type from format\n const textureFormat = TEXTURE_FORMATS[format];\n dataFormat = dataFormat || (textureFormat && textureFormat.dataFormat);\n type = type || (textureFormat && textureFormat.types[0]);\n\n // Deduce compression from format\n compressed = compressed || (textureFormat && textureFormat.compressed);\n\n ({width, height} = this._deduceImageSize(data, width, height));\n\n return {dataFormat, type, compressed, width, height, format, data};\n }\n\n // eslint-disable-next-line complexity\n _deduceImageSize(data, width, height) {\n let size;\n\n if (typeof ImageData !== 'undefined' && data instanceof ImageData) {\n size = {width: data.width, height: data.height};\n } else if (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) {\n size = {width: data.naturalWidth, height: data.naturalHeight};\n } else if (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) {\n size = {width: data.width, height: data.height};\n } else if (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) {\n size = {width: data.width, height: data.height};\n } else if (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) {\n size = {width: data.videoWidth, height: data.videoHeight};\n } else if (!data) {\n size = {width: width >= 0 ? width : 1, height: height >= 0 ? height : 1};\n } else {\n size = {width, height};\n }\n\n assert(size, 'Could not deduced texture size');\n assert(\n width === undefined || size.width === width,\n 'Deduced texture width does not match supplied width'\n );\n assert(\n height === undefined || size.height === height,\n 'Deduced texture height does not match supplied height'\n );\n\n return size;\n }\n\n // RESOURCE METHODS\n\n _createHandle() {\n return this.gl.createTexture();\n }\n\n _deleteHandle() {\n this.gl.deleteTexture(this.handle);\n this._trackDeallocatedMemory('Texture');\n }\n\n _getParameter(pname) {\n switch (pname) {\n case GL.TEXTURE_WIDTH:\n return this.width;\n case GL.TEXTURE_HEIGHT:\n return this.height;\n default:\n this.gl.bindTexture(this.target, this.handle);\n const value = this.gl.getTexParameter(this.target, pname);\n this.gl.bindTexture(this.target, null);\n return value;\n }\n }\n\n _setParameter(pname, param) {\n this.gl.bindTexture(this.target, this.handle);\n\n // NOTE: Apply NPOT workaround\n param = this._getNPOTParam(pname, param);\n\n // Apparently there are some integer/float conversion rules that made\n // the WebGL committe expose two parameter setting functions in JavaScript.\n // For now, pick the float version for parameters specified as GLfloat.\n switch (pname) {\n case GL.TEXTURE_MIN_LOD:\n case GL.TEXTURE_MAX_LOD:\n this.gl.texParameterf(this.handle, pname, param);\n break;\n\n case GL.TEXTURE_WIDTH:\n case GL.TEXTURE_HEIGHT:\n assert(false);\n break;\n\n default:\n this.gl.texParameteri(this.target, pname, param);\n break;\n }\n\n this.gl.bindTexture(this.target, null);\n return this;\n }\n\n _isNPOT() {\n if (isWebGL2(this.gl)) {\n // NPOT restriction is only for WebGL1\n return false;\n }\n // Width and height not available, consider it is not NPOT texture\n if (!this.width || !this.height) {\n return false;\n }\n return !isPowerOfTwo(this.width) || !isPowerOfTwo(this.height);\n }\n\n // Update default settings which are not supported by NPOT textures.\n _updateForNPOT(parameters) {\n if (parameters[this.gl.TEXTURE_MIN_FILTER] === undefined) {\n // log.warn(`texture: ${this} is Non-Power-Of-Two, forcing TEXTURE_MIN_FILTER to LINEAR`)();\n parameters[this.gl.TEXTURE_MIN_FILTER] = this.gl.LINEAR;\n }\n if (parameters[this.gl.TEXTURE_WRAP_S] === undefined) {\n // log.warn(`texture: ${this} is Non-Power-Of-Two, forcing TEXTURE_WRAP_S to CLAMP_TO_EDGE`)();\n parameters[this.gl.TEXTURE_WRAP_S] = this.gl.CLAMP_TO_EDGE;\n }\n if (parameters[this.gl.TEXTURE_WRAP_T] === undefined) {\n // log.warn(`texture: ${this} is Non-Power-Of-Two, forcing TEXTURE_WRAP_T to CLAMP_TO_EDGE`)();\n parameters[this.gl.TEXTURE_WRAP_T] = this.gl.CLAMP_TO_EDGE;\n }\n }\n\n _getNPOTParam(pname, param) {\n if (this._isNPOT()) {\n switch (pname) {\n case GL.TEXTURE_MIN_FILTER:\n if (NPOT_MIN_FILTERS.indexOf(param) === -1) {\n // log.warn(`texture: ${this} is Non-Power-Of-Two, forcing TEXTURE_MIN_FILTER to LINEAR`)();\n param = GL.LINEAR;\n }\n break;\n case GL.TEXTURE_WRAP_S:\n case GL.TEXTURE_WRAP_T:\n if (param !== GL.CLAMP_TO_EDGE) {\n // log.warn(`texture: ${this} is Non-Power-Of-Two, ${getKey(this.gl, pname)} to CLAMP_TO_EDGE`)();\n param = GL.CLAMP_TO_EDGE;\n }\n break;\n default:\n break;\n }\n }\n return param;\n }\n}\n","import * as glMatrix from \"./common.js\";\n/**\r\n * 3x3 Matrix\r\n * @module mat3\r\n */\n\n/**\r\n * Creates a new identity mat3\r\n *\r\n * @returns {mat3} a new 3x3 matrix\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(9);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n }\n\n out[0] = 1;\n out[4] = 1;\n out[8] = 1;\n return out;\n}\n/**\r\n * Copies the upper-left 3x3 values into the given mat3.\r\n *\r\n * @param {mat3} out the receiving 3x3 matrix\r\n * @param {ReadonlyMat4} a the source 4x4 matrix\r\n * @returns {mat3} out\r\n */\n\nexport function fromMat4(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[4];\n out[4] = a[5];\n out[5] = a[6];\n out[6] = a[8];\n out[7] = a[9];\n out[8] = a[10];\n return out;\n}\n/**\r\n * Creates a new mat3 initialized with values from an existing matrix\r\n *\r\n * @param {ReadonlyMat3} a matrix to clone\r\n * @returns {mat3} a new 3x3 matrix\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\r\n * Copy the values from one mat3 to another\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\r\n * Create a new mat3 with the given values\r\n *\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\r\n * @returns {mat3} A new mat3\r\n */\n\nexport function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\r\n * Set the components of a mat3 to the given values\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\r\n * @returns {mat3} out\r\n */\n\nexport function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\r\n * Set a mat3 to the identity matrix\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @returns {mat3} out\r\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\r\n * Transpose the values of a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a12 = a[5];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a01;\n out[5] = a[7];\n out[6] = a02;\n out[7] = a12;\n } else {\n out[0] = a[0];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a[1];\n out[4] = a[4];\n out[5] = a[7];\n out[6] = a[2];\n out[7] = a[5];\n out[8] = a[8];\n }\n\n return out;\n}\n/**\r\n * Inverts a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b01 = a22 * a11 - a12 * a21;\n var b11 = -a22 * a10 + a12 * a20;\n var b21 = a21 * a10 - a11 * a20; // Calculate the determinant\n\n var det = a00 * b01 + a01 * b11 + a02 * b21;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = b01 * det;\n out[1] = (-a22 * a01 + a02 * a21) * det;\n out[2] = (a12 * a01 - a02 * a11) * det;\n out[3] = b11 * det;\n out[4] = (a22 * a00 - a02 * a20) * det;\n out[5] = (-a12 * a00 + a02 * a10) * det;\n out[6] = b21 * det;\n out[7] = (-a21 * a00 + a01 * a20) * det;\n out[8] = (a11 * a00 - a01 * a10) * det;\n return out;\n}\n/**\r\n * Calculates the adjugate of a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n out[0] = a11 * a22 - a12 * a21;\n out[1] = a02 * a21 - a01 * a22;\n out[2] = a01 * a12 - a02 * a11;\n out[3] = a12 * a20 - a10 * a22;\n out[4] = a00 * a22 - a02 * a20;\n out[5] = a02 * a10 - a00 * a12;\n out[6] = a10 * a21 - a11 * a20;\n out[7] = a01 * a20 - a00 * a21;\n out[8] = a00 * a11 - a01 * a10;\n return out;\n}\n/**\r\n * Calculates the determinant of a mat3\r\n *\r\n * @param {ReadonlyMat3} a the source matrix\r\n * @returns {Number} determinant of a\r\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);\n}\n/**\r\n * Multiplies two mat3's\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the first operand\r\n * @param {ReadonlyMat3} b the second operand\r\n * @returns {mat3} out\r\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b00 = b[0],\n b01 = b[1],\n b02 = b[2];\n var b10 = b[3],\n b11 = b[4],\n b12 = b[5];\n var b20 = b[6],\n b21 = b[7],\n b22 = b[8];\n out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n return out;\n}\n/**\r\n * Translate a mat3 by the given vector\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the matrix to translate\r\n * @param {ReadonlyVec2} v vector to translate by\r\n * @returns {mat3} out\r\n */\n\nexport function translate(out, a, v) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n x = v[0],\n y = v[1];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a10;\n out[4] = a11;\n out[5] = a12;\n out[6] = x * a00 + y * a10 + a20;\n out[7] = x * a01 + y * a11 + a21;\n out[8] = x * a02 + y * a12 + a22;\n return out;\n}\n/**\r\n * Rotates a mat3 by the given angle\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat3} out\r\n */\n\nexport function rotate(out, a, rad) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c * a00 + s * a10;\n out[1] = c * a01 + s * a11;\n out[2] = c * a02 + s * a12;\n out[3] = c * a10 - s * a00;\n out[4] = c * a11 - s * a01;\n out[5] = c * a12 - s * a02;\n out[6] = a20;\n out[7] = a21;\n out[8] = a22;\n return out;\n}\n/**\r\n * Scales the mat3 by the dimensions in the given vec2\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the matrix to rotate\r\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\r\n * @returns {mat3} out\r\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1];\n out[0] = x * a[0];\n out[1] = x * a[1];\n out[2] = x * a[2];\n out[3] = y * a[3];\n out[4] = y * a[4];\n out[5] = y * a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\r\n * Creates a matrix from a vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.translate(dest, dest, vec);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {ReadonlyVec2} v Translation vector\r\n * @returns {mat3} out\r\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = v[0];\n out[7] = v[1];\n out[8] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a given angle\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.rotate(dest, dest, rad);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat3} out\r\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = -s;\n out[4] = c;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a vector scaling\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.scale(dest, dest, vec);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {ReadonlyVec2} v Scaling vector\r\n * @returns {mat3} out\r\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = v[1];\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\r\n * Copies the values from a mat2d into a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat2d} a the matrix to copy\r\n * @returns {mat3} out\r\n **/\n\nexport function fromMat2d(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = 0;\n out[3] = a[2];\n out[4] = a[3];\n out[5] = 0;\n out[6] = a[4];\n out[7] = a[5];\n out[8] = 1;\n return out;\n}\n/**\r\n * Calculates a 3x3 matrix from the given quaternion\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {ReadonlyQuat} q Quaternion to create matrix from\r\n *\r\n * @returns {mat3} out\r\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[3] = yx - wz;\n out[6] = zx + wy;\n out[1] = yx + wz;\n out[4] = 1 - xx - zz;\n out[7] = zy - wx;\n out[2] = zx - wy;\n out[5] = zy + wx;\n out[8] = 1 - xx - yy;\n return out;\n}\n/**\r\n * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from\r\n *\r\n * @returns {mat3} out\r\n */\n\nexport function normalFromMat4(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n return out;\n}\n/**\r\n * Generates a 2D projection matrix with the given bounds\r\n *\r\n * @param {mat3} out mat3 frustum matrix will be written into\r\n * @param {number} width Width of your gl context\r\n * @param {number} height Height of gl context\r\n * @returns {mat3} out\r\n */\n\nexport function projection(out, width, height) {\n out[0] = 2 / width;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = -2 / height;\n out[5] = 0;\n out[6] = -1;\n out[7] = 1;\n out[8] = 1;\n return out;\n}\n/**\r\n * Returns a string representation of a mat3\r\n *\r\n * @param {ReadonlyMat3} a matrix to represent as a string\r\n * @returns {String} string representation of the matrix\r\n */\n\nexport function str(a) {\n return \"mat3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \")\";\n}\n/**\r\n * Returns Frobenius norm of a mat3\r\n *\r\n * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of\r\n * @returns {Number} Frobenius norm\r\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);\n}\n/**\r\n * Adds two mat3's\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the first operand\r\n * @param {ReadonlyMat3} b the second operand\r\n * @returns {mat3} out\r\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n return out;\n}\n/**\r\n * Subtracts matrix b from matrix a\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the first operand\r\n * @param {ReadonlyMat3} b the second operand\r\n * @returns {mat3} out\r\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n return out;\n}\n/**\r\n * Multiply each element of the matrix by a scalar.\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {ReadonlyMat3} a the matrix to scale\r\n * @param {Number} b amount to scale the matrix's elements by\r\n * @returns {mat3} out\r\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n return out;\n}\n/**\r\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\r\n *\r\n * @param {mat3} out the receiving vector\r\n * @param {ReadonlyMat3} a the first operand\r\n * @param {ReadonlyMat3} b the second operand\r\n * @param {Number} scale the amount to scale b's elements by before adding\r\n * @returns {mat3} out\r\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n return out;\n}\n/**\r\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {ReadonlyMat3} a The first matrix.\r\n * @param {ReadonlyMat3} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8];\n}\n/**\r\n * Returns whether or not the matrices have approximately the same elements in the same position.\r\n *\r\n * @param {ReadonlyMat3} a The first matrix.\r\n * @param {ReadonlyMat3} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3],\n a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7],\n a8 = a[8];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));\n}\n/**\r\n * Alias for {@link mat3.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link mat3.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","module.exports = function() {\n\tthrow new Error(\"define cannot be used indirect\");\n};\n","var _typeof = require(\"../helpers/typeof\");\n\nfunction _getRequireWildcardCache() {\n if (typeof WeakMap !== \"function\") return null;\n var cache = new WeakMap();\n\n _getRequireWildcardCache = function _getRequireWildcardCache() {\n return cache;\n };\n\n return cache;\n}\n\nfunction _interopRequireWildcard(obj) {\n if (obj && obj.__esModule) {\n return obj;\n }\n\n if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") {\n return {\n \"default\": obj\n };\n }\n\n var cache = _getRequireWildcardCache();\n\n if (cache && cache.has(obj)) {\n return cache.get(obj);\n }\n\n var newObj = {};\n var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;\n\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;\n\n if (desc && (desc.get || desc.set)) {\n Object.defineProperty(newObj, key, desc);\n } else {\n newObj[key] = obj[key];\n }\n }\n }\n\n newObj[\"default\"] = obj;\n\n if (cache) {\n cache.set(obj, newObj);\n }\n\n return newObj;\n}\n\nmodule.exports = _interopRequireWildcard;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"default\", {\n enumerable: true,\n get: function get() {\n return _utils.createSvgIcon;\n }\n});\n\nvar _utils = require(\"@material-ui/core/utils\");","var e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nexport default function(start, stop, count) {\n var reverse,\n i = -1,\n n,\n ticks,\n step;\n\n stop = +stop, start = +start, count = +count;\n if (start === stop && count > 0) return [start];\n if (reverse = stop < start) n = start, start = stop, stop = n;\n if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];\n\n if (step > 0) {\n let r0 = Math.round(start / step), r1 = Math.round(stop / step);\n if (r0 * step < start) ++r0;\n if (r1 * step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) * step;\n } else {\n step = -step;\n let r0 = Math.round(start * step), r1 = Math.round(stop * step);\n if (r0 / step < start) ++r0;\n if (r1 / step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) / step;\n }\n\n if (reverse) ticks.reverse();\n\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n var step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log(step) / Math.LN10),\n error = step / Math.pow(10, power);\n return power >= 0\n ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)\n : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);\n}\n\nexport function tickStep(start, stop, count) {\n var step0 = Math.abs(stop - start) / Math.max(0, count),\n step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),\n error = step0 / step1;\n if (error >= e10) step1 *= 10;\n else if (error >= e5) step1 *= 5;\n else if (error >= e2) step1 *= 2;\n return stop < start ? -step1 : step1;\n}\n","// [[fill]align][sign][symbol][0][width][,][.precision][~][type]\nvar re = /^(?:(.)?([<>=^]))?([+\\-( ])?([$#])?(0)?(\\d+)?(,)?(\\.\\d+)?(~)?([a-z%])?$/i;\n\nexport default function formatSpecifier(specifier) {\n if (!(match = re.exec(specifier))) throw new Error(\"invalid format: \" + specifier);\n var match;\n return new FormatSpecifier({\n fill: match[1],\n align: match[2],\n sign: match[3],\n symbol: match[4],\n zero: match[5],\n width: match[6],\n comma: match[7],\n precision: match[8] && match[8].slice(1),\n trim: match[9],\n type: match[10]\n });\n}\n\nformatSpecifier.prototype = FormatSpecifier.prototype; // instanceof\n\nexport function FormatSpecifier(specifier) {\n this.fill = specifier.fill === undefined ? \" \" : specifier.fill + \"\";\n this.align = specifier.align === undefined ? \">\" : specifier.align + \"\";\n this.sign = specifier.sign === undefined ? \"-\" : specifier.sign + \"\";\n this.symbol = specifier.symbol === undefined ? \"\" : specifier.symbol + \"\";\n this.zero = !!specifier.zero;\n this.width = specifier.width === undefined ? undefined : +specifier.width;\n this.comma = !!specifier.comma;\n this.precision = specifier.precision === undefined ? undefined : +specifier.precision;\n this.trim = !!specifier.trim;\n this.type = specifier.type === undefined ? \"\" : specifier.type + \"\";\n}\n\nFormatSpecifier.prototype.toString = function() {\n return this.fill\n + this.align\n + this.sign\n + this.symbol\n + (this.zero ? \"0\" : \"\")\n + (this.width === undefined ? \"\" : Math.max(1, this.width | 0))\n + (this.comma ? \",\" : \"\")\n + (this.precision === undefined ? \"\" : \".\" + Math.max(0, this.precision | 0))\n + (this.trim ? \"~\" : \"\")\n + this.type;\n};\n","export default function(x) {\n return Math.abs(x = Math.round(x)) >= 1e21\n ? x.toLocaleString(\"en\").replace(/,/g, \"\")\n : x.toString(10);\n}\n\n// Computes the decimal coefficient and exponent of the specified number x with\n// significant digits p, where x is positive and p is in [1, 21] or undefined.\n// For example, formatDecimalParts(1.23) returns [\"123\", 0].\nexport function formatDecimalParts(x, p) {\n if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf(\"e\")) < 0) return null; // NaN, ±Infinity\n var i, coefficient = x.slice(0, i);\n\n // The string returned by toExponential either has the form \\d\\.\\d+e[-+]\\d+\n // (e.g., 1.2e+3) or the form \\de[-+]\\d+ (e.g., 1e+3).\n return [\n coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,\n +x.slice(i + 1)\n ];\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x) {\n return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport var prefixExponent;\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1],\n i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,\n n = coefficient.length;\n return i === n ? coefficient\n : i > n ? coefficient + new Array(i - n + 1).join(\"0\")\n : i > 0 ? coefficient.slice(0, i) + \".\" + coefficient.slice(i)\n : \"0.\" + new Array(1 - i).join(\"0\") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!\n}\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var format;\nexport var formatPrefix;\n\ndefaultLocale({\n thousands: \",\",\n grouping: [3],\n currency: [\"$\", \"\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n format = locale.format;\n formatPrefix = locale.formatPrefix;\n return locale;\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1];\n return exponent < 0 ? \"0.\" + new Array(-exponent).join(\"0\") + coefficient\n : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + \".\" + coefficient.slice(exponent + 1)\n : coefficient + new Array(exponent - coefficient.length + 2).join(\"0\");\n}\n","import formatDecimal from \"./formatDecimal.js\";\nimport formatPrefixAuto from \"./formatPrefixAuto.js\";\nimport formatRounded from \"./formatRounded.js\";\n\nexport default {\n \"%\": (x, p) => (x * 100).toFixed(p),\n \"b\": (x) => Math.round(x).toString(2),\n \"c\": (x) => x + \"\",\n \"d\": formatDecimal,\n \"e\": (x, p) => x.toExponential(p),\n \"f\": (x, p) => x.toFixed(p),\n \"g\": (x, p) => x.toPrecision(p),\n \"o\": (x) => Math.round(x).toString(8),\n \"p\": (x, p) => formatRounded(x * 100, p),\n \"r\": formatRounded,\n \"s\": formatPrefixAuto,\n \"X\": (x) => Math.round(x).toString(16).toUpperCase(),\n \"x\": (x) => Math.round(x).toString(16)\n};\n","export default function(x) {\n return x;\n}\n","import exponent from \"./exponent.js\";\nimport formatGroup from \"./formatGroup.js\";\nimport formatNumerals from \"./formatNumerals.js\";\nimport formatSpecifier from \"./formatSpecifier.js\";\nimport formatTrim from \"./formatTrim.js\";\nimport formatTypes from \"./formatTypes.js\";\nimport {prefixExponent} from \"./formatPrefixAuto.js\";\nimport identity from \"./identity.js\";\n\nvar map = Array.prototype.map,\n prefixes = [\"y\",\"z\",\"a\",\"f\",\"p\",\"n\",\"µ\",\"m\",\"\",\"k\",\"M\",\"G\",\"T\",\"P\",\"E\",\"Z\",\"Y\"];\n\nexport default function(locale) {\n var group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + \"\"),\n currencyPrefix = locale.currency === undefined ? \"\" : locale.currency[0] + \"\",\n currencySuffix = locale.currency === undefined ? \"\" : locale.currency[1] + \"\",\n decimal = locale.decimal === undefined ? \".\" : locale.decimal + \"\",\n numerals = locale.numerals === undefined ? identity : formatNumerals(map.call(locale.numerals, String)),\n percent = locale.percent === undefined ? \"%\" : locale.percent + \"\",\n minus = locale.minus === undefined ? \"−\" : locale.minus + \"\",\n nan = locale.nan === undefined ? \"NaN\" : locale.nan + \"\";\n\n function newFormat(specifier) {\n specifier = formatSpecifier(specifier);\n\n var fill = specifier.fill,\n align = specifier.align,\n sign = specifier.sign,\n symbol = specifier.symbol,\n zero = specifier.zero,\n width = specifier.width,\n comma = specifier.comma,\n precision = specifier.precision,\n trim = specifier.trim,\n type = specifier.type;\n\n // The \"n\" type is an alias for \",g\".\n if (type === \"n\") comma = true, type = \"g\";\n\n // The \"\" type, and any invalid type, is an alias for \".12~g\".\n else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = \"g\";\n\n // If zero fill is specified, padding goes after sign and before digits.\n if (zero || (fill === \"0\" && align === \"=\")) zero = true, fill = \"0\", align = \"=\";\n\n // Compute the prefix and suffix.\n // For SI-prefix, the suffix is lazily computed.\n var prefix = symbol === \"$\" ? currencyPrefix : symbol === \"#\" && /[boxX]/.test(type) ? \"0\" + type.toLowerCase() : \"\",\n suffix = symbol === \"$\" ? currencySuffix : /[%p]/.test(type) ? percent : \"\";\n\n // What format function should we use?\n // Is this an integer type?\n // Can this type generate exponential notation?\n var formatType = formatTypes[type],\n maybeSuffix = /[defgprs%]/.test(type);\n\n // Set the default precision if not specified,\n // or clamp the specified precision to the supported range.\n // For significant precision, it must be in [1, 21].\n // For fixed precision, it must be in [0, 20].\n precision = precision === undefined ? 6\n : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))\n : Math.max(0, Math.min(20, precision));\n\n function format(value) {\n var valuePrefix = prefix,\n valueSuffix = suffix,\n i, n, c;\n\n if (type === \"c\") {\n valueSuffix = formatType(value) + valueSuffix;\n value = \"\";\n } else {\n value = +value;\n\n // Determine the sign. -0 is not less than 0, but 1 / -0 is!\n var valueNegative = value < 0 || 1 / value < 0;\n\n // Perform the initial formatting.\n value = isNaN(value) ? nan : formatType(Math.abs(value), precision);\n\n // Trim insignificant zeros.\n if (trim) value = formatTrim(value);\n\n // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.\n if (valueNegative && +value === 0 && sign !== \"+\") valueNegative = false;\n\n // Compute the prefix and suffix.\n valuePrefix = (valueNegative ? (sign === \"(\" ? sign : minus) : sign === \"-\" || sign === \"(\" ? \"\" : sign) + valuePrefix;\n valueSuffix = (type === \"s\" ? prefixes[8 + prefixExponent / 3] : \"\") + valueSuffix + (valueNegative && sign === \"(\" ? \")\" : \"\");\n\n // Break the formatted value into the integer “value” part that can be\n // grouped, and fractional or exponential “suffix” part that is not.\n if (maybeSuffix) {\n i = -1, n = value.length;\n while (++i < n) {\n if (c = value.charCodeAt(i), 48 > c || c > 57) {\n valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;\n value = value.slice(0, i);\n break;\n }\n }\n }\n }\n\n // If the fill character is not \"0\", grouping is applied before padding.\n if (comma && !zero) value = group(value, Infinity);\n\n // Compute the padding.\n var length = valuePrefix.length + value.length + valueSuffix.length,\n padding = length < width ? new Array(width - length + 1).join(fill) : \"\";\n\n // If the fill character is \"0\", grouping is applied after padding.\n if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = \"\";\n\n // Reconstruct the final output based on the desired alignment.\n switch (align) {\n case \"<\": value = valuePrefix + value + valueSuffix + padding; break;\n case \"=\": value = valuePrefix + padding + value + valueSuffix; break;\n case \"^\": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;\n default: value = padding + valuePrefix + value + valueSuffix; break;\n }\n\n return numerals(value);\n }\n\n format.toString = function() {\n return specifier + \"\";\n };\n\n return format;\n }\n\n function formatPrefix(specifier, value) {\n var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = \"f\", specifier)),\n e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,\n k = Math.pow(10, -e),\n prefix = prefixes[8 + e / 3];\n return function(value) {\n return f(k * value) + prefix;\n };\n }\n\n return {\n format: newFormat,\n formatPrefix: formatPrefix\n };\n}\n","export default function(grouping, thousands) {\n return function(value, width) {\n var i = value.length,\n t = [],\n j = 0,\n g = grouping[0],\n length = 0;\n\n while (i > 0 && g > 0) {\n if (length + g + 1 > width) g = Math.max(1, width - length);\n t.push(value.substring(i -= g, i + g));\n if ((length += g + 1) > width) break;\n g = grouping[j = (j + 1) % grouping.length];\n }\n\n return t.reverse().join(thousands);\n };\n}\n","export default function(numerals) {\n return function(value) {\n return value.replace(/[0-9]/g, function(i) {\n return numerals[+i];\n });\n };\n}\n","// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.\nexport default function(s) {\n out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {\n switch (s[i]) {\n case \".\": i0 = i1 = i; break;\n case \"0\": if (i0 === 0) i0 = i; i1 = i; break;\n default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;\n }\n }\n return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;\n}\n","import {\n timeDay,\n timeSunday,\n timeMonday,\n timeThursday,\n timeYear,\n utcDay,\n utcSunday,\n utcMonday,\n utcThursday,\n utcYear\n} from \"d3-time\";\n\nfunction localDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);\n date.setFullYear(d.y);\n return date;\n }\n return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);\n}\n\nfunction utcDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));\n date.setUTCFullYear(d.y);\n return date;\n }\n return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));\n}\n\nfunction newDate(y, m, d) {\n return {y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0};\n}\n\nexport default function formatLocale(locale) {\n var locale_dateTime = locale.dateTime,\n locale_date = locale.date,\n locale_time = locale.time,\n locale_periods = locale.periods,\n locale_weekdays = locale.days,\n locale_shortWeekdays = locale.shortDays,\n locale_months = locale.months,\n locale_shortMonths = locale.shortMonths;\n\n var periodRe = formatRe(locale_periods),\n periodLookup = formatLookup(locale_periods),\n weekdayRe = formatRe(locale_weekdays),\n weekdayLookup = formatLookup(locale_weekdays),\n shortWeekdayRe = formatRe(locale_shortWeekdays),\n shortWeekdayLookup = formatLookup(locale_shortWeekdays),\n monthRe = formatRe(locale_months),\n monthLookup = formatLookup(locale_months),\n shortMonthRe = formatRe(locale_shortMonths),\n shortMonthLookup = formatLookup(locale_shortMonths);\n\n var formats = {\n \"a\": formatShortWeekday,\n \"A\": formatWeekday,\n \"b\": formatShortMonth,\n \"B\": formatMonth,\n \"c\": null,\n \"d\": formatDayOfMonth,\n \"e\": formatDayOfMonth,\n \"f\": formatMicroseconds,\n \"g\": formatYearISO,\n \"G\": formatFullYearISO,\n \"H\": formatHour24,\n \"I\": formatHour12,\n \"j\": formatDayOfYear,\n \"L\": formatMilliseconds,\n \"m\": formatMonthNumber,\n \"M\": formatMinutes,\n \"p\": formatPeriod,\n \"q\": formatQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatSeconds,\n \"u\": formatWeekdayNumberMonday,\n \"U\": formatWeekNumberSunday,\n \"V\": formatWeekNumberISO,\n \"w\": formatWeekdayNumberSunday,\n \"W\": formatWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatYear,\n \"Y\": formatFullYear,\n \"Z\": formatZone,\n \"%\": formatLiteralPercent\n };\n\n var utcFormats = {\n \"a\": formatUTCShortWeekday,\n \"A\": formatUTCWeekday,\n \"b\": formatUTCShortMonth,\n \"B\": formatUTCMonth,\n \"c\": null,\n \"d\": formatUTCDayOfMonth,\n \"e\": formatUTCDayOfMonth,\n \"f\": formatUTCMicroseconds,\n \"g\": formatUTCYearISO,\n \"G\": formatUTCFullYearISO,\n \"H\": formatUTCHour24,\n \"I\": formatUTCHour12,\n \"j\": formatUTCDayOfYear,\n \"L\": formatUTCMilliseconds,\n \"m\": formatUTCMonthNumber,\n \"M\": formatUTCMinutes,\n \"p\": formatUTCPeriod,\n \"q\": formatUTCQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatUTCSeconds,\n \"u\": formatUTCWeekdayNumberMonday,\n \"U\": formatUTCWeekNumberSunday,\n \"V\": formatUTCWeekNumberISO,\n \"w\": formatUTCWeekdayNumberSunday,\n \"W\": formatUTCWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatUTCYear,\n \"Y\": formatUTCFullYear,\n \"Z\": formatUTCZone,\n \"%\": formatLiteralPercent\n };\n\n var parses = {\n \"a\": parseShortWeekday,\n \"A\": parseWeekday,\n \"b\": parseShortMonth,\n \"B\": parseMonth,\n \"c\": parseLocaleDateTime,\n \"d\": parseDayOfMonth,\n \"e\": parseDayOfMonth,\n \"f\": parseMicroseconds,\n \"g\": parseYear,\n \"G\": parseFullYear,\n \"H\": parseHour24,\n \"I\": parseHour24,\n \"j\": parseDayOfYear,\n \"L\": parseMilliseconds,\n \"m\": parseMonthNumber,\n \"M\": parseMinutes,\n \"p\": parsePeriod,\n \"q\": parseQuarter,\n \"Q\": parseUnixTimestamp,\n \"s\": parseUnixTimestampSeconds,\n \"S\": parseSeconds,\n \"u\": parseWeekdayNumberMonday,\n \"U\": parseWeekNumberSunday,\n \"V\": parseWeekNumberISO,\n \"w\": parseWeekdayNumberSunday,\n \"W\": parseWeekNumberMonday,\n \"x\": parseLocaleDate,\n \"X\": parseLocaleTime,\n \"y\": parseYear,\n \"Y\": parseFullYear,\n \"Z\": parseZone,\n \"%\": parseLiteralPercent\n };\n\n // These recursive directive definitions must be deferred.\n formats.x = newFormat(locale_date, formats);\n formats.X = newFormat(locale_time, formats);\n formats.c = newFormat(locale_dateTime, formats);\n utcFormats.x = newFormat(locale_date, utcFormats);\n utcFormats.X = newFormat(locale_time, utcFormats);\n utcFormats.c = newFormat(locale_dateTime, utcFormats);\n\n function newFormat(specifier, formats) {\n return function(date) {\n var string = [],\n i = -1,\n j = 0,\n n = specifier.length,\n c,\n pad,\n format;\n\n if (!(date instanceof Date)) date = new Date(+date);\n\n while (++i < n) {\n if (specifier.charCodeAt(i) === 37) {\n string.push(specifier.slice(j, i));\n if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);\n else pad = c === \"e\" ? \" \" : \"0\";\n if (format = formats[c]) c = format(date, pad);\n string.push(c);\n j = i + 1;\n }\n }\n\n string.push(specifier.slice(j, i));\n return string.join(\"\");\n };\n }\n\n function newParse(specifier, Z) {\n return function(string) {\n var d = newDate(1900, undefined, 1),\n i = parseSpecifier(d, specifier, string += \"\", 0),\n week, day;\n if (i != string.length) return null;\n\n // If a UNIX timestamp is specified, return it.\n if (\"Q\" in d) return new Date(d.Q);\n if (\"s\" in d) return new Date(d.s * 1000 + (\"L\" in d ? d.L : 0));\n\n // If this is utcParse, never use the local timezone.\n if (Z && !(\"Z\" in d)) d.Z = 0;\n\n // The am-pm flag is 0 for AM, and 1 for PM.\n if (\"p\" in d) d.H = d.H % 12 + d.p * 12;\n\n // If the month was not specified, inherit from the quarter.\n if (d.m === undefined) d.m = \"q\" in d ? d.q : 0;\n\n // Convert day-of-week and week-of-year to day-of-year.\n if (\"V\" in d) {\n if (d.V < 1 || d.V > 53) return null;\n if (!(\"w\" in d)) d.w = 1;\n if (\"Z\" in d) {\n week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay();\n week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week);\n week = utcDay.offset(week, (d.V - 1) * 7);\n d.y = week.getUTCFullYear();\n d.m = week.getUTCMonth();\n d.d = week.getUTCDate() + (d.w + 6) % 7;\n } else {\n week = localDate(newDate(d.y, 0, 1)), day = week.getDay();\n week = day > 4 || day === 0 ? timeMonday.ceil(week) : timeMonday(week);\n week = timeDay.offset(week, (d.V - 1) * 7);\n d.y = week.getFullYear();\n d.m = week.getMonth();\n d.d = week.getDate() + (d.w + 6) % 7;\n }\n } else if (\"W\" in d || \"U\" in d) {\n if (!(\"w\" in d)) d.w = \"u\" in d ? d.u % 7 : \"W\" in d ? 1 : 0;\n day = \"Z\" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();\n d.m = 0;\n d.d = \"W\" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;\n }\n\n // If a time zone is specified, all fields are interpreted as UTC and then\n // offset according to the specified time zone.\n if (\"Z\" in d) {\n d.H += d.Z / 100 | 0;\n d.M += d.Z % 100;\n return utcDate(d);\n }\n\n // Otherwise, all fields are in local time.\n return localDate(d);\n };\n }\n\n function parseSpecifier(d, specifier, string, j) {\n var i = 0,\n n = specifier.length,\n m = string.length,\n c,\n parse;\n\n while (i < n) {\n if (j >= m) return -1;\n c = specifier.charCodeAt(i++);\n if (c === 37) {\n c = specifier.charAt(i++);\n parse = parses[c in pads ? specifier.charAt(i++) : c];\n if (!parse || ((j = parse(d, string, j)) < 0)) return -1;\n } else if (c != string.charCodeAt(j++)) {\n return -1;\n }\n }\n\n return j;\n }\n\n function parsePeriod(d, string, i) {\n var n = periodRe.exec(string.slice(i));\n return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseShortWeekday(d, string, i) {\n var n = shortWeekdayRe.exec(string.slice(i));\n return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseWeekday(d, string, i) {\n var n = weekdayRe.exec(string.slice(i));\n return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseShortMonth(d, string, i) {\n var n = shortMonthRe.exec(string.slice(i));\n return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseMonth(d, string, i) {\n var n = monthRe.exec(string.slice(i));\n return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;\n }\n\n function parseLocaleDateTime(d, string, i) {\n return parseSpecifier(d, locale_dateTime, string, i);\n }\n\n function parseLocaleDate(d, string, i) {\n return parseSpecifier(d, locale_date, string, i);\n }\n\n function parseLocaleTime(d, string, i) {\n return parseSpecifier(d, locale_time, string, i);\n }\n\n function formatShortWeekday(d) {\n return locale_shortWeekdays[d.getDay()];\n }\n\n function formatWeekday(d) {\n return locale_weekdays[d.getDay()];\n }\n\n function formatShortMonth(d) {\n return locale_shortMonths[d.getMonth()];\n }\n\n function formatMonth(d) {\n return locale_months[d.getMonth()];\n }\n\n function formatPeriod(d) {\n return locale_periods[+(d.getHours() >= 12)];\n }\n\n function formatQuarter(d) {\n return 1 + ~~(d.getMonth() / 3);\n }\n\n function formatUTCShortWeekday(d) {\n return locale_shortWeekdays[d.getUTCDay()];\n }\n\n function formatUTCWeekday(d) {\n return locale_weekdays[d.getUTCDay()];\n }\n\n function formatUTCShortMonth(d) {\n return locale_shortMonths[d.getUTCMonth()];\n }\n\n function formatUTCMonth(d) {\n return locale_months[d.getUTCMonth()];\n }\n\n function formatUTCPeriod(d) {\n return locale_periods[+(d.getUTCHours() >= 12)];\n }\n\n function formatUTCQuarter(d) {\n return 1 + ~~(d.getUTCMonth() / 3);\n }\n\n return {\n format: function(specifier) {\n var f = newFormat(specifier += \"\", formats);\n f.toString = function() { return specifier; };\n return f;\n },\n parse: function(specifier) {\n var p = newParse(specifier += \"\", false);\n p.toString = function() { return specifier; };\n return p;\n },\n utcFormat: function(specifier) {\n var f = newFormat(specifier += \"\", utcFormats);\n f.toString = function() { return specifier; };\n return f;\n },\n utcParse: function(specifier) {\n var p = newParse(specifier += \"\", true);\n p.toString = function() { return specifier; };\n return p;\n }\n };\n}\n\nvar pads = {\"-\": \"\", \"_\": \" \", \"0\": \"0\"},\n numberRe = /^\\s*\\d+/, // note: ignores next directive\n percentRe = /^%/,\n requoteRe = /[\\\\^$*+?|[\\]().{}]/g;\n\nfunction pad(value, fill, width) {\n var sign = value < 0 ? \"-\" : \"\",\n string = (sign ? -value : value) + \"\",\n length = string.length;\n return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);\n}\n\nfunction requote(s) {\n return s.replace(requoteRe, \"\\\\$&\");\n}\n\nfunction formatRe(names) {\n return new RegExp(\"^(?:\" + names.map(requote).join(\"|\") + \")\", \"i\");\n}\n\nfunction formatLookup(names) {\n return new Map(names.map((name, i) => [name.toLowerCase(), i]));\n}\n\nfunction parseWeekdayNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.w = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekdayNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.u = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.U = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberISO(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.V = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.W = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseFullYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 4));\n return n ? (d.y = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;\n}\n\nfunction parseZone(d, string, i) {\n var n = /^(Z)|([+-]\\d\\d)(?::?(\\d\\d))?/.exec(string.slice(i, i + 6));\n return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || \"00\")), i + n[0].length) : -1;\n}\n\nfunction parseQuarter(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;\n}\n\nfunction parseMonthNumber(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.m = n[0] - 1, i + n[0].length) : -1;\n}\n\nfunction parseDayOfMonth(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseDayOfYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseHour24(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.H = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMinutes(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.M = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.S = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMilliseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.L = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMicroseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 6));\n return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;\n}\n\nfunction parseLiteralPercent(d, string, i) {\n var n = percentRe.exec(string.slice(i, i + 1));\n return n ? i + n[0].length : -1;\n}\n\nfunction parseUnixTimestamp(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.Q = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseUnixTimestampSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.s = +n[0], i + n[0].length) : -1;\n}\n\nfunction formatDayOfMonth(d, p) {\n return pad(d.getDate(), p, 2);\n}\n\nfunction formatHour24(d, p) {\n return pad(d.getHours(), p, 2);\n}\n\nfunction formatHour12(d, p) {\n return pad(d.getHours() % 12 || 12, p, 2);\n}\n\nfunction formatDayOfYear(d, p) {\n return pad(1 + timeDay.count(timeYear(d), d), p, 3);\n}\n\nfunction formatMilliseconds(d, p) {\n return pad(d.getMilliseconds(), p, 3);\n}\n\nfunction formatMicroseconds(d, p) {\n return formatMilliseconds(d, p) + \"000\";\n}\n\nfunction formatMonthNumber(d, p) {\n return pad(d.getMonth() + 1, p, 2);\n}\n\nfunction formatMinutes(d, p) {\n return pad(d.getMinutes(), p, 2);\n}\n\nfunction formatSeconds(d, p) {\n return pad(d.getSeconds(), p, 2);\n}\n\nfunction formatWeekdayNumberMonday(d) {\n var day = d.getDay();\n return day === 0 ? 7 : day;\n}\n\nfunction formatWeekNumberSunday(d, p) {\n return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction dISO(d) {\n var day = d.getDay();\n return (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n}\n\nfunction formatWeekNumberISO(d, p) {\n d = dISO(d);\n return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);\n}\n\nfunction formatWeekdayNumberSunday(d) {\n return d.getDay();\n}\n\nfunction formatWeekNumberMonday(d, p) {\n return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction formatYear(d, p) {\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatYearISO(d, p) {\n d = dISO(d);\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatFullYear(d, p) {\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatFullYearISO(d, p) {\n var day = d.getDay();\n d = (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatZone(d) {\n var z = d.getTimezoneOffset();\n return (z > 0 ? \"-\" : (z *= -1, \"+\"))\n + pad(z / 60 | 0, \"0\", 2)\n + pad(z % 60, \"0\", 2);\n}\n\nfunction formatUTCDayOfMonth(d, p) {\n return pad(d.getUTCDate(), p, 2);\n}\n\nfunction formatUTCHour24(d, p) {\n return pad(d.getUTCHours(), p, 2);\n}\n\nfunction formatUTCHour12(d, p) {\n return pad(d.getUTCHours() % 12 || 12, p, 2);\n}\n\nfunction formatUTCDayOfYear(d, p) {\n return pad(1 + utcDay.count(utcYear(d), d), p, 3);\n}\n\nfunction formatUTCMilliseconds(d, p) {\n return pad(d.getUTCMilliseconds(), p, 3);\n}\n\nfunction formatUTCMicroseconds(d, p) {\n return formatUTCMilliseconds(d, p) + \"000\";\n}\n\nfunction formatUTCMonthNumber(d, p) {\n return pad(d.getUTCMonth() + 1, p, 2);\n}\n\nfunction formatUTCMinutes(d, p) {\n return pad(d.getUTCMinutes(), p, 2);\n}\n\nfunction formatUTCSeconds(d, p) {\n return pad(d.getUTCSeconds(), p, 2);\n}\n\nfunction formatUTCWeekdayNumberMonday(d) {\n var dow = d.getUTCDay();\n return dow === 0 ? 7 : dow;\n}\n\nfunction formatUTCWeekNumberSunday(d, p) {\n return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction UTCdISO(d) {\n var day = d.getUTCDay();\n return (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n}\n\nfunction formatUTCWeekNumberISO(d, p) {\n d = UTCdISO(d);\n return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);\n}\n\nfunction formatUTCWeekdayNumberSunday(d) {\n return d.getUTCDay();\n}\n\nfunction formatUTCWeekNumberMonday(d, p) {\n return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction formatUTCYear(d, p) {\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCYearISO(d, p) {\n d = UTCdISO(d);\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCFullYear(d, p) {\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCFullYearISO(d, p) {\n var day = d.getUTCDay();\n d = (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCZone() {\n return \"+0000\";\n}\n\nfunction formatLiteralPercent() {\n return \"%\";\n}\n\nfunction formatUnixTimestamp(d) {\n return +d;\n}\n\nfunction formatUnixTimestampSeconds(d) {\n return Math.floor(+d / 1000);\n}\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var timeFormat;\nexport var timeParse;\nexport var utcFormat;\nexport var utcParse;\n\ndefaultLocale({\n dateTime: \"%x, %X\",\n date: \"%-m/%-d/%Y\",\n time: \"%-I:%M:%S %p\",\n periods: [\"AM\", \"PM\"],\n days: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n shortDays: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n months: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n shortMonths: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n timeFormat = locale.format;\n timeParse = locale.parse;\n utcFormat = locale.utcFormat;\n utcParse = locale.utcParse;\n return locale;\n}\n","import { tickStep } from 'd3-array';\nimport { formatSpecifier, precisionFixed, precisionRound, precisionPrefix, formatLocale, format, formatPrefix } from 'd3-format';\nimport { SECONDS, MINUTES, HOURS, DATE, WEEK, MONTH, QUARTER, YEAR, MILLISECONDS, DAY, timeInterval, utcInterval } from 'vega-time';\nimport { isString, isObject, error, extend } from 'vega-util';\nimport { timeFormat, timeParse, utcFormat, utcParse, timeFormatLocale as timeFormatLocale$1 } from 'd3-time-format';\n\nfunction memoize (method) {\n const cache = {};\n return spec => cache[spec] || (cache[spec] = method(spec));\n}\n\nfunction trimZeroes(numberFormat, decimalChar) {\n return x => {\n const str = numberFormat(x),\n dec = str.indexOf(decimalChar);\n if (dec < 0) return str;\n let idx = rightmostDigit(str, dec);\n const end = idx < str.length ? str.slice(idx) : '';\n\n while (--idx > dec) if (str[idx] !== '0') {\n ++idx;\n break;\n }\n\n return str.slice(0, idx) + end;\n };\n}\n\nfunction rightmostDigit(str, dec) {\n let i = str.lastIndexOf('e'),\n c;\n if (i > 0) return i;\n\n for (i = str.length; --i > dec;) {\n c = str.charCodeAt(i);\n if (c >= 48 && c <= 57) return i + 1; // is digit\n }\n}\n\nfunction numberLocale(locale) {\n const format = memoize(locale.format),\n formatPrefix = locale.formatPrefix;\n return {\n format,\n formatPrefix,\n\n formatFloat(spec) {\n const s = formatSpecifier(spec || ',');\n\n if (s.precision == null) {\n s.precision = 12;\n\n switch (s.type) {\n case '%':\n s.precision -= 2;\n break;\n\n case 'e':\n s.precision -= 1;\n break;\n }\n\n return trimZeroes(format(s), // number format\n format('.1f')(1)[1] // decimal point character\n );\n } else {\n return format(s);\n }\n },\n\n formatSpan(start, stop, count, specifier) {\n specifier = formatSpecifier(specifier == null ? ',f' : specifier);\n const step = tickStep(start, stop, count),\n value = Math.max(Math.abs(start), Math.abs(stop));\n let precision;\n\n if (specifier.precision == null) {\n switch (specifier.type) {\n case 's':\n {\n if (!isNaN(precision = precisionPrefix(step, value))) {\n specifier.precision = precision;\n }\n\n return formatPrefix(specifier, value);\n }\n\n case '':\n case 'e':\n case 'g':\n case 'p':\n case 'r':\n {\n if (!isNaN(precision = precisionRound(step, value))) {\n specifier.precision = precision - (specifier.type === 'e');\n }\n\n break;\n }\n\n case 'f':\n case '%':\n {\n if (!isNaN(precision = precisionFixed(step))) {\n specifier.precision = precision - (specifier.type === '%') * 2;\n }\n\n break;\n }\n }\n }\n\n return format(specifier);\n }\n\n };\n}\n\nlet defaultNumberLocale;\nresetNumberFormatDefaultLocale();\nfunction resetNumberFormatDefaultLocale() {\n return defaultNumberLocale = numberLocale({\n format: format,\n formatPrefix: formatPrefix\n });\n}\nfunction numberFormatLocale(definition) {\n return numberLocale(formatLocale(definition));\n}\nfunction numberFormatDefaultLocale(definition) {\n return arguments.length ? defaultNumberLocale = numberFormatLocale(definition) : defaultNumberLocale;\n}\n\nfunction timeMultiFormat(format, interval, spec) {\n spec = spec || {};\n\n if (!isObject(spec)) {\n error(\"Invalid time multi-format specifier: \".concat(spec));\n }\n\n const second = interval(SECONDS),\n minute = interval(MINUTES),\n hour = interval(HOURS),\n day = interval(DATE),\n week = interval(WEEK),\n month = interval(MONTH),\n quarter = interval(QUARTER),\n year = interval(YEAR),\n L = format(spec[MILLISECONDS] || '.%L'),\n S = format(spec[SECONDS] || ':%S'),\n M = format(spec[MINUTES] || '%I:%M'),\n H = format(spec[HOURS] || '%I %p'),\n d = format(spec[DATE] || spec[DAY] || '%a %d'),\n w = format(spec[WEEK] || '%b %d'),\n m = format(spec[MONTH] || '%B'),\n q = format(spec[QUARTER] || '%B'),\n y = format(spec[YEAR] || '%Y');\n return date => (second(date) < date ? L : minute(date) < date ? S : hour(date) < date ? M : day(date) < date ? H : month(date) < date ? week(date) < date ? d : w : year(date) < date ? quarter(date) < date ? m : q : y)(date);\n}\n\nfunction timeLocale(locale) {\n const timeFormat = memoize(locale.format),\n utcFormat = memoize(locale.utcFormat);\n return {\n timeFormat: spec => isString(spec) ? timeFormat(spec) : timeMultiFormat(timeFormat, timeInterval, spec),\n utcFormat: spec => isString(spec) ? utcFormat(spec) : timeMultiFormat(utcFormat, utcInterval, spec),\n timeParse: memoize(locale.parse),\n utcParse: memoize(locale.utcParse)\n };\n}\n\nlet defaultTimeLocale;\nresetTimeFormatDefaultLocale();\nfunction resetTimeFormatDefaultLocale() {\n return defaultTimeLocale = timeLocale({\n format: timeFormat,\n parse: timeParse,\n utcFormat: utcFormat,\n utcParse: utcParse\n });\n}\nfunction timeFormatLocale(definition) {\n return timeLocale(timeFormatLocale$1(definition));\n}\nfunction timeFormatDefaultLocale(definition) {\n return arguments.length ? defaultTimeLocale = timeFormatLocale(definition) : defaultTimeLocale;\n}\n\nconst createLocale = (number, time) => extend({}, number, time);\n\nfunction locale(numberSpec, timeSpec) {\n const number = numberSpec ? numberFormatLocale(numberSpec) : numberFormatDefaultLocale();\n const time = timeSpec ? timeFormatLocale(timeSpec) : timeFormatDefaultLocale();\n return createLocale(number, time);\n}\nfunction defaultLocale(numberSpec, timeSpec) {\n const args = arguments.length;\n\n if (args && args !== 2) {\n error('defaultLocale expects either zero or two arguments.');\n }\n\n return args ? createLocale(numberFormatDefaultLocale(numberSpec), timeFormatDefaultLocale(timeSpec)) : createLocale(numberFormatDefaultLocale(), timeFormatDefaultLocale());\n}\nfunction resetDefaultLocale() {\n resetNumberFormatDefaultLocale();\n resetTimeFormatDefaultLocale();\n return defaultLocale();\n}\n\nexport { defaultLocale, locale, numberFormatDefaultLocale, numberFormatLocale, resetDefaultLocale, resetNumberFormatDefaultLocale, resetTimeFormatDefaultLocale, timeFormatDefaultLocale, timeFormatLocale };\n","import exponent from \"./exponent.js\";\n\nexport default function(step, value) {\n return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step, max) {\n step = Math.abs(step), max = Math.abs(max) - step;\n return Math.max(0, exponent(max) - exponent(step)) + 1;\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step) {\n return Math.max(0, -exponent(Math.abs(step)));\n}\n","/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document,\n process: typeof process === 'object' && process\n};\n\nconst self_ = globals.self || globals.window || globals.global;\nconst window_ = globals.window || globals.self || globals.global;\nconst global_ = globals.global || globals.self || globals.window;\nconst document_ = globals.document || {};\nconst process_ = globals.process || {};\nconst console_ = console;\n\nexport {\n self_ as self,\n window_ as window,\n global_ as global,\n document_ as document,\n process_ as process,\n console_ as console\n};\n","// Copyright (c) 2015 Uber Technologies, Inc.\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/* eslint-disable max-statements, complexity */\nimport TransitionManager, {TRANSITION_EVENTS} from './transition-manager';\nimport LinearInterpolator from '../transitions/linear-interpolator';\n\nconst NO_TRANSITION_PROPS = {\n transitionDuration: 0\n};\n\nconst LINEAR_TRANSITION_PROPS = {\n transitionDuration: 300,\n transitionEasing: t => t,\n transitionInterruption: TRANSITION_EVENTS.BREAK\n};\n\nconst DEFAULT_INERTIA = 300;\nconst INERTIA_EASING = t => 1 - (1 - t) * (1 - t);\n\nconst EVENT_TYPES = {\n WHEEL: ['wheel'],\n PAN: ['panstart', 'panmove', 'panend'],\n PINCH: ['pinchstart', 'pinchmove', 'pinchend'],\n TRIPLE_PAN: ['tripanstart', 'tripanmove', 'tripanend'],\n DOUBLE_TAP: ['doubletap'],\n KEYBOARD: ['keydown']\n};\n\nexport default class Controller {\n constructor(ControllerState, options = {}) {\n this.ControllerState = ControllerState;\n this.controllerState = null;\n this.controllerStateProps = null;\n this.eventManager = null;\n this.transitionManager = new TransitionManager(ControllerState, {\n ...options,\n onViewStateChange: this._onTransition.bind(this),\n onStateChange: this._setInteractionState.bind(this)\n });\n\n const linearTransitionProps = this.linearTransitionProps;\n this._transition = linearTransitionProps && {\n ...LINEAR_TRANSITION_PROPS,\n transitionInterpolator: new LinearInterpolator({\n transitionProps: linearTransitionProps\n })\n };\n\n this._events = null;\n this._interactionState = {\n isDragging: false\n };\n this._customEvents = [];\n this.onViewStateChange = null;\n this.onStateChange = null;\n\n this.handleEvent = this.handleEvent.bind(this);\n\n this.setProps(options);\n }\n\n get linearTransitionProps() {\n return null;\n }\n\n set events(customEvents) {\n this.toggleEvents(this._customEvents, false);\n this.toggleEvents(customEvents, true);\n this._customEvents = customEvents;\n // Make sure default events are not overwritten\n this.setProps(this.controllerStateProps);\n }\n\n finalize() {\n for (const eventName in this._events) {\n if (this._events[eventName]) {\n this.eventManager.off(eventName, this.handleEvent);\n }\n }\n this.transitionManager.finalize();\n }\n\n /**\n * Callback for events\n * @param {hammer.Event} event\n */\n handleEvent(event) {\n const {ControllerState} = this;\n this.controllerState = new ControllerState({\n makeViewport: this.makeViewport,\n ...this.controllerStateProps,\n ...this._state\n });\n const eventStartBlocked = this._eventStartBlocked;\n\n switch (event.type) {\n case 'panstart':\n return eventStartBlocked ? false : this._onPanStart(event);\n case 'panmove':\n return this._onPan(event);\n case 'panend':\n return this._onPanEnd(event);\n case 'pinchstart':\n return eventStartBlocked ? false : this._onPinchStart(event);\n case 'pinchmove':\n return this._onPinch(event);\n case 'pinchend':\n return this._onPinchEnd(event);\n case 'tripanstart':\n return eventStartBlocked ? false : this._onTriplePanStart(event);\n case 'tripanmove':\n return this._onTriplePan(event);\n case 'tripanend':\n return this._onTriplePanEnd(event);\n case 'doubletap':\n return this._onDoubleTap(event);\n case 'wheel':\n return this._onWheel(event);\n case 'keydown':\n return this._onKeyDown(event);\n default:\n return false;\n }\n }\n\n /* Event utils */\n // Event object: http://hammerjs.github.io/api/#event-object\n getCenter(event) {\n const {x, y} = this.controllerStateProps;\n const {offsetCenter} = event;\n return [offsetCenter.x - x, offsetCenter.y - y];\n }\n\n isPointInBounds(pos, event) {\n const {width, height} = this.controllerStateProps;\n if (event && event.handled) {\n return false;\n }\n\n const inside = pos[0] >= 0 && pos[0] <= width && pos[1] >= 0 && pos[1] <= height;\n if (inside && event) {\n event.stopPropagation();\n }\n return inside;\n }\n\n isFunctionKeyPressed(event) {\n const {srcEvent} = event;\n return Boolean(srcEvent.metaKey || srcEvent.altKey || srcEvent.ctrlKey || srcEvent.shiftKey);\n }\n\n isDragging() {\n return this._interactionState.isDragging;\n }\n\n // When a multi-touch event ends, e.g. pinch, not all pointers are lifted at the same time.\n // This triggers a brief `pan` event.\n // Calling this method will temporarily disable *start events to avoid conflicting transitions.\n blockEvents(timeout) {\n /* global setTimeout */\n const timer = setTimeout(() => {\n if (this._eventStartBlocked === timer) {\n this._eventStartBlocked = null;\n }\n }, timeout);\n this._eventStartBlocked = timer;\n }\n\n /**\n * Extract interactivity options\n */\n setProps(props) {\n if ('onViewStateChange' in props) {\n this.onViewStateChange = props.onViewStateChange;\n }\n if ('onStateChange' in props) {\n this.onStateChange = props.onStateChange;\n }\n if ('makeViewport' in props) {\n this.makeViewport = props.makeViewport;\n }\n if ('dragMode' in props) {\n this.dragMode = props.dragMode;\n }\n this.controllerStateProps = props;\n\n if ('eventManager' in props && this.eventManager !== props.eventManager) {\n // EventManager has changed\n this.eventManager = props.eventManager;\n this._events = {};\n this.toggleEvents(this._customEvents, true);\n }\n\n if (!('transitionInterpolator' in props)) {\n // Add default transition interpolator\n props.transitionInterpolator = this._getTransitionProps().transitionInterpolator;\n }\n\n this.transitionManager.processViewStateChange(props);\n\n let {inertia} = props;\n if (inertia === true) {\n inertia = DEFAULT_INERTIA;\n }\n this.inertia = inertia;\n\n // TODO - make sure these are not reset on every setProps\n const {\n scrollZoom = true,\n dragPan = true,\n dragRotate = true,\n doubleClickZoom = true,\n touchZoom = true,\n touchRotate = false,\n keyboard = true\n } = props;\n\n // Register/unregister events\n const isInteractive = Boolean(this.onViewStateChange);\n this.toggleEvents(EVENT_TYPES.WHEEL, isInteractive && scrollZoom);\n this.toggleEvents(EVENT_TYPES.PAN, isInteractive && (dragPan || dragRotate));\n this.toggleEvents(EVENT_TYPES.PINCH, isInteractive && (touchZoom || touchRotate));\n this.toggleEvents(EVENT_TYPES.TRIPLE_PAN, isInteractive && touchRotate);\n this.toggleEvents(EVENT_TYPES.DOUBLE_TAP, isInteractive && doubleClickZoom);\n this.toggleEvents(EVENT_TYPES.KEYBOARD, isInteractive && keyboard);\n\n // Interaction toggles\n this.scrollZoom = scrollZoom;\n this.dragPan = dragPan;\n this.dragRotate = dragRotate;\n this.doubleClickZoom = doubleClickZoom;\n this.touchZoom = touchZoom;\n this.touchRotate = touchRotate;\n this.keyboard = keyboard;\n }\n\n updateTransition() {\n this.transitionManager.updateTransition();\n }\n\n toggleEvents(eventNames, enabled) {\n if (this.eventManager) {\n eventNames.forEach(eventName => {\n if (this._events[eventName] !== enabled) {\n this._events[eventName] = enabled;\n if (enabled) {\n this.eventManager.on(eventName, this.handleEvent);\n } else {\n this.eventManager.off(eventName, this.handleEvent);\n }\n }\n });\n }\n }\n\n // Private Methods\n\n /* Callback util */\n // formats map state and invokes callback function\n updateViewport(newControllerState, extraProps = {}, interactionState = {}) {\n const viewState = {...newControllerState.getViewportProps(), ...extraProps};\n\n // TODO - to restore diffing, we need to include interactionState\n const changed = this.controllerState !== newControllerState;\n // const oldViewState = this.controllerState.getViewportProps();\n // const changed = Object.keys(viewState).some(key => oldViewState[key] !== viewState[key]);\n\n this._state = newControllerState.getState();\n this._setInteractionState(interactionState);\n\n if (changed) {\n const oldViewState = this.controllerState ? this.controllerState.getViewportProps() : null;\n if (this.onViewStateChange) {\n this.onViewStateChange({viewState, interactionState: this._interactionState, oldViewState});\n }\n }\n }\n\n _onTransition(params) {\n if (this.onViewStateChange) {\n params.interactionState = this._interactionState;\n this.onViewStateChange(params);\n }\n }\n\n _setInteractionState(newStates) {\n Object.assign(this._interactionState, newStates);\n if (this.onStateChange) {\n this.onStateChange(this._interactionState);\n }\n }\n\n /* Event handlers */\n // Default handler for the `panstart` event.\n _onPanStart(event) {\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n let alternateMode = this.isFunctionKeyPressed(event) || event.rightButton;\n if (this.invertPan || this.dragMode === 'pan') {\n // invertPan is replaced by props.dragMode, keeping for backward compatibility\n alternateMode = !alternateMode;\n }\n const newControllerState = this.controllerState[alternateMode ? 'panStart' : 'rotateStart']({\n pos\n });\n this._panMove = alternateMode;\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});\n return true;\n }\n\n // Default handler for the `panmove` and `panend` event.\n _onPan(event) {\n if (!this.isDragging()) {\n return false;\n }\n return this._panMove ? this._onPanMove(event) : this._onPanRotate(event);\n }\n\n _onPanEnd(event) {\n if (!this.isDragging()) {\n return false;\n }\n return this._panMove ? this._onPanMoveEnd(event) : this._onPanRotateEnd(event);\n }\n\n // Default handler for panning to move.\n // Called by `_onPan` when panning without function key pressed.\n _onPanMove(event) {\n if (!this.dragPan) {\n return false;\n }\n const pos = this.getCenter(event);\n const newControllerState = this.controllerState.pan({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isPanning: true\n });\n return true;\n }\n\n _onPanMoveEnd(event) {\n const {inertia} = this;\n if (this.dragPan && inertia && event.velocity) {\n const pos = this.getCenter(event);\n const endPos = [\n pos[0] + (event.velocityX * inertia) / 2,\n pos[1] + (event.velocityY * inertia) / 2\n ];\n const newControllerState = this.controllerState.pan({pos: endPos}).panEnd();\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps(),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isPanning: true\n }\n );\n } else {\n const newControllerState = this.controllerState.panEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isPanning: false\n });\n }\n return true;\n }\n\n // Default handler for panning to rotate.\n // Called by `_onPan` when panning with function key pressed.\n _onPanRotate(event) {\n if (!this.dragRotate) {\n return false;\n }\n\n const pos = this.getCenter(event);\n const newControllerState = this.controllerState.rotate({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isRotating: true\n });\n return true;\n }\n\n _onPanRotateEnd(event) {\n const {inertia} = this;\n if (this.dragRotate && inertia && event.velocity) {\n const pos = this.getCenter(event);\n const endPos = [\n pos[0] + (event.velocityX * inertia) / 2,\n pos[1] + (event.velocityY * inertia) / 2\n ];\n const newControllerState = this.controllerState.rotate({pos: endPos}).rotateEnd();\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps(),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isRotating: true\n }\n );\n } else {\n const newControllerState = this.controllerState.rotateEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isRotating: false\n });\n }\n return true;\n }\n\n // Default handler for the `wheel` event.\n _onWheel(event) {\n if (!this.scrollZoom) {\n return false;\n }\n event.preventDefault();\n\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n\n const {speed = 0.01, smooth = false} = this.scrollZoom;\n const {delta} = event;\n\n // Map wheel delta to relative scale\n let scale = 2 / (1 + Math.exp(-Math.abs(delta * speed)));\n if (delta < 0 && scale !== 0) {\n scale = 1 / scale;\n }\n\n const newControllerState = this.controllerState.zoom({pos, scale});\n this.updateViewport(\n newControllerState,\n {...this._getTransitionProps({around: pos}), transitionDuration: smooth ? 250 : 1},\n {\n isZooming: true,\n isPanning: true\n }\n );\n return true;\n }\n\n _onTriplePanStart(event) {\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n const newControllerState = this.controllerState.rotateStart({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});\n return true;\n }\n\n _onTriplePan(event) {\n if (!this.touchRotate) {\n return false;\n }\n if (!this.isDragging()) {\n return false;\n }\n\n const pos = this.getCenter(event);\n pos[0] -= event.deltaX;\n\n const newControllerState = this.controllerState.rotate({pos});\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isRotating: true\n });\n return true;\n }\n\n _onTriplePanEnd(event) {\n if (!this.isDragging()) {\n return false;\n }\n const {inertia} = this;\n if (this.touchRotate && inertia && event.velocityY) {\n const pos = this.getCenter(event);\n const endPos = [pos[0], (pos[1] += (event.velocityY * inertia) / 2)];\n const newControllerState = this.controllerState.rotate({pos: endPos});\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps(),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isRotating: true\n }\n );\n this.blockEvents(inertia);\n } else {\n const newControllerState = this.controllerState.rotateEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isRotating: false\n });\n }\n return true;\n }\n\n // Default handler for the `pinchstart` event.\n _onPinchStart(event) {\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n\n const newControllerState = this.controllerState.zoomStart({pos}).rotateStart({pos});\n // hack - hammer's `rotation` field doesn't seem to produce the correct angle\n this._startPinchRotation = event.rotation;\n this._lastPinchEvent = event;\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});\n return true;\n }\n\n // Default handler for the `pinchmove` and `pinchend` events.\n _onPinch(event) {\n if (!this.touchZoom && !this.touchRotate) {\n return false;\n }\n if (!this.isDragging()) {\n return false;\n }\n\n let newControllerState = this.controllerState;\n if (this.touchZoom) {\n const {scale} = event;\n const pos = this.getCenter(event);\n newControllerState = newControllerState.zoom({pos, scale});\n }\n if (this.touchRotate) {\n const {rotation} = event;\n newControllerState = newControllerState.rotate({\n deltaAngleX: this._startPinchRotation - rotation\n });\n }\n\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true,\n isPanning: this.touchZoom,\n isZooming: this.touchZoom,\n isRotating: this.touchRotate\n });\n this._lastPinchEvent = event;\n return true;\n }\n\n _onPinchEnd(event) {\n if (!this.isDragging()) {\n return false;\n }\n const {inertia, _lastPinchEvent} = this;\n if (this.touchZoom && inertia && _lastPinchEvent && event.scale !== _lastPinchEvent.scale) {\n const pos = this.getCenter(event);\n let newControllerState = this.controllerState.rotateEnd();\n const z = Math.log2(event.scale);\n const velocityZ =\n (z - Math.log2(_lastPinchEvent.scale)) / (event.deltaTime - _lastPinchEvent.deltaTime);\n const endScale = Math.pow(2, z + (velocityZ * inertia) / 2);\n newControllerState = newControllerState.zoom({pos, scale: endScale}).zoomEnd();\n\n this.updateViewport(\n newControllerState,\n {\n ...this._getTransitionProps({around: pos}),\n transitionDuration: inertia,\n transitionEasing: INERTIA_EASING\n },\n {\n isDragging: false,\n isPanning: this.touchZoom,\n isZooming: this.touchZoom,\n isRotating: false\n }\n );\n this.blockEvents(inertia);\n } else {\n const newControllerState = this.controllerState.zoomEnd().rotateEnd();\n this.updateViewport(newControllerState, null, {\n isDragging: false,\n isPanning: false,\n isZooming: false,\n isRotating: false\n });\n }\n this._startPinchRotation = null;\n this._lastPinchEvent = null;\n return true;\n }\n\n // Default handler for the `doubletap` event.\n _onDoubleTap(event) {\n if (!this.doubleClickZoom) {\n return false;\n }\n const pos = this.getCenter(event);\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n\n const isZoomOut = this.isFunctionKeyPressed(event);\n\n const newControllerState = this.controllerState.zoom({pos, scale: isZoomOut ? 0.5 : 2});\n this.updateViewport(newControllerState, this._getTransitionProps({around: pos}), {\n isZooming: true,\n isPanning: true\n });\n this.blockEvents(100);\n return true;\n }\n\n // Default handler for the `keydown` event\n _onKeyDown(event) {\n if (!this.keyboard) {\n return false;\n }\n const funcKey = this.isFunctionKeyPressed(event);\n const {zoomSpeed, moveSpeed, rotateSpeedX, rotateSpeedY} = this.keyboard;\n const {controllerState} = this;\n let newControllerState;\n const interactionState = {};\n\n switch (event.srcEvent.code) {\n case 'Minus':\n newControllerState = funcKey\n ? controllerState.zoomOut(zoomSpeed).zoomOut(zoomSpeed)\n : controllerState.zoomOut(zoomSpeed);\n interactionState.isZooming = true;\n break;\n case 'Equal':\n newControllerState = funcKey\n ? controllerState.zoomIn(zoomSpeed).zoomIn(zoomSpeed)\n : controllerState.zoomIn(zoomSpeed);\n interactionState.isZooming = true;\n break;\n case 'ArrowLeft':\n if (funcKey) {\n newControllerState = controllerState.rotateLeft(rotateSpeedX);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveLeft(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n case 'ArrowRight':\n if (funcKey) {\n newControllerState = controllerState.rotateRight(rotateSpeedX);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveRight(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n case 'ArrowUp':\n if (funcKey) {\n newControllerState = controllerState.rotateUp(rotateSpeedY);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveUp(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n case 'ArrowDown':\n if (funcKey) {\n newControllerState = controllerState.rotateDown(rotateSpeedY);\n interactionState.isRotating = true;\n } else {\n newControllerState = controllerState.moveDown(moveSpeed);\n interactionState.isPanning = true;\n }\n break;\n default:\n return false;\n }\n this.updateViewport(newControllerState, this._getTransitionProps(), interactionState);\n return true;\n }\n\n _getTransitionProps(opts) {\n const {_transition} = this;\n\n if (!_transition) {\n return NO_TRANSITION_PROPS;\n }\n\n // Enables Transitions on double-tap and key-down events.\n return opts\n ? {\n ..._transition,\n transitionInterpolator: new LinearInterpolator({\n ...opts,\n transitionProps: this.linearTransitionProps,\n makeViewport: this.controllerState.makeViewport\n })\n }\n : _transition;\n }\n}\n","const PERCENT_OR_PIXELS_REGEX = /([0-9]+\\.?[0-9]*)(%|px)/;\n\n// Takes a number or a string of formats `50%`, `33.3%` or `200px`\nexport function parsePosition(value) {\n switch (typeof value) {\n case 'number':\n return {\n position: value,\n relative: false\n };\n\n case 'string':\n const match = value.match(PERCENT_OR_PIXELS_REGEX);\n if (match && match.length >= 3) {\n const relative = match[2] === '%';\n const position = parseFloat(match[1]);\n return {\n position: relative ? position / 100 : position,\n relative\n };\n }\n // fallthrough\n\n default:\n // eslint-disable-line\n throw new Error(`Could not parse position string ${value}`);\n }\n}\n\nexport function getPosition(position, extent) {\n return position.relative ? Math.round(position.position * extent) : position.position;\n}\n","import Viewport from '../viewports/viewport';\nimport {parsePosition, getPosition} from '../utils/positions';\nimport {deepEqual} from '../utils/deep-equal';\nimport assert from '../utils/assert';\n\nexport default class View {\n constructor(props = {}) {\n const {\n id = null,\n\n // Window width/height in pixels (for pixel projection)\n x = 0,\n y = 0,\n width = '100%',\n height = '100%',\n\n // A View can be a wrapper for a viewport instance\n viewportInstance,\n\n // Internal: Viewport Type\n type = Viewport // TODO - default to WebMercator?\n } = props;\n\n assert(!viewportInstance || viewportInstance instanceof Viewport);\n this.viewportInstance = viewportInstance;\n\n // Id\n this.id = id || this.constructor.displayName || 'view';\n this.type = type;\n\n this.props = {...props, id: this.id};\n\n // Extents\n this._parseDimensions({x, y, width, height});\n\n // Bind methods for easy access\n this.equals = this.equals.bind(this);\n\n Object.seal(this);\n }\n\n equals(view) {\n if (this === view) {\n return true;\n }\n\n // if `viewportInstance` is set, it is the only prop that is used\n // Delegate to `Viewport.equals`\n if (this.viewportInstance) {\n return view.viewportInstance && this.viewportInstance.equals(view.viewportInstance);\n }\n\n const viewChanged = deepEqual(this.props, view.props);\n\n return viewChanged;\n }\n\n // Build a `Viewport` from a view descriptor\n // TODO - add support for autosizing viewports using width and height\n makeViewport({width, height, viewState}) {\n if (this.viewportInstance) {\n return this.viewportInstance;\n }\n\n viewState = this.filterViewState(viewState);\n\n // Resolve relative viewport dimensions\n const viewportDimensions = this.getDimensions({width, height});\n return this._getViewport(viewState, viewportDimensions);\n }\n\n getViewStateId() {\n switch (typeof this.props.viewState) {\n case 'string':\n // if View.viewState is a string, return it\n return this.props.viewState;\n\n case 'object':\n // If it is an object, return its id component\n return this.props.viewState && this.props.viewState.id;\n\n default:\n return this.id;\n }\n }\n\n // Allows view to override (or completely define) viewState\n filterViewState(viewState) {\n if (this.props.viewState && typeof this.props.viewState === 'object') {\n // If we have specified an id, then intent is to override,\n // If not, completely specify the view state\n if (!this.props.viewState.id) {\n return this.props.viewState;\n }\n\n // Merge in all props from View's viewState, except id\n const newViewState = {...viewState};\n for (const key in this.props.viewState) {\n if (key !== 'id') {\n newViewState[key] = this.props.viewState[key];\n }\n }\n return newViewState;\n }\n\n return viewState;\n }\n\n // Resolve relative viewport dimensions into actual dimensions (y='50%', width=800 => y=400)\n getDimensions({width, height}) {\n return {\n x: getPosition(this._x, width),\n y: getPosition(this._y, height),\n width: getPosition(this._width, width),\n height: getPosition(this._height, height)\n };\n }\n\n // Used by sub classes to resolve controller props\n _getControllerProps(defaultOpts) {\n let opts = this.props.controller;\n\n if (!opts) {\n return null;\n }\n if (opts === true) {\n return defaultOpts;\n }\n if (typeof opts === 'function') {\n opts = {type: opts};\n }\n return {...defaultOpts, ...opts};\n }\n\n // Overridable method\n _getViewport(viewState, viewportDimensions) {\n // Get the type of the viewport\n const {type: ViewportType} = this;\n return new ViewportType({...viewState, ...this.props, ...viewportDimensions});\n }\n\n // Parse relative viewport dimension descriptors (e.g {y: '50%', height: '50%'})\n _parseDimensions({x, y, width, height}) {\n this._x = parsePosition(x);\n this._y = parsePosition(y);\n this._width = parsePosition(width);\n this._height = parsePosition(height);\n }\n}\n","import {uid, assert} from '@luma.gl/webgl';\n\n// Rendering primitives - specify how to extract primitives from vertices.\n// NOTE: These are numerically identical to the corresponding WebGL/OpenGL constants\nexport const DRAW_MODE = {\n POINTS: 0x0000, // draw single points.\n LINES: 0x0001, // draw lines. Each vertex connects to the one after it.\n LINE_LOOP: 0x0002, // draw lines. Each set of two vertices is treated as a separate line segment.\n LINE_STRIP: 0x0003, // draw a connected group of line segments from the first vertex to the last\n TRIANGLES: 0x0004, // draw triangles. Each set of three vertices creates a separate triangle.\n TRIANGLE_STRIP: 0x0005, // draw a connected group of triangles.\n TRIANGLE_FAN: 0x0006 // draw a connected group of triangles.\n // Each vertex connects to the previous and the first vertex in the fan.\n};\n\nexport default class Geometry {\n static get DRAW_MODE() {\n return DRAW_MODE;\n }\n\n constructor(props = {}) {\n const {\n id = uid('geometry'),\n drawMode = DRAW_MODE.TRIANGLES,\n attributes = {},\n indices = null,\n vertexCount = null\n } = props;\n\n this.id = id;\n this.drawMode = drawMode | 0;\n this.attributes = {};\n this.userData = {};\n\n this._setAttributes(attributes, indices);\n\n this.vertexCount = vertexCount || this._calculateVertexCount(this.attributes, this.indices);\n\n // stubRemovedMethods(this, [\n // 'setNeedsRedraw', 'needsRedraw', 'setAttributes'\n // ], 'Immutable');\n\n // stubRemovedMethods(this, [\n // 'hasAttribute', 'getAttribute', 'getArray'\n // ], 'Use geometry.attributes and geometry.indices');\n\n // deprecateMethods(this, ['getAttributes'])\n }\n\n get mode() {\n return this.drawMode;\n }\n\n getVertexCount() {\n return this.vertexCount;\n }\n\n // Return an object with all attributes plus indices added as a field.\n getAttributes() {\n return this.indices ? {indices: this.indices, ...this.attributes} : this.attributes;\n }\n\n // PRIVATE\n\n _print(attributeName) {\n return `Geometry ${this.id} attribute ${attributeName}`;\n }\n\n // Attribute\n // value: typed array\n // type: indices, vertices, uvs\n // size: elements per vertex\n // target: WebGL buffer type (string or constant)\n _setAttributes(attributes, indices) {\n if (indices) {\n this.indices = ArrayBuffer.isView(indices) ? {value: indices, size: 1} : indices;\n }\n\n for (const attributeName in attributes) {\n let attribute = attributes[attributeName];\n\n // Wrap \"unwrapped\" arrays and try to autodetect their type\n attribute = ArrayBuffer.isView(attribute) ? {value: attribute} : attribute;\n\n assert(\n ArrayBuffer.isView(attribute.value),\n `${this._print(attributeName)}: must be typed array or object with value as typed array`\n );\n\n if ((attributeName === 'POSITION' || attributeName === 'positions') && !attribute.size) {\n attribute.size = 3;\n }\n\n // Move indices to separate field\n if (attributeName === 'indices') {\n assert(!this.indices);\n this.indices = attribute;\n } else {\n this.attributes[attributeName] = attribute;\n }\n }\n\n if (this.indices && this.indices.isIndexed !== undefined) {\n this.indices = Object.assign({}, this.indices);\n delete this.indices.isIndexed;\n }\n\n return this;\n }\n\n _calculateVertexCount(attributes, indices) {\n if (indices) {\n return indices.value.length;\n }\n let vertexCount = Infinity;\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n const {value, size, constant} = attribute;\n if (!constant && value && size >= 1) {\n vertexCount = Math.min(vertexCount, value.length / size);\n }\n }\n\n assert(Number.isFinite(vertexCount));\n return vertexCount;\n }\n}\n","// TODO v5: consider to make it private\nexport default function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}","import arrayWithoutHoles from \"./arrayWithoutHoles\";\nimport iterableToArray from \"./iterableToArray\";\nimport nonIterableSpread from \"./nonIterableSpread\";\nexport default function _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();\n}","export default function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n }\n}","export default function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance\");\n}","import GL from '@luma.gl/constants';\nimport {getTypedArrayFromGLType} from '../webgl-utils/typed-array-utils';\nimport {assert} from '../utils/assert';\nimport {checkProps} from '../utils/check-props';\n\nconst DEFAULT_ACCESSOR_VALUES = {\n offset: 0,\n stride: 0,\n type: GL.FLOAT,\n size: 1,\n divisor: 0,\n normalized: false,\n integer: false\n};\n\nconst PROP_CHECKS = {\n deprecatedProps: {\n instanced: 'divisor',\n isInstanced: 'divisor'\n }\n};\n\nexport default class Accessor {\n static getBytesPerElement(accessor) {\n // TODO: using `FLOAT` when type is not specified,\n // ensure this assumption is valid or force API to specify type.\n const ArrayType = getTypedArrayFromGLType(accessor.type || GL.FLOAT);\n return ArrayType.BYTES_PER_ELEMENT;\n }\n\n static getBytesPerVertex(accessor) {\n assert(accessor.size);\n // TODO: using `FLOAT` when type is not specified,\n // ensure this assumption is valid or force API to specify type.\n const ArrayType = getTypedArrayFromGLType(accessor.type || GL.FLOAT);\n return ArrayType.BYTES_PER_ELEMENT * accessor.size;\n }\n\n // Combines (merges) a list of accessors. On top of default values\n // Usually [programAccessor, bufferAccessor, appAccessor]\n // All props will be set in the returned object.\n // TODO check for conflicts between values in the supplied accessors\n static resolve(...accessors) {\n return new Accessor(...[DEFAULT_ACCESSOR_VALUES, ...accessors]); // Default values\n }\n\n constructor(...accessors) {\n accessors.forEach(accessor => this._assign(accessor)); // Merge in sequence\n Object.freeze(this);\n }\n\n toString() {\n return JSON.stringify(this);\n }\n\n // ACCESSORS\n\n // TODO - remove>\n get BYTES_PER_ELEMENT() {\n return Accessor.getBytesPerElement(this);\n }\n\n get BYTES_PER_VERTEX() {\n return Accessor.getBytesPerVertex(this);\n }\n\n // PRIVATE\n\n // eslint-disable-next-line complexity, max-statements\n _assign(props = {}) {\n props = checkProps('Accessor', props, PROP_CHECKS);\n\n if (props.type !== undefined) {\n this.type = props.type;\n\n // Auto-deduce integer type?\n if (props.type === GL.INT || props.type === GL.UNSIGNED_INT) {\n this.integer = true;\n }\n }\n if (props.size !== undefined) {\n this.size = props.size;\n }\n if (props.offset !== undefined) {\n this.offset = props.offset;\n }\n if (props.stride !== undefined) {\n this.stride = props.stride;\n }\n if (props.normalized !== undefined) {\n this.normalized = props.normalized;\n }\n if (props.integer !== undefined) {\n this.integer = props.integer;\n }\n\n // INSTANCE DIVISOR\n if (props.divisor !== undefined) {\n this.divisor = props.divisor;\n }\n\n // Buffer is optional\n if (props.buffer !== undefined) {\n this.buffer = props.buffer;\n }\n\n // The binding index (for binding e.g. Transform feedbacks and Uniform buffers)\n // TODO - should this be part of accessor?\n if (props.index !== undefined) {\n if (typeof props.index === 'boolean') {\n this.index = props.index ? 1 : 0;\n } else {\n this.index = props.index;\n }\n }\n\n // DEPRECATED\n if (props.instanced !== undefined) {\n this.divisor = props.instanced ? 1 : 0;\n }\n if (props.isInstanced !== undefined) {\n this.divisor = props.isInstanced ? 1 : 0;\n }\n\n return this;\n }\n}\n\n// TEST EXPORTS\nexport {DEFAULT_ACCESSOR_VALUES};\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar helpers = require('@turf/helpers');\n\n/**\n * Callback for coordEach\n *\n * @callback coordEachCallback\n * @param {Array} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Iterate over coordinates in any GeoJSON object, similar to Array.forEach()\n *\n * @name coordEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, multiFeatureIndex)\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction coordEach(geojson, callback, excludeWrapCoord) {\n // Handles null Geometry -- Skips this GeoJSON\n if (geojson === null) return;\n var j, k, l, geometry, stopG, coords,\n geometryMaybeCollection,\n wrapShrink = 0,\n coordIndex = 0,\n isGeometryCollection,\n type = geojson.type,\n isFeatureCollection = type === 'FeatureCollection',\n isFeature = type === 'Feature',\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (var featureIndex = 0; featureIndex < stop; featureIndex++) {\n geometryMaybeCollection = (isFeatureCollection ? geojson.features[featureIndex].geometry :\n (isFeature ? geojson.geometry : geojson));\n isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;\n stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;\n\n for (var geomIndex = 0; geomIndex < stopG; geomIndex++) {\n var multiFeatureIndex = 0;\n var geometryIndex = 0;\n geometry = isGeometryCollection ?\n geometryMaybeCollection.geometries[geomIndex] : geometryMaybeCollection;\n\n // Handles null Geometry -- Skips this geometry\n if (geometry === null) continue;\n coords = geometry.coordinates;\n var geomType = geometry.type;\n\n wrapShrink = (excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon')) ? 1 : 0;\n\n switch (geomType) {\n case null:\n break;\n case 'Point':\n if (callback(coords, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n multiFeatureIndex++;\n break;\n case 'LineString':\n case 'MultiPoint':\n for (j = 0; j < coords.length; j++) {\n if (callback(coords[j], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n if (geomType === 'MultiPoint') multiFeatureIndex++;\n }\n if (geomType === 'LineString') multiFeatureIndex++;\n break;\n case 'Polygon':\n case 'MultiLineString':\n for (j = 0; j < coords.length; j++) {\n for (k = 0; k < coords[j].length - wrapShrink; k++) {\n if (callback(coords[j][k], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n }\n if (geomType === 'MultiLineString') multiFeatureIndex++;\n if (geomType === 'Polygon') geometryIndex++;\n }\n if (geomType === 'Polygon') multiFeatureIndex++;\n break;\n case 'MultiPolygon':\n for (j = 0; j < coords.length; j++) {\n geometryIndex = 0;\n for (k = 0; k < coords[j].length; k++) {\n for (l = 0; l < coords[j][k].length - wrapShrink; l++) {\n if (callback(coords[j][k][l], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n }\n geometryIndex++;\n }\n multiFeatureIndex++;\n }\n break;\n case 'GeometryCollection':\n for (j = 0; j < geometry.geometries.length; j++)\n if (coordEach(geometry.geometries[j], callback, excludeWrapCoord) === false) return false;\n break;\n default:\n throw new Error('Unknown Geometry Type');\n }\n }\n }\n}\n\n/**\n * Callback for coordReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback coordReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Array} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * Starts at index 0, if an initialValue is provided, and at index 1 otherwise.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Reduce coordinates in any GeoJSON object, similar to Array.reduce()\n *\n * @name coordReduce\n * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentCoord;\n * });\n */\nfunction coordReduce(geojson, callback, initialValue, excludeWrapCoord) {\n var previousValue = initialValue;\n coordEach(geojson, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;\n else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex);\n }, excludeWrapCoord);\n return previousValue;\n}\n\n/**\n * Callback for propEach\n *\n * @callback propEachCallback\n * @param {Object} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over properties in any GeoJSON object, similar to Array.forEach()\n *\n * @name propEach\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentProperties, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propEach(features, function (currentProperties, featureIndex) {\n * //=currentProperties\n * //=featureIndex\n * });\n */\nfunction propEach(geojson, callback) {\n var i;\n switch (geojson.type) {\n case 'FeatureCollection':\n for (i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i].properties, i) === false) break;\n }\n break;\n case 'Feature':\n callback(geojson.properties, 0);\n break;\n }\n}\n\n\n/**\n * Callback for propReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback propReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {*} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce properties in any GeoJSON object into a single value,\n * similar to how Array.reduce works. However, in this case we lazily run\n * the reduction, so an array of all properties is unnecessary.\n *\n * @name propReduce\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) {\n * //=previousValue\n * //=currentProperties\n * //=featureIndex\n * return currentProperties\n * });\n */\nfunction propReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n propEach(geojson, function (currentProperties, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties;\n else previousValue = callback(previousValue, currentProperties, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Callback for featureEach\n *\n * @callback featureEachCallback\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name featureEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.featureEach(features, function (currentFeature, featureIndex) {\n * //=currentFeature\n * //=featureIndex\n * });\n */\nfunction featureEach(geojson, callback) {\n if (geojson.type === 'Feature') {\n callback(geojson, 0);\n } else if (geojson.type === 'FeatureCollection') {\n for (var i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i], i) === false) break;\n }\n }\n}\n\n/**\n * Callback for featureReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback featureReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name featureReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * return currentFeature\n * });\n */\nfunction featureReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n featureEach(geojson, function (currentFeature, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature;\n else previousValue = callback(previousValue, currentFeature, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Get all coordinates from any GeoJSON object.\n *\n * @name coordAll\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @returns {Array>} coordinate position array\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * var coords = turf.coordAll(features);\n * //= [[26, 37], [36, 53]]\n */\nfunction coordAll(geojson) {\n var coords = [];\n coordEach(geojson, function (coord) {\n coords.push(coord);\n });\n return coords;\n}\n\n/**\n * Callback for geomEach\n *\n * @callback geomEachCallback\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Iterate over each geometry in any GeoJSON object, similar to Array.forEach()\n *\n * @name geomEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * });\n */\nfunction geomEach(geojson, callback) {\n var i, j, g, geometry, stopG,\n geometryMaybeCollection,\n isGeometryCollection,\n featureProperties,\n featureBBox,\n featureId,\n featureIndex = 0,\n isFeatureCollection = geojson.type === 'FeatureCollection',\n isFeature = geojson.type === 'Feature',\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (i = 0; i < stop; i++) {\n\n geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry :\n (isFeature ? geojson.geometry : geojson));\n featureProperties = (isFeatureCollection ? geojson.features[i].properties :\n (isFeature ? geojson.properties : {}));\n featureBBox = (isFeatureCollection ? geojson.features[i].bbox :\n (isFeature ? geojson.bbox : undefined));\n featureId = (isFeatureCollection ? geojson.features[i].id :\n (isFeature ? geojson.id : undefined));\n isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;\n stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;\n\n for (g = 0; g < stopG; g++) {\n geometry = isGeometryCollection ?\n geometryMaybeCollection.geometries[g] : geometryMaybeCollection;\n\n // Handle null Geometry\n if (geometry === null) {\n if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n continue;\n }\n switch (geometry.type) {\n case 'Point':\n case 'LineString':\n case 'MultiPoint':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon': {\n if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n break;\n }\n case 'GeometryCollection': {\n for (j = 0; j < geometry.geometries.length; j++) {\n if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n }\n break;\n }\n default:\n throw new Error('Unknown Geometry Type');\n }\n }\n // Only increase `featureIndex` per each feature\n featureIndex++;\n }\n}\n\n/**\n * Callback for geomReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback geomReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Reduce geometry in any GeoJSON object, similar to Array.reduce().\n *\n * @name geomReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=previousValue\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * return currentGeometry\n * });\n */\nfunction geomReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry;\n else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId);\n });\n return previousValue;\n}\n\n/**\n * Callback for flattenEach\n *\n * @callback flattenEachCallback\n * @param {Feature} currentFeature The current flattened feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Iterate over flattened features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name flattenEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex)\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) {\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * });\n */\nfunction flattenEach(geojson, callback) {\n geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) {\n // Callback for single geometry\n var type = (geometry === null) ? null : geometry.type;\n switch (type) {\n case null:\n case 'Point':\n case 'LineString':\n case 'Polygon':\n if (callback(helpers.feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false;\n return;\n }\n\n var geomType;\n\n // Callback for multi-geometry\n switch (type) {\n case 'MultiPoint':\n geomType = 'Point';\n break;\n case 'MultiLineString':\n geomType = 'LineString';\n break;\n case 'MultiPolygon':\n geomType = 'Polygon';\n break;\n }\n\n for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) {\n var coordinate = geometry.coordinates[multiFeatureIndex];\n var geom = {\n type: geomType,\n coordinates: coordinate\n };\n if (callback(helpers.feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false;\n }\n });\n}\n\n/**\n * Callback for flattenReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback flattenReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Reduce flattened features in any GeoJSON object, similar to Array.reduce().\n *\n * @name flattenReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * return currentFeature\n * });\n */\nfunction flattenReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) {\n if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature;\n else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex);\n });\n return previousValue;\n}\n\n/**\n * Callback for segmentEach\n *\n * @callback segmentEachCallback\n * @param {Feature} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n * @returns {void}\n */\n\n/**\n * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex)\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //=currentSegment\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * //=segmentIndex\n * });\n *\n * // Calculate the total number of segments\n * var total = 0;\n * turf.segmentEach(polygon, function () {\n * total++;\n * });\n */\nfunction segmentEach(geojson, callback) {\n flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) {\n var segmentIndex = 0;\n\n // Exclude null Geometries\n if (!feature.geometry) return;\n // (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n var type = feature.geometry.type;\n if (type === 'Point' || type === 'MultiPoint') return;\n\n // Generate 2-vertex line segments\n var previousCoords;\n var previousFeatureIndex = 0;\n var previousMultiIndex = 0;\n var prevGeomIndex = 0;\n if (coordEach(feature, function (currentCoord, coordIndex, featureIndexCoord, multiPartIndexCoord, geometryIndex) {\n // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false`\n if (previousCoords === undefined || featureIndex > previousFeatureIndex || multiPartIndexCoord > previousMultiIndex || geometryIndex > prevGeomIndex) {\n previousCoords = currentCoord;\n previousFeatureIndex = featureIndex;\n previousMultiIndex = multiPartIndexCoord;\n prevGeomIndex = geometryIndex;\n segmentIndex = 0;\n return;\n }\n var currentSegment = helpers.lineString([previousCoords, currentCoord], feature.properties);\n if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false;\n segmentIndex++;\n previousCoords = currentCoord;\n }) === false) return false;\n });\n}\n\n/**\n * Callback for segmentReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback segmentReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n */\n\n/**\n * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //= previousSegment\n * //= currentSegment\n * //= featureIndex\n * //= multiFeatureIndex\n * //= geometryIndex\n * //= segmentInex\n * return currentSegment\n * });\n *\n * // Calculate the total number of segments\n * var initialValue = 0\n * var total = turf.segmentReduce(polygon, function (previousValue) {\n * previousValue++;\n * return previousValue;\n * }, initialValue);\n */\nfunction segmentReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n var started = false;\n segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n if (started === false && initialValue === undefined) previousValue = currentSegment;\n else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex);\n started = true;\n });\n return previousValue;\n}\n\n/**\n * Callback for lineEach\n *\n * @callback lineEachCallback\n * @param {Feature} currentLine The current LineString|LinearRing being processed\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries,\n * similar to Array.forEach.\n *\n * @name lineEach\n * @param {Geometry|Feature} geojson object\n * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @example\n * var multiLine = turf.multiLineString([\n * [[26, 37], [35, 45]],\n * [[36, 53], [38, 50], [41, 55]]\n * ]);\n *\n * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction lineEach(geojson, callback) {\n // validation\n if (!geojson) throw new Error('geojson is required');\n\n flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) {\n if (feature.geometry === null) return;\n var type = feature.geometry.type;\n var coords = feature.geometry.coordinates;\n switch (type) {\n case 'LineString':\n if (callback(feature, featureIndex, multiFeatureIndex, 0, 0) === false) return false;\n break;\n case 'Polygon':\n for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) {\n if (callback(helpers.lineString(coords[geometryIndex], feature.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n }\n break;\n }\n });\n}\n\n/**\n * Callback for lineReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback lineReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentLine The current LineString|LinearRing being processed.\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name lineReduce\n * @param {Geometry|Feature} geojson object\n * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var multiPoly = turf.multiPolygon([\n * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]),\n * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]])\n * ]);\n *\n * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentLine\n * });\n */\nfunction lineReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine;\n else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex);\n });\n return previousValue;\n}\n\n/**\n * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n * Point & MultiPoint will always return null.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.segmentIndex=0] Segment Index\n * @param {Object} [options.properties={}] Translate Properties to output LineString\n * @param {BBox} [options.bbox={}] Translate BBox to output LineString\n * @param {number|string} [options.id={}] Translate Id to output LineString\n * @returns {Feature} 2-vertex GeoJSON Feature LineString\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findSegment(multiLine);\n * // => Feature>\n *\n * // First Segment of 2nd Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: 1});\n * // => Feature>\n *\n * // Last Segment of Last Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1});\n * // => Feature>\n */\nfunction findSegment(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!helpers.isObject(options)) throw new Error('options is invalid');\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var segmentIndex = options.segmentIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case 'FeatureCollection':\n if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case 'Feature':\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon':\n geometry = geojson;\n break;\n default:\n throw new Error('geojson is invalid');\n }\n\n // Find SegmentIndex\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1;\n return helpers.lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options);\n case 'Polygon':\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1;\n return helpers.lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options);\n case 'MultiLineString':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;\n return helpers.lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options);\n case 'MultiPolygon':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;\n return helpers.lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options);\n }\n throw new Error('geojson is invalid');\n}\n\n/**\n * Finds a particular Point from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.coordIndex=0] Coord Index\n * @param {Object} [options.properties={}] Translate Properties to output Point\n * @param {BBox} [options.bbox={}] Translate BBox to output Point\n * @param {number|string} [options.id={}] Translate Id to output Point\n * @returns {Feature} 2-vertex GeoJSON Feature Point\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findPoint(multiLine);\n * // => Feature>\n *\n * // First Segment of the 2nd Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: 1});\n * // => Feature>\n *\n * // Last Segment of last Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1});\n * // => Feature>\n */\nfunction findPoint(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!helpers.isObject(options)) throw new Error('options is invalid');\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var coordIndex = options.coordIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case 'FeatureCollection':\n if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case 'Feature':\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon':\n geometry = geojson;\n break;\n default:\n throw new Error('geojson is invalid');\n }\n\n // Find Coord Index\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case 'Point':\n return helpers.point(coords, properties, options);\n case 'MultiPoint':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n return helpers.point(coords[multiFeatureIndex], properties, options);\n case 'LineString':\n if (coordIndex < 0) coordIndex = coords.length + coordIndex;\n return helpers.point(coords[coordIndex], properties, options);\n case 'Polygon':\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex;\n return helpers.point(coords[geometryIndex][coordIndex], properties, options);\n case 'MultiLineString':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex;\n return helpers.point(coords[multiFeatureIndex][coordIndex], properties, options);\n case 'MultiPolygon':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex;\n return helpers.point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options);\n }\n throw new Error('geojson is invalid');\n}\n\nexports.coordEach = coordEach;\nexports.coordReduce = coordReduce;\nexports.propEach = propEach;\nexports.propReduce = propReduce;\nexports.featureEach = featureEach;\nexports.featureReduce = featureReduce;\nexports.coordAll = coordAll;\nexports.geomEach = geomEach;\nexports.geomReduce = geomReduce;\nexports.flattenEach = flattenEach;\nexports.flattenReduce = flattenReduce;\nexports.segmentEach = segmentEach;\nexports.segmentReduce = segmentReduce;\nexports.lineEach = lineEach;\nexports.lineReduce = lineReduce;\nexports.findSegment = findSegment;\nexports.findPoint = findPoint;\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.red = exports.getContrastingColor = exports.isValidHex = exports.toState = exports.simpleCheckForValidColor = undefined;\n\nvar _each = require('lodash/each');\n\nvar _each2 = _interopRequireDefault(_each);\n\nvar _tinycolor = require('tinycolor2');\n\nvar _tinycolor2 = _interopRequireDefault(_tinycolor);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar simpleCheckForValidColor = exports.simpleCheckForValidColor = function simpleCheckForValidColor(data) {\n var keysToCheck = ['r', 'g', 'b', 'a', 'h', 's', 'l', 'v'];\n var checked = 0;\n var passed = 0;\n (0, _each2.default)(keysToCheck, function (letter) {\n if (data[letter]) {\n checked += 1;\n if (!isNaN(data[letter])) {\n passed += 1;\n }\n if (letter === 's' || letter === 'l') {\n var percentPatt = /^\\d+%$/;\n if (percentPatt.test(data[letter])) {\n passed += 1;\n }\n }\n }\n });\n return checked === passed ? data : false;\n};\n\nvar toState = exports.toState = function toState(data, oldHue) {\n var color = data.hex ? (0, _tinycolor2.default)(data.hex) : (0, _tinycolor2.default)(data);\n var hsl = color.toHsl();\n var hsv = color.toHsv();\n var rgb = color.toRgb();\n var hex = color.toHex();\n if (hsl.s === 0) {\n hsl.h = oldHue || 0;\n hsv.h = oldHue || 0;\n }\n var transparent = hex === '000000' && rgb.a === 0;\n\n return {\n hsl: hsl,\n hex: transparent ? 'transparent' : '#' + hex,\n rgb: rgb,\n hsv: hsv,\n oldHue: data.h || oldHue || hsl.h,\n source: data.source\n };\n};\n\nvar isValidHex = exports.isValidHex = function isValidHex(hex) {\n // disable hex4 and hex8\n var lh = String(hex).charAt(0) === '#' ? 1 : 0;\n return hex.length !== 4 + lh && hex.length < 7 + lh && (0, _tinycolor2.default)(hex).isValid();\n};\n\nvar getContrastingColor = exports.getContrastingColor = function getContrastingColor(data) {\n if (!data) {\n return '#fff';\n }\n var col = toState(data);\n if (col.hex === 'transparent') {\n return 'rgba(0,0,0,0.4)';\n }\n var yiq = (col.rgb.r * 299 + col.rgb.g * 587 + col.rgb.b * 114) / 1000;\n return yiq >= 128 ? '#000' : '#fff';\n};\n\nvar red = exports.red = {\n hsl: { a: 1, h: 0, l: 0.5, s: 1 },\n hex: '#ff0000',\n rgb: { r: 255, g: 0, b: 0, a: 1 },\n hsv: { h: 0, s: 1, v: 1, a: 1 }\n};\n\nexports.default = exports;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar helpers_1 = require(\"@turf/helpers\");\nvar invariant_1 = require(\"@turf/invariant\");\n// http://en.wikipedia.org/wiki/Haversine_formula\n// http://www.movable-type.co.uk/scripts/latlong.html\n/**\n * Takes two {@link Point|points} and finds the geographic bearing between them,\n * i.e. the angle measured in degrees from the north line (0 degrees)\n *\n * @name bearing\n * @param {Coord} start starting Point\n * @param {Coord} end ending Point\n * @param {Object} [options={}] Optional parameters\n * @param {boolean} [options.final=false] calculates the final bearing if true\n * @returns {number} bearing in decimal degrees, between -180 and 180 degrees (positive clockwise)\n * @example\n * var point1 = turf.point([-75.343, 39.984]);\n * var point2 = turf.point([-75.534, 39.123]);\n *\n * var bearing = turf.bearing(point1, point2);\n *\n * //addToMap\n * var addToMap = [point1, point2]\n * point1.properties['marker-color'] = '#f00'\n * point2.properties['marker-color'] = '#0f0'\n * point1.properties.bearing = bearing\n */\nfunction bearing(start, end, options) {\n if (options === void 0) { options = {}; }\n // Reverse calculation\n if (options.final === true) {\n return calculateFinalBearing(start, end);\n }\n var coordinates1 = invariant_1.getCoord(start);\n var coordinates2 = invariant_1.getCoord(end);\n var lon1 = helpers_1.degreesToRadians(coordinates1[0]);\n var lon2 = helpers_1.degreesToRadians(coordinates2[0]);\n var lat1 = helpers_1.degreesToRadians(coordinates1[1]);\n var lat2 = helpers_1.degreesToRadians(coordinates2[1]);\n var a = Math.sin(lon2 - lon1) * Math.cos(lat2);\n var b = Math.cos(lat1) * Math.sin(lat2) -\n Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);\n return helpers_1.radiansToDegrees(Math.atan2(a, b));\n}\n/**\n * Calculates Final Bearing\n *\n * @private\n * @param {Coord} start starting Point\n * @param {Coord} end ending Point\n * @returns {number} bearing\n */\nfunction calculateFinalBearing(start, end) {\n // Swap start & end\n var bear = bearing(end, start);\n bear = (bear + 180) % 360;\n return bear;\n}\nexports.default = bearing;\n","const SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n","// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.format()\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First, split based on boolean or ||\n this.raw = range\n this.set = range\n .split(/\\s*\\|\\|\\s*/)\n // map the range to a 2d array of comparators\n .map(range => this.parseRange(range.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${range}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0)\n this.set = [first]\n else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.format()\n }\n\n format () {\n this.range = this.set\n .map((comps) => {\n return comps.join(' ').trim()\n })\n .join('||')\n .trim()\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n range = range.trim()\n\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts = Object.keys(this.options).join(',')\n const memoKey = `parseRange:${memoOpts}:${range}`\n const cached = cache.get(memoKey)\n if (cached)\n return cached\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range, re[t.COMPARATORTRIM])\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n\n // normalize spaces\n range = range.split(/\\s+/).join(' ')\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n // in loose mode, throw out any that are not valid comparators\n .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)\n .map(comp => new Comparator(comp, this.options))\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const l = rangeList.length\n const rangeMap = new Map()\n for (const comp of rangeList) {\n if (isNullSet(comp))\n return [comp]\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has(''))\n rangeMap.delete('')\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\nmodule.exports = Range\n\nconst LRU = require('lru-cache')\nconst cache = new LRU({ max: 1000 })\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace\n} = require('../internal/re')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\nconst replaceTildes = (comp, options) =>\n comp.trim().split(/\\s+/).map((comp) => {\n return replaceTilde(comp, options)\n }).join(' ')\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\nconst replaceCarets = (comp, options) =>\n comp.trim().split(/\\s+/).map((comp) => {\n return replaceCaret(comp, options)\n }).join(' ')\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp.split(/\\s+/).map((comp) => {\n return replaceXRange(comp, options)\n }).join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<')\n pr = '-0'\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp.trim().replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp.trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr, tb) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return (`${from} ${to}`).trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/**\n * Flattens a nested array into a single level array,\n * or a single value into an array with one value\n * @example flatten([[1, [2]], [3], 4]) => [1, 2, 3, 4]\n * @example flatten(1) => [1]\n * @param {Array} array The array to flatten.\n * @param {Function} filter= - Optional predicate called on each `value` to\n * determine if it should be included (pushed onto) the resulting array.\n * @param {Function} map= - Optional transform applied to each array elements.\n * @param {Array} result=[] - Optional array to push value into\n * @return {Array} Returns the new flattened array (new array or `result` if provided)\n */\nexport function flatten(array, filter = () => true) {\n // Wrap single object in array\n if (!Array.isArray(array)) {\n return filter(array) ? [array] : [];\n }\n // Deep flatten and filter the array\n return flattenArray(array, filter, []);\n}\n\n// Deep flattens an array. Helper to `flatten`, see its parameters\nfunction flattenArray(array, filter, result) {\n let index = -1;\n while (++index < array.length) {\n const value = array[index];\n if (Array.isArray(value)) {\n flattenArray(value, filter, result);\n } else if (filter(value)) {\n result.push(value);\n }\n }\n return result;\n}\n\n// Uses copyWithin to significantly speed up typed array value filling\nexport function fillArray({target, source, start = 0, count = 1}) {\n const length = source.length;\n const total = count * length;\n let copied = 0;\n for (let i = start; copied < length; copied++) {\n target[i++] = source[copied];\n }\n\n while (copied < total) {\n // If we have copied less than half, copy everything we got\n // else copy remaining in one operation\n if (copied < total - copied) {\n target.copyWithin(start + copied, start, start + copied);\n copied *= 2;\n } else {\n target.copyWithin(start + copied, start, start + total - copied);\n copied = total;\n }\n }\n\n return target;\n}\n","// Corresponds to 10 frames at 60 Hz.\n// A few bytes payload overhead when lodash/debounce is ~3 kB and debounce ~300 B.\nexport default function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\n}","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options === 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n","export class TypedArrayManager {\n constructor(props) {\n this._pool = [];\n this.props = {overAlloc: 2, poolSize: 100};\n this.setProps(props);\n }\n\n setProps(props) {\n Object.assign(this.props, props);\n }\n\n allocate(\n typedArray,\n count,\n {size = 1, type, padding = 0, copy = false, initialize = false, maxCount}\n ) {\n const Type = type || (typedArray && typedArray.constructor) || Float32Array;\n\n const newSize = count * size + padding;\n if (ArrayBuffer.isView(typedArray)) {\n if (newSize <= typedArray.length) {\n return typedArray;\n }\n if (newSize * typedArray.BYTES_PER_ELEMENT <= typedArray.buffer.byteLength) {\n return new Type(typedArray.buffer, 0, newSize);\n }\n }\n\n let maxSize;\n if (maxCount) {\n maxSize = maxCount * size + padding;\n }\n\n const newArray = this._allocate(Type, newSize, initialize, maxSize);\n\n if (typedArray && copy) {\n newArray.set(typedArray);\n } else if (!initialize) {\n // Hack - always initialize the first 4 elements. NaNs crash the Attribute validation\n newArray.fill(0, 0, 4);\n }\n\n this._release(typedArray);\n return newArray;\n }\n\n release(typedArray) {\n this._release(typedArray);\n }\n\n _allocate(Type, size, initialize, maxSize) {\n // Allocate at least one element to ensure a valid buffer\n let sizeToAllocate = Math.max(Math.ceil(size * this.props.overAlloc), 1);\n // Don't over allocate after certain specified number of elements\n if (sizeToAllocate > maxSize) {\n sizeToAllocate = maxSize;\n }\n\n // Check if available in pool\n const pool = this._pool;\n const byteLength = Type.BYTES_PER_ELEMENT * sizeToAllocate;\n const i = pool.findIndex(b => b.byteLength >= byteLength);\n if (i >= 0) {\n // Create a new array using an existing buffer\n const array = new Type(pool.splice(i, 1)[0], 0, sizeToAllocate);\n if (initialize) {\n // Viewing a buffer with a different type may create NaNs\n array.fill(0);\n }\n return array;\n }\n return new Type(sizeToAllocate);\n }\n\n _release(typedArray) {\n if (!ArrayBuffer.isView(typedArray)) {\n return;\n }\n const pool = this._pool;\n const {buffer} = typedArray;\n // Save the buffer of the released array into the pool\n // Sort buffers by size\n // TODO - implement binary search?\n const {byteLength} = buffer;\n const i = pool.findIndex(b => b.byteLength >= byteLength);\n if (i < 0) {\n pool.push(buffer);\n } else if (i > 0 || pool.length < this.props.poolSize) {\n pool.splice(i, 0, buffer);\n }\n if (pool.length > this.props.poolSize) {\n // Drop the smallest one\n pool.shift();\n }\n }\n}\n\nexport default new TypedArrayManager();\n","export var reflow = function reflow(node) {\n return node.scrollTop;\n};\nexport function getTransitionProps(props, options) {\n var timeout = props.timeout,\n _props$style = props.style,\n style = _props$style === void 0 ? {} : _props$style;\n return {\n duration: style.transitionDuration || typeof timeout === 'number' ? timeout : timeout[options.mode] || 0,\n delay: style.transitionDelay\n };\n}","// Tables describing WebGL parameters\nimport GL from '@luma.gl/constants';\nimport {isWebGL2} from '../utils/webgl-checks';\n\n// DEFAULT SETTINGS - FOR FAST CACHE INITIALIZATION AND CONTEXT RESETS\n\n/* eslint-disable no-shadow */\n\nexport const GL_PARAMETER_DEFAULTS = {\n [GL.BLEND]: false,\n [GL.BLEND_COLOR]: new Float32Array([0, 0, 0, 0]),\n [GL.BLEND_EQUATION_RGB]: GL.FUNC_ADD,\n [GL.BLEND_EQUATION_ALPHA]: GL.FUNC_ADD,\n [GL.BLEND_SRC_RGB]: GL.ONE,\n [GL.BLEND_DST_RGB]: GL.ZERO,\n [GL.BLEND_SRC_ALPHA]: GL.ONE,\n [GL.BLEND_DST_ALPHA]: GL.ZERO,\n [GL.COLOR_CLEAR_VALUE]: new Float32Array([0, 0, 0, 0]), // TBD\n [GL.COLOR_WRITEMASK]: [true, true, true, true],\n [GL.CULL_FACE]: false,\n [GL.CULL_FACE_MODE]: GL.BACK,\n [GL.DEPTH_TEST]: false,\n [GL.DEPTH_CLEAR_VALUE]: 1,\n [GL.DEPTH_FUNC]: GL.LESS,\n [GL.DEPTH_RANGE]: new Float32Array([0, 1]), // TBD\n [GL.DEPTH_WRITEMASK]: true,\n [GL.DITHER]: true,\n // FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state.\n [GL.FRAMEBUFFER_BINDING]: null,\n [GL.FRONT_FACE]: GL.CCW,\n [GL.GENERATE_MIPMAP_HINT]: GL.DONT_CARE,\n [GL.LINE_WIDTH]: 1,\n [GL.POLYGON_OFFSET_FILL]: false,\n [GL.POLYGON_OFFSET_FACTOR]: 0,\n [GL.POLYGON_OFFSET_UNITS]: 0,\n [GL.SAMPLE_COVERAGE_VALUE]: 1.0,\n [GL.SAMPLE_COVERAGE_INVERT]: false,\n [GL.SCISSOR_TEST]: false,\n // Note: Dynamic value. If scissor test enabled we expect users to set correct scissor box\n [GL.SCISSOR_BOX]: new Int32Array([0, 0, 1024, 1024]),\n [GL.STENCIL_TEST]: false,\n [GL.STENCIL_CLEAR_VALUE]: 0,\n [GL.STENCIL_WRITEMASK]: 0xffffffff,\n [GL.STENCIL_BACK_WRITEMASK]: 0xffffffff,\n [GL.STENCIL_FUNC]: GL.ALWAYS,\n [GL.STENCIL_REF]: 0,\n [GL.STENCIL_VALUE_MASK]: 0xffffffff,\n [GL.STENCIL_BACK_FUNC]: GL.ALWAYS,\n [GL.STENCIL_BACK_REF]: 0,\n [GL.STENCIL_BACK_VALUE_MASK]: 0xffffffff,\n [GL.STENCIL_FAIL]: GL.KEEP,\n [GL.STENCIL_PASS_DEPTH_FAIL]: GL.KEEP,\n [GL.STENCIL_PASS_DEPTH_PASS]: GL.KEEP,\n [GL.STENCIL_BACK_FAIL]: GL.KEEP,\n [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: GL.KEEP,\n [GL.STENCIL_BACK_PASS_DEPTH_PASS]: GL.KEEP,\n // Dynamic value: We use [0, 0, 1024, 1024] as default, but usually this is updated in each frame.\n [GL.VIEWPORT]: [0, 0, 1024, 1024],\n // WEBGL1 PIXEL PACK/UNPACK MODES\n [GL.PACK_ALIGNMENT]: 4,\n [GL.UNPACK_ALIGNMENT]: 4,\n [GL.UNPACK_FLIP_Y_WEBGL]: false,\n [GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL]: false,\n [GL.UNPACK_COLORSPACE_CONVERSION_WEBGL]: GL.BROWSER_DEFAULT_WEBGL,\n\n // WEBGL2 / EXTENSIONS\n // gl1: 'OES_standard_derivatives'\n [GL.FRAGMENT_SHADER_DERIVATIVE_HINT]: GL.DONT_CARE,\n [GL.READ_FRAMEBUFFER_BINDING]: null,\n [GL.RASTERIZER_DISCARD]: false,\n [GL.PACK_ROW_LENGTH]: 0,\n [GL.PACK_SKIP_PIXELS]: 0,\n [GL.PACK_SKIP_ROWS]: 0,\n [GL.UNPACK_ROW_LENGTH]: 0,\n [GL.UNPACK_IMAGE_HEIGHT]: 0,\n [GL.UNPACK_SKIP_PIXELS]: 0,\n [GL.UNPACK_SKIP_ROWS]: 0,\n [GL.UNPACK_SKIP_IMAGES]: 0\n};\n\n// SETTER TABLES - ENABLES SETTING ANY PARAMETER WITH A COMMON API\n\nconst enable = (gl, value, key) => (value ? gl.enable(key) : gl.disable(key));\nconst hint = (gl, value, key) => gl.hint(key, value);\nconst pixelStorei = (gl, value, key) => gl.pixelStorei(key, value);\n\nconst drawFramebuffer = (gl, value) => {\n const target = isWebGL2(gl) ? GL.DRAW_FRAMEBUFFER : GL.FRAMEBUFFER;\n return gl.bindFramebuffer(target, value);\n};\nconst readFramebuffer = (gl, value) => {\n return gl.bindFramebuffer(GL.READ_FRAMEBUFFER, value);\n};\n\n// Utility\nfunction isArray(array) {\n return Array.isArray(array) || ArrayBuffer.isView(array);\n}\n\n// Map from WebGL parameter names to corresponding WebGL setter functions\n// WegGL constants are read by parameter names, but set by function names\n// NOTE: When value type is a string, it will be handled by 'GL_COMPOSITE_PARAMETER_SETTERS'\nexport const GL_PARAMETER_SETTERS = {\n [GL.BLEND]: enable,\n [GL.BLEND_COLOR]: (gl, value) => gl.blendColor(...value),\n [GL.BLEND_EQUATION_RGB]: 'blendEquation',\n [GL.BLEND_EQUATION_ALPHA]: 'blendEquation',\n [GL.BLEND_SRC_RGB]: 'blendFunc',\n [GL.BLEND_DST_RGB]: 'blendFunc',\n [GL.BLEND_SRC_ALPHA]: 'blendFunc',\n [GL.BLEND_DST_ALPHA]: 'blendFunc',\n [GL.COLOR_CLEAR_VALUE]: (gl, value) => gl.clearColor(...value),\n [GL.COLOR_WRITEMASK]: (gl, value) => gl.colorMask(...value),\n [GL.CULL_FACE]: enable,\n [GL.CULL_FACE_MODE]: (gl, value) => gl.cullFace(value),\n [GL.DEPTH_TEST]: enable,\n [GL.DEPTH_CLEAR_VALUE]: (gl, value) => gl.clearDepth(value),\n [GL.DEPTH_FUNC]: (gl, value) => gl.depthFunc(value),\n [GL.DEPTH_RANGE]: (gl, value) => gl.depthRange(...value),\n [GL.DEPTH_WRITEMASK]: (gl, value) => gl.depthMask(value),\n [GL.DITHER]: enable,\n [GL.FRAGMENT_SHADER_DERIVATIVE_HINT]: hint,\n // NOTE: FRAMEBUFFER_BINDING and DRAW_FRAMEBUFFER_BINDING(WebGL2) refer same state.\n [GL.FRAMEBUFFER_BINDING]: drawFramebuffer,\n [GL.FRONT_FACE]: (gl, value) => gl.frontFace(value),\n [GL.GENERATE_MIPMAP_HINT]: hint,\n [GL.LINE_WIDTH]: (gl, value) => gl.lineWidth(value),\n [GL.POLYGON_OFFSET_FILL]: enable,\n [GL.POLYGON_OFFSET_FACTOR]: 'polygonOffset',\n [GL.POLYGON_OFFSET_UNITS]: 'polygonOffset',\n [GL.RASTERIZER_DISCARD]: enable,\n [GL.SAMPLE_COVERAGE_VALUE]: 'sampleCoverage',\n [GL.SAMPLE_COVERAGE_INVERT]: 'sampleCoverage',\n [GL.SCISSOR_TEST]: enable,\n [GL.SCISSOR_BOX]: (gl, value) => gl.scissor(...value),\n [GL.STENCIL_TEST]: enable,\n [GL.STENCIL_CLEAR_VALUE]: (gl, value) => gl.clearStencil(value),\n [GL.STENCIL_WRITEMASK]: (gl, value) => gl.stencilMaskSeparate(GL.FRONT, value),\n [GL.STENCIL_BACK_WRITEMASK]: (gl, value) => gl.stencilMaskSeparate(GL.BACK, value),\n [GL.STENCIL_FUNC]: 'stencilFuncFront',\n [GL.STENCIL_REF]: 'stencilFuncFront',\n [GL.STENCIL_VALUE_MASK]: 'stencilFuncFront',\n [GL.STENCIL_BACK_FUNC]: 'stencilFuncBack',\n [GL.STENCIL_BACK_REF]: 'stencilFuncBack',\n [GL.STENCIL_BACK_VALUE_MASK]: 'stencilFuncBack',\n [GL.STENCIL_FAIL]: 'stencilOpFront',\n [GL.STENCIL_PASS_DEPTH_FAIL]: 'stencilOpFront',\n [GL.STENCIL_PASS_DEPTH_PASS]: 'stencilOpFront',\n [GL.STENCIL_BACK_FAIL]: 'stencilOpBack',\n [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: 'stencilOpBack',\n [GL.STENCIL_BACK_PASS_DEPTH_PASS]: 'stencilOpBack',\n [GL.VIEWPORT]: (gl, value) => gl.viewport(...value),\n\n // WEBGL1 PIXEL PACK/UNPACK MODES\n [GL.PACK_ALIGNMENT]: pixelStorei,\n [GL.UNPACK_ALIGNMENT]: pixelStorei,\n [GL.UNPACK_FLIP_Y_WEBGL]: pixelStorei,\n [GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL]: pixelStorei,\n [GL.UNPACK_COLORSPACE_CONVERSION_WEBGL]: pixelStorei,\n\n // WEBGL2 PIXEL PACK/UNPACK MODES\n // RASTERIZER_DISCARD ...\n [GL.PACK_ROW_LENGTH]: pixelStorei,\n [GL.PACK_SKIP_PIXELS]: pixelStorei,\n [GL.PACK_SKIP_ROWS]: pixelStorei,\n [GL.READ_FRAMEBUFFER_BINDING]: readFramebuffer,\n [GL.UNPACK_ROW_LENGTH]: pixelStorei,\n [GL.UNPACK_IMAGE_HEIGHT]: pixelStorei,\n [GL.UNPACK_SKIP_PIXELS]: pixelStorei,\n [GL.UNPACK_SKIP_ROWS]: pixelStorei,\n [GL.UNPACK_SKIP_IMAGES]: pixelStorei,\n\n // Function-style setters\n framebuffer: (gl, framebuffer) => {\n // accepts 1) a WebGLFramebuffer 2) null (default framebuffer), or 3) luma.gl Framebuffer class\n // framebuffer is null when restoring to default framebuffer, otherwise use the WebGL handle.\n const handle = framebuffer && 'handle' in framebuffer ? framebuffer.handle : framebuffer;\n return gl.bindFramebuffer(GL.FRAMEBUFFER, handle);\n },\n blend: (gl, value) => (value ? gl.enable(GL.BLEND) : gl.disable(GL.BLEND)),\n blendColor: (gl, value) => gl.blendColor(...value),\n blendEquation: (gl, args) => {\n args = isArray(args) ? args : [args, args];\n gl.blendEquationSeparate(...args);\n },\n blendFunc: (gl, args) => {\n args = isArray(args) && args.length === 2 ? [...args, ...args] : args;\n gl.blendFuncSeparate(...args);\n },\n\n clearColor: (gl, value) => gl.clearColor(...value),\n clearDepth: (gl, value) => gl.clearDepth(value),\n clearStencil: (gl, value) => gl.clearStencil(value),\n\n colorMask: (gl, value) => gl.colorMask(...value),\n\n cull: (gl, value) => (value ? gl.enable(GL.CULL_FACE) : gl.disable(GL.CULL_FACE)),\n cullFace: (gl, value) => gl.cullFace(value),\n\n depthTest: (gl, value) => (value ? gl.enable(GL.DEPTH_TEST) : gl.disable(GL.DEPTH_TEST)),\n depthFunc: (gl, value) => gl.depthFunc(value),\n depthMask: (gl, value) => gl.depthMask(value),\n depthRange: (gl, value) => gl.depthRange(...value),\n\n dither: (gl, value) => (value ? gl.enable(GL.DITHER) : gl.disable(GL.DITHER)),\n\n derivativeHint: (gl, value) => {\n // gl1: 'OES_standard_derivatives'\n gl.hint(GL.FRAGMENT_SHADER_DERIVATIVE_HINT, value);\n },\n\n frontFace: (gl, value) => gl.frontFace(value),\n\n mipmapHint: (gl, value) => gl.hint(GL.GENERATE_MIPMAP_HINT, value),\n\n lineWidth: (gl, value) => gl.lineWidth(value),\n\n polygonOffsetFill: (gl, value) =>\n value ? gl.enable(GL.POLYGON_OFFSET_FILL) : gl.disable(GL.POLYGON_OFFSET_FILL),\n polygonOffset: (gl, value) => gl.polygonOffset(...value),\n\n sampleCoverage: (gl, value) => gl.sampleCoverage(...value),\n\n scissorTest: (gl, value) => (value ? gl.enable(GL.SCISSOR_TEST) : gl.disable(GL.SCISSOR_TEST)),\n scissor: (gl, value) => gl.scissor(...value),\n\n stencilTest: (gl, value) => (value ? gl.enable(GL.STENCIL_TEST) : gl.disable(GL.STENCIL_TEST)),\n stencilMask: (gl, value) => {\n value = isArray(value) ? value : [value, value];\n const [mask, backMask] = value;\n gl.stencilMaskSeparate(GL.FRONT, mask);\n gl.stencilMaskSeparate(GL.BACK, backMask);\n },\n stencilFunc: (gl, args) => {\n args = isArray(args) && args.length === 3 ? [...args, ...args] : args;\n const [func, ref, mask, backFunc, backRef, backMask] = args;\n gl.stencilFuncSeparate(GL.FRONT, func, ref, mask);\n gl.stencilFuncSeparate(GL.BACK, backFunc, backRef, backMask);\n },\n stencilOp: (gl, args) => {\n args = isArray(args) && args.length === 3 ? [...args, ...args] : args;\n const [sfail, dpfail, dppass, backSfail, backDpfail, backDppass] = args;\n gl.stencilOpSeparate(GL.FRONT, sfail, dpfail, dppass);\n gl.stencilOpSeparate(GL.BACK, backSfail, backDpfail, backDppass);\n },\n\n viewport: (gl, value) => gl.viewport(...value)\n};\n\nfunction getValue(glEnum, values, cache) {\n return values[glEnum] !== undefined ? values[glEnum] : cache[glEnum];\n}\n\n// COMPOSITE_WEBGL_PARAMETER_\nexport const GL_COMPOSITE_PARAMETER_SETTERS = {\n blendEquation: (gl, values, cache) =>\n gl.blendEquationSeparate(\n getValue(GL.BLEND_EQUATION_RGB, values, cache),\n getValue(GL.BLEND_EQUATION_ALPHA, values, cache)\n ),\n blendFunc: (gl, values, cache) =>\n gl.blendFuncSeparate(\n getValue(GL.BLEND_SRC_RGB, values, cache),\n getValue(GL.BLEND_DST_RGB, values, cache),\n getValue(GL.BLEND_SRC_ALPHA, values, cache),\n getValue(GL.BLEND_DST_ALPHA, values, cache)\n ),\n polygonOffset: (gl, values, cache) =>\n gl.polygonOffset(\n getValue(GL.POLYGON_OFFSET_FACTOR, values, cache),\n getValue(GL.POLYGON_OFFSET_UNITS, values, cache)\n ),\n sampleCoverage: (gl, values, cache) =>\n gl.sampleCoverage(\n getValue(GL.SAMPLE_COVERAGE_VALUE, values, cache),\n getValue(GL.SAMPLE_COVERAGE_INVERT, values, cache)\n ),\n stencilFuncFront: (gl, values, cache) =>\n gl.stencilFuncSeparate(\n GL.FRONT,\n getValue(GL.STENCIL_FUNC, values, cache),\n getValue(GL.STENCIL_REF, values, cache),\n getValue(GL.STENCIL_VALUE_MASK, values, cache)\n ),\n stencilFuncBack: (gl, values, cache) =>\n gl.stencilFuncSeparate(\n GL.BACK,\n getValue(GL.STENCIL_BACK_FUNC, values, cache),\n getValue(GL.STENCIL_BACK_REF, values, cache),\n getValue(GL.STENCIL_BACK_VALUE_MASK, values, cache)\n ),\n stencilOpFront: (gl, values, cache) =>\n gl.stencilOpSeparate(\n GL.FRONT,\n getValue(GL.STENCIL_FAIL, values, cache),\n getValue(GL.STENCIL_PASS_DEPTH_FAIL, values, cache),\n getValue(GL.STENCIL_PASS_DEPTH_PASS, values, cache)\n ),\n stencilOpBack: (gl, values, cache) =>\n gl.stencilOpSeparate(\n GL.BACK,\n getValue(GL.STENCIL_BACK_FAIL, values, cache),\n getValue(GL.STENCIL_BACK_PASS_DEPTH_FAIL, values, cache),\n getValue(GL.STENCIL_BACK_PASS_DEPTH_PASS, values, cache)\n )\n};\n\n// Setter functions intercepted for cache updates\nexport const GL_HOOKED_SETTERS = {\n // GENERIC SETTERS\n\n enable: (update, capability) =>\n update({\n [capability]: true\n }),\n disable: (update, capability) =>\n update({\n [capability]: false\n }),\n pixelStorei: (update, pname, value) =>\n update({\n [pname]: value\n }),\n hint: (update, pname, hint) =>\n update({\n [pname]: hint\n }),\n\n // SPECIFIC SETTERS\n\n bindFramebuffer: (update, target, framebuffer) => {\n switch (target) {\n case GL.FRAMEBUFFER:\n return update({\n [GL.DRAW_FRAMEBUFFER_BINDING]: framebuffer,\n [GL.READ_FRAMEBUFFER_BINDING]: framebuffer\n });\n case GL.DRAW_FRAMEBUFFER:\n return update({[GL.DRAW_FRAMEBUFFER_BINDING]: framebuffer});\n case GL.READ_FRAMEBUFFER:\n return update({[GL.READ_FRAMEBUFFER_BINDING]: framebuffer});\n default:\n return null;\n }\n },\n blendColor: (update, r, g, b, a) =>\n update({\n [GL.BLEND_COLOR]: new Float32Array([r, g, b, a])\n }),\n\n blendEquation: (update, mode) =>\n update({\n [GL.BLEND_EQUATION_RGB]: mode,\n [GL.BLEND_EQUATION_ALPHA]: mode\n }),\n\n blendEquationSeparate: (update, modeRGB, modeAlpha) =>\n update({\n [GL.BLEND_EQUATION_RGB]: modeRGB,\n [GL.BLEND_EQUATION_ALPHA]: modeAlpha\n }),\n\n blendFunc: (update, src, dst) =>\n update({\n [GL.BLEND_SRC_RGB]: src,\n [GL.BLEND_DST_RGB]: dst,\n [GL.BLEND_SRC_ALPHA]: src,\n [GL.BLEND_DST_ALPHA]: dst\n }),\n\n blendFuncSeparate: (update, srcRGB, dstRGB, srcAlpha, dstAlpha) =>\n update({\n [GL.BLEND_SRC_RGB]: srcRGB,\n [GL.BLEND_DST_RGB]: dstRGB,\n [GL.BLEND_SRC_ALPHA]: srcAlpha,\n [GL.BLEND_DST_ALPHA]: dstAlpha\n }),\n\n clearColor: (update, r, g, b, a) =>\n update({\n [GL.COLOR_CLEAR_VALUE]: new Float32Array([r, g, b, a])\n }),\n\n clearDepth: (update, depth) =>\n update({\n [GL.DEPTH_CLEAR_VALUE]: depth\n }),\n\n clearStencil: (update, s) =>\n update({\n [GL.STENCIL_CLEAR_VALUE]: s\n }),\n\n colorMask: (update, r, g, b, a) =>\n update({\n [GL.COLOR_WRITEMASK]: [r, g, b, a]\n }),\n\n cullFace: (update, mode) =>\n update({\n [GL.CULL_FACE_MODE]: mode\n }),\n\n depthFunc: (update, func) =>\n update({\n [GL.DEPTH_FUNC]: func\n }),\n\n depthRange: (update, zNear, zFar) =>\n update({\n [GL.DEPTH_RANGE]: new Float32Array([zNear, zFar])\n }),\n\n depthMask: (update, mask) =>\n update({\n [GL.DEPTH_WRITEMASK]: mask\n }),\n\n frontFace: (update, face) =>\n update({\n [GL.FRONT_FACE]: face\n }),\n\n lineWidth: (update, width) =>\n update({\n [GL.LINE_WIDTH]: width\n }),\n\n polygonOffset: (update, factor, units) =>\n update({\n [GL.POLYGON_OFFSET_FACTOR]: factor,\n [GL.POLYGON_OFFSET_UNITS]: units\n }),\n\n sampleCoverage: (update, value, invert) =>\n update({\n [GL.SAMPLE_COVERAGE_VALUE]: value,\n [GL.SAMPLE_COVERAGE_INVERT]: invert\n }),\n\n scissor: (update, x, y, width, height) =>\n update({\n [GL.SCISSOR_BOX]: new Int32Array([x, y, width, height])\n }),\n\n stencilMask: (update, mask) =>\n update({\n [GL.STENCIL_WRITEMASK]: mask,\n [GL.STENCIL_BACK_WRITEMASK]: mask\n }),\n\n stencilMaskSeparate: (update, face, mask) =>\n update({\n [face === GL.FRONT ? GL.STENCIL_WRITEMASK : GL.STENCIL_BACK_WRITEMASK]: mask\n }),\n\n stencilFunc: (update, func, ref, mask) =>\n update({\n [GL.STENCIL_FUNC]: func,\n [GL.STENCIL_REF]: ref,\n [GL.STENCIL_VALUE_MASK]: mask,\n [GL.STENCIL_BACK_FUNC]: func,\n [GL.STENCIL_BACK_REF]: ref,\n [GL.STENCIL_BACK_VALUE_MASK]: mask\n }),\n\n stencilFuncSeparate: (update, face, func, ref, mask) =>\n update({\n [face === GL.FRONT ? GL.STENCIL_FUNC : GL.STENCIL_BACK_FUNC]: func,\n [face === GL.FRONT ? GL.STENCIL_REF : GL.STENCIL_BACK_REF]: ref,\n [face === GL.FRONT ? GL.STENCIL_VALUE_MASK : GL.STENCIL_BACK_VALUE_MASK]: mask\n }),\n\n stencilOp: (update, fail, zfail, zpass) =>\n update({\n [GL.STENCIL_FAIL]: fail,\n [GL.STENCIL_PASS_DEPTH_FAIL]: zfail,\n [GL.STENCIL_PASS_DEPTH_PASS]: zpass,\n [GL.STENCIL_BACK_FAIL]: fail,\n [GL.STENCIL_BACK_PASS_DEPTH_FAIL]: zfail,\n [GL.STENCIL_BACK_PASS_DEPTH_PASS]: zpass\n }),\n\n stencilOpSeparate: (update, face, fail, zfail, zpass) =>\n update({\n [face === GL.FRONT ? GL.STENCIL_FAIL : GL.STENCIL_BACK_FAIL]: fail,\n [face === GL.FRONT ? GL.STENCIL_PASS_DEPTH_FAIL : GL.STENCIL_BACK_PASS_DEPTH_FAIL]: zfail,\n [face === GL.FRONT ? GL.STENCIL_PASS_DEPTH_PASS : GL.STENCIL_BACK_PASS_DEPTH_PASS]: zpass\n }),\n\n viewport: (update, x, y, width, height) =>\n update({\n [GL.VIEWPORT]: [x, y, width, height]\n })\n};\n\n// GETTER TABLE - FOR READING OUT AN ENTIRE CONTEXT\n\nconst isEnabled = (gl, key) => gl.isEnabled(key);\n\n// Exceptions for any keys that cannot be queried by gl.getParameters\nexport const GL_PARAMETER_GETTERS = {\n [GL.BLEND]: isEnabled,\n [GL.CULL_FACE]: isEnabled,\n [GL.DEPTH_TEST]: isEnabled,\n [GL.DITHER]: isEnabled,\n [GL.POLYGON_OFFSET_FILL]: isEnabled,\n [GL.SAMPLE_ALPHA_TO_COVERAGE]: isEnabled,\n [GL.SAMPLE_COVERAGE]: isEnabled,\n [GL.SCISSOR_TEST]: isEnabled,\n [GL.STENCIL_TEST]: isEnabled,\n\n // WebGL 2\n [GL.RASTERIZER_DISCARD]: isEnabled\n};\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","export default function deprecatedPropType(validator, reason) {\n if (process.env.NODE_ENV === 'production') {\n return function () {\n return null;\n };\n }\n\n return function (props, propName, componentName, location, propFullName) {\n var componentNameSafe = componentName || '<>';\n var propFullNameSafe = propFullName || propName;\n\n if (typeof props[propName] !== 'undefined') {\n return new Error(\"The \".concat(location, \" `\").concat(propFullNameSafe, \"` of \") + \"`\".concat(componentNameSafe, \"` is deprecated. \").concat(reason));\n }\n\n return null;\n };\n}","import {\n Feature,\n FeatureCollection,\n Geometry,\n Polygon,\n MultiLineString,\n MultiPolygon,\n Position,\n PolygonCoordinates,\n} from '../geojson-types';\n\nexport class ImmutableFeatureCollection {\n featureCollection: FeatureCollection;\n\n constructor(featureCollection: FeatureCollection) {\n this.featureCollection = featureCollection;\n }\n\n getObject() {\n return this.featureCollection;\n }\n\n /**\n * Replaces the position deeply nested withing the given feature's geometry.\n * Works with Point, MultiPoint, LineString, MultiLineString, Polygon, and MultiPolygon.\n *\n * @param featureIndex The index of the feature to update\n * @param positionIndexes An array containing the indexes of the position to replace\n * @param updatedPosition The updated position to place in the result (i.e. [lng, lat])\n *\n * @returns A new `ImmutableFeatureCollection` with the given position replaced. Does not modify this `ImmutableFeatureCollection`.\n */\n replacePosition(\n featureIndex: number,\n positionIndexes: number[] | null | undefined,\n updatedPosition: Position\n ): ImmutableFeatureCollection {\n const geometry = this.featureCollection.features[featureIndex].geometry;\n\n const isPolygonal = geometry.type === 'Polygon' || geometry.type === 'MultiPolygon';\n const updatedGeometry: any = {\n ...geometry,\n coordinates: immutablyReplacePosition(\n geometry.coordinates,\n positionIndexes,\n updatedPosition,\n isPolygonal\n ),\n };\n\n return this.replaceGeometry(featureIndex, updatedGeometry);\n }\n\n /**\n * Removes a position deeply nested in a GeoJSON geometry coordinates array.\n * Works with MultiPoint, LineString, MultiLineString, Polygon, and MultiPolygon.\n *\n * @param featureIndex The index of the feature to update\n * @param positionIndexes An array containing the indexes of the postion to remove\n *\n * @returns A new `ImmutableFeatureCollection` with the given coordinate removed. Does not modify this `ImmutableFeatureCollection`.\n */\n removePosition(\n featureIndex: number,\n positionIndexes: number[] | null | undefined\n ): ImmutableFeatureCollection {\n const geometry = this.featureCollection.features[featureIndex].geometry;\n\n if (geometry.type === 'Point') {\n throw Error(`Can't remove a position from a Point or there'd be nothing left`);\n }\n if (\n geometry.type === 'MultiPoint' && // only 1 point left\n geometry.coordinates.length < 2\n ) {\n throw Error(`Can't remove the last point of a MultiPoint or there'd be nothing left`);\n }\n if (\n geometry.type === 'LineString' && // only 2 positions\n geometry.coordinates.length < 3\n ) {\n throw Error(`Can't remove position. LineString must have at least two positions`);\n }\n if (\n geometry.type === 'Polygon' && // outer ring is a triangle\n geometry.coordinates[0].length < 5 &&\n Array.isArray(positionIndexes) && // trying to remove from outer ring\n positionIndexes[0] === 0\n ) {\n throw Error(`Can't remove position. Polygon's outer ring must have at least four positions`);\n }\n if (\n geometry.type === 'MultiLineString' && // only 1 LineString left\n geometry.coordinates.length === 1 && // only 2 positions\n geometry.coordinates[0].length < 3\n ) {\n throw Error(`Can't remove position. MultiLineString must have at least two positions`);\n }\n if (\n geometry.type === 'MultiPolygon' && // only 1 polygon left\n geometry.coordinates.length === 1 && // outer ring is a triangle\n geometry.coordinates[0][0].length < 5 &&\n Array.isArray(positionIndexes) && // trying to remove from first polygon\n positionIndexes[0] === 0 && // trying to remove from outer ring\n positionIndexes[1] === 0\n ) {\n throw Error(\n `Can't remove position. MultiPolygon's outer ring must have at least four positions`\n );\n }\n\n const isPolygonal = geometry.type === 'Polygon' || geometry.type === 'MultiPolygon';\n const updatedGeometry: any = {\n ...geometry,\n coordinates: immutablyRemovePosition(geometry.coordinates, positionIndexes, isPolygonal),\n };\n\n // Handle cases where incomplete geometries need pruned (e.g. holes that were triangles)\n pruneGeometryIfNecessary(updatedGeometry);\n\n return this.replaceGeometry(featureIndex, updatedGeometry);\n }\n\n /**\n * Adds a position deeply nested in a GeoJSON geometry coordinates array.\n * Works with MultiPoint, LineString, MultiLineString, Polygon, and MultiPolygon.\n *\n * @param featureIndex The index of the feature to update\n * @param positionIndexes An array containing the indexes of the position that will proceed the new position\n * @param positionToAdd The new position to place in the result (i.e. [lng, lat])\n *\n * @returns A new `ImmutableFeatureCollection` with the given coordinate removed. Does not modify this `ImmutableFeatureCollection`.\n */\n addPosition(\n featureIndex: number,\n positionIndexes: number[] | null | undefined,\n positionToAdd: Position\n ): ImmutableFeatureCollection {\n const geometry = this.featureCollection.features[featureIndex].geometry;\n\n if (geometry.type === 'Point') {\n throw new Error('Unable to add a position to a Point feature');\n }\n\n const isPolygonal = geometry.type === 'Polygon' || geometry.type === 'MultiPolygon';\n const updatedGeometry: any = {\n ...geometry,\n coordinates: immutablyAddPosition(\n geometry.coordinates,\n positionIndexes,\n positionToAdd,\n isPolygonal\n ),\n };\n\n return this.replaceGeometry(featureIndex, updatedGeometry);\n }\n\n replaceGeometry(featureIndex: number, geometry: Geometry): ImmutableFeatureCollection {\n const updatedFeature: any = {\n ...this.featureCollection.features[featureIndex],\n geometry,\n };\n\n const updatedFeatureCollection = {\n ...this.featureCollection,\n features: [\n ...this.featureCollection.features.slice(0, featureIndex),\n updatedFeature,\n ...this.featureCollection.features.slice(featureIndex + 1),\n ],\n };\n\n return new ImmutableFeatureCollection(updatedFeatureCollection);\n }\n\n addFeature(feature: Feature): ImmutableFeatureCollection {\n return this.addFeatures([feature]);\n }\n\n addFeatures(features: Feature[]): ImmutableFeatureCollection {\n const updatedFeatureCollection = {\n ...this.featureCollection,\n features: [...this.featureCollection.features, ...features],\n };\n\n return new ImmutableFeatureCollection(updatedFeatureCollection);\n }\n\n deleteFeature(featureIndex: number) {\n return this.deleteFeatures([featureIndex]);\n }\n\n deleteFeatures(featureIndexes: number[]) {\n const features = [...this.featureCollection.features];\n featureIndexes.sort();\n for (let i = featureIndexes.length - 1; i >= 0; i--) {\n const featureIndex = featureIndexes[i];\n if (featureIndex >= 0 && featureIndex < features.length) {\n features.splice(featureIndex, 1);\n }\n }\n\n const updatedFeatureCollection = {\n ...this.featureCollection,\n features,\n };\n\n return new ImmutableFeatureCollection(updatedFeatureCollection);\n }\n}\n\nfunction getUpdatedPosition(updatedPosition: Position, previousPosition: Position): Position {\n // This function checks if the updatedPosition is missing elevation\n // and copies it from previousPosition\n if (updatedPosition.length === 2 && previousPosition.length === 3) {\n const elevation = (previousPosition as any)[2];\n return [updatedPosition[0], updatedPosition[1], elevation];\n }\n\n return updatedPosition;\n}\n\nfunction immutablyReplacePosition(\n coordinates: any,\n positionIndexes: number[] | null | undefined,\n updatedPosition: Position,\n isPolygonal: boolean\n): any {\n if (!positionIndexes) {\n return coordinates;\n }\n if (positionIndexes.length === 0) {\n return getUpdatedPosition(updatedPosition, coordinates);\n }\n if (positionIndexes.length === 1) {\n const updated = [\n ...coordinates.slice(0, positionIndexes[0]),\n getUpdatedPosition(updatedPosition, coordinates[positionIndexes[0]]),\n ...coordinates.slice(positionIndexes[0] + 1),\n ];\n\n if (\n isPolygonal &&\n (positionIndexes[0] === 0 || positionIndexes[0] === coordinates.length - 1)\n ) {\n // for polygons, the first point is repeated at the end of the array\n // so, update it on both ends of the array\n updated[0] = getUpdatedPosition(updatedPosition, coordinates[0]);\n updated[coordinates.length - 1] = getUpdatedPosition(updatedPosition, coordinates[0]);\n }\n return updated;\n }\n\n // recursively update inner array\n return [\n ...coordinates.slice(0, positionIndexes[0]),\n immutablyReplacePosition(\n coordinates[positionIndexes[0]],\n positionIndexes.slice(1, positionIndexes.length),\n updatedPosition,\n isPolygonal\n ),\n ...coordinates.slice(positionIndexes[0] + 1),\n ];\n}\n\nfunction immutablyRemovePosition(\n coordinates: any,\n positionIndexes: number[] | null | undefined,\n isPolygonal: boolean\n): any {\n if (!positionIndexes) {\n return coordinates;\n }\n if (positionIndexes.length === 0) {\n throw Error('Must specify the index of the position to remove');\n }\n if (positionIndexes.length === 1) {\n const updated = [\n ...coordinates.slice(0, positionIndexes[0]),\n ...coordinates.slice(positionIndexes[0] + 1),\n ];\n\n if (\n isPolygonal &&\n (positionIndexes[0] === 0 || positionIndexes[0] === coordinates.length - 1)\n ) {\n // for polygons, the first point is repeated at the end of the array\n // so, if the first/last coordinate is to be removed, coordinates[1] will be the new first/last coordinate\n if (positionIndexes[0] === 0) {\n // change the last to be the same as the first\n updated[updated.length - 1] = updated[0];\n } else if (positionIndexes[0] === coordinates.length - 1) {\n // change the first to be the same as the last\n updated[0] = updated[updated.length - 1];\n }\n }\n return updated;\n }\n\n // recursively update inner array\n return [\n ...coordinates.slice(0, positionIndexes[0]),\n immutablyRemovePosition(\n coordinates[positionIndexes[0]],\n positionIndexes.slice(1, positionIndexes.length),\n isPolygonal\n ),\n ...coordinates.slice(positionIndexes[0] + 1),\n ];\n}\n\nfunction immutablyAddPosition(\n coordinates: any,\n positionIndexes: number[] | null | undefined,\n positionToAdd: Position,\n isPolygonal: boolean\n): any {\n if (!positionIndexes) {\n return coordinates;\n }\n if (positionIndexes.length === 0) {\n throw Error('Must specify the index of the position to remove');\n }\n if (positionIndexes.length === 1) {\n const updated = [\n ...coordinates.slice(0, positionIndexes[0]),\n positionToAdd,\n ...coordinates.slice(positionIndexes[0]),\n ];\n return updated;\n }\n\n // recursively update inner array\n return [\n ...coordinates.slice(0, positionIndexes[0]),\n immutablyAddPosition(\n coordinates[positionIndexes[0]],\n positionIndexes.slice(1, positionIndexes.length),\n positionToAdd,\n isPolygonal\n ),\n ...coordinates.slice(positionIndexes[0] + 1),\n ];\n}\n\nfunction pruneGeometryIfNecessary(geometry: Geometry) {\n switch (geometry.type) {\n case 'Polygon':\n prunePolygonIfNecessary(geometry);\n break;\n case 'MultiLineString':\n pruneMultiLineStringIfNecessary(geometry);\n break;\n case 'MultiPolygon':\n pruneMultiPolygonIfNecessary(geometry);\n break;\n default:\n // Not downgradable\n break;\n }\n}\n\nfunction prunePolygonIfNecessary(geometry: Polygon) {\n const polygon = geometry.coordinates;\n\n // If any hole is no longer a polygon, remove the hole entirely\n for (let holeIndex = 1; holeIndex < polygon.length; holeIndex++) {\n if (removeHoleIfNecessary(polygon, holeIndex)) {\n // It was removed, so keep the index the same\n holeIndex--;\n }\n }\n}\n\nfunction pruneMultiLineStringIfNecessary(geometry: MultiLineString) {\n for (let lineStringIndex = 0; lineStringIndex < geometry.coordinates.length; lineStringIndex++) {\n const lineString = geometry.coordinates[lineStringIndex];\n if (lineString.length === 1) {\n // Only a single position left on this LineString, so remove it (can't have Point in MultiLineString)\n geometry.coordinates.splice(lineStringIndex, 1);\n // Keep the index the same\n lineStringIndex--;\n }\n }\n}\n\nfunction pruneMultiPolygonIfNecessary(geometry: MultiPolygon) {\n for (let polygonIndex = 0; polygonIndex < geometry.coordinates.length; polygonIndex++) {\n const polygon = geometry.coordinates[polygonIndex];\n const outerRing = polygon[0];\n\n // If the outer ring is no longer a polygon, remove the whole polygon\n if (outerRing.length <= 3) {\n geometry.coordinates.splice(polygonIndex, 1);\n // It was removed, so keep the index the same\n polygonIndex--;\n }\n\n for (let holeIndex = 1; holeIndex < polygon.length; holeIndex++) {\n if (removeHoleIfNecessary(polygon, holeIndex)) {\n // It was removed, so keep the index the same\n holeIndex--;\n }\n }\n }\n}\n\nfunction removeHoleIfNecessary(polygon: PolygonCoordinates, holeIndex: number) {\n const hole = polygon[holeIndex];\n if (hole.length <= 3) {\n polygon.splice(holeIndex, 1);\n return true;\n }\n return false;\n}\n","// Support for listening to context state changes and intercepting state queries\n// NOTE: this system does not handle buffer bindings\n/** @typedef {import('./track-context-state')} types */\n\nimport {GL_PARAMETER_DEFAULTS, GL_HOOKED_SETTERS} from './webgl-parameter-tables';\nimport {setParameters, getParameters} from './unified-parameter-api';\nimport {assert} from '../utils/assert';\nimport {deepArrayEqual} from '../utils/utils';\n\n// HELPER FUNCTIONS - INSTALL GET/SET INTERCEPTORS (SPYS) ON THE CONTEXT\n\n// Overrides a WebGLRenderingContext state \"getter\" function\n// to return values directly from cache\nfunction installGetterOverride(gl, functionName) {\n // Get the original function from the WebGLRenderingContext\n const originalGetterFunc = gl[functionName].bind(gl);\n\n // Wrap it with a spy so that we can update our state cache when it gets called\n gl[functionName] = function get(...params) {\n const pname = params[0];\n\n // WebGL limits are not prepopulated in the cache, it's neither undefined in GL_PARAMETER_DEFAULTS\n // nor intercepted by GL_HOOKED_SETTERS. Query the original getter.\n if (!(pname in gl.state.cache)) {\n return originalGetterFunc(...params);\n }\n\n // Optionally call the original function to do a \"hard\" query from the WebGLRenderingContext\n return gl.state.enable\n ? // Call the getter the params so that it can e.g. serve from a cache\n gl.state.cache[pname]\n : // Optionally call the original function to do a \"hard\" query from the WebGLRenderingContext\n originalGetterFunc(...params);\n };\n\n // Set the name of this anonymous function to help in debugging and profiling\n Object.defineProperty(gl[functionName], 'name', {\n value: `${functionName}-from-cache`,\n configurable: false\n });\n}\n\n// Overrides a WebGLRenderingContext state \"setter\" function\n// to call a setter spy before the actual setter. Allows us to keep a cache\n// updated with a copy of the WebGL context state.\nfunction installSetterSpy(gl, functionName, setter) {\n // Get the original function from the WebGLRenderingContext\n const originalSetterFunc = gl[functionName].bind(gl);\n\n // Wrap it with a spy so that we can update our state cache when it gets called\n gl[functionName] = function set(...params) {\n // Update the value\n // Call the setter with the state cache and the params so that it can store the parameters\n const {valueChanged, oldValue} = setter(gl.state._updateCache, ...params);\n\n // Call the original WebGLRenderingContext func to make sure the context actually gets updated\n if (valueChanged) {\n originalSetterFunc(...params);\n }\n\n // Note: if the original function fails to set the value, our state cache will be bad\n // No solution for this at the moment, but assuming that this is unlikely to be a real problem\n // We could call the setter after the originalSetterFunc. Concern is that this would\n // cause different behavior in debug mode, where originalSetterFunc can throw exceptions\n\n return oldValue;\n };\n\n // Set the name of this anonymous function to help in debugging and profiling\n Object.defineProperty(gl[functionName], 'name', {\n value: `${functionName}-to-cache`,\n configurable: false\n });\n}\n\nfunction installProgramSpy(gl) {\n const originalUseProgram = gl.useProgram.bind(gl);\n\n gl.useProgram = function useProgramLuma(handle) {\n if (gl.state.program !== handle) {\n originalUseProgram(handle);\n gl.state.program = handle;\n }\n };\n}\n\n// HELPER CLASS - GLState\n\n/* eslint-disable no-shadow */\nclass GLState {\n constructor(\n gl,\n {\n copyState = false, // Copy cache from params (slow) or initialize from WebGL defaults (fast)\n log = () => {} // Logging function, called when gl parameter change calls are actually issued\n } = {}\n ) {\n this.gl = gl;\n this.program = null;\n this.stateStack = [];\n this.enable = true;\n this.cache = copyState ? getParameters(gl) : Object.assign({}, GL_PARAMETER_DEFAULTS);\n this.log = log;\n\n this._updateCache = this._updateCache.bind(this);\n Object.seal(this);\n }\n\n push(values = {}) {\n this.stateStack.push({});\n }\n\n pop() {\n assert(this.stateStack.length > 0);\n // Use the saved values in the state stack to restore parameters\n const oldValues = this.stateStack[this.stateStack.length - 1];\n setParameters(this.gl, oldValues);\n // Don't pop until we have reset parameters (to make sure other \"stack frames\" are not affected)\n this.stateStack.pop();\n }\n\n // interceptor for context set functions - update our cache and our stack\n // values (Object) - the key values for this setter\n _updateCache(values) {\n let valueChanged = false;\n let oldValue; // = undefined\n\n const oldValues = this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1];\n\n for (const key in values) {\n assert(key !== undefined);\n const value = values[key];\n const cached = this.cache[key];\n // Check that value hasn't already been shadowed\n if (!deepArrayEqual(value, cached)) {\n valueChanged = true;\n oldValue = cached;\n\n // First, save current value being shadowed\n // If a state stack frame is active, save the current parameter values for pop\n // but first check that value hasn't already been shadowed and saved\n if (oldValues && !(key in oldValues)) {\n oldValues[key] = cached;\n }\n\n // Save current value being shadowed\n this.cache[key] = value;\n }\n }\n\n return {valueChanged, oldValue};\n }\n}\n\n// PUBLIC API\n\n/**\n * Initialize WebGL state caching on a context\n * @type {types['trackContextState']}\n */\n// After calling this function, context state will be cached\n// gl.state.push() and gl.state.pop() will be available for saving,\n// temporarily modifying, and then restoring state.\nexport function trackContextState(gl, options = {}) {\n const {enable = true, copyState} = options;\n assert(copyState !== undefined);\n // @ts-ignore\n if (!gl.state) {\n const global_ = typeof global !== 'undefined' ? global : window;\n // @ts-ignore\n const {polyfillContext} = global_;\n if (polyfillContext) {\n polyfillContext(gl);\n }\n\n // Create a state cache\n // @ts-ignore\n gl.state = new GLState(gl, {copyState});\n\n installProgramSpy(gl);\n\n // intercept all setter functions in the table\n for (const key in GL_HOOKED_SETTERS) {\n const setter = GL_HOOKED_SETTERS[key];\n installSetterSpy(gl, key, setter);\n }\n\n // intercept all getter functions in the table\n installGetterOverride(gl, 'getParameter');\n installGetterOverride(gl, 'isEnabled');\n }\n\n // @ts-ignore\n gl.state.enable = enable;\n\n return gl;\n}\n\n/**\n * Initialize WebGL state caching on a context\n * @type {types['pushContextState']}\n */\nexport function pushContextState(gl) {\n // @ts-ignore\n if (!gl.state) {\n trackContextState(gl, {copyState: false});\n }\n // @ts-ignore\n gl.state.push();\n}\n\n/**\n * Initialize WebGL state caching on a context\n * @type {types['popContextState']}\n */\nexport function popContextState(gl) {\n // @ts-ignore\n assert(gl.state);\n // @ts-ignore\n gl.state.pop();\n}\n","/* eslint-disable react-hooks/rules-of-hooks, react-hooks/exhaustive-deps */\nimport * as React from 'react';\nexport default function useControlled(_ref) {\n var controlled = _ref.controlled,\n defaultProp = _ref.default,\n name = _ref.name,\n _ref$state = _ref.state,\n state = _ref$state === void 0 ? 'value' : _ref$state;\n\n var _React$useRef = React.useRef(controlled !== undefined),\n isControlled = _React$useRef.current;\n\n var _React$useState = React.useState(defaultProp),\n valueState = _React$useState[0],\n setValue = _React$useState[1];\n\n var value = isControlled ? controlled : valueState;\n\n if (process.env.NODE_ENV !== 'production') {\n React.useEffect(function () {\n if (isControlled !== (controlled !== undefined)) {\n console.error([\"Material-UI: A component is changing the \".concat(isControlled ? '' : 'un', \"controlled \").concat(state, \" state of \").concat(name, \" to be \").concat(isControlled ? 'un' : '', \"controlled.\"), 'Elements should not switch from uncontrolled to controlled (or vice versa).', \"Decide between using a controlled or uncontrolled \".concat(name, \" \") + 'element for the lifetime of the component.', \"The nature of the state is determined during the first render, it's considered controlled if the value is not `undefined`.\", 'More info: https://fb.me/react-controlled-components'].join('\\n'));\n }\n }, [controlled]);\n\n var _React$useRef2 = React.useRef(defaultProp),\n defaultValue = _React$useRef2.current;\n\n React.useEffect(function () {\n if (!isControlled && defaultValue !== defaultProp) {\n console.error([\"Material-UI: A component is changing the default \".concat(state, \" state of an uncontrolled \").concat(name, \" after being initialized. \") + \"To suppress this warning opt to use a controlled \".concat(name, \".\")].join('\\n'));\n }\n }, [JSON.stringify(defaultProp)]);\n }\n\n var setValueIfUncontrolled = React.useCallback(function (newValue) {\n if (!isControlled) {\n setValue(newValue);\n }\n }, []);\n return [value, setValueIfUncontrolled];\n}","import GL from '@luma.gl/constants';\nimport {getWebGL2Context, assertWebGL2Context, log} from '@luma.gl/gltools';\nimport Resource from './resource';\nimport Texture2D from './texture-2d';\nimport Renderbuffer from './renderbuffer';\nimport {clear, clearBuffer} from './clear';\nimport {copyToDataUrl} from './copy-and-blit.js';\n\nimport {getFeatures} from '../features';\nimport {getKey} from '../webgl-utils/constants-to-keys';\nimport {assert} from '../utils/assert';\n\nconst ERR_MULTIPLE_RENDERTARGETS = 'Multiple render targets not supported';\n\nexport default class Framebuffer extends Resource {\n static isSupported(gl, options = {}) {\n const {\n colorBufferFloat, // Whether floating point textures can be rendered and read\n colorBufferHalfFloat // Whether half float textures can be rendered and read\n } = options;\n let supported = true;\n\n if (colorBufferFloat) {\n supported = Boolean(\n // WebGL 2\n gl.getExtension('EXT_color_buffer_float') ||\n // WebGL 1, not exposed on all platforms\n gl.getExtension('WEBGL_color_buffer_float') ||\n // WebGL 1, implicitly enables float render targets https://www.khronos.org/registry/webgl/extensions/OES_texture_float/\n gl.getExtension('OES_texture_float')\n );\n }\n\n if (colorBufferHalfFloat) {\n supported =\n supported &&\n Boolean(\n // WebGL 2\n gl.getExtension('EXT_color_buffer_float') ||\n // WebGL 1\n gl.getExtension('EXT_color_buffer_half_float')\n );\n }\n\n return supported;\n }\n\n // Create a Framebuffer wrapper for the default framebuffer (target === null)\n static getDefaultFramebuffer(gl) {\n gl.luma = gl.luma || {};\n gl.luma.defaultFramebuffer =\n gl.luma.defaultFramebuffer ||\n new Framebuffer(gl, {\n id: 'default-framebuffer',\n handle: null,\n attachments: {}\n });\n // TODO - can we query for and get a handle to the GL.FRONT renderbuffer?\n return gl.luma.defaultFramebuffer;\n }\n\n get MAX_COLOR_ATTACHMENTS() {\n const gl2 = assertWebGL2Context(this.gl);\n return gl2.getParameter(gl2.MAX_COLOR_ATTACHMENTS);\n }\n\n get MAX_DRAW_BUFFERS() {\n const gl2 = assertWebGL2Context(this.gl);\n return gl2.getParameter(gl2.MAX_DRAW_BUFFERS);\n }\n\n constructor(gl, opts = {}) {\n super(gl, opts);\n\n // Public members\n this.width = null;\n this.height = null;\n this.attachments = {};\n this.readBuffer = GL.COLOR_ATTACHMENT0;\n this.drawBuffers = [GL.COLOR_ATTACHMENT0];\n this.ownResources = [];\n this.initialize(opts);\n\n Object.seal(this);\n }\n\n get color() {\n return this.attachments[GL.COLOR_ATTACHMENT0] || null;\n }\n\n get texture() {\n return this.attachments[GL.COLOR_ATTACHMENT0] || null;\n }\n\n get depth() {\n return (\n this.attachments[GL.DEPTH_ATTACHMENT] || this.attachments[GL.DEPTH_STENCIL_ATTACHMENT] || null\n );\n }\n\n get stencil() {\n return (\n this.attachments[GL.STENCIL_ATTACHMENT] ||\n this.attachments[GL.DEPTH_STENCIL_ATTACHMENT] ||\n null\n );\n }\n\n initialize({\n width = 1,\n height = 1,\n attachments = null,\n color = true,\n depth = true,\n stencil = false,\n check = true,\n readBuffer = undefined,\n drawBuffers = undefined\n }) {\n assert(width >= 0 && height >= 0, 'Width and height need to be integers');\n\n // Store actual width and height for diffing\n this.width = width;\n this.height = height;\n\n // Resize any provided attachments - note that resize only resizes if needed\n // Note: A framebuffer has no separate size, it is defined by its attachments (which must agree)\n if (attachments) {\n for (const attachment in attachments) {\n const target = attachments[attachment];\n const object = Array.isArray(target) ? target[0] : target;\n object.resize({width, height});\n }\n } else {\n // Create any requested default attachments\n attachments = this._createDefaultAttachments(color, depth, stencil, width, height);\n }\n\n this.update({clearAttachments: true, attachments, readBuffer, drawBuffers});\n\n // Checks that framebuffer was properly set up, if not, throws an explanatory error\n if (attachments && check) {\n this.checkStatus();\n }\n }\n\n delete() {\n for (const resource of this.ownResources) {\n resource.delete();\n }\n super.delete();\n return this;\n }\n\n update({\n attachments = {},\n readBuffer,\n drawBuffers,\n clearAttachments = false,\n resizeAttachments = true\n }) {\n this.attach(attachments, {clearAttachments, resizeAttachments});\n\n const {gl} = this;\n // Multiple render target support, set read buffer and draw buffers\n const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle);\n if (readBuffer) {\n this._setReadBuffer(readBuffer);\n }\n if (drawBuffers) {\n this._setDrawBuffers(drawBuffers);\n }\n // @ts-ignore\n gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n\n return this;\n }\n\n // Attachment resize is expected to be a noop if size is same\n resize(options = {}) {\n let {width, height} = options;\n // for default framebuffer, just update the stored size\n if (this.handle === null) {\n assert(width === undefined && height === undefined);\n this.width = this.gl.drawingBufferWidth;\n this.height = this.gl.drawingBufferHeight;\n return this;\n }\n\n if (width === undefined) {\n width = this.gl.drawingBufferWidth;\n }\n if (height === undefined) {\n height = this.gl.drawingBufferHeight;\n }\n\n if (width !== this.width && height !== this.height) {\n log.log(2, `Resizing framebuffer ${this.id} to ${width}x${height}`)();\n }\n for (const attachmentPoint in this.attachments) {\n this.attachments[attachmentPoint].resize({width, height});\n }\n this.width = width;\n this.height = height;\n return this;\n }\n\n // Attach from a map of attachments\n attach(attachments, {clearAttachments = false, resizeAttachments = true} = {}) {\n const newAttachments = {};\n\n // Any current attachments need to be removed, add null values to map\n if (clearAttachments) {\n Object.keys(this.attachments).forEach(key => {\n newAttachments[key] = null;\n });\n }\n\n // Overlay the new attachments\n Object.assign(newAttachments, attachments);\n\n const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle);\n\n // Walk the attachments\n for (const key in newAttachments) {\n // Ensure key is not undefined\n assert(key !== undefined, 'Misspelled framebuffer binding point?');\n\n const attachment = Number(key);\n\n const descriptor = newAttachments[attachment];\n let object = descriptor;\n if (!object) {\n this._unattach(attachment);\n } else if (object instanceof Renderbuffer) {\n this._attachRenderbuffer({attachment, renderbuffer: object});\n } else if (Array.isArray(descriptor)) {\n const [texture, layer = 0, level = 0] = descriptor;\n object = texture;\n this._attachTexture({attachment, texture, layer, level});\n } else {\n this._attachTexture({attachment, texture: object, layer: 0, level: 0});\n }\n\n // Resize objects\n if (resizeAttachments && object) {\n object.resize({width: this.width, height: this.height});\n }\n }\n\n // @ts-ignore\n this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n\n // Assign to attachments and remove any nulls to get a clean attachment map\n Object.assign(this.attachments, attachments);\n Object.keys(this.attachments)\n .filter(key => !this.attachments[key])\n .forEach(key => {\n delete this.attachments[key];\n });\n }\n\n checkStatus() {\n const {gl} = this;\n const status = this.getStatus();\n if (status !== gl.FRAMEBUFFER_COMPLETE) {\n throw new Error(_getFrameBufferStatus(status));\n }\n return this;\n }\n\n getStatus() {\n const {gl} = this;\n const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle);\n const status = gl.checkFramebufferStatus(GL.FRAMEBUFFER);\n // @ts-ignore\n gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n return status;\n }\n\n clear(options = {}) {\n const {color, depth, stencil, drawBuffers = []} = options;\n\n // Bind framebuffer and delegate to global clear functions\n const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle);\n\n if (color || depth || stencil) {\n clear(this.gl, {color, depth, stencil});\n }\n\n drawBuffers.forEach((value, drawBuffer) => {\n clearBuffer(this.gl, {drawBuffer, value});\n });\n\n // @ts-ignore\n this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null);\n\n return this;\n }\n\n // NOTE: Slow requires roundtrip to GPU\n // App can provide pixelArray or have it auto allocated by this method\n // @returns {Uint8Array|Uint16Array|FloatArray} - pixel array,\n // newly allocated by this method unless provided by app.\n readPixels(opts = {}) {\n log.error(\n 'Framebuffer.readPixels() is no logner supported, use readPixelsToArray(framebuffer)'\n )();\n return null;\n }\n\n // Reads data into provided buffer object asynchronously\n // This function doesn't wait for copy to be complete, it programs GPU to perform a DMA transffer.\n readPixelsToBuffer(opts = {}) {\n log.error(\n 'Framebuffer.readPixelsToBuffer()is no logner supported, use readPixelsToBuffer(framebuffer)'\n )();\n return null;\n }\n\n // Reads pixels as a dataUrl\n copyToDataUrl(opts = {}) {\n log.error(\n 'Framebuffer.copyToDataUrl() is no logner supported, use copyToDataUrl(framebuffer)'\n )();\n return null;\n }\n\n // Reads pixels into an HTML Image\n copyToImage(opts = {}) {\n log.error('Framebuffer.copyToImage() is no logner supported, use copyToImage(framebuffer)')();\n return null;\n }\n\n // copyToFramebuffer({width, height}) {\n // const scaleX = width / this.width;\n // const scaleY = height / this.height;\n // const scale = Math.min(scaleX, scaleY);\n // width = width * scale;\n // height = height * scale;\n // const scaledFramebuffer = new Framebuffer(this.gl, {width, height});\n // this.blit();\n // }\n\n // Copy a rectangle from a framebuffer attachment into a texture (at an offset)\n // NOTE: assumes texture has enough storage allocated\n // eslint-disable-next-line complexity\n copyToTexture(opts = {}) {\n log.error(\n 'Framebuffer.copyToTexture({...}) is no logner supported, use copyToTexture(source, target, opts})'\n )();\n return null;\n }\n\n // WEBGL2 INTERFACE\n\n // Copies a rectangle of pixels between framebuffers\n // eslint-disable-next-line complexity\n blit(opts = {}) {\n log.error('Framebuffer.blit({...}) is no logner supported, use blit(source, target, opts)')();\n return null;\n }\n\n // signals to the GL that it need not preserve all pixels of a specified region of the framebuffer\n invalidate({attachments = [], x = 0, y = 0, width, height}) {\n const gl2 = assertWebGL2Context(this.gl);\n const prevHandle = gl2.bindFramebuffer(GL.READ_FRAMEBUFFER, this.handle);\n const invalidateAll = x === 0 && y === 0 && width === undefined && height === undefined;\n if (invalidateAll) {\n gl2.invalidateFramebuffer(GL.READ_FRAMEBUFFER, attachments);\n } else {\n // TODO - why does type checking fail on this line\n // @ts-ignore\n gl2.invalidateFramebuffer(GL.READ_FRAMEBUFFER, attachments, x, y, width, height);\n }\n // @ts-ignore\n gl2.bindFramebuffer(GL.READ_FRAMEBUFFER, prevHandle);\n return this;\n }\n\n // Return the value for `pname` of the specified attachment.\n // The type returned is the type of the requested pname\n getAttachmentParameter(attachment, pname, keys) {\n let value = this._getAttachmentParameterFallback(pname);\n if (value === null) {\n this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle);\n value = this.gl.getFramebufferAttachmentParameter(GL.FRAMEBUFFER, attachment, pname);\n this.gl.bindFramebuffer(GL.FRAMEBUFFER, null);\n }\n if (keys && value > 1000) {\n // @ts-ignore\n value = getKey(this.gl, value);\n }\n return value;\n }\n\n getAttachmentParameters(\n attachment = GL.COLOR_ATTACHMENT0,\n keys,\n // @ts-ignore\n parameters = this.constructor.ATTACHMENT_PARAMETERS || []\n ) {\n const values = {};\n for (const pname of parameters) {\n const key = keys ? getKey(this.gl, pname) : pname;\n values[key] = this.getAttachmentParameter(attachment, pname, keys);\n }\n return values;\n }\n\n getParameters(keys = true) {\n const attachments = Object.keys(this.attachments);\n // if (this === this.gl.luma.defaultFramebuffer) {\n // attachments = [GL.COLOR_ATTACHMENT0, GL.DEPTH_STENCIL_ATTACHMENT];\n // }\n const parameters = {};\n for (const attachmentName of attachments) {\n const attachment = Number(attachmentName);\n const key = keys ? getKey(this.gl, attachment) : attachment;\n parameters[key] = this.getAttachmentParameters(attachment, keys);\n }\n return parameters;\n }\n\n // DEBUG\n\n // Note: Will only work when called in an event handler\n show() {\n if (typeof window !== 'undefined') {\n window.open(copyToDataUrl(this), 'luma-debug-texture');\n }\n return this;\n }\n\n log(logLevel = 0, message = '') {\n if (logLevel > log.level || typeof window === 'undefined') {\n return this;\n }\n message = message || `Framebuffer ${this.id}`;\n const image = copyToDataUrl(this, {targetMaxHeight: 100});\n log.image({logLevel, message, image}, message)();\n return this;\n }\n\n // WEBGL INTERFACE\n bind({target = GL.FRAMEBUFFER} = {}) {\n this.gl.bindFramebuffer(target, this.handle);\n return this;\n }\n\n unbind({target = GL.FRAMEBUFFER} = {}) {\n this.gl.bindFramebuffer(target, null);\n return this;\n }\n\n // PRIVATE METHODS\n\n _createDefaultAttachments(color, depth, stencil, width, height) {\n let defaultAttachments = null;\n\n // Add a color buffer if requested and not supplied\n if (color) {\n defaultAttachments = defaultAttachments || {};\n defaultAttachments[GL.COLOR_ATTACHMENT0] = new Texture2D(this.gl, {\n id: `${this.id}-color0`,\n pixels: null, // reserves texture memory, but texels are undefined\n format: GL.RGBA,\n type: GL.UNSIGNED_BYTE,\n width,\n height,\n // Note: Mipmapping can be disabled by texture resource when we resize the texture\n // to a non-power-of-two dimenstion (NPOT texture) under WebGL1. To have consistant\n // behavior we always disable mipmaps.\n mipmaps: false,\n // Set MIN and MAG filtering parameters so mipmaps are not used in sampling.\n // Use LINEAR so subpixel algos like fxaa work.\n // Set WRAP modes that support NPOT textures too.\n parameters: {\n [GL.TEXTURE_MIN_FILTER]: GL.LINEAR,\n [GL.TEXTURE_MAG_FILTER]: GL.LINEAR,\n [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE,\n [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE\n }\n });\n // track to delete later\n this.ownResources.push(defaultAttachments[GL.COLOR_ATTACHMENT0]);\n }\n\n if (depth && stencil) {\n // TODO - handle separate stencil\n defaultAttachments = defaultAttachments || {};\n defaultAttachments[GL.DEPTH_STENCIL_ATTACHMENT] = new Renderbuffer(this.gl, {\n id: `${this.id}-depth-stencil`,\n format: GL.DEPTH24_STENCIL8,\n width,\n height: 111\n });\n // track to delete later\n this.ownResources.push(defaultAttachments[GL.DEPTH_STENCIL_ATTACHMENT]);\n // TODO - optional texture\n // new Texture2D(this.gl, {\n // id: `${this.id}-depth-stencil`,\n // format: GL.DEPTH24_STENCIL8,\n // dataFormat: GL.DEPTH_STENCIL,\n // type: GL.UNSIGNED_INT_24_8,\n // width,\n // height,\n // mipmaps: false\n // });\n } else if (depth) {\n // Add a depth buffer if requested and not supplied\n defaultAttachments = defaultAttachments || {};\n defaultAttachments[GL.DEPTH_ATTACHMENT] = new Renderbuffer(this.gl, {\n id: `${this.id}-depth`,\n format: GL.DEPTH_COMPONENT16,\n width,\n height\n });\n // track to delete later\n this.ownResources.push(defaultAttachments[GL.DEPTH_ATTACHMENT]);\n } else if (stencil) {\n // TODO - handle separate stencil\n assert(false);\n }\n\n return defaultAttachments;\n }\n\n _unattach(attachment) {\n const oldAttachment = this.attachments[attachment];\n if (!oldAttachment) {\n return;\n }\n if (oldAttachment instanceof Renderbuffer) {\n // render buffer\n this.gl.framebufferRenderbuffer(GL.FRAMEBUFFER, attachment, GL.RENDERBUFFER, null);\n } else {\n // Must be a texture attachment\n this.gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, GL.TEXTURE_2D, null, 0);\n }\n delete this.attachments[attachment];\n }\n\n _attachRenderbuffer({attachment = GL.COLOR_ATTACHMENT0, renderbuffer}) {\n const {gl} = this;\n // TODO - is the bind needed?\n // gl.bindRenderbuffer(GL.RENDERBUFFER, renderbuffer.handle);\n gl.framebufferRenderbuffer(GL.FRAMEBUFFER, attachment, GL.RENDERBUFFER, renderbuffer.handle);\n // TODO - is the unbind needed?\n // gl.bindRenderbuffer(GL.RENDERBUFFER, null);\n\n this.attachments[attachment] = renderbuffer;\n }\n\n // layer = 0 - index into Texture2DArray and Texture3D or face for `TextureCubeMap`\n // level = 0 - mipmapLevel (must be 0 in WebGL1)\n _attachTexture({attachment = GL.COLOR_ATTACHMENT0, texture, layer, level}) {\n const {gl} = this;\n gl.bindTexture(texture.target, texture.handle);\n\n switch (texture.target) {\n case GL.TEXTURE_2D_ARRAY:\n case GL.TEXTURE_3D:\n const gl2 = assertWebGL2Context(gl);\n gl2.framebufferTextureLayer(GL.FRAMEBUFFER, attachment, texture.target, level, layer);\n break;\n\n case GL.TEXTURE_CUBE_MAP:\n // layer must be a cubemap face (or if index, converted to cube map face)\n const face = mapIndexToCubeMapFace(layer);\n gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, face, texture.handle, level);\n break;\n\n case GL.TEXTURE_2D:\n gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, GL.TEXTURE_2D, texture.handle, level);\n break;\n\n default:\n assert(false, 'Illegal texture type');\n }\n\n gl.bindTexture(texture.target, null);\n this.attachments[attachment] = texture;\n }\n\n // Expects framebuffer to be bound\n _setReadBuffer(readBuffer) {\n const gl2 = getWebGL2Context(this.gl);\n if (gl2) {\n gl2.readBuffer(readBuffer);\n } else {\n // Setting to color attachment 0 is a noop, so allow it in WebGL1\n assert(\n readBuffer === GL.COLOR_ATTACHMENT0 || readBuffer === GL.BACK,\n ERR_MULTIPLE_RENDERTARGETS\n );\n }\n this.readBuffer = readBuffer;\n }\n\n // Expects framebuffer to be bound\n _setDrawBuffers(drawBuffers) {\n const {gl} = this;\n const gl2 = assertWebGL2Context(gl);\n if (gl2) {\n gl2.drawBuffers(drawBuffers);\n } else {\n // TODO - is this not handled by polyfills?\n const ext = gl.getExtension('WEBGL_draw_buffers');\n if (ext) {\n ext.drawBuffersWEBGL(drawBuffers);\n } else {\n // Setting a single draw buffer to color attachment 0 is a noop, allow in WebGL1\n assert(\n drawBuffers.length === 1 &&\n (drawBuffers[0] === GL.COLOR_ATTACHMENT0 || drawBuffers[0] === GL.BACK),\n ERR_MULTIPLE_RENDERTARGETS\n );\n }\n }\n this.drawBuffers = drawBuffers;\n }\n\n // Attempt to provide workable defaults for WebGL2 symbols under WebGL1\n // null means OK to query\n // TODO - move to webgl1 polyfills\n /* eslint-disable complexity */\n _getAttachmentParameterFallback(pname) {\n const caps = getFeatures(this.gl);\n\n switch (pname) {\n case GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER: // GLint\n return !caps.WEBGL2 ? 0 : null;\n case GL.FRAMEBUFFER_ATTACHMENT_RED_SIZE: // GLint\n case GL.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: // GLint\n case GL.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: // GLint\n case GL.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE: // GLint\n case GL.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE: // GLint\n case GL.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE: // GLint\n return !caps.WEBGL2 ? 8 : null;\n case GL.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE: // GLenum\n return !caps.WEBGL2 ? GL.UNSIGNED_INT : null;\n case GL.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING:\n return !caps.WEBGL2 && !caps.EXT_sRGB ? GL.LINEAR : null;\n default:\n return null;\n }\n }\n /* eslint-enable complexity */\n\n // RESOURCE METHODS\n\n _createHandle() {\n return this.gl.createFramebuffer();\n }\n\n _deleteHandle() {\n this.gl.deleteFramebuffer(this.handle);\n }\n\n _bindHandle(handle) {\n return this.gl.bindFramebuffer(GL.FRAMEBUFFER, handle);\n }\n}\n\n// PUBLIC METHODS\n\n// Map an index to a cube map face constant\nfunction mapIndexToCubeMapFace(layer) {\n // TEXTURE_CUBE_MAP_POSITIVE_X is a big value (0x8515)\n // if smaller assume layer is index, otherwise assume it is already a cube map face constant\n return layer < GL.TEXTURE_CUBE_MAP_POSITIVE_X ? layer + GL.TEXTURE_CUBE_MAP_POSITIVE_X : layer;\n}\n\n// Helper METHODS\n// Get a string describing the framebuffer error if installed\nfunction _getFrameBufferStatus(status) {\n // Use error mapping if installed\n // @ts-ignore\n const STATUS = Framebuffer.STATUS || {};\n return STATUS[status] || `Framebuffer error ${status}`;\n}\n\nexport const FRAMEBUFFER_ATTACHMENT_PARAMETERS = [\n GL.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, // WebGLRenderbuffer or WebGLTexture\n GL.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, // GL.RENDERBUFFER, GL.TEXTURE, GL.NONE\n // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, // GL.TEXTURE_CUBE_MAP_POSITIVE_X, etc.\n // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, // GLint\n // EXT_sRGB or WebGL2\n GL.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, // GL.LINEAR, GL.SRBG\n // WebGL2\n // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, // GLint\n GL.FRAMEBUFFER_ATTACHMENT_RED_SIZE, // GLint\n GL.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, // GLint\n GL.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, // GLint\n GL.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, // GLint\n GL.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, // GLint\n GL.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE // GLint\n // GL.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE\n // GL.FLOAT, GL.INT, GL.UNSIGNED_INT, GL.SIGNED_NORMALIZED, OR GL.UNSIGNED_NORMALIZED.\n];\n\nFramebuffer.ATTACHMENT_PARAMETERS = FRAMEBUFFER_ATTACHMENT_PARAMETERS;\n","function noop() {}\n\nconst DEFAULT_SETTINGS = {\n onStart: noop,\n onUpdate: noop,\n onInterrupt: noop,\n onEnd: noop\n};\n\nexport default class Transition {\n /**\n * @params timeline {Timeline}\n */\n constructor(timeline) {\n this._inProgress = false;\n this._handle = null;\n this.timeline = timeline;\n\n // Defaults\n this.settings = {};\n }\n\n /* Public API */\n get inProgress() {\n return this._inProgress;\n }\n\n /**\n * (re)start this transition.\n * @params props {object} - optional overriding props. see constructor\n */\n start(props) {\n this.cancel();\n this.settings = {...DEFAULT_SETTINGS, ...props};\n this._inProgress = true;\n this.settings.onStart(this);\n }\n\n /**\n * end this transition if it is in progress.\n */\n end() {\n if (this._inProgress) {\n this.timeline.removeChannel(this._handle);\n this._handle = null;\n this._inProgress = false;\n this.settings.onEnd(this);\n }\n }\n\n /**\n * cancel this transition if it is in progress.\n */\n cancel() {\n if (this._inProgress) {\n this.settings.onInterrupt(this);\n this.timeline.removeChannel(this._handle);\n this._handle = null;\n this._inProgress = false;\n }\n }\n\n /**\n * update this transition. Returns `true` if updated.\n */\n update() {\n if (!this._inProgress) {\n return false;\n }\n\n // It is important to initialize the handle during `update` instead of `start`.\n // The CPU time that the `start` frame takes should not be counted towards the duration.\n // On the other hand, `update` always happens during a render cycle. The clock starts when the\n // transition is rendered for the first time.\n if (this._handle === null) {\n const {timeline, settings} = this;\n this._handle = timeline.addChannel({\n delay: timeline.getTime(),\n duration: settings.duration\n });\n }\n\n this.time = this.timeline.getTime(this._handle);\n // Call subclass method\n this._onUpdate();\n // Call user callback\n this.settings.onUpdate(this);\n\n // This only works if `settings.duration` is set\n // Spring transition must call `end` manually\n if (this.timeline.isFinished(this._handle)) {\n this.end();\n }\n return true;\n }\n\n /* Private API */\n\n _onUpdate() {\n // for subclass override\n }\n}\n","// Partial deep equal (only recursive on arrays)\nexport function deepEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n for (const key in a) {\n const aValue = a[key];\n const bValue = b[key];\n const equals =\n aValue === bValue ||\n (Array.isArray(aValue) && Array.isArray(bValue) && deepEqual(aValue, bValue));\n if (!equals) {\n return false;\n }\n }\n return true;\n}\n","/**\n * @typedef Slice\n * @property {number} offset\n * @property {number} length\n */\n\nexport class BaseSource {\n /**\n *\n * @param {Slice[]} slices\n * @returns {ArrayBuffer[]}\n */\n async fetch(slices, signal = undefined) {\n return await Promise.all(\n slices.map((slice) => this.fetchSlice(slice, signal)),\n );\n }\n\n /**\n *\n * @param {Slice} slice\n * @returns {ArrayBuffer}\n */\n async fetchSlice(slice) {\n throw new Error(`fetching of slice ${slice} not possible, not implemented`);\n }\n\n /**\n * Returns the filesize if already determined and null otherwise\n */\n get fileSize() {\n return null;\n }\n\n async close() {\n // no-op by default\n }\n}\n","/**\n * Safe chained function\n *\n * Will only create a new function if needed,\n * otherwise will pass back existing functions or null.\n *\n * @param {function} functions to chain\n * @returns {function|null}\n */\nexport default function createChainedFunction() {\n for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {\n funcs[_key] = arguments[_key];\n }\n\n return funcs.reduce(function (acc, func) {\n if (func == null) {\n return acc;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof func !== 'function') {\n console.error('Material-UI: Invalid Argument Type, must only provide functions, undefined, or null.');\n }\n }\n\n return function chainedFunction() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n acc.apply(this, args);\n func.apply(this, args);\n };\n }, function () {});\n}","export default function formControlState(_ref) {\n var props = _ref.props,\n states = _ref.states,\n muiFormControl = _ref.muiFormControl;\n return states.reduce(function (acc, state) {\n acc[state] = props[state];\n\n if (muiFormControl) {\n if (typeof props[state] === 'undefined') {\n acc[state] = muiFormControl[state];\n }\n }\n\n return acc;\n }, {});\n}","import * as React from 'react';\nimport FormControlContext from './FormControlContext';\nexport default function useFormControl() {\n return React.useContext(FormControlContext);\n}","export var durationSecond = 1e3;\nexport var durationMinute = 6e4;\nexport var durationHour = 36e5;\nexport var durationDay = 864e5;\nexport var durationWeek = 6048e5;\n","// Purpose: include this in your module to avoid\n// dependencies on micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\ntype obj = {[key: string]: any};\nconst self_: obj = globals.self || globals.window || globals.global || {};\nconst window_: obj = globals.window || globals.self || globals.global || {};\nconst global_: obj = globals.global || globals.self || globals.window || {};\nconst document_: obj = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\n/** true if running in a browser */\nexport const isBrowser: boolean =\n // @ts-ignore process does not exist on browser\n typeof process !== 'object' || String(process) !== '[object process]' || process.browser;\n\n/** true if running in a worker thread */\nexport const isWorker: boolean = typeof importScripts === 'function';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\n/** Major Node version (as a number) */\nexport const nodeVersion: number = (matches && parseFloat(matches[1])) || 0;\n","'use strict';\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nconst nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nconst getAllMatches = function(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n};\n\nconst isName = function(string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n};\n\nexports.isExist = function(v) {\n return typeof v !== 'undefined';\n};\n\nexports.isEmptyObject = function(obj) {\n return Object.keys(obj).length === 0;\n};\n\n/**\n * Copy all the properties of a into b.\n * @param {*} target\n * @param {*} a\n */\nexports.merge = function(target, a, arrayMode) {\n if (a) {\n const keys = Object.keys(a); // will return an array of own properties\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n if (arrayMode === 'strict') {\n target[keys[i]] = [ a[keys[i]] ];\n } else {\n target[keys[i]] = a[keys[i]];\n }\n }\n }\n};\n/* exports.merge =function (b,a){\n return Object.assign(b,a);\n} */\n\nexports.getValue = function(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n};\n\n// const fakeCall = function(a) {return a;};\n// const fakeCallNoReturn = function() {};\n\nexports.buildOptions = function(options, defaultOptions, props) {\n let newOptions = {};\n if (!options) {\n return defaultOptions; //if there are not options\n }\n\n for (let i = 0; i < props.length; i++) {\n if (options[props[i]] !== undefined) {\n newOptions[props[i]] = options[props[i]];\n } else {\n newOptions[props[i]] = defaultOptions[props[i]];\n }\n }\n return newOptions;\n};\n\n/**\n * Check if a tag name should be treated as array\n *\n * @param tagName the node tagname\n * @param arrayMode the array mode option\n * @param parentTagName the parent tag name\n * @returns {boolean} true if node should be parsed as array\n */\nexports.isTagNameInArrayMode = function (tagName, arrayMode, parentTagName) {\n if (arrayMode === false) {\n return false;\n } else if (arrayMode instanceof RegExp) {\n return arrayMode.test(tagName);\n } else if (typeof arrayMode === 'function') {\n return !!arrayMode(tagName, parentTagName);\n }\n\n return arrayMode === \"strict\";\n}\n\nexports.isName = isName;\nexports.getAllMatches = getAllMatches;\nexports.nameRegexp = nameRegexp;\n","function isEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (Array.isArray(a)) {\n // Special treatment for arrays: compare 1-level deep\n // This is to support equality of matrix/coordinate props\n const len = a.length;\n if (!b || b.length !== len) {\n return false;\n }\n\n for (let i = 0; i < len; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\n/**\n * Speed up consecutive function calls by caching the result of calls with identical input\n * https://en.wikipedia.org/wiki/Memoization\n * @param {function} compute - the function to be memoized\n */\nexport default function memoize(compute) {\n let cachedArgs = {};\n let cachedResult;\n\n return args => {\n for (const key in args) {\n if (!isEqual(args[key], cachedArgs[key])) {\n cachedResult = compute(args);\n cachedArgs = args;\n break;\n }\n }\n return cachedResult;\n };\n}\n","import { deepmerge } from '@material-ui/utils';\n\nfunction merge(acc, item) {\n if (!item) {\n return acc;\n }\n\n return deepmerge(acc, item, {\n clone: false // No need to clone deep, it's way faster.\n\n });\n}\n\nexport default merge;","/* eslint-disable camelcase */\nimport {assert} from '../utils/assert';\n\nconst GL_BYTE = 0x1400;\nconst GL_UNSIGNED_BYTE = 0x1401;\nconst GL_SHORT = 0x1402;\nconst GL_UNSIGNED_SHORT = 0x1403;\n\nconst GL_POINTS = 0x0;\nconst GL_LINES = 0x1;\nconst GL_LINE_LOOP = 0x2;\nconst GL_LINE_STRIP = 0x3;\nconst GL_TRIANGLES = 0x4;\nconst GL_TRIANGLE_STRIP = 0x5;\nconst GL_TRIANGLE_FAN = 0x6;\n\n// Local constants - these will \"collapse\" during minification\nconst GL_FLOAT = 0x1406;\nconst GL_FLOAT_VEC2 = 0x8b50;\nconst GL_FLOAT_VEC3 = 0x8b51;\nconst GL_FLOAT_VEC4 = 0x8b52;\n\nconst GL_INT = 0x1404;\nconst GL_INT_VEC2 = 0x8b53;\nconst GL_INT_VEC3 = 0x8b54;\nconst GL_INT_VEC4 = 0x8b55;\n\nconst GL_UNSIGNED_INT = 0x1405;\nconst GL_UNSIGNED_INT_VEC2 = 0x8dc6;\nconst GL_UNSIGNED_INT_VEC3 = 0x8dc7;\nconst GL_UNSIGNED_INT_VEC4 = 0x8dc8;\n\nconst GL_BOOL = 0x8b56;\nconst GL_BOOL_VEC2 = 0x8b57;\nconst GL_BOOL_VEC3 = 0x8b58;\nconst GL_BOOL_VEC4 = 0x8b59;\n\nconst GL_FLOAT_MAT2 = 0x8b5a;\nconst GL_FLOAT_MAT3 = 0x8b5b;\nconst GL_FLOAT_MAT4 = 0x8b5c;\n\nconst GL_FLOAT_MAT2x3 = 0x8b65;\nconst GL_FLOAT_MAT2x4 = 0x8b66;\nconst GL_FLOAT_MAT3x2 = 0x8b67;\nconst GL_FLOAT_MAT3x4 = 0x8b68;\nconst GL_FLOAT_MAT4x2 = 0x8b69;\nconst GL_FLOAT_MAT4x3 = 0x8b6a;\n\n// Composite types table\nconst COMPOSITE_GL_TYPES = {\n [GL_FLOAT]: [GL_FLOAT, 1, 'float'],\n [GL_FLOAT_VEC2]: [GL_FLOAT, 2, 'vec2'],\n [GL_FLOAT_VEC3]: [GL_FLOAT, 3, 'vec3'],\n [GL_FLOAT_VEC4]: [GL_FLOAT, 4, 'vec4'],\n\n [GL_INT]: [GL_INT, 1, 'int'],\n [GL_INT_VEC2]: [GL_INT, 2, 'ivec2'],\n [GL_INT_VEC3]: [GL_INT, 3, 'ivec3'],\n [GL_INT_VEC4]: [GL_INT, 4, 'ivec4'],\n\n [GL_UNSIGNED_INT]: [GL_UNSIGNED_INT, 1, 'uint'],\n [GL_UNSIGNED_INT_VEC2]: [GL_UNSIGNED_INT, 2, 'uvec2'],\n [GL_UNSIGNED_INT_VEC3]: [GL_UNSIGNED_INT, 3, 'uvec3'],\n [GL_UNSIGNED_INT_VEC4]: [GL_UNSIGNED_INT, 4, 'uvec4'],\n\n [GL_BOOL]: [GL_FLOAT, 1, 'bool'],\n [GL_BOOL_VEC2]: [GL_FLOAT, 2, 'bvec2'],\n [GL_BOOL_VEC3]: [GL_FLOAT, 3, 'bvec3'],\n [GL_BOOL_VEC4]: [GL_FLOAT, 4, 'bvec4'],\n\n [GL_FLOAT_MAT2]: [GL_FLOAT, 8, 'mat2'], // 4\n [GL_FLOAT_MAT2x3]: [GL_FLOAT, 8, 'mat2x3'], // 6\n [GL_FLOAT_MAT2x4]: [GL_FLOAT, 8, 'mat2x4'], // 8\n\n [GL_FLOAT_MAT3]: [GL_FLOAT, 12, 'mat3'], // 9\n [GL_FLOAT_MAT3x2]: [GL_FLOAT, 12, 'mat3x2'], // 6\n [GL_FLOAT_MAT3x4]: [GL_FLOAT, 12, 'mat3x4'], // 12\n\n [GL_FLOAT_MAT4]: [GL_FLOAT, 16, 'mat4'], // 16\n [GL_FLOAT_MAT4x2]: [GL_FLOAT, 16, 'mat4x2'], // 8\n [GL_FLOAT_MAT4x3]: [GL_FLOAT, 16, 'mat4x3'] // 12\n};\n\n// Counts the number of complete primitives given a number of vertices and a drawMode\nexport function getPrimitiveDrawMode(drawMode) {\n switch (drawMode) {\n case GL_POINTS:\n return GL_POINTS;\n case GL_LINES:\n return GL_LINES;\n case GL_LINE_STRIP:\n return GL_LINES;\n case GL_LINE_LOOP:\n return GL_LINES;\n case GL_TRIANGLES:\n return GL_TRIANGLES;\n case GL_TRIANGLE_STRIP:\n return GL_TRIANGLES;\n case GL_TRIANGLE_FAN:\n return GL_TRIANGLES;\n default:\n assert(false);\n return 0;\n }\n}\n\n// Counts the number of complete \"primitives\" given a number of vertices and a drawMode\nexport function getPrimitiveCount({drawMode, vertexCount}) {\n switch (drawMode) {\n case GL_POINTS:\n case GL_LINE_LOOP:\n return vertexCount;\n case GL_LINES:\n return vertexCount / 2;\n case GL_LINE_STRIP:\n return vertexCount - 1;\n case GL_TRIANGLES:\n return vertexCount / 3;\n case GL_TRIANGLE_STRIP:\n case GL_TRIANGLE_FAN:\n return vertexCount - 2;\n default:\n assert(false);\n return 0;\n }\n}\n\n// Counts the number of vertices after splitting the vertex stream into separate \"primitives\"\nexport function getVertexCount({drawMode, vertexCount}) {\n const primitiveCount = getPrimitiveCount({drawMode, vertexCount});\n switch (getPrimitiveDrawMode(drawMode)) {\n case GL_POINTS:\n return primitiveCount;\n case GL_LINES:\n return primitiveCount * 2;\n case GL_TRIANGLES:\n return primitiveCount * 3;\n default:\n assert(false);\n return 0;\n }\n}\n\n// Decomposes a composite type GL.VEC3 into a basic type (GL.FLOAT) and components (3)\nexport function decomposeCompositeGLType(compositeGLType) {\n const typeAndSize = COMPOSITE_GL_TYPES[compositeGLType];\n if (!typeAndSize) {\n return null;\n }\n const [type, components] = typeAndSize;\n return {type, components};\n}\n\nexport function getCompositeGLType(type, components) {\n switch (type) {\n case GL_BYTE:\n case GL_UNSIGNED_BYTE:\n case GL_SHORT:\n case GL_UNSIGNED_SHORT:\n type = GL_FLOAT;\n break;\n default:\n }\n\n for (const glType in COMPOSITE_GL_TYPES) {\n const [compType, compComponents, name] = COMPOSITE_GL_TYPES[glType];\n if (compType === type && compComponents === components) {\n return {glType, name};\n }\n }\n return null;\n}\n","import type {Loader} from '@loaders.gl/loader-utils';\nimport {assert} from '@loaders.gl/loader-utils';\n\nexport function isLoaderObject(loader?: any): boolean {\n if (!loader) {\n return false;\n }\n\n if (Array.isArray(loader)) {\n loader = loader[0];\n }\n\n const hasExtensions = Array.isArray(loader?.extensions);\n\n /* Now handled by types and worker loaders do not have these\n let hasParser =\n loader.parseTextSync ||\n loader.parseSync ||\n loader.parse ||\n loader.parseStream || // TODO Remove, Replace with parseInBatches\n loader.parseInBatches;\n */\n\n return hasExtensions;\n}\n\nexport function normalizeLoader(loader: Loader): Loader {\n // This error is fairly easy to trigger by mixing up import statements etc\n // So we make an exception and add a developer error message for this case\n // To help new users from getting stuck here\n assert(loader, 'null loader');\n assert(isLoaderObject(loader), 'invalid loader');\n\n // NORMALIZE [LOADER, OPTIONS] => LOADER\n\n // If [loader, options], create a new loaders object with options merged in\n let options;\n if (Array.isArray(loader)) {\n options = loader[1];\n loader = loader[0];\n loader = {\n ...loader,\n options: {...loader.options, ...options}\n };\n }\n\n // NORMALIZE text and binary flags\n // Ensure at least one of text/binary flags are properly set\n\n // @ts-expect-error\n if (loader?.parseTextSync || loader?.parseText) {\n loader.text = true;\n }\n\n if (!loader.text) {\n loader.binary = true;\n }\n\n return loader;\n}\n","import { extend, error, isFunction, stringValue, toBoolean, toNumber, toDate, toString, identity, field, isObject, isArray, isIterable, hasOwnProperty } from 'vega-util';\nimport { dsvFormat } from 'd3-dsv';\nimport { feature, mesh } from 'topojson-client';\nimport { timeFormatDefaultLocale } from 'vega-format';\n\n// https://... file://... //...\n\nconst protocol_re = /^(data:|([A-Za-z]+:)?\\/\\/)/; // Matches allowed URIs. From https://github.com/cure53/DOMPurify/blob/master/src/regexp.js with added file://\n\nconst allowed_re = /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|file|data):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i; // eslint-disable-line no-useless-escape\n\nconst whitespace_re = /[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205f\\u3000]/g; // eslint-disable-line no-control-regex\n// Special treatment in node.js for the file: protocol\n\nconst fileProtocol = 'file://';\n/**\n * Factory for a loader constructor that provides methods for requesting\n * files from either the network or disk, and for sanitizing request URIs.\n * @param {function} fetch - The Fetch API for HTTP network requests.\n * If null or undefined, HTTP loading will be disabled.\n * @param {object} fs - The file system interface for file loading.\n * If null or undefined, local file loading will be disabled.\n * @return {function} A loader constructor with the following signature:\n * param {object} [options] - Optional default loading options to use.\n * return {object} - A new loader instance.\n */\n\nfunction loaderFactory (fetch, fs) {\n return options => ({\n options: options || {},\n sanitize: sanitize,\n load: load,\n fileAccess: !!fs,\n file: fileLoader(fs),\n http: httpLoader(fetch)\n });\n}\n/**\n * Load an external resource, typically either from the web or from the local\n * filesystem. This function uses {@link sanitize} to first sanitize the uri,\n * then calls either {@link http} (for web requests) or {@link file} (for\n * filesystem loading).\n * @param {string} uri - The resource indicator (e.g., URL or filename).\n * @param {object} [options] - Optional loading options. These options will\n * override any existing default options.\n * @return {Promise} - A promise that resolves to the loaded content.\n */\n\nasync function load(uri, options) {\n const opt = await this.sanitize(uri, options),\n url = opt.href;\n return opt.localFile ? this.file(url) : this.http(url, options);\n}\n/**\n * URI sanitizer function.\n * @param {string} uri - The uri (url or filename) to check.\n * @param {object} options - An options hash.\n * @return {Promise} - A promise that resolves to an object containing\n * sanitized uri data, or rejects it the input uri is deemed invalid.\n * The properties of the resolved object are assumed to be\n * valid attributes for an HTML 'a' tag. The sanitized uri *must* be\n * provided by the 'href' property of the returned object.\n */\n\n\nasync function sanitize(uri, options) {\n options = extend({}, this.options, options);\n const fileAccess = this.fileAccess,\n result = {\n href: null\n };\n let isFile, loadFile, base;\n const isAllowed = allowed_re.test(uri.replace(whitespace_re, ''));\n\n if (uri == null || typeof uri !== 'string' || !isAllowed) {\n error('Sanitize failure, invalid URI: ' + stringValue(uri));\n }\n\n const hasProtocol = protocol_re.test(uri); // if relative url (no protocol/host), prepend baseURL\n\n if ((base = options.baseURL) && !hasProtocol) {\n // Ensure that there is a slash between the baseURL (e.g. hostname) and url\n if (!uri.startsWith('/') && !base.endsWith('/')) {\n uri = '/' + uri;\n }\n\n uri = base + uri;\n } // should we load from file system?\n\n\n loadFile = (isFile = uri.startsWith(fileProtocol)) || options.mode === 'file' || options.mode !== 'http' && !hasProtocol && fileAccess;\n\n if (isFile) {\n // strip file protocol\n uri = uri.slice(fileProtocol.length);\n } else if (uri.startsWith('//')) {\n if (options.defaultProtocol === 'file') {\n // if is file, strip protocol and set loadFile flag\n uri = uri.slice(2);\n loadFile = true;\n } else {\n // if relative protocol (starts with '//'), prepend default protocol\n uri = (options.defaultProtocol || 'http') + ':' + uri;\n }\n } // set non-enumerable mode flag to indicate local file load\n\n\n Object.defineProperty(result, 'localFile', {\n value: !!loadFile\n }); // set uri\n\n result.href = uri; // set default result target, if specified\n\n if (options.target) {\n result.target = options.target + '';\n } // set default result rel, if specified (#1542)\n\n\n if (options.rel) {\n result.rel = options.rel + '';\n } // provide control over cross-origin image handling (#2238)\n // https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image\n\n\n if (options.context === 'image' && options.crossOrigin) {\n result.crossOrigin = options.crossOrigin + '';\n } // return\n\n\n return result;\n}\n/**\n * File system loader factory.\n * @param {object} fs - The file system interface.\n * @return {function} - A file loader with the following signature:\n * param {string} filename - The file system path to load.\n * param {string} filename - The file system path to load.\n * return {Promise} A promise that resolves to the file contents.\n */\n\n\nfunction fileLoader(fs) {\n return fs ? filename => new Promise((accept, reject) => {\n fs.readFile(filename, (error, data) => {\n if (error) reject(error);else accept(data);\n });\n }) : fileReject;\n}\n/**\n * Default file system loader that simply rejects.\n */\n\n\nasync function fileReject() {\n error('No file system access.');\n}\n/**\n * HTTP request handler factory.\n * @param {function} fetch - The Fetch API method.\n * @return {function} - An http loader with the following signature:\n * param {string} url - The url to request.\n * param {object} options - An options hash.\n * return {Promise} - A promise that resolves to the file contents.\n */\n\n\nfunction httpLoader(fetch) {\n return fetch ? async function (url, options) {\n const opt = extend({}, this.options.http, options),\n type = options && options.response,\n response = await fetch(url, opt);\n return !response.ok ? error(response.status + '' + response.statusText) : isFunction(response[type]) ? response[type]() : response.text();\n } : httpReject;\n}\n/**\n * Default http request handler that simply rejects.\n */\n\n\nasync function httpReject() {\n error('No HTTP fetch method available.');\n}\n\nconst isValid = _ => _ != null && _ === _;\n\nconst isBoolean = _ => _ === 'true' || _ === 'false' || _ === true || _ === false;\n\nconst isDate = _ => !Number.isNaN(Date.parse(_));\n\nconst isNumber = _ => !Number.isNaN(+_) && !(_ instanceof Date);\n\nconst isInteger = _ => isNumber(_) && Number.isInteger(+_);\n\nconst typeParsers = {\n boolean: toBoolean,\n integer: toNumber,\n number: toNumber,\n date: toDate,\n string: toString,\n unknown: identity\n};\nconst typeTests = [isBoolean, isInteger, isNumber, isDate];\nconst typeList = ['boolean', 'integer', 'number', 'date'];\nfunction inferType(values, field) {\n if (!values || !values.length) return 'unknown';\n const n = values.length,\n m = typeTests.length,\n a = typeTests.map((_, i) => i + 1);\n\n for (let i = 0, t = 0, j, value; i < n; ++i) {\n value = field ? values[i][field] : values[i];\n\n for (j = 0; j < m; ++j) {\n if (a[j] && isValid(value) && !typeTests[j](value)) {\n a[j] = 0;\n ++t;\n if (t === typeTests.length) return 'string';\n }\n }\n }\n\n return typeList[a.reduce((u, v) => u === 0 ? v : u, 0) - 1];\n}\nfunction inferTypes(data, fields) {\n return fields.reduce((types, field) => {\n types[field] = inferType(data, field);\n return types;\n }, {});\n}\n\nfunction delimitedFormat(delimiter) {\n const parse = function (data, format) {\n const delim = {\n delimiter: delimiter\n };\n return dsv(data, format ? extend(format, delim) : delim);\n };\n\n parse.responseType = 'text';\n return parse;\n}\nfunction dsv(data, format) {\n if (format.header) {\n data = format.header.map(stringValue).join(format.delimiter) + '\\n' + data;\n }\n\n return dsvFormat(format.delimiter).parse(data + '');\n}\ndsv.responseType = 'text';\n\nfunction isBuffer(_) {\n return typeof Buffer === 'function' && isFunction(Buffer.isBuffer) ? Buffer.isBuffer(_) : false;\n}\n\nfunction json(data, format) {\n const prop = format && format.property ? field(format.property) : identity;\n return isObject(data) && !isBuffer(data) ? parseJSON(prop(data), format) : prop(JSON.parse(data));\n}\njson.responseType = 'json';\n\nfunction parseJSON(data, format) {\n if (!isArray(data) && isIterable(data)) {\n data = [...data];\n }\n\n return format && format.copy ? JSON.parse(JSON.stringify(data)) : data;\n}\n\nconst filters = {\n interior: (a, b) => a !== b,\n exterior: (a, b) => a === b\n};\nfunction topojson(data, format) {\n let method, object, property, filter;\n data = json(data, format);\n\n if (format && format.feature) {\n method = feature;\n property = format.feature;\n } else if (format && format.mesh) {\n method = mesh;\n property = format.mesh;\n filter = filters[format.filter];\n } else {\n error('Missing TopoJSON feature or mesh parameter.');\n }\n\n object = (object = data.objects[property]) ? method(data, object, filter) : error('Invalid TopoJSON object: ' + property);\n return object && object.features || [object];\n}\ntopojson.responseType = 'json';\n\nconst format = {\n dsv: dsv,\n csv: delimitedFormat(','),\n tsv: delimitedFormat('\\t'),\n json: json,\n topojson: topojson\n};\nfunction formats(name, reader) {\n if (arguments.length > 1) {\n format[name] = reader;\n return this;\n } else {\n return hasOwnProperty(format, name) ? format[name] : null;\n }\n}\nfunction responseType(type) {\n const f = formats(type);\n return f && f.responseType || 'text';\n}\n\nfunction read (data, schema, timeParser, utcParser) {\n schema = schema || {};\n const reader = formats(schema.type || 'json');\n if (!reader) error('Unknown data format type: ' + schema.type);\n data = reader(data, schema);\n if (schema.parse) parse(data, schema.parse, timeParser, utcParser);\n if (hasOwnProperty(data, 'columns')) delete data.columns;\n return data;\n}\n\nfunction parse(data, types, timeParser, utcParser) {\n if (!data.length) return; // early exit for empty data\n\n const locale = timeFormatDefaultLocale();\n timeParser = timeParser || locale.timeParse;\n utcParser = utcParser || locale.utcParse;\n let fields = data.columns || Object.keys(data[0]),\n datum,\n field,\n i,\n j,\n n,\n m;\n if (types === 'auto') types = inferTypes(data, fields);\n fields = Object.keys(types);\n const parsers = fields.map(field => {\n const type = types[field];\n let parts, pattern;\n\n if (type && (type.startsWith('date:') || type.startsWith('utc:'))) {\n parts = type.split(/:(.+)?/, 2); // split on first :\n\n pattern = parts[1];\n\n if (pattern[0] === '\\'' && pattern[pattern.length - 1] === '\\'' || pattern[0] === '\"' && pattern[pattern.length - 1] === '\"') {\n pattern = pattern.slice(1, -1);\n }\n\n const parse = parts[0] === 'utc' ? utcParser : timeParser;\n return parse(pattern);\n }\n\n if (!typeParsers[type]) {\n throw Error('Illegal format pattern: ' + field + ':' + type);\n }\n\n return typeParsers[type];\n });\n\n for (i = 0, n = data.length, m = fields.length; i < n; ++i) {\n datum = data[i];\n\n for (j = 0; j < m; ++j) {\n field = fields[j];\n datum[field] = parsers[j](datum[field]);\n }\n }\n}\n\nconst loader = loaderFactory(typeof fetch !== 'undefined' && fetch, // use built-in fetch API\nnull // no file system access\n);\n\nexport { format, formats, inferType, inferTypes, loader, read, responseType, typeParsers };\n","import {resolvePath} from '@loaders.gl/loader-utils';\nimport {makeResponse} from '../utils/response-utils';\n// import {getErrorMessageFromResponse} from './fetch-error-message';\n\n/**\n * fetch compatible function\n * Reads file data from:\n * - http/http urls\n * - data urls\n * - File/Blob objects\n * Leverages `@loaders.gl/polyfills` for Node.js support\n * Respects pathPrefix and file aliases\n */\nexport async function fetchFile(\n url: string | Blob,\n options?: RequestInit & {fetch?: RequestInit | Function}\n): Promise {\n if (typeof url === 'string') {\n url = resolvePath(url);\n\n let fetchOptions: RequestInit = options as RequestInit;\n if (options?.fetch && typeof options?.fetch !== 'function') {\n fetchOptions = options.fetch;\n }\n\n return await fetch(url, fetchOptions);\n }\n\n return await makeResponse(url);\n}\n","// probe.gl Log compatible loggers\nimport {Log} from 'probe.gl';\n\nexport const probeLog = new Log({id: 'loaders.gl'});\n\n// Logs nothing\nexport class NullLog {\n log() {\n return () => {};\n }\n info() {\n return () => {};\n }\n warn() {\n return () => {};\n }\n error() {\n return () => {};\n }\n}\n\n// Logs to console\nexport class ConsoleLog {\n console;\n\n constructor() {\n this.console = console; // eslint-disable-line\n }\n log(...args) {\n return this.console.log.bind(this.console, ...args);\n }\n info(...args) {\n return this.console.info.bind(this.console, ...args);\n }\n warn(...args) {\n return this.console.warn.bind(this.console, ...args);\n }\n error(...args) {\n return this.console.error.bind(this.console, ...args);\n }\n}\n","import type {LoaderOptions} from '@loaders.gl/loader-utils';\nimport {ConsoleLog} from './loggers';\n\nexport const DEFAULT_LOADER_OPTIONS: LoaderOptions = {\n // baseUri\n fetch: null,\n mimeType: undefined,\n nothrow: false,\n log: new ConsoleLog(), // A probe.gl compatible (`log.log()()` syntax) that just logs to console\n\n CDN: 'https://unpkg.com/@loaders.gl',\n worker: true, // By default, use worker if provided by loader.\n maxConcurrency: 3, // How many worker instances should be created for each loader.\n maxMobileConcurrency: 1, // How many worker instances should be created for each loader on mobile devices.\n reuseWorkers: true, // By default reuse workers,\n _workerType: '', // 'test' to use locally generated workers\n\n limit: 0,\n _limitMB: 0,\n batchSize: 'auto',\n batchDebounceMs: 0,\n metadata: false, // TODO - currently only implemented for parseInBatches, adds initial metadata batch,\n transforms: []\n};\n\nexport const REMOVED_LOADER_OPTIONS = {\n throws: 'nothrow',\n dataType: '(no longer used)',\n uri: 'baseUri',\n // Warn if fetch options are used on top-level\n method: 'fetch.method',\n headers: 'fetch.headers',\n body: 'fetch.body',\n mode: 'fetch.mode',\n credentials: 'fetch.credentials',\n cache: 'fetch.cache',\n redirect: 'fetch.redirect',\n referrer: 'fetch.referrer',\n referrerPolicy: 'fetch.referrerPolicy',\n integrity: 'fetch.integrity',\n keepalive: 'fetch.keepalive',\n signal: 'fetch.signal'\n};\n","import type {Loader, LoaderContext, LoaderOptions} from '@loaders.gl/loader-utils';\nimport {global} from '@loaders.gl/loader-utils';\nimport {isPureObject, isObject} from '../../javascript-utils/is-type';\nimport {fetchFile} from '../fetch/fetch-file';\nimport {probeLog, NullLog} from './loggers';\nimport {DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS} from './option-defaults';\n/**\n * Global state for loaders.gl. Stored on `global.loaders._state`\n */\ntype GlobalLoaderState = {\n loaderRegistry: Loader[];\n globalOptions: {[key: string]: any};\n};\n\n/**\n * Helper for safely accessing global loaders.gl variables\n * Wraps initialization of global variable in function to defeat overly aggressive tree-shakers\n */\nexport function getGlobalLoaderState(): GlobalLoaderState {\n // @ts-ignore\n global.loaders = global.loaders || {};\n // @ts-ignore\n const {loaders} = global;\n\n // Add _state object to keep separate from modules added to global.loaders\n loaders._state = loaders._state || {};\n return loaders._state;\n}\n\n// Store global loader options on the global object to increase chances of cross loaders-version interoperability\n// NOTE: This use case is not reliable but can help when testing new versions of loaders.gl with existing frameworks\nconst getGlobalLoaderOptions = () => {\n const state = getGlobalLoaderState();\n // Ensure all default loader options from this library are mentioned\n state.globalOptions = state.globalOptions || {...DEFAULT_LOADER_OPTIONS};\n return state.globalOptions;\n};\n\n/**\n * Set global loader options\n * @param options\n */\nexport function setGlobalOptions(options: object): void {\n const state = getGlobalLoaderState();\n const globalOptions = getGlobalLoaderOptions();\n state.globalOptions = normalizeOptionsInternal(globalOptions, options);\n}\n\n/**\n * Merges options with global opts and loader defaults, also injects baseUri\n * @param options\n * @param loader\n * @param loaders\n * @param url\n */\nexport function normalizeOptions(\n options: object,\n loader: Loader,\n loaders?: Loader[],\n url?: string\n): object {\n loaders = loaders || [];\n loaders = Array.isArray(loaders) ? loaders : [loaders];\n\n validateOptions(options, loaders);\n return normalizeOptionsInternal(loader, options, url);\n}\n\n/**\n * Gets the current fetch function from options and context\n * @param options\n * @param context\n */\nexport function getFetchFunction(\n options?: LoaderOptions,\n context?: Omit & Partial>\n) {\n const globalOptions = getGlobalLoaderOptions();\n\n const fetchOptions = options || globalOptions;\n\n // options.fetch can be a function\n if (typeof fetchOptions.fetch === 'function') {\n return fetchOptions.fetch;\n }\n\n // options.fetch can be an options object\n if (isObject(fetchOptions.fetch)) {\n return (url) => fetchFile(url, fetchOptions);\n }\n\n // else refer to context (from parent loader) if available\n if (context?.fetch) {\n return context?.fetch;\n }\n\n // else return the default fetch function\n return fetchFile;\n}\n\n// VALIDATE OPTIONS\n\n/**\n * Warn for unsupported options\n * @param options\n * @param loaders\n */\nfunction validateOptions(options: LoaderOptions, loaders: Loader[]) {\n // Check top level options\n validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);\n for (const loader of loaders) {\n // Get the scoped, loader specific options from the user supplied options\n const idOptions = (options && options[loader.id]) || {};\n\n // Get scoped, loader specific default and deprecated options from the selected loader\n const loaderOptions = (loader.options && loader.options[loader.id]) || {};\n const deprecatedOptions =\n (loader.deprecatedOptions && loader.deprecatedOptions[loader.id]) || {};\n\n // Validate loader specific options\n validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);\n }\n}\n\n// eslint-disable-next-line max-params, complexity\nfunction validateOptionsObject(\n options,\n id: string | null,\n defaultOptions,\n deprecatedOptions,\n loaders: Loader[]\n) {\n const loaderName = id || 'Top level';\n const prefix = id ? `${id}.` : '';\n\n for (const key in options) {\n // If top level option value is an object it could options for a loader, so ignore\n const isSubOptions = !id && isObject(options[key]);\n const isBaseUriOption = key === 'baseUri' && !id;\n const isWorkerUrlOption = key === 'workerUrl' && id;\n // .workerUrl requires special handling as it is now auto-generated and no longer specified as a default option.\n if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {\n // Issue deprecation warnings\n if (key in deprecatedOptions) {\n probeLog.warn(\n `${loaderName} loader option \\'${prefix}${key}\\' no longer supported, use \\'${deprecatedOptions[key]}\\'`\n )();\n } else if (!isSubOptions) {\n const suggestion = findSimilarOption(key, loaders);\n probeLog.warn(\n `${loaderName} loader option \\'${prefix}${key}\\' not recognized. ${suggestion}`\n )();\n }\n }\n }\n}\n\nfunction findSimilarOption(optionKey, loaders) {\n const lowerCaseOptionKey = optionKey.toLowerCase();\n let bestSuggestion = '';\n for (const loader of loaders) {\n for (const key in loader.options) {\n if (optionKey === key) {\n return `Did you mean \\'${loader.id}.${key}\\'?`;\n }\n const lowerCaseKey = key.toLowerCase();\n const isPartialMatch =\n lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);\n if (isPartialMatch) {\n bestSuggestion = bestSuggestion || `Did you mean \\'${loader.id}.${key}\\'?`;\n }\n }\n }\n return bestSuggestion;\n}\n\nfunction normalizeOptionsInternal(loader, options, url?: string) {\n const loaderDefaultOptions = loader.options || {};\n\n const mergedOptions = {...loaderDefaultOptions};\n\n addUrlOptions(mergedOptions, url);\n\n // LOGGING: options.log can be set to `null` to defeat logging\n if (mergedOptions.log === null) {\n mergedOptions.log = new NullLog();\n }\n\n mergeNestedFields(mergedOptions, getGlobalLoaderOptions());\n mergeNestedFields(mergedOptions, options);\n\n return mergedOptions;\n}\n\n// Merge nested options objects\nfunction mergeNestedFields(mergedOptions, options) {\n for (const key in options) {\n // Check for nested options\n // object in options => either no key in defaultOptions or object in defaultOptions\n if (key in options) {\n const value = options[key];\n if (isPureObject(value) && isPureObject(mergedOptions[key])) {\n mergedOptions[key] = {\n ...mergedOptions[key],\n ...options[key]\n };\n } else {\n mergedOptions[key] = options[key];\n }\n }\n // else: No need to merge nested opts, and the initial merge already copied over the nested options\n }\n}\n\n// Harvest information from the url\n// TODO - baseUri should be a directory, i.e. remove file component from baseUri\n// TODO - extract extension?\n// TODO - extract query parameters?\n// TODO - should these be injected on context instead of options?\nfunction addUrlOptions(options, url?: string) {\n if (url && !('baseUri' in options)) {\n options.baseUri = url;\n }\n}\n","/**\n * @module helpers\n */\n/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n *\n * @memberof helpers\n * @type {number}\n */\nexport var earthRadius = 6371008.8;\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var factors = {\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n degrees: earthRadius / 111325,\n feet: earthRadius * 3.28084,\n inches: earthRadius * 39.37,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n meters: earthRadius,\n metres: earthRadius,\n miles: earthRadius / 1609.344,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n nauticalmiles: earthRadius / 1852,\n radians: 1,\n yards: earthRadius * 1.0936,\n};\n/**\n * Units of measurement factors based on 1 meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var unitsFactors = {\n centimeters: 100,\n centimetres: 100,\n degrees: 1 / 111325,\n feet: 3.28084,\n inches: 39.37,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n meters: 1,\n metres: 1,\n miles: 1 / 1609.344,\n millimeters: 1000,\n millimetres: 1000,\n nauticalmiles: 1 / 1852,\n radians: 1 / earthRadius,\n yards: 1.0936133,\n};\n/**\n * Area of measurement factors based on 1 square meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var areaFactors = {\n acres: 0.000247105,\n centimeters: 10000,\n centimetres: 10000,\n feet: 10.763910417,\n hectares: 0.0001,\n inches: 1550.003100006,\n kilometers: 0.000001,\n kilometres: 0.000001,\n meters: 1,\n metres: 1,\n miles: 3.86e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nexport function feature(geom, properties, options) {\n if (options === void 0) { options = {}; }\n var feat = { type: \"Feature\" };\n if (options.id === 0 || options.id) {\n feat.id = options.id;\n }\n if (options.bbox) {\n feat.bbox = options.bbox;\n }\n feat.properties = properties || {};\n feat.geometry = geom;\n return feat;\n}\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = \"Point\";\n * var coordinates = [110, 50];\n * var geometry = turf.geometry(type, coordinates);\n * // => geometry\n */\nexport function geometry(type, coordinates, _options) {\n if (_options === void 0) { _options = {}; }\n switch (type) {\n case \"Point\":\n return point(coordinates).geometry;\n case \"LineString\":\n return lineString(coordinates).geometry;\n case \"Polygon\":\n return polygon(coordinates).geometry;\n case \"MultiPoint\":\n return multiPoint(coordinates).geometry;\n case \"MultiLineString\":\n return multiLineString(coordinates).geometry;\n case \"MultiPolygon\":\n return multiPolygon(coordinates).geometry;\n default:\n throw new Error(type + \" is invalid\");\n }\n}\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nexport function point(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (!coordinates) {\n throw new Error(\"coordinates is required\");\n }\n if (!Array.isArray(coordinates)) {\n throw new Error(\"coordinates must be an Array\");\n }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be at least 2 numbers long\");\n }\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {\n throw new Error(\"coordinates must contain numbers\");\n }\n var geom = {\n type: \"Point\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nexport function points(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nexport function polygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {\n var ring = coordinates_1[_i];\n if (ring.length < 4) {\n throw new Error(\"Each LinearRing of a Polygon must have 4 or more Positions.\");\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n }\n }\n var geom = {\n type: \"Polygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nexport function polygons(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nexport function lineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n var geom = {\n type: \"LineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nexport function lineStrings(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nexport function featureCollection(features, options) {\n if (options === void 0) { options = {}; }\n var fc = { type: \"FeatureCollection\" };\n if (options.id) {\n fc.id = options.id;\n }\n if (options.bbox) {\n fc.bbox = options.bbox;\n }\n fc.features = features;\n return fc;\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nexport function multiLineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiLineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nexport function multiPoint(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPoint\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nexport function multiPolygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPolygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = turf.geometry(\"Point\", [100, 0]);\n * var line = turf.geometry(\"LineString\", [[101, 0], [102, 1]]);\n * var collection = turf.geometryCollection([pt, line]);\n *\n * // => collection\n */\nexport function geometryCollection(geometries, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"GeometryCollection\",\n geometries: geometries,\n };\n return feature(geom, properties, options);\n}\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nexport function round(num, precision) {\n if (precision === void 0) { precision = 0; }\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nexport function radiansToLength(radians, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return radians * factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nexport function lengthToRadians(distance, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return distance / factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nexport function lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nexport function bearingToAzimuth(bearing) {\n var angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nexport function radiansToDegrees(radians) {\n var degrees = radians % (2 * Math.PI);\n return (degrees * 180) / Math.PI;\n}\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nexport function degreesToRadians(degrees) {\n var radians = degrees % 360;\n return (radians * Math.PI) / 180;\n}\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] of the length\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted length\n */\nexport function convertLength(length, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"kilometers\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(length >= 0)) {\n throw new Error(\"length must be a positive number\");\n }\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);\n}\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches, hectares\n * @param {number} area to be converted\n * @param {Units} [originalUnit=\"meters\"] of the distance\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted area\n */\nexport function convertArea(area, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"meters\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n var startFactor = areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n var finalFactor = areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n return (area / startFactor) * finalFactor;\n}\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nexport function isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nexport function isObject(input) {\n return !!input && input.constructor === Object;\n}\n/**\n * Validate BBox\n *\n * @private\n * @param {Array} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nexport function validateBBox(bbox) {\n if (!bbox) {\n throw new Error(\"bbox is required\");\n }\n if (!Array.isArray(bbox)) {\n throw new Error(\"bbox must be an Array\");\n }\n if (bbox.length !== 4 && bbox.length !== 6) {\n throw new Error(\"bbox must be an Array of 4 or 6 numbers\");\n }\n bbox.forEach(function (num) {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nexport function validateId(id) {\n if (!id) {\n throw new Error(\"id is required\");\n }\n if ([\"string\", \"number\"].indexOf(typeof id) === -1) {\n throw new Error(\"id must be a number or a string\");\n }\n}\n","// https://en.wikipedia.org/wiki/Rhumb_line\nimport { convertLength, degreesToRadians, earthRadius, point, } from \"@turf/helpers\";\nimport { getCoord } from \"@turf/invariant\";\n/**\n * Returns the destination {@link Point} having travelled the given distance along a Rhumb line from the\n * origin Point with the (varant) given bearing.\n *\n * @name rhumbDestination\n * @param {Coord} origin starting point\n * @param {number} distance distance from the starting point\n * @param {number} bearing varant bearing angle ranging from -180 to 180 degrees from north\n * @param {Object} [options={}] Optional parameters\n * @param {string} [options.units='kilometers'] can be degrees, radians, miles, or kilometers\n * @param {Object} [options.properties={}] translate properties to destination point\n * @returns {Feature} Destination point.\n * @example\n * var pt = turf.point([-75.343, 39.984], {\"marker-color\": \"F00\"});\n * var distance = 50;\n * var bearing = 90;\n * var options = {units: 'miles'};\n *\n * var destination = turf.rhumbDestination(pt, distance, bearing, options);\n *\n * //addToMap\n * var addToMap = [pt, destination]\n * destination.properties['marker-color'] = '#00F';\n */\nfunction rhumbDestination(origin, distance, bearing, options) {\n if (options === void 0) { options = {}; }\n var wasNegativeDistance = distance < 0;\n var distanceInMeters = convertLength(Math.abs(distance), options.units, \"meters\");\n if (wasNegativeDistance)\n distanceInMeters = -Math.abs(distanceInMeters);\n var coords = getCoord(origin);\n var destination = calculateRhumbDestination(coords, distanceInMeters, bearing);\n // compensate the crossing of the 180th meridian (https://macwright.org/2016/09/26/the-180th-meridian.html)\n // solution from https://github.com/mapbox/mapbox-gl-js/issues/3250#issuecomment-294887678\n destination[0] +=\n destination[0] - coords[0] > 180\n ? -360\n : coords[0] - destination[0] > 180\n ? 360\n : 0;\n return point(destination, options.properties);\n}\n/**\n * Returns the destination point having travelled along a rhumb line from origin point the given\n * distance on the given bearing.\n * Adapted from Geodesy: http://www.movable-type.co.uk/scripts/latlong.html#rhumblines\n *\n * @private\n * @param {Array} origin - point\n * @param {number} distance - Distance travelled, in same units as earth radius (default: metres).\n * @param {number} bearing - Bearing in degrees from north.\n * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres).\n * @returns {Array} Destination point.\n */\nfunction calculateRhumbDestination(origin, distance, bearing, radius) {\n // φ => phi\n // λ => lambda\n // ψ => psi\n // Δ => Delta\n // δ => delta\n // θ => theta\n radius = radius === undefined ? earthRadius : Number(radius);\n var delta = distance / radius; // angular distance in radians\n var lambda1 = (origin[0] * Math.PI) / 180; // to radians, but without normalize to 𝜋\n var phi1 = degreesToRadians(origin[1]);\n var theta = degreesToRadians(bearing);\n var DeltaPhi = delta * Math.cos(theta);\n var phi2 = phi1 + DeltaPhi;\n // check for some daft bugger going past the pole, normalise latitude if so\n if (Math.abs(phi2) > Math.PI / 2) {\n phi2 = phi2 > 0 ? Math.PI - phi2 : -Math.PI - phi2;\n }\n var DeltaPsi = Math.log(Math.tan(phi2 / 2 + Math.PI / 4) / Math.tan(phi1 / 2 + Math.PI / 4));\n // E-W course becomes ill-conditioned with 0/0\n var q = Math.abs(DeltaPsi) > 10e-12 ? DeltaPhi / DeltaPsi : Math.cos(phi1);\n var DeltaLambda = (delta * Math.sin(theta)) / q;\n var lambda2 = lambda1 + DeltaLambda;\n return [\n (((lambda2 * 180) / Math.PI + 540) % 360) - 180,\n (phi2 * 180) / Math.PI,\n ]; // normalise to −180..+180°\n}\nexport default rhumbDestination;\n","import { isNumber, } from \"@turf/helpers\";\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array|Geometry|Feature} coord GeoJSON Point or an Array of numbers\n * @returns {Array} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nexport function getCoord(coord) {\n if (!coord) {\n throw new Error(\"coord is required\");\n }\n if (!Array.isArray(coord)) {\n if (coord.type === \"Feature\" &&\n coord.geometry !== null &&\n coord.geometry.type === \"Point\") {\n return coord.geometry.coordinates;\n }\n if (coord.type === \"Point\") {\n return coord.coordinates;\n }\n }\n if (Array.isArray(coord) &&\n coord.length >= 2 &&\n !Array.isArray(coord[0]) &&\n !Array.isArray(coord[1])) {\n return coord;\n }\n throw new Error(\"coord must be GeoJSON Point or an Array of numbers\");\n}\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nexport function getCoords(coords) {\n if (Array.isArray(coords)) {\n return coords;\n }\n // Feature\n if (coords.type === \"Feature\") {\n if (coords.geometry !== null) {\n return coords.geometry.coordinates;\n }\n }\n else {\n // Geometry\n if (coords.coordinates) {\n return coords.coordinates;\n }\n }\n throw new Error(\"coords must be GeoJSON Feature, Geometry Object or an Array\");\n}\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nexport function containsNumber(coordinates) {\n if (coordinates.length > 1 &&\n isNumber(coordinates[0]) &&\n isNumber(coordinates[1])) {\n return true;\n }\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error(\"coordinates must only contain numbers\");\n}\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nexport function geojsonType(value, type, name) {\n if (!type || !name) {\n throw new Error(\"type and name required\");\n }\n if (!value || value.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n value.type);\n }\n}\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nexport function featureOf(feature, type, name) {\n if (!feature) {\n throw new Error(\"No feature passed\");\n }\n if (!name) {\n throw new Error(\".featureOf() requires a name\");\n }\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type);\n }\n}\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nexport function collectionOf(featureCollection, type, name) {\n if (!featureCollection) {\n throw new Error(\"No featureCollection passed\");\n }\n if (!name) {\n throw new Error(\".collectionOf() requires a name\");\n }\n if (!featureCollection || featureCollection.type !== \"FeatureCollection\") {\n throw new Error(\"Invalid input to \" + name + \", FeatureCollection required\");\n }\n for (var _i = 0, _a = featureCollection.features; _i < _a.length; _i++) {\n var feature = _a[_i];\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type);\n }\n }\n}\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nexport function getGeom(geojson) {\n if (geojson.type === \"Feature\") {\n return geojson.geometry;\n }\n return geojson;\n}\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message (unused)\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nexport function getType(geojson, _name) {\n if (geojson.type === \"FeatureCollection\") {\n return \"FeatureCollection\";\n }\n if (geojson.type === \"GeometryCollection\") {\n return \"GeometryCollection\";\n }\n if (geojson.type === \"Feature\" && geojson.geometry !== null) {\n return geojson.geometry.type;\n }\n return geojson.type;\n}\n","import * as glMatrix from \"./common.js\";\n/**\r\n * 2 Dimensional Vector\r\n * @module vec2\r\n */\n\n/**\r\n * Creates a new, empty vec2\r\n *\r\n * @returns {vec2} a new 2D vector\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(2);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n }\n\n return out;\n}\n/**\r\n * Creates a new vec2 initialized with values from an existing vector\r\n *\r\n * @param {ReadonlyVec2} a vector to clone\r\n * @returns {vec2} a new 2D vector\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\r\n * Creates a new vec2 initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @returns {vec2} a new 2D vector\r\n */\n\nexport function fromValues(x, y) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\r\n * Copy the values from one vec2 to another\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the source vector\r\n * @returns {vec2} out\r\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\r\n * Set the components of a vec2 to the given values\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @returns {vec2} out\r\n */\n\nexport function set(out, x, y) {\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\r\n * Adds two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n return out;\n}\n/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n return out;\n}\n/**\r\n * Multiplies two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n return out;\n}\n/**\r\n * Divides two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n return out;\n}\n/**\r\n * Math.ceil the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a vector to ceil\r\n * @returns {vec2} out\r\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n return out;\n}\n/**\r\n * Math.floor the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a vector to floor\r\n * @returns {vec2} out\r\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n return out;\n}\n/**\r\n * Returns the minimum of two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n return out;\n}\n/**\r\n * Returns the maximum of two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {vec2} out\r\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n return out;\n}\n/**\r\n * Math.round the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a vector to round\r\n * @returns {vec2} out\r\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n return out;\n}\n/**\r\n * Scales a vec2 by a scalar number\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec2} out\r\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n return out;\n}\n/**\r\n * Adds two vec2's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec2} out\r\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n return out;\n}\n/**\r\n * Calculates the euclidian distance between two vec2's\r\n *\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {Number} distance between a and b\r\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0],\n y = b[1] - a[1];\n return Math.hypot(x, y);\n}\n/**\r\n * Calculates the squared euclidian distance between two vec2's\r\n *\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {Number} squared distance between a and b\r\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0],\n y = b[1] - a[1];\n return x * x + y * y;\n}\n/**\r\n * Calculates the length of a vec2\r\n *\r\n * @param {ReadonlyVec2} a vector to calculate length of\r\n * @returns {Number} length of a\r\n */\n\nexport function length(a) {\n var x = a[0],\n y = a[1];\n return Math.hypot(x, y);\n}\n/**\r\n * Calculates the squared length of a vec2\r\n *\r\n * @param {ReadonlyVec2} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\n */\n\nexport function squaredLength(a) {\n var x = a[0],\n y = a[1];\n return x * x + y * y;\n}\n/**\r\n * Negates the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a vector to negate\r\n * @returns {vec2} out\r\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n return out;\n}\n/**\r\n * Returns the inverse of the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a vector to invert\r\n * @returns {vec2} out\r\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n return out;\n}\n/**\r\n * Normalize a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a vector to normalize\r\n * @returns {vec2} out\r\n */\n\nexport function normalize(out, a) {\n var x = a[0],\n y = a[1];\n var len = x * x + y * y;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n return out;\n}\n/**\r\n * Calculates the dot product of two vec2's\r\n *\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {Number} dot product of a and b\r\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1];\n}\n/**\r\n * Computes the cross product of two vec2's\r\n * Note that the cross product must by definition produce a 3D vector\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function cross(out, a, b) {\n var z = a[0] * b[1] - a[1] * b[0];\n out[0] = out[1] = 0;\n out[2] = z;\n return out;\n}\n/**\r\n * Performs a linear interpolation between two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the first operand\r\n * @param {ReadonlyVec2} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec2} out\r\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0],\n ay = a[1];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n return out;\n}\n/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\r\n * @returns {vec2} out\r\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n out[0] = Math.cos(r) * scale;\n out[1] = Math.sin(r) * scale;\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the vector to transform\r\n * @param {ReadonlyMat2} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat2(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat2d\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the vector to transform\r\n * @param {ReadonlyMat2d} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat2d(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y + m[4];\n out[1] = m[1] * x + m[3] * y + m[5];\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat3\r\n * 3rd vector component is implicitly '1'\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the vector to transform\r\n * @param {ReadonlyMat3} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[3] * y + m[6];\n out[1] = m[1] * x + m[4] * y + m[7];\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat4\r\n * 3rd vector component is implicitly '0'\r\n * 4th vector component is implicitly '1'\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {ReadonlyVec2} a the vector to transform\r\n * @param {ReadonlyMat4} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0];\n var y = a[1];\n out[0] = m[0] * x + m[4] * y + m[12];\n out[1] = m[1] * x + m[5] * y + m[13];\n return out;\n}\n/**\r\n * Rotate a 2D vector\r\n * @param {vec2} out The receiving vec2\r\n * @param {ReadonlyVec2} a The vec2 point to rotate\r\n * @param {ReadonlyVec2} b The origin of the rotation\r\n * @param {Number} rad The angle of rotation in radians\r\n * @returns {vec2} out\r\n */\n\nexport function rotate(out, a, b, rad) {\n //Translate point to the origin\n var p0 = a[0] - b[0],\n p1 = a[1] - b[1],\n sinC = Math.sin(rad),\n cosC = Math.cos(rad); //perform rotation and translate to correct position\n\n out[0] = p0 * cosC - p1 * sinC + b[0];\n out[1] = p0 * sinC + p1 * cosC + b[1];\n return out;\n}\n/**\r\n * Get the angle between two 2D vectors\r\n * @param {ReadonlyVec2} a The first operand\r\n * @param {ReadonlyVec2} b The second operand\r\n * @returns {Number} The angle in radians\r\n */\n\nexport function angle(a, b) {\n var x1 = a[0],\n y1 = a[1],\n x2 = b[0],\n y2 = b[1],\n // mag is the product of the magnitudes of a and b\n mag = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2),\n // mag &&.. short circuits if mag == 0\n cosine = mag && (x1 * x2 + y1 * y2) / mag; // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1\n\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\r\n * Set the components of a vec2 to zero\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @returns {vec2} out\r\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n return out;\n}\n/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {ReadonlyVec2} a vector to represent as a string\r\n * @returns {String} string representation of the vector\r\n */\n\nexport function str(a) {\n return \"vec2(\" + a[0] + \", \" + a[1] + \")\";\n}\n/**\r\n * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)\r\n *\r\n * @param {ReadonlyVec2} a The first vector.\r\n * @param {ReadonlyVec2} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1];\n}\n/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {ReadonlyVec2} a The first vector.\r\n * @param {ReadonlyVec2} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1];\n var b0 = b[0],\n b1 = b[1];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1));\n}\n/**\r\n * Alias for {@link vec2.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec2.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec2.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec2.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec2.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec2.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec2.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec2s.\r\n *\r\n * @param {Array} a the array of vectors to iterate over\r\n * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed\r\n * @param {Number} offset Number of elements to skip at the beginning of the array\r\n * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array\r\n * @param {Function} fn Function to call for each vector in the array\r\n * @param {Object} [arg] additional argument to pass to fn\r\n * @returns {Array} a\r\n * @function\r\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 2;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n }\n\n return a;\n };\n}();","export class BaseResponse {\n /**\n * Returns whether the response has an ok'ish status code\n */\n get ok() {\n return this.status >= 200 && this.status <= 299;\n }\n\n /**\n * Returns the status code of the response\n */\n get status() {\n throw new Error('not implemented');\n }\n\n /**\n * Returns the value of the specified header\n * @param {string} headerName the header name\n * @returns {string} the header value\n */\n getHeader(headerName) {\n throw new Error('not implemented');\n }\n\n /**\n * @returns {ArrayBuffer} the response data of the request\n */\n async getData() {\n throw new Error('not implemented');\n }\n}\n\nexport class BaseClient {\n constructor(url) {\n this.url = url;\n }\n\n /**\n * Send a request with the options\n * @param {object} [options]\n */\n async request({ headers, credentials, signal } = {}) {\n throw new Error(`request is not implemented`);\n }\n}\n\n","var now = require('performance-now')\n , root = typeof window === 'undefined' ? global : window\n , vendors = ['moz', 'webkit']\n , suffix = 'AnimationFrame'\n , raf = root['request' + suffix]\n , caf = root['cancel' + suffix] || root['cancelRequest' + suffix]\n\nfor(var i = 0; !raf && i < vendors.length; i++) {\n raf = root[vendors[i] + 'Request' + suffix]\n caf = root[vendors[i] + 'Cancel' + suffix]\n || root[vendors[i] + 'CancelRequest' + suffix]\n}\n\n// Some versions of FF have rAF but not cAF\nif(!raf || !caf) {\n var last = 0\n , id = 0\n , queue = []\n , frameDuration = 1000 / 60\n\n raf = function(callback) {\n if(queue.length === 0) {\n var _now = now()\n , next = Math.max(0, frameDuration - (_now - last))\n last = next + _now\n setTimeout(function() {\n var cp = queue.slice(0)\n // Clear queue here to prevent\n // callbacks from appending listeners\n // to the current frame's queue\n queue.length = 0\n for(var i = 0; i < cp.length; i++) {\n if(!cp[i].cancelled) {\n try{\n cp[i].callback(last)\n } catch(e) {\n setTimeout(function() { throw e }, 0)\n }\n }\n }\n }, Math.round(next))\n }\n queue.push({\n handle: ++id,\n callback: callback,\n cancelled: false\n })\n return id\n }\n\n caf = function(handle) {\n for(var i = 0; i < queue.length; i++) {\n if(queue[i].handle === handle) {\n queue[i].cancelled = true\n }\n }\n }\n}\n\nmodule.exports = function(fn) {\n // Wrap in a new function to prevent\n // `cancel` potentially being assigned\n // to the native rAF function\n return raf.call(root, fn)\n}\nmodule.exports.cancel = function() {\n caf.apply(root, arguments)\n}\nmodule.exports.polyfill = function(object) {\n if (!object) {\n object = root;\n }\n object.requestAnimationFrame = raf\n object.cancelAnimationFrame = caf\n}\n","import GL from '@luma.gl/constants';\nimport {isWebGL2} from '@luma.gl/gltools';\n\n// const S3TC = 'WEBGL_compressed_texture_s3tc';\n// const PVRTC = 'WEBGL_compressed_texture_pvrtc';\n// const ES3 = 'WEBGL_compressed_texture_es3';\n// const ETC1 = 'WEBGL_compressed_texture_etc1';\n// const SRGB = 'EXT_sRGB';\n// const DEPTH = 'WEBGL_depth_texture';\n\n// Legal combinations for internalFormat, format and type\nexport const TEXTURE_FORMATS = {\n // Unsized texture format - more performance\n [GL.RGB]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_5_6_5]},\n // TODO: format: GL.RGBA type: GL.FLOAT is supported in WebGL1 when 'OES_texure_float' is suported\n // we need to update this table structure to specify extensions (gl1: 'OES_texure_float', gl2: false) for each type.\n [GL.RGBA]: {\n dataFormat: GL.RGBA,\n types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_4_4_4_4, GL.UNSIGNED_SHORT_5_5_5_1]\n },\n [GL.ALPHA]: {dataFormat: GL.ALPHA, types: [GL.UNSIGNED_BYTE]},\n [GL.LUMINANCE]: {dataFormat: GL.LUMINANCE, types: [GL.UNSIGNED_BYTE]},\n [GL.LUMINANCE_ALPHA]: {dataFormat: GL.LUMINANCE_ALPHA, types: [GL.UNSIGNED_BYTE]},\n\n // 32 bit floats\n [GL.R32F]: {dataFormat: GL.RED, types: [GL.FLOAT], gl2: true},\n [GL.RG32F]: {dataFormat: GL.RG, types: [GL.FLOAT], gl2: true},\n [GL.RGB32F]: {dataFormat: GL.RGB, types: [GL.FLOAT], gl2: true},\n [GL.RGBA32F]: {dataFormat: GL.RGBA, types: [GL.FLOAT], gl2: true}\n\n // [GL.DEPTH_COMPONENT]: {types: [GL.UNSIGNED_SHORT, GL.UNSIGNED_INT, GL.UNSIGNED_INT_24_8], gl1: DEPTH},\n // [GL.DEPTH_STENCIL]: {gl1: DEPTH},\n\n // Sized texture format - more performance\n // R\n // [GL.R8]: {dataFormat: GL.RED, types: [GL.UNSIGNED_BYTE], gl2: true},\n // [GL.R16F]: {dataFormat: GL.RED, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true},\n // [GL.R8UI]: {dataFormat: GL.RED_INTEGER, types: [GL.UNSIGNED_BYTE], gl2: true},\n // // RG\n // [GL.RG8]: {dataFormat: GL.RG, types: [GL.UNSIGNED_BYTE], gl2: true},\n // [GL.RG16F]: {dataFormat: GL.RG, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true},\n // [GL.RG8UI]: {dataFormat: GL.RG_INTEGER, types: [GL.UNSIGNED_BYTE], gl2: true},\n // // RGB\n // [GL.RGB8]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_BYTE], gl2: true, gl1: SRGB},\n // [GL.SRGB8]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_BYTE], gl2: true, gl1: SRGB},\n // [GL.RGB565]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_5_6_5], gl2: true},\n // [GL.R11F_G11F_B10F]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_INT_10F_11F_11F_REV, GL.HALF_FLOAT, GL.FLOAT], gl2: true},\n // [GL.RGB9_E5]: {dataFormat: GL.RGB, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true, gl1: 'WEBGL_color_buffer_half_float'},\n // [GL.RGB16F]: {dataFormat: GL.RGB, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true, gl1: 'WEBGL_color_buffer_float'},\n // [GL.RGB8UI]: {dataFormat: GL.RGB_INTEGER, types: [GL.UNSIGNED_BYTE], gl2: true},\n // // RGBA\n // [GL.RGBA8]: {dataFormat: GL.RGBA, types: [GL.UNSIGNED_BYTE], gl2: true, gl1: SRGB},\n // [GL.SRGB8_ALPHA8]: {dataFormat: GL.RGBA, types: [GL.UNSIGNED_BYTE], gl2: true, gl1: SRGB},\n // [GL.RGB5_A1]: {dataFormat: GL.RGBA, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_5_5_5_1], gl2: true},\n // [GL.RGBA4]: {dataFormat: GL.RGBA, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_4_4_4_4], gl2: true},\n // [GL.RGBA16F]: {dataFormat: GL.RGBA, types: [GL.HALF_FLOAT, GL.FLOAT], gl2: true},\n // [GL.RGBA8UI]: {dataFormat: GL.RGBA_INTEGER, types: [GL.UNSIGNED_BYTE], gl2: true}\n\n // Compressed formats\n\n // WEBGL_compressed_texture_s3tc\n\n // [GL.COMPRESSED_RGB_S3TC_DXT1_EXT]: {compressed: true, gl1: S3TC},\n // [GL.COMPRESSED_RGBA_S3TC_DXT1_EXT]: {compressed: true, gl1: S3TC},\n // [GL.COMPRESSED_RGBA_S3TC_DXT3_EXT]: {compressed: true, gl1: S3TC},\n // [GL.COMPRESSED_RGBA_S3TC_DXT5_EXT]: {compressed: true, gl1: S3TC},\n\n // WEBGL_compressed_texture_es3\n\n // [GL.COMPRESSED_R11_EAC]: {compressed: true, gl1: ES3}, // RED\n // [GL.COMPRESSED_SIGNED_R11_EAC]: {compressed: true, gl1: ES3}, // RED\n // [GL.COMPRESSED_RG11_EAC]: {compressed: true, gl1: ES3}, // RG\n // [GL.COMPRESSED_SIGNED_RG11_EAC]: {compressed: true, gl1: ES3}, // RG\n // [GL.COMPRESSED_RGB8_ETC2]: {compressed: true, gl1: ES3}, // RGB\n // [GL.COMPRESSED_RGBA8_ETC2_EAC]: {compressed: true, gl1: ES3}, // RBG\n // [GL.COMPRESSED_SRGB8_ETC2]: {compressed: true, gl1: ES3}, // RGB\n // [GL.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC]: {compressed: true, gl1: ES3}, // RGBA\n // [GL.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2]: {compressed: true, gl1: ES3}, // RGBA\n // [GL.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2]: {compressed: true, gl1: ES3}, // RGBA\n /* WebGL2 guaranteed availability compressed formats?\n COMPRESSED_R11_EAC RED\n COMPRESSED_SIGNED_R11_EAC RED\n COMPRESSED_RG11_EAC RG\n COMPRESSED_SIGNED_RG11_EAC RG\n COMPRESSED_RGB8_ETC2 RGB\n COMPRESSED_SRGB8_ETC2 RGB\n COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 RGBA\n COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 RGBA\n COMPRESSED_RGBA8_ETC2_EAC RGBA\n COMPRESSED_SRGB8_ALPHA8_ETC2_EAC\n */\n\n // WEBGL_compressed_texture_pvrtc\n\n // [GL.COMPRESSED_RGB_PVRTC_4BPPV1_IMG]: {compressed: true, gl1: PVRTC},\n // [GL.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG]: {compressed: true, gl1: PVRTC},\n // [GL.COMPRESSED_RGB_PVRTC_2BPPV1_IMG]: {compressed: true, gl1: PVRTC},\n // [GL.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG]: {compressed: true, gl1: PVRTC},\n\n // WEBGL_compressed_texture_etc1\n\n // [GL.COMPRESSED_RGB_ETC1_WEBGL]: {compressed: true, gl1: ETC1},\n\n // WEBGL_compressed_texture_atc\n\n // [GL.COMPRESSED_RGB_ATC_WEBGL]: {compressed: true, gl1: ETC1},\n // [GL.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL]: {compressed: true, gl1: ETC1},\n // [GL.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL]: {compressed: true, gl1: ETC1}\n};\n\nexport const DATA_FORMAT_CHANNELS = {\n [GL.RED]: 1,\n [GL.RED_INTEGER]: 1,\n [GL.RG]: 2,\n [GL.RG_INTEGER]: 2,\n [GL.RGB]: 3,\n [GL.RGB_INTEGER]: 3,\n [GL.RGBA]: 4,\n [GL.RGBA_INTEGER]: 4,\n [GL.DEPTH_COMPONENT]: 1,\n [GL.DEPTH_STENCIL]: 1,\n [GL.ALPHA]: 1,\n [GL.LUMINANCE]: 1,\n [GL.LUMINANCE_ALPHA]: 2\n};\n\nexport const TYPE_SIZES = {\n [GL.FLOAT]: 4,\n [GL.UNSIGNED_INT]: 4,\n [GL.INT]: 4,\n [GL.UNSIGNED_SHORT]: 2,\n [GL.SHORT]: 2,\n [GL.HALF_FLOAT]: 2,\n [GL.BYTE]: 1,\n [GL.UNSIGNED_BYTE]: 1\n};\n\nexport function isFormatSupported(gl, format) {\n const info = TEXTURE_FORMATS[format];\n if (!info) {\n return false;\n }\n if (info.gl1 === undefined && info.gl2 === undefined) {\n // No info - always supported\n return true;\n }\n const value = isWebGL2(gl) ? info.gl2 || info.gl1 : info.gl1;\n return typeof value === 'string' ? gl.getExtension(value) : value;\n}\n\nexport function isLinearFilteringSupported(gl, format) {\n const info = TEXTURE_FORMATS[format];\n switch (info && info.types[0]) {\n // Both WebGL1 and WebGL2?\n case GL.FLOAT:\n return gl.getExtension('OES_texture_float_linear');\n // Not in WebGL2?\n case GL.HALF_FLOAT:\n return gl.getExtension('OES_texture_half_float_linear');\n default:\n return true;\n }\n}\n","export { ArrowStyles, DEFAULT_ARROWS, MAX_ARROWS } from './style';\n\n// Layers\nexport { default as EditableGeoJsonLayer } from './layers/editable-geojson-layer';\nexport { default as EditableH3ClusterLayer } from './layers/editable-h3-cluster-layer';\nexport { default as SelectionLayer } from './layers/selection-layer';\nexport { default as ElevatedEditHandleLayer } from './layers/elevated-edit-handle-layer';\n\n// Layers moved from deck.gl\nexport { default as PathOutlineLayer } from './layers/path-outline-layer/path-outline-layer';\nexport { default as PathMarkerLayer } from './layers/path-marker-layer/path-marker-layer';\nexport { default as JunctionScatterplotLayer } from './layers/junction-scatterplot-layer';\n\n// Utils\nexport { toDeckColor } from './utils';\n\n// Types\nexport type { Color, Viewport } from './types';\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nvar global = module.exports = typeof window != 'undefined' && window.Math == Math\n ? window : typeof self != 'undefined' && self.Math == Math ? self\n // eslint-disable-next-line no-new-func\n : Function('return this')();\nif (typeof __g == 'number') __g = global; // eslint-disable-line no-undef\n","var core = module.exports = { version: '2.6.11' };\nif (typeof __e == 'number') __e = core; // eslint-disable-line no-undef\n","// Thank's IE8 for his funny defineProperty\nmodule.exports = !require('./_fails')(function () {\n return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;\n});\n","var arrayMap = require('./_arrayMap'),\n baseIteratee = require('./_baseIteratee'),\n baseMap = require('./_baseMap'),\n isArray = require('./isArray');\n\n/**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\nfunction map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, baseIteratee(iteratee, 3));\n}\n\nmodule.exports = map;\n","import {TypedArray} from '../../types';\nimport * as node from './buffer-utils';\n\n/**\n * Convert an object to an array buffer\n */\nexport function toArrayBuffer(data: any): ArrayBuffer {\n // Note: Should be called first, Buffers can trigger other detections below\n if (node.isBuffer(data)) {\n // TODO - per docs we should just be able to call buffer.buffer, but there are issues\n data = node.bufferToArrayBuffer(data);\n }\n\n if (data instanceof ArrayBuffer) {\n return data;\n }\n\n // Careful - Node Buffers look like Uint8Arrays (keep after isBuffer)\n if (ArrayBuffer.isView(data)) {\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);\n }\n\n if (typeof data === 'string') {\n const text = data;\n const uint8Array = new TextEncoder().encode(text);\n return uint8Array.buffer;\n }\n\n // HACK to support Blob polyfill\n if (data && typeof data === 'object' && data._toArrayBuffer) {\n return data._toArrayBuffer();\n }\n\n throw new Error('toArrayBuffer');\n}\n\n/**\n * compare two binary arrays for equality\n * @param {ArrayBuffer} a\n * @param {ArrayBuffer} b\n * @param {number} byteLength\n */\nexport function compareArrayBuffers(\n arrayBuffer1: ArrayBuffer,\n arrayBuffer2: ArrayBuffer,\n byteLength?: number\n): boolean {\n byteLength = byteLength || arrayBuffer1.byteLength;\n if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {\n return false;\n }\n const array1 = new Uint8Array(arrayBuffer1);\n const array2 = new Uint8Array(arrayBuffer2);\n for (let i = 0; i < array1.length; ++i) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Concatenate a sequence of ArrayBuffers\n * @return A concatenated ArrayBuffer\n */\nexport function concatenateArrayBuffers(...sources: (ArrayBuffer | Uint8Array)[]): ArrayBuffer {\n // Make sure all inputs are wrapped in typed arrays\n const sourceArrays = sources.map((source2) =>\n source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2\n );\n\n // Get length of all inputs\n const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);\n\n // Allocate array with space for all inputs\n const result = new Uint8Array(byteLength);\n\n // Copy the subarrays\n let offset = 0;\n for (const sourceArray of sourceArrays) {\n result.set(sourceArray, offset);\n offset += sourceArray.byteLength;\n }\n\n // We work with ArrayBuffers, discard the typed array wrapper\n return result.buffer;\n}\n\n/**\n * Concatenate arbitrary count of typed arrays\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays\n * @param {...*} arrays - list of arrays. All arrays should be the same type\n * @return A concatenated TypedArray\n */\nexport function concatenateTypedArrays(...typedArrays: T[]): T {\n // @ts-ignore\n const arrays = typedArrays as TypedArray[];\n // @ts-ignore\n const TypedArrayConstructor = (arrays && arrays.length > 1 && arrays[0].constructor) || null;\n if (!TypedArrayConstructor) {\n throw new Error(\n '\"concatenateTypedArrays\" - incorrect quantity of arguments or arguments have incompatible data types'\n );\n }\n\n const sumLength = arrays.reduce((acc, value) => acc + value.length, 0);\n // @ts-ignore typescript does not like dynamic constructors\n const result = new TypedArrayConstructor(sumLength);\n let offset = 0;\n for (const array of arrays) {\n result.set(array, offset);\n offset += array.length;\n }\n return result;\n}\n\n/**\n * Copy a view of an ArrayBuffer into new ArrayBuffer with byteOffset = 0\n * @param arrayBuffer\n * @param byteOffset\n * @param byteLength\n */\nexport function sliceArrayBuffer(\n arrayBuffer: ArrayBuffer,\n byteOffset: number,\n byteLength?: number\n): ArrayBuffer {\n const subArray =\n byteLength !== undefined\n ? new Uint8Array(arrayBuffer).subarray(byteOffset, byteOffset + byteLength)\n : new Uint8Array(arrayBuffer).subarray(byteOffset);\n const arrayCopy = new Uint8Array(subArray);\n return arrayCopy.buffer;\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","// Provides a unified API for getting and setting any WebGL parameter\n// Also knows default values of all parameters, enabling fast cache initialization\n// Provides base functionality for the state caching.\nimport {\n GL_PARAMETER_DEFAULTS,\n GL_PARAMETER_SETTERS,\n GL_COMPOSITE_PARAMETER_SETTERS,\n GL_PARAMETER_GETTERS\n} from './webgl-parameter-tables';\n\nimport {pushContextState, popContextState} from './track-context-state';\nimport {assert} from '../utils/assert';\nimport {isWebGL} from '../utils/webgl-checks';\nimport {isObjectEmpty} from '../utils/utils';\n\n// Sets any GL parameter regardless of function (gl.blendMode, ...)\n// Note: requires a `cache` object to be set on the context (gl.state.cache)\n// This object is used to fill in any missing values for composite setter functions\nexport function setParameters(gl, values) {\n assert(isWebGL(gl), 'setParameters requires a WebGL context');\n\n if (isObjectEmpty(values)) {\n return;\n }\n\n const compositeSetters = {};\n\n // HANDLE PRIMITIVE SETTERS (and make note of any composite setters)\n\n for (const key in values) {\n const glConstant = Number(key);\n const setter = GL_PARAMETER_SETTERS[key];\n if (setter) {\n // Composite setters should only be called once, so save them\n if (typeof setter === 'string') {\n compositeSetters[setter] = true;\n } else {\n // if (gl[glConstant] !== undefined) {\n // TODO - added above check since this is being called on WebGL2 values in WebGL1...\n // TODO - deep equal on values? only call setter if value has changed?\n // NOTE - the setter will automatically update this.state\n setter(gl, values[key], glConstant);\n }\n }\n }\n\n // HANDLE COMPOSITE SETTERS\n\n // NOTE: any non-provided values needed by composite setters are filled in from state cache\n // The cache parameter is automatically retrieved from the context\n // This depends on `trackContextState`, which is technically a \"circular\" dependency.\n // But it is too inconvenient to always require a cache parameter here.\n // This is the ONLY external dependency in this module/\n const cache = gl.state && gl.state.cache;\n if (cache) {\n for (const key in compositeSetters) {\n // TODO - avoid calling composite setters if values have not changed.\n const compositeSetter = GL_COMPOSITE_PARAMETER_SETTERS[key];\n // Note - if `trackContextState` has been called,\n // the setter will automatically update this.state.cache\n compositeSetter(gl, values, cache);\n }\n }\n\n // Add a log for the else case?\n}\n\n// Copies the state from a context (gl.getParameter should not be overriden)\n// Reads the entire WebGL state from a context\n// Caveat: This generates a huge amount of synchronous driver roundtrips and should be\n// considered a very slow operation, to be used only if/when a context already manipulated\n// by external code needs to be synchronized for the first time\n// @return {Object} - a newly created map, with values keyed by GL parameters\nexport function getParameters(gl, parameters) {\n // default to querying all parameters\n parameters = parameters || GL_PARAMETER_DEFAULTS;\n // support both arrays of parameters and objects (keys represent parameters)\n\n if (typeof parameters === 'number') {\n // single GL enum\n const key = parameters;\n const getter = GL_PARAMETER_GETTERS[key];\n return getter ? getter(gl, key) : gl.getParameter(key);\n }\n\n const parameterKeys = Array.isArray(parameters) ? parameters : Object.keys(parameters);\n\n const state = {};\n for (const key of parameterKeys) {\n const getter = GL_PARAMETER_GETTERS[key];\n state[key] = getter ? getter(gl, Number(key)) : gl.getParameter(Number(key));\n }\n return state;\n}\n\n// Reset all parameters to a (almost) pure context state\n// NOTE: viewport and scissor will be set to the values in GL_PARAMETER_DEFAULTS,\n// NOT the canvas size dimensions, so they will have to be properly set after\n// calling this function.\nexport function resetParameters(gl) {\n setParameters(gl, GL_PARAMETER_DEFAULTS);\n}\n\n// Stores current \"global\" WebGL context settings, changes selected parameters,\n// executes function, restores parameters\nexport function withParameters(gl, parameters, func) {\n if (isObjectEmpty(parameters)) {\n // Avoid setting state if no parameters provided. Just call and return\n return func(gl);\n }\n\n const {nocatch = true} = parameters;\n\n pushContextState(gl);\n setParameters(gl, parameters);\n\n // Setup is done, call the function\n let value;\n\n if (nocatch) {\n // Avoid try catch to minimize stack size impact for safe execution paths\n value = func(gl);\n popContextState(gl);\n } else {\n // Wrap in a try-catch to ensure that parameters are restored on exceptions\n try {\n value = func(gl);\n } finally {\n popContextState(gl);\n }\n }\n\n return value;\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport MathArray from './base/math-array';\nimport {clamp} from '../lib/common';\nimport {checkNumber} from '../lib/validators';\nimport Quaternion from './quaternion';\n\n// Internal constants\nconst ERR_UNKNOWN_ORDER = 'Unknown Euler angle order';\nconst ALMOST_ONE = 0.99999;\n\nfunction validateOrder(value) {\n return value >= 0 && value < 6;\n}\n\nfunction checkOrder(value) {\n if (value < 0 && value >= 6) {\n throw new Error(ERR_UNKNOWN_ORDER);\n }\n return value;\n}\n\nexport default class Euler extends MathArray {\n // static XYZ = 0;\n // static YZX = 1;\n // static ZXY = 2;\n // static XZY = 3;\n // static YXZ = 4;\n // static ZYX = 5;\n // static RollPitchYaw = 0;\n // static DefaultOrder = 0;\n\n // Constants\n /* eslint-disable no-multi-spaces, brace-style, no-return-assign */\n static get ZYX() {\n return 0;\n }\n\n static get YXZ() {\n return 1;\n }\n\n static get XZY() {\n return 2;\n }\n\n static get ZXY() {\n return 3;\n }\n\n static get YZX() {\n return 4;\n }\n\n static get XYZ() {\n return 5;\n }\n\n static get RollPitchYaw() {\n return 0;\n }\n\n static get DefaultOrder() {\n return Euler.ZYX;\n }\n\n static get RotationOrders() {\n return ['ZYX', 'YXZ', 'XZY', 'ZXY', 'YZX', 'XYZ'];\n }\n\n static rotationOrder(order) {\n return Euler.RotationOrders[order];\n }\n\n get ELEMENTS() {\n return 4;\n }\n\n /* eslint-enable no-multi-spaces, brace-style, no-return-assign */\n\n /**\n * @class\n * @param {Number | Number[]} x\n * @param {Number=} [y]\n * @param {Number=} [z]\n * @param {Number=} [order]\n */\n constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {\n // PERF NOTE: initialize elements as double precision numbers\n super(-0, -0, -0, -0);\n // eslint-disable-next-line prefer-rest-params\n if (arguments.length > 0 && Array.isArray(arguments[0])) {\n // eslint-disable-next-line prefer-rest-params\n this.fromVector3(...arguments);\n } else {\n // @ts-ignore error TS2345: Argument of type 'number | [number, number, number, number]' not assignable to 'number'\n this.set(x, y, z, order);\n }\n }\n\n fromQuaternion(quaternion) {\n const [x, y, z, w] = quaternion;\n const ysqr = y * y;\n const t0 = -2.0 * (ysqr + z * z) + 1.0;\n const t1 = +2.0 * (x * y + w * z);\n let t2 = -2.0 * (x * z - w * y);\n const t3 = +2.0 * (y * z + w * x);\n const t4 = -2.0 * (x * x + ysqr) + 1.0;\n\n t2 = t2 > 1.0 ? 1.0 : t2;\n t2 = t2 < -1.0 ? -1.0 : t2;\n\n const roll = Math.atan2(t3, t4);\n const pitch = Math.asin(t2);\n const yaw = Math.atan2(t1, t0);\n\n return new Euler(roll, pitch, yaw, Euler.RollPitchYaw);\n }\n\n // fromQuaternion(q, order) {\n // this._fromRotationMat[-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0];\n // return this.check();\n // }\n\n // If copied array does contain fourth element, preserves currently set order\n copy(array) {\n this[0] = array[0];\n this[1] = array[1];\n this[2] = array[2];\n this[3] = Number.isFinite(array[3]) || this.order;\n return this.check();\n }\n\n // Sets the three angles, and optionally sets the rotation order\n // If order is not specified, preserves currently set order\n set(x = 0, y = 0, z = 0, order) {\n this[0] = x;\n this[1] = y;\n this[2] = z;\n this[3] = Number.isFinite(order) ? order : this[3];\n return this.check();\n }\n\n validate() {\n return (\n validateOrder(this[3]) &&\n Number.isFinite(this[0]) &&\n Number.isFinite(this[1]) &&\n Number.isFinite(this[2])\n );\n }\n\n // Does not copy the orientation element\n toArray(array = [], offset = 0) {\n array[offset] = this[0];\n array[offset + 1] = this[1];\n array[offset + 2] = this[2];\n return array;\n }\n\n // Copies the orientation element\n toArray4(array = [], offset = 0) {\n array[offset] = this[0];\n array[offset + 1] = this[1];\n array[offset + 2] = this[2];\n array[offset + 3] = this[3];\n return array;\n }\n\n toVector3(result = [-0, -0, -0]) {\n result[0] = this[0];\n result[1] = this[1];\n result[2] = this[2];\n return result;\n }\n\n /* eslint-disable no-multi-spaces, brace-style, no-return-assign */\n\n // x, y, z angle notation (note: only corresponds to axis in XYZ orientation)\n /** @type {number} */\n get x() {\n return this[0];\n }\n\n set x(value) {\n this[0] = checkNumber(value);\n }\n\n /** @type {number} */\n get y() {\n return this[1];\n }\n\n set y(value) {\n this[1] = checkNumber(value);\n }\n\n /** @type {number} */\n get z() {\n return this[2];\n }\n\n set z(value) {\n this[2] = checkNumber(value);\n }\n\n // alpha, beta, gamma angle notation\n get alpha() {\n return this[0];\n }\n\n set alpha(value) {\n this[0] = checkNumber(value);\n }\n\n get beta() {\n return this[1];\n }\n\n set beta(value) {\n this[1] = checkNumber(value);\n }\n\n get gamma() {\n return this[2];\n }\n\n set gamma(value) {\n this[2] = checkNumber(value);\n }\n\n // phi, theta, psi angle notation\n get phi() {\n return this[0];\n }\n\n set phi(value) {\n this[0] = checkNumber(value);\n }\n\n get theta() {\n return this[1];\n }\n\n set theta(value) {\n this[1] = checkNumber(value);\n }\n\n get psi() {\n return this[2];\n }\n\n set psi(value) {\n this[2] = checkNumber(value);\n }\n\n // roll, pitch, yaw angle notation\n /** @type {number} */\n get roll() {\n return this[0];\n }\n\n set roll(value) {\n this[0] = checkNumber(value);\n }\n\n /** @type {number} */\n get pitch() {\n return this[1];\n }\n\n set pitch(value) {\n this[1] = checkNumber(value);\n }\n\n /** @type {number} */\n get yaw() {\n return this[2];\n }\n\n set yaw(value) {\n this[2] = checkNumber(value);\n }\n\n // rotation order, in all three angle notations\n get order() {\n return this[3];\n }\n\n set order(value) {\n this[3] = checkOrder(value);\n }\n\n /* eslint-disable no-multi-spaces, brace-style, no-return-assign */\n\n // Constructors\n fromVector3(v, order) {\n return this.set(v[0], v[1], v[2], Number.isFinite(order) ? order : this[3]);\n }\n\n // TODO - with and without 4th element\n fromArray(array, offset = 0) {\n this[0] = array[0 + offset];\n this[1] = array[1 + offset];\n this[2] = array[2 + offset];\n if (array[3] !== undefined) {\n this[3] = array[3];\n }\n return this.check();\n }\n\n // Common ZYX rotation order\n fromRollPitchYaw(roll, pitch, yaw) {\n return this.set(roll, pitch, yaw, Euler.ZYX);\n }\n\n fromRotationMatrix(m, order = Euler.DefaultOrder) {\n this._fromRotationMatrix(m, order);\n return this.check();\n }\n\n // ACCESSORS\n\n getRotationMatrix(m) {\n return this._getRotationMatrix(m);\n }\n\n // TODO - move to Quaternion\n getQuaternion() {\n const q = new Quaternion();\n switch (this[3]) {\n case Euler.XYZ:\n return q.rotateX(this[0]).rotateY(this[1]).rotateZ(this[2]);\n case Euler.YXZ:\n return q.rotateY(this[0]).rotateX(this[1]).rotateZ(this[2]);\n case Euler.ZXY:\n return q.rotateZ(this[0]).rotateX(this[1]).rotateY(this[2]);\n case Euler.ZYX:\n return q.rotateZ(this[0]).rotateY(this[1]).rotateX(this[2]);\n case Euler.YZX:\n return q.rotateY(this[0]).rotateZ(this[1]).rotateX(this[2]);\n case Euler.XZY:\n return q.rotateX(this[0]).rotateZ(this[1]).rotateY(this[2]);\n default:\n throw new Error(ERR_UNKNOWN_ORDER);\n }\n }\n\n // INTERNAL METHODS\n\n // Concersion from Euler to rotation matrix and from matrix to Euler\n // Adapted from three.js under MIT license\n\n // // WARNING: this discards revolution information -bhouston\n // reorder(newOrder) {\n // const q = new Quaternion().setFromEuler(this);\n // return this.setFromQuaternion(q, newOrder);\n\n /* eslint-disable complexity, max-statements, one-var */\n _fromRotationMatrix(m, order = Euler.DefaultOrder) {\n // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)\n\n const te = m.elements;\n const m11 = te[0],\n m12 = te[4],\n m13 = te[8];\n const m21 = te[1],\n m22 = te[5],\n m23 = te[9];\n const m31 = te[2],\n m32 = te[6],\n m33 = te[10];\n\n order = order || this[3];\n\n switch (order) {\n case Euler.XYZ:\n this[1] = Math.asin(clamp(m13, -1, 1));\n\n if (Math.abs(m13) < ALMOST_ONE) {\n this[0] = Math.atan2(-m23, m33);\n this[2] = Math.atan2(-m12, m11);\n } else {\n this[0] = Math.atan2(m32, m22);\n this[2] = 0;\n }\n break;\n\n case Euler.YXZ:\n this[0] = Math.asin(-clamp(m23, -1, 1));\n\n if (Math.abs(m23) < ALMOST_ONE) {\n this[1] = Math.atan2(m13, m33);\n this[2] = Math.atan2(m21, m22);\n } else {\n this[1] = Math.atan2(-m31, m11);\n this[2] = 0;\n }\n break;\n\n case Euler.ZXY:\n this[0] = Math.asin(clamp(m32, -1, 1));\n\n if (Math.abs(m32) < ALMOST_ONE) {\n this[1] = Math.atan2(-m31, m33);\n this[2] = Math.atan2(-m12, m22);\n } else {\n this[1] = 0;\n this[2] = Math.atan2(m21, m11);\n }\n break;\n\n case Euler.ZYX:\n this[1] = Math.asin(-clamp(m31, -1, 1));\n\n if (Math.abs(m31) < ALMOST_ONE) {\n this[0] = Math.atan2(m32, m33);\n this[2] = Math.atan2(m21, m11);\n } else {\n this[0] = 0;\n this[2] = Math.atan2(-m12, m22);\n }\n break;\n\n case Euler.YZX:\n this[2] = Math.asin(clamp(m21, -1, 1));\n\n if (Math.abs(m21) < ALMOST_ONE) {\n this[0] = Math.atan2(-m23, m22);\n this[1] = Math.atan2(-m31, m11);\n } else {\n this[0] = 0;\n this[1] = Math.atan2(m13, m33);\n }\n break;\n\n case Euler.XZY:\n this[2] = Math.asin(-clamp(m12, -1, 1));\n\n if (Math.abs(m12) < ALMOST_ONE) {\n this[0] = Math.atan2(m32, m22);\n this[1] = Math.atan2(m13, m11);\n } else {\n this[0] = Math.atan2(-m23, m33);\n this[1] = 0;\n }\n break;\n\n default:\n throw new Error(ERR_UNKNOWN_ORDER);\n }\n\n this[3] = order;\n\n return this;\n }\n\n _getRotationMatrix(result) {\n const te = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0];\n\n const x = this.x,\n y = this.y,\n z = this.z;\n const a = Math.cos(x);\n const c = Math.cos(y);\n const e = Math.cos(z);\n const b = Math.sin(x);\n const d = Math.sin(y);\n const f = Math.sin(z);\n\n switch (this[3]) {\n case Euler.XYZ: {\n const ae = a * e,\n af = a * f,\n be = b * e,\n bf = b * f;\n\n te[0] = c * e;\n te[4] = -c * f;\n te[8] = d;\n\n te[1] = af + be * d;\n te[5] = ae - bf * d;\n te[9] = -b * c;\n\n te[2] = bf - ae * d;\n te[6] = be + af * d;\n te[10] = a * c;\n break;\n }\n\n case Euler.YXZ: {\n const ce = c * e,\n cf = c * f,\n de = d * e,\n df = d * f;\n\n te[0] = ce + df * b;\n te[4] = de * b - cf;\n te[8] = a * d;\n\n te[1] = a * f;\n te[5] = a * e;\n te[9] = -b;\n\n te[2] = cf * b - de;\n te[6] = df + ce * b;\n te[10] = a * c;\n break;\n }\n\n case Euler.ZXY: {\n const ce = c * e,\n cf = c * f,\n de = d * e,\n df = d * f;\n\n te[0] = ce - df * b;\n te[4] = -a * f;\n te[8] = de + cf * b;\n\n te[1] = cf + de * b;\n te[5] = a * e;\n te[9] = df - ce * b;\n\n te[2] = -a * d;\n te[6] = b;\n te[10] = a * c;\n break;\n }\n\n case Euler.ZYX: {\n const ae = a * e,\n af = a * f,\n be = b * e,\n bf = b * f;\n\n te[0] = c * e;\n te[4] = be * d - af;\n te[8] = ae * d + bf;\n\n te[1] = c * f;\n te[5] = bf * d + ae;\n te[9] = af * d - be;\n\n te[2] = -d;\n te[6] = b * c;\n te[10] = a * c;\n break;\n }\n\n case Euler.YZX: {\n const ac = a * c,\n ad = a * d,\n bc = b * c,\n bd = b * d;\n\n te[0] = c * e;\n te[4] = bd - ac * f;\n te[8] = bc * f + ad;\n\n te[1] = f;\n te[5] = a * e;\n te[9] = -b * e;\n\n te[2] = -d * e;\n te[6] = ad * f + bc;\n te[10] = ac - bd * f;\n break;\n }\n\n case Euler.XZY: {\n const ac = a * c,\n ad = a * d,\n bc = b * c,\n bd = b * d;\n\n te[0] = c * e;\n te[4] = -f;\n te[8] = d * e;\n\n te[1] = ac * f + bd;\n te[5] = a * e;\n te[9] = ad * f - bc;\n\n te[2] = bc * f - ad;\n te[6] = b * e;\n te[10] = bd * f + ac;\n break;\n }\n\n default:\n throw new Error(ERR_UNKNOWN_ORDER);\n }\n\n // last column\n te[3] = 0;\n te[7] = 0;\n te[11] = 0;\n\n // bottom row\n te[12] = 0;\n te[13] = 0;\n te[14] = 0;\n te[15] = 1;\n\n return te;\n }\n\n toQuaternion() {\n // Abbreviations for the various angular functions\n const cy = Math.cos(this.yaw * 0.5);\n const sy = Math.sin(this.yaw * 0.5);\n const cr = Math.cos(this.roll * 0.5);\n const sr = Math.sin(this.roll * 0.5);\n const cp = Math.cos(this.pitch * 0.5);\n const sp = Math.sin(this.pitch * 0.5);\n\n const w = cy * cr * cp + sy * sr * sp;\n const x = cy * sr * cp - sy * cr * sp;\n const y = cy * cr * sp + sy * sr * cp;\n const z = sy * cr * cp - cy * sr * sp;\n\n return new Quaternion(x, y, z, w);\n }\n}\n","export default class Effect {\n constructor(props = {}) {\n const {id = 'effect'} = props;\n this.id = id;\n this.props = {...props};\n }\n\n preRender() {}\n\n getModuleParameters() {}\n\n cleanup() {}\n}\n","import GL from '@luma.gl/constants';\nimport Pass from './pass';\nimport {clear, setParameters, withParameters, cssToDeviceRatio} from '@luma.gl/core';\n\nexport default class LayersPass extends Pass {\n render(props) {\n const gl = this.gl;\n\n setParameters(gl, {framebuffer: props.target});\n return this._drawLayers(props);\n }\n\n // PRIVATE\n // Draw a list of layers in a list of viewports\n _drawLayers(props) {\n const {viewports, views, onViewportActive, clearCanvas = true} = props;\n props.pass = props.pass || 'unknown';\n\n const gl = this.gl;\n if (clearCanvas) {\n clearGLCanvas(gl);\n }\n\n const renderStats = [];\n\n for (const viewportOrDescriptor of viewports) {\n // Get a viewport from a viewport descriptor (which can be a plain viewport)\n const viewport = viewportOrDescriptor.viewport || viewportOrDescriptor;\n const view = views && views[viewport.id];\n\n // Update context to point to this viewport\n onViewportActive(viewport);\n\n const drawLayerParams = this._getDrawLayerParams(viewport, props);\n\n props.view = view;\n\n // render this viewport\n const subViewports = viewport.subViewports || [viewport];\n for (const subViewport of subViewports) {\n props.viewport = subViewport;\n\n const stats = this._drawLayersInViewport(gl, props, drawLayerParams);\n renderStats.push(stats);\n }\n }\n return renderStats;\n }\n\n // Resolve the parameters needed to draw each layer\n // When a viewport contains multiple subviewports (e.g. repeated web mercator map),\n // this is only done once for the parent viewport\n _getDrawLayerParams(viewport, {layers, pass, layerFilter, effects, moduleParameters}) {\n const drawLayerParams = [];\n const indexResolver = layerIndexResolver();\n const drawContext = {\n viewport,\n isPicking: pass.startsWith('picking'),\n renderPass: pass\n };\n const layerFilterCache = {};\n for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {\n const layer = layers[layerIndex];\n // Check if we should draw layer\n const shouldDrawLayer = this._shouldDrawLayer(\n layer,\n drawContext,\n layerFilter,\n layerFilterCache\n );\n\n // This is the \"logical\" index for ordering this layer in the stack\n // used to calculate polygon offsets\n // It can be the same as another layer\n const layerRenderIndex = indexResolver(layer, shouldDrawLayer);\n\n const layerParam = {\n shouldDrawLayer,\n layerRenderIndex\n };\n\n if (shouldDrawLayer) {\n layerParam.moduleParameters = this._getModuleParameters(\n layer,\n effects,\n pass,\n moduleParameters\n );\n layerParam.layerParameters = this.getLayerParameters(layer, layerIndex, viewport);\n }\n drawLayerParams[layerIndex] = layerParam;\n }\n return drawLayerParams;\n }\n\n // Draws a list of layers in one viewport\n // TODO - when picking we could completely skip rendering viewports that dont\n // intersect with the picking rect\n /* eslint-disable max-depth, max-statements */\n _drawLayersInViewport(gl, {layers, pass, viewport, view}, drawLayerParams) {\n const glViewport = getGLViewport(gl, {viewport});\n\n if (view && view.props.clear) {\n const clearOpts = view.props.clear === true ? {color: true, depth: true} : view.props.clear;\n withParameters(\n gl,\n {\n scissorTest: true,\n scissor: glViewport\n },\n () => clear(gl, clearOpts)\n );\n }\n\n // render layers in normal colors\n const renderStatus = {\n totalCount: layers.length,\n visibleCount: 0,\n compositeCount: 0,\n pickableCount: 0\n };\n\n setParameters(gl, {viewport: glViewport});\n\n // render layers in normal colors\n for (let layerIndex = 0; layerIndex < layers.length; layerIndex++) {\n const layer = layers[layerIndex];\n const {\n shouldDrawLayer,\n layerRenderIndex,\n moduleParameters,\n layerParameters\n } = drawLayerParams[layerIndex];\n\n // Calculate stats\n if (shouldDrawLayer && layer.props.pickable) {\n renderStatus.pickableCount++;\n }\n if (layer.isComposite) {\n renderStatus.compositeCount++;\n } else if (shouldDrawLayer) {\n // Draw the layer\n renderStatus.visibleCount++;\n\n // overwrite layer.context.viewport with the sub viewport\n moduleParameters.viewport = viewport;\n\n try {\n layer.drawLayer({\n moduleParameters,\n uniforms: {layerIndex: layerRenderIndex},\n parameters: layerParameters\n });\n } catch (err) {\n layer.raiseError(err, `drawing ${layer} to ${pass}`);\n }\n }\n }\n\n return renderStatus;\n }\n /* eslint-enable max-depth, max-statements */\n\n /* Methods for subclass overrides */\n shouldDrawLayer(layer) {\n return true;\n }\n\n getModuleParameters(layer, effects) {\n return null;\n }\n\n getLayerParameters(layer, layerIndex) {\n return layer.props.parameters;\n }\n\n /* Private */\n _shouldDrawLayer(layer, drawContext, layerFilter, layerFilterCache) {\n const shouldDrawLayer = this.shouldDrawLayer(layer) && layer.props.visible;\n\n if (!shouldDrawLayer) {\n return false;\n }\n\n drawContext.layer = layer;\n\n let parent = layer.parent;\n while (parent) {\n if (!parent.props.visible || !parent.filterSubLayer(drawContext)) {\n return false;\n }\n drawContext.layer = parent;\n parent = parent.parent;\n }\n\n if (layerFilter) {\n const rootLayerId = drawContext.layer.id;\n if (!(rootLayerId in layerFilterCache)) {\n layerFilterCache[rootLayerId] = layerFilter(drawContext);\n }\n if (!layerFilterCache[rootLayerId]) {\n return false;\n }\n }\n\n // If a layer is drawn, update its viewportChanged flag\n layer.activateViewport(drawContext.viewport);\n\n return true;\n }\n\n _getModuleParameters(layer, effects, pass, overrides) {\n const moduleParameters = Object.assign(Object.create(layer.props), {\n autoWrapLongitude: layer.wrapLongitude,\n viewport: layer.context.viewport,\n mousePosition: layer.context.mousePosition,\n pickingActive: 0,\n devicePixelRatio: cssToDeviceRatio(this.gl)\n });\n\n if (effects) {\n for (const effect of effects) {\n Object.assign(moduleParameters, effect.getModuleParameters(layer));\n }\n }\n\n return Object.assign(moduleParameters, this.getModuleParameters(layer, effects), overrides);\n }\n}\n\n// If the _index prop is defined, return a layer index that's relative to its parent\n// Otherwise return the index of the layer among all rendered layers\n// This is done recursively, i.e. if the user overrides a layer's default index,\n// all its descendants will be resolved relative to that index.\n// This implementation assumes that parent layers always appear before its children\n// which is true if the layer array comes from the LayerManager\nexport function layerIndexResolver(startIndex = 0, layerIndices = {}) {\n const resolvers = {};\n\n const resolveLayerIndex = (layer, isDrawn) => {\n const indexOverride = layer.props._offset;\n const layerId = layer.id;\n const parentId = layer.parent && layer.parent.id;\n\n let index;\n\n if (parentId && !(parentId in layerIndices)) {\n // Populate layerIndices with the parent layer's index\n resolveLayerIndex(layer.parent, false);\n }\n\n if (parentId in resolvers) {\n const resolver = (resolvers[parentId] =\n resolvers[parentId] || layerIndexResolver(layerIndices[parentId], layerIndices));\n index = resolver(layer, isDrawn);\n resolvers[layerId] = resolver;\n } else if (Number.isFinite(indexOverride)) {\n index = indexOverride + (layerIndices[parentId] || 0);\n // Mark layer as needing its own resolver\n // We don't actually create it until it's used for the first time\n resolvers[layerId] = null;\n } else {\n index = startIndex;\n }\n\n if (isDrawn && index >= startIndex) {\n startIndex = index + 1;\n }\n\n layerIndices[layerId] = index;\n return index;\n };\n return resolveLayerIndex;\n}\n\n// Convert viewport top-left CSS coordinates to bottom up WebGL coordinates\nfunction getGLViewport(gl, {viewport}) {\n // TODO - dummy default for node\n // Fallback to width/height when clientWidth/clientHeight are 0 or undefined.\n const height = gl.canvas ? gl.canvas.clientHeight || gl.canvas.height : 100;\n // Convert viewport top-left CSS coordinates to bottom up WebGL coordinates\n const dimensions = viewport;\n const pixelRatio = cssToDeviceRatio(gl);\n return [\n dimensions.x * pixelRatio,\n (height - dimensions.y - dimensions.height) * pixelRatio,\n dimensions.width * pixelRatio,\n dimensions.height * pixelRatio\n ];\n}\n\nfunction clearGLCanvas(gl) {\n const width = gl.drawingBufferWidth;\n const height = gl.drawingBufferHeight;\n // clear depth and color buffers, restoring transparency\n setParameters(gl, {viewport: [0, 0, width, height]});\n gl.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT);\n}\n","// based on https://github.com/WICG/focus-visible/blob/v4.1.5/src/focus-visible.js\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nvar hadKeyboardEvent = true;\nvar hadFocusVisibleRecently = false;\nvar hadFocusVisibleRecentlyTimeout = null;\nvar inputTypesWhitelist = {\n text: true,\n search: true,\n url: true,\n tel: true,\n email: true,\n password: true,\n number: true,\n date: true,\n month: true,\n week: true,\n time: true,\n datetime: true,\n 'datetime-local': true\n};\n/**\n * Computes whether the given element should automatically trigger the\n * `focus-visible` class being added, i.e. whether it should always match\n * `:focus-visible` when focused.\n * @param {Element} node\n * @return {boolean}\n */\n\nfunction focusTriggersKeyboardModality(node) {\n var type = node.type,\n tagName = node.tagName;\n\n if (tagName === 'INPUT' && inputTypesWhitelist[type] && !node.readOnly) {\n return true;\n }\n\n if (tagName === 'TEXTAREA' && !node.readOnly) {\n return true;\n }\n\n if (node.isContentEditable) {\n return true;\n }\n\n return false;\n}\n/**\n * Keep track of our keyboard modality state with `hadKeyboardEvent`.\n * If the most recent user interaction was via the keyboard;\n * and the key press did not include a meta, alt/option, or control key;\n * then the modality is keyboard. Otherwise, the modality is not keyboard.\n * @param {KeyboardEvent} event\n */\n\n\nfunction handleKeyDown(event) {\n if (event.metaKey || event.altKey || event.ctrlKey) {\n return;\n }\n\n hadKeyboardEvent = true;\n}\n/**\n * If at any point a user clicks with a pointing device, ensure that we change\n * the modality away from keyboard.\n * This avoids the situation where a user presses a key on an already focused\n * element, and then clicks on a different element, focusing it with a\n * pointing device, while we still think we're in keyboard modality.\n */\n\n\nfunction handlePointerDown() {\n hadKeyboardEvent = false;\n}\n\nfunction handleVisibilityChange() {\n if (this.visibilityState === 'hidden') {\n // If the tab becomes active again, the browser will handle calling focus\n // on the element (Safari actually calls it twice).\n // If this tab change caused a blur on an element with focus-visible,\n // re-apply the class when the user switches back to the tab.\n if (hadFocusVisibleRecently) {\n hadKeyboardEvent = true;\n }\n }\n}\n\nfunction prepare(doc) {\n doc.addEventListener('keydown', handleKeyDown, true);\n doc.addEventListener('mousedown', handlePointerDown, true);\n doc.addEventListener('pointerdown', handlePointerDown, true);\n doc.addEventListener('touchstart', handlePointerDown, true);\n doc.addEventListener('visibilitychange', handleVisibilityChange, true);\n}\n\nexport function teardown(doc) {\n doc.removeEventListener('keydown', handleKeyDown, true);\n doc.removeEventListener('mousedown', handlePointerDown, true);\n doc.removeEventListener('pointerdown', handlePointerDown, true);\n doc.removeEventListener('touchstart', handlePointerDown, true);\n doc.removeEventListener('visibilitychange', handleVisibilityChange, true);\n}\n\nfunction isFocusVisible(event) {\n var target = event.target;\n\n try {\n return target.matches(':focus-visible');\n } catch (error) {} // browsers not implementing :focus-visible will throw a SyntaxError\n // we use our own heuristic for those browsers\n // rethrow might be better if it's not the expected error but do we really\n // want to crash if focus-visible malfunctioned?\n // no need for validFocusTarget check. the user does that by attaching it to\n // focusable events only\n\n\n return hadKeyboardEvent || focusTriggersKeyboardModality(target);\n}\n/**\n * Should be called if a blur event is fired on a focus-visible element\n */\n\n\nfunction handleBlurVisible() {\n // To detect a tab/window switch, we look for a blur event followed\n // rapidly by a visibility change.\n // If we don't see a visibility change within 100ms, it's probably a\n // regular focus change.\n hadFocusVisibleRecently = true;\n window.clearTimeout(hadFocusVisibleRecentlyTimeout);\n hadFocusVisibleRecentlyTimeout = window.setTimeout(function () {\n hadFocusVisibleRecently = false;\n }, 100);\n}\n\nexport default function useIsFocusVisible() {\n var ref = React.useCallback(function (instance) {\n var node = ReactDOM.findDOMNode(instance);\n\n if (node != null) {\n prepare(node.ownerDocument);\n }\n }, []);\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(isFocusVisible);\n }\n\n return {\n isFocusVisible: isFocusVisible,\n onBlurVisible: handleBlurVisible,\n ref: ref\n };\n}","import ownerDocument from './ownerDocument';\nexport default function ownerWindow(node) {\n var doc = ownerDocument(node);\n return doc.defaultView || window;\n}","import arrayLikeToArray from \"./arrayLikeToArray\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(n);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}","import createTheme from './createTheme';\nvar defaultTheme = createTheme();\nexport default defaultTheme;","import * as React from 'react';\nexport default function isMuiElement(element, muiNames) {\n return /*#__PURE__*/React.isValidElement(element) && muiNames.indexOf(element.type.muiName) !== -1;\n}","/**\n * Returns a cloned copy of the passed GeoJSON Object, including possible 'Foreign Members'.\n * ~3-5x faster than the common JSON.parse + JSON.stringify combo method.\n *\n * @name clone\n * @param {GeoJSON} geojson GeoJSON Object\n * @returns {GeoJSON} cloned GeoJSON Object\n * @example\n * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]], {color: 'red'});\n *\n * var lineCloned = turf.clone(line);\n */\nfunction clone(geojson) {\n if (!geojson) {\n throw new Error(\"geojson is required\");\n }\n switch (geojson.type) {\n case \"Feature\":\n return cloneFeature(geojson);\n case \"FeatureCollection\":\n return cloneFeatureCollection(geojson);\n case \"Point\":\n case \"LineString\":\n case \"Polygon\":\n case \"MultiPoint\":\n case \"MultiLineString\":\n case \"MultiPolygon\":\n case \"GeometryCollection\":\n return cloneGeometry(geojson);\n default:\n throw new Error(\"unknown GeoJSON type\");\n }\n}\n/**\n * Clone Feature\n *\n * @private\n * @param {Feature} geojson GeoJSON Feature\n * @returns {Feature} cloned Feature\n */\nfunction cloneFeature(geojson) {\n var cloned = { type: \"Feature\" };\n // Preserve Foreign Members\n Object.keys(geojson).forEach(function (key) {\n switch (key) {\n case \"type\":\n case \"properties\":\n case \"geometry\":\n return;\n default:\n cloned[key] = geojson[key];\n }\n });\n // Add properties & geometry last\n cloned.properties = cloneProperties(geojson.properties);\n cloned.geometry = cloneGeometry(geojson.geometry);\n return cloned;\n}\n/**\n * Clone Properties\n *\n * @private\n * @param {Object} properties GeoJSON Properties\n * @returns {Object} cloned Properties\n */\nfunction cloneProperties(properties) {\n var cloned = {};\n if (!properties) {\n return cloned;\n }\n Object.keys(properties).forEach(function (key) {\n var value = properties[key];\n if (typeof value === \"object\") {\n if (value === null) {\n // handle null\n cloned[key] = null;\n }\n else if (Array.isArray(value)) {\n // handle Array\n cloned[key] = value.map(function (item) {\n return item;\n });\n }\n else {\n // handle generic Object\n cloned[key] = cloneProperties(value);\n }\n }\n else {\n cloned[key] = value;\n }\n });\n return cloned;\n}\n/**\n * Clone Feature Collection\n *\n * @private\n * @param {FeatureCollection} geojson GeoJSON Feature Collection\n * @returns {FeatureCollection} cloned Feature Collection\n */\nfunction cloneFeatureCollection(geojson) {\n var cloned = { type: \"FeatureCollection\" };\n // Preserve Foreign Members\n Object.keys(geojson).forEach(function (key) {\n switch (key) {\n case \"type\":\n case \"features\":\n return;\n default:\n cloned[key] = geojson[key];\n }\n });\n // Add features\n cloned.features = geojson.features.map(function (feature) {\n return cloneFeature(feature);\n });\n return cloned;\n}\n/**\n * Clone Geometry\n *\n * @private\n * @param {Geometry} geometry GeoJSON Geometry\n * @returns {Geometry} cloned Geometry\n */\nfunction cloneGeometry(geometry) {\n var geom = { type: geometry.type };\n if (geometry.bbox) {\n geom.bbox = geometry.bbox;\n }\n if (geometry.type === \"GeometryCollection\") {\n geom.geometries = geometry.geometries.map(function (g) {\n return cloneGeometry(g);\n });\n return geom;\n }\n geom.coordinates = deepSlice(geometry.coordinates);\n return geom;\n}\n/**\n * Deep Slice coordinates\n *\n * @private\n * @param {Coordinates} coords Coordinates\n * @returns {Coordinates} all coordinates sliced\n */\nfunction deepSlice(coords) {\n var cloned = coords;\n if (typeof cloned[0] !== \"object\") {\n return cloned.slice();\n }\n return cloned.map(function (coord) {\n return deepSlice(coord);\n });\n}\nexport default clone;\n","// TODO - build/integrate proper MIME type parsing\n// https://mimesniff.spec.whatwg.org/\n\nconst DATA_URL_PATTERN = /^data:([-\\w.]+\\/[-\\w.+]+)(;|,)/;\nconst MIME_TYPE_PATTERN = /^([-\\w.]+\\/[-\\w.+]+)/;\n\n/**\n * Remove extra data like `charset` from MIME types\n * @param mimeString\n * @returns A clean MIME type, or an empty string\n *\n * @todo - handle more advanced MIMETYpes, multiple types\n * @todo - extract charset etc\n */\nexport function parseMIMEType(mimeString: string): string {\n // If resource is a data url, extract any embedded mime type\n const matches = MIME_TYPE_PATTERN.exec(mimeString);\n if (matches) {\n return matches[1];\n }\n return mimeString;\n}\n\n/**\n * Extract MIME type from data URL\n *\n * @param mimeString\n * @returns A clean MIME type, or an empty string\n *\n * @todo - handle more advanced MIMETYpes, multiple types\n * @todo - extract charset etc\n */\nexport function parseMIMETypeFromURL(url: string): string {\n // If resource is a data URL, extract any embedded mime type\n const matches = DATA_URL_PATTERN.exec(url);\n if (matches) {\n return matches[1];\n }\n return '';\n}\n","import {isResponse, isBlob} from '../../javascript-utils/is-type';\nimport {parseMIMEType, parseMIMETypeFromURL} from './mime-type-utils';\n\nconst QUERY_STRING_PATTERN = /\\?.*/;\n\n/**\n * Returns an object with `url` and (MIME) `type` fields\n * If it cannot determine url or type, the corresponding value will be an empty string\n *\n * @param resource Any type, but only Responses, string URLs and data URLs are processed\n *\n * @todo string parameters are assumed to be URLs\n */\nexport function getResourceUrlAndType(resource: any): {url: string; type: string} {\n // If resource is a response, it contains the information directly\n if (isResponse(resource)) {\n const url = stripQueryString(resource.url || '');\n const contentTypeHeader = resource.headers.get('content-type') || '';\n return {\n url,\n type: parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(url)\n };\n }\n\n // If the resource is a Blob or a File (subclass of Blob)\n if (isBlob(resource)) {\n return {\n // File objects have a \"name\" property. Blob objects don't have any\n // url (name) information\n url: stripQueryString(resource.name || ''),\n type: resource.type || ''\n };\n }\n\n if (typeof resource === 'string') {\n return {\n // TODO this could mess up data URL but it doesn't matter as it is just used for inference\n url: stripQueryString(resource),\n // If a data url\n type: parseMIMETypeFromURL(resource)\n };\n }\n\n // Unknown\n return {\n url: '',\n type: ''\n };\n}\n\n/**\n * Returns (approximate) content length for a resource if it can be determined.\n * Returns -1 if content length cannot be determined.\n * @param resource\n\n * @note string parameters are NOT assumed to be URLs\n */\nexport function getResourceContentLength(resource: any): number {\n if (isResponse(resource)) {\n return resource.headers['content-length'] || -1;\n }\n if (isBlob(resource)) {\n return resource.size;\n }\n if (typeof resource === 'string') {\n // TODO - handle data URL?\n return resource.length;\n }\n if (resource instanceof ArrayBuffer) {\n return resource.byteLength;\n }\n if (ArrayBuffer.isView(resource)) {\n return resource.byteLength;\n }\n return -1;\n}\n\nfunction stripQueryString(url) {\n return url.replace(QUERY_STRING_PATTERN, '');\n}\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","var anObject = require('./_an-object');\nvar IE8_DOM_DEFINE = require('./_ie8-dom-define');\nvar toPrimitive = require('./_to-primitive');\nvar dP = Object.defineProperty;\n\nexports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes) {\n anObject(O);\n P = toPrimitive(P, true);\n anObject(Attributes);\n if (IE8_DOM_DEFINE) try {\n return dP(O, P, Attributes);\n } catch (e) { /* empty */ }\n if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');\n if ('value' in Attributes) O[P] = Attributes.value;\n return O;\n};\n","var hasOwnProperty = {}.hasOwnProperty;\nmodule.exports = function (it, key) {\n return hasOwnProperty.call(it, key);\n};\n","import * as node from '../node/buffer';\n\n/**\n * Check for Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n */\nexport function isBuffer(value: any): boolean {\n return value && typeof value === 'object' && value.isBuffer;\n}\n\n/**\n * Converts to Node.js `Buffer` (without triggering bundler to include Buffer polyfill on browser)\n * @todo better data type\n */\nexport function toBuffer(data: any): Buffer {\n return node.toBuffer ? node.toBuffer(data) : data;\n}\n\n/**\n * Converts Node.js `Buffer` to `ArrayBuffer` (without triggering bundler to include Buffer polyfill on browser)\n * @todo better data type\n */\nexport function bufferToArrayBuffer(data: any): ArrayBuffer {\n if (node.toArrayBuffer) {\n // TODO - per docs we should just be able to call buffer.buffer, but there are issues\n return node.toArrayBuffer(data);\n }\n return data;\n}\n","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function _typeof(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}","import {Vector3} from 'math.gl';\n\nconst DEFAULT_LIGHT_COLOR = [255, 255, 255];\nconst DEFAULT_LIGHT_INTENSITY = 1.0;\nconst DEFAULT_LIGHT_DIRECTION = [0.0, 0.0, -1.0];\n\nlet idCount = 0;\n\nexport class DirectionalLight {\n constructor(props = {}) {\n const {color = DEFAULT_LIGHT_COLOR} = props;\n const {intensity = DEFAULT_LIGHT_INTENSITY} = props;\n const {direction = DEFAULT_LIGHT_DIRECTION} = props;\n const {_shadow = false} = props;\n\n this.id = props.id || `directional-${idCount++}`;\n this.color = color;\n this.intensity = intensity;\n this.type = 'directional';\n this.direction = new Vector3(direction).normalize().toArray();\n this.shadow = _shadow;\n }\n\n getProjectedLight() {\n return this;\n }\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nconst vs = `\nstruct VertexGeometry {\n vec4 position;\n vec3 worldPosition;\n vec3 worldPositionAlt;\n vec3 normal;\n vec2 uv;\n vec3 pickingColor;\n} geometry = VertexGeometry(\n vec4(0.0),\n vec3(0.0),\n vec3(0.0),\n vec3(0.0),\n vec2(0.0),\n vec3(0.0)\n);\n`;\n\nconst fs = `\n#define SMOOTH_EDGE_RADIUS 0.5\n\nstruct FragmentGeometry {\n vec2 uv;\n} geometry;\n\nfloat smoothedge(float edge, float x) {\n return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x);\n}\n`;\n\nexport default {name: 'geometry', vs, fs};\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {COORDINATE_SYSTEM, PROJECTION_MODE, UNIT} from '../../lib/constants';\n\n// We are generating these from the js code in constants.js\nconst COORDINATE_SYSTEM_GLSL_CONSTANTS = Object.keys(COORDINATE_SYSTEM)\n .map(key => `const int COORDINATE_SYSTEM_${key} = ${COORDINATE_SYSTEM[key]};`)\n .join('');\nconst PROJECTION_MODE_GLSL_CONSTANTS = Object.keys(PROJECTION_MODE)\n .map(key => `const int PROJECTION_MODE_${key} = ${PROJECTION_MODE[key]};`)\n .join('');\nconst UNIT_GLSL_CONSTANTS = Object.keys(UNIT)\n .map(key => `const int UNIT_${key.toUpperCase()} = ${UNIT[key]};`)\n .join('');\n\nexport default `\\\n${COORDINATE_SYSTEM_GLSL_CONSTANTS}\n${PROJECTION_MODE_GLSL_CONSTANTS}\n${UNIT_GLSL_CONSTANTS}\n\nuniform int project_uCoordinateSystem;\nuniform int project_uProjectionMode;\nuniform float project_uScale;\nuniform bool project_uWrapLongitude;\nuniform vec3 project_uCommonUnitsPerMeter;\nuniform vec3 project_uCommonUnitsPerWorldUnit;\nuniform vec3 project_uCommonUnitsPerWorldUnit2;\nuniform vec4 project_uCenter;\nuniform mat4 project_uModelMatrix;\nuniform mat4 project_uViewProjectionMatrix;\nuniform vec2 project_uViewportSize;\nuniform float project_uDevicePixelRatio;\nuniform float project_uFocalDistance;\nuniform vec3 project_uCameraPosition;\nuniform vec3 project_uCoordinateOrigin;\nuniform vec3 project_uCommonOrigin;\nuniform bool project_uPseudoMeters;\n\nconst float TILE_SIZE = 512.0;\nconst float PI = 3.1415926536;\nconst float WORLD_SCALE = TILE_SIZE / (PI * 2.0);\nconst vec3 ZERO_64_LOW = vec3(0.0);\nconst float EARTH_RADIUS = 6370972.0; // meters\nconst float GLOBE_RADIUS = 256.0;\n\n// returns an adjustment factor for uCommonUnitsPerMeter\nfloat project_size() {\n if (project_uProjectionMode == PROJECTION_MODE_WEB_MERCATOR &&\n project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT &&\n project_uPseudoMeters == false) {\n\n // uCommonUnitsPerMeter in low-zoom Web Mercator is non-linear\n // Adjust by 1 / cos(latitude)\n // If geometry.position (vertex in common space) is populated, use it\n // Otherwise use geometry.worldPosition (anchor in world space)\n \n if (geometry.position.w == 0.0) {\n float y = clamp(geometry.worldPosition.y, -89.9, 89.9);\n return 1.0 / cos(radians(y));\n }\n\n // latitude from common y: 2.0 * (atan(exp(y / TILE_SIZE * 2.0 * PI - PI)) - PI / 4.0)\n // Taylor series of 1 / cos(latitude)\n // Max error < 0.003\n \n float y = geometry.position.y / TILE_SIZE * 2.0 - 1.0;\n float y2 = y * y;\n float y4 = y2 * y2;\n float y6 = y4 * y2;\n return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6;\n }\n return 1.0;\n}\n//\n// Scaling offsets - scales meters to \"world distance\"\n// Note the scalar version of project_size is for scaling the z component only\n//\nfloat project_size(float meters) {\n return meters * project_uCommonUnitsPerMeter.z * project_size();\n}\n\nvec2 project_size(vec2 meters) {\n return meters * project_uCommonUnitsPerMeter.xy * project_size();\n}\n\nvec3 project_size(vec3 meters) {\n return meters * project_uCommonUnitsPerMeter * project_size();\n}\n\nvec4 project_size(vec4 meters) {\n return vec4(meters.xyz * project_uCommonUnitsPerMeter, meters.w);\n}\n\n//\n// Projecting normal - transform deltas from current coordinate system to\n// normals in the worldspace\n//\nvec3 project_normal(vec3 vector) {\n // Apply model matrix\n vec4 normal_modelspace = project_uModelMatrix * vec4(vector, 0.0);\n return normalize(normal_modelspace.xyz * project_uCommonUnitsPerMeter);\n}\n\nvec4 project_offset_(vec4 offset) {\n float dy = offset.y;\n vec3 commonUnitsPerWorldUnit = project_uCommonUnitsPerWorldUnit + project_uCommonUnitsPerWorldUnit2 * dy;\n return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w);\n}\n\n//\n// Projecting positions - non-linear projection: lnglats => unit tile [0-1, 0-1]\n//\nvec2 project_mercator_(vec2 lnglat) {\n float x = lnglat.x;\n if (project_uWrapLongitude) {\n x = mod(x + 180., 360.0) - 180.;\n }\n float y = clamp(lnglat.y, -89.9, 89.9);\n return vec2(\n radians(x) + PI,\n PI + log(tan_fp32(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\nvec3 project_globe_(vec3 lnglatz) {\n float lambda = radians(lnglatz.x);\n float phi = radians(lnglatz.y);\n float cosPhi = cos(phi);\n float D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS;\n\n return vec3(\n sin(lambda) * cosPhi,\n -cos(lambda) * cosPhi,\n sin(phi)\n ) * D;\n}\n\n//\n// Projects positions (defined by project_uCoordinateSystem) to common space (defined by project_uProjectionMode)\n//\nvec4 project_position(vec4 position, vec3 position64Low) {\n vec4 position_world = project_uModelMatrix * position;\n\n // Work around for a Mac+NVIDIA bug https://github.com/visgl/deck.gl/issues/4145\n if (project_uProjectionMode == PROJECTION_MODE_WEB_MERCATOR) {\n if (project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_mercator_(position_world.xy),\n project_size(position_world.z),\n position_world.w\n );\n }\n if (project_uCoordinateSystem == COORDINATE_SYSTEM_CARTESIAN) {\n position_world.xyz += project_uCoordinateOrigin;\n }\n }\n if (project_uProjectionMode == PROJECTION_MODE_GLOBE) {\n if (project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n return vec4(\n project_globe_(position_world.xyz),\n position_world.w\n );\n }\n }\n if (project_uProjectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\n if (project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\n if (abs(position_world.y - project_uCoordinateOrigin.y) > 0.25) {\n // Too far from the projection center for offset mode to be accurate\n // Only use high parts\n return vec4(\n project_mercator_(position_world.xy) - project_uCommonOrigin.xy,\n project_size(position_world.z),\n position_world.w\n );\n }\n }\n }\n if (project_uProjectionMode == PROJECTION_MODE_IDENTITY ||\n (project_uProjectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET &&\n (project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project_uCoordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) {\n // Subtract high part of 64 bit value. Convert remainder to float32, preserving precision.\n position_world.xyz -= project_uCoordinateOrigin;\n }\n\n // Translation is already added to the high parts\n return project_offset_(position_world + project_uModelMatrix * vec4(position64Low, 0.0));\n}\n\nvec4 project_position(vec4 position) {\n return project_position(position, ZERO_64_LOW);\n}\n\nvec3 project_position(vec3 position, vec3 position64Low) {\n vec4 projected_position = project_position(vec4(position, 1.0), position64Low);\n return projected_position.xyz;\n}\n\nvec3 project_position(vec3 position) {\n vec4 projected_position = project_position(vec4(position, 1.0), ZERO_64_LOW);\n return projected_position.xyz;\n}\n\nvec2 project_position(vec2 position) {\n vec4 projected_position = project_position(vec4(position, 0.0, 1.0), ZERO_64_LOW);\n return projected_position.xy;\n}\n\nvec4 project_common_position_to_clipspace(vec4 position, mat4 viewProjectionMatrix, vec4 center) {\n return viewProjectionMatrix * position + center;\n}\n\n//\n// Projects from common space coordinates to clip space.\n// Uses project_uViewProjectionMatrix\n//\nvec4 project_common_position_to_clipspace(vec4 position) {\n return project_common_position_to_clipspace(position, project_uViewProjectionMatrix, project_uCenter);\n}\n\n// Returns a clip space offset that corresponds to a given number of screen pixels\nvec2 project_pixel_size_to_clipspace(vec2 pixels) {\n vec2 offset = pixels / project_uViewportSize * project_uDevicePixelRatio * 2.0;\n return offset * project_uFocalDistance;\n}\n\nfloat project_size_to_pixel(float meters) {\n return project_size(meters) * project_uScale;\n}\nfloat project_size_to_pixel(float size, int unit) {\n if (unit == UNIT_METERS) return project_size_to_pixel(size);\n if (unit == UNIT_COMMON) return size * project_uScale;\n // UNIT_PIXELS\n return size;\n}\nfloat project_pixel_size(float pixels) {\n return pixels / project_uScale;\n}\nvec2 project_pixel_size(vec2 pixels) {\n return pixels / project_uScale;\n}\n\n// Get rotation matrix that aligns the z axis with the given up vector\n// Find 3 unit vectors ux, uy, uz that are perpendicular to each other and uz == up\nmat3 project_get_orientation_matrix(vec3 up) {\n vec3 uz = normalize(up);\n // Tangent on XY plane\n vec3 ux = abs(uz.z) == 1.0 ? vec3(1.0, 0.0, 0.0) : normalize(vec3(uz.y, -uz.x, 0));\n vec3 uy = cross(uz, ux);\n return mat3(ux, uy, uz);\n}\n\nbool project_needs_rotation(vec3 commonPosition, out mat3 transform) {\n if (project_uProjectionMode == PROJECTION_MODE_GLOBE) {\n transform = project_get_orientation_matrix(commonPosition);\n return true;\n }\n return false;\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {fp32} from '@luma.gl/core';\nimport geometry from '../misc/geometry';\nimport projectShader from './project.glsl';\nimport {getUniformsFromViewport} from './viewport-uniforms';\n\nconst INITIAL_MODULE_OPTIONS = {};\n\nfunction getUniforms(opts = INITIAL_MODULE_OPTIONS) {\n if (opts.viewport) {\n return getUniformsFromViewport(opts);\n }\n return {};\n}\n\nexport default {\n name: 'project',\n dependencies: [fp32, geometry],\n vs: projectShader,\n getUniforms\n};\n","/* eslint-env browser */\nimport {log} from '@deck.gl/core';\n\nexport default class Tile2DHeader {\n constructor({x, y, z}) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.isVisible = false;\n this.isSelected = false;\n this.parent = null;\n this.children = [];\n\n this.content = null;\n\n this._loaderId = 0;\n this._isLoaded = false;\n this._isCancelled = false;\n this._needsReload = false;\n }\n\n get data() {\n return this.isLoading ? this._loader.then(() => this.data) : this.content;\n }\n\n get isLoaded() {\n return this._isLoaded && !this._needsReload;\n }\n\n get isLoading() {\n return Boolean(this._loader) && !this._isCancelled;\n }\n\n get needsReload() {\n return this._needsReload || this._isCancelled;\n }\n\n get byteLength() {\n const result = this.content ? this.content.byteLength : 0;\n if (!Number.isFinite(result)) {\n log.error('byteLength not defined in tile data')();\n }\n return result;\n }\n\n /* eslint-disable max-statements */\n async _loadData({getData, requestScheduler, onLoad, onError}) {\n const {x, y, z, bbox} = this;\n const loaderId = this._loaderId;\n\n this._abortController = new AbortController(); // eslint-disable-line no-undef\n const {signal} = this._abortController;\n\n const requestToken = await requestScheduler.scheduleRequest(this, tile => {\n return tile.isSelected ? 1 : -1;\n });\n\n if (!requestToken) {\n this._isCancelled = true;\n return;\n }\n // A tile can be cancelled while being scheduled\n if (this._isCancelled) {\n requestToken.done();\n return;\n }\n\n let tileData = null;\n let error;\n try {\n tileData = await getData({x, y, z, bbox, signal});\n } catch (err) {\n error = err || true;\n } finally {\n requestToken.done();\n }\n\n // If loadData has been called with a newer version, discard the result from this operation\n if (loaderId !== this._loaderId) {\n return;\n }\n // Clear the `isLoading` flag\n this._loader = undefined;\n // Rewrite tile content with the result of getTileData if successful, or `null` in case of\n // error or cancellation\n this.content = tileData;\n // If cancelled, do not invoke the callbacks\n // Consider it loaded if we tried to cancel but `getTileData` still returned data\n if (this._isCancelled && !tileData) {\n this._isLoaded = false;\n return;\n }\n this._isLoaded = true;\n this._isCancelled = false;\n\n if (error) {\n onError(error, this);\n } else {\n onLoad(this);\n }\n }\n /* eslint-enable max-statements */\n\n loadData(opts) {\n this._isLoaded = false;\n this._isCancelled = false;\n this._needsReload = false;\n this._loaderId++;\n this._loader = this._loadData(opts);\n return this._loader;\n }\n\n setNeedsReload() {\n if (this.isLoading) {\n this.abort();\n this._loader = undefined;\n }\n this._needsReload = true;\n }\n\n abort() {\n if (this.isLoaded) {\n return;\n }\n\n this._isCancelled = true;\n this._abortController.abort();\n }\n}\n","import Tile2DHeader from './tile-2d-header';\nimport {getTileIndices, tileToBoundingBox} from './utils';\nimport {RequestScheduler} from '@loaders.gl/loader-utils';\nimport {Matrix4} from 'math.gl';\n\nconst TILE_STATE_UNKNOWN = 0;\nconst TILE_STATE_VISIBLE = 1;\n/*\n show cached parent tile if children are loading\n +-----------+ +-----+ +-----+-----+\n | | | | | | |\n | | | | | | |\n | | --> +-----+-----+ -> +-----+-----+\n | | | | | | |\n | | | | | | |\n +-----------+ +-----+ +-----+-----+\n\n show cached children tiles when parent is loading\n +-------+---- +------------\n | | |\n | | |\n | | |\n +-------+---- --> |\n | | |\n */\nconst TILE_STATE_PLACEHOLDER = 3;\nconst TILE_STATE_HIDDEN = 4;\n// tiles that should be displayed in the current viewport\nconst TILE_STATE_SELECTED = 5;\n\nexport const STRATEGY_NEVER = 'never';\nexport const STRATEGY_REPLACE = 'no-overlap';\nexport const STRATEGY_DEFAULT = 'best-available';\n\nconst DEFAULT_CACHE_SCALE = 5;\n\n/**\n * Manages loading and purging of tiles data. This class caches recently visited tiles\n * and only create new tiles if they are present.\n */\n\nexport default class Tileset2D {\n /**\n * Takes in a function that returns tile data, a cache size, and a max and a min zoom level.\n * Cache size defaults to 5 * number of tiles in the current viewport\n */\n constructor(opts) {\n this.opts = opts;\n\n this.onTileLoad = tile => {\n this.opts.onTileLoad(tile);\n if (this.opts.maxCacheByteSize) {\n this._cacheByteSize += tile.byteLength;\n this._resizeCache();\n }\n };\n\n this._requestScheduler = new RequestScheduler({\n maxRequests: opts.maxRequests,\n throttleRequests: opts.maxRequests > 0\n });\n\n // Maps tile id in string {z}-{x}-{y} to a Tile object\n this._cache = new Map();\n this._tiles = [];\n this._dirty = false;\n this._cacheByteSize = 0;\n\n // Cache the last processed viewport\n this._viewport = null;\n this._selectedTiles = null;\n this._frameNumber = 0;\n\n this.setOptions(opts);\n }\n\n /* Public API */\n get tiles() {\n return this._tiles;\n }\n\n get selectedTiles() {\n return this._selectedTiles;\n }\n\n get isLoaded() {\n return this._selectedTiles.every(tile => tile.isLoaded);\n }\n\n setOptions(opts) {\n Object.assign(this.opts, opts);\n if (Number.isFinite(opts.maxZoom)) {\n this._maxZoom = Math.floor(opts.maxZoom);\n }\n if (Number.isFinite(opts.minZoom)) {\n this._minZoom = Math.ceil(opts.minZoom);\n }\n }\n\n // Clean up any outstanding tile requests.\n finalize() {\n for (const tile of this._cache.values()) {\n if (tile.isLoading) {\n tile.abort();\n }\n }\n this._cache.clear();\n this._tiles = [];\n this._selectedTiles = null;\n }\n\n reloadAll() {\n for (const tileId of this._cache.keys()) {\n const tile = this._cache.get(tileId);\n if (!this._selectedTiles.includes(tile)) {\n this._cache.delete(tileId);\n } else {\n tile.setNeedsReload();\n }\n }\n }\n\n /**\n * Update the cache with the given viewport and model matrix and triggers callback onUpdate.\n * @param {*} viewport\n * @param {*} onUpdate\n * @param {*} modelMatrix\n */\n update(viewport, {zRange, modelMatrix} = {}) {\n const modelMatrixAsMatrix4 = new Matrix4(modelMatrix);\n const isModelMatrixNew = !modelMatrixAsMatrix4.equals(this._modelMatrix);\n if (!viewport.equals(this._viewport) || isModelMatrixNew) {\n if (isModelMatrixNew) {\n this._modelMatrixInverse = modelMatrix && modelMatrixAsMatrix4.clone().invert();\n this._modelMatrix = modelMatrix && modelMatrixAsMatrix4;\n }\n this._viewport = viewport;\n const tileIndices = this.getTileIndices({\n viewport,\n maxZoom: this._maxZoom,\n minZoom: this._minZoom,\n zRange,\n modelMatrix: this._modelMatrix,\n modelMatrixInverse: this._modelMatrixInverse\n });\n this._selectedTiles = tileIndices.map(index => this._getTile(index, true));\n\n if (this._dirty) {\n // Some new tiles are added\n this._rebuildTree();\n }\n }\n\n // Update tile states\n const changed = this.updateTileStates();\n\n if (this._dirty) {\n // cache size is either the user defined maxSize or 5 * number of current tiles in the viewport.\n this._resizeCache();\n }\n\n if (changed) {\n this._frameNumber++;\n }\n\n return this._frameNumber;\n }\n\n /* Public interface for subclassing */\n\n // Returns array of {x, y, z}\n getTileIndices({viewport, maxZoom, minZoom, zRange, modelMatrix, modelMatrixInverse}) {\n const {tileSize, extent, zoomOffset} = this.opts;\n return getTileIndices({\n viewport,\n maxZoom,\n minZoom,\n zRange,\n tileSize,\n extent,\n modelMatrix,\n modelMatrixInverse,\n zoomOffset\n });\n }\n\n // Add custom metadata to tiles\n getTileMetadata({x, y, z}) {\n const {tileSize} = this.opts;\n return {bbox: tileToBoundingBox(this._viewport, x, y, z, tileSize)};\n }\n\n // Returns {x, y, z} of the parent tile\n getParentIndex(tileIndex) {\n // Perf: mutate the input object to avoid GC\n tileIndex.x = Math.floor(tileIndex.x / 2);\n tileIndex.y = Math.floor(tileIndex.y / 2);\n tileIndex.z -= 1;\n return tileIndex;\n }\n\n // Returns true if any tile's visibility changed\n updateTileStates() {\n this._updateTileStates(this.selectedTiles);\n\n const {maxRequests} = this.opts;\n\n const abortCandidates = [];\n let ongoingRequestCount = 0;\n let changed = false;\n for (const tile of this._cache.values()) {\n const isVisible = Boolean(tile.state & TILE_STATE_VISIBLE);\n if (tile.isVisible !== isVisible) {\n changed = true;\n tile.isVisible = isVisible;\n }\n\n // isSelected used in request scheduler\n tile.isSelected = tile.state === TILE_STATE_SELECTED;\n\n // Keep track of all the ongoing requests\n if (tile.isLoading) {\n ongoingRequestCount++;\n if (!tile.isSelected) {\n abortCandidates.push(tile);\n }\n }\n }\n\n if (maxRequests > 0) {\n while (ongoingRequestCount > maxRequests && abortCandidates.length > 0) {\n // There are too many ongoing requests, so abort some that are unselected\n const tile = abortCandidates.shift();\n tile.abort();\n ongoingRequestCount--;\n }\n }\n\n return changed;\n }\n\n /* Private methods */\n\n // This needs to be called every time some tiles have been added/removed from cache\n _rebuildTree() {\n const {_cache} = this;\n\n // Reset states\n for (const tile of _cache.values()) {\n tile.parent = null;\n tile.children.length = 0;\n }\n\n // Rebuild tree\n for (const tile of _cache.values()) {\n const parent = this._getNearestAncestor(tile.x, tile.y, tile.z);\n tile.parent = parent;\n if (parent) {\n parent.children.push(tile);\n }\n }\n }\n\n // A selected tile is always visible.\n // Never show two overlapping tiles.\n // If a selected tile is loading, try showing a cached ancester with the closest z\n // If a selected tile is loading, and no ancester is shown - try showing cached\n // descendants with the closest z\n _updateTileStates(selectedTiles) {\n const {_cache} = this;\n const refinementStrategy = this.opts.refinementStrategy || STRATEGY_DEFAULT;\n\n // Reset states\n for (const tile of _cache.values()) {\n tile.state = TILE_STATE_UNKNOWN;\n }\n\n // For all the selected && pending tiles:\n // - pick the closest ancestor as placeholder\n // - if no ancestor is visible, pick the closest children as placeholder\n for (const tile of selectedTiles) {\n tile.state = TILE_STATE_SELECTED;\n }\n\n if (refinementStrategy === STRATEGY_NEVER) {\n return;\n }\n for (const tile of selectedTiles) {\n getPlaceholderInAncestors(tile, refinementStrategy);\n }\n for (const tile of selectedTiles) {\n if (needsPlaceholder(tile)) {\n getPlaceholderInChildren(tile);\n }\n }\n }\n\n /**\n * Clear tiles that are not visible when the cache is full\n */\n /* eslint-disable complexity */\n _resizeCache() {\n const {_cache, opts} = this;\n\n const maxCacheSize =\n opts.maxCacheSize ||\n (opts.maxCacheByteSize ? Infinity : DEFAULT_CACHE_SCALE * this.selectedTiles.length);\n const maxCacheByteSize = opts.maxCacheByteSize || Infinity;\n\n const overflown = _cache.size > maxCacheSize || this._cacheByteSize > maxCacheByteSize;\n\n if (overflown) {\n for (const [tileId, tile] of _cache) {\n if (!tile.isVisible) {\n // delete tile\n this._cacheByteSize -= opts.maxCacheByteSize ? tile.byteLength : 0;\n _cache.delete(tileId);\n this.opts.onTileUnload(tile);\n }\n if (_cache.size <= maxCacheSize && this._cacheByteSize <= maxCacheByteSize) {\n break;\n }\n }\n this._rebuildTree();\n this._dirty = true;\n }\n if (this._dirty) {\n this._tiles = Array.from(this._cache.values())\n // sort by zoom level so that smaller tiles are displayed on top\n .sort((t1, t2) => t1.z - t2.z);\n\n this._dirty = false;\n }\n }\n /* eslint-enable complexity */\n\n _getTile({x, y, z}, create) {\n const tileId = `${x},${y},${z}`;\n let tile = this._cache.get(tileId);\n let needsReload = false;\n\n if (!tile && create) {\n tile = new Tile2DHeader({x, y, z});\n Object.assign(tile, this.getTileMetadata(tile));\n needsReload = true;\n this._cache.set(tileId, tile);\n this._dirty = true;\n } else if (tile && tile.needsReload) {\n needsReload = true;\n }\n if (needsReload) {\n tile.loadData({\n getData: this.opts.getTileData,\n requestScheduler: this._requestScheduler,\n onLoad: this.onTileLoad,\n onError: this.opts.onTileError\n });\n }\n\n return tile;\n }\n\n _getNearestAncestor(x, y, z) {\n const {_minZoom = 0} = this;\n let index = {x, y, z};\n\n while (index.z > _minZoom) {\n index = this.getParentIndex(index);\n const parent = this._getTile(index);\n if (parent) {\n return parent;\n }\n }\n return null;\n }\n}\n\n// A selected tile needs placeholder from its children if\n// - it is not loaded\n// - none of its ancestors is visible and loaded\nfunction needsPlaceholder(tile) {\n let t = tile;\n while (t) {\n if (t.state & (TILE_STATE_VISIBLE === 0)) {\n return true;\n }\n if (t.isLoaded) {\n return false;\n }\n t = t.parent;\n }\n return true;\n}\n\nfunction getPlaceholderInAncestors(tile, refinementStrategy) {\n let parent;\n let state = TILE_STATE_PLACEHOLDER;\n while ((parent = tile.parent)) {\n if (tile.isLoaded) {\n // If a tile is loaded, mark all its ancestors as hidden\n state = TILE_STATE_HIDDEN;\n if (refinementStrategy === STRATEGY_DEFAULT) {\n return;\n }\n }\n parent.state = Math.max(parent.state, state);\n tile = parent;\n }\n}\n\n// Recursively set children as placeholder\nfunction getPlaceholderInChildren(tile) {\n for (const child of tile.children) {\n child.state = Math.max(child.state, TILE_STATE_PLACEHOLDER);\n if (!child.isLoaded) {\n getPlaceholderInChildren(child);\n }\n }\n}\n","import {CompositeLayer, _flatten as flatten} from '@deck.gl/core';\nimport {GeoJsonLayer} from '@deck.gl/layers';\n\nimport Tileset2D, {STRATEGY_DEFAULT} from './tileset-2d';\nimport {urlType, getURLFromTemplate} from './utils';\n\nconst defaultProps = {\n data: [],\n dataComparator: urlType.equals,\n renderSubLayers: {type: 'function', value: props => new GeoJsonLayer(props), compare: false},\n getTileData: {type: 'function', optional: true, value: null, compare: false},\n // TODO - change to onViewportLoad to align with Tile3DLayer\n onViewportLoad: {type: 'function', optional: true, value: null, compare: false},\n onTileLoad: {type: 'function', value: tile => {}, compare: false},\n onTileUnload: {type: 'function', value: tile => {}, compare: false},\n // eslint-disable-next-line\n onTileError: {type: 'function', value: err => console.error(err), compare: false},\n extent: {type: 'array', optional: true, value: null, compare: true},\n tileSize: 512,\n maxZoom: null,\n minZoom: 0,\n maxCacheSize: null,\n maxCacheByteSize: null,\n refinementStrategy: STRATEGY_DEFAULT,\n zRange: null,\n maxRequests: 6,\n zoomOffset: 0\n};\n\nexport default class TileLayer extends CompositeLayer {\n initializeState() {\n this.state = {\n tileset: null,\n isLoaded: false\n };\n }\n\n finalizeState() {\n this.state.tileset?.finalize();\n }\n\n get isLoaded() {\n const {tileset} = this.state;\n return tileset.selectedTiles.every(\n tile => tile.isLoaded && tile.layers && tile.layers.every(layer => layer.isLoaded)\n );\n }\n\n shouldUpdateState({changeFlags}) {\n return changeFlags.somethingChanged;\n }\n\n updateState({props, changeFlags}) {\n let {tileset} = this.state;\n const propsChanged = changeFlags.propsOrDataChanged || changeFlags.updateTriggersChanged;\n const dataChanged =\n changeFlags.dataChanged ||\n (changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getTileData));\n\n if (!tileset) {\n tileset = new Tileset2D(this._getTilesetOptions(props));\n this.setState({tileset});\n } else if (propsChanged) {\n tileset.setOptions(this._getTilesetOptions(props));\n\n if (dataChanged) {\n // reload all tiles\n // use cached layers until new content is loaded\n tileset.reloadAll();\n } else {\n // some render options changed, regenerate sub layers now\n this.state.tileset.tiles.forEach(tile => {\n tile.layers = null;\n });\n }\n }\n\n this._updateTileset();\n }\n\n _getTilesetOptions(props) {\n const {\n tileSize,\n maxCacheSize,\n maxCacheByteSize,\n refinementStrategy,\n extent,\n maxZoom,\n minZoom,\n maxRequests,\n zoomOffset\n } = props;\n\n return {\n maxCacheSize,\n maxCacheByteSize,\n maxZoom,\n minZoom,\n tileSize,\n refinementStrategy,\n extent,\n maxRequests,\n zoomOffset,\n\n getTileData: this.getTileData.bind(this),\n onTileLoad: this._onTileLoad.bind(this),\n onTileError: this._onTileError.bind(this),\n onTileUnload: this._onTileUnload.bind(this)\n };\n }\n\n _updateTileset() {\n const {tileset} = this.state;\n const {zRange, modelMatrix} = this.props;\n const frameNumber = tileset.update(this.context.viewport, {zRange, modelMatrix});\n const {isLoaded} = tileset;\n\n const loadingStateChanged = this.state.isLoaded !== isLoaded;\n const tilesetChanged = this.state.frameNumber !== frameNumber;\n\n if (isLoaded && (loadingStateChanged || tilesetChanged)) {\n this._onViewportLoad();\n }\n\n if (tilesetChanged) {\n // Save the tileset frame number - trigger a rerender\n this.setState({frameNumber});\n }\n // Save the loaded state - should not trigger a rerender\n this.state.isLoaded = isLoaded;\n }\n\n _onViewportLoad() {\n const {tileset} = this.state;\n const {onViewportLoad} = this.props;\n\n if (onViewportLoad) {\n onViewportLoad(tileset.selectedTiles);\n }\n }\n\n _onTileLoad(tile) {\n this.props.onTileLoad(tile);\n tile.layers = null;\n\n if (tile.isVisible) {\n this.setNeedsUpdate();\n }\n }\n\n _onTileError(error, tile) {\n this.props.onTileError(error);\n tile.layers = null;\n\n if (tile.isVisible) {\n this.setNeedsUpdate();\n }\n }\n\n _onTileUnload(tile) {\n this.props.onTileUnload(tile);\n }\n\n // Methods for subclass to override\n\n getTileData(tile) {\n const {data, getTileData, fetch} = this.props;\n const {signal} = tile;\n\n tile.url = getURLFromTemplate(data, tile);\n\n if (getTileData) {\n return getTileData(tile);\n }\n if (tile.url) {\n return fetch(tile.url, {propName: 'data', layer: this, signal});\n }\n return null;\n }\n\n renderSubLayers(props) {\n return this.props.renderSubLayers(props);\n }\n\n getHighlightedObjectIndex() {\n return -1;\n }\n\n getPickingInfo({info, sourceLayer}) {\n info.tile = sourceLayer.props.tile;\n return info;\n }\n\n _updateAutoHighlight(info) {\n if (info.sourceLayer) {\n info.sourceLayer.updateAutoHighlight(info);\n }\n }\n\n renderLayers() {\n return this.state.tileset.tiles.map(tile => {\n const highlightedObjectIndex = this.getHighlightedObjectIndex(tile);\n // cache the rendered layer in the tile\n if (!tile.isLoaded && !tile.content) {\n // nothing to show\n } else if (!tile.layers) {\n const layers = this.renderSubLayers({\n ...this.props,\n id: `${this.id}-${tile.x}-${tile.y}-${tile.z}`,\n data: tile.content,\n _offset: 0,\n tile\n });\n tile.layers = flatten(layers, Boolean).map(layer =>\n layer.clone({\n tile,\n highlightedObjectIndex\n })\n );\n } else if (\n tile.layers[0] &&\n tile.layers[0].props.highlightedObjectIndex !== highlightedObjectIndex\n ) {\n tile.layers = tile.layers.map(layer => layer.clone({highlightedObjectIndex}));\n }\n return tile.layers;\n });\n }\n\n filterSubLayer({layer}) {\n return layer.props.tile.isVisible;\n }\n}\n\nTileLayer.layerName = 'TileLayer';\nTileLayer.defaultProps = defaultProps;\n","export default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\n// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves\n// to learn the context in which each easing should be used.\nexport var easing = {\n // This is the most common easing curve.\n easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',\n // Objects enter the screen at full velocity from off-screen and\n // slowly decelerate to a resting point.\n easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)',\n // Objects leave the screen at full velocity. They do not decelerate when off-screen.\n easeIn: 'cubic-bezier(0.4, 0, 1, 1)',\n // The sharp curve is used by objects that may return to the screen at any time.\n sharp: 'cubic-bezier(0.4, 0, 0.6, 1)'\n}; // Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations\n// to learn when use what timing\n\nexport var duration = {\n shortest: 150,\n shorter: 200,\n short: 250,\n // most basic recommended timing\n standard: 300,\n // this is to be used in complex animations\n complex: 375,\n // recommended when something is entering screen\n enteringScreen: 225,\n // recommended when something is leaving screen\n leavingScreen: 195\n};\n\nfunction formatMs(milliseconds) {\n return \"\".concat(Math.round(milliseconds), \"ms\");\n}\n/**\n * @param {string|Array} props\n * @param {object} param\n * @param {string} param.prop\n * @param {number} param.duration\n * @param {string} param.easing\n * @param {number} param.delay\n */\n\n\nexport default {\n easing: easing,\n duration: duration,\n create: function create() {\n var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['all'];\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n var _options$duration = options.duration,\n durationOption = _options$duration === void 0 ? duration.standard : _options$duration,\n _options$easing = options.easing,\n easingOption = _options$easing === void 0 ? easing.easeInOut : _options$easing,\n _options$delay = options.delay,\n delay = _options$delay === void 0 ? 0 : _options$delay,\n other = _objectWithoutProperties(options, [\"duration\", \"easing\", \"delay\"]);\n\n if (process.env.NODE_ENV !== 'production') {\n var isString = function isString(value) {\n return typeof value === 'string';\n };\n\n var isNumber = function isNumber(value) {\n return !isNaN(parseFloat(value));\n };\n\n if (!isString(props) && !Array.isArray(props)) {\n console.error('Material-UI: Argument \"props\" must be a string or Array.');\n }\n\n if (!isNumber(durationOption) && !isString(durationOption)) {\n console.error(\"Material-UI: Argument \\\"duration\\\" must be a number or a string but found \".concat(durationOption, \".\"));\n }\n\n if (!isString(easingOption)) {\n console.error('Material-UI: Argument \"easing\" must be a string.');\n }\n\n if (!isNumber(delay) && !isString(delay)) {\n console.error('Material-UI: Argument \"delay\" must be a number or a string.');\n }\n\n if (Object.keys(other).length !== 0) {\n console.error(\"Material-UI: Unrecognized argument(s) [\".concat(Object.keys(other).join(','), \"].\"));\n }\n }\n\n return (Array.isArray(props) ? props : [props]).map(function (animatedProp) {\n return \"\".concat(animatedProp, \" \").concat(typeof durationOption === 'string' ? durationOption : formatMs(durationOption), \" \").concat(easingOption, \" \").concat(typeof delay === 'string' ? delay : formatMs(delay));\n }).join(',');\n },\n getAutoHeightDuration: function getAutoHeightDuration(height) {\n if (!height) {\n return 0;\n }\n\n var constant = height / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10\n\n return Math.round((4 + 15 * Math.pow(constant, 0.25) + constant / 5) * 10);\n }\n};","export default function _asyncIterator(iterable) {\n var method;\n\n if (typeof Symbol !== \"undefined\") {\n if (Symbol.asyncIterator) {\n method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n\n if (Symbol.iterator) {\n method = iterable[Symbol.iterator];\n if (method != null) return method.call(iterable);\n }\n }\n\n throw new TypeError(\"Object is not async iterable\");\n}","import React from 'react';\nimport { isFragment } from 'react-is';\nexport default function toArray(children) {\n var ret = [];\n React.Children.forEach(children, function (child) {\n if (child === undefined || child === null) {\n return;\n }\n\n if (Array.isArray(child)) {\n ret = ret.concat(toArray(child));\n } else if (isFragment(child) && child.props) {\n ret = ret.concat(toArray(child.props.children));\n } else {\n ret.push(child);\n }\n });\n return ret;\n}","import * as React from 'react';\n/**\n * @ignore - internal component.\n */\n\nvar FormControlContext = React.createContext();\n\nif (process.env.NODE_ENV !== 'production') {\n FormControlContext.displayName = 'FormControlContext';\n}\n\nexport function useFormControl() {\n return React.useContext(FormControlContext);\n}\nexport default FormControlContext;","// Supports determination of isControlled().\n// Controlled input accepts its current value as a prop.\n//\n// @see https://facebook.github.io/react/docs/forms.html#controlled-components\n// @param value\n// @returns {boolean} true if string (including '') or number (including zero)\nexport function hasValue(value) {\n return value != null && !(Array.isArray(value) && value.length === 0);\n} // Determine if field is empty or filled.\n// Response determines if label is presented above field or as placeholder.\n//\n// @param obj\n// @param SSR\n// @returns {boolean} False when not present or empty string.\n// True when any number or string with length.\n\nexport function isFilled(obj) {\n var SSR = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n return obj && (hasValue(obj.value) && obj.value !== '' || SSR && hasValue(obj.defaultValue) && obj.defaultValue !== '');\n} // Determine if an Input is adorned on start.\n// It's corresponding to the left with LTR.\n//\n// @param obj\n// @returns {boolean} False when no adornments.\n// True when adorned at the start.\n\nexport function isAdornedStart(obj) {\n return obj.startAdornment;\n}","import {assert} from '../utils/assert';\n\nlet pathPrefix = '';\n\n/*\n * Set a relative path prefix\n */\nexport function setPathPrefix(prefix) {\n pathPrefix = prefix;\n}\n\n// Reads raw file data from:\nexport function loadFile(url, options = {}) {\n assert(typeof url === 'string');\n url = pathPrefix + url;\n const dataType = options.dataType || 'text';\n return fetch(url, options).then(res => res[dataType]());\n}\n\n/*\n * Loads images asynchronously\n * image.crossOrigin can be set via opts.crossOrigin, default to 'anonymous'\n * returns a promise tracking the load\n */\nexport function loadImage(url, opts) {\n assert(typeof url === 'string');\n url = pathPrefix + url;\n return new Promise((resolve, reject) => {\n try {\n const image = new Image();\n image.onload = () => resolve(image);\n image.onerror = () => reject(new Error(`Could not load image ${url}.`));\n image.crossOrigin = (opts && opts.crossOrigin) || 'anonymous';\n image.src = url;\n } catch (error) {\n reject(error);\n }\n });\n}\n","import GL from '@luma.gl/constants';\nimport {assertWebGLContext} from '@luma.gl/gltools';\nimport Texture from './texture';\nimport {loadImage} from '../utils/load-file';\n\nexport default class Texture2D extends Texture {\n static isSupported(gl, opts) {\n return Texture.isSupported(gl, opts);\n }\n\n constructor(gl, props = {}) {\n assertWebGLContext(gl);\n\n // Signature: new Texture2D(gl, url | Promise)\n if (props instanceof Promise || typeof props === 'string') {\n props = {data: props};\n }\n\n // Signature: new Texture2D(gl, {data: url})\n if (typeof props.data === 'string') {\n props = Object.assign({}, props, {data: loadImage(props.data)});\n }\n\n super(gl, Object.assign({}, props, {target: GL.TEXTURE_2D}));\n\n this.initialize(props);\n\n Object.seal(this);\n }\n}\n","var _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nexport var isBrowser = (typeof window === \"undefined\" ? \"undefined\" : _typeof(window)) === \"object\" && (typeof document === \"undefined\" ? \"undefined\" : _typeof(document)) === 'object' && document.nodeType === 9;\n\nexport default isBrowser;\n","import {isResponse} from '../../javascript-utils/is-type';\nimport {getResourceContentLength, getResourceUrlAndType} from './resource-utils';\n\n/**\n * Returns a Response object\n * Adds content-length header when possible\n *\n * @param resource\n */\nexport async function makeResponse(resource: any): Promise {\n if (isResponse(resource)) {\n return resource;\n }\n\n // Add content-length header if possible\n const headers: {[header: string]: string} = {};\n\n const contentLength = getResourceContentLength(resource);\n if (contentLength >= 0) {\n headers['content-length'] = String(contentLength);\n }\n\n // `new Response(File)` does not preserve content-type and URL\n // so we add them here\n const {url, type} = getResourceUrlAndType(resource);\n if (type) {\n headers['content-type'] = type;\n }\n\n // Add a custom header with initial bytes if available\n const initialDataUrl = await getInitialDataUrl(resource);\n if (initialDataUrl) {\n headers['x-first-bytes'] = initialDataUrl;\n }\n\n // TODO - is this the best way of handling strings?\n // Maybe package as data URL instead?\n if (typeof resource === 'string') {\n // Convert to ArrayBuffer to avoid Response treating it as a URL\n resource = new TextEncoder().encode(resource);\n }\n\n // Attempt to create a Response from the resource, adding headers and setting url\n const response = new Response(resource, {headers});\n // We can't control `Response.url` via constructor, use a property override to record URL.\n Object.defineProperty(response, 'url', {value: url});\n return response;\n}\n\n/**\n * Checks response status (async) and throws a helpful error message if status is not OK.\n * @param response\n */\nexport async function checkResponse(response: Response): Promise {\n if (!response.ok) {\n const message = await getResponseError(response);\n throw new Error(message);\n }\n}\n\n/**\n * Checks response status (sync) and throws a helpful error message if status is not OK.\n * @param response\n */\nexport function checkResponseSync(response: Response): void {\n if (!response.ok) {\n let message = `${response.status} ${response.statusText}`;\n message = message.length > 60 ? `${message.slice(60)}...` : message;\n throw new Error(message);\n }\n}\n\n// HELPERS\n\nasync function getResponseError(response): Promise {\n let message = `Failed to fetch resource ${response.url} (${response.status}): `;\n try {\n const contentType = response.headers.get('Content-Type');\n let text = response.statusText;\n if (contentType.includes('application/json')) {\n text += ` ${await response.text()}`;\n }\n message += text;\n message = message.length > 60 ? `${message.slice(60)}...` : message;\n } catch (error) {\n // eslint forbids return in a finally statement, so we just catch here\n }\n return message;\n}\n\nasync function getInitialDataUrl(resource): Promise {\n const INITIAL_DATA_LENGTH = 5;\n if (typeof resource === 'string') {\n return `data:,${resource.slice(0, INITIAL_DATA_LENGTH)}`;\n }\n if (resource instanceof Blob) {\n const blobSlice = resource.slice(0, 5);\n return await new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = (event) => resolve(event?.target?.result as string);\n reader.readAsDataURL(blobSlice);\n });\n }\n if (resource instanceof ArrayBuffer) {\n const slice = resource.slice(0, INITIAL_DATA_LENGTH);\n const base64 = arrayBufferToBase64(slice);\n return `data:base64,${base64}`;\n }\n return null;\n}\n\n// https://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string\nfunction arrayBufferToBase64(buffer) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n","var baseClone = require('./_baseClone');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nmodule.exports = cloneDeep;\n","var objectWithoutPropertiesLoose = require(\"./objectWithoutPropertiesLoose\");\n\nfunction _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n}\n\nmodule.exports = _objectWithoutProperties;","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\n/**\n * Similar to invariant but only logs a warning if the condition is not met.\n * This can be used to log issues in development environments in critical\n * paths. Removing the logging code for production environments will keep the\n * same logic and follow the same code paths.\n */\n\nvar __DEV__ = process.env.NODE_ENV !== 'production';\n\nvar warning = function() {};\n\nif (__DEV__) {\n var printWarning = function printWarning(format, args) {\n var len = arguments.length;\n args = new Array(len > 1 ? len - 1 : 0);\n for (var key = 1; key < len; key++) {\n args[key - 1] = arguments[key];\n }\n var argIndex = 0;\n var message = 'Warning: ' +\n format.replace(/%s/g, function() {\n return args[argIndex++];\n });\n if (typeof console !== 'undefined') {\n console.error(message);\n }\n try {\n // --- Welcome to debugging React ---\n // This error was thrown as a convenience so that you can use this stack\n // to find the callsite that caused this warning to fire.\n throw new Error(message);\n } catch (x) {}\n }\n\n warning = function(condition, format, args) {\n var len = arguments.length;\n args = new Array(len > 2 ? len - 2 : 0);\n for (var key = 2; key < len; key++) {\n args[key - 2] = arguments[key];\n }\n if (format === undefined) {\n throw new Error(\n '`warning(condition, format, ...args)` requires a warning ' +\n 'message argument'\n );\n }\n if (!condition) {\n printWarning.apply(null, [format].concat(args));\n }\n };\n}\n\nmodule.exports = warning;\n","import GL from '@luma.gl/constants';\n\n// Define local extension strings to optimize minification\n// const SRGB = 'EXT_sRGB';\n// const EXT_FLOAT_WEBGL1 = 'WEBGL_color_buffer_float';\nconst EXT_FLOAT_WEBGL2 = 'EXT_color_buffer_float';\n// const EXT_HALF_FLOAT_WEBGL1 = 'EXT_color_buffer_half_float';\n\n// NOTE(Tarek): bpp === \"bytes per pixel\", used for\n// memory usage calculations.\nexport default {\n [GL.DEPTH_COMPONENT16]: {bpp: 2}, // 16 depth bits.\n [GL.DEPTH_COMPONENT24]: {gl2: true, bpp: 3},\n [GL.DEPTH_COMPONENT32F]: {gl2: true, bpp: 4},\n\n [GL.STENCIL_INDEX8]: {bpp: 1}, // 8 stencil bits.\n\n [GL.DEPTH_STENCIL]: {bpp: 4},\n [GL.DEPTH24_STENCIL8]: {gl2: true, bpp: 4},\n [GL.DEPTH32F_STENCIL8]: {gl2: true, bpp: 5},\n\n // When using a WebGL 1 context, color renderbuffer formats are limited\n [GL.RGBA4]: {bpp: 2},\n [GL.RGB565]: {bpp: 2},\n [GL.RGB5_A1]: {bpp: 2},\n\n // When using a WebGL 2 context, the following values are available additionally:\n [GL.R8]: {gl2: true, bpp: 1},\n [GL.R8UI]: {gl2: true, bpp: 1},\n [GL.R8I]: {gl2: true, bpp: 1},\n [GL.R16UI]: {gl2: true, bpp: 2},\n [GL.R16I]: {gl2: true, bpp: 2},\n [GL.R32UI]: {gl2: true, bpp: 4},\n [GL.R32I]: {gl2: true, bpp: 4},\n [GL.RG8]: {gl2: true, bpp: 2},\n [GL.RG8UI]: {gl2: true, bpp: 2},\n [GL.RG8I]: {gl2: true, bpp: 2},\n [GL.RG16UI]: {gl2: true, bpp: 4},\n [GL.RG16I]: {gl2: true, bpp: 4},\n [GL.RG32UI]: {gl2: true, bpp: 8},\n [GL.RG32I]: {gl2: true, bpp: 8},\n [GL.RGB8]: {gl2: true, bpp: 3},\n [GL.RGBA8]: {gl2: true, bpp: 4},\n // [GL.SRGB8_ALPHA8]: {gl2: true, gl1: SRGB}, // When using the EXT_sRGB WebGL1 extension\n [GL.RGB10_A2]: {gl2: true, bpp: 4},\n [GL.RGBA8UI]: {gl2: true, bpp: 4},\n [GL.RGBA8I]: {gl2: true, bpp: 4},\n [GL.RGB10_A2UI]: {gl2: true, bpp: 4},\n [GL.RGBA16UI]: {gl2: true, bpp: 8},\n [GL.RGBA16I]: {gl2: true, bpp: 8},\n [GL.RGBA32I]: {gl2: true, bpp: 16},\n [GL.RGBA32UI]: {gl2: true, bpp: 16},\n\n // When using a WebGL 2 context and the EXT_color_buffer_float WebGL2 extension\n [GL.R16F]: {gl2: EXT_FLOAT_WEBGL2, bpp: 2},\n [GL.RG16F]: {gl2: EXT_FLOAT_WEBGL2, bpp: 4},\n [GL.RGBA16F]: {gl2: EXT_FLOAT_WEBGL2, bpp: 8},\n [GL.R32F]: {gl2: EXT_FLOAT_WEBGL2, bpp: 4},\n [GL.RG32F]: {gl2: EXT_FLOAT_WEBGL2, bpp: 8},\n // TODO - can't get WEBGL_color_buffer_float to work on renderbuffers\n [GL.RGBA32F]: {gl2: EXT_FLOAT_WEBGL2, bpp: 16},\n // [GL.RGBA32F]: {gl2: EXT_FLOAT_WEBGL2, gl1: EXT_FLOAT_WEBGL1},\n [GL.R11F_G11F_B10F]: {gl2: EXT_FLOAT_WEBGL2, bpp: 4}\n};\n","/* eslint-disable no-inline-comments */\nimport GL from '@luma.gl/constants';\nimport Resource from './resource';\nimport RENDERBUFFER_FORMATS from './renderbuffer-formats';\nimport {isWebGL2} from '@luma.gl/gltools';\nimport {assert} from '../utils/assert';\n\nfunction isFormatSupported(gl, format, formats) {\n const info = formats[format];\n if (!info) {\n return false;\n }\n const value = isWebGL2(gl) ? info.gl2 || info.gl1 : info.gl1;\n if (typeof value === 'string') {\n return gl.getExtension(value);\n }\n return value;\n}\n\nexport default class Renderbuffer extends Resource {\n static isSupported(gl, {format} = {format: null}) {\n return !format || isFormatSupported(gl, format, RENDERBUFFER_FORMATS);\n }\n\n static getSamplesForFormat(gl, {format}) {\n // Polyfilled to return [0] under WebGL1\n return gl.getInternalformatParameter(GL.RENDERBUFFER, format, GL.SAMPLES);\n }\n\n constructor(gl, opts = {}) {\n super(gl, opts);\n\n // @ts-ignore\n this.initialize(opts);\n\n Object.seal(this);\n }\n\n // Creates and initializes a renderbuffer object's data store\n initialize({format, width = 1, height = 1, samples = 0}) {\n assert(format, 'Needs format');\n\n this._trackDeallocatedMemory();\n\n this.gl.bindRenderbuffer(GL.RENDERBUFFER, this.handle);\n\n if (samples !== 0 && isWebGL2(this.gl)) {\n // @ts-ignore\n this.gl.renderbufferStorageMultisample(GL.RENDERBUFFER, samples, format, width, height);\n } else {\n this.gl.renderbufferStorage(GL.RENDERBUFFER, format, width, height);\n }\n\n // this.gl.bindRenderbuffer(GL.RENDERBUFFER, null);\n\n this.format = format;\n this.width = width;\n this.height = height;\n this.samples = samples;\n\n this._trackAllocatedMemory(\n this.width * this.height * (this.samples || 1) * RENDERBUFFER_FORMATS[this.format].bpp\n );\n\n return this;\n }\n\n resize({width, height}) {\n // Don't resize if width/height haven't changed\n if (width !== this.width || height !== this.height) {\n return this.initialize({width, height, format: this.format, samples: this.samples});\n }\n return this;\n }\n\n // PRIVATE METHODS\n _createHandle() {\n return this.gl.createRenderbuffer();\n }\n\n _deleteHandle() {\n this.gl.deleteRenderbuffer(this.handle);\n this._trackDeallocatedMemory();\n }\n\n _bindHandle(handle) {\n this.gl.bindRenderbuffer(GL.RENDERBUFFER, handle);\n }\n\n _syncHandle(handle) {\n this.format = this.getParameter(GL.RENDERBUFFER_INTERNAL_FORMAT);\n this.width = this.getParameter(GL.RENDERBUFFER_WIDTH);\n this.height = this.getParameter(GL.RENDERBUFFER_HEIGHT);\n this.samples = this.getParameter(GL.RENDERBUFFER_SAMPLES);\n }\n\n // @param {Boolean} opt.autobind=true - method call will bind/unbind object\n // @returns {GLenum|GLint} - depends on pname\n _getParameter(pname) {\n this.gl.bindRenderbuffer(GL.RENDERBUFFER, this.handle);\n const value = this.gl.getRenderbufferParameter(GL.RENDERBUFFER, pname);\n // this.gl.bindRenderbuffer(GL.RENDERBUFFER, null);\n return value;\n }\n}\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nvar react = require('react');\n\nfunction create$1(createState) {\n var state;\n var listeners = new Set();\n\n var setState = function setState(partial, replace) {\n var nextState = typeof partial === 'function' ? partial(state) : partial;\n\n if (nextState !== state) {\n var _previousState = state;\n state = replace ? nextState : Object.assign({}, state, nextState);\n listeners.forEach(function (listener) {\n return listener(state, _previousState);\n });\n }\n };\n\n var getState = function getState() {\n return state;\n };\n\n var subscribeWithSelector = function subscribeWithSelector(listener, selector, equalityFn) {\n if (selector === void 0) {\n selector = getState;\n }\n\n if (equalityFn === void 0) {\n equalityFn = Object.is;\n }\n\n var currentSlice = selector(state);\n\n function listenerToAdd() {\n var nextSlice = selector(state);\n\n if (!equalityFn(currentSlice, nextSlice)) {\n var _previousSlice = currentSlice;\n listener(currentSlice = nextSlice, _previousSlice);\n }\n }\n\n listeners.add(listenerToAdd);\n return function () {\n return listeners.delete(listenerToAdd);\n };\n };\n\n var subscribe = function subscribe(listener, selector, equalityFn) {\n if (selector || equalityFn) {\n return subscribeWithSelector(listener, selector, equalityFn);\n }\n\n listeners.add(listener);\n return function () {\n return listeners.delete(listener);\n };\n };\n\n var destroy = function destroy() {\n return listeners.clear();\n };\n\n var api = {\n setState: setState,\n getState: getState,\n subscribe: subscribe,\n destroy: destroy\n };\n state = createState(setState, getState, api);\n return api;\n}\n\nvar isSSR = typeof window === 'undefined' || !window.navigator || /ServerSideRendering|^Deno\\//.test(window.navigator.userAgent);\nvar useIsomorphicLayoutEffect = isSSR ? react.useEffect : react.useLayoutEffect;\nfunction create(createState) {\n var api = typeof createState === 'function' ? create$1(createState) : createState;\n\n var useStore = function useStore(selector, equalityFn) {\n if (selector === void 0) {\n selector = api.getState;\n }\n\n if (equalityFn === void 0) {\n equalityFn = Object.is;\n }\n\n var _ref = react.useReducer(function (c) {\n return c + 1;\n }, 0),\n forceUpdate = _ref[1];\n\n var state = api.getState();\n var stateRef = react.useRef(state);\n var selectorRef = react.useRef(selector);\n var equalityFnRef = react.useRef(equalityFn);\n var erroredRef = react.useRef(false);\n var currentSliceRef = react.useRef();\n\n if (currentSliceRef.current === undefined) {\n currentSliceRef.current = selector(state);\n }\n\n var newStateSlice;\n var hasNewStateSlice = false;\n\n if (stateRef.current !== state || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) {\n newStateSlice = selector(state);\n hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice);\n }\n\n useIsomorphicLayoutEffect(function () {\n if (hasNewStateSlice) {\n currentSliceRef.current = newStateSlice;\n }\n\n stateRef.current = state;\n selectorRef.current = selector;\n equalityFnRef.current = equalityFn;\n erroredRef.current = false;\n });\n var stateBeforeSubscriptionRef = react.useRef(state);\n useIsomorphicLayoutEffect(function () {\n var listener = function listener() {\n try {\n var nextState = api.getState();\n var nextStateSlice = selectorRef.current(nextState);\n\n if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) {\n stateRef.current = nextState;\n currentSliceRef.current = nextStateSlice;\n forceUpdate();\n }\n } catch (error) {\n erroredRef.current = true;\n forceUpdate();\n }\n };\n\n var unsubscribe = api.subscribe(listener);\n\n if (api.getState() !== stateBeforeSubscriptionRef.current) {\n listener();\n }\n\n return unsubscribe;\n }, []);\n return hasNewStateSlice ? newStateSlice : currentSliceRef.current;\n };\n\n Object.assign(useStore, api);\n\n useStore[Symbol.iterator] = function () {\n console.warn('[useStore, api] = create() is deprecated and will be removed in v4');\n var items = [useStore, api];\n return {\n next: function next() {\n var done = items.length <= 0;\n return {\n value: items.shift(),\n done: done\n };\n }\n };\n };\n\n return useStore;\n}\n\nexports['default'] = create;\n","import checkIfBrowser from '../env/is-browser';\n\nexport {self, window, global, document, process, console} from '../env/globals';\n\n// Extract injected version from package.json (injected by babel plugin)\n/* global __VERSION__ */\n// @ts-ignore\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';\n\nexport const isBrowser = checkIfBrowser();\n","/**\n * @license Fraction.js v4.0.12 09/09/2015\n * http://www.xarg.org/2014/03/rational-numbers-in-javascript/\n *\n * Copyright (c) 2015, Robert Eisele (robert@xarg.org)\n * Dual licensed under the MIT or GPL Version 2 licenses.\n **/\n\n\n/**\n *\n * This class offers the possibility to calculate fractions.\n * You can pass a fraction in different formats. Either as array, as double, as string or as an integer.\n *\n * Array/Object form\n * [ 0 => , 1 => ]\n * [ n => , d => ]\n *\n * Integer form\n * - Single integer value\n *\n * Double form\n * - Single double value\n *\n * String form\n * 123.456 - a simple double\n * 123/456 - a string fraction\n * 123.'456' - a double with repeating decimal places\n * 123.(456) - synonym\n * 123.45'6' - a double with repeating last place\n * 123.45(6) - synonym\n *\n * Example:\n *\n * var f = new Fraction(\"9.4'31'\");\n * f.mul([-4, 3]).div(4.9);\n *\n */\n\n(function(root) {\n\n \"use strict\";\n\n // Maximum search depth for cyclic rational numbers. 2000 should be more than enough.\n // Example: 1/7 = 0.(142857) has 6 repeating decimal places.\n // If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits\n var MAX_CYCLE_LEN = 2000;\n\n // Parsed data to avoid calling \"new\" all the time\n var P = {\n \"s\": 1,\n \"n\": 0,\n \"d\": 1\n };\n\n function createError(name) {\n\n function errorConstructor() {\n var temp = Error.apply(this, arguments);\n temp['name'] = this['name'] = name;\n this['stack'] = temp['stack'];\n this['message'] = temp['message'];\n }\n\n /**\n * Error constructor\n *\n * @constructor\n */\n function IntermediateInheritor() { }\n IntermediateInheritor.prototype = Error.prototype;\n errorConstructor.prototype = new IntermediateInheritor();\n\n return errorConstructor;\n }\n\n var DivisionByZero = Fraction['DivisionByZero'] = createError('DivisionByZero');\n var InvalidParameter = Fraction['InvalidParameter'] = createError('InvalidParameter');\n\n function assign(n, s) {\n\n if (isNaN(n = parseInt(n, 10))) {\n throwInvalidParam();\n }\n return n * s;\n }\n\n function throwInvalidParam() {\n throw new InvalidParameter();\n }\n\n var parse = function(p1, p2) {\n\n var n = 0, d = 1, s = 1;\n var v = 0, w = 0, x = 0, y = 1, z = 1;\n\n var A = 0, B = 1;\n var C = 1, D = 1;\n\n var N = 10000000;\n var M;\n\n if (p1 === undefined || p1 === null) {\n /* void */\n } else if (p2 !== undefined) {\n n = p1;\n d = p2;\n s = n * d;\n } else\n switch (typeof p1) {\n\n case \"object\":\n {\n if (\"d\" in p1 && \"n\" in p1) {\n n = p1[\"n\"];\n d = p1[\"d\"];\n if (\"s\" in p1)\n n *= p1[\"s\"];\n } else if (0 in p1) {\n n = p1[0];\n if (1 in p1)\n d = p1[1];\n } else {\n throwInvalidParam();\n }\n s = n * d;\n break;\n }\n case \"number\":\n {\n if (p1 < 0) {\n s = p1;\n p1 = -p1;\n }\n\n if (p1 % 1 === 0) {\n n = p1;\n } else if (p1 > 0) { // check for != 0, scale would become NaN (log(0)), which converges really slow\n\n if (p1 >= 1) {\n z = Math.pow(10, Math.floor(1 + Math.log(p1) / Math.LN10));\n p1 /= z;\n }\n\n // Using Farey Sequences\n // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation/\n\n while (B <= N && D <= N) {\n M = (A + C) / (B + D);\n\n if (p1 === M) {\n if (B + D <= N) {\n n = A + C;\n d = B + D;\n } else if (D > B) {\n n = C;\n d = D;\n } else {\n n = A;\n d = B;\n }\n break;\n\n } else {\n\n if (p1 > M) {\n A += C;\n B += D;\n } else {\n C += A;\n D += B;\n }\n\n if (B > N) {\n n = C;\n d = D;\n } else {\n n = A;\n d = B;\n }\n }\n }\n n *= z;\n } else if (isNaN(p1) || isNaN(p2)) {\n d = n = NaN;\n }\n break;\n }\n case \"string\":\n {\n B = p1.match(/\\d+|./g);\n\n if (B === null)\n throwInvalidParam();\n\n if (B[A] === '-') {// Check for minus sign at the beginning\n s = -1;\n A++;\n } else if (B[A] === '+') {// Check for plus sign at the beginning\n A++;\n }\n\n if (B.length === A + 1) { // Check if it's just a simple number \"1234\"\n w = assign(B[A++], s);\n } else if (B[A + 1] === '.' || B[A] === '.') { // Check if it's a decimal number\n\n if (B[A] !== '.') { // Handle 0.5 and .5\n v = assign(B[A++], s);\n }\n A++;\n\n // Check for decimal places\n if (A + 1 === B.length || B[A + 1] === '(' && B[A + 3] === ')' || B[A + 1] === \"'\" && B[A + 3] === \"'\") {\n w = assign(B[A], s);\n y = Math.pow(10, B[A].length);\n A++;\n }\n\n // Check for repeating places\n if (B[A] === '(' && B[A + 2] === ')' || B[A] === \"'\" && B[A + 2] === \"'\") {\n x = assign(B[A + 1], s);\n z = Math.pow(10, B[A + 1].length) - 1;\n A += 3;\n }\n\n } else if (B[A + 1] === '/' || B[A + 1] === ':') { // Check for a simple fraction \"123/456\" or \"123:456\"\n w = assign(B[A], s);\n y = assign(B[A + 2], 1);\n A += 3;\n } else if (B[A + 3] === '/' && B[A + 1] === ' ') { // Check for a complex fraction \"123 1/2\"\n v = assign(B[A], s);\n w = assign(B[A + 2], s);\n y = assign(B[A + 4], 1);\n A += 5;\n }\n\n if (B.length <= A) { // Check for more tokens on the stack\n d = y * z;\n s = /* void */\n n = x + d * v + z * w;\n break;\n }\n\n /* Fall through on error */\n }\n default:\n throwInvalidParam();\n }\n\n if (d === 0) {\n throw new DivisionByZero();\n }\n\n P[\"s\"] = s < 0 ? -1 : 1;\n P[\"n\"] = Math.abs(n);\n P[\"d\"] = Math.abs(d);\n };\n\n function modpow(b, e, m) {\n\n var r = 1;\n for (; e > 0; b = (b * b) % m, e >>= 1) {\n\n if (e & 1) {\n r = (r * b) % m;\n }\n }\n return r;\n }\n\n\n function cycleLen(n, d) {\n\n for (; d % 2 === 0;\n d /= 2) {\n }\n\n for (; d % 5 === 0;\n d /= 5) {\n }\n\n if (d === 1) // Catch non-cyclic numbers\n return 0;\n\n // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem:\n // 10^(d-1) % d == 1\n // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone,\n // as we want to translate the numbers to strings.\n\n var rem = 10 % d;\n var t = 1;\n\n for (; rem !== 1; t++) {\n rem = rem * 10 % d;\n\n if (t > MAX_CYCLE_LEN)\n return 0; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1`\n }\n return t;\n }\n\n\n function cycleStart(n, d, len) {\n\n var rem1 = 1;\n var rem2 = modpow(10, len, d);\n\n for (var t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE)\n // Solve 10^s == 10^(s+t) (mod d)\n\n if (rem1 === rem2)\n return t;\n\n rem1 = rem1 * 10 % d;\n rem2 = rem2 * 10 % d;\n }\n return 0;\n }\n\n function gcd(a, b) {\n\n if (!a)\n return b;\n if (!b)\n return a;\n\n while (1) {\n a %= b;\n if (!a)\n return b;\n b %= a;\n if (!b)\n return a;\n }\n };\n\n /**\n * Module constructor\n *\n * @constructor\n * @param {number|Fraction=} a\n * @param {number=} b\n */\n function Fraction(a, b) {\n\n if (!(this instanceof Fraction)) {\n return new Fraction(a, b);\n }\n\n parse(a, b);\n\n if (Fraction['REDUCE']) {\n a = gcd(P[\"d\"], P[\"n\"]); // Abuse a\n } else {\n a = 1;\n }\n\n this[\"s\"] = P[\"s\"];\n this[\"n\"] = P[\"n\"] / a;\n this[\"d\"] = P[\"d\"] / a;\n }\n\n /**\n * Boolean global variable to be able to disable automatic reduction of the fraction\n *\n */\n Fraction['REDUCE'] = 1;\n\n Fraction.prototype = {\n\n \"s\": 1,\n \"n\": 0,\n \"d\": 1,\n\n /**\n * Calculates the absolute value\n *\n * Ex: new Fraction(-4).abs() => 4\n **/\n \"abs\": function() {\n\n return new Fraction(this[\"n\"], this[\"d\"]);\n },\n\n /**\n * Inverts the sign of the current fraction\n *\n * Ex: new Fraction(-4).neg() => 4\n **/\n \"neg\": function() {\n\n return new Fraction(-this[\"s\"] * this[\"n\"], this[\"d\"]);\n },\n\n /**\n * Adds two rational numbers\n *\n * Ex: new Fraction({n: 2, d: 3}).add(\"14.9\") => 467 / 30\n **/\n \"add\": function(a, b) {\n\n parse(a, b);\n return new Fraction(\n this[\"s\"] * this[\"n\"] * P[\"d\"] + P[\"s\"] * this[\"d\"] * P[\"n\"],\n this[\"d\"] * P[\"d\"]\n );\n },\n\n /**\n * Subtracts two rational numbers\n *\n * Ex: new Fraction({n: 2, d: 3}).add(\"14.9\") => -427 / 30\n **/\n \"sub\": function(a, b) {\n\n parse(a, b);\n return new Fraction(\n this[\"s\"] * this[\"n\"] * P[\"d\"] - P[\"s\"] * this[\"d\"] * P[\"n\"],\n this[\"d\"] * P[\"d\"]\n );\n },\n\n /**\n * Multiplies two rational numbers\n *\n * Ex: new Fraction(\"-17.(345)\").mul(3) => 5776 / 111\n **/\n \"mul\": function(a, b) {\n\n parse(a, b);\n return new Fraction(\n this[\"s\"] * P[\"s\"] * this[\"n\"] * P[\"n\"],\n this[\"d\"] * P[\"d\"]\n );\n },\n\n /**\n * Divides two rational numbers\n *\n * Ex: new Fraction(\"-17.(345)\").inverse().div(3)\n **/\n \"div\": function(a, b) {\n\n parse(a, b);\n return new Fraction(\n this[\"s\"] * P[\"s\"] * this[\"n\"] * P[\"d\"],\n this[\"d\"] * P[\"n\"]\n );\n },\n\n /**\n * Clones the actual object\n *\n * Ex: new Fraction(\"-17.(345)\").clone()\n **/\n \"clone\": function() {\n return new Fraction(this);\n },\n\n /**\n * Calculates the modulo of two rational numbers - a more precise fmod\n *\n * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6)\n **/\n \"mod\": function(a, b) {\n\n if (isNaN(this['n']) || isNaN(this['d'])) {\n return new Fraction(NaN);\n }\n\n if (a === undefined) {\n return new Fraction(this[\"s\"] * this[\"n\"] % this[\"d\"], 1);\n }\n\n parse(a, b);\n if (0 === P[\"n\"] && 0 === this[\"d\"]) {\n Fraction(0, 0); // Throw DivisionByZero\n }\n\n /*\n * First silly attempt, kinda slow\n *\n return that[\"sub\"]({\n \"n\": num[\"n\"] * Math.floor((this.n / this.d) / (num.n / num.d)),\n \"d\": num[\"d\"],\n \"s\": this[\"s\"]\n });*/\n\n /*\n * New attempt: a1 / b1 = a2 / b2 * q + r\n * => b2 * a1 = a2 * b1 * q + b1 * b2 * r\n * => (b2 * a1 % a2 * b1) / (b1 * b2)\n */\n return new Fraction(\n this[\"s\"] * (P[\"d\"] * this[\"n\"]) % (P[\"n\"] * this[\"d\"]),\n P[\"d\"] * this[\"d\"]\n );\n },\n\n /**\n * Calculates the fractional gcd of two rational numbers\n *\n * Ex: new Fraction(5,8).gcd(3,7) => 1/56\n */\n \"gcd\": function(a, b) {\n\n parse(a, b);\n\n // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d)\n\n return new Fraction(gcd(P[\"n\"], this[\"n\"]) * gcd(P[\"d\"], this[\"d\"]), P[\"d\"] * this[\"d\"]);\n },\n\n /**\n * Calculates the fractional lcm of two rational numbers\n *\n * Ex: new Fraction(5,8).lcm(3,7) => 15\n */\n \"lcm\": function(a, b) {\n\n parse(a, b);\n\n // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d)\n\n if (P[\"n\"] === 0 && this[\"n\"] === 0) {\n return new Fraction;\n }\n return new Fraction(P[\"n\"] * this[\"n\"], gcd(P[\"n\"], this[\"n\"]) * gcd(P[\"d\"], this[\"d\"]));\n },\n\n /**\n * Calculates the ceil of a rational number\n *\n * Ex: new Fraction('4.(3)').ceil() => (5 / 1)\n **/\n \"ceil\": function(places) {\n\n places = Math.pow(10, places || 0);\n\n if (isNaN(this[\"n\"]) || isNaN(this[\"d\"])) {\n return new Fraction(NaN);\n }\n return new Fraction(Math.ceil(places * this[\"s\"] * this[\"n\"] / this[\"d\"]), places);\n },\n\n /**\n * Calculates the floor of a rational number\n *\n * Ex: new Fraction('4.(3)').floor() => (4 / 1)\n **/\n \"floor\": function(places) {\n\n places = Math.pow(10, places || 0);\n\n if (isNaN(this[\"n\"]) || isNaN(this[\"d\"])) {\n return new Fraction(NaN);\n }\n return new Fraction(Math.floor(places * this[\"s\"] * this[\"n\"] / this[\"d\"]), places);\n },\n\n /**\n * Rounds a rational numbers\n *\n * Ex: new Fraction('4.(3)').round() => (4 / 1)\n **/\n \"round\": function(places) {\n\n places = Math.pow(10, places || 0);\n\n if (isNaN(this[\"n\"]) || isNaN(this[\"d\"])) {\n return new Fraction(NaN);\n }\n return new Fraction(Math.round(places * this[\"s\"] * this[\"n\"] / this[\"d\"]), places);\n },\n\n /**\n * Gets the inverse of the fraction, means numerator and denominator are exchanged\n *\n * Ex: new Fraction([-3, 4]).inverse() => -4 / 3\n **/\n \"inverse\": function() {\n\n return new Fraction(this[\"s\"] * this[\"d\"], this[\"n\"]);\n },\n\n /**\n * Calculates the fraction to some integer exponent\n *\n * Ex: new Fraction(-1,2).pow(-3) => -8\n */\n \"pow\": function(m) {\n\n if (m < 0) {\n return new Fraction(Math.pow(this['s'] * this[\"d\"], -m), Math.pow(this[\"n\"], -m));\n } else {\n return new Fraction(Math.pow(this['s'] * this[\"n\"], m), Math.pow(this[\"d\"], m));\n }\n },\n\n /**\n * Check if two rational numbers are the same\n *\n * Ex: new Fraction(19.6).equals([98, 5]);\n **/\n \"equals\": function(a, b) {\n\n parse(a, b);\n return this[\"s\"] * this[\"n\"] * P[\"d\"] === P[\"s\"] * P[\"n\"] * this[\"d\"]; // Same as compare() === 0\n },\n\n /**\n * Check if two rational numbers are the same\n *\n * Ex: new Fraction(19.6).equals([98, 5]);\n **/\n \"compare\": function(a, b) {\n\n parse(a, b);\n var t = (this[\"s\"] * this[\"n\"] * P[\"d\"] - P[\"s\"] * P[\"n\"] * this[\"d\"]);\n return (0 < t) - (t < 0);\n },\n\n \"simplify\": function(eps) {\n\n // First naive implementation, needs improvement\n\n if (isNaN(this['n']) || isNaN(this['d'])) {\n return this;\n }\n\n var cont = this['abs']()['toContinued']();\n\n eps = eps || 0.001;\n\n function rec(a) {\n if (a.length === 1)\n return new Fraction(a[0]);\n return rec(a.slice(1))['inverse']()['add'](a[0]);\n }\n\n for (var i = 0; i < cont.length; i++) {\n var tmp = rec(cont.slice(0, i + 1));\n if (tmp['sub'](this['abs']())['abs']().valueOf() < eps) {\n return tmp['mul'](this['s']);\n }\n }\n return this;\n },\n\n /**\n * Check if two rational numbers are divisible\n *\n * Ex: new Fraction(19.6).divisible(1.5);\n */\n \"divisible\": function(a, b) {\n\n parse(a, b);\n return !(!(P[\"n\"] * this[\"d\"]) || ((this[\"n\"] * P[\"d\"]) % (P[\"n\"] * this[\"d\"])));\n },\n\n /**\n * Returns a decimal representation of the fraction\n *\n * Ex: new Fraction(\"100.'91823'\").valueOf() => 100.91823918239183\n **/\n 'valueOf': function() {\n\n return this[\"s\"] * this[\"n\"] / this[\"d\"];\n },\n\n /**\n * Returns a string-fraction representation of a Fraction object\n *\n * Ex: new Fraction(\"1.'3'\").toFraction() => \"4 1/3\"\n **/\n 'toFraction': function(excludeWhole) {\n\n var whole, str = \"\";\n var n = this[\"n\"];\n var d = this[\"d\"];\n if (this[\"s\"] < 0) {\n str += '-';\n }\n\n if (d === 1) {\n str += n;\n } else {\n\n if (excludeWhole && (whole = Math.floor(n / d)) > 0) {\n str += whole;\n str += \" \";\n n %= d;\n }\n\n str += n;\n str += '/';\n str += d;\n }\n return str;\n },\n\n /**\n * Returns a latex representation of a Fraction object\n *\n * Ex: new Fraction(\"1.'3'\").toLatex() => \"\\frac{4}{3}\"\n **/\n 'toLatex': function(excludeWhole) {\n\n var whole, str = \"\";\n var n = this[\"n\"];\n var d = this[\"d\"];\n if (this[\"s\"] < 0) {\n str += '-';\n }\n\n if (d === 1) {\n str += n;\n } else {\n\n if (excludeWhole && (whole = Math.floor(n / d)) > 0) {\n str += whole;\n n %= d;\n }\n\n str += \"\\\\frac{\";\n str += n;\n str += '}{';\n str += d;\n str += '}';\n }\n return str;\n },\n\n /**\n * Returns an array of continued fraction elements\n *\n * Ex: new Fraction(\"7/8\").toContinued() => [0,1,7]\n */\n 'toContinued': function() {\n\n var t;\n var a = this['n'];\n var b = this['d'];\n var res = [];\n\n if (isNaN(a) || isNaN(b)) {\n return res;\n }\n\n do {\n res.push(Math.floor(a / b));\n t = a % b;\n a = b;\n b = t;\n } while (a !== 1);\n\n return res;\n },\n\n /**\n * Creates a string representation of a fraction with all digits\n *\n * Ex: new Fraction(\"100.'91823'\").toString() => \"100.(91823)\"\n **/\n 'toString': function(dec) {\n\n var g;\n var N = this[\"n\"];\n var D = this[\"d\"];\n\n if (isNaN(N) || isNaN(D)) {\n return \"NaN\";\n }\n\n if (!Fraction['REDUCE']) {\n g = gcd(N, D);\n N /= g;\n D /= g;\n }\n\n dec = dec || 15; // 15 = decimal places when no repitation\n\n var cycLen = cycleLen(N, D); // Cycle length\n var cycOff = cycleStart(N, D, cycLen); // Cycle start\n\n var str = this['s'] === -1 ? \"-\" : \"\";\n\n str += N / D | 0;\n\n N %= D;\n N *= 10;\n\n if (N)\n str += \".\";\n\n if (cycLen) {\n\n for (var i = cycOff; i--;) {\n str += N / D | 0;\n N %= D;\n N *= 10;\n }\n str += \"(\";\n for (var i = cycLen; i--;) {\n str += N / D | 0;\n N %= D;\n N *= 10;\n }\n str += \")\";\n } else {\n for (var i = dec; N && i--;) {\n str += N / D | 0;\n N %= D;\n N *= 10;\n }\n }\n return str;\n }\n };\n\n if (typeof define === \"function\" && define[\"amd\"]) {\n define([], function() {\n return Fraction;\n });\n } else if (typeof exports === \"object\") {\n Object.defineProperty(Fraction, \"__esModule\", { 'value': true });\n Fraction['default'] = Fraction;\n Fraction['Fraction'] = Fraction;\n module['exports'] = Fraction;\n } else {\n root['Fraction'] = Fraction;\n }\n\n})(this);\n","/*\r\n * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license\r\n * Author: Jim Palmer (based on chunking idea from Dave Koelle)\r\n */\r\n/*jshint unused:false */\r\nmodule.exports = function naturalSort (a, b) {\r\n\t\"use strict\";\r\n\tvar re = /(^([+\\-]?(?:0|[1-9]\\d*)(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)?$|^0x[0-9a-f]+$|\\d+)/gi,\r\n\t\tsre = /(^[ ]*|[ ]*$)/g,\r\n\t\tdre = /(^([\\w ]+,?[\\w ]+)?[\\w ]+,?[\\w ]+\\d+:\\d+(:\\d+)?[\\w ]?|^\\d{1,4}[\\/\\-]\\d{1,4}[\\/\\-]\\d{1,4}|^\\w+, \\w+ \\d+, \\d{4})/,\r\n\t\thre = /^0x[0-9a-f]+$/i,\r\n\t\tore = /^0/,\r\n\t\ti = function(s) { return naturalSort.insensitive && ('' + s).toLowerCase() || '' + s; },\r\n\t\t// convert all to strings strip whitespace\r\n\t\tx = i(a).replace(sre, '') || '',\r\n\t\ty = i(b).replace(sre, '') || '',\r\n\t\t// chunk/tokenize\r\n\t\txN = x.replace(re, '\\0$1\\0').replace(/\\0$/,'').replace(/^\\0/,'').split('\\0'),\r\n\t\tyN = y.replace(re, '\\0$1\\0').replace(/\\0$/,'').replace(/^\\0/,'').split('\\0'),\r\n\t\t// numeric, hex or date detection\r\n\t\txD = parseInt(x.match(hre), 16) || (xN.length !== 1 && x.match(dre) && Date.parse(x)),\r\n\t\tyD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,\r\n\t\toFxNcL, oFyNcL;\r\n\t// first try and sort Hex codes or Dates\r\n\tif (yD) {\r\n\t\tif ( xD < yD ) { return -1; }\r\n\t\telse if ( xD > yD ) { return 1; }\r\n\t}\r\n\t// natural sorting through split numeric strings and default strings\r\n\tfor(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {\r\n\t\t// find floats not starting with '0', string or 0 if not defined (Clint Priest)\r\n\t\toFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;\r\n\t\toFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;\r\n\t\t// handle numeric vs string comparison - number < string - (Kyle Adams)\r\n\t\tif (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; }\r\n\t\t// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'\r\n\t\telse if (typeof oFxNcL !== typeof oFyNcL) {\r\n\t\t\toFxNcL += '';\r\n\t\t\toFyNcL += '';\r\n\t\t}\r\n\t\tif (oFxNcL < oFyNcL) { return -1; }\r\n\t\tif (oFxNcL > oFyNcL) { return 1; }\r\n\t}\r\n\treturn 0;\r\n};\r\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.bottom = bottom;\nexports.cloneLayout = cloneLayout;\nexports.cloneLayoutItem = cloneLayoutItem;\nexports.childrenEqual = childrenEqual;\nexports.fastPositionEqual = fastPositionEqual;\nexports.collides = collides;\nexports.compact = compact;\nexports.compactItem = compactItem;\nexports.correctBounds = correctBounds;\nexports.getLayoutItem = getLayoutItem;\nexports.getFirstCollision = getFirstCollision;\nexports.getAllCollisions = getAllCollisions;\nexports.getStatics = getStatics;\nexports.moveElement = moveElement;\nexports.moveElementAwayFromCollision = moveElementAwayFromCollision;\nexports.perc = perc;\nexports.setTransform = setTransform;\nexports.setTopLeft = setTopLeft;\nexports.sortLayoutItems = sortLayoutItems;\nexports.sortLayoutItemsByRowCol = sortLayoutItemsByRowCol;\nexports.sortLayoutItemsByColRow = sortLayoutItemsByColRow;\nexports.synchronizeLayoutWithChildren = synchronizeLayoutWithChildren;\nexports.validateLayout = validateLayout;\nexports.compactType = compactType;\nexports.autoBindHandlers = autoBindHandlers;\nexports.noop = exports.fastRGLPropsEqual = void 0;\n\nvar _lodash = _interopRequireDefault(require(\"lodash.isequal\"));\n\nvar _react = _interopRequireDefault(require(\"react\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar isProduction = process.env.NODE_ENV === \"production\";\nvar DEBUG = false;\n/**\n * Return the bottom coordinate of the layout.\n *\n * @param {Array} layout Layout array.\n * @return {Number} Bottom coordinate.\n */\n\nfunction bottom(layout\n/*: Layout*/\n)\n/*: number*/\n{\n var max = 0,\n bottomY;\n\n for (var i = 0, len = layout.length; i < len; i++) {\n bottomY = layout[i].y + layout[i].h;\n if (bottomY > max) max = bottomY;\n }\n\n return max;\n}\n\nfunction cloneLayout(layout\n/*: Layout*/\n)\n/*: Layout*/\n{\n var newLayout = Array(layout.length);\n\n for (var i = 0, len = layout.length; i < len; i++) {\n newLayout[i] = cloneLayoutItem(layout[i]);\n }\n\n return newLayout;\n} // Fast path to cloning, since this is monomorphic\n\n\nfunction cloneLayoutItem(layoutItem\n/*: LayoutItem*/\n)\n/*: LayoutItem*/\n{\n return {\n w: layoutItem.w,\n h: layoutItem.h,\n x: layoutItem.x,\n y: layoutItem.y,\n i: layoutItem.i,\n minW: layoutItem.minW,\n maxW: layoutItem.maxW,\n minH: layoutItem.minH,\n maxH: layoutItem.maxH,\n moved: Boolean(layoutItem.moved),\n static: Boolean(layoutItem.static),\n // These can be null/undefined\n isDraggable: layoutItem.isDraggable,\n isResizable: layoutItem.isResizable,\n resizeHandles: layoutItem.resizeHandles,\n isBounded: layoutItem.isBounded\n };\n}\n/**\n * Comparing React `children` is a bit difficult. This is a good way to compare them.\n * This will catch differences in keys, order, and length.\n */\n\n\nfunction childrenEqual(a\n/*: ReactChildren*/\n, b\n/*: ReactChildren*/\n)\n/*: boolean*/\n{\n return (0, _lodash.default)(_react.default.Children.map(a, function (c) {\n return c.key;\n }), _react.default.Children.map(b, function (c) {\n return c.key;\n }));\n}\n/**\n * See `fastRGLPropsEqual.js`.\n * We want this to run as fast as possible - it is called often - and to be\n * resilient to new props that we add. So rather than call lodash.isEqual,\n * which isn't suited to comparing props very well, we use this specialized\n * function in conjunction with preval to generate the fastest possible comparison\n * function, tuned for exactly our props.\n */\n\n/*:: type FastRGLPropsEqual = (Object, Object, Function) => boolean;*/\n\n\nvar fastRGLPropsEqual\n/*: FastRGLPropsEqual*/\n= require(\"./fastRGLPropsEqual\"); // Like the above, but a lot simpler.\n\n\nexports.fastRGLPropsEqual = fastRGLPropsEqual;\n\nfunction fastPositionEqual(a\n/*: Position*/\n, b\n/*: Position*/\n) {\n return a.left === b.left && a.top === b.top && a.width === b.width && a.height === b.height;\n}\n/**\n * Given two layoutitems, check if they collide.\n */\n\n\nfunction collides(l1\n/*: LayoutItem*/\n, l2\n/*: LayoutItem*/\n)\n/*: boolean*/\n{\n if (l1.i === l2.i) return false; // same element\n\n if (l1.x + l1.w <= l2.x) return false; // l1 is left of l2\n\n if (l1.x >= l2.x + l2.w) return false; // l1 is right of l2\n\n if (l1.y + l1.h <= l2.y) return false; // l1 is above l2\n\n if (l1.y >= l2.y + l2.h) return false; // l1 is below l2\n\n return true; // boxes overlap\n}\n/**\n * Given a layout, compact it. This involves going down each y coordinate and removing gaps\n * between items.\n *\n * Does not modify layout items (clones). Creates a new layout array.\n *\n * @param {Array} layout Layout.\n * @param {Boolean} verticalCompact Whether or not to compact the layout\n * vertically.\n * @return {Array} Compacted Layout.\n */\n\n\nfunction compact(layout\n/*: Layout*/\n, compactType\n/*: CompactType*/\n, cols\n/*: number*/\n)\n/*: Layout*/\n{\n // Statics go in the compareWith array right away so items flow around them.\n var compareWith = getStatics(layout); // We go through the items by row and column.\n\n var sorted = sortLayoutItems(layout, compactType); // Holding for new items.\n\n var out = Array(layout.length);\n\n for (var i = 0, len = sorted.length; i < len; i++) {\n var l = cloneLayoutItem(sorted[i]); // Don't move static elements\n\n if (!l.static) {\n l = compactItem(compareWith, l, compactType, cols, sorted); // Add to comparison array. We only collide with items before this one.\n // Statics are already in this array.\n\n compareWith.push(l);\n } // Add to output array to make sure they still come out in the right order.\n\n\n out[layout.indexOf(sorted[i])] = l; // Clear moved flag, if it exists.\n\n l.moved = false;\n }\n\n return out;\n}\n\nvar heightWidth = {\n x: \"w\",\n y: \"h\"\n};\n/**\n * Before moving item down, it will check if the movement will cause collisions and move those items down before.\n */\n\nfunction resolveCompactionCollision(layout\n/*: Layout*/\n, item\n/*: LayoutItem*/\n, moveToCoord\n/*: number*/\n, axis\n/*: \"x\" | \"y\"*/\n) {\n var sizeProp = heightWidth[axis];\n item[axis] += 1;\n var itemIndex = layout.map(function (layoutItem) {\n return layoutItem.i;\n }).indexOf(item.i); // Go through each item we collide with.\n\n for (var i = itemIndex + 1; i < layout.length; i++) {\n var otherItem = layout[i]; // Ignore static items\n\n if (otherItem.static) continue; // Optimization: we can break early if we know we're past this el\n // We can do this b/c it's a sorted layout\n\n if (otherItem.y > item.y + item.h) break;\n\n if (collides(item, otherItem)) {\n resolveCompactionCollision(layout, otherItem, moveToCoord + item[sizeProp], axis);\n }\n }\n\n item[axis] = moveToCoord;\n}\n/**\n * Compact an item in the layout.\n *\n * Modifies item.\n *\n */\n\n\nfunction compactItem(compareWith\n/*: Layout*/\n, l\n/*: LayoutItem*/\n, compactType\n/*: CompactType*/\n, cols\n/*: number*/\n, fullLayout\n/*: Layout*/\n)\n/*: LayoutItem*/\n{\n var compactV = compactType === \"vertical\";\n var compactH = compactType === \"horizontal\";\n\n if (compactV) {\n // Bottom 'y' possible is the bottom of the layout.\n // This allows you to do nice stuff like specify {y: Infinity}\n // This is here because the layout must be sorted in order to get the correct bottom `y`.\n l.y = Math.min(bottom(compareWith), l.y); // Move the element up as far as it can go without colliding.\n\n while (l.y > 0 && !getFirstCollision(compareWith, l)) {\n l.y--;\n }\n } else if (compactH) {\n l.y = Math.min(bottom(compareWith), l.y); // Move the element left as far as it can go without colliding.\n\n while (l.x > 0 && !getFirstCollision(compareWith, l)) {\n l.x--;\n }\n } // Move it down, and keep moving it down if it's colliding.\n\n\n var collides;\n\n while (collides = getFirstCollision(compareWith, l)) {\n if (compactH) {\n resolveCompactionCollision(fullLayout, l, collides.x + collides.w, \"x\");\n } else {\n resolveCompactionCollision(fullLayout, l, collides.y + collides.h, \"y\");\n } // Since we can't grow without bounds horizontally, if we've overflown, let's move it down and try again.\n\n\n if (compactH && l.x + l.w > cols) {\n l.x = cols - l.w;\n l.y++;\n }\n }\n\n return l;\n}\n/**\n * Given a layout, make sure all elements fit within its bounds.\n *\n * Modifies layout items.\n *\n * @param {Array} layout Layout array.\n * @param {Number} bounds Number of columns.\n */\n\n\nfunction correctBounds(layout\n/*: Layout*/\n, bounds\n/*: { cols: number }*/\n)\n/*: Layout*/\n{\n var collidesWith = getStatics(layout);\n\n for (var i = 0, len = layout.length; i < len; i++) {\n var l = layout[i]; // Overflows right\n\n if (l.x + l.w > bounds.cols) l.x = bounds.cols - l.w; // Overflows left\n\n if (l.x < 0) {\n l.x = 0;\n l.w = bounds.cols;\n }\n\n if (!l.static) collidesWith.push(l);else {\n // If this is static and collides with other statics, we must move it down.\n // We have to do something nicer than just letting them overlap.\n while (getFirstCollision(collidesWith, l)) {\n l.y++;\n }\n }\n }\n\n return layout;\n}\n/**\n * Get a layout item by ID. Used so we can override later on if necessary.\n *\n * @param {Array} layout Layout array.\n * @param {String} id ID\n * @return {LayoutItem} Item at ID.\n */\n\n\nfunction getLayoutItem(layout\n/*: Layout*/\n, id\n/*: string*/\n)\n/*: ?LayoutItem*/\n{\n for (var i = 0, len = layout.length; i < len; i++) {\n if (layout[i].i === id) return layout[i];\n }\n}\n/**\n * Returns the first item this layout collides with.\n * It doesn't appear to matter which order we approach this from, although\n * perhaps that is the wrong thing to do.\n *\n * @param {Object} layoutItem Layout item.\n * @return {Object|undefined} A colliding layout item, or undefined.\n */\n\n\nfunction getFirstCollision(layout\n/*: Layout*/\n, layoutItem\n/*: LayoutItem*/\n)\n/*: ?LayoutItem*/\n{\n for (var i = 0, len = layout.length; i < len; i++) {\n if (collides(layout[i], layoutItem)) return layout[i];\n }\n}\n\nfunction getAllCollisions(layout\n/*: Layout*/\n, layoutItem\n/*: LayoutItem*/\n)\n/*: Array*/\n{\n return layout.filter(function (l) {\n return collides(l, layoutItem);\n });\n}\n/**\n * Get all static elements.\n * @param {Array} layout Array of layout objects.\n * @return {Array} Array of static layout items..\n */\n\n\nfunction getStatics(layout\n/*: Layout*/\n)\n/*: Array*/\n{\n return layout.filter(function (l) {\n return l.static;\n });\n}\n/**\n * Move an element. Responsible for doing cascading movements of other elements.\n *\n * Modifies layout items.\n *\n * @param {Array} layout Full layout to modify.\n * @param {LayoutItem} l element to move.\n * @param {Number} [x] X position in grid units.\n * @param {Number} [y] Y position in grid units.\n */\n\n\nfunction moveElement(layout\n/*: Layout*/\n, l\n/*: LayoutItem*/\n, x\n/*: ?number*/\n, y\n/*: ?number*/\n, isUserAction\n/*: ?boolean*/\n, preventCollision\n/*: ?boolean*/\n, compactType\n/*: CompactType*/\n, cols\n/*: number*/\n)\n/*: Layout*/\n{\n // If this is static and not explicitly enabled as draggable,\n // no move is possible, so we can short-circuit this immediately.\n if (l.static && l.isDraggable !== true) return layout; // Short-circuit if nothing to do.\n\n if (l.y === y && l.x === x) return layout;\n log(\"Moving element \".concat(l.i, \" to [\").concat(String(x), \",\").concat(String(y), \"] from [\").concat(l.x, \",\").concat(l.y, \"]\"));\n var oldX = l.x;\n var oldY = l.y; // This is quite a bit faster than extending the object\n\n if (typeof x === \"number\") l.x = x;\n if (typeof y === \"number\") l.y = y;\n l.moved = true; // If this collides with anything, move it.\n // When doing this comparison, we have to sort the items we compare with\n // to ensure, in the case of multiple collisions, that we're getting the\n // nearest collision.\n\n var sorted = sortLayoutItems(layout, compactType);\n var movingUp = compactType === \"vertical\" && typeof y === \"number\" ? oldY >= y : compactType === \"horizontal\" && typeof x === \"number\" ? oldX >= x : false; // $FlowIgnore acceptable modification of read-only array as it was recently cloned\n\n if (movingUp) sorted = sorted.reverse();\n var collisions = getAllCollisions(sorted, l); // There was a collision; abort\n\n if (preventCollision && collisions.length) {\n log(\"Collision prevented on \".concat(l.i, \", reverting.\"));\n l.x = oldX;\n l.y = oldY;\n l.moved = false;\n return layout;\n } // Move each item that collides away from this element.\n\n\n for (var i = 0, len = collisions.length; i < len; i++) {\n var collision = collisions[i];\n log(\"Resolving collision between \".concat(l.i, \" at [\").concat(l.x, \",\").concat(l.y, \"] and \").concat(collision.i, \" at [\").concat(collision.x, \",\").concat(collision.y, \"]\")); // Short circuit so we can't infinite loop\n\n if (collision.moved) continue; // Don't move static items - we have to move *this* element away\n\n if (collision.static) {\n layout = moveElementAwayFromCollision(layout, collision, l, isUserAction, compactType, cols);\n } else {\n layout = moveElementAwayFromCollision(layout, l, collision, isUserAction, compactType, cols);\n }\n }\n\n return layout;\n}\n/**\n * This is where the magic needs to happen - given a collision, move an element away from the collision.\n * We attempt to move it up if there's room, otherwise it goes below.\n *\n * @param {Array} layout Full layout to modify.\n * @param {LayoutItem} collidesWith Layout item we're colliding with.\n * @param {LayoutItem} itemToMove Layout item we're moving.\n */\n\n\nfunction moveElementAwayFromCollision(layout\n/*: Layout*/\n, collidesWith\n/*: LayoutItem*/\n, itemToMove\n/*: LayoutItem*/\n, isUserAction\n/*: ?boolean*/\n, compactType\n/*: CompactType*/\n, cols\n/*: number*/\n)\n/*: Layout*/\n{\n var compactH = compactType === \"horizontal\"; // Compact vertically if not set to horizontal\n\n var compactV = compactType !== \"horizontal\";\n var preventCollision = collidesWith.static; // we're already colliding (not for static items)\n // If there is enough space above the collision to put this element, move it there.\n // We only do this on the main collision as this can get funky in cascades and cause\n // unwanted swapping behavior.\n\n if (isUserAction) {\n // Reset isUserAction flag because we're not in the main collision anymore.\n isUserAction = false; // Make a mock item so we don't modify the item here, only modify in moveElement.\n\n var fakeItem\n /*: LayoutItem*/\n = {\n x: compactH ? Math.max(collidesWith.x - itemToMove.w, 0) : itemToMove.x,\n y: compactV ? Math.max(collidesWith.y - itemToMove.h, 0) : itemToMove.y,\n w: itemToMove.w,\n h: itemToMove.h,\n i: \"-1\"\n }; // No collision? If so, we can go up there; otherwise, we'll end up moving down as normal\n\n if (!getFirstCollision(layout, fakeItem)) {\n log(\"Doing reverse collision on \".concat(itemToMove.i, \" up to [\").concat(fakeItem.x, \",\").concat(fakeItem.y, \"].\"));\n return moveElement(layout, itemToMove, compactH ? fakeItem.x : undefined, compactV ? fakeItem.y : undefined, isUserAction, preventCollision, compactType, cols);\n }\n }\n\n return moveElement(layout, itemToMove, compactH ? itemToMove.x + 1 : undefined, compactV ? itemToMove.y + 1 : undefined, isUserAction, preventCollision, compactType, cols);\n}\n/**\n * Helper to convert a number to a percentage string.\n *\n * @param {Number} num Any number\n * @return {String} That number as a percentage.\n */\n\n\nfunction perc(num\n/*: number*/\n)\n/*: string*/\n{\n return num * 100 + \"%\";\n}\n\nfunction setTransform(_ref)\n/*: Object*/\n{\n var top = _ref.top,\n left = _ref.left,\n width = _ref.width,\n height = _ref.height;\n // Replace unitless items with px\n var translate = \"translate(\".concat(left, \"px,\").concat(top, \"px)\");\n return {\n transform: translate,\n WebkitTransform: translate,\n MozTransform: translate,\n msTransform: translate,\n OTransform: translate,\n width: \"\".concat(width, \"px\"),\n height: \"\".concat(height, \"px\"),\n position: \"absolute\"\n };\n}\n\nfunction setTopLeft(_ref2)\n/*: Object*/\n{\n var top = _ref2.top,\n left = _ref2.left,\n width = _ref2.width,\n height = _ref2.height;\n return {\n top: \"\".concat(top, \"px\"),\n left: \"\".concat(left, \"px\"),\n width: \"\".concat(width, \"px\"),\n height: \"\".concat(height, \"px\"),\n position: \"absolute\"\n };\n}\n/**\n * Get layout items sorted from top left to right and down.\n *\n * @return {Array} Array of layout objects.\n * @return {Array} Layout, sorted static items first.\n */\n\n\nfunction sortLayoutItems(layout\n/*: Layout*/\n, compactType\n/*: CompactType*/\n)\n/*: Layout*/\n{\n if (compactType === \"horizontal\") return sortLayoutItemsByColRow(layout);else return sortLayoutItemsByRowCol(layout);\n}\n/**\n * Sort layout items by row ascending and column ascending.\n *\n * Does not modify Layout.\n */\n\n\nfunction sortLayoutItemsByRowCol(layout\n/*: Layout*/\n)\n/*: Layout*/\n{\n // Slice to clone array as sort modifies\n return layout.slice(0).sort(function (a, b) {\n if (a.y > b.y || a.y === b.y && a.x > b.x) {\n return 1;\n } else if (a.y === b.y && a.x === b.x) {\n // Without this, we can get different sort results in IE vs. Chrome/FF\n return 0;\n }\n\n return -1;\n });\n}\n/**\n * Sort layout items by column ascending then row ascending.\n *\n * Does not modify Layout.\n */\n\n\nfunction sortLayoutItemsByColRow(layout\n/*: Layout*/\n)\n/*: Layout*/\n{\n return layout.slice(0).sort(function (a, b) {\n if (a.x > b.x || a.x === b.x && a.y > b.y) {\n return 1;\n }\n\n return -1;\n });\n}\n/**\n * Generate a layout using the initialLayout and children as a template.\n * Missing entries will be added, extraneous ones will be truncated.\n *\n * Does not modify initialLayout.\n *\n * @param {Array} initialLayout Layout passed in through props.\n * @param {String} breakpoint Current responsive breakpoint.\n * @param {?String} compact Compaction option.\n * @return {Array} Working layout.\n */\n\n\nfunction synchronizeLayoutWithChildren(initialLayout\n/*: Layout*/\n, children\n/*: ReactChildren*/\n, cols\n/*: number*/\n, compactType\n/*: CompactType*/\n)\n/*: Layout*/\n{\n initialLayout = initialLayout || []; // Generate one layout item per child.\n\n var layout\n /*: LayoutItem[]*/\n = [];\n\n _react.default.Children.forEach(children, function (child\n /*: ReactElement*/\n , i\n /*: number*/\n ) {\n // Don't overwrite if it already exists.\n var exists = getLayoutItem(initialLayout, String(child.key));\n\n if (exists) {\n layout[i] = cloneLayoutItem(exists);\n } else {\n if (!isProduction && child.props._grid) {\n console.warn(\"`_grid` properties on children have been deprecated as of React 15.2. \" + // eslint-disable-line\n \"Please use `data-grid` or add your properties directly to the `layout`.\");\n }\n\n var g = child.props[\"data-grid\"] || child.props._grid; // Hey, this item has a data-grid property, use it.\n\n if (g) {\n if (!isProduction) {\n validateLayout([g], \"ReactGridLayout.children\");\n }\n\n layout[i] = cloneLayoutItem(_objectSpread(_objectSpread({}, g), {}, {\n i: child.key\n }));\n } else {\n // Nothing provided: ensure this is added to the bottom\n layout[i] = cloneLayoutItem({\n w: 1,\n h: 1,\n x: 0,\n y: bottom(layout),\n i: String(child.key)\n });\n }\n }\n }); // Correct the layout.\n\n\n var correctedLayout = correctBounds(layout, {\n cols: cols\n });\n return compact(correctedLayout, compactType, cols);\n}\n/**\n * Validate a layout. Throws errors.\n *\n * @param {Array} layout Array of layout items.\n * @param {String} [contextName] Context name for errors.\n * @throw {Error} Validation error.\n */\n\n\nfunction validateLayout(layout\n/*: Layout*/\n)\n/*: void*/\n{\n var contextName\n /*: string*/\n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"Layout\";\n var subProps = [\"x\", \"y\", \"w\", \"h\"];\n if (!Array.isArray(layout)) throw new Error(contextName + \" must be an array!\");\n\n for (var i = 0, len = layout.length; i < len; i++) {\n var item = layout[i];\n\n for (var j = 0; j < subProps.length; j++) {\n if (typeof item[subProps[j]] !== \"number\") {\n throw new Error(\"ReactGridLayout: \" + contextName + \"[\" + i + \"].\" + subProps[j] + \" must be a number!\");\n }\n }\n\n if (item.i && typeof item.i !== \"string\") {\n throw new Error(\"ReactGridLayout: \" + contextName + \"[\" + i + \"].i must be a string!\");\n }\n\n if (item.static !== undefined && typeof item.static !== \"boolean\") {\n throw new Error(\"ReactGridLayout: \" + contextName + \"[\" + i + \"].static must be a boolean!\");\n }\n }\n} // Legacy support for verticalCompact: false\n\n\nfunction compactType(props\n/*: ?{ verticalCompact: boolean, compactType: CompactType }*/\n)\n/*: CompactType*/\n{\n var _ref3 = props || {},\n verticalCompact = _ref3.verticalCompact,\n compactType = _ref3.compactType;\n\n return verticalCompact === false ? null : compactType;\n} // Flow can't really figure this out, so we just use Object\n\n\nfunction autoBindHandlers(el\n/*: Object*/\n, fns\n/*: Array*/\n)\n/*: void*/\n{\n fns.forEach(function (key) {\n return el[key] = el[key].bind(el);\n });\n}\n\nfunction log() {\n var _console;\n\n if (!DEBUG) return; // eslint-disable-next-line no-console\n\n (_console = console).log.apply(_console, arguments);\n}\n\nvar noop = function noop() {};\n\nexports.noop = noop;","'use strict';\n\n\nmodule.exports = {\n copy: copy,\n checkDataType: checkDataType,\n checkDataTypes: checkDataTypes,\n coerceToTypes: coerceToTypes,\n toHash: toHash,\n getProperty: getProperty,\n escapeQuotes: escapeQuotes,\n equal: require('fast-deep-equal'),\n ucs2length: require('./ucs2length'),\n varOccurences: varOccurences,\n varReplace: varReplace,\n cleanUpCode: cleanUpCode,\n finalCleanUpCode: finalCleanUpCode,\n schemaHasRules: schemaHasRules,\n schemaHasRulesExcept: schemaHasRulesExcept,\n schemaUnknownRules: schemaUnknownRules,\n toQuotedString: toQuotedString,\n getPathExpr: getPathExpr,\n getPath: getPath,\n getData: getData,\n unescapeFragment: unescapeFragment,\n unescapeJsonPointer: unescapeJsonPointer,\n escapeFragment: escapeFragment,\n escapeJsonPointer: escapeJsonPointer\n};\n\n\nfunction copy(o, to) {\n to = to || {};\n for (var key in o) to[key] = o[key];\n return to;\n}\n\n\nfunction checkDataType(dataType, data, negate) {\n var EQUAL = negate ? ' !== ' : ' === '\n , AND = negate ? ' || ' : ' && '\n , OK = negate ? '!' : ''\n , NOT = negate ? '' : '!';\n switch (dataType) {\n case 'null': return data + EQUAL + 'null';\n case 'array': return OK + 'Array.isArray(' + data + ')';\n case 'object': return '(' + OK + data + AND +\n 'typeof ' + data + EQUAL + '\"object\"' + AND +\n NOT + 'Array.isArray(' + data + '))';\n case 'integer': return '(typeof ' + data + EQUAL + '\"number\"' + AND +\n NOT + '(' + data + ' % 1)' +\n AND + data + EQUAL + data + ')';\n default: return 'typeof ' + data + EQUAL + '\"' + dataType + '\"';\n }\n}\n\n\nfunction checkDataTypes(dataTypes, data) {\n switch (dataTypes.length) {\n case 1: return checkDataType(dataTypes[0], data, true);\n default:\n var code = '';\n var types = toHash(dataTypes);\n if (types.array && types.object) {\n code = types.null ? '(': '(!' + data + ' || ';\n code += 'typeof ' + data + ' !== \"object\")';\n delete types.null;\n delete types.array;\n delete types.object;\n }\n if (types.number) delete types.integer;\n for (var t in types)\n code += (code ? ' && ' : '' ) + checkDataType(t, data, true);\n\n return code;\n }\n}\n\n\nvar COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);\nfunction coerceToTypes(optionCoerceTypes, dataTypes) {\n if (Array.isArray(dataTypes)) {\n var types = [];\n for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);\n return paths[lvl - up];\n }\n\n if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);\n data = 'data' + ((lvl - up) || '');\n if (!jsonPointer) return data;\n }\n\n var expr = data;\n var segments = jsonPointer.split('/');\n for (var i=0; i coord[0]) {\n result[0] = coord[0];\n }\n if (result[1] > coord[1]) {\n result[1] = coord[1];\n }\n if (result[2] < coord[0]) {\n result[2] = coord[0];\n }\n if (result[3] < coord[1]) {\n result[3] = coord[1];\n }\n });\n return result;\n}\nexports.default = bbox;\n","const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst src = exports.src = []\nconst t = exports.t = {}\nlet R = 0\n\nconst createToken = (name, value, isGlobal) => {\n const index = R++\n debug(index, value)\n t[name] = index\n src[index] = value\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*')\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCE', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\.0\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\.0\\.0-0\\\\s*$')\n","const {MAX_LENGTH} = require('../internal/constants')\nconst { re, t } = require('../internal/re')\nconst SemVer = require('../classes/semver')\n\nconst parseOptions = require('../internal/parse-options')\nconst parse = (version, options) => {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n if (version.length > MAX_LENGTH) {\n return null\n }\n\n const r = options.loose ? re[t.LOOSE] : re[t.FULL]\n if (!r.test(version)) {\n return null\n }\n\n try {\n return new SemVer(version, options)\n } catch (er) {\n return null\n }\n}\n\nmodule.exports = parse\n","/**\n * @module helpers\n */\n/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n *\n * @memberof helpers\n * @type {number}\n */\nexport var earthRadius = 6371008.8;\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var factors = {\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n degrees: earthRadius / 111325,\n feet: earthRadius * 3.28084,\n inches: earthRadius * 39.37,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n meters: earthRadius,\n metres: earthRadius,\n miles: earthRadius / 1609.344,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n nauticalmiles: earthRadius / 1852,\n radians: 1,\n yards: earthRadius * 1.0936,\n};\n/**\n * Units of measurement factors based on 1 meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var unitsFactors = {\n centimeters: 100,\n centimetres: 100,\n degrees: 1 / 111325,\n feet: 3.28084,\n inches: 39.37,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n meters: 1,\n metres: 1,\n miles: 1 / 1609.344,\n millimeters: 1000,\n millimetres: 1000,\n nauticalmiles: 1 / 1852,\n radians: 1 / earthRadius,\n yards: 1.0936133,\n};\n/**\n * Area of measurement factors based on 1 square meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var areaFactors = {\n acres: 0.000247105,\n centimeters: 10000,\n centimetres: 10000,\n feet: 10.763910417,\n hectares: 0.0001,\n inches: 1550.003100006,\n kilometers: 0.000001,\n kilometres: 0.000001,\n meters: 1,\n metres: 1,\n miles: 3.86e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nexport function feature(geom, properties, options) {\n if (options === void 0) { options = {}; }\n var feat = { type: \"Feature\" };\n if (options.id === 0 || options.id) {\n feat.id = options.id;\n }\n if (options.bbox) {\n feat.bbox = options.bbox;\n }\n feat.properties = properties || {};\n feat.geometry = geom;\n return feat;\n}\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = \"Point\";\n * var coordinates = [110, 50];\n * var geometry = turf.geometry(type, coordinates);\n * // => geometry\n */\nexport function geometry(type, coordinates, _options) {\n if (_options === void 0) { _options = {}; }\n switch (type) {\n case \"Point\":\n return point(coordinates).geometry;\n case \"LineString\":\n return lineString(coordinates).geometry;\n case \"Polygon\":\n return polygon(coordinates).geometry;\n case \"MultiPoint\":\n return multiPoint(coordinates).geometry;\n case \"MultiLineString\":\n return multiLineString(coordinates).geometry;\n case \"MultiPolygon\":\n return multiPolygon(coordinates).geometry;\n default:\n throw new Error(type + \" is invalid\");\n }\n}\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nexport function point(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (!coordinates) {\n throw new Error(\"coordinates is required\");\n }\n if (!Array.isArray(coordinates)) {\n throw new Error(\"coordinates must be an Array\");\n }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be at least 2 numbers long\");\n }\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {\n throw new Error(\"coordinates must contain numbers\");\n }\n var geom = {\n type: \"Point\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nexport function points(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nexport function polygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {\n var ring = coordinates_1[_i];\n if (ring.length < 4) {\n throw new Error(\"Each LinearRing of a Polygon must have 4 or more Positions.\");\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n }\n }\n var geom = {\n type: \"Polygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nexport function polygons(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nexport function lineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n var geom = {\n type: \"LineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nexport function lineStrings(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nexport function featureCollection(features, options) {\n if (options === void 0) { options = {}; }\n var fc = { type: \"FeatureCollection\" };\n if (options.id) {\n fc.id = options.id;\n }\n if (options.bbox) {\n fc.bbox = options.bbox;\n }\n fc.features = features;\n return fc;\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nexport function multiLineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiLineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nexport function multiPoint(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPoint\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nexport function multiPolygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPolygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = turf.geometry(\"Point\", [100, 0]);\n * var line = turf.geometry(\"LineString\", [[101, 0], [102, 1]]);\n * var collection = turf.geometryCollection([pt, line]);\n *\n * // => collection\n */\nexport function geometryCollection(geometries, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"GeometryCollection\",\n geometries: geometries,\n };\n return feature(geom, properties, options);\n}\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nexport function round(num, precision) {\n if (precision === void 0) { precision = 0; }\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nexport function radiansToLength(radians, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return radians * factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nexport function lengthToRadians(distance, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return distance / factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nexport function lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nexport function bearingToAzimuth(bearing) {\n var angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nexport function radiansToDegrees(radians) {\n var degrees = radians % (2 * Math.PI);\n return (degrees * 180) / Math.PI;\n}\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nexport function degreesToRadians(degrees) {\n var radians = degrees % 360;\n return (radians * Math.PI) / 180;\n}\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] of the length\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted length\n */\nexport function convertLength(length, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"kilometers\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(length >= 0)) {\n throw new Error(\"length must be a positive number\");\n }\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);\n}\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches, hectares\n * @param {number} area to be converted\n * @param {Units} [originalUnit=\"meters\"] of the distance\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted area\n */\nexport function convertArea(area, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"meters\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n var startFactor = areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n var finalFactor = areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n return (area / startFactor) * finalFactor;\n}\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nexport function isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nexport function isObject(input) {\n return !!input && input.constructor === Object;\n}\n/**\n * Validate BBox\n *\n * @private\n * @param {Array} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nexport function validateBBox(bbox) {\n if (!bbox) {\n throw new Error(\"bbox is required\");\n }\n if (!Array.isArray(bbox)) {\n throw new Error(\"bbox must be an Array\");\n }\n if (bbox.length !== 4 && bbox.length !== 6) {\n throw new Error(\"bbox must be an Array of 4 or 6 numbers\");\n }\n bbox.forEach(function (num) {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nexport function validateId(id) {\n if (!id) {\n throw new Error(\"id is required\");\n }\n if ([\"string\", \"number\"].indexOf(typeof id) === -1) {\n throw new Error(\"id must be a number or a string\");\n }\n}\n","import { polygon } from \"@turf/helpers\";\n/**\n * Takes a bbox and returns an equivalent {@link Polygon|polygon}.\n *\n * @name bboxPolygon\n * @param {BBox} bbox extent in [minX, minY, maxX, maxY] order\n * @param {Object} [options={}] Optional parameters\n * @param {Properties} [options.properties={}] Translate properties to Polygon\n * @param {string|number} [options.id={}] Translate Id to Polygon\n * @returns {Feature} a Polygon representation of the bounding box\n * @example\n * var bbox = [0, 0, 10, 10];\n *\n * var poly = turf.bboxPolygon(bbox);\n *\n * //addToMap\n * var addToMap = [poly]\n */\nexport default function bboxPolygon(bbox, options) {\n if (options === void 0) { options = {}; }\n // Convert BBox positions to Numbers\n // No performance loss for including Number()\n // https://github.com/Turfjs/turf/issues/1119\n var west = Number(bbox[0]);\n var south = Number(bbox[1]);\n var east = Number(bbox[2]);\n var north = Number(bbox[3]);\n if (bbox.length === 6) {\n throw new Error(\"@turf/bbox-polygon does not support BBox with 6 positions\");\n }\n var lowLeft = [west, south];\n var topLeft = [west, north];\n var topRight = [east, north];\n var lowRight = [east, south];\n return polygon([[lowLeft, lowRight, topRight, topLeft, lowLeft]], options.properties, { bbox: bbox, id: options.id });\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// View and Projection Matrix calculations for mapbox-js style\n// map view properties\nimport Viewport from './viewport';\n\nimport {\n pixelsToWorld,\n getViewMatrix,\n addMetersToLngLat,\n getProjectionParameters,\n altitudeToFovy,\n fovyToAltitude,\n fitBounds,\n getBounds\n} from '@math.gl/web-mercator';\n\n// TODO - import from math.gl\nimport * as vec2 from 'gl-matrix/vec2';\nimport {Matrix4} from 'math.gl';\n\nconst TILE_SIZE = 512;\nconst EARTH_CIRCUMFERENCE = 40.03e6;\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\nfunction unitsPerMeter(latitude) {\n const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);\n return TILE_SIZE / EARTH_CIRCUMFERENCE / latCosine;\n}\n\nexport default class WebMercatorViewport extends Viewport {\n /**\n * @classdesc\n * Creates view/projection matrices from mercator params\n * Note: The Viewport is immutable in the sense that it only has accessors.\n * A new viewport instance should be created if any parameters have changed.\n */\n /* eslint-disable complexity, max-statements */\n constructor(opts = {}) {\n const {\n latitude = 0,\n longitude = 0,\n zoom = 11,\n pitch = 0,\n bearing = 0,\n nearZMultiplier = 0.1,\n farZMultiplier = 1.01,\n orthographic = false,\n projectionMatrix,\n\n repeat = false,\n worldOffset = 0,\n\n // backward compatibility\n // TODO: remove in v9\n legacyMeterSizes = false\n } = opts;\n\n let {width, height, altitude = 1.5} = opts;\n const scale = Math.pow(2, zoom);\n\n // Silently allow apps to send in 0,0 to facilitate isomorphic render etc\n width = width || 1;\n height = height || 1;\n\n let fovy;\n let projectionParameters = null;\n if (projectionMatrix) {\n altitude = projectionMatrix[5] / 2;\n fovy = altitudeToFovy(altitude);\n } else {\n if (opts.fovy) {\n fovy = opts.fovy;\n altitude = fovyToAltitude(fovy);\n } else {\n fovy = altitudeToFovy(altitude);\n }\n projectionParameters = getProjectionParameters({\n width,\n height,\n pitch,\n fovy,\n nearZMultiplier,\n farZMultiplier\n });\n }\n\n // The uncentered matrix allows us two move the center addition to the\n // shader (cheap) which gives a coordinate system that has its center in\n // the layer's center position. This makes rotations and other modelMatrx\n // transforms much more useful.\n let viewMatrixUncentered = getViewMatrix({\n height,\n pitch,\n bearing,\n scale,\n altitude\n });\n\n if (worldOffset) {\n const viewOffset = new Matrix4().translate([512 * worldOffset, 0, 0]);\n viewMatrixUncentered = viewOffset.multiplyLeft(viewMatrixUncentered);\n }\n\n super({\n ...opts,\n // x, y,\n width,\n height,\n\n // view matrix\n viewMatrix: viewMatrixUncentered,\n longitude,\n latitude,\n zoom,\n\n // projection matrix parameters\n ...projectionParameters,\n fovy,\n focalDistance: altitude\n });\n\n // Save parameters\n this.latitude = latitude;\n this.longitude = longitude;\n this.zoom = zoom;\n this.pitch = pitch;\n this.bearing = bearing;\n this.altitude = altitude;\n this.fovy = fovy;\n\n this.orthographic = orthographic;\n\n this._subViewports = repeat ? [] : null;\n this._pseudoMeters = legacyMeterSizes;\n\n Object.freeze(this);\n }\n /* eslint-enable complexity, max-statements */\n\n get subViewports() {\n if (this._subViewports && !this._subViewports.length) {\n // Cache sub viewports so that we only calculate them once\n const bounds = this.getBounds();\n\n const minOffset = Math.floor((bounds[0] + 180) / 360);\n const maxOffset = Math.ceil((bounds[2] - 180) / 360);\n\n for (let x = minOffset; x <= maxOffset; x++) {\n const offsetViewport = x\n ? new WebMercatorViewport({\n ...this,\n worldOffset: x\n })\n : this;\n this._subViewports.push(offsetViewport);\n }\n }\n return this._subViewports;\n }\n\n projectPosition(xyz) {\n if (this._pseudoMeters) {\n // Backward compatibility\n return super.projectPosition(xyz);\n }\n const [X, Y] = this.projectFlat(xyz);\n const Z = (xyz[2] || 0) * unitsPerMeter(xyz[1]);\n return [X, Y, Z];\n }\n\n unprojectPosition(xyz) {\n if (this._pseudoMeters) {\n // Backward compatibility\n return super.unprojectPosition(xyz);\n }\n const [X, Y] = this.unprojectFlat(xyz);\n const Z = (xyz[2] || 0) / unitsPerMeter(Y);\n return [X, Y, Z];\n }\n\n /**\n * Add a meter delta to a base lnglat coordinate, returning a new lnglat array\n *\n * Note: Uses simple linear approximation around the viewport center\n * Error increases with size of offset (roughly 1% per 100km)\n *\n * @param {[Number,Number]|[Number,Number,Number]) lngLatZ - base coordinate\n * @param {[Number,Number]|[Number,Number,Number]) xyz - array of meter deltas\n * @return {[Number,Number]|[Number,Number,Number]) array of [lng,lat,z] deltas\n */\n addMetersToLngLat(lngLatZ, xyz) {\n return addMetersToLngLat(lngLatZ, xyz);\n }\n\n panByPosition(coords, pixel) {\n const fromLocation = pixelsToWorld(pixel, this.pixelUnprojectionMatrix);\n const toLocation = this.projectFlat(coords);\n\n const translate = vec2.add([], toLocation, vec2.negate([], fromLocation));\n const newCenter = vec2.add([], this.center, translate);\n\n const [longitude, latitude] = this.unprojectFlat(newCenter);\n return {longitude, latitude};\n }\n\n getBounds(options = {}) {\n const corners = getBounds(this, options.z || 0);\n\n return [\n Math.min(corners[0][0], corners[1][0], corners[2][0], corners[3][0]),\n Math.min(corners[0][1], corners[1][1], corners[2][1], corners[3][1]),\n Math.max(corners[0][0], corners[1][0], corners[2][0], corners[3][0]),\n Math.max(corners[0][1], corners[1][1], corners[2][1], corners[3][1])\n ];\n }\n\n /**\n * Returns a new viewport that fit around the given rectangle.\n * Only supports non-perspective mode.\n * @param {Array} bounds - [[lon, lat], [lon, lat]]\n * @param {Number} [options.padding] - The amount of padding in pixels to add to the given bounds.\n * @param {Array} [options.offset] - The center of the given bounds relative to the map's center,\n * [x, y] measured in pixels.\n * @returns {WebMercatorViewport}\n */\n fitBounds(bounds, options = {}) {\n const {width, height} = this;\n const {longitude, latitude, zoom} = fitBounds({width, height, bounds, ...options});\n return new WebMercatorViewport({width, height, longitude, latitude, zoom});\n }\n}\n\nWebMercatorViewport.displayName = 'WebMercatorViewport';\n","import {clamp} from 'math.gl';\nimport Controller from './controller';\nimport ViewState from './view-state';\nimport {mod} from '../utils/math-utils';\n\nconst DEFAULT_STATE = {\n rotationX: 0,\n rotationOrbit: 0,\n zoom: 0,\n target: [0, 0, 0],\n minRotationX: -90,\n maxRotationX: 90,\n minZoom: -Infinity,\n maxZoom: Infinity\n};\n\n/* Helpers */\n\nexport class OrbitState extends ViewState {\n constructor({\n makeViewport,\n\n /* Viewport arguments */\n width, // Width of viewport\n height, // Height of viewport\n rotationX = DEFAULT_STATE.rotationX, // Rotation around x axis\n rotationOrbit = DEFAULT_STATE.rotationOrbit, // Rotation around orbit axis\n target = DEFAULT_STATE.target,\n zoom = DEFAULT_STATE.zoom,\n\n /* Viewport constraints */\n minRotationX = DEFAULT_STATE.minRotationX,\n maxRotationX = DEFAULT_STATE.maxRotationX,\n minZoom = DEFAULT_STATE.minZoom,\n maxZoom = DEFAULT_STATE.maxZoom,\n\n /** Interaction states, required to calculate change during transform */\n // Model state when the pan operation first started\n startPanPosition,\n // Model state when the rotate operation first started\n startRotatePos,\n startRotationX,\n startRotationOrbit,\n // Model state when the zoom operation first started\n startZoomPosition,\n startZoom\n }) {\n super({\n width,\n height,\n rotationX,\n rotationOrbit,\n target,\n zoom,\n minRotationX,\n maxRotationX,\n minZoom,\n maxZoom\n });\n\n this._state = {\n startPanPosition,\n startRotatePos,\n startRotationX,\n startRotationOrbit,\n startZoomPosition,\n startZoom\n };\n\n this.makeViewport = makeViewport;\n }\n\n /**\n * Start panning\n * @param {[Number, Number]} pos - position on screen where the pointer grabs\n */\n panStart({pos}) {\n return this._getUpdatedState({\n startPanPosition: this._unproject(pos)\n });\n }\n\n /**\n * Pan\n * @param {[Number, Number]} pos - position on screen where the pointer is\n */\n pan({pos, startPosition}) {\n const startPanPosition = this._state.startPanPosition || startPosition;\n\n if (!startPanPosition) {\n return this;\n }\n\n const viewport = this.makeViewport(this._viewportProps);\n const newProps = viewport.panByPosition(startPanPosition, pos);\n\n return this._getUpdatedState(newProps);\n }\n\n /**\n * End panning\n * Must call if `panStart()` was called\n */\n panEnd() {\n return this._getUpdatedState({\n startPanPosition: null\n });\n }\n\n /**\n * Start rotating\n * @param {[Number, Number]} pos - position on screen where the pointer grabs\n */\n rotateStart({pos}) {\n return this._getUpdatedState({\n startRotatePos: pos,\n startRotationX: this._viewportProps.rotationX,\n startRotationOrbit: this._viewportProps.rotationOrbit\n });\n }\n\n /**\n * Rotate\n * @param {[Number, Number]} pos - position on screen where the pointer is\n */\n rotate({pos, deltaAngleX = 0, deltaAngleY = 0}) {\n const {startRotatePos, startRotationX, startRotationOrbit} = this._state;\n const {width, height} = this._viewportProps;\n\n if (\n !startRotatePos ||\n !Number.isFinite(startRotationX) ||\n !Number.isFinite(startRotationOrbit)\n ) {\n return this;\n }\n\n let newRotation;\n if (pos) {\n let deltaScaleX = (pos[0] - startRotatePos[0]) / width;\n const deltaScaleY = (pos[1] - startRotatePos[1]) / height;\n\n if (startRotationX < -90 || startRotationX > 90) {\n // When looking at the \"back\" side of the scene, invert horizontal drag\n // so that the camera movement follows user input\n deltaScaleX *= -1;\n }\n newRotation = {\n rotationX: startRotationX + deltaScaleY * 180,\n rotationOrbit: startRotationOrbit + deltaScaleX * 180\n };\n } else {\n newRotation = {\n rotationX: startRotationX + deltaAngleY,\n rotationOrbit: startRotationOrbit + deltaAngleX\n };\n }\n\n return this._getUpdatedState(newRotation);\n }\n\n /**\n * End rotating\n * Must call if `rotateStart()` was called\n */\n rotateEnd() {\n return this._getUpdatedState({\n startRotationX: null,\n startRotationOrbit: null\n });\n }\n\n // shortest path between two view states\n shortestPathFrom(viewState) {\n const fromProps = viewState.getViewportProps();\n const props = {...this._viewportProps};\n const {rotationOrbit} = props;\n\n if (Math.abs(rotationOrbit - fromProps.rotationOrbit) > 180) {\n props.rotationOrbit = rotationOrbit < 0 ? rotationOrbit + 360 : rotationOrbit - 360;\n }\n\n return props;\n }\n\n /**\n * Start zooming\n * @param {[Number, Number]} pos - position on screen where the pointer grabs\n */\n zoomStart({pos}) {\n return this._getUpdatedState({\n startZoomPosition: this._unproject(pos),\n startZoom: this._viewportProps.zoom\n });\n }\n\n /**\n * Zoom\n * @param {[Number, Number]} pos - position on screen where the current target is\n * @param {[Number, Number]} startPos - the target position at\n * the start of the operation. Must be supplied of `zoomStart()` was not called\n * @param {Number} scale - a number between [0, 1] specifying the accumulated\n * relative scale.\n */\n zoom({pos, startPos, scale}) {\n const {zoom} = this._viewportProps;\n let {startZoom, startZoomPosition} = this._state;\n if (!Number.isFinite(startZoom)) {\n // We have two modes of zoom:\n // scroll zoom that are discrete events (transform from the current zoom level),\n // and pinch zoom that are continuous events (transform from the zoom level when\n // pinch started).\n // If startZoom state is defined, then use the startZoom state;\n // otherwise assume discrete zooming\n startZoom = zoom;\n startZoomPosition = this._unproject(startPos) || this._unproject(pos);\n }\n\n const newZoom = this._calculateNewZoom({scale, startZoom});\n const zoomedViewport = this.makeViewport({...this._viewportProps, zoom: newZoom});\n\n return this._getUpdatedState({\n zoom: newZoom,\n ...zoomedViewport.panByPosition(startZoomPosition, pos)\n });\n }\n\n /**\n * End zooming\n * Must call if `zoomStart()` was called\n */\n zoomEnd() {\n return this._getUpdatedState({\n startZoomPosition: null,\n startZoom: null\n });\n }\n\n zoomIn(speed = 2) {\n return this._getUpdatedState({\n zoom: this._calculateNewZoom({scale: speed})\n });\n }\n\n zoomOut(speed = 2) {\n return this._getUpdatedState({\n zoom: this._calculateNewZoom({scale: 1 / speed})\n });\n }\n\n moveLeft(speed = 50) {\n return this._panFromCenter([-speed, 0]);\n }\n\n moveRight(speed = 50) {\n return this._panFromCenter([speed, 0]);\n }\n\n moveUp(speed = 50) {\n return this._panFromCenter([0, -speed]);\n }\n\n moveDown(speed = 50) {\n return this._panFromCenter([0, speed]);\n }\n\n rotateLeft(speed = 15) {\n return this._getUpdatedState({\n rotationOrbit: this._viewportProps.rotationOrbit - speed\n });\n }\n\n rotateRight(speed = 15) {\n return this._getUpdatedState({\n rotationOrbit: this._viewportProps.rotationOrbit + speed\n });\n }\n\n rotateUp(speed = 10) {\n return this._getUpdatedState({\n rotationX: this._viewportProps.rotationX - speed\n });\n }\n\n rotateDown(speed = 10) {\n return this._getUpdatedState({\n rotationX: this._viewportProps.rotationX + speed\n });\n }\n\n /* Private methods */\n\n _unproject(pos) {\n const viewport = this.makeViewport(this._viewportProps);\n return pos && viewport.unproject(pos);\n }\n\n // Calculates new zoom\n _calculateNewZoom({scale, startZoom}) {\n const {maxZoom, minZoom} = this._viewportProps;\n if (!Number.isFinite(startZoom)) {\n startZoom = this._viewportProps.zoom;\n }\n const zoom = startZoom + Math.log2(scale);\n return clamp(zoom, minZoom, maxZoom);\n }\n\n _panFromCenter(offset) {\n const {width, height, target} = this._viewportProps;\n return this.pan({\n startPosition: target,\n pos: [width / 2 + offset[0], height / 2 + offset[1]]\n });\n }\n\n _getUpdatedState(newProps) {\n // Update _viewportProps\n return new this.constructor({...this._viewportProps, ...this._state, ...newProps});\n }\n\n // Apply any constraints (mathematical or defined by _viewportProps) to map state\n _applyConstraints(props) {\n // Ensure zoom is within specified range\n const {maxZoom, minZoom, zoom, maxRotationX, minRotationX, rotationOrbit} = props;\n\n props.zoom = clamp(zoom, minZoom, maxZoom);\n props.rotationX = clamp(props.rotationX, minRotationX, maxRotationX);\n if (rotationOrbit < -180 || rotationOrbit > 180) {\n props.rotationOrbit = mod(rotationOrbit + 180, 360) - 180;\n }\n\n return props;\n }\n}\n\nexport default class OrbitController extends Controller {\n constructor(props) {\n super(OrbitState, props);\n }\n\n get linearTransitionProps() {\n return ['target', 'zoom', 'rotationX', 'rotationOrbit'];\n }\n}\n","import {equals} from 'math.gl';\nimport assert from '../utils/assert';\n\nexport default class TransitionInterpolator {\n /**\n * @param opts {array|object}\n * @param opts.compare {array} - prop names used in equality check\n * @param opts.extract {array} - prop names needed for interpolation\n * @param opts.required {array} - prop names that must be supplied\n * alternatively, supply one list of prop names as `opts` if all of the above are the same.\n */\n constructor(opts = {}) {\n if (Array.isArray(opts)) {\n opts = {\n compare: opts,\n extract: opts,\n required: opts\n };\n }\n const {compare, extract, required} = opts;\n\n this._propsToCompare = compare;\n this._propsToExtract = extract;\n this._requiredProps = required;\n }\n\n /**\n * Checks if two sets of props need transition in between\n * @param currentProps {object} - a list of viewport props\n * @param nextProps {object} - a list of viewport props\n * @returns {bool} - true if two props are equivalent\n */\n arePropsEqual(currentProps, nextProps) {\n for (const key of this._propsToCompare || Object.keys(nextProps)) {\n if (\n !(key in currentProps) ||\n !(key in nextProps) ||\n !equals(currentProps[key], nextProps[key])\n ) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Called before transition starts to validate/pre-process start and end props\n * @param startProps {object} - a list of starting viewport props\n * @param endProps {object} - a list of target viewport props\n * @returns {Object} {start, end} - start and end props to be passed\n * to `interpolateProps`\n */\n initializeProps(startProps, endProps) {\n let result;\n\n if (this._propsToExtract) {\n const startViewStateProps = {};\n const endViewStateProps = {};\n\n for (const key of this._propsToExtract) {\n startViewStateProps[key] = startProps[key];\n endViewStateProps[key] = endProps[key];\n }\n result = {start: startViewStateProps, end: endViewStateProps};\n } else {\n result = {start: startProps, end: endProps};\n }\n\n this._checkRequiredProps(result.start);\n this._checkRequiredProps(result.end);\n\n return result;\n }\n\n /**\n * Returns viewport props in transition\n * @param startProps {object} - a list of starting viewport props\n * @param endProps {object} - a list of target viewport props\n * @param t {number} - a time factor between [0, 1]\n * @returns {object} - a list of interpolated viewport props\n */\n interpolateProps(startProps, endProps, t) {\n return endProps;\n }\n\n /**\n * Returns transition duration\n * @param startProps {object} - a list of starting viewport props\n * @param endProps {object} - a list of target viewport props\n * @returns {Number} - transition duration in milliseconds\n */\n getDuration(startProps, endProps) {\n return endProps.transitionDuration;\n }\n\n _checkRequiredProps(props) {\n if (!this._requiredProps) {\n return;\n }\n\n this._requiredProps.forEach(propName => {\n const value = props[propName];\n assert(\n Number.isFinite(value) || Array.isArray(value),\n `${propName} is required for transition`\n );\n });\n }\n}\n","import {clamp} from 'math.gl';\nimport Controller from './controller';\nimport ViewState from './view-state';\nimport {normalizeViewportProps} from '@math.gl/web-mercator';\nimport assert from '../utils/assert';\n\nconst PITCH_MOUSE_THRESHOLD = 5;\nconst PITCH_ACCEL = 1.2;\n\nconst DEFAULT_STATE = {\n pitch: 0,\n bearing: 0,\n altitude: 1.5,\n minZoom: 0,\n maxZoom: 20,\n minPitch: 0,\n maxPitch: 60\n};\n\n/* Utils */\n\nexport class MapState extends ViewState {\n constructor({\n makeViewport,\n\n /** Mapbox viewport properties */\n /** The width of the viewport */\n width,\n /** The height of the viewport */\n height,\n /** The latitude at the center of the viewport */\n latitude,\n /** The longitude at the center of the viewport */\n longitude,\n /** The tile zoom level of the map. */\n zoom,\n /** The bearing of the viewport in degrees */\n bearing = DEFAULT_STATE.bearing,\n /** The pitch of the viewport in degrees */\n pitch = DEFAULT_STATE.pitch,\n /**\n * Specify the altitude of the viewport camera\n * Unit: map heights, default 1.5\n * Non-public API, see https://github.com/mapbox/mapbox-gl-js/issues/1137\n */\n altitude = DEFAULT_STATE.altitude,\n\n /** Viewport constraints */\n maxZoom = DEFAULT_STATE.maxZoom,\n minZoom = DEFAULT_STATE.minZoom,\n maxPitch = DEFAULT_STATE.maxPitch,\n minPitch = DEFAULT_STATE.minPitch,\n\n /** Interaction states, required to calculate change during transform */\n /* The point on map being grabbed when the operation first started */\n startPanLngLat,\n /* Center of the zoom when the operation first started */\n startZoomLngLat,\n /* Pointer position when rotation started */\n startRotatePos,\n /** Bearing when current perspective rotate operation started */\n startBearing,\n /** Pitch when current perspective rotate operation started */\n startPitch,\n /** Zoom when current zoom operation started */\n startZoom,\n\n /** Normalize viewport props to fit map height into viewport. Default `true` */\n normalize\n } = {}) {\n assert(Number.isFinite(longitude)); // `longitude` must be supplied\n assert(Number.isFinite(latitude)); // `latitude` must be supplied\n assert(Number.isFinite(zoom)); // `zoom` must be supplied\n\n super({\n width,\n height,\n latitude,\n longitude,\n zoom,\n bearing,\n pitch,\n altitude,\n maxZoom,\n minZoom,\n maxPitch,\n minPitch,\n normalize\n });\n\n this._state = {\n startPanLngLat,\n startZoomLngLat,\n startRotatePos,\n startBearing,\n startPitch,\n startZoom\n };\n\n this.makeViewport = makeViewport;\n }\n\n /**\n * Start panning\n * @param {[Number, Number]} pos - position on screen where the pointer grabs\n */\n panStart({pos}) {\n return this._getUpdatedState({\n startPanLngLat: this._unproject(pos)\n });\n }\n\n /**\n * Pan\n * @param {[Number, Number]} pos - position on screen where the pointer is\n * @param {[Number, Number], optional} startPos - where the pointer grabbed at\n * the start of the operation. Must be supplied of `panStart()` was not called\n */\n pan({pos, startPos}) {\n const startPanLngLat = this._state.startPanLngLat || this._unproject(startPos);\n\n if (!startPanLngLat) {\n return this;\n }\n\n const viewport = this.makeViewport(this._viewportProps);\n const newProps = viewport.panByPosition(startPanLngLat, pos);\n\n return this._getUpdatedState(newProps);\n }\n\n /**\n * End panning\n * Must call if `panStart()` was called\n */\n panEnd() {\n return this._getUpdatedState({\n startPanLngLat: null\n });\n }\n\n /**\n * Start rotating\n * @param {[Number, Number]} pos - position on screen where the center is\n */\n rotateStart({pos}) {\n return this._getUpdatedState({\n startRotatePos: pos,\n startBearing: this._viewportProps.bearing,\n startPitch: this._viewportProps.pitch\n });\n }\n\n /**\n * Rotate\n * @param {[Number, Number]} pos - position on screen where the center is\n */\n rotate({pos, deltaAngleX = 0, deltaAngleY = 0}) {\n const {startRotatePos, startBearing, startPitch} = this._state;\n\n if (!startRotatePos || !Number.isFinite(startBearing) || !Number.isFinite(startPitch)) {\n return this;\n }\n let newRotation;\n if (pos) {\n newRotation = this._calculateNewPitchAndBearing({\n ...this._getRotationParams(pos, startRotatePos),\n startBearing,\n startPitch\n });\n } else {\n newRotation = {\n bearing: startBearing + deltaAngleX,\n pitch: startPitch + deltaAngleY\n };\n }\n return this._getUpdatedState(newRotation);\n }\n\n /**\n * End rotating\n * Must call if `rotateStart()` was called\n */\n rotateEnd() {\n return this._getUpdatedState({\n startBearing: null,\n startPitch: null\n });\n }\n\n /**\n * Start zooming\n * @param {[Number, Number]} pos - position on screen where the center is\n */\n zoomStart({pos}) {\n return this._getUpdatedState({\n startZoomLngLat: this._unproject(pos),\n startZoom: this._viewportProps.zoom\n });\n }\n\n /**\n * Zoom\n * @param {[Number, Number]} pos - position on screen where the current center is\n * @param {[Number, Number]} startPos - the center position at\n * the start of the operation. Must be supplied of `zoomStart()` was not called\n * @param {Number} scale - a number between [0, 1] specifying the accumulated\n * relative scale.\n */\n zoom({pos, startPos, scale}) {\n // Make sure we zoom around the current mouse position rather than map center\n let {startZoom, startZoomLngLat} = this._state;\n\n if (!Number.isFinite(startZoom)) {\n // We have two modes of zoom:\n // scroll zoom that are discrete events (transform from the current zoom level),\n // and pinch zoom that are continuous events (transform from the zoom level when\n // pinch started).\n // If startZoom state is defined, then use the startZoom state;\n // otherwise assume discrete zooming\n startZoom = this._viewportProps.zoom;\n startZoomLngLat = this._unproject(startPos) || this._unproject(pos);\n }\n\n const zoom = this._calculateNewZoom({scale, startZoom});\n\n const zoomedViewport = this.makeViewport({...this._viewportProps, zoom});\n\n return this._getUpdatedState({\n zoom,\n ...zoomedViewport.panByPosition(startZoomLngLat, pos)\n });\n }\n\n /**\n * End zooming\n * Must call if `zoomStart()` was called\n */\n zoomEnd() {\n return this._getUpdatedState({\n startZoomLngLat: null,\n startZoom: null\n });\n }\n\n zoomIn(speed = 2) {\n return this._zoomFromCenter(speed);\n }\n\n zoomOut(speed = 2) {\n return this._zoomFromCenter(1 / speed);\n }\n\n moveLeft(speed = 100) {\n return this._panFromCenter([speed, 0]);\n }\n\n moveRight(speed = 100) {\n return this._panFromCenter([-speed, 0]);\n }\n\n moveUp(speed = 100) {\n return this._panFromCenter([0, speed]);\n }\n\n moveDown(speed = 100) {\n return this._panFromCenter([0, -speed]);\n }\n\n rotateLeft(speed = 15) {\n return this._getUpdatedState({\n bearing: this._viewportProps.bearing - speed\n });\n }\n\n rotateRight(speed = 15) {\n return this._getUpdatedState({\n bearing: this._viewportProps.bearing + speed\n });\n }\n\n rotateUp(speed = 10) {\n return this._getUpdatedState({\n pitch: this._viewportProps.pitch + speed\n });\n }\n\n rotateDown(speed = 10) {\n return this._getUpdatedState({\n pitch: this._viewportProps.pitch - speed\n });\n }\n\n shortestPathFrom(viewState) {\n // const endViewStateProps = new this.ControllerState(endProps).shortestPathFrom(startViewstate);\n const fromProps = viewState.getViewportProps();\n const props = {...this._viewportProps};\n const {bearing, longitude} = props;\n\n if (Math.abs(bearing - fromProps.bearing) > 180) {\n props.bearing = bearing < 0 ? bearing + 360 : bearing - 360;\n }\n if (Math.abs(longitude - fromProps.longitude) > 180) {\n props.longitude = longitude < 0 ? longitude + 360 : longitude - 360;\n }\n return props;\n }\n\n /* Private methods */\n\n _zoomFromCenter(scale) {\n const {width, height} = this._viewportProps;\n return this.zoom({\n pos: [width / 2, height / 2],\n scale\n });\n }\n\n _panFromCenter(offset) {\n const {width, height} = this._viewportProps;\n return this.pan({\n startPos: [width / 2, height / 2],\n pos: [width / 2 + offset[0], height / 2 + offset[1]]\n });\n }\n\n _getUpdatedState(newProps) {\n // Update _viewportProps\n return new this.constructor({\n makeViewport: this.makeViewport,\n ...this._viewportProps,\n ...this._state,\n ...newProps\n });\n }\n\n // Apply any constraints (mathematical or defined by _viewportProps) to map state\n _applyConstraints(props) {\n // Ensure zoom is within specified range\n const {maxZoom, minZoom, zoom} = props;\n props.zoom = clamp(zoom, minZoom, maxZoom);\n\n // Ensure pitch is within specified range\n const {maxPitch, minPitch, pitch} = props;\n props.pitch = clamp(pitch, minPitch, maxPitch);\n\n // Normalize viewport props to fit map height into viewport\n const {normalize = true} = props;\n if (normalize) {\n Object.assign(props, normalizeViewportProps(props));\n }\n\n return props;\n }\n\n _unproject(pos) {\n const viewport = this.makeViewport(this._viewportProps);\n return pos && viewport.unproject(pos);\n }\n\n // Calculates new zoom\n _calculateNewZoom({scale, startZoom}) {\n const {maxZoom, minZoom} = this._viewportProps;\n const zoom = startZoom + Math.log2(scale);\n return clamp(zoom, minZoom, maxZoom);\n }\n\n // Calculates a new pitch and bearing from a position (coming from an event)\n _calculateNewPitchAndBearing({deltaScaleX, deltaScaleY, startBearing, startPitch}) {\n // clamp deltaScaleY to [-1, 1] so that rotation is constrained between minPitch and maxPitch.\n // deltaScaleX does not need to be clamped as bearing does not have constraints.\n deltaScaleY = clamp(deltaScaleY, -1, 1);\n\n const {minPitch, maxPitch} = this._viewportProps;\n\n const bearing = startBearing + 180 * deltaScaleX;\n let pitch = startPitch;\n if (deltaScaleY > 0) {\n // Gradually increase pitch\n pitch = startPitch + deltaScaleY * (maxPitch - startPitch);\n } else if (deltaScaleY < 0) {\n // Gradually decrease pitch\n pitch = startPitch - deltaScaleY * (minPitch - startPitch);\n }\n\n return {\n pitch,\n bearing\n };\n }\n\n _getRotationParams(pos, startPos) {\n const deltaX = pos[0] - startPos[0];\n const deltaY = pos[1] - startPos[1];\n const centerY = pos[1];\n const startY = startPos[1];\n const {width, height} = this._viewportProps;\n\n const deltaScaleX = deltaX / width;\n let deltaScaleY = 0;\n\n if (deltaY > 0) {\n if (Math.abs(height - startY) > PITCH_MOUSE_THRESHOLD) {\n // Move from 0 to -1 as we drag upwards\n deltaScaleY = (deltaY / (startY - height)) * PITCH_ACCEL;\n }\n } else if (deltaY < 0) {\n if (startY > PITCH_MOUSE_THRESHOLD) {\n // Move from 0 to 1 as we drag upwards\n deltaScaleY = 1 - centerY / startY;\n }\n }\n deltaScaleY = Math.min(1, Math.max(-1, deltaScaleY));\n return {deltaScaleX, deltaScaleY};\n }\n}\n\nexport default class MapController extends Controller {\n constructor(props) {\n props.dragMode = props.dragMode || 'pan';\n super(MapState, props);\n }\n\n setProps(props) {\n const oldProps = this.controllerStateProps;\n\n super.setProps(props);\n\n const dimensionChanged = !oldProps || oldProps.height !== props.height;\n if (dimensionChanged) {\n // Dimensions changed, normalize the props\n this.updateViewport(\n new this.ControllerState({\n makeViewport: this.makeViewport,\n ...this.controllerStateProps,\n ...this._state\n })\n );\n }\n }\n\n get linearTransitionProps() {\n return ['longitude', 'latitude', 'zoom', 'bearing', 'pitch'];\n }\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// Handles tesselation of polygons with holes\n// - 2D surfaces\n// - 2D outlines\n// - 3D surfaces (top and sides only)\n// - 3D wireframes (not yet)\nimport * as Polygon from './polygon';\nimport {Tesselator} from '@deck.gl/core';\nimport {cutPolygonByGrid, cutPolygonByMercatorBounds} from '@math.gl/polygon';\n\n// This class is set up to allow querying one attribute at a time\n// the way the AttributeManager expects it\nexport default class PolygonTesselator extends Tesselator {\n constructor(opts) {\n const {fp64, IndexType = Uint32Array} = opts;\n super({\n ...opts,\n attributes: {\n positions: {size: 3, type: fp64 ? Float64Array : Float32Array},\n vertexValid: {type: Uint8ClampedArray, size: 1},\n indices: {type: IndexType, size: 1}\n }\n });\n }\n\n /* Getters */\n get(attributeName) {\n const {attributes} = this;\n if (attributeName === 'indices') {\n return attributes.indices && attributes.indices.subarray(0, this.vertexCount);\n }\n\n return attributes[attributeName];\n }\n\n /* Implement base Tesselator interface */\n updateGeometry(opts) {\n super.updateGeometry(opts);\n\n const externalIndices = this.buffers.indices;\n if (externalIndices) {\n this.vertexCount = (externalIndices.value || externalIndices).length;\n }\n }\n\n normalizeGeometry(polygon) {\n if (this.normalize) {\n polygon = Polygon.normalize(polygon, this.positionSize);\n if (this.opts.resolution) {\n return cutPolygonByGrid(polygon.positions || polygon, polygon.holeIndices, {\n size: this.positionSize,\n gridResolution: this.opts.resolution,\n edgeTypes: true\n });\n }\n if (this.opts.wrapLongitude) {\n return cutPolygonByMercatorBounds(polygon.positions || polygon, polygon.holeIndices, {\n size: this.positionSize,\n maxLatitude: 86,\n edgeTypes: true\n });\n }\n }\n return polygon;\n }\n\n getGeometrySize(polygon) {\n if (Array.isArray(polygon) && !Number.isFinite(polygon[0])) {\n let size = 0;\n for (const subPolygon of polygon) {\n size += this.getGeometrySize(subPolygon);\n }\n return size;\n }\n return (polygon.positions || polygon).length / this.positionSize;\n }\n\n getGeometryFromBuffer(buffer) {\n if (this.normalize || !this.buffers.indices) {\n return super.getGeometryFromBuffer(buffer);\n }\n // we don't need to read the positions if no normalization/tesselation\n return () => null;\n }\n\n updateGeometryAttributes(polygon, context) {\n if (Array.isArray(polygon) && !Number.isFinite(polygon[0])) {\n for (const subPolygon of polygon) {\n const geometrySize = this.getGeometrySize(subPolygon);\n context.geometrySize = geometrySize;\n this.updateGeometryAttributes(subPolygon, context);\n context.vertexStart += geometrySize;\n context.indexStart = this.indexStarts[context.geometryIndex + 1];\n }\n } else {\n this._updateIndices(polygon, context);\n this._updatePositions(polygon, context);\n this._updateVertexValid(polygon, context);\n }\n }\n\n // Flatten the indices array\n _updateIndices(polygon, {geometryIndex, vertexStart: offset, indexStart}) {\n const {attributes, indexStarts, typedArrayManager} = this;\n\n let target = attributes.indices;\n if (!target) {\n return;\n }\n let i = indexStart;\n\n // 1. get triangulated indices for the internal areas\n const indices = Polygon.getSurfaceIndices(polygon, this.positionSize, this.opts.preproject);\n\n // make sure the buffer is large enough\n target = typedArrayManager.allocate(target, indexStart + indices.length, {\n copy: true\n });\n\n // 2. offset each index by the number of indices in previous polygons\n for (let j = 0; j < indices.length; j++) {\n target[i++] = indices[j] + offset;\n }\n\n indexStarts[geometryIndex + 1] = indexStart + indices.length;\n attributes.indices = target;\n }\n\n // Flatten out all the vertices of all the sub subPolygons\n _updatePositions(polygon, {vertexStart, geometrySize}) {\n const {\n attributes: {positions},\n positionSize\n } = this;\n if (!positions) {\n return;\n }\n const polygonPositions = polygon.positions || polygon;\n\n for (let i = vertexStart, j = 0; j < geometrySize; i++, j++) {\n const x = polygonPositions[j * positionSize];\n const y = polygonPositions[j * positionSize + 1];\n const z = positionSize > 2 ? polygonPositions[j * positionSize + 2] : 0;\n\n positions[i * 3] = x;\n positions[i * 3 + 1] = y;\n positions[i * 3 + 2] = z;\n }\n }\n\n _updateVertexValid(polygon, {vertexStart, geometrySize}) {\n const {\n attributes: {vertexValid},\n positionSize\n } = this;\n const holeIndices = polygon && polygon.holeIndices;\n /* We are reusing the some buffer for `nextPositions` by offseting one vertex\n * to the left. As a result,\n * the last vertex of each ring overlaps with the first vertex of the next ring.\n * `vertexValid` is used to mark the end of each ring so we don't draw these\n * segments:\n positions A0 A1 A2 A3 A4 B0 B1 B2 C0 ...\n nextPositions A1 A2 A3 A4 B0 B1 B2 C0 C1 ...\n vertexValid 1 1 1 1 0 1 1 0 1 ...\n */\n if (polygon && polygon.edgeTypes) {\n vertexValid.set(polygon.edgeTypes, vertexStart);\n } else {\n vertexValid.fill(1, vertexStart, vertexStart + geometrySize);\n }\n if (holeIndices) {\n for (let j = 0; j < holeIndices.length; j++) {\n vertexValid[vertexStart + holeIndices[j] / positionSize - 1] = 0;\n }\n }\n vertexValid[vertexStart + geometrySize - 1] = 0;\n }\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n\nattribute vec2 vertexPositions;\nattribute float vertexValid;\n\nuniform bool extruded;\nuniform bool isWireframe;\nuniform float elevationScale;\nuniform float opacity;\n\nvarying vec4 vColor;\n\nstruct PolygonProps {\n vec4 fillColors;\n vec4 lineColors;\n vec3 positions;\n vec3 nextPositions;\n vec3 pickingColors;\n vec3 positions64Low;\n vec3 nextPositions64Low;\n float elevations;\n};\n\nvec3 project_offset_normal(vec3 vector) {\n if (project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project_uCoordinateSystem == COORDINATE_SYSTEM_LNGLAT_OFFSETS) {\n // normals generated by the polygon tesselator are in lnglat offsets instead of meters\n return normalize(vector * project_uCommonUnitsPerWorldUnit);\n }\n return project_normal(vector);\n}\n\nvoid calculatePosition(PolygonProps props) {\n#ifdef IS_SIDE_VERTEX\n if(vertexValid < 0.5){\n gl_Position = vec4(0.);\n return;\n }\n#endif\n\n vec3 pos;\n vec3 pos64Low;\n vec3 normal;\n vec4 colors = isWireframe ? props.lineColors : props.fillColors;\n\n geometry.worldPosition = props.positions;\n geometry.worldPositionAlt = props.nextPositions;\n geometry.pickingColor = props.pickingColors;\n\n#ifdef IS_SIDE_VERTEX\n pos = mix(props.positions, props.nextPositions, vertexPositions.x);\n pos64Low = mix(props.positions64Low, props.nextPositions64Low, vertexPositions.x);\n#else\n pos = props.positions;\n pos64Low = props.positions64Low;\n#endif\n\n if (extruded) {\n pos.z += props.elevations * vertexPositions.y * elevationScale;\n\n#ifdef IS_SIDE_VERTEX\n normal = vec3(\n props.positions.y - props.nextPositions.y + (props.positions64Low.y - props.nextPositions64Low.y),\n props.nextPositions.x - props.positions.x + (props.nextPositions64Low.x - props.positions64Low.x),\n 0.0);\n normal = project_offset_normal(normal);\n#else\n normal = vec3(0.0, 0.0, 1.0);\n#endif\n geometry.normal = normal;\n }\n\n gl_Position = project_position_to_clipspace(pos, pos64Low, vec3(0.), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n if (extruded) {\n vec3 lightColor = lighting_getLightColor(colors.rgb, project_uCameraPosition, geometry.position.xyz, normal);\n vColor = vec4(lightColor, colors.a * opacity);\n } else {\n vColor = vec4(colors.rgb, colors.a * opacity);\n }\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport main from './solid-polygon-layer-vertex-main.glsl';\n\nexport default `\\\n#define SHADER_NAME solid-polygon-layer-vertex-shader\n\nattribute vec3 positions;\nattribute vec3 positions64Low;\nattribute float elevations;\nattribute vec4 fillColors;\nattribute vec4 lineColors;\nattribute vec3 pickingColors;\n\n${main}\n\nvoid main(void) {\n PolygonProps props;\n\n props.positions = positions;\n props.positions64Low = positions64Low;\n props.elevations = elevations;\n props.fillColors = fillColors;\n props.lineColors = lineColors;\n props.pickingColors = pickingColors;\n\n calculatePosition(props);\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport main from './solid-polygon-layer-vertex-main.glsl';\n\nexport default `\\\n#define SHADER_NAME solid-polygon-layer-vertex-shader-side\n#define IS_SIDE_VERTEX\n\n\nattribute vec3 instancePositions;\nattribute vec3 nextPositions;\nattribute vec3 instancePositions64Low;\nattribute vec3 nextPositions64Low;\nattribute float instanceElevations;\nattribute vec4 instanceFillColors;\nattribute vec4 instanceLineColors;\nattribute vec3 instancePickingColors;\n\n${main}\n\nvoid main(void) {\n PolygonProps props;\n\n #if RING_WINDING_ORDER_CW == 1\n props.positions = instancePositions;\n props.positions64Low = instancePositions64Low;\n props.nextPositions = nextPositions;\n props.nextPositions64Low = nextPositions64Low;\n #else\n props.positions = nextPositions;\n props.positions64Low = nextPositions64Low;\n props.nextPositions = instancePositions;\n props.nextPositions64Low = instancePositions64Low;\n #endif\n props.elevations = instanceElevations;\n props.fillColors = instanceFillColors;\n props.lineColors = instanceLineColors;\n props.pickingColors = instancePickingColors;\n\n calculatePosition(props);\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {Layer, project32, gouraudLighting, picking, COORDINATE_SYSTEM} from '@deck.gl/core';\nimport GL from '@luma.gl/constants';\nimport {Model, Geometry, hasFeatures, FEATURES} from '@luma.gl/core';\n\n// Polygon geometry generation is managed by the polygon tesselator\nimport PolygonTesselator from './polygon-tesselator';\n\nimport vsTop from './solid-polygon-layer-vertex-top.glsl';\nimport vsSide from './solid-polygon-layer-vertex-side.glsl';\nimport fs from './solid-polygon-layer-fragment.glsl';\n\nconst DEFAULT_COLOR = [0, 0, 0, 255];\n\nconst defaultProps = {\n filled: true,\n // Whether to extrude\n extruded: false,\n // Whether to draw a GL.LINES wireframe of the polygon\n wireframe: false,\n _normalize: true,\n _windingOrder: 'CW',\n\n // elevation multiplier\n elevationScale: {type: 'number', min: 0, value: 1},\n\n // Accessor for polygon geometry\n getPolygon: {type: 'accessor', value: f => f.polygon},\n // Accessor for extrusion height\n getElevation: {type: 'accessor', value: 1000},\n // Accessor for colors\n getFillColor: {type: 'accessor', value: DEFAULT_COLOR},\n getLineColor: {type: 'accessor', value: DEFAULT_COLOR},\n\n // Optional settings for 'lighting' shader module\n material: true\n};\n\nconst ATTRIBUTE_TRANSITION = {\n enter: (value, chunk) => {\n return chunk.length ? chunk.subarray(chunk.length - value.length) : value;\n }\n};\n\nexport default class SolidPolygonLayer extends Layer {\n getShaders(type) {\n return super.getShaders({\n vs: type === 'top' ? vsTop : vsSide,\n fs,\n defines: {\n RING_WINDING_ORDER_CW: !this.props._normalize && this.props._windingOrder === 'CCW' ? 0 : 1\n },\n modules: [project32, gouraudLighting, picking]\n });\n }\n\n get wrapLongitude() {\n return false;\n }\n\n initializeState() {\n const {gl, viewport} = this.context;\n let {coordinateSystem} = this.props;\n if (viewport.isGeospatial && coordinateSystem === COORDINATE_SYSTEM.DEFAULT) {\n coordinateSystem = COORDINATE_SYSTEM.LNGLAT;\n }\n\n this.setState({\n numInstances: 0,\n polygonTesselator: new PolygonTesselator({\n // Lnglat coordinates are usually projected non-linearly, which affects tesselation results\n // Provide a preproject function if the coordinates are in lnglat\n preproject: coordinateSystem === COORDINATE_SYSTEM.LNGLAT && viewport.projectFlat,\n fp64: this.use64bitPositions(),\n IndexType: !gl || hasFeatures(gl, FEATURES.ELEMENT_INDEX_UINT32) ? Uint32Array : Uint16Array\n })\n });\n\n const attributeManager = this.getAttributeManager();\n const noAlloc = true;\n\n attributeManager.remove(['instancePickingColors']);\n\n /* eslint-disable max-len */\n attributeManager.add({\n indices: {size: 1, isIndexed: true, update: this.calculateIndices, noAlloc},\n positions: {\n size: 3,\n type: GL.DOUBLE,\n fp64: this.use64bitPositions(),\n transition: ATTRIBUTE_TRANSITION,\n accessor: 'getPolygon',\n update: this.calculatePositions,\n noAlloc,\n shaderAttributes: {\n positions: {\n vertexOffset: 0,\n divisor: 0\n },\n instancePositions: {\n vertexOffset: 0,\n divisor: 1\n },\n nextPositions: {\n vertexOffset: 1,\n divisor: 1\n }\n }\n },\n vertexValid: {\n size: 1,\n divisor: 1,\n type: GL.UNSIGNED_BYTE,\n update: this.calculateVertexValid,\n noAlloc\n },\n elevations: {\n size: 1,\n transition: ATTRIBUTE_TRANSITION,\n accessor: 'getElevation',\n shaderAttributes: {\n elevations: {\n divisor: 0\n },\n instanceElevations: {\n divisor: 1\n }\n }\n },\n fillColors: {\n alias: 'colors',\n size: this.props.colorFormat.length,\n type: GL.UNSIGNED_BYTE,\n normalized: true,\n transition: ATTRIBUTE_TRANSITION,\n accessor: 'getFillColor',\n defaultValue: DEFAULT_COLOR,\n shaderAttributes: {\n fillColors: {\n divisor: 0\n },\n instanceFillColors: {\n divisor: 1\n }\n }\n },\n lineColors: {\n alias: 'colors',\n size: this.props.colorFormat.length,\n type: GL.UNSIGNED_BYTE,\n normalized: true,\n transition: ATTRIBUTE_TRANSITION,\n accessor: 'getLineColor',\n defaultValue: DEFAULT_COLOR,\n shaderAttributes: {\n lineColors: {\n divisor: 0\n },\n instanceLineColors: {\n divisor: 1\n }\n }\n },\n pickingColors: {\n size: 3,\n type: GL.UNSIGNED_BYTE,\n accessor: (object, {index, target: value}) =>\n this.encodePickingColor(object && object.__source ? object.__source.index : index, value),\n shaderAttributes: {\n pickingColors: {\n divisor: 0\n },\n instancePickingColors: {\n divisor: 1\n }\n }\n }\n });\n /* eslint-enable max-len */\n }\n\n getPickingInfo(params) {\n const info = super.getPickingInfo(params);\n const {index} = info;\n const {data} = this.props;\n\n // Check if data comes from a composite layer, wrapped with getSubLayerRow\n if (data[0] && data[0].__source) {\n // index decoded from picking color refers to the source index\n info.object = data.find(d => d.__source.index === index);\n }\n return info;\n }\n\n disablePickingIndex(objectIndex) {\n const {data} = this.props;\n\n // Check if data comes from a composite layer, wrapped with getSubLayerRow\n if (data[0] && data[0].__source) {\n // index decoded from picking color refers to the source index\n for (let i = 0; i < data.length; i++) {\n if (data[i].__source.index === objectIndex) {\n this._disablePickingIndex(i);\n }\n }\n } else {\n this._disablePickingIndex(objectIndex);\n }\n }\n\n draw({uniforms}) {\n const {extruded, filled, wireframe, elevationScale} = this.props;\n const {topModel, sideModel, polygonTesselator} = this.state;\n\n const renderUniforms = {\n ...uniforms,\n extruded: Boolean(extruded),\n elevationScale\n };\n\n // Note: the order is important\n if (sideModel) {\n sideModel.setInstanceCount(polygonTesselator.instanceCount - 1);\n sideModel.setUniforms(renderUniforms);\n if (wireframe) {\n sideModel.setDrawMode(GL.LINE_STRIP);\n sideModel.setUniforms({isWireframe: true}).draw();\n }\n if (filled) {\n sideModel.setDrawMode(GL.TRIANGLE_FAN);\n sideModel.setUniforms({isWireframe: false}).draw();\n }\n }\n\n if (topModel) {\n topModel.setVertexCount(polygonTesselator.vertexCount);\n topModel.setUniforms(renderUniforms).draw();\n }\n }\n\n updateState(updateParams) {\n super.updateState(updateParams);\n\n this.updateGeometry(updateParams);\n\n const {props, oldProps, changeFlags} = updateParams;\n const attributeManager = this.getAttributeManager();\n\n const regenerateModels =\n changeFlags.extensionsChanged ||\n props.filled !== oldProps.filled ||\n props.extruded !== oldProps.extruded;\n\n if (regenerateModels) {\n this.state.models?.forEach(model => model.delete());\n\n this.setState(this._getModels(this.context.gl));\n attributeManager.invalidateAll();\n }\n }\n\n updateGeometry({props, oldProps, changeFlags}) {\n const geometryConfigChanged =\n changeFlags.dataChanged ||\n (changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getPolygon));\n\n // When the geometry config or the data is changed,\n // tessellator needs to be invoked\n if (geometryConfigChanged) {\n const {polygonTesselator} = this.state;\n const buffers = props.data.attributes || {};\n polygonTesselator.updateGeometry({\n data: props.data,\n normalize: props._normalize,\n geometryBuffer: buffers.getPolygon,\n buffers,\n getGeometry: props.getPolygon,\n positionFormat: props.positionFormat,\n wrapLongitude: props.wrapLongitude,\n // TODO - move the flag out of the viewport\n resolution: this.context.viewport.resolution,\n fp64: this.use64bitPositions(),\n dataChanged: changeFlags.dataChanged\n });\n\n this.setState({\n numInstances: polygonTesselator.instanceCount,\n startIndices: polygonTesselator.vertexStarts\n });\n\n if (!changeFlags.dataChanged) {\n // Base `layer.updateState` only invalidates all attributes on data change\n // Cover the rest of the scenarios here\n this.getAttributeManager().invalidateAll();\n }\n }\n }\n\n _getModels(gl) {\n const {id, filled, extruded} = this.props;\n\n let topModel;\n let sideModel;\n\n if (filled) {\n const shaders = this.getShaders('top');\n shaders.defines.NON_INSTANCED_MODEL = 1;\n\n topModel = new Model(gl, {\n ...shaders,\n id: `${id}-top`,\n drawMode: GL.TRIANGLES,\n attributes: {\n vertexPositions: new Float32Array([0, 1])\n },\n uniforms: {\n isWireframe: false,\n isSideVertex: false\n },\n vertexCount: 0,\n isIndexed: true\n });\n }\n if (extruded) {\n sideModel = new Model(gl, {\n ...this.getShaders('side'),\n id: `${id}-side`,\n geometry: new Geometry({\n drawMode: GL.LINES,\n vertexCount: 4,\n attributes: {\n // top right - top left - bootom left - bottom right\n vertexPositions: {\n size: 2,\n value: new Float32Array([1, 0, 0, 0, 0, 1, 1, 1])\n }\n }\n }),\n instanceCount: 0,\n isInstanced: 1\n });\n\n sideModel.userData.excludeAttributes = {indices: true};\n }\n\n return {\n models: [sideModel, topModel].filter(Boolean),\n topModel,\n sideModel\n };\n }\n\n calculateIndices(attribute) {\n const {polygonTesselator} = this.state;\n attribute.startIndices = polygonTesselator.indexStarts;\n attribute.value = polygonTesselator.get('indices');\n }\n\n calculatePositions(attribute) {\n const {polygonTesselator} = this.state;\n attribute.startIndices = polygonTesselator.vertexStarts;\n attribute.value = polygonTesselator.get('positions');\n }\n\n calculateVertexValid(attribute) {\n attribute.value = this.state.polygonTesselator.get('vertexValid');\n }\n}\n\nSolidPolygonLayer.layerName = 'SolidPolygonLayer';\nSolidPolygonLayer.defaultProps = defaultProps;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n#define SHADER_NAME solid-polygon-layer-fragment-shader\n\nprecision highp float;\n\nvarying vec4 vColor;\n\nvoid main(void) {\n gl_FragColor = vColor;\n\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\nimport {Tesselator} from '@deck.gl/core';\nimport {normalizePath} from './path';\n\nconst START_CAP = 1;\nconst END_CAP = 2;\nconst INVALID = 4;\n\n// This class is set up to allow querying one attribute at a time\n// the way the AttributeManager expects it\nexport default class PathTesselator extends Tesselator {\n constructor(opts) {\n super({\n ...opts,\n attributes: {\n // Padding covers shaderAttributes for last segment in largest case fp64\n // additional vertex + hi & low parts, 3 * 6\n positions: {\n size: 3,\n padding: 18,\n initialize: true,\n type: opts.fp64 ? Float64Array : Float32Array\n },\n segmentTypes: {size: 1, type: Uint8ClampedArray}\n }\n });\n }\n\n getGeometryFromBuffer(buffer) {\n if (this.normalize) {\n return super.getGeometryFromBuffer(buffer);\n }\n // we don't need to read the positions if no normalization\n return () => null;\n }\n\n normalizeGeometry(path) {\n if (this.normalize) {\n return normalizePath(path, this.positionSize, this.opts.resolution, this.opts.wrapLongitude);\n }\n return path;\n }\n\n /* Getters */\n get(attributeName) {\n return this.attributes[attributeName];\n }\n\n /* Implement base Tesselator interface */\n getGeometrySize(path) {\n if (Array.isArray(path[0])) {\n let size = 0;\n for (const subPath of path) {\n size += this.getGeometrySize(subPath);\n }\n return size;\n }\n const numPoints = this.getPathLength(path);\n if (numPoints < 2) {\n // invalid path\n return 0;\n }\n if (this.isClosed(path)) {\n // minimum 3 vertices\n return numPoints < 3 ? 0 : numPoints + 2;\n }\n return numPoints;\n }\n\n updateGeometryAttributes(path, context) {\n if (context.geometrySize === 0) {\n return;\n }\n if (path && Array.isArray(path[0])) {\n for (const subPath of path) {\n const geometrySize = this.getGeometrySize(subPath);\n context.geometrySize = geometrySize;\n this.updateGeometryAttributes(subPath, context);\n context.vertexStart += geometrySize;\n }\n } else {\n this._updateSegmentTypes(path, context);\n this._updatePositions(path, context);\n }\n }\n\n _updateSegmentTypes(path, context) {\n const {segmentTypes} = this.attributes;\n const isPathClosed = this.isClosed(path);\n const {vertexStart, geometrySize} = context;\n\n // positions -- A0 A1 B0 B1 B2 B3 B0 B1 B2 --\n // segmentTypes 3 4 4 0 0 0 0 4 4\n segmentTypes.fill(0, vertexStart, vertexStart + geometrySize);\n if (isPathClosed) {\n segmentTypes[vertexStart] = INVALID;\n segmentTypes[vertexStart + geometrySize - 2] = INVALID;\n } else {\n segmentTypes[vertexStart] += START_CAP;\n segmentTypes[vertexStart + geometrySize - 2] += END_CAP;\n }\n segmentTypes[vertexStart + geometrySize - 1] = INVALID;\n }\n\n _updatePositions(path, context) {\n const {positions} = this.attributes;\n if (!positions) {\n return;\n }\n const {vertexStart, geometrySize} = context;\n const p = new Array(3);\n\n // positions -- A0 A1 B0 B1 B2 B3 B0 B1 B2 --\n // segmentTypes 3 4 4 0 0 0 0 4 4\n for (let i = vertexStart, ptIndex = 0; ptIndex < geometrySize; i++, ptIndex++) {\n this.getPointOnPath(path, ptIndex, p);\n positions[i * 3] = p[0];\n positions[i * 3 + 1] = p[1];\n positions[i * 3 + 2] = p[2];\n }\n }\n\n /* Utilities */\n // Returns the number of points in the path\n getPathLength(path) {\n return path.length / this.positionSize;\n }\n\n // Returns a point on the path at the specified index\n getPointOnPath(path, index, target = []) {\n const {positionSize} = this;\n if (index * positionSize >= path.length) {\n // loop\n index += 1 - path.length / positionSize;\n }\n const i = index * positionSize;\n target[0] = path[i];\n target[1] = path[i + 1];\n target[2] = (positionSize === 3 && path[i + 2]) || 0;\n return target;\n }\n\n // Returns true if the first and last points are identical\n isClosed(path) {\n if (!this.normalize) {\n return this.opts.loop;\n }\n const {positionSize} = this;\n const lastPointIndex = path.length - positionSize;\n return (\n path[0] === path[lastPointIndex] &&\n path[1] === path[lastPointIndex + 1] &&\n (positionSize === 2 || path[2] === path[lastPointIndex + 2])\n );\n }\n}\n","import {cutPolylineByGrid, cutPolylineByMercatorBounds} from '@math.gl/polygon';\n\n/** Returns a flat array of path positions\n * Flattens a nested path object\n * Cut the feature if needed (globe projection, wrap longitude, etc.)\n */\nexport function normalizePath(path, size, gridResolution, wrapLongitude) {\n let flatPath = path;\n if (Array.isArray(path[0])) {\n const length = path.length * size;\n flatPath = new Array(length);\n for (let i = 0; i < path.length; i++) {\n for (let j = 0; j < size; j++) {\n flatPath[i * size + j] = path[i][j] || 0;\n }\n }\n }\n if (gridResolution) {\n return cutPolylineByGrid(flatPath, {size, gridResolution});\n }\n if (wrapLongitude) {\n return cutPolylineByMercatorBounds(flatPath, {size});\n }\n return flatPath;\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {Layer, project32, picking, log, UNIT} from '@deck.gl/core';\nimport GL from '@luma.gl/constants';\nimport {Model, Geometry} from '@luma.gl/core';\n\nimport PathTesselator from './path-tesselator';\n\nimport vs from './path-layer-vertex.glsl';\nimport fs from './path-layer-fragment.glsl';\n\nconst DEFAULT_COLOR = [0, 0, 0, 255];\n\nconst defaultProps = {\n widthUnits: 'meters',\n widthScale: {type: 'number', min: 0, value: 1}, // stroke width in meters\n widthMinPixels: {type: 'number', min: 0, value: 0}, // min stroke width in pixels\n widthMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER}, // max stroke width in pixels\n jointRounded: false,\n capRounded: false,\n miterLimit: {type: 'number', min: 0, value: 4},\n billboard: false,\n // `loop` or `open`\n _pathType: null,\n\n getPath: {type: 'accessor', value: object => object.path},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getWidth: {type: 'accessor', value: 1},\n\n // deprecated props\n rounded: {deprecatedFor: ['jointRounded', 'capRounded']}\n};\n\nconst ATTRIBUTE_TRANSITION = {\n enter: (value, chunk) => {\n return chunk.length ? chunk.subarray(chunk.length - value.length) : value;\n }\n};\n\nexport default class PathLayer extends Layer {\n getShaders() {\n return super.getShaders({vs, fs, modules: [project32, picking]}); // 'project' module added by default.\n }\n\n get wrapLongitude() {\n return false;\n }\n\n initializeState() {\n const noAlloc = true;\n const attributeManager = this.getAttributeManager();\n /* eslint-disable max-len */\n attributeManager.addInstanced({\n positions: {\n size: 3,\n // Start filling buffer from 1 vertex in\n vertexOffset: 1,\n type: GL.DOUBLE,\n fp64: this.use64bitPositions(),\n transition: ATTRIBUTE_TRANSITION,\n accessor: 'getPath',\n update: this.calculatePositions,\n noAlloc,\n shaderAttributes: {\n instanceLeftPositions: {\n vertexOffset: 0\n },\n instanceStartPositions: {\n vertexOffset: 1\n },\n instanceEndPositions: {\n vertexOffset: 2\n },\n instanceRightPositions: {\n vertexOffset: 3\n }\n }\n },\n instanceTypes: {\n size: 1,\n type: GL.UNSIGNED_BYTE,\n update: this.calculateSegmentTypes,\n noAlloc\n },\n instanceStrokeWidths: {\n size: 1,\n accessor: 'getWidth',\n transition: ATTRIBUTE_TRANSITION,\n defaultValue: 1\n },\n instanceColors: {\n size: this.props.colorFormat.length,\n type: GL.UNSIGNED_BYTE,\n normalized: true,\n accessor: 'getColor',\n transition: ATTRIBUTE_TRANSITION,\n defaultValue: DEFAULT_COLOR\n },\n instancePickingColors: {\n size: 3,\n type: GL.UNSIGNED_BYTE,\n accessor: (object, {index, target: value}) =>\n this.encodePickingColor(object && object.__source ? object.__source.index : index, value)\n }\n });\n /* eslint-enable max-len */\n\n this.setState({\n pathTesselator: new PathTesselator({\n fp64: this.use64bitPositions()\n })\n });\n\n if (this.props.getDashArray && !this.props.extensions.length) {\n log.removed('getDashArray', 'PathStyleExtension')();\n }\n }\n\n updateState({oldProps, props, changeFlags}) {\n super.updateState({props, oldProps, changeFlags});\n\n const attributeManager = this.getAttributeManager();\n\n const geometryChanged =\n changeFlags.dataChanged ||\n (changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getPath));\n\n if (geometryChanged) {\n const {pathTesselator} = this.state;\n const buffers = props.data.attributes || {};\n\n pathTesselator.updateGeometry({\n data: props.data,\n geometryBuffer: buffers.getPath,\n buffers,\n normalize: !props._pathType,\n loop: props._pathType === 'loop',\n getGeometry: props.getPath,\n positionFormat: props.positionFormat,\n wrapLongitude: props.wrapLongitude,\n // TODO - move the flag out of the viewport\n resolution: this.context.viewport.resolution,\n dataChanged: changeFlags.dataChanged\n });\n this.setState({\n numInstances: pathTesselator.instanceCount,\n startIndices: pathTesselator.vertexStarts\n });\n if (!changeFlags.dataChanged) {\n // Base `layer.updateState` only invalidates all attributes on data change\n // Cover the rest of the scenarios here\n attributeManager.invalidateAll();\n }\n }\n\n if (changeFlags.extensionsChanged) {\n const {gl} = this.context;\n this.state.model?.delete();\n this.state.model = this._getModel(gl);\n attributeManager.invalidateAll();\n }\n }\n\n getPickingInfo(params) {\n const info = super.getPickingInfo(params);\n const {index} = info;\n const {data} = this.props;\n\n // Check if data comes from a composite layer, wrapped with getSubLayerRow\n if (data[0] && data[0].__source) {\n // index decoded from picking color refers to the source index\n info.object = data.find(d => d.__source.index === index);\n }\n return info;\n }\n\n disablePickingIndex(objectIndex) {\n const {data} = this.props;\n\n // Check if data comes from a composite layer, wrapped with getSubLayerRow\n if (data[0] && data[0].__source) {\n // index decoded from picking color refers to the source index\n for (let i = 0; i < data.length; i++) {\n if (data[i].__source.index === objectIndex) {\n this._disablePickingIndex(i);\n }\n }\n } else {\n this._disablePickingIndex(objectIndex);\n }\n }\n\n draw({uniforms}) {\n const {\n jointRounded,\n capRounded,\n billboard,\n miterLimit,\n widthUnits,\n widthScale,\n widthMinPixels,\n widthMaxPixels\n } = this.props;\n\n this.state.model\n .setUniforms(uniforms)\n .setUniforms({\n jointType: Number(jointRounded),\n capType: Number(capRounded),\n billboard,\n widthUnits: UNIT[widthUnits],\n widthScale,\n miterLimit,\n widthMinPixels,\n widthMaxPixels\n })\n .draw();\n }\n\n _getModel(gl) {\n /*\n * _\n * \"-_ 1 3 5\n * _ \"o---------------------o-------------------_-o\n * - / \"\"--..__ '. _.-' /\n * _ \"@- - - - - \"\"--..__- - - - x - - - -_.@' /\n * \"-_ / \"\"--..__ '. _,-` : /\n * \"o----------------------------\"\"-o' : /\n * 0,2 4 / '. : /\n * / '.: /\n * / :'. /\n * / : ', /\n * / : o\n */\n\n // prettier-ignore\n const SEGMENT_INDICES = [\n // start corner\n 0, 1, 2,\n // body\n 1, 4, 2,\n 1, 3, 4,\n // end corner\n 3, 5, 4\n ];\n\n // [0] position on segment - 0: start, 1: end\n // [1] side of path - -1: left, 0: center (joint), 1: right\n // prettier-ignore\n const SEGMENT_POSITIONS = [\n // bevel start corner\n 0, 0,\n // start inner corner\n 0, -1,\n // start outer corner\n 0, 1,\n // end inner corner\n 1, -1,\n // end outer corner\n 1, 1,\n // bevel end corner\n 1, 0\n ];\n\n return new Model(gl, {\n ...this.getShaders(),\n id: this.props.id,\n geometry: new Geometry({\n drawMode: GL.TRIANGLES,\n attributes: {\n indices: new Uint16Array(SEGMENT_INDICES),\n positions: {value: new Float32Array(SEGMENT_POSITIONS), size: 2}\n }\n }),\n isInstanced: true\n });\n }\n\n calculatePositions(attribute) {\n const {pathTesselator} = this.state;\n\n attribute.startIndices = pathTesselator.vertexStarts;\n attribute.value = pathTesselator.get('positions');\n }\n\n calculateSegmentTypes(attribute) {\n const {pathTesselator} = this.state;\n\n attribute.startIndices = pathTesselator.vertexStarts;\n attribute.value = pathTesselator.get('segmentTypes');\n }\n}\n\nPathLayer.layerName = 'PathLayer';\nPathLayer.defaultProps = defaultProps;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n#define SHADER_NAME path-layer-vertex-shader\n\nattribute vec2 positions;\n\nattribute float instanceTypes;\nattribute vec3 instanceStartPositions;\nattribute vec3 instanceEndPositions;\nattribute vec3 instanceLeftPositions;\nattribute vec3 instanceRightPositions;\nattribute vec3 instanceLeftPositions64Low;\nattribute vec3 instanceStartPositions64Low;\nattribute vec3 instanceEndPositions64Low;\nattribute vec3 instanceRightPositions64Low;\nattribute float instanceStrokeWidths;\nattribute vec4 instanceColors;\nattribute vec3 instancePickingColors;\n\nuniform float widthScale;\nuniform float widthMinPixels;\nuniform float widthMaxPixels;\nuniform float jointType;\nuniform float capType;\nuniform float miterLimit;\nuniform bool billboard;\nuniform int widthUnits;\n\nuniform float opacity;\n\nvarying vec4 vColor;\nvarying vec2 vCornerOffset;\nvarying float vMiterLength;\nvarying vec2 vPathPosition;\nvarying float vPathLength;\nvarying float vJointType;\n\nconst float EPSILON = 0.001;\nconst vec3 ZERO_OFFSET = vec3(0.0);\n\nfloat flipIfTrue(bool flag) {\n return -(float(flag) * 2. - 1.);\n}\n\n// calculate line join positions\nvec3 lineJoin(\n vec3 prevPoint, vec3 currPoint, vec3 nextPoint,\n vec2 width\n) {\n bool isEnd = positions.x > 0.0;\n // side of the segment - -1: left, 0: center, 1: right\n float sideOfPath = positions.y;\n float isJoint = float(sideOfPath == 0.0);\n\n vec3 deltaA3 = (currPoint - prevPoint);\n vec3 deltaB3 = (nextPoint - currPoint);\n\n mat3 rotationMatrix;\n bool needsRotation = !billboard && project_needs_rotation(currPoint, rotationMatrix);\n if (needsRotation) {\n deltaA3 = deltaA3 * rotationMatrix;\n deltaB3 = deltaB3 * rotationMatrix;\n }\n vec2 deltaA = deltaA3.xy / width;\n vec2 deltaB = deltaB3.xy / width;\n\n float lenA = length(deltaA);\n float lenB = length(deltaB);\n\n vec2 dirA = lenA > 0. ? normalize(deltaA) : vec2(0.0, 0.0);\n vec2 dirB = lenB > 0. ? normalize(deltaB) : vec2(0.0, 0.0);\n\n vec2 perpA = vec2(-dirA.y, dirA.x);\n vec2 perpB = vec2(-dirB.y, dirB.x);\n\n // tangent of the corner\n vec2 tangent = dirA + dirB;\n tangent = length(tangent) > 0. ? normalize(tangent) : perpA;\n // direction of the corner\n vec2 miterVec = vec2(-tangent.y, tangent.x);\n // direction of the segment\n vec2 dir = isEnd ? dirA : dirB;\n // direction of the extrusion\n vec2 perp = isEnd ? perpA : perpB;\n // length of the segment\n float L = isEnd ? lenA : lenB;\n\n // A = angle of the corner\n float sinHalfA = abs(dot(miterVec, perp));\n float cosHalfA = abs(dot(dirA, miterVec));\n\n // -1: right, 1: left\n float turnDirection = flipIfTrue(dirA.x * dirB.y >= dirA.y * dirB.x);\n\n // relative position to the corner:\n // -1: inside (smaller side of the angle)\n // 0: center\n // 1: outside (bigger side of the angle)\n float cornerPosition = sideOfPath * turnDirection;\n\n float miterSize = 1.0 / max(sinHalfA, EPSILON);\n // trim if inside corner extends further than the line segment\n miterSize = mix(\n min(miterSize, max(lenA, lenB) / max(cosHalfA, EPSILON)),\n miterSize,\n step(0.0, cornerPosition)\n );\n\n vec2 offsetVec = mix(miterVec * miterSize, perp, step(0.5, cornerPosition))\n * (sideOfPath + isJoint * turnDirection);\n\n // special treatment for start cap and end cap\n bool isStartCap = lenA == 0.0 || (!isEnd && (instanceTypes == 1.0 || instanceTypes == 3.0));\n bool isEndCap = lenB == 0.0 || (isEnd && (instanceTypes == 2.0 || instanceTypes == 3.0));\n bool isCap = isStartCap || isEndCap;\n\n // extend out a triangle to envelope the round cap\n if (isCap) {\n offsetVec = mix(perp * sideOfPath, dir * capType * 4.0 * flipIfTrue(isStartCap), isJoint);\n vJointType = capType;\n } else {\n vJointType = jointType;\n }\n\n // Generate variables for fragment shader\n vPathLength = L;\n vCornerOffset = offsetVec;\n vMiterLength = dot(vCornerOffset, miterVec * turnDirection);\n vMiterLength = isCap ? isJoint : vMiterLength;\n\n vec2 offsetFromStartOfPath = vCornerOffset + deltaA * float(isEnd);\n vPathPosition = vec2(\n dot(offsetFromStartOfPath, perp),\n dot(offsetFromStartOfPath, dir)\n );\n geometry.uv = vPathPosition;\n\n float isValid = step(instanceTypes, 3.5);\n vec3 offset = vec3(offsetVec * width * isValid, 0.0);\n\n if (needsRotation) {\n offset = rotationMatrix * offset;\n }\n return currPoint + offset;\n}\n\n// In clipspace extrusion, if a line extends behind the camera, clip it to avoid visual artifacts\nvoid clipLine(inout vec4 position, vec4 refPosition) {\n if (position.w < EPSILON) {\n float r = (EPSILON - refPosition.w) / (position.w - refPosition.w);\n position = refPosition + (position - refPosition) * r;\n }\n}\n\nvoid main() {\n geometry.pickingColor = instancePickingColors;\n\n vColor = vec4(instanceColors.rgb, instanceColors.a * opacity);\n\n float isEnd = positions.x;\n\n vec3 prevPosition = mix(instanceLeftPositions, instanceStartPositions, isEnd);\n vec3 prevPosition64Low = mix(instanceLeftPositions64Low, instanceStartPositions64Low, isEnd);\n\n vec3 currPosition = mix(instanceStartPositions, instanceEndPositions, isEnd);\n vec3 currPosition64Low = mix(instanceStartPositions64Low, instanceEndPositions64Low, isEnd);\n\n vec3 nextPosition = mix(instanceEndPositions, instanceRightPositions, isEnd);\n vec3 nextPosition64Low = mix(instanceEndPositions64Low, instanceRightPositions64Low, isEnd);\n\n geometry.worldPosition = currPosition;\n vec2 widthPixels = vec2(clamp(\n project_size_to_pixel(instanceStrokeWidths * widthScale, widthUnits),\n widthMinPixels, widthMaxPixels) / 2.0);\n vec3 width;\n\n if (billboard) {\n // Extrude in clipspace\n vec4 prevPositionScreen = project_position_to_clipspace(prevPosition, prevPosition64Low, ZERO_OFFSET);\n vec4 currPositionScreen = project_position_to_clipspace(currPosition, currPosition64Low, ZERO_OFFSET, geometry.position);\n vec4 nextPositionScreen = project_position_to_clipspace(nextPosition, nextPosition64Low, ZERO_OFFSET);\n\n clipLine(prevPositionScreen, currPositionScreen);\n clipLine(nextPositionScreen, currPositionScreen);\n clipLine(currPositionScreen, mix(nextPositionScreen, prevPositionScreen, isEnd));\n\n width = vec3(widthPixels, 0.0);\n DECKGL_FILTER_SIZE(width, geometry);\n\n vec3 pos = lineJoin(\n prevPositionScreen.xyz / prevPositionScreen.w,\n currPositionScreen.xyz / currPositionScreen.w,\n nextPositionScreen.xyz / nextPositionScreen.w,\n project_pixel_size_to_clipspace(width.xy)\n );\n\n gl_Position = vec4(pos * currPositionScreen.w, currPositionScreen.w);\n } else {\n // Extrude in commonspace\n prevPosition = project_position(prevPosition, prevPosition64Low);\n currPosition = project_position(currPosition, currPosition64Low);\n nextPosition = project_position(nextPosition, nextPosition64Low);\n\n width = vec3(project_pixel_size(widthPixels), 0.0);\n DECKGL_FILTER_SIZE(width, geometry);\n\n vec4 pos = vec4(\n lineJoin(prevPosition, currPosition, nextPosition, width.xy),\n 1.0);\n geometry.position = pos;\n gl_Position = project_common_position_to_clipspace(pos);\n }\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n#define SHADER_NAME path-layer-fragment-shader\n\nprecision highp float;\n\nuniform float miterLimit;\n\nvarying vec4 vColor;\nvarying vec2 vCornerOffset;\nvarying float vMiterLength;\n/*\n * vPathPosition represents the relative coordinates of the current fragment on the path segment.\n * vPathPosition.x - position along the width of the path, between [-1, 1]. 0 is the center line.\n * vPathPosition.y - position along the length of the path, between [0, L / width].\n */\nvarying vec2 vPathPosition;\nvarying float vPathLength;\nvarying float vJointType;\n\nvoid main(void) {\n geometry.uv = vPathPosition;\n\n if (vPathPosition.y < 0.0 || vPathPosition.y > vPathLength) {\n // if joint is rounded, test distance from the corner\n if (vJointType > 0.5 && length(vCornerOffset) > 1.0) {\n discard;\n }\n // trim miter\n if (vJointType < 0.5 && vMiterLength > miterLimit + 1.0) {\n discard;\n }\n }\n gl_FragColor = vColor;\n\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n`;\n","/* global document */\nimport GL from '@luma.gl/constants';\nimport {Texture2D, copyToTexture, cloneTextureFrom} from '@luma.gl/core';\nimport {ImageLoader} from '@loaders.gl/images';\nimport {load} from '@loaders.gl/core';\nimport {createIterable} from '@deck.gl/core';\n\nconst DEFAULT_CANVAS_WIDTH = 1024;\nconst DEFAULT_BUFFER = 4;\n\nconst noop = () => {};\n\nconst DEFAULT_TEXTURE_PARAMETERS = {\n [GL.TEXTURE_MIN_FILTER]: GL.LINEAR_MIPMAP_LINEAR,\n // GL.LINEAR is the default value but explicitly set it here\n [GL.TEXTURE_MAG_FILTER]: GL.LINEAR,\n // for texture boundary artifact\n [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE,\n [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE\n};\n\nfunction nextPowOfTwo(number) {\n return Math.pow(2, Math.ceil(Math.log2(number)));\n}\n\n// update comment to create a new texture and copy original data.\nfunction resizeImage(ctx, imageData, width, height) {\n if (width === imageData.width && height === imageData.height) {\n return imageData;\n }\n\n ctx.canvas.height = height;\n ctx.canvas.width = width;\n\n ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n\n // image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight\n ctx.drawImage(imageData, 0, 0, imageData.width, imageData.height, 0, 0, width, height);\n\n return ctx.canvas;\n}\n\nfunction getIconId(icon) {\n return icon && (icon.id || icon.url);\n}\n\n// resize texture without losing original data\nfunction resizeTexture(gl, texture, width, height) {\n const oldWidth = texture.width;\n const oldHeight = texture.height;\n\n const newTexture = cloneTextureFrom(texture, {width, height});\n copyToTexture(texture, newTexture, {\n targetY: 0,\n width: oldWidth,\n height: oldHeight\n });\n\n texture.delete();\n return newTexture;\n}\n\n// traverse icons in a row of icon atlas\n// extend each icon with left-top coordinates\nfunction buildRowMapping(mapping, columns, yOffset) {\n for (let i = 0; i < columns.length; i++) {\n const {icon, xOffset} = columns[i];\n const id = getIconId(icon);\n mapping[id] = {\n ...icon,\n x: xOffset,\n y: yOffset\n };\n }\n}\n\n/**\n * Generate coordinate mapping to retrieve icon left-top position from an icon atlas\n * @param icons {Array} list of icons, each icon requires url, width, height\n * @param buffer {Number} add buffer to the right and bottom side of the image\n * @param xOffset {Number} right position of last icon in old mapping\n * @param yOffset {Number} top position in last icon in old mapping\n * @param rowHeight {Number} rowHeight of the last icon's row\n * @param canvasWidth {Number} max width of canvas\n * @param mapping {object} old mapping\n * @returns {{mapping: {'/icon/1': {url, width, height, ...}},, canvasHeight: {Number}}}\n */\nexport function buildMapping({\n icons,\n buffer,\n mapping = {},\n xOffset = 0,\n yOffset = 0,\n rowHeight = 0,\n canvasWidth\n}) {\n let columns = [];\n // Strategy to layout all the icons into a texture:\n // traverse the icons sequentially, layout the icons from left to right, top to bottom\n // when the sum of the icons width is equal or larger than canvasWidth,\n // move to next row starting from total height so far plus max height of the icons in previous row\n // row width is equal to canvasWidth\n // row height is decided by the max height of the icons in that row\n // mapping coordinates of each icon is its left-top position in the texture\n for (let i = 0; i < icons.length; i++) {\n const icon = icons[i];\n const id = getIconId(icon);\n\n if (!mapping[id]) {\n const {height, width} = icon;\n\n // fill one row\n if (xOffset + width + buffer > canvasWidth) {\n buildRowMapping(mapping, columns, yOffset);\n\n xOffset = 0;\n yOffset = rowHeight + yOffset + buffer;\n rowHeight = 0;\n columns = [];\n }\n\n columns.push({\n icon,\n xOffset\n });\n\n xOffset = xOffset + width + buffer;\n rowHeight = Math.max(rowHeight, height);\n }\n }\n\n if (columns.length > 0) {\n buildRowMapping(mapping, columns, yOffset);\n }\n\n return {\n mapping,\n rowHeight,\n xOffset,\n yOffset,\n canvasWidth,\n canvasHeight: nextPowOfTwo(rowHeight + yOffset + buffer)\n };\n}\n\n// extract icons from data\n// return icons should be unique, and not cached or cached but url changed\nexport function getDiffIcons(data, getIcon, cachedIcons) {\n if (!data || !getIcon) {\n return null;\n }\n\n cachedIcons = cachedIcons || {};\n const icons = {};\n const {iterable, objectInfo} = createIterable(data);\n for (const object of iterable) {\n objectInfo.index++;\n const icon = getIcon(object, objectInfo);\n const id = getIconId(icon);\n\n if (!icon) {\n throw new Error('Icon is missing.');\n }\n\n if (!icon.url) {\n throw new Error('Icon url is missing.');\n }\n\n if (!icons[id] && (!cachedIcons[id] || icon.url !== cachedIcons[id].url)) {\n icons[id] = {...icon, source: object, sourceIndex: objectInfo.index};\n }\n }\n return icons;\n}\n\nexport default class IconManager {\n constructor(\n gl,\n {\n onUpdate = noop, // notify IconLayer when icon texture update\n onError = noop\n }\n ) {\n this.gl = gl;\n this.onUpdate = onUpdate;\n this.onError = onError;\n\n // load options used for loading images\n this._loadOptions = null;\n this._getIcon = null;\n\n this._texture = null;\n this._externalTexture = null;\n this._mapping = {};\n // count of pending requests to fetch icons\n this._pendingCount = 0;\n\n this._autoPacking = false;\n\n // internal props used when autoPacking applied\n // right position of last icon\n this._xOffset = 0;\n // top position of last icon\n this._yOffset = 0;\n this._rowHeight = 0;\n this._buffer = DEFAULT_BUFFER;\n this._canvasWidth = DEFAULT_CANVAS_WIDTH;\n this._canvasHeight = 0;\n this._canvas = null;\n }\n\n finalize() {\n this._texture?.delete();\n }\n\n getTexture() {\n return this._texture || this._externalTexture;\n }\n\n getIconMapping(icon) {\n const id = this._autoPacking ? getIconId(icon) : icon;\n return this._mapping[id] || {};\n }\n\n setProps({loadOptions, autoPacking, iconAtlas, iconMapping, data, getIcon}) {\n if (loadOptions) {\n this._loadOptions = loadOptions;\n }\n\n if (autoPacking !== undefined) {\n this._autoPacking = autoPacking;\n }\n\n if (getIcon) {\n this._getIcon = getIcon;\n }\n\n if (iconMapping) {\n this._mapping = iconMapping;\n }\n\n if (iconAtlas) {\n this._updateIconAtlas(iconAtlas);\n }\n\n if (this._autoPacking && (data || getIcon) && typeof document !== 'undefined') {\n this._canvas = this._canvas || document.createElement('canvas');\n\n this._updateAutoPacking(data);\n }\n }\n\n get isLoaded() {\n return this._pendingCount === 0;\n }\n\n _updateIconAtlas(iconAtlas) {\n this._texture?.delete();\n this._texture = null;\n this._externalTexture = iconAtlas;\n this.onUpdate();\n }\n\n _updateAutoPacking(data) {\n const icons = Object.values(getDiffIcons(data, this._getIcon, this._mapping) || {});\n\n if (icons.length > 0) {\n // generate icon mapping\n const {mapping, xOffset, yOffset, rowHeight, canvasHeight} = buildMapping({\n icons,\n buffer: this._buffer,\n canvasWidth: this._canvasWidth,\n mapping: this._mapping,\n rowHeight: this._rowHeight,\n xOffset: this._xOffset,\n yOffset: this._yOffset\n });\n\n this._rowHeight = rowHeight;\n this._mapping = mapping;\n this._xOffset = xOffset;\n this._yOffset = yOffset;\n this._canvasHeight = canvasHeight;\n\n // create new texture\n if (!this._texture) {\n this._texture = new Texture2D(this.gl, {\n width: this._canvasWidth,\n height: this._canvasHeight,\n parameters: DEFAULT_TEXTURE_PARAMETERS\n });\n }\n\n if (this._texture.height !== this._canvasHeight) {\n this._texture = resizeTexture(\n this.gl,\n this._texture,\n this._canvasWidth,\n this._canvasHeight\n );\n }\n\n this.onUpdate();\n\n // load images\n this._loadIcons(icons);\n }\n }\n\n _loadIcons(icons) {\n const ctx = this._canvas.getContext('2d');\n\n for (const icon of icons) {\n this._pendingCount++;\n load(icon.url, ImageLoader, this._loadOptions)\n .then(imageData => {\n const id = getIconId(icon);\n const {x, y, width, height} = this._mapping[id];\n\n const data = resizeImage(ctx, imageData, width, height);\n\n this._texture.setSubImageData({\n data,\n x,\n y,\n width,\n height\n });\n\n // Call to regenerate mipmaps after modifying texture(s)\n this._texture.generateMipmap();\n\n this.onUpdate();\n })\n .catch(error => {\n this.onError({\n url: icon.url,\n source: icon.source,\n sourceIndex: icon.sourceIndex,\n loadOptions: this._loadOptions,\n error\n });\n })\n .finally(() => {\n this._pendingCount--;\n });\n }\n }\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\nimport {Layer, project32, picking, log, UNIT} from '@deck.gl/core';\nimport GL from '@luma.gl/constants';\nimport {Model, Geometry} from '@luma.gl/core';\n\nimport vs from './icon-layer-vertex.glsl';\nimport fs from './icon-layer-fragment.glsl';\nimport IconManager from './icon-manager';\n\nconst DEFAULT_COLOR = [0, 0, 0, 255];\n/*\n * @param {object} props\n * @param {Texture2D | string} props.iconAtlas - atlas image url or texture\n * @param {object} props.iconMapping - icon names mapped to icon definitions\n * @param {object} props.iconMapping[icon_name].x - x position of icon on the atlas image\n * @param {object} props.iconMapping[icon_name].y - y position of icon on the atlas image\n * @param {object} props.iconMapping[icon_name].width - width of icon on the atlas image\n * @param {object} props.iconMapping[icon_name].height - height of icon on the atlas image\n * @param {object} props.iconMapping[icon_name].anchorX - x anchor of icon on the atlas image,\n * default to width / 2\n * @param {object} props.iconMapping[icon_name].anchorY - y anchor of icon on the atlas image,\n * default to height / 2\n * @param {object} props.iconMapping[icon_name].mask - whether icon is treated as a transparency\n * mask. If true, user defined color is applied. If false, original color from the image is\n * applied. Default to false.\n * @param {number} props.size - icon size in pixels\n * @param {func} props.getPosition - returns anchor position of the icon, in [lng, lat, z]\n * @param {func} props.getIcon - returns icon name as a string\n * @param {func} props.getSize - returns icon size multiplier as a number\n * @param {func} props.getColor - returns color of the icon in [r, g, b, a]. Only works on icons\n * with mask: true.\n * @param {func} props.getAngle - returns rotating angle (in degree) of the icon.\n */\nconst defaultProps = {\n iconAtlas: {type: 'image', value: null, async: true},\n iconMapping: {type: 'object', value: {}, async: true},\n sizeScale: {type: 'number', value: 1, min: 0},\n billboard: true,\n sizeUnits: 'pixels',\n sizeMinPixels: {type: 'number', min: 0, value: 0}, // min point radius in pixels\n sizeMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER}, // max point radius in pixels\n alphaCutoff: {type: 'number', value: 0.05, min: 0, max: 1},\n\n getPosition: {type: 'accessor', value: x => x.position},\n getIcon: {type: 'accessor', value: x => x.icon},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getSize: {type: 'accessor', value: 1},\n getAngle: {type: 'accessor', value: 0},\n getPixelOffset: {type: 'accessor', value: [0, 0]},\n\n onIconError: {type: 'function', value: null, compare: false, optional: true}\n};\n\nexport default class IconLayer extends Layer {\n getShaders() {\n return super.getShaders({vs, fs, modules: [project32, picking]});\n }\n\n initializeState() {\n this.state = {\n iconManager: new IconManager(this.context.gl, {\n onUpdate: this._onUpdate.bind(this),\n onError: this._onError.bind(this)\n })\n };\n\n const attributeManager = this.getAttributeManager();\n /* eslint-disable max-len */\n attributeManager.addInstanced({\n instancePositions: {\n size: 3,\n type: GL.DOUBLE,\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceSizes: {\n size: 1,\n transition: true,\n accessor: 'getSize',\n defaultValue: 1\n },\n instanceOffsets: {size: 2, accessor: 'getIcon', transform: this.getInstanceOffset},\n instanceIconFrames: {size: 4, accessor: 'getIcon', transform: this.getInstanceIconFrame},\n instanceColorModes: {\n size: 1,\n type: GL.UNSIGNED_BYTE,\n accessor: 'getIcon',\n transform: this.getInstanceColorMode\n },\n instanceColors: {\n size: this.props.colorFormat.length,\n type: GL.UNSIGNED_BYTE,\n normalized: true,\n transition: true,\n accessor: 'getColor',\n defaultValue: DEFAULT_COLOR\n },\n instanceAngles: {\n size: 1,\n transition: true,\n accessor: 'getAngle'\n },\n instancePixelOffset: {\n size: 2,\n transition: true,\n accessor: 'getPixelOffset'\n }\n });\n /* eslint-enable max-len */\n }\n\n /* eslint-disable max-statements, complexity */\n updateState({oldProps, props, changeFlags}) {\n super.updateState({props, oldProps, changeFlags});\n\n const attributeManager = this.getAttributeManager();\n const {iconAtlas, iconMapping, data, getIcon} = props;\n const {iconManager} = this.state;\n\n iconManager.setProps({loadOptions: props.loadOptions});\n\n let iconMappingChanged = false;\n const prePacked = iconAtlas || this.internalState.isAsyncPropLoading('iconAtlas');\n\n // prepacked iconAtlas from user\n if (prePacked) {\n if (oldProps.iconAtlas !== props.iconAtlas) {\n iconManager.setProps({iconAtlas, autoPacking: false});\n }\n\n if (oldProps.iconMapping !== props.iconMapping) {\n iconManager.setProps({iconMapping});\n iconMappingChanged = true;\n }\n } else {\n // otherwise, use autoPacking\n iconManager.setProps({autoPacking: true});\n }\n\n if (\n changeFlags.dataChanged ||\n (changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getIcon))\n ) {\n iconManager.setProps({data, getIcon});\n }\n\n if (iconMappingChanged) {\n attributeManager.invalidate('instanceOffsets');\n attributeManager.invalidate('instanceIconFrames');\n attributeManager.invalidate('instanceColorModes');\n }\n\n if (changeFlags.extensionsChanged) {\n const {gl} = this.context;\n this.state.model?.delete();\n this.state.model = this._getModel(gl);\n attributeManager.invalidateAll();\n }\n }\n /* eslint-enable max-statements, complexity */\n\n get isLoaded() {\n return super.isLoaded && this.state.iconManager.isLoaded;\n }\n\n finalizeState() {\n super.finalizeState();\n // Release resources held by the icon manager\n this.state.iconManager.finalize();\n }\n\n draw({uniforms}) {\n const {sizeScale, sizeMinPixels, sizeMaxPixels, sizeUnits, billboard, alphaCutoff} = this.props;\n const {iconManager} = this.state;\n\n const iconsTexture = iconManager.getTexture();\n if (iconsTexture) {\n this.state.model\n .setUniforms(uniforms)\n .setUniforms({\n iconsTexture,\n iconsTextureDim: [iconsTexture.width, iconsTexture.height],\n sizeUnits: UNIT[sizeUnits],\n sizeScale,\n sizeMinPixels,\n sizeMaxPixels,\n billboard,\n alphaCutoff\n })\n .draw();\n }\n }\n\n _getModel(gl) {\n // The icon-layer vertex shader uses 2d positions\n // specifed via: attribute vec2 positions;\n const positions = [-1, -1, -1, 1, 1, 1, 1, -1];\n\n return new Model(gl, {\n ...this.getShaders(),\n id: this.props.id,\n geometry: new Geometry({\n drawMode: GL.TRIANGLE_FAN,\n attributes: {\n // The size must be explicitly passed here otherwise luma.gl\n // will default to assuming that positions are 3D (x,y,z)\n positions: {\n size: 2,\n value: new Float32Array(positions)\n }\n }\n }),\n isInstanced: true\n });\n }\n\n _onUpdate() {\n this.setNeedsRedraw();\n }\n\n _onError(evt) {\n const {onIconError} = this.getCurrentLayer().props;\n if (onIconError) {\n onIconError(evt);\n } else {\n log.error(evt.error)();\n }\n }\n\n getInstanceOffset(icon) {\n const rect = this.state.iconManager.getIconMapping(icon);\n return [rect.width / 2 - rect.anchorX || 0, rect.height / 2 - rect.anchorY || 0];\n }\n\n getInstanceColorMode(icon) {\n const mapping = this.state.iconManager.getIconMapping(icon);\n return mapping.mask ? 1 : 0;\n }\n\n getInstanceIconFrame(icon) {\n const rect = this.state.iconManager.getIconMapping(icon);\n return [rect.x || 0, rect.y || 0, rect.width || 0, rect.height || 0];\n }\n}\n\nIconLayer.layerName = 'IconLayer';\nIconLayer.defaultProps = defaultProps;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n#define SHADER_NAME icon-layer-vertex-shader\n\nattribute vec2 positions;\n\nattribute vec3 instancePositions;\nattribute vec3 instancePositions64Low;\nattribute float instanceSizes;\nattribute float instanceAngles;\nattribute vec4 instanceColors;\nattribute vec3 instancePickingColors;\nattribute vec4 instanceIconFrames;\nattribute float instanceColorModes;\nattribute vec2 instanceOffsets;\nattribute vec2 instancePixelOffset;\n\nuniform float sizeScale;\nuniform vec2 iconsTextureDim;\nuniform float sizeMinPixels;\nuniform float sizeMaxPixels;\nuniform bool billboard;\nuniform int sizeUnits;\n\nvarying float vColorMode;\nvarying vec4 vColor;\nvarying vec2 vTextureCoords;\nvarying vec2 uv;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = angle * PI / 180.0;\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n\n vec2 iconSize = instanceIconFrames.zw;\n // convert size in meters to pixels, then scaled and clamp\n \n // project meters to pixels and clamp to limits \n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * sizeScale, sizeUnits), \n sizeMinPixels, sizeMaxPixels\n );\n\n // scale icon height to match instanceSize\n float instanceScale = iconSize.y == 0.0 ? 0.0 : sizePixels / iconSize.y;\n\n // scale and rotate vertex in \"pixel\" value and convert back to fraction in clipspace\n vec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\n pixelOffset += instancePixelOffset;\n pixelOffset.y *= -1.0;\n\n if (billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n DECKGL_FILTER_SIZE(offset_common, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position); \n }\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n vTextureCoords = mix(\n instanceIconFrames.xy,\n instanceIconFrames.xy + iconSize,\n (positions.xy + 1.0) / 2.0\n ) / iconsTextureDim;\n\n vColor = instanceColors;\n DECKGL_FILTER_COLOR(vColor, geometry);\n\n vColorMode = instanceColorModes;\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n#define SHADER_NAME icon-layer-fragment-shader\n\nprecision highp float;\n\nuniform float opacity;\nuniform sampler2D iconsTexture;\nuniform float alphaCutoff;\n\nvarying float vColorMode;\nvarying vec4 vColor;\nvarying vec2 vTextureCoords;\nvarying vec2 uv;\n\nvoid main(void) {\n geometry.uv = uv;\n\n vec4 texColor = texture2D(iconsTexture, vTextureCoords);\n\n // if colorMode == 0, use pixel color from the texture\n // if colorMode == 1 or rendering picking buffer, use texture as transparency mask\n vec3 color = mix(texColor.rgb, vColor.rgb, vColorMode);\n // Take the global opacity and the alpha from vColor into account for the alpha component\n float a = texColor.a * opacity * vColor.a;\n\n if (a < alphaCutoff) {\n discard;\n }\n\n gl_FragColor = vec4(color, a);\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n`;\n","/**\n * @module helpers\n */\n/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n *\n * @memberof helpers\n * @type {number}\n */\nexport var earthRadius = 6371008.8;\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var factors = {\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n degrees: earthRadius / 111325,\n feet: earthRadius * 3.28084,\n inches: earthRadius * 39.37,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n meters: earthRadius,\n metres: earthRadius,\n miles: earthRadius / 1609.344,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n nauticalmiles: earthRadius / 1852,\n radians: 1,\n yards: earthRadius * 1.0936,\n};\n/**\n * Units of measurement factors based on 1 meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var unitsFactors = {\n centimeters: 100,\n centimetres: 100,\n degrees: 1 / 111325,\n feet: 3.28084,\n inches: 39.37,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n meters: 1,\n metres: 1,\n miles: 1 / 1609.344,\n millimeters: 1000,\n millimetres: 1000,\n nauticalmiles: 1 / 1852,\n radians: 1 / earthRadius,\n yards: 1.0936133,\n};\n/**\n * Area of measurement factors based on 1 square meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var areaFactors = {\n acres: 0.000247105,\n centimeters: 10000,\n centimetres: 10000,\n feet: 10.763910417,\n hectares: 0.0001,\n inches: 1550.003100006,\n kilometers: 0.000001,\n kilometres: 0.000001,\n meters: 1,\n metres: 1,\n miles: 3.86e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nexport function feature(geom, properties, options) {\n if (options === void 0) { options = {}; }\n var feat = { type: \"Feature\" };\n if (options.id === 0 || options.id) {\n feat.id = options.id;\n }\n if (options.bbox) {\n feat.bbox = options.bbox;\n }\n feat.properties = properties || {};\n feat.geometry = geom;\n return feat;\n}\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = \"Point\";\n * var coordinates = [110, 50];\n * var geometry = turf.geometry(type, coordinates);\n * // => geometry\n */\nexport function geometry(type, coordinates, _options) {\n if (_options === void 0) { _options = {}; }\n switch (type) {\n case \"Point\":\n return point(coordinates).geometry;\n case \"LineString\":\n return lineString(coordinates).geometry;\n case \"Polygon\":\n return polygon(coordinates).geometry;\n case \"MultiPoint\":\n return multiPoint(coordinates).geometry;\n case \"MultiLineString\":\n return multiLineString(coordinates).geometry;\n case \"MultiPolygon\":\n return multiPolygon(coordinates).geometry;\n default:\n throw new Error(type + \" is invalid\");\n }\n}\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nexport function point(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (!coordinates) {\n throw new Error(\"coordinates is required\");\n }\n if (!Array.isArray(coordinates)) {\n throw new Error(\"coordinates must be an Array\");\n }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be at least 2 numbers long\");\n }\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {\n throw new Error(\"coordinates must contain numbers\");\n }\n var geom = {\n type: \"Point\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nexport function points(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nexport function polygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {\n var ring = coordinates_1[_i];\n if (ring.length < 4) {\n throw new Error(\"Each LinearRing of a Polygon must have 4 or more Positions.\");\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n }\n }\n var geom = {\n type: \"Polygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nexport function polygons(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nexport function lineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n var geom = {\n type: \"LineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nexport function lineStrings(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nexport function featureCollection(features, options) {\n if (options === void 0) { options = {}; }\n var fc = { type: \"FeatureCollection\" };\n if (options.id) {\n fc.id = options.id;\n }\n if (options.bbox) {\n fc.bbox = options.bbox;\n }\n fc.features = features;\n return fc;\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nexport function multiLineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiLineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nexport function multiPoint(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPoint\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nexport function multiPolygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPolygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = turf.geometry(\"Point\", [100, 0]);\n * var line = turf.geometry(\"LineString\", [[101, 0], [102, 1]]);\n * var collection = turf.geometryCollection([pt, line]);\n *\n * // => collection\n */\nexport function geometryCollection(geometries, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"GeometryCollection\",\n geometries: geometries,\n };\n return feature(geom, properties, options);\n}\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nexport function round(num, precision) {\n if (precision === void 0) { precision = 0; }\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nexport function radiansToLength(radians, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return radians * factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nexport function lengthToRadians(distance, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return distance / factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nexport function lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nexport function bearingToAzimuth(bearing) {\n var angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nexport function radiansToDegrees(radians) {\n var degrees = radians % (2 * Math.PI);\n return (degrees * 180) / Math.PI;\n}\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nexport function degreesToRadians(degrees) {\n var radians = degrees % 360;\n return (radians * Math.PI) / 180;\n}\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] of the length\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted length\n */\nexport function convertLength(length, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"kilometers\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(length >= 0)) {\n throw new Error(\"length must be a positive number\");\n }\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);\n}\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches, hectares\n * @param {number} area to be converted\n * @param {Units} [originalUnit=\"meters\"] of the distance\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted area\n */\nexport function convertArea(area, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"meters\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n var startFactor = areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n var finalFactor = areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n return (area / startFactor) * finalFactor;\n}\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nexport function isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nexport function isObject(input) {\n return !!input && input.constructor === Object;\n}\n/**\n * Validate BBox\n *\n * @private\n * @param {Array} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nexport function validateBBox(bbox) {\n if (!bbox) {\n throw new Error(\"bbox is required\");\n }\n if (!Array.isArray(bbox)) {\n throw new Error(\"bbox must be an Array\");\n }\n if (bbox.length !== 4 && bbox.length !== 6) {\n throw new Error(\"bbox must be an Array of 4 or 6 numbers\");\n }\n bbox.forEach(function (num) {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nexport function validateId(id) {\n if (!id) {\n throw new Error(\"id is required\");\n }\n if ([\"string\", \"number\"].indexOf(typeof id) === -1) {\n throw new Error(\"id must be a number or a string\");\n }\n}\n","import { feature, lineString, isObject, point } from '@turf/helpers';\n\n/**\n * Callback for coordEach\n *\n * @callback coordEachCallback\n * @param {Array} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Iterate over coordinates in any GeoJSON object, similar to Array.forEach()\n *\n * @name coordEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, multiFeatureIndex)\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction coordEach(geojson, callback, excludeWrapCoord) {\n // Handles null Geometry -- Skips this GeoJSON\n if (geojson === null) return;\n var j,\n k,\n l,\n geometry,\n stopG,\n coords,\n geometryMaybeCollection,\n wrapShrink = 0,\n coordIndex = 0,\n isGeometryCollection,\n type = geojson.type,\n isFeatureCollection = type === \"FeatureCollection\",\n isFeature = type === \"Feature\",\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (var featureIndex = 0; featureIndex < stop; featureIndex++) {\n geometryMaybeCollection = isFeatureCollection\n ? geojson.features[featureIndex].geometry\n : isFeature\n ? geojson.geometry\n : geojson;\n isGeometryCollection = geometryMaybeCollection\n ? geometryMaybeCollection.type === \"GeometryCollection\"\n : false;\n stopG = isGeometryCollection\n ? geometryMaybeCollection.geometries.length\n : 1;\n\n for (var geomIndex = 0; geomIndex < stopG; geomIndex++) {\n var multiFeatureIndex = 0;\n var geometryIndex = 0;\n geometry = isGeometryCollection\n ? geometryMaybeCollection.geometries[geomIndex]\n : geometryMaybeCollection;\n\n // Handles null Geometry -- Skips this geometry\n if (geometry === null) continue;\n coords = geometry.coordinates;\n var geomType = geometry.type;\n\n wrapShrink =\n excludeWrapCoord &&\n (geomType === \"Polygon\" || geomType === \"MultiPolygon\")\n ? 1\n : 0;\n\n switch (geomType) {\n case null:\n break;\n case \"Point\":\n if (\n callback(\n coords,\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n return false;\n coordIndex++;\n multiFeatureIndex++;\n break;\n case \"LineString\":\n case \"MultiPoint\":\n for (j = 0; j < coords.length; j++) {\n if (\n callback(\n coords[j],\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n return false;\n coordIndex++;\n if (geomType === \"MultiPoint\") multiFeatureIndex++;\n }\n if (geomType === \"LineString\") multiFeatureIndex++;\n break;\n case \"Polygon\":\n case \"MultiLineString\":\n for (j = 0; j < coords.length; j++) {\n for (k = 0; k < coords[j].length - wrapShrink; k++) {\n if (\n callback(\n coords[j][k],\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n return false;\n coordIndex++;\n }\n if (geomType === \"MultiLineString\") multiFeatureIndex++;\n if (geomType === \"Polygon\") geometryIndex++;\n }\n if (geomType === \"Polygon\") multiFeatureIndex++;\n break;\n case \"MultiPolygon\":\n for (j = 0; j < coords.length; j++) {\n geometryIndex = 0;\n for (k = 0; k < coords[j].length; k++) {\n for (l = 0; l < coords[j][k].length - wrapShrink; l++) {\n if (\n callback(\n coords[j][k][l],\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n return false;\n coordIndex++;\n }\n geometryIndex++;\n }\n multiFeatureIndex++;\n }\n break;\n case \"GeometryCollection\":\n for (j = 0; j < geometry.geometries.length; j++)\n if (\n coordEach(geometry.geometries[j], callback, excludeWrapCoord) ===\n false\n )\n return false;\n break;\n default:\n throw new Error(\"Unknown Geometry Type\");\n }\n }\n }\n}\n\n/**\n * Callback for coordReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback coordReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Array} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * Starts at index 0, if an initialValue is provided, and at index 1 otherwise.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Reduce coordinates in any GeoJSON object, similar to Array.reduce()\n *\n * @name coordReduce\n * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentCoord;\n * });\n */\nfunction coordReduce(geojson, callback, initialValue, excludeWrapCoord) {\n var previousValue = initialValue;\n coordEach(\n geojson,\n function (\n currentCoord,\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) {\n if (coordIndex === 0 && initialValue === undefined)\n previousValue = currentCoord;\n else\n previousValue = callback(\n previousValue,\n currentCoord,\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n );\n },\n excludeWrapCoord\n );\n return previousValue;\n}\n\n/**\n * Callback for propEach\n *\n * @callback propEachCallback\n * @param {Object} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over properties in any GeoJSON object, similar to Array.forEach()\n *\n * @name propEach\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentProperties, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propEach(features, function (currentProperties, featureIndex) {\n * //=currentProperties\n * //=featureIndex\n * });\n */\nfunction propEach(geojson, callback) {\n var i;\n switch (geojson.type) {\n case \"FeatureCollection\":\n for (i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i].properties, i) === false) break;\n }\n break;\n case \"Feature\":\n callback(geojson.properties, 0);\n break;\n }\n}\n\n/**\n * Callback for propReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback propReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {*} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce properties in any GeoJSON object into a single value,\n * similar to how Array.reduce works. However, in this case we lazily run\n * the reduction, so an array of all properties is unnecessary.\n *\n * @name propReduce\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) {\n * //=previousValue\n * //=currentProperties\n * //=featureIndex\n * return currentProperties\n * });\n */\nfunction propReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n propEach(geojson, function (currentProperties, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined)\n previousValue = currentProperties;\n else\n previousValue = callback(previousValue, currentProperties, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Callback for featureEach\n *\n * @callback featureEachCallback\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name featureEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.featureEach(features, function (currentFeature, featureIndex) {\n * //=currentFeature\n * //=featureIndex\n * });\n */\nfunction featureEach(geojson, callback) {\n if (geojson.type === \"Feature\") {\n callback(geojson, 0);\n } else if (geojson.type === \"FeatureCollection\") {\n for (var i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i], i) === false) break;\n }\n }\n}\n\n/**\n * Callback for featureReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback featureReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name featureReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * return currentFeature\n * });\n */\nfunction featureReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n featureEach(geojson, function (currentFeature, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined)\n previousValue = currentFeature;\n else previousValue = callback(previousValue, currentFeature, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Get all coordinates from any GeoJSON object.\n *\n * @name coordAll\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @returns {Array>} coordinate position array\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * var coords = turf.coordAll(features);\n * //= [[26, 37], [36, 53]]\n */\nfunction coordAll(geojson) {\n var coords = [];\n coordEach(geojson, function (coord) {\n coords.push(coord);\n });\n return coords;\n}\n\n/**\n * Callback for geomEach\n *\n * @callback geomEachCallback\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Iterate over each geometry in any GeoJSON object, similar to Array.forEach()\n *\n * @name geomEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * });\n */\nfunction geomEach(geojson, callback) {\n var i,\n j,\n g,\n geometry,\n stopG,\n geometryMaybeCollection,\n isGeometryCollection,\n featureProperties,\n featureBBox,\n featureId,\n featureIndex = 0,\n isFeatureCollection = geojson.type === \"FeatureCollection\",\n isFeature = geojson.type === \"Feature\",\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (i = 0; i < stop; i++) {\n geometryMaybeCollection = isFeatureCollection\n ? geojson.features[i].geometry\n : isFeature\n ? geojson.geometry\n : geojson;\n featureProperties = isFeatureCollection\n ? geojson.features[i].properties\n : isFeature\n ? geojson.properties\n : {};\n featureBBox = isFeatureCollection\n ? geojson.features[i].bbox\n : isFeature\n ? geojson.bbox\n : undefined;\n featureId = isFeatureCollection\n ? geojson.features[i].id\n : isFeature\n ? geojson.id\n : undefined;\n isGeometryCollection = geometryMaybeCollection\n ? geometryMaybeCollection.type === \"GeometryCollection\"\n : false;\n stopG = isGeometryCollection\n ? geometryMaybeCollection.geometries.length\n : 1;\n\n for (g = 0; g < stopG; g++) {\n geometry = isGeometryCollection\n ? geometryMaybeCollection.geometries[g]\n : geometryMaybeCollection;\n\n // Handle null Geometry\n if (geometry === null) {\n if (\n callback(\n null,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) === false\n )\n return false;\n continue;\n }\n switch (geometry.type) {\n case \"Point\":\n case \"LineString\":\n case \"MultiPoint\":\n case \"Polygon\":\n case \"MultiLineString\":\n case \"MultiPolygon\": {\n if (\n callback(\n geometry,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) === false\n )\n return false;\n break;\n }\n case \"GeometryCollection\": {\n for (j = 0; j < geometry.geometries.length; j++) {\n if (\n callback(\n geometry.geometries[j],\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) === false\n )\n return false;\n }\n break;\n }\n default:\n throw new Error(\"Unknown Geometry Type\");\n }\n }\n // Only increase `featureIndex` per each feature\n featureIndex++;\n }\n}\n\n/**\n * Callback for geomReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback geomReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Reduce geometry in any GeoJSON object, similar to Array.reduce().\n *\n * @name geomReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=previousValue\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * return currentGeometry\n * });\n */\nfunction geomReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n geomEach(\n geojson,\n function (\n currentGeometry,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) {\n if (featureIndex === 0 && initialValue === undefined)\n previousValue = currentGeometry;\n else\n previousValue = callback(\n previousValue,\n currentGeometry,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n );\n }\n );\n return previousValue;\n}\n\n/**\n * Callback for flattenEach\n *\n * @callback flattenEachCallback\n * @param {Feature} currentFeature The current flattened feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Iterate over flattened features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name flattenEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex)\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) {\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * });\n */\nfunction flattenEach(geojson, callback) {\n geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) {\n // Callback for single geometry\n var type = geometry === null ? null : geometry.type;\n switch (type) {\n case null:\n case \"Point\":\n case \"LineString\":\n case \"Polygon\":\n if (\n callback(\n feature(geometry, properties, { bbox: bbox, id: id }),\n featureIndex,\n 0\n ) === false\n )\n return false;\n return;\n }\n\n var geomType;\n\n // Callback for multi-geometry\n switch (type) {\n case \"MultiPoint\":\n geomType = \"Point\";\n break;\n case \"MultiLineString\":\n geomType = \"LineString\";\n break;\n case \"MultiPolygon\":\n geomType = \"Polygon\";\n break;\n }\n\n for (\n var multiFeatureIndex = 0;\n multiFeatureIndex < geometry.coordinates.length;\n multiFeatureIndex++\n ) {\n var coordinate = geometry.coordinates[multiFeatureIndex];\n var geom = {\n type: geomType,\n coordinates: coordinate,\n };\n if (\n callback(feature(geom, properties), featureIndex, multiFeatureIndex) ===\n false\n )\n return false;\n }\n });\n}\n\n/**\n * Callback for flattenReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback flattenReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Reduce flattened features in any GeoJSON object, similar to Array.reduce().\n *\n * @name flattenReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * return currentFeature\n * });\n */\nfunction flattenReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n flattenEach(\n geojson,\n function (currentFeature, featureIndex, multiFeatureIndex) {\n if (\n featureIndex === 0 &&\n multiFeatureIndex === 0 &&\n initialValue === undefined\n )\n previousValue = currentFeature;\n else\n previousValue = callback(\n previousValue,\n currentFeature,\n featureIndex,\n multiFeatureIndex\n );\n }\n );\n return previousValue;\n}\n\n/**\n * Callback for segmentEach\n *\n * @callback segmentEachCallback\n * @param {Feature} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n * @returns {void}\n */\n\n/**\n * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex)\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //=currentSegment\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * //=segmentIndex\n * });\n *\n * // Calculate the total number of segments\n * var total = 0;\n * turf.segmentEach(polygon, function () {\n * total++;\n * });\n */\nfunction segmentEach(geojson, callback) {\n flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) {\n var segmentIndex = 0;\n\n // Exclude null Geometries\n if (!feature.geometry) return;\n // (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n var type = feature.geometry.type;\n if (type === \"Point\" || type === \"MultiPoint\") return;\n\n // Generate 2-vertex line segments\n var previousCoords;\n var previousFeatureIndex = 0;\n var previousMultiIndex = 0;\n var prevGeomIndex = 0;\n if (\n coordEach(\n feature,\n function (\n currentCoord,\n coordIndex,\n featureIndexCoord,\n multiPartIndexCoord,\n geometryIndex\n ) {\n // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false`\n if (\n previousCoords === undefined ||\n featureIndex > previousFeatureIndex ||\n multiPartIndexCoord > previousMultiIndex ||\n geometryIndex > prevGeomIndex\n ) {\n previousCoords = currentCoord;\n previousFeatureIndex = featureIndex;\n previousMultiIndex = multiPartIndexCoord;\n prevGeomIndex = geometryIndex;\n segmentIndex = 0;\n return;\n }\n var currentSegment = lineString(\n [previousCoords, currentCoord],\n feature.properties\n );\n if (\n callback(\n currentSegment,\n featureIndex,\n multiFeatureIndex,\n geometryIndex,\n segmentIndex\n ) === false\n )\n return false;\n segmentIndex++;\n previousCoords = currentCoord;\n }\n ) === false\n )\n return false;\n });\n}\n\n/**\n * Callback for segmentReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback segmentReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n */\n\n/**\n * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //= previousSegment\n * //= currentSegment\n * //= featureIndex\n * //= multiFeatureIndex\n * //= geometryIndex\n * //= segmentIndex\n * return currentSegment\n * });\n *\n * // Calculate the total number of segments\n * var initialValue = 0\n * var total = turf.segmentReduce(polygon, function (previousValue) {\n * previousValue++;\n * return previousValue;\n * }, initialValue);\n */\nfunction segmentReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n var started = false;\n segmentEach(\n geojson,\n function (\n currentSegment,\n featureIndex,\n multiFeatureIndex,\n geometryIndex,\n segmentIndex\n ) {\n if (started === false && initialValue === undefined)\n previousValue = currentSegment;\n else\n previousValue = callback(\n previousValue,\n currentSegment,\n featureIndex,\n multiFeatureIndex,\n geometryIndex,\n segmentIndex\n );\n started = true;\n }\n );\n return previousValue;\n}\n\n/**\n * Callback for lineEach\n *\n * @callback lineEachCallback\n * @param {Feature} currentLine The current LineString|LinearRing being processed\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries,\n * similar to Array.forEach.\n *\n * @name lineEach\n * @param {Geometry|Feature} geojson object\n * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @example\n * var multiLine = turf.multiLineString([\n * [[26, 37], [35, 45]],\n * [[36, 53], [38, 50], [41, 55]]\n * ]);\n *\n * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction lineEach(geojson, callback) {\n // validation\n if (!geojson) throw new Error(\"geojson is required\");\n\n flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) {\n if (feature.geometry === null) return;\n var type = feature.geometry.type;\n var coords = feature.geometry.coordinates;\n switch (type) {\n case \"LineString\":\n if (callback(feature, featureIndex, multiFeatureIndex, 0, 0) === false)\n return false;\n break;\n case \"Polygon\":\n for (\n var geometryIndex = 0;\n geometryIndex < coords.length;\n geometryIndex++\n ) {\n if (\n callback(\n lineString(coords[geometryIndex], feature.properties),\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n return false;\n }\n break;\n }\n });\n}\n\n/**\n * Callback for lineReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback lineReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentLine The current LineString|LinearRing being processed.\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name lineReduce\n * @param {Geometry|Feature} geojson object\n * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var multiPoly = turf.multiPolygon([\n * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]),\n * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]])\n * ]);\n *\n * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentLine\n * });\n */\nfunction lineReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n lineEach(\n geojson,\n function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n if (featureIndex === 0 && initialValue === undefined)\n previousValue = currentLine;\n else\n previousValue = callback(\n previousValue,\n currentLine,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n );\n }\n );\n return previousValue;\n}\n\n/**\n * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n * Point & MultiPoint will always return null.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.segmentIndex=0] Segment Index\n * @param {Object} [options.properties={}] Translate Properties to output LineString\n * @param {BBox} [options.bbox={}] Translate BBox to output LineString\n * @param {number|string} [options.id={}] Translate Id to output LineString\n * @returns {Feature} 2-vertex GeoJSON Feature LineString\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findSegment(multiLine);\n * // => Feature>\n *\n * // First Segment of 2nd Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: 1});\n * // => Feature>\n *\n * // Last Segment of Last Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1});\n * // => Feature>\n */\nfunction findSegment(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error(\"options is invalid\");\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var segmentIndex = options.segmentIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case \"FeatureCollection\":\n if (featureIndex < 0)\n featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case \"Feature\":\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case \"Point\":\n case \"MultiPoint\":\n return null;\n case \"LineString\":\n case \"Polygon\":\n case \"MultiLineString\":\n case \"MultiPolygon\":\n geometry = geojson;\n break;\n default:\n throw new Error(\"geojson is invalid\");\n }\n\n // Find SegmentIndex\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case \"Point\":\n case \"MultiPoint\":\n return null;\n case \"LineString\":\n if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1;\n return lineString(\n [coords[segmentIndex], coords[segmentIndex + 1]],\n properties,\n options\n );\n case \"Polygon\":\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (segmentIndex < 0)\n segmentIndex = coords[geometryIndex].length + segmentIndex - 1;\n return lineString(\n [\n coords[geometryIndex][segmentIndex],\n coords[geometryIndex][segmentIndex + 1],\n ],\n properties,\n options\n );\n case \"MultiLineString\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (segmentIndex < 0)\n segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;\n return lineString(\n [\n coords[multiFeatureIndex][segmentIndex],\n coords[multiFeatureIndex][segmentIndex + 1],\n ],\n properties,\n options\n );\n case \"MultiPolygon\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0)\n geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (segmentIndex < 0)\n segmentIndex =\n coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;\n return lineString(\n [\n coords[multiFeatureIndex][geometryIndex][segmentIndex],\n coords[multiFeatureIndex][geometryIndex][segmentIndex + 1],\n ],\n properties,\n options\n );\n }\n throw new Error(\"geojson is invalid\");\n}\n\n/**\n * Finds a particular Point from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.coordIndex=0] Coord Index\n * @param {Object} [options.properties={}] Translate Properties to output Point\n * @param {BBox} [options.bbox={}] Translate BBox to output Point\n * @param {number|string} [options.id={}] Translate Id to output Point\n * @returns {Feature} 2-vertex GeoJSON Feature Point\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findPoint(multiLine);\n * // => Feature>\n *\n * // First Segment of the 2nd Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: 1});\n * // => Feature>\n *\n * // Last Segment of last Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1});\n * // => Feature>\n */\nfunction findPoint(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error(\"options is invalid\");\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var coordIndex = options.coordIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case \"FeatureCollection\":\n if (featureIndex < 0)\n featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case \"Feature\":\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case \"Point\":\n case \"MultiPoint\":\n return null;\n case \"LineString\":\n case \"Polygon\":\n case \"MultiLineString\":\n case \"MultiPolygon\":\n geometry = geojson;\n break;\n default:\n throw new Error(\"geojson is invalid\");\n }\n\n // Find Coord Index\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case \"Point\":\n return point(coords, properties, options);\n case \"MultiPoint\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n return point(coords[multiFeatureIndex], properties, options);\n case \"LineString\":\n if (coordIndex < 0) coordIndex = coords.length + coordIndex;\n return point(coords[coordIndex], properties, options);\n case \"Polygon\":\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (coordIndex < 0)\n coordIndex = coords[geometryIndex].length + coordIndex;\n return point(coords[geometryIndex][coordIndex], properties, options);\n case \"MultiLineString\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (coordIndex < 0)\n coordIndex = coords[multiFeatureIndex].length + coordIndex;\n return point(coords[multiFeatureIndex][coordIndex], properties, options);\n case \"MultiPolygon\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0)\n geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (coordIndex < 0)\n coordIndex =\n coords[multiFeatureIndex][geometryIndex].length - coordIndex;\n return point(\n coords[multiFeatureIndex][geometryIndex][coordIndex],\n properties,\n options\n );\n }\n throw new Error(\"geojson is invalid\");\n}\n\nexport { coordAll, coordEach, coordReduce, featureEach, featureReduce, findPoint, findSegment, flattenEach, flattenReduce, geomEach, geomReduce, lineEach, lineReduce, propEach, propReduce, segmentEach, segmentReduce };\n","import { coordEach } from \"@turf/meta\";\n/**\n * Takes a set of features, calculates the bbox of all input features, and returns a bounding box.\n *\n * @name bbox\n * @param {GeoJSON} geojson any GeoJSON object\n * @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order\n * @example\n * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]]);\n * var bbox = turf.bbox(line);\n * var bboxPolygon = turf.bboxPolygon(bbox);\n *\n * //addToMap\n * var addToMap = [line, bboxPolygon]\n */\nfunction bbox(geojson) {\n var result = [Infinity, Infinity, -Infinity, -Infinity];\n coordEach(geojson, function (coord) {\n if (result[0] > coord[0]) {\n result[0] = coord[0];\n }\n if (result[1] > coord[1]) {\n result[1] = coord[1];\n }\n if (result[2] < coord[0]) {\n result[2] = coord[0];\n }\n if (result[3] < coord[1]) {\n result[3] = coord[1];\n }\n });\n return result;\n}\nbbox[\"default\"] = bbox;\nexport default bbox;\n","import bbox from \"@turf/bbox\";\nimport { point, } from \"@turf/helpers\";\n/**\n * Takes a {@link Feature} or {@link FeatureCollection} and returns the absolute center point of all features.\n *\n * @name center\n * @param {GeoJSON} geojson GeoJSON to be centered\n * @param {Object} [options={}] Optional parameters\n * @param {Object} [options.properties={}] Translate GeoJSON Properties to Point\n * @param {Object} [options.bbox={}] Translate GeoJSON BBox to Point\n * @param {Object} [options.id={}] Translate GeoJSON Id to Point\n * @returns {Feature} a Point feature at the absolute center point of all input features\n * @example\n * var features = turf.points([\n * [-97.522259, 35.4691],\n * [-97.502754, 35.463455],\n * [-97.508269, 35.463245]\n * ]);\n *\n * var center = turf.center(features);\n *\n * //addToMap\n * var addToMap = [features, center]\n * center.properties['marker-size'] = 'large';\n * center.properties['marker-color'] = '#000';\n */\nfunction center(geojson, options) {\n if (options === void 0) { options = {}; }\n var ext = bbox(geojson);\n var x = (ext[0] + ext[2]) / 2;\n var y = (ext[1] + ext[3]) / 2;\n return point([x, y], options.properties, options);\n}\nexport default center;\n","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","'use strict';\n\nmodule.exports = function (data, opts) {\n if (!opts) opts = {};\n if (typeof opts === 'function') opts = { cmp: opts };\n var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;\n\n var cmp = opts.cmp && (function (f) {\n return function (node) {\n return function (a, b) {\n var aobj = { key: a, value: node[a] };\n var bobj = { key: b, value: node[b] };\n return f(aobj, bobj);\n };\n };\n })(opts.cmp);\n\n var seen = [];\n return (function stringify (node) {\n if (node && node.toJSON && typeof node.toJSON === 'function') {\n node = node.toJSON();\n }\n\n if (node === undefined) return;\n if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';\n if (typeof node !== 'object') return JSON.stringify(node);\n\n var i, out;\n if (Array.isArray(node)) {\n out = '[';\n for (i = 0; i < node.length; i++) {\n if (i) out += ',';\n out += stringify(node[i]) || 'null';\n }\n return out + ']';\n }\n\n if (node === null) return 'null';\n\n if (seen.indexOf(node) !== -1) {\n if (cycles) return JSON.stringify('__cycle__');\n throw new TypeError('Converting circular structure to JSON');\n }\n\n var seenIndex = seen.push(node) - 1;\n var keys = Object.keys(node).sort(cmp && cmp(node));\n out = '';\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = stringify(node[key]);\n\n if (!value) continue;\n if (out) out += ',';\n out += JSON.stringify(key) + ':' + value;\n }\n seen.splice(seenIndex, 1);\n return '{' + out + '}';\n })(data);\n};\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n/* eslint-disable complexity */\n\nimport * as mat4 from 'gl-matrix/mat4';\nimport * as vec4 from 'gl-matrix/vec4';\n\nimport {COORDINATE_SYSTEM, PROJECTION_MODE} from '../../lib/constants';\n\nimport memoize from '../../utils/memoize';\n\n// To quickly set a vector to zero\nconst ZERO_VECTOR = [0, 0, 0, 0];\n// 4x4 matrix that drops 4th component of vector\nconst VECTOR_TO_POINT_MATRIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0];\nconst IDENTITY_MATRIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\nconst DEFAULT_PIXELS_PER_UNIT2 = [0, 0, 0];\nconst DEFAULT_COORDINATE_ORIGIN = [0, 0, 0];\n\nconst getMemoizedViewportUniforms = memoize(calculateViewportUniforms);\n\nexport function getOffsetOrigin(\n viewport,\n coordinateSystem,\n coordinateOrigin = DEFAULT_COORDINATE_ORIGIN\n) {\n let shaderCoordinateOrigin = coordinateOrigin;\n let geospatialOrigin;\n let offsetMode = true;\n\n if (\n coordinateSystem === COORDINATE_SYSTEM.LNGLAT_OFFSETS ||\n coordinateSystem === COORDINATE_SYSTEM.METER_OFFSETS\n ) {\n geospatialOrigin = coordinateOrigin;\n } else {\n geospatialOrigin = viewport.isGeospatial\n ? [Math.fround(viewport.longitude), Math.fround(viewport.latitude), 0]\n : null;\n }\n\n switch (viewport.projectionMode) {\n case PROJECTION_MODE.WEB_MERCATOR:\n if (\n coordinateSystem === COORDINATE_SYSTEM.LNGLAT ||\n coordinateSystem === COORDINATE_SYSTEM.CARTESIAN\n ) {\n geospatialOrigin = [0, 0, 0];\n offsetMode = false;\n }\n break;\n\n case PROJECTION_MODE.WEB_MERCATOR_AUTO_OFFSET:\n if (coordinateSystem === COORDINATE_SYSTEM.LNGLAT) {\n // viewport center in world space\n shaderCoordinateOrigin = geospatialOrigin;\n } else if (coordinateSystem === COORDINATE_SYSTEM.CARTESIAN) {\n // viewport center in common space\n shaderCoordinateOrigin = [\n Math.fround(viewport.center[0]),\n Math.fround(viewport.center[1]),\n 0\n ];\n // Geospatial origin (wgs84) must match shaderCoordinateOrigin (common)\n geospatialOrigin = viewport.unprojectPosition(shaderCoordinateOrigin);\n shaderCoordinateOrigin[0] -= coordinateOrigin[0];\n shaderCoordinateOrigin[1] -= coordinateOrigin[1];\n shaderCoordinateOrigin[2] -= coordinateOrigin[2];\n }\n break;\n\n case PROJECTION_MODE.IDENTITY:\n shaderCoordinateOrigin = viewport.position.map(Math.fround);\n break;\n\n case PROJECTION_MODE.GLOBE:\n offsetMode = false;\n geospatialOrigin = null;\n break;\n\n default:\n // Unknown projection mode\n offsetMode = false;\n }\n\n shaderCoordinateOrigin[2] = shaderCoordinateOrigin[2] || 0;\n\n return {geospatialOrigin, shaderCoordinateOrigin, offsetMode};\n}\n\n// The code that utilizes Matrix4 does the same calculation as their mat4 counterparts,\n// has lower performance but provides error checking.\nfunction calculateMatrixAndOffset(viewport, coordinateSystem, coordinateOrigin) {\n const {viewMatrixUncentered, projectionMatrix} = viewport;\n let {viewMatrix, viewProjectionMatrix} = viewport;\n\n let projectionCenter = ZERO_VECTOR;\n let originCommon = ZERO_VECTOR;\n let cameraPosCommon = viewport.cameraPosition;\n const {geospatialOrigin, shaderCoordinateOrigin, offsetMode} = getOffsetOrigin(\n viewport,\n coordinateSystem,\n coordinateOrigin\n );\n\n if (offsetMode) {\n // Calculate transformed projectionCenter (using 64 bit precision JS)\n // This is the key to offset mode precision\n // (avoids doing this addition in 32 bit precision in GLSL)\n originCommon = viewport.projectPosition(geospatialOrigin || shaderCoordinateOrigin);\n\n cameraPosCommon = [\n cameraPosCommon[0] - originCommon[0],\n cameraPosCommon[1] - originCommon[1],\n cameraPosCommon[2] - originCommon[2]\n ];\n\n originCommon[3] = 1;\n\n // projectionCenter = new Matrix4(viewProjectionMatrix)\n // .transformVector([positionPixels[0], positionPixels[1], 0.0, 1.0]);\n projectionCenter = vec4.transformMat4([], originCommon, viewProjectionMatrix);\n\n // Always apply uncentered projection matrix if available (shader adds center)\n viewMatrix = viewMatrixUncentered || viewMatrix;\n\n // Zero out 4th coordinate (\"after\" model matrix) - avoids further translations\n // viewMatrix = new Matrix4(viewMatrixUncentered || viewMatrix)\n // .multiplyRight(VECTOR_TO_POINT_MATRIX);\n viewProjectionMatrix = mat4.multiply([], projectionMatrix, viewMatrix);\n viewProjectionMatrix = mat4.multiply([], viewProjectionMatrix, VECTOR_TO_POINT_MATRIX);\n }\n\n return {\n viewMatrix,\n viewProjectionMatrix,\n projectionCenter,\n originCommon,\n cameraPosCommon,\n shaderCoordinateOrigin,\n geospatialOrigin\n };\n}\n\n/**\n * Returns uniforms for shaders based on current projection\n * includes: projection matrix suitable for shaders\n *\n * TODO - Ensure this works with any viewport, not just WebMercatorViewports\n *\n * @param {WebMercatorViewport} viewport -\n * @return {Float32Array} - 4x4 projection matrix that can be used in shaders\n */\nexport function getUniformsFromViewport({\n viewport,\n devicePixelRatio = 1,\n modelMatrix = null,\n // Match Layer.defaultProps\n coordinateSystem = COORDINATE_SYSTEM.DEFAULT,\n coordinateOrigin,\n autoWrapLongitude = false\n} = {}) {\n if (coordinateSystem === COORDINATE_SYSTEM.DEFAULT) {\n coordinateSystem = viewport.isGeospatial\n ? COORDINATE_SYSTEM.LNGLAT\n : COORDINATE_SYSTEM.CARTESIAN;\n }\n\n const uniforms = getMemoizedViewportUniforms({\n viewport,\n devicePixelRatio,\n coordinateSystem,\n coordinateOrigin\n });\n\n uniforms.project_uWrapLongitude = autoWrapLongitude;\n uniforms.project_uModelMatrix = modelMatrix || IDENTITY_MATRIX;\n\n return uniforms;\n}\n\nfunction calculateViewportUniforms({\n viewport,\n devicePixelRatio,\n coordinateSystem,\n coordinateOrigin\n}) {\n const {\n projectionCenter,\n viewProjectionMatrix,\n originCommon,\n cameraPosCommon,\n shaderCoordinateOrigin,\n geospatialOrigin\n } = calculateMatrixAndOffset(viewport, coordinateSystem, coordinateOrigin);\n\n // Calculate projection pixels per unit\n const distanceScales = viewport.getDistanceScales();\n\n const viewportSize = [viewport.width * devicePixelRatio, viewport.height * devicePixelRatio];\n\n // Distance at which screen pixels are projected.\n // Used to scale sizes in clipspace to match screen pixels.\n // When using Viewport class's default projection matrix, this yields 1 for orthographic\n // and `viewport.focalDistance` for perspective views\n const focalDistance =\n viewport.projectionMatrix.transform([0, 0, -viewport.focalDistance, 1])[3] || 1;\n\n const uniforms = {\n // Projection mode values\n project_uCoordinateSystem: coordinateSystem,\n project_uProjectionMode: viewport.projectionMode,\n project_uCoordinateOrigin: shaderCoordinateOrigin,\n project_uCommonOrigin: originCommon.slice(0, 3),\n project_uCenter: projectionCenter,\n\n // Backward compatibility\n // TODO: remove in v9\n project_uPseudoMeters: Boolean(viewport._pseudoMeters),\n\n // Screen size\n project_uViewportSize: viewportSize,\n project_uDevicePixelRatio: devicePixelRatio,\n\n project_uFocalDistance: focalDistance,\n project_uCommonUnitsPerMeter: distanceScales.unitsPerMeter,\n project_uCommonUnitsPerWorldUnit: distanceScales.unitsPerMeter,\n project_uCommonUnitsPerWorldUnit2: DEFAULT_PIXELS_PER_UNIT2,\n project_uScale: viewport.scale, // This is the mercator scale (2 ** zoom)\n\n project_uViewProjectionMatrix: viewProjectionMatrix,\n\n // This is for lighting calculations\n project_uCameraPosition: cameraPosCommon\n };\n\n if (geospatialOrigin) {\n const distanceScalesAtOrigin = viewport.getDistanceScales(geospatialOrigin);\n switch (coordinateSystem) {\n case COORDINATE_SYSTEM.METER_OFFSETS:\n uniforms.project_uCommonUnitsPerWorldUnit = distanceScalesAtOrigin.unitsPerMeter;\n uniforms.project_uCommonUnitsPerWorldUnit2 = distanceScalesAtOrigin.unitsPerMeter2;\n break;\n\n case COORDINATE_SYSTEM.LNGLAT:\n case COORDINATE_SYSTEM.LNGLAT_OFFSETS:\n if (!viewport._pseudoMeters) {\n uniforms.project_uCommonUnitsPerMeter = distanceScalesAtOrigin.unitsPerMeter;\n }\n uniforms.project_uCommonUnitsPerWorldUnit = distanceScalesAtOrigin.unitsPerDegree;\n uniforms.project_uCommonUnitsPerWorldUnit2 = distanceScalesAtOrigin.unitsPerDegree2;\n break;\n\n // a.k.a \"preprojected\" positions\n case COORDINATE_SYSTEM.CARTESIAN:\n uniforms.project_uCommonUnitsPerWorldUnit = [1, 1, distanceScalesAtOrigin.unitsPerMeter[2]];\n uniforms.project_uCommonUnitsPerWorldUnit2 = [\n 0,\n 0,\n distanceScalesAtOrigin.unitsPerMeter2[2]\n ];\n break;\n\n default:\n break;\n }\n }\n\n return uniforms;\n}\n","export default class ViewState {\n constructor(opts) {\n this._viewportProps = this._applyConstraints(opts);\n }\n\n getViewportProps() {\n return this._viewportProps;\n }\n\n getState() {\n return this._state;\n }\n\n shortestPathFrom(viewState) {\n return this._viewportProps;\n }\n\n // Redefined by subclass\n // Apply any constraints (mathematical or defined by _viewportProps) to map state\n _applyConstraints(props) {\n return props;\n }\n}\n","// Copyright (c) 2015-2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\nimport {COORDINATE_SYSTEM, PROJECTION_MODE} from '../../lib/constants';\nimport project from '../project/project';\nimport {Vector3, Matrix4} from 'math.gl';\nimport memoize from '../../utils/memoize';\nimport {pixelsToWorld} from '@math.gl/web-mercator';\n\nconst vs = `\nconst int max_lights = 2;\nuniform mat4 shadow_uViewProjectionMatrices[max_lights];\nuniform vec4 shadow_uProjectCenters[max_lights];\nuniform bool shadow_uDrawShadowMap;\nuniform bool shadow_uUseShadowMap;\nuniform int shadow_uLightId;\nuniform float shadow_uLightCount;\n\nvarying vec3 shadow_vPosition[max_lights];\n\nvec4 shadow_setVertexPosition(vec4 position_commonspace) {\n if (shadow_uDrawShadowMap) {\n return project_common_position_to_clipspace(position_commonspace, shadow_uViewProjectionMatrices[shadow_uLightId], shadow_uProjectCenters[shadow_uLightId]);\n }\n if (shadow_uUseShadowMap) {\n for (int i = 0; i < max_lights; i++) {\n if(i < int(shadow_uLightCount)) {\n vec4 shadowMap_position = project_common_position_to_clipspace(position_commonspace, shadow_uViewProjectionMatrices[i], shadow_uProjectCenters[i]);\n shadow_vPosition[i] = (shadowMap_position.xyz / shadowMap_position.w + 1.0) / 2.0;\n }\n }\n }\n return gl_Position;\n}\n`;\n\nconst fs = `\nconst int max_lights = 2;\nuniform bool shadow_uDrawShadowMap;\nuniform bool shadow_uUseShadowMap;\nuniform sampler2D shadow_uShadowMap0;\nuniform sampler2D shadow_uShadowMap1;\nuniform vec4 shadow_uColor;\nuniform float shadow_uLightCount;\n\nvarying vec3 shadow_vPosition[max_lights];\n\nconst vec4 bitPackShift = vec4(1.0, 255.0, 65025.0, 16581375.0);\nconst vec4 bitUnpackShift = 1.0 / bitPackShift;\nconst vec4 bitMask = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n\nfloat shadow_getShadowWeight(vec3 position, sampler2D shadowMap) {\n vec4 rgbaDepth = texture2D(shadowMap, position.xy);\n\n float z = dot(rgbaDepth, bitUnpackShift);\n return smoothstep(0.001, 0.01, position.z - z);\n}\n\nvec4 shadow_filterShadowColor(vec4 color) {\n if (shadow_uDrawShadowMap) {\n vec4 rgbaDepth = fract(gl_FragCoord.z * bitPackShift);\n rgbaDepth -= rgbaDepth.gbaa * bitMask;\n return rgbaDepth;\n }\n if (shadow_uUseShadowMap) {\n float shadowAlpha = 0.0;\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[0], shadow_uShadowMap0);\n if(shadow_uLightCount > 1.0) {\n shadowAlpha += shadow_getShadowWeight(shadow_vPosition[1], shadow_uShadowMap1);\n }\n shadowAlpha *= shadow_uColor.a / shadow_uLightCount;\n float blendedAlpha = shadowAlpha + color.a * (1.0 - shadowAlpha);\n\n return vec4(\n mix(color.rgb, shadow_uColor.rgb, shadowAlpha / blendedAlpha),\n blendedAlpha\n );\n }\n return color;\n}\n`;\n\nconst getMemoizedViewportCenterPosition = memoize(getViewportCenterPosition);\nconst getMemoizedViewProjectionMatrices = memoize(getViewProjectionMatrices);\n\nconst DEFAULT_SHADOW_COLOR = [0, 0, 0, 1.0];\nconst VECTOR_TO_POINT_MATRIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0];\n\nfunction screenToCommonSpace(xyz, pixelUnprojectionMatrix) {\n const [x, y, z] = xyz;\n const coord = pixelsToWorld([x, y, z], pixelUnprojectionMatrix);\n\n if (Number.isFinite(z)) {\n return coord;\n }\n return [coord[0], coord[1], 0];\n}\n\nfunction getViewportCenterPosition({viewport, center}) {\n return new Matrix4(viewport.viewProjectionMatrix).invert().transform(center);\n}\n\nfunction getViewProjectionMatrices({viewport, shadowMatrices}) {\n const projectionMatrices = [];\n const pixelUnprojectionMatrix = viewport.pixelUnprojectionMatrix;\n const farZ = viewport.isGeospatial ? undefined : 1;\n const corners = [\n [0, 0, farZ], // top left ground\n [viewport.width, 0, farZ], // top right ground\n [0, viewport.height, farZ], // bottom left ground\n [viewport.width, viewport.height, farZ], // bottom right ground\n [0, 0, -1], // top left near\n [viewport.width, 0, -1], // top right near\n [0, viewport.height, -1], // bottom left near\n [viewport.width, viewport.height, -1] // bottom right near\n ].map(pixel => screenToCommonSpace(pixel, pixelUnprojectionMatrix));\n\n for (const shadowMatrix of shadowMatrices) {\n const viewMatrix = shadowMatrix.clone().translate(new Vector3(viewport.center).negate());\n const positions = corners.map(corner => viewMatrix.transform(corner));\n const projectionMatrix = new Matrix4().ortho({\n left: Math.min(...positions.map(position => position[0])),\n right: Math.max(...positions.map(position => position[0])),\n bottom: Math.min(...positions.map(position => position[1])),\n top: Math.max(...positions.map(position => position[1])),\n near: Math.min(...positions.map(position => -position[2])),\n far: Math.max(...positions.map(position => -position[2]))\n });\n projectionMatrices.push(projectionMatrix.multiplyRight(shadowMatrix));\n }\n return projectionMatrices;\n}\n\nfunction createShadowUniforms(opts = {}, context = {}) {\n const uniforms = {\n shadow_uDrawShadowMap: Boolean(opts.drawToShadowMap),\n shadow_uUseShadowMap: opts.shadowMaps ? opts.shadowMaps.length > 0 : false,\n shadow_uColor: opts.shadowColor || DEFAULT_SHADOW_COLOR,\n shadow_uLightId: opts.shadowLightId || 0,\n shadow_uLightCount: opts.shadowMatrices.length\n };\n\n const center = getMemoizedViewportCenterPosition({\n viewport: opts.viewport,\n center: context.project_uCenter\n });\n\n const projectCenters = [];\n const viewProjectionMatrices = getMemoizedViewProjectionMatrices({\n shadowMatrices: opts.shadowMatrices,\n viewport: opts.viewport\n }).slice();\n\n for (let i = 0; i < opts.shadowMatrices.length; i++) {\n const viewProjectionMatrix = viewProjectionMatrices[i];\n const viewProjectionMatrixCentered = viewProjectionMatrix\n .clone()\n .translate(new Vector3(opts.viewport.center).negate());\n\n if (\n context.project_uCoordinateSystem === COORDINATE_SYSTEM.LNGLAT &&\n context.project_uProjectionMode === PROJECTION_MODE.WEB_MERCATOR\n ) {\n viewProjectionMatrices[i] = viewProjectionMatrixCentered;\n projectCenters[i] = center;\n } else {\n viewProjectionMatrices[i] = viewProjectionMatrix\n .clone()\n .multiplyRight(VECTOR_TO_POINT_MATRIX);\n projectCenters[i] = viewProjectionMatrixCentered.transform(center);\n }\n }\n\n for (let i = 0; i < viewProjectionMatrices.length; i++) {\n uniforms[`shadow_uViewProjectionMatrices[${i}]`] = viewProjectionMatrices[i];\n uniforms[`shadow_uProjectCenters[${i}]`] = projectCenters[i];\n\n if (opts.shadowMaps && opts.shadowMaps.length > 0) {\n uniforms[`shadow_uShadowMap${i}`] = opts.shadowMaps[i];\n } else {\n uniforms[`shadow_uShadowMap${i}`] = opts.dummyShadowMap;\n }\n }\n return uniforms;\n}\n\nexport default {\n name: 'shadow',\n dependencies: [project],\n vs,\n fs,\n inject: {\n 'vs:DECKGL_FILTER_GL_POSITION': `\n position = shadow_setVertexPosition(geometry.position);\n `,\n 'fs:DECKGL_FILTER_COLOR': `\n color = shadow_filterShadowColor(color);\n `\n },\n getUniforms: (opts = {}, context = {}) => {\n if (opts.drawToShadowMap || (opts.shadowMaps && opts.shadowMaps.length > 0)) {\n const {shadowEnabled = true} = opts;\n return shadowEnabled && opts.shadowMatrices && opts.shadowMatrices.length > 0\n ? createShadowUniforms(opts, context)\n : {\n shadow_uDrawShadowMap: false,\n shadow_uUseShadowMap: false\n };\n }\n return {};\n }\n};\n",";(function (globalScope) {\r\n 'use strict';\r\n\r\n\r\n /*\r\n * decimal.js v10.2.1\r\n * An arbitrary-precision Decimal type for JavaScript.\r\n * https://github.com/MikeMcl/decimal.js\r\n * Copyright (c) 2020 Michael Mclaughlin \r\n * MIT Licence\r\n */\r\n\r\n\r\n // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //\r\n\r\n\r\n // The maximum exponent magnitude.\r\n // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.\r\n var EXP_LIMIT = 9e15, // 0 to 9e15\r\n\r\n // The limit on the value of `precision`, and on the value of the first argument to\r\n // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.\r\n MAX_DIGITS = 1e9, // 0 to 1e9\r\n\r\n // Base conversion alphabet.\r\n NUMERALS = '0123456789abcdef',\r\n\r\n // The natural logarithm of 10 (1025 digits).\r\n LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',\r\n\r\n // Pi (1025 digits).\r\n PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',\r\n\r\n\r\n // The initial configuration properties of the Decimal constructor.\r\n DEFAULTS = {\r\n\r\n // These values must be integers within the stated ranges (inclusive).\r\n // Most of these values can be changed at run-time using the `Decimal.config` method.\r\n\r\n // The maximum number of significant digits of the result of a calculation or base conversion.\r\n // E.g. `Decimal.config({ precision: 20 });`\r\n precision: 20, // 1 to MAX_DIGITS\r\n\r\n // The rounding mode used when rounding to `precision`.\r\n //\r\n // ROUND_UP 0 Away from zero.\r\n // ROUND_DOWN 1 Towards zero.\r\n // ROUND_CEIL 2 Towards +Infinity.\r\n // ROUND_FLOOR 3 Towards -Infinity.\r\n // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n //\r\n // E.g.\r\n // `Decimal.rounding = 4;`\r\n // `Decimal.rounding = Decimal.ROUND_HALF_UP;`\r\n rounding: 4, // 0 to 8\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 The IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.\r\n //\r\n // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian\r\n // division (9) are commonly used for the modulus operation. The other rounding modes can also\r\n // be used, but they may not give useful results.\r\n modulo: 1, // 0 to 9\r\n\r\n // The exponent value at and beneath which `toString` returns exponential notation.\r\n // JavaScript numbers: -7\r\n toExpNeg: -7, // 0 to -EXP_LIMIT\r\n\r\n // The exponent value at and above which `toString` returns exponential notation.\r\n // JavaScript numbers: 21\r\n toExpPos: 21, // 0 to EXP_LIMIT\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // JavaScript numbers: -324 (5e-324)\r\n minE: -EXP_LIMIT, // -1 to -EXP_LIMIT\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // JavaScript numbers: 308 (1.7976931348623157e+308)\r\n maxE: EXP_LIMIT, // 1 to EXP_LIMIT\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n crypto: false // true/false\r\n },\r\n\r\n\r\n // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //\r\n\r\n\r\n Decimal, inexact, noConflict, quadrant,\r\n external = true,\r\n\r\n decimalError = '[DecimalError] ',\r\n invalidArgument = decimalError + 'Invalid argument: ',\r\n precisionLimitExceeded = decimalError + 'Precision limit exceeded',\r\n cryptoUnavailable = decimalError + 'crypto unavailable',\r\n\r\n mathfloor = Math.floor,\r\n mathpow = Math.pow,\r\n\r\n isBinary = /^0b([01]+(\\.[01]*)?|\\.[01]+)(p[+-]?\\d+)?$/i,\r\n isHex = /^0x([0-9a-f]+(\\.[0-9a-f]*)?|\\.[0-9a-f]+)(p[+-]?\\d+)?$/i,\r\n isOctal = /^0o([0-7]+(\\.[0-7]*)?|\\.[0-7]+)(p[+-]?\\d+)?$/i,\r\n isDecimal = /^(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?$/i,\r\n\r\n BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_SAFE_INTEGER = 9007199254740991,\r\n\r\n LN10_PRECISION = LN10.length - 1,\r\n PI_PRECISION = PI.length - 1,\r\n\r\n // Decimal.prototype object\r\n P = { name: '[object Decimal]' };\r\n\r\n\r\n // Decimal prototype methods\r\n\r\n\r\n /*\r\n * absoluteValue abs\r\n * ceil\r\n * comparedTo cmp\r\n * cosine cos\r\n * cubeRoot cbrt\r\n * decimalPlaces dp\r\n * dividedBy div\r\n * dividedToIntegerBy divToInt\r\n * equals eq\r\n * floor\r\n * greaterThan gt\r\n * greaterThanOrEqualTo gte\r\n * hyperbolicCosine cosh\r\n * hyperbolicSine sinh\r\n * hyperbolicTangent tanh\r\n * inverseCosine acos\r\n * inverseHyperbolicCosine acosh\r\n * inverseHyperbolicSine asinh\r\n * inverseHyperbolicTangent atanh\r\n * inverseSine asin\r\n * inverseTangent atan\r\n * isFinite\r\n * isInteger isInt\r\n * isNaN\r\n * isNegative isNeg\r\n * isPositive isPos\r\n * isZero\r\n * lessThan lt\r\n * lessThanOrEqualTo lte\r\n * logarithm log\r\n * [maximum] [max]\r\n * [minimum] [min]\r\n * minus sub\r\n * modulo mod\r\n * naturalExponential exp\r\n * naturalLogarithm ln\r\n * negated neg\r\n * plus add\r\n * precision sd\r\n * round\r\n * sine sin\r\n * squareRoot sqrt\r\n * tangent tan\r\n * times mul\r\n * toBinary\r\n * toDecimalPlaces toDP\r\n * toExponential\r\n * toFixed\r\n * toFraction\r\n * toHexadecimal toHex\r\n * toNearest\r\n * toNumber\r\n * toOctal\r\n * toPower pow\r\n * toPrecision\r\n * toSignificantDigits toSD\r\n * toString\r\n * truncated trunc\r\n * valueOf toJSON\r\n */\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the absolute value of this Decimal.\r\n *\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new this.constructor(this);\r\n if (x.s < 0) x.s = 1;\r\n return finalise(x);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of positive Infinity.\r\n *\r\n */\r\n P.ceil = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this Decimal is greater than the value of `y`,\r\n * -1 if the value of this Decimal is less than the value of `y`,\r\n * 0 if they have the same value,\r\n * NaN if the value of either Decimal is NaN.\r\n *\r\n */\r\n P.comparedTo = P.cmp = function (y) {\r\n var i, j, xdL, ydL,\r\n x = this,\r\n xd = x.d,\r\n yd = (y = new x.constructor(y)).d,\r\n xs = x.s,\r\n ys = y.s;\r\n\r\n // Either NaN or ±Infinity?\r\n if (!xd || !yd) {\r\n return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Either zero?\r\n if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;\r\n\r\n // Signs differ?\r\n if (xs !== ys) return xs;\r\n\r\n // Compare exponents.\r\n if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;\r\n\r\n xdL = xd.length;\r\n ydL = yd.length;\r\n\r\n // Compare digit by digit.\r\n for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {\r\n if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Compare lengths.\r\n return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * cos(0) = 1\r\n * cos(-0) = 1\r\n * cos(Infinity) = NaN\r\n * cos(-Infinity) = NaN\r\n * cos(NaN) = NaN\r\n *\r\n */\r\n P.cosine = P.cos = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.d) return new Ctor(NaN);\r\n\r\n // cos(0) = cos(-0) = 1\r\n if (!x.d[0]) return new Ctor(1);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;\r\n Ctor.rounding = 1;\r\n\r\n x = cosine(Ctor, toLessThanHalfPi(Ctor, x));\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);\r\n };\r\n\r\n\r\n /*\r\n *\r\n * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * cbrt(0) = 0\r\n * cbrt(-0) = -0\r\n * cbrt(1) = 1\r\n * cbrt(-1) = -1\r\n * cbrt(N) = N\r\n * cbrt(-I) = -I\r\n * cbrt(I) = I\r\n *\r\n * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))\r\n *\r\n */\r\n P.cubeRoot = P.cbrt = function () {\r\n var e, m, n, r, rep, s, sd, t, t3, t3plusx,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n external = false;\r\n\r\n // Initial estimate.\r\n s = x.s * mathpow(x.s * x, 1 / 3);\r\n\r\n // Math.cbrt underflow/overflow?\r\n // Pass x to Math.pow as integer, then adjust the exponent of the result.\r\n if (!s || Math.abs(s) == 1 / 0) {\r\n n = digitsToString(x.d);\r\n e = x.e;\r\n\r\n // Adjust n exponent so it is a multiple of 3 away from x exponent.\r\n if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');\r\n s = mathpow(n, 1 / 3);\r\n\r\n // Rarely, e may be one less than the result exponent value.\r\n e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new Ctor(n);\r\n r.s = x.s;\r\n } else {\r\n r = new Ctor(s.toString());\r\n }\r\n\r\n sd = (e = Ctor.precision) + 3;\r\n\r\n // Halley's method.\r\n // TODO? Compare Newton's method.\r\n for (;;) {\r\n t = r;\r\n t3 = t.times(t).times(t);\r\n t3plusx = t3.plus(x);\r\n r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);\r\n\r\n // TODO? Replace with for-loop and checkRoundingDigits.\r\n if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {\r\n n = n.slice(sd - 3, sd + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999\r\n // , i.e. approaching a rounding boundary, continue the iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the exact result as the\r\n // nines may infinitely repeat.\r\n if (!rep) {\r\n finalise(t, e + 1, 0);\r\n\r\n if (t.times(t).times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n sd += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.\r\n // If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n finalise(r, e + 1, 1);\r\n m = !r.times(r).times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, e, Ctor.rounding, m);\r\n };\r\n\r\n\r\n /*\r\n * Return the number of decimal places of the value of this Decimal.\r\n *\r\n */\r\n P.decimalPlaces = P.dp = function () {\r\n var w,\r\n d = this.d,\r\n n = NaN;\r\n\r\n if (d) {\r\n w = d.length - 1;\r\n n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last word.\r\n w = d[w];\r\n if (w) for (; w % 10 == 0; w /= 10) n--;\r\n if (n < 0) n = 0;\r\n }\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\n P.dividedBy = P.div = function (y) {\r\n return divide(this, new this.constructor(y));\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the integer part of dividing the value of this Decimal\r\n * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\n P.dividedToIntegerBy = P.divToInt = function (y) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.\r\n *\r\n */\r\n P.equals = P.eq = function (y) {\r\n return this.cmp(y) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of negative Infinity.\r\n *\r\n */\r\n P.floor = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 3);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is greater than the value of `y`, otherwise return\r\n * false.\r\n *\r\n */\r\n P.greaterThan = P.gt = function (y) {\r\n return this.cmp(y) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is greater than or equal to the value of `y`,\r\n * otherwise return false.\r\n *\r\n */\r\n P.greaterThanOrEqualTo = P.gte = function (y) {\r\n var k = this.cmp(y);\r\n return k == 1 || k === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [1, Infinity]\r\n *\r\n * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...\r\n *\r\n * cosh(0) = 1\r\n * cosh(-0) = 1\r\n * cosh(Infinity) = Infinity\r\n * cosh(-Infinity) = Infinity\r\n * cosh(NaN) = NaN\r\n *\r\n * x time taken (ms) result\r\n * 1000 9 9.8503555700852349694e+433\r\n * 10000 25 4.4034091128314607936e+4342\r\n * 100000 171 1.4033316802130615897e+43429\r\n * 1000000 3817 1.5166076984010437725e+434294\r\n * 10000000 abandoned after 2 minute wait\r\n *\r\n * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))\r\n *\r\n */\r\n P.hyperbolicCosine = P.cosh = function () {\r\n var k, n, pr, rm, len,\r\n x = this,\r\n Ctor = x.constructor,\r\n one = new Ctor(1);\r\n\r\n if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);\r\n if (x.isZero()) return one;\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n len = x.d.length;\r\n\r\n // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1\r\n // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n // TODO? Estimation reused from cosine() and may not be optimal here.\r\n if (len < 32) {\r\n k = Math.ceil(len / 3);\r\n n = (1 / tinyPow(4, k)).toString();\r\n } else {\r\n k = 16;\r\n n = '2.3283064365386962890625e-10';\r\n }\r\n\r\n x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);\r\n\r\n // Reverse argument reduction\r\n var cosh2_x,\r\n i = k,\r\n d8 = new Ctor(8);\r\n for (; i--;) {\r\n cosh2_x = x.times(x);\r\n x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));\r\n }\r\n\r\n return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...\r\n *\r\n * sinh(0) = 0\r\n * sinh(-0) = -0\r\n * sinh(Infinity) = Infinity\r\n * sinh(-Infinity) = -Infinity\r\n * sinh(NaN) = NaN\r\n *\r\n * x time taken (ms)\r\n * 10 2 ms\r\n * 100 5 ms\r\n * 1000 14 ms\r\n * 10000 82 ms\r\n * 100000 886 ms 1.4033316802130615897e+43429\r\n * 200000 2613 ms\r\n * 300000 5407 ms\r\n * 400000 8824 ms\r\n * 500000 13026 ms 8.7080643612718084129e+217146\r\n * 1000000 48543 ms\r\n *\r\n * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))\r\n *\r\n */\r\n P.hyperbolicSine = P.sinh = function () {\r\n var k, pr, rm, len,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n len = x.d.length;\r\n\r\n if (len < 3) {\r\n x = taylorSeries(Ctor, 2, x, x, true);\r\n } else {\r\n\r\n // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))\r\n // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))\r\n // 3 multiplications and 1 addition\r\n\r\n // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))\r\n // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))\r\n // 4 multiplications and 2 additions\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n k = 1.4 * Math.sqrt(len);\r\n k = k > 16 ? 16 : k | 0;\r\n\r\n x = x.times(1 / tinyPow(5, k));\r\n x = taylorSeries(Ctor, 2, x, x, true);\r\n\r\n // Reverse argument reduction\r\n var sinh2_x,\r\n d5 = new Ctor(5),\r\n d16 = new Ctor(16),\r\n d20 = new Ctor(20);\r\n for (; k--;) {\r\n sinh2_x = x.times(x);\r\n x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));\r\n }\r\n }\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(x, pr, rm, true);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * tanh(x) = sinh(x) / cosh(x)\r\n *\r\n * tanh(0) = 0\r\n * tanh(-0) = -0\r\n * tanh(Infinity) = 1\r\n * tanh(-Infinity) = -1\r\n * tanh(NaN) = NaN\r\n *\r\n */\r\n P.hyperbolicTangent = P.tanh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(x.s);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 7;\r\n Ctor.rounding = 1;\r\n\r\n return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of\r\n * this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [0, pi]\r\n *\r\n * acos(x) = pi/2 - asin(x)\r\n *\r\n * acos(0) = pi/2\r\n * acos(-0) = pi/2\r\n * acos(1) = 0\r\n * acos(-1) = pi\r\n * acos(1/2) = pi/3\r\n * acos(-1/2) = 2*pi/3\r\n * acos(|x| > 1) = NaN\r\n * acos(NaN) = NaN\r\n *\r\n */\r\n P.inverseCosine = P.acos = function () {\r\n var halfPi,\r\n x = this,\r\n Ctor = x.constructor,\r\n k = x.abs().cmp(1),\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding;\r\n\r\n if (k !== -1) {\r\n return k === 0\r\n // |x| is 1\r\n ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)\r\n // |x| > 1 or x is NaN\r\n : new Ctor(NaN);\r\n }\r\n\r\n if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3\r\n\r\n Ctor.precision = pr + 6;\r\n Ctor.rounding = 1;\r\n\r\n x = x.asin();\r\n halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return halfPi.minus(x);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [1, Infinity]\r\n * Range: [0, Infinity]\r\n *\r\n * acosh(x) = ln(x + sqrt(x^2 - 1))\r\n *\r\n * acosh(x < 1) = NaN\r\n * acosh(NaN) = NaN\r\n * acosh(Infinity) = Infinity\r\n * acosh(-Infinity) = NaN\r\n * acosh(0) = NaN\r\n * acosh(-0) = NaN\r\n * acosh(1) = 0\r\n * acosh(-1) = NaN\r\n *\r\n */\r\n P.inverseHyperbolicCosine = P.acosh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);\r\n if (!x.isFinite()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n external = false;\r\n\r\n x = x.times(x).minus(1).sqrt().plus(x);\r\n\r\n external = true;\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.ln();\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * asinh(x) = ln(x + sqrt(x^2 + 1))\r\n *\r\n * asinh(NaN) = NaN\r\n * asinh(Infinity) = Infinity\r\n * asinh(-Infinity) = -Infinity\r\n * asinh(0) = 0\r\n * asinh(-0) = -0\r\n *\r\n */\r\n P.inverseHyperbolicSine = P.asinh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;\r\n Ctor.rounding = 1;\r\n external = false;\r\n\r\n x = x.times(x).plus(1).sqrt().plus(x);\r\n\r\n external = true;\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.ln();\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * atanh(x) = 0.5 * ln((1 + x) / (1 - x))\r\n *\r\n * atanh(|x| > 1) = NaN\r\n * atanh(NaN) = NaN\r\n * atanh(Infinity) = NaN\r\n * atanh(-Infinity) = NaN\r\n * atanh(0) = 0\r\n * atanh(-0) = -0\r\n * atanh(1) = Infinity\r\n * atanh(-1) = -Infinity\r\n *\r\n */\r\n P.inverseHyperbolicTangent = P.atanh = function () {\r\n var pr, rm, wpr, xsd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n xsd = x.sd();\r\n\r\n if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);\r\n\r\n Ctor.precision = wpr = xsd - x.e;\r\n\r\n x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);\r\n\r\n Ctor.precision = pr + 4;\r\n Ctor.rounding = 1;\r\n\r\n x = x.ln();\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.times(0.5);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))\r\n *\r\n * asin(0) = 0\r\n * asin(-0) = -0\r\n * asin(1/2) = pi/6\r\n * asin(-1/2) = -pi/6\r\n * asin(1) = pi/2\r\n * asin(-1) = -pi/2\r\n * asin(|x| > 1) = NaN\r\n * asin(NaN) = NaN\r\n *\r\n * TODO? Compare performance of Taylor series.\r\n *\r\n */\r\n P.inverseSine = P.asin = function () {\r\n var halfPi, k,\r\n pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n k = x.abs().cmp(1);\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n if (k !== -1) {\r\n\r\n // |x| is 1\r\n if (k === 0) {\r\n halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n halfPi.s = x.s;\r\n return halfPi;\r\n }\r\n\r\n // |x| > 1 or x is NaN\r\n return new Ctor(NaN);\r\n }\r\n\r\n // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6\r\n\r\n Ctor.precision = pr + 6;\r\n Ctor.rounding = 1;\r\n\r\n x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.times(2);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n *\r\n * atan(0) = 0\r\n * atan(-0) = -0\r\n * atan(1) = pi/4\r\n * atan(-1) = -pi/4\r\n * atan(Infinity) = pi/2\r\n * atan(-Infinity) = -pi/2\r\n * atan(NaN) = NaN\r\n *\r\n */\r\n P.inverseTangent = P.atan = function () {\r\n var i, j, k, n, px, t, r, wpr, x2,\r\n x = this,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding;\r\n\r\n if (!x.isFinite()) {\r\n if (!x.s) return new Ctor(NaN);\r\n if (pr + 4 <= PI_PRECISION) {\r\n r = getPi(Ctor, pr + 4, rm).times(0.5);\r\n r.s = x.s;\r\n return r;\r\n }\r\n } else if (x.isZero()) {\r\n return new Ctor(x);\r\n } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {\r\n r = getPi(Ctor, pr + 4, rm).times(0.25);\r\n r.s = x.s;\r\n return r;\r\n }\r\n\r\n Ctor.precision = wpr = pr + 10;\r\n Ctor.rounding = 1;\r\n\r\n // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);\r\n\r\n // Argument reduction\r\n // Ensure |x| < 0.42\r\n // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))\r\n\r\n k = Math.min(28, wpr / LOG_BASE + 2 | 0);\r\n\r\n for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));\r\n\r\n external = false;\r\n\r\n j = Math.ceil(wpr / LOG_BASE);\r\n n = 1;\r\n x2 = x.times(x);\r\n r = new Ctor(x);\r\n px = x;\r\n\r\n // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n for (; i !== -1;) {\r\n px = px.times(x2);\r\n t = r.minus(px.div(n += 2));\r\n\r\n px = px.times(x2);\r\n r = t.plus(px.div(n += 2));\r\n\r\n if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);\r\n }\r\n\r\n if (k) r = r.times(2 << (k - 1));\r\n\r\n external = true;\r\n\r\n return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is a finite number, otherwise return false.\r\n *\r\n */\r\n P.isFinite = function () {\r\n return !!this.d;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is an integer, otherwise return false.\r\n *\r\n */\r\n P.isInteger = P.isInt = function () {\r\n return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is NaN, otherwise return false.\r\n *\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is negative, otherwise return false.\r\n *\r\n */\r\n P.isNegative = P.isNeg = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is positive, otherwise return false.\r\n *\r\n */\r\n P.isPositive = P.isPos = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is 0 or -0, otherwise return false.\r\n *\r\n */\r\n P.isZero = function () {\r\n return !!this.d && this.d[0] === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is less than `y`, otherwise return false.\r\n *\r\n */\r\n P.lessThan = P.lt = function (y) {\r\n return this.cmp(y) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.\r\n *\r\n */\r\n P.lessThanOrEqualTo = P.lte = function (y) {\r\n return this.cmp(y) < 1;\r\n };\r\n\r\n\r\n /*\r\n * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * If no base is specified, return log[10](arg).\r\n *\r\n * log[base](arg) = ln(arg) / ln(base)\r\n *\r\n * The result will always be correctly rounded if the base of the log is 10, and 'almost always'\r\n * otherwise:\r\n *\r\n * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen\r\n * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error\r\n * between the result and the correctly rounded result will be one ulp (unit in the last place).\r\n *\r\n * log[-b](a) = NaN\r\n * log[0](a) = NaN\r\n * log[1](a) = NaN\r\n * log[NaN](a) = NaN\r\n * log[Infinity](a) = NaN\r\n * log[b](0) = -Infinity\r\n * log[b](-0) = -Infinity\r\n * log[b](-a) = NaN\r\n * log[b](1) = 0\r\n * log[b](Infinity) = Infinity\r\n * log[b](NaN) = NaN\r\n *\r\n * [base] {number|string|Decimal} The base of the logarithm.\r\n *\r\n */\r\n P.logarithm = P.log = function (base) {\r\n var isBase10, d, denominator, k, inf, num, sd, r,\r\n arg = this,\r\n Ctor = arg.constructor,\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding,\r\n guard = 5;\r\n\r\n // Default base is 10.\r\n if (base == null) {\r\n base = new Ctor(10);\r\n isBase10 = true;\r\n } else {\r\n base = new Ctor(base);\r\n d = base.d;\r\n\r\n // Return NaN if base is negative, or non-finite, or is 0 or 1.\r\n if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);\r\n\r\n isBase10 = base.eq(10);\r\n }\r\n\r\n d = arg.d;\r\n\r\n // Is arg negative, non-finite, 0 or 1?\r\n if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {\r\n return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);\r\n }\r\n\r\n // The result will have a non-terminating decimal expansion if base is 10 and arg is not an\r\n // integer power of 10.\r\n if (isBase10) {\r\n if (d.length > 1) {\r\n inf = true;\r\n } else {\r\n for (k = d[0]; k % 10 === 0;) k /= 10;\r\n inf = k !== 1;\r\n }\r\n }\r\n\r\n external = false;\r\n sd = pr + guard;\r\n num = naturalLogarithm(arg, sd);\r\n denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);\r\n\r\n // The result will have 5 rounding digits.\r\n r = divide(num, denominator, sd, 1);\r\n\r\n // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,\r\n // calculate 10 further digits.\r\n //\r\n // If the result is known to have an infinite decimal expansion, repeat this until it is clear\r\n // that the result is above or below the boundary. Otherwise, if after calculating the 10\r\n // further digits, the last 14 are nines, round up and assume the result is exact.\r\n // Also assume the result is exact if the last 14 are zero.\r\n //\r\n // Example of a result that will be incorrectly rounded:\r\n // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...\r\n // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it\r\n // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so\r\n // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal\r\n // place is still 2.6.\r\n if (checkRoundingDigits(r.d, k = pr, rm)) {\r\n\r\n do {\r\n sd += 10;\r\n num = naturalLogarithm(arg, sd);\r\n denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);\r\n r = divide(num, denominator, sd, 1);\r\n\r\n if (!inf) {\r\n\r\n // Check for 14 nines from the 2nd rounding digit, as the first may be 4.\r\n if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {\r\n r = finalise(r, pr + 1, 0);\r\n }\r\n\r\n break;\r\n }\r\n } while (checkRoundingDigits(r.d, k += 10, rm));\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, pr, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n P.max = function () {\r\n Array.prototype.push.call(arguments, this);\r\n return maxOrMin(this.constructor, arguments, 'lt');\r\n };\r\n */\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n P.min = function () {\r\n Array.prototype.push.call(arguments, this);\r\n return maxOrMin(this.constructor, arguments, 'gt');\r\n };\r\n */\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\n P.minus = P.sub = function (y) {\r\n var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n y = new Ctor(y);\r\n\r\n // If either is not finite...\r\n if (!x.d || !y.d) {\r\n\r\n // Return NaN if either is NaN.\r\n if (!x.s || !y.s) y = new Ctor(NaN);\r\n\r\n // Return y negated if x is finite and y is ±Infinity.\r\n else if (x.d) y.s = -y.s;\r\n\r\n // Return x if y is finite and x is ±Infinity.\r\n // Return x if both are ±Infinity with different signs.\r\n // Return NaN if both are ±Infinity with the same sign.\r\n else y = new Ctor(y.d || x.s !== y.s ? x : NaN);\r\n\r\n return y;\r\n }\r\n\r\n // If signs differ...\r\n if (x.s != y.s) {\r\n y.s = -y.s;\r\n return x.plus(y);\r\n }\r\n\r\n xd = x.d;\r\n yd = y.d;\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n // If either is zero...\r\n if (!xd[0] || !yd[0]) {\r\n\r\n // Return y negated if x is zero and y is non-zero.\r\n if (yd[0]) y.s = -y.s;\r\n\r\n // Return x if y is zero and x is non-zero.\r\n else if (xd[0]) y = new Ctor(x);\r\n\r\n // Return zero if both are zero.\r\n // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.\r\n else return new Ctor(rm === 3 ? -0 : 0);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n }\r\n\r\n // x and y are finite, non-zero numbers with the same sign.\r\n\r\n // Calculate base 1e7 exponents.\r\n e = mathfloor(y.e / LOG_BASE);\r\n xe = mathfloor(x.e / LOG_BASE);\r\n\r\n xd = xd.slice();\r\n k = xe - e;\r\n\r\n // If base 1e7 exponents differ...\r\n if (k) {\r\n xLTy = k < 0;\r\n\r\n if (xLTy) {\r\n d = xd;\r\n k = -k;\r\n len = yd.length;\r\n } else {\r\n d = yd;\r\n e = xe;\r\n len = xd.length;\r\n }\r\n\r\n // Numbers with massively different exponents would result in a very high number of\r\n // zeros needing to be prepended, but this can be avoided while still ensuring correct\r\n // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.\r\n i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;\r\n\r\n if (k > i) {\r\n k = i;\r\n d.length = 1;\r\n }\r\n\r\n // Prepend zeros to equalise exponents.\r\n d.reverse();\r\n for (i = k; i--;) d.push(0);\r\n d.reverse();\r\n\r\n // Base 1e7 exponents equal.\r\n } else {\r\n\r\n // Check digits to determine which is the bigger number.\r\n\r\n i = xd.length;\r\n len = yd.length;\r\n xLTy = i < len;\r\n if (xLTy) len = i;\r\n\r\n for (i = 0; i < len; i++) {\r\n if (xd[i] != yd[i]) {\r\n xLTy = xd[i] < yd[i];\r\n break;\r\n }\r\n }\r\n\r\n k = 0;\r\n }\r\n\r\n if (xLTy) {\r\n d = xd;\r\n xd = yd;\r\n yd = d;\r\n y.s = -y.s;\r\n }\r\n\r\n len = xd.length;\r\n\r\n // Append zeros to `xd` if shorter.\r\n // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.\r\n for (i = yd.length - len; i > 0; --i) xd[len++] = 0;\r\n\r\n // Subtract yd from xd.\r\n for (i = yd.length; i > k;) {\r\n\r\n if (xd[--i] < yd[i]) {\r\n for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;\r\n --xd[j];\r\n xd[i] += BASE;\r\n }\r\n\r\n xd[i] -= yd[i];\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (; xd[--len] === 0;) xd.pop();\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xd[0] === 0; xd.shift()) --e;\r\n\r\n // Zero?\r\n if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);\r\n\r\n y.d = xd;\r\n y.e = getBase10Exponent(xd, e);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * The result depends on the modulo mode.\r\n *\r\n */\r\n P.modulo = P.mod = function (y) {\r\n var q,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n y = new Ctor(y);\r\n\r\n // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.\r\n if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);\r\n\r\n // Return x if y is ±Infinity or x is ±0.\r\n if (!y.d || x.d && !x.d[0]) {\r\n return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);\r\n }\r\n\r\n // Prevent rounding of intermediate calculations.\r\n external = false;\r\n\r\n if (Ctor.modulo == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // result = x - q * y where 0 <= result < abs(y)\r\n q = divide(x, y.abs(), 0, 3, 1);\r\n q.s *= y.s;\r\n } else {\r\n q = divide(x, y, 0, Ctor.modulo, 1);\r\n }\r\n\r\n q = q.times(y);\r\n\r\n external = true;\r\n\r\n return x.minus(q);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural exponential of the value of this Decimal,\r\n * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\n P.naturalExponential = P.exp = function () {\r\n return naturalExponential(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,\r\n * rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\n P.naturalLogarithm = P.ln = function () {\r\n return naturalLogarithm(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by\r\n * -1.\r\n *\r\n */\r\n P.negated = P.neg = function () {\r\n var x = new this.constructor(this);\r\n x.s = -x.s;\r\n return finalise(x);\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\n P.plus = P.add = function (y) {\r\n var carry, d, e, i, k, len, pr, rm, xd, yd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n y = new Ctor(y);\r\n\r\n // If either is not finite...\r\n if (!x.d || !y.d) {\r\n\r\n // Return NaN if either is NaN.\r\n if (!x.s || !y.s) y = new Ctor(NaN);\r\n\r\n // Return x if y is finite and x is ±Infinity.\r\n // Return x if both are ±Infinity with the same sign.\r\n // Return NaN if both are ±Infinity with different signs.\r\n // Return y if x is finite and y is ±Infinity.\r\n else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);\r\n\r\n return y;\r\n }\r\n\r\n // If signs differ...\r\n if (x.s != y.s) {\r\n y.s = -y.s;\r\n return x.minus(y);\r\n }\r\n\r\n xd = x.d;\r\n yd = y.d;\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n // If either is zero...\r\n if (!xd[0] || !yd[0]) {\r\n\r\n // Return x if y is zero.\r\n // Return y if y is non-zero.\r\n if (!yd[0]) y = new Ctor(x);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n }\r\n\r\n // x and y are finite, non-zero numbers with the same sign.\r\n\r\n // Calculate base 1e7 exponents.\r\n k = mathfloor(x.e / LOG_BASE);\r\n e = mathfloor(y.e / LOG_BASE);\r\n\r\n xd = xd.slice();\r\n i = k - e;\r\n\r\n // If base 1e7 exponents differ...\r\n if (i) {\r\n\r\n if (i < 0) {\r\n d = xd;\r\n i = -i;\r\n len = yd.length;\r\n } else {\r\n d = yd;\r\n e = k;\r\n len = xd.length;\r\n }\r\n\r\n // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.\r\n k = Math.ceil(pr / LOG_BASE);\r\n len = k > len ? k + 1 : len + 1;\r\n\r\n if (i > len) {\r\n i = len;\r\n d.length = 1;\r\n }\r\n\r\n // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.\r\n d.reverse();\r\n for (; i--;) d.push(0);\r\n d.reverse();\r\n }\r\n\r\n len = xd.length;\r\n i = yd.length;\r\n\r\n // If yd is longer than xd, swap xd and yd so xd points to the longer array.\r\n if (len - i < 0) {\r\n i = len;\r\n d = yd;\r\n yd = xd;\r\n xd = d;\r\n }\r\n\r\n // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.\r\n for (carry = 0; i;) {\r\n carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;\r\n xd[i] %= BASE;\r\n }\r\n\r\n if (carry) {\r\n xd.unshift(carry);\r\n ++e;\r\n }\r\n\r\n // Remove trailing zeros.\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n for (len = xd.length; xd[--len] == 0;) xd.pop();\r\n\r\n y.d = xd;\r\n y.e = getBase10Exponent(xd, e);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return the number of significant digits of the value of this Decimal.\r\n *\r\n * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.\r\n *\r\n */\r\n P.precision = P.sd = function (z) {\r\n var k,\r\n x = this;\r\n\r\n if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);\r\n\r\n if (x.d) {\r\n k = getPrecision(x.d);\r\n if (z && x.e + 1 > k) k = x.e + 1;\r\n } else {\r\n k = NaN;\r\n }\r\n\r\n return k;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using\r\n * rounding mode `rounding`.\r\n *\r\n */\r\n P.round = function () {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n return finalise(new Ctor(x), x.e + 1, Ctor.rounding);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the sine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * sin(x) = x - x^3/3! + x^5/5! - ...\r\n *\r\n * sin(0) = 0\r\n * sin(-0) = -0\r\n * sin(Infinity) = NaN\r\n * sin(-Infinity) = NaN\r\n * sin(NaN) = NaN\r\n *\r\n */\r\n P.sine = P.sin = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;\r\n Ctor.rounding = 1;\r\n\r\n x = sine(Ctor, toLessThanHalfPi(Ctor, x));\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, sd, r, rep, t,\r\n x = this,\r\n d = x.d,\r\n e = x.e,\r\n s = x.s,\r\n Ctor = x.constructor;\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !d || !d[0]) {\r\n return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);\r\n }\r\n\r\n external = false;\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+x);\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = digitsToString(d);\r\n\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(n);\r\n e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new Ctor(n);\r\n } else {\r\n r = new Ctor(s.toString());\r\n }\r\n\r\n sd = (e = Ctor.precision) + 3;\r\n\r\n // Newton-Raphson iteration.\r\n for (;;) {\r\n t = r;\r\n r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);\r\n\r\n // TODO? Replace with for-loop and checkRoundingDigits.\r\n if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {\r\n n = n.slice(sd - 3, sd + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or\r\n // 4999, i.e. approaching a rounding boundary, continue the iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the exact result as the\r\n // nines may infinitely repeat.\r\n if (!rep) {\r\n finalise(t, e + 1, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n sd += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.\r\n // If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n finalise(r, e + 1, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, e, Ctor.rounding, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * tan(0) = 0\r\n * tan(-0) = -0\r\n * tan(Infinity) = NaN\r\n * tan(-Infinity) = NaN\r\n * tan(NaN) = NaN\r\n *\r\n */\r\n P.tangent = P.tan = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 10;\r\n Ctor.rounding = 1;\r\n\r\n x = x.sin();\r\n x.s = 1;\r\n x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n */\r\n P.times = P.mul = function (y) {\r\n var carry, e, i, k, r, rL, t, xdL, ydL,\r\n x = this,\r\n Ctor = x.constructor,\r\n xd = x.d,\r\n yd = (y = new Ctor(y)).d;\r\n\r\n y.s *= x.s;\r\n\r\n // If either is NaN, ±Infinity or ±0...\r\n if (!xd || !xd[0] || !yd || !yd[0]) {\r\n\r\n return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd\r\n\r\n // Return NaN if either is NaN.\r\n // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.\r\n ? NaN\r\n\r\n // Return ±Infinity if either is ±Infinity.\r\n // Return ±0 if either is ±0.\r\n : !xd || !yd ? y.s / 0 : y.s * 0);\r\n }\r\n\r\n e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);\r\n xdL = xd.length;\r\n ydL = yd.length;\r\n\r\n // Ensure xd points to the longer array.\r\n if (xdL < ydL) {\r\n r = xd;\r\n xd = yd;\r\n yd = r;\r\n rL = xdL;\r\n xdL = ydL;\r\n ydL = rL;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n r = [];\r\n rL = xdL + ydL;\r\n for (i = rL; i--;) r.push(0);\r\n\r\n // Multiply!\r\n for (i = ydL; --i >= 0;) {\r\n carry = 0;\r\n for (k = xdL + i; k > i;) {\r\n t = r[k] + yd[i] * xd[k - i - 1] + carry;\r\n r[k--] = t % BASE | 0;\r\n carry = t / BASE | 0;\r\n }\r\n\r\n r[k] = (r[k] + carry) % BASE | 0;\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (; !r[--rL];) r.pop();\r\n\r\n if (carry) ++e;\r\n else r.shift();\r\n\r\n y.d = r;\r\n y.e = getBase10Exponent(r, e);\r\n\r\n return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal in base 2, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toBinary = function (sd, rm) {\r\n return toStringBinary(this, 2, sd, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`\r\n * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.\r\n *\r\n * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toDecimalPlaces = P.toDP = function (dp, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n x = new Ctor(x);\r\n if (dp === void 0) return x;\r\n\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n return finalise(x, dp + x.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal in exponential notation rounded to\r\n * `dp` fixed decimal places using rounding mode `rounding`.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toExponential = function (dp, rm) {\r\n var str,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (dp === void 0) {\r\n str = finiteToString(x, true);\r\n } else {\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n x = finalise(new Ctor(x), dp + 1, rm);\r\n str = finiteToString(x, true, dp + 1);\r\n }\r\n\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal in normal (fixed-point) notation to\r\n * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is\r\n * omitted.\r\n *\r\n * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.\r\n * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.\r\n * (-0).toFixed(3) is '0.000'.\r\n * (-0.5).toFixed(0) is '-0'.\r\n *\r\n */\r\n P.toFixed = function (dp, rm) {\r\n var str, y,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (dp === void 0) {\r\n str = finiteToString(x);\r\n } else {\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n y = finalise(new Ctor(x), dp + x.e + 1, rm);\r\n str = finiteToString(y, false, dp + y.e + 1);\r\n }\r\n\r\n // To determine whether to add the minus sign look at the value before it was rounded,\r\n // i.e. look at `x` rather than `y`.\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n };\r\n\r\n\r\n /*\r\n * Return an array representing the value of this Decimal as a simple fraction with an integer\r\n * numerator and an integer denominator.\r\n *\r\n * The denominator will be a positive non-zero value less than or equal to the specified maximum\r\n * denominator. If a maximum denominator is not specified, the denominator will be the lowest\r\n * value necessary to represent the number exactly.\r\n *\r\n * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.\r\n *\r\n */\r\n P.toFraction = function (maxD) {\r\n var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,\r\n x = this,\r\n xd = x.d,\r\n Ctor = x.constructor;\r\n\r\n if (!xd) return new Ctor(x);\r\n\r\n n1 = d0 = new Ctor(1);\r\n d1 = n0 = new Ctor(0);\r\n\r\n d = new Ctor(d1);\r\n e = d.e = getPrecision(xd) - x.e - 1;\r\n k = e % LOG_BASE;\r\n d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);\r\n\r\n if (maxD == null) {\r\n\r\n // d is 10**e, the minimum max-denominator needed.\r\n maxD = e > 0 ? d : n1;\r\n } else {\r\n n = new Ctor(maxD);\r\n if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);\r\n maxD = n.gt(d) ? (e > 0 ? d : n1) : n;\r\n }\r\n\r\n external = false;\r\n n = new Ctor(digitsToString(xd));\r\n pr = Ctor.precision;\r\n Ctor.precision = e = xd.length * LOG_BASE * 2;\r\n\r\n for (;;) {\r\n q = divide(n, d, 0, 1, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.cmp(maxD) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n d2 = n1;\r\n n1 = n0.plus(q.times(d2));\r\n n0 = d2;\r\n d2 = d;\r\n d = n.minus(q.times(d2));\r\n n = d2;\r\n }\r\n\r\n d2 = divide(maxD.minus(d0), d1, 0, 1, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1?\r\n r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1\r\n ? [n1, d1] : [n0, d0];\r\n\r\n Ctor.precision = pr;\r\n external = true;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal in base 16, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toHexadecimal = P.toHex = function (sd, rm) {\r\n return toStringBinary(this, 16, sd, rm);\r\n };\r\n\r\n\r\n /*\r\n * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding\r\n * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.\r\n *\r\n * The return value will always have the same sign as this Decimal, unless either this Decimal\r\n * or `y` is NaN, in which case the return value will be also be NaN.\r\n *\r\n * The return value is not affected by the value of `precision`.\r\n *\r\n * y {number|string|Decimal} The magnitude to round to a multiple of.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * 'toNearest() rounding mode not an integer: {rm}'\r\n * 'toNearest() rounding mode out of range: {rm}'\r\n *\r\n */\r\n P.toNearest = function (y, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n x = new Ctor(x);\r\n\r\n if (y == null) {\r\n\r\n // If x is not finite, return x.\r\n if (!x.d) return x;\r\n\r\n y = new Ctor(1);\r\n rm = Ctor.rounding;\r\n } else {\r\n y = new Ctor(y);\r\n if (rm === void 0) {\r\n rm = Ctor.rounding;\r\n } else {\r\n checkInt32(rm, 0, 8);\r\n }\r\n\r\n // If x is not finite, return x if y is not NaN, else NaN.\r\n if (!x.d) return y.s ? x : y;\r\n\r\n // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.\r\n if (!y.d) {\r\n if (y.s) y.s = x.s;\r\n return y;\r\n }\r\n }\r\n\r\n // If y is not zero, calculate the nearest multiple of y to x.\r\n if (y.d[0]) {\r\n external = false;\r\n x = divide(x, y, 0, rm, 1).times(y);\r\n external = true;\r\n finalise(x);\r\n\r\n // If y is zero, return zero with the sign of x.\r\n } else {\r\n y.s = x.s;\r\n x = y;\r\n }\r\n\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this Decimal converted to a number primitive.\r\n * Zero keeps its sign.\r\n *\r\n */\r\n P.toNumber = function () {\r\n return +this;\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal in base 8, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toOctal = function (sd, rm) {\r\n return toStringBinary(this, 8, sd, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded\r\n * to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * ECMAScript compliant.\r\n *\r\n * pow(x, NaN) = NaN\r\n * pow(x, ±0) = 1\r\n\r\n * pow(NaN, non-zero) = NaN\r\n * pow(abs(x) > 1, +Infinity) = +Infinity\r\n * pow(abs(x) > 1, -Infinity) = +0\r\n * pow(abs(x) == 1, ±Infinity) = NaN\r\n * pow(abs(x) < 1, +Infinity) = +0\r\n * pow(abs(x) < 1, -Infinity) = +Infinity\r\n * pow(+Infinity, y > 0) = +Infinity\r\n * pow(+Infinity, y < 0) = +0\r\n * pow(-Infinity, odd integer > 0) = -Infinity\r\n * pow(-Infinity, even integer > 0) = +Infinity\r\n * pow(-Infinity, odd integer < 0) = -0\r\n * pow(-Infinity, even integer < 0) = +0\r\n * pow(+0, y > 0) = +0\r\n * pow(+0, y < 0) = +Infinity\r\n * pow(-0, odd integer > 0) = -0\r\n * pow(-0, even integer > 0) = +0\r\n * pow(-0, odd integer < 0) = -Infinity\r\n * pow(-0, even integer < 0) = +Infinity\r\n * pow(finite x < 0, finite non-integer) = NaN\r\n *\r\n * For non-integer or very large exponents pow(x, y) is calculated using\r\n *\r\n * x^y = exp(y*ln(x))\r\n *\r\n * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the\r\n * probability of an incorrectly rounded result\r\n * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14\r\n * i.e. 1 in 250,000,000,000,000\r\n *\r\n * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).\r\n *\r\n * y {number|string|Decimal} The power to which to raise this Decimal.\r\n *\r\n */\r\n P.toPower = P.pow = function (y) {\r\n var e, k, pr, r, rm, s,\r\n x = this,\r\n Ctor = x.constructor,\r\n yn = +(y = new Ctor(y));\r\n\r\n // Either ±Infinity, NaN or ±0?\r\n if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));\r\n\r\n x = new Ctor(x);\r\n\r\n if (x.eq(1)) return x;\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n if (y.eq(1)) return finalise(x, pr, rm);\r\n\r\n // y exponent\r\n e = mathfloor(y.e / LOG_BASE);\r\n\r\n // If y is a small integer use the 'exponentiation by squaring' algorithm.\r\n if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {\r\n r = intPow(Ctor, x, k, pr);\r\n return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);\r\n }\r\n\r\n s = x.s;\r\n\r\n // if x is negative\r\n if (s < 0) {\r\n\r\n // if y is not an integer\r\n if (e < y.d.length - 1) return new Ctor(NaN);\r\n\r\n // Result is positive if x is negative and the last digit of integer y is even.\r\n if ((y.d[e] & 1) == 0) s = 1;\r\n\r\n // if x.eq(-1)\r\n if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {\r\n x.s = s;\r\n return x;\r\n }\r\n }\r\n\r\n // Estimate result exponent.\r\n // x^y = 10^e, where e = y * log10(x)\r\n // log10(x) = log10(x_significand) + x_exponent\r\n // log10(x_significand) = ln(x_significand) / ln(10)\r\n k = mathpow(+x, yn);\r\n e = k == 0 || !isFinite(k)\r\n ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))\r\n : new Ctor(k + '').e;\r\n\r\n // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.\r\n\r\n // Overflow/underflow?\r\n if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);\r\n\r\n external = false;\r\n Ctor.rounding = x.s = 1;\r\n\r\n // Estimate the extra guard digits needed to ensure five correct rounding digits from\r\n // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):\r\n // new Decimal(2.32456).pow('2087987436534566.46411')\r\n // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815\r\n k = Math.min(12, (e + '').length);\r\n\r\n // r = x^y = exp(y*ln(x))\r\n r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);\r\n\r\n // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)\r\n if (r.d) {\r\n\r\n // Truncate to the required precision plus five rounding digits.\r\n r = finalise(r, pr + 5, 1);\r\n\r\n // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate\r\n // the result.\r\n if (checkRoundingDigits(r.d, pr, rm)) {\r\n e = pr + 10;\r\n\r\n // Truncate to the increased precision plus five rounding digits.\r\n r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);\r\n\r\n // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).\r\n if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {\r\n r = finalise(r, pr + 1, 0);\r\n }\r\n }\r\n }\r\n\r\n r.s = s;\r\n external = true;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(r, pr, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal rounded to `sd` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * Return exponential notation if `sd` is less than the number of digits necessary to represent\r\n * the integer part of the value in normal notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n var str,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (sd === void 0) {\r\n str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n } else {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n x = finalise(new Ctor(x), sd, rm);\r\n str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);\r\n }\r\n\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`\r\n * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if\r\n * omitted.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * 'toSD() digits out of range: {sd}'\r\n * 'toSD() digits not an integer: {sd}'\r\n * 'toSD() rounding mode not an integer: {rm}'\r\n * 'toSD() rounding mode out of range: {rm}'\r\n *\r\n */\r\n P.toSignificantDigits = P.toSD = function (sd, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n if (sd === void 0) {\r\n sd = Ctor.precision;\r\n rm = Ctor.rounding;\r\n } else {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n }\r\n\r\n return finalise(new Ctor(x), sd, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal.\r\n *\r\n * Return exponential notation if this Decimal has a positive exponent equal to or greater than\r\n * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.\r\n *\r\n */\r\n P.toString = function () {\r\n var x = this,\r\n Ctor = x.constructor,\r\n str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n };\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.\r\n *\r\n */\r\n P.truncated = P.trunc = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this Decimal.\r\n * Unlike `toString`, negative zero will include the minus sign.\r\n *\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n var x = this,\r\n Ctor = x.constructor,\r\n str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n\r\n return x.isNeg() ? '-' + str : str;\r\n };\r\n\r\n\r\n /*\r\n // Add aliases to match BigDecimal method names.\r\n // P.add = P.plus;\r\n P.subtract = P.minus;\r\n P.multiply = P.times;\r\n P.divide = P.div;\r\n P.remainder = P.mod;\r\n P.compareTo = P.cmp;\r\n P.negate = P.neg;\r\n */\r\n\r\n\r\n // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.\r\n\r\n\r\n /*\r\n * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,\r\n * finiteToString, naturalExponential, naturalLogarithm\r\n * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,\r\n * P.toPrecision, P.toSignificantDigits, toStringBinary, random\r\n * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm\r\n * convertBase toStringBinary, parseOther\r\n * cos P.cos\r\n * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,\r\n * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,\r\n * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,\r\n * taylorSeries, atan2, parseOther\r\n * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,\r\n * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,\r\n * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,\r\n * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,\r\n * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,\r\n * P.truncated, divide, getLn10, getPi, naturalExponential,\r\n * naturalLogarithm, ceil, floor, round, trunc\r\n * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,\r\n * toStringBinary\r\n * getBase10Exponent P.minus, P.plus, P.times, parseOther\r\n * getLn10 P.logarithm, naturalLogarithm\r\n * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2\r\n * getPrecision P.precision, P.toFraction\r\n * getZeroString digitsToString, finiteToString\r\n * intPow P.toPower, parseOther\r\n * isOdd toLessThanHalfPi\r\n * maxOrMin max, min\r\n * naturalExponential P.naturalExponential, P.toPower\r\n * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,\r\n * P.toPower, naturalExponential\r\n * nonFiniteToString finiteToString, toStringBinary\r\n * parseDecimal Decimal\r\n * parseOther Decimal\r\n * sin P.sin\r\n * taylorSeries P.cosh, P.sinh, cos, sin\r\n * toLessThanHalfPi P.cos, P.sin\r\n * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal\r\n * truncate intPow\r\n *\r\n * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,\r\n * naturalLogarithm, config, parseOther, random, Decimal\r\n */\r\n\r\n\r\n function digitsToString(d) {\r\n var i, k, ws,\r\n indexOfLastWord = d.length - 1,\r\n str = '',\r\n w = d[0];\r\n\r\n if (indexOfLastWord > 0) {\r\n str += w;\r\n for (i = 1; i < indexOfLastWord; i++) {\r\n ws = d[i] + '';\r\n k = LOG_BASE - ws.length;\r\n if (k) str += getZeroString(k);\r\n str += ws;\r\n }\r\n\r\n w = d[i];\r\n ws = w + '';\r\n k = LOG_BASE - ws.length;\r\n if (k) str += getZeroString(k);\r\n } else if (w === 0) {\r\n return '0';\r\n }\r\n\r\n // Remove trailing zeros of last w.\r\n for (; w % 10 === 0;) w /= 10;\r\n\r\n return str + w;\r\n }\r\n\r\n\r\n function checkInt32(i, min, max) {\r\n if (i !== ~~i || i < min || i > max) {\r\n throw Error(invalidArgument + i);\r\n }\r\n }\r\n\r\n\r\n /*\r\n * Check 5 rounding digits if `repeating` is null, 4 otherwise.\r\n * `repeating == null` if caller is `log` or `pow`,\r\n * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.\r\n */\r\n function checkRoundingDigits(d, i, rm, repeating) {\r\n var di, k, r, rd;\r\n\r\n // Get the length of the first word of the array d.\r\n for (k = d[0]; k >= 10; k /= 10) --i;\r\n\r\n // Is the rounding digit in the first word of d?\r\n if (--i < 0) {\r\n i += LOG_BASE;\r\n di = 0;\r\n } else {\r\n di = Math.ceil((i + 1) / LOG_BASE);\r\n i %= LOG_BASE;\r\n }\r\n\r\n // i is the index (0 - 6) of the rounding digit.\r\n // E.g. if within the word 3487563 the first rounding digit is 5,\r\n // then i = 4, k = 1000, rd = 3487563 % 1000 = 563\r\n k = mathpow(10, LOG_BASE - i);\r\n rd = d[di] % k | 0;\r\n\r\n if (repeating == null) {\r\n if (i < 3) {\r\n if (i == 0) rd = rd / 100 | 0;\r\n else if (i == 1) rd = rd / 10 | 0;\r\n r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;\r\n } else {\r\n r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&\r\n (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||\r\n (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;\r\n }\r\n } else {\r\n if (i < 4) {\r\n if (i == 0) rd = rd / 1000 | 0;\r\n else if (i == 1) rd = rd / 100 | 0;\r\n else if (i == 2) rd = rd / 10 | 0;\r\n r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;\r\n } else {\r\n r = ((repeating || rm < 4) && rd + 1 == k ||\r\n (!repeating && rm > 3) && rd + 1 == k / 2) &&\r\n (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;\r\n }\r\n }\r\n\r\n return r;\r\n }\r\n\r\n\r\n // Convert string of `baseIn` to an array of numbers of `baseOut`.\r\n // Eg. convertBase('255', 10, 16) returns [15, 15].\r\n // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].\r\n function convertBase(str, baseIn, baseOut) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n strL = str.length;\r\n\r\n for (; i < strL;) {\r\n for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;\r\n arr[0] += NUMERALS.indexOf(str.charAt(i++));\r\n for (j = 0; j < arr.length; j++) {\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] === void 0) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n\r\n /*\r\n * cos(x) = 1 - x^2/2! + x^4/4! - ...\r\n * |x| < pi/2\r\n *\r\n */\r\n function cosine(Ctor, x) {\r\n var k, y,\r\n len = x.d.length;\r\n\r\n // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1\r\n // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n if (len < 32) {\r\n k = Math.ceil(len / 3);\r\n y = (1 / tinyPow(4, k)).toString();\r\n } else {\r\n k = 16;\r\n y = '2.3283064365386962890625e-10';\r\n }\r\n\r\n Ctor.precision += k;\r\n\r\n x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));\r\n\r\n // Reverse argument reduction\r\n for (var i = k; i--;) {\r\n var cos2x = x.times(x);\r\n x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);\r\n }\r\n\r\n Ctor.precision -= k;\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Perform division in the specified base.\r\n */\r\n var divide = (function () {\r\n\r\n // Assumes non-zero x and k, and hence non-zero result.\r\n function multiplyInteger(x, k, base) {\r\n var temp,\r\n carry = 0,\r\n i = x.length;\r\n\r\n for (x = x.slice(); i--;) {\r\n temp = x[i] * k + carry;\r\n x[i] = temp % base | 0;\r\n carry = temp / base | 0;\r\n }\r\n\r\n if (carry) x.unshift(carry);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, r;\r\n\r\n if (aL != bL) {\r\n r = aL > bL ? 1 : -1;\r\n } else {\r\n for (i = r = 0; i < aL; i++) {\r\n if (a[i] != b[i]) {\r\n r = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return r;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1;) a.shift();\r\n }\r\n\r\n return function (x, y, pr, rm, dp, base) {\r\n var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,\r\n yL, yz,\r\n Ctor = x.constructor,\r\n sign = x.s == y.s ? 1 : -1,\r\n xd = x.d,\r\n yd = y.d;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xd || !xd[0] || !yd || !yd[0]) {\r\n\r\n return new Ctor(// Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :\r\n\r\n // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.\r\n xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);\r\n }\r\n\r\n if (base) {\r\n logBase = 1;\r\n e = x.e - y.e;\r\n } else {\r\n base = BASE;\r\n logBase = LOG_BASE;\r\n e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);\r\n }\r\n\r\n yL = yd.length;\r\n xL = xd.length;\r\n q = new Ctor(sign);\r\n qd = q.d = [];\r\n\r\n // Result exponent may be one less than e.\r\n // The digit array of a Decimal from toStringBinary may have trailing zeros.\r\n for (i = 0; yd[i] == (xd[i] || 0); i++);\r\n\r\n if (yd[i] > (xd[i] || 0)) e--;\r\n\r\n if (pr == null) {\r\n sd = pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n } else if (dp) {\r\n sd = pr + (x.e - y.e) + 1;\r\n } else {\r\n sd = pr;\r\n }\r\n\r\n if (sd < 0) {\r\n qd.push(1);\r\n more = true;\r\n } else {\r\n\r\n // Convert precision in number of base 10 digits to base 1e7 digits.\r\n sd = sd / logBase + 2 | 0;\r\n i = 0;\r\n\r\n // divisor < 1e7\r\n if (yL == 1) {\r\n k = 0;\r\n yd = yd[0];\r\n sd++;\r\n\r\n // k is the carry.\r\n for (; (i < xL || k) && sd--; i++) {\r\n t = k * base + (xd[i] || 0);\r\n qd[i] = t / yd | 0;\r\n k = t % yd | 0;\r\n }\r\n\r\n more = k || i < xL;\r\n\r\n // divisor >= 1e7\r\n } else {\r\n\r\n // Normalise xd and yd so highest order digit of yd is >= base/2\r\n k = base / (yd[0] + 1) | 0;\r\n\r\n if (k > 1) {\r\n yd = multiplyInteger(yd, k, base);\r\n xd = multiplyInteger(xd, k, base);\r\n yL = yd.length;\r\n xL = xd.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xd.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL;) rem[remL++] = 0;\r\n\r\n yz = yd.slice();\r\n yz.unshift(0);\r\n yd0 = yd[0];\r\n\r\n if (yd[1] >= base / 2) ++yd0;\r\n\r\n do {\r\n k = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yd, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, k.\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // k will be how many times the divisor goes into the current remainder.\r\n k = rem0 / yd0 | 0;\r\n\r\n // Algorithm:\r\n // 1. product = divisor * trial digit (k)\r\n // 2. if product > remainder: product -= divisor, k--\r\n // 3. remainder -= product\r\n // 4. if product was < remainder at 2:\r\n // 5. compare new remainder and divisor\r\n // 6. If remainder > divisor: remainder -= divisor, k++\r\n\r\n if (k > 1) {\r\n if (k >= base) k = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiplyInteger(yd, k, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n cmp = compare(prod, rem, prodL, remL);\r\n\r\n // product > remainder.\r\n if (cmp == 1) {\r\n k--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yd, prodL, base);\r\n }\r\n } else {\r\n\r\n // cmp is -1.\r\n // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1\r\n // to avoid it. If k is 1 there is a need to compare yd and rem again below.\r\n if (k == 0) cmp = k = 1;\r\n prod = yd.slice();\r\n }\r\n\r\n prodL = prod.length;\r\n if (prodL < remL) prod.unshift(0);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n\r\n // If product was < previous remainder.\r\n if (cmp == -1) {\r\n remL = rem.length;\r\n\r\n // Compare divisor and new remainder.\r\n cmp = compare(yd, rem, yL, remL);\r\n\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n if (cmp < 1) {\r\n k++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yd, remL, base);\r\n }\r\n }\r\n\r\n remL = rem.length;\r\n } else if (cmp === 0) {\r\n k++;\r\n rem = [0];\r\n } // if cmp === 1, k will be 0\r\n\r\n // Add the next digit, k, to the result array.\r\n qd[i++] = k;\r\n\r\n // Update the remainder.\r\n if (cmp && rem[0]) {\r\n rem[remL++] = xd[xi] || 0;\r\n } else {\r\n rem = [xd[xi]];\r\n remL = 1;\r\n }\r\n\r\n } while ((xi++ < xL || rem[0] !== void 0) && sd--);\r\n\r\n more = rem[0] !== void 0;\r\n }\r\n\r\n // Leading zero?\r\n if (!qd[0]) qd.shift();\r\n }\r\n\r\n // logBase is 1 when divide is being used for base conversion.\r\n if (logBase == 1) {\r\n q.e = e;\r\n inexact = more;\r\n } else {\r\n\r\n // To calculate q.e, first get the number of digits of qd[0].\r\n for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;\r\n q.e = i + e * logBase - 1;\r\n\r\n finalise(q, dp ? pr + q.e + 1 : pr, rm, more);\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Round `x` to `sd` significant digits using rounding mode `rm`.\r\n * Check for over/under-flow.\r\n */\r\n function finalise(x, sd, rm, isTruncated) {\r\n var digits, i, j, k, rd, roundUp, w, xd, xdi,\r\n Ctor = x.constructor;\r\n\r\n // Don't round if sd is null or undefined.\r\n out: if (sd != null) {\r\n xd = x.d;\r\n\r\n // Infinity/NaN.\r\n if (!xd) return x;\r\n\r\n // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // w: the word of xd containing rd, a base 1e7 number.\r\n // xdi: the index of w within xd.\r\n // digits: the number of digits of w.\r\n // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if\r\n // they had leading zeros)\r\n // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).\r\n\r\n // Get the length of the first word of the digits array xd.\r\n for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;\r\n i = sd - digits;\r\n\r\n // Is the rounding digit in the first word of xd?\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n w = xd[xdi = 0];\r\n\r\n // Get the rounding digit at index j of w.\r\n rd = w / mathpow(10, digits - j - 1) % 10 | 0;\r\n } else {\r\n xdi = Math.ceil((i + 1) / LOG_BASE);\r\n k = xd.length;\r\n if (xdi >= k) {\r\n if (isTruncated) {\r\n\r\n // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.\r\n for (; k++ <= xdi;) xd.push(0);\r\n w = rd = 0;\r\n digits = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n w = k = xd[xdi];\r\n\r\n // Get the number of digits of w.\r\n for (digits = 1; k >= 10; k /= 10) digits++;\r\n\r\n // Get the index of rd within w.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within w, adjusted for leading zeros.\r\n // The number of leading zeros of w is given by LOG_BASE - digits.\r\n j = i - LOG_BASE + digits;\r\n\r\n // Get the rounding digit at index j of w.\r\n rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;\r\n }\r\n }\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n isTruncated = isTruncated || sd < 0 ||\r\n xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));\r\n\r\n // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right\r\n // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression\r\n // will give 714.\r\n\r\n roundUp = rm < 4\r\n ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xd[0]) {\r\n xd.length = 0;\r\n if (roundUp) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xd[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xd.length = xdi;\r\n k = 1;\r\n xdi--;\r\n } else {\r\n xd.length = xdi + 1;\r\n k = mathpow(10, LOG_BASE - i);\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of w.\r\n xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;\r\n }\r\n\r\n if (roundUp) {\r\n for (;;) {\r\n\r\n // Is the digit to be rounded up in the first word of xd?\r\n if (xdi == 0) {\r\n\r\n // i will be the length of xd[0] before k is added.\r\n for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;\r\n j = xd[0] += k;\r\n for (k = 1; j >= 10; j /= 10) k++;\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xd[0] == BASE) xd[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xd[xdi] += k;\r\n if (xd[xdi] != BASE) break;\r\n xd[xdi--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xd.length; xd[--i] === 0;) xd.pop();\r\n }\r\n\r\n if (external) {\r\n\r\n // Overflow?\r\n if (x.e > Ctor.maxE) {\r\n\r\n // Infinity.\r\n x.d = null;\r\n x.e = NaN;\r\n\r\n // Underflow?\r\n } else if (x.e < Ctor.minE) {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n // Ctor.underflow = true;\r\n } // else Ctor.underflow = false;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function finiteToString(x, isExp, sd) {\r\n if (!x.isFinite()) return nonFiniteToString(x);\r\n var k,\r\n e = x.e,\r\n str = digitsToString(x.d),\r\n len = str.length;\r\n\r\n if (isExp) {\r\n if (sd && (k = sd - len) > 0) {\r\n str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);\r\n } else if (len > 1) {\r\n str = str.charAt(0) + '.' + str.slice(1);\r\n }\r\n\r\n str = str + (x.e < 0 ? 'e' : 'e+') + x.e;\r\n } else if (e < 0) {\r\n str = '0.' + getZeroString(-e - 1) + str;\r\n if (sd && (k = sd - len) > 0) str += getZeroString(k);\r\n } else if (e >= len) {\r\n str += getZeroString(e + 1 - len);\r\n if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);\r\n } else {\r\n if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);\r\n if (sd && (k = sd - len) > 0) {\r\n if (e + 1 === len) str += '.';\r\n str += getZeroString(k);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // Calculate the base 10 exponent from the base 1e7 exponent.\r\n function getBase10Exponent(digits, e) {\r\n var w = digits[0];\r\n\r\n // Add the number of digits of the first word of the digits array.\r\n for ( e *= LOG_BASE; w >= 10; w /= 10) e++;\r\n return e;\r\n }\r\n\r\n\r\n function getLn10(Ctor, sd, pr) {\r\n if (sd > LN10_PRECISION) {\r\n\r\n // Reset global state in case the exception is caught.\r\n external = true;\r\n if (pr) Ctor.precision = pr;\r\n throw Error(precisionLimitExceeded);\r\n }\r\n return finalise(new Ctor(LN10), sd, 1, true);\r\n }\r\n\r\n\r\n function getPi(Ctor, sd, rm) {\r\n if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);\r\n return finalise(new Ctor(PI), sd, rm, true);\r\n }\r\n\r\n\r\n function getPrecision(digits) {\r\n var w = digits.length - 1,\r\n len = w * LOG_BASE + 1;\r\n\r\n w = digits[w];\r\n\r\n // If non-zero...\r\n if (w) {\r\n\r\n // Subtract the number of trailing zeros of the last word.\r\n for (; w % 10 == 0; w /= 10) len--;\r\n\r\n // Add the number of digits of the first word.\r\n for (w = digits[0]; w >= 10; w /= 10) len++;\r\n }\r\n\r\n return len;\r\n }\r\n\r\n\r\n function getZeroString(k) {\r\n var zs = '';\r\n for (; k--;) zs += '0';\r\n return zs;\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an\r\n * integer of type number.\r\n *\r\n * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.\r\n *\r\n */\r\n function intPow(Ctor, x, n, pr) {\r\n var isTruncated,\r\n r = new Ctor(1),\r\n\r\n // Max n of 9007199254740991 takes 53 loop iterations.\r\n // Maximum digits array length; leaves [28, 34] guard digits.\r\n k = Math.ceil(pr / LOG_BASE + 4);\r\n\r\n external = false;\r\n\r\n for (;;) {\r\n if (n % 2) {\r\n r = r.times(x);\r\n if (truncate(r.d, k)) isTruncated = true;\r\n }\r\n\r\n n = mathfloor(n / 2);\r\n if (n === 0) {\r\n\r\n // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.\r\n n = r.d.length - 1;\r\n if (isTruncated && r.d[n] === 0) ++r.d[n];\r\n break;\r\n }\r\n\r\n x = x.times(x);\r\n truncate(x.d, k);\r\n }\r\n\r\n external = true;\r\n\r\n return r;\r\n }\r\n\r\n\r\n function isOdd(n) {\r\n return n.d[n.d.length - 1] & 1;\r\n }\r\n\r\n\r\n /*\r\n * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.\r\n */\r\n function maxOrMin(Ctor, args, ltgt) {\r\n var y,\r\n x = new Ctor(args[0]),\r\n i = 0;\r\n\r\n for (; ++i < args.length;) {\r\n y = new Ctor(args[i]);\r\n if (!y.s) {\r\n x = y;\r\n break;\r\n } else if (x[ltgt](y)) {\r\n x = y;\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant\r\n * digits.\r\n *\r\n * Taylor/Maclaurin series.\r\n *\r\n * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...\r\n *\r\n * Argument reduction:\r\n * Repeat x = x / 32, k += 5, until |x| < 0.1\r\n * exp(x) = exp(x / 2^k)^(2^k)\r\n *\r\n * Previously, the argument was initially reduced by\r\n * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)\r\n * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was\r\n * found to be slower than just dividing repeatedly by 32 as above.\r\n *\r\n * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000\r\n * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000\r\n * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)\r\n *\r\n * exp(Infinity) = Infinity\r\n * exp(-Infinity) = 0\r\n * exp(NaN) = NaN\r\n * exp(±0) = 1\r\n *\r\n * exp(x) is non-terminating for any finite, non-zero x.\r\n *\r\n * The result will always be correctly rounded.\r\n *\r\n */\r\n function naturalExponential(x, sd) {\r\n var denominator, guard, j, pow, sum, t, wpr,\r\n rep = 0,\r\n i = 0,\r\n k = 0,\r\n Ctor = x.constructor,\r\n rm = Ctor.rounding,\r\n pr = Ctor.precision;\r\n\r\n // 0/NaN/Infinity?\r\n if (!x.d || !x.d[0] || x.e > 17) {\r\n\r\n return new Ctor(x.d\r\n ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0\r\n : x.s ? x.s < 0 ? 0 : x : 0 / 0);\r\n }\r\n\r\n if (sd == null) {\r\n external = false;\r\n wpr = pr;\r\n } else {\r\n wpr = sd;\r\n }\r\n\r\n t = new Ctor(0.03125);\r\n\r\n // while abs(x) >= 0.1\r\n while (x.e > -2) {\r\n\r\n // x = x / 2^5\r\n x = x.times(t);\r\n k += 5;\r\n }\r\n\r\n // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision\r\n // necessary to ensure the first 4 rounding digits are correct.\r\n guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;\r\n wpr += guard;\r\n denominator = pow = sum = new Ctor(1);\r\n Ctor.precision = wpr;\r\n\r\n for (;;) {\r\n pow = finalise(pow.times(x), wpr, 1);\r\n denominator = denominator.times(++i);\r\n t = sum.plus(divide(pow, denominator, wpr, 1));\r\n\r\n if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n j = k;\r\n while (j--) sum = finalise(sum.times(sum), wpr, 1);\r\n\r\n // Check to see if the first 4 rounding digits are [49]999.\r\n // If so, repeat the summation with a higher precision, otherwise\r\n // e.g. with precision: 18, rounding: 1\r\n // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)\r\n // `wpr - guard` is the index of first rounding digit.\r\n if (sd == null) {\r\n\r\n if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {\r\n Ctor.precision = wpr += 10;\r\n denominator = pow = t = new Ctor(1);\r\n i = 0;\r\n rep++;\r\n } else {\r\n return finalise(sum, Ctor.precision = pr, rm, external = true);\r\n }\r\n } else {\r\n Ctor.precision = pr;\r\n return sum;\r\n }\r\n }\r\n\r\n sum = t;\r\n }\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant\r\n * digits.\r\n *\r\n * ln(-n) = NaN\r\n * ln(0) = -Infinity\r\n * ln(-0) = -Infinity\r\n * ln(1) = 0\r\n * ln(Infinity) = Infinity\r\n * ln(-Infinity) = NaN\r\n * ln(NaN) = NaN\r\n *\r\n * ln(n) (n != 1) is non-terminating.\r\n *\r\n */\r\n function naturalLogarithm(y, sd) {\r\n var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,\r\n n = 1,\r\n guard = 10,\r\n x = y,\r\n xd = x.d,\r\n Ctor = x.constructor,\r\n rm = Ctor.rounding,\r\n pr = Ctor.precision;\r\n\r\n // Is x negative or Infinity, NaN, 0 or 1?\r\n if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {\r\n return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);\r\n }\r\n\r\n if (sd == null) {\r\n external = false;\r\n wpr = pr;\r\n } else {\r\n wpr = sd;\r\n }\r\n\r\n Ctor.precision = wpr += guard;\r\n c = digitsToString(xd);\r\n c0 = c.charAt(0);\r\n\r\n if (Math.abs(e = x.e) < 1.5e15) {\r\n\r\n // Argument reduction.\r\n // The series converges faster the closer the argument is to 1, so using\r\n // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b\r\n // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,\r\n // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can\r\n // later be divided by this number, then separate out the power of 10 using\r\n // ln(a*10^b) = ln(a) + b*ln(10).\r\n\r\n // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).\r\n //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {\r\n // max n is 6 (gives 0.7 - 1.3)\r\n while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {\r\n x = x.times(y);\r\n c = digitsToString(x.d);\r\n c0 = c.charAt(0);\r\n n++;\r\n }\r\n\r\n e = x.e;\r\n\r\n if (c0 > 1) {\r\n x = new Ctor('0.' + c);\r\n e++;\r\n } else {\r\n x = new Ctor(c0 + '.' + c.slice(1));\r\n }\r\n } else {\r\n\r\n // The argument reduction method above may result in overflow if the argument y is a massive\r\n // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this\r\n // function using ln(x*10^e) = ln(x) + e*ln(10).\r\n t = getLn10(Ctor, wpr + 2, pr).times(e + '');\r\n x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);\r\n Ctor.precision = pr;\r\n\r\n return sd == null ? finalise(x, pr, rm, external = true) : x;\r\n }\r\n\r\n // x1 is x reduced to a value near 1.\r\n x1 = x;\r\n\r\n // Taylor series.\r\n // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)\r\n // where x = (y - 1)/(y + 1) (|x| < 1)\r\n sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);\r\n x2 = finalise(x.times(x), wpr, 1);\r\n denominator = 3;\r\n\r\n for (;;) {\r\n numerator = finalise(numerator.times(x2), wpr, 1);\r\n t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));\r\n\r\n if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n sum = sum.times(2);\r\n\r\n // Reverse the argument reduction. Check that e is not 0 because, besides preventing an\r\n // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.\r\n if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));\r\n sum = divide(sum, new Ctor(n), wpr, 1);\r\n\r\n // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has\r\n // been repeated previously) and the first 4 rounding digits 9999?\r\n // If so, restart the summation with a higher precision, otherwise\r\n // e.g. with precision: 12, rounding: 1\r\n // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.\r\n // `wpr - guard` is the index of first rounding digit.\r\n if (sd == null) {\r\n if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {\r\n Ctor.precision = wpr += guard;\r\n t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);\r\n x2 = finalise(x.times(x), wpr, 1);\r\n denominator = rep = 1;\r\n } else {\r\n return finalise(sum, Ctor.precision = pr, rm, external = true);\r\n }\r\n } else {\r\n Ctor.precision = pr;\r\n return sum;\r\n }\r\n }\r\n\r\n sum = t;\r\n denominator += 2;\r\n }\r\n }\r\n\r\n\r\n // ±Infinity, NaN.\r\n function nonFiniteToString(x) {\r\n // Unsigned.\r\n return String(x.s * x.s / 0);\r\n }\r\n\r\n\r\n /*\r\n * Parse the value of a new Decimal `x` from string `str`.\r\n */\r\n function parseDecimal(x, str) {\r\n var e, i, len;\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(len - 1) === 48; --len);\r\n str = str.slice(i, len);\r\n\r\n if (str) {\r\n len -= i;\r\n x.e = e = e - i - 1;\r\n x.d = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first word of the digits array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE;\r\n\r\n if (i < len) {\r\n if (i) x.d.push(+str.slice(0, i));\r\n for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));\r\n str = str.slice(i);\r\n i = LOG_BASE - str.length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--;) str += '0';\r\n x.d.push(+str);\r\n\r\n if (external) {\r\n\r\n // Overflow?\r\n if (x.e > x.constructor.maxE) {\r\n\r\n // Infinity.\r\n x.d = null;\r\n x.e = NaN;\r\n\r\n // Underflow?\r\n } else if (x.e < x.constructor.minE) {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n // x.constructor.underflow = true;\r\n } // else x.constructor.underflow = false;\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.\r\n */\r\n function parseOther(x, str) {\r\n var base, Ctor, divisor, i, isFloat, len, p, xd, xe;\r\n\r\n if (str === 'Infinity' || str === 'NaN') {\r\n if (!+str) x.s = NaN;\r\n x.e = NaN;\r\n x.d = null;\r\n return x;\r\n }\r\n\r\n if (isHex.test(str)) {\r\n base = 16;\r\n str = str.toLowerCase();\r\n } else if (isBinary.test(str)) {\r\n base = 2;\r\n } else if (isOctal.test(str)) {\r\n base = 8;\r\n } else {\r\n throw Error(invalidArgument + str);\r\n }\r\n\r\n // Is there a binary exponent part?\r\n i = str.search(/p/i);\r\n\r\n if (i > 0) {\r\n p = +str.slice(i + 1);\r\n str = str.substring(2, i);\r\n } else {\r\n str = str.slice(2);\r\n }\r\n\r\n // Convert `str` as an integer then divide the result by `base` raised to a power such that the\r\n // fraction part will be restored.\r\n i = str.indexOf('.');\r\n isFloat = i >= 0;\r\n Ctor = x.constructor;\r\n\r\n if (isFloat) {\r\n str = str.replace('.', '');\r\n len = str.length;\r\n i = len - i;\r\n\r\n // log[10](16) = 1.2041... , log[10](88) = 1.9444....\r\n divisor = intPow(Ctor, new Ctor(base), i, i * 2);\r\n }\r\n\r\n xd = convertBase(str, base, BASE);\r\n xe = xd.length - 1;\r\n\r\n // Remove trailing zeros.\r\n for (i = xe; xd[i] === 0; --i) xd.pop();\r\n if (i < 0) return new Ctor(x.s * 0);\r\n x.e = getBase10Exponent(xd, xe);\r\n x.d = xd;\r\n external = false;\r\n\r\n // At what precision to perform the division to ensure exact conversion?\r\n // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)\r\n // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412\r\n // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.\r\n // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount\r\n // Therefore using 4 * the number of digits of str will always be enough.\r\n if (isFloat) x = divide(x, divisor, len * 4);\r\n\r\n // Multiply by the binary exponent part if present.\r\n if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));\r\n external = true;\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * sin(x) = x - x^3/3! + x^5/5! - ...\r\n * |x| < pi/2\r\n *\r\n */\r\n function sine(Ctor, x) {\r\n var k,\r\n len = x.d.length;\r\n\r\n if (len < 3) return taylorSeries(Ctor, 2, x, x);\r\n\r\n // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)\r\n // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)\r\n // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n k = 1.4 * Math.sqrt(len);\r\n k = k > 16 ? 16 : k | 0;\r\n\r\n x = x.times(1 / tinyPow(5, k));\r\n x = taylorSeries(Ctor, 2, x, x);\r\n\r\n // Reverse argument reduction\r\n var sin2_x,\r\n d5 = new Ctor(5),\r\n d16 = new Ctor(16),\r\n d20 = new Ctor(20);\r\n for (; k--;) {\r\n sin2_x = x.times(x);\r\n x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.\r\n function taylorSeries(Ctor, n, x, y, isHyperbolic) {\r\n var j, t, u, x2,\r\n i = 1,\r\n pr = Ctor.precision,\r\n k = Math.ceil(pr / LOG_BASE);\r\n\r\n external = false;\r\n x2 = x.times(x);\r\n u = new Ctor(y);\r\n\r\n for (;;) {\r\n t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);\r\n u = isHyperbolic ? y.plus(t) : y.minus(t);\r\n y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);\r\n t = u.plus(y);\r\n\r\n if (t.d[k] !== void 0) {\r\n for (j = k; t.d[j] === u.d[j] && j--;);\r\n if (j == -1) break;\r\n }\r\n\r\n j = u;\r\n u = y;\r\n y = t;\r\n t = j;\r\n i++;\r\n }\r\n\r\n external = true;\r\n t.d.length = k + 1;\r\n\r\n return t;\r\n }\r\n\r\n\r\n // Exponent e must be positive and non-zero.\r\n function tinyPow(b, e) {\r\n var n = b;\r\n while (--e) n *= b;\r\n return n;\r\n }\r\n\r\n\r\n // Return the absolute value of `x` reduced to less than or equal to half pi.\r\n function toLessThanHalfPi(Ctor, x) {\r\n var t,\r\n isNeg = x.s < 0,\r\n pi = getPi(Ctor, Ctor.precision, 1),\r\n halfPi = pi.times(0.5);\r\n\r\n x = x.abs();\r\n\r\n if (x.lte(halfPi)) {\r\n quadrant = isNeg ? 4 : 1;\r\n return x;\r\n }\r\n\r\n t = x.divToInt(pi);\r\n\r\n if (t.isZero()) {\r\n quadrant = isNeg ? 3 : 2;\r\n } else {\r\n x = x.minus(t.times(pi));\r\n\r\n // 0 <= x < pi\r\n if (x.lte(halfPi)) {\r\n quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);\r\n return x;\r\n }\r\n\r\n quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);\r\n }\r\n\r\n return x.minus(pi).abs();\r\n }\r\n\r\n\r\n /*\r\n * Return the value of Decimal `x` as a string in base `baseOut`.\r\n *\r\n * If the optional `sd` argument is present include a binary exponent suffix.\r\n */\r\n function toStringBinary(x, baseOut, sd, rm) {\r\n var base, e, i, k, len, roundUp, str, xd, y,\r\n Ctor = x.constructor,\r\n isExp = sd !== void 0;\r\n\r\n if (isExp) {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n } else {\r\n sd = Ctor.precision;\r\n rm = Ctor.rounding;\r\n }\r\n\r\n if (!x.isFinite()) {\r\n str = nonFiniteToString(x);\r\n } else {\r\n str = finiteToString(x);\r\n i = str.indexOf('.');\r\n\r\n // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:\r\n // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))\r\n // minBinaryExponent = floor(decimalExponent * log[2](10))\r\n // log[2](10) = 3.321928094887362347870319429489390175864\r\n\r\n if (isExp) {\r\n base = 2;\r\n if (baseOut == 16) {\r\n sd = sd * 4 - 3;\r\n } else if (baseOut == 8) {\r\n sd = sd * 3 - 2;\r\n }\r\n } else {\r\n base = baseOut;\r\n }\r\n\r\n // Convert the number as an integer then divide the result by its base raised to a power such\r\n // that the fraction part will be restored.\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n str = str.replace('.', '');\r\n y = new Ctor(1);\r\n y.e = str.length - i;\r\n y.d = convertBase(finiteToString(y), 10, base);\r\n y.e = y.d.length;\r\n }\r\n\r\n xd = convertBase(str, 10, base);\r\n e = len = xd.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xd[--len] == 0;) xd.pop();\r\n\r\n if (!xd[0]) {\r\n str = isExp ? '0p+0' : '0';\r\n } else {\r\n if (i < 0) {\r\n e--;\r\n } else {\r\n x = new Ctor(x);\r\n x.d = xd;\r\n x.e = e;\r\n x = divide(x, y, sd, rm, 0, base);\r\n xd = x.d;\r\n e = x.e;\r\n roundUp = inexact;\r\n }\r\n\r\n // The rounding digit, i.e. the digit after the digit that may be rounded up.\r\n i = xd[sd];\r\n k = base / 2;\r\n roundUp = roundUp || xd[sd + 1] !== void 0;\r\n\r\n roundUp = rm < 4\r\n ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))\r\n : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||\r\n rm === (x.s < 0 ? 8 : 7));\r\n\r\n xd.length = sd;\r\n\r\n if (roundUp) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (; ++xd[--sd] > base - 1;) {\r\n xd[sd] = 0;\r\n if (!sd) {\r\n ++e;\r\n xd.unshift(1);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (len = xd.length; !xd[len - 1]; --len);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);\r\n\r\n // Add binary exponent suffix?\r\n if (isExp) {\r\n if (len > 1) {\r\n if (baseOut == 16 || baseOut == 8) {\r\n i = baseOut == 16 ? 4 : 3;\r\n for (--len; len % i; len++) str += '0';\r\n xd = convertBase(str, base, baseOut);\r\n for (len = xd.length; !xd[len - 1]; --len);\r\n\r\n // xd[0] will always be be 1\r\n for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);\r\n } else {\r\n str = str.charAt(0) + '.' + str.slice(1);\r\n }\r\n }\r\n\r\n str = str + (e < 0 ? 'p' : 'p+') + e;\r\n } else if (e < 0) {\r\n for (; ++e;) str = '0' + str;\r\n str = '0.' + str;\r\n } else {\r\n if (++e > len) for (e -= len; e-- ;) str += '0';\r\n else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;\r\n }\r\n\r\n return x.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Does not strip trailing zeros.\r\n function truncate(arr, len) {\r\n if (arr.length > len) {\r\n arr.length = len;\r\n return true;\r\n }\r\n }\r\n\r\n\r\n // Decimal methods\r\n\r\n\r\n /*\r\n * abs\r\n * acos\r\n * acosh\r\n * add\r\n * asin\r\n * asinh\r\n * atan\r\n * atanh\r\n * atan2\r\n * cbrt\r\n * ceil\r\n * clone\r\n * config\r\n * cos\r\n * cosh\r\n * div\r\n * exp\r\n * floor\r\n * hypot\r\n * ln\r\n * log\r\n * log2\r\n * log10\r\n * max\r\n * min\r\n * mod\r\n * mul\r\n * pow\r\n * random\r\n * round\r\n * set\r\n * sign\r\n * sin\r\n * sinh\r\n * sqrt\r\n * sub\r\n * tan\r\n * tanh\r\n * trunc\r\n */\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the absolute value of `x`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function abs(x) {\r\n return new this(x).abs();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the arccosine in radians of `x`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function acos(x) {\r\n return new this(x).acos();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\n function acosh(x) {\r\n return new this(x).acosh();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\n function add(x, y) {\r\n return new this(x).plus(y);\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function asin(x) {\r\n return new this(x).asin();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\n function asinh(x) {\r\n return new this(x).asinh();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function atan(x) {\r\n return new this(x).atan();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\n function atanh(x) {\r\n return new this(x).atanh();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi\r\n * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi, pi]\r\n *\r\n * y {number|string|Decimal} The y-coordinate.\r\n * x {number|string|Decimal} The x-coordinate.\r\n *\r\n * atan2(±0, -0) = ±pi\r\n * atan2(±0, +0) = ±0\r\n * atan2(±0, -x) = ±pi for x > 0\r\n * atan2(±0, x) = ±0 for x > 0\r\n * atan2(-y, ±0) = -pi/2 for y > 0\r\n * atan2(y, ±0) = pi/2 for y > 0\r\n * atan2(±y, -Infinity) = ±pi for finite y > 0\r\n * atan2(±y, +Infinity) = ±0 for finite y > 0\r\n * atan2(±Infinity, x) = ±pi/2 for finite x\r\n * atan2(±Infinity, -Infinity) = ±3*pi/4\r\n * atan2(±Infinity, +Infinity) = ±pi/4\r\n * atan2(NaN, x) = NaN\r\n * atan2(y, NaN) = NaN\r\n *\r\n */\r\n function atan2(y, x) {\r\n y = new this(y);\r\n x = new this(x);\r\n var r,\r\n pr = this.precision,\r\n rm = this.rounding,\r\n wpr = pr + 4;\r\n\r\n // Either NaN\r\n if (!y.s || !x.s) {\r\n r = new this(NaN);\r\n\r\n // Both ±Infinity\r\n } else if (!y.d && !x.d) {\r\n r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);\r\n r.s = y.s;\r\n\r\n // x is ±Infinity or y is ±0\r\n } else if (!x.d || y.isZero()) {\r\n r = x.s < 0 ? getPi(this, pr, rm) : new this(0);\r\n r.s = y.s;\r\n\r\n // y is ±Infinity or x is ±0\r\n } else if (!y.d || x.isZero()) {\r\n r = getPi(this, wpr, 1).times(0.5);\r\n r.s = y.s;\r\n\r\n // Both non-zero and finite\r\n } else if (x.s < 0) {\r\n this.precision = wpr;\r\n this.rounding = 1;\r\n r = this.atan(divide(y, x, wpr, 1));\r\n x = getPi(this, wpr, 1);\r\n this.precision = pr;\r\n this.rounding = rm;\r\n r = y.s < 0 ? r.minus(x) : r.plus(x);\r\n } else {\r\n r = this.atan(divide(y, x, wpr, 1));\r\n }\r\n\r\n return r;\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function cbrt(x) {\r\n return new this(x).cbrt();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function ceil(x) {\r\n return finalise(x = new this(x), x.e + 1, 2);\r\n }\r\n\r\n\r\n /*\r\n * Configure global settings for a Decimal constructor.\r\n *\r\n * `obj` is an object with one or more of the following properties,\r\n *\r\n * precision {number}\r\n * rounding {number}\r\n * toExpNeg {number}\r\n * toExpPos {number}\r\n * maxE {number}\r\n * minE {number}\r\n * modulo {number}\r\n * crypto {boolean|number}\r\n * defaults {true}\r\n *\r\n * E.g. Decimal.config({ precision: 20, rounding: 4 })\r\n *\r\n */\r\n function config(obj) {\r\n if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');\r\n var i, p, v,\r\n useDefaults = obj.defaults === true,\r\n ps = [\r\n 'precision', 1, MAX_DIGITS,\r\n 'rounding', 0, 8,\r\n 'toExpNeg', -EXP_LIMIT, 0,\r\n 'toExpPos', 0, EXP_LIMIT,\r\n 'maxE', 0, EXP_LIMIT,\r\n 'minE', -EXP_LIMIT, 0,\r\n 'modulo', 0, 9\r\n ];\r\n\r\n for (i = 0; i < ps.length; i += 3) {\r\n if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];\r\n if ((v = obj[p]) !== void 0) {\r\n if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;\r\n else throw Error(invalidArgument + p + ': ' + v);\r\n }\r\n }\r\n\r\n if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];\r\n if ((v = obj[p]) !== void 0) {\r\n if (v === true || v === false || v === 0 || v === 1) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n this[p] = true;\r\n } else {\r\n throw Error(cryptoUnavailable);\r\n }\r\n } else {\r\n this[p] = false;\r\n }\r\n } else {\r\n throw Error(invalidArgument + p + ': ' + v);\r\n }\r\n }\r\n\r\n return this;\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\n function cos(x) {\r\n return new this(x).cos();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\n function cosh(x) {\r\n return new this(x).cosh();\r\n }\r\n\r\n\r\n /*\r\n * Create and return a Decimal constructor with the same configuration properties as this Decimal\r\n * constructor.\r\n *\r\n */\r\n function clone(obj) {\r\n var i, p, ps;\r\n\r\n /*\r\n * The Decimal constructor and exported function.\r\n * Return a new Decimal instance.\r\n *\r\n * v {number|string|Decimal} A numeric value.\r\n *\r\n */\r\n function Decimal(v) {\r\n var e, i, t,\r\n x = this;\r\n\r\n // Decimal called without new.\r\n if (!(x instanceof Decimal)) return new Decimal(v);\r\n\r\n // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor\r\n // which points to Object.\r\n x.constructor = Decimal;\r\n\r\n // Duplicate.\r\n if (v instanceof Decimal) {\r\n x.s = v.s;\r\n\r\n if (external) {\r\n if (!v.d || v.e > Decimal.maxE) {\r\n\r\n // Infinity.\r\n x.e = NaN;\r\n x.d = null;\r\n } else if (v.e < Decimal.minE) {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n } else {\r\n x.e = v.e;\r\n x.d = v.d.slice();\r\n }\r\n } else {\r\n x.e = v.e;\r\n x.d = v.d ? v.d.slice() : v.d;\r\n }\r\n\r\n return;\r\n }\r\n\r\n t = typeof v;\r\n\r\n if (t === 'number') {\r\n if (v === 0) {\r\n x.s = 1 / v < 0 ? -1 : 1;\r\n x.e = 0;\r\n x.d = [0];\r\n return;\r\n }\r\n\r\n if (v < 0) {\r\n v = -v;\r\n x.s = -1;\r\n } else {\r\n x.s = 1;\r\n }\r\n\r\n // Fast path for small integers.\r\n if (v === ~~v && v < 1e7) {\r\n for (e = 0, i = v; i >= 10; i /= 10) e++;\r\n\r\n if (external) {\r\n if (e > Decimal.maxE) {\r\n x.e = NaN;\r\n x.d = null;\r\n } else if (e < Decimal.minE) {\r\n x.e = 0;\r\n x.d = [0];\r\n } else {\r\n x.e = e;\r\n x.d = [v];\r\n }\r\n } else {\r\n x.e = e;\r\n x.d = [v];\r\n }\r\n\r\n return;\r\n\r\n // Infinity, NaN.\r\n } else if (v * 0 !== 0) {\r\n if (!v) x.s = NaN;\r\n x.e = NaN;\r\n x.d = null;\r\n return;\r\n }\r\n\r\n return parseDecimal(x, v.toString());\r\n\r\n } else if (t !== 'string') {\r\n throw Error(invalidArgument + v);\r\n }\r\n\r\n // Minus sign?\r\n if ((i = v.charCodeAt(0)) === 45) {\r\n v = v.slice(1);\r\n x.s = -1;\r\n } else {\r\n // Plus sign?\r\n if (i === 43) v = v.slice(1);\r\n x.s = 1;\r\n }\r\n\r\n return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);\r\n }\r\n\r\n Decimal.prototype = P;\r\n\r\n Decimal.ROUND_UP = 0;\r\n Decimal.ROUND_DOWN = 1;\r\n Decimal.ROUND_CEIL = 2;\r\n Decimal.ROUND_FLOOR = 3;\r\n Decimal.ROUND_HALF_UP = 4;\r\n Decimal.ROUND_HALF_DOWN = 5;\r\n Decimal.ROUND_HALF_EVEN = 6;\r\n Decimal.ROUND_HALF_CEIL = 7;\r\n Decimal.ROUND_HALF_FLOOR = 8;\r\n Decimal.EUCLID = 9;\r\n\r\n Decimal.config = Decimal.set = config;\r\n Decimal.clone = clone;\r\n Decimal.isDecimal = isDecimalInstance;\r\n\r\n Decimal.abs = abs;\r\n Decimal.acos = acos;\r\n Decimal.acosh = acosh; // ES6\r\n Decimal.add = add;\r\n Decimal.asin = asin;\r\n Decimal.asinh = asinh; // ES6\r\n Decimal.atan = atan;\r\n Decimal.atanh = atanh; // ES6\r\n Decimal.atan2 = atan2;\r\n Decimal.cbrt = cbrt; // ES6\r\n Decimal.ceil = ceil;\r\n Decimal.cos = cos;\r\n Decimal.cosh = cosh; // ES6\r\n Decimal.div = div;\r\n Decimal.exp = exp;\r\n Decimal.floor = floor;\r\n Decimal.hypot = hypot; // ES6\r\n Decimal.ln = ln;\r\n Decimal.log = log;\r\n Decimal.log10 = log10; // ES6\r\n Decimal.log2 = log2; // ES6\r\n Decimal.max = max;\r\n Decimal.min = min;\r\n Decimal.mod = mod;\r\n Decimal.mul = mul;\r\n Decimal.pow = pow;\r\n Decimal.random = random;\r\n Decimal.round = round;\r\n Decimal.sign = sign; // ES6\r\n Decimal.sin = sin;\r\n Decimal.sinh = sinh; // ES6\r\n Decimal.sqrt = sqrt;\r\n Decimal.sub = sub;\r\n Decimal.tan = tan;\r\n Decimal.tanh = tanh; // ES6\r\n Decimal.trunc = trunc; // ES6\r\n\r\n if (obj === void 0) obj = {};\r\n if (obj) {\r\n if (obj.defaults !== true) {\r\n ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];\r\n for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];\r\n }\r\n }\r\n\r\n Decimal.config(obj);\r\n\r\n return Decimal;\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\n function div(x, y) {\r\n return new this(x).div(y);\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} The power to which to raise the base of the natural log.\r\n *\r\n */\r\n function exp(x) {\r\n return new this(x).exp();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function floor(x) {\r\n return finalise(x = new this(x), x.e + 1, 3);\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,\r\n * rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\n function hypot() {\r\n var i, n,\r\n t = new this(0);\r\n\r\n external = false;\r\n\r\n for (i = 0; i < arguments.length;) {\r\n n = new this(arguments[i++]);\r\n if (!n.d) {\r\n if (n.s) {\r\n external = true;\r\n return new this(1 / 0);\r\n }\r\n t = n;\r\n } else if (t.d) {\r\n t = t.plus(n.times(n));\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return t.sqrt();\r\n }\r\n\r\n\r\n /*\r\n * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),\r\n * otherwise return false.\r\n *\r\n */\r\n function isDecimalInstance(obj) {\r\n return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false;\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function ln(x) {\r\n return new this(x).ln();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base\r\n * is specified, rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * log[y](x)\r\n *\r\n * x {number|string|Decimal} The argument of the logarithm.\r\n * y {number|string|Decimal} The base of the logarithm.\r\n *\r\n */\r\n function log(x, y) {\r\n return new this(x).log(y);\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function log2(x) {\r\n return new this(x).log(2);\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function log10(x) {\r\n return new this(x).log(10);\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\n function max() {\r\n return maxOrMin(this, arguments, 'lt');\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\n function min() {\r\n return maxOrMin(this, arguments, 'gt');\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\n function mod(x, y) {\r\n return new this(x).mod(y);\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\n function mul(x, y) {\r\n return new this(x).mul(y);\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} The base.\r\n * y {number|string|Decimal} The exponent.\r\n *\r\n */\r\n function pow(x, y) {\r\n return new this(x).pow(y);\r\n }\r\n\r\n\r\n /*\r\n * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with\r\n * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros\r\n * are produced).\r\n *\r\n * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.\r\n *\r\n */\r\n function random(sd) {\r\n var d, e, k, n,\r\n i = 0,\r\n r = new this(1),\r\n rd = [];\r\n\r\n if (sd === void 0) sd = this.precision;\r\n else checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n k = Math.ceil(sd / LOG_BASE);\r\n\r\n if (!this.crypto) {\r\n for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n } else if (crypto.getRandomValues) {\r\n d = crypto.getRandomValues(new Uint32Array(k));\r\n\r\n for (; i < k;) {\r\n n = d[i];\r\n\r\n // 0 <= n < 4294967296\r\n // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).\r\n if (n >= 4.29e9) {\r\n d[i] = crypto.getRandomValues(new Uint32Array(1))[0];\r\n } else {\r\n\r\n // 0 <= n <= 4289999999\r\n // 0 <= (n % 1e7) <= 9999999\r\n rd[i++] = n % 1e7;\r\n }\r\n }\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n d = crypto.randomBytes(k *= 4);\r\n\r\n for (; i < k;) {\r\n\r\n // 0 <= n < 2147483648\r\n n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);\r\n\r\n // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).\r\n if (n >= 2.14e9) {\r\n crypto.randomBytes(4).copy(d, i);\r\n } else {\r\n\r\n // 0 <= n <= 2139999999\r\n // 0 <= (n % 1e7) <= 9999999\r\n rd.push(n % 1e7);\r\n i += 4;\r\n }\r\n }\r\n\r\n i = k / 4;\r\n } else {\r\n throw Error(cryptoUnavailable);\r\n }\r\n\r\n k = rd[--i];\r\n sd %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to sd.\r\n if (k && sd) {\r\n n = mathpow(10, LOG_BASE - sd);\r\n rd[i] = (k / n | 0) * n;\r\n }\r\n\r\n // Remove trailing words which are zero.\r\n for (; rd[i] === 0; i--) rd.pop();\r\n\r\n // Zero?\r\n if (i < 0) {\r\n e = 0;\r\n rd = [0];\r\n } else {\r\n e = -1;\r\n\r\n // Remove leading words which are zero and adjust exponent accordingly.\r\n for (; rd[0] === 0; e -= LOG_BASE) rd.shift();\r\n\r\n // Count the digits of the first word of rd to determine leading zeros.\r\n for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;\r\n\r\n // Adjust the exponent for leading zeros of the first word of rd.\r\n if (k < LOG_BASE) e -= LOG_BASE - k;\r\n }\r\n\r\n r.e = e;\r\n r.d = rd;\r\n\r\n return r;\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.\r\n *\r\n * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function round(x) {\r\n return finalise(x = new this(x), x.e + 1, this.rounding);\r\n }\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if x > 0,\r\n * -1 if x < 0,\r\n * 0 if x is 0,\r\n * -0 if x is -0,\r\n * NaN otherwise\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function sign(x) {\r\n x = new this(x);\r\n return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\n function sin(x) {\r\n return new this(x).sin();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\n function sinh(x) {\r\n return new this(x).sinh();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function sqrt(x) {\r\n return new this(x).sqrt();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\n function sub(x, y) {\r\n return new this(x).sub(y);\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\n function tan(x) {\r\n return new this(x).tan();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\n function tanh(x) {\r\n return new this(x).tanh();\r\n }\r\n\r\n\r\n /*\r\n * Return a new Decimal whose value is `x` truncated to an integer.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\n function trunc(x) {\r\n return finalise(x = new this(x), x.e + 1, 1);\r\n }\r\n\r\n\r\n // Create and configure initial Decimal constructor.\r\n Decimal = clone(DEFAULTS);\r\n\r\n Decimal['default'] = Decimal.Decimal = Decimal;\r\n\r\n // Create the internal constants from their string values.\r\n LN10 = new Decimal(LN10);\r\n PI = new Decimal(PI);\r\n\r\n\r\n // Export.\r\n\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () {\r\n return Decimal;\r\n });\r\n\r\n // Node and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n if (typeof Symbol == 'function' && typeof Symbol.iterator == 'symbol') {\r\n P[Symbol.for('nodejs.util.inspect.custom')] = P.toString;\r\n P[Symbol.toStringTag] = 'Decimal';\r\n }\r\n\r\n module.exports = Decimal;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalScope) {\r\n globalScope = typeof self != 'undefined' && self && self.self == self ? self : window;\r\n }\r\n\r\n noConflict = globalScope.Decimal;\r\n Decimal.noConflict = function () {\r\n globalScope.Decimal = noConflict;\r\n return Decimal;\r\n };\r\n\r\n globalScope.Decimal = Decimal;\r\n }\r\n})(this);\r\n","\"use strict\";\n\nexports.__esModule = true;\n\nexports.default = function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n};","\"use strict\";\n\nexports.__esModule = true;\n\nvar _defineProperty = require(\"../core-js/object/define-property\");\n\nvar _defineProperty2 = _interopRequireDefault(_defineProperty);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n (0, _defineProperty2.default)(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n}();","\"use strict\";\n\nexports.__esModule = true;\n\nvar _typeof2 = require(\"../helpers/typeof\");\n\nvar _typeof3 = _interopRequireDefault(_typeof2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return call && ((typeof call === \"undefined\" ? \"undefined\" : (0, _typeof3.default)(call)) === \"object\" || typeof call === \"function\") ? call : self;\n};","\"use strict\";\n\nexports.__esModule = true;\n\nvar _setPrototypeOf = require(\"../core-js/object/set-prototype-of\");\n\nvar _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);\n\nvar _create = require(\"../core-js/object/create\");\n\nvar _create2 = _interopRequireDefault(_create);\n\nvar _typeof2 = require(\"../helpers/typeof\");\n\nvar _typeof3 = _interopRequireDefault(_typeof2);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.default = function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + (typeof superClass === \"undefined\" ? \"undefined\" : (0, _typeof3.default)(superClass)));\n }\n\n subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;\n};","import ReactDOM from 'react-dom';\n/**\n * Return if a node is a DOM node. Else will return by `findDOMNode`\n */\n\nexport default function findDOMNode(node) {\n if (node instanceof HTMLElement) {\n return node;\n }\n\n return ReactDOM.findDOMNode(node);\n}","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.polygonClipping = factory());\n}(this, (function () { 'use strict';\n\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n }\n\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n\n /**\n * splaytree v3.1.0\n * Fast Splay tree for Node and browser\n *\n * @author Alexander Milevski \n * @license MIT\n * @preserve\n */\n var Node =\n /** @class */\n function () {\n function Node(key, data) {\n this.next = null;\n this.key = key;\n this.data = data;\n this.left = null;\n this.right = null;\n }\n\n return Node;\n }();\n /* follows \"An implementation of top-down splaying\"\r\n * by D. Sleator March 1992\r\n */\n\n\n function DEFAULT_COMPARE(a, b) {\n return a > b ? 1 : a < b ? -1 : 0;\n }\n /**\r\n * Simple top down splay, not requiring i to be in the tree t.\r\n */\n\n\n function splay(i, t, comparator) {\n var N = new Node(null, null);\n var l = N;\n var r = N;\n\n while (true) {\n var cmp = comparator(i, t.key); //if (i < t.key) {\n\n if (cmp < 0) {\n if (t.left === null) break; //if (i < t.left.key) {\n\n if (comparator(i, t.left.key) < 0) {\n var y = t.left;\n /* rotate right */\n\n t.left = y.right;\n y.right = t;\n t = y;\n if (t.left === null) break;\n }\n\n r.left = t;\n /* link right */\n\n r = t;\n t = t.left; //} else if (i > t.key) {\n } else if (cmp > 0) {\n if (t.right === null) break; //if (i > t.right.key) {\n\n if (comparator(i, t.right.key) > 0) {\n var y = t.right;\n /* rotate left */\n\n t.right = y.left;\n y.left = t;\n t = y;\n if (t.right === null) break;\n }\n\n l.right = t;\n /* link left */\n\n l = t;\n t = t.right;\n } else break;\n }\n /* assemble */\n\n\n l.right = t.left;\n r.left = t.right;\n t.left = N.right;\n t.right = N.left;\n return t;\n }\n\n function insert(i, data, t, comparator) {\n var node = new Node(i, data);\n\n if (t === null) {\n node.left = node.right = null;\n return node;\n }\n\n t = splay(i, t, comparator);\n var cmp = comparator(i, t.key);\n\n if (cmp < 0) {\n node.left = t.left;\n node.right = t;\n t.left = null;\n } else if (cmp >= 0) {\n node.right = t.right;\n node.left = t;\n t.right = null;\n }\n\n return node;\n }\n\n function split(key, v, comparator) {\n var left = null;\n var right = null;\n\n if (v) {\n v = splay(key, v, comparator);\n var cmp = comparator(v.key, key);\n\n if (cmp === 0) {\n left = v.left;\n right = v.right;\n } else if (cmp < 0) {\n right = v.right;\n v.right = null;\n left = v;\n } else {\n left = v.left;\n v.left = null;\n right = v;\n }\n }\n\n return {\n left: left,\n right: right\n };\n }\n\n function merge(left, right, comparator) {\n if (right === null) return left;\n if (left === null) return right;\n right = splay(left.key, right, comparator);\n right.left = left;\n return right;\n }\n /**\r\n * Prints level of the tree\r\n */\n\n\n function printRow(root, prefix, isTail, out, printNode) {\n if (root) {\n out(\"\" + prefix + (isTail ? '└── ' : '├── ') + printNode(root) + \"\\n\");\n var indent = prefix + (isTail ? ' ' : '│ ');\n if (root.left) printRow(root.left, indent, false, out, printNode);\n if (root.right) printRow(root.right, indent, true, out, printNode);\n }\n }\n\n var Tree =\n /** @class */\n function () {\n function Tree(comparator) {\n if (comparator === void 0) {\n comparator = DEFAULT_COMPARE;\n }\n\n this._root = null;\n this._size = 0;\n this._comparator = comparator;\n }\n /**\r\n * Inserts a key, allows duplicates\r\n */\n\n\n Tree.prototype.insert = function (key, data) {\n this._size++;\n return this._root = insert(key, data, this._root, this._comparator);\n };\n /**\r\n * Adds a key, if it is not present in the tree\r\n */\n\n\n Tree.prototype.add = function (key, data) {\n var node = new Node(key, data);\n\n if (this._root === null) {\n node.left = node.right = null;\n this._size++;\n this._root = node;\n }\n\n var comparator = this._comparator;\n var t = splay(key, this._root, comparator);\n var cmp = comparator(key, t.key);\n if (cmp === 0) this._root = t;else {\n if (cmp < 0) {\n node.left = t.left;\n node.right = t;\n t.left = null;\n } else if (cmp > 0) {\n node.right = t.right;\n node.left = t;\n t.right = null;\n }\n\n this._size++;\n this._root = node;\n }\n return this._root;\n };\n /**\r\n * @param {Key} key\r\n * @return {Node|null}\r\n */\n\n\n Tree.prototype.remove = function (key) {\n this._root = this._remove(key, this._root, this._comparator);\n };\n /**\r\n * Deletes i from the tree if it's there\r\n */\n\n\n Tree.prototype._remove = function (i, t, comparator) {\n var x;\n if (t === null) return null;\n t = splay(i, t, comparator);\n var cmp = comparator(i, t.key);\n\n if (cmp === 0) {\n /* found it */\n if (t.left === null) {\n x = t.right;\n } else {\n x = splay(i, t.left, comparator);\n x.right = t.right;\n }\n\n this._size--;\n return x;\n }\n\n return t;\n /* It wasn't there */\n };\n /**\r\n * Removes and returns the node with smallest key\r\n */\n\n\n Tree.prototype.pop = function () {\n var node = this._root;\n\n if (node) {\n while (node.left) {\n node = node.left;\n }\n\n this._root = splay(node.key, this._root, this._comparator);\n this._root = this._remove(node.key, this._root, this._comparator);\n return {\n key: node.key,\n data: node.data\n };\n }\n\n return null;\n };\n /**\r\n * Find without splaying\r\n */\n\n\n Tree.prototype.findStatic = function (key) {\n var current = this._root;\n var compare = this._comparator;\n\n while (current) {\n var cmp = compare(key, current.key);\n if (cmp === 0) return current;else if (cmp < 0) current = current.left;else current = current.right;\n }\n\n return null;\n };\n\n Tree.prototype.find = function (key) {\n if (this._root) {\n this._root = splay(key, this._root, this._comparator);\n if (this._comparator(key, this._root.key) !== 0) return null;\n }\n\n return this._root;\n };\n\n Tree.prototype.contains = function (key) {\n var current = this._root;\n var compare = this._comparator;\n\n while (current) {\n var cmp = compare(key, current.key);\n if (cmp === 0) return true;else if (cmp < 0) current = current.left;else current = current.right;\n }\n\n return false;\n };\n\n Tree.prototype.forEach = function (visitor, ctx) {\n var current = this._root;\n var Q = [];\n /* Initialize stack s */\n\n var done = false;\n\n while (!done) {\n if (current !== null) {\n Q.push(current);\n current = current.left;\n } else {\n if (Q.length !== 0) {\n current = Q.pop();\n visitor.call(ctx, current);\n current = current.right;\n } else done = true;\n }\n }\n\n return this;\n };\n /**\r\n * Walk key range from `low` to `high`. Stops if `fn` returns a value.\r\n */\n\n\n Tree.prototype.range = function (low, high, fn, ctx) {\n var Q = [];\n var compare = this._comparator;\n var node = this._root;\n var cmp;\n\n while (Q.length !== 0 || node) {\n if (node) {\n Q.push(node);\n node = node.left;\n } else {\n node = Q.pop();\n cmp = compare(node.key, high);\n\n if (cmp > 0) {\n break;\n } else if (compare(node.key, low) >= 0) {\n if (fn.call(ctx, node)) return this; // stop if smth is returned\n }\n\n node = node.right;\n }\n }\n\n return this;\n };\n /**\r\n * Returns array of keys\r\n */\n\n\n Tree.prototype.keys = function () {\n var keys = [];\n this.forEach(function (_a) {\n var key = _a.key;\n return keys.push(key);\n });\n return keys;\n };\n /**\r\n * Returns array of all the data in the nodes\r\n */\n\n\n Tree.prototype.values = function () {\n var values = [];\n this.forEach(function (_a) {\n var data = _a.data;\n return values.push(data);\n });\n return values;\n };\n\n Tree.prototype.min = function () {\n if (this._root) return this.minNode(this._root).key;\n return null;\n };\n\n Tree.prototype.max = function () {\n if (this._root) return this.maxNode(this._root).key;\n return null;\n };\n\n Tree.prototype.minNode = function (t) {\n if (t === void 0) {\n t = this._root;\n }\n\n if (t) while (t.left) {\n t = t.left;\n }\n return t;\n };\n\n Tree.prototype.maxNode = function (t) {\n if (t === void 0) {\n t = this._root;\n }\n\n if (t) while (t.right) {\n t = t.right;\n }\n return t;\n };\n /**\r\n * Returns node at given index\r\n */\n\n\n Tree.prototype.at = function (index) {\n var current = this._root;\n var done = false;\n var i = 0;\n var Q = [];\n\n while (!done) {\n if (current) {\n Q.push(current);\n current = current.left;\n } else {\n if (Q.length > 0) {\n current = Q.pop();\n if (i === index) return current;\n i++;\n current = current.right;\n } else done = true;\n }\n }\n\n return null;\n };\n\n Tree.prototype.next = function (d) {\n var root = this._root;\n var successor = null;\n\n if (d.right) {\n successor = d.right;\n\n while (successor.left) {\n successor = successor.left;\n }\n\n return successor;\n }\n\n var comparator = this._comparator;\n\n while (root) {\n var cmp = comparator(d.key, root.key);\n if (cmp === 0) break;else if (cmp < 0) {\n successor = root;\n root = root.left;\n } else root = root.right;\n }\n\n return successor;\n };\n\n Tree.prototype.prev = function (d) {\n var root = this._root;\n var predecessor = null;\n\n if (d.left !== null) {\n predecessor = d.left;\n\n while (predecessor.right) {\n predecessor = predecessor.right;\n }\n\n return predecessor;\n }\n\n var comparator = this._comparator;\n\n while (root) {\n var cmp = comparator(d.key, root.key);\n if (cmp === 0) break;else if (cmp < 0) root = root.left;else {\n predecessor = root;\n root = root.right;\n }\n }\n\n return predecessor;\n };\n\n Tree.prototype.clear = function () {\n this._root = null;\n this._size = 0;\n return this;\n };\n\n Tree.prototype.toList = function () {\n return toList(this._root);\n };\n /**\r\n * Bulk-load items. Both array have to be same size\r\n */\n\n\n Tree.prototype.load = function (keys, values, presort) {\n if (values === void 0) {\n values = [];\n }\n\n if (presort === void 0) {\n presort = false;\n }\n\n var size = keys.length;\n var comparator = this._comparator; // sort if needed\n\n if (presort) sort(keys, values, 0, size - 1, comparator);\n\n if (this._root === null) {\n // empty tree\n this._root = loadRecursive(keys, values, 0, size);\n this._size = size;\n } else {\n // that re-builds the whole tree from two in-order traversals\n var mergedList = mergeLists(this.toList(), createList(keys, values), comparator);\n size = this._size + size;\n this._root = sortedListToBST({\n head: mergedList\n }, 0, size);\n }\n\n return this;\n };\n\n Tree.prototype.isEmpty = function () {\n return this._root === null;\n };\n\n Object.defineProperty(Tree.prototype, \"size\", {\n get: function get() {\n return this._size;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Tree.prototype, \"root\", {\n get: function get() {\n return this._root;\n },\n enumerable: true,\n configurable: true\n });\n\n Tree.prototype.toString = function (printNode) {\n if (printNode === void 0) {\n printNode = function printNode(n) {\n return String(n.key);\n };\n }\n\n var out = [];\n printRow(this._root, '', true, function (v) {\n return out.push(v);\n }, printNode);\n return out.join('');\n };\n\n Tree.prototype.update = function (key, newKey, newData) {\n var comparator = this._comparator;\n\n var _a = split(key, this._root, comparator),\n left = _a.left,\n right = _a.right;\n\n if (comparator(key, newKey) < 0) {\n right = insert(newKey, newData, right, comparator);\n } else {\n left = insert(newKey, newData, left, comparator);\n }\n\n this._root = merge(left, right, comparator);\n };\n\n Tree.prototype.split = function (key) {\n return split(key, this._root, this._comparator);\n };\n\n return Tree;\n }();\n\n function loadRecursive(keys, values, start, end) {\n var size = end - start;\n\n if (size > 0) {\n var middle = start + Math.floor(size / 2);\n var key = keys[middle];\n var data = values[middle];\n var node = new Node(key, data);\n node.left = loadRecursive(keys, values, start, middle);\n node.right = loadRecursive(keys, values, middle + 1, end);\n return node;\n }\n\n return null;\n }\n\n function createList(keys, values) {\n var head = new Node(null, null);\n var p = head;\n\n for (var i = 0; i < keys.length; i++) {\n p = p.next = new Node(keys[i], values[i]);\n }\n\n p.next = null;\n return head.next;\n }\n\n function toList(root) {\n var current = root;\n var Q = [];\n var done = false;\n var head = new Node(null, null);\n var p = head;\n\n while (!done) {\n if (current) {\n Q.push(current);\n current = current.left;\n } else {\n if (Q.length > 0) {\n current = p = p.next = Q.pop();\n current = current.right;\n } else done = true;\n }\n }\n\n p.next = null; // that'll work even if the tree was empty\n\n return head.next;\n }\n\n function sortedListToBST(list, start, end) {\n var size = end - start;\n\n if (size > 0) {\n var middle = start + Math.floor(size / 2);\n var left = sortedListToBST(list, start, middle);\n var root = list.head;\n root.left = left;\n list.head = list.head.next;\n root.right = sortedListToBST(list, middle + 1, end);\n return root;\n }\n\n return null;\n }\n\n function mergeLists(l1, l2, compare) {\n var head = new Node(null, null); // dummy\n\n var p = head;\n var p1 = l1;\n var p2 = l2;\n\n while (p1 !== null && p2 !== null) {\n if (compare(p1.key, p2.key) < 0) {\n p.next = p1;\n p1 = p1.next;\n } else {\n p.next = p2;\n p2 = p2.next;\n }\n\n p = p.next;\n }\n\n if (p1 !== null) {\n p.next = p1;\n } else if (p2 !== null) {\n p.next = p2;\n }\n\n return head.next;\n }\n\n function sort(keys, values, left, right, compare) {\n if (left >= right) return;\n var pivot = keys[left + right >> 1];\n var i = left - 1;\n var j = right + 1;\n\n while (true) {\n do {\n i++;\n } while (compare(keys[i], pivot) < 0);\n\n do {\n j--;\n } while (compare(keys[j], pivot) > 0);\n\n if (i >= j) break;\n var tmp = keys[i];\n keys[i] = keys[j];\n keys[j] = tmp;\n tmp = values[i];\n values[i] = values[j];\n values[j] = tmp;\n }\n\n sort(keys, values, left, j, compare);\n sort(keys, values, j + 1, right, compare);\n }\n\n /**\n * A bounding box has the format:\n *\n * { ll: { x: xmin, y: ymin }, ur: { x: xmax, y: ymax } }\n *\n */\n var isInBbox = function isInBbox(bbox, point) {\n return bbox.ll.x <= point.x && point.x <= bbox.ur.x && bbox.ll.y <= point.y && point.y <= bbox.ur.y;\n };\n /* Returns either null, or a bbox (aka an ordered pair of points)\n * If there is only one point of overlap, a bbox with identical points\n * will be returned */\n\n var getBboxOverlap = function getBboxOverlap(b1, b2) {\n // check if the bboxes overlap at all\n if (b2.ur.x < b1.ll.x || b1.ur.x < b2.ll.x || b2.ur.y < b1.ll.y || b1.ur.y < b2.ll.y) return null; // find the middle two X values\n\n var lowerX = b1.ll.x < b2.ll.x ? b2.ll.x : b1.ll.x;\n var upperX = b1.ur.x < b2.ur.x ? b1.ur.x : b2.ur.x; // find the middle two Y values\n\n var lowerY = b1.ll.y < b2.ll.y ? b2.ll.y : b1.ll.y;\n var upperY = b1.ur.y < b2.ur.y ? b1.ur.y : b2.ur.y; // put those middle values together to get the overlap\n\n return {\n ll: {\n x: lowerX,\n y: lowerY\n },\n ur: {\n x: upperX,\n y: upperY\n }\n };\n };\n\n /* Javascript doesn't do integer math. Everything is\n * floating point with percision Number.EPSILON.\n *\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON\n */\n var epsilon = Number.EPSILON; // IE Polyfill\n\n if (epsilon === undefined) epsilon = Math.pow(2, -52);\n var EPSILON_SQ = epsilon * epsilon;\n /* FLP comparator */\n\n var cmp = function cmp(a, b) {\n // check if they're both 0\n if (-epsilon < a && a < epsilon) {\n if (-epsilon < b && b < epsilon) {\n return 0;\n }\n } // check if they're flp equal\n\n\n var ab = a - b;\n\n if (ab * ab < EPSILON_SQ * a * b) {\n return 0;\n } // normal comparison\n\n\n return a < b ? -1 : 1;\n };\n\n /**\n * This class rounds incoming values sufficiently so that\n * floating points problems are, for the most part, avoided.\n *\n * Incoming points are have their x & y values tested against\n * all previously seen x & y values. If either is 'too close'\n * to a previously seen value, it's value is 'snapped' to the\n * previously seen value.\n *\n * All points should be rounded by this class before being\n * stored in any data structures in the rest of this algorithm.\n */\n\n var PtRounder = /*#__PURE__*/function () {\n function PtRounder() {\n _classCallCheck(this, PtRounder);\n\n this.reset();\n }\n\n _createClass(PtRounder, [{\n key: \"reset\",\n value: function reset() {\n this.xRounder = new CoordRounder();\n this.yRounder = new CoordRounder();\n }\n }, {\n key: \"round\",\n value: function round(x, y) {\n return {\n x: this.xRounder.round(x),\n y: this.yRounder.round(y)\n };\n }\n }]);\n\n return PtRounder;\n }();\n\n var CoordRounder = /*#__PURE__*/function () {\n function CoordRounder() {\n _classCallCheck(this, CoordRounder);\n\n this.tree = new Tree(); // preseed with 0 so we don't end up with values < Number.EPSILON\n\n this.round(0);\n } // Note: this can rounds input values backwards or forwards.\n // You might ask, why not restrict this to just rounding\n // forwards? Wouldn't that allow left endpoints to always\n // remain left endpoints during splitting (never change to\n // right). No - it wouldn't, because we snap intersections\n // to endpoints (to establish independence from the segment\n // angle for t-intersections).\n\n\n _createClass(CoordRounder, [{\n key: \"round\",\n value: function round(coord) {\n var node = this.tree.add(coord);\n var prevNode = this.tree.prev(node);\n\n if (prevNode !== null && cmp(node.key, prevNode.key) === 0) {\n this.tree.remove(coord);\n return prevNode.key;\n }\n\n var nextNode = this.tree.next(node);\n\n if (nextNode !== null && cmp(node.key, nextNode.key) === 0) {\n this.tree.remove(coord);\n return nextNode.key;\n }\n\n return coord;\n }\n }]);\n\n return CoordRounder;\n }(); // singleton available by import\n\n\n var rounder = new PtRounder();\n\n /* Cross Product of two vectors with first point at origin */\n\n var crossProduct = function crossProduct(a, b) {\n return a.x * b.y - a.y * b.x;\n };\n /* Dot Product of two vectors with first point at origin */\n\n var dotProduct = function dotProduct(a, b) {\n return a.x * b.x + a.y * b.y;\n };\n /* Comparator for two vectors with same starting point */\n\n var compareVectorAngles = function compareVectorAngles(basePt, endPt1, endPt2) {\n var v1 = {\n x: endPt1.x - basePt.x,\n y: endPt1.y - basePt.y\n };\n var v2 = {\n x: endPt2.x - basePt.x,\n y: endPt2.y - basePt.y\n };\n var kross = crossProduct(v1, v2);\n return cmp(kross, 0);\n };\n var length = function length(v) {\n return Math.sqrt(dotProduct(v, v));\n };\n /* Get the sine of the angle from pShared -> pAngle to pShaed -> pBase */\n\n var sineOfAngle = function sineOfAngle(pShared, pBase, pAngle) {\n var vBase = {\n x: pBase.x - pShared.x,\n y: pBase.y - pShared.y\n };\n var vAngle = {\n x: pAngle.x - pShared.x,\n y: pAngle.y - pShared.y\n };\n return crossProduct(vAngle, vBase) / length(vAngle) / length(vBase);\n };\n /* Get the cosine of the angle from pShared -> pAngle to pShaed -> pBase */\n\n var cosineOfAngle = function cosineOfAngle(pShared, pBase, pAngle) {\n var vBase = {\n x: pBase.x - pShared.x,\n y: pBase.y - pShared.y\n };\n var vAngle = {\n x: pAngle.x - pShared.x,\n y: pAngle.y - pShared.y\n };\n return dotProduct(vAngle, vBase) / length(vAngle) / length(vBase);\n };\n /* Get the x coordinate where the given line (defined by a point and vector)\n * crosses the horizontal line with the given y coordiante.\n * In the case of parrallel lines (including overlapping ones) returns null. */\n\n var horizontalIntersection = function horizontalIntersection(pt, v, y) {\n if (v.y === 0) return null;\n return {\n x: pt.x + v.x / v.y * (y - pt.y),\n y: y\n };\n };\n /* Get the y coordinate where the given line (defined by a point and vector)\n * crosses the vertical line with the given x coordiante.\n * In the case of parrallel lines (including overlapping ones) returns null. */\n\n var verticalIntersection = function verticalIntersection(pt, v, x) {\n if (v.x === 0) return null;\n return {\n x: x,\n y: pt.y + v.y / v.x * (x - pt.x)\n };\n };\n /* Get the intersection of two lines, each defined by a base point and a vector.\n * In the case of parrallel lines (including overlapping ones) returns null. */\n\n var intersection = function intersection(pt1, v1, pt2, v2) {\n // take some shortcuts for vertical and horizontal lines\n // this also ensures we don't calculate an intersection and then discover\n // it's actually outside the bounding box of the line\n if (v1.x === 0) return verticalIntersection(pt2, v2, pt1.x);\n if (v2.x === 0) return verticalIntersection(pt1, v1, pt2.x);\n if (v1.y === 0) return horizontalIntersection(pt2, v2, pt1.y);\n if (v2.y === 0) return horizontalIntersection(pt1, v1, pt2.y); // General case for non-overlapping segments.\n // This algorithm is based on Schneider and Eberly.\n // http://www.cimec.org.ar/~ncalvo/Schneider_Eberly.pdf - pg 244\n\n var kross = crossProduct(v1, v2);\n if (kross == 0) return null;\n var ve = {\n x: pt2.x - pt1.x,\n y: pt2.y - pt1.y\n };\n var d1 = crossProduct(ve, v1) / kross;\n var d2 = crossProduct(ve, v2) / kross; // take the average of the two calculations to minimize rounding error\n\n var x1 = pt1.x + d2 * v1.x,\n x2 = pt2.x + d1 * v2.x;\n var y1 = pt1.y + d2 * v1.y,\n y2 = pt2.y + d1 * v2.y;\n var x = (x1 + x2) / 2;\n var y = (y1 + y2) / 2;\n return {\n x: x,\n y: y\n };\n };\n\n var SweepEvent = /*#__PURE__*/function () {\n _createClass(SweepEvent, null, [{\n key: \"compare\",\n // for ordering sweep events in the sweep event queue\n value: function compare(a, b) {\n // favor event with a point that the sweep line hits first\n var ptCmp = SweepEvent.comparePoints(a.point, b.point);\n if (ptCmp !== 0) return ptCmp; // the points are the same, so link them if needed\n\n if (a.point !== b.point) a.link(b); // favor right events over left\n\n if (a.isLeft !== b.isLeft) return a.isLeft ? 1 : -1; // we have two matching left or right endpoints\n // ordering of this case is the same as for their segments\n\n return Segment.compare(a.segment, b.segment);\n } // for ordering points in sweep line order\n\n }, {\n key: \"comparePoints\",\n value: function comparePoints(aPt, bPt) {\n if (aPt.x < bPt.x) return -1;\n if (aPt.x > bPt.x) return 1;\n if (aPt.y < bPt.y) return -1;\n if (aPt.y > bPt.y) return 1;\n return 0;\n } // Warning: 'point' input will be modified and re-used (for performance)\n\n }]);\n\n function SweepEvent(point, isLeft) {\n _classCallCheck(this, SweepEvent);\n\n if (point.events === undefined) point.events = [this];else point.events.push(this);\n this.point = point;\n this.isLeft = isLeft; // this.segment, this.otherSE set by factory\n }\n\n _createClass(SweepEvent, [{\n key: \"link\",\n value: function link(other) {\n if (other.point === this.point) {\n throw new Error('Tried to link already linked events');\n }\n\n var otherEvents = other.point.events;\n\n for (var i = 0, iMax = otherEvents.length; i < iMax; i++) {\n var evt = otherEvents[i];\n this.point.events.push(evt);\n evt.point = this.point;\n }\n\n this.checkForConsuming();\n }\n /* Do a pass over our linked events and check to see if any pair\n * of segments match, and should be consumed. */\n\n }, {\n key: \"checkForConsuming\",\n value: function checkForConsuming() {\n // FIXME: The loops in this method run O(n^2) => no good.\n // Maintain little ordered sweep event trees?\n // Can we maintaining an ordering that avoids the need\n // for the re-sorting with getLeftmostComparator in geom-out?\n // Compare each pair of events to see if other events also match\n var numEvents = this.point.events.length;\n\n for (var i = 0; i < numEvents; i++) {\n var evt1 = this.point.events[i];\n if (evt1.segment.consumedBy !== undefined) continue;\n\n for (var j = i + 1; j < numEvents; j++) {\n var evt2 = this.point.events[j];\n if (evt2.consumedBy !== undefined) continue;\n if (evt1.otherSE.point.events !== evt2.otherSE.point.events) continue;\n evt1.segment.consume(evt2.segment);\n }\n }\n }\n }, {\n key: \"getAvailableLinkedEvents\",\n value: function getAvailableLinkedEvents() {\n // point.events is always of length 2 or greater\n var events = [];\n\n for (var i = 0, iMax = this.point.events.length; i < iMax; i++) {\n var evt = this.point.events[i];\n\n if (evt !== this && !evt.segment.ringOut && evt.segment.isInResult()) {\n events.push(evt);\n }\n }\n\n return events;\n }\n /**\n * Returns a comparator function for sorting linked events that will\n * favor the event that will give us the smallest left-side angle.\n * All ring construction starts as low as possible heading to the right,\n * so by always turning left as sharp as possible we'll get polygons\n * without uncessary loops & holes.\n *\n * The comparator function has a compute cache such that it avoids\n * re-computing already-computed values.\n */\n\n }, {\n key: \"getLeftmostComparator\",\n value: function getLeftmostComparator(baseEvent) {\n var _this = this;\n\n var cache = new Map();\n\n var fillCache = function fillCache(linkedEvent) {\n var nextEvent = linkedEvent.otherSE;\n cache.set(linkedEvent, {\n sine: sineOfAngle(_this.point, baseEvent.point, nextEvent.point),\n cosine: cosineOfAngle(_this.point, baseEvent.point, nextEvent.point)\n });\n };\n\n return function (a, b) {\n if (!cache.has(a)) fillCache(a);\n if (!cache.has(b)) fillCache(b);\n\n var _cache$get = cache.get(a),\n asine = _cache$get.sine,\n acosine = _cache$get.cosine;\n\n var _cache$get2 = cache.get(b),\n bsine = _cache$get2.sine,\n bcosine = _cache$get2.cosine; // both on or above x-axis\n\n\n if (asine >= 0 && bsine >= 0) {\n if (acosine < bcosine) return 1;\n if (acosine > bcosine) return -1;\n return 0;\n } // both below x-axis\n\n\n if (asine < 0 && bsine < 0) {\n if (acosine < bcosine) return -1;\n if (acosine > bcosine) return 1;\n return 0;\n } // one above x-axis, one below\n\n\n if (bsine < asine) return -1;\n if (bsine > asine) return 1;\n return 0;\n };\n }\n }]);\n\n return SweepEvent;\n }();\n\n // segments and sweep events when all else is identical\n\n var segmentId = 0;\n\n var Segment = /*#__PURE__*/function () {\n _createClass(Segment, null, [{\n key: \"compare\",\n\n /* This compare() function is for ordering segments in the sweep\n * line tree, and does so according to the following criteria:\n *\n * Consider the vertical line that lies an infinestimal step to the\n * right of the right-more of the two left endpoints of the input\n * segments. Imagine slowly moving a point up from negative infinity\n * in the increasing y direction. Which of the two segments will that\n * point intersect first? That segment comes 'before' the other one.\n *\n * If neither segment would be intersected by such a line, (if one\n * or more of the segments are vertical) then the line to be considered\n * is directly on the right-more of the two left inputs.\n */\n value: function compare(a, b) {\n var alx = a.leftSE.point.x;\n var blx = b.leftSE.point.x;\n var arx = a.rightSE.point.x;\n var brx = b.rightSE.point.x; // check if they're even in the same vertical plane\n\n if (brx < alx) return 1;\n if (arx < blx) return -1;\n var aly = a.leftSE.point.y;\n var bly = b.leftSE.point.y;\n var ary = a.rightSE.point.y;\n var bry = b.rightSE.point.y; // is left endpoint of segment B the right-more?\n\n if (alx < blx) {\n // are the two segments in the same horizontal plane?\n if (bly < aly && bly < ary) return 1;\n if (bly > aly && bly > ary) return -1; // is the B left endpoint colinear to segment A?\n\n var aCmpBLeft = a.comparePoint(b.leftSE.point);\n if (aCmpBLeft < 0) return 1;\n if (aCmpBLeft > 0) return -1; // is the A right endpoint colinear to segment B ?\n\n var bCmpARight = b.comparePoint(a.rightSE.point);\n if (bCmpARight !== 0) return bCmpARight; // colinear segments, consider the one with left-more\n // left endpoint to be first (arbitrary?)\n\n return -1;\n } // is left endpoint of segment A the right-more?\n\n\n if (alx > blx) {\n if (aly < bly && aly < bry) return -1;\n if (aly > bly && aly > bry) return 1; // is the A left endpoint colinear to segment B?\n\n var bCmpALeft = b.comparePoint(a.leftSE.point);\n if (bCmpALeft !== 0) return bCmpALeft; // is the B right endpoint colinear to segment A?\n\n var aCmpBRight = a.comparePoint(b.rightSE.point);\n if (aCmpBRight < 0) return 1;\n if (aCmpBRight > 0) return -1; // colinear segments, consider the one with left-more\n // left endpoint to be first (arbitrary?)\n\n return 1;\n } // if we get here, the two left endpoints are in the same\n // vertical plane, ie alx === blx\n // consider the lower left-endpoint to come first\n\n\n if (aly < bly) return -1;\n if (aly > bly) return 1; // left endpoints are identical\n // check for colinearity by using the left-more right endpoint\n // is the A right endpoint more left-more?\n\n if (arx < brx) {\n var _bCmpARight = b.comparePoint(a.rightSE.point);\n\n if (_bCmpARight !== 0) return _bCmpARight;\n } // is the B right endpoint more left-more?\n\n\n if (arx > brx) {\n var _aCmpBRight = a.comparePoint(b.rightSE.point);\n\n if (_aCmpBRight < 0) return 1;\n if (_aCmpBRight > 0) return -1;\n }\n\n if (arx !== brx) {\n // are these two [almost] vertical segments with opposite orientation?\n // if so, the one with the lower right endpoint comes first\n var ay = ary - aly;\n var ax = arx - alx;\n var by = bry - bly;\n var bx = brx - blx;\n if (ay > ax && by < bx) return 1;\n if (ay < ax && by > bx) return -1;\n } // we have colinear segments with matching orientation\n // consider the one with more left-more right endpoint to be first\n\n\n if (arx > brx) return 1;\n if (arx < brx) return -1; // if we get here, two two right endpoints are in the same\n // vertical plane, ie arx === brx\n // consider the lower right-endpoint to come first\n\n if (ary < bry) return -1;\n if (ary > bry) return 1; // right endpoints identical as well, so the segments are idential\n // fall back on creation order as consistent tie-breaker\n\n if (a.id < b.id) return -1;\n if (a.id > b.id) return 1; // identical segment, ie a === b\n\n return 0;\n }\n /* Warning: a reference to ringWindings input will be stored,\n * and possibly will be later modified */\n\n }]);\n\n function Segment(leftSE, rightSE, rings, windings) {\n _classCallCheck(this, Segment);\n\n this.id = ++segmentId;\n this.leftSE = leftSE;\n leftSE.segment = this;\n leftSE.otherSE = rightSE;\n this.rightSE = rightSE;\n rightSE.segment = this;\n rightSE.otherSE = leftSE;\n this.rings = rings;\n this.windings = windings; // left unset for performance, set later in algorithm\n // this.ringOut, this.consumedBy, this.prev\n }\n\n _createClass(Segment, [{\n key: \"replaceRightSE\",\n\n /* When a segment is split, the rightSE is replaced with a new sweep event */\n value: function replaceRightSE(newRightSE) {\n this.rightSE = newRightSE;\n this.rightSE.segment = this;\n this.rightSE.otherSE = this.leftSE;\n this.leftSE.otherSE = this.rightSE;\n }\n }, {\n key: \"bbox\",\n value: function bbox() {\n var y1 = this.leftSE.point.y;\n var y2 = this.rightSE.point.y;\n return {\n ll: {\n x: this.leftSE.point.x,\n y: y1 < y2 ? y1 : y2\n },\n ur: {\n x: this.rightSE.point.x,\n y: y1 > y2 ? y1 : y2\n }\n };\n }\n /* A vector from the left point to the right */\n\n }, {\n key: \"vector\",\n value: function vector() {\n return {\n x: this.rightSE.point.x - this.leftSE.point.x,\n y: this.rightSE.point.y - this.leftSE.point.y\n };\n }\n }, {\n key: \"isAnEndpoint\",\n value: function isAnEndpoint(pt) {\n return pt.x === this.leftSE.point.x && pt.y === this.leftSE.point.y || pt.x === this.rightSE.point.x && pt.y === this.rightSE.point.y;\n }\n /* Compare this segment with a point.\n *\n * A point P is considered to be colinear to a segment if there\n * exists a distance D such that if we travel along the segment\n * from one * endpoint towards the other a distance D, we find\n * ourselves at point P.\n *\n * Return value indicates:\n *\n * 1: point lies above the segment (to the left of vertical)\n * 0: point is colinear to segment\n * -1: point lies below the segment (to the right of vertical)\n */\n\n }, {\n key: \"comparePoint\",\n value: function comparePoint(point) {\n if (this.isAnEndpoint(point)) return 0;\n var lPt = this.leftSE.point;\n var rPt = this.rightSE.point;\n var v = this.vector(); // Exactly vertical segments.\n\n if (lPt.x === rPt.x) {\n if (point.x === lPt.x) return 0;\n return point.x < lPt.x ? 1 : -1;\n } // Nearly vertical segments with an intersection.\n // Check to see where a point on the line with matching Y coordinate is.\n\n\n var yDist = (point.y - lPt.y) / v.y;\n var xFromYDist = lPt.x + yDist * v.x;\n if (point.x === xFromYDist) return 0; // General case.\n // Check to see where a point on the line with matching X coordinate is.\n\n var xDist = (point.x - lPt.x) / v.x;\n var yFromXDist = lPt.y + xDist * v.y;\n if (point.y === yFromXDist) return 0;\n return point.y < yFromXDist ? -1 : 1;\n }\n /**\n * Given another segment, returns the first non-trivial intersection\n * between the two segments (in terms of sweep line ordering), if it exists.\n *\n * A 'non-trivial' intersection is one that will cause one or both of the\n * segments to be split(). As such, 'trivial' vs. 'non-trivial' intersection:\n *\n * * endpoint of segA with endpoint of segB --> trivial\n * * endpoint of segA with point along segB --> non-trivial\n * * endpoint of segB with point along segA --> non-trivial\n * * point along segA with point along segB --> non-trivial\n *\n * If no non-trivial intersection exists, return null\n * Else, return null.\n */\n\n }, {\n key: \"getIntersection\",\n value: function getIntersection(other) {\n // If bboxes don't overlap, there can't be any intersections\n var tBbox = this.bbox();\n var oBbox = other.bbox();\n var bboxOverlap = getBboxOverlap(tBbox, oBbox);\n if (bboxOverlap === null) return null; // We first check to see if the endpoints can be considered intersections.\n // This will 'snap' intersections to endpoints if possible, and will\n // handle cases of colinearity.\n\n var tlp = this.leftSE.point;\n var trp = this.rightSE.point;\n var olp = other.leftSE.point;\n var orp = other.rightSE.point; // does each endpoint touch the other segment?\n // note that we restrict the 'touching' definition to only allow segments\n // to touch endpoints that lie forward from where we are in the sweep line pass\n\n var touchesOtherLSE = isInBbox(tBbox, olp) && this.comparePoint(olp) === 0;\n var touchesThisLSE = isInBbox(oBbox, tlp) && other.comparePoint(tlp) === 0;\n var touchesOtherRSE = isInBbox(tBbox, orp) && this.comparePoint(orp) === 0;\n var touchesThisRSE = isInBbox(oBbox, trp) && other.comparePoint(trp) === 0; // do left endpoints match?\n\n if (touchesThisLSE && touchesOtherLSE) {\n // these two cases are for colinear segments with matching left\n // endpoints, and one segment being longer than the other\n if (touchesThisRSE && !touchesOtherRSE) return trp;\n if (!touchesThisRSE && touchesOtherRSE) return orp; // either the two segments match exactly (two trival intersections)\n // or just on their left endpoint (one trivial intersection\n\n return null;\n } // does this left endpoint matches (other doesn't)\n\n\n if (touchesThisLSE) {\n // check for segments that just intersect on opposing endpoints\n if (touchesOtherRSE) {\n if (tlp.x === orp.x && tlp.y === orp.y) return null;\n } // t-intersection on left endpoint\n\n\n return tlp;\n } // does other left endpoint matches (this doesn't)\n\n\n if (touchesOtherLSE) {\n // check for segments that just intersect on opposing endpoints\n if (touchesThisRSE) {\n if (trp.x === olp.x && trp.y === olp.y) return null;\n } // t-intersection on left endpoint\n\n\n return olp;\n } // trivial intersection on right endpoints\n\n\n if (touchesThisRSE && touchesOtherRSE) return null; // t-intersections on just one right endpoint\n\n if (touchesThisRSE) return trp;\n if (touchesOtherRSE) return orp; // None of our endpoints intersect. Look for a general intersection between\n // infinite lines laid over the segments\n\n var pt = intersection(tlp, this.vector(), olp, other.vector()); // are the segments parrallel? Note that if they were colinear with overlap,\n // they would have an endpoint intersection and that case was already handled above\n\n if (pt === null) return null; // is the intersection found between the lines not on the segments?\n\n if (!isInBbox(bboxOverlap, pt)) return null; // round the the computed point if needed\n\n return rounder.round(pt.x, pt.y);\n }\n /**\n * Split the given segment into multiple segments on the given points.\n * * Each existing segment will retain its leftSE and a new rightSE will be\n * generated for it.\n * * A new segment will be generated which will adopt the original segment's\n * rightSE, and a new leftSE will be generated for it.\n * * If there are more than two points given to split on, new segments\n * in the middle will be generated with new leftSE and rightSE's.\n * * An array of the newly generated SweepEvents will be returned.\n *\n * Warning: input array of points is modified\n */\n\n }, {\n key: \"split\",\n value: function split(point) {\n var newEvents = [];\n var alreadyLinked = point.events !== undefined;\n var newLeftSE = new SweepEvent(point, true);\n var newRightSE = new SweepEvent(point, false);\n var oldRightSE = this.rightSE;\n this.replaceRightSE(newRightSE);\n newEvents.push(newRightSE);\n newEvents.push(newLeftSE);\n var newSeg = new Segment(newLeftSE, oldRightSE, this.rings.slice(), this.windings.slice()); // when splitting a nearly vertical downward-facing segment,\n // sometimes one of the resulting new segments is vertical, in which\n // case its left and right events may need to be swapped\n\n if (SweepEvent.comparePoints(newSeg.leftSE.point, newSeg.rightSE.point) > 0) {\n newSeg.swapEvents();\n }\n\n if (SweepEvent.comparePoints(this.leftSE.point, this.rightSE.point) > 0) {\n this.swapEvents();\n } // in the point we just used to create new sweep events with was already\n // linked to other events, we need to check if either of the affected\n // segments should be consumed\n\n\n if (alreadyLinked) {\n newLeftSE.checkForConsuming();\n newRightSE.checkForConsuming();\n }\n\n return newEvents;\n }\n /* Swap which event is left and right */\n\n }, {\n key: \"swapEvents\",\n value: function swapEvents() {\n var tmpEvt = this.rightSE;\n this.rightSE = this.leftSE;\n this.leftSE = tmpEvt;\n this.leftSE.isLeft = true;\n this.rightSE.isLeft = false;\n\n for (var i = 0, iMax = this.windings.length; i < iMax; i++) {\n this.windings[i] *= -1;\n }\n }\n /* Consume another segment. We take their rings under our wing\n * and mark them as consumed. Use for perfectly overlapping segments */\n\n }, {\n key: \"consume\",\n value: function consume(other) {\n var consumer = this;\n var consumee = other;\n\n while (consumer.consumedBy) {\n consumer = consumer.consumedBy;\n }\n\n while (consumee.consumedBy) {\n consumee = consumee.consumedBy;\n }\n\n var cmp = Segment.compare(consumer, consumee);\n if (cmp === 0) return; // already consumed\n // the winner of the consumption is the earlier segment\n // according to sweep line ordering\n\n if (cmp > 0) {\n var tmp = consumer;\n consumer = consumee;\n consumee = tmp;\n } // make sure a segment doesn't consume it's prev\n\n\n if (consumer.prev === consumee) {\n var _tmp = consumer;\n consumer = consumee;\n consumee = _tmp;\n }\n\n for (var i = 0, iMax = consumee.rings.length; i < iMax; i++) {\n var ring = consumee.rings[i];\n var winding = consumee.windings[i];\n var index = consumer.rings.indexOf(ring);\n\n if (index === -1) {\n consumer.rings.push(ring);\n consumer.windings.push(winding);\n } else consumer.windings[index] += winding;\n }\n\n consumee.rings = null;\n consumee.windings = null;\n consumee.consumedBy = consumer; // mark sweep events consumed as to maintain ordering in sweep event queue\n\n consumee.leftSE.consumedBy = consumer.leftSE;\n consumee.rightSE.consumedBy = consumer.rightSE;\n }\n /* The first segment previous segment chain that is in the result */\n\n }, {\n key: \"prevInResult\",\n value: function prevInResult() {\n if (this._prevInResult !== undefined) return this._prevInResult;\n if (!this.prev) this._prevInResult = null;else if (this.prev.isInResult()) this._prevInResult = this.prev;else this._prevInResult = this.prev.prevInResult();\n return this._prevInResult;\n }\n }, {\n key: \"beforeState\",\n value: function beforeState() {\n if (this._beforeState !== undefined) return this._beforeState;\n if (!this.prev) this._beforeState = {\n rings: [],\n windings: [],\n multiPolys: []\n };else {\n var seg = this.prev.consumedBy || this.prev;\n this._beforeState = seg.afterState();\n }\n return this._beforeState;\n }\n }, {\n key: \"afterState\",\n value: function afterState() {\n if (this._afterState !== undefined) return this._afterState;\n var beforeState = this.beforeState();\n this._afterState = {\n rings: beforeState.rings.slice(0),\n windings: beforeState.windings.slice(0),\n multiPolys: []\n };\n var ringsAfter = this._afterState.rings;\n var windingsAfter = this._afterState.windings;\n var mpsAfter = this._afterState.multiPolys; // calculate ringsAfter, windingsAfter\n\n for (var i = 0, iMax = this.rings.length; i < iMax; i++) {\n var ring = this.rings[i];\n var winding = this.windings[i];\n var index = ringsAfter.indexOf(ring);\n\n if (index === -1) {\n ringsAfter.push(ring);\n windingsAfter.push(winding);\n } else windingsAfter[index] += winding;\n } // calcualte polysAfter\n\n\n var polysAfter = [];\n var polysExclude = [];\n\n for (var _i = 0, _iMax = ringsAfter.length; _i < _iMax; _i++) {\n if (windingsAfter[_i] === 0) continue; // non-zero rule\n\n var _ring = ringsAfter[_i];\n var poly = _ring.poly;\n if (polysExclude.indexOf(poly) !== -1) continue;\n if (_ring.isExterior) polysAfter.push(poly);else {\n if (polysExclude.indexOf(poly) === -1) polysExclude.push(poly);\n\n var _index = polysAfter.indexOf(_ring.poly);\n\n if (_index !== -1) polysAfter.splice(_index, 1);\n }\n } // calculate multiPolysAfter\n\n\n for (var _i2 = 0, _iMax2 = polysAfter.length; _i2 < _iMax2; _i2++) {\n var mp = polysAfter[_i2].multiPoly;\n if (mpsAfter.indexOf(mp) === -1) mpsAfter.push(mp);\n }\n\n return this._afterState;\n }\n /* Is this segment part of the final result? */\n\n }, {\n key: \"isInResult\",\n value: function isInResult() {\n // if we've been consumed, we're not in the result\n if (this.consumedBy) return false;\n if (this._isInResult !== undefined) return this._isInResult;\n var mpsBefore = this.beforeState().multiPolys;\n var mpsAfter = this.afterState().multiPolys;\n\n switch (operation.type) {\n case 'union':\n {\n // UNION - included iff:\n // * On one side of us there is 0 poly interiors AND\n // * On the other side there is 1 or more.\n var noBefores = mpsBefore.length === 0;\n var noAfters = mpsAfter.length === 0;\n this._isInResult = noBefores !== noAfters;\n break;\n }\n\n case 'intersection':\n {\n // INTERSECTION - included iff:\n // * on one side of us all multipolys are rep. with poly interiors AND\n // * on the other side of us, not all multipolys are repsented\n // with poly interiors\n var least;\n var most;\n\n if (mpsBefore.length < mpsAfter.length) {\n least = mpsBefore.length;\n most = mpsAfter.length;\n } else {\n least = mpsAfter.length;\n most = mpsBefore.length;\n }\n\n this._isInResult = most === operation.numMultiPolys && least < most;\n break;\n }\n\n case 'xor':\n {\n // XOR - included iff:\n // * the difference between the number of multipolys represented\n // with poly interiors on our two sides is an odd number\n var diff = Math.abs(mpsBefore.length - mpsAfter.length);\n this._isInResult = diff % 2 === 1;\n break;\n }\n\n case 'difference':\n {\n // DIFFERENCE included iff:\n // * on exactly one side, we have just the subject\n var isJustSubject = function isJustSubject(mps) {\n return mps.length === 1 && mps[0].isSubject;\n };\n\n this._isInResult = isJustSubject(mpsBefore) !== isJustSubject(mpsAfter);\n break;\n }\n\n default:\n throw new Error(\"Unrecognized operation type found \".concat(operation.type));\n }\n\n return this._isInResult;\n }\n }], [{\n key: \"fromRing\",\n value: function fromRing(pt1, pt2, ring) {\n var leftPt, rightPt, winding; // ordering the two points according to sweep line ordering\n\n var cmpPts = SweepEvent.comparePoints(pt1, pt2);\n\n if (cmpPts < 0) {\n leftPt = pt1;\n rightPt = pt2;\n winding = 1;\n } else if (cmpPts > 0) {\n leftPt = pt2;\n rightPt = pt1;\n winding = -1;\n } else throw new Error(\"Tried to create degenerate segment at [\".concat(pt1.x, \", \").concat(pt1.y, \"]\"));\n\n var leftSE = new SweepEvent(leftPt, true);\n var rightSE = new SweepEvent(rightPt, false);\n return new Segment(leftSE, rightSE, [ring], [winding]);\n }\n }]);\n\n return Segment;\n }();\n\n var RingIn = /*#__PURE__*/function () {\n function RingIn(geomRing, poly, isExterior) {\n _classCallCheck(this, RingIn);\n\n if (!Array.isArray(geomRing) || geomRing.length === 0) {\n throw new Error('Input geometry is not a valid Polygon or MultiPolygon');\n }\n\n this.poly = poly;\n this.isExterior = isExterior;\n this.segments = [];\n\n if (typeof geomRing[0][0] !== 'number' || typeof geomRing[0][1] !== 'number') {\n throw new Error('Input geometry is not a valid Polygon or MultiPolygon');\n }\n\n var firstPoint = rounder.round(geomRing[0][0], geomRing[0][1]);\n this.bbox = {\n ll: {\n x: firstPoint.x,\n y: firstPoint.y\n },\n ur: {\n x: firstPoint.x,\n y: firstPoint.y\n }\n };\n var prevPoint = firstPoint;\n\n for (var i = 1, iMax = geomRing.length; i < iMax; i++) {\n if (typeof geomRing[i][0] !== 'number' || typeof geomRing[i][1] !== 'number') {\n throw new Error('Input geometry is not a valid Polygon or MultiPolygon');\n }\n\n var point = rounder.round(geomRing[i][0], geomRing[i][1]); // skip repeated points\n\n if (point.x === prevPoint.x && point.y === prevPoint.y) continue;\n this.segments.push(Segment.fromRing(prevPoint, point, this));\n if (point.x < this.bbox.ll.x) this.bbox.ll.x = point.x;\n if (point.y < this.bbox.ll.y) this.bbox.ll.y = point.y;\n if (point.x > this.bbox.ur.x) this.bbox.ur.x = point.x;\n if (point.y > this.bbox.ur.y) this.bbox.ur.y = point.y;\n prevPoint = point;\n } // add segment from last to first if last is not the same as first\n\n\n if (firstPoint.x !== prevPoint.x || firstPoint.y !== prevPoint.y) {\n this.segments.push(Segment.fromRing(prevPoint, firstPoint, this));\n }\n }\n\n _createClass(RingIn, [{\n key: \"getSweepEvents\",\n value: function getSweepEvents() {\n var sweepEvents = [];\n\n for (var i = 0, iMax = this.segments.length; i < iMax; i++) {\n var segment = this.segments[i];\n sweepEvents.push(segment.leftSE);\n sweepEvents.push(segment.rightSE);\n }\n\n return sweepEvents;\n }\n }]);\n\n return RingIn;\n }();\n var PolyIn = /*#__PURE__*/function () {\n function PolyIn(geomPoly, multiPoly) {\n _classCallCheck(this, PolyIn);\n\n if (!Array.isArray(geomPoly)) {\n throw new Error('Input geometry is not a valid Polygon or MultiPolygon');\n }\n\n this.exteriorRing = new RingIn(geomPoly[0], this, true); // copy by value\n\n this.bbox = {\n ll: {\n x: this.exteriorRing.bbox.ll.x,\n y: this.exteriorRing.bbox.ll.y\n },\n ur: {\n x: this.exteriorRing.bbox.ur.x,\n y: this.exteriorRing.bbox.ur.y\n }\n };\n this.interiorRings = [];\n\n for (var i = 1, iMax = geomPoly.length; i < iMax; i++) {\n var ring = new RingIn(geomPoly[i], this, false);\n if (ring.bbox.ll.x < this.bbox.ll.x) this.bbox.ll.x = ring.bbox.ll.x;\n if (ring.bbox.ll.y < this.bbox.ll.y) this.bbox.ll.y = ring.bbox.ll.y;\n if (ring.bbox.ur.x > this.bbox.ur.x) this.bbox.ur.x = ring.bbox.ur.x;\n if (ring.bbox.ur.y > this.bbox.ur.y) this.bbox.ur.y = ring.bbox.ur.y;\n this.interiorRings.push(ring);\n }\n\n this.multiPoly = multiPoly;\n }\n\n _createClass(PolyIn, [{\n key: \"getSweepEvents\",\n value: function getSweepEvents() {\n var sweepEvents = this.exteriorRing.getSweepEvents();\n\n for (var i = 0, iMax = this.interiorRings.length; i < iMax; i++) {\n var ringSweepEvents = this.interiorRings[i].getSweepEvents();\n\n for (var j = 0, jMax = ringSweepEvents.length; j < jMax; j++) {\n sweepEvents.push(ringSweepEvents[j]);\n }\n }\n\n return sweepEvents;\n }\n }]);\n\n return PolyIn;\n }();\n var MultiPolyIn = /*#__PURE__*/function () {\n function MultiPolyIn(geom, isSubject) {\n _classCallCheck(this, MultiPolyIn);\n\n if (!Array.isArray(geom)) {\n throw new Error('Input geometry is not a valid Polygon or MultiPolygon');\n }\n\n try {\n // if the input looks like a polygon, convert it to a multipolygon\n if (typeof geom[0][0][0] === 'number') geom = [geom];\n } catch (ex) {// The input is either malformed or has empty arrays.\n // In either case, it will be handled later on.\n }\n\n this.polys = [];\n this.bbox = {\n ll: {\n x: Number.POSITIVE_INFINITY,\n y: Number.POSITIVE_INFINITY\n },\n ur: {\n x: Number.NEGATIVE_INFINITY,\n y: Number.NEGATIVE_INFINITY\n }\n };\n\n for (var i = 0, iMax = geom.length; i < iMax; i++) {\n var poly = new PolyIn(geom[i], this);\n if (poly.bbox.ll.x < this.bbox.ll.x) this.bbox.ll.x = poly.bbox.ll.x;\n if (poly.bbox.ll.y < this.bbox.ll.y) this.bbox.ll.y = poly.bbox.ll.y;\n if (poly.bbox.ur.x > this.bbox.ur.x) this.bbox.ur.x = poly.bbox.ur.x;\n if (poly.bbox.ur.y > this.bbox.ur.y) this.bbox.ur.y = poly.bbox.ur.y;\n this.polys.push(poly);\n }\n\n this.isSubject = isSubject;\n }\n\n _createClass(MultiPolyIn, [{\n key: \"getSweepEvents\",\n value: function getSweepEvents() {\n var sweepEvents = [];\n\n for (var i = 0, iMax = this.polys.length; i < iMax; i++) {\n var polySweepEvents = this.polys[i].getSweepEvents();\n\n for (var j = 0, jMax = polySweepEvents.length; j < jMax; j++) {\n sweepEvents.push(polySweepEvents[j]);\n }\n }\n\n return sweepEvents;\n }\n }]);\n\n return MultiPolyIn;\n }();\n\n var RingOut = /*#__PURE__*/function () {\n _createClass(RingOut, null, [{\n key: \"factory\",\n\n /* Given the segments from the sweep line pass, compute & return a series\n * of closed rings from all the segments marked to be part of the result */\n value: function factory(allSegments) {\n var ringsOut = [];\n\n for (var i = 0, iMax = allSegments.length; i < iMax; i++) {\n var segment = allSegments[i];\n if (!segment.isInResult() || segment.ringOut) continue;\n var prevEvent = null;\n var event = segment.leftSE;\n var nextEvent = segment.rightSE;\n var events = [event];\n var startingPoint = event.point;\n var intersectionLEs = [];\n /* Walk the chain of linked events to form a closed ring */\n\n while (true) {\n prevEvent = event;\n event = nextEvent;\n events.push(event);\n /* Is the ring complete? */\n\n if (event.point === startingPoint) break;\n\n while (true) {\n var availableLEs = event.getAvailableLinkedEvents();\n /* Did we hit a dead end? This shouldn't happen. Indicates some earlier\n * part of the algorithm malfunctioned... please file a bug report. */\n\n if (availableLEs.length === 0) {\n var firstPt = events[0].point;\n var lastPt = events[events.length - 1].point;\n throw new Error(\"Unable to complete output ring starting at [\".concat(firstPt.x, \",\") + \" \".concat(firstPt.y, \"]. Last matching segment found ends at\") + \" [\".concat(lastPt.x, \", \").concat(lastPt.y, \"].\"));\n }\n /* Only one way to go, so cotinue on the path */\n\n\n if (availableLEs.length === 1) {\n nextEvent = availableLEs[0].otherSE;\n break;\n }\n /* We must have an intersection. Check for a completed loop */\n\n\n var indexLE = null;\n\n for (var j = 0, jMax = intersectionLEs.length; j < jMax; j++) {\n if (intersectionLEs[j].point === event.point) {\n indexLE = j;\n break;\n }\n }\n /* Found a completed loop. Cut that off and make a ring */\n\n\n if (indexLE !== null) {\n var intersectionLE = intersectionLEs.splice(indexLE)[0];\n var ringEvents = events.splice(intersectionLE.index);\n ringEvents.unshift(ringEvents[0].otherSE);\n ringsOut.push(new RingOut(ringEvents.reverse()));\n continue;\n }\n /* register the intersection */\n\n\n intersectionLEs.push({\n index: events.length,\n point: event.point\n });\n /* Choose the left-most option to continue the walk */\n\n var comparator = event.getLeftmostComparator(prevEvent);\n nextEvent = availableLEs.sort(comparator)[0].otherSE;\n break;\n }\n }\n\n ringsOut.push(new RingOut(events));\n }\n\n return ringsOut;\n }\n }]);\n\n function RingOut(events) {\n _classCallCheck(this, RingOut);\n\n this.events = events;\n\n for (var i = 0, iMax = events.length; i < iMax; i++) {\n events[i].segment.ringOut = this;\n }\n\n this.poly = null;\n }\n\n _createClass(RingOut, [{\n key: \"getGeom\",\n value: function getGeom() {\n // Remove superfluous points (ie extra points along a straight line),\n var prevPt = this.events[0].point;\n var points = [prevPt];\n\n for (var i = 1, iMax = this.events.length - 1; i < iMax; i++) {\n var _pt = this.events[i].point;\n var _nextPt = this.events[i + 1].point;\n if (compareVectorAngles(_pt, prevPt, _nextPt) === 0) continue;\n points.push(_pt);\n prevPt = _pt;\n } // ring was all (within rounding error of angle calc) colinear points\n\n\n if (points.length === 1) return null; // check if the starting point is necessary\n\n var pt = points[0];\n var nextPt = points[1];\n if (compareVectorAngles(pt, prevPt, nextPt) === 0) points.shift();\n points.push(points[0]);\n var step = this.isExteriorRing() ? 1 : -1;\n var iStart = this.isExteriorRing() ? 0 : points.length - 1;\n var iEnd = this.isExteriorRing() ? points.length : -1;\n var orderedPoints = [];\n\n for (var _i = iStart; _i != iEnd; _i += step) {\n orderedPoints.push([points[_i].x, points[_i].y]);\n }\n\n return orderedPoints;\n }\n }, {\n key: \"isExteriorRing\",\n value: function isExteriorRing() {\n if (this._isExteriorRing === undefined) {\n var enclosing = this.enclosingRing();\n this._isExteriorRing = enclosing ? !enclosing.isExteriorRing() : true;\n }\n\n return this._isExteriorRing;\n }\n }, {\n key: \"enclosingRing\",\n value: function enclosingRing() {\n if (this._enclosingRing === undefined) {\n this._enclosingRing = this._calcEnclosingRing();\n }\n\n return this._enclosingRing;\n }\n /* Returns the ring that encloses this one, if any */\n\n }, {\n key: \"_calcEnclosingRing\",\n value: function _calcEnclosingRing() {\n // start with the ealier sweep line event so that the prevSeg\n // chain doesn't lead us inside of a loop of ours\n var leftMostEvt = this.events[0];\n\n for (var i = 1, iMax = this.events.length; i < iMax; i++) {\n var evt = this.events[i];\n if (SweepEvent.compare(leftMostEvt, evt) > 0) leftMostEvt = evt;\n }\n\n var prevSeg = leftMostEvt.segment.prevInResult();\n var prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null;\n\n while (true) {\n // no segment found, thus no ring can enclose us\n if (!prevSeg) return null; // no segments below prev segment found, thus the ring of the prev\n // segment must loop back around and enclose us\n\n if (!prevPrevSeg) return prevSeg.ringOut; // if the two segments are of different rings, the ring of the prev\n // segment must either loop around us or the ring of the prev prev\n // seg, which would make us and the ring of the prev peers\n\n if (prevPrevSeg.ringOut !== prevSeg.ringOut) {\n if (prevPrevSeg.ringOut.enclosingRing() !== prevSeg.ringOut) {\n return prevSeg.ringOut;\n } else return prevSeg.ringOut.enclosingRing();\n } // two segments are from the same ring, so this was a penisula\n // of that ring. iterate downward, keep searching\n\n\n prevSeg = prevPrevSeg.prevInResult();\n prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null;\n }\n }\n }]);\n\n return RingOut;\n }();\n var PolyOut = /*#__PURE__*/function () {\n function PolyOut(exteriorRing) {\n _classCallCheck(this, PolyOut);\n\n this.exteriorRing = exteriorRing;\n exteriorRing.poly = this;\n this.interiorRings = [];\n }\n\n _createClass(PolyOut, [{\n key: \"addInterior\",\n value: function addInterior(ring) {\n this.interiorRings.push(ring);\n ring.poly = this;\n }\n }, {\n key: \"getGeom\",\n value: function getGeom() {\n var geom = [this.exteriorRing.getGeom()]; // exterior ring was all (within rounding error of angle calc) colinear points\n\n if (geom[0] === null) return null;\n\n for (var i = 0, iMax = this.interiorRings.length; i < iMax; i++) {\n var ringGeom = this.interiorRings[i].getGeom(); // interior ring was all (within rounding error of angle calc) colinear points\n\n if (ringGeom === null) continue;\n geom.push(ringGeom);\n }\n\n return geom;\n }\n }]);\n\n return PolyOut;\n }();\n var MultiPolyOut = /*#__PURE__*/function () {\n function MultiPolyOut(rings) {\n _classCallCheck(this, MultiPolyOut);\n\n this.rings = rings;\n this.polys = this._composePolys(rings);\n }\n\n _createClass(MultiPolyOut, [{\n key: \"getGeom\",\n value: function getGeom() {\n var geom = [];\n\n for (var i = 0, iMax = this.polys.length; i < iMax; i++) {\n var polyGeom = this.polys[i].getGeom(); // exterior ring was all (within rounding error of angle calc) colinear points\n\n if (polyGeom === null) continue;\n geom.push(polyGeom);\n }\n\n return geom;\n }\n }, {\n key: \"_composePolys\",\n value: function _composePolys(rings) {\n var polys = [];\n\n for (var i = 0, iMax = rings.length; i < iMax; i++) {\n var ring = rings[i];\n if (ring.poly) continue;\n if (ring.isExteriorRing()) polys.push(new PolyOut(ring));else {\n var enclosingRing = ring.enclosingRing();\n if (!enclosingRing.poly) polys.push(new PolyOut(enclosingRing));\n enclosingRing.poly.addInterior(ring);\n }\n }\n\n return polys;\n }\n }]);\n\n return MultiPolyOut;\n }();\n\n /**\n * NOTE: We must be careful not to change any segments while\n * they are in the SplayTree. AFAIK, there's no way to tell\n * the tree to rebalance itself - thus before splitting\n * a segment that's in the tree, we remove it from the tree,\n * do the split, then re-insert it. (Even though splitting a\n * segment *shouldn't* change its correct position in the\n * sweep line tree, the reality is because of rounding errors,\n * it sometimes does.)\n */\n\n var SweepLine = /*#__PURE__*/function () {\n function SweepLine(queue) {\n var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Segment.compare;\n\n _classCallCheck(this, SweepLine);\n\n this.queue = queue;\n this.tree = new Tree(comparator);\n this.segments = [];\n }\n\n _createClass(SweepLine, [{\n key: \"process\",\n value: function process(event) {\n var segment = event.segment;\n var newEvents = []; // if we've already been consumed by another segment,\n // clean up our body parts and get out\n\n if (event.consumedBy) {\n if (event.isLeft) this.queue.remove(event.otherSE);else this.tree.remove(segment);\n return newEvents;\n }\n\n var node = event.isLeft ? this.tree.insert(segment) : this.tree.find(segment);\n if (!node) throw new Error(\"Unable to find segment #\".concat(segment.id, \" \") + \"[\".concat(segment.leftSE.point.x, \", \").concat(segment.leftSE.point.y, \"] -> \") + \"[\".concat(segment.rightSE.point.x, \", \").concat(segment.rightSE.point.y, \"] \") + 'in SweepLine tree. Please submit a bug report.');\n var prevNode = node;\n var nextNode = node;\n var prevSeg = undefined;\n var nextSeg = undefined; // skip consumed segments still in tree\n\n while (prevSeg === undefined) {\n prevNode = this.tree.prev(prevNode);\n if (prevNode === null) prevSeg = null;else if (prevNode.key.consumedBy === undefined) prevSeg = prevNode.key;\n } // skip consumed segments still in tree\n\n\n while (nextSeg === undefined) {\n nextNode = this.tree.next(nextNode);\n if (nextNode === null) nextSeg = null;else if (nextNode.key.consumedBy === undefined) nextSeg = nextNode.key;\n }\n\n if (event.isLeft) {\n // Check for intersections against the previous segment in the sweep line\n var prevMySplitter = null;\n\n if (prevSeg) {\n var prevInter = prevSeg.getIntersection(segment);\n\n if (prevInter !== null) {\n if (!segment.isAnEndpoint(prevInter)) prevMySplitter = prevInter;\n\n if (!prevSeg.isAnEndpoint(prevInter)) {\n var newEventsFromSplit = this._splitSafely(prevSeg, prevInter);\n\n for (var i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {\n newEvents.push(newEventsFromSplit[i]);\n }\n }\n }\n } // Check for intersections against the next segment in the sweep line\n\n\n var nextMySplitter = null;\n\n if (nextSeg) {\n var nextInter = nextSeg.getIntersection(segment);\n\n if (nextInter !== null) {\n if (!segment.isAnEndpoint(nextInter)) nextMySplitter = nextInter;\n\n if (!nextSeg.isAnEndpoint(nextInter)) {\n var _newEventsFromSplit = this._splitSafely(nextSeg, nextInter);\n\n for (var _i = 0, _iMax = _newEventsFromSplit.length; _i < _iMax; _i++) {\n newEvents.push(_newEventsFromSplit[_i]);\n }\n }\n }\n } // For simplicity, even if we find more than one intersection we only\n // spilt on the 'earliest' (sweep-line style) of the intersections.\n // The other intersection will be handled in a future process().\n\n\n if (prevMySplitter !== null || nextMySplitter !== null) {\n var mySplitter = null;\n if (prevMySplitter === null) mySplitter = nextMySplitter;else if (nextMySplitter === null) mySplitter = prevMySplitter;else {\n var cmpSplitters = SweepEvent.comparePoints(prevMySplitter, nextMySplitter);\n mySplitter = cmpSplitters <= 0 ? prevMySplitter : nextMySplitter;\n } // Rounding errors can cause changes in ordering,\n // so remove afected segments and right sweep events before splitting\n\n this.queue.remove(segment.rightSE);\n newEvents.push(segment.rightSE);\n\n var _newEventsFromSplit2 = segment.split(mySplitter);\n\n for (var _i2 = 0, _iMax2 = _newEventsFromSplit2.length; _i2 < _iMax2; _i2++) {\n newEvents.push(_newEventsFromSplit2[_i2]);\n }\n }\n\n if (newEvents.length > 0) {\n // We found some intersections, so re-do the current event to\n // make sure sweep line ordering is totally consistent for later\n // use with the segment 'prev' pointers\n this.tree.remove(segment);\n newEvents.push(event);\n } else {\n // done with left event\n this.segments.push(segment);\n segment.prev = prevSeg;\n }\n } else {\n // event.isRight\n // since we're about to be removed from the sweep line, check for\n // intersections between our previous and next segments\n if (prevSeg && nextSeg) {\n var inter = prevSeg.getIntersection(nextSeg);\n\n if (inter !== null) {\n if (!prevSeg.isAnEndpoint(inter)) {\n var _newEventsFromSplit3 = this._splitSafely(prevSeg, inter);\n\n for (var _i3 = 0, _iMax3 = _newEventsFromSplit3.length; _i3 < _iMax3; _i3++) {\n newEvents.push(_newEventsFromSplit3[_i3]);\n }\n }\n\n if (!nextSeg.isAnEndpoint(inter)) {\n var _newEventsFromSplit4 = this._splitSafely(nextSeg, inter);\n\n for (var _i4 = 0, _iMax4 = _newEventsFromSplit4.length; _i4 < _iMax4; _i4++) {\n newEvents.push(_newEventsFromSplit4[_i4]);\n }\n }\n }\n }\n\n this.tree.remove(segment);\n }\n\n return newEvents;\n }\n /* Safely split a segment that is currently in the datastructures\n * IE - a segment other than the one that is currently being processed. */\n\n }, {\n key: \"_splitSafely\",\n value: function _splitSafely(seg, pt) {\n // Rounding errors can cause changes in ordering,\n // so remove afected segments and right sweep events before splitting\n // removeNode() doesn't work, so have re-find the seg\n // https://github.com/w8r/splay-tree/pull/5\n this.tree.remove(seg);\n var rightSE = seg.rightSE;\n this.queue.remove(rightSE);\n var newEvents = seg.split(pt);\n newEvents.push(rightSE); // splitting can trigger consumption\n\n if (seg.consumedBy === undefined) this.tree.insert(seg);\n return newEvents;\n }\n }]);\n\n return SweepLine;\n }();\n\n var POLYGON_CLIPPING_MAX_QUEUE_SIZE = typeof process !== 'undefined' && process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE || 1000000;\n var POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS = typeof process !== 'undefined' && process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS || 1000000;\n var Operation = /*#__PURE__*/function () {\n function Operation() {\n _classCallCheck(this, Operation);\n }\n\n _createClass(Operation, [{\n key: \"run\",\n value: function run(type, geom, moreGeoms) {\n operation.type = type;\n rounder.reset();\n /* Convert inputs to MultiPoly objects */\n\n var multipolys = [new MultiPolyIn(geom, true)];\n\n for (var i = 0, iMax = moreGeoms.length; i < iMax; i++) {\n multipolys.push(new MultiPolyIn(moreGeoms[i], false));\n }\n\n operation.numMultiPolys = multipolys.length;\n /* BBox optimization for difference operation\n * If the bbox of a multipolygon that's part of the clipping doesn't\n * intersect the bbox of the subject at all, we can just drop that\n * multiploygon. */\n\n if (operation.type === 'difference') {\n // in place removal\n var subject = multipolys[0];\n var _i = 1;\n\n while (_i < multipolys.length) {\n if (getBboxOverlap(multipolys[_i].bbox, subject.bbox) !== null) _i++;else multipolys.splice(_i, 1);\n }\n }\n /* BBox optimization for intersection operation\n * If we can find any pair of multipolygons whose bbox does not overlap,\n * then the result will be empty. */\n\n\n if (operation.type === 'intersection') {\n // TODO: this is O(n^2) in number of polygons. By sorting the bboxes,\n // it could be optimized to O(n * ln(n))\n for (var _i2 = 0, _iMax = multipolys.length; _i2 < _iMax; _i2++) {\n var mpA = multipolys[_i2];\n\n for (var j = _i2 + 1, jMax = multipolys.length; j < jMax; j++) {\n if (getBboxOverlap(mpA.bbox, multipolys[j].bbox) === null) return [];\n }\n }\n }\n /* Put segment endpoints in a priority queue */\n\n\n var queue = new Tree(SweepEvent.compare);\n\n for (var _i3 = 0, _iMax2 = multipolys.length; _i3 < _iMax2; _i3++) {\n var sweepEvents = multipolys[_i3].getSweepEvents();\n\n for (var _j = 0, _jMax = sweepEvents.length; _j < _jMax; _j++) {\n queue.insert(sweepEvents[_j]);\n\n if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) {\n // prevents an infinite loop, an otherwise common manifestation of bugs\n throw new Error('Infinite loop when putting segment endpoints in a priority queue ' + '(queue size too big). Please file a bug report.');\n }\n }\n }\n /* Pass the sweep line over those endpoints */\n\n\n var sweepLine = new SweepLine(queue);\n var prevQueueSize = queue.size;\n var node = queue.pop();\n\n while (node) {\n var evt = node.key;\n\n if (queue.size === prevQueueSize) {\n // prevents an infinite loop, an otherwise common manifestation of bugs\n var seg = evt.segment;\n throw new Error(\"Unable to pop() \".concat(evt.isLeft ? 'left' : 'right', \" SweepEvent \") + \"[\".concat(evt.point.x, \", \").concat(evt.point.y, \"] from segment #\").concat(seg.id, \" \") + \"[\".concat(seg.leftSE.point.x, \", \").concat(seg.leftSE.point.y, \"] -> \") + \"[\".concat(seg.rightSE.point.x, \", \").concat(seg.rightSE.point.y, \"] from queue. \") + 'Please file a bug report.');\n }\n\n if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) {\n // prevents an infinite loop, an otherwise common manifestation of bugs\n throw new Error('Infinite loop when passing sweep line over endpoints ' + '(queue size too big). Please file a bug report.');\n }\n\n if (sweepLine.segments.length > POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS) {\n // prevents an infinite loop, an otherwise common manifestation of bugs\n throw new Error('Infinite loop when passing sweep line over endpoints ' + '(too many sweep line segments). Please file a bug report.');\n }\n\n var newEvents = sweepLine.process(evt);\n\n for (var _i4 = 0, _iMax3 = newEvents.length; _i4 < _iMax3; _i4++) {\n var _evt = newEvents[_i4];\n if (_evt.consumedBy === undefined) queue.insert(_evt);\n }\n\n prevQueueSize = queue.size;\n node = queue.pop();\n } // free some memory we don't need anymore\n\n\n rounder.reset();\n /* Collect and compile segments we're keeping into a multipolygon */\n\n var ringsOut = RingOut.factory(sweepLine.segments);\n var result = new MultiPolyOut(ringsOut);\n return result.getGeom();\n }\n }]);\n\n return Operation;\n }(); // singleton available by import\n\n var operation = new Operation();\n\n var union = function union(geom) {\n for (var _len = arguments.length, moreGeoms = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n moreGeoms[_key - 1] = arguments[_key];\n }\n\n return operation.run('union', geom, moreGeoms);\n };\n\n var intersection$1 = function intersection(geom) {\n for (var _len2 = arguments.length, moreGeoms = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n moreGeoms[_key2 - 1] = arguments[_key2];\n }\n\n return operation.run('intersection', geom, moreGeoms);\n };\n\n var xor = function xor(geom) {\n for (var _len3 = arguments.length, moreGeoms = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n moreGeoms[_key3 - 1] = arguments[_key3];\n }\n\n return operation.run('xor', geom, moreGeoms);\n };\n\n var difference = function difference(subjectGeom) {\n for (var _len4 = arguments.length, clippingGeoms = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {\n clippingGeoms[_key4 - 1] = arguments[_key4];\n }\n\n return operation.run('difference', subjectGeom, clippingGeoms);\n };\n\n var index = {\n union: union,\n intersection: intersection$1,\n xor: xor,\n difference: difference\n };\n\n return index;\n\n})));\n","import * as React from 'react';\n/**\n * @ignore - internal component.\n */\n\nvar Tablelvl2Context = React.createContext();\n\nif (process.env.NODE_ENV !== 'production') {\n Tablelvl2Context.displayName = 'Tablelvl2Context';\n}\n\nexport default Tablelvl2Context;","/**\n * @module helpers\n */\n/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n *\n * @memberof helpers\n * @type {number}\n */\nexport var earthRadius = 6371008.8;\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var factors = {\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n degrees: earthRadius / 111325,\n feet: earthRadius * 3.28084,\n inches: earthRadius * 39.37,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n meters: earthRadius,\n metres: earthRadius,\n miles: earthRadius / 1609.344,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n nauticalmiles: earthRadius / 1852,\n radians: 1,\n yards: earthRadius * 1.0936,\n};\n/**\n * Units of measurement factors based on 1 meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var unitsFactors = {\n centimeters: 100,\n centimetres: 100,\n degrees: 1 / 111325,\n feet: 3.28084,\n inches: 39.37,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n meters: 1,\n metres: 1,\n miles: 1 / 1609.344,\n millimeters: 1000,\n millimetres: 1000,\n nauticalmiles: 1 / 1852,\n radians: 1 / earthRadius,\n yards: 1.0936133,\n};\n/**\n * Area of measurement factors based on 1 square meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var areaFactors = {\n acres: 0.000247105,\n centimeters: 10000,\n centimetres: 10000,\n feet: 10.763910417,\n hectares: 0.0001,\n inches: 1550.003100006,\n kilometers: 0.000001,\n kilometres: 0.000001,\n meters: 1,\n metres: 1,\n miles: 3.86e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nexport function feature(geom, properties, options) {\n if (options === void 0) { options = {}; }\n var feat = { type: \"Feature\" };\n if (options.id === 0 || options.id) {\n feat.id = options.id;\n }\n if (options.bbox) {\n feat.bbox = options.bbox;\n }\n feat.properties = properties || {};\n feat.geometry = geom;\n return feat;\n}\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = \"Point\";\n * var coordinates = [110, 50];\n * var geometry = turf.geometry(type, coordinates);\n * // => geometry\n */\nexport function geometry(type, coordinates, _options) {\n if (_options === void 0) { _options = {}; }\n switch (type) {\n case \"Point\":\n return point(coordinates).geometry;\n case \"LineString\":\n return lineString(coordinates).geometry;\n case \"Polygon\":\n return polygon(coordinates).geometry;\n case \"MultiPoint\":\n return multiPoint(coordinates).geometry;\n case \"MultiLineString\":\n return multiLineString(coordinates).geometry;\n case \"MultiPolygon\":\n return multiPolygon(coordinates).geometry;\n default:\n throw new Error(type + \" is invalid\");\n }\n}\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nexport function point(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (!coordinates) {\n throw new Error(\"coordinates is required\");\n }\n if (!Array.isArray(coordinates)) {\n throw new Error(\"coordinates must be an Array\");\n }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be at least 2 numbers long\");\n }\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {\n throw new Error(\"coordinates must contain numbers\");\n }\n var geom = {\n type: \"Point\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nexport function points(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nexport function polygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {\n var ring = coordinates_1[_i];\n if (ring.length < 4) {\n throw new Error(\"Each LinearRing of a Polygon must have 4 or more Positions.\");\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n }\n }\n var geom = {\n type: \"Polygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nexport function polygons(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nexport function lineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n var geom = {\n type: \"LineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nexport function lineStrings(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nexport function featureCollection(features, options) {\n if (options === void 0) { options = {}; }\n var fc = { type: \"FeatureCollection\" };\n if (options.id) {\n fc.id = options.id;\n }\n if (options.bbox) {\n fc.bbox = options.bbox;\n }\n fc.features = features;\n return fc;\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nexport function multiLineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiLineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nexport function multiPoint(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPoint\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nexport function multiPolygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPolygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = turf.geometry(\"Point\", [100, 0]);\n * var line = turf.geometry(\"LineString\", [[101, 0], [102, 1]]);\n * var collection = turf.geometryCollection([pt, line]);\n *\n * // => collection\n */\nexport function geometryCollection(geometries, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"GeometryCollection\",\n geometries: geometries,\n };\n return feature(geom, properties, options);\n}\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nexport function round(num, precision) {\n if (precision === void 0) { precision = 0; }\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nexport function radiansToLength(radians, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return radians * factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nexport function lengthToRadians(distance, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return distance / factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nexport function lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nexport function bearingToAzimuth(bearing) {\n var angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nexport function radiansToDegrees(radians) {\n var degrees = radians % (2 * Math.PI);\n return (degrees * 180) / Math.PI;\n}\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nexport function degreesToRadians(degrees) {\n var radians = degrees % 360;\n return (radians * Math.PI) / 180;\n}\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] of the length\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted length\n */\nexport function convertLength(length, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"kilometers\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(length >= 0)) {\n throw new Error(\"length must be a positive number\");\n }\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);\n}\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches, hectares\n * @param {number} area to be converted\n * @param {Units} [originalUnit=\"meters\"] of the distance\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted area\n */\nexport function convertArea(area, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"meters\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n var startFactor = areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n var finalFactor = areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n return (area / startFactor) * finalFactor;\n}\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nexport function isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nexport function isObject(input) {\n return !!input && input.constructor === Object;\n}\n/**\n * Validate BBox\n *\n * @private\n * @param {Array} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nexport function validateBBox(bbox) {\n if (!bbox) {\n throw new Error(\"bbox is required\");\n }\n if (!Array.isArray(bbox)) {\n throw new Error(\"bbox must be an Array\");\n }\n if (bbox.length !== 4 && bbox.length !== 6) {\n throw new Error(\"bbox must be an Array of 4 or 6 numbers\");\n }\n bbox.forEach(function (num) {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nexport function validateId(id) {\n if (!id) {\n throw new Error(\"id is required\");\n }\n if ([\"string\", \"number\"].indexOf(typeof id) === -1) {\n throw new Error(\"id must be a number or a string\");\n }\n}\n","import { isNumber, } from \"@turf/helpers\";\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array|Geometry|Feature} coord GeoJSON Point or an Array of numbers\n * @returns {Array} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nexport function getCoord(coord) {\n if (!coord) {\n throw new Error(\"coord is required\");\n }\n if (!Array.isArray(coord)) {\n if (coord.type === \"Feature\" &&\n coord.geometry !== null &&\n coord.geometry.type === \"Point\") {\n return coord.geometry.coordinates;\n }\n if (coord.type === \"Point\") {\n return coord.coordinates;\n }\n }\n if (Array.isArray(coord) &&\n coord.length >= 2 &&\n !Array.isArray(coord[0]) &&\n !Array.isArray(coord[1])) {\n return coord;\n }\n throw new Error(\"coord must be GeoJSON Point or an Array of numbers\");\n}\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nexport function getCoords(coords) {\n if (Array.isArray(coords)) {\n return coords;\n }\n // Feature\n if (coords.type === \"Feature\") {\n if (coords.geometry !== null) {\n return coords.geometry.coordinates;\n }\n }\n else {\n // Geometry\n if (coords.coordinates) {\n return coords.coordinates;\n }\n }\n throw new Error(\"coords must be GeoJSON Feature, Geometry Object or an Array\");\n}\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nexport function containsNumber(coordinates) {\n if (coordinates.length > 1 &&\n isNumber(coordinates[0]) &&\n isNumber(coordinates[1])) {\n return true;\n }\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error(\"coordinates must only contain numbers\");\n}\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nexport function geojsonType(value, type, name) {\n if (!type || !name) {\n throw new Error(\"type and name required\");\n }\n if (!value || value.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n value.type);\n }\n}\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nexport function featureOf(feature, type, name) {\n if (!feature) {\n throw new Error(\"No feature passed\");\n }\n if (!name) {\n throw new Error(\".featureOf() requires a name\");\n }\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type);\n }\n}\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nexport function collectionOf(featureCollection, type, name) {\n if (!featureCollection) {\n throw new Error(\"No featureCollection passed\");\n }\n if (!name) {\n throw new Error(\".collectionOf() requires a name\");\n }\n if (!featureCollection || featureCollection.type !== \"FeatureCollection\") {\n throw new Error(\"Invalid input to \" + name + \", FeatureCollection required\");\n }\n for (var _i = 0, _a = featureCollection.features; _i < _a.length; _i++) {\n var feature = _a[_i];\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type);\n }\n }\n}\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nexport function getGeom(geojson) {\n if (geojson.type === \"Feature\") {\n return geojson.geometry;\n }\n return geojson;\n}\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message (unused)\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nexport function getType(geojson, _name) {\n if (geojson.type === \"FeatureCollection\") {\n return \"FeatureCollection\";\n }\n if (geojson.type === \"GeometryCollection\") {\n return \"GeometryCollection\";\n }\n if (geojson.type === \"Feature\" && geojson.geometry !== null) {\n return geojson.geometry.type;\n }\n return geojson.type;\n}\n","// https://en.wikipedia.org/wiki/Rhumb_line\nimport { convertLength, earthRadius } from \"@turf/helpers\";\nimport { getCoord } from \"@turf/invariant\";\n/**\n * Calculates the distance along a rhumb line between two {@link Point|points} in degrees, radians,\n * miles, or kilometers.\n *\n * @name rhumbDistance\n * @param {Coord} from origin point\n * @param {Coord} to destination point\n * @param {Object} [options] Optional parameters\n * @param {string} [options.units=\"kilometers\"] can be degrees, radians, miles, or kilometers\n * @returns {number} distance between the two points\n * @example\n * var from = turf.point([-75.343, 39.984]);\n * var to = turf.point([-75.534, 39.123]);\n * var options = {units: 'miles'};\n *\n * var distance = turf.rhumbDistance(from, to, options);\n *\n * //addToMap\n * var addToMap = [from, to];\n * from.properties.distance = distance;\n * to.properties.distance = distance;\n */\nfunction rhumbDistance(from, to, options) {\n if (options === void 0) { options = {}; }\n var origin = getCoord(from);\n var destination = getCoord(to);\n // compensate the crossing of the 180th meridian (https://macwright.org/2016/09/26/the-180th-meridian.html)\n // solution from https://github.com/mapbox/mapbox-gl-js/issues/3250#issuecomment-294887678\n destination[0] +=\n destination[0] - origin[0] > 180\n ? -360\n : origin[0] - destination[0] > 180\n ? 360\n : 0;\n var distanceInMeters = calculateRhumbDistance(origin, destination);\n var distance = convertLength(distanceInMeters, \"meters\", options.units);\n return distance;\n}\n/**\n * Returns the distance travelling from ‘this’ point to destination point along a rhumb line.\n * Adapted from Geodesy: https://github.com/chrisveness/geodesy/blob/master/latlon-spherical.js\n *\n * @private\n * @param {Array} origin point.\n * @param {Array} destination point.\n * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres).\n * @returns {number} Distance in km between this point and destination point (same units as radius).\n *\n * @example\n * var p1 = new LatLon(51.127, 1.338);\n * var p2 = new LatLon(50.964, 1.853);\n * var d = p1.distanceTo(p2); // 40.31 km\n */\nfunction calculateRhumbDistance(origin, destination, radius) {\n // φ => phi\n // λ => lambda\n // ψ => psi\n // Δ => Delta\n // δ => delta\n // θ => theta\n radius = radius === undefined ? earthRadius : Number(radius);\n // see www.edwilliams.org/avform.htm#Rhumb\n var R = radius;\n var phi1 = (origin[1] * Math.PI) / 180;\n var phi2 = (destination[1] * Math.PI) / 180;\n var DeltaPhi = phi2 - phi1;\n var DeltaLambda = (Math.abs(destination[0] - origin[0]) * Math.PI) / 180;\n // if dLon over 180° take shorter rhumb line across the anti-meridian:\n if (DeltaLambda > Math.PI) {\n DeltaLambda -= 2 * Math.PI;\n }\n // on Mercator projection, longitude distances shrink by latitude; q is the 'stretch factor'\n // q becomes ill-conditioned along E-W line (0/0); use empirical tolerance to avoid it\n var DeltaPsi = Math.log(Math.tan(phi2 / 2 + Math.PI / 4) / Math.tan(phi1 / 2 + Math.PI / 4));\n var q = Math.abs(DeltaPsi) > 10e-12 ? DeltaPhi / DeltaPsi : Math.cos(phi1);\n // distance is pythagoras on 'stretched' Mercator projection\n var delta = Math.sqrt(DeltaPhi * DeltaPhi + q * q * DeltaLambda * DeltaLambda); // angular distance in radians\n var dist = delta * R;\n return dist;\n}\nexport default rhumbDistance;\n","import * as glMatrix from \"./common.js\";\n/**\r\n * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.\r\n * @module mat4\r\n */\n\n/**\r\n * Creates a new identity mat4\r\n *\r\n * @returns {mat4} a new 4x4 matrix\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(16);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n/**\r\n * Creates a new mat4 initialized with values from an existing matrix\r\n *\r\n * @param {ReadonlyMat4} a matrix to clone\r\n * @returns {mat4} a new 4x4 matrix\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\r\n * Copy the values from one mat4 to another\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the source matrix\r\n * @returns {mat4} out\r\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\r\n * Create a new mat4 with the given values\r\n *\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\r\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\r\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\r\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\r\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\r\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\r\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\r\n * @returns {mat4} A new mat4\r\n */\n\nexport function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\r\n * Set the components of a mat4 to the given values\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\r\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\r\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\r\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\r\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\r\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\r\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\r\n * @returns {mat4} out\r\n */\n\nexport function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\r\n * Set a mat4 to the identity matrix\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @returns {mat4} out\r\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\r\n * Transpose the values of a mat4\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the source matrix\r\n * @returns {mat4} out\r\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a12 = a[6],\n a13 = a[7];\n var a23 = a[11];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\r\n * Inverts a mat4\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the source matrix\r\n * @returns {mat4} out\r\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n return out;\n}\n/**\r\n * Calculates the adjugate of a mat4\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the source matrix\r\n * @returns {mat4} out\r\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);\n out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));\n out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);\n out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));\n out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));\n out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);\n out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));\n out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);\n out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);\n out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));\n out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);\n out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));\n out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));\n out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);\n out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));\n out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);\n return out;\n}\n/**\r\n * Calculates the determinant of a mat4\r\n *\r\n * @param {ReadonlyMat4} a the source matrix\r\n * @returns {Number} determinant of a\r\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n}\n/**\r\n * Multiplies two mat4s\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the first operand\r\n * @param {ReadonlyMat4} b the second operand\r\n * @returns {mat4} out\r\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15]; // Cache only the current line of the second matrix\n\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n/**\r\n * Translate a mat4 by the given vector\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the matrix to translate\r\n * @param {ReadonlyVec3} v vector to translate by\r\n * @returns {mat4} out\r\n */\n\nexport function translate(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n\n return out;\n}\n/**\r\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the matrix to scale\r\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\r\n * @returns {mat4} out\r\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\r\n * Rotates a mat4 by the given angle around the given axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @param {ReadonlyVec3} axis the axis to rotate around\r\n * @returns {mat4} out\r\n */\n\nexport function rotate(out, a, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n var b00, b01, b02;\n var b10, b11, b12;\n var b20, b21, b22;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11]; // Construct the elements of the rotation matrix\n\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c; // Perform rotation-specific matrix multiplication\n\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\r\n * Rotates a matrix by the given angle around the X axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\n */\n\nexport function rotateX(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n/**\r\n * Rotates a matrix by the given angle around the Y axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\n */\n\nexport function rotateY(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n/**\r\n * Rotates a matrix by the given angle around the Z axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\n */\n\nexport function rotateZ(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n/**\r\n * Creates a matrix from a vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, dest, vec);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {ReadonlyVec3} v Translation vector\r\n * @returns {mat4} out\r\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a vector scaling\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.scale(dest, dest, vec);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {ReadonlyVec3} v Scaling vector\r\n * @returns {mat4} out\r\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a given angle around a given axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotate(dest, dest, rad, axis);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @param {ReadonlyVec3} axis the axis to rotate around\r\n * @returns {mat4} out\r\n */\n\nexport function fromRotation(out, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c; // Perform rotation-specific matrix multiplication\n\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from the given angle around the X axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotateX(dest, dest, rad);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\n */\n\nexport function fromXRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from the given angle around the Y axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotateY(dest, dest, rad);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\n */\n\nexport function fromYRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from the given angle around the Z axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotateZ(dest, dest, rad);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\n */\n\nexport function fromZRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a quaternion rotation and vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, vec);\r\n * let quatMat = mat4.create();\r\n * quat4.toMat4(quat, quatMat);\r\n * mat4.multiply(dest, quatMat);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat4} q Rotation quaternion\r\n * @param {ReadonlyVec3} v Translation vector\r\n * @returns {mat4} out\r\n */\n\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\r\n * Creates a new mat4 from a dual quat.\r\n *\r\n * @param {mat4} out Matrix\r\n * @param {ReadonlyQuat2} a Dual Quaternion\r\n * @returns {mat4} mat4 receiving operation result\r\n */\n\nexport function fromQuat2(out, a) {\n var translation = new glMatrix.ARRAY_TYPE(3);\n var bx = -a[0],\n by = -a[1],\n bz = -a[2],\n bw = a[3],\n ax = a[4],\n ay = a[5],\n az = a[6],\n aw = a[7];\n var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense\n\n if (magnitude > 0) {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n\n fromRotationTranslation(out, a, translation);\n return out;\n}\n/**\r\n * Returns the translation vector component of a transformation\r\n * matrix. If a matrix is built with fromRotationTranslation,\r\n * the returned vector will be the same as the translation vector\r\n * originally supplied.\r\n * @param {vec3} out Vector to receive translation component\r\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\r\n * @return {vec3} out\r\n */\n\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n return out;\n}\n/**\r\n * Returns the scaling factor component of a transformation\r\n * matrix. If a matrix is built with fromRotationTranslationScale\r\n * with a normalized Quaternion paramter, the returned vector will be\r\n * the same as the scaling vector\r\n * originally supplied.\r\n * @param {vec3} out Vector to receive scaling factor component\r\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\r\n * @return {vec3} out\r\n */\n\nexport function getScaling(out, mat) {\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out[0] = Math.hypot(m11, m12, m13);\n out[1] = Math.hypot(m21, m22, m23);\n out[2] = Math.hypot(m31, m32, m33);\n return out;\n}\n/**\r\n * Returns a quaternion representing the rotational component\r\n * of a transformation matrix. If a matrix is built with\r\n * fromRotationTranslation, the returned quaternion will be the\r\n * same as the quaternion originally supplied.\r\n * @param {quat} out Quaternion to receive the rotation component\r\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\r\n * @return {quat} out\r\n */\n\nexport function getRotation(out, mat) {\n var scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n var is1 = 1 / scaling[0];\n var is2 = 1 / scaling[1];\n var is3 = 1 / scaling[2];\n var sm11 = mat[0] * is1;\n var sm12 = mat[1] * is2;\n var sm13 = mat[2] * is3;\n var sm21 = mat[4] * is1;\n var sm22 = mat[5] * is2;\n var sm23 = mat[6] * is3;\n var sm31 = mat[8] * is1;\n var sm32 = mat[9] * is2;\n var sm33 = mat[10] * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n\n return out;\n}\n/**\r\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, vec);\r\n * let quatMat = mat4.create();\r\n * quat4.toMat4(quat, quatMat);\r\n * mat4.multiply(dest, quatMat);\r\n * mat4.scale(dest, scale)\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat4} q Rotation quaternion\r\n * @param {ReadonlyVec3} v Translation vector\r\n * @param {ReadonlyVec3} s Scaling vector\r\n * @returns {mat4} out\r\n */\n\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, vec);\r\n * mat4.translate(dest, origin);\r\n * let quatMat = mat4.create();\r\n * quat4.toMat4(quat, quatMat);\r\n * mat4.multiply(dest, quatMat);\r\n * mat4.scale(dest, scale)\r\n * mat4.translate(dest, negativeOrigin);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat4} q Rotation quaternion\r\n * @param {ReadonlyVec3} v Translation vector\r\n * @param {ReadonlyVec3} s Scaling vector\r\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\r\n * @returns {mat4} out\r\n */\n\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n var ox = o[0];\n var oy = o[1];\n var oz = o[2];\n var out0 = (1 - (yy + zz)) * sx;\n var out1 = (xy + wz) * sx;\n var out2 = (xz - wy) * sx;\n var out4 = (xy - wz) * sy;\n var out5 = (1 - (xx + zz)) * sy;\n var out6 = (yz + wx) * sy;\n var out8 = (xz + wy) * sz;\n var out9 = (yz - wx) * sz;\n var out10 = (1 - (xx + yy)) * sz;\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n return out;\n}\n/**\r\n * Calculates a 4x4 matrix from the given quaternion\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {ReadonlyQuat} q Quaternion to create matrix from\r\n *\r\n * @returns {mat4} out\r\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\r\n * Generates a frustum matrix with the given bounds\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {Number} left Left bound of the frustum\r\n * @param {Number} right Right bound of the frustum\r\n * @param {Number} bottom Bottom bound of the frustum\r\n * @param {Number} top Top bound of the frustum\r\n * @param {Number} near Near bound of the frustum\r\n * @param {Number} far Far bound of the frustum\r\n * @returns {mat4} out\r\n */\n\nexport function frustum(out, left, right, bottom, top, near, far) {\n var rl = 1 / (right - left);\n var tb = 1 / (top - bottom);\n var nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n/**\r\n * Generates a perspective projection matrix with the given bounds.\r\n * Passing null/undefined/no value for far will generate infinite projection matrix.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {number} fovy Vertical field of view in radians\r\n * @param {number} aspect Aspect ratio. typically viewport width/height\r\n * @param {number} near Near bound of the frustum\r\n * @param {number} far Far bound of the frustum, can be null or Infinity\r\n * @returns {mat4} out\r\n */\n\nexport function perspective(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n\n return out;\n}\n/**\r\n * Generates a perspective projection matrix with the given field of view.\r\n * This is primarily useful for generating projection matrices to be used\r\n * with the still experiemental WebVR API.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\r\n * @param {number} near Near bound of the frustum\r\n * @param {number} far Far bound of the frustum\r\n * @returns {mat4} out\r\n */\n\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = far * near / (near - far);\n out[15] = 0.0;\n return out;\n}\n/**\r\n * Generates a orthogonal projection matrix with the given bounds\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {number} left Left bound of the frustum\r\n * @param {number} right Right bound of the frustum\r\n * @param {number} bottom Bottom bound of the frustum\r\n * @param {number} top Top bound of the frustum\r\n * @param {number} near Near bound of the frustum\r\n * @param {number} far Far bound of the frustum\r\n * @returns {mat4} out\r\n */\n\nexport function ortho(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n/**\r\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\r\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {ReadonlyVec3} eye Position of the viewer\r\n * @param {ReadonlyVec3} center Point the viewer is looking at\r\n * @param {ReadonlyVec3} up vec3 pointing up\r\n * @returns {mat4} out\r\n */\n\nexport function lookAt(out, eye, center, up) {\n var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;\n var eyex = eye[0];\n var eyey = eye[1];\n var eyez = eye[2];\n var upx = up[0];\n var upy = up[1];\n var upz = up[2];\n var centerx = center[0];\n var centery = center[1];\n var centerz = center[2];\n\n if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {\n return identity(out);\n }\n\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n len = 1 / Math.hypot(z0, z1, z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.hypot(x0, x1, x2);\n\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n len = Math.hypot(y0, y1, y2);\n\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n return out;\n}\n/**\r\n * Generates a matrix that makes something look at something else.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {ReadonlyVec3} eye Position of the viewer\r\n * @param {ReadonlyVec3} center Point the viewer is looking at\r\n * @param {ReadonlyVec3} up vec3 pointing up\r\n * @returns {mat4} out\r\n */\n\nexport function targetTo(out, eye, target, up) {\n var eyex = eye[0],\n eyey = eye[1],\n eyez = eye[2],\n upx = up[0],\n upy = up[1],\n upz = up[2];\n var z0 = eyex - target[0],\n z1 = eyey - target[1],\n z2 = eyez - target[2];\n var len = z0 * z0 + z1 * z1 + z2 * z2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n\n var x0 = upy * z2 - upz * z1,\n x1 = upz * z0 - upx * z2,\n x2 = upx * z1 - upy * z0;\n len = x0 * x0 + x1 * x1 + x2 * x2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n/**\r\n * Returns a string representation of a mat4\r\n *\r\n * @param {ReadonlyMat4} a matrix to represent as a string\r\n * @returns {String} string representation of the matrix\r\n */\n\nexport function str(a) {\n return \"mat4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \", \" + a[9] + \", \" + a[10] + \", \" + a[11] + \", \" + a[12] + \", \" + a[13] + \", \" + a[14] + \", \" + a[15] + \")\";\n}\n/**\r\n * Returns Frobenius norm of a mat4\r\n *\r\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\r\n * @returns {Number} Frobenius norm\r\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);\n}\n/**\r\n * Adds two mat4's\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the first operand\r\n * @param {ReadonlyMat4} b the second operand\r\n * @returns {mat4} out\r\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n/**\r\n * Subtracts matrix b from matrix a\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the first operand\r\n * @param {ReadonlyMat4} b the second operand\r\n * @returns {mat4} out\r\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n/**\r\n * Multiply each element of the matrix by a scalar.\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {ReadonlyMat4} a the matrix to scale\r\n * @param {Number} b amount to scale the matrix's elements by\r\n * @returns {mat4} out\r\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n/**\r\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\r\n *\r\n * @param {mat4} out the receiving vector\r\n * @param {ReadonlyMat4} a the first operand\r\n * @param {ReadonlyMat4} b the second operand\r\n * @param {Number} scale the amount to scale b's elements by before adding\r\n * @returns {mat4} out\r\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n/**\r\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {ReadonlyMat4} a The first matrix.\r\n * @param {ReadonlyMat4} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];\n}\n/**\r\n * Returns whether or not the matrices have approximately the same elements in the same position.\r\n *\r\n * @param {ReadonlyMat4} a The first matrix.\r\n * @param {ReadonlyMat4} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7];\n var a8 = a[8],\n a9 = a[9],\n a10 = a[10],\n a11 = a[11];\n var a12 = a[12],\n a13 = a[13],\n a14 = a[14],\n a15 = a[15];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n var b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7];\n var b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11];\n var b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));\n}\n/**\r\n * Alias for {@link mat4.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link mat4.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}","import React from 'react';\nexport default React.createContext(null);","import * as React from 'react';\n/**\n * @ignore - internal component.\n */\n\nvar ListContext = React.createContext({});\n\nif (process.env.NODE_ENV !== 'production') {\n ListContext.displayName = 'ListContext';\n}\n\nexport default ListContext;","/*\r\n Copyright 2013 Daniel Wirtz \r\n Copyright 2009 The Closure Library Authors. All Rights Reserved.\r\n\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License.\r\n */\r\n\r\n/**\r\n * @license long.js (c) 2013 Daniel Wirtz \r\n * Released under the Apache License, Version 2.0\r\n * see: https://github.com/dcodeIO/long.js for details\r\n */\r\n(function(global, factory) {\r\n\r\n /* AMD */ if (typeof define === 'function' && define[\"amd\"])\r\n define([], factory);\r\n /* CommonJS */ else if (typeof require === 'function' && typeof module === \"object\" && module && module[\"exports\"])\r\n module[\"exports\"] = factory();\r\n /* Global */ else\r\n (global[\"dcodeIO\"] = global[\"dcodeIO\"] || {})[\"Long\"] = factory();\r\n\r\n})(this, function() {\r\n \"use strict\";\r\n\r\n /**\r\n * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.\r\n * See the from* functions below for more convenient ways of constructing Longs.\r\n * @exports Long\r\n * @class A Long class for representing a 64 bit two's-complement integer value.\r\n * @param {number} low The low (signed) 32 bits of the long\r\n * @param {number} high The high (signed) 32 bits of the long\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed\r\n * @constructor\r\n */\r\n function Long(low, high, unsigned) {\r\n\r\n /**\r\n * The low 32 bits as a signed value.\r\n * @type {number}\r\n */\r\n this.low = low | 0;\r\n\r\n /**\r\n * The high 32 bits as a signed value.\r\n * @type {number}\r\n */\r\n this.high = high | 0;\r\n\r\n /**\r\n * Whether unsigned or not.\r\n * @type {boolean}\r\n */\r\n this.unsigned = !!unsigned;\r\n }\r\n\r\n // The internal representation of a long is the two given signed, 32-bit values.\r\n // We use 32-bit pieces because these are the size of integers on which\r\n // Javascript performs bit-operations. For operations like addition and\r\n // multiplication, we split each number into 16 bit pieces, which can easily be\r\n // multiplied within Javascript's floating-point representation without overflow\r\n // or change in sign.\r\n //\r\n // In the algorithms below, we frequently reduce the negative case to the\r\n // positive case by negating the input(s) and then post-processing the result.\r\n // Note that we must ALWAYS check specially whether those values are MIN_VALUE\r\n // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as\r\n // a positive number, it overflows back into a negative). Not handling this\r\n // case would often result in infinite recursion.\r\n //\r\n // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*\r\n // methods on which they depend.\r\n\r\n /**\r\n * An indicator used to reliably determine if an object is a Long or not.\r\n * @type {boolean}\r\n * @const\r\n * @private\r\n */\r\n Long.prototype.__isLong__;\r\n\r\n Object.defineProperty(Long.prototype, \"__isLong__\", {\r\n value: true,\r\n enumerable: false,\r\n configurable: false\r\n });\r\n\r\n /**\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n * @inner\r\n */\r\n function isLong(obj) {\r\n return (obj && obj[\"__isLong__\"]) === true;\r\n }\r\n\r\n /**\r\n * Tests if the specified object is a Long.\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n */\r\n Long.isLong = isLong;\r\n\r\n /**\r\n * A cache of the Long representations of small integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\n var INT_CACHE = {};\r\n\r\n /**\r\n * A cache of the Long representations of small unsigned integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\n var UINT_CACHE = {};\r\n\r\n /**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\n function fromInt(value, unsigned) {\r\n var obj, cachedObj, cache;\r\n if (unsigned) {\r\n value >>>= 0;\r\n if (cache = (0 <= value && value < 256)) {\r\n cachedObj = UINT_CACHE[value];\r\n if (cachedObj)\r\n return cachedObj;\r\n }\r\n obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);\r\n if (cache)\r\n UINT_CACHE[value] = obj;\r\n return obj;\r\n } else {\r\n value |= 0;\r\n if (cache = (-128 <= value && value < 128)) {\r\n cachedObj = INT_CACHE[value];\r\n if (cachedObj)\r\n return cachedObj;\r\n }\r\n obj = fromBits(value, value < 0 ? -1 : 0, false);\r\n if (cache)\r\n INT_CACHE[value] = obj;\r\n return obj;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a Long representing the given 32 bit integer value.\r\n * @function\r\n * @param {number} value The 32 bit integer in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\n Long.fromInt = fromInt;\r\n\r\n /**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\n function fromNumber(value, unsigned) {\r\n if (isNaN(value) || !isFinite(value))\r\n return unsigned ? UZERO : ZERO;\r\n if (unsigned) {\r\n if (value < 0)\r\n return UZERO;\r\n if (value >= TWO_PWR_64_DBL)\r\n return MAX_UNSIGNED_VALUE;\r\n } else {\r\n if (value <= -TWO_PWR_63_DBL)\r\n return MIN_VALUE;\r\n if (value + 1 >= TWO_PWR_63_DBL)\r\n return MAX_VALUE;\r\n }\r\n if (value < 0)\r\n return fromNumber(-value, unsigned).neg();\r\n return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);\r\n }\r\n\r\n /**\r\n * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.\r\n * @function\r\n * @param {number} value The number in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\n Long.fromNumber = fromNumber;\r\n\r\n /**\r\n * @param {number} lowBits\r\n * @param {number} highBits\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\n function fromBits(lowBits, highBits, unsigned) {\r\n return new Long(lowBits, highBits, unsigned);\r\n }\r\n\r\n /**\r\n * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is\r\n * assumed to use 32 bits.\r\n * @function\r\n * @param {number} lowBits The low 32 bits\r\n * @param {number} highBits The high 32 bits\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\n Long.fromBits = fromBits;\r\n\r\n /**\r\n * @function\r\n * @param {number} base\r\n * @param {number} exponent\r\n * @returns {number}\r\n * @inner\r\n */\r\n var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)\r\n\r\n /**\r\n * @param {string} str\r\n * @param {(boolean|number)=} unsigned\r\n * @param {number=} radix\r\n * @returns {!Long}\r\n * @inner\r\n */\r\n function fromString(str, unsigned, radix) {\r\n if (str.length === 0)\r\n throw Error('empty string');\r\n if (str === \"NaN\" || str === \"Infinity\" || str === \"+Infinity\" || str === \"-Infinity\")\r\n return ZERO;\r\n if (typeof unsigned === 'number') {\r\n // For goog.math.long compatibility\r\n radix = unsigned,\r\n unsigned = false;\r\n } else {\r\n unsigned = !! unsigned;\r\n }\r\n radix = radix || 10;\r\n if (radix < 2 || 36 < radix)\r\n throw RangeError('radix');\r\n\r\n var p;\r\n if ((p = str.indexOf('-')) > 0)\r\n throw Error('interior hyphen');\r\n else if (p === 0) {\r\n return fromString(str.substring(1), unsigned, radix).neg();\r\n }\r\n\r\n // Do several (8) digits each time through the loop, so as to\r\n // minimize the calls to the very expensive emulated div.\r\n var radixToPower = fromNumber(pow_dbl(radix, 8));\r\n\r\n var result = ZERO;\r\n for (var i = 0; i < str.length; i += 8) {\r\n var size = Math.min(8, str.length - i),\r\n value = parseInt(str.substring(i, i + size), radix);\r\n if (size < 8) {\r\n var power = fromNumber(pow_dbl(radix, size));\r\n result = result.mul(power).add(fromNumber(value));\r\n } else {\r\n result = result.mul(radixToPower);\r\n result = result.add(fromNumber(value));\r\n }\r\n }\r\n result.unsigned = unsigned;\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a Long representation of the given string, written using the specified radix.\r\n * @function\r\n * @param {string} str The textual representation of the Long\r\n * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed\r\n * @param {number=} radix The radix in which the text is written (2-36), defaults to 10\r\n * @returns {!Long} The corresponding Long value\r\n */\r\n Long.fromString = fromString;\r\n\r\n /**\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val\r\n * @returns {!Long}\r\n * @inner\r\n */\r\n function fromValue(val) {\r\n if (val /* is compatible */ instanceof Long)\r\n return val;\r\n if (typeof val === 'number')\r\n return fromNumber(val);\r\n if (typeof val === 'string')\r\n return fromString(val);\r\n // Throws for non-objects, converts non-instanceof Long:\r\n return fromBits(val.low, val.high, val.unsigned);\r\n }\r\n\r\n /**\r\n * Converts the specified value to a Long.\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value\r\n * @returns {!Long}\r\n */\r\n Long.fromValue = fromValue;\r\n\r\n // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be\r\n // no runtime penalty for these.\r\n\r\n /**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\n var TWO_PWR_16_DBL = 1 << 16;\r\n\r\n /**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\n var TWO_PWR_24_DBL = 1 << 24;\r\n\r\n /**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\n var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\r\n\r\n /**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\n var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\r\n\r\n /**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\n var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;\r\n\r\n /**\r\n * @type {!Long}\r\n * @const\r\n * @inner\r\n */\r\n var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);\r\n\r\n /**\r\n * @type {!Long}\r\n * @inner\r\n */\r\n var ZERO = fromInt(0);\r\n\r\n /**\r\n * Signed zero.\r\n * @type {!Long}\r\n */\r\n Long.ZERO = ZERO;\r\n\r\n /**\r\n * @type {!Long}\r\n * @inner\r\n */\r\n var UZERO = fromInt(0, true);\r\n\r\n /**\r\n * Unsigned zero.\r\n * @type {!Long}\r\n */\r\n Long.UZERO = UZERO;\r\n\r\n /**\r\n * @type {!Long}\r\n * @inner\r\n */\r\n var ONE = fromInt(1);\r\n\r\n /**\r\n * Signed one.\r\n * @type {!Long}\r\n */\r\n Long.ONE = ONE;\r\n\r\n /**\r\n * @type {!Long}\r\n * @inner\r\n */\r\n var UONE = fromInt(1, true);\r\n\r\n /**\r\n * Unsigned one.\r\n * @type {!Long}\r\n */\r\n Long.UONE = UONE;\r\n\r\n /**\r\n * @type {!Long}\r\n * @inner\r\n */\r\n var NEG_ONE = fromInt(-1);\r\n\r\n /**\r\n * Signed negative one.\r\n * @type {!Long}\r\n */\r\n Long.NEG_ONE = NEG_ONE;\r\n\r\n /**\r\n * @type {!Long}\r\n * @inner\r\n */\r\n var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);\r\n\r\n /**\r\n * Maximum signed value.\r\n * @type {!Long}\r\n */\r\n Long.MAX_VALUE = MAX_VALUE;\r\n\r\n /**\r\n * @type {!Long}\r\n * @inner\r\n */\r\n var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);\r\n\r\n /**\r\n * Maximum unsigned value.\r\n * @type {!Long}\r\n */\r\n Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;\r\n\r\n /**\r\n * @type {!Long}\r\n * @inner\r\n */\r\n var MIN_VALUE = fromBits(0, 0x80000000|0, false);\r\n\r\n /**\r\n * Minimum signed value.\r\n * @type {!Long}\r\n */\r\n Long.MIN_VALUE = MIN_VALUE;\r\n\r\n /**\r\n * @alias Long.prototype\r\n * @inner\r\n */\r\n var LongPrototype = Long.prototype;\r\n\r\n /**\r\n * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.\r\n * @returns {number}\r\n */\r\n LongPrototype.toInt = function toInt() {\r\n return this.unsigned ? this.low >>> 0 : this.low;\r\n };\r\n\r\n /**\r\n * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).\r\n * @returns {number}\r\n */\r\n LongPrototype.toNumber = function toNumber() {\r\n if (this.unsigned)\r\n return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);\r\n return this.high * TWO_PWR_32_DBL + (this.low >>> 0);\r\n };\r\n\r\n /**\r\n * Converts the Long to a string written in the specified radix.\r\n * @param {number=} radix Radix (2-36), defaults to 10\r\n * @returns {string}\r\n * @override\r\n * @throws {RangeError} If `radix` is out of range\r\n */\r\n LongPrototype.toString = function toString(radix) {\r\n radix = radix || 10;\r\n if (radix < 2 || 36 < radix)\r\n throw RangeError('radix');\r\n if (this.isZero())\r\n return '0';\r\n if (this.isNegative()) { // Unsigned Longs are never negative\r\n if (this.eq(MIN_VALUE)) {\r\n // We need to change the Long value before it can be negated, so we remove\r\n // the bottom-most digit in this base and then recurse to do the rest.\r\n var radixLong = fromNumber(radix),\r\n div = this.div(radixLong),\r\n rem1 = div.mul(radixLong).sub(this);\r\n return div.toString(radix) + rem1.toInt().toString(radix);\r\n } else\r\n return '-' + this.neg().toString(radix);\r\n }\r\n\r\n // Do several (6) digits each time through the loop, so as to\r\n // minimize the calls to the very expensive emulated div.\r\n var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),\r\n rem = this;\r\n var result = '';\r\n while (true) {\r\n var remDiv = rem.div(radixToPower),\r\n intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,\r\n digits = intval.toString(radix);\r\n rem = remDiv;\r\n if (rem.isZero())\r\n return digits + result;\r\n else {\r\n while (digits.length < 6)\r\n digits = '0' + digits;\r\n result = '' + digits + result;\r\n }\r\n }\r\n };\r\n\r\n /**\r\n * Gets the high 32 bits as a signed integer.\r\n * @returns {number} Signed high bits\r\n */\r\n LongPrototype.getHighBits = function getHighBits() {\r\n return this.high;\r\n };\r\n\r\n /**\r\n * Gets the high 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned high bits\r\n */\r\n LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {\r\n return this.high >>> 0;\r\n };\r\n\r\n /**\r\n * Gets the low 32 bits as a signed integer.\r\n * @returns {number} Signed low bits\r\n */\r\n LongPrototype.getLowBits = function getLowBits() {\r\n return this.low;\r\n };\r\n\r\n /**\r\n * Gets the low 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned low bits\r\n */\r\n LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {\r\n return this.low >>> 0;\r\n };\r\n\r\n /**\r\n * Gets the number of bits needed to represent the absolute value of this Long.\r\n * @returns {number}\r\n */\r\n LongPrototype.getNumBitsAbs = function getNumBitsAbs() {\r\n if (this.isNegative()) // Unsigned Longs are never negative\r\n return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();\r\n var val = this.high != 0 ? this.high : this.low;\r\n for (var bit = 31; bit > 0; bit--)\r\n if ((val & (1 << bit)) != 0)\r\n break;\r\n return this.high != 0 ? bit + 33 : bit + 1;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value equals zero.\r\n * @returns {boolean}\r\n */\r\n LongPrototype.isZero = function isZero() {\r\n return this.high === 0 && this.low === 0;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value is negative.\r\n * @returns {boolean}\r\n */\r\n LongPrototype.isNegative = function isNegative() {\r\n return !this.unsigned && this.high < 0;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value is positive.\r\n * @returns {boolean}\r\n */\r\n LongPrototype.isPositive = function isPositive() {\r\n return this.unsigned || this.high >= 0;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value is odd.\r\n * @returns {boolean}\r\n */\r\n LongPrototype.isOdd = function isOdd() {\r\n return (this.low & 1) === 1;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value is even.\r\n * @returns {boolean}\r\n */\r\n LongPrototype.isEven = function isEven() {\r\n return (this.low & 1) === 0;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value equals the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.equals = function equals(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)\r\n return false;\r\n return this.high === other.high && this.low === other.low;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.eq = LongPrototype.equals;\r\n\r\n /**\r\n * Tests if this Long's value differs from the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.notEquals = function notEquals(other) {\r\n return !this.eq(/* validates */ other);\r\n };\r\n\r\n /**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.neq = LongPrototype.notEquals;\r\n\r\n /**\r\n * Tests if this Long's value is less than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.lessThan = function lessThan(other) {\r\n return this.comp(/* validates */ other) < 0;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.lt = LongPrototype.lessThan;\r\n\r\n /**\r\n * Tests if this Long's value is less than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {\r\n return this.comp(/* validates */ other) <= 0;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.lte = LongPrototype.lessThanOrEqual;\r\n\r\n /**\r\n * Tests if this Long's value is greater than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.greaterThan = function greaterThan(other) {\r\n return this.comp(/* validates */ other) > 0;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.gt = LongPrototype.greaterThan;\r\n\r\n /**\r\n * Tests if this Long's value is greater than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {\r\n return this.comp(/* validates */ other) >= 0;\r\n };\r\n\r\n /**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\n LongPrototype.gte = LongPrototype.greaterThanOrEqual;\r\n\r\n /**\r\n * Compares this Long's value with the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n * if the given one is greater\r\n */\r\n LongPrototype.compare = function compare(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n if (this.eq(other))\r\n return 0;\r\n var thisNeg = this.isNegative(),\r\n otherNeg = other.isNegative();\r\n if (thisNeg && !otherNeg)\r\n return -1;\r\n if (!thisNeg && otherNeg)\r\n return 1;\r\n // At this point the sign bits are the same\r\n if (!this.unsigned)\r\n return this.sub(other).isNegative() ? -1 : 1;\r\n // Both are positive if at least one is unsigned\r\n return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;\r\n };\r\n\r\n /**\r\n * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n * if the given one is greater\r\n */\r\n LongPrototype.comp = LongPrototype.compare;\r\n\r\n /**\r\n * Negates this Long's value.\r\n * @returns {!Long} Negated Long\r\n */\r\n LongPrototype.negate = function negate() {\r\n if (!this.unsigned && this.eq(MIN_VALUE))\r\n return MIN_VALUE;\r\n return this.not().add(ONE);\r\n };\r\n\r\n /**\r\n * Negates this Long's value. This is an alias of {@link Long#negate}.\r\n * @function\r\n * @returns {!Long} Negated Long\r\n */\r\n LongPrototype.neg = LongPrototype.negate;\r\n\r\n /**\r\n * Returns the sum of this and the specified Long.\r\n * @param {!Long|number|string} addend Addend\r\n * @returns {!Long} Sum\r\n */\r\n LongPrototype.add = function add(addend) {\r\n if (!isLong(addend))\r\n addend = fromValue(addend);\r\n\r\n // Divide each number into 4 chunks of 16 bits, and then sum the chunks.\r\n\r\n var a48 = this.high >>> 16;\r\n var a32 = this.high & 0xFFFF;\r\n var a16 = this.low >>> 16;\r\n var a00 = this.low & 0xFFFF;\r\n\r\n var b48 = addend.high >>> 16;\r\n var b32 = addend.high & 0xFFFF;\r\n var b16 = addend.low >>> 16;\r\n var b00 = addend.low & 0xFFFF;\r\n\r\n var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n c00 += a00 + b00;\r\n c16 += c00 >>> 16;\r\n c00 &= 0xFFFF;\r\n c16 += a16 + b16;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c32 += a32 + b32;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c48 += a48 + b48;\r\n c48 &= 0xFFFF;\r\n return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n };\r\n\r\n /**\r\n * Returns the difference of this and the specified Long.\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\n LongPrototype.subtract = function subtract(subtrahend) {\r\n if (!isLong(subtrahend))\r\n subtrahend = fromValue(subtrahend);\r\n return this.add(subtrahend.neg());\r\n };\r\n\r\n /**\r\n * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.\r\n * @function\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\n LongPrototype.sub = LongPrototype.subtract;\r\n\r\n /**\r\n * Returns the product of this and the specified Long.\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\n LongPrototype.multiply = function multiply(multiplier) {\r\n if (this.isZero())\r\n return ZERO;\r\n if (!isLong(multiplier))\r\n multiplier = fromValue(multiplier);\r\n if (multiplier.isZero())\r\n return ZERO;\r\n if (this.eq(MIN_VALUE))\r\n return multiplier.isOdd() ? MIN_VALUE : ZERO;\r\n if (multiplier.eq(MIN_VALUE))\r\n return this.isOdd() ? MIN_VALUE : ZERO;\r\n\r\n if (this.isNegative()) {\r\n if (multiplier.isNegative())\r\n return this.neg().mul(multiplier.neg());\r\n else\r\n return this.neg().mul(multiplier).neg();\r\n } else if (multiplier.isNegative())\r\n return this.mul(multiplier.neg()).neg();\r\n\r\n // If both longs are small, use float multiplication\r\n if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))\r\n return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);\r\n\r\n // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.\r\n // We can skip products that would overflow.\r\n\r\n var a48 = this.high >>> 16;\r\n var a32 = this.high & 0xFFFF;\r\n var a16 = this.low >>> 16;\r\n var a00 = this.low & 0xFFFF;\r\n\r\n var b48 = multiplier.high >>> 16;\r\n var b32 = multiplier.high & 0xFFFF;\r\n var b16 = multiplier.low >>> 16;\r\n var b00 = multiplier.low & 0xFFFF;\r\n\r\n var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n c00 += a00 * b00;\r\n c16 += c00 >>> 16;\r\n c00 &= 0xFFFF;\r\n c16 += a16 * b00;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c16 += a00 * b16;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c32 += a32 * b00;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c32 += a16 * b16;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c32 += a00 * b32;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;\r\n c48 &= 0xFFFF;\r\n return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n };\r\n\r\n /**\r\n * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.\r\n * @function\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\n LongPrototype.mul = LongPrototype.multiply;\r\n\r\n /**\r\n * Returns this Long divided by the specified. The result is signed if this Long is signed or\r\n * unsigned if this Long is unsigned.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\n LongPrototype.divide = function divide(divisor) {\r\n if (!isLong(divisor))\r\n divisor = fromValue(divisor);\r\n if (divisor.isZero())\r\n throw Error('division by zero');\r\n if (this.isZero())\r\n return this.unsigned ? UZERO : ZERO;\r\n var approx, rem, res;\r\n if (!this.unsigned) {\r\n // This section is only relevant for signed longs and is derived from the\r\n // closure library as a whole.\r\n if (this.eq(MIN_VALUE)) {\r\n if (divisor.eq(ONE) || divisor.eq(NEG_ONE))\r\n return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE\r\n else if (divisor.eq(MIN_VALUE))\r\n return ONE;\r\n else {\r\n // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.\r\n var halfThis = this.shr(1);\r\n approx = halfThis.div(divisor).shl(1);\r\n if (approx.eq(ZERO)) {\r\n return divisor.isNegative() ? ONE : NEG_ONE;\r\n } else {\r\n rem = this.sub(divisor.mul(approx));\r\n res = approx.add(rem.div(divisor));\r\n return res;\r\n }\r\n }\r\n } else if (divisor.eq(MIN_VALUE))\r\n return this.unsigned ? UZERO : ZERO;\r\n if (this.isNegative()) {\r\n if (divisor.isNegative())\r\n return this.neg().div(divisor.neg());\r\n return this.neg().div(divisor).neg();\r\n } else if (divisor.isNegative())\r\n return this.div(divisor.neg()).neg();\r\n res = ZERO;\r\n } else {\r\n // The algorithm below has not been made for unsigned longs. It's therefore\r\n // required to take special care of the MSB prior to running it.\r\n if (!divisor.unsigned)\r\n divisor = divisor.toUnsigned();\r\n if (divisor.gt(this))\r\n return UZERO;\r\n if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true\r\n return UONE;\r\n res = UZERO;\r\n }\r\n\r\n // Repeat the following until the remainder is less than other: find a\r\n // floating-point that approximates remainder / other *from below*, add this\r\n // into the result, and subtract it from the remainder. It is critical that\r\n // the approximate value is less than or equal to the real value so that the\r\n // remainder never becomes negative.\r\n rem = this;\r\n while (rem.gte(divisor)) {\r\n // Approximate the result of division. This may be a little greater or\r\n // smaller than the actual value.\r\n approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));\r\n\r\n // We will tweak the approximate result by changing it in the 48-th digit or\r\n // the smallest non-fractional digit, whichever is larger.\r\n var log2 = Math.ceil(Math.log(approx) / Math.LN2),\r\n delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),\r\n\r\n // Decrease the approximation until it is smaller than the remainder. Note\r\n // that if it is too large, the product overflows and is negative.\r\n approxRes = fromNumber(approx),\r\n approxRem = approxRes.mul(divisor);\r\n while (approxRem.isNegative() || approxRem.gt(rem)) {\r\n approx -= delta;\r\n approxRes = fromNumber(approx, this.unsigned);\r\n approxRem = approxRes.mul(divisor);\r\n }\r\n\r\n // We know the answer can't be zero... and actually, zero would cause\r\n // infinite recursion since we would make no progress.\r\n if (approxRes.isZero())\r\n approxRes = ONE;\r\n\r\n res = res.add(approxRes);\r\n rem = rem.sub(approxRem);\r\n }\r\n return res;\r\n };\r\n\r\n /**\r\n * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\n LongPrototype.div = LongPrototype.divide;\r\n\r\n /**\r\n * Returns this Long modulo the specified.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\n LongPrototype.modulo = function modulo(divisor) {\r\n if (!isLong(divisor))\r\n divisor = fromValue(divisor);\r\n return this.sub(this.div(divisor).mul(divisor));\r\n };\r\n\r\n /**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\n LongPrototype.mod = LongPrototype.modulo;\r\n\r\n /**\r\n * Returns the bitwise NOT of this Long.\r\n * @returns {!Long}\r\n */\r\n LongPrototype.not = function not() {\r\n return fromBits(~this.low, ~this.high, this.unsigned);\r\n };\r\n\r\n /**\r\n * Returns the bitwise AND of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\n LongPrototype.and = function and(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low & other.low, this.high & other.high, this.unsigned);\r\n };\r\n\r\n /**\r\n * Returns the bitwise OR of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\n LongPrototype.or = function or(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low | other.low, this.high | other.high, this.unsigned);\r\n };\r\n\r\n /**\r\n * Returns the bitwise XOR of this Long and the given one.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\n LongPrototype.xor = function xor(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);\r\n };\r\n\r\n /**\r\n * Returns this Long with bits shifted to the left by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\n LongPrototype.shiftLeft = function shiftLeft(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n if ((numBits &= 63) === 0)\r\n return this;\r\n else if (numBits < 32)\r\n return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);\r\n else\r\n return fromBits(0, this.low << (numBits - 32), this.unsigned);\r\n };\r\n\r\n /**\r\n * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\n LongPrototype.shl = LongPrototype.shiftLeft;\r\n\r\n /**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\n LongPrototype.shiftRight = function shiftRight(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n if ((numBits &= 63) === 0)\r\n return this;\r\n else if (numBits < 32)\r\n return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);\r\n else\r\n return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);\r\n };\r\n\r\n /**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\n LongPrototype.shr = LongPrototype.shiftRight;\r\n\r\n /**\r\n * Returns this Long with bits logically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\n LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n numBits &= 63;\r\n if (numBits === 0)\r\n return this;\r\n else {\r\n var high = this.high;\r\n if (numBits < 32) {\r\n var low = this.low;\r\n return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);\r\n } else if (numBits === 32)\r\n return fromBits(high, 0, this.unsigned);\r\n else\r\n return fromBits(high >>> (numBits - 32), 0, this.unsigned);\r\n }\r\n };\r\n\r\n /**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\n LongPrototype.shru = LongPrototype.shiftRightUnsigned;\r\n\r\n /**\r\n * Converts this Long to signed.\r\n * @returns {!Long} Signed long\r\n */\r\n LongPrototype.toSigned = function toSigned() {\r\n if (!this.unsigned)\r\n return this;\r\n return fromBits(this.low, this.high, false);\r\n };\r\n\r\n /**\r\n * Converts this Long to unsigned.\r\n * @returns {!Long} Unsigned long\r\n */\r\n LongPrototype.toUnsigned = function toUnsigned() {\r\n if (this.unsigned)\r\n return this;\r\n return fromBits(this.low, this.high, true);\r\n };\r\n\r\n /**\r\n * Converts this Long to its byte representation.\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {!Array.} Byte representation\r\n */\r\n LongPrototype.toBytes = function(le) {\r\n return le ? this.toBytesLE() : this.toBytesBE();\r\n }\r\n\r\n /**\r\n * Converts this Long to its little endian byte representation.\r\n * @returns {!Array.} Little endian byte representation\r\n */\r\n LongPrototype.toBytesLE = function() {\r\n var hi = this.high,\r\n lo = this.low;\r\n return [\r\n lo & 0xff,\r\n (lo >>> 8) & 0xff,\r\n (lo >>> 16) & 0xff,\r\n (lo >>> 24) & 0xff,\r\n hi & 0xff,\r\n (hi >>> 8) & 0xff,\r\n (hi >>> 16) & 0xff,\r\n (hi >>> 24) & 0xff\r\n ];\r\n }\r\n\r\n /**\r\n * Converts this Long to its big endian byte representation.\r\n * @returns {!Array.} Big endian byte representation\r\n */\r\n LongPrototype.toBytesBE = function() {\r\n var hi = this.high,\r\n lo = this.low;\r\n return [\r\n (hi >>> 24) & 0xff,\r\n (hi >>> 16) & 0xff,\r\n (hi >>> 8) & 0xff,\r\n hi & 0xff,\r\n (lo >>> 24) & 0xff,\r\n (lo >>> 16) & 0xff,\r\n (lo >>> 8) & 0xff,\r\n lo & 0xff\r\n ];\r\n }\r\n\r\n return Long;\r\n});\r\n","import {COORDINATE_SYSTEM, createIterable} from '@deck.gl/core';\n\n/* eslint-disable max-statements, complexity */\nconst RADIAN_PER_DEGREE = Math.PI / 180;\nconst modelMatrix = new Float32Array(16);\nconst valueArray = new Float32Array(12);\n\nfunction calculateTransformMatrix(targetMatrix, orientation, scale) {\n const pitch = orientation[0] * RADIAN_PER_DEGREE;\n const yaw = orientation[1] * RADIAN_PER_DEGREE;\n const roll = orientation[2] * RADIAN_PER_DEGREE;\n\n const sr = Math.sin(roll);\n const sp = Math.sin(pitch);\n const sw = Math.sin(yaw);\n\n const cr = Math.cos(roll);\n const cp = Math.cos(pitch);\n const cw = Math.cos(yaw);\n\n const scx = scale[0];\n const scy = scale[1];\n const scz = scale[2];\n\n targetMatrix[0] = scx * cw * cp; // 0,0\n targetMatrix[1] = scx * sw * cp; // 1,0\n targetMatrix[2] = scx * -sp; // 2,0\n targetMatrix[3] = scy * (-sw * cr + cw * sp * sr); // 0,1\n targetMatrix[4] = scy * (cw * cr + sw * sp * sr); // 1,1\n targetMatrix[5] = scy * cp * sr; // 2,1\n targetMatrix[6] = scz * (sw * sr + cw * sp * cr); // 0,2\n targetMatrix[7] = scz * (-cw * sr + sw * sp * cr); // 1,2\n targetMatrix[8] = scz * cp * cr; // 2,2\n}\n\nfunction getExtendedMat3FromMat4(mat4) {\n mat4[0] = mat4[0];\n mat4[1] = mat4[1];\n mat4[2] = mat4[2];\n mat4[3] = mat4[4];\n mat4[4] = mat4[5];\n mat4[5] = mat4[6];\n mat4[6] = mat4[8];\n mat4[7] = mat4[9];\n mat4[8] = mat4[10];\n mat4[9] = mat4[12];\n mat4[10] = mat4[13];\n mat4[11] = mat4[14];\n\n return mat4.subarray(0, 12);\n}\n\nexport const MATRIX_ATTRIBUTES = {\n size: 12,\n accessor: ['getOrientation', 'getScale', 'getTranslation', 'getTransformMatrix'],\n shaderAttributes: {\n instanceModelMatrix__LOCATION_0: {\n size: 3,\n elementOffset: 0\n },\n instanceModelMatrix__LOCATION_1: {\n size: 3,\n elementOffset: 3\n },\n instanceModelMatrix__LOCATION_2: {\n size: 3,\n elementOffset: 6\n },\n instanceTranslation: {\n size: 3,\n elementOffset: 9\n }\n },\n\n update(attribute, {startRow, endRow}) {\n // NOTE(Tarek): \"this\" will be bound to a layer!\n const {data, getOrientation, getScale, getTranslation, getTransformMatrix} = this.props;\n\n const arrayMatrix = Array.isArray(getTransformMatrix);\n const constantMatrix = arrayMatrix && getTransformMatrix.length === 16;\n const constantScale = Array.isArray(getScale);\n const constantOrientation = Array.isArray(getOrientation);\n const constantTranslation = Array.isArray(getTranslation);\n\n const hasMatrix = constantMatrix || (!arrayMatrix && Boolean(getTransformMatrix(data[0])));\n\n if (hasMatrix) {\n attribute.constant = constantMatrix;\n } else {\n attribute.constant = constantOrientation && constantScale && constantTranslation;\n }\n\n const instanceModelMatrixData = attribute.value;\n\n if (attribute.constant) {\n let matrix;\n\n if (hasMatrix) {\n modelMatrix.set(getTransformMatrix);\n matrix = getExtendedMat3FromMat4(modelMatrix);\n } else {\n matrix = valueArray;\n\n const orientation = getOrientation;\n const scale = getScale;\n\n calculateTransformMatrix(matrix, orientation, scale);\n matrix.set(getTranslation, 9);\n }\n\n attribute.value = new Float32Array(matrix);\n } else {\n let i = startRow * attribute.size;\n const {iterable, objectInfo} = createIterable(data, startRow, endRow);\n for (const object of iterable) {\n objectInfo.index++;\n let matrix;\n\n if (hasMatrix) {\n modelMatrix.set(\n constantMatrix ? getTransformMatrix : getTransformMatrix(object, objectInfo)\n );\n matrix = getExtendedMat3FromMat4(modelMatrix);\n } else {\n matrix = valueArray;\n\n const orientation = constantOrientation\n ? getOrientation\n : getOrientation(object, objectInfo);\n const scale = constantScale ? getScale : getScale(object, objectInfo);\n\n calculateTransformMatrix(matrix, orientation, scale);\n matrix.set(constantTranslation ? getTranslation : getTranslation(object, objectInfo), 9);\n }\n\n instanceModelMatrixData[i++] = matrix[0];\n instanceModelMatrixData[i++] = matrix[1];\n instanceModelMatrixData[i++] = matrix[2];\n instanceModelMatrixData[i++] = matrix[3];\n instanceModelMatrixData[i++] = matrix[4];\n instanceModelMatrixData[i++] = matrix[5];\n instanceModelMatrixData[i++] = matrix[6];\n instanceModelMatrixData[i++] = matrix[7];\n instanceModelMatrixData[i++] = matrix[8];\n instanceModelMatrixData[i++] = matrix[9];\n instanceModelMatrixData[i++] = matrix[10];\n instanceModelMatrixData[i++] = matrix[11];\n }\n }\n }\n};\n\n// only apply composeModelMatrix when in cartesian or meter_offsets coordinate system\n// with `composeModelMatrix` enabled, the rotation part of the layer's modelMatrix will be composed to instance's transformations\n// since rotating latitude and longitude can not provide meaningful results, hence `composeModelMatrix` is disabled\n// when in LNGLAT and LNGLAT_OFFSET coordinates.\nexport function shouldComposeModelMatrix(viewport, coordinateSystem) {\n return (\n coordinateSystem === COORDINATE_SYSTEM.CARTESIAN ||\n coordinateSystem === COORDINATE_SYSTEM.METER_OFFSETS ||\n (coordinateSystem === COORDINATE_SYSTEM.DEFAULT && !viewport.isGeospatial)\n );\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-dev-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-dev-runtime.development.js');\n}\n","/* eslint-disable no-inline-comments, max-len, camelcase */\nimport GL from '@luma.gl/constants';\nimport {isWebGL2} from '../utils/webgl-checks';\n\nconst OES_element_index = 'OES_element_index';\nconst WEBGL_draw_buffers = 'WEBGL_draw_buffers';\nconst EXT_disjoint_timer_query = 'EXT_disjoint_timer_query';\nconst EXT_disjoint_timer_query_webgl2 = 'EXT_disjoint_timer_query_webgl2';\nconst EXT_texture_filter_anisotropic = 'EXT_texture_filter_anisotropic';\nconst WEBGL_debug_renderer_info = 'WEBGL_debug_renderer_info';\n\nconst GL_FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8b8b;\nconst GL_DONT_CARE = 0x1100;\nconst GL_GPU_DISJOINT_EXT = 0x8fbb;\nconst GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff;\nconst GL_UNMASKED_VENDOR_WEBGL = 0x9245; // vendor string of the graphics driver.\nconst GL_UNMASKED_RENDERER_WEBGL = 0x9246; // renderer string of the graphics driver.\n\nconst getWebGL2ValueOrZero = gl => (!isWebGL2(gl) ? 0 : undefined);\n\n// if a function returns undefined in this table,\n// the original getParameter will be called, defeating the override\nconst WEBGL_PARAMETERS = {\n [GL.READ_BUFFER]: gl => (!isWebGL2(gl) ? GL.COLOR_ATTACHMENT0 : undefined),\n\n // WebGL2 context parameters\n [GL_FRAGMENT_SHADER_DERIVATIVE_HINT]: gl => (!isWebGL2(gl) ? GL_DONT_CARE : undefined),\n\n [GL.RASTERIZER_DISCARD]: getWebGL2ValueOrZero,\n\n [GL.SAMPLES]: getWebGL2ValueOrZero,\n\n // WebGL2 extension context parameters\n [GL_GPU_DISJOINT_EXT]: (gl, getParameter) => {\n const ext = isWebGL2(gl)\n ? gl.getExtension(EXT_disjoint_timer_query_webgl2)\n : gl.getExtension(EXT_disjoint_timer_query);\n return ext && ext.GPU_DISJOINT_EXT ? getParameter(ext.GPU_DISJOINT_EXT) : 0;\n },\n\n // Extension fixed values\n [GL_UNMASKED_VENDOR_WEBGL]: (gl, getParameter) => {\n const ext = gl.getExtension(WEBGL_debug_renderer_info);\n return getParameter((ext && ext.UNMASKED_VENDOR_WEBGL) || GL.VENDOR);\n },\n\n [GL_UNMASKED_RENDERER_WEBGL]: (gl, getParameter) => {\n const ext = gl.getExtension(WEBGL_debug_renderer_info);\n return getParameter((ext && ext.UNMASKED_RENDERER_WEBGL) || GL.RENDERER);\n },\n\n // Extension LIMITS\n [GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT]: (gl, getParameter) => {\n const ext = gl.luma.extensions[EXT_texture_filter_anisotropic];\n return ext ? getParameter(ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 1.0;\n },\n\n // WebGL2 Limits\n [GL.MAX_3D_TEXTURE_SIZE]: getWebGL2ValueOrZero,\n [GL.MAX_ARRAY_TEXTURE_LAYERS]: getWebGL2ValueOrZero,\n [GL.MAX_CLIENT_WAIT_TIMEOUT_WEBGL]: getWebGL2ValueOrZero,\n [GL.MAX_COLOR_ATTACHMENTS]: (gl, getParameter) => {\n if (!isWebGL2(gl)) {\n const ext = gl.getExtension(WEBGL_draw_buffers);\n return ext ? getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL) : 0;\n }\n return undefined;\n },\n [GL.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS]: getWebGL2ValueOrZero,\n [GL.MAX_COMBINED_UNIFORM_BLOCKS]: getWebGL2ValueOrZero,\n [GL.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS]: getWebGL2ValueOrZero,\n [GL.MAX_DRAW_BUFFERS]: gl => {\n if (!isWebGL2(gl)) {\n const ext = gl.getExtension(WEBGL_draw_buffers);\n return ext ? ext.MAX_DRAW_BUFFERS_WEBGL : 0;\n }\n return undefined;\n },\n [GL.MAX_ELEMENT_INDEX]:\n // Guess: per webglstats.com 99.6% of webgl2 supports 2147483647\n gl => (gl.getExtension(OES_element_index) ? 2147483647 : 65535),\n [GL.MAX_ELEMENTS_INDICES]:\n // Guess: \"Reasonably safe\" per webglstats.com - could be higher/lower (on some mobile devices)\n gl => (gl.getExtension(OES_element_index) ? 16777216 : 65535),\n [GL.MAX_ELEMENTS_VERTICES]:\n // Guess: \"Reasonably safe\" per webglstats.com - could be higher/lower (on some mobile devices)\n gl => 16777216,\n [GL.MAX_FRAGMENT_INPUT_COMPONENTS]: getWebGL2ValueOrZero,\n [GL.MAX_FRAGMENT_UNIFORM_BLOCKS]: getWebGL2ValueOrZero,\n [GL.MAX_FRAGMENT_UNIFORM_COMPONENTS]: getWebGL2ValueOrZero,\n [GL.MAX_SAMPLES]: getWebGL2ValueOrZero,\n [GL.MAX_SERVER_WAIT_TIMEOUT]: getWebGL2ValueOrZero,\n [GL.MAX_TEXTURE_LOD_BIAS]: getWebGL2ValueOrZero,\n [GL.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS]: getWebGL2ValueOrZero,\n [GL.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS]: getWebGL2ValueOrZero,\n [GL.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS]: getWebGL2ValueOrZero,\n [GL.MAX_UNIFORM_BLOCK_SIZE]: getWebGL2ValueOrZero,\n [GL.MAX_UNIFORM_BUFFER_BINDINGS]: getWebGL2ValueOrZero,\n [GL.MAX_VARYING_COMPONENTS]: getWebGL2ValueOrZero,\n [GL.MAX_VERTEX_OUTPUT_COMPONENTS]: getWebGL2ValueOrZero,\n [GL.MAX_VERTEX_UNIFORM_BLOCKS]: getWebGL2ValueOrZero,\n [GL.MAX_VERTEX_UNIFORM_COMPONENTS]: getWebGL2ValueOrZero,\n [GL.MIN_PROGRAM_TEXEL_OFFSET]: getWebGL2ValueOrZero,\n [GL.MAX_PROGRAM_TEXEL_OFFSET]: getWebGL2ValueOrZero,\n [GL.UNIFORM_BUFFER_OFFSET_ALIGNMENT]: getWebGL2ValueOrZero\n};\n\n// A \"replacement\" gl.getParameter that accepts \"enums\" from extensions and WebGL2\n// and returns reasonably safe defaults\nexport function getParameterPolyfill(gl, originalGetParameter, pname) {\n // Return mock limits (usually 0) for WebGL2 constants to ensure these\n // can be queries without error\n const limit = WEBGL_PARAMETERS[pname];\n // @ts-ignore TODO pname parameter not declared\n const value = typeof limit === 'function' ? limit(gl, originalGetParameter, pname) : limit;\n const result = value !== undefined ? value : originalGetParameter(pname);\n return result;\n}\n","import GL from '@luma.gl/constants';\nimport {assert} from '../utils/assert';\nimport {isWebGL2} from '../utils/webgl-checks';\n\nimport {getParameterPolyfill} from './get-parameter-polyfill';\n\nconst OES_vertex_array_object = 'OES_vertex_array_object';\nconst ANGLE_instanced_arrays = 'ANGLE_instanced_arrays';\nconst WEBGL_draw_buffers = 'WEBGL_draw_buffers';\nconst EXT_disjoint_timer_query = 'EXT_disjoint_timer_query';\nconst EXT_texture_filter_anisotropic = 'EXT_texture_filter_anisotropic';\n\nconst ERR_VAO_NOT_SUPPORTED = 'VertexArray requires WebGL2 or OES_vertex_array_object extension';\n\n// Return object with webgl2 flag and an extension\nfunction getExtensionData(gl, extension) {\n return {\n webgl2: isWebGL2(gl),\n ext: gl.getExtension(extension)\n };\n}\n\n// function mapExtensionConstant(gl, constant) {\n// switch (constant) {\n// case ext.FRAGMENT_SHADER_DERIVATIVE_HINT_OES: return GL.FRAGMENT_SHADER_DERIVATIVE_HINT;\n// }\n// }\n\nexport const WEBGL2_CONTEXT_POLYFILLS = {\n // POLYFILL TABLE\n [OES_vertex_array_object]: {\n meta: {suffix: 'OES'},\n // NEW METHODS\n createVertexArray: () => {\n assert(false, ERR_VAO_NOT_SUPPORTED);\n },\n deleteVertexArray: () => {},\n bindVertexArray: () => {},\n isVertexArray: () => false\n },\n [ANGLE_instanced_arrays]: {\n meta: {\n suffix: 'ANGLE'\n // constants: {\n // VERTEX_ATTRIB_ARRAY_DIVISOR: 'VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE'\n // }\n },\n vertexAttribDivisor(location, divisor) {\n // Accept divisor 0 even if instancing is not supported (0 = no instancing)\n assert(divisor === 0, 'WebGL instanced rendering not supported');\n },\n drawElementsInstanced: () => {},\n drawArraysInstanced: () => {}\n },\n [WEBGL_draw_buffers]: {\n meta: {\n suffix: 'WEBGL'\n },\n drawBuffers: () => {\n assert(false);\n }\n },\n [EXT_disjoint_timer_query]: {\n meta: {suffix: 'EXT'},\n // WebGL1: Polyfills the WebGL2 Query API\n createQuery: () => {\n assert(false);\n },\n deleteQuery: () => {\n assert(false);\n },\n beginQuery: () => {\n assert(false);\n },\n endQuery: () => {},\n getQuery(handle, pname) {\n // @ts-ignore\n return this.getQueryObject(handle, pname);\n },\n // The WebGL1 extension uses getQueryObject rather then getQueryParameter\n getQueryParameter(handle, pname) {\n // @ts-ignore\n return this.getQueryObject(handle, pname);\n },\n getQueryObject: () => {}\n }\n};\n\nexport const WEBGL2_CONTEXT_OVERRIDES = {\n // Ensure readBuffer is a no-op\n readBuffer: (gl, originalFunc, attachment) => {\n if (isWebGL2(gl)) {\n originalFunc(attachment);\n } else {\n // assert(attachment !== GL_COLOR_ATTACHMENT0 && attachment !== GL_FRONT);\n }\n },\n // Override for getVertexAttrib that returns sane values for non-WebGL1 constants\n getVertexAttrib: (gl, originalFunc, location, pname) => {\n // const gl = this; // eslint-disable-line\n const {webgl2, ext} = getExtensionData(gl, ANGLE_instanced_arrays);\n\n let result;\n switch (pname) {\n // WebGL1 attributes will never be integer\n case GL.VERTEX_ATTRIB_ARRAY_INTEGER:\n result = !webgl2 ? false : undefined;\n break;\n // if instancing is not available, return 0 meaning divisor has not been set\n case GL.VERTEX_ATTRIB_ARRAY_DIVISOR:\n result = !webgl2 && !ext ? 0 : undefined;\n break;\n default:\n }\n\n return result !== undefined ? result : originalFunc(location, pname);\n },\n // Handle transform feedback and uniform block queries in WebGL1\n getProgramParameter: (gl, originalFunc, program, pname) => {\n if (!isWebGL2(gl)) {\n switch (pname) {\n case GL.TRANSFORM_FEEDBACK_BUFFER_MODE:\n return GL.SEPARATE_ATTRIBS;\n case GL.TRANSFORM_FEEDBACK_VARYINGS:\n return 0;\n case GL.ACTIVE_UNIFORM_BLOCKS:\n return 0;\n default:\n }\n }\n return originalFunc(program, pname);\n },\n getInternalformatParameter: (gl, originalFunc, target, format, pname) => {\n if (!isWebGL2(gl)) {\n switch (pname) {\n case GL.SAMPLES:\n return new Int32Array([0]);\n default:\n }\n }\n return gl.getInternalformatParameter(target, format, pname);\n },\n getTexParameter(gl, originalFunc, target, pname) {\n switch (pname) {\n case GL.TEXTURE_MAX_ANISOTROPY_EXT:\n const {extensions} = gl.luma;\n const ext = extensions[EXT_texture_filter_anisotropic];\n pname = (ext && ext.TEXTURE_MAX_ANISOTROPY_EXT) || GL.TEXTURE_MAX_ANISOTROPY_EXT;\n break;\n default:\n }\n return originalFunc(target, pname);\n },\n getParameter: getParameterPolyfill,\n hint(gl, originalFunc, pname, value) {\n // TODO - handle GL.FRAGMENT_SHADER_DERIVATIVE_HINT:\n // switch (pname) {\n // case GL.FRAGMENT_SHADER_DERIVATIVE_HINT:\n // }\n return originalFunc(pname, value);\n }\n};\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeys = require('./_baseKeys'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nmodule.exports = keys;\n","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck;","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nmodule.exports = _createClass;","var assignValue = require('./_assignValue'),\n baseAssignValue = require('./_baseAssignValue');\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nmodule.exports = copyObject;\n","var isObject = require('./_is-object');\nmodule.exports = function (it) {\n if (!isObject(it)) throw TypeError(it + ' is not an object!');\n return it;\n};\n","module.exports = function (exec) {\n try {\n return !!exec();\n } catch (e) {\n return true;\n }\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n// http://en.wikipedia.org/wiki/Haversine_formula\n// http://www.movable-type.co.uk/scripts/latlong.html\nvar helpers_1 = require(\"@turf/helpers\");\nvar invariant_1 = require(\"@turf/invariant\");\n/**\n * Takes a {@link Point} and calculates the location of a destination point given a distance in\n * degrees, radians, miles, or kilometers; and bearing in degrees.\n * This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.\n *\n * @name destination\n * @param {Coord} origin starting point\n * @param {number} distance distance from the origin point\n * @param {number} bearing ranging from -180 to 180\n * @param {Object} [options={}] Optional parameters\n * @param {string} [options.units='kilometers'] miles, kilometers, degrees, or radians\n * @param {Object} [options.properties={}] Translate properties to Point\n * @returns {Feature} destination point\n * @example\n * var point = turf.point([-75.343, 39.984]);\n * var distance = 50;\n * var bearing = 90;\n * var options = {units: 'miles'};\n *\n * var destination = turf.destination(point, distance, bearing, options);\n *\n * //addToMap\n * var addToMap = [point, destination]\n * destination.properties['marker-color'] = '#f00';\n * point.properties['marker-color'] = '#0f0';\n */\nfunction destination(origin, distance, bearing, options) {\n if (options === void 0) { options = {}; }\n // Handle input\n var coordinates1 = invariant_1.getCoord(origin);\n var longitude1 = helpers_1.degreesToRadians(coordinates1[0]);\n var latitude1 = helpers_1.degreesToRadians(coordinates1[1]);\n var bearingRad = helpers_1.degreesToRadians(bearing);\n var radians = helpers_1.lengthToRadians(distance, options.units);\n // Main\n var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(radians) +\n Math.cos(latitude1) * Math.sin(radians) * Math.cos(bearingRad));\n var longitude2 = longitude1 + Math.atan2(Math.sin(bearingRad) * Math.sin(radians) * Math.cos(latitude1), Math.cos(radians) - Math.sin(latitude1) * Math.sin(latitude2));\n var lng = helpers_1.radiansToDegrees(longitude2);\n var lat = helpers_1.radiansToDegrees(latitude2);\n return helpers_1.point([lng, lat], options.properties);\n}\nexports.default = destination;\n","import Event from 'events';\nimport uuid from 'uuid';\n\nimport Feature from './feature';\n\nexport default class NebulaLayer extends Event.EventEmitter {\n getData: () => Record[];\n toNebulaFeature: (data: Record) => Feature;\n id: string;\n helperLayers: Record[];\n\n // flags\n usesMapEvents = false;\n enablePicking = false;\n enableSelection = false;\n //\n\n constructor({ getData, on, toNebulaFeature }: Record) {\n super();\n this.id = uuid.v4();\n this.getData = getData;\n this.toNebulaFeature = toNebulaFeature;\n this.helperLayers = [];\n\n if (on) {\n // @ts-ignore\n Object.keys(on).forEach((key) => this.on(key, on[key]));\n }\n }\n\n render(config: Record): unknown {\n return null;\n }\n}\n","import {\n ClickEvent,\n StartDraggingEvent,\n StopDraggingEvent,\n PointerMoveEvent,\n ModeProps,\n GuideFeatureCollection,\n TentativeFeature,\n} from '../types';\nimport { Polygon, FeatureCollection, FeatureOf, Position } from '../geojson-types';\nimport { GeoJsonEditMode } from './geojson-edit-mode';\n\nexport class TwoClickPolygonMode extends GeoJsonEditMode {\n handleClick(event: ClickEvent, props: ModeProps) {\n if (props.modeConfig && props.modeConfig.dragToDraw) {\n // handled in drag handlers\n return;\n }\n\n this.addClickSequence(event);\n\n this.checkAndFinishPolygon(props);\n }\n\n handleStartDragging(event: StartDraggingEvent, props: ModeProps): void {\n if (!props.modeConfig || !props.modeConfig.dragToDraw) {\n // handled in click handlers\n return;\n }\n\n this.addClickSequence(event);\n event.cancelPan();\n }\n\n handleStopDragging(event: StopDraggingEvent, props: ModeProps): void {\n if (!props.modeConfig || !props.modeConfig.dragToDraw) {\n // handled in click handlers\n return;\n }\n this.addClickSequence(event);\n\n this.checkAndFinishPolygon(props);\n }\n\n checkAndFinishPolygon(props: ModeProps) {\n const clickSequence = this.getClickSequence();\n const tentativeFeature = this.getTentativeGuide(props);\n\n if (\n clickSequence.length > 1 &&\n tentativeFeature &&\n tentativeFeature.geometry.type === 'Polygon'\n ) {\n const feature: FeatureOf = {\n type: 'Feature',\n properties: {\n shape: tentativeFeature.properties.shape,\n },\n geometry: {\n type: 'Polygon',\n coordinates: tentativeFeature.geometry.coordinates,\n },\n };\n const editAction = this.getAddFeatureOrBooleanPolygonAction(feature, props);\n\n this.resetClickSequence();\n\n if (editAction) {\n props.onEdit(editAction);\n }\n }\n }\n\n getGuides(props: ModeProps): GuideFeatureCollection {\n const { lastPointerMoveEvent, modeConfig } = props;\n const clickSequence = this.getClickSequence();\n\n const guides: GuideFeatureCollection = {\n type: 'FeatureCollection',\n features: [],\n };\n\n if (clickSequence.length === 0) {\n // nothing to do yet\n return guides;\n }\n\n const corner1 = clickSequence[0];\n const corner2 = lastPointerMoveEvent.mapCoords;\n\n const polygon = this.getTwoClickPolygon(corner1, corner2, modeConfig);\n if (polygon) {\n guides.features.push({\n type: 'Feature',\n properties: {\n shape: polygon.properties && polygon.properties.shape,\n guideType: 'tentative',\n },\n geometry: polygon.geometry,\n });\n }\n\n return guides;\n }\n\n getTwoClickPolygon(\n coord1: Position,\n coord2: Position,\n modeConfig: any\n ): FeatureOf | null | undefined {\n return null;\n }\n\n handlePointerMove(event: PointerMoveEvent, props: ModeProps) {\n props.onUpdateCursor('cell');\n super.handlePointerMove(event, props);\n }\n\n createTentativeFeature(props: ModeProps): TentativeFeature {\n const { lastPointerMoveEvent } = props;\n const clickSequence = this.getClickSequence();\n\n const lastCoords = lastPointerMoveEvent ? [lastPointerMoveEvent.mapCoords] : [];\n\n let tentativeFeature;\n if (clickSequence.length === 1) {\n tentativeFeature = this.getTwoClickPolygon(clickSequence[0], lastCoords[0], props.modeConfig);\n }\n\n return tentativeFeature;\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar meta_1 = require(\"@turf/meta\");\nvar helpers_1 = require(\"@turf/helpers\");\n/**\n * Takes one or more features and calculates the centroid using the mean of all vertices.\n * This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons.\n *\n * @name centroid\n * @param {GeoJSON} geojson GeoJSON to be centered\n * @param {Object} [options={}] Optional Parameters\n * @param {Object} [options.properties={}] an Object that is used as the {@link Feature}'s properties\n * @returns {Feature} the centroid of the input features\n * @example\n * var polygon = turf.polygon([[[-81, 41], [-88, 36], [-84, 31], [-80, 33], [-77, 39], [-81, 41]]]);\n *\n * var centroid = turf.centroid(polygon);\n *\n * //addToMap\n * var addToMap = [polygon, centroid]\n */\nfunction centroid(geojson, options) {\n if (options === void 0) { options = {}; }\n var xSum = 0;\n var ySum = 0;\n var len = 0;\n meta_1.coordEach(geojson, function (coord) {\n xSum += coord[0];\n ySum += coord[1];\n len++;\n });\n return helpers_1.point([xSum / len, ySum / len], options.properties);\n}\nexports.default = centroid;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar invariant_1 = require(\"@turf/invariant\");\n// http://en.wikipedia.org/wiki/Even%E2%80%93odd_rule\n// modified from: https://github.com/substack/point-in-polygon/blob/master/index.js\n// which was modified from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html\n/**\n * Takes a {@link Point} and a {@link Polygon} or {@link MultiPolygon} and determines if the point\n * resides inside the polygon. The polygon can be convex or concave. The function accounts for holes.\n *\n * @name booleanPointInPolygon\n * @param {Coord} point input point\n * @param {Feature} polygon input polygon or multipolygon\n * @param {Object} [options={}] Optional parameters\n * @param {boolean} [options.ignoreBoundary=false] True if polygon boundary should be ignored when determining if\n * the point is inside the polygon otherwise false.\n * @returns {boolean} `true` if the Point is inside the Polygon; `false` if the Point is not inside the Polygon\n * @example\n * var pt = turf.point([-77, 44]);\n * var poly = turf.polygon([[\n * [-81, 41],\n * [-81, 47],\n * [-72, 47],\n * [-72, 41],\n * [-81, 41]\n * ]]);\n *\n * turf.booleanPointInPolygon(pt, poly);\n * //= true\n */\nfunction booleanPointInPolygon(point, polygon, options) {\n if (options === void 0) { options = {}; }\n // validation\n if (!point) {\n throw new Error(\"point is required\");\n }\n if (!polygon) {\n throw new Error(\"polygon is required\");\n }\n var pt = invariant_1.getCoord(point);\n var geom = invariant_1.getGeom(polygon);\n var type = geom.type;\n var bbox = polygon.bbox;\n var polys = geom.coordinates;\n // Quick elimination if point is not inside bbox\n if (bbox && inBBox(pt, bbox) === false) {\n return false;\n }\n // normalize to multipolygon\n if (type === \"Polygon\") {\n polys = [polys];\n }\n var insidePoly = false;\n for (var i = 0; i < polys.length && !insidePoly; i++) {\n // check if it is in the outer ring first\n if (inRing(pt, polys[i][0], options.ignoreBoundary)) {\n var inHole = false;\n var k = 1;\n // check for the point in any of the holes\n while (k < polys[i].length && !inHole) {\n if (inRing(pt, polys[i][k], !options.ignoreBoundary)) {\n inHole = true;\n }\n k++;\n }\n if (!inHole) {\n insidePoly = true;\n }\n }\n }\n return insidePoly;\n}\nexports.default = booleanPointInPolygon;\n/**\n * inRing\n *\n * @private\n * @param {Array} pt [x,y]\n * @param {Array>} ring [[x,y], [x,y],..]\n * @param {boolean} ignoreBoundary ignoreBoundary\n * @returns {boolean} inRing\n */\nfunction inRing(pt, ring, ignoreBoundary) {\n var isInside = false;\n if (ring[0][0] === ring[ring.length - 1][0] && ring[0][1] === ring[ring.length - 1][1]) {\n ring = ring.slice(0, ring.length - 1);\n }\n for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n var xi = ring[i][0];\n var yi = ring[i][1];\n var xj = ring[j][0];\n var yj = ring[j][1];\n var onBoundary = (pt[1] * (xi - xj) + yi * (xj - pt[0]) + yj * (pt[0] - xi) === 0) &&\n ((xi - pt[0]) * (xj - pt[0]) <= 0) && ((yi - pt[1]) * (yj - pt[1]) <= 0);\n if (onBoundary) {\n return !ignoreBoundary;\n }\n var intersect = ((yi > pt[1]) !== (yj > pt[1])) &&\n (pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi);\n if (intersect) {\n isInside = !isInside;\n }\n }\n return isInside;\n}\n/**\n * inBBox\n *\n * @private\n * @param {Position} pt point [x,y]\n * @param {BBox} bbox BBox [west, south, east, north]\n * @returns {boolean} true/false if point is inside BBox\n */\nfunction inBBox(pt, bbox) {\n return bbox[0] <= pt[0] &&\n bbox[1] <= pt[1] &&\n bbox[2] >= pt[0] &&\n bbox[3] >= pt[1];\n}\n","export function getFirstCharacters(data, length = 5): string {\n if (typeof data === 'string') {\n return data.slice(0, length);\n } else if (ArrayBuffer.isView(data)) {\n // Typed Arrays can have offsets into underlying buffer\n return getMagicString(data.buffer, data.byteOffset, length);\n } else if (data instanceof ArrayBuffer) {\n const byteOffset = 0;\n return getMagicString(data, byteOffset, length);\n }\n return '';\n}\n\nexport function getMagicString(\n arrayBuffer: ArrayBuffer,\n byteOffset: number,\n length: number\n): string {\n if (arrayBuffer.byteLength <= byteOffset + length) {\n return '';\n }\n const dataView = new DataView(arrayBuffer);\n let magic = '';\n for (let i = 0; i < length; i++) {\n magic += String.fromCharCode(dataView.getUint8(byteOffset + i));\n }\n return magic;\n}\n","var isProduction = process.env.NODE_ENV === 'production';\nfunction warning(condition, message) {\n if (!isProduction) {\n if (condition) {\n return;\n }\n\n var text = \"Warning: \" + message;\n\n if (typeof console !== 'undefined') {\n console.warn(text);\n }\n\n try {\n throw Error(text);\n } catch (x) {}\n }\n}\n\nexport default warning;\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// @ts-nocheck\n\n/**\n * Common environment setup\n */\nimport {window, process, isBrowser} from './globals';\n\nexport default function getHiResTimestamp() {\n let timestamp;\n // Get best timer available.\n if (isBrowser && window.performance) {\n timestamp = window.performance.now();\n } else if (process.hrtime) {\n const timeParts = process.hrtime();\n timestamp = timeParts[0] * 1000 + timeParts[1] / 1e6;\n } else {\n timestamp = Date.now();\n }\n\n return timestamp;\n}\n","import {PROP_SYMBOLS} from './constants';\n\nconst {COMPONENT} = PROP_SYMBOLS;\n\nexport function validateProps(props) {\n const propTypes = getPropTypes(props);\n\n for (const propName in propTypes) {\n const propType = propTypes[propName];\n const {validate} = propType;\n if (validate && !validate(props[propName], propType)) {\n throw new Error(`Invalid prop ${propName}: ${props[propName]}`);\n }\n }\n}\n\n// Returns an object with \"change flags\", either false or strings indicating reason for change\nexport function diffProps(props, oldProps) {\n // First check if any props have changed (ignore props that will be examined separately)\n const propsChangedReason = compareProps({\n newProps: props,\n oldProps,\n propTypes: getPropTypes(props),\n ignoreProps: {data: null, updateTriggers: null, extensions: null, transitions: null}\n });\n\n // Now check if any data related props have changed\n const dataChangedReason = diffDataProps(props, oldProps);\n\n // Check update triggers to determine if any attributes need regeneration\n // Note - if data has changed, all attributes will need regeneration, so skip this step\n let updateTriggersChangedReason = false;\n if (!dataChangedReason) {\n updateTriggersChangedReason = diffUpdateTriggers(props, oldProps);\n }\n\n return {\n dataChanged: dataChangedReason,\n propsChanged: propsChangedReason,\n updateTriggersChanged: updateTriggersChangedReason,\n extensionsChanged: diffExtensions(props, oldProps),\n transitionsChanged: diffTransitions(props, oldProps)\n };\n}\n\nfunction diffTransitions(props, oldProps) {\n if (!props.transitions) {\n return null;\n }\n const result = {};\n const propTypes = getPropTypes(props);\n\n for (const key in props.transitions) {\n const propType = propTypes[key];\n const type = propType && propType.type;\n const isTransitionable = type === 'number' || type === 'color' || type === 'array';\n if (isTransitionable && comparePropValues(props[key], oldProps[key], propType)) {\n result[key] = true;\n }\n }\n return result;\n}\n\n/**\n * Performs equality by iterating through keys on an object and returning false\n * when any key has values which are not strictly equal between the arguments.\n * @param {Object} opt.oldProps - object with old key/value pairs\n * @param {Object} opt.newProps - object with new key/value pairs\n * @param {Object} opt.ignoreProps={} - object, keys that should not be compared\n * @returns {null|String} - null when values of all keys are strictly equal.\n * if unequal, returns a string explaining what changed.\n */\n/* eslint-disable max-statements, max-depth, complexity */\n/*\n * Note: for better performance, this function assumes that both oldProps and newProps\n inherit the same prototype (defaultProps). That is, if neither object contains own\n property , assume `oldProps.` and `newProps.` are equal.\n */\nexport function compareProps({\n newProps,\n oldProps,\n ignoreProps = {},\n propTypes = {},\n triggerName = 'props'\n} = {}) {\n // shallow equality => deep equality\n if (oldProps === newProps) {\n return null;\n }\n\n // TODO - do we need these checks? Should never happen...\n if (typeof newProps !== 'object' || newProps === null) {\n return `${triggerName} changed shallowly`;\n }\n\n if (typeof oldProps !== 'object' || oldProps === null) {\n return `${triggerName} changed shallowly`;\n }\n\n // Compare explicitly defined new props against old/default values\n for (const key of Object.keys(newProps)) {\n if (!(key in ignoreProps)) {\n if (!(key in oldProps)) {\n return `${triggerName}.${key} added`;\n }\n const changed = comparePropValues(newProps[key], oldProps[key], propTypes[key]);\n if (changed) {\n return `${triggerName}.${key} ${changed}`;\n }\n }\n }\n\n // Test if any old props have been dropped\n for (const key of Object.keys(oldProps)) {\n if (!(key in ignoreProps)) {\n if (!(key in newProps)) {\n return `${triggerName}.${key} dropped`;\n }\n if (!Object.hasOwnProperty.call(newProps, key)) {\n // Compare dropped old prop against default value\n const changed = comparePropValues(newProps[key], oldProps[key], propTypes[key]);\n if (changed) {\n return `${triggerName}.${key} ${changed}`;\n }\n }\n }\n }\n\n return null;\n}\n/* eslint-enable max-statements, max-depth, complexity */\n\n// HELPERS\nfunction comparePropValues(newProp, oldProp, propType) {\n // If prop type has an equal function, invoke it\n let equal = propType && propType.equal;\n if (equal && !equal(newProp, oldProp, propType)) {\n return 'changed deeply';\n }\n\n if (!equal) {\n // If object has an equals function, invoke it\n equal = newProp && oldProp && newProp.equals;\n if (equal && !equal.call(newProp, oldProp)) {\n return 'changed deeply';\n }\n }\n\n if (!equal && oldProp !== newProp) {\n return 'changed shallowly';\n }\n\n return null;\n}\n\n// The comparison of the data prop requires special handling\n// the dataComparator should be used if supplied\nfunction diffDataProps(props, oldProps) {\n if (oldProps === null) {\n return 'oldProps is null, initial diff';\n }\n\n let dataChanged = null;\n // Support optional app defined comparison of data\n const {dataComparator, _dataDiff} = props;\n if (dataComparator) {\n if (!dataComparator(props.data, oldProps.data)) {\n dataChanged = 'Data comparator detected a change';\n }\n // Otherwise, do a shallow equal on props\n } else if (props.data !== oldProps.data) {\n dataChanged = 'A new data container was supplied';\n }\n if (dataChanged && _dataDiff) {\n dataChanged = _dataDiff(props.data, oldProps.data) || dataChanged;\n }\n\n return dataChanged;\n}\n\n// Checks if any update triggers have changed\n// also calls callback to invalidate attributes accordingly.\nfunction diffUpdateTriggers(props, oldProps) {\n if (oldProps === null) {\n return 'oldProps is null, initial diff';\n }\n\n // If the 'all' updateTrigger fires, ignore testing others\n if ('all' in props.updateTriggers) {\n const diffReason = diffUpdateTrigger(props, oldProps, 'all');\n if (diffReason) {\n return {all: true};\n }\n }\n\n const triggerChanged = {};\n let reason = false;\n // If the 'all' updateTrigger didn't fire, need to check all others\n for (const triggerName in props.updateTriggers) {\n if (triggerName !== 'all') {\n const diffReason = diffUpdateTrigger(props, oldProps, triggerName);\n if (diffReason) {\n triggerChanged[triggerName] = true;\n reason = triggerChanged;\n }\n }\n }\n\n return reason;\n}\n\n// Returns true if any extensions have changed\nfunction diffExtensions(props, oldProps) {\n if (oldProps === null) {\n return 'oldProps is null, initial diff';\n }\n\n const oldExtensions = oldProps.extensions;\n const {extensions} = props;\n\n if (extensions === oldExtensions) {\n return false;\n }\n if (extensions.length !== oldExtensions.length) {\n return true;\n }\n for (let i = 0; i < extensions.length; i++) {\n if (!extensions[i].equals(oldExtensions[i])) {\n return true;\n }\n }\n return false;\n}\n\nfunction diffUpdateTrigger(props, oldProps, triggerName) {\n let newTriggers = props.updateTriggers[triggerName];\n newTriggers = newTriggers === undefined || newTriggers === null ? {} : newTriggers;\n let oldTriggers = oldProps.updateTriggers[triggerName];\n oldTriggers = oldTriggers === undefined || oldTriggers === null ? {} : oldTriggers;\n const diffReason = compareProps({\n oldProps: oldTriggers,\n newProps: newTriggers,\n triggerName\n });\n return diffReason;\n}\n\nfunction getPropTypes(props) {\n const layer = props[COMPONENT];\n const LayerType = layer && layer.constructor;\n return LayerType ? LayerType._propTypes : {};\n}\n","import Transition from '../transitions/transition';\n\nconst noop = () => {};\n\nexport const TRANSITION_EVENTS = {\n BREAK: 1,\n SNAP_TO_END: 2,\n IGNORE: 3\n};\n\nconst DEFAULT_PROPS = {\n transitionEasing: t => t,\n transitionInterruption: TRANSITION_EVENTS.BREAK,\n onTransitionStart: noop,\n onTransitionInterrupt: noop,\n onTransitionEnd: noop\n};\n\nexport default class TransitionManager {\n constructor(ControllerState, props = {}) {\n this.ControllerState = ControllerState;\n this.props = {...DEFAULT_PROPS, ...props};\n this.propsInTransition = null;\n this.transition = new Transition(props.timeline);\n\n this.onViewStateChange = props.onViewStateChange || noop;\n this.onStateChange = props.onStateChange || noop;\n\n this._onTransitionUpdate = this._onTransitionUpdate.bind(this);\n }\n\n finalize() {\n this.transition.cancel();\n }\n\n // Returns current transitioned viewport.\n getViewportInTransition() {\n return this.propsInTransition;\n }\n\n // Process the vewiport change, either ignore or trigger a new transition.\n // Return true if a new transition is triggered, false otherwise.\n processViewStateChange(nextProps) {\n let transitionTriggered = false;\n const currentProps = this.props;\n // Set this.props here as '_triggerTransition' calls '_updateViewport' that uses this.props.\n nextProps = {...DEFAULT_PROPS, ...nextProps};\n this.props = nextProps;\n\n // NOTE: Be cautious re-ordering statements in this function.\n if (this._shouldIgnoreViewportChange(currentProps, nextProps)) {\n return transitionTriggered;\n }\n\n if (this._isTransitionEnabled(nextProps)) {\n const {interruption, endProps} = this.transition.settings;\n const startProps = {\n ...currentProps,\n ...(interruption === TRANSITION_EVENTS.SNAP_TO_END\n ? endProps\n : this.propsInTransition || currentProps)\n };\n\n this._triggerTransition(startProps, nextProps);\n\n transitionTriggered = true;\n } else {\n this.transition.cancel();\n }\n\n return transitionTriggered;\n }\n\n updateTransition() {\n this.transition.update();\n }\n\n // Helper methods\n\n _isTransitionEnabled(props) {\n const {transitionDuration, transitionInterpolator} = props;\n return (\n (transitionDuration > 0 || transitionDuration === 'auto') && Boolean(transitionInterpolator)\n );\n }\n\n _isUpdateDueToCurrentTransition(props) {\n if (this.transition.inProgress) {\n return this.transition.settings.interpolator.arePropsEqual(props, this.propsInTransition);\n }\n return false;\n }\n\n _shouldIgnoreViewportChange(currentProps, nextProps) {\n if (this.transition.inProgress) {\n // Ignore update if it is requested to be ignored\n return (\n this.transition.settings.interruption === TRANSITION_EVENTS.IGNORE ||\n // Ignore update if it is due to current active transition.\n this._isUpdateDueToCurrentTransition(nextProps)\n );\n } else if (this._isTransitionEnabled(nextProps)) {\n // Ignore if none of the viewport props changed.\n return nextProps.transitionInterpolator.arePropsEqual(currentProps, nextProps);\n }\n return true;\n }\n\n _triggerTransition(startProps, endProps) {\n const startViewstate = new this.ControllerState(startProps);\n const endViewStateProps = new this.ControllerState(endProps).shortestPathFrom(startViewstate);\n\n // update transitionDuration for 'auto' mode\n const {transitionInterpolator} = endProps;\n const duration = transitionInterpolator.getDuration\n ? transitionInterpolator.getDuration(startProps, endProps)\n : endProps.transitionDuration;\n\n if (duration === 0) {\n return;\n }\n\n const initialProps = endProps.transitionInterpolator.initializeProps(\n startProps,\n endViewStateProps\n );\n\n this.propsInTransition = {};\n this.duration = duration;\n this.transition.start({\n duration,\n easing: endProps.transitionEasing,\n interpolator: endProps.transitionInterpolator,\n interruption: endProps.transitionInterruption,\n\n startProps: initialProps.start,\n endProps: initialProps.end,\n\n onStart: endProps.onTransitionStart,\n onUpdate: this._onTransitionUpdate,\n onInterrupt: this._onTransitionEnd(endProps.onTransitionInterrupt),\n onEnd: this._onTransitionEnd(endProps.onTransitionEnd)\n });\n\n this.onStateChange({inTransition: true});\n\n this.updateTransition();\n }\n\n _onTransitionEnd(callback) {\n return transition => {\n this.propsInTransition = null;\n\n this.onStateChange({\n inTransition: false,\n isZooming: false,\n isPanning: false,\n isRotating: false\n });\n\n callback(transition);\n };\n }\n\n _onTransitionUpdate(transition) {\n // NOTE: Be cautious re-ordering statements in this function.\n const {\n time,\n settings: {interpolator, startProps, endProps, duration, easing}\n } = transition;\n const t = easing(time / duration);\n const viewport = interpolator.interpolateProps(startProps, endProps, t);\n\n // This gurantees all props (e.g. bearing, longitude) are normalized\n // So when viewports are compared they are in same range.\n this.propsInTransition = new this.ControllerState({\n ...this.props,\n ...viewport\n }).getViewportProps();\n\n this.onViewStateChange({\n viewState: this.propsInTransition,\n oldViewState: this.props\n });\n }\n}\n","import TransitionInterpolator from './transition-interpolator';\nimport {lerp} from 'math.gl';\n\nconst DEFAULT_PROPS = ['longitude', 'latitude', 'zoom', 'bearing', 'pitch'];\nconst DEFAULT_REQUIRED_PROPS = ['longitude', 'latitude', 'zoom'];\n\n/**\n * Performs linear interpolation of two view states.\n */\nexport default class LinearInterpolator extends TransitionInterpolator {\n /**\n * @param {Object} opts\n * @param {Array} opts.transitionProps - list of props to apply linear transition to.\n * @param {Array} opts.around - a screen point to zoom/rotate around.\n * @param {Function} opts.makeViewport - construct a viewport instance with given props.\n */\n constructor(opts = {}) {\n // Backward compatibility\n const transitionProps = Array.isArray(opts) ? opts : opts.transitionProps;\n super(\n transitionProps || {\n compare: DEFAULT_PROPS,\n extract: DEFAULT_PROPS,\n required: DEFAULT_REQUIRED_PROPS\n }\n );\n this.opts = opts;\n }\n\n initializeProps(startProps, endProps) {\n const result = super.initializeProps(startProps, endProps);\n\n const {makeViewport, around} = this.opts;\n if (makeViewport && around) {\n const startViewport = makeViewport(startProps);\n const endViewport = makeViewport(endProps);\n const aroundPosition = startViewport.unproject(around);\n result.start.around = around;\n Object.assign(result.end, {\n around: endViewport.project(aroundPosition),\n aroundPosition,\n width: endProps.width,\n height: endProps.height\n });\n }\n\n return result;\n }\n\n interpolateProps(startProps, endProps, t) {\n const propsInTransition = {};\n for (const key of this._propsToExtract) {\n propsInTransition[key] = lerp(startProps[key] || 0, endProps[key] || 0, t);\n }\n\n if (endProps.aroundPosition) {\n // Linear transition should be performed in common space\n const viewport = this.opts.makeViewport({...endProps, ...propsInTransition});\n Object.assign(\n propsInTransition,\n viewport.panByPosition(\n endProps.aroundPosition,\n // anchor point in current screen coordinates\n lerp(startProps.around, endProps.around, t)\n )\n );\n }\n return propsInTransition;\n }\n}\n","var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n\n// ================= Transition =================\n// Event wrapper. Copy from react source code\nfunction makePrefixMap(styleProp, eventName) {\n var prefixes = {};\n\n prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();\n prefixes['Webkit' + styleProp] = 'webkit' + eventName;\n prefixes['Moz' + styleProp] = 'moz' + eventName;\n prefixes['ms' + styleProp] = 'MS' + eventName;\n prefixes['O' + styleProp] = 'o' + eventName.toLowerCase();\n\n return prefixes;\n}\n\nexport function getVendorPrefixes(domSupport, win) {\n var prefixes = {\n animationend: makePrefixMap('Animation', 'AnimationEnd'),\n transitionend: makePrefixMap('Transition', 'TransitionEnd')\n };\n\n if (domSupport) {\n if (!('AnimationEvent' in win)) {\n delete prefixes.animationend.animation;\n }\n\n if (!('TransitionEvent' in win)) {\n delete prefixes.transitionend.transition;\n }\n }\n\n return prefixes;\n}\n\nvar vendorPrefixes = getVendorPrefixes(canUseDOM, typeof window !== 'undefined' ? window : {});\n\nvar style = {};\n\nif (canUseDOM) {\n style = document.createElement('div').style;\n}\n\nvar prefixedEventNames = {};\n\nexport function getVendorPrefixedEventName(eventName) {\n if (prefixedEventNames[eventName]) {\n return prefixedEventNames[eventName];\n }\n\n var prefixMap = vendorPrefixes[eventName];\n\n if (prefixMap) {\n var stylePropList = Object.keys(prefixMap);\n var len = stylePropList.length;\n for (var i = 0; i < len; i += 1) {\n var styleProp = stylePropList[i];\n if (Object.prototype.hasOwnProperty.call(prefixMap, styleProp) && styleProp in style) {\n prefixedEventNames[eventName] = prefixMap[styleProp];\n return prefixedEventNames[eventName];\n }\n }\n }\n\n return '';\n}\n\nexport var animationEndName = getVendorPrefixedEventName('animationend');\nexport var transitionEndName = getVendorPrefixedEventName('transitionend');\nexport var supportTransition = !!(animationEndName && transitionEndName);\n\nexport function getTransitionName(transitionName, transitionType) {\n if (!transitionName) return null;\n\n if (typeof transitionName === 'object') {\n var type = transitionType.replace(/-\\w/g, function (match) {\n return match[1].toUpperCase();\n });\n return transitionName[type];\n }\n\n return transitionName + '-' + transitionType;\n}","import _defineProperty from 'babel-runtime/helpers/defineProperty';\nimport _extends from 'babel-runtime/helpers/extends';\nimport _classCallCheck from 'babel-runtime/helpers/classCallCheck';\nimport _createClass from 'babel-runtime/helpers/createClass';\nimport _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';\nimport _inherits from 'babel-runtime/helpers/inherits';\n/* eslint-disable react/default-props-match-prop-types, react/no-multi-comp */\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport { polyfill } from 'react-lifecycles-compat';\nimport findDOMNode from 'rc-util/es/Dom/findDOMNode';\nimport classNames from 'classnames';\nimport raf from 'raf';\nimport { getTransitionName, animationEndName, transitionEndName, supportTransition } from './util/motion';\n\nvar STATUS_NONE = 'none';\nvar STATUS_APPEAR = 'appear';\nvar STATUS_ENTER = 'enter';\nvar STATUS_LEAVE = 'leave';\n\nexport var MotionPropTypes = {\n eventProps: PropTypes.object, // Internal usage. Only pass by CSSMotionList\n visible: PropTypes.bool,\n children: PropTypes.func,\n motionName: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),\n motionAppear: PropTypes.bool,\n motionEnter: PropTypes.bool,\n motionLeave: PropTypes.bool,\n motionLeaveImmediately: PropTypes.bool, // Trigger leave motion immediately\n removeOnLeave: PropTypes.bool,\n leavedClassName: PropTypes.string,\n onAppearStart: PropTypes.func,\n onAppearActive: PropTypes.func,\n onAppearEnd: PropTypes.func,\n onEnterStart: PropTypes.func,\n onEnterActive: PropTypes.func,\n onEnterEnd: PropTypes.func,\n onLeaveStart: PropTypes.func,\n onLeaveActive: PropTypes.func,\n onLeaveEnd: PropTypes.func\n};\n\n/**\n * `transitionSupport` is used for none transition test case.\n * Default we use browser transition event support check.\n */\nexport function genCSSMotion(config) {\n var transitionSupport = config;\n var forwardRef = !!React.forwardRef;\n\n if (typeof config === 'object') {\n transitionSupport = config.transitionSupport;\n forwardRef = 'forwardRef' in config ? config.forwardRef : forwardRef;\n }\n\n function isSupportTransition(props) {\n return !!(props.motionName && transitionSupport);\n }\n\n var CSSMotion = function (_React$Component) {\n _inherits(CSSMotion, _React$Component);\n\n function CSSMotion() {\n _classCallCheck(this, CSSMotion);\n\n var _this = _possibleConstructorReturn(this, (CSSMotion.__proto__ || Object.getPrototypeOf(CSSMotion)).call(this));\n\n _this.onDomUpdate = function () {\n var _this$state = _this.state,\n status = _this$state.status,\n newStatus = _this$state.newStatus;\n var _this$props = _this.props,\n onAppearStart = _this$props.onAppearStart,\n onEnterStart = _this$props.onEnterStart,\n onLeaveStart = _this$props.onLeaveStart,\n onAppearActive = _this$props.onAppearActive,\n onEnterActive = _this$props.onEnterActive,\n onLeaveActive = _this$props.onLeaveActive,\n motionAppear = _this$props.motionAppear,\n motionEnter = _this$props.motionEnter,\n motionLeave = _this$props.motionLeave;\n\n\n if (!isSupportTransition(_this.props)) {\n return;\n }\n\n // Event injection\n var $ele = _this.getElement();\n if (_this.$cacheEle !== $ele) {\n _this.removeEventListener(_this.$cacheEle);\n _this.addEventListener($ele);\n _this.$cacheEle = $ele;\n }\n\n // Init status\n if (newStatus && status === STATUS_APPEAR && motionAppear) {\n _this.updateStatus(onAppearStart, null, null, function () {\n _this.updateActiveStatus(onAppearActive, STATUS_APPEAR);\n });\n } else if (newStatus && status === STATUS_ENTER && motionEnter) {\n _this.updateStatus(onEnterStart, null, null, function () {\n _this.updateActiveStatus(onEnterActive, STATUS_ENTER);\n });\n } else if (newStatus && status === STATUS_LEAVE && motionLeave) {\n _this.updateStatus(onLeaveStart, null, null, function () {\n _this.updateActiveStatus(onLeaveActive, STATUS_LEAVE);\n });\n }\n };\n\n _this.onMotionEnd = function (event) {\n var _this$state2 = _this.state,\n status = _this$state2.status,\n statusActive = _this$state2.statusActive;\n var _this$props2 = _this.props,\n onAppearEnd = _this$props2.onAppearEnd,\n onEnterEnd = _this$props2.onEnterEnd,\n onLeaveEnd = _this$props2.onLeaveEnd;\n\n if (status === STATUS_APPEAR && statusActive) {\n _this.updateStatus(onAppearEnd, { status: STATUS_NONE }, event);\n } else if (status === STATUS_ENTER && statusActive) {\n _this.updateStatus(onEnterEnd, { status: STATUS_NONE }, event);\n } else if (status === STATUS_LEAVE && statusActive) {\n _this.updateStatus(onLeaveEnd, { status: STATUS_NONE }, event);\n }\n };\n\n _this.setNodeRef = function (node) {\n var internalRef = _this.props.internalRef;\n\n _this.node = node;\n\n if (typeof internalRef === 'function') {\n internalRef(node);\n } else if (internalRef && 'current' in internalRef) {\n internalRef.current = node;\n }\n };\n\n _this.getElement = function () {\n return findDOMNode(_this.node || _this);\n };\n\n _this.addEventListener = function ($ele) {\n if (!$ele) return;\n\n $ele.addEventListener(transitionEndName, _this.onMotionEnd);\n $ele.addEventListener(animationEndName, _this.onMotionEnd);\n };\n\n _this.removeEventListener = function ($ele) {\n if (!$ele) return;\n\n $ele.removeEventListener(transitionEndName, _this.onMotionEnd);\n $ele.removeEventListener(animationEndName, _this.onMotionEnd);\n };\n\n _this.updateStatus = function (styleFunc, additionalState, event, callback) {\n var statusStyle = styleFunc ? styleFunc(_this.getElement(), event) : null;\n\n if (statusStyle === false || _this._destroyed) return;\n\n var nextStep = void 0;\n if (callback) {\n nextStep = function nextStep() {\n _this.nextFrame(callback);\n };\n }\n\n _this.setState(_extends({\n statusStyle: typeof statusStyle === 'object' ? statusStyle : null,\n newStatus: false\n }, additionalState), nextStep); // Trigger before next frame & after `componentDidMount`\n };\n\n _this.updateActiveStatus = function (styleFunc, currentStatus) {\n // `setState` use `postMessage` to trigger at the end of frame.\n // Let's use requestAnimationFrame to update new state in next frame.\n _this.nextFrame(function () {\n var status = _this.state.status;\n\n if (status !== currentStatus) return;\n\n _this.updateStatus(styleFunc, { statusActive: true });\n });\n };\n\n _this.nextFrame = function (func) {\n _this.cancelNextFrame();\n _this.raf = raf(func);\n };\n\n _this.cancelNextFrame = function () {\n if (_this.raf) {\n raf.cancel(_this.raf);\n _this.raf = null;\n }\n };\n\n _this.state = {\n status: STATUS_NONE,\n statusActive: false,\n newStatus: false,\n statusStyle: null\n };\n _this.$cacheEle = null;\n _this.node = null;\n _this.raf = null;\n return _this;\n }\n\n _createClass(CSSMotion, [{\n key: 'componentDidMount',\n value: function componentDidMount() {\n this.onDomUpdate();\n }\n }, {\n key: 'componentDidUpdate',\n value: function componentDidUpdate() {\n this.onDomUpdate();\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n this._destroyed = true;\n this.removeEventListener(this.$cacheEle);\n this.cancelNextFrame();\n }\n }, {\n key: 'render',\n value: function render() {\n var _classNames;\n\n var _state = this.state,\n status = _state.status,\n statusActive = _state.statusActive,\n statusStyle = _state.statusStyle;\n var _props = this.props,\n children = _props.children,\n motionName = _props.motionName,\n visible = _props.visible,\n removeOnLeave = _props.removeOnLeave,\n leavedClassName = _props.leavedClassName,\n eventProps = _props.eventProps;\n\n\n if (!children) return null;\n\n if (status === STATUS_NONE || !isSupportTransition(this.props)) {\n if (visible) {\n return children(_extends({}, eventProps), this.setNodeRef);\n } else if (!removeOnLeave) {\n return children(_extends({}, eventProps, { className: leavedClassName }), this.setNodeRef);\n }\n\n return null;\n }\n\n return children(_extends({}, eventProps, {\n className: classNames((_classNames = {}, _defineProperty(_classNames, getTransitionName(motionName, status), status !== STATUS_NONE), _defineProperty(_classNames, getTransitionName(motionName, status + '-active'), status !== STATUS_NONE && statusActive), _defineProperty(_classNames, motionName, typeof motionName === 'string'), _classNames)),\n style: statusStyle\n }), this.setNodeRef);\n }\n }], [{\n key: 'getDerivedStateFromProps',\n value: function getDerivedStateFromProps(props, _ref) {\n var prevProps = _ref.prevProps,\n prevStatus = _ref.status;\n\n if (!isSupportTransition(props)) return {};\n\n var visible = props.visible,\n motionAppear = props.motionAppear,\n motionEnter = props.motionEnter,\n motionLeave = props.motionLeave,\n motionLeaveImmediately = props.motionLeaveImmediately;\n\n var newState = {\n prevProps: props\n };\n\n // Clean up status if prop set to false\n if (prevStatus === STATUS_APPEAR && !motionAppear || prevStatus === STATUS_ENTER && !motionEnter || prevStatus === STATUS_LEAVE && !motionLeave) {\n newState.status = STATUS_NONE;\n newState.statusActive = false;\n newState.newStatus = false;\n }\n\n // Appear\n if (!prevProps && visible && motionAppear) {\n newState.status = STATUS_APPEAR;\n newState.statusActive = false;\n newState.newStatus = true;\n }\n\n // Enter\n if (prevProps && !prevProps.visible && visible && motionEnter) {\n newState.status = STATUS_ENTER;\n newState.statusActive = false;\n newState.newStatus = true;\n }\n\n // Leave\n if (prevProps && prevProps.visible && !visible && motionLeave || !prevProps && motionLeaveImmediately && !visible && motionLeave) {\n newState.status = STATUS_LEAVE;\n newState.statusActive = false;\n newState.newStatus = true;\n }\n\n return newState;\n }\n }]);\n\n return CSSMotion;\n }(React.Component);\n\n CSSMotion.propTypes = _extends({}, MotionPropTypes, {\n\n internalRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func])\n });\n CSSMotion.defaultProps = {\n visible: true,\n motionEnter: true,\n motionAppear: true,\n motionLeave: true,\n removeOnLeave: true\n };\n\n\n polyfill(CSSMotion);\n\n if (!forwardRef) {\n return CSSMotion;\n }\n\n return React.forwardRef(function (props, ref) {\n return React.createElement(CSSMotion, _extends({ internalRef: ref }, props));\n });\n}\n\nexport default genCSSMotion(supportTransition);","import _defineProperty from 'babel-runtime/helpers/defineProperty';\nimport _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';\nimport _extends from 'babel-runtime/helpers/extends';\nimport _classCallCheck from 'babel-runtime/helpers/classCallCheck';\nimport _createClass from 'babel-runtime/helpers/createClass';\nimport _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';\nimport _inherits from 'babel-runtime/helpers/inherits';\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport CSSMotion from 'rc-animate/es/CSSMotion';\nimport toArray from 'rc-util/es/Children/toArray';\nimport { polyfill } from 'react-lifecycles-compat';\nimport { nodeContextTypes } from './contextTypes';\nimport { getNodeChildren, getDataAndAria, mapChildren, warnOnlyTreeNode } from './util';\n\nvar ICON_OPEN = 'open';\nvar ICON_CLOSE = 'close';\n\nvar defaultTitle = '---';\n\nvar TreeNode = function (_React$Component) {\n _inherits(TreeNode, _React$Component);\n\n function TreeNode(props) {\n _classCallCheck(this, TreeNode);\n\n var _this = _possibleConstructorReturn(this, (TreeNode.__proto__ || Object.getPrototypeOf(TreeNode)).call(this, props));\n\n _initialiseProps.call(_this);\n\n _this.state = {\n dragNodeHighlight: false\n };\n return _this;\n }\n\n _createClass(TreeNode, [{\n key: 'getChildContext',\n value: function getChildContext() {\n return _extends({}, this.context, {\n rcTreeNode: {\n // onUpCheckConduct: this.onUpCheckConduct,\n }\n });\n }\n\n // Isomorphic needn't load data in server side\n\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n var eventKey = this.props.eventKey;\n var registerTreeNode = this.context.rcTree.registerTreeNode;\n\n\n this.syncLoadData(this.props);\n\n registerTreeNode(eventKey, this);\n }\n }, {\n key: 'componentDidUpdate',\n value: function componentDidUpdate() {\n this.syncLoadData(this.props);\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n var eventKey = this.props.eventKey;\n var registerTreeNode = this.context.rcTree.registerTreeNode;\n\n registerTreeNode(eventKey, null);\n }\n\n // Disabled item still can be switch\n\n\n // Drag usage\n\n }, {\n key: 'isSelectable',\n value: function isSelectable() {\n var selectable = this.props.selectable;\n var treeSelectable = this.context.rcTree.selectable;\n\n // Ignore when selectable is undefined or null\n\n if (typeof selectable === 'boolean') {\n return selectable;\n }\n\n return treeSelectable;\n }\n\n // Load data to avoid default expanded tree without data\n\n\n // Switcher\n\n\n // Checkbox\n\n\n // Icon + Title\n\n\n // Children list wrapped with `Animation`\n\n }, {\n key: 'render',\n value: function render() {\n var _classNames;\n\n var loading = this.props.loading;\n\n var _props = this.props,\n className = _props.className,\n style = _props.style,\n dragOver = _props.dragOver,\n dragOverGapTop = _props.dragOverGapTop,\n dragOverGapBottom = _props.dragOverGapBottom,\n isLeaf = _props.isLeaf,\n expanded = _props.expanded,\n selected = _props.selected,\n checked = _props.checked,\n halfChecked = _props.halfChecked,\n otherProps = _objectWithoutProperties(_props, ['className', 'style', 'dragOver', 'dragOverGapTop', 'dragOverGapBottom', 'isLeaf', 'expanded', 'selected', 'checked', 'halfChecked']);\n\n var _context$rcTree = this.context.rcTree,\n prefixCls = _context$rcTree.prefixCls,\n filterTreeNode = _context$rcTree.filterTreeNode,\n draggable = _context$rcTree.draggable;\n\n var disabled = this.isDisabled();\n var dataOrAriaAttributeProps = getDataAndAria(otherProps);\n\n return React.createElement(\n 'li',\n _extends({\n className: classNames(className, (_classNames = {}, _defineProperty(_classNames, prefixCls + '-treenode-disabled', disabled), _defineProperty(_classNames, prefixCls + '-treenode-switcher-' + (expanded ? 'open' : 'close'), !isLeaf), _defineProperty(_classNames, prefixCls + '-treenode-checkbox-checked', checked), _defineProperty(_classNames, prefixCls + '-treenode-checkbox-indeterminate', halfChecked), _defineProperty(_classNames, prefixCls + '-treenode-selected', selected), _defineProperty(_classNames, prefixCls + '-treenode-loading', loading), _defineProperty(_classNames, 'drag-over', !disabled && dragOver), _defineProperty(_classNames, 'drag-over-gap-top', !disabled && dragOverGapTop), _defineProperty(_classNames, 'drag-over-gap-bottom', !disabled && dragOverGapBottom), _defineProperty(_classNames, 'filter-node', filterTreeNode && filterTreeNode(this)), _classNames)),\n\n style: style,\n\n role: 'treeitem',\n\n onDragEnter: draggable ? this.onDragEnter : undefined,\n onDragOver: draggable ? this.onDragOver : undefined,\n onDragLeave: draggable ? this.onDragLeave : undefined,\n onDrop: draggable ? this.onDrop : undefined,\n onDragEnd: draggable ? this.onDragEnd : undefined\n }, dataOrAriaAttributeProps),\n this.renderSwitcher(),\n this.renderCheckbox(),\n this.renderSelector(),\n this.renderChildren()\n );\n }\n }]);\n\n return TreeNode;\n}(React.Component);\n\nTreeNode.propTypes = {\n eventKey: PropTypes.string, // Pass by parent `cloneElement`\n prefixCls: PropTypes.string,\n className: PropTypes.string,\n style: PropTypes.object,\n root: PropTypes.object,\n onSelect: PropTypes.func,\n\n // By parent\n expanded: PropTypes.bool,\n selected: PropTypes.bool,\n checked: PropTypes.bool,\n loaded: PropTypes.bool,\n loading: PropTypes.bool,\n halfChecked: PropTypes.bool,\n children: PropTypes.node,\n title: PropTypes.node,\n pos: PropTypes.string,\n dragOver: PropTypes.bool,\n dragOverGapTop: PropTypes.bool,\n dragOverGapBottom: PropTypes.bool,\n\n // By user\n isLeaf: PropTypes.bool,\n checkable: PropTypes.bool,\n selectable: PropTypes.bool,\n disabled: PropTypes.bool,\n disableCheckbox: PropTypes.bool,\n icon: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),\n switcherIcon: PropTypes.oneOfType([PropTypes.node, PropTypes.func])\n};\nTreeNode.contextTypes = nodeContextTypes;\nTreeNode.childContextTypes = nodeContextTypes;\nTreeNode.defaultProps = {\n title: defaultTitle\n};\n\nvar _initialiseProps = function _initialiseProps() {\n var _this2 = this;\n\n this.onSelectorClick = function (e) {\n // Click trigger before select/check operation\n var onNodeClick = _this2.context.rcTree.onNodeClick;\n\n onNodeClick(e, _this2);\n\n if (_this2.isSelectable()) {\n _this2.onSelect(e);\n } else {\n _this2.onCheck(e);\n }\n };\n\n this.onSelectorDoubleClick = function (e) {\n var onNodeDoubleClick = _this2.context.rcTree.onNodeDoubleClick;\n\n onNodeDoubleClick(e, _this2);\n };\n\n this.onSelect = function (e) {\n if (_this2.isDisabled()) return;\n\n var onNodeSelect = _this2.context.rcTree.onNodeSelect;\n\n e.preventDefault();\n onNodeSelect(e, _this2);\n };\n\n this.onCheck = function (e) {\n if (_this2.isDisabled()) return;\n\n var _props2 = _this2.props,\n disableCheckbox = _props2.disableCheckbox,\n checked = _props2.checked;\n var onNodeCheck = _this2.context.rcTree.onNodeCheck;\n\n\n if (!_this2.isCheckable() || disableCheckbox) return;\n\n e.preventDefault();\n var targetChecked = !checked;\n onNodeCheck(e, _this2, targetChecked);\n };\n\n this.onMouseEnter = function (e) {\n var onNodeMouseEnter = _this2.context.rcTree.onNodeMouseEnter;\n\n onNodeMouseEnter(e, _this2);\n };\n\n this.onMouseLeave = function (e) {\n var onNodeMouseLeave = _this2.context.rcTree.onNodeMouseLeave;\n\n onNodeMouseLeave(e, _this2);\n };\n\n this.onContextMenu = function (e) {\n var onNodeContextMenu = _this2.context.rcTree.onNodeContextMenu;\n\n onNodeContextMenu(e, _this2);\n };\n\n this.onDragStart = function (e) {\n var onNodeDragStart = _this2.context.rcTree.onNodeDragStart;\n\n\n e.stopPropagation();\n _this2.setState({\n dragNodeHighlight: true\n });\n onNodeDragStart(e, _this2);\n\n try {\n // ie throw error\n // firefox-need-it\n e.dataTransfer.setData('text/plain', '');\n } catch (error) {\n // empty\n }\n };\n\n this.onDragEnter = function (e) {\n var onNodeDragEnter = _this2.context.rcTree.onNodeDragEnter;\n\n\n e.preventDefault();\n e.stopPropagation();\n onNodeDragEnter(e, _this2);\n };\n\n this.onDragOver = function (e) {\n var onNodeDragOver = _this2.context.rcTree.onNodeDragOver;\n\n\n e.preventDefault();\n e.stopPropagation();\n onNodeDragOver(e, _this2);\n };\n\n this.onDragLeave = function (e) {\n var onNodeDragLeave = _this2.context.rcTree.onNodeDragLeave;\n\n\n e.stopPropagation();\n onNodeDragLeave(e, _this2);\n };\n\n this.onDragEnd = function (e) {\n var onNodeDragEnd = _this2.context.rcTree.onNodeDragEnd;\n\n\n e.stopPropagation();\n _this2.setState({\n dragNodeHighlight: false\n });\n onNodeDragEnd(e, _this2);\n };\n\n this.onDrop = function (e) {\n var onNodeDrop = _this2.context.rcTree.onNodeDrop;\n\n\n e.preventDefault();\n e.stopPropagation();\n _this2.setState({\n dragNodeHighlight: false\n });\n onNodeDrop(e, _this2);\n };\n\n this.onExpand = function (e) {\n var onNodeExpand = _this2.context.rcTree.onNodeExpand;\n\n onNodeExpand(e, _this2);\n };\n\n this.setSelectHandle = function (node) {\n _this2.selectHandle = node;\n };\n\n this.getNodeChildren = function () {\n var children = _this2.props.children;\n\n var originList = toArray(children).filter(function (node) {\n return node;\n });\n var targetList = getNodeChildren(originList);\n\n if (originList.length !== targetList.length) {\n warnOnlyTreeNode();\n }\n\n return targetList;\n };\n\n this.getNodeState = function () {\n var expanded = _this2.props.expanded;\n\n\n if (_this2.isLeaf()) {\n return null;\n }\n\n return expanded ? ICON_OPEN : ICON_CLOSE;\n };\n\n this.isLeaf = function () {\n var _props3 = _this2.props,\n isLeaf = _props3.isLeaf,\n loaded = _props3.loaded;\n var loadData = _this2.context.rcTree.loadData;\n\n\n var hasChildren = _this2.getNodeChildren().length !== 0;\n\n if (isLeaf === false) {\n return false;\n }\n\n return isLeaf || !loadData && !hasChildren || loadData && loaded && !hasChildren;\n };\n\n this.isDisabled = function () {\n var disabled = _this2.props.disabled;\n var treeDisabled = _this2.context.rcTree.disabled;\n\n // Follow the logic of Selectable\n\n if (disabled === false) {\n return false;\n }\n\n return !!(treeDisabled || disabled);\n };\n\n this.isCheckable = function () {\n var checkable = _this2.props.checkable;\n var treeCheckable = _this2.context.rcTree.checkable;\n\n // Return false if tree or treeNode is not checkable\n\n if (!treeCheckable || checkable === false) return false;\n return treeCheckable;\n };\n\n this.syncLoadData = function (props) {\n var expanded = props.expanded,\n loading = props.loading,\n loaded = props.loaded;\n var _context$rcTree2 = _this2.context.rcTree,\n loadData = _context$rcTree2.loadData,\n onNodeLoad = _context$rcTree2.onNodeLoad;\n\n\n if (loading) return;\n\n // read from state to avoid loadData at same time\n if (loadData && expanded && !_this2.isLeaf()) {\n // We needn't reload data when has children in sync logic\n // It's only needed in node expanded\n var hasChildren = _this2.getNodeChildren().length !== 0;\n if (!hasChildren && !loaded) {\n onNodeLoad(_this2);\n }\n }\n };\n\n this.renderSwitcher = function () {\n var _props4 = _this2.props,\n expanded = _props4.expanded,\n switcherIconFromProps = _props4.switcherIcon;\n var _context$rcTree3 = _this2.context.rcTree,\n prefixCls = _context$rcTree3.prefixCls,\n switcherIconFromCtx = _context$rcTree3.switcherIcon;\n\n\n var switcherIcon = switcherIconFromProps || switcherIconFromCtx;\n\n if (_this2.isLeaf()) {\n return React.createElement(\n 'span',\n { className: classNames(prefixCls + '-switcher', prefixCls + '-switcher-noop') },\n typeof switcherIcon === 'function' ? switcherIcon(_extends({}, _this2.props, { isLeaf: true })) : switcherIcon\n );\n }\n\n var switcherCls = classNames(prefixCls + '-switcher', prefixCls + '-switcher_' + (expanded ? ICON_OPEN : ICON_CLOSE));\n return React.createElement(\n 'span',\n { onClick: _this2.onExpand, className: switcherCls },\n typeof switcherIcon === 'function' ? switcherIcon(_extends({}, _this2.props, { isLeaf: false })) : switcherIcon\n );\n };\n\n this.renderCheckbox = function () {\n var _props5 = _this2.props,\n checked = _props5.checked,\n halfChecked = _props5.halfChecked,\n disableCheckbox = _props5.disableCheckbox;\n var prefixCls = _this2.context.rcTree.prefixCls;\n\n var disabled = _this2.isDisabled();\n var checkable = _this2.isCheckable();\n\n if (!checkable) return null;\n\n // [Legacy] Custom element should be separate with `checkable` in future\n var $custom = typeof checkable !== 'boolean' ? checkable : null;\n\n return React.createElement(\n 'span',\n {\n className: classNames(prefixCls + '-checkbox', checked && prefixCls + '-checkbox-checked', !checked && halfChecked && prefixCls + '-checkbox-indeterminate', (disabled || disableCheckbox) && prefixCls + '-checkbox-disabled'),\n onClick: _this2.onCheck\n },\n $custom\n );\n };\n\n this.renderIcon = function () {\n var loading = _this2.props.loading;\n var prefixCls = _this2.context.rcTree.prefixCls;\n\n\n return React.createElement('span', {\n className: classNames(prefixCls + '-iconEle', prefixCls + '-icon__' + (_this2.getNodeState() || 'docu'), loading && prefixCls + '-icon_loading')\n });\n };\n\n this.renderSelector = function () {\n var dragNodeHighlight = _this2.state.dragNodeHighlight;\n var _props6 = _this2.props,\n title = _props6.title,\n selected = _props6.selected,\n icon = _props6.icon,\n loading = _props6.loading;\n var _context$rcTree4 = _this2.context.rcTree,\n prefixCls = _context$rcTree4.prefixCls,\n showIcon = _context$rcTree4.showIcon,\n treeIcon = _context$rcTree4.icon,\n draggable = _context$rcTree4.draggable,\n loadData = _context$rcTree4.loadData;\n\n var disabled = _this2.isDisabled();\n\n var wrapClass = prefixCls + '-node-content-wrapper';\n\n // Icon - Still show loading icon when loading without showIcon\n var $icon = void 0;\n\n if (showIcon) {\n var currentIcon = icon || treeIcon;\n\n $icon = currentIcon ? React.createElement(\n 'span',\n {\n className: classNames(prefixCls + '-iconEle', prefixCls + '-icon__customize')\n },\n typeof currentIcon === 'function' ? React.createElement(currentIcon, _extends({}, _this2.props)) : currentIcon\n ) : _this2.renderIcon();\n } else if (loadData && loading) {\n $icon = _this2.renderIcon();\n }\n\n // Title\n var $title = React.createElement(\n 'span',\n { className: prefixCls + '-title' },\n title\n );\n\n return React.createElement(\n 'span',\n {\n ref: _this2.setSelectHandle,\n title: typeof title === 'string' ? title : '',\n className: classNames('' + wrapClass, wrapClass + '-' + (_this2.getNodeState() || 'normal'), !disabled && (selected || dragNodeHighlight) && prefixCls + '-node-selected', !disabled && draggable && 'draggable'),\n draggable: !disabled && draggable || undefined,\n 'aria-grabbed': !disabled && draggable || undefined,\n\n onMouseEnter: _this2.onMouseEnter,\n onMouseLeave: _this2.onMouseLeave,\n onContextMenu: _this2.onContextMenu,\n onClick: _this2.onSelectorClick,\n onDoubleClick: _this2.onSelectorDoubleClick,\n onDragStart: draggable ? _this2.onDragStart : undefined\n },\n $icon,\n $title\n );\n };\n\n this.renderChildren = function () {\n var _props7 = _this2.props,\n expanded = _props7.expanded,\n pos = _props7.pos;\n var _context$rcTree5 = _this2.context.rcTree,\n prefixCls = _context$rcTree5.prefixCls,\n motion = _context$rcTree5.motion,\n renderTreeNode = _context$rcTree5.renderTreeNode;\n\n // Children TreeNode\n\n var nodeList = _this2.getNodeChildren();\n\n if (nodeList.length === 0) {\n return null;\n }\n return React.createElement(\n CSSMotion,\n _extends({ visible: expanded }, motion),\n function (_ref) {\n var style = _ref.style,\n className = _ref.className;\n\n return React.createElement(\n 'ul',\n {\n className: classNames(className, prefixCls + '-child-tree', expanded && prefixCls + '-child-tree-open'),\n style: style,\n 'data-expanded': expanded,\n role: 'group'\n },\n mapChildren(nodeList, function (node, index) {\n return renderTreeNode(node, index, pos);\n })\n );\n }\n );\n };\n};\n\nTreeNode.isTreeNode = 1;\n\npolyfill(TreeNode);\n\nexport default TreeNode;","import {default as LayersPass} from './layers-pass';\nimport {\n Framebuffer,\n Texture2D,\n Renderbuffer,\n withParameters,\n cssToDeviceRatio\n} from '@luma.gl/core';\n\nexport default class ShadowPass extends LayersPass {\n constructor(gl, props) {\n super(gl, props);\n\n // The shadowMap texture\n this.shadowMap = new Texture2D(gl, {\n width: 1,\n height: 1,\n parameters: {\n [gl.TEXTURE_MIN_FILTER]: gl.LINEAR,\n [gl.TEXTURE_MAG_FILTER]: gl.LINEAR,\n [gl.TEXTURE_WRAP_S]: gl.CLAMP_TO_EDGE,\n [gl.TEXTURE_WRAP_T]: gl.CLAMP_TO_EDGE\n }\n });\n\n this.depthBuffer = new Renderbuffer(gl, {\n format: gl.DEPTH_COMPONENT16,\n width: 1,\n height: 1\n });\n\n this.fbo = new Framebuffer(gl, {\n id: 'shadowmap',\n width: 1,\n height: 1,\n attachments: {\n [gl.COLOR_ATTACHMENT0]: this.shadowMap,\n // Depth attachment has to be specified for depth test to work\n [gl.DEPTH_ATTACHMENT]: this.depthBuffer\n }\n });\n }\n\n render(params) {\n const target = this.fbo;\n\n withParameters(\n this.gl,\n {\n depthRange: [0, 1],\n depthTest: true,\n blend: false,\n clearColor: [1, 1, 1, 1]\n },\n () => {\n const viewport = params.viewports[0];\n const pixelRatio = cssToDeviceRatio(this.gl);\n const width = viewport.width * pixelRatio;\n const height = viewport.height * pixelRatio;\n if (width !== target.width || height !== target.height) {\n target.resize({width, height});\n }\n\n super.render({...params, target, pass: 'shadow'});\n }\n );\n }\n\n shouldDrawLayer(layer) {\n return layer.props.shadowEnabled !== false;\n }\n\n getModuleParameters() {\n return {\n drawToShadowMap: true\n };\n }\n\n delete() {\n if (this.fbo) {\n this.fbo.delete();\n this.fbo = null;\n }\n\n if (this.shadowMap) {\n this.shadowMap.delete();\n this.shadowMap = null;\n }\n\n if (this.depthBuffer) {\n this.depthBuffer.delete();\n this.depthBuffer = null;\n }\n }\n}\n","import {Texture2D, ProgramManager} from '@luma.gl/core';\nimport {AmbientLight} from './ambient-light';\nimport {DirectionalLight} from './directional-light';\nimport Effect from '../../lib/effect';\nimport {Matrix4, Vector3} from 'math.gl';\nimport ShadowPass from '../../passes/shadow-pass';\nimport {default as shadow} from '../../shaderlib/shadow/shadow';\n\nconst DEFAULT_AMBIENT_LIGHT_PROPS = {color: [255, 255, 255], intensity: 1.0};\nconst DEFAULT_DIRECTIONAL_LIGHT_PROPS = [\n {\n color: [255, 255, 255],\n intensity: 1.0,\n direction: [-1, 3, -1]\n },\n {\n color: [255, 255, 255],\n intensity: 0.9,\n direction: [1, -8, -2.5]\n }\n];\nconst DEFAULT_SHADOW_COLOR = [0, 0, 0, 200 / 255];\n\n// Class to manage ambient, point and directional light sources in deck\nexport default class LightingEffect extends Effect {\n constructor(props) {\n super(props);\n this.ambientLight = null;\n this.directionalLights = [];\n this.pointLights = [];\n\n this.shadowColor = DEFAULT_SHADOW_COLOR;\n this.shadowPasses = [];\n this.shadowMaps = [];\n this.dummyShadowMap = null;\n this.shadow = false;\n this.programManager = null;\n\n for (const key in props) {\n const lightSource = props[key];\n\n switch (lightSource.type) {\n case 'ambient':\n this.ambientLight = lightSource;\n break;\n\n case 'directional':\n this.directionalLights.push(lightSource);\n break;\n\n case 'point':\n this.pointLights.push(lightSource);\n break;\n default:\n }\n }\n this._applyDefaultLights();\n\n this.shadow = this.directionalLights.some(light => light.shadow);\n }\n\n preRender(gl, {layers, layerFilter, viewports, onViewportActive, views}) {\n if (!this.shadow) return;\n\n // create light matrix every frame to make sure always updated from light source\n this.shadowMatrices = this._createLightMatrix();\n\n if (this.shadowPasses.length === 0) {\n this._createShadowPasses(gl);\n }\n if (!this.programManager) {\n // TODO - support multiple contexts\n this.programManager = ProgramManager.getDefaultProgramManager(gl);\n if (shadow) {\n this.programManager.addDefaultModule(shadow);\n }\n }\n\n if (!this.dummyShadowMap) {\n this.dummyShadowMap = new Texture2D(gl, {\n width: 1,\n height: 1\n });\n }\n\n for (let i = 0; i < this.shadowPasses.length; i++) {\n const shadowPass = this.shadowPasses[i];\n shadowPass.render({\n layers,\n layerFilter,\n viewports,\n onViewportActive,\n views,\n moduleParameters: {\n shadowLightId: i,\n dummyShadowMap: this.dummyShadowMap,\n shadowMatrices: this.shadowMatrices\n }\n });\n }\n }\n\n getModuleParameters(layer) {\n const parameters = this.shadow\n ? {\n shadowMaps: this.shadowMaps,\n dummyShadowMap: this.dummyShadowMap,\n shadowColor: this.shadowColor,\n shadowMatrices: this.shadowMatrices\n }\n : {};\n\n // when not rendering to screen, turn off lighting by adding empty light source object\n // lights shader module relies on the `lightSources` to turn on/off lighting\n parameters.lightSources = {\n ambientLight: this.ambientLight,\n directionalLights: this.directionalLights.map(directionalLight =>\n directionalLight.getProjectedLight({layer})\n ),\n pointLights: this.pointLights.map(pointLight => pointLight.getProjectedLight({layer}))\n };\n\n return parameters;\n }\n\n cleanup() {\n for (const shadowPass of this.shadowPasses) {\n shadowPass.delete();\n }\n this.shadowPasses.length = 0;\n this.shadowMaps.length = 0;\n\n if (this.dummyShadowMap) {\n this.dummyShadowMap.delete();\n this.dummyShadowMap = null;\n }\n\n if (this.shadow && this.programManager) {\n this.programManager.removeDefaultModule(shadow);\n this.programManager = null;\n }\n }\n\n _createLightMatrix() {\n const lightMatrices = [];\n for (const light of this.directionalLights) {\n const viewMatrix = new Matrix4().lookAt({\n eye: new Vector3(light.direction).negate()\n });\n\n lightMatrices.push(viewMatrix);\n }\n return lightMatrices;\n }\n\n _createShadowPasses(gl) {\n for (let i = 0; i < this.directionalLights.length; i++) {\n const shadowPass = new ShadowPass(gl);\n this.shadowPasses[i] = shadowPass;\n this.shadowMaps[i] = shadowPass.shadowMap;\n }\n }\n\n _applyDefaultLights() {\n const {ambientLight, pointLights, directionalLights} = this;\n if (!ambientLight && pointLights.length === 0 && directionalLights.length === 0) {\n this.ambientLight = new AmbientLight(DEFAULT_AMBIENT_LIGHT_PROPS);\n this.directionalLights.push(\n new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[0]),\n new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[1])\n );\n }\n }\n}\n","import * as glMatrix from \"./common.js\";\nimport * as mat3 from \"./mat3.js\";\nimport * as vec3 from \"./vec3.js\";\nimport * as vec4 from \"./vec4.js\";\n/**\r\n * Quaternion\r\n * @module quat\r\n */\n\n/**\r\n * Creates a new identity quat\r\n *\r\n * @returns {quat} a new quaternion\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n out[3] = 1;\n return out;\n}\n/**\r\n * Set a quat to the identity quaternion\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @returns {quat} out\r\n */\n\nexport function identity(out) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n}\n/**\r\n * Sets a quat from the given angle and rotation axis,\r\n * then returns it.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyVec3} axis the axis around which to rotate\r\n * @param {Number} rad the angle in radians\r\n * @returns {quat} out\r\n **/\n\nexport function setAxisAngle(out, axis, rad) {\n rad = rad * 0.5;\n var s = Math.sin(rad);\n out[0] = s * axis[0];\n out[1] = s * axis[1];\n out[2] = s * axis[2];\n out[3] = Math.cos(rad);\n return out;\n}\n/**\r\n * Gets the rotation axis and angle for a given\r\n * quaternion. If a quaternion is created with\r\n * setAxisAngle, this method will return the same\r\n * values as providied in the original parameter list\r\n * OR functionally equivalent values.\r\n * Example: The quaternion formed by axis [0, 0, 1] and\r\n * angle -90 is the same as the quaternion formed by\r\n * [0, 0, 1] and 270. This method favors the latter.\r\n * @param {vec3} out_axis Vector receiving the axis of rotation\r\n * @param {ReadonlyQuat} q Quaternion to be decomposed\r\n * @return {Number} Angle, in radians, of the rotation\r\n */\n\nexport function getAxisAngle(out_axis, q) {\n var rad = Math.acos(q[3]) * 2.0;\n var s = Math.sin(rad / 2.0);\n\n if (s > glMatrix.EPSILON) {\n out_axis[0] = q[0] / s;\n out_axis[1] = q[1] / s;\n out_axis[2] = q[2] / s;\n } else {\n // If s is zero, return any axis (no rotation - axis does not matter)\n out_axis[0] = 1;\n out_axis[1] = 0;\n out_axis[2] = 0;\n }\n\n return rad;\n}\n/**\r\n * Gets the angular distance between two unit quaternions\r\n *\r\n * @param {ReadonlyQuat} a Origin unit quaternion\r\n * @param {ReadonlyQuat} b Destination unit quaternion\r\n * @return {Number} Angle, in radians, between the two quaternions\r\n */\n\nexport function getAngle(a, b) {\n var dotproduct = dot(a, b);\n return Math.acos(2 * dotproduct * dotproduct - 1);\n}\n/**\r\n * Multiplies two quat's\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a the first operand\r\n * @param {ReadonlyQuat} b the second operand\r\n * @returns {quat} out\r\n */\n\nexport function multiply(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n out[0] = ax * bw + aw * bx + ay * bz - az * by;\n out[1] = ay * bw + aw * by + az * bx - ax * bz;\n out[2] = az * bw + aw * bz + ax * by - ay * bx;\n out[3] = aw * bw - ax * bx - ay * by - az * bz;\n return out;\n}\n/**\r\n * Rotates a quaternion by the given angle about the X axis\r\n *\r\n * @param {quat} out quat receiving operation result\r\n * @param {ReadonlyQuat} a quat to rotate\r\n * @param {number} rad angle (in radians) to rotate\r\n * @returns {quat} out\r\n */\n\nexport function rotateX(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + aw * bx;\n out[1] = ay * bw + az * bx;\n out[2] = az * bw - ay * bx;\n out[3] = aw * bw - ax * bx;\n return out;\n}\n/**\r\n * Rotates a quaternion by the given angle about the Y axis\r\n *\r\n * @param {quat} out quat receiving operation result\r\n * @param {ReadonlyQuat} a quat to rotate\r\n * @param {number} rad angle (in radians) to rotate\r\n * @returns {quat} out\r\n */\n\nexport function rotateY(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var by = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw - az * by;\n out[1] = ay * bw + aw * by;\n out[2] = az * bw + ax * by;\n out[3] = aw * bw - ay * by;\n return out;\n}\n/**\r\n * Rotates a quaternion by the given angle about the Z axis\r\n *\r\n * @param {quat} out quat receiving operation result\r\n * @param {ReadonlyQuat} a quat to rotate\r\n * @param {number} rad angle (in radians) to rotate\r\n * @returns {quat} out\r\n */\n\nexport function rotateZ(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bz = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + ay * bz;\n out[1] = ay * bw - ax * bz;\n out[2] = az * bw + aw * bz;\n out[3] = aw * bw - az * bz;\n return out;\n}\n/**\r\n * Calculates the W component of a quat from the X, Y, and Z components.\r\n * Assumes that quaternion is 1 unit in length.\r\n * Any existing W component will be ignored.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a quat to calculate W component of\r\n * @returns {quat} out\r\n */\n\nexport function calculateW(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));\n return out;\n}\n/**\r\n * Calculate the exponential of a unit quaternion.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a quat to calculate the exponential of\r\n * @returns {quat} out\r\n */\n\nexport function exp(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var et = Math.exp(w);\n var s = r > 0 ? et * Math.sin(r) / r : 0;\n out[0] = x * s;\n out[1] = y * s;\n out[2] = z * s;\n out[3] = et * Math.cos(r);\n return out;\n}\n/**\r\n * Calculate the natural logarithm of a unit quaternion.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a quat to calculate the exponential of\r\n * @returns {quat} out\r\n */\n\nexport function ln(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var t = r > 0 ? Math.atan2(r, w) / r : 0;\n out[0] = x * t;\n out[1] = y * t;\n out[2] = z * t;\n out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w);\n return out;\n}\n/**\r\n * Calculate the scalar power of a unit quaternion.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a quat to calculate the exponential of\r\n * @param {Number} b amount to scale the quaternion by\r\n * @returns {quat} out\r\n */\n\nexport function pow(out, a, b) {\n ln(out, a);\n scale(out, out, b);\n exp(out, out);\n return out;\n}\n/**\r\n * Performs a spherical linear interpolation between two quat\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a the first operand\r\n * @param {ReadonlyQuat} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {quat} out\r\n */\n\nexport function slerp(out, a, b, t) {\n // benchmarks:\n // http://jsperf.com/quaternion-slerp-implementations\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n var omega, cosom, sinom, scale0, scale1; // calc cosine\n\n cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)\n\n if (cosom < 0.0) {\n cosom = -cosom;\n bx = -bx;\n by = -by;\n bz = -bz;\n bw = -bw;\n } // calculate coefficients\n\n\n if (1.0 - cosom > glMatrix.EPSILON) {\n // standard case (slerp)\n omega = Math.acos(cosom);\n sinom = Math.sin(omega);\n scale0 = Math.sin((1.0 - t) * omega) / sinom;\n scale1 = Math.sin(t * omega) / sinom;\n } else {\n // \"from\" and \"to\" quaternions are very close\n // ... so we can do a linear interpolation\n scale0 = 1.0 - t;\n scale1 = t;\n } // calculate final values\n\n\n out[0] = scale0 * ax + scale1 * bx;\n out[1] = scale0 * ay + scale1 * by;\n out[2] = scale0 * az + scale1 * bz;\n out[3] = scale0 * aw + scale1 * bw;\n return out;\n}\n/**\r\n * Generates a random unit quaternion\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @returns {quat} out\r\n */\n\nexport function random(out) {\n // Implementation of http://planning.cs.uiuc.edu/node198.html\n // TODO: Calling random 3 times is probably not the fastest solution\n var u1 = glMatrix.RANDOM();\n var u2 = glMatrix.RANDOM();\n var u3 = glMatrix.RANDOM();\n var sqrt1MinusU1 = Math.sqrt(1 - u1);\n var sqrtU1 = Math.sqrt(u1);\n out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2);\n out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2);\n out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3);\n out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3);\n return out;\n}\n/**\r\n * Calculates the inverse of a quat\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a quat to calculate inverse of\r\n * @returns {quat} out\r\n */\n\nexport function invert(out, a) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0\n\n out[0] = -a0 * invDot;\n out[1] = -a1 * invDot;\n out[2] = -a2 * invDot;\n out[3] = a3 * invDot;\n return out;\n}\n/**\r\n * Calculates the conjugate of a quat\r\n * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a quat to calculate conjugate of\r\n * @returns {quat} out\r\n */\n\nexport function conjugate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = a[3];\n return out;\n}\n/**\r\n * Creates a quaternion from the given 3x3 rotation matrix.\r\n *\r\n * NOTE: The resultant quaternion is not normalized, so you should be sure\r\n * to renormalize the quaternion yourself where necessary.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyMat3} m rotation matrix\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport function fromMat3(out, m) {\n // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n // article \"Quaternion Calculus and Fast Animation\".\n var fTrace = m[0] + m[4] + m[8];\n var fRoot;\n\n if (fTrace > 0.0) {\n // |w| > 1/2, may as well choose w > 1/2\n fRoot = Math.sqrt(fTrace + 1.0); // 2w\n\n out[3] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot; // 1/(4w)\n\n out[0] = (m[5] - m[7]) * fRoot;\n out[1] = (m[6] - m[2]) * fRoot;\n out[2] = (m[1] - m[3]) * fRoot;\n } else {\n // |w| <= 1/2\n var i = 0;\n if (m[4] > m[0]) i = 1;\n if (m[8] > m[i * 3 + i]) i = 2;\n var j = (i + 1) % 3;\n var k = (i + 2) % 3;\n fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);\n out[i] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot;\n out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;\n out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;\n out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;\n }\n\n return out;\n}\n/**\r\n * Creates a quaternion from the given euler angle x, y, z.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {x} Angle to rotate around X axis in degrees.\r\n * @param {y} Angle to rotate around Y axis in degrees.\r\n * @param {z} Angle to rotate around Z axis in degrees.\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport function fromEuler(out, x, y, z) {\n var halfToRad = 0.5 * Math.PI / 180.0;\n x *= halfToRad;\n y *= halfToRad;\n z *= halfToRad;\n var sx = Math.sin(x);\n var cx = Math.cos(x);\n var sy = Math.sin(y);\n var cy = Math.cos(y);\n var sz = Math.sin(z);\n var cz = Math.cos(z);\n out[0] = sx * cy * cz - cx * sy * sz;\n out[1] = cx * sy * cz + sx * cy * sz;\n out[2] = cx * cy * sz - sx * sy * cz;\n out[3] = cx * cy * cz + sx * sy * sz;\n return out;\n}\n/**\r\n * Returns a string representation of a quatenion\r\n *\r\n * @param {ReadonlyQuat} a vector to represent as a string\r\n * @returns {String} string representation of the vector\r\n */\n\nexport function str(a) {\n return \"quat(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\r\n * Creates a new quat initialized with values from an existing quaternion\r\n *\r\n * @param {ReadonlyQuat} a quaternion to clone\r\n * @returns {quat} a new quaternion\r\n * @function\r\n */\n\nexport var clone = vec4.clone;\n/**\r\n * Creates a new quat initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {quat} a new quaternion\r\n * @function\r\n */\n\nexport var fromValues = vec4.fromValues;\n/**\r\n * Copy the values from one quat to another\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a the source quaternion\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var copy = vec4.copy;\n/**\r\n * Set the components of a quat to the given values\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var set = vec4.set;\n/**\r\n * Adds two quat's\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a the first operand\r\n * @param {ReadonlyQuat} b the second operand\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var add = vec4.add;\n/**\r\n * Alias for {@link quat.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Scales a quat by a scalar number\r\n *\r\n * @param {quat} out the receiving vector\r\n * @param {ReadonlyQuat} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var scale = vec4.scale;\n/**\r\n * Calculates the dot product of two quat's\r\n *\r\n * @param {ReadonlyQuat} a the first operand\r\n * @param {ReadonlyQuat} b the second operand\r\n * @returns {Number} dot product of a and b\r\n * @function\r\n */\n\nexport var dot = vec4.dot;\n/**\r\n * Performs a linear interpolation between two quat's\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a the first operand\r\n * @param {ReadonlyQuat} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var lerp = vec4.lerp;\n/**\r\n * Calculates the length of a quat\r\n *\r\n * @param {ReadonlyQuat} a vector to calculate length of\r\n * @returns {Number} length of a\r\n */\n\nexport var length = vec4.length;\n/**\r\n * Alias for {@link quat.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Calculates the squared length of a quat\r\n *\r\n * @param {ReadonlyQuat} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\n * @function\r\n */\n\nexport var squaredLength = vec4.squaredLength;\n/**\r\n * Alias for {@link quat.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Normalize a quat\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a quaternion to normalize\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var normalize = vec4.normalize;\n/**\r\n * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {ReadonlyQuat} a The first quaternion.\r\n * @param {ReadonlyQuat} b The second quaternion.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport var exactEquals = vec4.exactEquals;\n/**\r\n * Returns whether or not the quaternions have approximately the same elements in the same position.\r\n *\r\n * @param {ReadonlyQuat} a The first vector.\r\n * @param {ReadonlyQuat} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport var equals = vec4.equals;\n/**\r\n * Sets a quaternion to represent the shortest rotation from one\r\n * vector to another.\r\n *\r\n * Both vectors are assumed to be unit length.\r\n *\r\n * @param {quat} out the receiving quaternion.\r\n * @param {ReadonlyVec3} a the initial vector\r\n * @param {ReadonlyVec3} b the destination vector\r\n * @returns {quat} out\r\n */\n\nexport var rotationTo = function () {\n var tmpvec3 = vec3.create();\n var xUnitVec3 = vec3.fromValues(1, 0, 0);\n var yUnitVec3 = vec3.fromValues(0, 1, 0);\n return function (out, a, b) {\n var dot = vec3.dot(a, b);\n\n if (dot < -0.999999) {\n vec3.cross(tmpvec3, xUnitVec3, a);\n if (vec3.len(tmpvec3) < 0.000001) vec3.cross(tmpvec3, yUnitVec3, a);\n vec3.normalize(tmpvec3, tmpvec3);\n setAxisAngle(out, tmpvec3, Math.PI);\n return out;\n } else if (dot > 0.999999) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n } else {\n vec3.cross(tmpvec3, a, b);\n out[0] = tmpvec3[0];\n out[1] = tmpvec3[1];\n out[2] = tmpvec3[2];\n out[3] = 1 + dot;\n return normalize(out, out);\n }\n };\n}();\n/**\r\n * Performs a spherical linear interpolation with two control points\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {ReadonlyQuat} a the first operand\r\n * @param {ReadonlyQuat} b the second operand\r\n * @param {ReadonlyQuat} c the third operand\r\n * @param {ReadonlyQuat} d the fourth operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {quat} out\r\n */\n\nexport var sqlerp = function () {\n var temp1 = create();\n var temp2 = create();\n return function (out, a, b, c, d, t) {\n slerp(temp1, a, d, t);\n slerp(temp2, b, c, t);\n slerp(out, temp1, temp2, 2 * t * (1 - t));\n return out;\n };\n}();\n/**\r\n * Sets the specified quaternion with values corresponding to the given\r\n * axes. Each axis is a vec3 and is expected to be unit length and\r\n * perpendicular to all other specified axes.\r\n *\r\n * @param {ReadonlyVec3} view the vector representing the viewing direction\r\n * @param {ReadonlyVec3} right the vector representing the local \"right\" direction\r\n * @param {ReadonlyVec3} up the vector representing the local \"up\" direction\r\n * @returns {quat} out\r\n */\n\nexport var setAxes = function () {\n var matr = mat3.create();\n return function (out, view, right, up) {\n matr[0] = right[0];\n matr[3] = right[1];\n matr[6] = right[2];\n matr[1] = up[0];\n matr[4] = up[1];\n matr[7] = up[2];\n matr[2] = -view[0];\n matr[5] = -view[1];\n matr[8] = -view[2];\n return normalize(out, fromMat3(out, matr));\n };\n}();","export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","/* Use as\nimport {checkProps} from '../util/check-props;'\n\nconst PROP_CHECKS = {\n // Removed props no longer supported, print error and link to upgrade guide\n removedProps: {\n },\n // Deprecated props\n deprecatedProps: {\n offset: 'accessor',\n stride: 'accessor',\n type: 'accessor',\n size: 'accessor',\n divisor: 'accessor',\n normalized: 'accessor',\n integer: 'accessor'\n },\n // Deprecated props that can be autosubstituted, print warning and return updated props object\n replacedProps: {\n bytes: 'byteLength'\n }\n}\n\nclass Buffer {\n setProps(props) {\n checkProps('Buffer', props, PROP_CHECKS);\n }\n}\n*/\nimport {log} from '@luma.gl/gltools';\n\nexport function checkProps(className, props, propChecks) {\n const {removedProps = {}, deprecatedProps = {}, replacedProps = {}} = propChecks;\n\n // removedProps: Removed props no longer supported\n // print error and link to upgrade guide\n for (const propName in removedProps) {\n if (propName in props) {\n const replacementProp = removedProps[propName];\n const replacement = replacementProp ? `${className}.${removedProps[propName]}` : 'N/A';\n log.removed(`${className}.${propName}`, replacement)();\n }\n }\n\n // deprecatedProps: Deprecated props that can not be autosubstituted\n // print warning and rely on caller to substitute\n for (const propName in deprecatedProps) {\n if (propName in props) {\n const replacementProp = deprecatedProps[propName];\n log.deprecated(`${className}.${propName}`, `${className}.${replacementProp}`)();\n }\n }\n\n // replacedProps: Deprecated props that can be autosubstituted\n // print warning and return updated props object\n let newProps = null;\n for (const propName in replacedProps) {\n if (propName in props) {\n const replacementProp = replacedProps[propName];\n log.deprecated(`${className}.${propName}`, `${className}.${replacementProp}`)();\n newProps = newProps || Object.assign({}, props);\n newProps[replacementProp] = props[propName];\n delete newProps[propName];\n }\n }\n\n return newProps || props;\n}\n","/**\n * Projection utils\n * TODO: move to Viewport class?\n */\nimport {COORDINATE_SYSTEM} from '../../lib/constants';\nimport {getOffsetOrigin} from './viewport-uniforms';\nimport WebMercatorViewport from '../../viewports/web-mercator-viewport';\n\nimport * as vec4 from 'gl-matrix/vec4';\nimport * as vec3 from 'gl-matrix/vec3';\nimport {addMetersToLngLat} from '@math.gl/web-mercator';\n\n// In project.glsl, offset modes calculate z differently from LNG_LAT mode.\n// offset modes apply the y adjustment (unitsPerMeter2) when projecting z\n// LNG_LAT mode only use the linear scale.\nfunction lngLatZToWorldPosition(lngLatZ, viewport, offsetMode = false) {\n const p = viewport.projectPosition(lngLatZ);\n\n // TODO - avoid using instanceof\n if (offsetMode && viewport instanceof WebMercatorViewport) {\n const [longitude, latitude, z = 0] = lngLatZ;\n const distanceScales = viewport.getDistanceScales([longitude, latitude]);\n p[2] = z * distanceScales.unitsPerMeter[2];\n }\n return p;\n}\n\nfunction normalizeParameters(opts) {\n const normalizedParams = {...opts};\n\n let {coordinateSystem} = opts;\n const {viewport, coordinateOrigin, fromCoordinateSystem, fromCoordinateOrigin} = opts;\n\n if (coordinateSystem === COORDINATE_SYSTEM.DEFAULT) {\n coordinateSystem = viewport.isGeospatial\n ? COORDINATE_SYSTEM.LNGLAT\n : COORDINATE_SYSTEM.CARTESIAN;\n }\n\n if (fromCoordinateSystem === undefined) {\n normalizedParams.fromCoordinateSystem = coordinateSystem;\n }\n if (fromCoordinateOrigin === undefined) {\n normalizedParams.fromCoordinateOrigin = coordinateOrigin;\n }\n\n normalizedParams.coordinateSystem = coordinateSystem;\n\n return normalizedParams;\n}\n\nexport function getWorldPosition(\n position,\n {viewport, modelMatrix, coordinateSystem, coordinateOrigin, offsetMode}\n) {\n let [x, y, z = 0] = position;\n\n if (modelMatrix) {\n [x, y, z] = vec4.transformMat4([], [x, y, z, 1.0], modelMatrix);\n }\n\n switch (coordinateSystem) {\n case COORDINATE_SYSTEM.LNGLAT:\n return lngLatZToWorldPosition([x, y, z], viewport, offsetMode);\n\n case COORDINATE_SYSTEM.LNGLAT_OFFSETS:\n return lngLatZToWorldPosition(\n [x + coordinateOrigin[0], y + coordinateOrigin[1], z + (coordinateOrigin[2] || 0)],\n viewport,\n offsetMode\n );\n\n case COORDINATE_SYSTEM.METER_OFFSETS:\n return lngLatZToWorldPosition(\n addMetersToLngLat(coordinateOrigin, [x, y, z]),\n viewport,\n offsetMode\n );\n\n case COORDINATE_SYSTEM.CARTESIAN:\n default:\n return viewport.isGeospatial\n ? [x + coordinateOrigin[0], y + coordinateOrigin[1], z + coordinateOrigin[2]]\n : viewport.projectPosition([x, y, z]);\n }\n}\n\n/**\n * Equivalent to project_position in project.glsl\n * projects a user supplied position to world position directly with or without\n * a reference coordinate system\n * @param {array} position - [x, y, z]\n * @param {object} params\n * @param {Viewport} params.viewport - the current viewport\n * @param {number} params.coordinateSystem - the reference coordinate system used\n * align world position\n * @param {array} params.coordinateOrigin - the reference coordinate origin used\n * to align world position\n * @param {Matrix4} [params.modelMatrix] - the model matrix of the supplied position\n * @param {number} [params.fromCoordinateSystem] - the coordinate system that the\n * supplied position is in. Default to the same as `coordinateSystem`.\n * @param {array} [params.fromCoordinateOrigin] - the coordinate origin that the\n * supplied position is in. Default to the same as `coordinateOrigin`.\n */\nexport function projectPosition(position, params) {\n const {\n viewport,\n coordinateSystem,\n coordinateOrigin,\n // optional\n modelMatrix,\n fromCoordinateSystem,\n fromCoordinateOrigin\n } = normalizeParameters(params);\n\n const {geospatialOrigin, shaderCoordinateOrigin, offsetMode} = getOffsetOrigin(\n viewport,\n coordinateSystem,\n coordinateOrigin\n );\n\n const worldPosition = getWorldPosition(position, {\n viewport,\n modelMatrix,\n coordinateSystem: fromCoordinateSystem,\n coordinateOrigin: fromCoordinateOrigin,\n offsetMode\n });\n\n if (offsetMode) {\n const positionCommonSpace = viewport.projectPosition(\n geospatialOrigin || shaderCoordinateOrigin\n );\n vec3.sub(worldPosition, worldPosition, positionCommonSpace);\n }\n\n return worldPosition;\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// Purpose: include this in your module to avoids adding dependencies on\n// micro modules like 'global' and 'is-browser';\n\n/* eslint-disable no-restricted-globals */\nconst globals = {\n self: typeof self !== 'undefined' && self,\n window: typeof window !== 'undefined' && window,\n global: typeof global !== 'undefined' && global,\n document: typeof document !== 'undefined' && document\n};\n\nconst self_ = globals.self || globals.window || globals.global;\nconst window_ = globals.window || globals.self || globals.global;\nconst global_ = globals.global || globals.self || globals.window;\nconst document_ = globals.document || {};\n\nexport {self_ as self, window_ as window, global_ as global, document_ as document};\n\nexport const isBrowser =\n // @ts-ignore\n typeof process !== 'object' || String(process) !== '[object process]' || process.browser;\n\nexport const isWorker = typeof importScripts === 'function';\n\n// Extract node major version\nconst matches =\n typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);\nexport const nodeVersion = (matches && parseFloat(matches[1])) || 0;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/* eslint-disable max-params */\nimport earcut from 'earcut';\nimport {modifyPolygonWindingDirection, WINDING} from '@math.gl/polygon';\n\nconst OUTER_POLYGON_WINDING = WINDING.CLOCKWISE;\nconst HOLE_POLYGON_WINDING = WINDING.COUNTER_CLOCKWISE;\n\nconst windingOptions = {\n isClosed: true\n};\n\n// 4 data formats are supported:\n// Simple Polygon: an array of points\n// Complex Polygon: an array of array of points (array of rings)\n// with the first ring representing the outer hull and other rings representing holes\n// Simple Flat: an array of numbers (flattened \"simple polygon\")\n// Complex Flat: {position: array, holeIndices: array}\n// (flattened \"complex polygon\")\n\n/**\n * Ensure a polygon is valid format\n * @param {Array|Object} polygon\n */\nfunction validate(polygon) {\n polygon = (polygon && polygon.positions) || polygon;\n if (!Array.isArray(polygon) && !ArrayBuffer.isView(polygon)) {\n throw new Error('invalid polygon');\n }\n}\n\n/**\n * Check if a polygon is simple or complex\n * @param {Array} polygon - either a complex or simple polygon\n * @return {Boolean} - true if the polygon is a simple polygon (i.e. not an array of polygons)\n */\nfunction isSimple(polygon) {\n return polygon.length >= 1 && polygon[0].length >= 2 && Number.isFinite(polygon[0][0]);\n}\n\n/**\n * Check if a simple polygon is a closed ring\n * @param {Array} simplePolygon - array of points\n * @return {Boolean} - true if the simple polygon is a closed ring\n */\nfunction isNestedRingClosed(simplePolygon) {\n // check if first and last vertex are the same\n const p0 = simplePolygon[0];\n const p1 = simplePolygon[simplePolygon.length - 1];\n\n return p0[0] === p1[0] && p0[1] === p1[1] && p0[2] === p1[2];\n}\n\n/**\n * Check if a simple flat array is a closed ring\n * @param {Array} positions - array of numbers\n * @param {Number} size - size of a position, 2 (xy) or 3 (xyz)\n * @param {Number} startIndex - start index of the path in the positions array\n * @param {Number} endIndex - end index of the path in the positions array\n * @return {Boolean} - true if the simple flat array is a closed ring\n */\nfunction isFlatRingClosed(positions, size, startIndex, endIndex) {\n for (let i = 0; i < size; i++) {\n if (positions[startIndex + i] !== positions[endIndex - size + i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Copy a simple polygon coordinates into a flat array, closes the ring if needed.\n * @param {Float64Array} target - destination\n * @param {Number} targetStartIndex - index in the destination to start copying into\n * @param {Array} simplePolygon - array of points\n * @param {Number} size - size of a position, 2 (xy) or 3 (xyz)\n * @param {Number} [windingDirection] - modify polygon to be of the specified winding direction\n * @returns {Number} - the index of the write head in the destination\n */\nfunction copyNestedRing(target, targetStartIndex, simplePolygon, size, windingDirection) {\n let targetIndex = targetStartIndex;\n const len = simplePolygon.length;\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < size; j++) {\n target[targetIndex++] = simplePolygon[i][j] || 0;\n }\n }\n\n if (!isNestedRingClosed(simplePolygon)) {\n for (let j = 0; j < size; j++) {\n target[targetIndex++] = simplePolygon[0][j] || 0;\n }\n }\n\n windingOptions.start = targetStartIndex;\n windingOptions.end = targetIndex;\n windingOptions.size = size;\n modifyPolygonWindingDirection(target, windingDirection, windingOptions);\n\n return targetIndex;\n}\n\n/**\n * Copy a simple flat array into another flat array, closes the ring if needed.\n * @param {Float64Array} target - destination\n * @param {Number} targetStartIndex - index in the destination to start copying into\n * @param {Array} positions - array of numbers\n * @param {Number} size - size of a position, 2 (xy) or 3 (xyz)\n * @param {Number} [srcStartIndex] - start index of the path in the positions array\n * @param {Number} [srcEndIndex] - end index of the path in the positions array\n * @param {Number} [windingDirection] - modify polygon to be of the specified winding direction\n * @returns {Number} - the index of the write head in the destination\n */\nfunction copyFlatRing(\n target,\n targetStartIndex,\n positions,\n size,\n srcStartIndex = 0,\n srcEndIndex,\n windingDirection\n) {\n srcEndIndex = srcEndIndex || positions.length;\n const srcLength = srcEndIndex - srcStartIndex;\n if (srcLength <= 0) {\n return targetStartIndex;\n }\n let targetIndex = targetStartIndex;\n\n for (let i = 0; i < srcLength; i++) {\n target[targetIndex++] = positions[srcStartIndex + i];\n }\n\n if (!isFlatRingClosed(positions, size, srcStartIndex, srcEndIndex)) {\n for (let i = 0; i < size; i++) {\n target[targetIndex++] = positions[srcStartIndex + i];\n }\n }\n\n windingOptions.start = targetStartIndex;\n windingOptions.end = targetIndex;\n windingOptions.size = size;\n modifyPolygonWindingDirection(target, windingDirection, windingOptions);\n\n return targetIndex;\n}\n\n/**\n * Normalize any polygon representation into the \"complex flat\" format\n * @param {Array|Object} polygon\n * @param {Number} positionSize - size of a position, 2 (xy) or 3 (xyz)\n * @param {Number} [vertexCount] - pre-computed vertex count in the polygon.\n * If provided, will skip counting.\n * @return {Object} - {positions: , holeIndices: }\n */\n/* eslint-disable max-statements */\nexport function normalize(polygon, positionSize) {\n validate(polygon);\n\n const positions = [];\n const holeIndices = [];\n\n if (polygon.positions) {\n // complex flat\n const {positions: srcPositions, holeIndices: srcHoleIndices} = polygon;\n\n if (srcHoleIndices) {\n let targetIndex = 0;\n // split the positions array into `holeIndices.length + 1` rings\n // holeIndices[-1] falls back to 0\n // holeIndices[holeIndices.length] falls back to positions.length\n for (let i = 0; i <= srcHoleIndices.length; i++) {\n targetIndex = copyFlatRing(\n positions,\n targetIndex,\n srcPositions,\n positionSize,\n srcHoleIndices[i - 1],\n srcHoleIndices[i],\n i === 0 ? OUTER_POLYGON_WINDING : HOLE_POLYGON_WINDING\n );\n holeIndices.push(targetIndex);\n }\n // The last one is not a starting index of a hole, remove\n holeIndices.pop();\n\n return {positions, holeIndices};\n }\n polygon = srcPositions;\n }\n if (Number.isFinite(polygon[0])) {\n // simple flat\n copyFlatRing(positions, 0, polygon, positionSize, 0, positions.length, OUTER_POLYGON_WINDING);\n return positions;\n }\n if (!isSimple(polygon)) {\n // complex polygon\n let targetIndex = 0;\n\n for (const [polygonIndex, simplePolygon] of polygon.entries()) {\n targetIndex = copyNestedRing(\n positions,\n targetIndex,\n simplePolygon,\n positionSize,\n polygonIndex === 0 ? OUTER_POLYGON_WINDING : HOLE_POLYGON_WINDING\n );\n holeIndices.push(targetIndex);\n }\n // The last one is not a starting index of a hole, remove\n holeIndices.pop();\n // last index points to the end of the array, remove it\n return {positions, holeIndices};\n }\n // simple polygon\n copyNestedRing(positions, 0, polygon, positionSize, OUTER_POLYGON_WINDING);\n return positions;\n}\n/* eslint-enable max-statements */\n\n/*\n * Get vertex indices for drawing polygon mesh\n * @param {Object} normalizedPolygon - {positions, holeIndices}\n * @param {Number} positionSize - size of a position, 2 (xy) or 3 (xyz)\n * @returns {Array} array of indices\n */\nexport function getSurfaceIndices(normalizedPolygon, positionSize, preproject) {\n let holeIndices = null;\n\n if (normalizedPolygon.holeIndices) {\n holeIndices = normalizedPolygon.holeIndices.map(positionIndex => positionIndex / positionSize);\n }\n let positions = normalizedPolygon.positions || normalizedPolygon;\n\n if (preproject) {\n // When tesselating lnglat coordinates, project them to the common space for accuracy\n const n = positions.length;\n // Clone the array\n positions = positions.slice();\n const p = [];\n for (let i = 0; i < n; i += positionSize) {\n p[0] = positions[i];\n p[1] = positions[i + 1];\n const xy = preproject(p);\n positions[i] = xy[0];\n positions[i + 1] = xy[1];\n }\n }\n\n // Let earcut triangulate the polygon\n return earcut(positions, holeIndices, positionSize);\n}\n","/**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\nfunction isNil(value) {\n return value == null;\n}\n\nmodule.exports = isNil;\n","import _extends from 'babel-runtime/helpers/extends';\n/**\n * Webpack has bug for import loop, which is not the same behavior as ES module.\n * When util.js imports the TreeNode for tree generate will cause treeContextTypes be empty.\n */\n\nimport PropTypes from 'prop-types';\n\n/**\n * Thought we still use `cloneElement` to pass `key`,\n * other props can pass with context for future refactor.\n */\nexport var treeContextTypes = {\n rcTree: PropTypes.shape({\n root: PropTypes.object,\n\n prefixCls: PropTypes.string,\n selectable: PropTypes.bool,\n showIcon: PropTypes.bool,\n icon: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),\n draggable: PropTypes.bool,\n checkable: PropTypes.oneOfType([PropTypes.bool, PropTypes.node]),\n checkStrictly: PropTypes.bool,\n disabled: PropTypes.bool,\n openTransitionName: PropTypes.string,\n openAnimation: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),\n\n loadData: PropTypes.func,\n filterTreeNode: PropTypes.func,\n renderTreeNode: PropTypes.func,\n\n isKeyChecked: PropTypes.func,\n\n onNodeClick: PropTypes.func,\n onNodeDoubleClick: PropTypes.func,\n onNodeExpand: PropTypes.func,\n onNodeSelect: PropTypes.func,\n onNodeCheck: PropTypes.func,\n onNodeMouseEnter: PropTypes.func,\n onNodeMouseLeave: PropTypes.func,\n onNodeContextMenu: PropTypes.func,\n onNodeDragStart: PropTypes.func,\n onNodeDragEnter: PropTypes.func,\n onNodeDragOver: PropTypes.func,\n onNodeDragLeave: PropTypes.func,\n onNodeDragEnd: PropTypes.func,\n onNodeDrop: PropTypes.func\n\n // TODO: Remove this\n // onBatchNodeCheck: PropTypes.func,\n // onCheckConductFinished: PropTypes.func,\n\n // Tree will store the entities when the treeNode refresh.\n // User can pass the func to add more info to customize the additional info.\n // processTreeEntity: PropTypes.func,\n })\n};\n\nexport var nodeContextTypes = _extends({}, treeContextTypes, {\n rcTreeNode: PropTypes.shape({\n onUpCheckConduct: PropTypes.func\n })\n});","export default `\\\n#if (defined(SHADER_TYPE_FRAGMENT) && defined(LIGHTING_FRAGMENT)) || (defined(SHADER_TYPE_VERTEX) && defined(LIGHTING_VERTEX))\n\nstruct AmbientLight {\n vec3 color;\n};\n\nstruct PointLight {\n vec3 color;\n vec3 position;\n\n // Constant-Linear-Exponential\n vec3 attenuation;\n};\n\nstruct DirectionalLight {\n vec3 color;\n vec3 direction;\n};\n\nuniform AmbientLight lighting_uAmbientLight;\nuniform PointLight lighting_uPointLight[MAX_LIGHTS];\nuniform DirectionalLight lighting_uDirectionalLight[MAX_LIGHTS];\nuniform int lighting_uPointLightCount;\nuniform int lighting_uDirectionalLightCount;\n\nuniform bool lighting_uEnabled;\n\nfloat getPointLightAttenuation(PointLight pointLight, float distance) {\n return pointLight.attenuation.x\n + pointLight.attenuation.y * distance\n + pointLight.attenuation.z * distance * distance;\n}\n\n#endif\n`;\n","/** @typedef {import('../../types').ShaderModule} ShaderModule */\n\nimport lightingShader from './lights.glsl';\n\nconst INITIAL_MODULE_OPTIONS = {\n lightSources: {}\n};\n\n// Take color 0-255 and intensity as input and output 0.0-1.0 range\nfunction convertColor({color = [0, 0, 0], intensity = 1.0} = {}) {\n return color.map(component => (component * intensity) / 255.0);\n}\n\nfunction getLightSourceUniforms({ambientLight, pointLights = [], directionalLights = []}) {\n const lightSourceUniforms = {};\n\n if (ambientLight) {\n lightSourceUniforms['lighting_uAmbientLight.color'] = convertColor(ambientLight);\n } else {\n lightSourceUniforms['lighting_uAmbientLight.color'] = [0, 0, 0];\n }\n\n pointLights.forEach((pointLight, index) => {\n lightSourceUniforms[`lighting_uPointLight[${index}].color`] = convertColor(pointLight);\n lightSourceUniforms[`lighting_uPointLight[${index}].position`] = pointLight.position;\n lightSourceUniforms[`lighting_uPointLight[${index}].attenuation`] = pointLight.attenuation || [\n 1,\n 0,\n 0\n ];\n });\n lightSourceUniforms.lighting_uPointLightCount = pointLights.length;\n\n directionalLights.forEach((directionalLight, index) => {\n lightSourceUniforms[`lighting_uDirectionalLight[${index}].color`] = convertColor(\n directionalLight\n );\n lightSourceUniforms[`lighting_uDirectionalLight[${index}].direction`] =\n directionalLight.direction;\n });\n lightSourceUniforms.lighting_uDirectionalLightCount = directionalLights.length;\n\n return lightSourceUniforms;\n}\n\n// eslint-disable-next-line complexity\nfunction getUniforms(opts = INITIAL_MODULE_OPTIONS) {\n // Specify lights separately\n if ('lightSources' in opts) {\n const {ambientLight, pointLights, directionalLights} = opts.lightSources || {};\n const hasLights =\n ambientLight ||\n (pointLights && pointLights.length > 0) ||\n (directionalLights && directionalLights.length > 0);\n\n if (!hasLights) {\n return {lighting_uEnabled: false};\n }\n\n return Object.assign(\n {},\n getLightSourceUniforms({ambientLight, pointLights, directionalLights}),\n {\n lighting_uEnabled: true\n }\n );\n }\n\n // Support for array of lights. Type of light is detected by type field\n if ('lights' in opts) {\n const lightSources = {pointLights: [], directionalLights: []};\n // @ts-ignore\n for (const light of opts.lights || []) {\n switch (light.type) {\n case 'ambient':\n // Note: Only uses last ambient light\n // TODO - add ambient light sources on CPU?\n lightSources.ambientLight = light;\n break;\n case 'directional':\n lightSources.directionalLights.push(light);\n break;\n case 'point':\n lightSources.pointLights.push(light);\n break;\n default:\n // eslint-disable-next-line\n // console.warn(light.type);\n }\n }\n\n // Call the `opts.lightSources`` version\n return getUniforms({lightSources});\n }\n\n return {};\n}\n\n/** @type {ShaderModule} */\nexport const lights = {\n name: 'lights',\n vs: lightingShader,\n fs: lightingShader,\n getUniforms,\n defines: {\n MAX_LIGHTS: 3\n }\n};\n","import {log} from '@luma.gl/gltools';\nimport {Stats} from 'probe.gl';\nimport {isBrowser, global} from 'probe.gl/env';\n\n// Version detection using babel plugin\n/* global __VERSION__ */\n// @ts-ignore\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'untranspiled source';\n\nconst STARTUP_MESSAGE = 'set luma.log.level=1 (or higher) to trace rendering';\n// Assign luma.log.level in console to control logging: \\\n// 0: none, 1: minimal, 2: verbose, 3: attribute/uniforms, 4: gl logs\n// luma.log.break[], set to gl funcs, luma.log.profile[] set to model names`;\n\nclass StatsManager {\n constructor() {\n this.stats = new Map();\n }\n\n get(name) {\n if (!this.stats.has(name)) {\n this.stats.set(name, new Stats({id: name}));\n }\n\n return this.stats.get(name);\n }\n}\n\nconst lumaStats = new StatsManager();\n\nif (global.luma && global.luma.VERSION !== VERSION) {\n throw new Error(`luma.gl - multiple VERSIONs detected: ${global.luma.VERSION} vs ${VERSION}`);\n}\n\nif (!global.luma) {\n if (isBrowser()) {\n log.log(1, `luma.gl ${VERSION} - ${STARTUP_MESSAGE}`)();\n }\n\n global.luma = global.luma || {\n VERSION,\n version: VERSION,\n log,\n\n // A global stats object that various components can add information to\n // E.g. see webgl/resource.js\n stats: lumaStats,\n\n // Keep some luma globals in a sub-object\n // This allows us to dynamically detect if certain modules have been\n // included (such as IO and headless) and enable related functionality,\n // without unconditionally requiring and thus bundling big dependencies\n // into the app.\n globals: {\n modules: {},\n nodeIO: {}\n }\n };\n}\n\nexport {lumaStats};\nexport default global.luma;\n","/*! Hammer.JS - v2.0.7 - 2016-04-22\n * http://hammerjs.github.io/\n *\n * Copyright (c) 2016 Jorik Tangelder;\n * Licensed under the MIT license */\n(function(window, document, exportName, undefined) {\n 'use strict';\n\nvar VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];\nvar TEST_ELEMENT = document.createElement('div');\n\nvar TYPE_FUNCTION = 'function';\n\nvar round = Math.round;\nvar abs = Math.abs;\nvar now = Date.now;\n\n/**\n * set a timeout with a given scope\n * @param {Function} fn\n * @param {Number} timeout\n * @param {Object} context\n * @returns {number}\n */\nfunction setTimeoutContext(fn, timeout, context) {\n return setTimeout(bindFn(fn, context), timeout);\n}\n\n/**\n * if the argument is an array, we want to execute the fn on each entry\n * if it aint an array we don't want to do a thing.\n * this is used by all the methods that accept a single and array argument.\n * @param {*|Array} arg\n * @param {String} fn\n * @param {Object} [context]\n * @returns {Boolean}\n */\nfunction invokeArrayArg(arg, fn, context) {\n if (Array.isArray(arg)) {\n each(arg, context[fn], context);\n return true;\n }\n return false;\n}\n\n/**\n * walk objects and arrays\n * @param {Object} obj\n * @param {Function} iterator\n * @param {Object} context\n */\nfunction each(obj, iterator, context) {\n var i;\n\n if (!obj) {\n return;\n }\n\n if (obj.forEach) {\n obj.forEach(iterator, context);\n } else if (obj.length !== undefined) {\n i = 0;\n while (i < obj.length) {\n iterator.call(context, obj[i], i, obj);\n i++;\n }\n } else {\n for (i in obj) {\n obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);\n }\n }\n}\n\n/**\n * wrap a method with a deprecation warning and stack trace\n * @param {Function} method\n * @param {String} name\n * @param {String} message\n * @returns {Function} A new function wrapping the supplied method.\n */\nfunction deprecate(method, name, message) {\n var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\\n' + message + ' AT \\n';\n return function() {\n var e = new Error('get-stack-trace');\n var stack = e && e.stack ? e.stack.replace(/^[^\\(]+?[\\n$]/gm, '')\n .replace(/^\\s+at\\s+/gm, '')\n .replace(/^Object.\\s*\\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';\n\n var log = window.console && (window.console.warn || window.console.log);\n if (log) {\n log.call(window.console, deprecationMessage, stack);\n }\n return method.apply(this, arguments);\n };\n}\n\n/**\n * extend object.\n * means that properties in dest will be overwritten by the ones in src.\n * @param {Object} target\n * @param {...Object} objects_to_assign\n * @returns {Object} target\n */\nvar assign;\nif (typeof Object.assign !== 'function') {\n assign = function assign(target) {\n if (target === undefined || target === null) {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n\n var output = Object(target);\n for (var index = 1; index < arguments.length; index++) {\n var source = arguments[index];\n if (source !== undefined && source !== null) {\n for (var nextKey in source) {\n if (source.hasOwnProperty(nextKey)) {\n output[nextKey] = source[nextKey];\n }\n }\n }\n }\n return output;\n };\n} else {\n assign = Object.assign;\n}\n\n/**\n * extend object.\n * means that properties in dest will be overwritten by the ones in src.\n * @param {Object} dest\n * @param {Object} src\n * @param {Boolean} [merge=false]\n * @returns {Object} dest\n */\nvar extend = deprecate(function extend(dest, src, merge) {\n var keys = Object.keys(src);\n var i = 0;\n while (i < keys.length) {\n if (!merge || (merge && dest[keys[i]] === undefined)) {\n dest[keys[i]] = src[keys[i]];\n }\n i++;\n }\n return dest;\n}, 'extend', 'Use `assign`.');\n\n/**\n * merge the values from src in the dest.\n * means that properties that exist in dest will not be overwritten by src\n * @param {Object} dest\n * @param {Object} src\n * @returns {Object} dest\n */\nvar merge = deprecate(function merge(dest, src) {\n return extend(dest, src, true);\n}, 'merge', 'Use `assign`.');\n\n/**\n * simple class inheritance\n * @param {Function} child\n * @param {Function} base\n * @param {Object} [properties]\n */\nfunction inherit(child, base, properties) {\n var baseP = base.prototype,\n childP;\n\n childP = child.prototype = Object.create(baseP);\n childP.constructor = child;\n childP._super = baseP;\n\n if (properties) {\n assign(childP, properties);\n }\n}\n\n/**\n * simple function bind\n * @param {Function} fn\n * @param {Object} context\n * @returns {Function}\n */\nfunction bindFn(fn, context) {\n return function boundFn() {\n return fn.apply(context, arguments);\n };\n}\n\n/**\n * let a boolean value also be a function that must return a boolean\n * this first item in args will be used as the context\n * @param {Boolean|Function} val\n * @param {Array} [args]\n * @returns {Boolean}\n */\nfunction boolOrFn(val, args) {\n if (typeof val == TYPE_FUNCTION) {\n return val.apply(args ? args[0] || undefined : undefined, args);\n }\n return val;\n}\n\n/**\n * use the val2 when val1 is undefined\n * @param {*} val1\n * @param {*} val2\n * @returns {*}\n */\nfunction ifUndefined(val1, val2) {\n return (val1 === undefined) ? val2 : val1;\n}\n\n/**\n * addEventListener with multiple events at once\n * @param {EventTarget} target\n * @param {String} types\n * @param {Function} handler\n */\nfunction addEventListeners(target, types, handler) {\n each(splitStr(types), function(type) {\n target.addEventListener(type, handler, false);\n });\n}\n\n/**\n * removeEventListener with multiple events at once\n * @param {EventTarget} target\n * @param {String} types\n * @param {Function} handler\n */\nfunction removeEventListeners(target, types, handler) {\n each(splitStr(types), function(type) {\n target.removeEventListener(type, handler, false);\n });\n}\n\n/**\n * find if a node is in the given parent\n * @method hasParent\n * @param {HTMLElement} node\n * @param {HTMLElement} parent\n * @return {Boolean} found\n */\nfunction hasParent(node, parent) {\n while (node) {\n if (node == parent) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n}\n\n/**\n * small indexOf wrapper\n * @param {String} str\n * @param {String} find\n * @returns {Boolean} found\n */\nfunction inStr(str, find) {\n return str.indexOf(find) > -1;\n}\n\n/**\n * split string on whitespace\n * @param {String} str\n * @returns {Array} words\n */\nfunction splitStr(str) {\n return str.trim().split(/\\s+/g);\n}\n\n/**\n * find if a array contains the object using indexOf or a simple polyFill\n * @param {Array} src\n * @param {String} find\n * @param {String} [findByKey]\n * @return {Boolean|Number} false when not found, or the index\n */\nfunction inArray(src, find, findByKey) {\n if (src.indexOf && !findByKey) {\n return src.indexOf(find);\n } else {\n var i = 0;\n while (i < src.length) {\n if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {\n return i;\n }\n i++;\n }\n return -1;\n }\n}\n\n/**\n * convert array-like objects to real arrays\n * @param {Object} obj\n * @returns {Array}\n */\nfunction toArray(obj) {\n return Array.prototype.slice.call(obj, 0);\n}\n\n/**\n * unique array with objects based on a key (like 'id') or just by the array's value\n * @param {Array} src [{id:1},{id:2},{id:1}]\n * @param {String} [key]\n * @param {Boolean} [sort=False]\n * @returns {Array} [{id:1},{id:2}]\n */\nfunction uniqueArray(src, key, sort) {\n var results = [];\n var values = [];\n var i = 0;\n\n while (i < src.length) {\n var val = key ? src[i][key] : src[i];\n if (inArray(values, val) < 0) {\n results.push(src[i]);\n }\n values[i] = val;\n i++;\n }\n\n if (sort) {\n if (!key) {\n results = results.sort();\n } else {\n results = results.sort(function sortUniqueArray(a, b) {\n return a[key] > b[key];\n });\n }\n }\n\n return results;\n}\n\n/**\n * get the prefixed property\n * @param {Object} obj\n * @param {String} property\n * @returns {String|Undefined} prefixed\n */\nfunction prefixed(obj, property) {\n var prefix, prop;\n var camelProp = property[0].toUpperCase() + property.slice(1);\n\n var i = 0;\n while (i < VENDOR_PREFIXES.length) {\n prefix = VENDOR_PREFIXES[i];\n prop = (prefix) ? prefix + camelProp : property;\n\n if (prop in obj) {\n return prop;\n }\n i++;\n }\n return undefined;\n}\n\n/**\n * get a unique id\n * @returns {number} uniqueId\n */\nvar _uniqueId = 1;\nfunction uniqueId() {\n return _uniqueId++;\n}\n\n/**\n * get the window object of an element\n * @param {HTMLElement} element\n * @returns {DocumentView|Window}\n */\nfunction getWindowForElement(element) {\n var doc = element.ownerDocument || element;\n return (doc.defaultView || doc.parentWindow || window);\n}\n\nvar MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;\n\nvar SUPPORT_TOUCH = ('ontouchstart' in window);\nvar SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;\nvar SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);\n\nvar INPUT_TYPE_TOUCH = 'touch';\nvar INPUT_TYPE_PEN = 'pen';\nvar INPUT_TYPE_MOUSE = 'mouse';\nvar INPUT_TYPE_KINECT = 'kinect';\n\nvar COMPUTE_INTERVAL = 25;\n\nvar INPUT_START = 1;\nvar INPUT_MOVE = 2;\nvar INPUT_END = 4;\nvar INPUT_CANCEL = 8;\n\nvar DIRECTION_NONE = 1;\nvar DIRECTION_LEFT = 2;\nvar DIRECTION_RIGHT = 4;\nvar DIRECTION_UP = 8;\nvar DIRECTION_DOWN = 16;\n\nvar DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;\nvar DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;\nvar DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;\n\nvar PROPS_XY = ['x', 'y'];\nvar PROPS_CLIENT_XY = ['clientX', 'clientY'];\n\n/**\n * create new input type manager\n * @param {Manager} manager\n * @param {Function} callback\n * @returns {Input}\n * @constructor\n */\nfunction Input(manager, callback) {\n var self = this;\n this.manager = manager;\n this.callback = callback;\n this.element = manager.element;\n this.target = manager.options.inputTarget;\n\n // smaller wrapper around the handler, for the scope and the enabled state of the manager,\n // so when disabled the input events are completely bypassed.\n this.domHandler = function(ev) {\n if (boolOrFn(manager.options.enable, [manager])) {\n self.handler(ev);\n }\n };\n\n this.init();\n\n}\n\nInput.prototype = {\n /**\n * should handle the inputEvent data and trigger the callback\n * @virtual\n */\n handler: function() { },\n\n /**\n * bind the events\n */\n init: function() {\n this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);\n this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);\n this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);\n },\n\n /**\n * unbind the events\n */\n destroy: function() {\n this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);\n this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);\n this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);\n }\n};\n\n/**\n * create new input type manager\n * called by the Manager constructor\n * @param {Hammer} manager\n * @returns {Input}\n */\nfunction createInputInstance(manager) {\n var Type;\n var inputClass = manager.options.inputClass;\n\n if (inputClass) {\n Type = inputClass;\n } else if (SUPPORT_POINTER_EVENTS) {\n Type = PointerEventInput;\n } else if (SUPPORT_ONLY_TOUCH) {\n Type = TouchInput;\n } else if (!SUPPORT_TOUCH) {\n Type = MouseInput;\n } else {\n Type = TouchMouseInput;\n }\n return new (Type)(manager, inputHandler);\n}\n\n/**\n * handle input events\n * @param {Manager} manager\n * @param {String} eventType\n * @param {Object} input\n */\nfunction inputHandler(manager, eventType, input) {\n var pointersLen = input.pointers.length;\n var changedPointersLen = input.changedPointers.length;\n var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));\n var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));\n\n input.isFirst = !!isFirst;\n input.isFinal = !!isFinal;\n\n if (isFirst) {\n manager.session = {};\n }\n\n // source event is the normalized value of the domEvents\n // like 'touchstart, mouseup, pointerdown'\n input.eventType = eventType;\n\n // compute scale, rotation etc\n computeInputData(manager, input);\n\n // emit secret event\n manager.emit('hammer.input', input);\n\n manager.recognize(input);\n manager.session.prevInput = input;\n}\n\n/**\n * extend the data with some usable properties like scale, rotate, velocity etc\n * @param {Object} manager\n * @param {Object} input\n */\nfunction computeInputData(manager, input) {\n var session = manager.session;\n var pointers = input.pointers;\n var pointersLength = pointers.length;\n\n // store the first input to calculate the distance and direction\n if (!session.firstInput) {\n session.firstInput = simpleCloneInputData(input);\n }\n\n // to compute scale and rotation we need to store the multiple touches\n if (pointersLength > 1 && !session.firstMultiple) {\n session.firstMultiple = simpleCloneInputData(input);\n } else if (pointersLength === 1) {\n session.firstMultiple = false;\n }\n\n var firstInput = session.firstInput;\n var firstMultiple = session.firstMultiple;\n var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;\n\n var center = input.center = getCenter(pointers);\n input.timeStamp = now();\n input.deltaTime = input.timeStamp - firstInput.timeStamp;\n\n input.angle = getAngle(offsetCenter, center);\n input.distance = getDistance(offsetCenter, center);\n\n computeDeltaXY(session, input);\n input.offsetDirection = getDirection(input.deltaX, input.deltaY);\n\n var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);\n input.overallVelocityX = overallVelocity.x;\n input.overallVelocityY = overallVelocity.y;\n input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;\n\n input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;\n input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;\n\n input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >\n session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);\n\n computeIntervalInputData(session, input);\n\n // find the correct target\n var target = manager.element;\n if (hasParent(input.srcEvent.target, target)) {\n target = input.srcEvent.target;\n }\n input.target = target;\n}\n\nfunction computeDeltaXY(session, input) {\n var center = input.center;\n var offset = session.offsetDelta || {};\n var prevDelta = session.prevDelta || {};\n var prevInput = session.prevInput || {};\n\n if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {\n prevDelta = session.prevDelta = {\n x: prevInput.deltaX || 0,\n y: prevInput.deltaY || 0\n };\n\n offset = session.offsetDelta = {\n x: center.x,\n y: center.y\n };\n }\n\n input.deltaX = prevDelta.x + (center.x - offset.x);\n input.deltaY = prevDelta.y + (center.y - offset.y);\n}\n\n/**\n * velocity is calculated every x ms\n * @param {Object} session\n * @param {Object} input\n */\nfunction computeIntervalInputData(session, input) {\n var last = session.lastInterval || input,\n deltaTime = input.timeStamp - last.timeStamp,\n velocity, velocityX, velocityY, direction;\n\n if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {\n var deltaX = input.deltaX - last.deltaX;\n var deltaY = input.deltaY - last.deltaY;\n\n var v = getVelocity(deltaTime, deltaX, deltaY);\n velocityX = v.x;\n velocityY = v.y;\n velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;\n direction = getDirection(deltaX, deltaY);\n\n session.lastInterval = input;\n } else {\n // use latest velocity info if it doesn't overtake a minimum period\n velocity = last.velocity;\n velocityX = last.velocityX;\n velocityY = last.velocityY;\n direction = last.direction;\n }\n\n input.velocity = velocity;\n input.velocityX = velocityX;\n input.velocityY = velocityY;\n input.direction = direction;\n}\n\n/**\n * create a simple clone from the input used for storage of firstInput and firstMultiple\n * @param {Object} input\n * @returns {Object} clonedInputData\n */\nfunction simpleCloneInputData(input) {\n // make a simple copy of the pointers because we will get a reference if we don't\n // we only need clientXY for the calculations\n var pointers = [];\n var i = 0;\n while (i < input.pointers.length) {\n pointers[i] = {\n clientX: round(input.pointers[i].clientX),\n clientY: round(input.pointers[i].clientY)\n };\n i++;\n }\n\n return {\n timeStamp: now(),\n pointers: pointers,\n center: getCenter(pointers),\n deltaX: input.deltaX,\n deltaY: input.deltaY\n };\n}\n\n/**\n * get the center of all the pointers\n * @param {Array} pointers\n * @return {Object} center contains `x` and `y` properties\n */\nfunction getCenter(pointers) {\n var pointersLength = pointers.length;\n\n // no need to loop when only one touch\n if (pointersLength === 1) {\n return {\n x: round(pointers[0].clientX),\n y: round(pointers[0].clientY)\n };\n }\n\n var x = 0, y = 0, i = 0;\n while (i < pointersLength) {\n x += pointers[i].clientX;\n y += pointers[i].clientY;\n i++;\n }\n\n return {\n x: round(x / pointersLength),\n y: round(y / pointersLength)\n };\n}\n\n/**\n * calculate the velocity between two points. unit is in px per ms.\n * @param {Number} deltaTime\n * @param {Number} x\n * @param {Number} y\n * @return {Object} velocity `x` and `y`\n */\nfunction getVelocity(deltaTime, x, y) {\n return {\n x: x / deltaTime || 0,\n y: y / deltaTime || 0\n };\n}\n\n/**\n * get the direction between two points\n * @param {Number} x\n * @param {Number} y\n * @return {Number} direction\n */\nfunction getDirection(x, y) {\n if (x === y) {\n return DIRECTION_NONE;\n }\n\n if (abs(x) >= abs(y)) {\n return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;\n }\n return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;\n}\n\n/**\n * calculate the absolute distance between two points\n * @param {Object} p1 {x, y}\n * @param {Object} p2 {x, y}\n * @param {Array} [props] containing x and y keys\n * @return {Number} distance\n */\nfunction getDistance(p1, p2, props) {\n if (!props) {\n props = PROPS_XY;\n }\n var x = p2[props[0]] - p1[props[0]],\n y = p2[props[1]] - p1[props[1]];\n\n return Math.sqrt((x * x) + (y * y));\n}\n\n/**\n * calculate the angle between two coordinates\n * @param {Object} p1\n * @param {Object} p2\n * @param {Array} [props] containing x and y keys\n * @return {Number} angle\n */\nfunction getAngle(p1, p2, props) {\n if (!props) {\n props = PROPS_XY;\n }\n var x = p2[props[0]] - p1[props[0]],\n y = p2[props[1]] - p1[props[1]];\n return Math.atan2(y, x) * 180 / Math.PI;\n}\n\n/**\n * calculate the rotation degrees between two pointersets\n * @param {Array} start array of pointers\n * @param {Array} end array of pointers\n * @return {Number} rotation\n */\nfunction getRotation(start, end) {\n return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);\n}\n\n/**\n * calculate the scale factor between two pointersets\n * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out\n * @param {Array} start array of pointers\n * @param {Array} end array of pointers\n * @return {Number} scale\n */\nfunction getScale(start, end) {\n return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);\n}\n\nvar MOUSE_INPUT_MAP = {\n mousedown: INPUT_START,\n mousemove: INPUT_MOVE,\n mouseup: INPUT_END\n};\n\nvar MOUSE_ELEMENT_EVENTS = 'mousedown';\nvar MOUSE_WINDOW_EVENTS = 'mousemove mouseup';\n\n/**\n * Mouse events input\n * @constructor\n * @extends Input\n */\nfunction MouseInput() {\n this.evEl = MOUSE_ELEMENT_EVENTS;\n this.evWin = MOUSE_WINDOW_EVENTS;\n\n this.pressed = false; // mousedown state\n\n Input.apply(this, arguments);\n}\n\ninherit(MouseInput, Input, {\n /**\n * handle mouse events\n * @param {Object} ev\n */\n handler: function MEhandler(ev) {\n var eventType = MOUSE_INPUT_MAP[ev.type];\n\n // on start we want to have the left mouse button down\n if (eventType & INPUT_START && ev.button === 0) {\n this.pressed = true;\n }\n\n if (eventType & INPUT_MOVE && ev.which !== 1) {\n eventType = INPUT_END;\n }\n\n // mouse must be down\n if (!this.pressed) {\n return;\n }\n\n if (eventType & INPUT_END) {\n this.pressed = false;\n }\n\n this.callback(this.manager, eventType, {\n pointers: [ev],\n changedPointers: [ev],\n pointerType: INPUT_TYPE_MOUSE,\n srcEvent: ev\n });\n }\n});\n\nvar POINTER_INPUT_MAP = {\n pointerdown: INPUT_START,\n pointermove: INPUT_MOVE,\n pointerup: INPUT_END,\n pointercancel: INPUT_CANCEL,\n pointerout: INPUT_CANCEL\n};\n\n// in IE10 the pointer types is defined as an enum\nvar IE10_POINTER_TYPE_ENUM = {\n 2: INPUT_TYPE_TOUCH,\n 3: INPUT_TYPE_PEN,\n 4: INPUT_TYPE_MOUSE,\n 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816\n};\n\nvar POINTER_ELEMENT_EVENTS = 'pointerdown';\nvar POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';\n\n// IE10 has prefixed support, and case-sensitive\nif (window.MSPointerEvent && !window.PointerEvent) {\n POINTER_ELEMENT_EVENTS = 'MSPointerDown';\n POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';\n}\n\n/**\n * Pointer events input\n * @constructor\n * @extends Input\n */\nfunction PointerEventInput() {\n this.evEl = POINTER_ELEMENT_EVENTS;\n this.evWin = POINTER_WINDOW_EVENTS;\n\n Input.apply(this, arguments);\n\n this.store = (this.manager.session.pointerEvents = []);\n}\n\ninherit(PointerEventInput, Input, {\n /**\n * handle mouse events\n * @param {Object} ev\n */\n handler: function PEhandler(ev) {\n var store = this.store;\n var removePointer = false;\n\n var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');\n var eventType = POINTER_INPUT_MAP[eventTypeNormalized];\n var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;\n\n var isTouch = (pointerType == INPUT_TYPE_TOUCH);\n\n // get index of the event in the store\n var storeIndex = inArray(store, ev.pointerId, 'pointerId');\n\n // start and mouse must be down\n if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {\n if (storeIndex < 0) {\n store.push(ev);\n storeIndex = store.length - 1;\n }\n } else if (eventType & (INPUT_END | INPUT_CANCEL)) {\n removePointer = true;\n }\n\n // it not found, so the pointer hasn't been down (so it's probably a hover)\n if (storeIndex < 0) {\n return;\n }\n\n // update the event in the store\n store[storeIndex] = ev;\n\n this.callback(this.manager, eventType, {\n pointers: store,\n changedPointers: [ev],\n pointerType: pointerType,\n srcEvent: ev\n });\n\n if (removePointer) {\n // remove from the store\n store.splice(storeIndex, 1);\n }\n }\n});\n\nvar SINGLE_TOUCH_INPUT_MAP = {\n touchstart: INPUT_START,\n touchmove: INPUT_MOVE,\n touchend: INPUT_END,\n touchcancel: INPUT_CANCEL\n};\n\nvar SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';\nvar SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';\n\n/**\n * Touch events input\n * @constructor\n * @extends Input\n */\nfunction SingleTouchInput() {\n this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;\n this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;\n this.started = false;\n\n Input.apply(this, arguments);\n}\n\ninherit(SingleTouchInput, Input, {\n handler: function TEhandler(ev) {\n var type = SINGLE_TOUCH_INPUT_MAP[ev.type];\n\n // should we handle the touch events?\n if (type === INPUT_START) {\n this.started = true;\n }\n\n if (!this.started) {\n return;\n }\n\n var touches = normalizeSingleTouches.call(this, ev, type);\n\n // when done, reset the started state\n if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {\n this.started = false;\n }\n\n this.callback(this.manager, type, {\n pointers: touches[0],\n changedPointers: touches[1],\n pointerType: INPUT_TYPE_TOUCH,\n srcEvent: ev\n });\n }\n});\n\n/**\n * @this {TouchInput}\n * @param {Object} ev\n * @param {Number} type flag\n * @returns {undefined|Array} [all, changed]\n */\nfunction normalizeSingleTouches(ev, type) {\n var all = toArray(ev.touches);\n var changed = toArray(ev.changedTouches);\n\n if (type & (INPUT_END | INPUT_CANCEL)) {\n all = uniqueArray(all.concat(changed), 'identifier', true);\n }\n\n return [all, changed];\n}\n\nvar TOUCH_INPUT_MAP = {\n touchstart: INPUT_START,\n touchmove: INPUT_MOVE,\n touchend: INPUT_END,\n touchcancel: INPUT_CANCEL\n};\n\nvar TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';\n\n/**\n * Multi-user touch events input\n * @constructor\n * @extends Input\n */\nfunction TouchInput() {\n this.evTarget = TOUCH_TARGET_EVENTS;\n this.targetIds = {};\n\n Input.apply(this, arguments);\n}\n\ninherit(TouchInput, Input, {\n handler: function MTEhandler(ev) {\n var type = TOUCH_INPUT_MAP[ev.type];\n var touches = getTouches.call(this, ev, type);\n if (!touches) {\n return;\n }\n\n this.callback(this.manager, type, {\n pointers: touches[0],\n changedPointers: touches[1],\n pointerType: INPUT_TYPE_TOUCH,\n srcEvent: ev\n });\n }\n});\n\n/**\n * @this {TouchInput}\n * @param {Object} ev\n * @param {Number} type flag\n * @returns {undefined|Array} [all, changed]\n */\nfunction getTouches(ev, type) {\n var allTouches = toArray(ev.touches);\n var targetIds = this.targetIds;\n\n // when there is only one touch, the process can be simplified\n if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {\n targetIds[allTouches[0].identifier] = true;\n return [allTouches, allTouches];\n }\n\n var i,\n targetTouches,\n changedTouches = toArray(ev.changedTouches),\n changedTargetTouches = [],\n target = this.target;\n\n // get target touches from touches\n targetTouches = allTouches.filter(function(touch) {\n return hasParent(touch.target, target);\n });\n\n // collect touches\n if (type === INPUT_START) {\n i = 0;\n while (i < targetTouches.length) {\n targetIds[targetTouches[i].identifier] = true;\n i++;\n }\n }\n\n // filter changed touches to only contain touches that exist in the collected target ids\n i = 0;\n while (i < changedTouches.length) {\n if (targetIds[changedTouches[i].identifier]) {\n changedTargetTouches.push(changedTouches[i]);\n }\n\n // cleanup removed touches\n if (type & (INPUT_END | INPUT_CANCEL)) {\n delete targetIds[changedTouches[i].identifier];\n }\n i++;\n }\n\n if (!changedTargetTouches.length) {\n return;\n }\n\n return [\n // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'\n uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),\n changedTargetTouches\n ];\n}\n\n/**\n * Combined touch and mouse input\n *\n * Touch has a higher priority then mouse, and while touching no mouse events are allowed.\n * This because touch devices also emit mouse events while doing a touch.\n *\n * @constructor\n * @extends Input\n */\n\nvar DEDUP_TIMEOUT = 2500;\nvar DEDUP_DISTANCE = 25;\n\nfunction TouchMouseInput() {\n Input.apply(this, arguments);\n\n var handler = bindFn(this.handler, this);\n this.touch = new TouchInput(this.manager, handler);\n this.mouse = new MouseInput(this.manager, handler);\n\n this.primaryTouch = null;\n this.lastTouches = [];\n}\n\ninherit(TouchMouseInput, Input, {\n /**\n * handle mouse and touch events\n * @param {Hammer} manager\n * @param {String} inputEvent\n * @param {Object} inputData\n */\n handler: function TMEhandler(manager, inputEvent, inputData) {\n var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),\n isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);\n\n if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {\n return;\n }\n\n // when we're in a touch event, record touches to de-dupe synthetic mouse event\n if (isTouch) {\n recordTouches.call(this, inputEvent, inputData);\n } else if (isMouse && isSyntheticEvent.call(this, inputData)) {\n return;\n }\n\n this.callback(manager, inputEvent, inputData);\n },\n\n /**\n * remove the event listeners\n */\n destroy: function destroy() {\n this.touch.destroy();\n this.mouse.destroy();\n }\n});\n\nfunction recordTouches(eventType, eventData) {\n if (eventType & INPUT_START) {\n this.primaryTouch = eventData.changedPointers[0].identifier;\n setLastTouch.call(this, eventData);\n } else if (eventType & (INPUT_END | INPUT_CANCEL)) {\n setLastTouch.call(this, eventData);\n }\n}\n\nfunction setLastTouch(eventData) {\n var touch = eventData.changedPointers[0];\n\n if (touch.identifier === this.primaryTouch) {\n var lastTouch = {x: touch.clientX, y: touch.clientY};\n this.lastTouches.push(lastTouch);\n var lts = this.lastTouches;\n var removeLastTouch = function() {\n var i = lts.indexOf(lastTouch);\n if (i > -1) {\n lts.splice(i, 1);\n }\n };\n setTimeout(removeLastTouch, DEDUP_TIMEOUT);\n }\n}\n\nfunction isSyntheticEvent(eventData) {\n var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY;\n for (var i = 0; i < this.lastTouches.length; i++) {\n var t = this.lastTouches[i];\n var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);\n if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {\n return true;\n }\n }\n return false;\n}\n\nvar PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');\nvar NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;\n\n// magical touchAction value\nvar TOUCH_ACTION_COMPUTE = 'compute';\nvar TOUCH_ACTION_AUTO = 'auto';\nvar TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented\nvar TOUCH_ACTION_NONE = 'none';\nvar TOUCH_ACTION_PAN_X = 'pan-x';\nvar TOUCH_ACTION_PAN_Y = 'pan-y';\nvar TOUCH_ACTION_MAP = getTouchActionProps();\n\n/**\n * Touch Action\n * sets the touchAction property or uses the js alternative\n * @param {Manager} manager\n * @param {String} value\n * @constructor\n */\nfunction TouchAction(manager, value) {\n this.manager = manager;\n this.set(value);\n}\n\nTouchAction.prototype = {\n /**\n * set the touchAction value on the element or enable the polyfill\n * @param {String} value\n */\n set: function(value) {\n // find out the touch-action by the event handlers\n if (value == TOUCH_ACTION_COMPUTE) {\n value = this.compute();\n }\n\n if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {\n this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;\n }\n this.actions = value.toLowerCase().trim();\n },\n\n /**\n * just re-set the touchAction value\n */\n update: function() {\n this.set(this.manager.options.touchAction);\n },\n\n /**\n * compute the value for the touchAction property based on the recognizer's settings\n * @returns {String} value\n */\n compute: function() {\n var actions = [];\n each(this.manager.recognizers, function(recognizer) {\n if (boolOrFn(recognizer.options.enable, [recognizer])) {\n actions = actions.concat(recognizer.getTouchAction());\n }\n });\n return cleanTouchActions(actions.join(' '));\n },\n\n /**\n * this method is called on each input cycle and provides the preventing of the browser behavior\n * @param {Object} input\n */\n preventDefaults: function(input) {\n var srcEvent = input.srcEvent;\n var direction = input.offsetDirection;\n\n // if the touch action did prevented once this session\n if (this.manager.session.prevented) {\n srcEvent.preventDefault();\n return;\n }\n\n var actions = this.actions;\n var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];\n var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];\n var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];\n\n if (hasNone) {\n //do not prevent defaults if this is a tap gesture\n\n var isTapPointer = input.pointers.length === 1;\n var isTapMovement = input.distance < 2;\n var isTapTouchTime = input.deltaTime < 250;\n\n if (isTapPointer && isTapMovement && isTapTouchTime) {\n return;\n }\n }\n\n if (hasPanX && hasPanY) {\n // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent\n return;\n }\n\n if (hasNone ||\n (hasPanY && direction & DIRECTION_HORIZONTAL) ||\n (hasPanX && direction & DIRECTION_VERTICAL)) {\n return this.preventSrc(srcEvent);\n }\n },\n\n /**\n * call preventDefault to prevent the browser's default behavior (scrolling in most cases)\n * @param {Object} srcEvent\n */\n preventSrc: function(srcEvent) {\n this.manager.session.prevented = true;\n srcEvent.preventDefault();\n }\n};\n\n/**\n * when the touchActions are collected they are not a valid value, so we need to clean things up. *\n * @param {String} actions\n * @returns {*}\n */\nfunction cleanTouchActions(actions) {\n // none\n if (inStr(actions, TOUCH_ACTION_NONE)) {\n return TOUCH_ACTION_NONE;\n }\n\n var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);\n var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);\n\n // if both pan-x and pan-y are set (different recognizers\n // for different directions, e.g. horizontal pan but vertical swipe?)\n // we need none (as otherwise with pan-x pan-y combined none of these\n // recognizers will work, since the browser would handle all panning\n if (hasPanX && hasPanY) {\n return TOUCH_ACTION_NONE;\n }\n\n // pan-x OR pan-y\n if (hasPanX || hasPanY) {\n return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;\n }\n\n // manipulation\n if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {\n return TOUCH_ACTION_MANIPULATION;\n }\n\n return TOUCH_ACTION_AUTO;\n}\n\nfunction getTouchActionProps() {\n if (!NATIVE_TOUCH_ACTION) {\n return false;\n }\n var touchMap = {};\n var cssSupports = window.CSS && window.CSS.supports;\n ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) {\n\n // If css.supports is not supported but there is native touch-action assume it supports\n // all values. This is the case for IE 10 and 11.\n touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;\n });\n return touchMap;\n}\n\n/**\n * Recognizer flow explained; *\n * All recognizers have the initial state of POSSIBLE when a input session starts.\n * The definition of a input session is from the first input until the last input, with all it's movement in it. *\n * Example session for mouse-input: mousedown -> mousemove -> mouseup\n *\n * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed\n * which determines with state it should be.\n *\n * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to\n * POSSIBLE to give it another change on the next cycle.\n *\n * Possible\n * |\n * +-----+---------------+\n * | |\n * +-----+-----+ |\n * | | |\n * Failed Cancelled |\n * +-------+------+\n * | |\n * Recognized Began\n * |\n * Changed\n * |\n * Ended/Recognized\n */\nvar STATE_POSSIBLE = 1;\nvar STATE_BEGAN = 2;\nvar STATE_CHANGED = 4;\nvar STATE_ENDED = 8;\nvar STATE_RECOGNIZED = STATE_ENDED;\nvar STATE_CANCELLED = 16;\nvar STATE_FAILED = 32;\n\n/**\n * Recognizer\n * Every recognizer needs to extend from this class.\n * @constructor\n * @param {Object} options\n */\nfunction Recognizer(options) {\n this.options = assign({}, this.defaults, options || {});\n\n this.id = uniqueId();\n\n this.manager = null;\n\n // default is enable true\n this.options.enable = ifUndefined(this.options.enable, true);\n\n this.state = STATE_POSSIBLE;\n\n this.simultaneous = {};\n this.requireFail = [];\n}\n\nRecognizer.prototype = {\n /**\n * @virtual\n * @type {Object}\n */\n defaults: {},\n\n /**\n * set options\n * @param {Object} options\n * @return {Recognizer}\n */\n set: function(options) {\n assign(this.options, options);\n\n // also update the touchAction, in case something changed about the directions/enabled state\n this.manager && this.manager.touchAction.update();\n return this;\n },\n\n /**\n * recognize simultaneous with an other recognizer.\n * @param {Recognizer} otherRecognizer\n * @returns {Recognizer} this\n */\n recognizeWith: function(otherRecognizer) {\n if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {\n return this;\n }\n\n var simultaneous = this.simultaneous;\n otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);\n if (!simultaneous[otherRecognizer.id]) {\n simultaneous[otherRecognizer.id] = otherRecognizer;\n otherRecognizer.recognizeWith(this);\n }\n return this;\n },\n\n /**\n * drop the simultaneous link. it doesnt remove the link on the other recognizer.\n * @param {Recognizer} otherRecognizer\n * @returns {Recognizer} this\n */\n dropRecognizeWith: function(otherRecognizer) {\n if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {\n return this;\n }\n\n otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);\n delete this.simultaneous[otherRecognizer.id];\n return this;\n },\n\n /**\n * recognizer can only run when an other is failing\n * @param {Recognizer} otherRecognizer\n * @returns {Recognizer} this\n */\n requireFailure: function(otherRecognizer) {\n if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {\n return this;\n }\n\n var requireFail = this.requireFail;\n otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);\n if (inArray(requireFail, otherRecognizer) === -1) {\n requireFail.push(otherRecognizer);\n otherRecognizer.requireFailure(this);\n }\n return this;\n },\n\n /**\n * drop the requireFailure link. it does not remove the link on the other recognizer.\n * @param {Recognizer} otherRecognizer\n * @returns {Recognizer} this\n */\n dropRequireFailure: function(otherRecognizer) {\n if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {\n return this;\n }\n\n otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);\n var index = inArray(this.requireFail, otherRecognizer);\n if (index > -1) {\n this.requireFail.splice(index, 1);\n }\n return this;\n },\n\n /**\n * has require failures boolean\n * @returns {boolean}\n */\n hasRequireFailures: function() {\n return this.requireFail.length > 0;\n },\n\n /**\n * if the recognizer can recognize simultaneous with an other recognizer\n * @param {Recognizer} otherRecognizer\n * @returns {Boolean}\n */\n canRecognizeWith: function(otherRecognizer) {\n return !!this.simultaneous[otherRecognizer.id];\n },\n\n /**\n * You should use `tryEmit` instead of `emit` directly to check\n * that all the needed recognizers has failed before emitting.\n * @param {Object} input\n */\n emit: function(input) {\n var self = this;\n var state = this.state;\n\n function emit(event) {\n self.manager.emit(event, input);\n }\n\n // 'panstart' and 'panmove'\n if (state < STATE_ENDED) {\n emit(self.options.event + stateStr(state));\n }\n\n emit(self.options.event); // simple 'eventName' events\n\n if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)\n emit(input.additionalEvent);\n }\n\n // panend and pancancel\n if (state >= STATE_ENDED) {\n emit(self.options.event + stateStr(state));\n }\n },\n\n /**\n * Check that all the require failure recognizers has failed,\n * if true, it emits a gesture event,\n * otherwise, setup the state to FAILED.\n * @param {Object} input\n */\n tryEmit: function(input) {\n if (this.canEmit()) {\n return this.emit(input);\n }\n // it's failing anyway\n this.state = STATE_FAILED;\n },\n\n /**\n * can we emit?\n * @returns {boolean}\n */\n canEmit: function() {\n var i = 0;\n while (i < this.requireFail.length) {\n if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {\n return false;\n }\n i++;\n }\n return true;\n },\n\n /**\n * update the recognizer\n * @param {Object} inputData\n */\n recognize: function(inputData) {\n // make a new copy of the inputData\n // so we can change the inputData without messing up the other recognizers\n var inputDataClone = assign({}, inputData);\n\n // is is enabled and allow recognizing?\n if (!boolOrFn(this.options.enable, [this, inputDataClone])) {\n this.reset();\n this.state = STATE_FAILED;\n return;\n }\n\n // reset when we've reached the end\n if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {\n this.state = STATE_POSSIBLE;\n }\n\n this.state = this.process(inputDataClone);\n\n // the recognizer has recognized a gesture\n // so trigger an event\n if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {\n this.tryEmit(inputDataClone);\n }\n },\n\n /**\n * return the state of the recognizer\n * the actual recognizing happens in this method\n * @virtual\n * @param {Object} inputData\n * @returns {Const} STATE\n */\n process: function(inputData) { }, // jshint ignore:line\n\n /**\n * return the preferred touch-action\n * @virtual\n * @returns {Array}\n */\n getTouchAction: function() { },\n\n /**\n * called when the gesture isn't allowed to recognize\n * like when another is being recognized or it is disabled\n * @virtual\n */\n reset: function() { }\n};\n\n/**\n * get a usable string, used as event postfix\n * @param {Const} state\n * @returns {String} state\n */\nfunction stateStr(state) {\n if (state & STATE_CANCELLED) {\n return 'cancel';\n } else if (state & STATE_ENDED) {\n return 'end';\n } else if (state & STATE_CHANGED) {\n return 'move';\n } else if (state & STATE_BEGAN) {\n return 'start';\n }\n return '';\n}\n\n/**\n * direction cons to string\n * @param {Const} direction\n * @returns {String}\n */\nfunction directionStr(direction) {\n if (direction == DIRECTION_DOWN) {\n return 'down';\n } else if (direction == DIRECTION_UP) {\n return 'up';\n } else if (direction == DIRECTION_LEFT) {\n return 'left';\n } else if (direction == DIRECTION_RIGHT) {\n return 'right';\n }\n return '';\n}\n\n/**\n * get a recognizer by name if it is bound to a manager\n * @param {Recognizer|String} otherRecognizer\n * @param {Recognizer} recognizer\n * @returns {Recognizer}\n */\nfunction getRecognizerByNameIfManager(otherRecognizer, recognizer) {\n var manager = recognizer.manager;\n if (manager) {\n return manager.get(otherRecognizer);\n }\n return otherRecognizer;\n}\n\n/**\n * This recognizer is just used as a base for the simple attribute recognizers.\n * @constructor\n * @extends Recognizer\n */\nfunction AttrRecognizer() {\n Recognizer.apply(this, arguments);\n}\n\ninherit(AttrRecognizer, Recognizer, {\n /**\n * @namespace\n * @memberof AttrRecognizer\n */\n defaults: {\n /**\n * @type {Number}\n * @default 1\n */\n pointers: 1\n },\n\n /**\n * Used to check if it the recognizer receives valid input, like input.distance > 10.\n * @memberof AttrRecognizer\n * @param {Object} input\n * @returns {Boolean} recognized\n */\n attrTest: function(input) {\n var optionPointers = this.options.pointers;\n return optionPointers === 0 || input.pointers.length === optionPointers;\n },\n\n /**\n * Process the input and return the state for the recognizer\n * @memberof AttrRecognizer\n * @param {Object} input\n * @returns {*} State\n */\n process: function(input) {\n var state = this.state;\n var eventType = input.eventType;\n\n var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);\n var isValid = this.attrTest(input);\n\n // on cancel input and we've recognized before, return STATE_CANCELLED\n if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {\n return state | STATE_CANCELLED;\n } else if (isRecognized || isValid) {\n if (eventType & INPUT_END) {\n return state | STATE_ENDED;\n } else if (!(state & STATE_BEGAN)) {\n return STATE_BEGAN;\n }\n return state | STATE_CHANGED;\n }\n return STATE_FAILED;\n }\n});\n\n/**\n * Pan\n * Recognized when the pointer is down and moved in the allowed direction.\n * @constructor\n * @extends AttrRecognizer\n */\nfunction PanRecognizer() {\n AttrRecognizer.apply(this, arguments);\n\n this.pX = null;\n this.pY = null;\n}\n\ninherit(PanRecognizer, AttrRecognizer, {\n /**\n * @namespace\n * @memberof PanRecognizer\n */\n defaults: {\n event: 'pan',\n threshold: 10,\n pointers: 1,\n direction: DIRECTION_ALL\n },\n\n getTouchAction: function() {\n var direction = this.options.direction;\n var actions = [];\n if (direction & DIRECTION_HORIZONTAL) {\n actions.push(TOUCH_ACTION_PAN_Y);\n }\n if (direction & DIRECTION_VERTICAL) {\n actions.push(TOUCH_ACTION_PAN_X);\n }\n return actions;\n },\n\n directionTest: function(input) {\n var options = this.options;\n var hasMoved = true;\n var distance = input.distance;\n var direction = input.direction;\n var x = input.deltaX;\n var y = input.deltaY;\n\n // lock to axis?\n if (!(direction & options.direction)) {\n if (options.direction & DIRECTION_HORIZONTAL) {\n direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;\n hasMoved = x != this.pX;\n distance = Math.abs(input.deltaX);\n } else {\n direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;\n hasMoved = y != this.pY;\n distance = Math.abs(input.deltaY);\n }\n }\n input.direction = direction;\n return hasMoved && distance > options.threshold && direction & options.direction;\n },\n\n attrTest: function(input) {\n return AttrRecognizer.prototype.attrTest.call(this, input) &&\n (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));\n },\n\n emit: function(input) {\n\n this.pX = input.deltaX;\n this.pY = input.deltaY;\n\n var direction = directionStr(input.direction);\n\n if (direction) {\n input.additionalEvent = this.options.event + direction;\n }\n this._super.emit.call(this, input);\n }\n});\n\n/**\n * Pinch\n * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).\n * @constructor\n * @extends AttrRecognizer\n */\nfunction PinchRecognizer() {\n AttrRecognizer.apply(this, arguments);\n}\n\ninherit(PinchRecognizer, AttrRecognizer, {\n /**\n * @namespace\n * @memberof PinchRecognizer\n */\n defaults: {\n event: 'pinch',\n threshold: 0,\n pointers: 2\n },\n\n getTouchAction: function() {\n return [TOUCH_ACTION_NONE];\n },\n\n attrTest: function(input) {\n return this._super.attrTest.call(this, input) &&\n (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);\n },\n\n emit: function(input) {\n if (input.scale !== 1) {\n var inOut = input.scale < 1 ? 'in' : 'out';\n input.additionalEvent = this.options.event + inOut;\n }\n this._super.emit.call(this, input);\n }\n});\n\n/**\n * Press\n * Recognized when the pointer is down for x ms without any movement.\n * @constructor\n * @extends Recognizer\n */\nfunction PressRecognizer() {\n Recognizer.apply(this, arguments);\n\n this._timer = null;\n this._input = null;\n}\n\ninherit(PressRecognizer, Recognizer, {\n /**\n * @namespace\n * @memberof PressRecognizer\n */\n defaults: {\n event: 'press',\n pointers: 1,\n time: 251, // minimal time of the pointer to be pressed\n threshold: 9 // a minimal movement is ok, but keep it low\n },\n\n getTouchAction: function() {\n return [TOUCH_ACTION_AUTO];\n },\n\n process: function(input) {\n var options = this.options;\n var validPointers = input.pointers.length === options.pointers;\n var validMovement = input.distance < options.threshold;\n var validTime = input.deltaTime > options.time;\n\n this._input = input;\n\n // we only allow little movement\n // and we've reached an end event, so a tap is possible\n if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {\n this.reset();\n } else if (input.eventType & INPUT_START) {\n this.reset();\n this._timer = setTimeoutContext(function() {\n this.state = STATE_RECOGNIZED;\n this.tryEmit();\n }, options.time, this);\n } else if (input.eventType & INPUT_END) {\n return STATE_RECOGNIZED;\n }\n return STATE_FAILED;\n },\n\n reset: function() {\n clearTimeout(this._timer);\n },\n\n emit: function(input) {\n if (this.state !== STATE_RECOGNIZED) {\n return;\n }\n\n if (input && (input.eventType & INPUT_END)) {\n this.manager.emit(this.options.event + 'up', input);\n } else {\n this._input.timeStamp = now();\n this.manager.emit(this.options.event, this._input);\n }\n }\n});\n\n/**\n * Rotate\n * Recognized when two or more pointer are moving in a circular motion.\n * @constructor\n * @extends AttrRecognizer\n */\nfunction RotateRecognizer() {\n AttrRecognizer.apply(this, arguments);\n}\n\ninherit(RotateRecognizer, AttrRecognizer, {\n /**\n * @namespace\n * @memberof RotateRecognizer\n */\n defaults: {\n event: 'rotate',\n threshold: 0,\n pointers: 2\n },\n\n getTouchAction: function() {\n return [TOUCH_ACTION_NONE];\n },\n\n attrTest: function(input) {\n return this._super.attrTest.call(this, input) &&\n (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);\n }\n});\n\n/**\n * Swipe\n * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.\n * @constructor\n * @extends AttrRecognizer\n */\nfunction SwipeRecognizer() {\n AttrRecognizer.apply(this, arguments);\n}\n\ninherit(SwipeRecognizer, AttrRecognizer, {\n /**\n * @namespace\n * @memberof SwipeRecognizer\n */\n defaults: {\n event: 'swipe',\n threshold: 10,\n velocity: 0.3,\n direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,\n pointers: 1\n },\n\n getTouchAction: function() {\n return PanRecognizer.prototype.getTouchAction.call(this);\n },\n\n attrTest: function(input) {\n var direction = this.options.direction;\n var velocity;\n\n if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {\n velocity = input.overallVelocity;\n } else if (direction & DIRECTION_HORIZONTAL) {\n velocity = input.overallVelocityX;\n } else if (direction & DIRECTION_VERTICAL) {\n velocity = input.overallVelocityY;\n }\n\n return this._super.attrTest.call(this, input) &&\n direction & input.offsetDirection &&\n input.distance > this.options.threshold &&\n input.maxPointers == this.options.pointers &&\n abs(velocity) > this.options.velocity && input.eventType & INPUT_END;\n },\n\n emit: function(input) {\n var direction = directionStr(input.offsetDirection);\n if (direction) {\n this.manager.emit(this.options.event + direction, input);\n }\n\n this.manager.emit(this.options.event, input);\n }\n});\n\n/**\n * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur\n * between the given interval and position. The delay option can be used to recognize multi-taps without firing\n * a single tap.\n *\n * The eventData from the emitted event contains the property `tapCount`, which contains the amount of\n * multi-taps being recognized.\n * @constructor\n * @extends Recognizer\n */\nfunction TapRecognizer() {\n Recognizer.apply(this, arguments);\n\n // previous time and center,\n // used for tap counting\n this.pTime = false;\n this.pCenter = false;\n\n this._timer = null;\n this._input = null;\n this.count = 0;\n}\n\ninherit(TapRecognizer, Recognizer, {\n /**\n * @namespace\n * @memberof PinchRecognizer\n */\n defaults: {\n event: 'tap',\n pointers: 1,\n taps: 1,\n interval: 300, // max time between the multi-tap taps\n time: 250, // max time of the pointer to be down (like finger on the screen)\n threshold: 9, // a minimal movement is ok, but keep it low\n posThreshold: 10 // a multi-tap can be a bit off the initial position\n },\n\n getTouchAction: function() {\n return [TOUCH_ACTION_MANIPULATION];\n },\n\n process: function(input) {\n var options = this.options;\n\n var validPointers = input.pointers.length === options.pointers;\n var validMovement = input.distance < options.threshold;\n var validTouchTime = input.deltaTime < options.time;\n\n this.reset();\n\n if ((input.eventType & INPUT_START) && (this.count === 0)) {\n return this.failTimeout();\n }\n\n // we only allow little movement\n // and we've reached an end event, so a tap is possible\n if (validMovement && validTouchTime && validPointers) {\n if (input.eventType != INPUT_END) {\n return this.failTimeout();\n }\n\n var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;\n var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;\n\n this.pTime = input.timeStamp;\n this.pCenter = input.center;\n\n if (!validMultiTap || !validInterval) {\n this.count = 1;\n } else {\n this.count += 1;\n }\n\n this._input = input;\n\n // if tap count matches we have recognized it,\n // else it has began recognizing...\n var tapCount = this.count % options.taps;\n if (tapCount === 0) {\n // no failing requirements, immediately trigger the tap event\n // or wait as long as the multitap interval to trigger\n if (!this.hasRequireFailures()) {\n return STATE_RECOGNIZED;\n } else {\n this._timer = setTimeoutContext(function() {\n this.state = STATE_RECOGNIZED;\n this.tryEmit();\n }, options.interval, this);\n return STATE_BEGAN;\n }\n }\n }\n return STATE_FAILED;\n },\n\n failTimeout: function() {\n this._timer = setTimeoutContext(function() {\n this.state = STATE_FAILED;\n }, this.options.interval, this);\n return STATE_FAILED;\n },\n\n reset: function() {\n clearTimeout(this._timer);\n },\n\n emit: function() {\n if (this.state == STATE_RECOGNIZED) {\n this._input.tapCount = this.count;\n this.manager.emit(this.options.event, this._input);\n }\n }\n});\n\n/**\n * Simple way to create a manager with a default set of recognizers.\n * @param {HTMLElement} element\n * @param {Object} [options]\n * @constructor\n */\nfunction Hammer(element, options) {\n options = options || {};\n options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);\n return new Manager(element, options);\n}\n\n/**\n * @const {string}\n */\nHammer.VERSION = '2.0.7';\n\n/**\n * default settings\n * @namespace\n */\nHammer.defaults = {\n /**\n * set if DOM events are being triggered.\n * But this is slower and unused by simple implementations, so disabled by default.\n * @type {Boolean}\n * @default false\n */\n domEvents: false,\n\n /**\n * The value for the touchAction property/fallback.\n * When set to `compute` it will magically set the correct value based on the added recognizers.\n * @type {String}\n * @default compute\n */\n touchAction: TOUCH_ACTION_COMPUTE,\n\n /**\n * @type {Boolean}\n * @default true\n */\n enable: true,\n\n /**\n * EXPERIMENTAL FEATURE -- can be removed/changed\n * Change the parent input target element.\n * If Null, then it is being set the to main element.\n * @type {Null|EventTarget}\n * @default null\n */\n inputTarget: null,\n\n /**\n * force an input class\n * @type {Null|Function}\n * @default null\n */\n inputClass: null,\n\n /**\n * Default recognizer setup when calling `Hammer()`\n * When creating a new Manager these will be skipped.\n * @type {Array}\n */\n preset: [\n // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]\n [RotateRecognizer, {enable: false}],\n [PinchRecognizer, {enable: false}, ['rotate']],\n [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],\n [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],\n [TapRecognizer],\n [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],\n [PressRecognizer]\n ],\n\n /**\n * Some CSS properties can be used to improve the working of Hammer.\n * Add them to this method and they will be set when creating a new Manager.\n * @namespace\n */\n cssProps: {\n /**\n * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.\n * @type {String}\n * @default 'none'\n */\n userSelect: 'none',\n\n /**\n * Disable the Windows Phone grippers when pressing an element.\n * @type {String}\n * @default 'none'\n */\n touchSelect: 'none',\n\n /**\n * Disables the default callout shown when you touch and hold a touch target.\n * On iOS, when you touch and hold a touch target such as a link, Safari displays\n * a callout containing information about the link. This property allows you to disable that callout.\n * @type {String}\n * @default 'none'\n */\n touchCallout: 'none',\n\n /**\n * Specifies whether zooming is enabled. Used by IE10>\n * @type {String}\n * @default 'none'\n */\n contentZooming: 'none',\n\n /**\n * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.\n * @type {String}\n * @default 'none'\n */\n userDrag: 'none',\n\n /**\n * Overrides the highlight color shown when the user taps a link or a JavaScript\n * clickable element in iOS. This property obeys the alpha value, if specified.\n * @type {String}\n * @default 'rgba(0,0,0,0)'\n */\n tapHighlightColor: 'rgba(0,0,0,0)'\n }\n};\n\nvar STOP = 1;\nvar FORCED_STOP = 2;\n\n/**\n * Manager\n * @param {HTMLElement} element\n * @param {Object} [options]\n * @constructor\n */\nfunction Manager(element, options) {\n this.options = assign({}, Hammer.defaults, options || {});\n\n this.options.inputTarget = this.options.inputTarget || element;\n\n this.handlers = {};\n this.session = {};\n this.recognizers = [];\n this.oldCssProps = {};\n\n this.element = element;\n this.input = createInputInstance(this);\n this.touchAction = new TouchAction(this, this.options.touchAction);\n\n toggleCssProps(this, true);\n\n each(this.options.recognizers, function(item) {\n var recognizer = this.add(new (item[0])(item[1]));\n item[2] && recognizer.recognizeWith(item[2]);\n item[3] && recognizer.requireFailure(item[3]);\n }, this);\n}\n\nManager.prototype = {\n /**\n * set options\n * @param {Object} options\n * @returns {Manager}\n */\n set: function(options) {\n assign(this.options, options);\n\n // Options that need a little more setup\n if (options.touchAction) {\n this.touchAction.update();\n }\n if (options.inputTarget) {\n // Clean up existing event listeners and reinitialize\n this.input.destroy();\n this.input.target = options.inputTarget;\n this.input.init();\n }\n return this;\n },\n\n /**\n * stop recognizing for this session.\n * This session will be discarded, when a new [input]start event is fired.\n * When forced, the recognizer cycle is stopped immediately.\n * @param {Boolean} [force]\n */\n stop: function(force) {\n this.session.stopped = force ? FORCED_STOP : STOP;\n },\n\n /**\n * run the recognizers!\n * called by the inputHandler function on every movement of the pointers (touches)\n * it walks through all the recognizers and tries to detect the gesture that is being made\n * @param {Object} inputData\n */\n recognize: function(inputData) {\n var session = this.session;\n if (session.stopped) {\n return;\n }\n\n // run the touch-action polyfill\n this.touchAction.preventDefaults(inputData);\n\n var recognizer;\n var recognizers = this.recognizers;\n\n // this holds the recognizer that is being recognized.\n // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED\n // if no recognizer is detecting a thing, it is set to `null`\n var curRecognizer = session.curRecognizer;\n\n // reset when the last recognizer is recognized\n // or when we're in a new session\n if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {\n curRecognizer = session.curRecognizer = null;\n }\n\n var i = 0;\n while (i < recognizers.length) {\n recognizer = recognizers[i];\n\n // find out if we are allowed try to recognize the input for this one.\n // 1. allow if the session is NOT forced stopped (see the .stop() method)\n // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one\n // that is being recognized.\n // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.\n // this can be setup with the `recognizeWith()` method on the recognizer.\n if (session.stopped !== FORCED_STOP && ( // 1\n !curRecognizer || recognizer == curRecognizer || // 2\n recognizer.canRecognizeWith(curRecognizer))) { // 3\n recognizer.recognize(inputData);\n } else {\n recognizer.reset();\n }\n\n // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the\n // current active recognizer. but only if we don't already have an active recognizer\n if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {\n curRecognizer = session.curRecognizer = recognizer;\n }\n i++;\n }\n },\n\n /**\n * get a recognizer by its event name.\n * @param {Recognizer|String} recognizer\n * @returns {Recognizer|Null}\n */\n get: function(recognizer) {\n if (recognizer instanceof Recognizer) {\n return recognizer;\n }\n\n var recognizers = this.recognizers;\n for (var i = 0; i < recognizers.length; i++) {\n if (recognizers[i].options.event == recognizer) {\n return recognizers[i];\n }\n }\n return null;\n },\n\n /**\n * add a recognizer to the manager\n * existing recognizers with the same event name will be removed\n * @param {Recognizer} recognizer\n * @returns {Recognizer|Manager}\n */\n add: function(recognizer) {\n if (invokeArrayArg(recognizer, 'add', this)) {\n return this;\n }\n\n // remove existing\n var existing = this.get(recognizer.options.event);\n if (existing) {\n this.remove(existing);\n }\n\n this.recognizers.push(recognizer);\n recognizer.manager = this;\n\n this.touchAction.update();\n return recognizer;\n },\n\n /**\n * remove a recognizer by name or instance\n * @param {Recognizer|String} recognizer\n * @returns {Manager}\n */\n remove: function(recognizer) {\n if (invokeArrayArg(recognizer, 'remove', this)) {\n return this;\n }\n\n recognizer = this.get(recognizer);\n\n // let's make sure this recognizer exists\n if (recognizer) {\n var recognizers = this.recognizers;\n var index = inArray(recognizers, recognizer);\n\n if (index !== -1) {\n recognizers.splice(index, 1);\n this.touchAction.update();\n }\n }\n\n return this;\n },\n\n /**\n * bind event\n * @param {String} events\n * @param {Function} handler\n * @returns {EventEmitter} this\n */\n on: function(events, handler) {\n if (events === undefined) {\n return;\n }\n if (handler === undefined) {\n return;\n }\n\n var handlers = this.handlers;\n each(splitStr(events), function(event) {\n handlers[event] = handlers[event] || [];\n handlers[event].push(handler);\n });\n return this;\n },\n\n /**\n * unbind event, leave emit blank to remove all handlers\n * @param {String} events\n * @param {Function} [handler]\n * @returns {EventEmitter} this\n */\n off: function(events, handler) {\n if (events === undefined) {\n return;\n }\n\n var handlers = this.handlers;\n each(splitStr(events), function(event) {\n if (!handler) {\n delete handlers[event];\n } else {\n handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);\n }\n });\n return this;\n },\n\n /**\n * emit event to the listeners\n * @param {String} event\n * @param {Object} data\n */\n emit: function(event, data) {\n // we also want to trigger dom events\n if (this.options.domEvents) {\n triggerDomEvent(event, data);\n }\n\n // no handlers, so skip it all\n var handlers = this.handlers[event] && this.handlers[event].slice();\n if (!handlers || !handlers.length) {\n return;\n }\n\n data.type = event;\n data.preventDefault = function() {\n data.srcEvent.preventDefault();\n };\n\n var i = 0;\n while (i < handlers.length) {\n handlers[i](data);\n i++;\n }\n },\n\n /**\n * destroy the manager and unbinds all events\n * it doesn't unbind dom events, that is the user own responsibility\n */\n destroy: function() {\n this.element && toggleCssProps(this, false);\n\n this.handlers = {};\n this.session = {};\n this.input.destroy();\n this.element = null;\n }\n};\n\n/**\n * add/remove the css properties as defined in manager.options.cssProps\n * @param {Manager} manager\n * @param {Boolean} add\n */\nfunction toggleCssProps(manager, add) {\n var element = manager.element;\n if (!element.style) {\n return;\n }\n var prop;\n each(manager.options.cssProps, function(value, name) {\n prop = prefixed(element.style, name);\n if (add) {\n manager.oldCssProps[prop] = element.style[prop];\n element.style[prop] = value;\n } else {\n element.style[prop] = manager.oldCssProps[prop] || '';\n }\n });\n if (!add) {\n manager.oldCssProps = {};\n }\n}\n\n/**\n * trigger dom event\n * @param {String} event\n * @param {Object} data\n */\nfunction triggerDomEvent(event, data) {\n var gestureEvent = document.createEvent('Event');\n gestureEvent.initEvent(event, true, true);\n gestureEvent.gesture = data;\n data.target.dispatchEvent(gestureEvent);\n}\n\nassign(Hammer, {\n INPUT_START: INPUT_START,\n INPUT_MOVE: INPUT_MOVE,\n INPUT_END: INPUT_END,\n INPUT_CANCEL: INPUT_CANCEL,\n\n STATE_POSSIBLE: STATE_POSSIBLE,\n STATE_BEGAN: STATE_BEGAN,\n STATE_CHANGED: STATE_CHANGED,\n STATE_ENDED: STATE_ENDED,\n STATE_RECOGNIZED: STATE_RECOGNIZED,\n STATE_CANCELLED: STATE_CANCELLED,\n STATE_FAILED: STATE_FAILED,\n\n DIRECTION_NONE: DIRECTION_NONE,\n DIRECTION_LEFT: DIRECTION_LEFT,\n DIRECTION_RIGHT: DIRECTION_RIGHT,\n DIRECTION_UP: DIRECTION_UP,\n DIRECTION_DOWN: DIRECTION_DOWN,\n DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,\n DIRECTION_VERTICAL: DIRECTION_VERTICAL,\n DIRECTION_ALL: DIRECTION_ALL,\n\n Manager: Manager,\n Input: Input,\n TouchAction: TouchAction,\n\n TouchInput: TouchInput,\n MouseInput: MouseInput,\n PointerEventInput: PointerEventInput,\n TouchMouseInput: TouchMouseInput,\n SingleTouchInput: SingleTouchInput,\n\n Recognizer: Recognizer,\n AttrRecognizer: AttrRecognizer,\n Tap: TapRecognizer,\n Pan: PanRecognizer,\n Swipe: SwipeRecognizer,\n Pinch: PinchRecognizer,\n Rotate: RotateRecognizer,\n Press: PressRecognizer,\n\n on: addEventListeners,\n off: removeEventListeners,\n each: each,\n merge: merge,\n extend: extend,\n assign: assign,\n inherit: inherit,\n bindFn: bindFn,\n prefixed: prefixed\n});\n\n// this prevents errors when Hammer is loaded in the presence of an AMD\n// style loader but by script tag, not by the loader.\nvar freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line\nfreeGlobal.Hammer = Hammer;\n\nif (typeof define === 'function' && define.amd) {\n define(function() {\n return Hammer;\n });\n} else if (typeof module != 'undefined' && module.exports) {\n module.exports = Hammer;\n} else {\n window[exportName] = Hammer;\n}\n\n})(window, document, 'Hammer');\n","/*! pako 2.0.2 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN = 2;\n\n/*============================================================================*/\n\n\nfunction zero(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES = 30;\n/* number of distance codes */\n\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) =>\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) =>\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nconst copy_block = (s, buf, len, header) =>\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n// while (len--) {\n// put_byte(s, *buf++);\n// }\n s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending);\n s.pending += len;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) =>\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let lx = 0; /* running index in l_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) =>\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) =>\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let black_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block = (s, buf, stored_len, last) =>\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nconst _tr_flush_block = (s, buf, stored_len, last) =>\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally = (s, dist, lc) =>\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //let out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n\n//#ifdef TRUNCATE_BLOCK\n// /* Try to guess if it is profitable to stop the current block here */\n// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n// /* Compute an upper bound for the compressed length */\n// out_length = s.last_lit*8;\n// in_length = s.strstart - s.block_start;\n//\n// for (dcode = 0; dcode < D_CODES; dcode++) {\n// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n// }\n// out_length >>>= 3;\n// //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n// // s->last_lit, in_length, out_length,\n// // 100L - out_length*100L/in_length));\n// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n// return true;\n// }\n// }\n//#endif\n\n return (s.last_lit === s.lit_bufsize - 1);\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n};\n\nvar _tr_init_1 = _tr_init;\nvar _tr_stored_block_1 = _tr_stored_block;\nvar _tr_flush_block_1 = _tr_flush_block;\nvar _tr_tally_1 = _tr_tally;\nvar _tr_align_1 = _tr_align;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init: _tr_init$1, _tr_stored_block: _tr_stored_block$1, _tr_flush_block: _tr_flush_block$1, _tr_tally: _tr_tally$1, _tr_align: _tr_align$1 } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_FULL_FLUSH, Z_FINISH, Z_BLOCK,\n Z_OK, Z_STREAM_END, Z_STREAM_ERROR, Z_DATA_ERROR, Z_BUF_ERROR,\n Z_DEFAULT_COMPRESSION,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED: Z_FIXED$1, Z_DEFAULT_STRATEGY,\n Z_UNKNOWN: Z_UNKNOWN$1,\n Z_DEFLATED\n} = constants;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES$1 = 30;\n/* number of distance codes */\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42;\nconst EXTRA_STATE = 69;\nconst NAME_STATE = 73;\nconst COMMENT_STATE = 91;\nconst HCRC_STATE = 103;\nconst BUSY_STATE = 113;\nconst FINISH_STATE = 666;\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero$1 = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block$1(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH$1;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH$1 - (strend - scan);\n scan = strend - MAX_MATCH$1;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH$1) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH$1 - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH$1) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n let max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (;;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n// s.block_start >= s.w_size)) {\n// throw new Error(\"slide too late\");\n// }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n// if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n const max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n};\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH$1) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH$1) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally$1(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH$1) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH$1 - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH$1 - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH$1;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally$1(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH$1 - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH$1) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH$1;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH$1 - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH$1) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally$1(s, 1, s.match_length - MIN_MATCH$1);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero$1(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH$1 - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE$1 * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES$1 + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES$1 + 1) * 2);\n zero$1(this.dyn_ltree);\n zero$1(this.dyn_dtree);\n zero$1(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */\n zero$1(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];\n zero$1(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\nconst deflateResetKeep = (strm) => {\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN$1;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n _tr_init$1(s);\n return Z_OK;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED$1) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n};\n\n\nconst deflate = (strm, flush) => {\n\n let beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n//#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n//#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n let bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align$1(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block$1(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero$1(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n const status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero$1(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH$1) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH$1 - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH$1 - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH$1 - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH$1 - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2 = deflate;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n let i, out;\n const len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$1,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION$1,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY$1\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$1) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$1) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$1 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH$1) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$1) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$1;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$1) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1 = Deflate;\nvar deflate_2$1 = deflate$1;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar constants$1 = constants;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_2$1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD = 30; /* got a data error -- remain here until reset */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n let base_index = 0;\n// let shoextra; /* extra bits table to use */\n let end; /* use base and extra for symbol > end */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n let extra_index = 0;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$2, Z_BLOCK: Z_BLOCK$1, Z_TREES,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2, Z_NEED_DICT, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 1; /* i: waiting for magic header */\nconst FLAGS = 2; /* i: waiting for method and flags (gzip) */\nconst TIME = 3; /* i: waiting for modification time (gzip) */\nconst OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 5; /* i: waiting for extra length (gzip) */\nconst EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nconst NAME = 7; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 8; /* i: waiting for end of comment (gzip) */\nconst HCRC = 9; /* i: waiting for header crc (gzip) */\nconst DICTID = 10; /* i: waiting for dictionary check value */\nconst DICT = 11; /* waiting for inflateSetDictionary() call */\nconst TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 14; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 17; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 18; /* i: waiting for code length code lengths */\nconst CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 20; /* i: same as LEN below, but only first time in */\nconst LEN = 21; /* i: waiting for length/lit/eob code */\nconst LENEXT = 22; /* i: waiting for length extra bits */\nconst DIST = 23; /* i: waiting for distance code */\nconst DISTEXT = 24; /* i: waiting for distance extra bits */\nconst MATCH = 25; /* o: waiting for output space to copy string */\nconst LIT = 26; /* o: waiting for output space to write literal */\nconst CHECK = 27; /* i: waiting for 32-bit check value */\nconst LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 29; /* finished check, done -- remain here until reset */\nconst BAD$1 = 30; /* got a data error -- remain here until reset */\nconst MEM = 31; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS$1;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateResetKeep = (strm) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS$1);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS$1);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$2;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$2) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$2;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD$1;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED$2) {\n strm.msg = 'unknown compression method';\n state.mode = BAD$1;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD$1;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE$1;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED$2) {\n strm.msg = 'unknown compression method';\n state.mode = BAD$1;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD$1;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE$1;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE$1;\n /* falls through */\n case TYPE$1:\n if (flush === Z_BLOCK$1 || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD$1;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD$1;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE$1;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD$1;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD$1;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD$1;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD$1;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD$1) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD$1;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD$1;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD$1;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE$1) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE$1;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$2;\n break inf_leave;\n case BAD$1:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&\n (state.mode < CHECK || flush !== Z_FINISH$2))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE$1 ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$2) && ret === Z_OK$2) {\n ret = Z_BUF_ERROR$1;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$2;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$2;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$2;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2 = inflate;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\n*/\n\nvar inflate_1 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_FINISH: Z_FINISH$3,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_MEM_ERROR: Z_MEM_ERROR$1\n} = constants;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK$3) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK$3) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$3 : Z_NO_FLUSH$2;\n\n // Convert data if needed\n if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT$1 && dictionary) {\n status = inflate_1.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK$3) {\n status = inflate_1.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR$2) {\n // Replace code with more verbose\n status = Z_NEED_DICT$1;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END$3 &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1.inflateReset(strm);\n status = inflate_1.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR$2:\n case Z_DATA_ERROR$2:\n case Z_NEED_DICT$1:\n case Z_MEM_ERROR$1:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END$3) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK$3 && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END$3) {\n status = inflate_1.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$3) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1 = Inflate;\nvar inflate_2$1 = inflate$1;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip = inflate$1;\nvar constants$2 = constants;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1,\n\tinflate: inflate_2$1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip,\n\tconstants: constants$2\n};\n\nconst { Deflate: Deflate$1, deflate: deflate$2, deflateRaw: deflateRaw$1, gzip: gzip$1 } = deflate_1$1;\n\nconst { Inflate: Inflate$1, inflate: inflate$2, inflateRaw: inflateRaw$1, ungzip: ungzip$1 } = inflate_1$1;\n\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_1$2 = deflate$2;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar Inflate_1$1 = Inflate$1;\nvar inflate_1$2 = inflate$2;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip_1 = ungzip$1;\nvar constants_1 = constants;\n\nvar pako = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_1$2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tInflate: Inflate_1$1,\n\tinflate: inflate_1$2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nexport { pako as p };\n","var ListCache = require('./_ListCache'),\n stackClear = require('./_stackClear'),\n stackDelete = require('./_stackDelete'),\n stackGet = require('./_stackGet'),\n stackHas = require('./_stackHas'),\n stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var baseIsArguments = require('./_baseIsArguments'),\n isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n","var root = require('./_root'),\n stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n","var DataView = require('./_DataView'),\n Map = require('./_Map'),\n Promise = require('./_Promise'),\n Set = require('./_Set'),\n WeakMap = require('./_WeakMap'),\n baseGetTag = require('./_baseGetTag'),\n toSource = require('./_toSource');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nmodule.exports = getTag;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.findInArray = findInArray;\nexports.isFunction = isFunction;\nexports.isNum = isNum;\nexports.int = int;\nexports.dontSetMe = dontSetMe;\n\n// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc\nfunction findInArray(array\n/*: Array | TouchList*/\n, callback\n/*: Function*/\n)\n/*: any*/\n{\n for (var i = 0, length = array.length; i < length; i++) {\n if (callback.apply(callback, [array[i], i, array])) return array[i];\n }\n}\n\nfunction isFunction(func\n/*: any*/\n)\n/*: boolean %checks*/\n{\n return typeof func === 'function' || Object.prototype.toString.call(func) === '[object Function]';\n}\n\nfunction isNum(num\n/*: any*/\n)\n/*: boolean %checks*/\n{\n return typeof num === 'number' && !isNaN(num);\n}\n\nfunction int(a\n/*: string*/\n)\n/*: number*/\n{\n return parseInt(a, 10);\n}\n\nfunction dontSetMe(props\n/*: Object*/\n, propName\n/*: string*/\n, componentName\n/*: string*/\n) {\n if (props[propName]) {\n return new Error(\"Invalid prop \".concat(propName, \" passed to \").concat(componentName, \" - do not set this, set it on the child.\"));\n }\n}","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// Adaptation of THREE.js Spherical class, under MIT license\nimport {formatValue, equals, config} from '../lib/common';\nimport {degrees, radians, clamp} from '../lib/common';\nimport Vector3 from './vector3';\n\n// @ts-ignore: error TS2307: Cannot find module 'gl-matrix/...'.\nimport * as vec3 from 'gl-matrix/vec3';\n\n// TODO - import epsilon\nconst EPSILON = 0.000001;\n\nconst EARTH_RADIUS_METERS = 6.371e6;\n\n// Todo [rho, theta, phi] ?\nexport default class SphericalCoordinates {\n // @ts-ignore TS2740: Type '{}' is missing the following properties from type\n // eslint-disable-next-line complexity\n constructor({\n phi = 0,\n theta = 0,\n radius = 1,\n bearing = undefined,\n pitch = undefined,\n altitude = undefined,\n radiusScale = EARTH_RADIUS_METERS\n } = {}) {\n this.phi = phi;\n this.theta = theta;\n // TODO - silently accepts illegal 0\n this.radius = radius || altitude || 1; // radial distance from center\n this.radiusScale = radiusScale || 1; // Used by lngLatZ\n\n if (bearing !== undefined) {\n this.bearing = bearing; // up / down towards top and bottom pole\n }\n if (pitch !== undefined) {\n this.pitch = pitch; // around the equator of the sphere\n }\n this.check();\n }\n\n toString() {\n return this.formatString(config);\n }\n\n formatString({printTypes = false}) {\n const f = formatValue;\n return `${printTypes ? 'Spherical' : ''}\\\n[rho:${f(this.radius)},theta:${f(this.theta)},phi:${f(this.phi)}]`;\n }\n\n equals(other) {\n return (\n equals(this.radius, other.radius) &&\n equals(this.theta, other.theta) &&\n equals(this.phi, other.phi)\n );\n }\n\n exactEquals(other) {\n return this.radius === other.radius && this.theta === other.theta && this.phi === other.phi;\n }\n\n /* eslint-disable brace-style */\n // Cartographic (bearing 0 north, pitch 0 look from above)\n get bearing() {\n return 180 - degrees(this.phi);\n }\n set bearing(v) {\n this.phi = Math.PI - radians(v);\n }\n get pitch() {\n return degrees(this.theta);\n }\n set pitch(v) {\n this.theta = radians(v);\n }\n // get pitch() { return 90 - degrees(this.phi); }\n // set pitch(v) { this.phi = radians(v) + Math.PI / 2; }\n // get altitude() { return this.radius - 1; } // relative altitude\n\n // lnglatZ coordinates\n get longitude() {\n return degrees(this.phi);\n }\n get latitude() {\n return degrees(this.theta);\n }\n get lng() {\n return degrees(this.phi);\n }\n get lat() {\n return degrees(this.theta);\n }\n get z() {\n return (this.radius - 1) * this.radiusScale;\n }\n /* eslint-enable brace-style */\n\n set(radius, phi, theta) {\n this.radius = radius;\n this.phi = phi;\n this.theta = theta;\n return this.check();\n }\n\n clone() {\n return new SphericalCoordinates().copy(this);\n }\n\n copy(other) {\n this.radius = other.radius;\n this.phi = other.phi;\n this.theta = other.theta;\n return this.check();\n }\n\n fromLngLatZ([lng, lat, z]) {\n this.radius = 1 + z / this.radiusScale;\n this.phi = radians(lat);\n this.theta = radians(lng);\n }\n\n fromVector3(v) {\n this.radius = vec3.length(v);\n if (this.radius > 0) {\n this.theta = Math.atan2(v[0], v[1]); // equator angle around y-up axis\n this.phi = Math.acos(clamp(v[2] / this.radius, -1, 1)); // polar angle\n }\n return this.check();\n }\n\n toVector3() {\n return new Vector3(0, 0, this.radius)\n .rotateX({radians: this.theta})\n .rotateZ({radians: this.phi});\n }\n\n // restrict phi to be betwee EPS and PI-EPS\n makeSafe() {\n this.phi = Math.max(EPSILON, Math.min(Math.PI - EPSILON, this.phi));\n return this;\n }\n\n check() {\n // this.makeSafe();\n if (!Number.isFinite(this.phi) || !Number.isFinite(this.theta) || !(this.radius > 0)) {\n throw new Error('SphericalCoordinates: some fields set to invalid numbers');\n }\n return this;\n }\n}\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\nimport Matrix4 from './matrix4';\nimport Vector3 from './vector3';\nimport Euler from './euler';\n\nexport default class Pose {\n // @ts-ignore TS2740: Type '{}' is missing the following properties from type\n constructor({\n x = 0,\n y = 0,\n z = 0,\n roll = 0,\n pitch = 0,\n yaw = 0,\n position = undefined,\n orientation = undefined\n } = {}) {\n if (Array.isArray(position) && position.length === 3) {\n this.position = new Vector3(position);\n } else {\n this.position = new Vector3(x, y, z);\n }\n if (Array.isArray(orientation) && orientation.length === 4) {\n this.orientation = new Euler(orientation, orientation[3]);\n } else {\n this.orientation = new Euler(roll, pitch, yaw, Euler.RollPitchYaw);\n }\n }\n\n get x() {\n return this.position.x;\n }\n set x(value) {\n this.position.x = value;\n }\n get y() {\n return this.position.y;\n }\n set y(value) {\n this.position.y = value;\n }\n get z() {\n return this.position.z;\n }\n set z(value) {\n this.position.z = value;\n }\n get roll() {\n return this.orientation.roll;\n }\n set roll(value) {\n this.orientation.roll = value;\n }\n get pitch() {\n return this.orientation.pitch;\n }\n set pitch(value) {\n this.orientation.pitch = value;\n }\n get yaw() {\n return this.orientation.yaw;\n }\n set yaw(value) {\n this.orientation.yaw = value;\n }\n\n getPosition() {\n return this.position;\n }\n\n getOrientation() {\n return this.orientation;\n }\n\n equals(pose) {\n if (!pose) {\n return false;\n }\n return this.position.equals(pose.position) && this.orientation.equals(pose.orientation);\n }\n\n exactEquals(pose) {\n if (!pose) {\n return false;\n }\n return (\n this.position.exactEquals(pose.position) && this.orientation.exactEquals(pose.orientation)\n );\n }\n\n getTransformationMatrix() {\n // setup precomputations for the sin/cos of the angles\n const sr = Math.sin(this.roll);\n const sp = Math.sin(this.pitch);\n const sw = Math.sin(this.yaw);\n\n const cr = Math.cos(this.roll);\n const cp = Math.cos(this.pitch);\n const cw = Math.cos(this.yaw);\n\n const matrix = new Matrix4().setRowMajor(\n cw * cp, // 0,0\n -sw * cr + cw * sp * sr, // 0,1\n sw * sr + cw * sp * cr, // 0,2\n this.x, // 0,3\n\n sw * cp, // 1,0\n cw * cr + sw * sp * sr, // 1,1\n -cw * sr + sw * sp * cr, // 1,2\n this.y, // 1,3\n\n -sp, // 2,0\n cp * sr, // 2,1\n cp * cr, // 2,2\n this.z, // 2,3\n\n 0,\n 0,\n 0,\n 1\n );\n\n return matrix;\n }\n\n getTransformationMatrixFromPose(pose) {\n return new Matrix4()\n .multiplyRight(this.getTransformationMatrix())\n .multiplyRight(pose.getTransformationMatrix().invert());\n }\n\n getTransformationMatrixToPose(pose) {\n return new Matrix4()\n .multiplyRight(pose.getTransformationMatrix())\n .multiplyRight(this.getTransformationMatrix().invert());\n }\n}\n","'use strict';\n\nconst util = require('./util');\nconst buildOptions = require('./util').buildOptions;\nconst xmlNode = require('./xmlNode');\nconst toNumber = require(\"strnum\");\n\nconst regx =\n '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\n//polyfill\nif (!Number.parseInt && window.parseInt) {\n Number.parseInt = window.parseInt;\n}\nif (!Number.parseFloat && window.parseFloat) {\n Number.parseFloat = window.parseFloat;\n}\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attrNodeName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n ignoreNameSpace: false,\n allowBooleanAttributes: false, //a tag can have attributes without any value\n //ignoreRootElement : false,\n parseNodeValue: true,\n parseAttributeValue: false,\n arrayMode: false,\n trimValues: true, //Trim string values of tag and attributes\n cdataTagName: false,\n cdataPositionChar: '\\\\c',\n numParseOptions: {\n hex: true,\n leadingZeros: true\n },\n tagValueProcessor: function(a, tagName) {\n return a;\n },\n attrValueProcessor: function(a, attrName) {\n return a;\n },\n stopNodes: [],\n alwaysCreateTextNode: false\n //decodeStrict: false,\n};\n\nexports.defaultOptions = defaultOptions;\n\nconst props = [\n 'attributeNamePrefix',\n 'attrNodeName',\n 'textNodeName',\n 'ignoreAttributes',\n 'ignoreNameSpace',\n 'allowBooleanAttributes',\n 'parseNodeValue',\n 'parseAttributeValue',\n 'arrayMode',\n 'trimValues',\n 'cdataTagName',\n 'cdataPositionChar',\n 'tagValueProcessor',\n 'attrValueProcessor',\n 'parseTrueNumberOnly',\n 'numParseOptions',\n 'stopNodes',\n 'alwaysCreateTextNode'\n];\nexports.props = props;\n\n/**\n * Trim -> valueProcessor -> parse value\n * @param {string} tagName\n * @param {string} val\n * @param {object} options\n */\nfunction processTagValue(tagName, val, options) {\n if (val) {\n if (options.trimValues) {\n val = val.trim();\n }\n val = options.tagValueProcessor(val, tagName);\n val = parseValue(val, options.parseNodeValue, options.numParseOptions);\n }\n\n return val;\n}\n\nfunction resolveNameSpace(tagname, options) {\n if (options.ignoreNameSpace) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if(newval === 'true' ) return true;\n else if(newval === 'false' ) return false;\n else return toNumber(val, options);\n } else {\n if (util.isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])(.*?)\\\\3)?', 'g');\n\nfunction buildAttributesMap(attrStr, options) {\n if (!options.ignoreAttributes && typeof attrStr === 'string') {\n attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = util.getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n for (let i = 0; i < len; i++) {\n const attrName = resolveNameSpace(matches[i][1], options);\n if (attrName.length) {\n if (matches[i][4] !== undefined) {\n if (options.trimValues) {\n matches[i][4] = matches[i][4].trim();\n }\n matches[i][4] = options.attrValueProcessor(matches[i][4], attrName);\n attrs[options.attributeNamePrefix + attrName] = parseValue(\n matches[i][4],\n options.parseAttributeValue,\n options.numParseOptions\n );\n } else if (options.allowBooleanAttributes) {\n attrs[options.attributeNamePrefix + attrName] = true;\n }\n }\n }\n if (!Object.keys(attrs).length) {\n return;\n }\n if (options.attrNodeName) {\n const attrCollection = {};\n attrCollection[options.attrNodeName] = attrs;\n return attrCollection;\n }\n return attrs;\n }\n}\n\nconst getTraversalObj = function(xmlData, options) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\");\n options = buildOptions(options, defaultOptions, props);\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n\n//function match(xmlData){\n for(let i=0; i< xmlData.length; i++){\n const ch = xmlData[i];\n if(ch === '<'){\n if( xmlData[i+1] === '/') {//Closing Tag\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i+2,closeIndex).trim();\n\n if(options.ignoreNameSpace){\n const colonIndex = tagName.indexOf(\":\");\n if(colonIndex !== -1){\n tagName = tagName.substr(colonIndex+1);\n }\n }\n\n /* if (currentNode.parent) {\n currentNode.parent.val = util.getValue(currentNode.parent.val) + '' + processTagValue2(tagName, textData , options);\n } */\n if(currentNode){\n if(currentNode.val){\n currentNode.val = util.getValue(currentNode.val) + '' + processTagValue(tagName, textData , options);\n }else{\n currentNode.val = processTagValue(tagName, textData , options);\n }\n }\n\n if (options.stopNodes.length && options.stopNodes.includes(currentNode.tagname)) {\n currentNode.child = []\n if (currentNode.attrsMap == undefined) { currentNode.attrsMap = {}}\n currentNode.val = xmlData.substr(currentNode.startIndex + 1, i - currentNode.startIndex - 1)\n }\n currentNode = currentNode.parent;\n textData = \"\";\n i = closeIndex;\n } else if( xmlData[i+1] === '?') {\n i = findClosingIndex(xmlData, \"?>\", i, \"Pi Tag is not closed.\")\n } else if(xmlData.substr(i + 1, 3) === '!--') {\n i = findClosingIndex(xmlData, \"-->\", i, \"Comment is not closed.\")\n } else if( xmlData.substr(i + 1, 2) === '!D') {\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"DOCTYPE is not closed.\")\n const tagExp = xmlData.substring(i, closeIndex);\n if(tagExp.indexOf(\"[\") >= 0){\n i = xmlData.indexOf(\"]>\", i) + 1;\n }else{\n i = closeIndex;\n }\n }else if(xmlData.substr(i + 1, 2) === '![') {\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2\n const tagExp = xmlData.substring(i + 9,closeIndex);\n\n //considerations\n //1. CDATA will always have parent node\n //2. A tag with CDATA is not a leaf node so it's value would be string type.\n if(textData){\n currentNode.val = util.getValue(currentNode.val) + '' + processTagValue(currentNode.tagname, textData , options);\n textData = \"\";\n }\n\n if (options.cdataTagName) {\n //add cdata node\n const childNode = new xmlNode(options.cdataTagName, currentNode, tagExp);\n currentNode.addChild(childNode);\n //for backtracking\n currentNode.val = util.getValue(currentNode.val) + options.cdataPositionChar;\n //add rest value to parent node\n if (tagExp) {\n childNode.val = tagExp;\n }\n } else {\n currentNode.val = (currentNode.val || '') + (tagExp || '');\n }\n\n i = closeIndex + 2;\n }else {//Opening tag\n const result = closingIndexForOpeningTag(xmlData, i+1)\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.indexOf(\" \");\n let tagName = tagExp;\n let shouldBuildAttributesMap = true;\n if(separatorIndex !== -1){\n tagName = tagExp.substr(0, separatorIndex).replace(/\\s\\s*$/, '');\n tagExp = tagExp.substr(separatorIndex + 1);\n }\n\n if(options.ignoreNameSpace){\n const colonIndex = tagName.indexOf(\":\");\n if(colonIndex !== -1){\n tagName = tagName.substr(colonIndex+1);\n shouldBuildAttributesMap = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n //save text to parent node\n if (currentNode && textData) {\n if(currentNode.tagname !== '!xml'){\n currentNode.val = util.getValue(currentNode.val) + '' + processTagValue( currentNode.tagname, textData, options);\n }\n }\n\n if(tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1){//selfClosing tag\n\n if(tagName[tagName.length - 1] === \"/\"){ //remove trailing '/'\n tagName = tagName.substr(0, tagName.length - 1);\n tagExp = tagName;\n }else{\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n\n const childNode = new xmlNode(tagName, currentNode, '');\n if(tagName !== tagExp){\n childNode.attrsMap = buildAttributesMap(tagExp, options);\n }\n currentNode.addChild(childNode);\n }else{//opening tag\n\n const childNode = new xmlNode( tagName, currentNode );\n if (options.stopNodes.length && options.stopNodes.includes(childNode.tagname)) {\n childNode.startIndex=closeIndex;\n }\n if(tagName !== tagExp && shouldBuildAttributesMap){\n childNode.attrsMap = buildAttributesMap(tagExp, options);\n }\n currentNode.addChild(childNode);\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }else{\n textData += xmlData[i];\n }\n }\n return xmlObj;\n}\n\nfunction closingIndexForOpeningTag(data, i){\n let attrBoundary;\n let tagExp = \"\";\n for (let index = i; index < data.length; index++) {\n let ch = data[index];\n if (attrBoundary) {\n if (ch === attrBoundary) attrBoundary = \"\";//reset\n } else if (ch === '\"' || ch === \"'\") {\n attrBoundary = ch;\n } else if (ch === '>') {\n return {\n data: tagExp,\n index: index\n }\n } else if (ch === '\\t') {\n ch = \" \"\n }\n tagExp += ch;\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg){\n const closingIndex = xmlData.indexOf(str, i);\n if(closingIndex === -1){\n throw new Error(errMsg)\n }else{\n return closingIndex + str.length - 1;\n }\n}\n\nexports.getTraversalObj = getTraversalObj;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeysIn = require('./_baseKeysIn'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nmodule.exports = keysIn;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nmodule.exports = identity;\n","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n","// 19.1.2.14 / 15.2.3.14 Object.keys(O)\nvar $keys = require('./_object-keys-internal');\nvar enumBugKeys = require('./_enum-bug-keys');\n\nmodule.exports = Object.keys || function keys(O) {\n return $keys(O, enumBugKeys);\n};\n","module.exports = true;\n","var id = 0;\nvar px = Math.random();\nmodule.exports = function (key) {\n return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));\n};\n","exports.f = {}.propertyIsEnumerable;\n","var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar helpers_1 = require(\"@turf/helpers\");\nvar invariant_1 = require(\"@turf/invariant\");\nvar line_segment_1 = __importDefault(require(\"@turf/line-segment\"));\nvar meta_1 = require(\"@turf/meta\");\nvar geojson_rbush_1 = __importDefault(require(\"geojson-rbush\"));\n/**\n * Takes any LineString or Polygon GeoJSON and returns the intersecting point(s).\n *\n * @name lineIntersect\n * @param {GeoJSON} line1 any LineString or Polygon\n * @param {GeoJSON} line2 any LineString or Polygon\n * @returns {FeatureCollection} point(s) that intersect both\n * @example\n * var line1 = turf.lineString([[126, -11], [129, -21]]);\n * var line2 = turf.lineString([[123, -18], [131, -14]]);\n * var intersects = turf.lineIntersect(line1, line2);\n *\n * //addToMap\n * var addToMap = [line1, line2, intersects]\n */\nfunction lineIntersect(line1, line2) {\n var unique = {};\n var results = [];\n // First, normalize geometries to features\n // Then, handle simple 2-vertex segments\n if (line1.type === \"LineString\") {\n line1 = helpers_1.feature(line1);\n }\n if (line2.type === \"LineString\") {\n line2 = helpers_1.feature(line2);\n }\n if (line1.type === \"Feature\" &&\n line2.type === \"Feature\" &&\n line1.geometry !== null &&\n line2.geometry !== null &&\n line1.geometry.type === \"LineString\" &&\n line2.geometry.type === \"LineString\" &&\n line1.geometry.coordinates.length === 2 &&\n line2.geometry.coordinates.length === 2) {\n var intersect = intersects(line1, line2);\n if (intersect) {\n results.push(intersect);\n }\n return helpers_1.featureCollection(results);\n }\n // Handles complex GeoJSON Geometries\n var tree = geojson_rbush_1.default();\n tree.load(line_segment_1.default(line2));\n meta_1.featureEach(line_segment_1.default(line1), function (segment) {\n meta_1.featureEach(tree.search(segment), function (match) {\n var intersect = intersects(segment, match);\n if (intersect) {\n // prevent duplicate points https://github.com/Turfjs/turf/issues/688\n var key = invariant_1.getCoords(intersect).join(\",\");\n if (!unique[key]) {\n unique[key] = true;\n results.push(intersect);\n }\n }\n });\n });\n return helpers_1.featureCollection(results);\n}\n/**\n * Find a point that intersects LineStrings with two coordinates each\n *\n * @private\n * @param {Feature} line1 GeoJSON LineString (Must only contain 2 coordinates)\n * @param {Feature} line2 GeoJSON LineString (Must only contain 2 coordinates)\n * @returns {Feature} intersecting GeoJSON Point\n */\nfunction intersects(line1, line2) {\n var coords1 = invariant_1.getCoords(line1);\n var coords2 = invariant_1.getCoords(line2);\n if (coords1.length !== 2) {\n throw new Error(\" line1 must only contain 2 coordinates\");\n }\n if (coords2.length !== 2) {\n throw new Error(\" line2 must only contain 2 coordinates\");\n }\n var x1 = coords1[0][0];\n var y1 = coords1[0][1];\n var x2 = coords1[1][0];\n var y2 = coords1[1][1];\n var x3 = coords2[0][0];\n var y3 = coords2[0][1];\n var x4 = coords2[1][0];\n var y4 = coords2[1][1];\n var denom = ((y4 - y3) * (x2 - x1)) - ((x4 - x3) * (y2 - y1));\n var numeA = ((x4 - x3) * (y1 - y3)) - ((y4 - y3) * (x1 - x3));\n var numeB = ((x2 - x1) * (y1 - y3)) - ((y2 - y1) * (x1 - x3));\n if (denom === 0) {\n if (numeA === 0 && numeB === 0) {\n return null;\n }\n return null;\n }\n var uA = numeA / denom;\n var uB = numeB / denom;\n if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) {\n var x = x1 + (uA * (x2 - x1));\n var y = y1 + (uA * (y2 - y1));\n return helpers_1.point([x, y]);\n }\n return null;\n}\nexports.default = lineIntersect;\n","import {assert} from '../env-utils/assert';\n\n/**\n * Calculate new size of an arrayBuffer to be aligned to an n-byte boundary\n * This function increases `byteLength` by the minimum delta,\n * allowing the total length to be divided by `padding`\n * @param byteLength\n * @param padding\n */\nexport function padToNBytes(byteLength: number, padding: number): number {\n assert(byteLength >= 0); // `Incorrect 'byteLength' value: ${byteLength}`\n assert(padding > 0); // `Incorrect 'padding' value: ${padding}`\n return (byteLength + (padding - 1)) & ~(padding - 1);\n}\n\n/**\n * Creates a new Uint8Array based on two different ArrayBuffers\n * @param targetBuffer The first buffer.\n * @param sourceBuffer The second buffer.\n * @return The new ArrayBuffer created out of the two.\n */\nexport function copyArrayBuffer(\n targetBuffer: ArrayBuffer,\n sourceBuffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number = sourceBuffer.byteLength\n): ArrayBuffer {\n const targetArray = new Uint8Array(targetBuffer, byteOffset, byteLength);\n const sourceArray = new Uint8Array(sourceBuffer);\n targetArray.set(sourceArray);\n return targetBuffer;\n}\n\n/**\n * Copy from source to target at the targetOffset\n *\n * @param source - The data to copy\n * @param target - The destination to copy data into\n * @param targetOffset - The start offset into target to place the copied data\n * @returns the new offset taking into account proper padding\n */\nexport function copyToArray(source: ArrayBuffer | any, target: any, targetOffset: number): number {\n let sourceArray;\n\n if (source instanceof ArrayBuffer) {\n sourceArray = new Uint8Array(source);\n } else {\n // Pack buffer onto the big target array\n //\n // 'source.data.buffer' could be a view onto a larger buffer.\n // We MUST use this constructor to ensure the byteOffset and byteLength is\n // set to correct values from 'source.data' and not the underlying\n // buffer for target.set() to work properly.\n const srcByteOffset = source.byteOffset;\n const srcByteLength = source.byteLength;\n // In gltf parser it is set as \"arrayBuffer\" instead of \"buffer\"\n // https://github.com/visgl/loaders.gl/blob/1e3a82a0a65d7b6a67b1e60633453e5edda2960a/modules/gltf/src/lib/parse-gltf.js#L85\n sourceArray = new Uint8Array(source.buffer || source.arrayBuffer, srcByteOffset, srcByteLength);\n }\n\n // Pack buffer onto the big target array\n target.set(sourceArray, targetOffset);\n\n return targetOffset + padToNBytes(sourceArray.byteLength, 4);\n}\n","export function toDeckColor(\n color?: [number, number, number, number] | null | undefined,\n defaultColor: [number, number, number, number] = [255, 0, 0, 255]\n): [number, number, number, number] {\n if (!Array.isArray(color)) {\n return defaultColor;\n }\n return [color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255];\n}\n\n//\n// a GeoJSON helper function that calls the provided function with\n// an argument that is the most deeply-nested array having elements\n// that are arrays of primitives as an argument, e.g.\n//\n// {\n// \"type\": \"MultiPolygon\",\n// \"coordinates\": [\n// [\n// [[30, 20], [45, 40], [10, 40], [30, 20]]\n// ],\n// [\n// [[15, 5], [40, 10], [10, 20], [5, 10], [15, 5]]\n// ]\n// ]\n// }\n//\n// the function would be called on:\n//\n// [[30, 20], [45, 40], [10, 40], [30, 20]]\n//\n// and\n//\n// [[15, 5], [40, 10], [10, 20], [5, 10], [15, 5]]\n//\nexport function recursivelyTraverseNestedArrays(\n array: Array,\n prefix: Array,\n fn: Function\n) {\n if (!Array.isArray(array[0])) {\n return true;\n }\n for (let i = 0; i < array.length; i++) {\n if (recursivelyTraverseNestedArrays(array[i], [...prefix, i], fn)) {\n fn(array, prefix);\n break;\n }\n }\n return false;\n}\n","// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n /* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\nmodule.exports = {\n SEMVER_SPEC_VERSION,\n MAX_LENGTH,\n MAX_SAFE_INTEGER,\n MAX_SAFE_COMPONENT_LENGTH\n}\n","const debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n","// parse out just the options we care about so we always get a consistent\n// obj with keys in a consistent order.\nconst opts = ['includePrerelease', 'loose', 'rtl']\nconst parseOptions = options =>\n !options ? {}\n : typeof options !== 'object' ? { loose: true }\n : opts.filter(k => options[k]).reduce((options, k) => {\n options[k] = true\n return options\n }, {})\nmodule.exports = parseOptions\n","const compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n","const ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (!options || typeof options !== 'object') {\n options = {\n loose: !!options,\n includePrerelease: false\n }\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n const sameDirectionIncreasing =\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '>=' || comp.operator === '>')\n const sameDirectionDecreasing =\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '<=' || comp.operator === '<')\n const sameSemVer = this.semver.version === comp.semver.version\n const differentDirectionsInclusive =\n (this.operator === '>=' || this.operator === '<=') &&\n (comp.operator === '>=' || comp.operator === '<=')\n const oppositeDirectionsLessThan =\n cmp(this.semver, '<', comp.semver, options) &&\n (this.operator === '>=' || this.operator === '>') &&\n (comp.operator === '<=' || comp.operator === '<')\n const oppositeDirectionsGreaterThan =\n cmp(this.semver, '>', comp.semver, options) &&\n (this.operator === '<=' || this.operator === '<') &&\n (comp.operator === '>=' || comp.operator === '>')\n\n return (\n sameDirectionIncreasing ||\n sameDirectionDecreasing ||\n (sameSemVer && differentDirectionsInclusive) ||\n oppositeDirectionsLessThan ||\n oppositeDirectionsGreaterThan\n )\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst {re, t} = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n","const Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n","/**\n * @module helpers\n */\n/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n *\n * @memberof helpers\n * @type {number}\n */\nexport var earthRadius = 6371008.8;\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var factors = {\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n degrees: earthRadius / 111325,\n feet: earthRadius * 3.28084,\n inches: earthRadius * 39.37,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n meters: earthRadius,\n metres: earthRadius,\n miles: earthRadius / 1609.344,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n nauticalmiles: earthRadius / 1852,\n radians: 1,\n yards: earthRadius * 1.0936,\n};\n/**\n * Units of measurement factors based on 1 meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var unitsFactors = {\n centimeters: 100,\n centimetres: 100,\n degrees: 1 / 111325,\n feet: 3.28084,\n inches: 39.37,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n meters: 1,\n metres: 1,\n miles: 1 / 1609.344,\n millimeters: 1000,\n millimetres: 1000,\n nauticalmiles: 1 / 1852,\n radians: 1 / earthRadius,\n yards: 1.0936133,\n};\n/**\n * Area of measurement factors based on 1 square meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var areaFactors = {\n acres: 0.000247105,\n centimeters: 10000,\n centimetres: 10000,\n feet: 10.763910417,\n hectares: 0.0001,\n inches: 1550.003100006,\n kilometers: 0.000001,\n kilometres: 0.000001,\n meters: 1,\n metres: 1,\n miles: 3.86e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nexport function feature(geom, properties, options) {\n if (options === void 0) { options = {}; }\n var feat = { type: \"Feature\" };\n if (options.id === 0 || options.id) {\n feat.id = options.id;\n }\n if (options.bbox) {\n feat.bbox = options.bbox;\n }\n feat.properties = properties || {};\n feat.geometry = geom;\n return feat;\n}\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = \"Point\";\n * var coordinates = [110, 50];\n * var geometry = turf.geometry(type, coordinates);\n * // => geometry\n */\nexport function geometry(type, coordinates, _options) {\n if (_options === void 0) { _options = {}; }\n switch (type) {\n case \"Point\":\n return point(coordinates).geometry;\n case \"LineString\":\n return lineString(coordinates).geometry;\n case \"Polygon\":\n return polygon(coordinates).geometry;\n case \"MultiPoint\":\n return multiPoint(coordinates).geometry;\n case \"MultiLineString\":\n return multiLineString(coordinates).geometry;\n case \"MultiPolygon\":\n return multiPolygon(coordinates).geometry;\n default:\n throw new Error(type + \" is invalid\");\n }\n}\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nexport function point(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (!coordinates) {\n throw new Error(\"coordinates is required\");\n }\n if (!Array.isArray(coordinates)) {\n throw new Error(\"coordinates must be an Array\");\n }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be at least 2 numbers long\");\n }\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {\n throw new Error(\"coordinates must contain numbers\");\n }\n var geom = {\n type: \"Point\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nexport function points(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nexport function polygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {\n var ring = coordinates_1[_i];\n if (ring.length < 4) {\n throw new Error(\"Each LinearRing of a Polygon must have 4 or more Positions.\");\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n }\n }\n var geom = {\n type: \"Polygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nexport function polygons(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nexport function lineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n var geom = {\n type: \"LineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nexport function lineStrings(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nexport function featureCollection(features, options) {\n if (options === void 0) { options = {}; }\n var fc = { type: \"FeatureCollection\" };\n if (options.id) {\n fc.id = options.id;\n }\n if (options.bbox) {\n fc.bbox = options.bbox;\n }\n fc.features = features;\n return fc;\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nexport function multiLineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiLineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nexport function multiPoint(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPoint\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nexport function multiPolygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPolygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = turf.geometry(\"Point\", [100, 0]);\n * var line = turf.geometry(\"LineString\", [[101, 0], [102, 1]]);\n * var collection = turf.geometryCollection([pt, line]);\n *\n * // => collection\n */\nexport function geometryCollection(geometries, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"GeometryCollection\",\n geometries: geometries,\n };\n return feature(geom, properties, options);\n}\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nexport function round(num, precision) {\n if (precision === void 0) { precision = 0; }\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nexport function radiansToLength(radians, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return radians * factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nexport function lengthToRadians(distance, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return distance / factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nexport function lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nexport function bearingToAzimuth(bearing) {\n var angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nexport function radiansToDegrees(radians) {\n var degrees = radians % (2 * Math.PI);\n return (degrees * 180) / Math.PI;\n}\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nexport function degreesToRadians(degrees) {\n var radians = degrees % 360;\n return (radians * Math.PI) / 180;\n}\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] of the length\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted length\n */\nexport function convertLength(length, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"kilometers\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(length >= 0)) {\n throw new Error(\"length must be a positive number\");\n }\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);\n}\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches, hectares\n * @param {number} area to be converted\n * @param {Units} [originalUnit=\"meters\"] of the distance\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted area\n */\nexport function convertArea(area, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"meters\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n var startFactor = areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n var finalFactor = areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n return (area / startFactor) * finalFactor;\n}\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nexport function isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nexport function isObject(input) {\n return !!input && input.constructor === Object;\n}\n/**\n * Validate BBox\n *\n * @private\n * @param {Array} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nexport function validateBBox(bbox) {\n if (!bbox) {\n throw new Error(\"bbox is required\");\n }\n if (!Array.isArray(bbox)) {\n throw new Error(\"bbox must be an Array\");\n }\n if (bbox.length !== 4 && bbox.length !== 6) {\n throw new Error(\"bbox must be an Array of 4 or 6 numbers\");\n }\n bbox.forEach(function (num) {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nexport function validateId(id) {\n if (!id) {\n throw new Error(\"id is required\");\n }\n if ([\"string\", \"number\"].indexOf(typeof id) === -1) {\n throw new Error(\"id must be a number or a string\");\n }\n}\n","import { isNumber, } from \"@turf/helpers\";\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array|Geometry|Feature} coord GeoJSON Point or an Array of numbers\n * @returns {Array} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nexport function getCoord(coord) {\n if (!coord) {\n throw new Error(\"coord is required\");\n }\n if (!Array.isArray(coord)) {\n if (coord.type === \"Feature\" &&\n coord.geometry !== null &&\n coord.geometry.type === \"Point\") {\n return coord.geometry.coordinates;\n }\n if (coord.type === \"Point\") {\n return coord.coordinates;\n }\n }\n if (Array.isArray(coord) &&\n coord.length >= 2 &&\n !Array.isArray(coord[0]) &&\n !Array.isArray(coord[1])) {\n return coord;\n }\n throw new Error(\"coord must be GeoJSON Point or an Array of numbers\");\n}\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nexport function getCoords(coords) {\n if (Array.isArray(coords)) {\n return coords;\n }\n // Feature\n if (coords.type === \"Feature\") {\n if (coords.geometry !== null) {\n return coords.geometry.coordinates;\n }\n }\n else {\n // Geometry\n if (coords.coordinates) {\n return coords.coordinates;\n }\n }\n throw new Error(\"coords must be GeoJSON Feature, Geometry Object or an Array\");\n}\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nexport function containsNumber(coordinates) {\n if (coordinates.length > 1 &&\n isNumber(coordinates[0]) &&\n isNumber(coordinates[1])) {\n return true;\n }\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error(\"coordinates must only contain numbers\");\n}\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nexport function geojsonType(value, type, name) {\n if (!type || !name) {\n throw new Error(\"type and name required\");\n }\n if (!value || value.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n value.type);\n }\n}\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nexport function featureOf(feature, type, name) {\n if (!feature) {\n throw new Error(\"No feature passed\");\n }\n if (!name) {\n throw new Error(\".featureOf() requires a name\");\n }\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type);\n }\n}\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nexport function collectionOf(featureCollection, type, name) {\n if (!featureCollection) {\n throw new Error(\"No featureCollection passed\");\n }\n if (!name) {\n throw new Error(\".collectionOf() requires a name\");\n }\n if (!featureCollection || featureCollection.type !== \"FeatureCollection\") {\n throw new Error(\"Invalid input to \" + name + \", FeatureCollection required\");\n }\n for (var _i = 0, _a = featureCollection.features; _i < _a.length; _i++) {\n var feature = _a[_i];\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type);\n }\n }\n}\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nexport function getGeom(geojson) {\n if (geojson.type === \"Feature\") {\n return geojson.geometry;\n }\n return geojson;\n}\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message (unused)\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nexport function getType(geojson, _name) {\n if (geojson.type === \"FeatureCollection\") {\n return \"FeatureCollection\";\n }\n if (geojson.type === \"GeometryCollection\") {\n return \"GeometryCollection\";\n }\n if (geojson.type === \"Feature\" && geojson.geometry !== null) {\n return geojson.geometry.type;\n }\n return geojson.type;\n}\n","import polygonClipping from 'polygon-clipping';\nimport { polygon, multiPolygon } from '@turf/helpers';\nimport { getGeom } from '@turf/invariant';\n\n/**\n * Finds the difference between two {@link Polygon|polygons} by clipping the second polygon from the first.\n *\n * @name difference\n * @param {Feature} polygon1 input Polygon feature\n * @param {Feature} polygon2 Polygon feature to difference from polygon1\n * @returns {Feature|null} a Polygon or MultiPolygon feature showing the area of `polygon1` excluding the area of `polygon2` (if empty returns `null`)\n * @example\n * var polygon1 = turf.polygon([[\n * [128, -26],\n * [141, -26],\n * [141, -21],\n * [128, -21],\n * [128, -26]\n * ]], {\n * \"fill\": \"#F00\",\n * \"fill-opacity\": 0.1\n * });\n * var polygon2 = turf.polygon([[\n * [126, -28],\n * [140, -28],\n * [140, -20],\n * [126, -20],\n * [126, -28]\n * ]], {\n * \"fill\": \"#00F\",\n * \"fill-opacity\": 0.1\n * });\n *\n * var difference = turf.difference(polygon1, polygon2);\n *\n * //addToMap\n * var addToMap = [polygon1, polygon2, difference];\n */\nfunction difference(polygon1, polygon2) {\n var geom1 = getGeom(polygon1);\n var geom2 = getGeom(polygon2);\n var properties = polygon1.properties || {};\n\n var differenced = polygonClipping.difference(\n geom1.coordinates,\n geom2.coordinates\n );\n if (differenced.length === 0) return null;\n if (differenced.length === 1) return polygon(differenced[0], properties);\n return multiPolygon(differenced, properties);\n}\n\nexport default difference;\n","// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\n// __VERSION__ is injected by babel-plugin-version-inline\n\n// Change to `latest` on production branches\nconst DEFAULT_VERSION = 'beta';\ndeclare let __VERSION__;\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : DEFAULT_VERSION;\nif (typeof __VERSION__ === 'undefined') {\n // eslint-disable-next-line\n console.error(\n 'loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN.'\n );\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// Merge two luma.gl shader descriptors\nexport function mergeShaders(target, source) {\n if (!source) {\n return target;\n }\n const result = {...target, ...source};\n\n if ('defines' in source) {\n result.defines = {...target.defines, ...source.defines};\n }\n if ('modules' in source) {\n result.modules = (target.modules || []).concat(source.modules);\n\n // Hack: prject32 and project64 cannot co-exist\n if (source.modules.some(module => module.name === 'project64')) {\n const index = result.modules.findIndex(module => module.name === 'project32');\n if (index >= 0) {\n result.modules.splice(index, 1);\n }\n }\n }\n if ('inject' in source) {\n if (!target.inject) {\n result.inject = source.inject;\n } else {\n const mergedInjection = {...target.inject};\n for (const key in source.inject) {\n mergedInjection[key] = (mergedInjection[key] || '') + source.inject[key];\n }\n result.inject = mergedInjection;\n }\n }\n return result;\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nconst ERR_NOT_OBJECT = 'count(): argument not an object';\nconst ERR_NOT_CONTAINER = 'count(): argument not a container';\n\n/**\n * Deduces numer of elements in a JavaScript container.\n * - Auto-deduction for ES6 containers that define a count() method\n * - Auto-deduction for ES6 containers that define a size member\n * - Auto-deduction for Classic Arrays via the built-in length attribute\n * - Also handles objects, although note that this an O(N) operation\n */\nexport function count(container) {\n if (!isObject(container)) {\n throw new Error(ERR_NOT_OBJECT);\n }\n\n // Check if ES6 collection \"count\" function is available\n if (typeof container.count === 'function') {\n return container.count();\n }\n\n // Check if ES6 collection \"size\" attribute is set\n if (Number.isFinite(container.size)) {\n return container.size;\n }\n\n // Check if array length attribute is set\n // Note: checking this last since some ES6 collections (Immutable.js)\n // emit profuse warnings when trying to access `length` attribute\n if (Number.isFinite(container.length)) {\n return container.length;\n }\n\n // Note that getting the count of an object is O(N)\n if (isPlainObject(container)) {\n return Object.keys(container).length;\n }\n\n throw new Error(ERR_NOT_CONTAINER);\n}\n\n/**\n * Checks if argument is a plain object (not a class or array etc)\n * @param {*} value - JavaScript value to be tested\n * @return {Boolean} - true if argument is a plain JavaScript object\n */\nfunction isPlainObject(value) {\n return value !== null && typeof value === 'object' && value.constructor === Object;\n}\n\n/**\n * Checks if argument is an indexable object (not a primitive value, nor null)\n * @param {*} value - JavaScript value to be tested\n * @return {Boolean} - true if argument is a JavaScript object\n */\nfunction isObject(value) {\n return value !== null && typeof value === 'object';\n}\n","import {clamp} from 'math.gl';\nimport Controller from './controller';\nimport {OrbitState} from './orbit-controller';\n\nclass OrthographicState extends OrbitState {\n constructor(props) {\n super(props);\n\n this.zoomAxis = props.zoomAxis || 'all';\n }\n\n _applyConstraints(props) {\n const {maxZoom, minZoom, zoom} = props;\n props.zoom = Array.isArray(zoom)\n ? [clamp(zoom[0], minZoom, maxZoom), clamp(zoom[1], minZoom, maxZoom)]\n : clamp(zoom, minZoom, maxZoom);\n return props;\n }\n\n _calculateNewZoom({scale, startZoom}) {\n const {maxZoom, minZoom} = this._viewportProps;\n if (!startZoom && startZoom !== 0) {\n startZoom = this._viewportProps.zoom;\n }\n let deltaZoom = Math.log2(scale);\n if (Array.isArray(startZoom)) {\n let [newZoomX, newZoomY] = startZoom;\n switch (this.zoomAxis) {\n case 'X':\n // Scale x only\n newZoomX = clamp(newZoomX + deltaZoom, minZoom, maxZoom);\n break;\n case 'Y':\n // Scale y only\n newZoomY = clamp(newZoomY + deltaZoom, minZoom, maxZoom);\n break;\n default:\n // Lock aspect ratio\n let z = Math.min(newZoomX + deltaZoom, newZoomY + deltaZoom);\n if (z < minZoom) {\n deltaZoom += minZoom - z;\n }\n z = Math.max(newZoomX + deltaZoom, newZoomY + deltaZoom);\n if (z > maxZoom) {\n deltaZoom += maxZoom - z;\n }\n newZoomX += deltaZoom;\n newZoomY += deltaZoom;\n }\n return [newZoomX, newZoomY];\n }\n // Ignore `zoomAxis`\n // `LinearTransitionInterpolator` does not support interpolation between a number and an array\n // So if zoom is a number (legacy use case), new zoom still has to be a number\n return clamp(startZoom + deltaZoom, minZoom, maxZoom);\n }\n}\n\nexport default class OrthographicController extends Controller {\n constructor(props) {\n props.dragMode = props.dragMode || 'pan';\n super(OrthographicState, props);\n }\n\n _onPanRotate(event) {\n // No rotation in orthographic view\n return false;\n }\n\n get linearTransitionProps() {\n return ['target', 'zoom'];\n }\n}\n","import View from './view';\nimport WebMercatorViewport from '../viewports/web-mercator-viewport';\nimport MapController from '../controllers/map-controller';\n\nexport default class MapView extends View {\n constructor(props) {\n super({\n ...props,\n type: WebMercatorViewport\n });\n }\n\n get controller() {\n return this._getControllerProps({\n type: MapController\n });\n }\n}\n\nMapView.displayName = 'MapView';\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {ProgramManager} from '@luma.gl/core';\nimport {gouraudLighting, phongLighting} from '@luma.gl/core';\nimport project from './project/project';\nimport project32 from './project32/project32';\nimport shadow from './shadow/shadow';\nimport picking from './picking/picking';\n\nconst DEFAULT_MODULES = [project];\n\nconst SHADER_HOOKS = [\n 'vs:DECKGL_FILTER_SIZE(inout vec3 size, VertexGeometry geometry)',\n 'vs:DECKGL_FILTER_GL_POSITION(inout vec4 position, VertexGeometry geometry)',\n 'vs:DECKGL_FILTER_COLOR(inout vec4 color, VertexGeometry geometry)',\n 'fs:DECKGL_FILTER_COLOR(inout vec4 color, FragmentGeometry geometry)'\n];\n\nexport function createProgramManager(gl) {\n const programManager = ProgramManager.getDefaultProgramManager(gl);\n\n for (const shaderModule of DEFAULT_MODULES) {\n programManager.addDefaultModule(shaderModule);\n }\n for (const shaderHook of SHADER_HOOKS) {\n programManager.addShaderHook(shaderHook);\n }\n\n return programManager;\n}\n\nexport {picking, project, project32, gouraudLighting, phongLighting, shadow};\n","const DEFAULT_LIGHT_COLOR = [255, 255, 255];\nconst DEFAULT_LIGHT_INTENSITY = 1.0;\n\nlet idCount = 0;\n\nexport class AmbientLight {\n constructor(props = {}) {\n const {color = DEFAULT_LIGHT_COLOR} = props;\n const {intensity = DEFAULT_LIGHT_INTENSITY} = props;\n\n this.id = props.id || `ambient-${idCount++}`;\n this.color = color;\n this.intensity = intensity;\n this.type = 'ambient';\n }\n}\n","import {lerp} from 'math.gl';\nimport Transition from './transition';\n\nexport default class CPUInterpolationTransition extends Transition {\n get value() {\n return this._value;\n }\n\n _onUpdate() {\n const {\n time,\n settings: {fromValue, toValue, duration, easing}\n } = this;\n const t = easing(time / duration);\n this._value = lerp(fromValue, toValue, t);\n }\n}\n","import Transition from './transition';\n\nconst EPSILON = 1e-5;\n\n/*\n * Calculate the next value in the spring transition\n * @param prev {Number} - previous value\n * @param cur {Number} - current value\n * @param dest {Number} - destination value\n * @param damping {Number}\n * @param stiffness {Number}\n */\nfunction updateSpringElement(prev, cur, dest, damping, stiffness) {\n const velocity = cur - prev;\n const delta = dest - cur;\n const spring = delta * stiffness;\n const damper = -velocity * damping;\n return spring + damper + velocity + cur;\n}\n\n/*\n * Calculate the next value in the spring transition\n * @param prev {Number|Array} - previous value\n * @param cur {Number|Array} - current value\n * @param dest {Number|Array} - destination value\n * @param damping {Number}\n * @param stiffness {Number}\n */\nfunction updateSpring(prev, cur, dest, damping, stiffness) {\n if (Array.isArray(dest)) {\n const next = [];\n for (let i = 0; i < dest.length; i++) {\n next[i] = updateSpringElement(prev[i], cur[i], dest[i], damping, stiffness);\n }\n return next;\n }\n return updateSpringElement(prev, cur, dest, damping, stiffness);\n}\n\n/*\n * Calculate the distance between two numbers or two vectors\n */\nfunction distance(value1, value2) {\n if (Array.isArray(value1)) {\n let distanceSquare = 0;\n for (let i = 0; i < value1.length; i++) {\n const d = value1[i] - value2[i];\n distanceSquare += d * d;\n }\n return Math.sqrt(distanceSquare);\n }\n return Math.abs(value1 - value2);\n}\n\nexport default class CPUSpringTransition extends Transition {\n get value() {\n return this._currValue;\n }\n\n _onUpdate() {\n // TODO - use timeline\n // const {time} = this;\n\n const {fromValue, toValue, damping, stiffness} = this.settings;\n const {_prevValue = fromValue, _currValue = fromValue} = this;\n let nextValue = updateSpring(_prevValue, _currValue, toValue, damping, stiffness);\n const delta = distance(nextValue, toValue);\n const velocity = distance(nextValue, _currValue);\n\n if (delta < EPSILON && velocity < EPSILON) {\n nextValue = toValue;\n this.end();\n }\n\n this._prevValue = _currValue;\n this._currValue = nextValue;\n }\n}\n","import {normalizeTransitionSettings} from './attribute/attribute-transition-utils';\nimport CPUInterpolationTransition from '../transitions/cpu-interpolation-transition';\nimport CPUSpringTransition from '../transitions/cpu-spring-transition';\nimport log from '../utils/log';\n\nconst TRANSITION_TYPES = {\n interpolation: CPUInterpolationTransition,\n spring: CPUSpringTransition\n};\n\nexport default class UniformTransitionManager {\n constructor(timeline) {\n this.transitions = new Map();\n this.timeline = timeline;\n }\n\n get active() {\n return this.transitions.size > 0;\n }\n\n add(key, fromValue, toValue, settings) {\n const {transitions} = this;\n if (transitions.has(key)) {\n const transition = transitions.get(key);\n // value may not be available if `update()` has not been called. Fallback to `fromValue`\n const {value = transition.settings.fromValue} = transition;\n // start from interrupted position\n fromValue = value;\n this.remove(key);\n }\n\n settings = normalizeTransitionSettings(settings);\n if (!settings) {\n return;\n }\n\n const TransitionType = TRANSITION_TYPES[settings.type];\n if (!TransitionType) {\n log.error(`unsupported transition type '${settings.type}'`)();\n return;\n }\n const transition = new TransitionType(this.timeline);\n transition.start({\n ...settings,\n fromValue,\n toValue\n });\n transitions.set(key, transition);\n }\n\n remove(key) {\n const {transitions} = this;\n if (transitions.has(key)) {\n transitions.get(key).cancel();\n transitions.delete(key);\n }\n }\n\n update() {\n const propsInTransition = {};\n\n for (const [key, transition] of this.transitions) {\n transition.update();\n propsInTransition[key] = transition.value;\n if (!transition.inProgress) {\n // transition ended\n this.remove(key);\n }\n }\n\n return propsInTransition;\n }\n\n clear() {\n for (const key of this.transitions.keys()) {\n this.remove(key);\n }\n }\n}\n","import {Texture2D} from '@luma.gl/core';\nimport GL from '@luma.gl/constants';\n\nconst DEFAULT_TEXTURE_PARAMETERS = {\n [GL.TEXTURE_MIN_FILTER]: GL.LINEAR_MIPMAP_LINEAR,\n [GL.TEXTURE_MAG_FILTER]: GL.LINEAR,\n [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE,\n [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE\n};\n\n// Track the textures that are created by us. They need to be released when they are no longer used.\nconst internalTextures = {};\n\nexport function createTexture(layer, image) {\n const gl = layer.context && layer.context.gl;\n if (!gl || !image) {\n return null;\n }\n\n // image could be one of:\n // - Texture2D\n // - Browser object: Image, ImageData, ImageData, HTMLCanvasElement, HTMLVideoElement, ImageBitmap\n // - Plain object: {width: , height: , data: }\n if (image instanceof Texture2D) {\n return image;\n } else if (image.constructor && image.constructor.name !== 'Object') {\n // Browser object\n image = {data: image};\n }\n\n let specialTextureParameters = null;\n if (image.compressed) {\n specialTextureParameters = {\n [GL.TEXTURE_MIN_FILTER]: image.data.length > 1 ? GL.LINEAR_MIPMAP_NEAREST : GL.LINEAR\n };\n }\n\n const texture = new Texture2D(gl, {\n ...image,\n parameters: {\n ...DEFAULT_TEXTURE_PARAMETERS,\n ...specialTextureParameters,\n ...layer.props.textureParameters\n }\n });\n // Track this texture\n internalTextures[texture.id] = true;\n return texture;\n}\n\nexport function destroyTexture(texture) {\n if (!texture || !(texture instanceof Texture2D)) {\n return;\n }\n if (internalTextures[texture.id]) {\n texture.delete();\n delete internalTextures[texture.id];\n }\n}\n","import {createTexture, destroyTexture} from '../utils/texture';\n\nconst TYPE_DEFINITIONS = {\n boolean: {\n validate(value, propType) {\n return true;\n },\n equal(value1, value2, propType) {\n return Boolean(value1) === Boolean(value2);\n }\n },\n number: {\n validate(value, propType) {\n return (\n Number.isFinite(value) &&\n (!('max' in propType) || value <= propType.max) &&\n (!('min' in propType) || value >= propType.min)\n );\n }\n },\n color: {\n validate(value, propType) {\n return (\n (propType.optional && !value) ||\n (isArray(value) && (value.length === 3 || value.length === 4))\n );\n },\n equal(value1, value2, propType) {\n return arrayEqual(value1, value2);\n }\n },\n accessor: {\n validate(value, propType) {\n const valueType = getTypeOf(value);\n return valueType === 'function' || valueType === getTypeOf(propType.value);\n },\n equal(value1, value2, propType) {\n if (typeof value2 === 'function') {\n return true;\n }\n return arrayEqual(value1, value2);\n }\n },\n array: {\n validate(value, propType) {\n return (propType.optional && !value) || isArray(value);\n },\n equal(value1, value2, propType) {\n return propType.compare ? arrayEqual(value1, value2) : value1 === value2;\n }\n },\n function: {\n validate(value, propType) {\n return (propType.optional && !value) || typeof value === 'function';\n },\n equal(value1, value2, propType) {\n return !propType.compare || value1 === value2;\n }\n },\n data: {\n transform: (value, propType, component) => {\n const {dataTransform} = component ? component.props : {};\n return dataTransform && value ? dataTransform(value) : value;\n }\n },\n image: {\n transform: (value, propType, component) => {\n return createTexture(component, value);\n },\n release: value => {\n destroyTexture(value);\n }\n }\n};\n\nfunction arrayEqual(array1, array2) {\n if (array1 === array2) {\n return true;\n }\n if (!isArray(array1) || !isArray(array2)) {\n return false;\n }\n const len = array1.length;\n if (len !== array2.length) {\n return false;\n }\n for (let i = 0; i < len; i++) {\n if (array1[i] !== array2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function parsePropTypes(propDefs) {\n const propTypes = {};\n const defaultProps = {};\n const deprecatedProps = {};\n\n for (const [propName, propDef] of Object.entries(propDefs)) {\n if (propDef && propDef.deprecatedFor) {\n deprecatedProps[propName] = Array.isArray(propDef.deprecatedFor)\n ? propDef.deprecatedFor\n : [propDef.deprecatedFor];\n } else {\n const propType = parsePropType(propName, propDef);\n propTypes[propName] = propType;\n defaultProps[propName] = propType.value;\n }\n }\n return {propTypes, defaultProps, deprecatedProps};\n}\n\n// Parses one property definition entry. Either contains:\n// * a valid prop type object ({type, ...})\n// * or just a default value, in which case type and name inference is used\nfunction parsePropType(name, propDef) {\n switch (getTypeOf(propDef)) {\n case 'object':\n return normalizePropDefinition(name, propDef);\n\n case 'array':\n return normalizePropDefinition(name, {type: 'array', value: propDef, compare: false});\n\n case 'boolean':\n return normalizePropDefinition(name, {type: 'boolean', value: propDef});\n\n case 'number':\n return normalizePropDefinition(name, {type: 'number', value: propDef});\n\n case 'function':\n return normalizePropDefinition(name, {type: 'function', value: propDef, compare: true});\n // return guessFunctionType(name, propDef);\n\n default:\n return {name, type: 'unknown', value: propDef};\n }\n}\n\nfunction normalizePropDefinition(name, propDef) {\n if (!('type' in propDef)) {\n if (!('value' in propDef)) {\n // If no type and value this object is likely the value\n return {name, type: 'object', value: propDef};\n }\n return {name, type: getTypeOf(propDef.value), ...propDef};\n }\n return {name, ...TYPE_DEFINITIONS[propDef.type], ...propDef};\n}\n\nfunction isArray(value) {\n return Array.isArray(value) || ArrayBuffer.isView(value);\n}\n\n// improved version of javascript typeof that can distinguish arrays and null values\nfunction getTypeOf(value) {\n if (isArray(value)) {\n return 'array';\n }\n if (value === null) {\n return 'null';\n }\n return typeof value;\n}\n","import log from '../utils/log';\nimport {isAsyncIterable} from '../utils/iterable-utils';\nimport {parsePropTypes} from './prop-types';\nimport {PROP_SYMBOLS} from './constants';\n\nconst {COMPONENT, ASYNC_ORIGINAL, ASYNC_RESOLVED, ASYNC_DEFAULTS} = PROP_SYMBOLS;\n\n// Create a property object\nexport function createProps() {\n const component = this; // eslint-disable-line\n\n // Get default prop object (a prototype chain for now)\n const propsPrototype = getPropsPrototype(component.constructor);\n\n // Create a new prop object with default props object in prototype chain\n const propsInstance = Object.create(propsPrototype);\n\n // Props need a back pointer to the owning component\n propsInstance[COMPONENT] = component;\n // The supplied (original) values for those async props that are set to url strings or Promises.\n // In this case, the actual (i.e. resolved) values are looked up from component.internalState\n propsInstance[ASYNC_ORIGINAL] = {};\n // Note: the actual (resolved) values for props that are NOT set to urls or Promises.\n // in this case the values are served directly from this map\n propsInstance[ASYNC_RESOLVED] = {};\n\n // \"Copy\" all sync props\n for (let i = 0; i < arguments.length; ++i) {\n const props = arguments[i];\n // Do not use Object.assign here to avoid Symbols in props overwriting our private fields\n // This might happen if one of the arguments is another props instance\n for (const key in props) {\n propsInstance[key] = props[key];\n }\n }\n\n // Props must be immutable\n Object.freeze(propsInstance);\n\n return propsInstance;\n}\n\n// Return precalculated defaultProps and propType objects if available\n// build them if needed\nfunction getPropsPrototype(componentClass) {\n const defaultProps = getOwnProperty(componentClass, '_mergedDefaultProps');\n if (!defaultProps) {\n createPropsPrototypeAndTypes(componentClass);\n return componentClass._mergedDefaultProps;\n }\n return defaultProps;\n}\n\n// Build defaultProps and propType objects by walking component prototype chain\nfunction createPropsPrototypeAndTypes(componentClass) {\n const parent = componentClass.prototype;\n if (!parent) {\n return;\n }\n\n const parentClass = Object.getPrototypeOf(componentClass);\n const parentDefaultProps = getPropsPrototype(parentClass);\n\n // Parse propTypes from Component.defaultProps\n const componentDefaultProps = getOwnProperty(componentClass, 'defaultProps') || {};\n const componentPropDefs = parsePropTypes(componentDefaultProps);\n\n // Create any necessary property descriptors and create the default prop object\n // Assign merged default props\n const defaultProps = createPropsPrototype(\n componentPropDefs.defaultProps,\n parentDefaultProps,\n componentClass\n );\n\n // Create a merged type object\n const propTypes = {...parentClass._propTypes, ...componentPropDefs.propTypes};\n // Add getters/setters for async props\n addAsyncPropsToPropPrototype(defaultProps, propTypes);\n\n // Create a map for prop whose default value is a callback\n const deprecatedProps = {\n ...parentClass._deprecatedProps,\n ...componentPropDefs.deprecatedProps\n };\n // Add setters for deprecated props\n addDeprecatedPropsToPropPrototype(defaultProps, deprecatedProps);\n\n // Store the precalculated props\n componentClass._mergedDefaultProps = defaultProps;\n componentClass._propTypes = propTypes;\n componentClass._deprecatedProps = deprecatedProps;\n}\n\n// Builds a pre-merged default props object that component props can inherit from\nfunction createPropsPrototype(props, parentProps, componentClass) {\n const defaultProps = Object.create(null);\n\n Object.assign(defaultProps, parentProps, props);\n\n // Avoid freezing `id` prop\n const id = getComponentName(componentClass);\n delete props.id;\n\n Object.defineProperties(defaultProps, {\n // `id` is treated specially because layer might need to override it\n id: {\n writable: true,\n value: id\n }\n });\n\n return defaultProps;\n}\n\nfunction addDeprecatedPropsToPropPrototype(defaultProps, deprecatedProps) {\n for (const propName in deprecatedProps) {\n /* eslint-disable accessor-pairs */\n Object.defineProperty(defaultProps, propName, {\n enumerable: false,\n set(newValue) {\n const nameStr = `${this.id}: ${propName}`;\n\n for (const newPropName of deprecatedProps[propName]) {\n if (!hasOwnProperty(this, newPropName)) {\n this[newPropName] = newValue;\n }\n }\n\n log.deprecated(nameStr, deprecatedProps[propName].join('/'))();\n }\n });\n /* eslint-enable accessor-pairs */\n }\n}\n\n// Create descriptors for overridable props\nfunction addAsyncPropsToPropPrototype(defaultProps, propTypes) {\n const defaultValues = {};\n\n const descriptors = {};\n\n // Move async props into shadow values\n for (const propName in propTypes) {\n const propType = propTypes[propName];\n const {name, value} = propType;\n\n // Note: async is ES7 keyword, can't destructure\n if (propType.async) {\n defaultValues[name] = value;\n descriptors[name] = getDescriptorForAsyncProp(name, value);\n }\n }\n\n // Default \"resolved\" values for async props, returned if value not yet resolved/set.\n defaultProps[ASYNC_DEFAULTS] = defaultValues;\n // Shadowed object, just to make sure \"early indexing\" into the instance does not fail\n defaultProps[ASYNC_ORIGINAL] = {};\n\n Object.defineProperties(defaultProps, descriptors);\n}\n\n// Helper: Configures getter and setter for one async prop\nfunction getDescriptorForAsyncProp(name) {\n return {\n enumerable: true,\n // Save the provided value for async props in a special map\n set(newValue) {\n if (\n typeof newValue === 'string' ||\n newValue instanceof Promise ||\n isAsyncIterable(newValue)\n ) {\n this[ASYNC_ORIGINAL][name] = newValue;\n } else {\n this[ASYNC_RESOLVED][name] = newValue;\n }\n },\n // Only the component's state knows the true value of async prop\n get() {\n if (this[ASYNC_RESOLVED]) {\n // Prop value isn't async, so just return it\n if (name in this[ASYNC_RESOLVED]) {\n const value = this[ASYNC_RESOLVED][name];\n\n return value || this[ASYNC_DEFAULTS][name];\n }\n\n if (name in this[ASYNC_ORIGINAL]) {\n // It's an async prop value: look into component state\n const state = this[COMPONENT] && this[COMPONENT].internalState;\n if (state && state.hasAsyncProp(name)) {\n return state.getAsyncProp(name) || this[ASYNC_DEFAULTS][name];\n }\n }\n }\n\n // the prop is not supplied, or\n // component not yet initialized/matched, return the component's default value for the prop\n return this[ASYNC_DEFAULTS][name];\n }\n };\n}\n\n// HELPER METHODS\n\nfunction hasOwnProperty(object, prop) {\n return Object.prototype.hasOwnProperty.call(object, prop);\n}\n\n// Constructors have their super class constructors as prototypes\nfunction getOwnProperty(object, prop) {\n return hasOwnProperty(object, prop) && object[prop];\n}\n\nfunction getComponentName(componentClass) {\n const componentName =\n getOwnProperty(componentClass, 'layerName') || getOwnProperty(componentClass, 'componentName');\n if (!componentName) {\n log.once(0, `${componentClass.name}.componentName not specified`)();\n }\n return componentName || componentClass.name;\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {isAsyncIterable} from '../utils/iterable-utils';\nimport {PROP_SYMBOLS} from './constants';\nconst {ASYNC_ORIGINAL, ASYNC_RESOLVED, ASYNC_DEFAULTS} = PROP_SYMBOLS;\n\nconst EMPTY_PROPS = Object.freeze({});\n\nexport default class ComponentState {\n constructor(component = null) {\n this.component = component;\n this.asyncProps = {}; // Prop values that the layer sees\n this.onAsyncPropUpdated = () => {};\n this.oldProps = EMPTY_PROPS; // Last props before update\n this.oldAsyncProps = null; // Last props before update, with async values copied.\n }\n\n finalize() {\n for (const propName in this.asyncProps) {\n const asyncProp = this.asyncProps[propName];\n if (asyncProp.type && asyncProp.type.release) {\n // Release any resources created by transforms\n asyncProp.type.release(asyncProp.resolvedValue, asyncProp.type, this.component);\n }\n }\n }\n\n getOldProps() {\n return this.oldAsyncProps || this.oldProps;\n }\n\n resetOldProps() {\n this.oldAsyncProps = null;\n this.oldProps = this.component.props;\n }\n\n // Whenever async props are changing, we need to make a copy of oldProps\n // otherwise the prop rewriting will affect the value both in props and oldProps.\n // While the copy is relatively expensive, this only happens on load completion.\n freezeAsyncOldProps() {\n if (!this.oldAsyncProps) {\n // Make sure oldProps is set\n this.oldProps = this.oldProps || this.component.props;\n\n // 1. inherit all synchronous props from oldProps\n // 2. reconfigure the async prop descriptors to fixed values\n this.oldAsyncProps = Object.create(this.oldProps);\n for (const propName in this.asyncProps) {\n Object.defineProperty(this.oldAsyncProps, propName, {\n enumerable: true,\n value: this.oldProps[propName]\n });\n }\n }\n }\n\n // ASYNC PROP HANDLING\n //\n\n // Checks if a prop is overridden\n hasAsyncProp(propName) {\n return propName in this.asyncProps;\n }\n\n // Returns value of an overriden prop\n getAsyncProp(propName) {\n const asyncProp = this.asyncProps[propName];\n return asyncProp && asyncProp.resolvedValue;\n }\n\n isAsyncPropLoading(propName) {\n if (propName) {\n const asyncProp = this.asyncProps[propName];\n return Boolean(\n asyncProp &&\n asyncProp.pendingLoadCount > 0 &&\n asyncProp.pendingLoadCount !== asyncProp.resolvedLoadCount\n );\n }\n for (const key in this.asyncProps) {\n if (this.isAsyncPropLoading(key)) {\n return true;\n }\n }\n return false;\n }\n\n // Without changing the original prop value, swap out the data resolution under the hood\n reloadAsyncProp(propName, value) {\n this._watchPromise(propName, Promise.resolve(value));\n }\n\n // Updates all async/overridden props (when new props come in)\n // Checks if urls have changed, starts loading, or removes override\n setAsyncProps(props) {\n // NOTE: prop param and default values are only support for testing\n const resolvedValues = props[ASYNC_RESOLVED] || {};\n const originalValues = props[ASYNC_ORIGINAL] || props;\n const defaultValues = props[ASYNC_DEFAULTS] || {};\n\n // TODO - use async props from the layer's prop types\n for (const propName in resolvedValues) {\n const value = resolvedValues[propName];\n this._createAsyncPropData(propName, defaultValues[propName]);\n this._updateAsyncProp(propName, value);\n // Use transformed value\n resolvedValues[propName] = this.getAsyncProp(propName);\n }\n\n for (const propName in originalValues) {\n const value = originalValues[propName];\n // Makes sure a record exists for this prop\n this._createAsyncPropData(propName, defaultValues[propName]);\n this._updateAsyncProp(propName, value);\n }\n }\n\n // Intercept strings (URLs) and Promises and activates loading and prop rewriting\n _updateAsyncProp(propName, value) {\n if (!this._didAsyncInputValueChange(propName, value)) {\n return;\n }\n\n // interpret value string as url and start a new load tracked by a promise\n if (typeof value === 'string') {\n const fetch = this.layer?.props.fetch;\n const url = value;\n if (fetch) {\n value = fetch(url, {propName, layer: this.layer});\n }\n }\n\n // interprets promise and track the \"loading\"\n if (value instanceof Promise) {\n this._watchPromise(propName, value);\n return;\n }\n\n if (isAsyncIterable(value)) {\n this._resolveAsyncIterable(propName, value);\n return;\n }\n\n // else, normal, non-async value. Just store value for now\n this._setPropValue(propName, value);\n }\n\n // Checks if an input value actually changed (to avoid reloading/rewatching promises/urls)\n _didAsyncInputValueChange(propName, value) {\n const asyncProp = this.asyncProps[propName];\n if (value === asyncProp.resolvedValue || value === asyncProp.lastValue) {\n return false;\n }\n asyncProp.lastValue = value;\n return true;\n }\n\n // Set normal, non-async value\n _setPropValue(propName, value) {\n // Save the current value before overwriting so that diffProps can access both\n this.freezeAsyncOldProps();\n\n const asyncProp = this.asyncProps[propName];\n value = this._postProcessValue(asyncProp, value);\n asyncProp.resolvedValue = value;\n asyncProp.pendingLoadCount++;\n asyncProp.resolvedLoadCount = asyncProp.pendingLoadCount;\n }\n\n // Set a just resolved async value, calling onAsyncPropUpdates if value changes asynchronously\n _setAsyncPropValue(propName, value, loadCount) {\n // Only update if loadCount is larger or equal to resolvedLoadCount\n // otherwise a more recent load has already completed\n const asyncProp = this.asyncProps[propName];\n if (asyncProp && loadCount >= asyncProp.resolvedLoadCount && value !== undefined) {\n // Save the current value before overwriting so that diffProps can access both\n this.freezeAsyncOldProps();\n\n asyncProp.resolvedValue = value;\n asyncProp.resolvedLoadCount = loadCount;\n\n // Call callback to inform listener\n this.onAsyncPropUpdated(propName, value);\n }\n }\n\n // Tracks a promise, sets the prop when loaded, handles load count\n _watchPromise(propName, promise) {\n const asyncProp = this.asyncProps[propName];\n asyncProp.pendingLoadCount++;\n const loadCount = asyncProp.pendingLoadCount;\n promise\n .then(data => {\n data = this._postProcessValue(asyncProp, data);\n this._setAsyncPropValue(propName, data, loadCount);\n\n const onDataLoad = this.layer?.props.onDataLoad;\n if (propName === 'data' && onDataLoad) {\n onDataLoad(data, {propName, layer: this.layer});\n }\n })\n .catch(error => {\n this.layer?.raiseError(error, `loading ${propName} of ${this.layer}`);\n });\n }\n\n async _resolveAsyncIterable(propName, iterable) {\n if (propName !== 'data') {\n // we only support data as async iterable\n this._setPropValue(propName, iterable);\n }\n\n const asyncProp = this.asyncProps[propName];\n asyncProp.pendingLoadCount++;\n const loadCount = asyncProp.pendingLoadCount;\n let data = [];\n let count = 0;\n\n for await (const chunk of iterable) {\n const {dataTransform} = this.component ? this.component.props : {};\n if (dataTransform) {\n data = dataTransform(chunk, data);\n } else {\n data = data.concat(chunk);\n }\n\n // Used by the default _dataDiff function\n Object.defineProperty(data, '__diff', {\n enumerable: false,\n value: [{startRow: count, endRow: data.length}]\n });\n\n count = data.length;\n this._setAsyncPropValue(propName, data, loadCount);\n }\n\n const onDataLoad = this.layer?.props.onDataLoad;\n if (onDataLoad) {\n onDataLoad(data, {propName, layer: this.layer});\n }\n }\n\n // Give the app a chance to post process the loaded data\n _postProcessValue(asyncProp, value) {\n const propType = asyncProp.type;\n if (propType) {\n if (propType.release) {\n propType.release(asyncProp.resolvedValue, propType, this.component);\n }\n if (propType.transform) {\n return propType.transform(value, propType, this.component);\n }\n }\n return value;\n }\n\n // Creating an asyncProp record if needed\n _createAsyncPropData(propName, defaultValue) {\n const asyncProp = this.asyncProps[propName];\n if (!asyncProp) {\n const propTypes = this.component && this.component.constructor._propTypes;\n // assert(defaultValue !== undefined);\n this.asyncProps[propName] = {\n type: propTypes && propTypes[propName],\n lastValue: null, // Supplied prop value (can be url/promise, not visible to layer)\n resolvedValue: defaultValue, // Resolved prop value (valid data, can be \"shown\" to layer)\n pendingLoadCount: 0, // How many loads have been issued\n resolvedLoadCount: 0 // Latest resolved load, (earlier loads will be ignored)\n };\n }\n }\n}\n","import {LIFECYCLE} from '../lifecycle/constants';\nimport {createProps} from './create-props';\nimport {PROP_SYMBOLS} from './constants';\nconst {ASYNC_ORIGINAL, ASYNC_RESOLVED, ASYNC_DEFAULTS} = PROP_SYMBOLS;\nimport ComponentState from './component-state';\n\nconst defaultProps = {};\n\nlet counter = 0;\n\nexport default class Component {\n constructor(/* ...propObjects */) {\n // Merge supplied props with default props and freeze them.\n /* eslint-disable prefer-spread */\n this.props = createProps.apply(this, arguments);\n /* eslint-enable prefer-spread */\n\n // Define all members before layer is sealed\n this.id = this.props.id; // The layer's id, used for matching with layers from last render cycle\n this.count = counter++; // Keep track of how many layer instances you are generating\n this.lifecycle = LIFECYCLE.NO_STATE; // Helps track and debug the life cycle of the layers\n this.parent = null; // reference to the composite layer parent that rendered this layer\n this.context = null; // Will reference layer manager's context, contains state shared by layers\n this.state = null; // Will be set to the shared layer state object during layer matching\n this.internalState = null;\n\n // Seal the layer\n Object.seal(this);\n }\n\n get root() {\n // eslint-disable-next-line consistent-this\n let component = this;\n while (component.parent) {\n component = component.parent;\n }\n return component;\n }\n\n // clone this layer with modified props\n clone(newProps) {\n const {props} = this;\n\n // Async props cannot be copied with Object.assign, copy them separately\n const asyncProps = {};\n\n // See async props definition in create-props.js\n for (const key in props[ASYNC_DEFAULTS]) {\n if (key in props[ASYNC_RESOLVED]) {\n asyncProps[key] = props[ASYNC_RESOLVED][key];\n } else if (key in props[ASYNC_ORIGINAL]) {\n asyncProps[key] = props[ASYNC_ORIGINAL][key];\n }\n }\n\n // Some custom layer implementation may not support multiple arguments in the constructor\n return new this.constructor({...props, ...asyncProps, ...newProps});\n }\n\n get stats() {\n return this.internalState.stats;\n }\n\n // PROTECTED METHODS, override in subclass\n\n _initState() {\n this.internalState = new ComponentState({});\n }\n}\n\nComponent.componentName = 'Component';\nComponent.defaultProps = defaultProps;\n","import ComponentState from '../lifecycle/component-state';\n\nexport default class LayerState extends ComponentState {\n constructor({attributeManager, layer}) {\n super(layer);\n this.attributeManager = attributeManager;\n this.model = null;\n this.needsRedraw = true;\n this.subLayers = null; // reference to sublayers rendered in a previous cycle\n this.usesPickingColorCache = false;\n }\n\n get layer() {\n return this.component;\n }\n\n set layer(layer) {\n this.component = layer;\n }\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/* eslint-disable react/no-direct-mutation-state */\nimport {COORDINATE_SYSTEM} from './constants';\nimport AttributeManager from './attribute/attribute-manager';\nimport UniformTransitionManager from './uniform-transition-manager';\nimport {diffProps, validateProps} from '../lifecycle/props';\nimport {count} from '../utils/count';\nimport log from '../utils/log';\nimport debug from '../debug';\nimport GL from '@luma.gl/constants';\nimport {withParameters, setParameters} from '@luma.gl/core';\nimport assert from '../utils/assert';\nimport memoize from '../utils/memoize';\nimport {mergeShaders} from '../utils/shader';\nimport {projectPosition, getWorldPosition} from '../shaderlib/project/project-functions';\nimport typedArrayManager from '../utils/typed-array-manager';\n\nimport Component from '../lifecycle/component';\nimport LayerState from './layer-state';\n\nimport {worldToPixels} from '@math.gl/web-mercator';\n\nimport {load} from '@loaders.gl/core';\n\nconst TRACE_CHANGE_FLAG = 'layer.changeFlag';\nconst TRACE_INITIALIZE = 'layer.initialize';\nconst TRACE_UPDATE = 'layer.update';\nconst TRACE_FINALIZE = 'layer.finalize';\nconst TRACE_MATCHED = 'layer.matched';\n\nconst MAX_PICKING_COLOR_CACHE_SIZE = 2 ** 24 - 1;\n\nconst EMPTY_ARRAY = Object.freeze([]);\n\n// Only compare the same two viewports once\nconst areViewportsEqual = memoize(({oldViewport, viewport}) => {\n return oldViewport.equals(viewport);\n});\n\nlet pickingColorCache = new Uint8ClampedArray(0);\n\nconst defaultProps = {\n // data: Special handling for null, see below\n data: {type: 'data', value: EMPTY_ARRAY, async: true},\n dataComparator: null,\n _dataDiff: {type: 'function', value: data => data && data.__diff, compare: false, optional: true},\n dataTransform: {type: 'function', value: null, compare: false, optional: true},\n onDataLoad: {type: 'function', value: null, compare: false, optional: true},\n onError: {type: 'function', value: null, compare: false, optional: true},\n fetch: {\n type: 'function',\n value: (url, {propName, layer, loaders, loadOptions, signal}) => {\n const {resourceManager} = layer.context;\n loadOptions = loadOptions || layer.getLoadOptions();\n loaders = loaders || layer.props.loaders;\n if (signal) {\n loadOptions = {\n ...loadOptions,\n fetch: {\n ...loadOptions?.fetch,\n signal\n }\n };\n }\n\n let inResourceManager = resourceManager.contains(url);\n\n if (!inResourceManager && !loadOptions) {\n // If there is no layer-specific load options, then attempt to cache this resource in the data manager\n resourceManager.add({resourceId: url, data: load(url, loaders), persistent: false});\n inResourceManager = true;\n }\n if (inResourceManager) {\n return resourceManager.subscribe({\n resourceId: url,\n onChange: data => layer.internalState.reloadAsyncProp(propName, data),\n consumerId: layer.id,\n requestId: propName\n });\n }\n\n return load(url, loaders, loadOptions);\n },\n compare: false\n },\n updateTriggers: {}, // Update triggers: a core change detection mechanism in deck.gl\n\n visible: true,\n pickable: false,\n opacity: {type: 'number', min: 0, max: 1, value: 1},\n\n onHover: {type: 'function', value: null, compare: false, optional: true},\n onClick: {type: 'function', value: null, compare: false, optional: true},\n onDragStart: {type: 'function', value: null, compare: false, optional: true},\n onDrag: {type: 'function', value: null, compare: false, optional: true},\n onDragEnd: {type: 'function', value: null, compare: false, optional: true},\n\n coordinateSystem: COORDINATE_SYSTEM.DEFAULT,\n coordinateOrigin: {type: 'array', value: [0, 0, 0], compare: true},\n modelMatrix: {type: 'array', value: null, compare: true, optional: true},\n wrapLongitude: false,\n positionFormat: 'XYZ',\n colorFormat: 'RGBA',\n\n parameters: {},\n transitions: null,\n extensions: [],\n loaders: {type: 'array', value: [], optional: true, compare: true},\n\n // Offset depth based on layer index to avoid z-fighting.\n // Negative values pull layer towards the camera\n // https://www.opengl.org/archives/resources/faq/technical/polygonoffset.htm\n getPolygonOffset: {\n type: 'function',\n value: ({layerIndex}) => [0, -layerIndex * 100],\n compare: false\n },\n\n // Selection/Highlighting\n highlightedObjectIndex: -1,\n autoHighlight: false,\n highlightColor: {type: 'accessor', value: [0, 0, 128, 128]}\n};\n\nexport default class Layer extends Component {\n toString() {\n const className = this.constructor.layerName || this.constructor.name;\n return `${className}({id: '${this.props.id}'})`;\n }\n\n raiseError(error, message) {\n if (message) {\n error.message = `${message}: ${error.message}`;\n }\n if (!this.props.onError?.(error)) {\n this.context?.onError?.(error, this);\n }\n }\n\n // Public API\n\n // Updates selected state members and marks the object for redraw\n setState(updateObject) {\n this.setChangeFlags({stateChanged: true});\n Object.assign(this.state, updateObject);\n this.setNeedsRedraw();\n }\n\n // Sets the redraw flag for this layer, will trigger a redraw next animation frame\n setNeedsRedraw(redraw = true) {\n if (this.internalState) {\n this.internalState.needsRedraw = redraw;\n }\n }\n\n // This layer needs a deep update\n setNeedsUpdate() {\n this.context.layerManager.setNeedsUpdate(String(this));\n this.internalState.needsUpdate = true;\n }\n\n // Checks state of attributes and model\n getNeedsRedraw(opts = {clearRedrawFlags: false}) {\n return this._getNeedsRedraw(opts);\n }\n\n // Checks if layer attributes needs updating\n needsUpdate() {\n // Call subclass lifecycle method\n return (\n this.internalState.needsUpdate ||\n this.hasUniformTransition() ||\n this.shouldUpdateState(this._getUpdateParams())\n );\n // End lifecycle method\n }\n\n hasUniformTransition() {\n return this.internalState.uniformTransitions.active;\n }\n\n get isLoaded() {\n return this.internalState && !this.internalState.isAsyncPropLoading();\n }\n\n get wrapLongitude() {\n return this.props.wrapLongitude;\n }\n\n // Returns true if the layer is pickable and visible.\n isPickable() {\n return this.props.pickable && this.props.visible;\n }\n\n // Return an array of models used by this layer, can be overriden by layer subclass\n getModels() {\n return this.state && (this.state.models || (this.state.model ? [this.state.model] : []));\n }\n\n getAttributeManager() {\n return this.internalState && this.internalState.attributeManager;\n }\n\n // Returns the most recent layer that matched to this state\n // (When reacting to an async event, this layer may no longer be the latest)\n getCurrentLayer() {\n return this.internalState && this.internalState.layer;\n }\n\n // Returns the default parse options for async props\n getLoadOptions() {\n return this.props.loadOptions;\n }\n\n // PROJECTION METHODS\n\n // Projects a point with current map state (lat, lon, zoom, pitch, bearing)\n // From the current layer's coordinate system to screen\n project(xyz) {\n const {viewport} = this.context;\n const worldPosition = getWorldPosition(xyz, {\n viewport,\n modelMatrix: this.props.modelMatrix,\n coordinateOrigin: this.props.coordinateOrigin,\n coordinateSystem: this.props.coordinateSystem\n });\n const [x, y, z] = worldToPixels(worldPosition, viewport.pixelProjectionMatrix);\n return xyz.length === 2 ? [x, y] : [x, y, z];\n }\n\n // Note: this does not reverse `project`.\n // Always unprojects to the viewport's coordinate system\n unproject(xy) {\n const {viewport} = this.context;\n return viewport.unproject(xy);\n }\n\n projectPosition(xyz) {\n return projectPosition(xyz, {\n viewport: this.context.viewport,\n modelMatrix: this.props.modelMatrix,\n coordinateOrigin: this.props.coordinateOrigin,\n coordinateSystem: this.props.coordinateSystem\n });\n }\n\n use64bitPositions() {\n const {coordinateSystem} = this.props;\n return (\n coordinateSystem === COORDINATE_SYSTEM.DEFAULT ||\n coordinateSystem === COORDINATE_SYSTEM.LNGLAT ||\n coordinateSystem === COORDINATE_SYSTEM.CARTESIAN\n );\n }\n\n // Event handling\n onHover(info, pickingEvent) {\n if (this.props.onHover) {\n return this.props.onHover(info, pickingEvent);\n }\n return false;\n }\n\n onClick(info, pickingEvent) {\n if (this.props.onClick) {\n return this.props.onClick(info, pickingEvent);\n }\n return false;\n }\n\n // Returns the picking color that doesn't match any subfeature\n // Use if some graphics do not belong to any pickable subfeature\n // @return {Array} - a black color\n nullPickingColor() {\n return [0, 0, 0];\n }\n\n // Returns the picking color that doesn't match any subfeature\n // Use if some graphics do not belong to any pickable subfeature\n encodePickingColor(i, target = []) {\n target[0] = (i + 1) & 255;\n target[1] = ((i + 1) >> 8) & 255;\n target[2] = (((i + 1) >> 8) >> 8) & 255;\n return target;\n }\n\n // Returns the index corresponding to a picking color that doesn't match any subfeature\n // @param {Uint8Array} color - color array to be decoded\n // @return {Array} - the decoded picking color\n decodePickingColor(color) {\n assert(color instanceof Uint8Array);\n const [i1, i2, i3] = color;\n // 1 was added to seperate from no selection\n const index = i1 + i2 * 256 + i3 * 65536 - 1;\n return index;\n }\n\n // //////////////////////////////////////////////////\n // LIFECYCLE METHODS, overridden by the layer subclasses\n\n // Called once to set up the initial state\n // App can create WebGL resources\n initializeState() {\n throw new Error(`Layer ${this} has not defined initializeState`);\n }\n\n getShaders(shaders) {\n for (const extension of this.props.extensions) {\n shaders = mergeShaders(shaders, extension.getShaders.call(this, extension));\n }\n return shaders;\n }\n\n // Let's layer control if updateState should be called\n shouldUpdateState({oldProps, props, context, changeFlags}) {\n return changeFlags.propsOrDataChanged;\n }\n\n // Default implementation, all attributes will be invalidated and updated\n // when data changes\n /* eslint-disable-next-line complexity */\n updateState({oldProps, props, context, changeFlags}) {\n const attributeManager = this.getAttributeManager();\n if (changeFlags.dataChanged && attributeManager) {\n const {dataChanged} = changeFlags;\n if (Array.isArray(dataChanged)) {\n // is partial update\n for (const dataRange of dataChanged) {\n attributeManager.invalidateAll(dataRange);\n }\n } else {\n attributeManager.invalidateAll();\n }\n }\n\n const neededPickingBuffer = oldProps.highlightedObjectIndex >= 0 || oldProps.pickable;\n const needPickingBuffer = props.highlightedObjectIndex >= 0 || props.pickable;\n if (neededPickingBuffer !== needPickingBuffer && attributeManager) {\n const {pickingColors, instancePickingColors} = attributeManager.attributes;\n const pickingColorsAttribute = pickingColors || instancePickingColors;\n if (pickingColorsAttribute) {\n if (needPickingBuffer && pickingColorsAttribute.constant) {\n pickingColorsAttribute.constant = false;\n attributeManager.invalidate(pickingColorsAttribute.id);\n }\n if (!pickingColorsAttribute.value && !needPickingBuffer) {\n pickingColorsAttribute.constant = true;\n pickingColorsAttribute.value = [0, 0, 0];\n }\n }\n }\n }\n\n // Called once when layer is no longer matched and state will be discarded\n // App can destroy WebGL resources here\n finalizeState() {\n for (const model of this.getModels()) {\n model.delete();\n }\n const attributeManager = this.getAttributeManager();\n if (attributeManager) {\n attributeManager.finalize();\n }\n this.context.resourceManager.unsubscribe({consumerId: this.id});\n this.internalState.uniformTransitions.clear();\n this.internalState.finalize();\n }\n\n // If state has a model, draw it with supplied uniforms\n draw(opts) {\n for (const model of this.getModels()) {\n model.draw(opts);\n }\n }\n\n // called to populate the info object that is passed to the event handler\n // @return null to cancel event\n getPickingInfo({info, mode}) {\n const {index} = info;\n\n if (index >= 0) {\n // If props.data is an indexable array, get the object\n if (Array.isArray(this.props.data)) {\n info.object = this.props.data[index];\n }\n }\n\n return info;\n }\n\n // END LIFECYCLE METHODS\n // //////////////////////////////////////////////////\n\n // INTERNAL METHODS\n activateViewport(viewport) {\n const oldViewport = this.internalState.viewport;\n this.internalState.viewport = viewport;\n\n if (!oldViewport || !areViewportsEqual({oldViewport, viewport})) {\n this.setChangeFlags({viewportChanged: true});\n\n if (this.isComposite) {\n if (this.needsUpdate()) {\n // Composite layers may add/remove sublayers on viewport change\n // Because we cannot change the layers list during a draw cycle, we don't want to update sublayers right away\n // This will not call update immediately, but mark the layerManager as needs update on the next frame\n this.setNeedsUpdate();\n }\n } else {\n this._update();\n }\n }\n }\n\n // Default implementation of attribute invalidation, can be redefined\n invalidateAttribute(name = 'all', diffReason = '') {\n const attributeManager = this.getAttributeManager();\n if (!attributeManager) {\n return;\n }\n\n if (name === 'all') {\n attributeManager.invalidateAll();\n } else {\n attributeManager.invalidate(name);\n }\n }\n\n updateAttributes(changedAttributes) {\n for (const model of this.getModels()) {\n this._setModelAttributes(model, changedAttributes);\n }\n }\n\n // Calls attribute manager to update any WebGL attributes\n _updateAttributes(props) {\n const attributeManager = this.getAttributeManager();\n if (!attributeManager) {\n return;\n }\n\n // Figure out data length\n const numInstances = this.getNumInstances(props);\n const startIndices = this.getStartIndices(props);\n\n attributeManager.update({\n data: props.data,\n numInstances,\n startIndices,\n props,\n transitions: props.transitions,\n buffers: props.data.attributes,\n context: this,\n // Don't worry about non-attribute props\n ignoreUnknownAttributes: true\n });\n\n const changedAttributes = attributeManager.getChangedAttributes({clearChangedFlags: true});\n this.updateAttributes(changedAttributes);\n }\n\n // Update attribute transitions. This is called in drawLayer, no model updates required.\n _updateAttributeTransition() {\n const attributeManager = this.getAttributeManager();\n if (attributeManager) {\n attributeManager.updateTransition();\n }\n }\n\n // Update uniform (prop) transitions. This is called in updateState, may result in model updates.\n _updateUniformTransition() {\n const {uniformTransitions} = this.internalState;\n if (uniformTransitions.active) {\n // clone props\n const propsInTransition = uniformTransitions.update();\n const props = Object.create(this.props);\n for (const key in propsInTransition) {\n Object.defineProperty(props, key, {value: propsInTransition[key]});\n }\n return props;\n }\n return this.props;\n }\n\n calculateInstancePickingColors(attribute, {numInstances}) {\n if (attribute.constant) {\n return;\n }\n\n // calculateInstancePickingColors always generates the same sequence.\n // pickingColorCache saves the largest generated sequence for reuse\n const cacheSize = Math.floor(pickingColorCache.length / 3);\n\n // Record when using the picking buffer cache, so that layers can always point at the most recently allocated cache\n this.internalState.usesPickingColorCache = true;\n\n if (cacheSize < numInstances) {\n if (numInstances > MAX_PICKING_COLOR_CACHE_SIZE) {\n log.warn(\n 'Layer has too many data objects. Picking might not be able to distinguish all objects.'\n )();\n }\n\n pickingColorCache = typedArrayManager.allocate(pickingColorCache, numInstances, {\n size: 3,\n copy: true,\n maxCount: Math.max(numInstances, MAX_PICKING_COLOR_CACHE_SIZE)\n });\n\n // If the attribute is larger than the cache, resize the cache and populate the missing chunk\n const newCacheSize = Math.floor(pickingColorCache.length / 3);\n const pickingColor = [];\n for (let i = cacheSize; i < newCacheSize; i++) {\n this.encodePickingColor(i, pickingColor);\n pickingColorCache[i * 3 + 0] = pickingColor[0];\n pickingColorCache[i * 3 + 1] = pickingColor[1];\n pickingColorCache[i * 3 + 2] = pickingColor[2];\n }\n }\n\n attribute.value = pickingColorCache.subarray(0, numInstances * 3);\n }\n\n _setModelAttributes(model, changedAttributes) {\n const attributeManager = this.getAttributeManager();\n const excludeAttributes = model.userData.excludeAttributes || {};\n const shaderAttributes = attributeManager.getShaderAttributes(\n changedAttributes,\n excludeAttributes\n );\n\n model.setAttributes(shaderAttributes);\n }\n\n // Sets the picking color at the specified index to null picking color. Used for multi-depth picking.\n // This method may be overriden by layer implementations\n disablePickingIndex(objectIndex) {\n this._disablePickingIndex(objectIndex);\n }\n\n _disablePickingIndex(objectIndex) {\n const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;\n const colors = pickingColors || instancePickingColors;\n\n const start = colors.getVertexOffset(objectIndex);\n const end = colors.getVertexOffset(objectIndex + 1);\n\n // Fill the sub buffer with 0s\n colors.buffer.subData({\n data: new Uint8Array(end - start),\n offset: start // 1 byte per element\n });\n }\n\n restorePickingColors() {\n const {pickingColors, instancePickingColors} = this.getAttributeManager().attributes;\n const colors = pickingColors || instancePickingColors;\n // The picking color cache may have been freed and then reallocated. This ensures we read from the currently allocated cache.\n if (\n this.internalState.usesPickingColorCache &&\n colors.value.buffer !== pickingColorCache.buffer\n ) {\n colors.value = pickingColorCache.subarray(0, colors.value.length);\n }\n colors.updateSubBuffer({startOffset: 0});\n }\n\n // Deduces numer of instances. Intention is to support:\n // - Explicit setting of numInstances\n // - Auto-deduction for ES6 containers that define a size member\n // - Auto-deduction for Classic Arrays via the built-in length attribute\n // - Auto-deduction via arrays\n getNumInstances(props) {\n props = props || this.props;\n\n // First Check if app has provided an explicit value\n if (props.numInstances !== undefined) {\n return props.numInstances;\n }\n\n // Second check if the layer has set its own value\n if (this.state && this.state.numInstances !== undefined) {\n return this.state.numInstances;\n }\n\n // Use container library to get a count for any ES6 container or object\n return count(props.data);\n }\n\n // Buffer layout describes how many attribute values are packed for each data object\n // The default (null) is one value each object.\n // Some data formats (e.g. paths, polygons) have various length. Their buffer layout\n // is in the form of [L0, L1, L2, ...]\n getStartIndices(props) {\n props = props || this.props;\n\n // First Check if startIndices is provided as an explicit value\n if (props.startIndices !== undefined) {\n return props.startIndices;\n }\n\n // Second check if the layer has set its own value\n if (this.state && this.state.startIndices) {\n return this.state.startIndices;\n }\n\n return null;\n }\n\n // LAYER MANAGER API\n // Should only be called by the deck.gl LayerManager class\n\n // Called by layer manager when a new layer is found\n /* eslint-disable max-statements */\n _initialize() {\n debug(TRACE_INITIALIZE, this);\n\n this._initState();\n\n // Call subclass lifecycle methods\n this.initializeState(this.context);\n // Initialize extensions\n for (const extension of this.props.extensions) {\n extension.initializeState.call(this, this.context, extension);\n }\n // End subclass lifecycle methods\n\n // initializeState callback tends to clear state\n this.setChangeFlags({\n dataChanged: true,\n propsChanged: true,\n viewportChanged: true,\n extensionsChanged: true\n });\n\n this._updateState();\n }\n\n // Called by layer manager\n // if this layer is new (not matched with an existing layer) oldProps will be empty object\n _update() {\n // Call subclass lifecycle method\n const stateNeedsUpdate = this.needsUpdate();\n // End lifecycle method\n debug(TRACE_UPDATE, this, stateNeedsUpdate);\n\n if (stateNeedsUpdate) {\n this._updateState();\n }\n }\n\n // Common code for _initialize and _update\n _updateState() {\n const currentProps = this.props;\n const currentViewport = this.context.viewport;\n const propsInTransition = this._updateUniformTransition();\n this.internalState.propsInTransition = propsInTransition;\n // Overwrite this.context.viewport during update to use the last activated viewport on this layer\n // In multi-view applications, a layer may only be drawn in one of the views\n // Which would make the \"active\" viewport different from the shared context\n this.context.viewport = this.internalState.viewport || currentViewport;\n // Overwrite this.props during update to use in-transition prop values\n this.props = propsInTransition;\n\n try {\n const updateParams = this._getUpdateParams();\n const oldModels = this.getModels();\n\n // Safely call subclass lifecycle methods\n if (this.context.gl) {\n this.updateState(updateParams);\n } else {\n try {\n this.updateState(updateParams);\n } catch (error) {\n // ignore error if gl context is missing\n }\n }\n // Execute extension updates\n for (const extension of this.props.extensions) {\n extension.updateState.call(this, updateParams, extension);\n }\n\n const modelChanged = this.getModels()[0] !== oldModels[0];\n this._updateModules(updateParams, modelChanged);\n // End subclass lifecycle methods\n\n if (this.isComposite) {\n // Render or update previously rendered sublayers\n this._renderLayers(updateParams);\n } else {\n this.setNeedsRedraw();\n // Add any subclass attributes\n this._updateAttributes(this.props);\n\n // Note: Automatic instance count update only works for single layers\n if (this.state.model) {\n this.state.model.setInstanceCount(this.getNumInstances());\n }\n }\n } finally {\n // Restore shared context\n this.context.viewport = currentViewport;\n this.props = currentProps;\n this.clearChangeFlags();\n this.internalState.needsUpdate = false;\n this.internalState.resetOldProps();\n }\n }\n /* eslint-enable max-statements */\n\n // Called by manager when layer is about to be disposed\n // Note: not guaranteed to be called on application shutdown\n _finalize() {\n debug(TRACE_FINALIZE, this);\n\n // Call subclass lifecycle method\n this.finalizeState(this.context);\n // Finalize extensions\n for (const extension of this.props.extensions) {\n extension.finalizeState.call(this, extension);\n }\n }\n\n // Calculates uniforms\n drawLayer({moduleParameters = null, uniforms = {}, parameters = {}}) {\n this._updateAttributeTransition();\n\n const currentProps = this.props;\n // Overwrite this.props during redraw to use in-transition prop values\n // `internalState.propsInTransition` could be missing if `updateState` failed\n this.props = this.internalState.propsInTransition || currentProps;\n\n const {opacity} = this.props;\n // apply gamma to opacity to make it visually \"linear\"\n uniforms.opacity = Math.pow(opacity, 1 / 2.2);\n\n try {\n // TODO/ib - hack move to luma Model.draw\n if (moduleParameters) {\n this.setModuleParameters(moduleParameters);\n }\n\n // Apply polygon offset to avoid z-fighting\n // TODO - move to draw-layers\n const {getPolygonOffset} = this.props;\n const offsets = (getPolygonOffset && getPolygonOffset(uniforms)) || [0, 0];\n\n setParameters(this.context.gl, {polygonOffset: offsets});\n\n // Call subclass lifecycle method\n withParameters(this.context.gl, parameters, () => {\n const opts = {moduleParameters, uniforms, parameters, context: this.context};\n\n // extensions\n for (const extension of this.props.extensions) {\n extension.draw.call(this, opts, extension);\n }\n\n this.draw(opts);\n });\n } finally {\n this.props = currentProps;\n }\n\n // End lifecycle method\n }\n\n // Helper methods\n getChangeFlags() {\n return this.internalState.changeFlags;\n }\n\n // Dirty some change flags, will be handled by updateLayer\n /* eslint-disable complexity */\n setChangeFlags(flags) {\n const {changeFlags} = this.internalState;\n\n /* eslint-disable no-fallthrough, max-depth */\n for (const key in flags) {\n if (flags[key]) {\n let flagChanged = false;\n switch (key) {\n case 'dataChanged':\n // changeFlags.dataChanged may be `false`, a string (reason) or an array of ranges\n if (Array.isArray(changeFlags[key])) {\n changeFlags[key] = Array.isArray(flags[key])\n ? changeFlags[key].concat(flags[key])\n : flags[key];\n flagChanged = true;\n }\n\n default:\n if (!changeFlags[key]) {\n changeFlags[key] = flags[key];\n flagChanged = true;\n }\n }\n if (flagChanged) {\n debug(TRACE_CHANGE_FLAG, this, key, flags);\n }\n }\n }\n /* eslint-enable no-fallthrough, max-depth */\n\n // Update composite flags\n const propsOrDataChanged =\n changeFlags.dataChanged ||\n changeFlags.updateTriggersChanged ||\n changeFlags.propsChanged ||\n changeFlags.extensionsChanged;\n changeFlags.propsOrDataChanged = propsOrDataChanged;\n changeFlags.somethingChanged =\n propsOrDataChanged || flags.viewportChanged || flags.stateChanged;\n }\n /* eslint-enable complexity */\n\n // Clear all changeFlags, typically after an update\n clearChangeFlags() {\n this.internalState.changeFlags = {\n // Primary changeFlags, can be strings stating reason for change\n dataChanged: false,\n propsChanged: false,\n updateTriggersChanged: false,\n viewportChanged: false,\n stateChanged: false,\n extensionsChanged: false,\n\n // Derived changeFlags\n propsOrDataChanged: false,\n somethingChanged: false\n };\n }\n\n // Compares the layers props with old props from a matched older layer\n // and extracts change flags that describe what has change so that state\n // can be update correctly with minimal effort\n diffProps(newProps, oldProps) {\n const changeFlags = diffProps(newProps, oldProps);\n\n // iterate over changedTriggers\n if (changeFlags.updateTriggersChanged) {\n for (const key in changeFlags.updateTriggersChanged) {\n if (changeFlags.updateTriggersChanged[key]) {\n this.invalidateAttribute(key);\n }\n }\n }\n\n // trigger uniform transitions\n if (changeFlags.transitionsChanged) {\n for (const key in changeFlags.transitionsChanged) {\n // prop changed and transition is enabled\n this.internalState.uniformTransitions.add(\n key,\n oldProps[key],\n newProps[key],\n newProps.transitions[key]\n );\n }\n }\n\n return this.setChangeFlags(changeFlags);\n }\n\n // Called by layer manager to validate props (in development)\n validateProps() {\n validateProps(this.props);\n }\n\n setModuleParameters(moduleParameters) {\n for (const model of this.getModels()) {\n model.updateModuleSettings(moduleParameters);\n }\n }\n\n updateAutoHighlight(info) {\n if (this.props.autoHighlight) {\n this._updateAutoHighlight(info);\n }\n }\n\n // May be overriden by classes\n _updateAutoHighlight(info) {\n const pickingModuleParameters = {\n pickingSelectedColor: info.picked ? info.color : null\n };\n const {highlightColor} = this.props;\n if (info.picked && typeof highlightColor === 'function') {\n pickingModuleParameters.pickingHighlightColor = highlightColor(info);\n }\n this.setModuleParameters(pickingModuleParameters);\n // setModuleParameters does not trigger redraw\n this.setNeedsRedraw();\n }\n\n // PRIVATE METHODS\n _updateModules({props, oldProps}, forceUpdate) {\n // Picking module parameters\n const {autoHighlight, highlightedObjectIndex, highlightColor} = props;\n if (\n forceUpdate ||\n oldProps.autoHighlight !== autoHighlight ||\n oldProps.highlightedObjectIndex !== highlightedObjectIndex ||\n oldProps.highlightColor !== highlightColor\n ) {\n const parameters = {};\n if (!autoHighlight) {\n parameters.pickingSelectedColor = null;\n }\n if (Array.isArray(highlightColor)) {\n parameters.pickingHighlightColor = highlightColor;\n }\n\n // highlightedObjectIndex will overwrite any settings from auto highlighting.\n if (Number.isInteger(highlightedObjectIndex)) {\n parameters.pickingSelectedColor =\n highlightedObjectIndex >= 0 ? this.encodePickingColor(highlightedObjectIndex) : null;\n }\n\n this.setModuleParameters(parameters);\n }\n }\n\n _getUpdateParams() {\n return {\n props: this.props,\n oldProps: this.internalState.getOldProps(),\n context: this.context,\n changeFlags: this.internalState.changeFlags\n };\n }\n\n // Checks state of attributes and model\n _getNeedsRedraw(opts) {\n // this method may be called by the render loop as soon a the layer\n // has been created, so guard against uninitialized state\n if (!this.internalState) {\n return false;\n }\n\n let redraw = false;\n redraw = redraw || (this.internalState.needsRedraw && this.id);\n this.internalState.needsRedraw = this.internalState.needsRedraw && !opts.clearRedrawFlags;\n\n // TODO - is attribute manager needed? - Model should be enough.\n const attributeManager = this.getAttributeManager();\n const attributeManagerNeedsRedraw = attributeManager && attributeManager.getNeedsRedraw(opts);\n redraw = redraw || attributeManagerNeedsRedraw;\n\n return redraw;\n }\n\n // Create new attribute manager\n _getAttributeManager() {\n return new AttributeManager(this.context.gl, {\n id: this.props.id,\n stats: this.context.stats,\n timeline: this.context.timeline\n });\n }\n\n _initState() {\n assert(!this.internalState && !this.state); // finalized layer cannot be reused\n assert(isFinite(this.props.coordinateSystem)); // invalid coordinateSystem\n\n const attributeManager = this._getAttributeManager();\n\n if (attributeManager) {\n // All instanced layers get instancePickingColors attribute by default\n // Their shaders can use it to render a picking scene\n // TODO - this slightly slows down non instanced layers\n attributeManager.addInstanced({\n instancePickingColors: {\n type: GL.UNSIGNED_BYTE,\n size: 3,\n noAlloc: true,\n update: this.calculateInstancePickingColors\n }\n });\n }\n\n this.internalState = new LayerState({\n attributeManager,\n layer: this\n });\n this.clearChangeFlags(); // populate this.internalState.changeFlags\n\n this.state = {};\n // for backwards compatibility with older layers\n // TODO - remove in next release\n /* eslint-disable accessor-pairs */\n Object.defineProperty(this.state, 'attributeManager', {\n get: () => {\n log.deprecated('layer.state.attributeManager', 'layer.getAttributeManager()');\n return attributeManager;\n }\n });\n /* eslint-enable accessor-pairs */\n\n this.internalState.layer = this;\n this.internalState.uniformTransitions = new UniformTransitionManager(this.context.timeline);\n this.internalState.onAsyncPropUpdated = this._onAsyncPropUpdated.bind(this);\n\n // Ensure any async props are updated\n this.internalState.setAsyncProps(this.props);\n }\n\n // Called by layer manager to transfer state from an old layer\n _transferState(oldLayer) {\n debug(TRACE_MATCHED, this, this === oldLayer);\n\n const {state, internalState} = oldLayer;\n\n if (this === oldLayer) {\n return;\n }\n\n // Move internalState\n this.internalState = internalState;\n this.internalState.layer = this;\n\n // Move state\n this.state = state;\n // We keep the state ref on old layers to support async actions\n // oldLayer.state = null;\n\n // Ensure any async props are updated\n this.internalState.setAsyncProps(this.props);\n\n this.diffProps(this.props, this.internalState.getOldProps());\n }\n\n _onAsyncPropUpdated() {\n this.diffProps(this.props, this.internalState.getOldProps());\n this.setNeedsUpdate();\n }\n}\n\nLayer.layerName = 'Layer';\nLayer.defaultProps = defaultProps;\n","/* eslint-disable complexity */\n\n/* This class creates a luma.gl-compatible \"view\" on top of a DataColumn instance */\nexport default class ShaderAttribute {\n constructor(dataColumn, opts) {\n // Options that cannot be changed later\n this.opts = opts;\n this.source = dataColumn;\n }\n\n get value() {\n return this.source.value;\n }\n\n getValue() {\n const buffer = this.source.getBuffer();\n const accessor = this.getAccessor();\n if (buffer) {\n return [buffer, accessor];\n }\n\n const {value} = this.source;\n const {size} = accessor;\n let constantValue = value;\n\n if (value && value.length !== size) {\n constantValue = new Float32Array(size);\n // initiate offset values\n const index = accessor.elementOffset || 0; // element offset\n for (let i = 0; i < size; ++i) {\n constantValue[i] = value[index + i];\n }\n }\n\n return constantValue;\n }\n\n getAccessor() {\n return {\n // source data accessor\n ...this.source.getAccessor(),\n // shader attribute overrides\n ...this.opts\n };\n }\n}\n","/* eslint-disable complexity */\nimport GL from '@luma.gl/constants';\nimport {hasFeature, FEATURES, Buffer} from '@luma.gl/core';\nimport ShaderAttribute from './shader-attribute';\nimport {glArrayFromType} from './gl-utils';\nimport typedArrayManager from '../../utils/typed-array-manager';\nimport {toDoublePrecisionArray} from '../../utils/math-utils';\nimport log from '../../utils/log';\n\nfunction getStride(accessor) {\n return accessor.stride || accessor.size * accessor.bytesPerElement;\n}\n\nfunction resolveShaderAttribute(baseAccessor, shaderAttributeOptions) {\n if (shaderAttributeOptions.offset) {\n log.removed('shaderAttribute.offset', 'vertexOffset, elementOffset')();\n }\n\n // All shader attributes share the parent's stride\n const stride = getStride(baseAccessor);\n // `vertexOffset` is used to access the neighboring vertex's value\n // e.g. `nextPositions` in polygon\n const vertexOffset =\n 'vertexOffset' in shaderAttributeOptions\n ? shaderAttributeOptions.vertexOffset\n : baseAccessor.vertexOffset || 0;\n // `elementOffset` is defined when shader attribute's size is smaller than the parent's\n // e.g. `translations` in transform matrix\n const elementOffset = shaderAttributeOptions.elementOffset || 0;\n const offset =\n // offsets defined by the attribute\n vertexOffset * stride +\n elementOffset * baseAccessor.bytesPerElement +\n // offsets defined by external buffers if any\n (baseAccessor.offset || 0);\n\n return {\n ...shaderAttributeOptions,\n offset,\n stride\n };\n}\n\nfunction resolveDoublePrecisionShaderAttributes(baseAccessor, shaderAttributeOptions) {\n const resolvedOptions = resolveShaderAttribute(baseAccessor, shaderAttributeOptions);\n\n return {\n high: resolvedOptions,\n low: {\n ...resolvedOptions,\n offset: resolvedOptions.offset + baseAccessor.size * 4\n }\n };\n}\n\nexport default class DataColumn {\n /* eslint-disable max-statements */\n constructor(gl, opts) {\n this.gl = gl;\n this.id = opts.id;\n this.size = opts.size;\n\n const logicalType = opts.logicalType || opts.type;\n const doublePrecision = logicalType === GL.DOUBLE;\n\n let {defaultValue} = opts;\n defaultValue = Number.isFinite(defaultValue)\n ? [defaultValue]\n : defaultValue || new Array(this.size).fill(0);\n opts.defaultValue = defaultValue;\n\n let bufferType = logicalType;\n if (doublePrecision) {\n bufferType = GL.FLOAT;\n } else if (!bufferType && opts.isIndexed) {\n bufferType =\n gl && hasFeature(gl, FEATURES.ELEMENT_INDEX_UINT32) ? GL.UNSIGNED_INT : GL.UNSIGNED_SHORT;\n } else if (!bufferType) {\n bufferType = GL.FLOAT;\n }\n opts.logicalType = logicalType;\n opts.type = bufferType;\n\n // This is the attribute type defined by the layer\n // If an external buffer is provided, this.type may be overwritten\n // But we always want to use defaultType for allocation\n let defaultType = glArrayFromType(logicalType || bufferType || GL.FLOAT);\n this.shaderAttributes = {};\n this.doublePrecision = doublePrecision;\n\n // `fp64: false` tells a double-precision attribute to allocate Float32Arrays\n // by default when using auto-packing. This is more efficient in use cases where\n // high precision is unnecessary, but the `64Low` attribute is still required\n // by the shader.\n if (doublePrecision && opts.fp64 === false) {\n defaultType = Float32Array;\n }\n opts.bytesPerElement = defaultType.BYTES_PER_ELEMENT;\n\n this.defaultType = defaultType;\n this.value = null;\n this.settings = opts;\n this.state = {\n externalBuffer: null,\n bufferAccessor: opts,\n allocatedValue: null,\n constant: false\n };\n this._buffer = null;\n\n this.setData(opts);\n }\n /* eslint-enable max-statements */\n\n get buffer() {\n if (!this._buffer) {\n const {isIndexed, type} = this.settings;\n this._buffer = new Buffer(this.gl, {\n id: this.id,\n target: isIndexed ? GL.ELEMENT_ARRAY_BUFFER : GL.ARRAY_BUFFER,\n accessor: {type}\n });\n }\n return this._buffer;\n }\n\n get byteOffset() {\n const accessor = this.getAccessor();\n if (accessor.vertexOffset) {\n return accessor.vertexOffset * getStride(accessor);\n }\n return 0;\n }\n\n delete() {\n if (this._buffer) {\n this._buffer.delete();\n this._buffer = null;\n }\n typedArrayManager.release(this.state.allocatedValue);\n }\n\n getShaderAttributes(id, options) {\n if (this.doublePrecision) {\n const shaderAttributes = {};\n const isBuffer64Bit = this.value instanceof Float64Array;\n\n const doubleShaderAttributeDefs = resolveDoublePrecisionShaderAttributes(\n this.getAccessor(),\n options || {}\n );\n\n shaderAttributes[id] = new ShaderAttribute(this, doubleShaderAttributeDefs.high);\n shaderAttributes[`${id}64Low`] = isBuffer64Bit\n ? new ShaderAttribute(this, doubleShaderAttributeDefs.low)\n : new Float32Array(this.size); // use constant for low part if buffer is 32-bit\n return shaderAttributes;\n }\n if (options) {\n const shaderAttributeDef = resolveShaderAttribute(this.getAccessor(), options);\n return {[id]: new ShaderAttribute(this, shaderAttributeDef)};\n }\n return {[id]: this};\n }\n\n getBuffer() {\n if (this.state.constant) {\n return null;\n }\n return this.state.externalBuffer || this._buffer;\n }\n\n getValue() {\n if (this.state.constant) {\n return this.value;\n }\n return [this.getBuffer(), this.getAccessor()];\n }\n\n getAccessor() {\n return this.state.bufferAccessor;\n }\n\n // returns true if success\n // eslint-disable-next-line max-statements\n setData(opts) {\n const {state} = this;\n if (ArrayBuffer.isView(opts)) {\n opts = {value: opts};\n } else if (opts instanceof Buffer) {\n opts = {buffer: opts};\n }\n\n const accessor = {...this.settings, ...opts};\n state.bufferAccessor = accessor;\n\n if (opts.constant) {\n // set constant\n let value = opts.value;\n value = this._normalizeValue(value, [], 0);\n if (this.settings.normalized) {\n value = this._normalizeConstant(value);\n }\n const hasChanged = !state.constant || !this._areValuesEqual(value, this.value);\n\n if (!hasChanged) {\n return false;\n }\n state.externalBuffer = null;\n state.constant = true;\n this.value = value;\n } else if (opts.buffer) {\n const buffer = opts.buffer;\n state.externalBuffer = buffer;\n state.constant = false;\n this.value = opts.value;\n const isBuffer64Bit = opts.value instanceof Float64Array;\n\n // Copy the type of the buffer into the accessor\n accessor.type = opts.type || buffer.accessor.type;\n accessor.bytesPerElement = buffer.accessor.BYTES_PER_ELEMENT * (isBuffer64Bit ? 2 : 1);\n accessor.stride = getStride(accessor);\n } else if (opts.value) {\n this._checkExternalBuffer(opts);\n\n let value = opts.value;\n state.externalBuffer = null;\n state.constant = false;\n this.value = value;\n\n accessor.bytesPerElement = value.BYTES_PER_ELEMENT;\n accessor.stride = getStride(accessor);\n\n const {buffer, byteOffset} = this;\n\n if (this.doublePrecision && value instanceof Float64Array) {\n value = toDoublePrecisionArray(value, accessor);\n }\n\n // A small over allocation is used as safety margin\n // Shader attributes may try to access this buffer with bigger offsets\n const requiredBufferSize = value.byteLength + byteOffset + accessor.stride * 2;\n if (buffer.byteLength < requiredBufferSize) {\n buffer.reallocate(requiredBufferSize);\n }\n // Hack: force Buffer to infer data type\n buffer.setAccessor(null);\n buffer.subData({data: value, offset: byteOffset});\n accessor.type = opts.type || buffer.accessor.type;\n }\n\n return true;\n }\n\n updateSubBuffer(opts = {}) {\n const {value} = this;\n const {startOffset = 0, endOffset} = opts;\n this.buffer.subData({\n data:\n this.doublePrecision && value instanceof Float64Array\n ? toDoublePrecisionArray(value, {\n size: this.size,\n startIndex: startOffset,\n endIndex: endOffset\n })\n : value.subarray(startOffset, endOffset),\n offset: startOffset * value.BYTES_PER_ELEMENT + this.byteOffset\n });\n }\n\n allocate({numInstances, copy = false}) {\n const {state} = this;\n const oldValue = state.allocatedValue;\n\n // Allocate at least one element to ensure a valid buffer\n const value = typedArrayManager.allocate(oldValue, numInstances + 1, {\n size: this.size,\n type: this.defaultType,\n copy\n });\n\n this.value = value;\n\n const {buffer, byteOffset} = this;\n\n if (buffer.byteLength < value.byteLength + byteOffset) {\n buffer.reallocate(value.byteLength + byteOffset);\n\n if (copy && oldValue) {\n // Upload the full existing attribute value to the GPU, so that updateBuffer\n // can choose to only update a partial range.\n // TODO - copy old buffer to new buffer on the GPU\n buffer.subData({\n data:\n oldValue instanceof Float64Array ? toDoublePrecisionArray(oldValue, this) : oldValue,\n offset: byteOffset\n });\n }\n }\n\n state.allocatedValue = value;\n state.constant = false;\n state.externalBuffer = null;\n state.bufferAccessor = this.settings;\n return true;\n }\n\n // PRIVATE HELPER METHODS\n _checkExternalBuffer(opts) {\n const {value} = opts;\n if (!opts.constant && value) {\n const ArrayType = this.defaultType;\n\n let illegalArrayType = false;\n if (this.doublePrecision) {\n // not 32bit or 64bit\n illegalArrayType = value.BYTES_PER_ELEMENT < 4;\n }\n if (illegalArrayType) {\n throw new Error(`Attribute ${this.id} does not support ${value.constructor.name}`);\n }\n if (!(value instanceof ArrayType) && this.settings.normalized && !('normalized' in opts)) {\n log.warn(`Attribute ${this.id} is normalized`)();\n }\n }\n }\n\n // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer\n _normalizeConstant(value) {\n switch (this.settings.type) {\n case GL.BYTE:\n // normalize [-128, 127] to [-1, 1]\n return new Float32Array(value).map(x => ((x + 128) / 255) * 2 - 1);\n\n case GL.SHORT:\n // normalize [-32768, 32767] to [-1, 1]\n return new Float32Array(value).map(x => ((x + 32768) / 65535) * 2 - 1);\n\n case GL.UNSIGNED_BYTE:\n // normalize [0, 255] to [0, 1]\n return new Float32Array(value).map(x => x / 255);\n\n case GL.UNSIGNED_SHORT:\n // normalize [0, 65535] to [0, 1]\n return new Float32Array(value).map(x => x / 65535);\n\n default:\n // No normalization for gl.FLOAT and gl.HALF_FLOAT\n return value;\n }\n }\n\n /* check user supplied values and apply fallback */\n _normalizeValue(value, out, start) {\n const {defaultValue, size} = this.settings;\n\n if (Number.isFinite(value)) {\n out[start] = value;\n return out;\n }\n if (!value) {\n out[start] = defaultValue[0];\n return out;\n }\n\n // Important - switch cases are 5x more performant than a for loop!\n /* eslint-disable no-fallthrough, default-case */\n switch (size) {\n case 4:\n out[start + 3] = Number.isFinite(value[3]) ? value[3] : defaultValue[3];\n case 3:\n out[start + 2] = Number.isFinite(value[2]) ? value[2] : defaultValue[2];\n case 2:\n out[start + 1] = Number.isFinite(value[1]) ? value[1] : defaultValue[1];\n case 1:\n out[start + 0] = Number.isFinite(value[0]) ? value[0] : defaultValue[0];\n break;\n\n default:\n // In the rare case where the attribute size > 4, do it the slow way\n // This is used for e.g. transform matrices\n let i = size;\n while (--i >= 0) {\n out[start + i] = Number.isFinite(value[i]) ? value[i] : defaultValue[i];\n }\n }\n\n return out;\n }\n\n _areValuesEqual(value1, value2) {\n if (!value1 || !value2) {\n return false;\n }\n const {size} = this;\n for (let i = 0; i < size; i++) {\n if (value1[i] !== value2[i]) {\n return false;\n }\n }\n return true;\n }\n}\n","import GL from '@luma.gl/constants';\n\n/* eslint-disable complexity */\nexport function glArrayFromType(glType) {\n // Sorted in some order of likelihood to reduce amount of comparisons\n switch (glType) {\n case GL.FLOAT:\n return Float32Array;\n case GL.DOUBLE:\n return Float64Array;\n case GL.UNSIGNED_SHORT:\n case GL.UNSIGNED_SHORT_5_6_5:\n case GL.UNSIGNED_SHORT_4_4_4_4:\n case GL.UNSIGNED_SHORT_5_5_5_1:\n return Uint16Array;\n case GL.UNSIGNED_INT:\n return Uint32Array;\n case GL.UNSIGNED_BYTE:\n return Uint8ClampedArray;\n case GL.BYTE:\n return Int8Array;\n case GL.SHORT:\n return Int16Array;\n case GL.INT:\n return Int32Array;\n default:\n throw new Error('Unknown GL type');\n }\n}\n/* eslint-enable complexity */\n","/* \n * range (Array)\n * + start (Number) - the start index (incl.)\n * + end (Number) - the end index (excl.)\n * rangeList (Array) - array of sorted, combined ranges\n */\nexport const EMPTY = [];\nexport const FULL = [[0, Infinity]];\n\n// Insert a range into a range collection\nexport function add(rangeList, range) {\n // Noop if range collection already covers all\n if (rangeList === FULL) {\n return rangeList;\n }\n\n // Validate the input range\n if (range[0] < 0) {\n range[0] = 0;\n }\n if (range[0] >= range[1]) {\n return rangeList;\n }\n\n // TODO - split off to tree-shakable Range class\n const newRangeList = [];\n const len = rangeList.length;\n let insertPosition = 0;\n\n for (let i = 0; i < len; i++) {\n const range0 = rangeList[i];\n\n if (range0[1] < range[0]) {\n // the current range is to the left of the new range\n newRangeList.push(range0);\n insertPosition = i + 1;\n } else if (range0[0] > range[1]) {\n // the current range is to the right of the new range\n newRangeList.push(range0);\n } else {\n range = [Math.min(range0[0], range[0]), Math.max(range0[1], range[1])];\n }\n }\n newRangeList.splice(insertPosition, 0, range);\n return newRangeList;\n}\n","/* eslint-disable complexity */\nimport DataColumn from './data-column';\nimport assert from '../../utils/assert';\nimport {createIterable, getAccessorFromBuffer} from '../../utils/iterable-utils';\nimport {fillArray} from '../../utils/flatten';\nimport * as range from '../../utils/range';\nimport {normalizeTransitionSettings} from './attribute-transition-utils';\n\nexport default class Attribute extends DataColumn {\n constructor(gl, opts = {}) {\n super(gl, opts);\n\n const {\n // deck.gl fields\n transition = false,\n noAlloc = false,\n update = null,\n accessor = null,\n transform = null,\n startIndices = null\n } = opts;\n\n Object.assign(this.settings, {\n transition,\n noAlloc,\n update: update || (accessor && this._autoUpdater),\n accessor,\n transform\n });\n\n Object.assign(this.state, {\n lastExternalBuffer: null,\n binaryValue: null,\n binaryAccessor: null,\n needsUpdate: true,\n needsRedraw: false,\n updateRanges: range.FULL,\n startIndices\n });\n\n Object.seal(this.settings);\n Object.seal(this.state);\n\n // Check all fields and generate helpful error messages\n this._validateAttributeUpdaters();\n }\n\n get startIndices() {\n return this.state.startIndices;\n }\n\n set startIndices(layout) {\n this.state.startIndices = layout;\n }\n\n needsUpdate() {\n return this.state.needsUpdate;\n }\n\n needsRedraw({clearChangedFlags = false} = {}) {\n const needsRedraw = this.state.needsRedraw;\n this.state.needsRedraw = needsRedraw && !clearChangedFlags;\n return needsRedraw;\n }\n\n getUpdateTriggers() {\n const {accessor} = this.settings;\n\n // Backards compatibility: allow attribute name to be used as update trigger key\n return [this.id].concat((typeof accessor !== 'function' && accessor) || []);\n }\n\n supportsTransition() {\n return Boolean(this.settings.transition);\n }\n\n // Resolve transition settings object if transition is enabled, otherwise `null`\n getTransitionSetting(opts) {\n if (!opts || !this.supportsTransition()) {\n return null;\n }\n const {accessor} = this.settings;\n // TODO: have the layer resolve these transition settings itself?\n const layerSettings = this.settings.transition;\n // these are the transition settings passed in by the user\n const userSettings = Array.isArray(accessor)\n ? opts[accessor.find(a => opts[a])]\n : opts[accessor];\n\n // Shorthand: use duration instead of parameter object\n return normalizeTransitionSettings(userSettings, layerSettings);\n }\n\n setNeedsUpdate(reason = this.id, dataRange) {\n this.state.needsUpdate = this.state.needsUpdate || reason;\n this.setNeedsRedraw(reason);\n if (dataRange) {\n const {startRow = 0, endRow = Infinity} = dataRange;\n this.state.updateRanges = range.add(this.state.updateRanges, [startRow, endRow]);\n } else {\n this.state.updateRanges = range.FULL;\n }\n }\n\n clearNeedsUpdate() {\n this.state.needsUpdate = false;\n this.state.updateRanges = range.EMPTY;\n }\n\n setNeedsRedraw(reason = this.id) {\n this.state.needsRedraw = this.state.needsRedraw || reason;\n }\n\n update(opts) {\n // backward compatibility\n this.setData(opts);\n }\n\n allocate(numInstances) {\n const {state, settings} = this;\n\n if (settings.noAlloc) {\n // Data is provided through a Buffer object.\n return false;\n }\n\n if (settings.update) {\n super.allocate({\n numInstances,\n copy: state.updateRanges !== range.FULL\n });\n return true;\n }\n\n return false;\n }\n\n updateBuffer({numInstances, data, props, context}) {\n if (!this.needsUpdate()) {\n return false;\n }\n\n const {\n state: {updateRanges},\n settings: {update, noAlloc}\n } = this;\n\n let updated = true;\n if (update) {\n // Custom updater - typically for non-instanced layers\n for (const [startRow, endRow] of updateRanges) {\n update.call(context, this, {data, startRow, endRow, props, numInstances});\n }\n if (!this.value) {\n // no value was assigned during update\n } else if (\n this.constant ||\n this.buffer.byteLength < this.value.byteLength + this.byteOffset\n ) {\n this.setData({\n value: this.value,\n constant: this.constant\n });\n // Setting attribute.constant in updater is a legacy approach that interferes with allocation in the next cycle\n // Respect it here but reset after use\n this.constant = false;\n } else {\n for (const [startRow, endRow] of updateRanges) {\n const startOffset = Number.isFinite(startRow) ? this.getVertexOffset(startRow) : 0;\n const endOffset = Number.isFinite(endRow)\n ? this.getVertexOffset(endRow)\n : noAlloc || !Number.isFinite(numInstances)\n ? this.value.length\n : numInstances * this.size;\n\n super.updateSubBuffer({startOffset, endOffset});\n }\n }\n this._checkAttributeArray();\n } else {\n updated = false;\n }\n\n this.clearNeedsUpdate();\n this.setNeedsRedraw();\n\n return updated;\n }\n\n // Use generic value\n // Returns true if successful\n setConstantValue(value) {\n if (value === undefined || typeof value === 'function') {\n return false;\n }\n\n const hasChanged = this.setData({constant: true, value});\n\n if (hasChanged) {\n this.setNeedsRedraw();\n }\n this.clearNeedsUpdate();\n return true;\n }\n\n // Use external buffer\n // Returns true if successful\n // eslint-disable-next-line max-statements\n setExternalBuffer(buffer) {\n const {state} = this;\n\n if (!buffer) {\n state.lastExternalBuffer = null;\n return false;\n }\n\n this.clearNeedsUpdate();\n\n if (state.lastExternalBuffer === buffer) {\n return true;\n }\n state.lastExternalBuffer = buffer;\n this.setNeedsRedraw();\n this.setData(buffer);\n return true;\n }\n\n // Binary value is a typed array packed from mapping the source data with the accessor\n // If the returned value from the accessor is the same as the attribute value, set it directly\n // Otherwise use the auto updater for transform/normalization\n setBinaryValue(buffer, startIndices = null) {\n const {state, settings} = this;\n\n if (!buffer) {\n state.binaryValue = null;\n state.binaryAccessor = null;\n return false;\n }\n\n if (settings.noAlloc) {\n // Let the layer handle this\n return false;\n }\n\n if (state.binaryValue === buffer) {\n this.clearNeedsUpdate();\n return true;\n }\n state.binaryValue = buffer;\n this.setNeedsRedraw();\n\n if (ArrayBuffer.isView(buffer)) {\n buffer = {value: buffer};\n }\n const needsUpdate = settings.transform || startIndices !== this.startIndices;\n\n if (needsUpdate) {\n assert(ArrayBuffer.isView(buffer.value), `invalid ${settings.accessor}`);\n const needsNormalize = buffer.size && buffer.size !== this.size;\n\n state.binaryAccessor = getAccessorFromBuffer(buffer.value, {\n size: buffer.size || this.size,\n stride: buffer.stride,\n offset: buffer.offset,\n startIndices,\n nested: needsNormalize\n });\n // Fall through to auto updater\n return false;\n }\n\n this.clearNeedsUpdate();\n this.setData(buffer);\n return true;\n }\n\n getVertexOffset(row) {\n const {startIndices} = this;\n const vertexIndex = startIndices ? startIndices[row] : row;\n return vertexIndex * this.size;\n }\n\n getShaderAttributes() {\n const shaderAttributeDefs = this.settings.shaderAttributes || {[this.id]: null};\n const shaderAttributes = {};\n\n for (const shaderAttributeName in shaderAttributeDefs) {\n Object.assign(\n shaderAttributes,\n super.getShaderAttributes(shaderAttributeName, shaderAttributeDefs[shaderAttributeName])\n );\n }\n\n return shaderAttributes;\n }\n\n /* eslint-disable max-depth, max-statements */\n _autoUpdater(attribute, {data, startRow, endRow, props, numInstances}) {\n if (attribute.constant) {\n return;\n }\n const {settings, state, value, size, startIndices} = attribute;\n\n const {accessor, transform} = settings;\n const accessorFunc =\n state.binaryAccessor || (typeof accessor === 'function' ? accessor : props[accessor]);\n\n assert(typeof accessorFunc === 'function', `accessor \"${accessor}\" is not a function`);\n\n let i = attribute.getVertexOffset(startRow);\n const {iterable, objectInfo} = createIterable(data, startRow, endRow);\n for (const object of iterable) {\n objectInfo.index++;\n\n let objectValue = accessorFunc(object, objectInfo);\n if (transform) {\n // transform callbacks could be bound to a particular layer instance.\n // always point `this` to the current layer.\n objectValue = transform.call(this, objectValue);\n }\n\n if (startIndices) {\n const numVertices =\n (objectInfo.index < startIndices.length - 1\n ? startIndices[objectInfo.index + 1]\n : numInstances) - startIndices[objectInfo.index];\n if (objectValue && Array.isArray(objectValue[0])) {\n let startIndex = i;\n for (const item of objectValue) {\n attribute._normalizeValue(item, value, startIndex);\n startIndex += size;\n }\n } else if (objectValue && objectValue.length > size) {\n value.set(objectValue, i);\n } else {\n attribute._normalizeValue(objectValue, objectInfo.target, 0);\n fillArray({\n target: value,\n source: objectInfo.target,\n start: i,\n count: numVertices\n });\n }\n i += numVertices * size;\n } else {\n attribute._normalizeValue(objectValue, value, i);\n i += size;\n }\n }\n }\n /* eslint-enable max-depth, max-statements */\n\n // Validate deck.gl level fields\n _validateAttributeUpdaters() {\n const {settings} = this;\n\n // Check that 'update' is a valid function\n const hasUpdater = settings.noAlloc || typeof settings.update === 'function';\n if (!hasUpdater) {\n throw new Error(`Attribute ${this.id} missing update or accessor`);\n }\n }\n\n // check that the first few elements of the attribute are reasonable\n /* eslint-disable no-fallthrough */\n _checkAttributeArray() {\n const {value} = this;\n const limit = Math.min(4, this.size);\n if (value && value.length >= limit) {\n let valid = true;\n switch (limit) {\n case 4:\n valid = valid && Number.isFinite(value[3]);\n case 3:\n valid = valid && Number.isFinite(value[2]);\n case 2:\n valid = valid && Number.isFinite(value[1]);\n case 1:\n valid = valid && Number.isFinite(value[0]);\n break;\n default:\n valid = false;\n }\n\n if (!valid) {\n throw new Error(`Illegal attribute generated for ${this.id}`);\n }\n }\n }\n /* eslint-enable no-fallthrough */\n}\n","import GL from '@luma.gl/constants';\nimport {Buffer, Transform} from '@luma.gl/core';\nimport Attribute from '../lib/attribute/attribute';\nimport {\n padBuffer,\n getAttributeTypeFromSize,\n getSourceBufferAttribute,\n getAttributeBufferLength,\n cycleBuffers\n} from '../lib/attribute/attribute-transition-utils';\nimport Transition from './transition';\n\nexport default class GPUInterpolationTransition {\n constructor({gl, attribute, timeline}) {\n this.gl = gl;\n this.type = 'interpolation';\n this.transition = new Transition(timeline);\n this.attribute = attribute;\n // this is the attribute we return during the transition - note: if it is a constant\n // attribute, it will be converted and returned as a regular attribute\n // `attribute.userData` is the original options passed when constructing the attribute.\n // This ensures that we set the proper `doublePrecision` flag and shader attributes.\n this.attributeInTransition = new Attribute(gl, attribute.settings);\n this.currentStartIndices = attribute.startIndices;\n // storing currentLength because this.buffer may be larger than the actual length we want to use\n // this is because we only reallocate buffers when they grow, not when they shrink,\n // due to performance costs\n this.currentLength = 0;\n this.transform = getTransform(gl, attribute);\n const bufferOpts = {\n byteLength: 0,\n usage: GL.DYNAMIC_COPY\n };\n this.buffers = [\n new Buffer(gl, bufferOpts), // from\n new Buffer(gl, bufferOpts) // current\n ];\n }\n\n get inProgress() {\n return this.transition.inProgress;\n }\n\n // this is called when an attribute's values have changed and\n // we need to start animating towards the new values\n // this also correctly resizes / pads the transform's buffers\n // in case the attribute's buffer has changed in length or in\n // startIndices\n start(transitionSettings, numInstances) {\n if (transitionSettings.duration <= 0) {\n this.transition.cancel();\n return;\n }\n\n const {gl, buffers, attribute} = this;\n // Alternate between two buffers when new transitions start.\n // Last destination buffer is used as an attribute (from state),\n // And the other buffer is now the current buffer.\n cycleBuffers(buffers);\n\n const padBufferOpts = {\n numInstances,\n attribute,\n fromLength: this.currentLength,\n fromStartIndices: this.currentStartIndices,\n getData: transitionSettings.enter\n };\n\n for (const buffer of buffers) {\n padBuffer({buffer, ...padBufferOpts});\n }\n\n this.currentStartIndices = attribute.startIndices;\n this.currentLength = getAttributeBufferLength(attribute, numInstances);\n this.attributeInTransition.update({\n buffer: buffers[1],\n // Hack: Float64Array is required for double-precision attributes\n // to generate correct shader attributes\n value: attribute.value\n });\n\n this.transition.start(transitionSettings);\n\n this.transform.update({\n elementCount: Math.floor(this.currentLength / attribute.size),\n sourceBuffers: {\n aFrom: buffers[0],\n aTo: getSourceBufferAttribute(gl, attribute)\n },\n feedbackBuffers: {\n vCurrent: buffers[1]\n }\n });\n }\n\n update() {\n const updated = this.transition.update();\n if (updated) {\n const {\n time,\n settings: {duration, easing}\n } = this.transition;\n const t = easing(time / duration);\n this.transform.run({\n uniforms: {time: t}\n });\n }\n return updated;\n }\n\n cancel() {\n this.transition.cancel();\n this.transform.delete();\n while (this.buffers.length) {\n this.buffers.pop().delete();\n }\n }\n}\n\nconst vs = `\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nuniform float time;\nattribute ATTRIBUTE_TYPE aFrom;\nattribute ATTRIBUTE_TYPE aTo;\nvarying ATTRIBUTE_TYPE vCurrent;\n\nvoid main(void) {\n vCurrent = mix(aFrom, aTo, time);\n gl_Position = vec4(0.0);\n}\n`;\n\nfunction getTransform(gl, attribute) {\n const attributeType = getAttributeTypeFromSize(attribute.size);\n return new Transform(gl, {\n vs,\n defines: {\n ATTRIBUTE_TYPE: attributeType\n },\n varyings: ['vCurrent']\n });\n}\n","import {Transform} from '@luma.gl/core';\nimport GPUInterpolationTransition from '../../transitions/gpu-interpolation-transition';\nimport GPUSpringTransition from '../../transitions/gpu-spring-transition';\nimport log from '../../utils/log';\n\nconst TRANSITION_TYPES = {\n interpolation: GPUInterpolationTransition,\n spring: GPUSpringTransition\n};\n\nexport default class AttributeTransitionManager {\n constructor(gl, {id, timeline}) {\n this.id = id;\n this.gl = gl;\n this.timeline = timeline;\n\n this.transitions = {};\n this.needsRedraw = false;\n this.numInstances = 1;\n\n this.isSupported = Transform.isSupported(gl);\n }\n\n finalize() {\n for (const attributeName in this.transitions) {\n this._removeTransition(attributeName);\n }\n }\n\n /* Public methods */\n\n // Called when attribute manager updates\n // Check the latest attributes for updates.\n update({attributes, transitions, numInstances}) {\n // Transform class will crash if elementCount is 0\n this.numInstances = numInstances || 1;\n\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n const settings = attribute.getTransitionSetting(transitions);\n\n // this attribute might not support transitions?\n if (!settings) continue; // eslint-disable-line no-continue\n this._updateAttribute(attributeName, attribute, settings);\n }\n\n for (const attributeName in this.transitions) {\n const attribute = attributes[attributeName];\n if (!attribute || !attribute.getTransitionSetting(transitions)) {\n // Animated attribute has been removed\n this._removeTransition(attributeName);\n }\n }\n }\n\n // Returns `true` if attribute is transition-enabled\n hasAttribute(attributeName) {\n const transition = this.transitions[attributeName];\n return transition && transition.inProgress;\n }\n\n // Get all the animated attributes\n getAttributes() {\n const animatedAttributes = {};\n\n for (const attributeName in this.transitions) {\n const transition = this.transitions[attributeName];\n if (transition.inProgress) {\n animatedAttributes[attributeName] = transition.attributeInTransition;\n }\n }\n\n return animatedAttributes;\n }\n\n /* eslint-disable max-statements */\n // Called every render cycle, run transform feedback\n // Returns `true` if anything changes\n run() {\n if (!this.isSupported || this.numInstances === 0) {\n return false;\n }\n\n for (const attributeName in this.transitions) {\n const updated = this.transitions[attributeName].update();\n if (updated) {\n this.needsRedraw = true;\n }\n }\n\n const needsRedraw = this.needsRedraw;\n this.needsRedraw = false;\n return needsRedraw;\n }\n /* eslint-enable max-statements */\n\n /* Private methods */\n _removeTransition(attributeName) {\n this.transitions[attributeName].cancel();\n delete this.transitions[attributeName];\n }\n\n // Check an attributes for updates\n // Returns a transition object if a new transition is triggered.\n _updateAttribute(attributeName, attribute, settings) {\n const transition = this.transitions[attributeName];\n // an attribute can change transition type when it updates\n // let's remove the transition when that happens so we can create the new transition type\n // TODO: when switching transition types, make sure to carry over the attribute's\n // previous buffers, currentLength, startIndices, etc, to be used as the starting point\n // for the next transition\n let isNew = !transition || transition.type !== settings.type;\n if (isNew) {\n if (!this.isSupported) {\n log.warn(\n `WebGL2 not supported by this browser. Transition for ${attributeName} is disabled.`\n )();\n return;\n }\n\n if (transition) {\n this._removeTransition(attributeName);\n }\n\n const TransitionType = TRANSITION_TYPES[settings.type];\n if (TransitionType) {\n this.transitions[attributeName] = new TransitionType({\n attribute,\n timeline: this.timeline,\n gl: this.gl\n });\n } else {\n log.error(`unsupported transition type '${settings.type}'`)();\n isNew = false;\n }\n }\n\n if (isNew || attribute.needsRedraw()) {\n this.needsRedraw = true;\n this.transitions[attributeName].start(settings, this.numInstances);\n }\n }\n}\n","/* eslint-disable complexity, max-statements, max-params */\nimport GL from '@luma.gl/constants';\nimport {Buffer, Transform, Framebuffer, Texture2D, readPixelsToArray} from '@luma.gl/core';\nimport {\n padBuffer,\n getAttributeTypeFromSize,\n getSourceBufferAttribute,\n getAttributeBufferLength,\n cycleBuffers\n} from '../lib/attribute/attribute-transition-utils';\nimport Attribute from '../lib/attribute/attribute';\nimport Transition from './transition';\n\nexport default class GPUSpringTransition {\n constructor({gl, attribute, timeline}) {\n this.gl = gl;\n this.type = 'spring';\n this.transition = new Transition(timeline);\n this.attribute = attribute;\n // this is the attribute we return during the transition - note: if it is a constant\n // attribute, it will be converted and returned as a regular attribute\n // `attribute.userData` is the original options passed when constructing the attribute.\n // This ensures that we set the proper `doublePrecision` flag and shader attributes.\n this.attributeInTransition = new Attribute(gl, {...attribute.settings, normalized: false});\n this.currentStartIndices = attribute.startIndices;\n // storing currentLength because this.buffer may be larger than the actual length we want to use\n // this is because we only reallocate buffers when they grow, not when they shrink,\n // due to performance costs\n this.currentLength = 0;\n this.texture = getTexture(gl);\n this.framebuffer = getFramebuffer(gl, this.texture);\n this.transform = getTransform(gl, attribute, this.framebuffer);\n const bufferOpts = {\n byteLength: 0,\n usage: GL.DYNAMIC_COPY\n };\n this.buffers = [\n new Buffer(gl, bufferOpts), // previous\n new Buffer(gl, bufferOpts), // current\n new Buffer(gl, bufferOpts) // next\n ];\n }\n\n get inProgress() {\n return this.transition.inProgress;\n }\n\n // this is called when an attribute's values have changed and\n // we need to start animating towards the new values\n // this also correctly resizes / pads the transform's buffers\n // in case the attribute's buffer has changed in length or in\n // startIndices\n start(transitionSettings, numInstances) {\n const {gl, buffers, attribute} = this;\n const padBufferOpts = {\n numInstances,\n attribute,\n fromLength: this.currentLength,\n fromStartIndices: this.currentStartIndices,\n getData: transitionSettings.enter\n };\n\n for (const buffer of buffers) {\n padBuffer({buffer, ...padBufferOpts});\n }\n\n this.currentStartIndices = attribute.startIndices;\n this.currentLength = getAttributeBufferLength(attribute, numInstances);\n this.attributeInTransition.update({\n buffer: buffers[1],\n // Hack: Float64Array is required for double-precision attributes\n // to generate correct shader attributes\n value: attribute.value\n });\n\n // when an attribute changes values, a new transition is started. These\n // are properties that we have to store on this.transition but can change\n // when new transitions are started, so we have to keep them up-to-date.\n // this.transition.start() takes the latest settings and updates them.\n this.transition.start(transitionSettings);\n\n this.transform.update({\n elementCount: Math.floor(this.currentLength / attribute.size),\n sourceBuffers: {\n aTo: getSourceBufferAttribute(gl, attribute)\n }\n });\n }\n\n update() {\n const {buffers, transform, framebuffer, transition} = this;\n const updated = transition.update();\n if (!updated) {\n return false;\n }\n\n transform.update({\n sourceBuffers: {\n aPrev: buffers[0],\n aCur: buffers[1]\n },\n feedbackBuffers: {\n vNext: buffers[2]\n }\n });\n transform.run({\n framebuffer,\n discard: false,\n clearRenderTarget: true,\n uniforms: {\n stiffness: transition.settings.stiffness,\n damping: transition.settings.damping\n },\n parameters: {\n depthTest: false,\n blend: true,\n viewport: [0, 0, 1, 1],\n blendFunc: [GL.ONE, GL.ONE],\n blendEquation: [GL.MAX, GL.MAX]\n }\n });\n\n cycleBuffers(buffers);\n this.attributeInTransition.update({\n buffer: buffers[1],\n // Hack: Float64Array is required for double-precision attributes\n // to generate correct shader attributes\n value: this.attribute.value\n });\n\n const isTransitioning = readPixelsToArray(framebuffer)[0] > 0;\n\n if (!isTransitioning) {\n transition.end();\n }\n\n return true;\n }\n\n cancel() {\n this.transition.cancel();\n this.transform.delete();\n while (this.buffers.length) {\n this.buffers.pop().delete();\n }\n this.texture.delete();\n this.texture = null;\n this.framebuffer.delete();\n this.framebuffer = null;\n }\n}\n\nfunction getTransform(gl, attribute, framebuffer) {\n const attributeType = getAttributeTypeFromSize(attribute.size);\n return new Transform(gl, {\n framebuffer,\n vs: `\n#define SHADER_NAME spring-transition-vertex-shader\n\n#define EPSILON 0.00001\n\nuniform float stiffness;\nuniform float damping;\nattribute ATTRIBUTE_TYPE aPrev;\nattribute ATTRIBUTE_TYPE aCur;\nattribute ATTRIBUTE_TYPE aTo;\nvarying ATTRIBUTE_TYPE vNext;\nvarying float vIsTransitioningFlag;\n\nATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) {\n ATTRIBUTE_TYPE velocity = cur - prev;\n ATTRIBUTE_TYPE delta = dest - cur;\n ATTRIBUTE_TYPE spring = delta * stiffness;\n ATTRIBUTE_TYPE damper = velocity * -1.0 * damping;\n return spring + damper + velocity + cur;\n}\n\nvoid main(void) {\n bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON;\n vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0;\n\n vNext = getNextValue(aCur, aPrev, aTo);\n gl_Position = vec4(0, 0, 0, 1);\n gl_PointSize = 100.0;\n}\n`,\n fs: `\n#define SHADER_NAME spring-transition-is-transitioning-fragment-shader\n\nvarying float vIsTransitioningFlag;\n\nvoid main(void) {\n if (vIsTransitioningFlag == 0.0) {\n discard;\n }\n gl_FragColor = vec4(1.0);\n}`,\n defines: {\n ATTRIBUTE_TYPE: attributeType\n },\n varyings: ['vNext']\n });\n}\n\nfunction getTexture(gl) {\n return new Texture2D(gl, {\n data: new Uint8Array(4),\n format: GL.RGBA,\n type: GL.UNSIGNED_BYTE,\n border: 0,\n mipmaps: false,\n dataFormat: GL.RGBA,\n width: 1,\n height: 1\n });\n}\n\nfunction getFramebuffer(gl, texture) {\n return new Framebuffer(gl, {\n id: 'spring-transition-is-transitioning-framebuffer',\n width: 1,\n height: 1,\n attachments: {\n [GL.COLOR_ATTACHMENT0]: texture\n }\n });\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/* eslint-disable guard-for-in */\nimport Attribute from './attribute';\nimport log from '../../utils/log';\nimport debug from '../../debug';\n\nimport AttributeTransitionManager from './attribute-transition-manager';\n\nconst TRACE_INVALIDATE = 'attributeManager.invalidate';\nconst TRACE_UPDATE_START = 'attributeManager.updateStart';\nconst TRACE_UPDATE_END = 'attributeManager.updateEnd';\nconst TRACE_ATTRIBUTE_UPDATE_START = 'attribute.updateStart';\nconst TRACE_ATTRIBUTE_ALLOCATE = 'attribute.allocate';\nconst TRACE_ATTRIBUTE_UPDATE_END = 'attribute.updateEnd';\n\nexport default class AttributeManager {\n /**\n * @classdesc\n * Automated attribute generation and management. Suitable when a set of\n * vertex shader attributes are generated by iteration over a data array,\n * and updates to these attributes are needed either when the data itself\n * changes, or when other data relevant to the calculations change.\n *\n * - First the application registers descriptions of its dynamic vertex\n * attributes using AttributeManager.add().\n * - Then, when any change that affects attributes is detected by the\n * application, the app will call AttributeManager.invalidate().\n * - Finally before it renders, it calls AttributeManager.update() to\n * ensure that attributes are automatically rebuilt if anything has been\n * invalidated.\n *\n * The application provided update functions describe how attributes\n * should be updated from a data array and are expected to traverse\n * that data array (or iterable) and fill in the attribute's typed array.\n *\n * Note that the attribute manager intentionally does not do advanced\n * change detection, but instead makes it easy to build such detection\n * by offering the ability to \"invalidate\" each attribute separately.\n */\n constructor(gl, {id = 'attribute-manager', stats, timeline} = {}) {\n this.id = id;\n this.gl = gl;\n\n this.attributes = {};\n\n this.updateTriggers = {};\n this.accessors = {};\n this.needsRedraw = true;\n\n this.userData = {};\n this.stats = stats;\n\n this.attributeTransitionManager = new AttributeTransitionManager(gl, {\n id: `${id}-transitions`,\n timeline\n });\n\n // For debugging sanity, prevent uninitialized members\n Object.seal(this);\n }\n\n finalize() {\n for (const attributeName in this.attributes) {\n this.attributes[attributeName].delete();\n }\n this.attributeTransitionManager.finalize();\n }\n\n // Returns the redraw flag, optionally clearing it.\n // Redraw flag will be set if any attributes attributes changed since\n // flag was last cleared.\n //\n // @param {String} [clearRedrawFlags=false] - whether to clear the flag\n // @return {false|String} - reason a redraw is needed.\n getNeedsRedraw(opts = {clearRedrawFlags: false}) {\n const redraw = this.needsRedraw;\n this.needsRedraw = this.needsRedraw && !opts.clearRedrawFlags;\n return redraw && this.id;\n }\n\n // Sets the redraw flag.\n // @param {Boolean} redraw=true\n // @return {AttributeManager} - for chaining\n setNeedsRedraw(redraw = true) {\n this.needsRedraw = true;\n return this;\n }\n\n // Adds attributes\n add(attributes, updaters) {\n this._add(attributes, updaters);\n }\n\n // Adds attributes\n addInstanced(attributes, updaters) {\n this._add(attributes, updaters, {instanced: 1});\n }\n\n /**\n * Removes attributes\n * Takes an array of attribute names and delete them from\n * the attribute map if they exists\n *\n * @example\n * attributeManager.remove(['position']);\n *\n * @param {Object} attributeNameArray - attribute name array (see above)\n */\n remove(attributeNameArray) {\n for (let i = 0; i < attributeNameArray.length; i++) {\n const name = attributeNameArray[i];\n if (this.attributes[name] !== undefined) {\n this.attributes[name].delete();\n delete this.attributes[name];\n }\n }\n }\n\n // Marks an attribute for update\n invalidate(triggerName, dataRange) {\n const invalidatedAttributes = this._invalidateTrigger(triggerName, dataRange);\n // For performance tuning\n debug(TRACE_INVALIDATE, this, triggerName, invalidatedAttributes);\n }\n\n invalidateAll(dataRange) {\n for (const attributeName in this.attributes) {\n this.attributes[attributeName].setNeedsUpdate(attributeName, dataRange);\n }\n // For performance tuning\n debug(TRACE_INVALIDATE, this, 'all');\n }\n\n // Ensure all attribute buffers are updated from props or data.\n update({\n data,\n numInstances,\n startIndices = null,\n transitions,\n props = {},\n buffers = {},\n context = {}\n } = {}) {\n // keep track of whether some attributes are updated\n let updated = false;\n\n debug(TRACE_UPDATE_START, this);\n if (this.stats) {\n this.stats.get('Update Attributes').timeStart();\n }\n\n for (const attributeName in this.attributes) {\n const attribute = this.attributes[attributeName];\n const accessorName = attribute.settings.accessor;\n attribute.startIndices = startIndices;\n\n if (props[attributeName]) {\n log.removed(`props.${attributeName}`, `data.attributes.${attributeName}`)();\n }\n\n if (attribute.setExternalBuffer(buffers[attributeName])) {\n // Step 1: try update attribute directly from external buffers\n } else if (attribute.setBinaryValue(buffers[accessorName], data.startIndices)) {\n // Step 2: try set packed value from external typed array\n } else if (!buffers[accessorName] && attribute.setConstantValue(props[accessorName])) {\n // Step 3: try set constant value from props\n // Note: if buffers[accessorName] is supplied, ignore props[accessorName]\n // This may happen when setBinaryValue falls through to use the auto updater\n } else if (attribute.needsUpdate()) {\n // Step 4: update via updater callback\n updated = true;\n this._updateAttribute({\n attribute,\n numInstances,\n data,\n props,\n context\n });\n }\n\n this.needsRedraw |= attribute.needsRedraw();\n }\n\n if (updated) {\n // Only initiate alloc/update (and logging) if actually needed\n debug(TRACE_UPDATE_END, this, numInstances);\n }\n\n if (this.stats) {\n this.stats.get('Update Attributes').timeEnd();\n }\n\n this.attributeTransitionManager.update({\n attributes: this.attributes,\n numInstances,\n transitions\n });\n }\n\n // Update attribute transition to the current timestamp\n // Returns `true` if any transition is in progress\n updateTransition() {\n const {attributeTransitionManager} = this;\n const transitionUpdated = attributeTransitionManager.run();\n this.needsRedraw = this.needsRedraw || transitionUpdated;\n return transitionUpdated;\n }\n\n /**\n * Returns all attribute descriptors\n * Note: Format matches luma.gl Model/Program.setAttributes()\n * @return {Object} attributes - descriptors\n */\n getAttributes() {\n return this.attributes;\n }\n\n /**\n * Returns changed attribute descriptors\n * This indicates which WebGLBuffers need to be updated\n * @return {Object} attributes - descriptors\n */\n getChangedAttributes(opts = {clearChangedFlags: false}) {\n const {attributes, attributeTransitionManager} = this;\n\n const changedAttributes = {...attributeTransitionManager.getAttributes()};\n\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n if (attribute.needsRedraw(opts) && !attributeTransitionManager.hasAttribute(attributeName)) {\n changedAttributes[attributeName] = attribute;\n }\n }\n\n return changedAttributes;\n }\n\n // Returns shader attributes\n getShaderAttributes(attributes, excludeAttributes = {}) {\n if (!attributes) {\n attributes = this.getAttributes();\n }\n const shaderAttributes = {};\n for (const attributeName in attributes) {\n if (!excludeAttributes[attributeName]) {\n Object.assign(shaderAttributes, attributes[attributeName].getShaderAttributes());\n }\n }\n return shaderAttributes;\n }\n\n // PROTECTED METHODS - Only to be used by collaborating classes, not by apps\n\n // Returns object containing all accessors as keys, with non-null values\n // @return {Object} - accessors object\n getAccessors() {\n return this.updateTriggers;\n }\n\n // PRIVATE METHODS\n\n // Used to register an attribute\n _add(attributes, updaters, extraProps = {}) {\n if (updaters) {\n log.warn('AttributeManager.add({updaters}) - updater map no longer supported')();\n }\n\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n\n // Initialize the attribute descriptor, with WebGL and metadata fields\n this.attributes[attributeName] = this._createAttribute(attributeName, attribute, extraProps);\n }\n\n this._mapUpdateTriggersToAttributes();\n }\n /* eslint-enable max-statements */\n\n _createAttribute(name, attribute, extraProps) {\n // For expected default values see:\n // https://github.com/visgl/luma.gl/blob/1affe21352e289eeaccee2a876865138858a765c/modules/webgl/src/classes/accessor.js#L5-L13\n // and https://deck.gl/docs/api-reference/core/attribute-manager#add\n const props = {\n ...attribute,\n id: name,\n isIndexed: attribute.isIndexed || attribute.elements || false,\n // Luma fields\n constant: attribute.constant || false,\n size: (attribute.elements && 1) || attribute.size || 1,\n value: attribute.value || null,\n divisor: attribute.instanced || extraProps.instanced ? 1 : attribute.divisor || 0\n };\n\n return new Attribute(this.gl, props);\n }\n\n // build updateTrigger name to attribute name mapping\n _mapUpdateTriggersToAttributes() {\n const triggers = {};\n\n for (const attributeName in this.attributes) {\n const attribute = this.attributes[attributeName];\n attribute.getUpdateTriggers().forEach(triggerName => {\n if (!triggers[triggerName]) {\n triggers[triggerName] = [];\n }\n triggers[triggerName].push(attributeName);\n });\n }\n\n this.updateTriggers = triggers;\n }\n\n _invalidateTrigger(triggerName, dataRange) {\n const {attributes, updateTriggers} = this;\n const invalidatedAttributes = updateTriggers[triggerName];\n\n if (invalidatedAttributes) {\n invalidatedAttributes.forEach(name => {\n const attribute = attributes[name];\n if (attribute) {\n attribute.setNeedsUpdate(attribute.id, dataRange);\n }\n });\n }\n return invalidatedAttributes;\n }\n\n _updateAttribute(opts) {\n const {attribute, numInstances} = opts;\n debug(TRACE_ATTRIBUTE_UPDATE_START, attribute);\n\n if (attribute.constant) {\n // The attribute is flagged as constant outside of an update cycle\n // Skip allocation and updater call\n attribute.setConstantValue(attribute.value);\n return;\n }\n\n if (attribute.allocate(numInstances)) {\n debug(TRACE_ATTRIBUTE_ALLOCATE, attribute, numInstances);\n }\n\n // Calls update on any buffers that need update\n const updated = attribute.updateBuffer(opts);\n if (updated) {\n this.needsRedraw = true;\n debug(TRACE_ATTRIBUTE_UPDATE_END, attribute, numInstances);\n }\n }\n}\n","/* eslint-disable max-statements, max-params, complexity, max-depth */\n// TODO merge with icon-layer/icon-manager\nimport {log} from '@deck.gl/core';\n\nconst MISSING_CHAR_WIDTH = 32;\nconst SINGLE_LINE = [];\n\nexport function nextPowOfTwo(number) {\n return Math.pow(2, Math.ceil(Math.log2(number)));\n}\n\n/**\n * Generate character mapping table or update from an existing mapping table\n * @param characterSet {Array|Set} new characters\n * @param getFontWidth {Function} function to get width of each character\n * @param fontHeight {Number} height of font\n * @param buffer {Number} buffer surround each character\n * @param maxCanvasWidth {Number} max width of font atlas\n * @param mapping {Object} old mapping table\n * @param xOffset {Number} x position of last character in old mapping table\n * @param yOffset {Number} y position of last character in old mapping table\n * @returns {{\n * mapping: Object,\n * xOffset: Number, x position of last character\n * yOffset: Number, y position of last character in old mapping table\n * canvasHeight: Number, height of the font atlas canvas, power of 2\n * }}\n */\nexport function buildMapping({\n characterSet,\n getFontWidth,\n fontHeight,\n buffer,\n maxCanvasWidth,\n mapping = {},\n xOffset = 0,\n yOffset = 0\n}) {\n let row = 0;\n // continue from x position of last character in the old mapping\n let x = xOffset;\n\n let i = 0;\n for (const char of characterSet) {\n if (!mapping[char]) {\n // measure texts\n // TODO - use Advanced text metrics when they are adopted:\n // https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics\n const width = getFontWidth(char, i++);\n\n if (x + width + buffer * 2 > maxCanvasWidth) {\n x = 0;\n row++;\n }\n mapping[char] = {\n x: x + buffer,\n y: yOffset + row * (fontHeight + buffer * 2) + buffer,\n width,\n height: fontHeight\n };\n x += width + buffer * 2;\n }\n }\n\n const rowHeight = fontHeight + buffer * 2;\n\n return {\n mapping,\n xOffset: x,\n yOffset: yOffset + row * rowHeight,\n canvasHeight: nextPowOfTwo(yOffset + (row + 1) * rowHeight)\n };\n}\n\nfunction getTextWidth(text, startIndex, endIndex, mapping) {\n let width = 0;\n for (let i = startIndex; i < endIndex; i++) {\n const character = text[i];\n let frameWidth = null;\n const frame = mapping && mapping[character];\n if (frame) {\n frameWidth = frame.width;\n }\n\n width += frameWidth;\n }\n\n return width;\n}\n\nfunction breakAll(text, startIndex, endIndex, maxWidth, iconMapping, target) {\n let rowStartCharIndex = startIndex;\n let rowOffsetLeft = 0;\n\n for (let i = startIndex; i < endIndex; i++) {\n // 2. figure out where to break lines\n const textWidth = getTextWidth(text, i, i + 1, iconMapping);\n if (rowOffsetLeft + textWidth > maxWidth) {\n if (rowStartCharIndex < i) {\n target.push(i);\n }\n rowStartCharIndex = i;\n rowOffsetLeft = 0;\n }\n rowOffsetLeft += textWidth;\n }\n\n return rowOffsetLeft;\n}\n\nfunction breakWord(text, startIndex, endIndex, maxWidth, iconMapping, target) {\n let rowStartCharIndex = startIndex;\n let groupStartCharIndex = startIndex;\n let groupEndCharIndex = startIndex;\n let rowOffsetLeft = 0;\n\n for (let i = startIndex; i < endIndex; i++) {\n // 1. break text into word groups\n // - if current char is white space\n // - else if next char is white space\n // - else if reach last char\n if (text[i] === ' ') {\n groupEndCharIndex = i + 1;\n } else if (text[i + 1] === ' ' || i + 1 === endIndex) {\n groupEndCharIndex = i + 1;\n }\n\n if (groupEndCharIndex > groupStartCharIndex) {\n // 2. break text into next row at maxWidth\n let groupWidth = getTextWidth(text, groupStartCharIndex, groupEndCharIndex, iconMapping);\n if (rowOffsetLeft + groupWidth > maxWidth) {\n if (rowStartCharIndex < groupStartCharIndex) {\n target.push(groupStartCharIndex);\n rowStartCharIndex = groupStartCharIndex;\n rowOffsetLeft = 0;\n }\n\n // if a single text group is bigger than maxWidth, then `break-all`\n if (groupWidth > maxWidth) {\n groupWidth = breakAll(\n text,\n groupStartCharIndex,\n groupEndCharIndex,\n maxWidth,\n iconMapping,\n target\n );\n // move reference to last row\n rowStartCharIndex = target[target.length - 1];\n }\n }\n groupStartCharIndex = groupEndCharIndex;\n rowOffsetLeft += groupWidth;\n }\n }\n\n return rowOffsetLeft;\n}\n\n// Returns a list of indices where line breaks should be inserted\nexport function autoWrapping(text, wordBreak, maxWidth, iconMapping, startIndex = 0, endIndex) {\n if (endIndex === undefined) {\n endIndex = text.length;\n }\n const result = [];\n if (wordBreak === 'break-all') {\n breakAll(text, startIndex, endIndex, maxWidth, iconMapping, result);\n } else {\n breakWord(text, startIndex, endIndex, maxWidth, iconMapping, result);\n }\n return result;\n}\n\nfunction transformRow(line, startIndex, endIndex, iconMapping, leftOffsets, rowSize) {\n let x = 0;\n let rowHeight = 0;\n\n for (let i = startIndex; i < endIndex; i++) {\n const character = line[i];\n const frame = iconMapping[character];\n if (frame) {\n if (!rowHeight) {\n // frame.height should be a constant\n rowHeight = frame.height;\n }\n leftOffsets[i] = x + frame.width / 2;\n x += frame.width;\n } else {\n log.warn(`Missing character: ${character} (${character.codePointAt(0)})`)();\n leftOffsets[i] = x;\n x += MISSING_CHAR_WIDTH;\n }\n }\n\n rowSize[0] = x;\n rowSize[1] = rowHeight;\n}\n\n/**\n * Transform a text paragraph to an array of characters, each character contains\n * @param paragraph: {String}\n * @param iconMapping {Object} character mapping table for retrieving a character from font atlas\n * @param lineHeight {Number} css line-height\n * @param wordBreak {String} css word-break option\n * @param maxWidth {number} css max-width\n * @param transformedData {Array} output transformed data array, each datum contains\n * - text: character\n * - index: character index in the paragraph\n * - x: x offset in the row,\n * - y: y offset in the paragraph\n * - size: [width, height] size of the paragraph\n * - rowSize: [rowWidth, rowHeight] size of the row\n * - len: length of the paragraph\n */\nexport function transformParagraph(paragraph, lineHeight, wordBreak, maxWidth, iconMapping) {\n // Break into an array of characters\n // When dealing with double-length unicode characters, `str.length` or `str[i]` do not work\n paragraph = Array.from(paragraph);\n const numCharacters = paragraph.length;\n const x = new Array(numCharacters);\n const y = new Array(numCharacters);\n const rowWidth = new Array(numCharacters);\n const autoWrappingEnabled =\n (wordBreak === 'break-word' || wordBreak === 'break-all') && isFinite(maxWidth) && maxWidth > 0;\n\n // maxWidth and height of the paragraph\n const size = [0, 0];\n const rowSize = [];\n let rowOffsetTop = 0;\n let lineStartIndex = 0;\n let lineEndIndex = 0;\n\n for (let i = 0; i <= numCharacters; i++) {\n const char = paragraph[i];\n if (char === '\\n' || i === numCharacters) {\n lineEndIndex = i;\n }\n\n if (lineEndIndex > lineStartIndex) {\n const rows = autoWrappingEnabled\n ? autoWrapping(paragraph, wordBreak, maxWidth, iconMapping, lineStartIndex, lineEndIndex)\n : SINGLE_LINE;\n\n for (let rowIndex = 0; rowIndex <= rows.length; rowIndex++) {\n const rowStart = rowIndex === 0 ? lineStartIndex : rows[rowIndex - 1];\n const rowEnd = rowIndex < rows.length ? rows[rowIndex] : lineEndIndex;\n transformRow(paragraph, rowStart, rowEnd, iconMapping, x, rowSize);\n for (let j = rowStart; j < rowEnd; j++) {\n y[j] = rowOffsetTop + rowSize[1] / 2;\n rowWidth[j] = rowSize[0];\n }\n\n rowOffsetTop = rowOffsetTop + rowSize[1] * lineHeight;\n size[0] = Math.max(size[0], rowSize[0]);\n }\n lineStartIndex = lineEndIndex;\n }\n\n if (char === '\\n') {\n // Make sure result.length matches paragraph.length\n x[lineStartIndex] = 0;\n y[lineStartIndex] = 0;\n rowWidth[lineStartIndex] = 0;\n lineStartIndex++;\n }\n }\n\n // last row\n size[1] = rowOffsetTop;\n return {x, y, rowWidth, size};\n}\n\nexport function getTextFromBuffer({value, length, stride, offset, startIndices, characterSet}) {\n const bytesPerElement = value.BYTES_PER_ELEMENT;\n const elementStride = stride ? stride / bytesPerElement : 1;\n const elementOffset = offset ? offset / bytesPerElement : 0;\n const characterCount =\n startIndices[length] || Math.ceil((value.length - elementOffset) / elementStride);\n const autoCharacterSet = characterSet && new Set();\n\n const texts = new Array(length);\n\n let codes = value;\n if (elementStride > 1 || elementOffset > 0) {\n codes = new value.constructor(characterCount);\n for (let i = 0; i < characterCount; i++) {\n codes[i] = value[i * elementStride + elementOffset];\n }\n }\n\n for (let index = 0; index < length; index++) {\n const startIndex = startIndices[index];\n const endIndex = startIndices[index + 1] || characterCount;\n const codesAtIndex = codes.subarray(startIndex, endIndex);\n texts[index] = String.fromCodePoint.apply(null, codesAtIndex);\n if (autoCharacterSet) {\n codesAtIndex.forEach(autoCharacterSet.add, autoCharacterSet);\n }\n }\n\n if (autoCharacterSet) {\n for (const charCode of autoCharacterSet) {\n characterSet.add(String.fromCodePoint(charCode));\n }\n }\n\n return {texts, characterCount};\n}\n","/**\n * LRU Cache class with limit\n *\n * Update order for each get/set operation\n * Delete oldest when reach given limit\n */\n\nexport default class LRUCache {\n constructor(limit = 5) {\n this.limit = limit;\n\n this.clear();\n }\n\n clear() {\n this._cache = {};\n // access/update order, first item is oldest, last item is newest\n this._order = [];\n }\n\n get(key) {\n const value = this._cache[key];\n if (value) {\n // update order\n this._deleteOrder(key);\n this._appendOrder(key);\n }\n return value;\n }\n\n set(key, value) {\n if (!this._cache[key]) {\n // if reach limit, delete the oldest\n if (Object.keys(this._cache).length === this.limit) {\n this.delete(this._order[0]);\n }\n\n this._cache[key] = value;\n this._appendOrder(key);\n } else {\n // if found in cache, delete the old one, insert new one to the first of list\n this.delete(key);\n\n this._cache[key] = value;\n this._appendOrder(key);\n }\n }\n\n delete(key) {\n const value = this._cache[key];\n if (value) {\n this._deleteCache(key);\n this._deleteOrder(key);\n }\n }\n\n _deleteCache(key) {\n delete this._cache[key];\n }\n\n _deleteOrder(key) {\n const index = this._order.findIndex(o => o === key);\n if (index >= 0) {\n this._order.splice(index, 1);\n }\n }\n\n _appendOrder(key) {\n this._order.push(key);\n }\n}\n","/* global document */\nimport TinySDF from '@mapbox/tiny-sdf';\n\nimport {buildMapping} from './utils';\nimport LRUCache from './lru-cache';\n\nfunction getDefaultCharacterSet() {\n const charSet = [];\n for (let i = 32; i < 128; i++) {\n charSet.push(String.fromCharCode(i));\n }\n return charSet;\n}\n\nexport const DEFAULT_CHAR_SET = getDefaultCharacterSet();\nexport const DEFAULT_FONT_FAMILY = 'Monaco, monospace';\nexport const DEFAULT_FONT_WEIGHT = 'normal';\nexport const DEFAULT_FONT_SIZE = 64;\nexport const DEFAULT_BUFFER = 4;\nexport const DEFAULT_CUTOFF = 0.25;\nexport const DEFAULT_RADIUS = 12;\n\nconst MAX_CANVAS_WIDTH = 1024;\n\nconst BASELINE_SCALE = 0.9;\nconst HEIGHT_SCALE = 1.2;\n\n// only preserve latest three fontAtlas\nconst CACHE_LIMIT = 3;\n\n/**\n * [key]: {\n * xOffset, // x position of last character in mapping\n * yOffset, // y position of last character in mapping\n * mapping, // x, y coordinate of each character in shared `fontAtlas`\n * data, // canvas\n * width. // canvas.width,\n * height, // canvas.height\n * }\n *\n */\nconst cache = new LRUCache(CACHE_LIMIT);\n\nconst VALID_PROPS = [\n 'fontFamily',\n 'fontWeight',\n 'characterSet',\n 'fontSize',\n 'sdf',\n 'buffer',\n 'cutoff',\n 'radius'\n];\n\n/**\n * get all the chars not in cache\n * @param key cache key\n * @param characterSet (Array|Set)\n * @returns {Array} chars not in cache\n */\nfunction getNewChars(key, characterSet) {\n const cachedFontAtlas = cache.get(key);\n if (!cachedFontAtlas) {\n return characterSet;\n }\n\n const newChars = [];\n const cachedMapping = cachedFontAtlas.mapping;\n let cachedCharSet = Object.keys(cachedMapping);\n cachedCharSet = new Set(cachedCharSet);\n\n let charSet = characterSet;\n if (charSet instanceof Array) {\n charSet = new Set(charSet);\n }\n\n charSet.forEach(char => {\n if (!cachedCharSet.has(char)) {\n newChars.push(char);\n }\n });\n\n return newChars;\n}\n\nfunction populateAlphaChannel(alphaChannel, imageData) {\n // populate distance value from tinySDF to image alpha channel\n for (let i = 0; i < alphaChannel.length; i++) {\n imageData.data[4 * i + 3] = alphaChannel[i];\n }\n}\n\nfunction setTextStyle(ctx, fontFamily, fontSize, fontWeight) {\n ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;\n ctx.fillStyle = '#000';\n ctx.textBaseline = 'baseline';\n ctx.textAlign = 'left';\n}\n\nexport default class FontAtlasManager {\n constructor() {\n // font settings\n this.props = {\n fontFamily: DEFAULT_FONT_FAMILY,\n fontWeight: DEFAULT_FONT_WEIGHT,\n characterSet: DEFAULT_CHAR_SET,\n fontSize: DEFAULT_FONT_SIZE,\n buffer: DEFAULT_BUFFER,\n // sdf only props\n // https://github.com/mapbox/tiny-sdf\n sdf: false,\n cutoff: DEFAULT_CUTOFF,\n radius: DEFAULT_RADIUS\n };\n\n // key is used for caching generated fontAtlas\n this._key = null;\n this._atlas = null;\n }\n\n get texture() {\n return this._atlas;\n }\n\n get mapping() {\n return this._atlas && this._atlas.mapping;\n }\n\n get scale() {\n return HEIGHT_SCALE;\n }\n\n setProps(props = {}) {\n VALID_PROPS.forEach(prop => {\n if (prop in props) {\n this.props[prop] = props[prop];\n }\n });\n\n // update cache key\n const oldKey = this._key;\n this._key = this._getKey();\n\n const charSet = getNewChars(this._key, this.props.characterSet);\n const cachedFontAtlas = cache.get(this._key);\n\n // if a fontAtlas associated with the new settings is cached and\n // there are no new chars\n if (cachedFontAtlas && charSet.length === 0) {\n // update texture with cached fontAtlas\n if (this._key !== oldKey) {\n this._atlas = cachedFontAtlas;\n }\n return;\n }\n\n // update fontAtlas with new settings\n const fontAtlas = this._generateFontAtlas(this._key, charSet, cachedFontAtlas);\n this._atlas = fontAtlas;\n\n // update cache\n cache.set(this._key, fontAtlas);\n }\n\n _generateFontAtlas(key, characterSet, cachedFontAtlas) {\n const {fontFamily, fontWeight, fontSize, buffer, sdf, radius, cutoff} = this.props;\n let canvas = cachedFontAtlas && cachedFontAtlas.data;\n if (!canvas) {\n canvas = document.createElement('canvas');\n canvas.width = MAX_CANVAS_WIDTH;\n }\n const ctx = canvas.getContext('2d');\n\n setTextStyle(ctx, fontFamily, fontSize, fontWeight);\n\n // 1. build mapping\n const {mapping, canvasHeight, xOffset, yOffset} = buildMapping({\n getFontWidth: char => ctx.measureText(char).width,\n fontHeight: fontSize * HEIGHT_SCALE,\n buffer,\n characterSet,\n maxCanvasWidth: MAX_CANVAS_WIDTH,\n ...(cachedFontAtlas && {\n mapping: cachedFontAtlas.mapping,\n xOffset: cachedFontAtlas.xOffset,\n yOffset: cachedFontAtlas.yOffset\n })\n });\n\n // 2. update canvas\n // copy old canvas data to new canvas only when height changed\n if (canvas.height !== canvasHeight) {\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n canvas.height = canvasHeight;\n ctx.putImageData(imageData, 0, 0);\n }\n setTextStyle(ctx, fontFamily, fontSize, fontWeight);\n\n // 3. layout characters\n if (sdf) {\n const tinySDF = new TinySDF(fontSize, buffer, radius, cutoff, fontFamily, fontWeight);\n // used to store distance values from tinySDF\n // tinySDF.size equals `fontSize + buffer * 2`\n const imageData = ctx.getImageData(0, 0, tinySDF.size, tinySDF.size);\n\n for (const char of characterSet) {\n populateAlphaChannel(tinySDF.draw(char), imageData);\n ctx.putImageData(imageData, mapping[char].x - buffer, mapping[char].y + buffer);\n }\n } else {\n for (const char of characterSet) {\n ctx.fillText(char, mapping[char].x, mapping[char].y + fontSize * BASELINE_SCALE);\n }\n }\n\n return {\n xOffset,\n yOffset,\n mapping,\n data: canvas,\n width: canvas.width,\n height: canvas.height\n };\n }\n\n _getKey() {\n const {fontFamily, fontWeight, fontSize, buffer, sdf, radius, cutoff} = this.props;\n if (sdf) {\n return `${fontFamily} ${fontWeight} ${fontSize} ${buffer} ${radius} ${cutoff}`;\n }\n return `${fontFamily} ${fontWeight} ${fontSize} ${buffer}`;\n }\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {CompositeLayer, createIterable} from '@deck.gl/core';\nimport MultiIconLayer from './multi-icon-layer/multi-icon-layer';\nimport FontAtlasManager, {\n DEFAULT_CHAR_SET,\n DEFAULT_FONT_FAMILY,\n DEFAULT_FONT_WEIGHT,\n DEFAULT_FONT_SIZE,\n DEFAULT_BUFFER,\n DEFAULT_RADIUS,\n DEFAULT_CUTOFF\n} from './font-atlas-manager';\nimport {transformParagraph, getTextFromBuffer} from './utils';\n\nimport TextBackgroundLayer from './text-background-layer/text-background-layer';\n\nconst DEFAULT_FONT_SETTINGS = {\n fontSize: DEFAULT_FONT_SIZE,\n buffer: DEFAULT_BUFFER,\n sdf: false,\n radius: DEFAULT_RADIUS,\n cutoff: DEFAULT_CUTOFF,\n smoothing: 0.1\n};\n\nconst TEXT_ANCHOR = {\n start: 1,\n middle: 0,\n end: -1\n};\n\nconst ALIGNMENT_BASELINE = {\n top: 1,\n center: 0,\n bottom: -1\n};\n\nconst DEFAULT_COLOR = [0, 0, 0, 255];\n\nconst DEFAULT_LINE_HEIGHT = 1.0;\n\nconst FONT_SETTINGS_PROPS = ['fontSize', 'buffer', 'sdf', 'radius', 'cutoff'];\n\nconst defaultProps = {\n billboard: true,\n sizeScale: 1,\n sizeUnits: 'pixels',\n sizeMinPixels: 0,\n sizeMaxPixels: Number.MAX_SAFE_INTEGER,\n\n background: false,\n getBackgroundColor: {type: 'accessor', value: [255, 255, 255, 255]},\n getBorderColor: {type: 'accessor', value: DEFAULT_COLOR},\n getBorderWidth: {type: 'accessor', value: 0},\n backgroundPadding: {type: 'array', value: [0, 0, 0, 0]},\n\n characterSet: {type: 'object', value: DEFAULT_CHAR_SET},\n fontFamily: DEFAULT_FONT_FAMILY,\n fontWeight: DEFAULT_FONT_WEIGHT,\n lineHeight: DEFAULT_LINE_HEIGHT,\n outlineWidth: {type: 'number', value: 0, min: 0},\n outlineColor: {type: 'color', value: DEFAULT_COLOR},\n fontSettings: {},\n\n // auto wrapping options\n wordBreak: 'break-word',\n maxWidth: {type: 'number', value: -1},\n\n getText: {type: 'accessor', value: x => x.text},\n getPosition: {type: 'accessor', value: x => x.position},\n getColor: {type: 'accessor', value: DEFAULT_COLOR},\n getSize: {type: 'accessor', value: 32},\n getAngle: {type: 'accessor', value: 0},\n getTextAnchor: {type: 'accessor', value: 'middle'},\n getAlignmentBaseline: {type: 'accessor', value: 'center'},\n getPixelOffset: {type: 'accessor', value: [0, 0]},\n\n // deprecated\n backgroundColor: {deprecatedFor: ['background', 'getBackgroundColor']}\n};\n\nexport default class TextLayer extends CompositeLayer {\n initializeState() {\n this.state = {\n styleVersion: 0,\n fontAtlasManager: new FontAtlasManager()\n };\n }\n\n // eslint-disable-next-line complexity\n updateState({props, oldProps, changeFlags}) {\n const textChanged =\n changeFlags.dataChanged ||\n (changeFlags.updateTriggersChanged &&\n (changeFlags.updateTriggersChanged.all || changeFlags.updateTriggersChanged.getText));\n const oldCharacterSet = this.state.characterSet;\n\n if (textChanged) {\n this._updateText();\n }\n\n const fontChanged =\n oldCharacterSet !== this.state.characterSet || this._fontChanged(oldProps, props);\n\n if (fontChanged) {\n this._updateFontAtlas(oldProps, props);\n }\n\n const styleChanged =\n fontChanged ||\n props.lineHeight !== oldProps.lineHeight ||\n props.wordBreak !== oldProps.wordBreak ||\n props.maxWidth !== oldProps.maxWidth;\n\n if (styleChanged) {\n this.setState({\n styleVersion: this.state.styleVersion + 1\n });\n }\n }\n\n getPickingInfo({info}) {\n // because `TextLayer` assign the same pickingInfoIndex for one text label,\n // here info.index refers the index of text label in props.data\n info.object = info.index >= 0 ? this.props.data[info.index] : null;\n return info;\n }\n\n _updateFontAtlas(oldProps, props) {\n const {fontSettings, fontFamily, fontWeight} = props;\n\n // generate test characterSet\n const {fontAtlasManager, characterSet} = this.state;\n fontAtlasManager.setProps({\n ...DEFAULT_FONT_SETTINGS,\n ...fontSettings,\n characterSet,\n fontFamily,\n fontWeight\n });\n }\n\n _fontChanged(oldProps, props) {\n if (oldProps.fontFamily !== props.fontFamily || oldProps.fontWeight !== props.fontWeight) {\n return true;\n }\n\n if (oldProps.fontSettings === props.fontSettings) {\n return false;\n }\n\n const oldFontSettings = oldProps.fontSettings || {};\n const fontSettings = props.fontSettings || {};\n\n return FONT_SETTINGS_PROPS.some(prop => oldFontSettings[prop] !== fontSettings[prop]);\n }\n\n // Text strings are variable width objects\n // Count characters and start offsets\n _updateText() {\n const {data, characterSet} = this.props;\n const textBuffer = data.attributes && data.attributes.getText;\n let {getText} = this.props;\n let {startIndices} = data;\n let numInstances;\n\n const autoCharacterSet = characterSet === 'auto' && new Set();\n\n if (textBuffer && startIndices) {\n const {texts, characterCount} = getTextFromBuffer({\n ...(ArrayBuffer.isView(textBuffer) ? {value: textBuffer} : textBuffer),\n length: data.length,\n startIndices,\n characterSet: autoCharacterSet\n });\n numInstances = characterCount;\n getText = (_, {index}) => texts[index];\n } else {\n const {iterable, objectInfo} = createIterable(data);\n startIndices = [0];\n numInstances = 0;\n\n for (const object of iterable) {\n objectInfo.index++;\n // Break into an array of characters\n // When dealing with double-length unicode characters, `str.length` or `str[i]` do not work\n const text = Array.from(getText(object, objectInfo) || '');\n if (autoCharacterSet) {\n text.forEach(autoCharacterSet.add, autoCharacterSet);\n }\n numInstances += text.length;\n startIndices.push(numInstances);\n }\n }\n\n this.setState({\n getText,\n startIndices,\n numInstances,\n characterSet: autoCharacterSet || characterSet\n });\n }\n\n // Returns the x, y offsets of each character in a text string\n getBoundingRect(object, objectInfo) {\n const iconMapping = this.state.fontAtlasManager.mapping;\n const {getText} = this.state;\n const {wordBreak, maxWidth, lineHeight, getTextAnchor, getAlignmentBaseline} = this.props;\n\n const paragraph = getText(object, objectInfo) || '';\n const {\n size: [width, height]\n } = transformParagraph(paragraph, lineHeight, wordBreak, maxWidth, iconMapping);\n const anchorX =\n TEXT_ANCHOR[\n typeof getTextAnchor === 'function' ? getTextAnchor(object, objectInfo) : getTextAnchor\n ];\n const anchorY =\n ALIGNMENT_BASELINE[\n typeof getAlignmentBaseline === 'function'\n ? getAlignmentBaseline(object, objectInfo)\n : getAlignmentBaseline\n ];\n\n return [((anchorX - 1) * width) / 2, ((anchorY - 1) * height) / 2, width, height];\n }\n\n // Returns the x, y, w, h of each text object\n getIconOffsets(object, objectInfo) {\n const iconMapping = this.state.fontAtlasManager.mapping;\n const {getText} = this.state;\n const {wordBreak, maxWidth, lineHeight, getTextAnchor, getAlignmentBaseline} = this.props;\n\n const paragraph = getText(object, objectInfo) || '';\n const {\n x,\n y,\n rowWidth,\n size: [width, height]\n } = transformParagraph(paragraph, lineHeight, wordBreak, maxWidth, iconMapping);\n const anchorX =\n TEXT_ANCHOR[\n typeof getTextAnchor === 'function' ? getTextAnchor(object, objectInfo) : getTextAnchor\n ];\n const anchorY =\n ALIGNMENT_BASELINE[\n typeof getAlignmentBaseline === 'function'\n ? getAlignmentBaseline(object, objectInfo)\n : getAlignmentBaseline\n ];\n\n const numCharacters = x.length;\n const offsets = new Array(numCharacters * 2);\n let index = 0;\n\n for (let i = 0; i < numCharacters; i++) {\n // For a multi-line object, offset in x-direction needs consider\n // the row offset in the paragraph and the object offset in the row\n const rowOffset = ((1 - anchorX) * (width - rowWidth[i])) / 2;\n offsets[index++] = ((anchorX - 1) * width) / 2 + rowOffset + x[i];\n offsets[index++] = ((anchorY - 1) * height) / 2 + y[i];\n }\n return offsets;\n }\n\n renderLayers() {\n const {\n startIndices,\n numInstances,\n getText,\n fontAtlasManager: {scale, texture, mapping},\n styleVersion\n } = this.state;\n\n const {\n data,\n _dataDiff,\n getPosition,\n getColor,\n getSize,\n getAngle,\n getPixelOffset,\n getBackgroundColor,\n getBorderColor,\n getBorderWidth,\n backgroundPadding,\n background,\n billboard,\n fontSettings,\n outlineWidth,\n outlineColor,\n sizeScale,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n transitions,\n updateTriggers\n } = this.props;\n\n const CharactersLayerClass = this.getSubLayerClass('characters', MultiIconLayer);\n const BackgroundLayerClass = this.getSubLayerClass('background', TextBackgroundLayer);\n\n return [\n background &&\n new BackgroundLayerClass(\n {\n // background props\n getFillColor: getBackgroundColor,\n getLineColor: getBorderColor,\n getLineWidth: getBorderWidth,\n padding: backgroundPadding,\n\n // props shared with characters layer\n getPosition,\n getSize,\n getAngle,\n getPixelOffset,\n billboard,\n sizeScale: sizeScale / this.state.fontAtlasManager.props.fontSize,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n\n transitions: transitions && {\n getPosition: transitions.getPosition,\n getAngle: transitions.getAngle,\n getSize: transitions.getSize,\n getFillColor: transitions.getBackgroundColor,\n getLineColor: transitions.getBorderColor,\n getLineWidth: transitions.getBorderWidth,\n getPixelOffset: transitions.getPixelOffset\n }\n },\n this.getSubLayerProps({\n id: 'background',\n updateTriggers: {\n getPosition: updateTriggers.getPosition,\n getAngle: updateTriggers.getAngle,\n getSize: updateTriggers.getSize,\n getFillColor: updateTriggers.getBackgroundColor,\n getLineColor: updateTriggers.getBorderColor,\n getLineWidth: updateTriggers.getBorderWidth,\n getPixelOffset: updateTriggers.getPixelOffset,\n getBoundingRect: {\n getText: updateTriggers.getText,\n getTextAnchor: updateTriggers.getTextAnchor,\n getAlignmentBaseline: updateTriggers.getAlignmentBaseline,\n styleVersion\n }\n }\n }),\n {\n data: data.attributes\n ? {length: data.length, attributes: data.attributes.background || {}}\n : data,\n _dataDiff,\n // Maintain the same background behavior as <=8.3. Remove in v9?\n autoHighlight: false,\n getBoundingRect: this.getBoundingRect.bind(this)\n }\n ),\n new CharactersLayerClass(\n {\n sdf: fontSettings.sdf,\n smoothing: Number.isFinite(fontSettings.smoothing)\n ? fontSettings.smoothing\n : DEFAULT_FONT_SETTINGS.smoothing,\n outlineWidth,\n outlineColor,\n iconAtlas: texture,\n iconMapping: mapping,\n\n getPosition,\n getColor,\n getSize,\n getAngle,\n getPixelOffset,\n\n billboard,\n sizeScale: sizeScale * scale,\n sizeUnits,\n sizeMinPixels: sizeMinPixels * scale,\n sizeMaxPixels: sizeMaxPixels * scale,\n\n transitions: transitions && {\n getPosition: transitions.getPosition,\n getAngle: transitions.getAngle,\n getColor: transitions.getColor,\n getSize: transitions.getSize,\n getPixelOffset: transitions.getPixelOffset\n }\n },\n this.getSubLayerProps({\n id: 'characters',\n updateTriggers: {\n getIcon: updateTriggers.getText,\n getPosition: updateTriggers.getPosition,\n getAngle: updateTriggers.getAngle,\n getColor: updateTriggers.getColor,\n getSize: updateTriggers.getSize,\n getPixelOffset: updateTriggers.getPixelOffset,\n getIconOffsets: {\n getText: updateTriggers.getText,\n getTextAnchor: updateTriggers.getTextAnchor,\n getAlignmentBaseline: updateTriggers.getAlignmentBaseline,\n styleVersion\n }\n }\n }),\n {\n data,\n _dataDiff,\n startIndices,\n numInstances,\n getIconOffsets: this.getIconOffsets.bind(this),\n getIcon: getText\n }\n )\n ];\n }\n}\n\nTextLayer.layerName = 'TextLayer';\nTextLayer.defaultProps = defaultProps;\n","import {log} from '@deck.gl/core';\nimport {Geometry, uid} from '@luma.gl/core';\nimport {modifyPolygonWindingDirection, WINDING} from '@math.gl/polygon';\n\nexport default class ColumnGeometry extends Geometry {\n constructor(props = {}) {\n const {id = uid('column-geometry')} = props;\n const {indices, attributes} = tesselateColumn(props);\n super({\n ...props,\n id,\n indices,\n attributes\n });\n }\n}\n\n/* eslint-disable max-statements, complexity */\nfunction tesselateColumn(props) {\n const {radius, height = 1, nradial = 10} = props;\n let {vertices} = props;\n\n if (vertices) {\n log.assert(vertices.length >= nradial); // `vertices` must contain at least `diskResolution` points\n vertices = vertices.flatMap(v => [v[0], v[1]]);\n modifyPolygonWindingDirection(vertices, WINDING.COUNTER_CLOCKWISE);\n }\n\n const isExtruded = height > 0;\n const vertsAroundEdge = nradial + 1; // loop\n const numVertices = isExtruded\n ? vertsAroundEdge * 3 + 1 // top, side top edge, side bottom edge, one additional degenerage vertex\n : nradial; // top\n\n const stepAngle = (Math.PI * 2) / nradial;\n\n // Used for wireframe\n const indices = new Uint16Array(isExtruded ? nradial * 3 * 2 : 0); // top loop, side vertical, bottom loop\n\n const positions = new Float32Array(numVertices * 3);\n const normals = new Float32Array(numVertices * 3);\n\n let i = 0;\n\n // side tesselation: 0, 1, 2, 3, 4, 5, ...\n //\n // 0 - 2 - 4 ... top\n // | / | / |\n // 1 - 3 - 5 ... bottom\n //\n if (isExtruded) {\n for (let j = 0; j < vertsAroundEdge; j++) {\n const a = j * stepAngle;\n const vertexIndex = j % nradial;\n const sin = Math.sin(a);\n const cos = Math.cos(a);\n\n for (let k = 0; k < 2; k++) {\n positions[i + 0] = vertices ? vertices[vertexIndex * 2] : cos * radius;\n positions[i + 1] = vertices ? vertices[vertexIndex * 2 + 1] : sin * radius;\n positions[i + 2] = (1 / 2 - k) * height;\n\n normals[i + 0] = vertices ? vertices[vertexIndex * 2] : cos;\n normals[i + 1] = vertices ? vertices[vertexIndex * 2 + 1] : sin;\n\n i += 3;\n }\n }\n\n // duplicate the last vertex to create proper degenerate triangle.\n positions[i + 0] = positions[i - 3];\n positions[i + 1] = positions[i - 2];\n positions[i + 2] = positions[i - 1];\n i += 3;\n }\n\n // The column geometry is rendered as a triangle strip, so\n // in order to render sides and top in one go we need to use degenerate triangles.\n // Duplicate last vertex of side trinagles and first vertex of the top cap to preserve winding order.\n\n // top tesselation: 0, -1, 1, -2, 2, -3, 3, ...\n //\n // 0 -- 1\n // / \\\n // -1 2\n // | |\n // -2 3\n // \\ /\n // -3 -- 4\n //\n for (let j = isExtruded ? 0 : 1; j < vertsAroundEdge; j++) {\n const v = Math.floor(j / 2) * Math.sign(0.5 - (j % 2));\n const a = v * stepAngle;\n const vertexIndex = (v + nradial) % nradial;\n const sin = Math.sin(a);\n const cos = Math.cos(a);\n\n positions[i + 0] = vertices ? vertices[vertexIndex * 2] : cos * radius;\n positions[i + 1] = vertices ? vertices[vertexIndex * 2 + 1] : sin * radius;\n positions[i + 2] = height / 2;\n\n normals[i + 2] = 1;\n\n i += 3;\n }\n\n if (isExtruded) {\n let index = 0;\n for (let j = 0; j < nradial; j++) {\n // top loop\n indices[index++] = j * 2 + 0;\n indices[index++] = j * 2 + 2;\n // side vertical\n indices[index++] = j * 2 + 0;\n indices[index++] = j * 2 + 1;\n // bottom loop\n indices[index++] = j * 2 + 1;\n indices[index++] = j * 2 + 3;\n }\n }\n\n return {\n indices,\n attributes: {\n POSITION: {size: 3, value: positions},\n NORMAL: {size: 3, value: normals}\n }\n };\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {Layer, project32, gouraudLighting, picking, UNIT} from '@deck.gl/core';\nimport GL from '@luma.gl/constants';\nimport {Model} from '@luma.gl/core';\nimport ColumnGeometry from './column-geometry';\n\nimport vs from './column-layer-vertex.glsl';\nimport fs from './column-layer-fragment.glsl';\n\nconst DEFAULT_COLOR = [0, 0, 0, 255];\n\nconst defaultProps = {\n diskResolution: {type: 'number', min: 4, value: 20},\n vertices: null,\n radius: {type: 'number', min: 0, value: 1000},\n angle: {type: 'number', value: 0},\n offset: {type: 'array', value: [0, 0]},\n coverage: {type: 'number', min: 0, max: 1, value: 1},\n elevationScale: {type: 'number', min: 0, value: 1},\n radiusUnits: 'meters',\n lineWidthUnits: 'meters',\n lineWidthScale: 1,\n lineWidthMinPixels: 0,\n lineWidthMaxPixels: Number.MAX_SAFE_INTEGER,\n\n extruded: true,\n wireframe: false,\n filled: true,\n stroked: false,\n\n getPosition: {type: 'accessor', value: x => x.position},\n getFillColor: {type: 'accessor', value: DEFAULT_COLOR},\n getLineColor: {type: 'accessor', value: DEFAULT_COLOR},\n getLineWidth: {type: 'accessor', value: 1},\n getElevation: {type: 'accessor', value: 1000},\n material: true,\n getColor: {deprecatedFor: ['getFillColor', 'getLineColor']}\n};\n\nexport default class ColumnLayer extends Layer {\n getShaders() {\n return super.getShaders({vs, fs, modules: [project32, gouraudLighting, picking]});\n }\n\n /**\n * DeckGL calls initializeState when GL context is available\n * Essentially a deferred constructor\n */\n initializeState() {\n const attributeManager = this.getAttributeManager();\n /* eslint-disable max-len */\n attributeManager.addInstanced({\n instancePositions: {\n size: 3,\n type: GL.DOUBLE,\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceElevations: {\n size: 1,\n transition: true,\n accessor: 'getElevation'\n },\n instanceFillColors: {\n size: this.props.colorFormat.length,\n type: GL.UNSIGNED_BYTE,\n normalized: true,\n transition: true,\n accessor: 'getFillColor',\n defaultValue: DEFAULT_COLOR\n },\n instanceLineColors: {\n size: this.props.colorFormat.length,\n type: GL.UNSIGNED_BYTE,\n normalized: true,\n transition: true,\n accessor: 'getLineColor',\n defaultValue: DEFAULT_COLOR\n },\n instanceStrokeWidths: {\n size: 1,\n accessor: 'getLineWidth',\n transition: true\n }\n });\n /* eslint-enable max-len */\n }\n\n updateState({props, oldProps, changeFlags}) {\n super.updateState({props, oldProps, changeFlags});\n\n const regenerateModels = changeFlags.extensionsChanged;\n\n if (regenerateModels) {\n const {gl} = this.context;\n this.state.model?.delete();\n this.state.model = this._getModel(gl);\n this.getAttributeManager().invalidateAll();\n }\n\n if (\n regenerateModels ||\n props.diskResolution !== oldProps.diskResolution ||\n props.vertices !== oldProps.vertices ||\n (props.extruded || props.stroked) !== (oldProps.extruded || oldProps.stroked)\n ) {\n this._updateGeometry(props);\n }\n }\n\n getGeometry(diskResolution, vertices, hasThinkness) {\n const geometry = new ColumnGeometry({\n radius: 1,\n height: hasThinkness ? 2 : 0,\n vertices,\n nradial: diskResolution\n });\n\n let meanVertexDistance = 0;\n if (vertices) {\n for (let i = 0; i < diskResolution; i++) {\n const p = vertices[i];\n const d = Math.sqrt(p[0] * p[0] + p[1] * p[1]);\n meanVertexDistance += d / diskResolution;\n }\n } else {\n meanVertexDistance = 1;\n }\n this.setState({\n edgeDistance: Math.cos(Math.PI / diskResolution) * meanVertexDistance\n });\n\n return geometry;\n }\n\n _getModel(gl) {\n return new Model(gl, {\n ...this.getShaders(),\n id: this.props.id,\n isInstanced: true\n });\n }\n\n _updateGeometry({diskResolution, vertices, extruded, stroked}) {\n const geometry = this.getGeometry(diskResolution, vertices, extruded || stroked);\n\n this.setState({\n fillVertexCount: geometry.attributes.POSITION.value.length / 3,\n wireframeVertexCount: geometry.indices.value.length\n });\n\n this.state.model.setProps({geometry});\n }\n\n draw({uniforms}) {\n const {\n lineWidthUnits,\n lineWidthScale,\n lineWidthMinPixels,\n lineWidthMaxPixels,\n radiusUnits,\n elevationScale,\n extruded,\n filled,\n stroked,\n wireframe,\n offset,\n coverage,\n radius,\n angle\n } = this.props;\n const {model, fillVertexCount, wireframeVertexCount, edgeDistance} = this.state;\n\n model.setUniforms(uniforms).setUniforms({\n radius,\n angle: (angle / 180) * Math.PI,\n offset,\n extruded,\n coverage,\n elevationScale,\n edgeDistance,\n radiusUnits: UNIT[radiusUnits],\n widthUnits: UNIT[lineWidthUnits],\n widthScale: lineWidthScale,\n widthMinPixels: lineWidthMinPixels,\n widthMaxPixels: lineWidthMaxPixels\n });\n\n // When drawing 3d: draw wireframe first so it doesn't get occluded by depth test\n if (extruded && wireframe) {\n model.setProps({isIndexed: true});\n model\n .setVertexCount(wireframeVertexCount)\n .setDrawMode(GL.LINES)\n .setUniforms({isStroke: true})\n .draw();\n }\n if (filled) {\n model.setProps({isIndexed: false});\n model\n .setVertexCount(fillVertexCount)\n .setDrawMode(GL.TRIANGLE_STRIP)\n .setUniforms({isStroke: false})\n .draw();\n }\n // When drawing 2d: draw fill before stroke so that the outline is always on top\n if (!extruded && stroked) {\n model.setProps({isIndexed: false});\n // The width of the stroke is achieved by flattening the side of the cylinder.\n // Skip the last 1/3 of the vertices which is the top.\n model\n .setVertexCount((fillVertexCount * 2) / 3)\n .setDrawMode(GL.TRIANGLE_STRIP)\n .setUniforms({isStroke: true})\n .draw();\n }\n }\n}\n\nColumnLayer.layerName = 'ColumnLayer';\nColumnLayer.defaultProps = defaultProps;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n\n#define SHADER_NAME column-layer-vertex-shader\n\nattribute vec3 positions;\nattribute vec3 normals;\n\nattribute vec3 instancePositions;\nattribute float instanceElevations;\nattribute vec3 instancePositions64Low;\nattribute vec4 instanceFillColors;\nattribute vec4 instanceLineColors;\nattribute float instanceStrokeWidths;\n\nattribute vec3 instancePickingColors;\n\n// Custom uniforms\nuniform float opacity;\nuniform float radius;\nuniform float angle;\nuniform vec2 offset;\nuniform bool extruded;\nuniform bool isStroke;\nuniform float coverage;\nuniform float elevationScale;\nuniform float edgeDistance;\nuniform float widthScale;\nuniform float widthMinPixels;\nuniform float widthMaxPixels;\nuniform int radiusUnits;\nuniform int widthUnits;\n\n// Result\nvarying vec4 vColor;\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n\n vec4 color = isStroke ? instanceLineColors : instanceFillColors;\n // rotate primitive position and normal\n mat2 rotationMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n\n // calculate elevation, if 3d not enabled set to 0\n // cylindar gemoetry height are between -1.0 to 1.0, transform it to between 0, 1\n float elevation = 0.0;\n // calculate stroke offset\n float strokeOffsetRatio = 1.0;\n\n if (extruded) {\n elevation = instanceElevations * (positions.z + 1.0) / 2.0 * elevationScale;\n } else if (isStroke) {\n float widthPixels = clamp(\n project_size_to_pixel(instanceStrokeWidths * widthScale, widthUnits),\n widthMinPixels, widthMaxPixels) / 2.0;\n strokeOffsetRatio -= sign(positions.z) * project_pixel_size(widthPixels) / project_size(edgeDistance * coverage * radius);\n }\n\n // if alpha == 0.0 or z < 0.0, do not render element\n float shouldRender = float(color.a > 0.0 && instanceElevations >= 0.0);\n float dotRadius = radius * coverage * shouldRender;\n\n geometry.normal = project_normal(vec3(rotationMatrix * normals.xy, normals.z));\n geometry.pickingColor = instancePickingColors;\n\n // project center of column\n vec3 centroidPosition = vec3(instancePositions.xy, instancePositions.z + elevation);\n vec3 centroidPosition64Low = instancePositions64Low;\n vec2 offset = (rotationMatrix * positions.xy * strokeOffsetRatio + offset) * dotRadius;\n if (radiusUnits == UNIT_METERS) {\n offset = project_size(offset);\n }\n vec3 pos = vec3(offset, 0.);\n DECKGL_FILTER_SIZE(pos, geometry);\n\n gl_Position = project_position_to_clipspace(centroidPosition, centroidPosition64Low, pos, geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n // Light calculations\n if (extruded && !isStroke) {\n vec3 lightColor = lighting_getLightColor(color.rgb, project_uCameraPosition, geometry.position.xyz, geometry.normal);\n vColor = vec4(lightColor, color.a * opacity);\n } else {\n vColor = vec4(color.rgb, color.a * opacity);\n }\n DECKGL_FILTER_COLOR(vColor, geometry);\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n#define SHADER_NAME column-layer-fragment-shader\n\nprecision highp float;\n\nvarying vec4 vColor;\n\nvoid main(void) {\n gl_FragColor = vColor;\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {Layer, project32, picking, UNIT} from '@deck.gl/core';\nimport GL from '@luma.gl/constants';\nimport {Model, Geometry} from '@luma.gl/core';\n\nimport vs from './scatterplot-layer-vertex.glsl';\nimport fs from './scatterplot-layer-fragment.glsl';\n\nconst DEFAULT_COLOR = [0, 0, 0, 255];\n\nconst defaultProps = {\n radiusUnits: 'meters',\n radiusScale: {type: 'number', min: 0, value: 1},\n radiusMinPixels: {type: 'number', min: 0, value: 0}, // min point radius in pixels\n radiusMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER}, // max point radius in pixels\n\n lineWidthUnits: 'meters',\n lineWidthScale: {type: 'number', min: 0, value: 1},\n lineWidthMinPixels: {type: 'number', min: 0, value: 0},\n lineWidthMaxPixels: {type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER},\n\n stroked: false,\n filled: true,\n billboard: false,\n antialiasing: true,\n\n getPosition: {type: 'accessor', value: x => x.position},\n getRadius: {type: 'accessor', value: 1},\n getFillColor: {type: 'accessor', value: DEFAULT_COLOR},\n getLineColor: {type: 'accessor', value: DEFAULT_COLOR},\n getLineWidth: {type: 'accessor', value: 1},\n\n // deprecated\n strokeWidth: {deprecatedFor: 'getLineWidth'},\n outline: {deprecatedFor: 'stroked'},\n getColor: {deprecatedFor: ['getFillColor', 'getLineColor']}\n};\n\nexport default class ScatterplotLayer extends Layer {\n getShaders() {\n return super.getShaders({vs, fs, modules: [project32, picking]});\n }\n\n initializeState() {\n this.getAttributeManager().addInstanced({\n instancePositions: {\n size: 3,\n type: GL.DOUBLE,\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceRadius: {\n size: 1,\n transition: true,\n accessor: 'getRadius',\n defaultValue: 1\n },\n instanceFillColors: {\n size: this.props.colorFormat.length,\n transition: true,\n normalized: true,\n type: GL.UNSIGNED_BYTE,\n accessor: 'getFillColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineColors: {\n size: this.props.colorFormat.length,\n transition: true,\n normalized: true,\n type: GL.UNSIGNED_BYTE,\n accessor: 'getLineColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineWidths: {\n size: 1,\n transition: true,\n accessor: 'getLineWidth',\n defaultValue: 1\n }\n });\n }\n\n updateState({props, oldProps, changeFlags}) {\n super.updateState({props, oldProps, changeFlags});\n if (changeFlags.extensionsChanged) {\n const {gl} = this.context;\n this.state.model?.delete();\n this.state.model = this._getModel(gl);\n this.getAttributeManager().invalidateAll();\n }\n }\n\n draw({uniforms}) {\n const {\n radiusUnits,\n radiusScale,\n radiusMinPixels,\n radiusMaxPixels,\n stroked,\n filled,\n billboard,\n antialiasing,\n lineWidthUnits,\n lineWidthScale,\n lineWidthMinPixels,\n lineWidthMaxPixels\n } = this.props;\n\n this.state.model\n .setUniforms(uniforms)\n .setUniforms({\n stroked: stroked ? 1 : 0,\n filled,\n billboard,\n antialiasing,\n radiusUnits: UNIT[radiusUnits],\n radiusScale,\n radiusMinPixels,\n radiusMaxPixels,\n lineWidthUnits: UNIT[lineWidthUnits],\n lineWidthScale,\n lineWidthMinPixels,\n lineWidthMaxPixels\n })\n .draw();\n }\n\n _getModel(gl) {\n // a square that minimally cover the unit circle\n const positions = [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0];\n\n return new Model(gl, {\n ...this.getShaders(),\n id: this.props.id,\n geometry: new Geometry({\n drawMode: GL.TRIANGLE_FAN,\n vertexCount: 4,\n attributes: {\n positions: {size: 3, value: new Float32Array(positions)}\n }\n }),\n isInstanced: true\n });\n }\n}\n\nScatterplotLayer.layerName = 'ScatterplotLayer';\nScatterplotLayer.defaultProps = defaultProps;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n#define SHADER_NAME scatterplot-layer-vertex-shader\n\nattribute vec3 positions;\n\nattribute vec3 instancePositions;\nattribute vec3 instancePositions64Low;\nattribute float instanceRadius;\nattribute float instanceLineWidths;\nattribute vec4 instanceFillColors;\nattribute vec4 instanceLineColors;\nattribute vec3 instancePickingColors;\n\nuniform float opacity;\nuniform float radiusScale;\nuniform float radiusMinPixels;\nuniform float radiusMaxPixels;\nuniform float lineWidthScale;\nuniform float lineWidthMinPixels;\nuniform float lineWidthMaxPixels;\nuniform float stroked;\nuniform bool filled;\nuniform bool billboard;\nuniform int radiusUnits;\nuniform int lineWidthUnits;\n\nvarying vec4 vFillColor;\nvarying vec4 vLineColor;\nvarying vec2 unitPosition;\nvarying float innerUnitRadius;\nvarying float outerRadiusPixels;\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n\n // Multiply out radius and clamp to limits\n outerRadiusPixels = clamp(\n project_size_to_pixel(radiusScale * instanceRadius, radiusUnits),\n radiusMinPixels, radiusMaxPixels\n );\n \n // Multiply out line width and clamp to limits\n float lineWidthPixels = clamp(\n project_size_to_pixel(lineWidthScale * instanceLineWidths, lineWidthUnits),\n lineWidthMinPixels, lineWidthMaxPixels\n );\n\n // outer radius needs to offset by half stroke width\n outerRadiusPixels += stroked * lineWidthPixels / 2.0;\n\n // position on the containing square in [-1, 1] space\n unitPosition = positions.xy;\n geometry.uv = unitPosition;\n geometry.pickingColor = instancePickingColors;\n\n innerUnitRadius = 1.0 - stroked * lineWidthPixels / outerRadiusPixels;\n \n if (billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n vec3 offset = positions * outerRadiusPixels;\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset = positions * project_pixel_size(outerRadiusPixels);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position);\n }\n\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n // Apply opacity to instance color, or return instance picking color\n vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * opacity);\n DECKGL_FILTER_COLOR(vFillColor, geometry);\n vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * opacity);\n DECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n`;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n#define SHADER_NAME scatterplot-layer-fragment-shader\n\nprecision highp float;\n\nuniform bool filled;\nuniform float stroked;\nuniform bool antialiasing;\n\nvarying vec4 vFillColor;\nvarying vec4 vLineColor;\nvarying vec2 unitPosition;\nvarying float innerUnitRadius;\nvarying float outerRadiusPixels;\n\nvoid main(void) {\n geometry.uv = unitPosition;\n\n float distToCenter = length(unitPosition) * outerRadiusPixels;\n float inCircle = antialiasing ? \n smoothedge(distToCenter, outerRadiusPixels) : \n step(distToCenter, outerRadiusPixels);\n\n if (inCircle == 0.0) {\n discard;\n }\n\n if (stroked > 0.5) {\n float isLine = antialiasing ? \n smoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) :\n step(innerUnitRadius * outerRadiusPixels, distToCenter);\n\n if (filled) {\n gl_FragColor = mix(vFillColor, vLineColor, isLine);\n } else {\n if (isLine == 0.0) {\n discard;\n }\n gl_FragColor = vec4(vLineColor.rgb, vLineColor.a * isLine);\n }\n } else if (filled) {\n gl_FragColor = vFillColor;\n } else {\n discard;\n }\n\n gl_FragColor.a *= inCircle;\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n`;\n","import {Layer, project32, picking, UNIT} from '@deck.gl/core';\nimport GL from '@luma.gl/constants';\nimport {Model, Geometry} from '@luma.gl/core';\n\nimport vs from './text-background-layer-vertex.glsl';\nimport fs from './text-background-layer-fragment.glsl';\n\nconst defaultProps = {\n billboard: true,\n sizeScale: 1,\n sizeUnits: 'pixels',\n sizeMinPixels: 0,\n sizeMaxPixels: Number.MAX_SAFE_INTEGER,\n\n padding: {type: 'array', value: [0, 0, 0, 0]},\n\n getPosition: {type: 'accessor', value: x => x.position},\n getSize: {type: 'accessor', value: 1},\n getAngle: {type: 'accessor', value: 0},\n getPixelOffset: {type: 'accessor', value: [0, 0]},\n getBoundingRect: {type: 'accessor', value: [0, 0, 0, 0]},\n getFillColor: {type: 'accessor', value: [0, 0, 0, 255]},\n getLineColor: {type: 'accessor', value: [0, 0, 0, 255]},\n getLineWidth: {type: 'accessor', value: 1}\n};\n\nexport default class TextBackgroundLayer extends Layer {\n getShaders() {\n return super.getShaders({vs, fs, modules: [project32, picking]});\n }\n\n initializeState() {\n this.getAttributeManager().addInstanced({\n instancePositions: {\n size: 3,\n type: GL.DOUBLE,\n fp64: this.use64bitPositions(),\n transition: true,\n accessor: 'getPosition'\n },\n instanceSizes: {\n size: 1,\n transition: true,\n accessor: 'getSize',\n defaultValue: 1\n },\n instanceAngles: {\n size: 1,\n transition: true,\n accessor: 'getAngle'\n },\n instanceRects: {\n size: 4,\n accessor: 'getBoundingRect'\n },\n instancePixelOffsets: {\n size: 2,\n transition: true,\n accessor: 'getPixelOffset'\n },\n instanceFillColors: {\n size: 4,\n transition: true,\n normalized: true,\n type: GL.UNSIGNED_BYTE,\n accessor: 'getFillColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineColors: {\n size: 4,\n transition: true,\n normalized: true,\n type: GL.UNSIGNED_BYTE,\n accessor: 'getLineColor',\n defaultValue: [0, 0, 0, 255]\n },\n instanceLineWidths: {\n size: 1,\n transition: true,\n accessor: 'getLineWidth',\n defaultValue: 1\n }\n });\n }\n\n updateState({props, oldProps, changeFlags}) {\n super.updateState({props, oldProps, changeFlags});\n if (changeFlags.extensionsChanged) {\n const {gl} = this.context;\n this.state.model?.delete();\n this.state.model = this._getModel(gl);\n this.getAttributeManager().invalidateAll();\n }\n }\n\n draw({uniforms}) {\n const {\n billboard,\n sizeScale,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n getLineWidth\n } = this.props;\n let {padding} = this.props;\n\n if (padding.length < 4) {\n padding = [padding[0], padding[1], padding[0], padding[1]];\n }\n\n this.state.model\n .setUniforms(uniforms)\n .setUniforms({\n billboard,\n stroked: Boolean(getLineWidth),\n padding,\n sizeUnits: UNIT[sizeUnits],\n sizeScale,\n sizeMinPixels,\n sizeMaxPixels\n })\n .draw();\n }\n\n _getModel(gl) {\n // a square that minimally cover the unit circle\n const positions = [0, 0, 1, 0, 1, 1, 0, 1];\n\n return new Model(gl, {\n ...this.getShaders(),\n id: this.props.id,\n geometry: new Geometry({\n drawMode: GL.TRIANGLE_FAN,\n vertexCount: 4,\n attributes: {\n positions: {size: 2, value: new Float32Array(positions)}\n }\n }),\n isInstanced: true\n });\n }\n}\n\nTextBackgroundLayer.layerName = 'TextBackgroundLayer';\nTextBackgroundLayer.defaultProps = defaultProps;\n","export default `\\\n#define SHADER_NAME text-background-layer-vertex-shader\n\nattribute vec2 positions;\n\nattribute vec3 instancePositions;\nattribute vec3 instancePositions64Low;\nattribute vec4 instanceRects;\nattribute float instanceSizes;\nattribute float instanceAngles;\nattribute vec2 instancePixelOffsets;\nattribute float instanceLineWidths;\nattribute vec4 instanceFillColors;\nattribute vec4 instanceLineColors;\nattribute vec3 instancePickingColors;\n\nuniform bool billboard;\nuniform float opacity;\nuniform float sizeScale;\nuniform float sizeMinPixels;\nuniform float sizeMaxPixels;\nuniform vec4 padding;\nuniform int sizeUnits;\n\nvarying vec4 vFillColor;\nvarying vec4 vLineColor;\nvarying float vLineWidth;\nvarying vec2 uv;\nvarying vec2 dimensions;\n\nvec2 rotate_by_angle(vec2 vertex, float angle) {\n float angle_radian = radians(angle);\n float cos_angle = cos(angle_radian);\n float sin_angle = sin(angle_radian);\n mat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\n return rotationMatrix * vertex;\n}\n\nvoid main(void) {\n geometry.worldPosition = instancePositions;\n geometry.uv = positions;\n geometry.pickingColor = instancePickingColors;\n uv = positions;\n vLineWidth = instanceLineWidths;\n\n // convert size in meters to pixels, then scaled and clamp\n\n // project meters to pixels and clamp to limits\n float sizePixels = clamp(\n project_size_to_pixel(instanceSizes * sizeScale, sizeUnits),\n sizeMinPixels, sizeMaxPixels\n );\n\n dimensions = instanceRects.zw * sizePixels + padding.xy + padding.zw;\n\n vec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * sizePixels + mix(-padding.xy, padding.zw, positions);\n pixelOffset = rotate_by_angle(pixelOffset, instanceAngles);\n pixelOffset += instancePixelOffsets;\n pixelOffset.y *= -1.0;\n\n if (billboard) {\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n vec3 offset = vec3(pixelOffset, 0.0);\n DECKGL_FILTER_SIZE(offset, geometry);\n gl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n } else {\n vec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\n DECKGL_FILTER_SIZE(offset_common, geometry);\n gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\n }\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n // Apply opacity to instance color, or return instance picking color\n vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * opacity);\n DECKGL_FILTER_COLOR(vFillColor, geometry);\n vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * opacity);\n DECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n`;\n","export default `\\\n#define SHADER_NAME text-background-layer-fragment-shader\n\nprecision highp float;\n\nuniform bool stroked;\n\nvarying vec4 vFillColor;\nvarying vec4 vLineColor;\nvarying float vLineWidth;\nvarying vec2 uv;\nvarying vec2 dimensions;\n\nvoid main(void) {\n geometry.uv = uv;\n\n vec2 pixelPosition = uv * dimensions;\n if (stroked) {\n float distToEdge = min(\n min(pixelPosition.x, dimensions.x - pixelPosition.x),\n min(pixelPosition.y, dimensions.y - pixelPosition.y)\n );\n float isBorder = smoothedge(distToEdge, vLineWidth);\n gl_FragColor = mix(vFillColor, vLineColor, isBorder);\n } else {\n gl_FragColor = vFillColor;\n }\n\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n`;\n","import {load} from '@loaders.gl/core';\n\nexport default class Resource {\n constructor(id, data, context) {\n this.id = id;\n this.context = context;\n\n this._loadCount = 0;\n this._subscribers = new Set();\n\n this.setData(data);\n }\n\n // consumer: {onChange: Function}\n subscribe(consumer) {\n this._subscribers.add(consumer);\n }\n\n unsubscribe(consumer) {\n this._subscribers.delete(consumer);\n }\n\n inUse() {\n return this._subscribers.size > 0;\n }\n\n delete() {\n // Remove any resources created\n }\n\n getData() {\n return this.isLoaded\n ? this._error\n ? Promise.reject(this._error)\n : this._content\n : this._loader.then(() => this.getData());\n }\n\n setData(data, forceUpdate) {\n if (data === this._data && !forceUpdate) {\n return;\n }\n this._data = data;\n const loadCount = ++this._loadCount;\n\n let loader = data;\n if (typeof data === 'string') {\n loader = load(data);\n }\n if (loader instanceof Promise) {\n this.isLoaded = false;\n this._loader = loader\n .then(result => {\n // check if source has changed\n if (this._loadCount === loadCount) {\n this.isLoaded = true;\n this._error = null;\n this._content = result;\n }\n })\n .catch(error => {\n if (this._loadCount === loadCount) {\n this.isLoaded = true;\n this._error = error || true;\n }\n });\n } else {\n this.isLoaded = true;\n this._error = null;\n this._content = data;\n }\n\n for (const subscriber of this._subscribers) {\n subscriber.onChange(this.getData());\n }\n }\n}\n","/* global setTimeout */\nimport Resource from './resource';\n\nexport default class ResourceManager {\n constructor({gl, protocol}) {\n this.protocol = protocol || 'resource://';\n\n this._context = {\n gl,\n resourceManager: this\n };\n this._resources = {};\n this._consumers = {};\n\n this._pruneRequest = null;\n }\n\n contains(resourceId) {\n if (resourceId.startsWith(this.protocol)) {\n return true;\n }\n return resourceId in this._resources;\n }\n\n add({resourceId, data, forceUpdate = false, persistent = true}) {\n let res = this._resources[resourceId];\n\n if (res) {\n res.setData(data, forceUpdate);\n } else {\n res = new Resource(resourceId, data, this._context);\n this._resources[resourceId] = res;\n }\n // persistent resources can only be removed by calling `remove`\n // non-persistent resources may be released when there are no more consumers\n res.persistent = persistent;\n }\n\n remove(resourceId) {\n const res = this._resources[resourceId];\n\n if (res) {\n res.delete();\n delete this._resources[resourceId];\n }\n }\n\n unsubscribe({consumerId}) {\n const consumer = this._consumers[consumerId];\n if (consumer) {\n for (const requestId in consumer) {\n const request = consumer[requestId];\n if (request.resource) {\n request.resource.unsubscribe(request);\n }\n }\n delete this._consumers[consumerId];\n this.prune();\n }\n }\n\n subscribe({resourceId, onChange, consumerId, requestId = 'default'}) {\n const {_resources: resources, protocol} = this;\n if (resourceId.startsWith(protocol)) {\n resourceId = resourceId.replace(protocol, '');\n if (!resources[resourceId]) {\n // Add placeholder. When this resource becomes available, the consumer will be notified.\n this.add({resourceId, data: null, persistent: false});\n }\n }\n const res = resources[resourceId];\n this._track(consumerId, requestId, res, onChange);\n if (res) {\n return res.getData();\n }\n\n return undefined;\n }\n\n prune() {\n if (!this._pruneRequest) {\n // prune() may be called multiple times in the same animation frame.\n // Batch multiple requests together\n this._pruneRequest = setTimeout(() => this._prune(), 0);\n }\n }\n\n finalize() {\n for (const key in this._resources) {\n this._resources[key].delete();\n }\n }\n\n _track(consumerId, requestId, resource, onChange) {\n const consumers = this._consumers;\n const consumer = (consumers[consumerId] = consumers[consumerId] || {});\n const request = consumer[requestId] || {};\n\n if (request.resource) {\n request.resource.unsubscribe(request);\n request.resource = null;\n this.prune();\n }\n if (resource) {\n consumer[requestId] = request;\n request.onChange = onChange;\n request.resource = resource;\n resource.subscribe(request);\n }\n }\n\n _prune() {\n this._pruneRequest = null;\n\n for (const key of Object.keys(this._resources)) {\n const res = this._resources[key];\n if (!res.persistent && !res.inUse()) {\n res.delete();\n delete this._resources[key];\n }\n }\n }\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport {Timeline} from '@luma.gl/core';\nimport {LIFECYCLE} from '../lifecycle/constants';\nimport log from '../utils/log';\nimport debug from '../debug';\nimport {flatten} from '../utils/flatten';\nimport {Stats} from 'probe.gl';\nimport ResourceManager from './resource/resource-manager';\n\nimport Viewport from '../viewports/viewport';\nimport {createProgramManager} from '../shaderlib';\n\nconst TRACE_SET_LAYERS = 'layerManager.setLayers';\nconst TRACE_ACTIVATE_VIEWPORT = 'layerManager.activateViewport';\n\n// CONTEXT IS EXPOSED TO LAYERS\nconst INITIAL_CONTEXT = Object.seal({\n layerManager: null,\n resourceManager: null,\n deck: null,\n gl: null,\n\n // General resources\n stats: null, // for tracking lifecycle performance\n\n // GL Resources\n shaderCache: null,\n pickingFBO: null, // Screen-size framebuffer that layers can reuse\n\n mousePosition: null,\n\n userData: {} // Place for any custom app `context`\n});\n\nexport default class LayerManager {\n // eslint-disable-next-line\n constructor(gl, {deck, stats, viewport, timeline} = {}) {\n // Currently deck.gl expects the DeckGL.layers array to be different\n // whenever React rerenders. If the same layers array is used, the\n // LayerManager's diffing algorithm will generate a fatal error and\n // break the rendering.\n\n // `this.lastRenderedLayers` stores the UNFILTERED layers sent\n // down to LayerManager, so that `layers` reference can be compared.\n // If it's the same across two React render calls, the diffing logic\n // will be skipped.\n this.lastRenderedLayers = [];\n this.layers = [];\n this.resourceManager = new ResourceManager({gl, protocol: 'deck://'});\n\n this.context = {\n ...INITIAL_CONTEXT,\n layerManager: this,\n gl,\n deck,\n // Enabling luma.gl Program caching using private API (_cachePrograms)\n programManager: gl && createProgramManager(gl),\n stats: stats || new Stats({id: 'deck.gl'}),\n // Make sure context.viewport is not empty on the first layer initialization\n viewport: viewport || new Viewport({id: 'DEFAULT-INITIAL-VIEWPORT'}), // Current viewport, exposed to layers for project* function\n timeline: timeline || new Timeline(),\n resourceManager: this.resourceManager\n };\n\n this._nextLayers = null;\n this._needsRedraw = 'Initial render';\n this._needsUpdate = false;\n this._debug = false;\n\n this.activateViewport = this.activateViewport.bind(this);\n\n Object.seal(this);\n }\n\n // Method to call when the layer manager is not needed anymore.\n finalize() {\n this.resourceManager.finalize();\n // Finalize all layers\n for (const layer of this.layers) {\n this._finalizeLayer(layer);\n }\n }\n\n // Check if a redraw is needed\n needsRedraw(opts = {clearRedrawFlags: false}) {\n let redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n\n // This layers list doesn't include sublayers, relying on composite layers\n for (const layer of this.layers) {\n // Call every layer to clear their flags\n const layerNeedsRedraw = layer.getNeedsRedraw(opts);\n redraw = redraw || layerNeedsRedraw;\n }\n\n return redraw;\n }\n\n // Check if a deep update of all layers is needed\n needsUpdate() {\n if (this._nextLayers && this._nextLayers !== this.lastRenderedLayers) {\n // New layers array may be the same as the old one if `setProps` is called by React\n return 'layers changed';\n }\n return this._needsUpdate;\n }\n\n // Layers will be redrawn (in next animation frame)\n setNeedsRedraw(reason) {\n this._needsRedraw = this._needsRedraw || reason;\n }\n\n // Layers will be updated deeply (in next animation frame)\n // Potentially regenerating attributes and sub layers\n setNeedsUpdate(reason) {\n this._needsUpdate = this._needsUpdate || reason;\n }\n\n // Gets an (optionally) filtered list of layers\n getLayers({layerIds = null} = {}) {\n // Filtering by layerId compares beginning of strings, so that sublayers will be included\n // Dependes on the convention of adding suffixes to the parent's layer name\n return layerIds\n ? this.layers.filter(layer => layerIds.find(layerId => layer.id.indexOf(layerId) === 0))\n : this.layers;\n }\n\n // Set props needed for layer rendering and picking.\n setProps(props) {\n if ('debug' in props) {\n this._debug = props.debug;\n }\n\n // A way for apps to add data to context that can be accessed in layers\n if ('userData' in props) {\n this.context.userData = props.userData;\n }\n\n // New layers will be processed in `updateLayers` in the next update cycle\n if ('layers' in props) {\n this._nextLayers = props.layers;\n }\n\n if ('onError' in props) {\n this.context.onError = props.onError;\n }\n }\n\n // Supply a new layer list, initiating sublayer generation and layer matching\n setLayers(newLayers, reason) {\n debug(TRACE_SET_LAYERS, this, reason, newLayers);\n\n this.lastRenderedLayers = newLayers;\n\n newLayers = flatten(newLayers, Boolean);\n\n for (const layer of newLayers) {\n layer.context = this.context;\n }\n\n this._updateLayers(this.layers, newLayers);\n\n return this;\n }\n\n // Update layers from last cycle if `setNeedsUpdate()` has been called\n updateLayers() {\n // NOTE: For now, even if only some layer has changed, we update all layers\n // to ensure that layer id maps etc remain consistent even if different\n // sublayers are rendered\n const reason = this.needsUpdate();\n if (reason) {\n this.setNeedsRedraw(`updating layers: ${reason}`);\n // Force a full update\n this.setLayers(this._nextLayers || this.lastRenderedLayers, reason);\n }\n // Updated, clear the backlog\n this._nextLayers = null;\n }\n\n //\n // PRIVATE METHODS\n //\n\n // Make a viewport \"current\" in layer context, updating viewportChanged flags\n activateViewport(viewport) {\n debug(TRACE_ACTIVATE_VIEWPORT, this, viewport);\n if (viewport) {\n this.context.viewport = viewport;\n }\n return this;\n }\n\n _handleError(stage, error, layer) {\n layer.raiseError(error, `${stage} of ${layer}`);\n }\n\n // Match all layers, checking for caught errors\n // To avoid having an exception in one layer disrupt other layers\n // TODO - mark layers with exceptions as bad and remove from rendering cycle?\n _updateLayers(oldLayers, newLayers) {\n // Create old layer map\n const oldLayerMap = {};\n for (const oldLayer of oldLayers) {\n if (oldLayerMap[oldLayer.id]) {\n log.warn(`Multiple old layers with same id ${oldLayer.id}`)();\n } else {\n oldLayerMap[oldLayer.id] = oldLayer;\n }\n }\n\n // Allocate array for generated layers\n const generatedLayers = [];\n\n // Match sublayers\n this._updateSublayersRecursively(newLayers, oldLayerMap, generatedLayers);\n\n // Finalize unmatched layers\n this._finalizeOldLayers(oldLayerMap);\n\n let needsUpdate = false;\n for (const layer of generatedLayers) {\n if (layer.hasUniformTransition()) {\n needsUpdate = true;\n break;\n }\n }\n\n this._needsUpdate = needsUpdate;\n this.layers = generatedLayers;\n }\n\n /* eslint-disable complexity,max-statements */\n // Note: adds generated layers to `generatedLayers` array parameter\n _updateSublayersRecursively(newLayers, oldLayerMap, generatedLayers) {\n for (const newLayer of newLayers) {\n newLayer.context = this.context;\n\n // Given a new coming layer, find its matching old layer (if any)\n const oldLayer = oldLayerMap[newLayer.id];\n if (oldLayer === null) {\n // null, rather than undefined, means this id was originally there\n log.warn(`Multiple new layers with same id ${newLayer.id}`)();\n }\n // Remove the old layer from candidates, as it has been matched with this layer\n oldLayerMap[newLayer.id] = null;\n\n let sublayers = null;\n\n // We must not generate exceptions until after layer matching is complete\n try {\n if (this._debug && oldLayer !== newLayer) {\n newLayer.validateProps();\n }\n\n if (!oldLayer) {\n this._initializeLayer(newLayer);\n } else {\n this._transferLayerState(oldLayer, newLayer);\n this._updateLayer(newLayer);\n }\n generatedLayers.push(newLayer);\n\n // Call layer lifecycle method: render sublayers\n sublayers = newLayer.isComposite && newLayer.getSubLayers();\n // End layer lifecycle method: render sublayers\n } catch (err) {\n this._handleError('matching', err, newLayer); // Record first exception\n }\n\n if (sublayers) {\n this._updateSublayersRecursively(sublayers, oldLayerMap, generatedLayers);\n }\n }\n }\n /* eslint-enable complexity,max-statements */\n\n // Finalize any old layers that were not matched\n _finalizeOldLayers(oldLayerMap) {\n for (const layerId in oldLayerMap) {\n const layer = oldLayerMap[layerId];\n if (layer) {\n this._finalizeLayer(layer);\n }\n }\n }\n\n // EXCEPTION SAFE LAYER ACCESS\n\n // Initializes a single layer, calling layer methods\n _initializeLayer(layer) {\n try {\n layer._initialize();\n layer.lifecycle = LIFECYCLE.INITIALIZED;\n } catch (err) {\n this._handleError('initialization', err, layer);\n // TODO - what should the lifecycle state be here? LIFECYCLE.INITIALIZATION_FAILED?\n }\n }\n\n _transferLayerState(oldLayer, newLayer) {\n newLayer._transferState(oldLayer);\n newLayer.lifecycle = LIFECYCLE.MATCHED;\n\n if (newLayer !== oldLayer) {\n oldLayer.lifecycle = LIFECYCLE.AWAITING_GC;\n }\n }\n\n // Updates a single layer, cleaning all flags\n _updateLayer(layer) {\n try {\n layer._update();\n } catch (err) {\n this._handleError('update', err, layer);\n }\n }\n\n // Finalizes a single layer\n _finalizeLayer(layer) {\n this._needsRedraw = this._needsRedraw || `finalized ${layer}`;\n\n layer.lifecycle = LIFECYCLE.AWAITING_FINALIZATION;\n\n try {\n layer._finalize();\n layer.lifecycle = LIFECYCLE.FINALIZED;\n } catch (err) {\n this._handleError('finalization', err, layer);\n }\n }\n}\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport GL from '@luma.gl/constants';\nimport {log} from '@deck.gl/core';\nimport IconLayer from '../../icon-layer/icon-layer';\n\nimport fs from './multi-icon-layer-fragment.glsl';\n\n// TODO expose as layer properties\nconst DEFAULT_BUFFER = 192.0 / 256;\nconst EMPTY_ARRAY = [];\n\nconst defaultProps = {\n getIconOffsets: {type: 'accessor', value: x => x.offsets},\n alphaCutoff: 0.001,\n smoothing: 0.1,\n outlineWidth: 0,\n outlineColor: {type: 'color', value: [0, 0, 0, 255]}\n};\n\nexport default class MultiIconLayer extends IconLayer {\n getShaders() {\n return {...super.getShaders(), fs};\n }\n\n initializeState() {\n super.initializeState();\n\n const attributeManager = this.getAttributeManager();\n attributeManager.addInstanced({\n instanceOffsets: {\n size: 2,\n accessor: 'getIconOffsets'\n },\n instancePickingColors: {\n type: GL.UNSIGNED_BYTE,\n size: 3,\n accessor: (object, {index, target: value}) => this.encodePickingColor(index, value)\n }\n });\n }\n\n updateState(params) {\n super.updateState(params);\n const {props, oldProps} = params;\n let {outlineColor} = props;\n\n if (outlineColor !== oldProps.outlineColor) {\n outlineColor = outlineColor.map(x => x / 255);\n outlineColor[3] = Number.isFinite(outlineColor[3]) ? outlineColor[3] : 1;\n\n this.setState({\n outlineColor\n });\n }\n if (!props.sdf && props.outlineWidth) {\n log.warn(`${this.id}: fontSettings.sdf is required to render outline`)();\n }\n }\n\n draw(params) {\n const {sdf, smoothing, outlineWidth} = this.props;\n const {outlineColor} = this.state;\n\n params.uniforms = {\n ...params.uniforms,\n // Refer the following doc about gamma and buffer\n // https://blog.mapbox.com/drawing-text-with-signed-distance-fields-in-mapbox-gl-b0933af6f817\n buffer: DEFAULT_BUFFER,\n outlineBuffer: outlineWidth ? Math.max(smoothing, DEFAULT_BUFFER * (1 - outlineWidth)) : -1,\n gamma: smoothing,\n sdf: Boolean(sdf),\n outlineColor\n };\n super.draw(params);\n }\n\n getInstanceOffset(icons) {\n return icons ? Array.from(icons).map(icon => super.getInstanceOffset(icon)) : EMPTY_ARRAY;\n }\n\n getInstanceColorMode(icons) {\n return 1; // mask\n }\n\n getInstanceIconFrame(icons) {\n return icons ? Array.from(icons).map(icon => super.getInstanceIconFrame(icon)) : EMPTY_ARRAY;\n }\n}\n\nMultiIconLayer.layerName = 'MultiIconLayer';\nMultiIconLayer.defaultProps = defaultProps;\n","// Copyright (c) 2015 - 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nexport default `\\\n#define SHADER_NAME multi-icon-layer-fragment-shader\n\nprecision highp float;\n\nuniform float opacity;\nuniform sampler2D iconsTexture;\nuniform float gamma;\nuniform bool sdf;\nuniform float alphaCutoff;\nuniform float buffer;\nuniform float outlineBuffer;\nuniform vec4 outlineColor;\n\nvarying vec4 vColor;\nvarying vec2 vTextureCoords;\nvarying vec2 uv;\n\nvoid main(void) {\n geometry.uv = uv;\n\n if (!picking_uActive) {\n float alpha = texture2D(iconsTexture, vTextureCoords).a;\n vec4 color = vColor;\n\n // if enable sdf (signed distance fields)\n if (sdf) {\n float distance = alpha;\n alpha = smoothstep(buffer - gamma, buffer + gamma, distance);\n\n if (outlineBuffer > 0.0) {\n float inFill = alpha;\n float inBorder = smoothstep(outlineBuffer - gamma, outlineBuffer + gamma, distance);\n color = mix(outlineColor, vColor, inFill);\n alpha = inBorder;\n }\n }\n\n // Take the global opacity and the alpha from color into account for the alpha component\n float a = alpha * color.a;\n \n if (a < alphaCutoff) {\n discard;\n }\n\n gl_FragColor = vec4(color.rgb, a * opacity);\n }\n\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n`;\n","import LayersPass from './layers-pass';\n\nexport default class DrawLayersPass extends LayersPass {}\n","import debug from '../debug';\nimport DrawLayersPass from '../passes/draw-layers-pass';\nimport PickLayersPass from '../passes/pick-layers-pass';\nimport {Framebuffer} from '@luma.gl/core';\n\nconst TRACE_RENDER_LAYERS = 'deckRenderer.renderLayers';\n\nexport default class DeckRenderer {\n constructor(gl) {\n this.gl = gl;\n this.layerFilter = null;\n this.drawPickingColors = false;\n this.drawLayersPass = new DrawLayersPass(gl);\n this.pickLayersPass = new PickLayersPass(gl);\n this.renderCount = 0;\n this._needsRedraw = 'Initial render';\n this.renderBuffers = [];\n this.lastPostProcessEffect = null;\n }\n\n setProps(props) {\n if ('layerFilter' in props && this.layerFilter !== props.layerFilter) {\n this.layerFilter = props.layerFilter;\n this._needsRedraw = 'layerFilter changed';\n }\n\n if ('drawPickingColors' in props && this.drawPickingColors !== props.drawPickingColors) {\n this.drawPickingColors = props.drawPickingColors;\n this._needsRedraw = 'drawPickingColors changed';\n }\n }\n\n /*\n target,\n layers,\n viewports,\n onViewportActive,\n views,\n redrawReason,\n clearCanvas,\n effects,\n pass,\n stats\n */\n renderLayers(opts) {\n const layerPass = this.drawPickingColors ? this.pickLayersPass : this.drawLayersPass;\n\n opts.layerFilter = opts.layerFilter || this.layerFilter;\n opts.effects = opts.effects || [];\n opts.target = opts.target || Framebuffer.getDefaultFramebuffer(this.gl);\n\n this._preRender(opts.effects, opts);\n\n const outputBuffer = this.lastPostProcessEffect ? this.renderBuffers[0] : opts.target;\n const renderStats = layerPass.render({...opts, target: outputBuffer});\n\n this._postRender(opts.effects, opts);\n\n this.renderCount++;\n\n debug(TRACE_RENDER_LAYERS, this, renderStats, opts);\n }\n\n needsRedraw(opts = {clearRedrawFlags: false}) {\n const redraw = this._needsRedraw;\n if (opts.clearRedrawFlags) {\n this._needsRedraw = false;\n }\n return redraw;\n }\n\n finalize() {\n const {renderBuffers} = this;\n for (const buffer of renderBuffers) {\n buffer.delete();\n }\n renderBuffers.length = 0;\n }\n\n // Private\n _preRender(effects, opts) {\n let lastPostProcessEffect = null;\n\n for (const effect of effects) {\n effect.preRender(this.gl, opts);\n if (effect.postRender) {\n lastPostProcessEffect = effect;\n }\n }\n\n if (lastPostProcessEffect) {\n this._resizeRenderBuffers();\n }\n this.lastPostProcessEffect = lastPostProcessEffect;\n }\n\n _resizeRenderBuffers() {\n const {renderBuffers} = this;\n if (renderBuffers.length === 0) {\n renderBuffers.push(new Framebuffer(this.gl), new Framebuffer(this.gl));\n }\n for (const buffer of renderBuffers) {\n buffer.resize();\n }\n }\n\n _postRender(effects, opts) {\n const {renderBuffers} = this;\n const params = {\n inputBuffer: renderBuffers[0],\n swapBuffer: renderBuffers[1],\n target: null\n };\n for (const effect of effects) {\n if (effect.postRender) {\n if (effect === this.lastPostProcessEffect) {\n params.target = opts.target;\n effect.postRender(this.gl, params);\n break;\n }\n const buffer = effect.postRender(this.gl, params);\n params.inputBuffer = buffer;\n params.swapBuffer = buffer === renderBuffers[0] ? renderBuffers[1] : renderBuffers[0];\n }\n }\n }\n}\n","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","export default function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter);\n}","import React from 'react';\nvar ThemeContext = React.createContext(null);\n\nif (process.env.NODE_ENV !== 'production') {\n ThemeContext.displayName = 'ThemeContext';\n}\n\nexport default ThemeContext;","export default function _iterableToArray(iter) {\n if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter);\n}","var hasSymbol = typeof Symbol === 'function' && Symbol.for;\nexport default hasSymbol ? Symbol.for('mui.nested') : '__THEME_NESTED__';","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n}","import _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport PropTypes from 'prop-types';\nimport merge from './merge'; // The breakpoint **start** at this value.\n// For instance with the first breakpoint xs: [xs, sm[.\n\nvar values = {\n xs: 0,\n sm: 600,\n md: 960,\n lg: 1280,\n xl: 1920\n};\nvar defaultBreakpoints = {\n // Sorted ASC by size. That's important.\n // It can't be configured as it's used statically for propTypes.\n keys: ['xs', 'sm', 'md', 'lg', 'xl'],\n up: function up(key) {\n return \"@media (min-width:\".concat(values[key], \"px)\");\n }\n};\nexport function handleBreakpoints(props, propValue, styleFromPropValue) {\n if (process.env.NODE_ENV !== 'production') {\n if (!props.theme) {\n console.error('Material-UI: You are calling a style function without a theme value.');\n }\n }\n\n if (Array.isArray(propValue)) {\n var themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;\n return propValue.reduce(function (acc, item, index) {\n acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]);\n return acc;\n }, {});\n }\n\n if (_typeof(propValue) === 'object') {\n var _themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;\n\n return Object.keys(propValue).reduce(function (acc, breakpoint) {\n acc[_themeBreakpoints.up(breakpoint)] = styleFromPropValue(propValue[breakpoint]);\n return acc;\n }, {});\n }\n\n var output = styleFromPropValue(propValue);\n return output;\n}\n\nfunction breakpoints(styleFunction) {\n var newStyleFunction = function newStyleFunction(props) {\n var base = styleFunction(props);\n var themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;\n var extended = themeBreakpoints.keys.reduce(function (acc, key) {\n if (props[key]) {\n acc = acc || {};\n acc[themeBreakpoints.up(key)] = styleFunction(_extends({\n theme: props.theme\n }, props[key]));\n }\n\n return acc;\n }, null);\n return merge(base, extended);\n };\n\n newStyleFunction.propTypes = process.env.NODE_ENV !== 'production' ? _extends({}, styleFunction.propTypes, {\n xs: PropTypes.object,\n sm: PropTypes.object,\n md: PropTypes.object,\n lg: PropTypes.object,\n xl: PropTypes.object\n }) : {};\n newStyleFunction.filterProps = ['xs', 'sm', 'md', 'lg', 'xl'].concat(_toConsumableArray(styleFunction.filterProps));\n return newStyleFunction;\n}\n\nexport default breakpoints;","// We need to centralize the zIndex definitions as they work\n// like global values in the browser.\nvar zIndex = {\n mobileStepper: 1000,\n speedDial: 1050,\n appBar: 1100,\n drawer: 1200,\n modal: 1300,\n snackbar: 1400,\n tooltip: 1500\n};\nexport default zIndex;","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","// This function is needed in initialization stages,\n// make sure it can be imported in isolation\n\nimport isElectron from './is-electron';\n\nexport default function isBrowser() {\n // Check if in browser by duck-typing Node context\n const isNode =\n // @ts-ignore\n typeof process === 'object' && String(process) === '[object process]' && !process.browser;\n\n return !isNode || isElectron();\n}\n\n// document does not exist on worker thread\nexport function isBrowserMainThread() {\n return isBrowser() && typeof document !== 'undefined';\n}\n","// based on https://github.com/cheton/is-electron\n// https://github.com/electron/electron/issues/2288\n/* eslint-disable complexity */\nexport default function isElectron(mockUserAgent) {\n // Renderer process\n if (\n typeof window !== 'undefined' &&\n typeof window.process === 'object' &&\n // @ts-ignore\n window.process.type === 'renderer'\n ) {\n return true;\n }\n // Main process\n if (\n typeof process !== 'undefined' &&\n typeof process.versions === 'object' &&\n // @ts-ignore\n Boolean(process.versions.electron)\n ) {\n return true;\n }\n // Detect the user agent when the `nodeIntegration` option is set to true\n const realUserAgent =\n typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent;\n const userAgent = mockUserAgent || realUserAgent;\n if (userAgent && userAgent.indexOf('Electron') >= 0) {\n return true;\n }\n return false;\n}\n","import {log} from '@luma.gl/gltools';\n\n// Install stubs for removed methods\nexport function stubRemovedMethods(instance, className, version, methodNames) {\n const upgradeMessage = `See luma.gl ${version} Upgrade Guide at \\\nhttps://luma.gl/docs/upgrade-guide`;\n\n const prototype = Object.getPrototypeOf(instance);\n\n methodNames.forEach(methodName => {\n if (prototype.methodName) {\n return;\n }\n\n prototype[methodName] = () => {\n log.removed(`Calling removed method ${className}.${methodName}: `, upgradeMessage)();\n throw new Error(methodName);\n };\n });\n}\n","// Attributions\n// * Based on binary-gltf-utils under MIT license: Copyright (c) 2016-17 Karl Cheng\n\n// TODO: make these functions work for Node.js buffers?\n// Quarantine references to Buffer to prevent bundler from adding big polyfills\n// import {bufferToArrayBuffer} from '../node/buffer-to-array-buffer';\n// TODO - this should be handled in @loaders.gl/polyfills\n\n/** MIME type, width and height extracted from binary compressed image data */\nexport type BinaryImageMetadata = {\n mimeType: string;\n width: number;\n height: number;\n};\n\nconst BIG_ENDIAN = false;\nconst LITTLE_ENDIAN = true;\n\n/**\n * Extracts `{mimeType, width and height}` from a memory buffer containing a known image format\n * Currently supports `image/png`, `image/jpeg`, `image/bmp` and `image/gif`.\n * @param binaryData image file memory to parse\n * @returns metadata or null if memory is not a valid image file format layout.\n */\nexport function getBinaryImageMetadata(\n binaryData: DataView | ArrayBuffer\n): BinaryImageMetadata | null {\n const dataView = toDataView(binaryData);\n return (\n getPngMetadata(dataView) ||\n getJpegMetadata(dataView) ||\n getGifMetadata(dataView) ||\n getBmpMetadata(dataView)\n );\n}\n\n// PNG\n\nfunction getPngMetadata(binaryData) {\n const dataView = toDataView(binaryData);\n // Check file contains the first 4 bytes of the PNG signature.\n const isPng = dataView.byteLength >= 24 && dataView.getUint32(0, BIG_ENDIAN) === 0x89504e47;\n if (!isPng) {\n return null;\n }\n\n // Extract size from a binary PNG file\n return {\n mimeType: 'image/png',\n width: dataView.getUint32(16, BIG_ENDIAN),\n height: dataView.getUint32(20, BIG_ENDIAN)\n };\n}\n\n// GIF\n\n// Extract size from a binary GIF file\n// TODO: GIF is not this simple\nfunction getGifMetadata(binaryData) {\n const dataView = toDataView(binaryData);\n // Check first 4 bytes of the GIF signature (\"GIF8\").\n const isGif = dataView.byteLength >= 10 && dataView.getUint32(0, BIG_ENDIAN) === 0x47494638;\n if (!isGif) {\n return null;\n }\n\n // GIF is little endian.\n return {\n mimeType: 'image/gif',\n width: dataView.getUint16(6, LITTLE_ENDIAN),\n height: dataView.getUint16(8, LITTLE_ENDIAN)\n };\n}\n\n// BMP\n\n// TODO: BMP is not this simple\nexport function getBmpMetadata(binaryData) {\n const dataView = toDataView(binaryData);\n // Check magic number is valid (first 2 characters should be \"BM\").\n // The mandatory bitmap file header is 14 bytes long.\n const isBmp =\n dataView.byteLength >= 14 &&\n dataView.getUint16(0, BIG_ENDIAN) === 0x424d &&\n dataView.getUint32(2, LITTLE_ENDIAN) === dataView.byteLength;\n\n if (!isBmp) {\n return null;\n }\n\n // BMP is little endian.\n return {\n mimeType: 'image/bmp',\n width: dataView.getUint32(18, LITTLE_ENDIAN),\n height: dataView.getUint32(22, LITTLE_ENDIAN)\n };\n}\n\n// JPEG\n\n// Extract width and height from a binary JPEG file\nfunction getJpegMetadata(binaryData) {\n const dataView = toDataView(binaryData);\n // Check file contains the JPEG \"start of image\" (SOI) marker\n // followed by another marker.\n const isJpeg =\n dataView.byteLength >= 3 &&\n dataView.getUint16(0, BIG_ENDIAN) === 0xffd8 &&\n dataView.getUint8(2) === 0xff;\n\n if (!isJpeg) {\n return null;\n }\n\n const {tableMarkers, sofMarkers} = getJpegMarkers();\n\n // Exclude the two byte SOI marker.\n let i = 2;\n while (i + 9 < dataView.byteLength) {\n const marker = dataView.getUint16(i, BIG_ENDIAN);\n\n // The frame that contains the width and height of the JPEG image.\n if (sofMarkers.has(marker)) {\n return {\n mimeType: 'image/jpeg',\n height: dataView.getUint16(i + 5, BIG_ENDIAN), // Number of lines\n width: dataView.getUint16(i + 7, BIG_ENDIAN) // Number of pixels per line\n };\n }\n\n // Miscellaneous tables/data preceding the frame header.\n if (!tableMarkers.has(marker)) {\n return null;\n }\n\n // Length includes size of length parameter but not the two byte header.\n i += 2;\n i += dataView.getUint16(i, BIG_ENDIAN);\n }\n\n return null;\n}\n\nfunction getJpegMarkers() {\n // Tables/misc header markers.\n // DQT, DHT, DAC, DRI, COM, APP_n\n const tableMarkers = new Set([0xffdb, 0xffc4, 0xffcc, 0xffdd, 0xfffe]);\n for (let i = 0xffe0; i < 0xfff0; ++i) {\n tableMarkers.add(i);\n }\n\n // SOF markers and DHP marker.\n // These markers are after tables/misc data.\n const sofMarkers = new Set([\n 0xffc0, 0xffc1, 0xffc2, 0xffc3, 0xffc5, 0xffc6, 0xffc7, 0xffc9, 0xffca, 0xffcb, 0xffcd, 0xffce,\n 0xffcf, 0xffde\n ]);\n\n return {tableMarkers, sofMarkers};\n}\n\n// TODO - move into image module?\nfunction toDataView(data) {\n if (data instanceof DataView) {\n return data;\n }\n if (ArrayBuffer.isView(data)) {\n return new DataView(data.buffer);\n }\n\n // TODO: make these functions work for Node.js buffers?\n // if (bufferToArrayBuffer) {\n // data = bufferToArrayBuffer(data);\n // }\n\n // Careful - Node Buffers will look like ArrayBuffers (keep after isBuffer)\n if (data instanceof ArrayBuffer) {\n return new DataView(data);\n }\n throw new Error('toDataView');\n}\n","export default class Pass {\n constructor(gl, props = {}) {\n const {id = 'pass'} = props;\n this.id = id; // id of this pass\n this.gl = gl;\n this.props = {...props};\n }\n\n setProps(props) {\n Object.assign(this.props, props);\n }\n\n render() {}\n\n cleanup() {}\n}\n","import LayersPass from './layers-pass';\nimport {withParameters} from '@luma.gl/core';\nimport GL from '@luma.gl/constants';\nimport log from '../utils/log';\n\nconst PICKING_PARAMETERS = {\n blendFunc: [GL.ONE, GL.ZERO, GL.CONSTANT_ALPHA, GL.ZERO],\n blendEquation: GL.FUNC_ADD\n};\n\nexport default class PickLayersPass extends LayersPass {\n render(props) {\n if (props.pickingFBO) {\n // When drawing into an off-screen buffer, use the alpha channel to encode layer index\n return this._drawPickingBuffer(props);\n }\n // When drawing to screen (debug mode), do not use the alpha channel so that result is always visible\n return super.render(props);\n }\n\n // Private\n // Draws list of layers and viewports into the picking buffer\n // Note: does not sample the buffer, that has to be done by the caller\n _drawPickingBuffer({\n layers,\n layerFilter,\n views,\n viewports,\n onViewportActive,\n pickingFBO,\n deviceRect: {x, y, width, height},\n pass = 'picking',\n redrawReason,\n pickZ\n }) {\n const gl = this.gl;\n this.pickZ = pickZ;\n\n // Track encoded layer indices\n const encodedColors = !pickZ && {\n byLayer: new Map(),\n byAlpha: []\n };\n // Temporarily store it on the instance so that it can be accessed by this.getLayerParameters\n this._colors = encodedColors;\n\n // Make sure we clear scissor test and fbo bindings in case of exceptions\n // We are only interested in one pixel, no need to render anything else\n // Note that the callback here is called synchronously.\n // Set blend mode for picking\n // always overwrite existing pixel with [r,g,b,layerIndex]\n const renderStatus = withParameters(\n gl,\n {\n scissorTest: true,\n scissor: [x, y, width, height],\n clearColor: [0, 0, 0, 0],\n // When used as Mapbox custom layer, the context state may be dirty\n // TODO - Remove when mapbox fixes this issue\n // https://github.com/mapbox/mapbox-gl-js/issues/7801\n depthMask: true,\n depthTest: true,\n depthRange: [0, 1],\n colorMask: [true, true, true, true],\n // Blending\n ...PICKING_PARAMETERS,\n blend: !pickZ\n },\n () =>\n super.render({\n target: pickingFBO,\n layers,\n layerFilter,\n views,\n viewports,\n onViewportActive,\n pass,\n redrawReason\n })\n );\n\n // Clear the temp field\n this._colors = null;\n const decodePickingColor = encodedColors && decodeColor.bind(null, encodedColors);\n return {decodePickingColor, stats: renderStatus};\n }\n\n // PRIVATE\n shouldDrawLayer(layer) {\n return layer.props.pickable;\n }\n\n getModuleParameters() {\n return {\n pickingActive: 1,\n pickingAttribute: this.pickZ,\n // turn off lighting by adding empty light source object\n // lights shader module relies on the `lightSources` to turn on/off lighting\n lightSources: {}\n };\n }\n\n getLayerParameters(layer, layerIndex, viewport) {\n const pickParameters = {...layer.props.parameters};\n\n if (this.pickZ) {\n pickParameters.blend = false;\n } else {\n Object.assign(pickParameters, PICKING_PARAMETERS);\n pickParameters.blend = true;\n pickParameters.blendColor = encodeColor(this._colors, layer, viewport);\n }\n\n return pickParameters;\n }\n}\n\n// Assign an unique alpha value for each pickable layer and track the encoding in the cache object\n// Returns normalized blend color\nfunction encodeColor(encoded, layer, viewport) {\n const {byLayer, byAlpha} = encoded;\n let a;\n\n // Encode layerIndex in the alpha channel\n // TODO - combine small layers to better utilize the picking color space\n if (byLayer.has(layer)) {\n const entry = byLayer.get(layer);\n entry.viewports.push(viewport);\n a = entry.a;\n } else {\n a = byLayer.size + 1;\n if (a <= 255) {\n const entry = {a, layer, viewports: [viewport]};\n byLayer.set(layer, entry);\n byAlpha[a] = entry;\n } else {\n log.warn('Too many pickable layers, only picking the first 255')();\n a = 0;\n }\n }\n return [0, 0, 0, a / 255];\n}\n\n// Given a picked color, retrieve the corresponding layer and viewports from cache\nfunction decodeColor(encoded, pickedColor) {\n const entry = encoded.byAlpha[pickedColor[3]];\n return (\n entry && {\n pickedLayer: entry.layer,\n pickedViewports: entry.viewports,\n pickedObjectIndex: entry.layer.decodePickingColor(pickedColor)\n }\n );\n}\n","// TinyColor v1.4.1\n// https://github.com/bgrins/TinyColor\n// Brian Grinstead, MIT License\n\n(function(Math) {\n\nvar trimLeft = /^\\s+/,\n trimRight = /\\s+$/,\n tinyCounter = 0,\n mathRound = Math.round,\n mathMin = Math.min,\n mathMax = Math.max,\n mathRandom = Math.random;\n\nfunction tinycolor (color, opts) {\n\n color = (color) ? color : '';\n opts = opts || { };\n\n // If input is already a tinycolor, return itself\n if (color instanceof tinycolor) {\n return color;\n }\n // If we are called as a function, call using new instead\n if (!(this instanceof tinycolor)) {\n return new tinycolor(color, opts);\n }\n\n var rgb = inputToRGB(color);\n this._originalInput = color,\n this._r = rgb.r,\n this._g = rgb.g,\n this._b = rgb.b,\n this._a = rgb.a,\n this._roundA = mathRound(100*this._a) / 100,\n this._format = opts.format || rgb.format;\n this._gradientType = opts.gradientType;\n\n // Don't let the range of [0,255] come back in [0,1].\n // Potentially lose a little bit of precision here, but will fix issues where\n // .5 gets interpreted as half of the total, instead of half of 1\n // If it was supposed to be 128, this was already taken care of by `inputToRgb`\n if (this._r < 1) { this._r = mathRound(this._r); }\n if (this._g < 1) { this._g = mathRound(this._g); }\n if (this._b < 1) { this._b = mathRound(this._b); }\n\n this._ok = rgb.ok;\n this._tc_id = tinyCounter++;\n}\n\ntinycolor.prototype = {\n isDark: function() {\n return this.getBrightness() < 128;\n },\n isLight: function() {\n return !this.isDark();\n },\n isValid: function() {\n return this._ok;\n },\n getOriginalInput: function() {\n return this._originalInput;\n },\n getFormat: function() {\n return this._format;\n },\n getAlpha: function() {\n return this._a;\n },\n getBrightness: function() {\n //http://www.w3.org/TR/AERT#color-contrast\n var rgb = this.toRgb();\n return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;\n },\n getLuminance: function() {\n //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef\n var rgb = this.toRgb();\n var RsRGB, GsRGB, BsRGB, R, G, B;\n RsRGB = rgb.r/255;\n GsRGB = rgb.g/255;\n BsRGB = rgb.b/255;\n\n if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}\n if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}\n if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}\n return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);\n },\n setAlpha: function(value) {\n this._a = boundAlpha(value);\n this._roundA = mathRound(100*this._a) / 100;\n return this;\n },\n toHsv: function() {\n var hsv = rgbToHsv(this._r, this._g, this._b);\n return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };\n },\n toHsvString: function() {\n var hsv = rgbToHsv(this._r, this._g, this._b);\n var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);\n return (this._a == 1) ?\n \"hsv(\" + h + \", \" + s + \"%, \" + v + \"%)\" :\n \"hsva(\" + h + \", \" + s + \"%, \" + v + \"%, \"+ this._roundA + \")\";\n },\n toHsl: function() {\n var hsl = rgbToHsl(this._r, this._g, this._b);\n return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };\n },\n toHslString: function() {\n var hsl = rgbToHsl(this._r, this._g, this._b);\n var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);\n return (this._a == 1) ?\n \"hsl(\" + h + \", \" + s + \"%, \" + l + \"%)\" :\n \"hsla(\" + h + \", \" + s + \"%, \" + l + \"%, \"+ this._roundA + \")\";\n },\n toHex: function(allow3Char) {\n return rgbToHex(this._r, this._g, this._b, allow3Char);\n },\n toHexString: function(allow3Char) {\n return '#' + this.toHex(allow3Char);\n },\n toHex8: function(allow4Char) {\n return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);\n },\n toHex8String: function(allow4Char) {\n return '#' + this.toHex8(allow4Char);\n },\n toRgb: function() {\n return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };\n },\n toRgbString: function() {\n return (this._a == 1) ?\n \"rgb(\" + mathRound(this._r) + \", \" + mathRound(this._g) + \", \" + mathRound(this._b) + \")\" :\n \"rgba(\" + mathRound(this._r) + \", \" + mathRound(this._g) + \", \" + mathRound(this._b) + \", \" + this._roundA + \")\";\n },\n toPercentageRgb: function() {\n return { r: mathRound(bound01(this._r, 255) * 100) + \"%\", g: mathRound(bound01(this._g, 255) * 100) + \"%\", b: mathRound(bound01(this._b, 255) * 100) + \"%\", a: this._a };\n },\n toPercentageRgbString: function() {\n return (this._a == 1) ?\n \"rgb(\" + mathRound(bound01(this._r, 255) * 100) + \"%, \" + mathRound(bound01(this._g, 255) * 100) + \"%, \" + mathRound(bound01(this._b, 255) * 100) + \"%)\" :\n \"rgba(\" + mathRound(bound01(this._r, 255) * 100) + \"%, \" + mathRound(bound01(this._g, 255) * 100) + \"%, \" + mathRound(bound01(this._b, 255) * 100) + \"%, \" + this._roundA + \")\";\n },\n toName: function() {\n if (this._a === 0) {\n return \"transparent\";\n }\n\n if (this._a < 1) {\n return false;\n }\n\n return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;\n },\n toFilter: function(secondColor) {\n var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);\n var secondHex8String = hex8String;\n var gradientType = this._gradientType ? \"GradientType = 1, \" : \"\";\n\n if (secondColor) {\n var s = tinycolor(secondColor);\n secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);\n }\n\n return \"progid:DXImageTransform.Microsoft.gradient(\"+gradientType+\"startColorstr=\"+hex8String+\",endColorstr=\"+secondHex8String+\")\";\n },\n toString: function(format) {\n var formatSet = !!format;\n format = format || this._format;\n\n var formattedString = false;\n var hasAlpha = this._a < 1 && this._a >= 0;\n var needsAlphaFormat = !formatSet && hasAlpha && (format === \"hex\" || format === \"hex6\" || format === \"hex3\" || format === \"hex4\" || format === \"hex8\" || format === \"name\");\n\n if (needsAlphaFormat) {\n // Special case for \"transparent\", all other non-alpha formats\n // will return rgba when there is transparency.\n if (format === \"name\" && this._a === 0) {\n return this.toName();\n }\n return this.toRgbString();\n }\n if (format === \"rgb\") {\n formattedString = this.toRgbString();\n }\n if (format === \"prgb\") {\n formattedString = this.toPercentageRgbString();\n }\n if (format === \"hex\" || format === \"hex6\") {\n formattedString = this.toHexString();\n }\n if (format === \"hex3\") {\n formattedString = this.toHexString(true);\n }\n if (format === \"hex4\") {\n formattedString = this.toHex8String(true);\n }\n if (format === \"hex8\") {\n formattedString = this.toHex8String();\n }\n if (format === \"name\") {\n formattedString = this.toName();\n }\n if (format === \"hsl\") {\n formattedString = this.toHslString();\n }\n if (format === \"hsv\") {\n formattedString = this.toHsvString();\n }\n\n return formattedString || this.toHexString();\n },\n clone: function() {\n return tinycolor(this.toString());\n },\n\n _applyModification: function(fn, args) {\n var color = fn.apply(null, [this].concat([].slice.call(args)));\n this._r = color._r;\n this._g = color._g;\n this._b = color._b;\n this.setAlpha(color._a);\n return this;\n },\n lighten: function() {\n return this._applyModification(lighten, arguments);\n },\n brighten: function() {\n return this._applyModification(brighten, arguments);\n },\n darken: function() {\n return this._applyModification(darken, arguments);\n },\n desaturate: function() {\n return this._applyModification(desaturate, arguments);\n },\n saturate: function() {\n return this._applyModification(saturate, arguments);\n },\n greyscale: function() {\n return this._applyModification(greyscale, arguments);\n },\n spin: function() {\n return this._applyModification(spin, arguments);\n },\n\n _applyCombination: function(fn, args) {\n return fn.apply(null, [this].concat([].slice.call(args)));\n },\n analogous: function() {\n return this._applyCombination(analogous, arguments);\n },\n complement: function() {\n return this._applyCombination(complement, arguments);\n },\n monochromatic: function() {\n return this._applyCombination(monochromatic, arguments);\n },\n splitcomplement: function() {\n return this._applyCombination(splitcomplement, arguments);\n },\n triad: function() {\n return this._applyCombination(triad, arguments);\n },\n tetrad: function() {\n return this._applyCombination(tetrad, arguments);\n }\n};\n\n// If input is an object, force 1 into \"1.0\" to handle ratios properly\n// String input requires \"1.0\" as input, so 1 will be treated as 1\ntinycolor.fromRatio = function(color, opts) {\n if (typeof color == \"object\") {\n var newColor = {};\n for (var i in color) {\n if (color.hasOwnProperty(i)) {\n if (i === \"a\") {\n newColor[i] = color[i];\n }\n else {\n newColor[i] = convertToPercentage(color[i]);\n }\n }\n }\n color = newColor;\n }\n\n return tinycolor(color, opts);\n};\n\n// Given a string or object, convert that input to RGB\n// Possible string inputs:\n//\n// \"red\"\n// \"#f00\" or \"f00\"\n// \"#ff0000\" or \"ff0000\"\n// \"#ff000000\" or \"ff000000\"\n// \"rgb 255 0 0\" or \"rgb (255, 0, 0)\"\n// \"rgb 1.0 0 0\" or \"rgb (1, 0, 0)\"\n// \"rgba (255, 0, 0, 1)\" or \"rgba 255, 0, 0, 1\"\n// \"rgba (1.0, 0, 0, 1)\" or \"rgba 1.0, 0, 0, 1\"\n// \"hsl(0, 100%, 50%)\" or \"hsl 0 100% 50%\"\n// \"hsla(0, 100%, 50%, 1)\" or \"hsla 0 100% 50%, 1\"\n// \"hsv(0, 100%, 100%)\" or \"hsv 0 100% 100%\"\n//\nfunction inputToRGB(color) {\n\n var rgb = { r: 0, g: 0, b: 0 };\n var a = 1;\n var s = null;\n var v = null;\n var l = null;\n var ok = false;\n var format = false;\n\n if (typeof color == \"string\") {\n color = stringInputToObject(color);\n }\n\n if (typeof color == \"object\") {\n if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {\n rgb = rgbToRgb(color.r, color.g, color.b);\n ok = true;\n format = String(color.r).substr(-1) === \"%\" ? \"prgb\" : \"rgb\";\n }\n else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {\n s = convertToPercentage(color.s);\n v = convertToPercentage(color.v);\n rgb = hsvToRgb(color.h, s, v);\n ok = true;\n format = \"hsv\";\n }\n else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {\n s = convertToPercentage(color.s);\n l = convertToPercentage(color.l);\n rgb = hslToRgb(color.h, s, l);\n ok = true;\n format = \"hsl\";\n }\n\n if (color.hasOwnProperty(\"a\")) {\n a = color.a;\n }\n }\n\n a = boundAlpha(a);\n\n return {\n ok: ok,\n format: color.format || format,\n r: mathMin(255, mathMax(rgb.r, 0)),\n g: mathMin(255, mathMax(rgb.g, 0)),\n b: mathMin(255, mathMax(rgb.b, 0)),\n a: a\n };\n}\n\n\n// Conversion Functions\n// --------------------\n\n// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:\n// \n\n// `rgbToRgb`\n// Handle bounds / percentage checking to conform to CSS color spec\n// \n// *Assumes:* r, g, b in [0, 255] or [0, 1]\n// *Returns:* { r, g, b } in [0, 255]\nfunction rgbToRgb(r, g, b){\n return {\n r: bound01(r, 255) * 255,\n g: bound01(g, 255) * 255,\n b: bound01(b, 255) * 255\n };\n}\n\n// `rgbToHsl`\n// Converts an RGB color value to HSL.\n// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]\n// *Returns:* { h, s, l } in [0,1]\nfunction rgbToHsl(r, g, b) {\n\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n\n var max = mathMax(r, g, b), min = mathMin(r, g, b);\n var h, s, l = (max + min) / 2;\n\n if(max == min) {\n h = s = 0; // achromatic\n }\n else {\n var d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch(max) {\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n\n h /= 6;\n }\n\n return { h: h, s: s, l: l };\n}\n\n// `hslToRgb`\n// Converts an HSL color value to RGB.\n// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]\n// *Returns:* { r, g, b } in the set [0, 255]\nfunction hslToRgb(h, s, l) {\n var r, g, b;\n\n h = bound01(h, 360);\n s = bound01(s, 100);\n l = bound01(l, 100);\n\n function hue2rgb(p, q, t) {\n if(t < 0) t += 1;\n if(t > 1) t -= 1;\n if(t < 1/6) return p + (q - p) * 6 * t;\n if(t < 1/2) return q;\n if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;\n return p;\n }\n\n if(s === 0) {\n r = g = b = l; // achromatic\n }\n else {\n var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n var p = 2 * l - q;\n r = hue2rgb(p, q, h + 1/3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1/3);\n }\n\n return { r: r * 255, g: g * 255, b: b * 255 };\n}\n\n// `rgbToHsv`\n// Converts an RGB color value to HSV\n// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]\n// *Returns:* { h, s, v } in [0,1]\nfunction rgbToHsv(r, g, b) {\n\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n\n var max = mathMax(r, g, b), min = mathMin(r, g, b);\n var h, s, v = max;\n\n var d = max - min;\n s = max === 0 ? 0 : d / max;\n\n if(max == min) {\n h = 0; // achromatic\n }\n else {\n switch(max) {\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n h /= 6;\n }\n return { h: h, s: s, v: v };\n}\n\n// `hsvToRgb`\n// Converts an HSV color value to RGB.\n// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]\n// *Returns:* { r, g, b } in the set [0, 255]\n function hsvToRgb(h, s, v) {\n\n h = bound01(h, 360) * 6;\n s = bound01(s, 100);\n v = bound01(v, 100);\n\n var i = Math.floor(h),\n f = h - i,\n p = v * (1 - s),\n q = v * (1 - f * s),\n t = v * (1 - (1 - f) * s),\n mod = i % 6,\n r = [v, q, p, p, t, v][mod],\n g = [t, v, v, q, p, p][mod],\n b = [p, p, t, v, v, q][mod];\n\n return { r: r * 255, g: g * 255, b: b * 255 };\n}\n\n// `rgbToHex`\n// Converts an RGB color to hex\n// Assumes r, g, and b are contained in the set [0, 255]\n// Returns a 3 or 6 character hex\nfunction rgbToHex(r, g, b, allow3Char) {\n\n var hex = [\n pad2(mathRound(r).toString(16)),\n pad2(mathRound(g).toString(16)),\n pad2(mathRound(b).toString(16))\n ];\n\n // Return a 3 character hex if possible\n if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);\n }\n\n return hex.join(\"\");\n}\n\n// `rgbaToHex`\n// Converts an RGBA color plus alpha transparency to hex\n// Assumes r, g, b are contained in the set [0, 255] and\n// a in [0, 1]. Returns a 4 or 8 character rgba hex\nfunction rgbaToHex(r, g, b, a, allow4Char) {\n\n var hex = [\n pad2(mathRound(r).toString(16)),\n pad2(mathRound(g).toString(16)),\n pad2(mathRound(b).toString(16)),\n pad2(convertDecimalToHex(a))\n ];\n\n // Return a 4 character hex if possible\n if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);\n }\n\n return hex.join(\"\");\n}\n\n// `rgbaToArgbHex`\n// Converts an RGBA color to an ARGB Hex8 string\n// Rarely used, but required for \"toFilter()\"\nfunction rgbaToArgbHex(r, g, b, a) {\n\n var hex = [\n pad2(convertDecimalToHex(a)),\n pad2(mathRound(r).toString(16)),\n pad2(mathRound(g).toString(16)),\n pad2(mathRound(b).toString(16))\n ];\n\n return hex.join(\"\");\n}\n\n// `equals`\n// Can be called with any tinycolor input\ntinycolor.equals = function (color1, color2) {\n if (!color1 || !color2) { return false; }\n return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();\n};\n\ntinycolor.random = function() {\n return tinycolor.fromRatio({\n r: mathRandom(),\n g: mathRandom(),\n b: mathRandom()\n });\n};\n\n\n// Modification Functions\n// ----------------------\n// Thanks to less.js for some of the basics here\n// \n\nfunction desaturate(color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.s -= amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n}\n\nfunction saturate(color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.s += amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n}\n\nfunction greyscale(color) {\n return tinycolor(color).desaturate(100);\n}\n\nfunction lighten (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.l += amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n}\n\nfunction brighten(color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var rgb = tinycolor(color).toRgb();\n rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));\n rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));\n rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));\n return tinycolor(rgb);\n}\n\nfunction darken (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.l -= amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n}\n\n// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.\n// Values outside of this range will be wrapped into this range.\nfunction spin(color, amount) {\n var hsl = tinycolor(color).toHsl();\n var hue = (hsl.h + amount) % 360;\n hsl.h = hue < 0 ? 360 + hue : hue;\n return tinycolor(hsl);\n}\n\n// Combination Functions\n// ---------------------\n// Thanks to jQuery xColor for some of the ideas behind these\n// \n\nfunction complement(color) {\n var hsl = tinycolor(color).toHsl();\n hsl.h = (hsl.h + 180) % 360;\n return tinycolor(hsl);\n}\n\nfunction triad(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })\n ];\n}\n\nfunction tetrad(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })\n ];\n}\n\nfunction splitcomplement(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),\n tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})\n ];\n}\n\nfunction analogous(color, results, slices) {\n results = results || 6;\n slices = slices || 30;\n\n var hsl = tinycolor(color).toHsl();\n var part = 360 / slices;\n var ret = [tinycolor(color)];\n\n for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {\n hsl.h = (hsl.h + part) % 360;\n ret.push(tinycolor(hsl));\n }\n return ret;\n}\n\nfunction monochromatic(color, results) {\n results = results || 6;\n var hsv = tinycolor(color).toHsv();\n var h = hsv.h, s = hsv.s, v = hsv.v;\n var ret = [];\n var modification = 1 / results;\n\n while (results--) {\n ret.push(tinycolor({ h: h, s: s, v: v}));\n v = (v + modification) % 1;\n }\n\n return ret;\n}\n\n// Utility Functions\n// ---------------------\n\ntinycolor.mix = function(color1, color2, amount) {\n amount = (amount === 0) ? 0 : (amount || 50);\n\n var rgb1 = tinycolor(color1).toRgb();\n var rgb2 = tinycolor(color2).toRgb();\n\n var p = amount / 100;\n\n var rgba = {\n r: ((rgb2.r - rgb1.r) * p) + rgb1.r,\n g: ((rgb2.g - rgb1.g) * p) + rgb1.g,\n b: ((rgb2.b - rgb1.b) * p) + rgb1.b,\n a: ((rgb2.a - rgb1.a) * p) + rgb1.a\n };\n\n return tinycolor(rgba);\n};\n\n\n// Readability Functions\n// ---------------------\n// false\n// tinycolor.isReadable(\"#000\", \"#111\",{level:\"AA\",size:\"large\"}) => false\ntinycolor.isReadable = function(color1, color2, wcag2) {\n var readability = tinycolor.readability(color1, color2);\n var wcag2Parms, out;\n\n out = false;\n\n wcag2Parms = validateWCAG2Parms(wcag2);\n switch (wcag2Parms.level + wcag2Parms.size) {\n case \"AAsmall\":\n case \"AAAlarge\":\n out = readability >= 4.5;\n break;\n case \"AAlarge\":\n out = readability >= 3;\n break;\n case \"AAAsmall\":\n out = readability >= 7;\n break;\n }\n return out;\n\n};\n\n// `mostReadable`\n// Given a base color and a list of possible foreground or background\n// colors for that base, returns the most readable color.\n// Optionally returns Black or White if the most readable color is unreadable.\n// *Example*\n// tinycolor.mostReadable(tinycolor.mostReadable(\"#123\", [\"#124\", \"#125\"],{includeFallbackColors:false}).toHexString(); // \"#112255\"\n// tinycolor.mostReadable(tinycolor.mostReadable(\"#123\", [\"#124\", \"#125\"],{includeFallbackColors:true}).toHexString(); // \"#ffffff\"\n// tinycolor.mostReadable(\"#a8015a\", [\"#faf3f3\"],{includeFallbackColors:true,level:\"AAA\",size:\"large\"}).toHexString(); // \"#faf3f3\"\n// tinycolor.mostReadable(\"#a8015a\", [\"#faf3f3\"],{includeFallbackColors:true,level:\"AAA\",size:\"small\"}).toHexString(); // \"#ffffff\"\ntinycolor.mostReadable = function(baseColor, colorList, args) {\n var bestColor = null;\n var bestScore = 0;\n var readability;\n var includeFallbackColors, level, size ;\n args = args || {};\n includeFallbackColors = args.includeFallbackColors ;\n level = args.level;\n size = args.size;\n\n for (var i= 0; i < colorList.length ; i++) {\n readability = tinycolor.readability(baseColor, colorList[i]);\n if (readability > bestScore) {\n bestScore = readability;\n bestColor = tinycolor(colorList[i]);\n }\n }\n\n if (tinycolor.isReadable(baseColor, bestColor, {\"level\":level,\"size\":size}) || !includeFallbackColors) {\n return bestColor;\n }\n else {\n args.includeFallbackColors=false;\n return tinycolor.mostReadable(baseColor,[\"#fff\", \"#000\"],args);\n }\n};\n\n\n// Big List of Colors\n// ------------------\n// \nvar names = tinycolor.names = {\n aliceblue: \"f0f8ff\",\n antiquewhite: \"faebd7\",\n aqua: \"0ff\",\n aquamarine: \"7fffd4\",\n azure: \"f0ffff\",\n beige: \"f5f5dc\",\n bisque: \"ffe4c4\",\n black: \"000\",\n blanchedalmond: \"ffebcd\",\n blue: \"00f\",\n blueviolet: \"8a2be2\",\n brown: \"a52a2a\",\n burlywood: \"deb887\",\n burntsienna: \"ea7e5d\",\n cadetblue: \"5f9ea0\",\n chartreuse: \"7fff00\",\n chocolate: \"d2691e\",\n coral: \"ff7f50\",\n cornflowerblue: \"6495ed\",\n cornsilk: \"fff8dc\",\n crimson: \"dc143c\",\n cyan: \"0ff\",\n darkblue: \"00008b\",\n darkcyan: \"008b8b\",\n darkgoldenrod: \"b8860b\",\n darkgray: \"a9a9a9\",\n darkgreen: \"006400\",\n darkgrey: \"a9a9a9\",\n darkkhaki: \"bdb76b\",\n darkmagenta: \"8b008b\",\n darkolivegreen: \"556b2f\",\n darkorange: \"ff8c00\",\n darkorchid: \"9932cc\",\n darkred: \"8b0000\",\n darksalmon: \"e9967a\",\n darkseagreen: \"8fbc8f\",\n darkslateblue: \"483d8b\",\n darkslategray: \"2f4f4f\",\n darkslategrey: \"2f4f4f\",\n darkturquoise: \"00ced1\",\n darkviolet: \"9400d3\",\n deeppink: \"ff1493\",\n deepskyblue: \"00bfff\",\n dimgray: \"696969\",\n dimgrey: \"696969\",\n dodgerblue: \"1e90ff\",\n firebrick: \"b22222\",\n floralwhite: \"fffaf0\",\n forestgreen: \"228b22\",\n fuchsia: \"f0f\",\n gainsboro: \"dcdcdc\",\n ghostwhite: \"f8f8ff\",\n gold: \"ffd700\",\n goldenrod: \"daa520\",\n gray: \"808080\",\n green: \"008000\",\n greenyellow: \"adff2f\",\n grey: \"808080\",\n honeydew: \"f0fff0\",\n hotpink: \"ff69b4\",\n indianred: \"cd5c5c\",\n indigo: \"4b0082\",\n ivory: \"fffff0\",\n khaki: \"f0e68c\",\n lavender: \"e6e6fa\",\n lavenderblush: \"fff0f5\",\n lawngreen: \"7cfc00\",\n lemonchiffon: \"fffacd\",\n lightblue: \"add8e6\",\n lightcoral: \"f08080\",\n lightcyan: \"e0ffff\",\n lightgoldenrodyellow: \"fafad2\",\n lightgray: \"d3d3d3\",\n lightgreen: \"90ee90\",\n lightgrey: \"d3d3d3\",\n lightpink: \"ffb6c1\",\n lightsalmon: \"ffa07a\",\n lightseagreen: \"20b2aa\",\n lightskyblue: \"87cefa\",\n lightslategray: \"789\",\n lightslategrey: \"789\",\n lightsteelblue: \"b0c4de\",\n lightyellow: \"ffffe0\",\n lime: \"0f0\",\n limegreen: \"32cd32\",\n linen: \"faf0e6\",\n magenta: \"f0f\",\n maroon: \"800000\",\n mediumaquamarine: \"66cdaa\",\n mediumblue: \"0000cd\",\n mediumorchid: \"ba55d3\",\n mediumpurple: \"9370db\",\n mediumseagreen: \"3cb371\",\n mediumslateblue: \"7b68ee\",\n mediumspringgreen: \"00fa9a\",\n mediumturquoise: \"48d1cc\",\n mediumvioletred: \"c71585\",\n midnightblue: \"191970\",\n mintcream: \"f5fffa\",\n mistyrose: \"ffe4e1\",\n moccasin: \"ffe4b5\",\n navajowhite: \"ffdead\",\n navy: \"000080\",\n oldlace: \"fdf5e6\",\n olive: \"808000\",\n olivedrab: \"6b8e23\",\n orange: \"ffa500\",\n orangered: \"ff4500\",\n orchid: \"da70d6\",\n palegoldenrod: \"eee8aa\",\n palegreen: \"98fb98\",\n paleturquoise: \"afeeee\",\n palevioletred: \"db7093\",\n papayawhip: \"ffefd5\",\n peachpuff: \"ffdab9\",\n peru: \"cd853f\",\n pink: \"ffc0cb\",\n plum: \"dda0dd\",\n powderblue: \"b0e0e6\",\n purple: \"800080\",\n rebeccapurple: \"663399\",\n red: \"f00\",\n rosybrown: \"bc8f8f\",\n royalblue: \"4169e1\",\n saddlebrown: \"8b4513\",\n salmon: \"fa8072\",\n sandybrown: \"f4a460\",\n seagreen: \"2e8b57\",\n seashell: \"fff5ee\",\n sienna: \"a0522d\",\n silver: \"c0c0c0\",\n skyblue: \"87ceeb\",\n slateblue: \"6a5acd\",\n slategray: \"708090\",\n slategrey: \"708090\",\n snow: \"fffafa\",\n springgreen: \"00ff7f\",\n steelblue: \"4682b4\",\n tan: \"d2b48c\",\n teal: \"008080\",\n thistle: \"d8bfd8\",\n tomato: \"ff6347\",\n turquoise: \"40e0d0\",\n violet: \"ee82ee\",\n wheat: \"f5deb3\",\n white: \"fff\",\n whitesmoke: \"f5f5f5\",\n yellow: \"ff0\",\n yellowgreen: \"9acd32\"\n};\n\n// Make it easy to access colors via `hexNames[hex]`\nvar hexNames = tinycolor.hexNames = flip(names);\n\n\n// Utilities\n// ---------\n\n// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`\nfunction flip(o) {\n var flipped = { };\n for (var i in o) {\n if (o.hasOwnProperty(i)) {\n flipped[o[i]] = i;\n }\n }\n return flipped;\n}\n\n// Return a valid alpha value [0,1] with all invalid values being set to 1\nfunction boundAlpha(a) {\n a = parseFloat(a);\n\n if (isNaN(a) || a < 0 || a > 1) {\n a = 1;\n }\n\n return a;\n}\n\n// Take input from [0, n] and return it as [0, 1]\nfunction bound01(n, max) {\n if (isOnePointZero(n)) { n = \"100%\"; }\n\n var processPercent = isPercentage(n);\n n = mathMin(max, mathMax(0, parseFloat(n)));\n\n // Automatically convert percentage into number\n if (processPercent) {\n n = parseInt(n * max, 10) / 100;\n }\n\n // Handle floating point rounding errors\n if ((Math.abs(n - max) < 0.000001)) {\n return 1;\n }\n\n // Convert into [0, 1] range if it isn't already\n return (n % max) / parseFloat(max);\n}\n\n// Force a number between 0 and 1\nfunction clamp01(val) {\n return mathMin(1, mathMax(0, val));\n}\n\n// Parse a base-16 hex value into a base-10 integer\nfunction parseIntFromHex(val) {\n return parseInt(val, 16);\n}\n\n// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1\n// \nfunction isOnePointZero(n) {\n return typeof n == \"string\" && n.indexOf('.') != -1 && parseFloat(n) === 1;\n}\n\n// Check to see if string passed in is a percentage\nfunction isPercentage(n) {\n return typeof n === \"string\" && n.indexOf('%') != -1;\n}\n\n// Force a hex value to have 2 characters\nfunction pad2(c) {\n return c.length == 1 ? '0' + c : '' + c;\n}\n\n// Replace a decimal with it's percentage value\nfunction convertToPercentage(n) {\n if (n <= 1) {\n n = (n * 100) + \"%\";\n }\n\n return n;\n}\n\n// Converts a decimal to a hex value\nfunction convertDecimalToHex(d) {\n return Math.round(parseFloat(d) * 255).toString(16);\n}\n// Converts a hex value to a decimal\nfunction convertHexToDecimal(h) {\n return (parseIntFromHex(h) / 255);\n}\n\nvar matchers = (function() {\n\n // \n var CSS_INTEGER = \"[-\\\\+]?\\\\d+%?\";\n\n // \n var CSS_NUMBER = \"[-\\\\+]?\\\\d*\\\\.\\\\d+%?\";\n\n // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.\n var CSS_UNIT = \"(?:\" + CSS_NUMBER + \")|(?:\" + CSS_INTEGER + \")\";\n\n // Actual matching.\n // Parentheses and commas are optional, but not required.\n // Whitespace can take the place of commas or opening paren\n var PERMISSIVE_MATCH3 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n var PERMISSIVE_MATCH4 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n\n return {\n CSS_UNIT: new RegExp(CSS_UNIT),\n rgb: new RegExp(\"rgb\" + PERMISSIVE_MATCH3),\n rgba: new RegExp(\"rgba\" + PERMISSIVE_MATCH4),\n hsl: new RegExp(\"hsl\" + PERMISSIVE_MATCH3),\n hsla: new RegExp(\"hsla\" + PERMISSIVE_MATCH4),\n hsv: new RegExp(\"hsv\" + PERMISSIVE_MATCH3),\n hsva: new RegExp(\"hsva\" + PERMISSIVE_MATCH4),\n hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,\n hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/\n };\n})();\n\n// `isValidCSSUnit`\n// Take in a single string / number and check to see if it looks like a CSS unit\n// (see `matchers` above for definition).\nfunction isValidCSSUnit(color) {\n return !!matchers.CSS_UNIT.exec(color);\n}\n\n// `stringInputToObject`\n// Permissive string parsing. Take in a number of formats, and output an object\n// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`\nfunction stringInputToObject(color) {\n\n color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();\n var named = false;\n if (names[color]) {\n color = names[color];\n named = true;\n }\n else if (color == 'transparent') {\n return { r: 0, g: 0, b: 0, a: 0, format: \"name\" };\n }\n\n // Try to match string input using regular expressions.\n // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]\n // Just return an object and let the conversion functions handle that.\n // This way the result will be the same whether the tinycolor is initialized with string or object.\n var match;\n if ((match = matchers.rgb.exec(color))) {\n return { r: match[1], g: match[2], b: match[3] };\n }\n if ((match = matchers.rgba.exec(color))) {\n return { r: match[1], g: match[2], b: match[3], a: match[4] };\n }\n if ((match = matchers.hsl.exec(color))) {\n return { h: match[1], s: match[2], l: match[3] };\n }\n if ((match = matchers.hsla.exec(color))) {\n return { h: match[1], s: match[2], l: match[3], a: match[4] };\n }\n if ((match = matchers.hsv.exec(color))) {\n return { h: match[1], s: match[2], v: match[3] };\n }\n if ((match = matchers.hsva.exec(color))) {\n return { h: match[1], s: match[2], v: match[3], a: match[4] };\n }\n if ((match = matchers.hex8.exec(color))) {\n return {\n r: parseIntFromHex(match[1]),\n g: parseIntFromHex(match[2]),\n b: parseIntFromHex(match[3]),\n a: convertHexToDecimal(match[4]),\n format: named ? \"name\" : \"hex8\"\n };\n }\n if ((match = matchers.hex6.exec(color))) {\n return {\n r: parseIntFromHex(match[1]),\n g: parseIntFromHex(match[2]),\n b: parseIntFromHex(match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n if ((match = matchers.hex4.exec(color))) {\n return {\n r: parseIntFromHex(match[1] + '' + match[1]),\n g: parseIntFromHex(match[2] + '' + match[2]),\n b: parseIntFromHex(match[3] + '' + match[3]),\n a: convertHexToDecimal(match[4] + '' + match[4]),\n format: named ? \"name\" : \"hex8\"\n };\n }\n if ((match = matchers.hex3.exec(color))) {\n return {\n r: parseIntFromHex(match[1] + '' + match[1]),\n g: parseIntFromHex(match[2] + '' + match[2]),\n b: parseIntFromHex(match[3] + '' + match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n\n return false;\n}\n\nfunction validateWCAG2Parms(parms) {\n // return valid WCAG2 parms for isReadable.\n // If input parms are invalid, return {\"level\":\"AA\", \"size\":\"small\"}\n var level, size;\n parms = parms || {\"level\":\"AA\", \"size\":\"small\"};\n level = (parms.level || \"AA\").toUpperCase();\n size = (parms.size || \"small\").toLowerCase();\n if (level !== \"AA\" && level !== \"AAA\") {\n level = \"AA\";\n }\n if (size !== \"small\" && size !== \"large\") {\n size = \"small\";\n }\n return {\"level\":level, \"size\":size};\n}\n\n// Node: Export function\nif (typeof module !== \"undefined\" && module.exports) {\n module.exports = tinycolor;\n}\n// AMD/requirejs: Define the module\nelse if (typeof define === 'function' && define.amd) {\n define(function () {return tinycolor;});\n}\n// Browser: Expose to window\nelse {\n window.tinycolor = tinycolor;\n}\n\n})(Math);\n","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","// A change of the browser zoom change the scrollbar size.\n// Credit https://github.com/twbs/bootstrap/blob/3ffe3a5d82f6f561b82ff78d82b32a7d14aed558/js/src/modal.js#L512-L519\nexport default function getScrollbarSize() {\n var scrollDiv = document.createElement('div');\n scrollDiv.style.width = '99px';\n scrollDiv.style.height = '99px';\n scrollDiv.style.position = 'absolute';\n scrollDiv.style.top = '-9999px';\n scrollDiv.style.overflow = 'scroll';\n document.body.appendChild(scrollDiv);\n var scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth;\n document.body.removeChild(scrollDiv);\n return scrollbarSize;\n}","/**\n * Detect Element Resize.\n * https://github.com/sdecima/javascript-detect-element-resize\n * Sebastian Decima\n *\n * Forked from version 0.5.3; includes the following modifications:\n * 1) Guard against unsafe 'window' and 'document' references (to support SSR).\n * 2) Defer initialization code via a top-level function wrapper (to support SSR).\n * 3) Avoid unnecessary reflows by not measuring size for scroll events bubbling from children.\n * 4) Add nonce for style element.\n * 5) Added support for injecting custom window object\n **/\nexport default function createDetectElementResize(nonce, hostWindow) {\n // Check `document` and `window` in case of server-side rendering\n var _window;\n\n if (typeof hostWindow !== 'undefined') {\n _window = hostWindow;\n } else if (typeof window !== 'undefined') {\n _window = window;\n } else if (typeof self !== 'undefined') {\n _window = self;\n } else {\n _window = global;\n }\n\n var attachEvent = typeof _window.document !== 'undefined' && _window.document.attachEvent;\n\n if (!attachEvent) {\n var requestFrame = function () {\n var raf = _window.requestAnimationFrame || _window.mozRequestAnimationFrame || _window.webkitRequestAnimationFrame || function (fn) {\n return _window.setTimeout(fn, 20);\n };\n\n return function (fn) {\n return raf(fn);\n };\n }();\n\n var cancelFrame = function () {\n var cancel = _window.cancelAnimationFrame || _window.mozCancelAnimationFrame || _window.webkitCancelAnimationFrame || _window.clearTimeout;\n return function (id) {\n return cancel(id);\n };\n }();\n\n var resetTriggers = function resetTriggers(element) {\n var triggers = element.__resizeTriggers__,\n expand = triggers.firstElementChild,\n contract = triggers.lastElementChild,\n expandChild = expand.firstElementChild;\n contract.scrollLeft = contract.scrollWidth;\n contract.scrollTop = contract.scrollHeight;\n expandChild.style.width = expand.offsetWidth + 1 + 'px';\n expandChild.style.height = expand.offsetHeight + 1 + 'px';\n expand.scrollLeft = expand.scrollWidth;\n expand.scrollTop = expand.scrollHeight;\n };\n\n var checkTriggers = function checkTriggers(element) {\n return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height;\n };\n\n var scrollListener = function scrollListener(e) {\n // Don't measure (which forces) reflow for scrolls that happen inside of children!\n if (e.target.className && typeof e.target.className.indexOf === 'function' && e.target.className.indexOf('contract-trigger') < 0 && e.target.className.indexOf('expand-trigger') < 0) {\n return;\n }\n\n var element = this;\n resetTriggers(this);\n\n if (this.__resizeRAF__) {\n cancelFrame(this.__resizeRAF__);\n }\n\n this.__resizeRAF__ = requestFrame(function () {\n if (checkTriggers(element)) {\n element.__resizeLast__.width = element.offsetWidth;\n element.__resizeLast__.height = element.offsetHeight;\n\n element.__resizeListeners__.forEach(function (fn) {\n fn.call(element, e);\n });\n }\n });\n };\n /* Detect CSS Animations support to detect element display/re-attach */\n\n\n var animation = false,\n keyframeprefix = '',\n animationstartevent = 'animationstart',\n domPrefixes = 'Webkit Moz O ms'.split(' '),\n startEvents = 'webkitAnimationStart animationstart oAnimationStart MSAnimationStart'.split(' '),\n pfx = '';\n {\n var elm = _window.document.createElement('fakeelement');\n\n if (elm.style.animationName !== undefined) {\n animation = true;\n }\n\n if (animation === false) {\n for (var i = 0; i < domPrefixes.length; i++) {\n if (elm.style[domPrefixes[i] + 'AnimationName'] !== undefined) {\n pfx = domPrefixes[i];\n keyframeprefix = '-' + pfx.toLowerCase() + '-';\n animationstartevent = startEvents[i];\n animation = true;\n break;\n }\n }\n }\n }\n var animationName = 'resizeanim';\n var animationKeyframes = '@' + keyframeprefix + 'keyframes ' + animationName + ' { from { opacity: 0; } to { opacity: 0; } } ';\n var animationStyle = keyframeprefix + 'animation: 1ms ' + animationName + '; ';\n }\n\n var createStyles = function createStyles(doc) {\n if (!doc.getElementById('detectElementResize')) {\n //opacity:0 works around a chrome bug https://code.google.com/p/chromium/issues/detail?id=286360\n var css = (animationKeyframes ? animationKeyframes : '') + '.resize-triggers { ' + (animationStyle ? animationStyle : '') + 'visibility: hidden; opacity: 0; } ' + '.resize-triggers, .resize-triggers > div, .contract-trigger:before { content: \" \"; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; z-index: -1; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',\n head = doc.head || doc.getElementsByTagName('head')[0],\n style = doc.createElement('style');\n style.id = 'detectElementResize';\n style.type = 'text/css';\n\n if (nonce != null) {\n style.setAttribute('nonce', nonce);\n }\n\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n style.appendChild(doc.createTextNode(css));\n }\n\n head.appendChild(style);\n }\n };\n\n var addResizeListener = function addResizeListener(element, fn) {\n if (attachEvent) {\n element.attachEvent('onresize', fn);\n } else {\n if (!element.__resizeTriggers__) {\n var doc = element.ownerDocument;\n\n var elementStyle = _window.getComputedStyle(element);\n\n if (elementStyle && elementStyle.position == 'static') {\n element.style.position = 'relative';\n }\n\n createStyles(doc);\n element.__resizeLast__ = {};\n element.__resizeListeners__ = [];\n (element.__resizeTriggers__ = doc.createElement('div')).className = 'resize-triggers';\n element.__resizeTriggers__.innerHTML = '
' + '
';\n element.appendChild(element.__resizeTriggers__);\n resetTriggers(element);\n element.addEventListener('scroll', scrollListener, true);\n /* Listen for a css animation to detect element display/re-attach */\n\n if (animationstartevent) {\n element.__resizeTriggers__.__animationListener__ = function animationListener(e) {\n if (e.animationName == animationName) {\n resetTriggers(element);\n }\n };\n\n element.__resizeTriggers__.addEventListener(animationstartevent, element.__resizeTriggers__.__animationListener__);\n }\n }\n\n element.__resizeListeners__.push(fn);\n }\n };\n\n var removeResizeListener = function removeResizeListener(element, fn) {\n if (attachEvent) {\n element.detachEvent('onresize', fn);\n } else {\n element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);\n\n if (!element.__resizeListeners__.length) {\n element.removeEventListener('scroll', scrollListener, true);\n\n if (element.__resizeTriggers__.__animationListener__) {\n element.__resizeTriggers__.removeEventListener(animationstartevent, element.__resizeTriggers__.__animationListener__);\n\n element.__resizeTriggers__.__animationListener__ = null;\n }\n\n try {\n element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__);\n } catch (e) {// Preact compat; see developit/preact-compat/issues/228\n }\n }\n }\n };\n\n return {\n addResizeListener: addResizeListener,\n removeResizeListener: removeResizeListener\n };\n}","\"use strict\";\n\nexports.__esModule = true;\n\nexports.default = function (obj, keys) {\n var target = {};\n\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n\n return target;\n};","import * as React from 'react';\n/**\n * @ignore - internal component.\n */\n\nvar TableContext = React.createContext();\n\nif (process.env.NODE_ENV !== 'production') {\n TableContext.displayName = 'TableContext';\n}\n\nexport default TableContext;","import * as React from 'react';\n/**\n * @ignore - internal component.\n * @type {React.Context<{} | {expanded: boolean, disabled: boolean, toggle: () => void}>}\n */\n\nvar AccordionContext = React.createContext({});\n\nif (process.env.NODE_ENV !== 'production') {\n AccordionContext.displayName = 'AccordionContext';\n}\n\nexport default AccordionContext;","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nvar _interopRequireWildcard = require(\"@babel/runtime/helpers/interopRequireWildcard\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar React = _interopRequireWildcard(require(\"react\"));\n\nvar _createSvgIcon = _interopRequireDefault(require(\"./utils/createSvgIcon\"));\n\nvar _default = (0, _createSvgIcon.default)( /*#__PURE__*/React.createElement(\"path\", {\n d: \"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z\"\n}), 'Add');\n\nexports.default = _default;","import { isArray, isString, isObject } from 'vega-util';\n\nvar name = \"vega-tooltip\";\nvar version$1 = \"0.27.0\";\nvar description = \"A tooltip plugin for Vega-Lite and Vega visualizations.\";\nvar keywords = [\n\t\"vega-lite\",\n\t\"vega\",\n\t\"tooltip\"\n];\nvar repository = {\n\ttype: \"git\",\n\turl: \"https://github.com/vega/vega-tooltip.git\"\n};\nvar author = {\n\tname: \"UW Interactive Data Lab\",\n\turl: \"https://idl.cs.washington.edu\"\n};\nvar collaborators = [\n\t\"Dominik Moritz\",\n\t\"Sira Horradarn\",\n\t\"Zening Qu\",\n\t\"Kanit Wongsuphasawat\",\n\t\"Yuri Astrakhan\",\n\t\"Jeffrey Heer\"\n];\nvar license = \"BSD-3-Clause\";\nvar bugs = {\n\turl: \"https://github.com/vega/vega-tooltip/issues\"\n};\nvar homepage = \"https://github.com/vega/vega-tooltip#readme\";\nvar main = \"build/vega-tooltip.js\";\nvar module = \"build/vega-tooltip.module.js\";\nvar unpkg = \"build/vega-tooltip.min.js\";\nvar jsdelivr = \"build/vega-tooltip.min.js\";\nvar types = \"build/vega-tooltip.module.d.ts\";\nvar files = [\n\t\"src\",\n\t\"build\",\n\t\"types\"\n];\nvar scripts = {\n\tprebuild: \"yarn clean && yarn build:style\",\n\tbuild: \"rollup -c\",\n\t\"build:style\": \"./build-style.sh\",\n\tclean: \"rimraf build && rimraf src/style.ts\",\n\t\"copy:data\": \"rsync -r node_modules/vega-datasets/data/* examples/data\",\n\t\"copy:build\": \"rsync -r build/* examples/build\",\n\t\"deploy:gh\": \"yarn build && yarn copy:build && gh-pages -d examples && yarn clean\",\n\tprepublishOnly: \"yarn clean && yarn build\",\n\tpreversion: \"yarn lint && yarn test\",\n\tserve: \"browser-sync start -s -f build examples --serveStatic examples\",\n\tstart: \"yarn build && concurrently --kill-others -n Server,Rollup 'yarn serve' 'rollup -c -w'\",\n\tpretest: \"yarn build:style\",\n\ttest: \"beemo jest\",\n\t\"test:inspect\": \"node --inspect-brk ./node_modules/.bin/jest --runInBand\",\n\tprepare: \"beemo create-config && yarn copy:data\",\n\tprettierbase: \"beemo prettier '*.{css,scss,html}'\",\n\teslintbase: \"beemo eslint .\",\n\tformat: \"yarn eslintbase --fix && yarn prettierbase --write\",\n\tlint: \"yarn eslintbase && yarn prettierbase --check\",\n\trelease: \"yarn run prebuild && yarn build && auto shipit\"\n};\nvar devDependencies = {\n\t\"@auto-it/conventional-commits\": \"^10.30.0\",\n\t\"@auto-it/first-time-contributor\": \"^10.30.0\",\n\t\"@rollup/plugin-json\": \"^4.1.0\",\n\t\"@rollup/plugin-node-resolve\": \"^13.0.0\",\n\t\"@wessberg/rollup-plugin-ts\": \"^1.3.8\",\n\tauto: \"^10.30.0\",\n\t\"browser-sync\": \"^2.26.14\",\n\tconcurrently: \"^6.0.0\",\n\t\"gh-pages\": \"^3.1.0\",\n\t\"node-sass\": \"^6.0.0\",\n\tpath: \"^0.12.7\",\n\trollup: \"^2.39.1\",\n\t\"rollup-plugin-bundle-size\": \"^1.0.3\",\n\t\"rollup-plugin-terser\": \"^7.0.2\",\n\ttypescript: \"~4.3.2\",\n\t\"vega-datasets\": \"^2.2.0\",\n\t\"vega-lite-dev-config\": \"^0.18.0\",\n\t\"vega-typings\": \"^0.21.0\"\n};\nvar dependencies = {\n\t\"vega-util\": \"^1.16.0\"\n};\nvar pkg = {\n\tname: name,\n\tversion: version$1,\n\tdescription: description,\n\tkeywords: keywords,\n\trepository: repository,\n\tauthor: author,\n\tcollaborators: collaborators,\n\tlicense: license,\n\tbugs: bugs,\n\thomepage: homepage,\n\tmain: main,\n\tmodule: module,\n\tunpkg: unpkg,\n\tjsdelivr: jsdelivr,\n\ttypes: types,\n\tfiles: files,\n\tscripts: scripts,\n\tdevDependencies: devDependencies,\n\tdependencies: dependencies\n};\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\n\n/**\n * Format the value to be shown in the tooltip.\n *\n * @param value The value to show in the tooltip.\n * @param valueToHtml Function to convert a single cell value to an HTML string\n */\nfunction formatValue(value, valueToHtml, maxDepth) {\n if (isArray(value)) {\n return `[${value.map((v) => valueToHtml(isString(v) ? v : stringify(v, maxDepth))).join(', ')}]`;\n }\n if (isObject(value)) {\n let content = '';\n const _a = value, { title, image } = _a, rest = __rest(_a, [\"title\", \"image\"]);\n if (title) {\n content += `

${valueToHtml(title)}

`;\n }\n if (image) {\n content += ``;\n }\n const keys = Object.keys(rest);\n if (keys.length > 0) {\n content += '';\n for (const key of keys) {\n let val = rest[key];\n // ignore undefined properties\n if (val === undefined) {\n continue;\n }\n if (isObject(val)) {\n val = stringify(val, maxDepth);\n }\n content += ``;\n }\n content += `
${valueToHtml(key)}:${valueToHtml(val)}
`;\n }\n return content || '{}'; // show empty object if there are no properties\n }\n return valueToHtml(value);\n}\nfunction replacer(maxDepth) {\n const stack = [];\n return function (key, value) {\n if (typeof value !== 'object' || value === null) {\n return value;\n }\n const pos = stack.indexOf(this) + 1;\n stack.length = pos;\n if (stack.length > maxDepth) {\n return '[Object]';\n }\n if (stack.indexOf(value) >= 0) {\n return '[Circular]';\n }\n stack.push(value);\n return value;\n };\n}\n/**\n * Stringify any JS object to valid JSON\n */\nfunction stringify(obj, maxDepth) {\n return JSON.stringify(obj, replacer(maxDepth));\n}\n\n// generated with build-style.sh\nvar defaultStyle = `#vg-tooltip-element {\n visibility: hidden;\n padding: 8px;\n position: fixed;\n z-index: 1000;\n font-family: sans-serif;\n font-size: 11px;\n border-radius: 3px;\n box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);\n /* The default theme is the light theme. */\n background-color: rgba(255, 255, 255, 0.95);\n border: 1px solid #d9d9d9;\n color: black; }\n #vg-tooltip-element.visible {\n visibility: visible; }\n #vg-tooltip-element h2 {\n margin-top: 0;\n margin-bottom: 10px;\n font-size: 13px; }\n #vg-tooltip-element img {\n max-width: 200px;\n max-height: 200px; }\n #vg-tooltip-element table {\n border-spacing: 0; }\n #vg-tooltip-element table tr {\n border: none; }\n #vg-tooltip-element table tr td {\n overflow: hidden;\n text-overflow: ellipsis;\n padding-top: 2px;\n padding-bottom: 2px; }\n #vg-tooltip-element table tr td.key {\n color: #808080;\n max-width: 150px;\n text-align: right;\n padding-right: 4px; }\n #vg-tooltip-element table tr td.value {\n display: block;\n max-width: 300px;\n max-height: 7em;\n text-align: left; }\n #vg-tooltip-element.dark-theme {\n background-color: rgba(32, 32, 32, 0.9);\n border: 1px solid #f5f5f5;\n color: white; }\n #vg-tooltip-element.dark-theme td.key {\n color: #bfbfbf; }\n`;\n\nconst EL_ID = 'vg-tooltip-element';\nconst DEFAULT_OPTIONS = {\n /**\n * X offset.\n */\n offsetX: 10,\n /**\n * Y offset.\n */\n offsetY: 10,\n /**\n * ID of the tooltip element.\n */\n id: EL_ID,\n /**\n * ID of the tooltip CSS style.\n */\n styleId: 'vega-tooltip-style',\n /**\n * The name of the theme. You can use the CSS class called [THEME]-theme to style the tooltips.\n *\n * There are two predefined themes: \"light\" (default) and \"dark\".\n */\n theme: 'light',\n /**\n * Do not use the default styles provided by Vega Tooltip. If you enable this option, you need to use your own styles. It is not necessary to disable the default style when using a custom theme.\n */\n disableDefaultStyle: false,\n /**\n * HTML sanitizer function that removes dangerous HTML to prevent XSS.\n *\n * This should be a function from string to string. You may replace it with a formatter such as a markdown formatter.\n */\n sanitize: escapeHTML,\n /**\n * The maximum recursion depth when printing objects in the tooltip.\n */\n maxDepth: 2,\n /**\n * A function to customize the rendered HTML of the tooltip.\n * @param value A value string, or object of value strings keyed by field\n * @param sanitize The `sanitize` function from `options.sanitize`\n * @returns {string} The returned string will become the `innerHTML` of the tooltip element\n */\n formatTooltip: formatValue,\n};\n/**\n * Escape special HTML characters.\n *\n * @param value A value to convert to string and HTML-escape.\n */\nfunction escapeHTML(value) {\n return String(value).replace(/&/g, '&').replace(/ window.innerWidth) {\n x = +event.clientX - offsetX - tooltipBox.width;\n }\n let y = event.clientY + offsetY;\n if (y + tooltipBox.height > window.innerHeight) {\n y = +event.clientY - offsetY - tooltipBox.height;\n }\n return { x, y };\n}\n\n/**\n * The tooltip handler class.\n */\nclass Handler {\n /**\n * Create the tooltip handler and initialize the element and style.\n *\n * @param options Tooltip Options\n */\n constructor(options) {\n this.options = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);\n const elementId = this.options.id;\n this.el = null;\n // bind this to call\n this.call = this.tooltipHandler.bind(this);\n // prepend a default stylesheet for tooltips to the head\n if (!this.options.disableDefaultStyle && !document.getElementById(this.options.styleId)) {\n const style = document.createElement('style');\n style.setAttribute('id', this.options.styleId);\n style.innerHTML = createDefaultStyle(elementId);\n const head = document.head;\n if (head.childNodes.length > 0) {\n head.insertBefore(style, head.childNodes[0]);\n }\n else {\n head.appendChild(style);\n }\n }\n }\n /**\n * The tooltip handler function.\n */\n tooltipHandler(handler, event, item, value) {\n // console.log(handler, event, item, value);\n var _a;\n // append a div element that we use as a tooltip unless it already exists\n this.el = document.getElementById(this.options.id);\n if (!this.el) {\n this.el = document.createElement('div');\n this.el.setAttribute('id', this.options.id);\n this.el.classList.add('vg-tooltip');\n document.body.appendChild(this.el);\n }\n const tooltipContainer = (_a = document.fullscreenElement) !== null && _a !== void 0 ? _a : document.body;\n tooltipContainer.appendChild(this.el);\n // hide tooltip for null, undefined, or empty string values\n if (value == null || value === '') {\n this.el.classList.remove('visible', `${this.options.theme}-theme`);\n return;\n }\n // set the tooltip content\n this.el.innerHTML = this.options.formatTooltip(value, this.options.sanitize, this.options.maxDepth);\n // make the tooltip visible\n this.el.classList.add('visible', `${this.options.theme}-theme`);\n const { x, y } = calculatePosition(event, this.el.getBoundingClientRect(), this.options.offsetX, this.options.offsetY);\n this.el.setAttribute('style', `top: ${y}px; left: ${x}px`);\n }\n}\n\nconst version = pkg.version;\n/**\n * Create a tooltip handler and register it with the provided view.\n *\n * @param view The Vega view.\n * @param opt Tooltip options.\n */\nfunction index (view, opt) {\n const handler = new Handler(opt);\n view.tooltip(handler.call).run();\n return handler;\n}\n\nexport { DEFAULT_OPTIONS, Handler, calculatePosition, createDefaultStyle, index as default, escapeHTML, formatValue, replacer, stringify, version };\n","import type {Loader, LoaderOptions} from '@loaders.gl/loader-utils';\nimport type {DracoParseOptions} from './lib/draco-parser';\n// import type {DracoMeshData} from './types';\nimport {VERSION} from './lib/utils/version';\n\nexport type DracoLoaderOptions = LoaderOptions & {\n draco?: DracoParseOptions & {\n decoderType?: 'wasm' | 'js';\n libraryPath?: string;\n extraAttributes?;\n attributeNameEntry?: string;\n };\n};\n\nconst DEFAULT_DRACO_OPTIONS: DracoLoaderOptions = {\n draco: {\n decoderType: typeof WebAssembly === 'object' ? 'wasm' : 'js', // 'js' for IE11\n libraryPath: 'libs/',\n extraAttributes: {},\n attributeNameEntry: undefined\n }\n};\n\n/**\n * Worker loader for Draco3D compressed geometries\n */\nexport const DracoLoader = {\n name: 'Draco',\n id: 'draco',\n module: 'draco',\n version: VERSION,\n worker: true,\n extensions: ['drc'],\n mimeTypes: ['application/octet-stream'],\n binary: true,\n tests: ['DRACO'],\n options: DEFAULT_DRACO_OPTIONS\n};\n\nexport const _TypecheckDracoLoader: Loader = DracoLoader;\n","// Version constant cannot be imported, it needs to correspond to the build version of **this** module.\n// __VERSION__ is injected by babel-plugin-version-inline\n// @ts-ignore TS2304: Cannot find name '__VERSION__'.\nexport const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest';\n","// Mesh category utilities\n// TODO - move to mesh category module, or to math.gl/geometry module\nimport {TypedArray} from '../../types';\n\ntype Attribute = {\n size?: number;\n type?: number;\n normalized?: boolean;\n value: TypedArray;\n};\n\ntype TypedArrays = {[key: string]: TypedArray};\nexport type Attributes = {[key: string]: Attribute};\n\n/**\n * Holds an axis aligned bounding box\n * TODO - make sure AxisAlignedBoundingBox in math.gl/culling understands this format (or change this format)\n */\ntype BoundingBox = [[number, number, number], [number, number, number]];\n\n/**\n * Get number of vertices in mesh\n * @param attributes\n */\nexport function getMeshSize(attributes: TypedArrays): number {\n let size = 0;\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n if (ArrayBuffer.isView(attribute)) {\n // @ts-ignore DataView doesn't have BYTES_PER_ELEMENT\n size += attribute.byteLength * attribute.BYTES_PER_ELEMENT;\n }\n }\n return size;\n}\n\n/**\n * Get the (axis aligned) bounding box of a mesh\n * @param attributes\n * @returns array of two vectors representing the axis aligned bounding box\n */\n// eslint-disable-next-line complexity\nexport function getMeshBoundingBox(attributes: Attributes): BoundingBox {\n let minX = Infinity;\n let minY = Infinity;\n let minZ = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n let maxZ = -Infinity;\n\n const positions = attributes.POSITION ? attributes.POSITION.value : [];\n const len = positions && positions.length;\n\n for (let i = 0; i < len; i += 3) {\n const x = positions[i];\n const y = positions[i + 1];\n const z = positions[i + 2];\n\n minX = x < minX ? x : minX;\n minY = y < minY ? y : minY;\n minZ = z < minZ ? z : minZ;\n\n maxX = x > maxX ? x : maxX;\n maxY = y > maxY ? y : maxY;\n maxZ = z > maxZ ? z : maxZ;\n }\n return [\n [minX, minY, minZ],\n [maxX, maxY, maxZ]\n ];\n}\n","import {assert} from '../../utils/assert';\nimport Field from './field';\n\nexport type SchemaMetadata = Map;\n\n/**\n * ArrowJS `Schema` API-compatible class for row-based tables (returned from `DataTable`)\n * https://loaders.gl/arrowjs/docs/api-reference/schema\n */\nexport default class Schema {\n fields: Field[];\n // TODO - Arrow just allows Map\n metadata: SchemaMetadata;\n\n constructor(fields: Field[], metadata?: SchemaMetadata) {\n assert(Array.isArray(fields));\n checkNames(fields);\n // For kepler fields, create arrow compatible `Fields` that have kepler fields as `metadata`\n this.fields = fields;\n this.metadata = metadata || new Map();\n }\n\n // TODO - arrow only seems to compare fields, not metadata\n compareTo(other: Schema): boolean {\n if (this.metadata !== other.metadata) {\n return false;\n }\n if (this.fields.length !== other.fields.length) {\n return false;\n }\n for (let i = 0; i < this.fields.length; ++i) {\n if (!this.fields[i].compareTo(other.fields[i])) {\n return false;\n }\n }\n return true;\n }\n\n select(...columnNames: string[]): Schema {\n // Ensure column names reference valid fields\n const nameMap = Object.create(null);\n for (const name of columnNames) {\n nameMap[name] = true;\n }\n const selectedFields = this.fields.filter((field) => nameMap[field.name]);\n return new Schema(selectedFields, this.metadata);\n }\n\n selectAt(...columnIndices: number[]): Schema {\n // Ensure column indices reference valid fields\n const selectedFields = columnIndices.map((index) => this.fields[index]).filter(Boolean);\n return new Schema(selectedFields, this.metadata);\n }\n\n assign(schemaOrFields: Schema | Field[]): Schema {\n let fields: Field[];\n let metadata: SchemaMetadata = this.metadata;\n\n if (schemaOrFields instanceof Schema) {\n const otherSchema = schemaOrFields;\n fields = otherSchema.fields;\n metadata = mergeMaps(mergeMaps(new Map(), this.metadata), otherSchema.metadata);\n } else {\n fields = schemaOrFields;\n }\n\n // Create a merged list of fields, overwrite fields in place, new fields at end\n const fieldMap: {[key: string]: Field} = Object.create(null);\n\n for (const field of this.fields) {\n fieldMap[field.name] = field;\n }\n\n for (const field of fields) {\n fieldMap[field.name] = field;\n }\n\n const mergedFields = Object.values(fieldMap);\n\n return new Schema(mergedFields, metadata);\n }\n}\n\n// Warn if any duplicated field names\nfunction checkNames(fields) {\n const usedNames = {};\n for (const field of fields) {\n if (usedNames[field.name]) {\n // eslint-disable-next-line\n console.warn('Schema: duplicated field name', field.name, field);\n }\n usedNames[field.name] = true;\n }\n}\n\nfunction mergeMaps(m1: T, m2: T): T {\n // @ts-ignore\n return new Map([...(m1 || new Map()), ...(m2 || new Map())]);\n}\n","// Replacement for the external assert method to reduce bundle size\n// Note: We don't use the second \"message\" argument in calling code,\n// so no need to support it here\nexport function assert(condition: boolean, message?: string) {\n if (!condition) {\n throw new Error(message || 'loader assertion failed.');\n }\n}\n","// This code is adapted from ArrowJS https://github.com/apache/arrow\n// under Apache license http://www.apache.org/licenses/LICENSE-2.0\n\n/**\n * Main data type enumeration.\n *\n * Data types in this library are all *logical*. They can be expressed as\n * either a primitive physical type (bytes or bits of some fixed size), a\n * nested type consisting of other data types, or another data type (e.g. a\n * timestamp encoded as an int64).\n *\n * **Note**: Only enum values 0-17 (NONE through Map) are written to an Arrow\n * IPC payload.\n *\n * The rest of the values are specified here so TypeScript can narrow the type\n * signatures further beyond the base Arrow Types. The Arrow DataTypes include\n * metadata like `bitWidth` that impact the type signatures of the values we\n * accept and return.\n *\n * For example, the `Int8Vector` reads 1-byte numbers from an `Int8Array`, an\n * `Int32Vector` reads a 4-byte number from an `Int32Array`, and an `Int64Vector`\n * reads a pair of 4-byte lo, hi 32-bit integers as a zero-copy slice from the\n * underlying `Int32Array`.\n *\n * Library consumers benefit by knowing the narrowest type, since we can ensure\n * the types across all public methods are propagated, and never bail to `any`.\n * These values are _never_ used at runtime, and they will _never_ be written\n * to the flatbuffers metadata of serialized Arrow IPC payloads.\n */\nexport enum Type {\n /** The default placeholder type */\n NONE = 0,\n /** A NULL type having no physical storage */\n Null = 1,\n /** Signed or unsigned 8, 16, 32, or 64-bit little-endian integer */\n Int = 2,\n /** 2, 4, or 8-byte floating point value */\n Float = 3,\n /** Variable-length bytes (no guarantee of UTF8-ness) */\n Binary = 4,\n /** UTF8 variable-length string as List */\n Utf8 = 5,\n /** Boolean as 1 bit, LSB bit-packed ordering */\n Bool = 6,\n /** Precision-and-scale-based decimal type. Storage type depends on the parameters. */\n Decimal = 7,\n /** int32_t days or int64_t milliseconds since the UNIX epoch */\n Date = 8,\n /** Time as signed 32 or 64-bit integer, representing either seconds, milliseconds, microseconds, or nanoseconds since midnight since midnight */\n Time = 9,\n /** Exact timestamp encoded with int64 since UNIX epoch (Default unit millisecond) */\n Timestamp = 10,\n /** YEAR_MONTH or DAY_TIME interval in SQL style */\n Interval = 11,\n /** A list of some logical data type */\n List = 12,\n /** Struct of logical types */\n Struct = 13,\n /** Union of logical types */\n Union = 14,\n /** Fixed-size binary. Each value occupies the same number of bytes */\n FixedSizeBinary = 15,\n /** Fixed-size list. Each value occupies the same number of bytes */\n FixedSizeList = 16,\n /** Map of named logical types */\n Map = 17,\n\n /** Dictionary aka Category type */\n Dictionary = -1,\n Int8 = -2,\n Int16 = -3,\n Int32 = -4,\n Int64 = -5,\n Uint8 = -6,\n Uint16 = -7,\n Uint32 = -8,\n Uint64 = -9,\n Float16 = -10,\n Float32 = -11,\n Float64 = -12,\n DateDay = -13,\n DateMillisecond = -14,\n TimestampSecond = -15,\n TimestampMillisecond = -16,\n TimestampMicrosecond = -17,\n TimestampNanosecond = -18,\n TimeSecond = -19,\n TimeMillisecond = -20,\n TimeMicrosecond = -21,\n TimeNanosecond = -22,\n DenseUnion = -23,\n SparseUnion = -24,\n IntervalDayTime = -25,\n IntervalYearMonth = -26\n}\n","// This code is adapted from ArrowJS https://github.com/apache/arrow\n// under Apache license http://www.apache.org/licenses/LICENSE-2.0\n\nimport {Type} from './enum';\n\nimport Field from './field';\n\nexport {Type} from './enum';\n\nexport type TypedIntArray =\n | Int8Array\n | Uint8Array\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Int32Array\n | Uint32Array\n | Uint8ClampedArray;\n\nexport type TypedFloatArray = Float32Array | Float64Array;\n\nexport type TypedArray = TypedIntArray | TypedFloatArray;\n\nexport type AnyArrayType = Array | TypedIntArray | TypedFloatArray;\n\nexport class DataType {\n static isNull(x: any): boolean {\n return x && x.typeId === Type.Null;\n }\n static isInt(x: any): boolean {\n return x && x.typeId === Type.Int;\n }\n static isFloat(x: any): boolean {\n return x && x.typeId === Type.Float;\n }\n static isBinary(x: any): boolean {\n return x && x.typeId === Type.Binary;\n }\n static isUtf8(x: any): boolean {\n return x && x.typeId === Type.Utf8;\n }\n static isBool(x: any): boolean {\n return x && x.typeId === Type.Bool;\n }\n static isDecimal(x: any): boolean {\n return x && x.typeId === Type.Decimal;\n }\n static isDate(x: any): boolean {\n return x && x.typeId === Type.Date;\n }\n static isTime(x: any): boolean {\n return x && x.typeId === Type.Time;\n }\n static isTimestamp(x: any): boolean {\n return x && x.typeId === Type.Timestamp;\n }\n static isInterval(x: any): boolean {\n return x && x.typeId === Type.Interval;\n }\n static isList(x: any): boolean {\n return x && x.typeId === Type.List;\n }\n static isStruct(x: any): boolean {\n return x && x.typeId === Type.Struct;\n }\n static isUnion(x: any): boolean {\n return x && x.typeId === Type.Union;\n }\n static isFixedSizeBinary(x: any): boolean {\n return x && x.typeId === Type.FixedSizeBinary;\n }\n static isFixedSizeList(x: any): boolean {\n return x && x.typeId === Type.FixedSizeList;\n }\n static isMap(x: any): boolean {\n return x && x.typeId === Type.Map;\n }\n static isDictionary(x: any): boolean {\n return x && x.typeId === Type.Dictionary;\n }\n\n get typeId(): Type {\n return Type.NONE;\n }\n\n // get ArrayType(): AnyArrayType {\n // return Int8Array;\n // }\n\n // get ArrayType() { return Array; }\n compareTo(other: DataType): boolean {\n // TODO\n return this === other; // comparer.visit(this, other);\n }\n}\n\n// NULL\n\nexport class Null extends DataType {\n get typeId(): Type {\n return Type.Null;\n }\n get [Symbol.toStringTag](): string {\n return 'Null';\n }\n toString(): string {\n return 'Null';\n }\n}\n\n// BOOLEANS\n\nexport class Bool extends DataType {\n get typeId(): Type {\n return Type.Bool;\n }\n // get ArrayType() {\n // return Uint8Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Bool';\n }\n toString(): string {\n return 'Bool';\n }\n}\n\n// INTS\n\nexport class Int extends DataType {\n readonly isSigned: boolean;\n readonly bitWidth: number;\n constructor(isSigned, bitWidth) {\n super();\n this.isSigned = isSigned;\n this.bitWidth = bitWidth;\n }\n get typeId(): Type {\n return Type.Int;\n }\n // get ArrayType() {\n // switch (this.bitWidth) {\n // case 8:\n // return this.isSigned ? Int8Array : Uint8Array;\n // case 16:\n // return this.isSigned ? Int16Array : Uint16Array;\n // case 32:\n // return this.isSigned ? Int32Array : Uint32Array;\n // case 64:\n // return this.isSigned ? Int32Array : Uint32Array;\n // default:\n // throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);\n // }\n // }\n get [Symbol.toStringTag](): string {\n return 'Int';\n }\n toString(): string {\n return `${this.isSigned ? 'I' : 'Ui'}nt${this.bitWidth}`;\n }\n}\n\nexport class Int8 extends Int {\n constructor() {\n super(true, 8);\n }\n}\nexport class Int16 extends Int {\n constructor() {\n super(true, 16);\n }\n}\nexport class Int32 extends Int {\n constructor() {\n super(true, 32);\n }\n}\nexport class Int64 extends Int {\n constructor() {\n super(true, 64);\n }\n}\nexport class Uint8 extends Int {\n constructor() {\n super(false, 8);\n }\n}\nexport class Uint16 extends Int {\n constructor() {\n super(false, 16);\n }\n}\nexport class Uint32 extends Int {\n constructor() {\n super(false, 32);\n }\n}\nexport class Uint64 extends Int {\n constructor() {\n super(false, 64);\n }\n}\n\n// FLOATS\n\nconst Precision = {\n HALF: 16,\n SINGLE: 32,\n DOUBLE: 64\n};\n\nexport class Float extends DataType {\n readonly precision: number;\n constructor(precision) {\n super();\n this.precision = precision;\n }\n get typeId(): Type {\n return Type.Float;\n }\n // get ArrayType() {\n // switch (this.precision) {\n // case Precision.HALF:\n // return Uint16Array;\n // case Precision.SINGLE:\n // return Float32Array;\n // case Precision.DOUBLE:\n // return Float64Array;\n // default:\n // throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`);\n // }\n // }\n get [Symbol.toStringTag](): string {\n return 'Float';\n }\n toString(): string {\n return `Float${this.precision}`;\n }\n}\n\nexport class Float16 extends Float {\n constructor() {\n super(Precision.HALF);\n }\n}\nexport class Float32 extends Float {\n constructor() {\n super(Precision.SINGLE);\n }\n}\nexport class Float64 extends Float {\n constructor() {\n super(Precision.DOUBLE);\n }\n}\n\nexport class Binary extends DataType {\n constructor() {\n super();\n }\n get typeId() {\n return Type.Binary;\n }\n toString() {\n return 'Binary';\n }\n get [Symbol.toStringTag]() {\n return 'Binary';\n }\n}\n\n// STRINGS\n\nexport class Utf8 extends DataType {\n get typeId(): Type {\n return Type.Utf8;\n }\n // get ArrayType() {\n // return Uint8Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Utf8';\n }\n toString(): string {\n return 'Utf8';\n }\n}\n\n// DATES, TIMES AND INTERVALS\n\nconst DateUnit = {\n DAY: 0,\n MILLISECOND: 1\n};\n\nexport class Date extends DataType {\n readonly unit: number;\n constructor(unit) {\n super();\n this.unit = unit;\n }\n get typeId(): Type {\n return Type.Date;\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Date';\n }\n toString(): string {\n return `Date${(this.unit + 1) * 32}<${DateUnit[this.unit]}>`;\n }\n}\n\nexport class DateDay extends Date {\n constructor() {\n super(DateUnit.DAY);\n }\n}\nexport class DateMillisecond extends Date {\n constructor() {\n super(DateUnit.MILLISECOND);\n }\n}\n\nconst TimeUnit = {\n SECOND: 1,\n MILLISECOND: 1e3,\n MICROSECOND: 1e6,\n NANOSECOND: 1e9\n};\n\nexport class Time extends DataType {\n readonly unit: number;\n readonly bitWidth: number;\n\n constructor(unit, bitWidth) {\n super();\n this.unit = unit;\n this.bitWidth = bitWidth;\n }\n get typeId(): Type {\n return Type.Time;\n }\n toString(): string {\n return `Time${this.bitWidth}<${TimeUnit[this.unit]}>`;\n }\n get [Symbol.toStringTag](): string {\n return 'Time';\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n}\n\nexport class TimeSecond extends Time {\n constructor() {\n super(TimeUnit.SECOND, 32);\n }\n}\nexport class TimeMillisecond extends Time {\n constructor() {\n super(TimeUnit.MILLISECOND, 32);\n }\n}\n// export class TimeMicrosecond extends Time { constructor() { super(TimeUnit.MICROSECOND, 64); } }\n// export class TimeNanosecond extends Time { constructor() { super(TimeUnit.NANOSECOND, 64); } }\n\nexport class Timestamp extends DataType {\n readonly unit: any;\n readonly timezone: any;\n\n constructor(unit: any, timezone = null) {\n super();\n this.unit = unit;\n this.timezone = timezone;\n }\n get typeId(): Type {\n return Type.Timestamp;\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Timestamp';\n }\n toString(): string {\n return `Timestamp<${TimeUnit[this.unit]}${this.timezone ? `, ${this.timezone}` : ''}>`;\n }\n}\n\nexport class TimestampSecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.SECOND, timezone);\n }\n}\nexport class TimestampMillisecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.MILLISECOND, timezone);\n }\n}\nexport class TimestampMicrosecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.MICROSECOND, timezone);\n }\n}\nexport class TimestampNanosecond extends Timestamp {\n constructor(timezone = null) {\n super(TimeUnit.NANOSECOND, timezone);\n }\n}\n\nconst IntervalUnit = {\n DAY_TIME: 0,\n YEAR_MONTH: 1\n};\n\nexport class Interval extends DataType {\n readonly unit: number;\n constructor(unit: number) {\n super();\n this.unit = unit;\n }\n get typeId(): Type {\n return Type.Interval;\n }\n // get ArrayType() {\n // return Int32Array;\n // }\n get [Symbol.toStringTag](): string {\n return 'Interval';\n }\n toString(): string {\n return `Interval<${IntervalUnit[this.unit]}>`;\n }\n}\n\nexport class IntervalDayTime extends Interval {\n constructor() {\n super(IntervalUnit.DAY_TIME);\n }\n}\nexport class IntervalYearMonth extends Interval {\n constructor() {\n super(IntervalUnit.YEAR_MONTH);\n }\n}\n\nexport class FixedSizeList extends DataType {\n readonly listSize: number;\n readonly children: Field[];\n\n constructor(listSize: number, child: Field) {\n super();\n this.listSize = listSize;\n this.children = [child];\n }\n get typeId(): Type {\n return Type.FixedSizeList;\n }\n get valueType() {\n return this.children[0].type;\n }\n get valueField() {\n return this.children[0];\n }\n // get ArrayType() {\n // return this.valueType.ArrayType;\n // }\n get [Symbol.toStringTag](): string {\n return 'FixedSizeList';\n }\n toString(): string {\n return `FixedSizeList[${this.listSize}]<${this.valueType}>`;\n }\n}\n","import {DataType} from './type';\n\n/**\n * ArrowJS `Field` API-compatible class for row-based tables\n * https://loaders.gl/arrowjs/docs/api-reference/field\n * A field holds name, nullable, and metadata information about a table \"column\"\n * A Schema is essentially a list of fields\n */\nexport default class Field {\n name: string;\n type: DataType;\n nullable: boolean;\n metadata: Map;\n\n constructor(\n name: string,\n type: DataType,\n nullable = false,\n metadata: Map = new Map()\n ) {\n this.name = name;\n this.type = type;\n this.nullable = nullable;\n this.metadata = metadata;\n }\n\n get typeId(): number {\n return this.type && this.type.typeId;\n }\n\n clone(): Field {\n return new Field(this.name, this.type, this.nullable, this.metadata);\n }\n\n compareTo(other: this): boolean {\n return (\n this.name === other.name &&\n this.type === other.type &&\n this.nullable === other.nullable &&\n this.metadata === other.metadata\n );\n }\n\n toString(): string {\n return `${this.type}${this.nullable ? ', nullable' : ''}${\n this.metadata ? `, metadata: ${this.metadata}` : ''\n }`;\n }\n}\n","import {Schema, Field, FixedSizeList, getArrowTypeFromTypedArray} from '@loaders.gl/schema';\n\nimport {MeshAttribute, DracoAttribute, DracoLoaderData, DracoMetadataEntry} from '../draco-types';\n\nexport function makeSchemaFromAttributes(\n attributes: {[attributeName: string]: MeshAttribute},\n loaderData: DracoLoaderData,\n indices?: MeshAttribute\n): Schema {\n const metadataMap = makeMetadata(loaderData.metadata);\n const fields: Field[] = [];\n const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);\n for (const attributeName in attributes) {\n const attribute = attributes[attributeName];\n const field = getArrowFieldFromAttribute(\n attributeName,\n attribute,\n namedLoaderDataAttributes[attributeName]\n );\n fields.push(field);\n }\n if (indices) {\n const indicesField = getArrowFieldFromAttribute('indices', indices);\n fields.push(indicesField);\n }\n return new Schema(fields, metadataMap);\n}\n\nfunction transformAttributesLoaderData(loaderData: {[key: number]: DracoAttribute}): {\n [attributeName: string]: DracoAttribute;\n} {\n const result: {[attributeName: string]: DracoAttribute} = {};\n for (const key in loaderData) {\n const dracoAttribute = loaderData[key];\n result[dracoAttribute.name || 'undefined'] = dracoAttribute;\n }\n return result;\n}\n\nfunction getArrowFieldFromAttribute(\n attributeName: string,\n attribute: MeshAttribute,\n loaderData?: DracoAttribute\n): Field {\n const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : undefined;\n const type = getArrowTypeFromTypedArray(attribute.value);\n return new Field(\n attributeName,\n new FixedSizeList(attribute.size, new Field('value', type)),\n false,\n metadataMap\n );\n}\n\nfunction makeMetadata(metadata: {[key: string]: DracoMetadataEntry}): Map {\n const metadataMap = new Map();\n for (const key in metadata) {\n metadataMap.set(`${key}.string`, JSON.stringify(metadata[key]));\n }\n\n return metadataMap;\n}\n","import type {TypedArray} from '../../types';\nimport {DataType, Float32, Float64, Int16, Int32, Int8, Uint16, Uint32, Uint8} from '../schema';\n\nexport function getArrowTypeFromTypedArray(array: TypedArray): DataType {\n switch (array.constructor) {\n case Int8Array:\n return new Int8();\n case Uint8Array:\n return new Uint8();\n case Int16Array:\n return new Int16();\n case Uint16Array:\n return new Uint16();\n case Int32Array:\n return new Int32();\n case Uint32Array:\n return new Uint32();\n case Float32Array:\n return new Float32();\n case Float64Array:\n return new Float64();\n default:\n throw new Error('array type not supported');\n }\n}\n","/* eslint-disable camelcase */\n\n// Draco types (input)\nimport type {\n Draco3D,\n Decoder,\n Mesh,\n PointCloud,\n PointAttribute,\n Metadata,\n MetadataQuerier,\n DracoInt32Array,\n draco_DataType\n} from '../draco3d/draco3d-types';\n\n// Parsed data types (output)\nimport type {\n TypedArray,\n // standard mesh output data\n MeshData,\n MeshAttribute,\n // standard mesh with draco metadata\n DracoMeshData,\n DracoLoaderData,\n DracoAttribute,\n DracoMetadataEntry,\n DracoQuantizationTransform,\n DracoOctahedronTransform\n} from './draco-types';\n\nimport {getMeshBoundingBox} from '@loaders.gl/schema';\nimport {makeSchemaFromAttributes} from './utils/schema-attribute-utils';\n\n/**\n * @param topology - How triangle indices should be generated (mesh only)\n * @param attributeNameEntry\n * @param extraAttributes\n * @param quantizedAttributes\n * @param octahedronAttributes\n */\nexport type DracoParseOptions = {\n topology?: 'triangle-list' | 'triangle-strip';\n attributeNameEntry?: string;\n extraAttributes?: {[uniqueId: string]: number};\n quantizedAttributes?: ('POSITION' | 'NORMAL' | 'COLOR' | 'TEX_COORD' | 'GENERIC')[];\n octahedronAttributes?: ('POSITION' | 'NORMAL' | 'COLOR' | 'TEX_COORD' | 'GENERIC')[];\n};\n\n// @ts-ignore\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst GEOMETRY_TYPE = {\n TRIANGULAR_MESH: 0,\n POINT_CLOUD: 1\n};\n\n// Native Draco attribute names to GLTF attribute names.\nconst DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {\n POSITION: 'POSITION',\n NORMAL: 'NORMAL',\n COLOR: 'COLOR_0',\n TEX_COORD: 'TEXCOORD_0'\n};\n\nconst DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {\n 1: Int8Array,\n 2: Uint8Array,\n 3: Int16Array,\n 4: Uint16Array,\n 5: Int32Array,\n 6: Uint32Array,\n 9: Float32Array\n};\n\nconst INDEX_ITEM_SIZE = 4;\n\nexport default class DracoParser {\n draco: Draco3D;\n decoder: Decoder;\n metadataQuerier: MetadataQuerier;\n\n // draco - the draco decoder, either import `draco3d` or load dynamically\n constructor(draco: Draco3D) {\n this.draco = draco;\n this.decoder = new this.draco.Decoder();\n this.metadataQuerier = new this.draco.MetadataQuerier();\n }\n\n /**\n * Destroy draco resources\n */\n destroy(): void {\n this.draco.destroy(this.decoder);\n this.draco.destroy(this.metadataQuerier);\n }\n\n /**\n * NOTE: caller must call `destroyGeometry` on the return value after using it\n * @param arrayBuffer\n * @param options\n */\n parseSync(arrayBuffer: ArrayBuffer, options: DracoParseOptions = {}): DracoMeshData {\n const buffer = new this.draco.DecoderBuffer();\n buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);\n\n this._disableAttributeTransforms(options);\n\n const geometry_type = this.decoder.GetEncodedGeometryType(buffer);\n const dracoGeometry =\n geometry_type === this.draco.TRIANGULAR_MESH\n ? new this.draco.Mesh()\n : new this.draco.PointCloud();\n\n try {\n let dracoStatus;\n switch (geometry_type) {\n case this.draco.TRIANGULAR_MESH:\n dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry as Mesh);\n break;\n\n case this.draco.POINT_CLOUD:\n dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);\n break;\n\n default:\n throw new Error('DRACO: Unknown geometry type.');\n }\n\n if (!dracoStatus.ok() || !dracoGeometry.ptr) {\n const message = `DRACO decompression failed: ${dracoStatus.error_msg()}`;\n // console.error(message);\n throw new Error(message);\n }\n\n const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);\n\n const geometry = this._getMeshData(dracoGeometry, loaderData, options);\n\n const boundingBox = getMeshBoundingBox(geometry.attributes);\n\n const schema = makeSchemaFromAttributes(geometry.attributes, loaderData, geometry.indices);\n\n const data: DracoMeshData = {\n loader: 'draco',\n loaderData,\n header: {\n vertexCount: dracoGeometry.num_points(),\n boundingBox\n },\n ...geometry,\n schema\n };\n return data;\n } finally {\n this.draco.destroy(buffer);\n if (dracoGeometry) {\n this.draco.destroy(dracoGeometry);\n }\n }\n }\n\n // Draco specific \"loader data\"\n\n /**\n * Extract\n * @param dracoGeometry\n * @param geometry_type\n * @param options\n * @returns\n */\n _getDracoLoaderData(\n dracoGeometry: Mesh | PointCloud,\n geometry_type,\n options: DracoParseOptions\n ): DracoLoaderData {\n const metadata = this._getTopLevelMetadata(dracoGeometry);\n const attributes = this._getDracoAttributes(dracoGeometry, options);\n\n return {\n geometry_type,\n num_attributes: dracoGeometry.num_attributes(),\n num_points: dracoGeometry.num_points(),\n num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,\n metadata,\n attributes\n };\n }\n\n /**\n * Extract all draco provided information and metadata for each attribute\n * @param dracoGeometry\n * @param options\n * @returns\n */\n _getDracoAttributes(\n dracoGeometry: Mesh | PointCloud,\n options: DracoParseOptions\n ): {[unique_id: number]: DracoAttribute} {\n const dracoAttributes: {[unique_id: number]: DracoAttribute} = {};\n\n for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {\n // Note: Draco docs do not seem clear on `GetAttribute` ids just being a zero-based index,\n // but it does seems to work this way\n const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);\n\n const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);\n\n dracoAttributes[dracoAttribute.unique_id()] = {\n unique_id: dracoAttribute.unique_id(),\n attribute_type: dracoAttribute.attribute_type(),\n data_type: dracoAttribute.data_type(),\n num_components: dracoAttribute.num_components(),\n\n byte_offset: dracoAttribute.byte_offset(),\n byte_stride: dracoAttribute.byte_stride(),\n normalized: dracoAttribute.normalized(),\n attribute_index: attributeId,\n\n metadata\n };\n\n // Add transformation parameters for any attributes app wants untransformed\n const quantization = this._getQuantizationTransform(dracoAttribute, options);\n if (quantization) {\n dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;\n }\n\n const octahedron = this._getOctahedronTransform(dracoAttribute, options);\n if (octahedron) {\n dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;\n }\n }\n\n return dracoAttributes;\n }\n\n /**\n * Get standard loaders.gl mesh category data\n * Extracts the geometry from draco\n * @param dracoGeometry\n * @param options\n */\n _getMeshData(\n dracoGeometry: Mesh | PointCloud,\n loaderData: DracoLoaderData,\n options: DracoParseOptions\n ): MeshData {\n const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);\n\n const positionAttribute = attributes.POSITION;\n if (!positionAttribute) {\n throw new Error('DRACO: No position attribute found.');\n }\n\n // For meshes, we need indices to define the faces.\n if (dracoGeometry instanceof this.draco.Mesh) {\n switch (options.topology) {\n case 'triangle-strip':\n return {\n topology: 'triangle-strip',\n mode: 4, // GL.TRIANGLES\n attributes,\n indices: {\n value: this._getTriangleStripIndices(dracoGeometry),\n size: 1\n }\n };\n case 'triangle-list':\n default:\n return {\n topology: 'triangle-list',\n mode: 5, // GL.TRIANGLE_STRIP\n attributes,\n indices: {\n value: this._getTriangleListIndices(dracoGeometry),\n size: 1\n }\n };\n }\n }\n\n // PointCloud - must come last as Mesh inherits from PointCloud\n return {\n topology: 'point-list',\n mode: 0, // GL.POINTS\n attributes\n };\n }\n\n _getMeshAttributes(\n loaderData: DracoLoaderData,\n dracoGeometry: Mesh | PointCloud,\n options: DracoParseOptions\n ): {[attributeName: string]: MeshAttribute} {\n const attributes: {[key: string]: MeshAttribute} = {};\n\n for (const loaderAttribute of Object.values(loaderData.attributes)) {\n const attributeName = this._deduceAttributeName(loaderAttribute, options);\n loaderAttribute.name = attributeName;\n const {value, size} = this._getAttributeValues(dracoGeometry, loaderAttribute);\n attributes[attributeName] = {\n value,\n size,\n byteOffset: loaderAttribute.byte_offset,\n byteStride: loaderAttribute.byte_stride,\n normalized: loaderAttribute.normalized\n };\n }\n\n return attributes;\n }\n\n // MESH INDICES EXTRACTION\n\n /**\n * For meshes, we need indices to define the faces.\n * @param dracoGeometry\n */\n _getTriangleListIndices(dracoGeometry: Mesh) {\n // Example on how to retrieve mesh and attributes.\n const numFaces = dracoGeometry.num_faces();\n const numIndices = numFaces * 3;\n const byteLength = numIndices * INDEX_ITEM_SIZE;\n\n const ptr = this.draco._malloc(byteLength);\n try {\n this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);\n return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();\n } finally {\n this.draco._free(ptr);\n }\n }\n\n /**\n * For meshes, we need indices to define the faces.\n * @param dracoGeometry\n */\n _getTriangleStripIndices(dracoGeometry: Mesh) {\n const dracoArray = new this.draco.DracoInt32Array();\n try {\n /* const numStrips = */ this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);\n return getUint32Array(dracoArray);\n } finally {\n this.draco.destroy(dracoArray);\n }\n }\n\n /**\n *\n * @param dracoGeometry\n * @param dracoAttribute\n * @param attributeName\n */\n _getAttributeValues(\n dracoGeometry: Mesh | PointCloud,\n attribute: DracoAttribute\n ): {value: TypedArray; size: number} {\n const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];\n const numComponents = attribute.num_components;\n const numPoints = dracoGeometry.num_points();\n const numValues = numPoints * numComponents;\n\n const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;\n const dataType = getDracoDataType(this.draco, TypedArrayCtor);\n\n let value: TypedArray;\n\n const ptr = this.draco._malloc(byteLength);\n try {\n const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);\n this.decoder.GetAttributeDataArrayForAllPoints(\n dracoGeometry,\n dracoAttribute,\n dataType,\n byteLength,\n ptr\n );\n value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();\n } finally {\n this.draco._free(ptr);\n }\n\n return {value, size: numComponents};\n }\n\n // Attribute names\n\n /** \n * DRACO does not store attribute names - We need to deduce an attribute name\n * for each attribute\n _getAttributeNames(\n dracoGeometry: Mesh | PointCloud,\n options: DracoParseOptions\n ): {[unique_id: number]: string} {\n const attributeNames: {[unique_id: number]: string} = {};\n for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {\n const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);\n const attributeName = this._deduceAttributeName(dracoAttribute, options);\n attributeNames[attributeName] = attributeName;\n }\n return attributeNames;\n }\n */\n\n /**\n * Deduce an attribute name.\n * @note DRACO does not save attribute names, just general type (POSITION, COLOR)\n * to help optimize compression. We generate GLTF compatible names for the Draco-recognized\n * types\n * @param attributeData\n */\n _deduceAttributeName(attribute: DracoAttribute, options: DracoParseOptions): string {\n // Deduce name based on application provided map\n const uniqueId = attribute.unique_id;\n for (const [attributeName, attributeUniqueId] of Object.entries(\n options.extraAttributes || {}\n )) {\n if (attributeUniqueId === uniqueId) {\n return attributeName;\n }\n }\n\n // Deduce name based on attribute type\n const thisAttributeType = attribute.attribute_type;\n for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {\n const attributeType = this.draco[dracoAttributeConstant];\n if (attributeType === thisAttributeType) {\n // TODO - Return unique names if there multiple attributes per type\n // (e.g. multiple TEX_COORDS or COLORS)\n return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];\n }\n }\n\n // Look up in metadata\n // TODO - shouldn't this have priority?\n const entryName = options.attributeNameEntry || 'name';\n if (attribute.metadata[entryName]) {\n return attribute.metadata[entryName].string;\n }\n\n // Attribute of \"GENERIC\" type, we need to assign some name\n return `CUSTOM_ATTRIBUTE_${uniqueId}`;\n }\n\n // METADATA EXTRACTION\n\n /** Get top level metadata */\n _getTopLevelMetadata(dracoGeometry: Mesh | PointCloud) {\n const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);\n return this._getDracoMetadata(dracoMetadata);\n }\n\n /** Get per attribute metadata */\n _getAttributeMetadata(dracoGeometry: Mesh | PointCloud, attributeId: number) {\n const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);\n return this._getDracoMetadata(dracoMetadata);\n }\n\n /**\n * Extract metadata field values\n * @param dracoMetadata\n * @returns\n */\n _getDracoMetadata(dracoMetadata: Metadata): {[entry: string]: DracoMetadataEntry} {\n // The not so wonderful world of undocumented Draco APIs :(\n if (!dracoMetadata || !dracoMetadata.ptr) {\n return {};\n }\n const result = {};\n const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);\n for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {\n const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);\n result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);\n }\n return result;\n }\n\n /**\n * Extracts possible values for one metadata entry by name\n * @param dracoMetadata\n * @param entryName\n */\n _getDracoMetadataField(dracoMetadata: Metadata, entryName: string): DracoMetadataEntry {\n const dracoArray = new this.draco.DracoInt32Array();\n try {\n // Draco metadata fields can hold int32 arrays\n this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);\n const intArray = getInt32Array(dracoArray);\n return {\n int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),\n string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),\n double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),\n intArray\n };\n } finally {\n this.draco.destroy(dracoArray);\n }\n }\n\n // QUANTIZED ATTRIBUTE SUPPORT (NO DECOMPRESSION)\n\n /** Skip transforms for specific attribute types */\n _disableAttributeTransforms(options: DracoParseOptions) {\n const {quantizedAttributes = [], octahedronAttributes = []} = options;\n const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];\n for (const dracoAttributeName of skipAttributes) {\n this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);\n }\n }\n\n /**\n * Extract (and apply?) Position Transform\n * @todo not used\n */\n _getQuantizationTransform(\n dracoAttribute: PointAttribute,\n options: DracoParseOptions\n ): DracoQuantizationTransform | null {\n const {quantizedAttributes = []} = options;\n const attribute_type = dracoAttribute.attribute_type();\n const skip = quantizedAttributes.map((type) => this.decoder[type]).includes(attribute_type);\n if (skip) {\n const transform = new this.draco.AttributeQuantizationTransform();\n try {\n if (transform.InitFromAttribute(dracoAttribute)) {\n return {\n quantization_bits: transform.quantization_bits(),\n range: transform.range(),\n min_values: new Float32Array([1, 2, 3]).map((i) => transform.min_value(i))\n };\n }\n } finally {\n this.draco.destroy(transform);\n }\n }\n return null;\n }\n\n _getOctahedronTransform(\n dracoAttribute: PointAttribute,\n options: DracoParseOptions\n ): DracoOctahedronTransform | null {\n const {octahedronAttributes = []} = options;\n const attribute_type = dracoAttribute.attribute_type();\n const octahedron = octahedronAttributes\n .map((type) => this.decoder[type])\n .includes(attribute_type);\n if (octahedron) {\n const transform = new this.draco.AttributeQuantizationTransform();\n try {\n if (transform.InitFromAttribute(dracoAttribute)) {\n return {\n quantization_bits: transform.quantization_bits()\n };\n }\n } finally {\n this.draco.destroy(transform);\n }\n }\n return null;\n }\n\n // HELPERS\n}\n\n/**\n * Get draco specific data type by TypedArray constructor type\n * @param attributeType\n * @returns draco specific data type\n */\nfunction getDracoDataType(draco: Draco3D, attributeType: any): draco_DataType {\n switch (attributeType) {\n case Float32Array:\n return draco.DT_FLOAT32;\n case Int8Array:\n return draco.DT_INT8;\n case Int16Array:\n return draco.DT_INT16;\n case Int32Array:\n return draco.DT_INT32;\n case Uint8Array:\n return draco.DT_UINT8;\n case Uint16Array:\n return draco.DT_UINT16;\n case Uint32Array:\n return draco.DT_UINT32;\n default:\n return draco.DT_INVALID;\n }\n}\n\n/**\n * Copy a Draco int32 array into a JS typed array\n */\nfunction getInt32Array(dracoArray: DracoInt32Array): Int32Array {\n const numValues = dracoArray.size();\n const intArray = new Int32Array(numValues);\n for (let i = 0; i < numValues; i++) {\n intArray[i] = dracoArray.GetValue(i);\n }\n return intArray;\n}\n\n/**\n * Copy a Draco int32 array into a JS typed array\n */\nfunction getUint32Array(dracoArray: DracoInt32Array): Int32Array {\n const numValues = dracoArray.size();\n const intArray = new Int32Array(numValues);\n for (let i = 0; i < numValues; i++) {\n intArray[i] = dracoArray.GetValue(i);\n }\n return intArray;\n}\n","/* global importScripts */\nimport {global, isBrowser, isWorker} from '../env-utils/globals';\nimport * as node from '../node/require-utils.node';\nimport {assert} from '../env-utils/assert';\nimport {VERSION as __VERSION__} from '../env-utils/version';\n\n// TODO - unpkg.com doesn't seem to have a `latest` specifier for alpha releases...\nconst LATEST = 'beta';\nconst VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : LATEST;\n\nconst loadLibraryPromises = {}; // promises\n\n/**\n * Dynamically loads a library (\"module\")\n *\n * - wasm library: Array buffer is returned\n * - js library: Parse JS is returned\n *\n * Method depends on environment\n * - browser - script element is created and installed on document\n * - worker - eval is called on global context\n * - node - file is required\n *\n * @param libraryUrl\n * @param moduleName\n * @param options\n */\nexport async function loadLibrary(\n libraryUrl: string,\n moduleName: string | null = null,\n options: object = {}\n): Promise {\n if (moduleName) {\n libraryUrl = getLibraryUrl(libraryUrl, moduleName, options);\n }\n\n // Ensure libraries are only loaded once\n loadLibraryPromises[libraryUrl] =\n loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);\n return await loadLibraryPromises[libraryUrl];\n}\n\n// TODO - sort out how to resolve paths for main/worker and dev/prod\nexport function getLibraryUrl(library, moduleName?: string, options?): string {\n // Check if already a URL\n if (library.startsWith('http')) {\n return library;\n }\n\n // Allow application to import and supply libraries through `options.modules`\n const modules = options.modules || {};\n if (modules[library]) {\n return modules[library];\n }\n\n // Load from local files, not from CDN scripts in Node.js\n // TODO - needs to locate the modules directory when installed!\n if (!isBrowser) {\n return `modules/${moduleName}/dist/libs/${library}`;\n }\n\n // In browser, load from external scripts\n if (options.CDN) {\n assert(options.CDN.startsWith('http'));\n return `${options.CDN}/${moduleName}@${VERSION}/dist/libs/${library}`;\n }\n\n // TODO - loading inside workers requires paths relative to worker script location...\n if (isWorker) {\n return `../src/libs/${library}`;\n }\n\n return `modules/${moduleName}/src/libs/${library}`;\n}\n\nasync function loadLibraryFromFile(libraryUrl) {\n if (libraryUrl.endsWith('wasm')) {\n const response = await fetch(libraryUrl);\n return await response.arrayBuffer();\n }\n\n if (!isBrowser) {\n return node.requireFromFile && (await node.requireFromFile(libraryUrl));\n }\n if (isWorker) {\n return importScripts(libraryUrl);\n }\n // TODO - fix - should be more secure than string parsing since observes CORS\n // if (isBrowser) {\n // return await loadScriptFromFile(libraryUrl);\n // }\n\n const response = await fetch(libraryUrl);\n const scriptSource = await response.text();\n return loadLibraryFromString(scriptSource, libraryUrl);\n}\n\n/*\nasync function loadScriptFromFile(libraryUrl) {\n const script = document.createElement('script');\n script.src = libraryUrl;\n return await new Promise((resolve, reject) => {\n script.onload = data => {\n resolve(data);\n };\n script.onerror = reject;\n });\n}\n*/\n\n// TODO - Needs security audit...\n// - Raw eval call\n// - Potentially bypasses CORS\n// Upside is that this separates fetching and parsing\n// we could create a`LibraryLoader` or`ModuleLoader`\nfunction loadLibraryFromString(scriptSource, id) {\n if (!isBrowser) {\n return node.requireFromString && node.requireFromString(scriptSource, id);\n }\n\n if (isWorker) {\n // Use lvalue trick to make eval run in global scope\n eval.call(global, scriptSource); // eslint-disable-line no-eval\n // https://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript\n // http://perfectionkills.com/global-eval-what-are-the-options/\n return null;\n }\n\n const script = document.createElement('script');\n script.id = id;\n // most browsers like a separate text node but some throw an error. The second method covers those.\n try {\n script.appendChild(document.createTextNode(scriptSource));\n } catch (e) {\n script.text = scriptSource;\n }\n document.body.appendChild(script);\n return null;\n}\n\n// TODO - technique for module injection into worker, from THREE.DracoLoader...\n/*\nfunction combineWorkerWithLibrary(worker, jsContent) {\n var fn = wWorker.toString();\n var body = [\n '// injected',\n jsContent,\n '',\n '// worker',\n fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))\n ].join('\\n');\n this.workerSourceURL = URL.createObjectURL(new Blob([body]));\n}\n*/\n","// Dynamic DRACO module loading inspired by THREE.DRACOLoader\n// https://github.com/mrdoob/three.js/blob/398c4f39ebdb8b23eefd4a7a5ec49ec0c96c7462/examples/jsm/loaders/DRACOLoader.js\n// by Don McCurdy / https://www.donmccurdy.com / MIT license\n\nimport {loadLibrary} from '@loaders.gl/worker-utils';\n\nconst DRACO_VERSION = '1.4.1';\nconst DRACO_JS_DECODER_URL = `https://www.gstatic.com/draco/versioned/decoders/${DRACO_VERSION}/draco_decoder.js`;\nconst DRACO_WASM_WRAPPER_URL = `https://www.gstatic.com/draco/versioned/decoders/${DRACO_VERSION}/draco_wasm_wrapper.js`;\nconst DRACO_WASM_DECODER_URL = `https://www.gstatic.com/draco/versioned/decoders/${DRACO_VERSION}/draco_decoder.wasm`;\n\nconst DRACO_ENCODER_URL = `https://raw.githubusercontent.com/google/draco/${DRACO_VERSION}/javascript/draco_encoder.js`;\n\nlet loadDecoderPromise;\nlet loadEncoderPromise;\n\nexport async function loadDracoDecoderModule(options) {\n const modules = options.modules || {};\n\n // Check if a bundled draco3d library has been supplied by application\n if (modules.draco3d) {\n loadDecoderPromise =\n loadDecoderPromise ||\n modules.draco3d.createDecoderModule({}).then((draco) => {\n return {draco};\n });\n } else {\n // If not, dynamically load the WASM script from our CDN\n loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);\n }\n return await loadDecoderPromise;\n}\n\nexport async function loadDracoEncoderModule(options) {\n const modules = options.modules || {};\n\n // Check if a bundled draco3d library has been supplied by application\n if (modules.draco3d) {\n loadEncoderPromise =\n loadEncoderPromise ||\n modules.draco3d.createEncoderModule({}).then((draco) => {\n return {draco};\n });\n } else {\n // If not, dynamically load the WASM script from our CDN\n loadEncoderPromise = loadEncoderPromise || loadDracoEncoder(options);\n }\n return await loadEncoderPromise;\n}\n\n// DRACO DECODER LOADING\n\nasync function loadDracoDecoder(options) {\n let DracoDecoderModule;\n let wasmBinary;\n switch (options.draco && options.draco.decoderType) {\n case 'js':\n DracoDecoderModule = await loadLibrary(DRACO_JS_DECODER_URL, 'draco', options);\n break;\n\n case 'wasm':\n default:\n [DracoDecoderModule, wasmBinary] = await Promise.all([\n await loadLibrary(DRACO_WASM_WRAPPER_URL, 'draco', options),\n await loadLibrary(DRACO_WASM_DECODER_URL, 'draco', options)\n ]);\n }\n // Depends on how import happened...\n // @ts-ignore\n DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;\n return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);\n}\n\nfunction initializeDracoDecoder(DracoDecoderModule, wasmBinary) {\n const options: {wasmBinary?: any} = {};\n if (wasmBinary) {\n options.wasmBinary = wasmBinary;\n }\n\n return new Promise((resolve) => {\n DracoDecoderModule({\n ...options,\n onModuleLoaded: (draco) => resolve({draco}) // Module is Promise-like. Wrap in object to avoid loop.\n });\n });\n}\n\n// ENCODER\n\nasync function loadDracoEncoder(options) {\n let DracoEncoderModule = await loadLibrary(DRACO_ENCODER_URL, 'draco', options);\n // @ts-ignore\n DracoEncoderModule = DracoEncoderModule || globalThis.DracoEncoderModule;\n\n return new Promise((resolve) => {\n DracoEncoderModule({\n onModuleLoaded: (draco) => resolve({draco}) // Module is Promise-like. Wrap in object to avoid loop.\n });\n });\n}\n","let arrayBuffer = null;\n\nexport function getScratchArrayBuffer(byteLength) {\n if (!arrayBuffer || arrayBuffer.byteLength < byteLength) {\n arrayBuffer = new ArrayBuffer(byteLength);\n }\n return arrayBuffer;\n}\n\nexport function getScratchArray(Type, length) {\n const scratchArrayBuffer = getScratchArrayBuffer(Type.BYTES_PER_ELEMENT * length);\n return new Type(scratchArrayBuffer, 0, length); // arrayBuffer, byteOffset, length (in elements)\n}\n\n// Uses copyWithin to significantly speed up typed array value filling\nexport function fillArray({target, source, start = 0, count = 1}) {\n const length = source.length;\n const total = count * length;\n let copied = 0;\n for (let i = start; copied < length; copied++) {\n target[i++] = source[copied];\n }\n\n while (copied < total) {\n // If we have copied less than half, copy everything we got\n // else copy remaining in one operation\n if (copied < total - copied) {\n target.copyWithin(start + copied, start, start + copied);\n copied *= 2;\n } else {\n target.copyWithin(start + copied, start, start + total - copied);\n copied = total;\n }\n }\n\n return target;\n}\n\n/*\n\n// Creates a new Uint8Array based on two different ArrayBuffers\n// @private\n// @param {ArrayBuffers} buffer1 The first buffer.\n// @param {ArrayBuffers} buffer2 The second buffer.\n// @return {ArrayBuffers} The new ArrayBuffer created out of the two.\n//\nexport function copyArrayBuffer(\n targetBuffer, sourceBuffer, byteOffset, byteLength = sourceBuffer.byteLength\n) {\n const targetArray = new Uint8Array(targetBuffer, byteOffset, byteLength);\n const sourceArray = new Uint8Array(sourceBuffer);\n targetArray.set(sourceArray);\n return targetBuffer;\n}\n\n*/\n","// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// This function is needed in initialization stages,\n// make sure it can be imported in isolation\n\nimport {window} from './globals';\nimport isBrowser from './is-browser';\nimport isElectron from './is-electron';\n\nexport function isMobile() {\n // @ts-ignore\n return typeof window.orientation !== 'undefined';\n}\n\n// Simple browser detection\n// `mockUserAgent` parameter allows user agent to be overridden for testing\n/* eslint-disable complexity */\nexport default function getBrowser(mockUserAgent) {\n if (!mockUserAgent && !isBrowser()) {\n return 'Node';\n }\n\n if (isElectron(mockUserAgent)) {\n return 'Electron';\n }\n\n const navigator_ = typeof navigator !== 'undefined' ? navigator : {};\n const userAgent = mockUserAgent || navigator_.userAgent || '';\n // const appVersion = navigator_.appVersion || '';\n\n // NOTE: Order of tests matter, as many agents list Chrome etc.\n if (userAgent.indexOf('Edge') > -1) {\n return 'Edge';\n }\n const isMSIE = userAgent.indexOf('MSIE ') !== -1;\n const isTrident = userAgent.indexOf('Trident/') !== -1;\n if (isMSIE || isTrident) {\n return 'IE';\n }\n // @ts-ignore\n if (window.chrome) {\n return 'Chrome';\n }\n // @ts-ignore\n if (window.safari) {\n return 'Safari';\n }\n // @ts-ignore\n if (window.mozInnerScreenX) {\n return 'Firefox';\n }\n return 'Unknown';\n}\n","import GL from '@luma.gl/constants';\nimport Resource from './resource';\nimport Buffer from './buffer';\nimport {isWebGL2} from '@luma.gl/gltools';\nimport {getScratchArray, fillArray} from '../utils/array-utils-flat';\nimport {assert} from '../utils/assert';\nimport {getBrowser} from 'probe.gl';\n\nconst ERR_ELEMENTS = 'elements must be GL.ELEMENT_ARRAY_BUFFER';\n\nexport default class VertexArrayObject extends Resource {\n static isSupported(gl, options = {}) {\n // Attribute 0 can not be disable on most desktop OpenGL based browsers\n // and on iOS Safari browser.\n if (options.constantAttributeZero) {\n return isWebGL2(gl) || getBrowser() === 'Chrome';\n }\n\n // Whether additional objects can be created\n return true;\n }\n\n // Returns the global (null) vertex array object. Exists even when no extension available\n // TODO(Tarek): VAOs are now polyfilled. Deprecate this in 9.0\n static getDefaultArray(gl) {\n gl.luma = gl.luma || {};\n if (!gl.luma.defaultVertexArray) {\n gl.luma.defaultVertexArray = new VertexArrayObject(gl, {handle: null, isDefaultArray: true});\n }\n return gl.luma.defaultVertexArray;\n }\n\n static getMaxAttributes(gl) {\n // TODO - should be cached per context\n // @ts-ignore\n VertexArrayObject.MAX_ATTRIBUTES =\n // @ts-ignore\n VertexArrayObject.MAX_ATTRIBUTES || gl.getParameter(gl.MAX_VERTEX_ATTRIBS);\n // @ts-ignore\n return VertexArrayObject.MAX_ATTRIBUTES;\n }\n\n // Note: Constants are stored globally on the WebGL context, not the VAO\n // So they need to be updated before every render\n // TODO - use known type (in configuration or passed in) to allow non-typed arrays?\n // TODO - remember/cache values to avoid setting them unnecessarily?\n static setConstant(gl, location, array) {\n switch (array.constructor) {\n case Float32Array:\n VertexArrayObject._setConstantFloatArray(gl, location, array);\n break;\n case Int32Array:\n VertexArrayObject._setConstantIntArray(gl, location, array);\n break;\n case Uint32Array:\n VertexArrayObject._setConstantUintArray(gl, location, array);\n break;\n default:\n assert(false);\n }\n }\n\n // Create a VertexArray\n constructor(gl, opts = {}) {\n // Use program's id if program but no id is supplied\n const id = opts.id || (opts.program && opts.program.id);\n super(gl, Object.assign({}, opts, {id}));\n\n this.buffer = null;\n this.bufferValue = null;\n this.isDefaultArray = opts.isDefaultArray || false;\n\n /** @type {WebGL2RenderingContext} */\n this.gl2 = gl;\n\n this.initialize(opts);\n\n Object.seal(this);\n }\n\n delete() {\n super.delete();\n if (this.buffer) {\n this.buffer.delete();\n }\n return this;\n }\n\n get MAX_ATTRIBUTES() {\n return VertexArrayObject.getMaxAttributes(this.gl);\n }\n\n initialize(props = {}) {\n return this.setProps(props);\n }\n\n setProps(props) {\n // TODO: decide which props should be supported\n return this;\n }\n\n // Set (bind) an elements buffer, for indexed rendering.\n // Must be a Buffer bound to GL.ELEMENT_ARRAY_BUFFER. Constants not supported\n setElementBuffer(elementBuffer = null, opts = {}) {\n assert(!elementBuffer || elementBuffer.target === GL.ELEMENT_ARRAY_BUFFER, ERR_ELEMENTS);\n\n // The GL.ELEMENT_ARRAY_BUFFER_BINDING is stored on the VertexArrayObject...\n this.bind(() => {\n this.gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, elementBuffer ? elementBuffer.handle : null);\n });\n\n return this;\n }\n\n // Set a location in vertex attributes array to a bufferk, enables the location, sets divisor\n setBuffer(location, buffer, accessor) {\n // Check target\n if (buffer.target === GL.ELEMENT_ARRAY_BUFFER) {\n return this.setElementBuffer(buffer, accessor);\n }\n\n const {size, type, stride, offset, normalized, integer, divisor} = accessor;\n\n const {gl, gl2} = this;\n location = Number(location);\n\n this.bind(() => {\n // A non-zero buffer object must be bound to the GL_ARRAY_BUFFER target\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer.handle);\n\n // WebGL2 supports *integer* data formats, i.e. GPU will see integer values\n if (integer) {\n assert(isWebGL2(gl));\n gl2.vertexAttribIPointer(location, size, type, stride, offset);\n } else {\n // Attaches ARRAY_BUFFER with specified buffer format to location\n gl.vertexAttribPointer(location, size, type, normalized, stride, offset);\n }\n gl.enableVertexAttribArray(location);\n gl2.vertexAttribDivisor(location, divisor || 0);\n\n // NOTE We don't unbind buffer here, typically another buffer will be bound just after\n });\n\n return this;\n }\n\n // Enabling an attribute location makes it reference the currently bound buffer\n // Disabling an attribute location makes it reference the global constant value\n // TODO - handle single values for size 1 attributes?\n // TODO - convert classic arrays based on known type?\n enable(location, enable = true) {\n // Attribute 0 cannot be disabled in most desktop OpenGL based browsers\n const disablingAttributeZero =\n !enable &&\n location === 0 &&\n !VertexArrayObject.isSupported(this.gl, {constantAttributeZero: true});\n\n if (!disablingAttributeZero) {\n location = Number(location);\n this.bind(\n () =>\n enable\n ? this.gl.enableVertexAttribArray(location)\n : this.gl.disableVertexAttribArray(location)\n );\n }\n return this;\n }\n\n // Provide a means to create a buffer that is equivalent to a constant.\n // NOTE: Desktop OpenGL cannot disable attribute 0.\n // https://stackoverflow.com/questions/20305231/webgl-warning-attribute-0-is-disabled-\n // this-has-significant-performance-penalt\n getConstantBuffer(elementCount, value) {\n // Create buffer only when needed, and reuse it (avoids inflating buffer creation statistics)\n\n const constantValue = this._normalizeConstantArrayValue(value);\n\n const byteLength = constantValue.byteLength * elementCount;\n const length = constantValue.length * elementCount;\n\n let updateNeeded = !this.buffer;\n\n this.buffer = this.buffer || new Buffer(this.gl, byteLength);\n updateNeeded = updateNeeded || this.buffer.reallocate(byteLength);\n\n // Reallocate and update contents if needed\n updateNeeded =\n updateNeeded || !this._compareConstantArrayValues(constantValue, this.bufferValue);\n\n if (updateNeeded) {\n // Create a typed array that is big enough, and fill it with the required data\n const typedArray = getScratchArray(value.constructor, length);\n fillArray({target: typedArray, source: constantValue, start: 0, count: length});\n this.buffer.subData(typedArray);\n this.bufferValue = value;\n }\n\n return this.buffer;\n }\n\n // PRIVATE\n\n // TODO - convert Arrays based on known type? (read type from accessor, don't assume Float32Array)\n // TODO - handle single values for size 1 attributes?\n _normalizeConstantArrayValue(arrayValue) {\n if (Array.isArray(arrayValue)) {\n return new Float32Array(arrayValue);\n }\n return arrayValue;\n }\n\n _compareConstantArrayValues(v1, v2) {\n if (!v1 || !v2 || v1.length !== v2.length || v1.constructor !== v2.constructor) {\n return false;\n }\n for (let i = 0; i < v1.length; ++i) {\n if (v1[i] !== v2[i]) {\n return false;\n }\n }\n return true;\n }\n\n static _setConstantFloatArray(gl, location, array) {\n switch (array.length) {\n case 1:\n gl.vertexAttrib1fv(location, array);\n break;\n case 2:\n gl.vertexAttrib2fv(location, array);\n break;\n case 3:\n gl.vertexAttrib3fv(location, array);\n break;\n case 4:\n gl.vertexAttrib4fv(location, array);\n break;\n default:\n assert(false);\n }\n }\n\n static _setConstantIntArray(gl, location, array) {\n assert(isWebGL2(gl));\n switch (array.length) {\n case 1:\n gl.vertexAttribI1iv(location, array);\n break;\n case 2:\n gl.vertexAttribI2iv(location, array);\n break;\n case 3:\n gl.vertexAttribI3iv(location, array);\n break;\n case 4:\n gl.vertexAttribI4iv(location, array);\n break;\n default:\n assert(false);\n }\n }\n\n static _setConstantUintArray(gl, location, array) {\n assert(isWebGL2(gl));\n switch (array.length) {\n case 1:\n gl.vertexAttribI1uiv(location, array);\n break;\n case 2:\n gl.vertexAttribI2uiv(location, array);\n break;\n case 3:\n gl.vertexAttribI3uiv(location, array);\n break;\n case 4:\n gl.vertexAttribI4uiv(location, array);\n break;\n default:\n assert(false);\n }\n }\n\n // RESOURCE IMPLEMENTATION\n\n _createHandle() {\n /** @type {WebGL2RenderingContext} */\n // @ts-ignore\n const gl2 = this.gl;\n return gl2.createVertexArray();\n }\n\n _deleteHandle(handle) {\n this.gl2.deleteVertexArray(handle);\n // @ts-ignore\n return [this.elements];\n // return [this.elements, ...this.buffers];\n }\n\n _bindHandle(handle) {\n this.gl2.bindVertexArray(handle);\n }\n\n // Generic getter for information about a vertex attribute at a given position\n _getParameter(pname, {location}) {\n assert(Number.isFinite(location));\n return this.bind(() => {\n switch (pname) {\n case GL.VERTEX_ATTRIB_ARRAY_POINTER:\n return this.gl.getVertexAttribOffset(location, pname);\n default:\n return this.gl.getVertexAttrib(location, pname);\n }\n });\n }\n}\n","import GL from '@luma.gl/constants';\nimport {log} from '@luma.gl/gltools';\nimport Accessor from './accessor';\nimport Buffer from './buffer';\nimport VertexArrayObject from './vertex-array-object';\nimport {assert} from '../utils/assert';\nimport {stubRemovedMethods} from '../utils/stub-methods';\n\nconst ERR_ATTRIBUTE_TYPE =\n 'VertexArray: attributes must be Buffers or constants (i.e. typed array)';\n\n// This is done to support mat type attributes.\n// See section \"Notes about setting mat type attributes\"\n// in vertex-array.md\nconst MULTI_LOCATION_ATTRIBUTE_REGEXP = /^(.+)__LOCATION_([0-9]+)$/;\n\nconst DEPRECATIONS_V6 = [\n 'setBuffers',\n 'setGeneric',\n 'clearBindings',\n 'setLocations',\n 'setGenericValues',\n 'setDivisor',\n 'enable',\n 'disable'\n];\n\nexport default class VertexArray {\n constructor(gl, opts = {}) {\n // Use program's id if program is supplied but no id is supplied\n const id = opts.id || (opts.program && opts.program.id);\n // super(gl, Object.assign({}, opts, {id}));\n\n this.id = id;\n this.gl = gl;\n this.configuration = null;\n\n // Extracted information\n this.elements = null;\n this.elementsAccessor = null;\n this.values = null;\n this.accessors = null;\n this.unused = null;\n this.drawParams = null;\n this.buffer = null; // For attribute 0 on desktops, and created when unbinding buffers\n\n this.attributes = {};\n\n this.vertexArrayObject = new VertexArrayObject(gl);\n\n // Issue errors when using removed methods\n stubRemovedMethods(this, 'VertexArray', 'v6.0', DEPRECATIONS_V6);\n\n this.initialize(opts);\n Object.seal(this);\n }\n\n delete() {\n if (this.buffer) {\n this.buffer.delete();\n }\n\n this.vertexArrayObject.delete();\n }\n\n initialize(props = {}) {\n this.reset();\n this.configuration = null;\n this.bindOnUse = false;\n return this.setProps(props);\n }\n\n // Resets all attributes (to default valued constants)\n reset() {\n // this.vertexArrayObject.reset();\n\n this.elements = null;\n this.elementsAccessor = null;\n const {MAX_ATTRIBUTES} = this.vertexArrayObject;\n this.values = new Array(MAX_ATTRIBUTES).fill(null);\n this.accessors = new Array(MAX_ATTRIBUTES).fill(null);\n this.unused = {};\n\n // Auto detects draw params\n this.drawParams = null;\n\n return this;\n }\n\n setProps(props) {\n if ('program' in props) {\n this.configuration = props.program && props.program.configuration;\n }\n if ('configuration' in props) {\n this.configuration = props.configuration;\n }\n if ('attributes' in props) {\n this.setAttributes(props.attributes);\n }\n if ('elements' in props) {\n this.setElementBuffer(props.elements);\n }\n if ('bindOnUse' in props) {\n props = props.bindOnUse;\n }\n return this;\n }\n\n // Automatically called if buffers changed through VertexArray API\n clearDrawParams() {\n this.drawParams = null;\n }\n\n getDrawParams() {\n // Auto deduced draw parameters\n this.drawParams = this.drawParams || this._updateDrawParams();\n\n return this.drawParams;\n }\n\n // Set (bind) an array or map of vertex array buffers, either in numbered or named locations.\n // For names that are not present in `location`, the supplied buffers will be ignored.\n // if a single buffer of type GL.ELEMENT_ARRAY_BUFFER is present, it will be set as elements\n // Signatures:\n // {attributeName: buffer}\n // {attributeName: [buffer, accessor]}\n // {attributeName: (typed) array} => constant\n setAttributes(attributes) {\n Object.assign(this.attributes, attributes);\n this.vertexArrayObject.bind(() => {\n for (const locationOrName in attributes) {\n const value = attributes[locationOrName];\n this._setAttribute(locationOrName, value);\n }\n // Make sure we don't leave any bindings\n this.gl.bindBuffer(GL.ARRAY_BUFFER, null);\n });\n\n return this;\n }\n\n // Set (bind) an elements buffer, for indexed rendering.\n // Must be a Buffer bound to GL.ELEMENT_ARRAY_BUFFER. Constants not supported\n setElementBuffer(elementBuffer = null, accessor = {}) {\n this.elements = elementBuffer; // Save value for debugging\n this.elementsAccessor = accessor;\n this.clearDrawParams();\n this.vertexArrayObject.setElementBuffer(elementBuffer, accessor);\n\n return this;\n }\n\n // Set a location in vertex attributes array to a buffer\n setBuffer(locationOrName, buffer, appAccessor = {}) {\n // Check target\n if (buffer.target === GL.ELEMENT_ARRAY_BUFFER) {\n return this.setElementBuffer(buffer, appAccessor);\n }\n\n const {location, accessor} = this._resolveLocationAndAccessor(\n locationOrName,\n buffer,\n buffer.accessor,\n appAccessor\n );\n\n if (location >= 0) {\n this.values[location] = buffer;\n this.accessors[location] = accessor;\n this.clearDrawParams();\n this.vertexArrayObject.setBuffer(location, buffer, accessor);\n }\n\n return this;\n }\n\n // Set attribute to constant value (small typed array corresponding to one vertex' worth of data)\n setConstant(locationOrName, arrayValue, appAccessor = {}) {\n const {location, accessor} = this._resolveLocationAndAccessor(\n locationOrName,\n arrayValue,\n // Ensure that size isn't taken from program for multi-column\n // attributes\n Object.assign({size: arrayValue.length}, appAccessor)\n );\n\n if (location >= 0) {\n arrayValue = this.vertexArrayObject._normalizeConstantArrayValue(arrayValue);\n\n this.values[location] = arrayValue;\n this.accessors[location] = accessor;\n this.clearDrawParams();\n\n // NOTE: We set the actual constant value later on bind. We can't set the value now since\n // constants are global and affect all other VertexArrays that have disabled attributes\n // in the same location.\n // We do disable the attribute which makes it use the global constant value at that location\n this.vertexArrayObject.enable(location, false);\n }\n\n return this;\n }\n\n // Workaround for Chrome TransformFeedback binding issue\n // If required, unbind temporarily to avoid conflicting with TransformFeedback\n unbindBuffers() {\n this.vertexArrayObject.bind(() => {\n if (this.elements) {\n this.vertexArrayObject.setElementBuffer(null);\n }\n\n // Chrome does not like buffers that are bound to several binding points,\n // so we need to offer and unbind facility\n // WebGL offers disabling, but no clear way to set a VertexArray buffer to `null`\n // So we just bind all the attributes to the dummy \"attribute zero\" buffer\n this.buffer = this.buffer || new Buffer(this.gl, {accessor: {size: 4}});\n\n for (let location = 0; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {\n if (this.values[location] instanceof Buffer) {\n this.gl.disableVertexAttribArray(location);\n this.gl.bindBuffer(GL.ARRAY_BUFFER, this.buffer.handle);\n this.gl.vertexAttribPointer(location, 1, GL.FLOAT, false, 0, 0);\n }\n }\n });\n return this;\n }\n\n // Workaround for Chrome TransformFeedback binding issue\n // If required, rebind rebind after temporary unbind\n bindBuffers() {\n this.vertexArrayObject.bind(() => {\n if (this.elements) {\n this.setElementBuffer(this.elements);\n }\n\n for (let location = 0; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {\n const buffer = this.values[location];\n if (buffer instanceof Buffer) {\n this.setBuffer(location, buffer);\n }\n }\n });\n return this;\n }\n\n // Bind for use\n // When a vertex array is about to be used, we must:\n // - Set constant attributes (since these are stored on the context and reset on bind)\n // - Check if we need to initialize the buffer\n bindForDraw(vertexCount, instanceCount, func) {\n let value;\n\n this.vertexArrayObject.bind(() => {\n // Make sure that any constant attributes are updated (stored on the context, not the VAO)\n // Also handles attribute 0\n this._setConstantAttributes(vertexCount, instanceCount);\n\n value = func();\n });\n\n return value;\n }\n\n // PRIVATE\n\n // Resolve locations and accessors\n _resolveLocationAndAccessor(locationOrName, value, valueAccessor, appAccessor) {\n const INVALID_RESULT = {\n location: -1,\n accessor: null\n };\n\n const {location, name} = this._getAttributeIndex(locationOrName);\n if (!Number.isFinite(location) || location < 0) {\n this.unused[locationOrName] = value;\n log.once(3, () => `unused value ${locationOrName} in ${this.id}`)();\n return INVALID_RESULT;\n }\n\n const accessInfo = this._getAttributeInfo(name || location);\n\n // Attribute location wasn't directly found.\n // Likely due to multi-location attributes (e.g. matrix)\n if (!accessInfo) {\n return INVALID_RESULT;\n }\n\n // Resolve the partial accessors into a final accessor\n const currentAccessor = this.accessors[location] || {};\n const accessor = Accessor.resolve(\n accessInfo.accessor,\n currentAccessor,\n valueAccessor,\n appAccessor\n );\n\n const {size, type} = accessor;\n assert(Number.isFinite(size) && Number.isFinite(type));\n\n return {location, accessor};\n }\n\n _getAttributeInfo(attributeName) {\n return this.configuration && this.configuration.getAttributeInfo(attributeName);\n }\n\n _getAttributeIndex(locationOrName) {\n const location = Number(locationOrName);\n if (Number.isFinite(location)) {\n return {location};\n }\n\n const multiLocation = MULTI_LOCATION_ATTRIBUTE_REGEXP.exec(locationOrName);\n const name = multiLocation ? multiLocation[1] : locationOrName;\n const locationOffset = multiLocation ? Number(multiLocation[2]) : 0;\n\n if (this.configuration) {\n return {\n location: this.configuration.getAttributeLocation(name) + locationOffset,\n name\n };\n }\n\n return {location: -1};\n }\n\n _setAttribute(locationOrName, value) {\n if (value instanceof Buffer) {\n // Signature: {attributeName: Buffer}\n this.setBuffer(locationOrName, value);\n } else if (Array.isArray(value) && value.length && value[0] instanceof Buffer) {\n // Signature: {attributeName: [buffer, accessor]}\n const buffer = value[0];\n const accessor = value[1];\n this.setBuffer(locationOrName, buffer, accessor);\n } else if (ArrayBuffer.isView(value) || Array.isArray(value)) {\n // Signature: {attributeName: constant}, constant == short (typed) array\n const constant = value;\n this.setConstant(locationOrName, constant);\n } else if (value.buffer instanceof Buffer) {\n // luma.gl v7: Support accessor objects with 'buffer' field\n // for interleaved data\n // Signature: {attributeName: {...accessor, buffer}}\n const accessor = value;\n this.setBuffer(locationOrName, accessor.buffer, accessor);\n } else {\n throw new Error(ERR_ATTRIBUTE_TYPE);\n }\n }\n\n // Updates all constant attribute values (constants are used when vertex attributes are disabled).\n // This needs to be done repeatedly since in contrast to buffer bindings,\n // constants are stored on the WebGL context, not the VAO\n _setConstantAttributes(vertexCount, instanceCount) {\n // TODO - use accessor to determine what length to use\n const elementCount = Math.max(vertexCount | 0, instanceCount | 0);\n let constant = this.values[0];\n if (ArrayBuffer.isView(constant)) {\n this._setConstantAttributeZero(constant, elementCount);\n }\n\n for (let location = 1; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {\n constant = this.values[location];\n if (ArrayBuffer.isView(constant)) {\n this._setConstantAttribute(location, constant);\n }\n }\n }\n\n _setConstantAttributeZero(constant, elementCount) {\n if (VertexArrayObject.isSupported(this.gl, {constantAttributeZero: true})) {\n this._setConstantAttribute(0, constant);\n return;\n }\n\n // Get a dummy buffer populated with repeated constants\n const buffer = this.vertexArrayObject.getConstantBuffer(elementCount, constant);\n\n // Set the buffer on location 0\n this.vertexArrayObject.setBuffer(0, buffer, this.accessors[0]);\n }\n\n _setConstantAttribute(location, constant) {\n VertexArrayObject.setConstant(this.gl, location, constant);\n }\n\n // Walks the buffers and updates draw parameters\n _updateDrawParams() {\n const drawParams = {\n isIndexed: false,\n isInstanced: false,\n indexCount: Infinity,\n vertexCount: Infinity,\n instanceCount: Infinity\n };\n\n for (let location = 0; location < this.vertexArrayObject.MAX_ATTRIBUTES; location++) {\n this._updateDrawParamsForLocation(drawParams, location);\n }\n\n if (this.elements) {\n // indexing is autodetected - buffer with target GL.ELEMENT_ARRAY_BUFFER\n // index type is saved for drawElement calls\n drawParams.elementCount = this.elements.getElementCount(this.elements.accessor);\n drawParams.isIndexed = true;\n drawParams.indexType = this.elementsAccessor.type || this.elements.accessor.type;\n drawParams.indexOffset = this.elementsAccessor.offset || 0;\n }\n\n // Post-calculation checks\n if (drawParams.indexCount === Infinity) {\n drawParams.indexCount = 0;\n }\n if (drawParams.vertexCount === Infinity) {\n drawParams.vertexCount = 0;\n }\n if (drawParams.instanceCount === Infinity) {\n drawParams.instanceCount = 0;\n }\n\n return drawParams;\n }\n\n _updateDrawParamsForLocation(drawParams, location) {\n const value = this.values[location];\n const accessor = this.accessors[location];\n\n if (!value) {\n return;\n }\n\n // Check if instanced (whether buffer or constant)\n const {divisor} = accessor;\n const isInstanced = divisor > 0;\n drawParams.isInstanced = drawParams.isInstanced || isInstanced;\n\n if (value instanceof Buffer) {\n const buffer = value;\n\n if (isInstanced) {\n // instance attribute\n const instanceCount = buffer.getVertexCount(accessor);\n drawParams.instanceCount = Math.min(drawParams.instanceCount, instanceCount);\n } else {\n // normal attribute\n const vertexCount = buffer.getVertexCount(accessor);\n drawParams.vertexCount = Math.min(drawParams.vertexCount, vertexCount);\n }\n }\n }\n\n // DEPRECATED in v6.x - but not warnings not properly implemented\n\n setElements(elementBuffer = null, accessor = {}) {\n log.deprecated('setElements', 'setElementBuffer')();\n return this.setElementBuffer(elementBuffer, accessor);\n }\n}\n","// TODO / DEPRECATED - delete when confident that probe.gl logging implements all opts\n/* eslint-disable no-console */\nfunction formatArrayValue(v, opts) {\n const {maxElts = 16, size = 1} = opts;\n let string = '[';\n for (let i = 0; i < v.length && i < maxElts; ++i) {\n if (i > 0) {\n string += `,${i % size === 0 ? ' ' : ''}`;\n }\n string += formatValue(v[i], opts);\n }\n const terminator = v.length > maxElts ? '...' : ']';\n return `${string}${terminator}`;\n}\n\nexport function formatValue(v, opts = {}) {\n const EPSILON = 1e-16;\n const {isInteger = false} = opts;\n if (Array.isArray(v) || ArrayBuffer.isView(v)) {\n return formatArrayValue(v, opts);\n }\n if (!Number.isFinite(v)) {\n return String(v);\n }\n if (Math.abs(v) < EPSILON) {\n return isInteger ? '0' : '0.';\n }\n if (isInteger) {\n return v.toFixed(0);\n }\n if (Math.abs(v) > 100 && Math.abs(v) < 10000) {\n return v.toFixed(0);\n }\n const string = v.toPrecision(2);\n const decimal = string.indexOf('.0');\n return decimal === string.length - 2 ? string.slice(0, -1) : string;\n}\n","import Buffer from '../classes/buffer';\nimport {getKey} from '../webgl-utils/constants-to-keys';\nimport {getCompositeGLType} from '../webgl-utils/attribute-utils';\nimport {formatValue} from '../utils/format-value';\n\n// Creates object suitable as input for console.table\nexport function getDebugTableForVertexArray({vertexArray, header = 'Attributes'}) {\n if (!vertexArray.configuration) {\n return {};\n }\n\n const table = {}; // {[header]: {}};\n\n // Add index (elements) if available\n if (vertexArray.elements) {\n // const elements = Object.assign({size: 1}, vertexArray.elements);\n table.ELEMENT_ARRAY_BUFFER = getDebugTableRow(vertexArray, vertexArray.elements, null, header);\n }\n\n // Add used attributes\n const attributes = vertexArray.values;\n\n for (const attributeLocation in attributes) {\n const info = vertexArray._getAttributeInfo(attributeLocation);\n if (info) {\n let rowHeader = `${attributeLocation}: ${info.name}`;\n const accessor = vertexArray.accessors[info.location];\n if (accessor) {\n rowHeader = `${attributeLocation}: ${getGLSLDeclaration(info.name, accessor)}`;\n }\n table[rowHeader] = getDebugTableRow(\n vertexArray,\n attributes[attributeLocation],\n accessor,\n header\n );\n }\n }\n\n return table;\n}\n\n/* eslint-disable max-statements */\nfunction getDebugTableRow(vertexArray, attribute, accessor, header) {\n const {gl} = vertexArray;\n\n if (!attribute) {\n return {\n [header]: 'null',\n 'Format ': 'N/A'\n };\n }\n\n let type = 'NOT PROVIDED';\n let size = 1;\n let verts = 0;\n let bytes = 0;\n\n let isInteger;\n let marker;\n let value;\n\n if (accessor) {\n type = accessor.type;\n size = accessor.size;\n\n // Generate a type name by dropping Array from Float32Array etc.\n type = String(type).replace('Array', '');\n\n // Look for 'nt' to detect integer types, e.g. Int32Array, Uint32Array\n isInteger = type.indexOf('nt') !== -1;\n }\n\n if (attribute instanceof Buffer) {\n const buffer = attribute;\n\n const {data, changed} = buffer.getDebugData();\n marker = changed ? '*' : '';\n\n value = data;\n // @ts-ignore\n bytes = buffer.byteLength;\n // @ts-ignore\n verts = bytes / data.BYTES_PER_ELEMENT / size;\n\n let format;\n\n if (accessor) {\n const instanced = accessor.divisor > 0;\n format = `${instanced ? 'I ' : 'P '} ${verts} (x${size}=${bytes} bytes ${getKey(gl, type)})`;\n } else {\n // element buffer\n isInteger = true;\n format = `${bytes} bytes`;\n }\n\n return {\n [header]: `${marker}${formatValue(value, {size, isInteger})}`,\n 'Format ': format\n };\n }\n\n // CONSTANT VALUE\n value = attribute;\n size = attribute.length;\n // Generate a type name by dropping Array from Float32Array etc.\n type = String(attribute.constructor.name).replace('Array', '');\n // Look for 'nt' to detect integer types, e.g. Int32Array, Uint32Array\n isInteger = type.indexOf('nt') !== -1;\n\n return {\n [header]: `${formatValue(value, {size, isInteger})} (constant)`,\n 'Format ': `${size}x${type} (constant)`\n };\n}\n/* eslint-ensable max-statements */\n\nfunction getGLSLDeclaration(name, accessor) {\n const {type, size} = accessor;\n const typeAndName = getCompositeGLType(type, size);\n return typeAndName ? `${name} (${typeAndName.name})` : name;\n}\n","import {assert} from '../utils/assert';\nimport {formatValue} from '../utils/format-value';\n\n// Prepares a table suitable for console.table\n/* eslint-disable max-statements, complexity */\nexport function getDebugTableForUniforms({\n header = 'Uniforms',\n program,\n uniforms,\n undefinedOnly = false\n}) {\n assert(program);\n\n const SHADER_MODULE_UNIFORM_REGEXP = '.*_.*';\n const PROJECT_MODULE_UNIFORM_REGEXP = '.*Matrix'; // TODO - Use explicit list\n\n const uniformLocations = program._uniformSetters;\n const table = {}; // {[header]: {}};\n\n // Add program's provided uniforms (in alphabetical order)\n const uniformNames = Object.keys(uniformLocations).sort();\n\n let count = 0;\n\n // First add non-underscored uniforms (assumed not coming from shader modules)\n for (const uniformName of uniformNames) {\n if (\n !uniformName.match(SHADER_MODULE_UNIFORM_REGEXP) &&\n !uniformName.match(PROJECT_MODULE_UNIFORM_REGEXP)\n ) {\n if (addUniformToTable({table, header, uniforms, uniformName, undefinedOnly})) {\n count++;\n }\n }\n }\n\n // add underscored uniforms (assumed from shader modules)\n for (const uniformName of uniformNames) {\n if (uniformName.match(PROJECT_MODULE_UNIFORM_REGEXP)) {\n if (addUniformToTable({table, header, uniforms, uniformName, undefinedOnly})) {\n count++;\n }\n }\n }\n\n for (const uniformName of uniformNames) {\n if (!table[uniformName]) {\n if (addUniformToTable({table, header, uniforms, uniformName, undefinedOnly})) {\n count++;\n }\n }\n }\n\n // Create a table of unused uniforms\n let unusedCount = 0;\n const unusedTable = {};\n if (!undefinedOnly) {\n for (const uniformName in uniforms) {\n const uniform = uniforms[uniformName];\n if (!table[uniformName]) {\n unusedCount++;\n unusedTable[uniformName] = {\n Type: `NOT USED: ${uniform}`,\n [header]: formatValue(uniform)\n };\n }\n }\n }\n\n return {table, count, unusedTable, unusedCount};\n}\n\n// Helper\nfunction addUniformToTable({table, header, uniforms, uniformName, undefinedOnly}) {\n const value = uniforms[uniformName];\n const isDefined = isUniformDefined(value);\n if (!undefinedOnly || !isDefined) {\n table[uniformName] = {\n // Add program's unprovided uniforms\n [header]: isDefined ? formatValue(value) : 'N/A',\n 'Uniform Type': isDefined ? value : 'NOT PROVIDED'\n };\n return true;\n }\n return false;\n}\n\nfunction isUniformDefined(value) {\n return value !== undefined && value !== null;\n}\n","import {getCompositeGLType} from '../webgl-utils/attribute-utils';\n\nexport function getDebugTableForProgramConfiguration(config) {\n const table = {};\n\n const header = `Accessors for ${config.id}`;\n\n for (const attributeInfo of config.attributeInfos) {\n if (attributeInfo) {\n const glslDeclaration = getGLSLDeclaration(attributeInfo);\n table[`in ${glslDeclaration}`] = {[header]: JSON.stringify(attributeInfo.accessor)};\n }\n }\n\n for (const varyingInfo of config.varyingInfos) {\n if (varyingInfo) {\n const glslDeclaration = getGLSLDeclaration(varyingInfo);\n table[`out ${glslDeclaration}`] = {[header]: JSON.stringify(varyingInfo.accessor)};\n }\n }\n\n return table;\n}\n\nfunction getGLSLDeclaration(attributeInfo) {\n const {type, size} = attributeInfo.accessor;\n const typeAndName = getCompositeGLType(type, size);\n if (typeAndName) {\n return `${typeAndName.name} ${attributeInfo.name}`;\n }\n return attributeInfo.name;\n}\n","import GL from '@luma.gl/constants';\nimport {Buffer, assert} from '@luma.gl/webgl';\n\n// Support for mapping new geometries with glTF attribute names to \"classic\" luma.gl shader names\nconst GLTF_TO_LUMA_ATTRIBUTE_MAP = {\n POSITION: 'positions',\n NORMAL: 'normals',\n COLOR_0: 'colors',\n TEXCOORD_0: 'texCoords',\n TEXCOORD_1: 'texCoords1',\n TEXCOORD_2: 'texCoords2'\n};\n\nexport function getBuffersFromGeometry(gl, geometry, options) {\n const buffers = {};\n let indices = geometry.indices;\n\n for (const name in geometry.attributes) {\n const attribute = geometry.attributes[name];\n const remappedName = mapAttributeName(name, options);\n\n if (name === 'indices') {\n indices = attribute;\n } else if (attribute.constant) {\n buffers[remappedName] = attribute.value;\n } else {\n const typedArray = attribute.value;\n // Create accessor by copying the attribute and removing `value``\n const accessor = {...attribute};\n delete accessor.value;\n buffers[remappedName] = [new Buffer(gl, typedArray), accessor];\n\n inferAttributeAccessor(name, accessor);\n }\n }\n\n if (indices) {\n const data = indices.value || indices;\n assert(\n data instanceof Uint16Array || data instanceof Uint32Array,\n 'attribute array for \"indices\" must be of integer type'\n );\n const accessor = {\n size: 1,\n isIndexed: indices.isIndexed === undefined ? true : indices.isIndexed\n };\n buffers.indices = [\n new Buffer(gl, {\n data,\n target: GL.ELEMENT_ARRAY_BUFFER\n }),\n accessor\n ];\n }\n\n return buffers;\n}\n\nfunction mapAttributeName(name, options) {\n const {attributeMap = GLTF_TO_LUMA_ATTRIBUTE_MAP} = options || {};\n return (attributeMap && attributeMap[name]) || name;\n}\n\n// Check for well known attribute names\n// eslint-disable-next-line complexity\nexport function inferAttributeAccessor(attributeName, attribute) {\n let category;\n switch (attributeName) {\n case 'texCoords':\n case 'texCoord1':\n case 'texCoord2':\n case 'texCoord3':\n category = 'uvs';\n break;\n case 'vertices':\n case 'positions':\n case 'normals':\n case 'pickingColors':\n category = 'vectors';\n break;\n default:\n }\n\n // Check for categorys\n switch (category) {\n case 'vectors':\n attribute.size = attribute.size || 3;\n break;\n case 'uvs':\n attribute.size = attribute.size || 2;\n break;\n default:\n }\n\n assert(Number.isFinite(attribute.size), `attribute ${attributeName} needs size`);\n}\n","/* eslint-disable complexity */\n\nimport GL from '@luma.gl/constants';\nimport {isWebGL} from '@luma.gl/gltools';\nimport ProgramManager from './program-manager';\nimport {\n Program,\n VertexArray,\n clear,\n TransformFeedback,\n Buffer,\n log,\n isObjectEmpty,\n uid,\n assert\n} from '@luma.gl/webgl';\nimport {\n getDebugTableForUniforms,\n getDebugTableForVertexArray,\n getDebugTableForProgramConfiguration\n} from '@luma.gl/webgl';\nimport {getBuffersFromGeometry} from './model-utils';\n\nconst LOG_DRAW_PRIORITY = 2;\nconst LOG_DRAW_TIMEOUT = 10000;\n\nconst ERR_MODEL_PARAMS = 'Model needs drawMode and vertexCount';\n\nconst NOOP = () => {};\nconst DRAW_PARAMS = {};\n\nexport default class Model {\n constructor(gl, props = {}) {\n // Deduce a helpful id\n const {id = uid('model')} = props;\n assert(isWebGL(gl));\n this.id = id;\n this.gl = gl;\n this.id = props.id || uid('Model');\n this.lastLogTime = 0; // TODO - move to probe.gl\n this.animated = false;\n this.initialize(props);\n }\n\n initialize(props) {\n this.props = {};\n\n this.programManager = props.programManager || ProgramManager.getDefaultProgramManager(this.gl);\n this._programManagerState = -1;\n this._managedProgram = false;\n\n const {\n program = null,\n vs,\n fs,\n modules,\n defines,\n inject,\n varyings,\n bufferMode,\n transpileToGLSL100\n } = props;\n\n this.programProps = {\n program,\n vs,\n fs,\n modules,\n defines,\n inject,\n varyings,\n bufferMode,\n transpileToGLSL100\n };\n this.program = null;\n this.vertexArray = null;\n this._programDirty = true;\n\n // Initialize state\n this.userData = {};\n this.needsRedraw = true;\n\n // Attributes and buffers\n // Model manages auto Buffer creation from typed arrays\n this._attributes = {}; // All attributes\n this.attributes = {}; // User defined attributes\n\n // Model manages uniform animation\n this.uniforms = {};\n\n // picking options\n this.pickable = true;\n\n this._checkProgram();\n\n this.setUniforms(\n Object.assign(\n {},\n this.getModuleUniforms(props.moduleSettings) // Get unforms for supplied parameters\n )\n );\n\n this.drawMode = props.drawMode !== undefined ? props.drawMode : GL.TRIANGLES;\n this.vertexCount = props.vertexCount || 0;\n\n // Track buffers created by setGeometry\n this.geometryBuffers = {};\n\n // geometry might have set drawMode and vertexCount\n this.isInstanced = props.isInstanced || props.instanced || props.instanceCount > 0;\n\n this._setModelProps(props);\n\n // TODO - just to unbreak deck.gl 7.0-beta, remove as soon as updated\n this.geometry = {};\n\n // assert(program || program instanceof Program);\n assert(this.drawMode !== undefined && Number.isFinite(this.vertexCount), ERR_MODEL_PARAMS);\n }\n\n setProps(props) {\n this._setModelProps(props);\n }\n\n delete() {\n // delete all attributes created by this model\n // TODO - should buffer deletes be handled by vertex array?\n for (const key in this._attributes) {\n if (this._attributes[key] !== this.attributes[key]) {\n this._attributes[key].delete();\n }\n }\n\n if (this._managedProgram) {\n this.programManager.release(this.program);\n this._managedProgram = false;\n }\n\n this.vertexArray.delete();\n\n this._deleteGeometryBuffers();\n }\n\n // GETTERS\n\n getDrawMode() {\n return this.drawMode;\n }\n\n getVertexCount() {\n return this.vertexCount;\n }\n\n getInstanceCount() {\n return this.instanceCount;\n }\n\n getAttributes() {\n return this.attributes;\n }\n\n getProgram() {\n return this.program;\n }\n\n setProgram(props) {\n const {\n program,\n vs,\n fs,\n modules,\n defines,\n inject,\n varyings,\n bufferMode,\n transpileToGLSL100\n } = props;\n this.programProps = {\n program,\n vs,\n fs,\n modules,\n defines,\n inject,\n varyings,\n bufferMode,\n transpileToGLSL100\n };\n this._programDirty = true;\n }\n\n getUniforms() {\n return this.uniforms;\n }\n\n // SETTERS\n\n setDrawMode(drawMode) {\n this.drawMode = drawMode;\n return this;\n }\n\n setVertexCount(vertexCount) {\n assert(Number.isFinite(vertexCount));\n this.vertexCount = vertexCount;\n return this;\n }\n\n setInstanceCount(instanceCount) {\n assert(Number.isFinite(instanceCount));\n this.instanceCount = instanceCount;\n return this;\n }\n\n setGeometry(geometry) {\n this.drawMode = geometry.drawMode;\n this.vertexCount = geometry.getVertexCount();\n\n this._deleteGeometryBuffers();\n\n this.geometryBuffers = getBuffersFromGeometry(this.gl, geometry);\n this.vertexArray.setAttributes(this.geometryBuffers);\n return this;\n }\n\n setAttributes(attributes = {}) {\n // Avoid setting needsRedraw if no attributes\n if (isObjectEmpty(attributes)) {\n return this;\n }\n\n const normalizedAttributes = {};\n for (const name in attributes) {\n const attribute = attributes[name];\n // The `getValue` call provides support for deck.gl `Attribute` class\n // TODO - remove once deck refactoring completes\n normalizedAttributes[name] = attribute.getValue ? attribute.getValue() : attribute;\n }\n\n this.vertexArray.setAttributes(normalizedAttributes);\n return this;\n }\n\n // TODO - should actually set the uniforms\n setUniforms(uniforms = {}) {\n Object.assign(this.uniforms, uniforms);\n\n return this;\n }\n\n getModuleUniforms(opts) {\n this._checkProgram();\n\n const getUniforms = this.programManager.getUniforms(this.program);\n\n if (getUniforms) {\n return getUniforms(opts);\n }\n\n return {};\n }\n\n updateModuleSettings(opts) {\n const uniforms = this.getModuleUniforms(opts || {});\n return this.setUniforms(uniforms);\n }\n\n // DRAW CALLS\n\n clear(opts) {\n clear(this.program.gl, opts);\n return this;\n }\n\n draw(opts = {}) {\n // Lazy update program and vertex array\n this._checkProgram();\n\n const {\n moduleSettings = null,\n framebuffer,\n uniforms = {},\n attributes = {},\n transformFeedback = this.transformFeedback,\n parameters = {},\n vertexArray = this.vertexArray\n } = opts;\n\n // Update model with any just provided attributes, settings or uniforms\n this.setAttributes(attributes);\n this.updateModuleSettings(moduleSettings);\n this.setUniforms(uniforms);\n\n let logPriority;\n\n if (log.priority >= LOG_DRAW_PRIORITY) {\n logPriority = this._logDrawCallStart(LOG_DRAW_PRIORITY);\n }\n\n const drawParams = this.vertexArray.getDrawParams();\n const {\n isIndexed = drawParams.isIndexed,\n indexType = drawParams.indexType,\n indexOffset = drawParams.indexOffset,\n vertexArrayInstanced = drawParams.isInstanced\n } = this.props;\n\n if (vertexArrayInstanced && !this.isInstanced) {\n log.warn('Found instanced attributes on non-instanced model', this.id)();\n }\n\n const {isInstanced, instanceCount} = this;\n\n const {onBeforeRender = NOOP, onAfterRender = NOOP} = this.props;\n\n onBeforeRender();\n\n this.program.setUniforms(this.uniforms);\n\n const didDraw = this.program.draw(\n Object.assign(DRAW_PARAMS, opts, {\n logPriority,\n uniforms: null, // Already set (may contain \"function values\" not understood by Program)\n framebuffer,\n parameters,\n drawMode: this.getDrawMode(),\n vertexCount: this.getVertexCount(),\n vertexArray,\n transformFeedback,\n isIndexed,\n indexType,\n isInstanced,\n instanceCount,\n offset: isIndexed ? indexOffset : 0\n })\n );\n\n onAfterRender();\n\n if (log.priority >= LOG_DRAW_PRIORITY) {\n this._logDrawCallEnd(logPriority, vertexArray, framebuffer);\n }\n\n return didDraw;\n }\n\n // Draw call for transform feedback\n transform(opts = {}) {\n const {discard = true, feedbackBuffers, unbindModels = []} = opts;\n\n let {parameters} = opts;\n\n if (feedbackBuffers) {\n this._setFeedbackBuffers(feedbackBuffers);\n }\n\n if (discard) {\n parameters = Object.assign({}, parameters, {[GL.RASTERIZER_DISCARD]: discard});\n }\n\n unbindModels.forEach(model => model.vertexArray.unbindBuffers());\n try {\n this.draw(Object.assign({}, opts, {parameters}));\n } finally {\n unbindModels.forEach(model => model.vertexArray.bindBuffers());\n }\n\n return this;\n }\n\n // DEPRECATED METHODS\n\n render(uniforms = {}) {\n log.warn('Model.render() is deprecated. Use Model.setUniforms() and Model.draw()')();\n return this.setUniforms(uniforms).draw();\n }\n\n // PRIVATE METHODS\n\n _setModelProps(props) {\n Object.assign(this.props, props);\n\n if ('uniforms' in props) {\n this.setUniforms(props.uniforms);\n }\n\n if ('pickable' in props) {\n this.pickable = props.pickable;\n }\n\n if ('instanceCount' in props) {\n this.instanceCount = props.instanceCount;\n }\n if ('geometry' in props) {\n this.setGeometry(props.geometry);\n }\n\n // webgl settings\n if ('attributes' in props) {\n this.setAttributes(props.attributes);\n }\n if ('_feedbackBuffers' in props) {\n this._setFeedbackBuffers(props._feedbackBuffers);\n }\n }\n\n _checkProgram() {\n const needsUpdate =\n this._programDirty || this.programManager.stateHash !== this._programManagerState;\n\n if (!needsUpdate) {\n return;\n }\n\n let {program} = this.programProps;\n\n if (program) {\n this._managedProgram = false;\n } else {\n const {\n vs,\n fs,\n modules,\n inject,\n defines,\n varyings,\n bufferMode,\n transpileToGLSL100\n } = this.programProps;\n program = this.programManager.get({\n vs,\n fs,\n modules,\n inject,\n defines,\n varyings,\n bufferMode,\n transpileToGLSL100\n });\n if (this.program && this._managedProgram) {\n this.programManager.release(this.program);\n }\n this._programManagerState = this.programManager.stateHash;\n this._managedProgram = true;\n }\n\n assert(program instanceof Program, 'Model needs a program');\n\n this._programDirty = false;\n\n if (program === this.program) {\n return;\n }\n\n this.program = program;\n\n if (this.vertexArray) {\n // @ts-ignore TODO\n this.vertexArray.setProps({program: this.program, attributes: this.vertexArray.attributes});\n } else {\n this.vertexArray = new VertexArray(this.gl, {program: this.program});\n }\n\n // Make sure we have some reasonable default uniforms in place\n this.setUniforms(\n Object.assign(\n {},\n this.getModuleUniforms() // Get all default uniforms,\n )\n );\n }\n\n _deleteGeometryBuffers() {\n for (const name in this.geometryBuffers) {\n // Buffer is raw value (for indices) or first element of [buffer, accessor] pair\n const buffer = this.geometryBuffers[name][0] || this.geometryBuffers[name];\n if (buffer instanceof Buffer) {\n buffer.delete();\n }\n }\n }\n\n // Updates (evaluates) all function valued uniforms based on a new set of animationProps\n // experimental\n _setAnimationProps(animationProps) {\n if (this.animated) {\n assert(animationProps, 'Model.draw(): animated uniforms but no animationProps');\n // const animatedUniforms = this._evaluateAnimateUniforms(animationProps);\n // Object.assign(this.uniforms, animatedUniforms);\n }\n }\n\n // Transform Feedback\n\n _setFeedbackBuffers(feedbackBuffers = {}) {\n // Avoid setting needsRedraw if no feedbackBuffers\n if (isObjectEmpty(feedbackBuffers)) {\n return this;\n }\n\n const {gl} = this.program;\n this.transformFeedback =\n this.transformFeedback ||\n new TransformFeedback(gl, {\n program: this.program\n });\n\n this.transformFeedback.setBuffers(feedbackBuffers);\n return this;\n }\n\n _logDrawCallStart(logLevel) {\n const logDrawTimeout = logLevel > 3 ? 0 : LOG_DRAW_TIMEOUT;\n if (Date.now() - this.lastLogTime < logDrawTimeout) {\n return undefined;\n }\n\n this.lastLogTime = Date.now();\n\n log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, {collapsed: log.level <= 2})();\n\n return logLevel;\n }\n\n _logDrawCallEnd(logLevel, vertexArray, uniforms, framebuffer) {\n // HACK: logLevel === undefined means logDrawCallStart didn't run\n if (logLevel === undefined) {\n return;\n }\n\n const attributeTable = getDebugTableForVertexArray({\n vertexArray,\n header: `${this.id} attributes`,\n // @ts-ignore\n attributes: this._attributes\n });\n\n const {table: uniformTable, unusedTable, unusedCount} = getDebugTableForUniforms({\n header: `${this.id} uniforms`,\n program: this.program,\n uniforms: Object.assign({}, this.program.uniforms, uniforms)\n });\n\n // log missing uniforms\n const {table: missingTable, count: missingCount} = getDebugTableForUniforms({\n header: `${this.id} uniforms`,\n program: this.program,\n uniforms: Object.assign({}, this.program.uniforms, uniforms),\n undefinedOnly: true\n });\n\n if (missingCount > 0) {\n log.log('MISSING UNIFORMS', Object.keys(missingTable))();\n // log.table(logLevel, missingTable)();\n }\n if (unusedCount > 0) {\n log.log('UNUSED UNIFORMS', Object.keys(unusedTable))();\n // log.log(logLevel, 'Unused uniforms ', unusedTable)();\n }\n\n const configTable = getDebugTableForProgramConfiguration(this.vertexArray.configuration);\n\n log.table(logLevel, attributeTable)();\n\n log.table(logLevel, uniformTable)();\n\n log.table(logLevel + 1, configTable)();\n\n if (framebuffer) {\n framebuffer.log({logLevel: LOG_DRAW_PRIORITY, message: `Rendered to ${framebuffer.id}`});\n }\n\n log.groupEnd(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`)();\n }\n}\n","import getHiResTimestamp from '../utils/hi-res-timestamp';\n\nexport default class Stat {\n constructor(name, type) {\n this.name = name;\n this.type = type;\n this.sampleSize = 1;\n this.reset();\n }\n\n setSampleSize(samples) {\n this.sampleSize = samples;\n\n return this;\n }\n\n // Call to increment count (+1)\n incrementCount() {\n this.addCount(1);\n\n return this;\n }\n\n // Call to decrement count (-1)\n decrementCount() {\n this.subtractCount(1);\n\n return this;\n }\n\n // Increase count\n addCount(value) {\n this._count += value;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n // Decrease count\n subtractCount(value) {\n this._count -= value;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n // Add an arbitrary timing and bump the count\n addTime(time) {\n this._time += time;\n this.lastTiming = time;\n this._samples++;\n this._checkSampling();\n\n return this;\n }\n\n // Start a timer\n timeStart() {\n this._startTime = getHiResTimestamp();\n this._timerPending = true;\n\n return this;\n }\n\n // End a timer. Adds to time and bumps the timing count.\n timeEnd() {\n if (!this._timerPending) {\n return this;\n }\n\n this.addTime(getHiResTimestamp() - this._startTime);\n this._timerPending = false;\n this._checkSampling();\n\n return this;\n }\n\n getSampleAverageCount() {\n return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;\n }\n\n // Calculate average time / count for the previous window\n getSampleAverageTime() {\n return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;\n }\n\n // Calculate counts per second for the previous window\n getSampleHz() {\n return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1000) : 0;\n }\n\n getAverageCount() {\n return this.samples > 0 ? this.count / this.samples : 0;\n }\n\n // Calculate average time / count\n getAverageTime() {\n return this.samples > 0 ? this.time / this.samples : 0;\n }\n\n // Calculate counts per second\n getHz() {\n return this.time > 0 ? this.samples / (this.time / 1000) : 0;\n }\n\n reset() {\n this.time = 0;\n this.count = 0;\n this.samples = 0;\n this.lastTiming = 0;\n this.lastSampleTime = 0;\n this.lastSampleCount = 0;\n this._count = 0;\n this._time = 0;\n this._samples = 0;\n this._startTime = 0;\n this._timerPending = false;\n\n return this;\n }\n\n _checkSampling() {\n if (this._samples === this.sampleSize) {\n this.lastSampleTime = this._time;\n this.lastSampleCount = this._count;\n this.count += this._count;\n this.time += this._time;\n this.samples += this._samples;\n this._time = 0;\n this._count = 0;\n this._samples = 0;\n }\n }\n}\n","import Stat from './stat';\n\nexport default class Stats {\n constructor({id, stats}) {\n this.id = id;\n this.stats = {};\n\n this._initializeStats(stats);\n\n Object.seal(this);\n }\n\n // Acquire a stat. Create if it doesn't exist.\n get(name, type = 'count') {\n return this._getOrCreate({name, type});\n }\n\n get size() {\n return Object.keys(this.stats).length;\n }\n\n // Reset all stats\n reset() {\n for (const key in this.stats) {\n this.stats[key].reset();\n }\n\n return this;\n }\n\n forEach(fn) {\n for (const key in this.stats) {\n fn(this.stats[key]);\n }\n }\n\n getTable() {\n const table = {};\n this.forEach(stat => {\n table[stat.name] = {\n time: stat.time || 0,\n count: stat.count || 0,\n average: stat.getAverageTime() || 0,\n hz: stat.getHz() || 0\n };\n });\n\n return table;\n }\n\n _initializeStats(stats = []) {\n stats.forEach(stat => this._getOrCreate(stat));\n }\n\n _getOrCreate(stat) {\n if (!stat || !stat.name) {\n return null;\n }\n\n const {name, type} = stat;\n if (!this.stats[name]) {\n if (stat instanceof Stat) {\n this.stats[name] = stat;\n } else {\n this.stats[name] = new Stat(name, type);\n }\n }\n return this.stats[name];\n }\n}\n","/**\n * @module helpers\n */\n/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n *\n * @memberof helpers\n * @type {number}\n */\nexport var earthRadius = 6371008.8;\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var factors = {\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n degrees: earthRadius / 111325,\n feet: earthRadius * 3.28084,\n inches: earthRadius * 39.37,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n meters: earthRadius,\n metres: earthRadius,\n miles: earthRadius / 1609.344,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n nauticalmiles: earthRadius / 1852,\n radians: 1,\n yards: earthRadius * 1.0936,\n};\n/**\n * Units of measurement factors based on 1 meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var unitsFactors = {\n centimeters: 100,\n centimetres: 100,\n degrees: 1 / 111325,\n feet: 3.28084,\n inches: 39.37,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n meters: 1,\n metres: 1,\n miles: 1 / 1609.344,\n millimeters: 1000,\n millimetres: 1000,\n nauticalmiles: 1 / 1852,\n radians: 1 / earthRadius,\n yards: 1.0936133,\n};\n/**\n * Area of measurement factors based on 1 square meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var areaFactors = {\n acres: 0.000247105,\n centimeters: 10000,\n centimetres: 10000,\n feet: 10.763910417,\n hectares: 0.0001,\n inches: 1550.003100006,\n kilometers: 0.000001,\n kilometres: 0.000001,\n meters: 1,\n metres: 1,\n miles: 3.86e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nexport function feature(geom, properties, options) {\n if (options === void 0) { options = {}; }\n var feat = { type: \"Feature\" };\n if (options.id === 0 || options.id) {\n feat.id = options.id;\n }\n if (options.bbox) {\n feat.bbox = options.bbox;\n }\n feat.properties = properties || {};\n feat.geometry = geom;\n return feat;\n}\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = \"Point\";\n * var coordinates = [110, 50];\n * var geometry = turf.geometry(type, coordinates);\n * // => geometry\n */\nexport function geometry(type, coordinates, _options) {\n if (_options === void 0) { _options = {}; }\n switch (type) {\n case \"Point\":\n return point(coordinates).geometry;\n case \"LineString\":\n return lineString(coordinates).geometry;\n case \"Polygon\":\n return polygon(coordinates).geometry;\n case \"MultiPoint\":\n return multiPoint(coordinates).geometry;\n case \"MultiLineString\":\n return multiLineString(coordinates).geometry;\n case \"MultiPolygon\":\n return multiPolygon(coordinates).geometry;\n default:\n throw new Error(type + \" is invalid\");\n }\n}\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nexport function point(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (!coordinates) {\n throw new Error(\"coordinates is required\");\n }\n if (!Array.isArray(coordinates)) {\n throw new Error(\"coordinates must be an Array\");\n }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be at least 2 numbers long\");\n }\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {\n throw new Error(\"coordinates must contain numbers\");\n }\n var geom = {\n type: \"Point\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nexport function points(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nexport function polygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {\n var ring = coordinates_1[_i];\n if (ring.length < 4) {\n throw new Error(\"Each LinearRing of a Polygon must have 4 or more Positions.\");\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n }\n }\n var geom = {\n type: \"Polygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nexport function polygons(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nexport function lineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n var geom = {\n type: \"LineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nexport function lineStrings(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nexport function featureCollection(features, options) {\n if (options === void 0) { options = {}; }\n var fc = { type: \"FeatureCollection\" };\n if (options.id) {\n fc.id = options.id;\n }\n if (options.bbox) {\n fc.bbox = options.bbox;\n }\n fc.features = features;\n return fc;\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nexport function multiLineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiLineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nexport function multiPoint(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPoint\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nexport function multiPolygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPolygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = turf.geometry(\"Point\", [100, 0]);\n * var line = turf.geometry(\"LineString\", [[101, 0], [102, 1]]);\n * var collection = turf.geometryCollection([pt, line]);\n *\n * // => collection\n */\nexport function geometryCollection(geometries, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"GeometryCollection\",\n geometries: geometries,\n };\n return feature(geom, properties, options);\n}\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nexport function round(num, precision) {\n if (precision === void 0) { precision = 0; }\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nexport function radiansToLength(radians, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return radians * factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nexport function lengthToRadians(distance, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return distance / factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nexport function lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nexport function bearingToAzimuth(bearing) {\n var angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nexport function radiansToDegrees(radians) {\n var degrees = radians % (2 * Math.PI);\n return (degrees * 180) / Math.PI;\n}\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nexport function degreesToRadians(degrees) {\n var radians = degrees % 360;\n return (radians * Math.PI) / 180;\n}\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] of the length\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted length\n */\nexport function convertLength(length, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"kilometers\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(length >= 0)) {\n throw new Error(\"length must be a positive number\");\n }\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);\n}\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches, hectares\n * @param {number} area to be converted\n * @param {Units} [originalUnit=\"meters\"] of the distance\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted area\n */\nexport function convertArea(area, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"meters\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n var startFactor = areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n var finalFactor = areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n return (area / startFactor) * finalFactor;\n}\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nexport function isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nexport function isObject(input) {\n return !!input && input.constructor === Object;\n}\n/**\n * Validate BBox\n *\n * @private\n * @param {Array} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nexport function validateBBox(bbox) {\n if (!bbox) {\n throw new Error(\"bbox is required\");\n }\n if (!Array.isArray(bbox)) {\n throw new Error(\"bbox must be an Array\");\n }\n if (bbox.length !== 4 && bbox.length !== 6) {\n throw new Error(\"bbox must be an Array of 4 or 6 numbers\");\n }\n bbox.forEach(function (num) {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nexport function validateId(id) {\n if (!id) {\n throw new Error(\"id is required\");\n }\n if ([\"string\", \"number\"].indexOf(typeof id) === -1) {\n throw new Error(\"id must be a number or a string\");\n }\n}\n","import { isNumber, } from \"@turf/helpers\";\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array|Geometry|Feature} coord GeoJSON Point or an Array of numbers\n * @returns {Array} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nexport function getCoord(coord) {\n if (!coord) {\n throw new Error(\"coord is required\");\n }\n if (!Array.isArray(coord)) {\n if (coord.type === \"Feature\" &&\n coord.geometry !== null &&\n coord.geometry.type === \"Point\") {\n return coord.geometry.coordinates;\n }\n if (coord.type === \"Point\") {\n return coord.coordinates;\n }\n }\n if (Array.isArray(coord) &&\n coord.length >= 2 &&\n !Array.isArray(coord[0]) &&\n !Array.isArray(coord[1])) {\n return coord;\n }\n throw new Error(\"coord must be GeoJSON Point or an Array of numbers\");\n}\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nexport function getCoords(coords) {\n if (Array.isArray(coords)) {\n return coords;\n }\n // Feature\n if (coords.type === \"Feature\") {\n if (coords.geometry !== null) {\n return coords.geometry.coordinates;\n }\n }\n else {\n // Geometry\n if (coords.coordinates) {\n return coords.coordinates;\n }\n }\n throw new Error(\"coords must be GeoJSON Feature, Geometry Object or an Array\");\n}\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nexport function containsNumber(coordinates) {\n if (coordinates.length > 1 &&\n isNumber(coordinates[0]) &&\n isNumber(coordinates[1])) {\n return true;\n }\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error(\"coordinates must only contain numbers\");\n}\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nexport function geojsonType(value, type, name) {\n if (!type || !name) {\n throw new Error(\"type and name required\");\n }\n if (!value || value.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n value.type);\n }\n}\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nexport function featureOf(feature, type, name) {\n if (!feature) {\n throw new Error(\"No feature passed\");\n }\n if (!name) {\n throw new Error(\".featureOf() requires a name\");\n }\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type);\n }\n}\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nexport function collectionOf(featureCollection, type, name) {\n if (!featureCollection) {\n throw new Error(\"No featureCollection passed\");\n }\n if (!name) {\n throw new Error(\".collectionOf() requires a name\");\n }\n if (!featureCollection || featureCollection.type !== \"FeatureCollection\") {\n throw new Error(\"Invalid input to \" + name + \", FeatureCollection required\");\n }\n for (var _i = 0, _a = featureCollection.features; _i < _a.length; _i++) {\n var feature = _a[_i];\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\"Invalid input to \" + name + \", Feature with geometry required\");\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type);\n }\n }\n}\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nexport function getGeom(geojson) {\n if (geojson.type === \"Feature\") {\n return geojson.geometry;\n }\n return geojson;\n}\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message (unused)\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nexport function getType(geojson, _name) {\n if (geojson.type === \"FeatureCollection\") {\n return \"FeatureCollection\";\n }\n if (geojson.type === \"GeometryCollection\") {\n return \"GeometryCollection\";\n }\n if (geojson.type === \"Feature\" && geojson.geometry !== null) {\n return geojson.geometry.type;\n }\n return geojson.type;\n}\n","// https://en.wikipedia.org/wiki/Rhumb_line\nimport { degreesToRadians, radiansToDegrees } from \"@turf/helpers\";\nimport { getCoord } from \"@turf/invariant\";\n/**\n * Takes two {@link Point|points} and finds the bearing angle between them along a Rhumb line\n * i.e. the angle measured in degrees start the north line (0 degrees)\n *\n * @name rhumbBearing\n * @param {Coord} start starting Point\n * @param {Coord} end ending Point\n * @param {Object} [options] Optional parameters\n * @param {boolean} [options.final=false] calculates the final bearing if true\n * @returns {number} bearing from north in decimal degrees, between -180 and 180 degrees (positive clockwise)\n * @example\n * var point1 = turf.point([-75.343, 39.984], {\"marker-color\": \"#F00\"});\n * var point2 = turf.point([-75.534, 39.123], {\"marker-color\": \"#00F\"});\n *\n * var bearing = turf.rhumbBearing(point1, point2);\n *\n * //addToMap\n * var addToMap = [point1, point2];\n * point1.properties.bearing = bearing;\n * point2.properties.bearing = bearing;\n */\nfunction rhumbBearing(start, end, options) {\n if (options === void 0) { options = {}; }\n var bear360;\n if (options.final) {\n bear360 = calculateRhumbBearing(getCoord(end), getCoord(start));\n }\n else {\n bear360 = calculateRhumbBearing(getCoord(start), getCoord(end));\n }\n var bear180 = bear360 > 180 ? -(360 - bear360) : bear360;\n return bear180;\n}\n/**\n * Returns the bearing from ‘this’ point to destination point along a rhumb line.\n * Adapted from Geodesy: https://github.com/chrisveness/geodesy/blob/master/latlon-spherical.js\n *\n * @private\n * @param {Array} from - origin point.\n * @param {Array} to - destination point.\n * @returns {number} Bearing in degrees from north.\n * @example\n * var p1 = new LatLon(51.127, 1.338);\n * var p2 = new LatLon(50.964, 1.853);\n * var d = p1.rhumbBearingTo(p2); // 116.7 m\n */\nfunction calculateRhumbBearing(from, to) {\n // φ => phi\n // Δλ => deltaLambda\n // Δψ => deltaPsi\n // θ => theta\n var phi1 = degreesToRadians(from[1]);\n var phi2 = degreesToRadians(to[1]);\n var deltaLambda = degreesToRadians(to[0] - from[0]);\n // if deltaLambdaon over 180° take shorter rhumb line across the anti-meridian:\n if (deltaLambda > Math.PI) {\n deltaLambda -= 2 * Math.PI;\n }\n if (deltaLambda < -Math.PI) {\n deltaLambda += 2 * Math.PI;\n }\n var deltaPsi = Math.log(Math.tan(phi2 / 2 + Math.PI / 4) / Math.tan(phi1 / 2 + Math.PI / 4));\n var theta = Math.atan2(deltaLambda, deltaPsi);\n return (radiansToDegrees(theta) + 360) % 360;\n}\nexport default rhumbBearing;\n","import _extends from 'babel-runtime/helpers/extends';\nimport _defineProperty from 'babel-runtime/helpers/defineProperty';\nimport _classCallCheck from 'babel-runtime/helpers/classCallCheck';\nimport _createClass from 'babel-runtime/helpers/createClass';\nimport _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';\nimport _inherits from 'babel-runtime/helpers/inherits';\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\nimport warning from 'warning';\nimport toArray from 'rc-util/es/Children/toArray';\nimport { polyfill } from 'react-lifecycles-compat';\n\nimport { treeContextTypes } from './contextTypes';\nimport { convertTreeToEntities, convertDataToTree, getDataAndAria, getPosition, getDragNodesKeys, parseCheckedKeys, conductExpandParent, calcSelectedKeys, calcDropPosition, arrAdd, arrDel, posToArr, mapChildren, conductCheck, warnOnlyTreeNode } from './util';\n\nvar Tree = function (_React$Component) {\n _inherits(Tree, _React$Component);\n\n function Tree(props) {\n _classCallCheck(this, Tree);\n\n var _this = _possibleConstructorReturn(this, (Tree.__proto__ || Object.getPrototypeOf(Tree)).call(this, props));\n\n _this.onNodeDragStart = function (event, node) {\n var expandedKeys = _this.state.expandedKeys;\n var onDragStart = _this.props.onDragStart;\n var _node$props = node.props,\n eventKey = _node$props.eventKey,\n children = _node$props.children;\n\n\n _this.dragNode = node;\n\n _this.setState({\n dragNodesKeys: getDragNodesKeys(children, node),\n expandedKeys: arrDel(expandedKeys, eventKey)\n });\n\n if (onDragStart) {\n onDragStart({ event: event, node: node });\n }\n };\n\n _this.onNodeDragEnter = function (event, node) {\n var expandedKeys = _this.state.expandedKeys;\n var onDragEnter = _this.props.onDragEnter;\n var _node$props2 = node.props,\n pos = _node$props2.pos,\n eventKey = _node$props2.eventKey;\n\n\n if (!_this.dragNode) return;\n\n var dropPosition = calcDropPosition(event, node);\n\n // Skip if drag node is self\n if (_this.dragNode.props.eventKey === eventKey && dropPosition === 0) {\n _this.setState({\n dragOverNodeKey: '',\n dropPosition: null\n });\n return;\n }\n\n // Ref: https://github.com/react-component/tree/issues/132\n // Add timeout to let onDragLevel fire before onDragEnter,\n // so that we can clean drag props for onDragLeave node.\n // Macro task for this:\n // https://html.spec.whatwg.org/multipage/webappapis.html#clean-up-after-running-script\n setTimeout(function () {\n // Update drag over node\n _this.setState({\n dragOverNodeKey: eventKey,\n dropPosition: dropPosition\n });\n\n // Side effect for delay drag\n if (!_this.delayedDragEnterLogic) {\n _this.delayedDragEnterLogic = {};\n }\n Object.keys(_this.delayedDragEnterLogic).forEach(function (key) {\n clearTimeout(_this.delayedDragEnterLogic[key]);\n });\n _this.delayedDragEnterLogic[pos] = setTimeout(function () {\n var newExpandedKeys = arrAdd(expandedKeys, eventKey);\n if (!('expandedKeys' in _this.props)) {\n _this.setState({\n expandedKeys: newExpandedKeys\n });\n }\n\n if (onDragEnter) {\n onDragEnter({ event: event, node: node, expandedKeys: newExpandedKeys });\n }\n }, 400);\n }, 0);\n };\n\n _this.onNodeDragOver = function (event, node) {\n var onDragOver = _this.props.onDragOver;\n var eventKey = node.props.eventKey;\n\n // Update drag position\n\n if (_this.dragNode && eventKey === _this.state.dragOverNodeKey) {\n var dropPosition = calcDropPosition(event, node);\n\n if (dropPosition === _this.state.dropPosition) return;\n\n _this.setState({\n dropPosition: dropPosition\n });\n }\n\n if (onDragOver) {\n onDragOver({ event: event, node: node });\n }\n };\n\n _this.onNodeDragLeave = function (event, node) {\n var onDragLeave = _this.props.onDragLeave;\n\n\n _this.setState({\n dragOverNodeKey: ''\n });\n\n if (onDragLeave) {\n onDragLeave({ event: event, node: node });\n }\n };\n\n _this.onNodeDragEnd = function (event, node) {\n var onDragEnd = _this.props.onDragEnd;\n\n _this.setState({\n dragOverNodeKey: ''\n });\n if (onDragEnd) {\n onDragEnd({ event: event, node: node });\n }\n\n _this.dragNode = null;\n };\n\n _this.onNodeDrop = function (event, node) {\n var _this$state = _this.state,\n _this$state$dragNodes = _this$state.dragNodesKeys,\n dragNodesKeys = _this$state$dragNodes === undefined ? [] : _this$state$dragNodes,\n dropPosition = _this$state.dropPosition;\n var onDrop = _this.props.onDrop;\n var _node$props3 = node.props,\n eventKey = _node$props3.eventKey,\n pos = _node$props3.pos;\n\n\n _this.setState({\n dragOverNodeKey: ''\n });\n\n if (dragNodesKeys.indexOf(eventKey) !== -1) {\n warning(false, 'Can not drop to dragNode(include it\\'s children node)');\n return;\n }\n\n var posArr = posToArr(pos);\n\n var dropResult = {\n event: event,\n node: node,\n dragNode: _this.dragNode,\n dragNodesKeys: dragNodesKeys.slice(),\n dropPosition: dropPosition + Number(posArr[posArr.length - 1])\n };\n\n if (dropPosition !== 0) {\n dropResult.dropToGap = true;\n }\n\n if (onDrop) {\n onDrop(dropResult);\n }\n\n _this.dragNode = null;\n };\n\n _this.onNodeClick = function (e, treeNode) {\n var onClick = _this.props.onClick;\n\n if (onClick) {\n onClick(e, treeNode);\n }\n };\n\n _this.onNodeDoubleClick = function (e, treeNode) {\n var onDoubleClick = _this.props.onDoubleClick;\n\n if (onDoubleClick) {\n onDoubleClick(e, treeNode);\n }\n };\n\n _this.onNodeSelect = function (e, treeNode) {\n var selectedKeys = _this.state.selectedKeys;\n var keyEntities = _this.state.keyEntities;\n var _this$props = _this.props,\n onSelect = _this$props.onSelect,\n multiple = _this$props.multiple;\n var _treeNode$props = treeNode.props,\n selected = _treeNode$props.selected,\n eventKey = _treeNode$props.eventKey;\n\n var targetSelected = !selected;\n\n // Update selected keys\n if (!targetSelected) {\n selectedKeys = arrDel(selectedKeys, eventKey);\n } else if (!multiple) {\n selectedKeys = [eventKey];\n } else {\n selectedKeys = arrAdd(selectedKeys, eventKey);\n }\n\n // [Legacy] Not found related usage in doc or upper libs\n var selectedNodes = selectedKeys.map(function (key) {\n var entity = keyEntities[key];\n if (!entity) return null;\n\n return entity.node;\n }).filter(function (node) {\n return node;\n });\n\n _this.setUncontrolledState({ selectedKeys: selectedKeys });\n\n if (onSelect) {\n var eventObj = {\n event: 'select',\n selected: targetSelected,\n node: treeNode,\n selectedNodes: selectedNodes,\n nativeEvent: e.nativeEvent\n };\n onSelect(selectedKeys, eventObj);\n }\n };\n\n _this.onNodeCheck = function (e, treeNode, checked) {\n var _this$state2 = _this.state,\n keyEntities = _this$state2.keyEntities,\n oriCheckedKeys = _this$state2.checkedKeys,\n oriHalfCheckedKeys = _this$state2.halfCheckedKeys;\n var _this$props2 = _this.props,\n checkStrictly = _this$props2.checkStrictly,\n onCheck = _this$props2.onCheck;\n var eventKey = treeNode.props.eventKey;\n\n // Prepare trigger arguments\n\n var checkedObj = void 0;\n var eventObj = {\n event: 'check',\n node: treeNode,\n checked: checked,\n nativeEvent: e.nativeEvent\n };\n\n if (checkStrictly) {\n var checkedKeys = checked ? arrAdd(oriCheckedKeys, eventKey) : arrDel(oriCheckedKeys, eventKey);\n var halfCheckedKeys = arrDel(oriHalfCheckedKeys, eventKey);\n checkedObj = { checked: checkedKeys, halfChecked: halfCheckedKeys };\n\n eventObj.checkedNodes = checkedKeys.map(function (key) {\n return keyEntities[key];\n }).filter(function (entity) {\n return entity;\n }).map(function (entity) {\n return entity.node;\n });\n\n _this.setUncontrolledState({ checkedKeys: checkedKeys });\n } else {\n var _conductCheck = conductCheck([eventKey], checked, keyEntities, {\n checkedKeys: oriCheckedKeys, halfCheckedKeys: oriHalfCheckedKeys\n }),\n _checkedKeys = _conductCheck.checkedKeys,\n _halfCheckedKeys = _conductCheck.halfCheckedKeys;\n\n checkedObj = _checkedKeys;\n\n // [Legacy] This is used for `rc-tree-select`\n eventObj.checkedNodes = [];\n eventObj.checkedNodesPositions = [];\n eventObj.halfCheckedKeys = _halfCheckedKeys;\n\n _checkedKeys.forEach(function (key) {\n var entity = keyEntities[key];\n if (!entity) return;\n\n var node = entity.node,\n pos = entity.pos;\n\n\n eventObj.checkedNodes.push(node);\n eventObj.checkedNodesPositions.push({ node: node, pos: pos });\n });\n\n _this.setUncontrolledState({\n checkedKeys: _checkedKeys,\n halfCheckedKeys: _halfCheckedKeys\n });\n }\n\n if (onCheck) {\n onCheck(checkedObj, eventObj);\n }\n };\n\n _this.onNodeLoad = function (treeNode) {\n return new Promise(function (resolve) {\n // We need to get the latest state of loading/loaded keys\n _this.setState(function (_ref) {\n var _ref$loadedKeys = _ref.loadedKeys,\n loadedKeys = _ref$loadedKeys === undefined ? [] : _ref$loadedKeys,\n _ref$loadingKeys = _ref.loadingKeys,\n loadingKeys = _ref$loadingKeys === undefined ? [] : _ref$loadingKeys;\n var _this$props3 = _this.props,\n loadData = _this$props3.loadData,\n onLoad = _this$props3.onLoad;\n var eventKey = treeNode.props.eventKey;\n\n\n if (!loadData || loadedKeys.indexOf(eventKey) !== -1 || loadingKeys.indexOf(eventKey) !== -1) {\n // react 15 will warn if return null\n return {};\n }\n\n // Process load data\n var promise = loadData(treeNode);\n promise.then(function () {\n var newLoadedKeys = arrAdd(_this.state.loadedKeys, eventKey);\n var newLoadingKeys = arrDel(_this.state.loadingKeys, eventKey);\n\n // onLoad should trigger before internal setState to avoid `loadData` trigger twice.\n // https://github.com/ant-design/ant-design/issues/12464\n if (onLoad) {\n var eventObj = {\n event: 'load',\n node: treeNode\n };\n onLoad(newLoadedKeys, eventObj);\n }\n\n _this.setUncontrolledState({\n loadedKeys: newLoadedKeys\n });\n _this.setState({\n loadingKeys: newLoadingKeys\n });\n\n resolve();\n });\n\n return {\n loadingKeys: arrAdd(loadingKeys, eventKey)\n };\n });\n });\n };\n\n _this.onNodeExpand = function (e, treeNode) {\n var expandedKeys = _this.state.expandedKeys;\n var _this$props4 = _this.props,\n onExpand = _this$props4.onExpand,\n loadData = _this$props4.loadData;\n var _treeNode$props2 = treeNode.props,\n eventKey = _treeNode$props2.eventKey,\n expanded = _treeNode$props2.expanded;\n\n // Update selected keys\n\n var index = expandedKeys.indexOf(eventKey);\n var targetExpanded = !expanded;\n\n warning(expanded && index !== -1 || !expanded && index === -1, 'Expand state not sync with index check');\n\n if (targetExpanded) {\n expandedKeys = arrAdd(expandedKeys, eventKey);\n } else {\n expandedKeys = arrDel(expandedKeys, eventKey);\n }\n\n _this.setUncontrolledState({ expandedKeys: expandedKeys });\n\n if (onExpand) {\n onExpand(expandedKeys, {\n node: treeNode,\n expanded: targetExpanded,\n nativeEvent: e.nativeEvent\n });\n }\n\n // Async Load data\n if (targetExpanded && loadData) {\n var loadPromise = _this.onNodeLoad(treeNode);\n return loadPromise ? loadPromise.then(function () {\n // [Legacy] Refresh logic\n _this.setUncontrolledState({ expandedKeys: expandedKeys });\n }) : null;\n }\n\n return null;\n };\n\n _this.onNodeMouseEnter = function (event, node) {\n var onMouseEnter = _this.props.onMouseEnter;\n\n if (onMouseEnter) {\n onMouseEnter({ event: event, node: node });\n }\n };\n\n _this.onNodeMouseLeave = function (event, node) {\n var onMouseLeave = _this.props.onMouseLeave;\n\n if (onMouseLeave) {\n onMouseLeave({ event: event, node: node });\n }\n };\n\n _this.onNodeContextMenu = function (event, node) {\n var onRightClick = _this.props.onRightClick;\n\n if (onRightClick) {\n event.preventDefault();\n onRightClick({ event: event, node: node });\n }\n };\n\n _this.setUncontrolledState = function (state) {\n var needSync = false;\n var newState = {};\n\n Object.keys(state).forEach(function (name) {\n if (name in _this.props) return;\n\n needSync = true;\n newState[name] = state[name];\n });\n\n if (needSync) {\n _this.setState(newState);\n }\n };\n\n _this.registerTreeNode = function (key, node) {\n if (node) {\n _this.domTreeNodes[key] = node;\n } else {\n delete _this.domTreeNodes[key];\n }\n };\n\n _this.isKeyChecked = function (key) {\n var _this$state$checkedKe = _this.state.checkedKeys,\n checkedKeys = _this$state$checkedKe === undefined ? [] : _this$state$checkedKe;\n\n return checkedKeys.indexOf(key) !== -1;\n };\n\n _this.renderTreeNode = function (child, index) {\n var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n var _this$state3 = _this.state,\n keyEntities = _this$state3.keyEntities,\n _this$state3$expanded = _this$state3.expandedKeys,\n expandedKeys = _this$state3$expanded === undefined ? [] : _this$state3$expanded,\n _this$state3$selected = _this$state3.selectedKeys,\n selectedKeys = _this$state3$selected === undefined ? [] : _this$state3$selected,\n _this$state3$halfChec = _this$state3.halfCheckedKeys,\n halfCheckedKeys = _this$state3$halfChec === undefined ? [] : _this$state3$halfChec,\n _this$state3$loadedKe = _this$state3.loadedKeys,\n loadedKeys = _this$state3$loadedKe === undefined ? [] : _this$state3$loadedKe,\n _this$state3$loadingK = _this$state3.loadingKeys,\n loadingKeys = _this$state3$loadingK === undefined ? [] : _this$state3$loadingK,\n dragOverNodeKey = _this$state3.dragOverNodeKey,\n dropPosition = _this$state3.dropPosition;\n\n var pos = getPosition(level, index);\n var key = child.key || pos;\n\n if (!keyEntities[key]) {\n warnOnlyTreeNode();\n return null;\n }\n\n return React.cloneElement(child, {\n key: key,\n eventKey: key,\n expanded: expandedKeys.indexOf(key) !== -1,\n selected: selectedKeys.indexOf(key) !== -1,\n loaded: loadedKeys.indexOf(key) !== -1,\n loading: loadingKeys.indexOf(key) !== -1,\n checked: _this.isKeyChecked(key),\n halfChecked: halfCheckedKeys.indexOf(key) !== -1,\n pos: pos,\n\n // [Legacy] Drag props\n dragOver: dragOverNodeKey === key && dropPosition === 0,\n dragOverGapTop: dragOverNodeKey === key && dropPosition === -1,\n dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1\n });\n };\n\n _this.state = {\n // TODO: Remove this eslint\n posEntities: {}, // eslint-disable-line react/no-unused-state\n keyEntities: {},\n\n selectedKeys: [],\n checkedKeys: [],\n halfCheckedKeys: [],\n loadedKeys: [],\n loadingKeys: [],\n\n treeNode: []\n };\n\n // Internal usage for `rc-tree-select`, we don't promise it will not change.\n _this.domTreeNodes = {};\n return _this;\n }\n\n _createClass(Tree, [{\n key: 'getChildContext',\n value: function getChildContext() {\n var _props = this.props,\n prefixCls = _props.prefixCls,\n selectable = _props.selectable,\n showIcon = _props.showIcon,\n icon = _props.icon,\n draggable = _props.draggable,\n checkable = _props.checkable,\n checkStrictly = _props.checkStrictly,\n disabled = _props.disabled,\n loadData = _props.loadData,\n filterTreeNode = _props.filterTreeNode,\n motion = _props.motion,\n switcherIcon = _props.switcherIcon;\n\n\n return {\n rcTree: {\n // root: this,\n\n prefixCls: prefixCls,\n selectable: selectable,\n showIcon: showIcon,\n icon: icon,\n switcherIcon: switcherIcon,\n draggable: draggable,\n checkable: checkable,\n checkStrictly: checkStrictly,\n disabled: disabled,\n motion: motion,\n\n loadData: loadData,\n filterTreeNode: filterTreeNode,\n renderTreeNode: this.renderTreeNode,\n isKeyChecked: this.isKeyChecked,\n\n onNodeClick: this.onNodeClick,\n onNodeDoubleClick: this.onNodeDoubleClick,\n onNodeExpand: this.onNodeExpand,\n onNodeSelect: this.onNodeSelect,\n onNodeCheck: this.onNodeCheck,\n onNodeLoad: this.onNodeLoad,\n onNodeMouseEnter: this.onNodeMouseEnter,\n onNodeMouseLeave: this.onNodeMouseLeave,\n onNodeContextMenu: this.onNodeContextMenu,\n onNodeDragStart: this.onNodeDragStart,\n onNodeDragEnter: this.onNodeDragEnter,\n onNodeDragOver: this.onNodeDragOver,\n onNodeDragLeave: this.onNodeDragLeave,\n onNodeDragEnd: this.onNodeDragEnd,\n onNodeDrop: this.onNodeDrop,\n\n registerTreeNode: this.registerTreeNode\n }\n };\n }\n }, {\n key: 'render',\n value: function render() {\n var _this2 = this;\n\n var treeNode = this.state.treeNode;\n var _props2 = this.props,\n prefixCls = _props2.prefixCls,\n className = _props2.className,\n focusable = _props2.focusable,\n style = _props2.style,\n showLine = _props2.showLine,\n _props2$tabIndex = _props2.tabIndex,\n tabIndex = _props2$tabIndex === undefined ? 0 : _props2$tabIndex;\n\n var domProps = getDataAndAria(this.props);\n\n if (focusable) {\n domProps.tabIndex = tabIndex;\n domProps.onKeyDown = this.onKeyDown;\n }\n\n return React.createElement(\n 'ul',\n _extends({}, domProps, {\n className: classNames(prefixCls, className, _defineProperty({}, prefixCls + '-show-line', showLine)),\n style: style,\n role: 'tree',\n unselectable: 'on'\n }),\n mapChildren(treeNode, function (node, index) {\n return _this2.renderTreeNode(node, index);\n })\n );\n }\n }], [{\n key: 'getDerivedStateFromProps',\n value: function getDerivedStateFromProps(props, prevState) {\n var prevProps = prevState.prevProps;\n\n var newState = {\n prevProps: props\n };\n\n function needSync(name) {\n return !prevProps && name in props || prevProps && prevProps[name] !== props[name];\n }\n\n // ================== Tree Node ==================\n var treeNode = null;\n\n // Check if `treeData` or `children` changed and save into the state.\n if (needSync('treeData')) {\n treeNode = convertDataToTree(props.treeData);\n } else if (needSync('children')) {\n treeNode = toArray(props.children);\n }\n\n // Tree support filter function which will break the tree structure in the vdm.\n // We cache the treeNodes in state so that we can return the treeNode in event trigger.\n if (treeNode) {\n newState.treeNode = treeNode;\n\n // Calculate the entities data for quick match\n var entitiesMap = convertTreeToEntities(treeNode);\n newState.posEntities = entitiesMap.posEntities;\n newState.keyEntities = entitiesMap.keyEntities;\n }\n\n var keyEntities = newState.keyEntities || prevState.keyEntities;\n\n // ================ expandedKeys =================\n if (needSync('expandedKeys') || prevProps && needSync('autoExpandParent')) {\n newState.expandedKeys = props.autoExpandParent || !prevProps && props.defaultExpandParent ? conductExpandParent(props.expandedKeys, keyEntities) : props.expandedKeys;\n } else if (!prevProps && props.defaultExpandAll) {\n newState.expandedKeys = Object.keys(keyEntities);\n } else if (!prevProps && props.defaultExpandedKeys) {\n newState.expandedKeys = props.autoExpandParent || props.defaultExpandParent ? conductExpandParent(props.defaultExpandedKeys, keyEntities) : props.defaultExpandedKeys;\n }\n\n // ================ selectedKeys =================\n if (props.selectable) {\n if (needSync('selectedKeys')) {\n newState.selectedKeys = calcSelectedKeys(props.selectedKeys, props);\n } else if (!prevProps && props.defaultSelectedKeys) {\n newState.selectedKeys = calcSelectedKeys(props.defaultSelectedKeys, props);\n }\n }\n\n // ================= checkedKeys =================\n if (props.checkable) {\n var checkedKeyEntity = void 0;\n\n if (needSync('checkedKeys')) {\n checkedKeyEntity = parseCheckedKeys(props.checkedKeys) || {};\n } else if (!prevProps && props.defaultCheckedKeys) {\n checkedKeyEntity = parseCheckedKeys(props.defaultCheckedKeys) || {};\n } else if (treeNode) {\n // If treeNode changed, we also need check it\n checkedKeyEntity = parseCheckedKeys(props.checkedKeys) || {\n checkedKeys: prevState.checkedKeys,\n halfCheckedKeys: prevState.halfCheckedKeys\n };\n }\n\n if (checkedKeyEntity) {\n var _checkedKeyEntity = checkedKeyEntity,\n _checkedKeyEntity$che = _checkedKeyEntity.checkedKeys,\n checkedKeys = _checkedKeyEntity$che === undefined ? [] : _checkedKeyEntity$che,\n _checkedKeyEntity$hal = _checkedKeyEntity.halfCheckedKeys,\n halfCheckedKeys = _checkedKeyEntity$hal === undefined ? [] : _checkedKeyEntity$hal;\n\n\n if (!props.checkStrictly) {\n var conductKeys = conductCheck(checkedKeys, true, keyEntities);\n checkedKeys = conductKeys.checkedKeys;\n halfCheckedKeys = conductKeys.halfCheckedKeys;\n }\n\n newState.checkedKeys = checkedKeys;\n newState.halfCheckedKeys = halfCheckedKeys;\n }\n }\n // ================= loadedKeys ==================\n if (needSync('loadedKeys')) {\n newState.loadedKeys = props.loadedKeys;\n }\n\n return newState;\n }\n\n /**\n * [Legacy] Select handler is less small than node,\n * so that this will trigger when drag enter node or select handler.\n * This is a little tricky if customize css without padding.\n * Better for use mouse move event to refresh drag state.\n * But let's just keep it to avoid event trigger logic change.\n */\n\n\n /**\n * Only update the value which is not in props\n */\n\n\n /**\n * [Legacy] Original logic use `key` as tracking clue.\n * We have to use `cloneElement` to pass `key`.\n */\n\n }]);\n\n return Tree;\n}(React.Component);\n\nTree.propTypes = {\n prefixCls: PropTypes.string,\n className: PropTypes.string,\n style: PropTypes.object,\n tabIndex: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n children: PropTypes.any,\n treeData: PropTypes.array, // Generate treeNode by children\n showLine: PropTypes.bool,\n showIcon: PropTypes.bool,\n icon: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),\n focusable: PropTypes.bool,\n selectable: PropTypes.bool,\n disabled: PropTypes.bool,\n multiple: PropTypes.bool,\n checkable: PropTypes.oneOfType([PropTypes.bool, PropTypes.node]),\n checkStrictly: PropTypes.bool,\n draggable: PropTypes.bool,\n defaultExpandParent: PropTypes.bool,\n autoExpandParent: PropTypes.bool,\n defaultExpandAll: PropTypes.bool,\n defaultExpandedKeys: PropTypes.arrayOf(PropTypes.string),\n expandedKeys: PropTypes.arrayOf(PropTypes.string),\n defaultCheckedKeys: PropTypes.arrayOf(PropTypes.string),\n checkedKeys: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), PropTypes.object]),\n defaultSelectedKeys: PropTypes.arrayOf(PropTypes.string),\n selectedKeys: PropTypes.arrayOf(PropTypes.string),\n onClick: PropTypes.func,\n onDoubleClick: PropTypes.func,\n onExpand: PropTypes.func,\n onCheck: PropTypes.func,\n onSelect: PropTypes.func,\n onLoad: PropTypes.func,\n loadData: PropTypes.func,\n loadedKeys: PropTypes.arrayOf(PropTypes.string),\n onMouseEnter: PropTypes.func,\n onMouseLeave: PropTypes.func,\n onRightClick: PropTypes.func,\n onDragStart: PropTypes.func,\n onDragEnter: PropTypes.func,\n onDragOver: PropTypes.func,\n onDragLeave: PropTypes.func,\n onDragEnd: PropTypes.func,\n onDrop: PropTypes.func,\n filterTreeNode: PropTypes.func,\n motion: PropTypes.object,\n switcherIcon: PropTypes.oneOfType([PropTypes.node, PropTypes.func])\n};\nTree.childContextTypes = treeContextTypes;\nTree.defaultProps = {\n prefixCls: 'rc-tree',\n showLine: false,\n showIcon: true,\n selectable: true,\n multiple: false,\n checkable: false,\n disabled: false,\n checkStrictly: false,\n draggable: false,\n defaultExpandParent: true,\n autoExpandParent: false,\n defaultExpandAll: false,\n defaultExpandedKeys: [],\n defaultCheckedKeys: [],\n defaultSelectedKeys: []\n};\n\n\npolyfill(Tree);\n\nexport default Tree;","import Tree from './Tree';\nimport TreeNode from './TreeNode';\n\nTree.TreeNode = TreeNode;\n\nexport { TreeNode };\nexport default Tree;","var grey = {\n 50: '#fafafa',\n 100: '#f5f5f5',\n 200: '#eeeeee',\n 300: '#e0e0e0',\n 400: '#bdbdbd',\n 500: '#9e9e9e',\n 600: '#757575',\n 700: '#616161',\n 800: '#424242',\n 900: '#212121',\n A100: '#d5d5d5',\n A200: '#aaaaaa',\n A400: '#303030',\n A700: '#616161'\n};\nexport default grey;","import Framebuffer from '../classes/framebuffer';\nimport Texture2D from '../classes/texture-2d';\n// TODO - this should be the default export, test cases need updating\nexport const FEATURES = {\n WEBGL2: 'WEBGL2',\n\n // API SUPPORT\n VERTEX_ARRAY_OBJECT: 'VERTEX_ARRAY_OBJECT',\n TIMER_QUERY: 'TIMER_QUERY',\n INSTANCED_RENDERING: 'INSTANCED_RENDERING',\n MULTIPLE_RENDER_TARGETS: 'MULTIPLE_RENDER_TARGETS',\n\n // FEATURES\n ELEMENT_INDEX_UINT32: 'ELEMENT_INDEX_UINT32',\n\n // BLENDING\n BLEND_EQUATION_MINMAX: 'BLEND_EQUATION_MINMAX',\n FLOAT_BLEND: 'FLOAT_BLEND',\n\n // TEXTURES: '// TEXTURES', RENDERBUFFERS\n COLOR_ENCODING_SRGB: 'COLOR_ENCODING_SRGB',\n\n // TEXTURES\n TEXTURE_DEPTH: 'TEXTURE_DEPTH',\n TEXTURE_FLOAT: 'TEXTURE_FLOAT',\n TEXTURE_HALF_FLOAT: 'TEXTURE_HALF_FLOAT',\n\n TEXTURE_FILTER_LINEAR_FLOAT: 'TEXTURE_FILTER_LINEAR_FLOAT',\n TEXTURE_FILTER_LINEAR_HALF_FLOAT: 'TEXTURE_FILTER_LINEAR_HALF_FLOAT',\n TEXTURE_FILTER_ANISOTROPIC: 'TEXTURE_FILTER_ANISOTROPIC',\n\n // FRAMEBUFFERS: '// FRAMEBUFFERS', TEXTURES AND RENDERBUFFERS\n COLOR_ATTACHMENT_RGBA32F: 'COLOR_ATTACHMENT_RGBA32F',\n COLOR_ATTACHMENT_FLOAT: 'COLOR_ATTACHMENT_FLOAT',\n COLOR_ATTACHMENT_HALF_FLOAT: 'COLOR_ATTACHMENT_HALF_FLOAT',\n\n // GLSL extensions\n GLSL_FRAG_DATA: 'GLSL_FRAG_DATA',\n GLSL_FRAG_DEPTH: 'GLSL_FRAG_DEPTH',\n GLSL_DERIVATIVES: 'GLSL_DERIVATIVES',\n GLSL_TEXTURE_LOD: 'GLSL_TEXTURE_LOD'\n};\n\n// function to test if Float 32 bit format texture can be bound as color attachment\nfunction checkFloat32ColorAttachment(gl) {\n const testTexture = new Texture2D(gl, {\n format: gl.RGBA,\n type: gl.FLOAT,\n dataFormat: gl.RGBA\n });\n const testFb = new Framebuffer(gl, {\n id: `test-framebuffer`,\n check: false,\n attachments: {\n [gl.COLOR_ATTACHMENT0]: testTexture\n }\n });\n const status = testFb.getStatus();\n testTexture.delete();\n testFb.delete();\n return status === gl.FRAMEBUFFER_COMPLETE;\n}\n\n// Defines luma.gl \"feature\" names and semantics\n// Format: 'feature-name: [WebGL1 support, WebGL2 support] / [WebGL1 and WebGL2 support]', when support is 'string' it is the name of the extension\nexport default {\n [FEATURES.WEBGL2]: [false, true],\n\n // API SUPPORT\n [FEATURES.VERTEX_ARRAY_OBJECT]: ['OES_vertex_array_object', true],\n [FEATURES.TIMER_QUERY]: ['EXT_disjoint_timer_query', 'EXT_disjoint_timer_query_webgl2'],\n [FEATURES.INSTANCED_RENDERING]: ['ANGLE_instanced_arrays', true],\n [FEATURES.MULTIPLE_RENDER_TARGETS]: ['WEBGL_draw_buffers', true],\n\n // FEATURES\n [FEATURES.ELEMENT_INDEX_UINT32]: ['OES_element_index_uint', true],\n\n // BLENDING\n [FEATURES.BLEND_EQUATION_MINMAX]: ['EXT_blend_minmax', true],\n [FEATURES.FLOAT_BLEND]: ['EXT_float_blend'],\n\n // TEXTURES, RENDERBUFFERS\n [FEATURES.COLOR_ENCODING_SRGB]: ['EXT_sRGB', true],\n\n // TEXTURES\n [FEATURES.TEXTURE_DEPTH]: ['WEBGL_depth_texture', true],\n [FEATURES.TEXTURE_FLOAT]: ['OES_texture_float', true],\n [FEATURES.TEXTURE_HALF_FLOAT]: ['OES_texture_half_float', true],\n\n [FEATURES.TEXTURE_FILTER_LINEAR_FLOAT]: ['OES_texture_float_linear'],\n [FEATURES.TEXTURE_FILTER_LINEAR_HALF_FLOAT]: ['OES_texture_half_float_linear'],\n [FEATURES.TEXTURE_FILTER_ANISOTROPIC]: ['EXT_texture_filter_anisotropic'],\n\n // FRAMEBUFFERS, TEXTURES AND RENDERBUFFERS\n [FEATURES.COLOR_ATTACHMENT_RGBA32F]: [checkFloat32ColorAttachment, 'EXT_color_buffer_float'],\n [FEATURES.COLOR_ATTACHMENT_FLOAT]: [false, 'EXT_color_buffer_float'],\n [FEATURES.COLOR_ATTACHMENT_HALF_FLOAT]: ['EXT_color_buffer_half_float'],\n\n // GLSL extensions\n [FEATURES.GLSL_FRAG_DATA]: ['WEBGL_draw_buffers', true],\n [FEATURES.GLSL_FRAG_DEPTH]: ['EXT_frag_depth', true],\n [FEATURES.GLSL_DERIVATIVES]: ['OES_standard_derivatives', true],\n [FEATURES.GLSL_TEXTURE_LOD]: ['EXT_shader_texture_lod', true]\n};\n","import {assertWebGL2Context, withParameters} from '@luma.gl/gltools';\nimport {assert} from '../utils/assert';\n\n// Should collapse during minification\nconst GL_DEPTH_BUFFER_BIT = 0x00000100;\nconst GL_STENCIL_BUFFER_BIT = 0x00000400;\nconst GL_COLOR_BUFFER_BIT = 0x00004000;\n\nconst GL_COLOR = 0x1800;\nconst GL_DEPTH = 0x1801;\nconst GL_STENCIL = 0x1802;\nconst GL_DEPTH_STENCIL = 0x84f9;\n\n// Should disappear if asserts are removed\nconst ERR_ARGUMENTS = 'clear: bad arguments';\n\n// Optionally clears depth, color and stencil buffers\n/** @type {import('./clear').clear} */\nexport function clear(gl, {framebuffer = null, color = null, depth = null, stencil = null} = {}) {\n const parameters = {};\n\n if (framebuffer) {\n parameters.framebuffer = framebuffer;\n }\n\n let clearFlags = 0;\n\n if (color) {\n clearFlags |= GL_COLOR_BUFFER_BIT;\n if (color !== true) {\n parameters.clearColor = color;\n }\n }\n\n if (depth) {\n clearFlags |= GL_DEPTH_BUFFER_BIT;\n if (depth !== true) {\n parameters.clearDepth = depth;\n }\n }\n\n if (stencil) {\n clearFlags |= GL_STENCIL_BUFFER_BIT;\n if (depth !== true) {\n parameters.clearStencil = depth;\n }\n }\n\n assert(clearFlags !== 0, ERR_ARGUMENTS);\n\n // Temporarily set any clear \"colors\" and call clear\n withParameters(gl, parameters, () => {\n gl.clear(clearFlags);\n });\n}\n\n// WebGL2 - clear a specific drawing buffer\n/** @type {import('./clear').clearBuffer} */\nexport function clearBuffer(\n gl,\n {framebuffer = null, buffer = GL_COLOR, drawBuffer = 0, value = [0, 0, 0, 0]} = {}\n) {\n assertWebGL2Context(gl);\n\n withParameters(gl, {framebuffer}, () => {\n // Method selection per OpenGL ES 3 docs\n switch (buffer) {\n case GL_COLOR:\n switch (value.constructor) {\n case Int32Array:\n gl.clearBufferiv(buffer, drawBuffer, value);\n break;\n case Uint32Array:\n gl.clearBufferuiv(buffer, drawBuffer, value);\n break;\n case Float32Array:\n default:\n gl.clearBufferfv(buffer, drawBuffer, value);\n }\n break;\n\n case GL_DEPTH:\n gl.clearBufferfv(GL_DEPTH, 0, [value]);\n break;\n\n case GL_STENCIL:\n gl.clearBufferiv(GL_STENCIL, 0, [value]);\n break;\n\n case GL_DEPTH_STENCIL:\n const [depth, stencil] = value;\n gl.clearBufferfi(GL_DEPTH_STENCIL, 0, depth, stencil);\n break;\n\n default:\n assert(false, ERR_ARGUMENTS);\n }\n });\n}\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?e(exports):\"function\"==typeof define&&define.amd?define([\"exports\"],e):e(t.jsts={})}(this,function(t){\"use strict\";function e(){}function n(t){this.message=t||\"\"}function i(t){this.message=t||\"\"}function r(t){this.message=t||\"\"}function o(){}function s(t){return null===t?Mt:t.color}function a(t){return null===t?null:t.parent}function u(t,e){null!==t&&(t.color=e)}function l(t){return null===t?null:t.left}function c(t){return null===t?null:t.right}function p(){this.root_=null,this.size_=0}function h(){}function f(){this.array_=[],arguments[0]instanceof It&&this.addAll(arguments[0])}function g(){}function d(t){this.message=t||\"\"}function y(){this.array_=[]}\"fill\"in Array.prototype||Object.defineProperty(Array.prototype,\"fill\",{configurable:!0,value:function(t){if(void 0===this||null===this)throw new TypeError(this+\" is not an object\");var e=Object(this),n=Math.max(Math.min(e.length,9007199254740991),0)||0,i=1 in arguments?parseInt(Number(arguments[1]),10)||0:0;i=i<0?Math.max(n+i,0):Math.min(i,n);var r=2 in arguments&&void 0!==arguments[2]?parseInt(Number(arguments[2]),10)||0:n;for(r=r<0?Math.max(n+arguments[2],0):Math.min(r,n);ie.x?1:this.ye.y?1:0},C.prototype.clone=function(){},C.prototype.copy=function(){return new C(this)},C.prototype.toString=function(){return\"(\"+this.x+\", \"+this.y+\", \"+this.z+\")\"},C.prototype.distance3D=function(t){var e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return Math.sqrt(e*e+n*n+i*i)},C.prototype.distance=function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)},C.prototype.hashCode=function(){var t=17;return t=37*t+C.hashCode(this.x),t=37*t+C.hashCode(this.y)},C.prototype.setCoordinate=function(t){this.x=t.x,this.y=t.y,this.z=t.z},C.prototype.interfaces_=function(){return[E,x,e]},C.prototype.getClass=function(){return C},C.hashCode=function(){if(1===arguments.length){var t=arguments[0],e=v.doubleToLongBits(t);return Math.trunc((e^e)>>>32)}},S.DimensionalComparator.get=function(){return L},S.serialVersionUID.get=function(){return 0x5cbf2c235c7e5800},S.NULL_ORDINATE.get=function(){return v.NaN},S.X.get=function(){return 0},S.Y.get=function(){return 1},S.Z.get=function(){return 2},Object.defineProperties(C,S);var L=function(t){if(this._dimensionsToTest=2,0===arguments.length);else if(1===arguments.length){var e=arguments[0];if(2!==e&&3!==e)throw new m(\"only 2 or 3 dimensions may be specified\");this._dimensionsToTest=e}};L.prototype.compare=function(t,e){var n=t,i=e,r=L.compare(n.x,i.x);if(0!==r)return r;var o=L.compare(n.y,i.y);if(0!==o)return o;if(this._dimensionsToTest<=2)return 0;return L.compare(n.z,i.z)},L.prototype.interfaces_=function(){return[N]},L.prototype.getClass=function(){return L},L.compare=function(t,e){return te?1:v.isNaN(t)?v.isNaN(e)?0:-1:v.isNaN(e)?1:0};var b=function(){};b.prototype.create=function(){},b.prototype.interfaces_=function(){return[]},b.prototype.getClass=function(){return b};var w=function(){},O={INTERIOR:{configurable:!0},BOUNDARY:{configurable:!0},EXTERIOR:{configurable:!0},NONE:{configurable:!0}};w.prototype.interfaces_=function(){return[]},w.prototype.getClass=function(){return w},w.toLocationSymbol=function(t){switch(t){case w.EXTERIOR:return\"e\";case w.BOUNDARY:return\"b\";case w.INTERIOR:return\"i\";case w.NONE:return\"-\"}throw new m(\"Unknown location value: \"+t)},O.INTERIOR.get=function(){return 0},O.BOUNDARY.get=function(){return 1},O.EXTERIOR.get=function(){return 2},O.NONE.get=function(){return-1},Object.defineProperties(w,O);var T=function(t,e){return t.interfaces_&&t.interfaces_().indexOf(e)>-1},R=function(){},P={LOG_10:{configurable:!0}};R.prototype.interfaces_=function(){return[]},R.prototype.getClass=function(){return R},R.log10=function(t){var e=Math.log(t);return v.isInfinite(e)?e:v.isNaN(e)?e:e/R.LOG_10},R.min=function(t,e,n,i){var r=t;return en?n:t}if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){var i=arguments[0],r=arguments[1],o=arguments[2];return io?o:i}},R.wrap=function(t,e){return t<0?e- -t%e:t%e},R.max=function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2],i=t;return e>i&&(i=e),n>i&&(i=n),i}if(4===arguments.length){var r=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3],u=r;return o>u&&(u=o),s>u&&(u=s),a>u&&(u=a),u}},R.average=function(t,e){return(t+e)/2},P.LOG_10.get=function(){return Math.log(10)},Object.defineProperties(R,P);var D=function(t){this.str=t};D.prototype.append=function(t){this.str+=t},D.prototype.setCharAt=function(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)},D.prototype.toString=function(t){return this.str};var M=function(t){this.value=t};M.prototype.intValue=function(){return this.value},M.prototype.compareTo=function(t){return this.valuet?1:0},M.isNaN=function(t){return Number.isNaN(t)};var A=function(){};A.isWhitespace=function(t){return t<=32&&t>=0||127===t},A.toUpperCase=function(t){return t.toUpperCase()};var F=function t(){if(this._hi=0,this._lo=0,0===arguments.length)this.init(0);else if(1===arguments.length){if(\"number\"==typeof arguments[0]){var e=arguments[0];this.init(e)}else if(arguments[0]instanceof t){var n=arguments[0];this.init(n)}else if(\"string\"==typeof arguments[0]){var i=arguments[0];t.call(this,t.parse(i))}}else if(2===arguments.length){var r=arguments[0],o=arguments[1];this.init(r,o)}},G={PI:{configurable:!0},TWO_PI:{configurable:!0},PI_2:{configurable:!0},E:{configurable:!0},NaN:{configurable:!0},EPS:{configurable:!0},SPLIT:{configurable:!0},MAX_PRINT_DIGITS:{configurable:!0},TEN:{configurable:!0},ONE:{configurable:!0},SCI_NOT_EXPONENT_CHAR:{configurable:!0},SCI_NOT_ZERO:{configurable:!0}};F.prototype.le=function(t){return(this._hi9?(c=!0,p=\"9\"):p=\"0\"+l,s.append(p),n=n.subtract(F.valueOf(l)).multiply(F.TEN),c&&n.selfAdd(F.TEN);var h=!0,f=F.magnitude(n._hi);if(f<0&&Math.abs(f)>=a-u&&(h=!1),!h)break}return e[0]=i,s.toString()},F.prototype.sqr=function(){return this.multiply(this)},F.prototype.doubleValue=function(){return this._hi+this._lo},F.prototype.subtract=function(){if(arguments[0]instanceof F){var t=arguments[0];return this.add(t.negate())}if(\"number\"==typeof arguments[0]){var e=arguments[0];return this.add(-e)}},F.prototype.equals=function(){if(1===arguments.length){var t=arguments[0];return this._hi===t._hi&&this._lo===t._lo}},F.prototype.isZero=function(){return 0===this._hi&&0===this._lo},F.prototype.selfSubtract=function(){if(arguments[0]instanceof F){var t=arguments[0];return this.isNaN()?this:this.selfAdd(-t._hi,-t._lo)}if(\"number\"==typeof arguments[0]){var e=arguments[0];return this.isNaN()?this:this.selfAdd(-e,0)}},F.prototype.getSpecialNumberString=function(){return this.isZero()?\"0.0\":this.isNaN()?\"NaN \":null},F.prototype.min=function(t){return this.le(t)?this:t},F.prototype.selfDivide=function(){if(1===arguments.length){if(arguments[0]instanceof F){var t=arguments[0];return this.selfDivide(t._hi,t._lo)}if(\"number\"==typeof arguments[0]){var e=arguments[0];return this.selfDivide(e,0)}}else if(2===arguments.length){var n=arguments[0],i=arguments[1],r=null,o=null,s=null,a=null,u=null,l=null,c=null,p=null;return u=this._hi/n,l=F.SPLIT*u,r=l-u,p=F.SPLIT*n,r=l-r,o=u-r,s=p-n,c=u*n,s=p-s,a=n-s,p=r*s-c+r*a+o*s+o*a,l=(this._hi-c-p+this._lo-u*i)/n,p=u+l,this._hi=p,this._lo=u-p+l,this}},F.prototype.dump=function(){return\"DD<\"+this._hi+\", \"+this._lo+\">\"},F.prototype.divide=function(){if(arguments[0]instanceof F){var t=arguments[0],e=null,n=null,i=null,r=null,o=null,s=null,a=null,u=null;n=(o=this._hi/t._hi)-(e=(s=F.SPLIT*o)-(e=s-o)),u=e*(i=(u=F.SPLIT*t._hi)-(i=u-t._hi))-(a=o*t._hi)+e*(r=t._hi-i)+n*i+n*r,s=(this._hi-a-u+this._lo-o*t._lo)/t._hi;return new F(u=o+s,o-u+s)}if(\"number\"==typeof arguments[0]){var l=arguments[0];return v.isNaN(l)?F.createNaN():F.copy(this).selfDivide(l,0)}},F.prototype.ge=function(t){return(this._hi>t._hi||this._hi===t._hi)&&this._lo>=t._lo},F.prototype.pow=function(t){if(0===t)return F.valueOf(1);var e=new F(this),n=F.valueOf(1),i=Math.abs(t);if(i>1)for(;i>0;)i%2==1&&n.selfMultiply(e),(i/=2)>0&&(e=e.sqr());else n=e;return t<0?n.reciprocal():n},F.prototype.ceil=function(){if(this.isNaN())return F.NaN;var t=Math.ceil(this._hi),e=0;return t===this._hi&&(e=Math.ceil(this._lo)),new F(t,e)},F.prototype.compareTo=function(t){var e=t;return this._hie._hi?1:this._loe._lo?1:0},F.prototype.rint=function(){if(this.isNaN())return this;return this.add(.5).floor()},F.prototype.setValue=function(){if(arguments[0]instanceof F){var t=arguments[0];return this.init(t),this}if(\"number\"==typeof arguments[0]){var e=arguments[0];return this.init(e),this}},F.prototype.max=function(t){return this.ge(t)?this:t},F.prototype.sqrt=function(){if(this.isZero())return F.valueOf(0);if(this.isNegative())return F.NaN;var t=1/Math.sqrt(this._hi),e=this._hi*t,n=F.valueOf(e),i=this.subtract(n.sqr())._hi*(.5*t);return n.add(i)},F.prototype.selfAdd=function(){if(1===arguments.length){if(arguments[0]instanceof F){var t=arguments[0];return this.selfAdd(t._hi,t._lo)}if(\"number\"==typeof arguments[0]){var e=arguments[0],n=null,i=null,r=null,o=null,s=null,a=null;return r=this._hi+e,s=r-this._hi,o=r-s,o=e-s+(this._hi-o),a=o+this._lo,n=r+a,i=a+(r-n),this._hi=n+i,this._lo=i+(n-this._hi),this}}else if(2===arguments.length){var u=arguments[0],l=arguments[1],c=null,p=null,h=null,f=null,g=null,d=null,y=null;f=this._hi+u,p=this._lo+l,g=f-(d=f-this._hi),h=p-(y=p-this._lo);var _=(c=f+(d=(g=u-d+(this._hi-g))+p))+(d=(h=l-y+(this._lo-h))+(d+(f-c))),m=d+(c-_);return this._hi=_,this._lo=m,this}},F.prototype.selfMultiply=function(){if(1===arguments.length){if(arguments[0]instanceof F){var t=arguments[0];return this.selfMultiply(t._hi,t._lo)}if(\"number\"==typeof arguments[0]){var e=arguments[0];return this.selfMultiply(e,0)}}else if(2===arguments.length){var n=arguments[0],i=arguments[1],r=null,o=null,s=null,a=null,u=null,l=null;r=(u=F.SPLIT*this._hi)-this._hi,l=F.SPLIT*n,r=u-r,o=this._hi-r,s=l-n;var c=(u=this._hi*n)+(l=r*(s=l-s)-u+r*(a=n-s)+o*s+o*a+(this._hi*i+this._lo*n)),p=l+(r=u-c);return this._hi=c,this._lo=p,this}},F.prototype.selfSqr=function(){return this.selfMultiply(this)},F.prototype.floor=function(){if(this.isNaN())return F.NaN;var t=Math.floor(this._hi),e=0;return t===this._hi&&(e=Math.floor(this._lo)),new F(t,e)},F.prototype.negate=function(){return this.isNaN()?this:new F(-this._hi,-this._lo)},F.prototype.clone=function(){},F.prototype.multiply=function(){if(arguments[0]instanceof F){var t=arguments[0];return t.isNaN()?F.createNaN():F.copy(this).selfMultiply(t)}if(\"number\"==typeof arguments[0]){var e=arguments[0];return v.isNaN(e)?F.createNaN():F.copy(this).selfMultiply(e,0)}},F.prototype.isNaN=function(){return v.isNaN(this._hi)},F.prototype.intValue=function(){return Math.trunc(this._hi)},F.prototype.toString=function(){var t=F.magnitude(this._hi);return t>=-3&&t<=20?this.toStandardNotation():this.toSciNotation()},F.prototype.toStandardNotation=function(){var t=this.getSpecialNumberString();if(null!==t)return t;var e=new Array(1).fill(null),n=this.extractSignificantDigits(!0,e),i=e[0]+1,r=n;if(\".\"===n.charAt(0))r=\"0\"+n;else if(i<0)r=\"0.\"+F.stringOfChar(\"0\",-i)+n;else if(-1===n.indexOf(\".\")){var o=i-n.length;r=n+F.stringOfChar(\"0\",o)+\".0\"}return this.isNegative()?\"-\"+r:r},F.prototype.reciprocal=function(){var t=null,e=null,n=null,i=null,r=null,o=null,s=null,a=null;e=(r=1/this._hi)-(t=(o=F.SPLIT*r)-(t=o-r)),n=(a=F.SPLIT*this._hi)-this._hi;var u=r+(o=(1-(s=r*this._hi)-(a=t*(n=a-n)-s+t*(i=this._hi-n)+e*n+e*i)-r*this._lo)/this._hi);return new F(u,r-u+o)},F.prototype.toSciNotation=function(){if(this.isZero())return F.SCI_NOT_ZERO;var t=this.getSpecialNumberString();if(null!==t)return t;var e=new Array(1).fill(null),n=this.extractSignificantDigits(!1,e),i=F.SCI_NOT_EXPONENT_CHAR+e[0];if(\"0\"===n.charAt(0))throw new Error(\"Found leading zero: \"+n);var r=\"\";n.length>1&&(r=n.substring(1));var o=n.charAt(0)+\".\"+r;return this.isNegative()?\"-\"+o+i:o+i},F.prototype.abs=function(){return this.isNaN()?F.NaN:this.isNegative()?this.negate():new F(this)},F.prototype.isPositive=function(){return(this._hi>0||0===this._hi)&&this._lo>0},F.prototype.lt=function(t){return(this._hit._hi||this._hi===t._hi)&&this._lo>t._lo},F.prototype.isNegative=function(){return(this._hi<0||0===this._hi)&&this._lo<0},F.prototype.trunc=function(){return this.isNaN()?F.NaN:this.isPositive()?this.floor():this.ceil()},F.prototype.signum=function(){return this._hi>0?1:this._hi<0?-1:this._lo>0?1:this._lo<0?-1:0},F.prototype.interfaces_=function(){return[e,E,x]},F.prototype.getClass=function(){return F},F.sqr=function(t){return F.valueOf(t).selfMultiply(t)},F.valueOf=function(){if(\"string\"==typeof arguments[0]){var t=arguments[0];return F.parse(t)}if(\"number\"==typeof arguments[0]){var e=arguments[0];return new F(e)}},F.sqrt=function(t){return F.valueOf(t).sqrt()},F.parse=function(t){for(var e=0,n=t.length;A.isWhitespace(t.charAt(e));)e++;var i=!1;if(e=n);){var l=t.charAt(e);if(e++,A.isDigit(l)){var c=l-\"0\";o.selfMultiply(F.TEN),o.selfAdd(c),s++}else{if(\".\"!==l){if(\"e\"===l||\"E\"===l){var p=t.substring(e);try{u=M.parseInt(p)}catch(e){throw e instanceof Error?new Error(\"Invalid exponent \"+p+\" in string \"+t):e}break}throw new Error(\"Unexpected character '\"+l+\"' at position \"+e+\" in string \"+t)}a=s}}var h=o,f=s-a-u;if(0===f)h=o;else if(f>0){var g=F.TEN.pow(f);h=o.divide(g)}else if(f<0){var d=F.TEN.pow(-f);h=o.multiply(d)}return i?h.negate():h},F.createNaN=function(){return new F(v.NaN,v.NaN)},F.copy=function(t){return new F(t)},F.magnitude=function(t){var e=Math.abs(t),n=Math.log(e)/Math.log(10),i=Math.trunc(Math.floor(n));return 10*Math.pow(10,i)<=e&&(i+=1),i},F.stringOfChar=function(t,e){for(var n=new D,i=0;i0){if(o<=0)return q.signum(s);i=r+o}else{if(!(r<0))return q.signum(s);if(o>=0)return q.signum(s);i=-r-o}var a=q.DP_SAFE_EPSILON*i;return s>=a||-s>=a?q.signum(s):2},q.signum=function(t){return t>0?1:t<0?-1:0},B.DP_SAFE_EPSILON.get=function(){return 1e-15},Object.defineProperties(q,B);var V=function(){},U={X:{configurable:!0},Y:{configurable:!0},Z:{configurable:!0},M:{configurable:!0}};U.X.get=function(){return 0},U.Y.get=function(){return 1},U.Z.get=function(){return 2},U.M.get=function(){return 3},V.prototype.setOrdinate=function(t,e,n){},V.prototype.size=function(){},V.prototype.getOrdinate=function(t,e){},V.prototype.getCoordinate=function(){},V.prototype.getCoordinateCopy=function(t){},V.prototype.getDimension=function(){},V.prototype.getX=function(t){},V.prototype.clone=function(){},V.prototype.expandEnvelope=function(t){},V.prototype.copy=function(){},V.prototype.getY=function(t){},V.prototype.toCoordinateArray=function(){},V.prototype.interfaces_=function(){return[x]},V.prototype.getClass=function(){return V},Object.defineProperties(V,U);var z=function(){},X=function(t){function e(){t.call(this,\"Projective point not representable on the Cartesian plane.\")}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(z),Y=function(){};Y.arraycopy=function(t,e,n,i,r){for(var o=0,s=e;st._minx?this._minx:t._minx,n=this._miny>t._miny?this._miny:t._miny,i=this._maxx=this._minx&&e.getMaxX()<=this._maxx&&e.getMinY()>=this._miny&&e.getMaxY()<=this._maxy)}}else if(2===arguments.length){var n=arguments[0],i=arguments[1];return!this.isNull()&&(n>=this._minx&&n<=this._maxx&&i>=this._miny&&i<=this._maxy)}},j.prototype.intersects=function(){if(1===arguments.length){if(arguments[0]instanceof j){var t=arguments[0];return!this.isNull()&&!t.isNull()&&!(t._minx>this._maxx||t._maxxthis._maxy||t._maxythis._maxx||nthis._maxy||ithis._maxx&&(this._maxx=e._maxx),e._minythis._maxy&&(this._maxy=e._maxy))}}else if(2===arguments.length){var n=arguments[0],i=arguments[1];this.isNull()?(this._minx=n,this._maxx=n,this._miny=i,this._maxy=i):(nthis._maxx&&(this._maxx=n),ithis._maxy&&(this._maxy=i))}},j.prototype.minExtent=function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return te._minx?1:this._minye._miny?1:this._maxxe._maxx?1:this._maxye._maxy?1:0},j.prototype.translate=function(t,e){if(this.isNull())return null;this.init(this.getMinX()+t,this.getMaxX()+t,this.getMinY()+e,this.getMaxY()+e)},j.prototype.toString=function(){return\"Env[\"+this._minx+\" : \"+this._maxx+\", \"+this._miny+\" : \"+this._maxy+\"]\"},j.prototype.setToNull=function(){this._minx=0,this._maxx=-1,this._miny=0,this._maxy=-1},j.prototype.getHeight=function(){return this.isNull()?0:this._maxy-this._miny},j.prototype.maxExtent=function(){if(this.isNull())return 0;var t=this.getWidth(),e=this.getHeight();return t>e?t:e},j.prototype.expandBy=function(){if(1===arguments.length){var t=arguments[0];this.expandBy(t,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this.isNull())return null;this._minx-=e,this._maxx+=e,this._miny-=n,this._maxy+=n,(this._minx>this._maxx||this._miny>this._maxy)&&this.setToNull()}},j.prototype.contains=function(){if(1===arguments.length){if(arguments[0]instanceof j){var t=arguments[0];return this.covers(t)}if(arguments[0]instanceof C){var e=arguments[0];return this.covers(e)}}else if(2===arguments.length){var n=arguments[0],i=arguments[1];return this.covers(n,i)}},j.prototype.centre=function(){return this.isNull()?null:new C((this.getMinX()+this.getMaxX())/2,(this.getMinY()+this.getMaxY())/2)},j.prototype.init=function(){if(0===arguments.length)this.setToNull();else if(1===arguments.length){if(arguments[0]instanceof C){var t=arguments[0];this.init(t.x,t.x,t.y,t.y)}else if(arguments[0]instanceof j){var e=arguments[0];this._minx=e._minx,this._maxx=e._maxx,this._miny=e._miny,this._maxy=e._maxy}}else if(2===arguments.length){var n=arguments[0],i=arguments[1];this.init(n.x,i.x,n.y,i.y)}else if(4===arguments.length){var r=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];rt._maxx&&(e=this._minx-t._maxx);var n=0;return this._maxyt._maxy&&(n=this._miny-t._maxy),0===e?n:0===n?e:Math.sqrt(e*e+n*n)},j.prototype.hashCode=function(){var t=17;return t=37*t+C.hashCode(this._minx),t=37*t+C.hashCode(this._maxx),t=37*t+C.hashCode(this._miny),t=37*t+C.hashCode(this._maxy)},j.prototype.interfaces_=function(){return[E,e]},j.prototype.getClass=function(){return j},j.intersects=function(){if(3===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2];return n.x>=(t.xe.x?t.x:e.x)&&n.y>=(t.ye.y?t.y:e.y)}if(4===arguments.length){var i=arguments[0],r=arguments[1],o=arguments[2],s=arguments[3],a=Math.min(o.x,s.x),u=Math.max(o.x,s.x),l=Math.min(i.x,r.x),c=Math.max(i.x,r.x);return!(l>u)&&(!(cu)&&!(cthis.getEdgeDistance(t,1)?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}},nt.prototype.isProper=function(){return this.hasIntersection()&&this._isProper},nt.prototype.setPrecisionModel=function(t){this._precisionModel=t},nt.prototype.isInteriorIntersection=function(){if(0===arguments.length)return!!this.isInteriorIntersection(0)||!!this.isInteriorIntersection(1);if(1===arguments.length){for(var t=arguments[0],e=0;er?i:r;else{var s=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y);0!==(o=i>r?s:a)||t.equals(e)||(o=Math.max(s,a))}return et.isTrue(!(0===o&&!t.equals(e)),\"Bad distance calculation\"),o},nt.nonRobustComputeEdgeDistance=function(t,e,n){var i=t.x-e.x,r=t.y-e.y,o=Math.sqrt(i*i+r*r);return et.isTrue(!(0===o&&!t.equals(e)),\"Invalid distance calculation\"),o},it.DONT_INTERSECT.get=function(){return 0},it.DO_INTERSECT.get=function(){return 1},it.COLLINEAR.get=function(){return 2},it.NO_INTERSECTION.get=function(){return 0},it.POINT_INTERSECTION.get=function(){return 1},it.COLLINEAR_INTERSECTION.get=function(){return 2},Object.defineProperties(nt,it);var rt=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.isInSegmentEnvelopes=function(t){var e=new j(this._inputLines[0][0],this._inputLines[0][1]),n=new j(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)},e.prototype.computeIntersection=function(){if(3!==arguments.length)return t.prototype.computeIntersection.apply(this,arguments);var e=arguments[0],n=arguments[1],i=arguments[2];if(this._isProper=!1,j.intersects(n,i,e)&&0===at.orientationIndex(n,i,e)&&0===at.orientationIndex(i,n,e))return this._isProper=!0,(e.equals(n)||e.equals(i))&&(this._isProper=!1),this._result=t.POINT_INTERSECTION,null;this._result=t.NO_INTERSECTION},e.prototype.normalizeToMinimum=function(t,e,n,i,r){r.x=this.smallestInAbsValue(t.x,e.x,n.x,i.x),r.y=this.smallestInAbsValue(t.y,e.y,n.y,i.y),t.x-=r.x,t.y-=r.y,e.x-=r.x,e.y-=r.y,n.x-=r.x,n.y-=r.y,i.x-=r.x,i.y-=r.y},e.prototype.safeHCoordinateIntersection=function(t,n,i,r){var o=null;try{o=k.intersection(t,n,i,r)}catch(s){if(!(s instanceof X))throw s;o=e.nearestEndpoint(t,n,i,r)}return o},e.prototype.intersection=function(t,n,i,r){var o=this.intersectionWithNormalization(t,n,i,r);return this.isInSegmentEnvelopes(o)||(o=new C(e.nearestEndpoint(t,n,i,r))),null!==this._precisionModel&&this._precisionModel.makePrecise(o),o},e.prototype.smallestInAbsValue=function(t,e,n,i){var r=t,o=Math.abs(r);return Math.abs(e)1e-4&&Y.out.println(\"Distance = \"+r.distance(o))},e.prototype.intersectionWithNormalization=function(t,e,n,i){var r=new C(t),o=new C(e),s=new C(n),a=new C(i),u=new C;this.normalizeToEnvCentre(r,o,s,a,u);var l=this.safeHCoordinateIntersection(r,o,s,a);return l.x+=u.x,l.y+=u.y,l},e.prototype.computeCollinearIntersection=function(e,n,i,r){var o=j.intersects(e,n,i),s=j.intersects(e,n,r),a=j.intersects(i,r,e),u=j.intersects(i,r,n);return o&&s?(this._intPt[0]=i,this._intPt[1]=r,t.COLLINEAR_INTERSECTION):a&&u?(this._intPt[0]=e,this._intPt[1]=n,t.COLLINEAR_INTERSECTION):o&&a?(this._intPt[0]=i,this._intPt[1]=e,!i.equals(e)||s||u?t.COLLINEAR_INTERSECTION:t.POINT_INTERSECTION):o&&u?(this._intPt[0]=i,this._intPt[1]=n,!i.equals(n)||s||a?t.COLLINEAR_INTERSECTION:t.POINT_INTERSECTION):s&&a?(this._intPt[0]=r,this._intPt[1]=e,!r.equals(e)||o||u?t.COLLINEAR_INTERSECTION:t.POINT_INTERSECTION):s&&u?(this._intPt[0]=r,this._intPt[1]=n,!r.equals(n)||o||a?t.COLLINEAR_INTERSECTION:t.POINT_INTERSECTION):t.NO_INTERSECTION},e.prototype.normalizeToEnvCentre=function(t,e,n,i,r){var o=t.xe.x?t.x:e.x,u=t.y>e.y?t.y:e.y,l=n.xi.x?n.x:i.x,h=n.y>i.y?n.y:i.y,f=((o>l?o:l)+(ac?s:c)+(u0&&s>0||o<0&&s<0)return t.NO_INTERSECTION;var a=at.orientationIndex(i,r,e),u=at.orientationIndex(i,r,n);if(a>0&&u>0||a<0&&u<0)return t.NO_INTERSECTION;return 0===o&&0===s&&0===a&&0===u?this.computeCollinearIntersection(e,n,i,r):(0===o||0===s||0===a||0===u?(this._isProper=!1,e.equals2D(i)||e.equals2D(r)?this._intPt[0]=e:n.equals2D(i)||n.equals2D(r)?this._intPt[0]=n:0===o?this._intPt[0]=new C(i):0===s?this._intPt[0]=new C(r):0===a?this._intPt[0]=new C(e):0===u&&(this._intPt[0]=new C(n))):(this._isProper=!0,this._intPt[0]=this.intersection(e,n,i,r)),t.POINT_INTERSECTION)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e.nearestEndpoint=function(t,e,n,i){var r=t,o=at.distancePointLine(t,n,i),s=at.distancePointLine(e,n,i);return s0?n>0?-r:r:n>0?r:-r;if(0===e||0===n)return i>0?t>0?r:-r:t>0?-r:r;if(e>0?i>0?e<=i||(r=-r,o=t,t=n,n=o,o=e,e=i,i=o):e<=-i?(r=-r,n=-n,i=-i):(o=t,t=-n,n=o,o=e,e=-i,i=o):i>0?-e<=i?(r=-r,t=-t,e=-e):(o=-t,t=n,n=o,o=-e,e=i,i=o):e>=i?(t=-t,e=-e,n=-n,i=-i):(r=-r,o=-t,t=-n,n=o,o=-e,e=-i,i=o),t>0){if(!(n>0))return r;if(!(t<=n))return r}else{if(n>0)return-r;if(!(t>=n))return-r;r=-r,t=-t,n=-n}for(;;){if(s=Math.floor(n/t),n-=s*t,(i-=s*e)<0)return-r;if(i>e)return r;if(t>n+n){if(ei+i)return-r;n=t-n,i=e-i,r=-r}if(0===i)return 0===n?0:-r;if(0===n)return r;if(s=Math.floor(t/n),t-=s*n,(e-=s*i)<0)return r;if(e>i)return-r;if(n>t+t){if(ie+e)return r;t=n-t,e=i-e,r=-r}if(0===e)return 0===t?0:r;if(0===t)return-r}};var st=function(){this._p=null,this._crossingCount=0,this._isPointOnSegment=!1;var t=arguments[0];this._p=t};st.prototype.countSegment=function(t,e){if(t.xi&&(n=e.x,i=t.x),this._p.x>=n&&this._p.x<=i&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){var r=t.x-this._p.x,o=t.y-this._p.y,s=e.x-this._p.x,a=e.y-this._p.y,u=ot.signOfDet2x2(r,o,s,a);if(0===u)return this._isPointOnSegment=!0,null;a0&&this._crossingCount++}},st.prototype.isPointInPolygon=function(){return this.getLocation()!==w.EXTERIOR},st.prototype.getLocation=function(){return this._isPointOnSegment?w.BOUNDARY:this._crossingCount%2==1?w.INTERIOR:w.EXTERIOR},st.prototype.isOnSegment=function(){return this._isPointOnSegment},st.prototype.interfaces_=function(){return[]},st.prototype.getClass=function(){return st},st.locatePointInRing=function(){if(arguments[0]instanceof C&&T(arguments[1],V)){for(var t=arguments[0],e=arguments[1],n=new st(t),i=new C,r=new C,o=1;o1||a<0||a>1)&&(r=!0)}}else r=!0;return r?R.min(at.distancePointLine(t,n,i),at.distancePointLine(e,n,i),at.distancePointLine(n,t,e),at.distancePointLine(i,t,e)):0},at.isPointInRing=function(t,e){return at.locatePointInRing(t,e)!==w.EXTERIOR},at.computeLength=function(t){var e=t.size();if(e<=1)return 0;var n=0,i=new C;t.getCoordinate(0,i);for(var r=i.x,o=i.y,s=1;sn.y&&(n=o,i=r)}var s=i;do{(s-=1)<0&&(s=e)}while(t[s].equals2D(n)&&s!==i);var a=i;do{a=(a+1)%e}while(t[a].equals2D(n)&&a!==i);var u=t[s],l=t[a];if(u.equals2D(n)||l.equals2D(n)||u.equals2D(l))return!1;var c=at.computeOrientation(u,n,l),p=!1;return p=0===c?u.x>l.x:c>0,p},at.locatePointInRing=function(t,e){return st.locatePointInRing(t,e)},at.distancePointLinePerpendicular=function(t,e,n){var i=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),r=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/i;return Math.abs(r)*Math.sqrt(i)},at.computeOrientation=function(t,e,n){return at.orientationIndex(t,e,n)},at.distancePointLine=function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];if(0===e.length)throw new m(\"Line array must contain at least one vertex\");for(var n=t.distance(e[0]),i=0;i=1)return o.distance(a);var c=((s.y-o.y)*(a.x-s.x)-(s.x-o.x)*(a.y-s.y))/u;return Math.abs(c)*Math.sqrt(u)}},at.isOnLine=function(t,e){for(var n=new rt,i=1;i0},_t.prototype.interfaces_=function(){return[gt]},_t.prototype.getClass=function(){return _t};var mt=function(){};mt.prototype.isInBoundary=function(t){return t>1},mt.prototype.interfaces_=function(){return[gt]},mt.prototype.getClass=function(){return mt};var vt=function(){};vt.prototype.isInBoundary=function(t){return 1===t},vt.prototype.interfaces_=function(){return[gt]},vt.prototype.getClass=function(){return vt};var It=function(){};It.prototype.add=function(){},It.prototype.addAll=function(){},It.prototype.isEmpty=function(){},It.prototype.iterator=function(){},It.prototype.size=function(){},It.prototype.toArray=function(){},It.prototype.remove=function(){},(n.prototype=new Error).name=\"IndexOutOfBoundsException\";var Et=function(){};Et.prototype.hasNext=function(){},Et.prototype.next=function(){},Et.prototype.remove=function(){};var xt=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(){},e.prototype.set=function(){},e.prototype.isEmpty=function(){},e}(It);(i.prototype=new Error).name=\"NoSuchElementException\";var Nt=function(t){function e(){t.call(this),this.array_=[],arguments[0]instanceof It&&this.addAll(arguments[0])}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.ensureCapacity=function(){},e.prototype.interfaces_=function(){return[t,It]},e.prototype.add=function(t){return 1===arguments.length?this.array_.push(t):this.array_.splice(arguments[0],arguments[1]),!0},e.prototype.clear=function(){this.array_=[]},e.prototype.addAll=function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next());return!0},e.prototype.set=function(t,e){var n=this.array_[t];return this.array_[t]=e,n},e.prototype.iterator=function(){return new Ct(this)},e.prototype.get=function(t){if(t<0||t>=this.size())throw new n;return this.array_[t]},e.prototype.isEmpty=function(){return 0===this.array_.length},e.prototype.size=function(){return this.array_.length},e.prototype.toArray=function(){for(var t=[],e=0,n=this.array_.length;e=1){if(this.get(this.size()-1).equals2D(r))return null}t.prototype.add.call(this,r)}else if(arguments[0]instanceof Object&&\"boolean\"==typeof arguments[1]){var o=arguments[0],s=arguments[1];return this.add(o,s),!0}}else if(3===arguments.length){if(\"boolean\"==typeof arguments[2]&&arguments[0]instanceof Array&&\"boolean\"==typeof arguments[1]){var a=arguments[0],u=arguments[1];if(arguments[2])for(var l=0;l=0;c--)this.add(a[c],u);return!0}if(\"boolean\"==typeof arguments[2]&&Number.isInteger(arguments[0])&&arguments[1]instanceof C){var p=arguments[0],h=arguments[1];if(!arguments[2]){var f=this.size();if(f>0){if(p>0){if(this.get(p-1).equals2D(h))return null}if(p_&&(m=-1);for(var v=y;v!==_;v+=m)this.add(g[v],d);return!0}},e.prototype.closeRing=function(){this.size()>0&&this.add(new C(this.get(0)),!1)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},Object.defineProperties(e,n),e}(Nt),Lt=function(){},bt={ForwardComparator:{configurable:!0},BidirectionalComparator:{configurable:!0},coordArrayType:{configurable:!0}};bt.ForwardComparator.get=function(){return wt},bt.BidirectionalComparator.get=function(){return Ot},bt.coordArrayType.get=function(){return new Array(0).fill(null)},Lt.prototype.interfaces_=function(){return[]},Lt.prototype.getClass=function(){return Lt},Lt.isRing=function(t){return!(t.length<4)&&!!t[0].equals2D(t[t.length-1])},Lt.ptNotInList=function(t,e){for(var n=0;n=t?e:[]},Lt.indexOf=function(t,e){for(var n=0;n0)&&(e=t[n]);return e},Lt.extract=function(t,e,n){e=R.clamp(e,0,t.length);var i=(n=R.clamp(n,-1,t.length))-e+1;n<0&&(i=0),e>=t.length&&(i=0),ni.length)return 1;if(0===n.length)return 0;var r=Lt.compare(n,i);return Lt.isEqualReversed(n,i)?0:r},Ot.prototype.OLDcompare=function(t,e){var n=t,i=e;if(n.lengthi.length)return 1;if(0===n.length)return 0;for(var r=Lt.increasingDirection(n),o=Lt.increasingDirection(i),s=r>0?0:n.length-1,a=o>0?0:n.length-1,u=0;u0))return e.value;e=e.right}}return null},p.prototype.put=function(t,e){if(null===this.root_)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:Mt,getValue:function(){return this.value},getKey:function(){return this.key}},this.size_=1,null;var n,i,r=this.root_;do{if(n=r,(i=t.compareTo(r.key))<0)r=r.left;else{if(!(i>0)){var o=r.value;return r.value=e,o}r=r.right}}while(null!==r);var s={key:t,left:null,right:null,value:e,parent:n,color:Mt,getValue:function(){return this.value},getKey:function(){return this.key}};return i<0?n.left=s:n.right=s,this.fixAfterInsertion(s),this.size_++,null},p.prototype.fixAfterInsertion=function(t){for(t.color=1;null!=t&&t!==this.root_&&1===t.parent.color;)if(a(t)===l(a(a(t)))){var e=c(a(a(t)));1===s(e)?(u(a(t),Mt),u(e,Mt),u(a(a(t)),1),t=a(a(t))):(t===c(a(t))&&(t=a(t),this.rotateLeft(t)),u(a(t),Mt),u(a(a(t)),1),this.rotateRight(a(a(t))))}else{var n=l(a(a(t)));1===s(n)?(u(a(t),Mt),u(n,Mt),u(a(a(t)),1),t=a(a(t))):(t===l(a(t))&&(t=a(t),this.rotateRight(t)),u(a(t),Mt),u(a(a(t)),1),this.rotateLeft(a(a(t))))}this.root_.color=Mt},p.prototype.values=function(){var t=new Nt,e=this.getFirstEntry();if(null!==e)for(t.add(e.value);null!==(e=p.successor(e));)t.add(e.value);return t},p.prototype.entrySet=function(){var t=new Pt,e=this.getFirstEntry();if(null!==e)for(t.add(e);null!==(e=p.successor(e));)t.add(e);return t},p.prototype.rotateLeft=function(t){if(null!=t){var e=t.right;t.right=e.left,null!=e.left&&(e.left.parent=t),e.parent=t.parent,null===t.parent?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}},p.prototype.rotateRight=function(t){if(null!=t){var e=t.left;t.left=e.right,null!=e.right&&(e.right.parent=t),e.parent=t.parent,null===t.parent?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}},p.prototype.getFirstEntry=function(){var t=this.root_;if(null!=t)for(;null!=t.left;)t=t.left;return t},p.successor=function(t){if(null===t)return null;if(null!==t.right){for(var e=t.right;null!==e.left;)e=e.left;return e}for(var n=t.parent,i=t;null!==n&&i===n.right;)i=n,n=n.parent;return n},p.prototype.size=function(){return this.size_};var At=function(){};At.prototype.interfaces_=function(){return[]},At.prototype.getClass=function(){return At},h.prototype=new o,(f.prototype=new h).contains=function(t){for(var e=0,n=this.array_.length;e=0;){var s=r.substring(0,o);i.add(s),o=(r=r.substring(o+n)).indexOf(e)}r.length>0&&i.add(r);for(var a=new Array(i.size()).fill(null),u=0;u0)for(var o=r;o0&&i.append(\" \");for(var o=0;o0&&i.append(\",\"),i.append(jt.toString(t.getOrdinate(r,o)))}return i.append(\")\"),i.toString()}},Wt.ensureValidRing=function(t,e){var n=e.size();if(0===n)return e;if(n<=3)return Wt.createClosedRing(t,e,4);return e.getOrdinate(0,V.X)===e.getOrdinate(n-1,V.X)&&e.getOrdinate(0,V.Y)===e.getOrdinate(n-1,V.Y)?e:Wt.createClosedRing(t,e,n+1)},Wt.createClosedRing=function(t,e,n){var i=t.create(n,e.getDimension()),r=e.size();Wt.copy(e,0,i,0,r);for(var o=r;o0&&Wt.reverse(this._points),null}},e.prototype.getCoordinate=function(){return this.isEmpty()?null:this._points.getCoordinate(0)},e.prototype.getBoundaryDimension=function(){return this.isClosed()?qt.FALSE:0},e.prototype.isClosed=function(){return!this.isEmpty()&&this.getCoordinateN(0).equals2D(this.getCoordinateN(this.getNumPoints()-1))},e.prototype.getEndPoint=function(){return this.isEmpty()?null:this.getPointN(this.getNumPoints()-1)},e.prototype.getDimension=function(){return 1},e.prototype.getLength=function(){return at.computeLength(this._points)},e.prototype.getNumPoints=function(){return this._points.size()},e.prototype.reverse=function(){var t=this._points.copy();Wt.reverse(t);return this.getFactory().createLineString(t)},e.prototype.compareToSameClass=function(){if(1===arguments.length){for(var t=arguments[0],e=0,n=0;e= 2)\");this._points=t},e.prototype.isCoordinate=function(t){for(var e=0;e=1&&this.getCoordinateSequence().size()= 4)\")},e.prototype.getGeometryType=function(){return\"LinearRing\"},e.prototype.copy=function(){return new e(this._points.copy(),this._factory)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},n.MINIMUM_VALID_SIZE.get=function(){return 4},n.serialVersionUID.get=function(){return-0x3b229e262367a600},Object.defineProperties(e,n),e}(Kt),ne=function(t){function e(){t.apply(this,arguments)}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var n={serialVersionUID:{configurable:!0}};return e.prototype.getSortIndex=function(){return ct.SORTINDEX_MULTIPOLYGON},e.prototype.equalsExact=function(){if(2===arguments.length){var e=arguments[0],n=arguments[1];return!!this.isEquivalentClass(e)&&t.prototype.equalsExact.call(this,e,n)}return t.prototype.equalsExact.apply(this,arguments)},e.prototype.getBoundaryDimension=function(){return 1},e.prototype.getDimension=function(){return 2},e.prototype.reverse=function(){for(var t=this._geometries.length,e=new Array(t).fill(null),n=0;n0?e.createPoint(n[0]):e.createPoint():t},se.prototype.interfaces_=function(){return[ie.GeometryEditorOperation]},se.prototype.getClass=function(){return se};var ae=function(){};ae.prototype.edit=function(t,e){return t instanceof ee?e.createLinearRing(this.edit(t.getCoordinateSequence(),t)):t instanceof Kt?e.createLineString(this.edit(t.getCoordinateSequence(),t)):t instanceof Qt?e.createPoint(this.edit(t.getCoordinateSequence(),t)):t},ae.prototype.interfaces_=function(){return[ie.GeometryEditorOperation]},ae.prototype.getClass=function(){return ae};var ue=function(){if(this._dimension=3,this._coordinates=null,1===arguments.length){if(arguments[0]instanceof Array)this._coordinates=arguments[0],this._dimension=3;else if(Number.isInteger(arguments[0])){var t=arguments[0];this._coordinates=new Array(t).fill(null);for(var e=0;e0){var t=new D(17*this._coordinates.length);t.append(\"(\"),t.append(this._coordinates[0]);for(var e=1;e3&&(i=3),i<2?new ue(n):new ue(n,i)}},ce.prototype.interfaces_=function(){return[b,e]},ce.prototype.getClass=function(){return ce},ce.instance=function(){return ce.instanceObject},pe.serialVersionUID.get=function(){return-0x38e49fa6cf6f2e00},pe.instanceObject.get=function(){return new ce},Object.defineProperties(ce,pe);var he=function(t){function e(){t.call(this),this.map_=new Map}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.get=function(t){return this.map_.get(t)||null},e.prototype.put=function(t,e){return this.map_.set(t,e),e},e.prototype.values=function(){for(var t=new Nt,e=this.map_.values(),n=e.next();!n.done;)t.add(n.value),n=e.next();return t},e.prototype.entrySet=function(){var t=new Pt;return this.map_.entries().forEach(function(e){return t.add(e)}),t},e.prototype.size=function(){return this.map_.size()},e}(Tt),fe=function t(){if(this._modelType=null,this._scale=null,0===arguments.length)this._modelType=t.FLOATING;else if(1===arguments.length)if(arguments[0]instanceof de){var e=arguments[0];this._modelType=e,e===t.FIXED&&this.setScale(1)}else if(\"number\"==typeof arguments[0]){var n=arguments[0];this._modelType=t.FIXED,this.setScale(n)}else if(arguments[0]instanceof t){var i=arguments[0];this._modelType=i._modelType,this._scale=i._scale}},ge={serialVersionUID:{configurable:!0},maximumPreciseValue:{configurable:!0}};fe.prototype.equals=function(t){if(!(t instanceof fe))return!1;var e=t;return this._modelType===e._modelType&&this._scale===e._scale},fe.prototype.compareTo=function(t){var e=t,n=this.getMaximumSignificantDigits(),i=e.getMaximumSignificantDigits();return new M(n).compareTo(new M(i))},fe.prototype.getScale=function(){return this._scale},fe.prototype.isFloating=function(){return this._modelType===fe.FLOATING||this._modelType===fe.FLOATING_SINGLE},fe.prototype.getType=function(){return this._modelType},fe.prototype.toString=function(){var t=\"UNKNOWN\";return this._modelType===fe.FLOATING?t=\"Floating\":this._modelType===fe.FLOATING_SINGLE?t=\"Floating-Single\":this._modelType===fe.FIXED&&(t=\"Fixed (Scale=\"+this.getScale()+\")\"),t},fe.prototype.makePrecise=function(){if(\"number\"==typeof arguments[0]){var t=arguments[0];if(v.isNaN(t))return t;if(this._modelType===fe.FLOATING_SINGLE){return t}return this._modelType===fe.FIXED?Math.round(t*this._scale)/this._scale:t}if(arguments[0]instanceof C){var e=arguments[0];if(this._modelType===fe.FLOATING)return null;e.x=this.makePrecise(e.x),e.y=this.makePrecise(e.y)}},fe.prototype.getMaximumSignificantDigits=function(){var t=16;return this._modelType===fe.FLOATING?t=16:this._modelType===fe.FLOATING_SINGLE?t=6:this._modelType===fe.FIXED&&(t=1+Math.trunc(Math.ceil(Math.log(this.getScale())/Math.log(10)))),t},fe.prototype.setScale=function(t){this._scale=Math.abs(t)},fe.prototype.interfaces_=function(){return[e,E]},fe.prototype.getClass=function(){return fe},fe.mostPrecise=function(t,e){return t.compareTo(e)>=0?t:e},ge.serialVersionUID.get=function(){return 0x6bee6404e9a25c00},ge.maximumPreciseValue.get=function(){return 9007199254740992},Object.defineProperties(fe,ge);var de=function t(e){this._name=e||null,t.nameToTypeMap.put(e,this)},ye={serialVersionUID:{configurable:!0},nameToTypeMap:{configurable:!0}};de.prototype.readResolve=function(){return de.nameToTypeMap.get(this._name)},de.prototype.toString=function(){return this._name},de.prototype.interfaces_=function(){return[e]},de.prototype.getClass=function(){return de},ye.serialVersionUID.get=function(){return-552860263173159e4},ye.nameToTypeMap.get=function(){return new he},Object.defineProperties(de,ye),fe.Type=de,fe.FIXED=new de(\"FIXED\"),fe.FLOATING=new de(\"FLOATING\"),fe.FLOATING_SINGLE=new de(\"FLOATING SINGLE\");var _e=function t(){this._precisionModel=new fe,this._SRID=0,this._coordinateSequenceFactory=t.getDefaultCoordinateSequenceFactory(),0===arguments.length||(1===arguments.length?T(arguments[0],b)?this._coordinateSequenceFactory=arguments[0]:arguments[0]instanceof fe&&(this._precisionModel=arguments[0]):2===arguments.length?(this._precisionModel=arguments[0],this._SRID=arguments[1]):3===arguments.length&&(this._precisionModel=arguments[0],this._SRID=arguments[1],this._coordinateSequenceFactory=arguments[2]))},me={serialVersionUID:{configurable:!0}};_e.prototype.toGeometry=function(t){return t.isNull()?this.createPoint(null):t.getMinX()===t.getMaxX()&&t.getMinY()===t.getMaxY()?this.createPoint(new C(t.getMinX(),t.getMinY())):t.getMinX()===t.getMaxX()||t.getMinY()===t.getMaxY()?this.createLineString([new C(t.getMinX(),t.getMinY()),new C(t.getMaxX(),t.getMaxY())]):this.createPolygon(this.createLinearRing([new C(t.getMinX(),t.getMinY()),new C(t.getMinX(),t.getMaxY()),new C(t.getMaxX(),t.getMaxY()),new C(t.getMaxX(),t.getMinY()),new C(t.getMinX(),t.getMinY())]),null)},_e.prototype.createLineString=function(t){return t?t instanceof Array?new Kt(this.getCoordinateSequenceFactory().create(t),this):T(t,V)?new Kt(t,this):void 0:new Kt(this.getCoordinateSequenceFactory().create([]),this)},_e.prototype.createMultiLineString=function(){if(0===arguments.length)return new Xt(null,this);if(1===arguments.length){var t=arguments[0];return new Xt(t,this)}},_e.prototype.buildGeometry=function(t){for(var e=null,n=!1,i=!1,r=t.iterator();r.hasNext();){var o=r.next(),s=o.getClass();null===e&&(e=s),s!==e&&(n=!0),o.isGeometryCollectionOrDerived()&&(i=!0)}if(null===e)return this.createGeometryCollection();if(n||i)return this.createGeometryCollection(_e.toGeometryArray(t));var a=t.iterator().next();if(t.size()>1){if(a instanceof $t)return this.createMultiPolygon(_e.toPolygonArray(t));if(a instanceof Kt)return this.createMultiLineString(_e.toLineStringArray(t));if(a instanceof Qt)return this.createMultiPoint(_e.toPointArray(t));et.shouldNeverReachHere(\"Unhandled class: \"+a.getClass().getName())}return a},_e.prototype.createMultiPointFromCoords=function(t){return this.createMultiPoint(null!==t?this.getCoordinateSequenceFactory().create(t):null)},_e.prototype.createPoint=function(){if(0===arguments.length)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof C){var t=arguments[0];return this.createPoint(null!==t?this.getCoordinateSequenceFactory().create([t]):null)}if(T(arguments[0],V)){var e=arguments[0];return new Qt(e,this)}}},_e.prototype.getCoordinateSequenceFactory=function(){return this._coordinateSequenceFactory},_e.prototype.createPolygon=function(){if(0===arguments.length)return new $t(null,null,this);if(1===arguments.length){if(T(arguments[0],V)){var t=arguments[0];return this.createPolygon(this.createLinearRing(t))}if(arguments[0]instanceof Array){var e=arguments[0];return this.createPolygon(this.createLinearRing(e))}if(arguments[0]instanceof ee){var n=arguments[0];return this.createPolygon(n,null)}}else if(2===arguments.length){var i=arguments[0],r=arguments[1];return new $t(i,r,this)}},_e.prototype.getSRID=function(){return this._SRID},_e.prototype.createGeometryCollection=function(){if(0===arguments.length)return new zt(null,this);if(1===arguments.length){var t=arguments[0];return new zt(t,this)}},_e.prototype.createGeometry=function(t){return new ie(this).edit(t,{edit:function(){if(2===arguments.length){var t=arguments[0];return this._coordinateSequenceFactory.create(t)}}})},_e.prototype.getPrecisionModel=function(){return this._precisionModel},_e.prototype.createLinearRing=function(){if(0===arguments.length)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return this.createLinearRing(null!==t?this.getCoordinateSequenceFactory().create(t):null)}if(T(arguments[0],V)){var e=arguments[0];return new ee(e,this)}}},_e.prototype.createMultiPolygon=function(){if(0===arguments.length)return new ne(null,this);if(1===arguments.length){var t=arguments[0];return new ne(t,this)}},_e.prototype.createMultiPoint=function(){if(0===arguments.length)return new te(null,this);if(1===arguments.length){if(arguments[0]instanceof Array){var t=arguments[0];return new te(t,this)}if(arguments[0]instanceof Array){var e=arguments[0];return this.createMultiPoint(null!==e?this.getCoordinateSequenceFactory().create(e):null)}if(T(arguments[0],V)){var n=arguments[0];if(null===n)return this.createMultiPoint(new Array(0).fill(null));for(var i=new Array(n.size()).fill(null),r=0;r=this.size())throw new Error;return this.array_[t]},y.prototype.push=function(t){return this.array_.push(t),t},y.prototype.pop=function(t){if(0===this.array_.length)throw new d;return this.array_.pop()},y.prototype.peek=function(){if(0===this.array_.length)throw new d;return this.array_[this.array_.length-1]},y.prototype.empty=function(){return 0===this.array_.length},y.prototype.isEmpty=function(){return this.empty()},y.prototype.search=function(t){return this.array_.indexOf(t)},y.prototype.size=function(){return this.array_.length},y.prototype.toArray=function(){for(var t=[],e=0,n=this.array_.length;e0&&this._minIndexthis._minCoord.y&&n.y>this._minCoord.y&&i===at.CLOCKWISE&&(r=!0),r&&(this._minIndex=this._minIndex-1)},be.prototype.getRightmostSideOfSegment=function(t,e){var n=t.getEdge().getCoordinates();if(e<0||e+1>=n.length)return-1;if(n[e].y===n[e+1].y)return-1;var i=Se.LEFT;return n[e].ythis._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])},be.prototype.findRightmostEdgeAtNode=function(){var t=this._minDe.getNode().getEdges();this._minDe=t.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)},be.prototype.findEdge=function(t){for(var e=t.iterator();e.hasNext();){var n=e.next();n.isForward()&&this.checkForRightmostCoordinate(n)}et.isTrue(0!==this._minIndex||this._minCoord.equals(this._minDe.getCoordinate()),\"inconsistency in rightmost processing\"),0===this._minIndex?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe;this.getRightmostSide(this._minDe,this._minIndex)===Se.LEFT&&(this._orientedDe=this._minDe.getSym())},be.prototype.interfaces_=function(){return[]},be.prototype.getClass=function(){return be};var we=function(t){function e(n,i){t.call(this,e.msgWithCoord(n,i)),this.pt=i?new C(i):null,this.name=\"TopologyException\"}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getCoordinate=function(){return this.pt},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e.msgWithCoord=function(t,e){return e?t:t+\" [ \"+e+\" ]\"},e}($),Oe=function(){this.array_=[]};Oe.prototype.addLast=function(t){this.array_.push(t)},Oe.prototype.removeFirst=function(){return this.array_.shift()},Oe.prototype.isEmpty=function(){return 0===this.array_.length};var Te=function(){this._finder=null,this._dirEdgeList=new Nt,this._nodes=new Nt,this._rightMostCoord=null,this._env=null,this._finder=new be};Te.prototype.clearVisitedEdges=function(){for(var t=this._dirEdgeList.iterator();t.hasNext();){t.next().setVisited(!1)}},Te.prototype.getRightmostCoordinate=function(){return this._rightMostCoord},Te.prototype.computeNodeDepth=function(t){for(var e=null,n=t.getEdges().iterator();n.hasNext();){var i=n.next();if(i.isVisited()||i.getSym().isVisited()){e=i;break}}if(null===e)throw new we(\"unable to find edge to compute depths at \"+t.getCoordinate());t.getEdges().computeDepths(e);for(var r=t.getEdges().iterator();r.hasNext();){var o=r.next();o.setVisited(!0),this.copySymDepths(o)}},Te.prototype.computeDepth=function(t){this.clearVisitedEdges();var e=this._finder.getEdge();e.setEdgeDepths(Se.RIGHT,t),this.copySymDepths(e),this.computeDepths(e)},Te.prototype.create=function(t){this.addReachable(t),this._finder.findEdge(this._dirEdgeList),this._rightMostCoord=this._finder.getCoordinate()},Te.prototype.findResultEdges=function(){for(var t=this._dirEdgeList.iterator();t.hasNext();){var e=t.next();e.getDepth(Se.RIGHT)>=1&&e.getDepth(Se.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}},Te.prototype.computeDepths=function(t){var e=new Pt,n=new Oe,i=t.getNode();for(n.addLast(i),e.add(i),t.setVisited(!0);!n.isEmpty();){var r=n.removeFirst();e.add(r),this.computeNodeDepth(r);for(var o=r.getEdges().iterator();o.hasNext();){var s=o.next().getSym();if(!s.isVisited()){var a=s.getNode();e.contains(a)||(n.addLast(a),e.add(a))}}}},Te.prototype.compareTo=function(t){var e=t;return this._rightMostCoord.xe._rightMostCoord.x?1:0},Te.prototype.getEnvelope=function(){if(null===this._env){for(var t=new j,e=this._dirEdgeList.iterator();e.hasNext();)for(var n=e.next().getEdge().getCoordinates(),i=0;ithis.location.length){var e=new Array(3).fill(null);e[Se.ON]=this.location[Se.ON],e[Se.LEFT]=w.NONE,e[Se.RIGHT]=w.NONE,this.location=e}for(var n=0;n1&&t.append(w.toLocationSymbol(this.location[Se.LEFT])),t.append(w.toLocationSymbol(this.location[Se.ON])),this.location.length>1&&t.append(w.toLocationSymbol(this.location[Se.RIGHT])),t.toString()},Re.prototype.setLocations=function(t,e,n){this.location[Se.ON]=t,this.location[Se.LEFT]=e,this.location[Se.RIGHT]=n},Re.prototype.get=function(t){return t1},Re.prototype.isAnyNull=function(){for(var t=0;tthis._maxNodeDegree&&(this._maxNodeDegree=e),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2},De.prototype.addPoints=function(t,e,n){var i=t.getCoordinates();if(e){var r=1;n&&(r=0);for(var o=r;o=0;a--)this._pts.add(i[a])}},De.prototype.isHole=function(){return this._isHole},De.prototype.setInResult=function(){var t=this._startDe;do{t.getEdge().setInResult(!0),t=t.getNext()}while(t!==this._startDe)},De.prototype.containsPoint=function(t){var e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t))return!1;if(!at.isPointInRing(t,e.getCoordinates()))return!1;for(var n=this._holes.iterator();n.hasNext();){if(n.next().containsPoint(t))return!1}return!0},De.prototype.addHole=function(t){this._holes.add(t)},De.prototype.isShell=function(){return null===this._shell},De.prototype.getLabel=function(){return this._label},De.prototype.getEdges=function(){return this._edges},De.prototype.getMaxNodeDegree=function(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree},De.prototype.getShell=function(){return this._shell},De.prototype.mergeLabel=function(){if(1===arguments.length){var t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(2===arguments.length){var e=arguments[0],n=arguments[1],i=e.getLocation(n,Se.RIGHT);if(i===w.NONE)return null;if(this._label.getLocation(n)===w.NONE)return this._label.setLocation(n,i),null}},De.prototype.setShell=function(t){this._shell=t,null!==t&&t.addHole(this)},De.prototype.toPolygon=function(t){for(var e=new Array(this._holes.size()).fill(null),n=0;n=2,\"found partial label\"),this.computeIM(t)},Fe.prototype.isInResult=function(){return this._isInResult},Fe.prototype.isVisited=function(){return this._isVisited},Fe.prototype.interfaces_=function(){return[]},Fe.prototype.getClass=function(){return Fe};var Ge=function(t){function e(){t.call(this),this._coord=null,this._edges=null;var e=arguments[0],n=arguments[1];this._coord=e,this._edges=n,this._label=new Pe(0,w.NONE)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.isIncidentEdgeInResult=function(){for(var t=this.getEdges().getEdges().iterator();t.hasNext();){if(t.next().getEdge().isInResult())return!0}return!1},e.prototype.isIsolated=function(){return 1===this._label.getGeometryCount()},e.prototype.getCoordinate=function(){return this._coord},e.prototype.print=function(t){t.println(\"node \"+this._coord+\" lbl: \"+this._label)},e.prototype.computeIM=function(t){},e.prototype.computeMergedLocation=function(t,e){var n=w.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){var i=t.getLocation(e);n!==w.BOUNDARY&&(n=i)}return n},e.prototype.setLabel=function(){if(2!==arguments.length)return t.prototype.setLabel.apply(this,arguments);var e=arguments[0],n=arguments[1];null===this._label?this._label=new Pe(e,n):this._label.setLocation(e,n)},e.prototype.getEdges=function(){return this._edges},e.prototype.mergeLabel=function(){if(arguments[0]instanceof e){var t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Pe)for(var n=arguments[0],i=0;i<2;i++){var r=this.computeMergedLocation(n,i);this._label.getLocation(i)===w.NONE&&this._label.setLocation(i,r)}},e.prototype.add=function(t){this._edges.insert(t),t.setNode(this)},e.prototype.setLabelBoundary=function(t){if(null===this._label)return null;var e=w.NONE;null!==this._label&&(e=this._label.getLocation(t));var n=null;switch(e){case w.BOUNDARY:n=w.INTERIOR;break;case w.INTERIOR:default:n=w.BOUNDARY}this._label.setLocation(t,n)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(Fe),qe=function(){this.nodeMap=new p,this.nodeFact=null;var t=arguments[0];this.nodeFact=t};qe.prototype.find=function(t){return this.nodeMap.get(t)},qe.prototype.addNode=function(){if(arguments[0]instanceof C){var t=arguments[0],e=this.nodeMap.get(t);return null===e&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}if(arguments[0]instanceof Ge){var n=arguments[0],i=this.nodeMap.get(n.getCoordinate());return null===i?(this.nodeMap.put(n.getCoordinate(),n),n):(i.mergeLabel(n),i)}},qe.prototype.print=function(t){for(var e=this.iterator();e.hasNext();){e.next().print(t)}},qe.prototype.iterator=function(){return this.nodeMap.values().iterator()},qe.prototype.values=function(){return this.nodeMap.values()},qe.prototype.getBoundaryNodes=function(t){for(var e=new Nt,n=this.iterator();n.hasNext();){var i=n.next();i.getLabel().getLocation(t)===w.BOUNDARY&&e.add(i)}return e},qe.prototype.add=function(t){var e=t.getCoordinate();this.addNode(e).add(t)},qe.prototype.interfaces_=function(){return[]},qe.prototype.getClass=function(){return qe};var Be=function(){},Ve={NE:{configurable:!0},NW:{configurable:!0},SW:{configurable:!0},SE:{configurable:!0}};Be.prototype.interfaces_=function(){return[]},Be.prototype.getClass=function(){return Be},Be.isNorthern=function(t){return t===Be.NE||t===Be.NW},Be.isOpposite=function(t,e){if(t===e)return!1;return 2===(t-e+4)%4},Be.commonHalfPlane=function(t,e){if(t===e)return t;if(2===(t-e+4)%4)return-1;var n=te?t:e)?3:n},Be.isInHalfPlane=function(t,e){return e===Be.SE?t===Be.SE||t===Be.SW:t===e||t===e+1},Be.quadrant=function(){if(\"number\"==typeof arguments[0]&&\"number\"==typeof arguments[1]){var t=arguments[0],e=arguments[1];if(0===t&&0===e)throw new m(\"Cannot compute the quadrant for point ( \"+t+\", \"+e+\" )\");return t>=0?e>=0?Be.NE:Be.SE:e>=0?Be.NW:Be.SW}if(arguments[0]instanceof C&&arguments[1]instanceof C){var n=arguments[0],i=arguments[1];if(i.x===n.x&&i.y===n.y)throw new m(\"Cannot compute the quadrant for two identical points \"+n);return i.x>=n.x?i.y>=n.y?Be.NE:Be.SE:i.y>=n.y?Be.NW:Be.SW}},Ve.NE.get=function(){return 0},Ve.NW.get=function(){return 1},Ve.SW.get=function(){return 2},Ve.SE.get=function(){return 3},Object.defineProperties(Be,Ve);var Ue=function(){if(this._edge=null,this._label=null,this._node=null,this._p0=null,this._p1=null,this._dx=null,this._dy=null,this._quadrant=null,1===arguments.length){var t=arguments[0];this._edge=t}else if(3===arguments.length){var e=arguments[0],n=arguments[1],i=arguments[2];this._edge=e,this.init(n,i),this._label=null}else if(4===arguments.length){var r=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this._edge=r,this.init(o,s),this._label=a}};Ue.prototype.compareDirection=function(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant2){o.linkDirectedEdgesForMinimalEdgeRings();var s=o.buildMinimalRings(),a=this.findShell(s);null!==a?(this.placePolygonHoles(a,s),e.add(a)):n.addAll(s)}else i.add(o)}return i},ke.prototype.containsPoint=function(t){for(var e=this._shellList.iterator();e.hasNext();){if(e.next().containsPoint(t))return!0}return!1},ke.prototype.buildMaximalEdgeRings=function(t){for(var e=new Nt,n=t.iterator();n.hasNext();){var i=n.next();if(i.isInResult()&&i.getLabel().isArea()&&null===i.getEdgeRing()){var r=new Ae(i,this._geometryFactory);e.add(r),r.setInResult()}}return e},ke.prototype.placePolygonHoles=function(t,e){for(var n=e.iterator();n.hasNext();){var i=n.next();i.isHole()&&i.setShell(t)}},ke.prototype.getPolygons=function(){return this.computePolygons(this._shellList)},ke.prototype.findEdgeRingContaining=function(t,e){for(var n=t.getLinearRing(),i=n.getEnvelopeInternal(),r=n.getCoordinateN(0),o=null,s=null,a=e.iterator();a.hasNext();){var u=a.next(),l=u.getLinearRing(),c=l.getEnvelopeInternal();null!==o&&(s=o.getLinearRing().getEnvelopeInternal());var p=!1;c.contains(i)&&at.isPointInRing(r,l.getCoordinates())&&(p=!0),p&&(null===o||s.contains(c))&&(o=u)}return o},ke.prototype.findShell=function(t){for(var e=0,n=null,i=t.iterator();i.hasNext();){var r=i.next();r.isHole()||(n=r,e++)}return et.isTrue(e<=1,\"found two shells in MinimalEdgeRing list\"),n},ke.prototype.add=function(){if(1===arguments.length){var t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(2===arguments.length){var e=arguments[0],n=arguments[1];Ye.linkResultDirectedEdges(n);var i=this.buildMaximalEdgeRings(e),r=new Nt,o=this.buildMinimalEdgeRings(i,this._shellList,r);this.sortShellsAndHoles(o,this._shellList,r),this.placeFreeHoles(this._shellList,r)}},ke.prototype.interfaces_=function(){return[]},ke.prototype.getClass=function(){return ke};var je=function(){};je.prototype.getBounds=function(){},je.prototype.interfaces_=function(){return[]},je.prototype.getClass=function(){return je};var He=function(){this._bounds=null,this._item=null;var t=arguments[0],e=arguments[1];this._bounds=t,this._item=e};He.prototype.getItem=function(){return this._item},He.prototype.getBounds=function(){return this._bounds},He.prototype.interfaces_=function(){return[je,e]},He.prototype.getClass=function(){return He};var We=function(){this._size=null,this._items=null,this._size=0,this._items=new Nt,this._items.add(null)};We.prototype.poll=function(){if(this.isEmpty())return null;var t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t},We.prototype.size=function(){return this._size},We.prototype.reorder=function(t){for(var e=null,n=this._items.get(t);2*t<=this._size&&((e=2*t)!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)},We.prototype.clear=function(){this._size=0,this._items.clear()},We.prototype.isEmpty=function(){return 0===this._size},We.prototype.add=function(t){this._items.add(null),this._size+=1;var e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)},We.prototype.interfaces_=function(){return[]},We.prototype.getClass=function(){return We};var Ke=function(){};Ke.prototype.visitItem=function(t){},Ke.prototype.interfaces_=function(){return[]},Ke.prototype.getClass=function(){return Ke};var Je=function(){};Je.prototype.insert=function(t,e){},Je.prototype.remove=function(t,e){},Je.prototype.query=function(){},Je.prototype.interfaces_=function(){return[]},Je.prototype.getClass=function(){return Je};var Qe=function(){if(this._childBoundables=new Nt,this._bounds=null,this._level=null,0===arguments.length);else if(1===arguments.length){var t=arguments[0];this._level=t}},Ze={serialVersionUID:{configurable:!0}};Qe.prototype.getLevel=function(){return this._level},Qe.prototype.size=function(){return this._childBoundables.size()},Qe.prototype.getChildBoundables=function(){return this._childBoundables},Qe.prototype.addChildBoundable=function(t){et.isTrue(null===this._bounds),this._childBoundables.add(t)},Qe.prototype.isEmpty=function(){return this._childBoundables.isEmpty()},Qe.prototype.getBounds=function(){return null===this._bounds&&(this._bounds=this.computeBounds()),this._bounds},Qe.prototype.interfaces_=function(){return[je,e]},Qe.prototype.getClass=function(){return Qe},Ze.serialVersionUID.get=function(){return 0x5a1e55ec41369800},Object.defineProperties(Qe,Ze);var $e=function(){};$e.reverseOrder=function(){return{compare:function(t,e){return e.compareTo(t)}}},$e.min=function(t){return $e.sort(t),t.get(0)},$e.sort=function(t,e){var n=t.toArray();e?Gt.sort(n,e):Gt.sort(n);for(var i=t.iterator(),r=0,o=n.length;rtn.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,t,e),null):(this.expand(this._boundable2,this._boundable1,t,e),null);if(n)return this.expand(this._boundable1,this._boundable2,t,e),null;if(i)return this.expand(this._boundable2,this._boundable1,t,e),null;throw new m(\"neither boundable is composite\")},tn.prototype.isLeaves=function(){return!(tn.isComposite(this._boundable1)||tn.isComposite(this._boundable2))},tn.prototype.compareTo=function(t){var e=t;return this._distancee._distance?1:0},tn.prototype.expand=function(t,e,n,i){for(var r=t.getChildBoundables().iterator();r.hasNext();){var o=r.next(),s=new tn(o,e,this._itemDistance);s.getDistance()1,\"Node capacity must be greater than 1\"),this._nodeCapacity=n}},nn={IntersectsOp:{configurable:!0},serialVersionUID:{configurable:!0},DEFAULT_NODE_CAPACITY:{configurable:!0}};en.prototype.getNodeCapacity=function(){return this._nodeCapacity},en.prototype.lastNode=function(t){return t.get(t.size()-1)},en.prototype.size=function(){if(0===arguments.length)return this.isEmpty()?0:(this.build(),this.size(this._root));if(1===arguments.length){for(var t=0,e=arguments[0].getChildBoundables().iterator();e.hasNext();){var n=e.next();n instanceof Qe?t+=this.size(n):n instanceof He&&(t+=1)}return t}},en.prototype.removeItem=function(t,e){for(var n=null,i=t.getChildBoundables().iterator();i.hasNext();){var r=i.next();r instanceof He&&r.getItem()===e&&(n=r)}return null!==n&&(t.getChildBoundables().remove(n),!0)},en.prototype.itemsTree=function(){if(0===arguments.length){this.build();var t=this.itemsTree(this._root);return null===t?new Nt:t}if(1===arguments.length){for(var e=arguments[0],n=new Nt,i=e.getChildBoundables().iterator();i.hasNext();){var r=i.next();if(r instanceof Qe){var o=this.itemsTree(r);null!==o&&n.add(o)}else r instanceof He?n.add(r.getItem()):et.shouldNeverReachHere()}return n.size()<=0?null:n}},en.prototype.insert=function(t,e){et.isTrue(!this._built,\"Cannot insert items into an STR packed R-tree after it has been built.\"),this._itemBoundables.add(new He(t,e))},en.prototype.boundablesAtLevel=function(){if(1===arguments.length){var t=arguments[0],e=new Nt;return this.boundablesAtLevel(t,this._root,e),e}if(3===arguments.length){var n=arguments[0],i=arguments[1],r=arguments[2];if(et.isTrue(n>-2),i.getLevel()===n)return r.add(i),null;for(var o=i.getChildBoundables().iterator();o.hasNext();){var s=o.next();s instanceof Qe?this.boundablesAtLevel(n,s,r):(et.isTrue(s instanceof He),-1===n&&r.add(s))}return null}},en.prototype.query=function(){if(1===arguments.length){var t=arguments[0];this.build();var e=new Nt;return this.isEmpty()?e:(this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.query(t,this._root,e),e)}if(2===arguments.length){var n=arguments[0],i=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),n)&&this.query(n,this._root,i)}else if(3===arguments.length)if(T(arguments[2],Ke)&&arguments[0]instanceof Object&&arguments[1]instanceof Qe)for(var r=arguments[0],o=arguments[1],s=arguments[2],a=o.getChildBoundables(),u=0;ut&&(t=i)}}return t+1}},en.prototype.createParentBoundables=function(t,e){et.isTrue(!t.isEmpty());var n=new Nt;n.add(this.createNode(e));var i=new Nt(t);$e.sort(i,this.getComparator());for(var r=i.iterator();r.hasNext();){var o=r.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n},en.prototype.isEmpty=function(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()},en.prototype.interfaces_=function(){return[e]},en.prototype.getClass=function(){return en},en.compareDoubles=function(t,e){return t>e?1:t0);for(var n=new Nt,i=0;i0;){var p=c.poll(),h=p.getDistance();if(h>=u)break;p.isLeaves()?(u=h,l=p):p.expandToQueue(c,u)}return[l.getBoundable(0).getItem(),l.getBoundable(1).getItem()]}}else if(3===arguments.length){var f=arguments[0],g=arguments[1],d=arguments[2],y=new He(f,g),_=new tn(this.getRoot(),y,d);return this.nearestNeighbour(_)[0]}},n.prototype.interfaces_=function(){return[Je,e]},n.prototype.getClass=function(){return n},n.centreX=function(t){return n.avg(t.getMinX(),t.getMaxX())},n.avg=function(t,e){return(t+e)/2},n.centreY=function(t){return n.avg(t.getMinY(),t.getMaxY())},i.STRtreeNode.get=function(){return an},i.serialVersionUID.get=function(){return 0x39920f7d5f261e0},i.xComparator.get=function(){return{interfaces_:function(){return[N]},compare:function(e,i){return t.compareDoubles(n.centreX(e.getBounds()),n.centreX(i.getBounds()))}}},i.yComparator.get=function(){return{interfaces_:function(){return[N]},compare:function(e,i){return t.compareDoubles(n.centreY(e.getBounds()),n.centreY(i.getBounds()))}}},i.intersectsOp.get=function(){return{interfaces_:function(){return[t.IntersectsOp]},intersects:function(t,e){return t.intersects(e)}}},i.DEFAULT_NODE_CAPACITY.get=function(){return 10},Object.defineProperties(n,i),n}(en),an=function(t){function e(){var e=arguments[0];t.call(this,e)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.computeBounds=function(){for(var t=null,e=this.getChildBoundables().iterator();e.hasNext();){var n=e.next();null===t?t=new j(n.getBounds()):t.expandToInclude(n.getBounds())}return t},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(Qe),un=function(){};un.prototype.interfaces_=function(){return[]},un.prototype.getClass=function(){return un},un.relativeSign=function(t,e){return te?1:0},un.compare=function(t,e,n){if(e.equals2D(n))return 0;var i=un.relativeSign(e.x,n.x),r=un.relativeSign(e.y,n.y);switch(t){case 0:return un.compareValue(i,r);case 1:return un.compareValue(r,i);case 2:return un.compareValue(r,-i);case 3:return un.compareValue(-i,r);case 4:return un.compareValue(-i,-r);case 5:return un.compareValue(-r,-i);case 6:return un.compareValue(-r,i);case 7:return un.compareValue(i,-r)}return et.shouldNeverReachHere(\"invalid octant value\"),0},un.compareValue=function(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0};var ln=function(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;var t=arguments[0],e=arguments[1],n=arguments[2],i=arguments[3];this._segString=t,this.coord=new C(e),this.segmentIndex=n,this._segmentOctant=i,this._isInterior=!e.equals2D(t.getCoordinate(n))};ln.prototype.getCoordinate=function(){return this.coord},ln.prototype.print=function(t){t.print(this.coord),t.print(\" seg # = \"+this.segmentIndex)},ln.prototype.compareTo=function(t){var e=t;return this.segmentIndexe.segmentIndex?1:this.coord.equals2D(e.coord)?0:un.compare(this._segmentOctant,this.coord,e.coord)},ln.prototype.isEndPoint=function(t){return 0===this.segmentIndex&&!this._isInterior||this.segmentIndex===t},ln.prototype.isInterior=function(){return this._isInterior},ln.prototype.interfaces_=function(){return[E]},ln.prototype.getClass=function(){return ln};var cn=function(){this._nodeMap=new p,this._edge=null;var t=arguments[0];this._edge=t};cn.prototype.getSplitCoordinates=function(){var t=new St;this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var i=e.next();this.addEdgeCoordinates(n,i,t),n=i}return t.toCoordinateArray()},cn.prototype.addCollapsedNodes=function(){var t=new Nt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(var e=t.iterator();e.hasNext();){var n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}},cn.prototype.print=function(t){t.println(\"Intersections:\");for(var e=this.iterator();e.hasNext();){e.next().print(t)}},cn.prototype.findCollapsesFromExistingVertices=function(t){for(var e=0;e=0?e>=0?n>=i?0:1:n>=i?7:6:e>=0?n>=i?3:2:n>=i?4:5}if(arguments[0]instanceof C&&arguments[1]instanceof C){var r=arguments[0],o=arguments[1],s=o.x-r.x,a=o.y-r.y;if(0===s&&0===a)throw new m(\"Cannot compute the octant for two identical points \"+r);return pn.octant(s,a)}};var hn=function(){};hn.prototype.getCoordinates=function(){},hn.prototype.size=function(){},hn.prototype.getCoordinate=function(t){},hn.prototype.isClosed=function(){},hn.prototype.setData=function(t){},hn.prototype.getData=function(){},hn.prototype.interfaces_=function(){return[]},hn.prototype.getClass=function(){return hn};var fn=function(){};fn.prototype.addIntersection=function(t,e){},fn.prototype.interfaces_=function(){return[hn]},fn.prototype.getClass=function(){return fn};var gn=function(){this._nodeList=new cn(this),this._pts=null,this._data=null;var t=arguments[0],e=arguments[1];this._pts=t,this._data=e};gn.prototype.getCoordinates=function(){return this._pts},gn.prototype.size=function(){return this._pts.length},gn.prototype.getCoordinate=function(t){return this._pts[t]},gn.prototype.isClosed=function(){return this._pts[0].equals(this._pts[this._pts.length-1])},gn.prototype.getSegmentOctant=function(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))},gn.prototype.setData=function(t){this._data=t},gn.prototype.safeOctant=function(t,e){return t.equals2D(e)?0:pn.octant(t,e)},gn.prototype.getData=function(){return this._data},gn.prototype.addIntersection=function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(4===arguments.length){var n=arguments[0],i=arguments[1],r=arguments[3],o=new C(n.getIntersection(r));this.addIntersection(o,i)}},gn.prototype.toString=function(){return Z.toLineString(new ue(this._pts))},gn.prototype.getNodeList=function(){return this._nodeList},gn.prototype.addIntersectionNode=function(t,e){var n=e,i=n+1;if(i=0&&n>=0?Math.max(e,n):e<=0&&n<=0?Math.max(e,n):0}if(arguments[0]instanceof C){var i=arguments[0];return at.orientationIndex(this.p0,this.p1,i)}},dn.prototype.toGeometry=function(t){return t.createLineString([this.p0,this.p1])},dn.prototype.isVertical=function(){return this.p0.x===this.p1.x},dn.prototype.equals=function(t){if(!(t instanceof dn))return!1;var e=t;return this.p0.equals(e.p0)&&this.p1.equals(e.p1)},dn.prototype.intersection=function(t){var e=new rt;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null},dn.prototype.project=function(){if(arguments[0]instanceof C){var t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new C(t);var e=this.projectionFactor(t),n=new C;return n.x=this.p0.x+e*(this.p1.x-this.p0.x),n.y=this.p0.y+e*(this.p1.y-this.p0.y),n}if(arguments[0]instanceof dn){var i=arguments[0],r=this.projectionFactor(i.p0),o=this.projectionFactor(i.p1);if(r>=1&&o>=1)return null;if(r<=0&&o<=0)return null;var s=this.project(i.p0);r<0&&(s=this.p0),r>1&&(s=this.p1);var a=this.project(i.p1);return o<0&&(a=this.p0),o>1&&(a=this.p1),new dn(s,a)}},dn.prototype.normalize=function(){this.p1.compareTo(this.p0)<0&&this.reverse()},dn.prototype.angle=function(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)},dn.prototype.getCoordinate=function(t){return 0===t?this.p0:this.p1},dn.prototype.distancePerpendicular=function(t){return at.distancePointLinePerpendicular(t,this.p0,this.p1)},dn.prototype.minY=function(){return Math.min(this.p0.y,this.p1.y)},dn.prototype.midPoint=function(){return dn.midPoint(this.p0,this.p1)},dn.prototype.projectionFactor=function(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;var e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,i=e*e+n*n;if(i<=0)return v.NaN;return((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/i},dn.prototype.closestPoints=function(t){var e=this.intersection(t);if(null!==e)return[e,e];var n=new Array(2).fill(null),i=v.MAX_VALUE,r=null,o=this.closestPoint(t.p0);i=o.distance(t.p0),n[0]=o,n[1]=t.p0;var s=this.closestPoint(t.p1);(r=s.distance(t.p1))0&&e<1)return this.project(t);return this.p0.distance(t)1||v.isNaN(e))&&(e=1),e},dn.prototype.toString=function(){return\"LINESTRING( \"+this.p0.x+\" \"+this.p0.y+\", \"+this.p1.x+\" \"+this.p1.y+\")\"},dn.prototype.isHorizontal=function(){return this.p0.y===this.p1.y},dn.prototype.distance=function(){if(arguments[0]instanceof dn){var t=arguments[0];return at.distanceLineLine(this.p0,this.p1,t.p0,t.p1)}if(arguments[0]instanceof C){var e=arguments[0];return at.distancePointLine(e,this.p0,this.p1)}},dn.prototype.pointAlong=function(t){var e=new C;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e},dn.prototype.hashCode=function(){var t=v.doubleToLongBits(this.p0.x);t^=31*v.doubleToLongBits(this.p0.y);var e=Math.trunc(t)^Math.trunc(t>>32),n=v.doubleToLongBits(this.p1.x);n^=31*v.doubleToLongBits(this.p1.y);return e^(Math.trunc(n)^Math.trunc(n>>32))},dn.prototype.interfaces_=function(){return[E,e]},dn.prototype.getClass=function(){return dn},dn.midPoint=function(t,e){return new C((t.x+e.x)/2,(t.y+e.y)/2)},yn.serialVersionUID.get=function(){return 0x2d2172135f411c00},Object.defineProperties(dn,yn);var _n=function(){this.tempEnv1=new j,this.tempEnv2=new j,this._overlapSeg1=new dn,this._overlapSeg2=new dn};_n.prototype.overlap=function(){if(2===arguments.length);else if(4===arguments.length){var t=arguments[0],e=arguments[1],n=arguments[2],i=arguments[3];t.getLineSegment(e,this._overlapSeg1),n.getLineSegment(i,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}},_n.prototype.interfaces_=function(){return[]},_n.prototype.getClass=function(){return _n};var mn=function(){this._pts=null,this._start=null,this._end=null,this._env=null,this._context=null,this._id=null;var t=arguments[0],e=arguments[1],n=arguments[2],i=arguments[3];this._pts=t,this._start=e,this._end=n,this._context=i};mn.prototype.getLineSegment=function(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]},mn.prototype.computeSelect=function(t,e,n,i){var r=this._pts[e],o=this._pts[n];if(i.tempEnv1.init(r,o),n-e==1)return i.select(this,e),null;if(!t.intersects(i.tempEnv1))return null;var s=Math.trunc((e+n)/2);e=t.length-1)return t.length-1;for(var i=Be.quadrant(t[n],t[n+1]),r=e+1;rn.getId()&&(n.computeOverlaps(r,t),this._nOverlaps++),this._segInt.isDone())return null}},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},n.SegmentOverlapAction.get=function(){return Nn},Object.defineProperties(e,n),e}(En),Nn=function(t){function e(){t.call(this),this._si=null;var e=arguments[0];this._si=e}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.overlap=function(){if(4!==arguments.length)return t.prototype.overlap.apply(this,arguments);var e=arguments[0],n=arguments[1],i=arguments[2],r=arguments[3],o=e.getContext(),s=i.getContext();this._si.processIntersections(o,n,s,r)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(_n),Cn=function t(){if(this._quadrantSegments=t.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=t.CAP_ROUND,this._joinStyle=t.JOIN_ROUND,this._mitreLimit=t.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=t.DEFAULT_SIMPLIFY_FACTOR,0===arguments.length);else if(1===arguments.length){var e=arguments[0];this.setQuadrantSegments(e)}else if(2===arguments.length){var n=arguments[0],i=arguments[1];this.setQuadrantSegments(n),this.setEndCapStyle(i)}else if(4===arguments.length){var r=arguments[0],o=arguments[1],s=arguments[2],a=arguments[3];this.setQuadrantSegments(r),this.setEndCapStyle(o),this.setJoinStyle(s),this.setMitreLimit(a)}},Sn={CAP_ROUND:{configurable:!0},CAP_FLAT:{configurable:!0},CAP_SQUARE:{configurable:!0},JOIN_ROUND:{configurable:!0},JOIN_MITRE:{configurable:!0},JOIN_BEVEL:{configurable:!0},DEFAULT_QUADRANT_SEGMENTS:{configurable:!0},DEFAULT_MITRE_LIMIT:{configurable:!0},DEFAULT_SIMPLIFY_FACTOR:{configurable:!0}};Cn.prototype.getEndCapStyle=function(){return this._endCapStyle},Cn.prototype.isSingleSided=function(){return this._isSingleSided},Cn.prototype.setQuadrantSegments=function(t){this._quadrantSegments=t,0===this._quadrantSegments&&(this._joinStyle=Cn.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=Cn.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==Cn.JOIN_ROUND&&(this._quadrantSegments=Cn.DEFAULT_QUADRANT_SEGMENTS)},Cn.prototype.getJoinStyle=function(){return this._joinStyle},Cn.prototype.setJoinStyle=function(t){this._joinStyle=t},Cn.prototype.setSimplifyFactor=function(t){this._simplifyFactor=t<0?0:t},Cn.prototype.getSimplifyFactor=function(){return this._simplifyFactor},Cn.prototype.getQuadrantSegments=function(){return this._quadrantSegments},Cn.prototype.setEndCapStyle=function(t){this._endCapStyle=t},Cn.prototype.getMitreLimit=function(){return this._mitreLimit},Cn.prototype.setMitreLimit=function(t){this._mitreLimit=t},Cn.prototype.setSingleSided=function(t){this._isSingleSided=t},Cn.prototype.interfaces_=function(){return[]},Cn.prototype.getClass=function(){return Cn},Cn.bufferDistanceError=function(t){var e=Math.PI/2/t;return 1-Math.cos(e/2)},Sn.CAP_ROUND.get=function(){return 1},Sn.CAP_FLAT.get=function(){return 2},Sn.CAP_SQUARE.get=function(){return 3},Sn.JOIN_ROUND.get=function(){return 1},Sn.JOIN_MITRE.get=function(){return 2},Sn.JOIN_BEVEL.get=function(){return 3},Sn.DEFAULT_QUADRANT_SEGMENTS.get=function(){return 8},Sn.DEFAULT_MITRE_LIMIT.get=function(){return 5},Sn.DEFAULT_SIMPLIFY_FACTOR.get=function(){return.01},Object.defineProperties(Cn,Sn);var Ln=function(t){this._distanceTol=null,this._isDeleted=null,this._angleOrientation=at.COUNTERCLOCKWISE,this._inputLine=t||null},bn={INIT:{configurable:!0},DELETE:{configurable:!0},KEEP:{configurable:!0},NUM_PTS_TO_CHECK:{configurable:!0}};Ln.prototype.isDeletable=function(t,e,n,i){var r=this._inputLine[t],o=this._inputLine[e],s=this._inputLine[n];return!!this.isConcave(r,o,s)&&(!!this.isShallow(r,o,s,i)&&this.isShallowSampled(r,o,t,n,i))},Ln.prototype.deleteShallowConcavities=function(){for(var t=1,e=this.findNextNonDeletedIndex(t),n=this.findNextNonDeletedIndex(e),i=!1;n=0;i--)this.addPt(t[i])},wn.prototype.isRedundant=function(t){if(this._ptList.size()<1)return!1;var e=this._ptList.get(this._ptList.size()-1);return t.distance(e)Math.PI;)t-=Tn.PI_TIMES_2;for(;t<=-Math.PI;)t+=Tn.PI_TIMES_2;return t},Tn.angle=function(){if(1===arguments.length){var t=arguments[0];return Math.atan2(t.y,t.x)}if(2===arguments.length){var e=arguments[0],n=arguments[1],i=n.x-e.x,r=n.y-e.y;return Math.atan2(r,i)}},Tn.isAcute=function(t,e,n){var i=t.x-e.x,r=t.y-e.y;return i*(n.x-e.x)+r*(n.y-e.y)>0},Tn.isObtuse=function(t,e,n){var i=t.x-e.x,r=t.y-e.y;return i*(n.x-e.x)+r*(n.y-e.y)<0},Tn.interiorAngle=function(t,e,n){var i=Tn.angle(e,t),r=Tn.angle(e,n);return Math.abs(r-i)},Tn.normalizePositive=function(t){if(t<0){for(;t<0;)t+=Tn.PI_TIMES_2;t>=Tn.PI_TIMES_2&&(t=0)}else{for(;t>=Tn.PI_TIMES_2;)t-=Tn.PI_TIMES_2;t<0&&(t=0)}return t},Tn.angleBetween=function(t,e,n){var i=Tn.angle(e,t),r=Tn.angle(e,n);return Tn.diff(i,r)},Tn.diff=function(t,e){var n=null;return(n=tMath.PI&&(n=2*Math.PI-n),n},Tn.toRadians=function(t){return t*Math.PI/180},Tn.getTurn=function(t,e){var n=Math.sin(e-t);return n>0?Tn.COUNTERCLOCKWISE:n<0?Tn.CLOCKWISE:Tn.NONE},Tn.angleBetweenOriented=function(t,e,n){var i=Tn.angle(e,t),r=Tn.angle(e,n)-i;return r<=-Math.PI?r+Tn.PI_TIMES_2:r>Math.PI?r-Tn.PI_TIMES_2:r},Rn.PI_TIMES_2.get=function(){return 2*Math.PI},Rn.PI_OVER_2.get=function(){return Math.PI/2},Rn.PI_OVER_4.get=function(){return Math.PI/4},Rn.COUNTERCLOCKWISE.get=function(){return at.COUNTERCLOCKWISE},Rn.CLOCKWISE.get=function(){return at.CLOCKWISE},Rn.NONE.get=function(){return at.COLLINEAR},Object.defineProperties(Tn,Rn);var Pn=function t(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new dn,this._seg1=new dn,this._offset0=new dn,this._offset1=new dn,this._side=0,this._hasNarrowConcaveAngle=!1;var e=arguments[0],n=arguments[1],i=arguments[2];this._precisionModel=e,this._bufParams=n,this._li=new rt,this._filletAngleQuantum=Math.PI/2/n.getQuadrantSegments(),n.getQuadrantSegments()>=8&&n.getJoinStyle()===Cn.JOIN_ROUND&&(this._closingSegLengthFactor=t.MAX_CLOSING_SEG_LEN_FACTOR),this.init(i)},Dn={OFFSET_SEGMENT_SEPARATION_FACTOR:{configurable:!0},INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR:{configurable:!0},CURVE_VERTEX_SNAP_DISTANCE_FACTOR:{configurable:!0},MAX_CLOSING_SEG_LEN_FACTOR:{configurable:!0}};Pn.prototype.addNextSegment=function(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;var n=at.computeOrientation(this._s0,this._s1,this._s2),i=n===at.CLOCKWISE&&this._side===Se.LEFT||n===at.COUNTERCLOCKWISE&&this._side===Se.RIGHT;0===n?this.addCollinear(e):i?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)},Pn.prototype.addLineEndCap=function(t,e){var n=new dn(t,e),i=new dn;this.computeOffsetSegment(n,Se.LEFT,this._distance,i);var r=new dn;this.computeOffsetSegment(n,Se.RIGHT,this._distance,r);var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o);switch(this._bufParams.getEndCapStyle()){case Cn.CAP_ROUND:this._segList.addPt(i.p1),this.addFilletArc(e,a+Math.PI/2,a-Math.PI/2,at.CLOCKWISE,this._distance),this._segList.addPt(r.p1);break;case Cn.CAP_FLAT:this._segList.addPt(i.p1),this._segList.addPt(r.p1);break;case Cn.CAP_SQUARE:var u=new C;u.x=Math.abs(this._distance)*Math.cos(a),u.y=Math.abs(this._distance)*Math.sin(a);var l=new C(i.p1.x+u.x,i.p1.y+u.y),c=new C(r.p1.x+u.x,r.p1.y+u.y);this._segList.addPt(l),this._segList.addPt(c)}},Pn.prototype.getCoordinates=function(){return this._segList.getCoordinates()},Pn.prototype.addMitreJoin=function(t,e,n,i){var r=!0,o=null;try{o=k.intersection(e.p0,e.p1,n.p0,n.p1);(i<=0?1:o.distance(t)/Math.abs(i))>this._bufParams.getMitreLimit()&&(r=!1)}catch(t){if(!(t instanceof X))throw t;o=new C(0,0),r=!1}r?this._segList.addPt(o):this.addLimitedMitreJoin(e,n,i,this._bufParams.getMitreLimit())},Pn.prototype.addFilletCorner=function(t,e,n,i,r){var o=e.x-t.x,s=e.y-t.y,a=Math.atan2(s,o),u=n.x-t.x,l=n.y-t.y,c=Math.atan2(l,u);i===at.CLOCKWISE?a<=c&&(a+=2*Math.PI):a>=c&&(a-=2*Math.PI),this._segList.addPt(e),this.addFilletArc(t,a,c,i,r),this._segList.addPt(n)},Pn.prototype.addOutsideTurn=function(t,e){if(this._offset0.p1.distance(this._offset1.p0)0){var n=new C((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(n);var i=new C((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(i)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}},Pn.prototype.createCircle=function(t){var e=new C(t.x+this._distance,t.y);this._segList.addPt(e),this.addFilletArc(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()},Pn.prototype.addBevelJoin=function(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)},Pn.prototype.init=function(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new wn,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*Pn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)},Pn.prototype.addCollinear=function(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2);this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===Cn.JOIN_BEVEL||this._bufParams.getJoinStyle()===Cn.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addFilletCorner(this._s1,this._offset0.p1,this._offset1.p0,at.CLOCKWISE,this._distance))},Pn.prototype.closeRing=function(){this._segList.closeRing()},Pn.prototype.hasNarrowConcaveAngle=function(){return this._hasNarrowConcaveAngle},Pn.prototype.interfaces_=function(){return[]},Pn.prototype.getClass=function(){return Pn},Dn.OFFSET_SEGMENT_SEPARATION_FACTOR.get=function(){return.001},Dn.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR.get=function(){return.001},Dn.CURVE_VERTEX_SNAP_DISTANCE_FACTOR.get=function(){return 1e-6},Dn.MAX_CLOSING_SEG_LEN_FACTOR.get=function(){return 80},Object.defineProperties(Pn,Dn);var Mn=function(){this._distance=0,this._precisionModel=null,this._bufParams=null;var t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e};Mn.prototype.getOffsetCurve=function(t,e){if(this._distance=e,0===e)return null;var n=e<0,i=Math.abs(e),r=this.getSegGen(i);t.length<=1?this.computePointCurve(t[0],r):this.computeOffsetCurve(t,n,r);var o=r.getCoordinates();return n&&Lt.reverse(o),o},Mn.prototype.computeSingleSidedBufferCurve=function(t,e,n){var i=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);var r=Ln.simplify(t,-i),o=r.length-1;n.initSideSegments(r[o],r[o-1],Se.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(r[s],!0)}else{n.addSegments(t,!1);var a=Ln.simplify(t,i),u=a.length-1;n.initSideSegments(a[0],a[1],Se.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment(),n.closeRing()},Mn.prototype.computeRingBufferCurve=function(t,e,n){var i=this.simplifyTolerance(this._distance);e===Se.RIGHT&&(i=-i);var r=Ln.simplify(t,i),o=r.length-1;n.initSideSegments(r[o-1],r[0],e);for(var s=1;s<=o;s++){var a=1!==s;n.addNextSegment(r[s],a)}n.closeRing()},Mn.prototype.computeLineBufferCurve=function(t,e){var n=this.simplifyTolerance(this._distance),i=Ln.simplify(t,n),r=i.length-1;e.initSideSegments(i[0],i[1],Se.LEFT);for(var o=2;o<=r;o++)e.addNextSegment(i[o],!0);e.addLastSegment(),e.addLineEndCap(i[r-1],i[r]);var s=Ln.simplify(t,-n),a=s.length-1;e.initSideSegments(s[a],s[a-1],Se.LEFT);for(var u=a-2;u>=0;u--)e.addNextSegment(s[u],!0);e.addLastSegment(),e.addLineEndCap(s[1],s[0]),e.closeRing()},Mn.prototype.computePointCurve=function(t,e){switch(this._bufParams.getEndCapStyle()){case Cn.CAP_ROUND:e.createCircle(t);break;case Cn.CAP_SQUARE:e.createSquare(t)}},Mn.prototype.getLineCurve=function(t,e){if(this._distance=e,e<0&&!this._bufParams.isSingleSided())return null;if(0===e)return null;var n=Math.abs(e),i=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],i);else if(this._bufParams.isSingleSided()){var r=e<0;this.computeSingleSidedBufferCurve(t,r,i)}else this.computeLineBufferCurve(t,i);return i.getCoordinates()},Mn.prototype.getBufferParameters=function(){return this._bufParams},Mn.prototype.simplifyTolerance=function(t){return t*this._bufParams.getSimplifyFactor()},Mn.prototype.getRingCurve=function(t,e,n){if(this._distance=n,t.length<=2)return this.getLineCurve(t,n);if(0===n)return Mn.copyCoordinates(t);var i=this.getSegGen(n);return this.computeRingBufferCurve(t,e,i),i.getCoordinates()},Mn.prototype.computeOffsetCurve=function(t,e,n){var i=this.simplifyTolerance(this._distance);if(e){var r=Ln.simplify(t,-i),o=r.length-1;n.initSideSegments(r[o],r[o-1],Se.LEFT),n.addFirstSegment();for(var s=o-2;s>=0;s--)n.addNextSegment(r[s],!0)}else{var a=Ln.simplify(t,i),u=a.length-1;n.initSideSegments(a[0],a[1],Se.LEFT),n.addFirstSegment();for(var l=2;l<=u;l++)n.addNextSegment(a[l],!0)}n.addLastSegment()},Mn.prototype.getSegGen=function(t){return new Pn(this._precisionModel,this._bufParams,t)},Mn.prototype.interfaces_=function(){return[]},Mn.prototype.getClass=function(){return Mn},Mn.copyCoordinates=function(t){for(var e=new Array(t.length).fill(null),n=0;nr.getMaxY()||this.findStabbedSegments(t,i.getDirectedEdges(),e)}return e}if(3===arguments.length)if(T(arguments[2],xt)&&arguments[0]instanceof C&&arguments[1]instanceof ze)for(var o=arguments[0],s=arguments[1],a=arguments[2],u=s.getEdge().getCoordinates(),l=0;lthis._seg.p1.y&&this._seg.reverse();if(!(Math.max(this._seg.p0.x,this._seg.p1.x)this._seg.p1.y||at.computeOrientation(this._seg.p0,this._seg.p1,o)===at.RIGHT)){var c=s.getDepth(Se.LEFT);this._seg.p0.equals(u[l])||(c=s.getDepth(Se.RIGHT));var p=new Gn(this._seg,c);a.add(p)}}else if(T(arguments[2],xt)&&arguments[0]instanceof C&&T(arguments[1],xt))for(var h=arguments[0],f=arguments[1],g=arguments[2],d=f.iterator();d.hasNext();){var y=d.next();y.isForward()&&this.findStabbedSegments(h,y,g)}},An.prototype.getDepth=function(t){var e=this.findStabbedSegments(t);if(0===e.size())return 0;return $e.min(e)._leftDepth},An.prototype.interfaces_=function(){return[]},An.prototype.getClass=function(){return An},Fn.DepthSegment.get=function(){return Gn},Object.defineProperties(An,Fn);var Gn=function(){this._upwardSeg=null,this._leftDepth=null;var t=arguments[0],e=arguments[1];this._upwardSeg=new dn(t),this._leftDepth=e};Gn.prototype.compareTo=function(t){var e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;var n=this._upwardSeg.orientationIndex(e._upwardSeg);return 0!==n?n:0!=(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg))?n:this._upwardSeg.compareTo(e._upwardSeg)},Gn.prototype.compareX=function(t,e){var n=t.p0.compareTo(e.p0);return 0!==n?n:t.p1.compareTo(e.p1)},Gn.prototype.toString=function(){return this._upwardSeg.toString()},Gn.prototype.interfaces_=function(){return[E]},Gn.prototype.getClass=function(){return Gn};var qn=function(t,e,n){this.p0=t||null,this.p1=e||null,this.p2=n||null};qn.prototype.area=function(){return qn.area(this.p0,this.p1,this.p2)},qn.prototype.signedArea=function(){return qn.signedArea(this.p0,this.p1,this.p2)},qn.prototype.interpolateZ=function(t){if(null===t)throw new m(\"Supplied point is null.\");return qn.interpolateZ(t,this.p0,this.p1,this.p2)},qn.prototype.longestSideLength=function(){return qn.longestSideLength(this.p0,this.p1,this.p2)},qn.prototype.isAcute=function(){return qn.isAcute(this.p0,this.p1,this.p2)},qn.prototype.circumcentre=function(){return qn.circumcentre(this.p0,this.p1,this.p2)},qn.prototype.area3D=function(){return qn.area3D(this.p0,this.p1,this.p2)},qn.prototype.centroid=function(){return qn.centroid(this.p0,this.p1,this.p2)},qn.prototype.inCentre=function(){return qn.inCentre(this.p0,this.p1,this.p2)},qn.prototype.interfaces_=function(){return[]},qn.prototype.getClass=function(){return qn},qn.area=function(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)},qn.signedArea=function(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2},qn.det=function(t,e,n,i){return t*i-e*n},qn.interpolateZ=function(t,e,n,i){var r=e.x,o=e.y,s=n.x-r,a=i.x-r,u=n.y-o,l=i.y-o,c=s*l-a*u,p=t.x-r,h=t.y-o,f=(l*p-a*h)/c,g=(-u*p+s*h)/c;return e.z+f*(n.z-e.z)+g*(i.z-e.z)},qn.longestSideLength=function(t,e,n){var i=t.distance(e),r=e.distance(n),o=n.distance(t),s=i;return r>s&&(s=r),o>s&&(s=o),s},qn.isAcute=function(t,e,n){return!!Tn.isAcute(t,e,n)&&(!!Tn.isAcute(e,n,t)&&!!Tn.isAcute(n,t,e))},qn.circumcentre=function(t,e,n){var i=n.x,r=n.y,o=t.x-i,s=t.y-r,a=e.x-i,u=e.y-r,l=2*qn.det(o,s,a,u),c=qn.det(s,o*o+s*s,u,a*a+u*u),p=qn.det(o,o*o+s*s,a,a*a+u*u);return new C(i-c/l,r+p/l)},qn.perpendicularBisector=function(t,e){var n=e.x-t.x,i=e.y-t.y,r=new k(t.x+n/2,t.y+i/2,1),o=new k(t.x-i+n/2,t.y+n+i/2,1);return new k(r,o)},qn.angleBisector=function(t,e,n){var i=e.distance(t),r=i/(i+e.distance(n)),o=n.x-t.x,s=n.y-t.y;return new C(t.x+r*o,t.y+r*s)},qn.area3D=function(t,e,n){var i=e.x-t.x,r=e.y-t.y,o=e.z-t.z,s=n.x-t.x,a=n.y-t.y,u=n.z-t.z,l=r*u-o*a,c=o*s-i*u,p=i*a-r*s,h=l*l+c*c+p*p,f=Math.sqrt(h)/2;return f},qn.centroid=function(t,e,n){var i=(t.x+e.x+n.x)/3,r=(t.y+e.y+n.y)/3;return new C(i,r)},qn.inCentre=function(t,e,n){var i=e.distance(n),r=t.distance(n),o=t.distance(e),s=i+r+o,a=(i*t.x+r*e.x+o*n.x)/s,u=(i*t.y+r*e.y+o*n.y)/s;return new C(a,u)};var Bn=function(){this._inputGeom=null,this._distance=null,this._curveBuilder=null,this._curveList=new Nt;var t=arguments[0],e=arguments[1],n=arguments[2];this._inputGeom=t,this._distance=e,this._curveBuilder=n};Bn.prototype.addPoint=function(t){if(this._distance<=0)return null;var e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,w.EXTERIOR,w.INTERIOR)},Bn.prototype.addPolygon=function(t){var e=this._distance,n=Se.LEFT;this._distance<0&&(e=-this._distance,n=Se.RIGHT);var i=t.getExteriorRing(),r=Lt.removeRepeatedPoints(i.getCoordinates());if(this._distance<0&&this.isErodedCompletely(i,this._distance))return null;if(this._distance<=0&&r.length<3)return null;this.addPolygonRing(r,e,n,w.EXTERIOR,w.INTERIOR);for(var o=0;o0&&this.isErodedCompletely(s,-this._distance)||this.addPolygonRing(a,e,Se.opposite(n),w.INTERIOR,w.EXTERIOR)}},Bn.prototype.isTriangleErodedCompletely=function(t,e){var n=new qn(t[0],t[1],t[2]),i=n.inCentre();return at.distancePointLine(i,n.p0,n.p1)=ee.MINIMUM_VALID_SIZE&&at.isCCW(t)&&(o=r,s=i,n=Se.opposite(n));var a=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(a,o,s)},Bn.prototype.add=function(t){if(t.isEmpty())return null;t instanceof $t?this.addPolygon(t):t instanceof Kt?this.addLineString(t):t instanceof Qt?this.addPoint(t):t instanceof te?this.addCollection(t):t instanceof Xt?this.addCollection(t):t instanceof ne?this.addCollection(t):t instanceof zt&&this.addCollection(t)},Bn.prototype.isErodedCompletely=function(t,e){var n=t.getCoordinates();if(n.length<4)return e<0;if(4===n.length)return this.isTriangleErodedCompletely(n,e);var i=t.getEnvelopeInternal(),r=Math.min(i.getHeight(),i.getWidth());return e<0&&2*Math.abs(e)>r},Bn.prototype.addCollection=function(t){for(var e=0;e=this._max)throw new i;var t=this._parent.getGeometryN(this._index++);return t instanceof zt?(this._subcollectionIterator=new Un(t),this._subcollectionIterator.next()):t},Un.prototype.remove=function(){throw new Error(this.getClass().getName())},Un.prototype.hasNext=function(){if(this._atStart)return!0;if(null!==this._subcollectionIterator){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)},Un.prototype.interfaces_=function(){return[Et]},Un.prototype.getClass=function(){return Un},Un.isAtomic=function(t){return!(t instanceof zt)};var zn=function(){this._geom=null;var t=arguments[0];this._geom=t};zn.prototype.locate=function(t){return zn.locate(t,this._geom)},zn.prototype.interfaces_=function(){return[Vn]},zn.prototype.getClass=function(){return zn},zn.isPointInRing=function(t,e){return!!e.getEnvelopeInternal().intersects(t)&&at.isPointInRing(t,e.getCoordinates())},zn.containsPointInPolygon=function(t,e){if(e.isEmpty())return!1;var n=e.getExteriorRing();if(!zn.isPointInRing(t,n))return!1;for(var i=0;i=0;n--){var i=this._edgeList.get(n),r=i.getSym();null===e&&(e=r),null!==t&&r.setNext(t),t=i}e.setNext(t)},e.prototype.computeDepths=function(){if(1===arguments.length){var t=arguments[0],e=this.findIndex(t),n=t.getDepth(Se.LEFT),i=t.getDepth(Se.RIGHT),r=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,r)!==i)throw new we(\"depth mismatch at \"+t.getCoordinate())}else if(3===arguments.length){for(var o=arguments[0],s=arguments[1],a=arguments[2],u=o;u=0;r--){var o=this._resultAreaEdgeList.get(r),s=o.getSym();switch(null===e&&o.getEdgeRing()===t&&(e=o),i){case this._SCANNING_FOR_INCOMING:if(s.getEdgeRing()!==t)continue;n=s,i=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),i=this._SCANNING_FOR_INCOMING}}i===this._LINKING_TO_OUTGOING&&(et.isTrue(null!==e,\"found null for first outgoing dirEdge\"),et.isTrue(e.getEdgeRing()===t,\"unable to link last incoming dirEdge\"),n.setNextMin(e))},e.prototype.getOutgoingDegree=function(){if(0===arguments.length){for(var t=0,e=this.iterator();e.hasNext();){e.next().isInResult()&&t++}return t}if(1===arguments.length){for(var n=arguments[0],i=0,r=this.iterator();r.hasNext();){r.next().getEdgeRing()===n&&i++}return i}},e.prototype.getLabel=function(){return this._label},e.prototype.findCoveredLineEdges=function(){for(var t=w.NONE,e=this.iterator();e.hasNext();){var n=e.next(),i=n.getSym();if(!n.isLineEdge()){if(n.isInResult()){t=w.INTERIOR;break}if(i.isInResult()){t=w.EXTERIOR;break}}}if(t===w.NONE)return null;for(var r=t,o=this.iterator();o.hasNext();){var s=o.next(),a=s.getSym();s.isLineEdge()?s.getEdge().setCovered(r===w.INTERIOR):(s.isInResult()&&(r=w.EXTERIOR),a.isInResult()&&(r=w.INTERIOR))}},e.prototype.computeLabelling=function(e){t.prototype.computeLabelling.call(this,e),this._label=new Pe(w.NONE);for(var n=this.iterator();n.hasNext();)for(var i=n.next().getEdge().getLabel(),r=0;r<2;r++){var o=i.getLocation(r);o!==w.INTERIOR&&o!==w.BOUNDARY||this._label.setLocation(r,w.INTERIOR)}},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(Xn),kn=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createNode=function(t){return new Ge(t,new Yn)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(Xe),jn=function t(){this._pts=null,this._orientation=null;var e=arguments[0];this._pts=e,this._orientation=t.orientation(e)};jn.prototype.compareTo=function(t){var e=t;return jn.compareOriented(this._pts,this._orientation,e._pts,e._orientation)},jn.prototype.interfaces_=function(){return[E]},jn.prototype.getClass=function(){return jn},jn.orientation=function(t){return 1===Lt.increasingDirection(t)},jn.compareOriented=function(t,e,n,i){for(var r=e?1:-1,o=i?1:-1,s=e?t.length:-1,a=i?n.length:-1,u=e?0:t.length-1,l=i?0:n.length-1;;){var c=t[u].compareTo(n[l]);if(0!==c)return c;var p=(u+=r)===s,h=(l+=o)===a;if(p&&!h)return-1;if(!p&&h)return 1;if(p&&h)return 0}};var Hn=function(){this._edges=new Nt,this._ocaMap=new p};Hn.prototype.print=function(t){t.print(\"MULTILINESTRING ( \");for(var e=0;e0&&t.print(\",\"),t.print(\"(\");for(var i=n.getCoordinates(),r=0;r0&&t.print(\",\"),t.print(i[r].x+\" \"+i[r].y);t.println(\")\")}t.print(\") \")},Hn.prototype.addAll=function(t){for(var e=t.iterator();e.hasNext();)this.add(e.next())},Hn.prototype.findEdgeIndex=function(t){for(var e=0;et?1:this.diste?1:0},Jn.prototype.interfaces_=function(){return[E]},Jn.prototype.getClass=function(){return Jn};var Qn=function(){this._nodeMap=new p,this.edge=null;var t=arguments[0];this.edge=t};Qn.prototype.print=function(t){t.println(\"Intersections:\");for(var e=this.iterator();e.hasNext();){e.next().print(t)}},Qn.prototype.iterator=function(){return this._nodeMap.values().iterator()},Qn.prototype.addSplitEdges=function(t){this.addEndpoints();for(var e=this.iterator(),n=e.next();e.hasNext();){var i=e.next(),r=this.createSplitEdge(n,i);t.add(r),n=i}},Qn.prototype.addEndpoints=function(){var t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)},Qn.prototype.createSplitEdge=function(t,e){var n=e.segmentIndex-t.segmentIndex+2,i=this.edge.pts[e.segmentIndex],r=e.dist>0||!e.coord.equals2D(i);r||n--;var o=new Array(n).fill(null),s=0;o[s++]=new C(t.coord);for(var a=t.segmentIndex+1;a<=e.segmentIndex;a++)o[s++]=this.edge.pts[a];return r&&(o[s]=e.coord),new ni(o,new Pe(this.edge._label))},Qn.prototype.add=function(t,e,n){var i=new Jn(t,e,n),r=this._nodeMap.get(i);return null!==r?r:(this._nodeMap.put(i,i),i)},Qn.prototype.isIntersection=function(t){for(var e=this.iterator();e.hasNext();){if(e.next().coord.equals(t))return!0}return!1},Qn.prototype.interfaces_=function(){return[]},Qn.prototype.getClass=function(){return Qn};var Zn=function(){};Zn.prototype.getChainStartIndices=function(t){var e=0,n=new Nt;n.add(new M(e));do{var i=this.findChainEnd(t,e);n.add(new M(i)),e=i}while(en?e:n},$n.prototype.getMinX=function(t){var e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return ee&&(i=1),this._depth[t][n]=i}}},ti.prototype.getDelta=function(t){return this._depth[t][Se.RIGHT]-this._depth[t][Se.LEFT]},ti.prototype.getLocation=function(t,e){return this._depth[t][e]<=0?w.EXTERIOR:w.INTERIOR},ti.prototype.toString=function(){return\"A: \"+this._depth[0][1]+\",\"+this._depth[0][2]+\" B: \"+this._depth[1][1]+\",\"+this._depth[1][2]},ti.prototype.add=function(){if(1===arguments.length)for(var t=arguments[0],e=0;e<2;e++)for(var n=1;n<3;n++){var i=t.getLocation(e,n);i!==w.EXTERIOR&&i!==w.INTERIOR||(this.isNull(e,n)?this._depth[e][n]=ti.depthAtLocation(i):this._depth[e][n]+=ti.depthAtLocation(i))}else if(3===arguments.length){var r=arguments[0],o=arguments[1];arguments[2]===w.INTERIOR&&this._depth[r][o]++}},ti.prototype.interfaces_=function(){return[]},ti.prototype.getClass=function(){return ti},ti.depthAtLocation=function(t){return t===w.EXTERIOR?0:t===w.INTERIOR?1:ti.NULL_VALUE},ei.NULL_VALUE.get=function(){return-1},Object.defineProperties(ti,ei);var ni=function(t){function e(){if(t.call(this),this.pts=null,this._env=null,this.eiList=new Qn(this),this._name=null,this._mce=null,this._isIsolated=!0,this._depth=new ti,this._depthDelta=0,1===arguments.length){var n=arguments[0];e.call(this,n,null)}else if(2===arguments.length){var i=arguments[0],r=arguments[1];this.pts=i,this._label=r}}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getDepth=function(){return this._depth},e.prototype.getCollapsedEdge=function(){var t=new Array(2).fill(null);t[0]=this.pts[0],t[1]=this.pts[1];return new e(t,Pe.toLineLabel(this._label))},e.prototype.isIsolated=function(){return this._isIsolated},e.prototype.getCoordinates=function(){return this.pts},e.prototype.setIsolated=function(t){this._isIsolated=t},e.prototype.setName=function(t){this._name=t},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;if(this.pts.length!==n.pts.length)return!1;for(var i=!0,r=!0,o=this.pts.length,s=0;s0?this.pts[0]:null;if(1===arguments.length){var t=arguments[0];return this.pts[t]}},e.prototype.print=function(t){t.print(\"edge \"+this._name+\": \"),t.print(\"LINESTRING (\");for(var e=0;e0&&t.print(\",\"),t.print(this.pts[e].x+\" \"+this.pts[e].y);t.print(\") \"+this._label+\" \"+this._depthDelta)},e.prototype.computeIM=function(t){e.updateIM(this._label,t)},e.prototype.isCollapsed=function(){return!!this._label.isArea()&&(3===this.pts.length&&!!this.pts[0].equals(this.pts[2]))},e.prototype.isClosed=function(){return this.pts[0].equals(this.pts[this.pts.length-1])},e.prototype.getMaximumSegmentIndex=function(){return this.pts.length-1},e.prototype.getDepthDelta=function(){return this._depthDelta},e.prototype.getNumPoints=function(){return this.pts.length},e.prototype.printReverse=function(t){t.print(\"edge \"+this._name+\": \");for(var e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+\" \");t.println(\"\")},e.prototype.getMonotoneChainEdge=function(){return null===this._mce&&(this._mce=new $n(this)),this._mce},e.prototype.getEnvelope=function(){if(null===this._env){this._env=new j;for(var t=0;t0&&t.append(\",\"),t.append(this.pts[e].x+\" \"+this.pts[e].y);return t.append(\") \"+this._label+\" \"+this._depthDelta),t.toString()},e.prototype.isPointwiseEqual=function(t){if(this.pts.length!==t.pts.length)return!1;for(var e=0;ei||this._maxyo;if(s)return!1;var a=this.intersectsToleranceSquare(t,e);return et.isTrue(!(s&&a),\"Found bad envelope test\"),a},ai.prototype.initCorners=function(t){this._minx=t.x-.5,this._maxx=t.x+.5,this._miny=t.y-.5,this._maxy=t.y+.5,this._corner[0]=new C(this._maxx,this._maxy),this._corner[1]=new C(this._minx,this._maxy),this._corner[2]=new C(this._minx,this._miny),this._corner[3]=new C(this._maxx,this._miny)},ai.prototype.intersects=function(t,e){return 1===this._scaleFactor?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))},ai.prototype.scale=function(t){return Math.round(t*this._scaleFactor)},ai.prototype.getCoordinate=function(){return this._originalPt},ai.prototype.copyScaled=function(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)},ai.prototype.getSafeEnvelope=function(){if(null===this._safeEnv){var t=ai.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new j(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv},ai.prototype.intersectsPixelClosure=function(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),!!this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),!!this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),!!this._li.hasIntersection())))},ai.prototype.intersectsToleranceSquare=function(t,e){var n=!1,i=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),!!this._li.isProper()||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),!!this._li.isProper()||(this._li.hasIntersection()&&(i=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),!!this._li.isProper()||(!(!n||!i)||(!!t.equals(this._pt)||!!e.equals(this._pt))))))},ai.prototype.addSnappedNode=function(t,e){var n=t.getCoordinate(e),i=t.getCoordinate(e+1);return!!this.intersects(n,i)&&(t.addIntersection(this.getCoordinate(),e),!0)},ai.prototype.interfaces_=function(){return[]},ai.prototype.getClass=function(){return ai},ui.SAFE_ENV_EXPANSION_FACTOR.get=function(){return.75},Object.defineProperties(ai,ui);var li=function(){this.tempEnv1=new j,this.selectedSegment=new dn};li.prototype.select=function(){if(1===arguments.length);else if(2===arguments.length){var t=arguments[0],e=arguments[1];t.getLineSegment(e,this.selectedSegment),this.select(this.selectedSegment)}},li.prototype.interfaces_=function(){return[]},li.prototype.getClass=function(){return li};var ci=function(){this._index=null;var t=arguments[0];this._index=t},pi={HotPixelSnapAction:{configurable:!0}};ci.prototype.snap=function(){if(1===arguments.length){var t=arguments[0];return this.snap(t,null,-1)}if(3===arguments.length){var e=arguments[0],n=arguments[1],i=arguments[2],r=e.getSafeEnvelope(),o=new hi(e,n,i);return this._index.query(r,{interfaces_:function(){return[Ke]},visitItem:function(t){t.select(r,o)}}),o.isNodeAdded()}},ci.prototype.interfaces_=function(){return[]},ci.prototype.getClass=function(){return ci},pi.HotPixelSnapAction.get=function(){return hi},Object.defineProperties(ci,pi);var hi=function(t){function e(){t.call(this),this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;var e=arguments[0],n=arguments[1],i=arguments[2];this._hotPixel=e,this._parentEdge=n,this._hotPixelVertexIndex=i}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.isNodeAdded=function(){return this._isNodeAdded},e.prototype.select=function(){if(2!==arguments.length)return t.prototype.select.apply(this,arguments);var e=arguments[0],n=arguments[1],i=e.getContext();if(null!==this._parentEdge&&i===this._parentEdge&&n===this._hotPixelVertexIndex)return null;this._isNodeAdded=this._hotPixel.addSnappedNode(i,n)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(li),fi=function(){this._li=null,this._interiorIntersections=null;var t=arguments[0];this._li=t,this._interiorIntersections=new Nt};fi.prototype.processIntersections=function(t,e,n,i){if(t===n&&e===i)return null;var r=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[i],a=n.getCoordinates()[i+1];if(this._li.computeIntersection(r,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(var u=0;u=0;e--){try{t.bufferReducedPrecision(e)}catch(e){if(!(e instanceof we))throw e;t._saveException=e}if(null!==t._resultGeometry)return null}throw this._saveException}if(1===arguments.length){var n=arguments[0],i=di.precisionScaleFactor(this._argGeom,this._distance,n),r=new fe(i);this.bufferFixedPrecision(r)}},di.prototype.computeGeometry=function(){if(this.bufferOriginalPrecision(),null!==this._resultGeometry)return null;var t=this._argGeom.getFactory().getPrecisionModel();t.getType()===fe.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()},di.prototype.setQuadrantSegments=function(t){this._bufParams.setQuadrantSegments(t)},di.prototype.bufferOriginalPrecision=function(){try{var t=new ii(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(!(t instanceof $))throw t;this._saveException=t}},di.prototype.getResultGeometry=function(t){return this._distance=t,this.computeGeometry(),this._resultGeometry},di.prototype.setEndCapStyle=function(t){this._bufParams.setEndCapStyle(t)},di.prototype.interfaces_=function(){return[]},di.prototype.getClass=function(){return di},di.bufferOp=function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return new di(t).getResultGeometry(e)}if(3===arguments.length){if(Number.isInteger(arguments[2])&&arguments[0]instanceof ct&&\"number\"==typeof arguments[1]){var n=arguments[0],i=arguments[1],r=arguments[2],o=new di(n);o.setQuadrantSegments(r);return o.getResultGeometry(i)}if(arguments[2]instanceof Cn&&arguments[0]instanceof ct&&\"number\"==typeof arguments[1]){var s=arguments[0],a=arguments[1],u=arguments[2];return new di(s,u).getResultGeometry(a)}}else if(4===arguments.length){var l=arguments[0],c=arguments[1],p=arguments[2],h=arguments[3],f=new di(l);f.setQuadrantSegments(p),f.setEndCapStyle(h);return f.getResultGeometry(c)}},di.precisionScaleFactor=function(t,e,n){var i=t.getEnvelopeInternal(),r=R.max(Math.abs(i.getMaxX()),Math.abs(i.getMaxY()),Math.abs(i.getMinX()),Math.abs(i.getMinY()))+2*(e>0?e:0),o=n-Math.trunc(Math.log(r)/Math.log(10)+1);return Math.pow(10,o)},yi.CAP_ROUND.get=function(){return Cn.CAP_ROUND},yi.CAP_BUTT.get=function(){return Cn.CAP_FLAT},yi.CAP_FLAT.get=function(){return Cn.CAP_FLAT},yi.CAP_SQUARE.get=function(){return Cn.CAP_SQUARE},yi.MAX_PRECISION_DIGITS.get=function(){return 12},Object.defineProperties(di,yi);var _i=function(){this._pt=[new C,new C],this._distance=v.NaN,this._isNull=!0};_i.prototype.getCoordinates=function(){return this._pt},_i.prototype.getCoordinate=function(t){return this._pt[t]},_i.prototype.setMinimum=function(){if(1===arguments.length){var t=arguments[0];this.setMinimum(t._pt[0],t._pt[1])}else if(2===arguments.length){var e=arguments[0],n=arguments[1];if(this._isNull)return this.initialize(e,n),null;var i=e.distance(n);ithis._distance&&this.initialize(e,n,i)}},_i.prototype.interfaces_=function(){return[]},_i.prototype.getClass=function(){return _i};var mi=function(){};mi.prototype.interfaces_=function(){return[]},mi.prototype.getClass=function(){return mi},mi.computeDistance=function(){if(arguments[2]instanceof _i&&arguments[0]instanceof Kt&&arguments[1]instanceof C)for(var t=arguments[0],e=arguments[1],n=arguments[2],i=t.getCoordinates(),r=new dn,o=0;o0||this._isIn?w.INTERIOR:w.EXTERIOR)},Si.prototype.interfaces_=function(){return[]},Si.prototype.getClass=function(){return Si};var Li=function t(){if(this._component=null,this._segIndex=null,this._pt=null,2===arguments.length){var e=arguments[0],n=arguments[1];t.call(this,e,t.INSIDE_AREA,n)}else if(3===arguments.length){var i=arguments[0],r=arguments[1],o=arguments[2];this._component=i,this._segIndex=r,this._pt=o}},bi={INSIDE_AREA:{configurable:!0}};Li.prototype.isInsideArea=function(){return this._segIndex===Li.INSIDE_AREA},Li.prototype.getCoordinate=function(){return this._pt},Li.prototype.getGeometryComponent=function(){return this._component},Li.prototype.getSegmentIndex=function(){return this._segIndex},Li.prototype.interfaces_=function(){return[]},Li.prototype.getClass=function(){return Li},bi.INSIDE_AREA.get=function(){return-1},Object.defineProperties(Li,bi);var wi=function(t){this._pts=t||null};wi.prototype.filter=function(t){t instanceof Qt&&this._pts.add(t)},wi.prototype.interfaces_=function(){return[Vt]},wi.prototype.getClass=function(){return wi},wi.getPoints=function(){if(1===arguments.length){var t=arguments[0];return t instanceof Qt?$e.singletonList(t):wi.getPoints(t,new Nt)}if(2===arguments.length){var e=arguments[0],n=arguments[1];return e instanceof Qt?n.add(e):e instanceof zt&&e.apply(new wi(n)),n}};var Oi=function(){this._locations=null;var t=arguments[0];this._locations=t};Oi.prototype.filter=function(t){(t instanceof Qt||t instanceof Kt||t instanceof $t)&&this._locations.add(new Li(t,0,t.getCoordinate()))},Oi.prototype.interfaces_=function(){return[Vt]},Oi.prototype.getClass=function(){return Oi},Oi.getLocations=function(t){var e=new Nt;return t.apply(new Oi(e)),e};var Ti=function(){if(this._geom=null,this._terminateDistance=0,this._ptLocator=new Si,this._minDistanceLocation=null,this._minDistance=v.MAX_VALUE,2===arguments.length){var t=arguments[0],e=arguments[1];this._geom=[t,e],this._terminateDistance=0}else if(3===arguments.length){var n=arguments[0],i=arguments[1],r=arguments[2];this._geom=new Array(2).fill(null),this._geom[0]=n,this._geom[1]=i,this._terminateDistance=r}};Ti.prototype.computeContainmentDistance=function(){if(0===arguments.length){var t=new Array(2).fill(null);if(this.computeContainmentDistance(0,t),this._minDistance<=this._terminateDistance)return null;this.computeContainmentDistance(1,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1],i=1-e,r=Ni.getPolygons(this._geom[e]);if(r.size()>0){var o=Oi.getLocations(this._geom[i]);if(this.computeContainmentDistance(o,r,n),this._minDistance<=this._terminateDistance)return this._minDistanceLocation[i]=n[0],this._minDistanceLocation[e]=n[1],null}}else if(3===arguments.length)if(arguments[2]instanceof Array&&T(arguments[0],xt)&&T(arguments[1],xt)){for(var s=arguments[0],a=arguments[1],u=arguments[2],l=0;lthis._minDistance)return null;for(var i=t.getCoordinates(),r=e.getCoordinate(),o=0;othis._minDistance)return null;for(var p=u.getCoordinates(),h=l.getCoordinates(),f=0;fthis._distance&&this.initialize(e,n,i)}},Ri.prototype.interfaces_=function(){return[]},Ri.prototype.getClass=function(){return Ri};var Pi=function(){};Pi.prototype.interfaces_=function(){return[]},Pi.prototype.getClass=function(){return Pi},Pi.computeDistance=function(){if(arguments[2]instanceof Ri&&arguments[0]instanceof Kt&&arguments[1]instanceof C)for(var t=arguments[0],e=arguments[1],n=arguments[2],i=new dn,r=t.getCoordinates(),o=0;o1||t<=0)throw new m(\"Fraction is not in range (0.0 - 1.0]\");this._densifyFrac=t},Di.prototype.compute=function(t,e){this.computeOrientedDistance(t,e,this._ptDist),this.computeOrientedDistance(e,t,this._ptDist)},Di.prototype.distance=function(){return this.compute(this._g0,this._g1),this._ptDist.getDistance()},Di.prototype.computeOrientedDistance=function(t,e,n){var i=new Ai(e);if(t.apply(i),n.setMaximum(i.getMaxPointDistance()),this._densifyFrac>0){var r=new Fi(e,this._densifyFrac);t.apply(r),n.setMaximum(r.getMaxPointDistance())}},Di.prototype.orientedDistance=function(){return this.computeOrientedDistance(this._g0,this._g1,this._ptDist),this._ptDist.getDistance()},Di.prototype.interfaces_=function(){return[]},Di.prototype.getClass=function(){return Di},Di.distance=function(){if(2===arguments.length){var t=arguments[0],e=arguments[1];return new Di(t,e).distance()}if(3===arguments.length){var n=arguments[0],i=arguments[1],r=arguments[2],o=new Di(n,i);return o.setDensifyFraction(r),o.distance()}},Mi.MaxPointDistanceFilter.get=function(){return Ai},Mi.MaxDensifiedByFractionDistanceFilter.get=function(){return Fi},Object.defineProperties(Di,Mi);var Ai=function(){this._maxPtDist=new Ri,this._minPtDist=new Ri,this._euclideanDist=new Pi,this._geom=null;var t=arguments[0];this._geom=t};Ai.prototype.filter=function(t){this._minPtDist.initialize(),Pi.computeDistance(this._geom,t,this._minPtDist),this._maxPtDist.setMaximum(this._minPtDist)},Ai.prototype.getMaxPointDistance=function(){return this._maxPtDist},Ai.prototype.interfaces_=function(){return[ft]},Ai.prototype.getClass=function(){return Ai};var Fi=function(){this._maxPtDist=new Ri,this._minPtDist=new Ri,this._geom=null,this._numSubSegs=0;var t=arguments[0],e=arguments[1];this._geom=t,this._numSubSegs=Math.trunc(Math.round(1/e))};Fi.prototype.filter=function(t,e){if(0===e)return null;for(var n=t.getCoordinate(e-1),i=t.getCoordinate(e),r=(i.x-n.x)/this._numSubSegs,o=(i.y-n.y)/this._numSubSegs,s=0;sn){this._isValid=!1;var r=i.getCoordinates();this._errorLocation=r[1],this._errorIndicator=t.getFactory().createLineString(r),this._errMsg=\"Distance between buffer curve and input is too large (\"+this._maxDistanceFound+\" at \"+Z.toLineString(r[0],r[1])+\")\"}},Gi.prototype.isValid=function(){var t=Math.abs(this._bufDistance),e=Gi.MAX_DISTANCE_DIFF_FRAC*t;return this._minValidDistance=t-e,this._maxValidDistance=t+e,!(!this._input.isEmpty()&&!this._result.isEmpty())||(this._bufDistance>0?this.checkPositiveValid():this.checkNegativeValid(),Gi.VERBOSE&&Y.out.println(\"Min Dist= \"+this._minDistanceFound+\" err= \"+(1-this._minDistanceFound/this._bufDistance)+\" Max Dist= \"+this._maxDistanceFound+\" err= \"+(this._maxDistanceFound/this._bufDistance-1)),this._isValid)},Gi.prototype.checkNegativeValid=function(){if(!(this._input instanceof $t||this._input instanceof ne||this._input instanceof zt))return null;var t=this.getPolygonLines(this._input);if(this.checkMinimumDistance(t,this._result,this._minValidDistance),!this._isValid)return null;this.checkMaximumDistance(t,this._result,this._maxValidDistance)},Gi.prototype.getErrorIndicator=function(){return this._errorIndicator},Gi.prototype.checkMinimumDistance=function(t,e,n){var i=new Ti(t,e,n);if(this._minDistanceFound=i.distance(),this._minDistanceFound0&&t>e&&(this._isValid=!1,this._errorMsg=\"Area of positive buffer is smaller than input\",this._errorIndicator=this._result),this._distance<0&&t=2?null:this._distance>0?null:(this._result.isEmpty()||(this._isValid=!1,this._errorMsg=\"Result is non-empty\",this._errorIndicator=this._result),void this.report(\"ExpectedEmpty\"))},Bi.prototype.report=function(t){if(!Bi.VERBOSE)return null;Y.out.println(\"Check \"+t+\": \"+(this._isValid?\"passed\":\"FAILED\"))},Bi.prototype.getErrorMessage=function(){return this._errorMsg},Bi.prototype.interfaces_=function(){return[]},Bi.prototype.getClass=function(){return Bi},Bi.isValidMsg=function(t,e,n){var i=new Bi(t,e,n);return i.isValid()?null:i.getErrorMessage()},Bi.isValid=function(t,e,n){return!!new Bi(t,e,n).isValid()},Vi.VERBOSE.get=function(){return!1},Vi.MAX_ENV_DIFF_FRAC.get=function(){return.012},Object.defineProperties(Bi,Vi);var Ui=function(){this._pts=null,this._data=null;var t=arguments[0],e=arguments[1];this._pts=t,this._data=e};Ui.prototype.getCoordinates=function(){return this._pts},Ui.prototype.size=function(){return this._pts.length},Ui.prototype.getCoordinate=function(t){return this._pts[t]},Ui.prototype.isClosed=function(){return this._pts[0].equals(this._pts[this._pts.length-1])},Ui.prototype.getSegmentOctant=function(t){return t===this._pts.length-1?-1:pn.octant(this.getCoordinate(t),this.getCoordinate(t+1))},Ui.prototype.setData=function(t){this._data=t},Ui.prototype.getData=function(){return this._data},Ui.prototype.toString=function(){return Z.toLineString(new ue(this._pts))},Ui.prototype.interfaces_=function(){return[hn]},Ui.prototype.getClass=function(){return Ui};var zi=function(){this._findAllIntersections=!1,this._isCheckEndSegmentsOnly=!1,this._li=null,this._interiorIntersection=null,this._intSegments=null,this._intersections=new Nt,this._intersectionCount=0,this._keepIntersections=!0;var t=arguments[0];this._li=t,this._interiorIntersection=null};zi.prototype.getInteriorIntersection=function(){return this._interiorIntersection},zi.prototype.setCheckEndSegmentsOnly=function(t){this._isCheckEndSegmentsOnly=t},zi.prototype.getIntersectionSegments=function(){return this._intSegments},zi.prototype.count=function(){return this._intersectionCount},zi.prototype.getIntersections=function(){return this._intersections},zi.prototype.setFindAllIntersections=function(t){this._findAllIntersections=t},zi.prototype.setKeepIntersections=function(t){this._keepIntersections=t},zi.prototype.processIntersections=function(t,e,n,i){if(!this._findAllIntersections&&this.hasIntersection())return null;if(t===n&&e===i)return null;if(this._isCheckEndSegmentsOnly){if(!(this.isEndSegment(t,e)||this.isEndSegment(n,i)))return null}var r=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[i],a=n.getCoordinates()[i+1];this._li.computeIntersection(r,o,s,a),this._li.hasIntersection()&&this._li.isInteriorIntersection()&&(this._intSegments=new Array(4).fill(null),this._intSegments[0]=r,this._intSegments[1]=o,this._intSegments[2]=s,this._intSegments[3]=a,this._interiorIntersection=this._li.getIntersection(0),this._keepIntersections&&this._intersections.add(this._interiorIntersection),this._intersectionCount++)},zi.prototype.isEndSegment=function(t,e){return 0===e||e>=t.size()-2},zi.prototype.hasIntersection=function(){return null!==this._interiorIntersection},zi.prototype.isDone=function(){return!this._findAllIntersections&&null!==this._interiorIntersection},zi.prototype.interfaces_=function(){return[Wn]},zi.prototype.getClass=function(){return zi},zi.createAllIntersectionsFinder=function(t){var e=new zi(t);return e.setFindAllIntersections(!0),e},zi.createAnyIntersectionFinder=function(t){return new zi(t)},zi.createIntersectionCounter=function(t){var e=new zi(t);return e.setFindAllIntersections(!0),e.setKeepIntersections(!1),e};var Xi=function(){this._li=new rt,this._segStrings=null,this._findAllIntersections=!1,this._segInt=null,this._isValid=!0;var t=arguments[0];this._segStrings=t};Xi.prototype.execute=function(){if(null!==this._segInt)return null;this.checkInteriorIntersections()},Xi.prototype.getIntersections=function(){return this._segInt.getIntersections()},Xi.prototype.isValid=function(){return this.execute(),this._isValid},Xi.prototype.setFindAllIntersections=function(t){this._findAllIntersections=t},Xi.prototype.checkInteriorIntersections=function(){this._isValid=!0,this._segInt=new zi(this._li),this._segInt.setFindAllIntersections(this._findAllIntersections);var t=new xn;if(t.setSegmentIntersector(this._segInt),t.computeNodes(this._segStrings),this._segInt.hasIntersection())return this._isValid=!1,null},Xi.prototype.checkValid=function(){if(this.execute(),!this._isValid)throw new we(this.getErrorMessage(),this._segInt.getInteriorIntersection())},Xi.prototype.getErrorMessage=function(){if(this._isValid)return\"no intersections found\";var t=this._segInt.getIntersectionSegments();return\"found non-noded intersection between \"+Z.toLineString(t[0],t[1])+\" and \"+Z.toLineString(t[2],t[3])},Xi.prototype.interfaces_=function(){return[]},Xi.prototype.getClass=function(){return Xi},Xi.computeIntersections=function(t){var e=new Xi(t);return e.setFindAllIntersections(!0),e.isValid(),e.getIntersections()};var Yi=function t(){this._nv=null;var e=arguments[0];this._nv=new Xi(t.toSegmentStrings(e))};Yi.prototype.checkValid=function(){this._nv.checkValid()},Yi.prototype.interfaces_=function(){return[]},Yi.prototype.getClass=function(){return Yi},Yi.toSegmentStrings=function(t){for(var e=new Nt,n=t.iterator();n.hasNext();){var i=n.next();e.add(new Ui(i.getCoordinates(),i))}return e},Yi.checkValid=function(t){new Yi(t).checkValid()};var ki=function(t){this._mapOp=t};ki.prototype.map=function(t){for(var e=new Nt,n=0;n0&&i<4&&!this._preserveType?this._factory.createLineString(n):this._factory.createLinearRing(n)},Wi.prototype.interfaces_=function(){return[]},Wi.prototype.getClass=function(){return Wi};var Ki=function t(){if(this._snapTolerance=0,this._srcPts=null,this._seg=new dn,this._allowSnappingToSourceVertices=!1,this._isClosed=!1,arguments[0]instanceof Kt&&\"number\"==typeof arguments[1]){var e=arguments[0],n=arguments[1];t.call(this,e.getCoordinates(),n)}else if(arguments[0]instanceof Array&&\"number\"==typeof arguments[1]){var i=arguments[0],r=arguments[1];this._srcPts=i,this._isClosed=t.isClosed(i),this._snapTolerance=r}};Ki.prototype.snapVertices=function(t,e){for(var n=this._isClosed?t.size()-1:t.size(),i=0;i=0&&t.add(o+1,new C(r),!1)}},Ki.prototype.findSegmentIndexToSnap=function(t,e){for(var n=v.MAX_VALUE,i=-1,r=0;re&&(e=i)}return e}if(2===arguments.length){var r=arguments[0],o=arguments[1];return Math.min(Ji.computeOverlaySnapTolerance(r),Ji.computeOverlaySnapTolerance(o))}},Ji.computeSizeBasedSnapTolerance=function(t){var e=t.getEnvelopeInternal();return Math.min(e.getHeight(),e.getWidth())*Ji.SNAP_PRECISION_FACTOR},Ji.snapToSelf=function(t,e,n){return new Ji(t).snapToSelf(e,n)},Qi.SNAP_PRECISION_FACTOR.get=function(){return 1e-9},Object.defineProperties(Ji,Qi);var Zi=function(t){function e(e,n,i){t.call(this),this._snapTolerance=e||null,this._snapPts=n||null,this._isSelfSnap=void 0!==i&&i}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.snapLine=function(t,e){var n=new Ki(t,this._snapTolerance);return n.setAllowSnappingToSourceVertices(this._isSelfSnap),n.snapTo(e)},e.prototype.transformCoordinates=function(t,e){var n=t.toCoordinateArray(),i=this.snapLine(n,this._snapPts);return this._factory.getCoordinateSequenceFactory().create(i)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(Wi),$i=function(){this._isFirst=!0,this._commonMantissaBitsCount=53,this._commonBits=0,this._commonSignExp=null};$i.prototype.getCommon=function(){return v.longBitsToDouble(this._commonBits)},$i.prototype.add=function(t){var e=v.doubleToLongBits(t);if(this._isFirst)return this._commonBits=e,this._commonSignExp=$i.signExpBits(this._commonBits),this._isFirst=!1,null;if($i.signExpBits(e)!==this._commonSignExp)return this._commonBits=0,null;this._commonMantissaBitsCount=$i.numCommonMostSigMantissaBits(this._commonBits,e),this._commonBits=$i.zeroLowerBits(this._commonBits,64-(12+this._commonMantissaBitsCount))},$i.prototype.toString=function(){if(1===arguments.length){var t=arguments[0],e=v.longBitsToDouble(t),n=\"0000000000000000000000000000000000000000000000000000000000000000\"+v.toBinaryString(t),i=n.substring(n.length-64);return i.substring(0,1)+\" \"+i.substring(1,12)+\"(exp) \"+i.substring(12)+\" [ \"+e+\" ]\"}},$i.prototype.interfaces_=function(){return[]},$i.prototype.getClass=function(){return $i},$i.getBit=function(t,e){return 0!=(t&1<>52},$i.zeroLowerBits=function(t,e){return t&~((1<=0;i--){if($i.getBit(t,i)!==$i.getBit(e,i))return n;n++}return 52};var tr=function(){this._commonCoord=null,this._ccFilter=new nr},er={CommonCoordinateFilter:{configurable:!0},Translater:{configurable:!0}};tr.prototype.addCommonBits=function(t){var e=new ir(this._commonCoord);t.apply(e),t.geometryChanged()},tr.prototype.removeCommonBits=function(t){if(0===this._commonCoord.x&&0===this._commonCoord.y)return t;var e=new C(this._commonCoord);e.x=-e.x,e.y=-e.y;var n=new ir(e);return t.apply(n),t.geometryChanged(),t},tr.prototype.getCommonCoordinate=function(){return this._commonCoord},tr.prototype.add=function(t){t.apply(this._ccFilter),this._commonCoord=this._ccFilter.getCommonCoordinate()},tr.prototype.interfaces_=function(){return[]},tr.prototype.getClass=function(){return tr},er.CommonCoordinateFilter.get=function(){return nr},er.Translater.get=function(){return ir},Object.defineProperties(tr,er);var nr=function(){this._commonBitsX=new $i,this._commonBitsY=new $i};nr.prototype.filter=function(t){this._commonBitsX.add(t.x),this._commonBitsY.add(t.y)},nr.prototype.getCommonCoordinate=function(){return new C(this._commonBitsX.getCommon(),this._commonBitsY.getCommon())},nr.prototype.interfaces_=function(){return[ft]},nr.prototype.getClass=function(){return nr};var ir=function(){this.trans=null;var t=arguments[0];this.trans=t};ir.prototype.filter=function(t,e){var n=t.getOrdinate(e,0)+this.trans.x,i=t.getOrdinate(e,1)+this.trans.y;t.setOrdinate(e,0,n),t.setOrdinate(e,1,i)},ir.prototype.isDone=function(){return!1},ir.prototype.isGeometryChanged=function(){return!0},ir.prototype.interfaces_=function(){return[Ut]},ir.prototype.getClass=function(){return ir};var rr=function(t,e){this._geom=new Array(2).fill(null),this._snapTolerance=null,this._cbr=null,this._geom[0]=t,this._geom[1]=e,this.computeSnapTolerance()};rr.prototype.selfSnap=function(t){return new Ji(t).snapTo(t,this._snapTolerance)},rr.prototype.removeCommonBits=function(t){this._cbr=new tr,this._cbr.add(t[0]),this._cbr.add(t[1]);var e=new Array(2).fill(null);return e[0]=this._cbr.removeCommonBits(t[0].copy()),e[1]=this._cbr.removeCommonBits(t[1].copy()),e},rr.prototype.prepareResult=function(t){return this._cbr.addCommonBits(t),t},rr.prototype.getResultGeometry=function(t){var e=this.snap(this._geom),n=Lr.overlayOp(e[0],e[1],t);return this.prepareResult(n)},rr.prototype.checkValid=function(t){t.isValid()||Y.out.println(\"Snapped geometry is invalid\")},rr.prototype.computeSnapTolerance=function(){this._snapTolerance=Ji.computeOverlaySnapTolerance(this._geom[0],this._geom[1])},rr.prototype.snap=function(t){var e=this.removeCommonBits(t);return Ji.snap(e[0],e[1],this._snapTolerance)},rr.prototype.interfaces_=function(){return[]},rr.prototype.getClass=function(){return rr},rr.overlayOp=function(t,e,n){return new rr(t,e).getResultGeometry(n)},rr.union=function(t,e){return rr.overlayOp(t,e,Lr.UNION)},rr.intersection=function(t,e){return rr.overlayOp(t,e,Lr.INTERSECTION)},rr.symDifference=function(t,e){return rr.overlayOp(t,e,Lr.SYMDIFFERENCE)},rr.difference=function(t,e){return rr.overlayOp(t,e,Lr.DIFFERENCE)};var or=function(t,e){this._geom=new Array(2).fill(null),this._geom[0]=t,this._geom[1]=e};or.prototype.getResultGeometry=function(t){var e=null,n=!1,i=null;try{e=Lr.overlayOp(this._geom[0],this._geom[1],t);n=!0}catch(t){if(!(t instanceof $))throw t;i=t}if(!n)try{e=rr.overlayOp(this._geom[0],this._geom[1],t)}catch(t){throw t instanceof $?i:t}return e},or.prototype.interfaces_=function(){return[]},or.prototype.getClass=function(){return or},or.overlayOp=function(t,e,n){return new or(t,e).getResultGeometry(n)},or.union=function(t,e){return or.overlayOp(t,e,Lr.UNION)},or.intersection=function(t,e){return or.overlayOp(t,e,Lr.INTERSECTION)},or.symDifference=function(t,e){return or.overlayOp(t,e,Lr.SYMDIFFERENCE)},or.difference=function(t,e){return or.overlayOp(t,e,Lr.DIFFERENCE)};var sr=function(){this.mce=null,this.chainIndex=null;var t=arguments[0],e=arguments[1];this.mce=t,this.chainIndex=e};sr.prototype.computeIntersections=function(t,e){this.mce.computeIntersectsForChain(this.chainIndex,t.mce,t.chainIndex,e)},sr.prototype.interfaces_=function(){return[]},sr.prototype.getClass=function(){return sr};var ar=function t(){if(this._label=null,this._xValue=null,this._eventType=null,this._insertEvent=null,this._deleteEventIndex=null,this._obj=null,2===arguments.length){var e=arguments[0],n=arguments[1];this._eventType=t.DELETE,this._xValue=e,this._insertEvent=n}else if(3===arguments.length){var i=arguments[0],r=arguments[1],o=arguments[2];this._eventType=t.INSERT,this._label=i,this._xValue=r,this._obj=o}},ur={INSERT:{configurable:!0},DELETE:{configurable:!0}};ar.prototype.isDelete=function(){return this._eventType===ar.DELETE},ar.prototype.setDeleteEventIndex=function(t){this._deleteEventIndex=t},ar.prototype.getObject=function(){return this._obj},ar.prototype.compareTo=function(t){var e=t;return this._xValuee._xValue?1:this._eventTypee._eventType?1:0},ar.prototype.getInsertEvent=function(){return this._insertEvent},ar.prototype.isInsert=function(){return this._eventType===ar.INSERT},ar.prototype.isSameLabel=function(t){return null!==this._label&&this._label===t._label},ar.prototype.getDeleteEventIndex=function(){return this._deleteEventIndex},ar.prototype.interfaces_=function(){return[E]},ar.prototype.getClass=function(){return ar},ur.INSERT.get=function(){return 1},ur.DELETE.get=function(){return 2},Object.defineProperties(ar,ur);var lr=function(){};lr.prototype.interfaces_=function(){return[]},lr.prototype.getClass=function(){return lr};var cr=function(){this._hasIntersection=!1,this._hasProper=!1,this._hasProperInterior=!1,this._properIntersectionPoint=null,this._li=null,this._includeProper=null,this._recordIsolated=null,this._isSelfIntersection=null,this._numIntersections=0,this.numTests=0,this._bdyNodes=null,this._isDone=!1,this._isDoneWhenProperInt=!1;var t=arguments[0],e=arguments[1],n=arguments[2];this._li=t,this._includeProper=e,this._recordIsolated=n};cr.prototype.isTrivialIntersection=function(t,e,n,i){if(t===n&&1===this._li.getIntersectionNum()){if(cr.isAdjacentSegments(e,i))return!0;if(t.isClosed()){var r=t.getNumPoints()-1;if(0===e&&i===r||0===i&&e===r)return!0}}return!1},cr.prototype.getProperIntersectionPoint=function(){return this._properIntersectionPoint},cr.prototype.setIsDoneIfProperInt=function(t){this._isDoneWhenProperInt=t},cr.prototype.hasProperInteriorIntersection=function(){return this._hasProperInterior},cr.prototype.isBoundaryPointInternal=function(t,e){for(var n=e.iterator();n.hasNext();){var i=n.next().getCoordinate();if(t.isIntersection(i))return!0}return!1},cr.prototype.hasProperIntersection=function(){return this._hasProper},cr.prototype.hasIntersection=function(){return this._hasIntersection},cr.prototype.isDone=function(){return this._isDone},cr.prototype.isBoundaryPoint=function(t,e){return null!==e&&(!!this.isBoundaryPointInternal(t,e[0])||!!this.isBoundaryPointInternal(t,e[1]))},cr.prototype.setBoundaryNodes=function(t,e){this._bdyNodes=new Array(2).fill(null),this._bdyNodes[0]=t,this._bdyNodes[1]=e},cr.prototype.addIntersections=function(t,e,n,i){if(t===n&&e===i)return null;this.numTests++;var r=t.getCoordinates()[e],o=t.getCoordinates()[e+1],s=n.getCoordinates()[i],a=n.getCoordinates()[i+1];this._li.computeIntersection(r,o,s,a),this._li.hasIntersection()&&(this._recordIsolated&&(t.setIsolated(!1),n.setIsolated(!1)),this._numIntersections++,this.isTrivialIntersection(t,e,n,i)||(this._hasIntersection=!0,!this._includeProper&&this._li.isProper()||(t.addIntersections(this._li,e,0),n.addIntersections(this._li,i,1)),this._li.isProper()&&(this._properIntersectionPoint=this._li.getIntersection(0).copy(),this._hasProper=!0,this._isDoneWhenProperInt&&(this._isDone=!0),this.isBoundaryPoint(this._li,this._bdyNodes)||(this._hasProperInterior=!0))))},cr.prototype.interfaces_=function(){return[]},cr.prototype.getClass=function(){return cr},cr.isAdjacentSegments=function(t,e){return 1===Math.abs(t-e)};var pr=function(t){function e(){t.call(this),this.events=new Nt,this.nOverlaps=null}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.prepareEvents=function(){$e.sort(this.events);for(var t=0;te||this._maxo?1:0},gr.prototype.interfaces_=function(){return[N]},gr.prototype.getClass=function(){return gr};var dr=function(t){function e(){t.call(this),this._item=null;var e=arguments[0],n=arguments[1],i=arguments[2];this._min=e,this._max=n,this._item=i}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.query=function(t,e,n){if(!this.intersects(t,e))return null;n.visitItem(this._item)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(hr),yr=function(t){function e(){t.call(this),this._node1=null,this._node2=null;var e=arguments[0],n=arguments[1];this._node1=e,this._node2=n,this.buildExtent(this._node1,this._node2)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.buildExtent=function(t,e){this._min=Math.min(t._min,e._min),this._max=Math.max(t._max,e._max)},e.prototype.query=function(t,e,n){if(!this.intersects(t,e))return null;null!==this._node1&&this._node1.query(t,e,n),null!==this._node2&&this._node2.query(t,e,n)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e}(hr),_r=function(){this._leaves=new Nt,this._root=null,this._level=0};_r.prototype.buildTree=function(){$e.sort(this._leaves,new hr.NodeComparator);for(var t=this._leaves,e=null,n=new Nt;;){if(this.buildLevel(t,n),1===n.size())return n.get(0);e=t,t=n,n=e}},_r.prototype.insert=function(t,e,n){if(null!==this._root)throw new Error(\"Index cannot be added to once it has been queried\");this._leaves.add(new dr(t,e,n))},_r.prototype.query=function(t,e,n){this.init(),this._root.query(t,e,n)},_r.prototype.buildRoot=function(){if(null!==this._root)return null;this._root=this.buildTree()},_r.prototype.printNode=function(t){Y.out.println(Z.toLineString(new C(t._min,this._level),new C(t._max,this._level)))},_r.prototype.init=function(){if(null!==this._root)return null;this.buildRoot()},_r.prototype.buildLevel=function(t,e){this._level++,e.clear();for(var n=0;n=2,\"found LineString with single point\"),this.insertBoundaryPoint(this._argIndex,e[0]),this.insertBoundaryPoint(this._argIndex,e[e.length-1])},e.prototype.getInvalidPoint=function(){return this._invalidPoint},e.prototype.getBoundaryPoints=function(){for(var t=this.getBoundaryNodes(),e=new Array(t.size()).fill(null),n=0,i=t.iterator();i.hasNext();){var r=i.next();e[n++]=r.getCoordinate().copy()}return e},e.prototype.getBoundaryNodes=function(){return null===this._boundaryNodes&&(this._boundaryNodes=this._nodes.getBoundaryNodes(this._argIndex)),this._boundaryNodes},e.prototype.addSelfIntersectionNode=function(t,e,n){if(this.isBoundaryNode(t,e))return null;n===w.BOUNDARY&&this._useBoundaryDeterminationRule?this.insertBoundaryPoint(t,e):this.insertPoint(t,e,n)},e.prototype.addPolygonRing=function(t,e,n){if(t.isEmpty())return null;var i=Lt.removeRepeatedPoints(t.getCoordinates());if(i.length<4)return this._hasTooFewPoints=!0,this._invalidPoint=i[0],null;var r=e,o=n;at.isCCW(i)&&(r=n,o=e);var s=new ni(i,new Pe(this._argIndex,w.BOUNDARY,r,o));this._lineEdgeMap.put(t,s),this.insertEdge(s),this.insertPoint(this._argIndex,i[0],w.BOUNDARY)},e.prototype.insertPoint=function(t,e,n){var i=this._nodes.addNode(e),r=i.getLabel();null===r?i._label=new Pe(t,n):r.setLocation(t,n)},e.prototype.createEdgeSetIntersector=function(){return new pr},e.prototype.addSelfIntersectionNodes=function(t){for(var e=this._edges.iterator();e.hasNext();)for(var n=e.next(),i=n.getLabel().getLocation(t),r=n.eiList.iterator();r.hasNext();){var o=r.next();this.addSelfIntersectionNode(t,o.coord,i)}},e.prototype.add=function(){if(1!==arguments.length)return t.prototype.add.apply(this,arguments);var e=arguments[0];if(e.isEmpty())return null;if(e instanceof ne&&(this._useBoundaryDeterminationRule=!1),e instanceof $t)this.addPolygon(e);else if(e instanceof Kt)this.addLineString(e);else if(e instanceof Qt)this.addPoint(e);else if(e instanceof te)this.addCollection(e);else if(e instanceof Xt)this.addCollection(e);else if(e instanceof ne)this.addCollection(e);else{if(!(e instanceof zt))throw new Error(e.getClass().getName());this.addCollection(e)}},e.prototype.addCollection=function(t){for(var e=0;e50?(null===this._areaPtLocator&&(this._areaPtLocator=new vr(this._parentGeom)),this._areaPtLocator.locate(t)):this._ptLocator.locate(t,this._parentGeom)},e.prototype.findEdge=function(){if(1===arguments.length){var e=arguments[0];return this._lineEdgeMap.get(e)}return t.prototype.findEdge.apply(this,arguments)},e.prototype.interfaces_=function(){return[]},e.prototype.getClass=function(){return e},e.determineBoundary=function(t,e){return t.isInBoundary(e)?w.BOUNDARY:w.INTERIOR},e}(Ye),Cr=function(){if(this._li=new rt,this._resultPrecisionModel=null,this._arg=null,1===arguments.length){var t=arguments[0];this.setComputationPrecision(t.getPrecisionModel()),this._arg=new Array(1).fill(null),this._arg[0]=new Nr(0,t)}else if(2===arguments.length){var e=arguments[0],n=arguments[1],i=gt.OGC_SFS_BOUNDARY_RULE;e.getPrecisionModel().compareTo(n.getPrecisionModel())>=0?this.setComputationPrecision(e.getPrecisionModel()):this.setComputationPrecision(n.getPrecisionModel()),this._arg=new Array(2).fill(null),this._arg[0]=new Nr(0,e,i),this._arg[1]=new Nr(1,n,i)}else if(3===arguments.length){var r=arguments[0],o=arguments[1],s=arguments[2];r.getPrecisionModel().compareTo(o.getPrecisionModel())>=0?this.setComputationPrecision(r.getPrecisionModel()):this.setComputationPrecision(o.getPrecisionModel()),this._arg=new Array(2).fill(null),this._arg[0]=new Nr(0,r,s),this._arg[1]=new Nr(1,o,s)}};Cr.prototype.getArgGeometry=function(t){return this._arg[t].getGeometry()},Cr.prototype.setComputationPrecision=function(t){this._resultPrecisionModel=t,this._li.setPrecisionModel(this._resultPrecisionModel)},Cr.prototype.interfaces_=function(){return[]},Cr.prototype.getClass=function(){return Cr};var Sr=function(){};Sr.prototype.interfaces_=function(){return[]},Sr.prototype.getClass=function(){return Sr},Sr.map=function(){if(arguments[0]instanceof ct&&T(arguments[1],Sr.MapOp)){for(var t=arguments[0],e=arguments[1],n=new Nt,i=0;i=t.size()?null:t.get(e)},Dr.union=function(t){return new Dr(t).union()},Mr.STRTREE_NODE_CAPACITY.get=function(){return 4},Object.defineProperties(Dr,Mr);var Ar=function(){};Ar.prototype.interfaces_=function(){return[]},Ar.prototype.getClass=function(){return Ar},Ar.union=function(t,e){if(t.isEmpty()||e.isEmpty()){if(t.isEmpty()&&e.isEmpty())return Lr.createEmptyResult(Lr.UNION,t,e,t.getFactory());if(t.isEmpty())return e.copy();if(e.isEmpty())return t.copy()}return t.checkNotGeometryCollection(t),t.checkNotGeometryCollection(e),or.overlayOp(t,e,Lr.UNION)},t.GeoJSONReader=Ne,t.GeoJSONWriter=Ce,t.OverlayOp=Lr,t.UnionOp=Ar,t.BufferOp=di,Object.defineProperty(t,\"__esModule\",{value:!0})});\n","\"use strict\";\n\n// Note: This regex matches even invalid JSON strings, but since we’re\n// working on the output of `JSON.stringify` we know that only valid strings\n// are present (unless the user supplied a weird `options.indent` but in\n// that case we don’t care since the output would be invalid anyway).\nvar stringOrChar = /(\"(?:[^\\\\\"]|\\\\.)*\")|[:,]/g;\n\nmodule.exports = function stringify(passedObj, options) {\n var indent, maxLength, replacer;\n\n options = options || {};\n indent = JSON.stringify(\n [1],\n undefined,\n options.indent === undefined ? 2 : options.indent\n ).slice(2, -3);\n maxLength =\n indent === \"\"\n ? Infinity\n : options.maxLength === undefined\n ? 80\n : options.maxLength;\n replacer = options.replacer;\n\n return (function _stringify(obj, currentIndent, reserved) {\n // prettier-ignore\n var end, index, items, key, keyPart, keys, length, nextIndent, prettified, start, string, value;\n\n if (obj && typeof obj.toJSON === \"function\") {\n obj = obj.toJSON();\n }\n\n string = JSON.stringify(obj, replacer);\n\n if (string === undefined) {\n return string;\n }\n\n length = maxLength - currentIndent.length - reserved;\n\n if (string.length <= length) {\n prettified = string.replace(\n stringOrChar,\n function (match, stringLiteral) {\n return stringLiteral || match + \" \";\n }\n );\n if (prettified.length <= length) {\n return prettified;\n }\n }\n\n if (replacer != null) {\n obj = JSON.parse(string);\n replacer = undefined;\n }\n\n if (typeof obj === \"object\" && obj !== null) {\n nextIndent = currentIndent + indent;\n items = [];\n index = 0;\n\n if (Array.isArray(obj)) {\n start = \"[\";\n end = \"]\";\n length = obj.length;\n for (; index < length; index++) {\n items.push(\n _stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) ||\n \"null\"\n );\n }\n } else {\n start = \"{\";\n end = \"}\";\n keys = Object.keys(obj);\n length = keys.length;\n for (; index < length; index++) {\n key = keys[index];\n keyPart = JSON.stringify(key) + \": \";\n value = _stringify(\n obj[key],\n nextIndent,\n keyPart.length + (index === length - 1 ? 0 : 1)\n );\n if (value !== undefined) {\n items.push(keyPart + value);\n }\n }\n }\n\n if (items.length > 0) {\n return [start, indent + items.join(\",\\n\" + nextIndent), end].join(\n \"\\n\" + currentIndent\n );\n }\n }\n\n return string;\n })(passedObj, \"\", 0);\n};\n","import {MODULE_INJECTORS_VS, MODULE_INJECTORS_FS} from '../modules/module-injectors';\nimport {VERTEX_SHADER, FRAGMENT_SHADER} from './constants';\nimport {assert} from '../utils';\n\n// TODO - experimental\nconst MODULE_INJECTORS = {\n [VERTEX_SHADER]: MODULE_INJECTORS_VS,\n [FRAGMENT_SHADER]: MODULE_INJECTORS_FS\n};\n\nexport const DECLARATION_INJECT_MARKER = '__LUMA_INJECT_DECLARATIONS__'; // Uniform/attribute declarations\n\nconst REGEX_START_OF_MAIN = /void\\s+main\\s*\\([^)]*\\)\\s*\\{\\n?/; // Beginning of main\nconst REGEX_END_OF_MAIN = /}\\n?[^{}]*$/; // End of main, assumes main is last function\nconst fragments = [];\n\n// A minimal shader injection/templating system.\n// RFC: https://github.com/visgl/luma.gl/blob/7.0-release/dev-docs/RFCs/v6.0/shader-injection-rfc.md\n/* eslint-disable complexity */\nexport default function injectShader(source, type, inject, injectStandardStubs = false) {\n const isVertex = type === VERTEX_SHADER;\n\n for (const key in inject) {\n const fragmentData = inject[key];\n fragmentData.sort((a, b) => a.order - b.order);\n fragments.length = fragmentData.length;\n for (let i = 0, len = fragmentData.length; i < len; ++i) {\n fragments[i] = fragmentData[i].injection;\n }\n const fragmentString = `${fragments.join('\\n')}\\n`;\n switch (key) {\n // declarations are injected before the main function\n case 'vs:#decl':\n if (isVertex) {\n source = source.replace(DECLARATION_INJECT_MARKER, fragmentString);\n }\n break;\n // inject code at the beginning of the main function\n case 'vs:#main-start':\n if (isVertex) {\n source = source.replace(REGEX_START_OF_MAIN, match => match + fragmentString);\n }\n break;\n // inject code at the end of main function\n case 'vs:#main-end':\n if (isVertex) {\n source = source.replace(REGEX_END_OF_MAIN, match => fragmentString + match);\n }\n break;\n // declarations are injected before the main function\n case 'fs:#decl':\n if (!isVertex) {\n source = source.replace(DECLARATION_INJECT_MARKER, fragmentString);\n }\n break;\n // inject code at the beginning of the main function\n case 'fs:#main-start':\n if (!isVertex) {\n source = source.replace(REGEX_START_OF_MAIN, match => match + fragmentString);\n }\n break;\n // inject code at the end of main function\n case 'fs:#main-end':\n if (!isVertex) {\n source = source.replace(REGEX_END_OF_MAIN, match => fragmentString + match);\n }\n break;\n\n default:\n // TODO(Tarek): I think this usage should be deprecated.\n\n // inject code after key, leaving key in place\n source = source.replace(key, match => match + fragmentString);\n }\n }\n\n // Remove if it hasn't already been replaced\n source = source.replace(DECLARATION_INJECT_MARKER, '');\n\n // Finally, if requested, insert an automatic module injector chunk\n if (injectStandardStubs) {\n source = source.replace(/\\}\\s*$/, match => match + MODULE_INJECTORS[type]);\n }\n\n return source;\n}\n\n/* eslint-enable complexity */\n\n// Takes an array of inject objects and combines them into one\nexport function combineInjects(injects) {\n const result = {};\n assert(Array.isArray(injects) && injects.length > 1);\n injects.forEach(inject => {\n for (const key in inject) {\n result[key] = result[key] ? `${result[key]}\\n${inject[key]}` : inject[key];\n }\n });\n return result;\n}\n","export const MODULE_INJECTORS_VS = `\\\n#ifdef MODULE_LOGDEPTH\n logdepth_adjustPosition(gl_Position);\n#endif\n`;\n\nexport const MODULE_INJECTORS_FS = `\\\n#ifdef MODULE_MATERIAL\n gl_FragColor = material_filterColor(gl_FragColor);\n#endif\n\n#ifdef MODULE_LIGHTING\n gl_FragColor = lighting_filterColor(gl_FragColor);\n#endif\n\n#ifdef MODULE_FOG\n gl_FragColor = fog_filterColor(gl_FragColor);\n#endif\n\n#ifdef MODULE_PICKING\n gl_FragColor = picking_filterHighlightColor(gl_FragColor);\n gl_FragColor = picking_filterPickingColor(gl_FragColor);\n#endif\n\n#ifdef MODULE_LOGDEPTH\n logdepth_setFragDepth();\n#endif\n`;\n","import { Children, cloneElement, isValidElement } from 'react';\n/**\n * Given `this.props.children`, return an object mapping key to child.\n *\n * @param {*} children `this.props.children`\n * @return {object} Mapping of key to child\n */\n\nexport function getChildMapping(children, mapFn) {\n var mapper = function mapper(child) {\n return mapFn && isValidElement(child) ? mapFn(child) : child;\n };\n\n var result = Object.create(null);\n if (children) Children.map(children, function (c) {\n return c;\n }).forEach(function (child) {\n // run the map function here instead so that the key is the computed one\n result[child.key] = mapper(child);\n });\n return result;\n}\n/**\n * When you're adding or removing children some may be added or removed in the\n * same render pass. We want to show *both* since we want to simultaneously\n * animate elements in and out. This function takes a previous set of keys\n * and a new set of keys and merges them with its best guess of the correct\n * ordering. In the future we may expose some of the utilities in\n * ReactMultiChild to make this easy, but for now React itself does not\n * directly have this concept of the union of prevChildren and nextChildren\n * so we implement it here.\n *\n * @param {object} prev prev children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @param {object} next next children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @return {object} a key set that contains all keys in `prev` and all keys\n * in `next` in a reasonable order.\n */\n\nexport function mergeChildMappings(prev, next) {\n prev = prev || {};\n next = next || {};\n\n function getValueForKey(key) {\n return key in next ? next[key] : prev[key];\n } // For each key of `next`, the list of keys to insert before that key in\n // the combined list\n\n\n var nextKeysPending = Object.create(null);\n var pendingKeys = [];\n\n for (var prevKey in prev) {\n if (prevKey in next) {\n if (pendingKeys.length) {\n nextKeysPending[prevKey] = pendingKeys;\n pendingKeys = [];\n }\n } else {\n pendingKeys.push(prevKey);\n }\n }\n\n var i;\n var childMapping = {};\n\n for (var nextKey in next) {\n if (nextKeysPending[nextKey]) {\n for (i = 0; i < nextKeysPending[nextKey].length; i++) {\n var pendingNextKey = nextKeysPending[nextKey][i];\n childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);\n }\n }\n\n childMapping[nextKey] = getValueForKey(nextKey);\n } // Finally, add the keys which didn't appear before any key in `next`\n\n\n for (i = 0; i < pendingKeys.length; i++) {\n childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);\n }\n\n return childMapping;\n}\n\nfunction getProp(child, prop, props) {\n return props[prop] != null ? props[prop] : child.props[prop];\n}\n\nexport function getInitialChildMapping(props, onExited) {\n return getChildMapping(props.children, function (child) {\n return cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: true,\n appear: getProp(child, 'appear', props),\n enter: getProp(child, 'enter', props),\n exit: getProp(child, 'exit', props)\n });\n });\n}\nexport function getNextChildMapping(nextProps, prevChildMapping, onExited) {\n var nextChildMapping = getChildMapping(nextProps.children);\n var children = mergeChildMappings(prevChildMapping, nextChildMapping);\n Object.keys(children).forEach(function (key) {\n var child = children[key];\n if (!isValidElement(child)) return;\n var hasPrev = (key in prevChildMapping);\n var hasNext = (key in nextChildMapping);\n var prevChild = prevChildMapping[key];\n var isLeaving = isValidElement(prevChild) && !prevChild.props.in; // item is new (entering)\n\n if (hasNext && (!hasPrev || isLeaving)) {\n // console.log('entering', key)\n children[key] = cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: true,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n } else if (!hasNext && hasPrev && !isLeaving) {\n // item is old (exiting)\n // console.log('leaving', key)\n children[key] = cloneElement(child, {\n in: false\n });\n } else if (hasNext && hasPrev && isValidElement(prevChild)) {\n // item hasn't changed transition states\n // copy over the last transition props;\n // console.log('unchanged', key)\n children[key] = cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: prevChild.props.in,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n }\n });\n return children;\n}","import _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _assertThisInitialized from \"@babel/runtime/helpers/esm/assertThisInitialized\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport TransitionGroupContext from './TransitionGroupContext';\nimport { getChildMapping, getInitialChildMapping, getNextChildMapping } from './utils/ChildMapping';\n\nvar values = Object.values || function (obj) {\n return Object.keys(obj).map(function (k) {\n return obj[k];\n });\n};\n\nvar defaultProps = {\n component: 'div',\n childFactory: function childFactory(child) {\n return child;\n }\n};\n/**\n * The `` component manages a set of transition components\n * (`` and ``) in a list. Like with the transition\n * components, `` is a state machine for managing the mounting\n * and unmounting of components over time.\n *\n * Consider the example below. As items are removed or added to the TodoList the\n * `in` prop is toggled automatically by the ``.\n *\n * Note that `` does not define any animation behavior!\n * Exactly _how_ a list item animates is up to the individual transition\n * component. This means you can mix and match animations across different list\n * items.\n */\n\nvar TransitionGroup = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(TransitionGroup, _React$Component);\n\n function TransitionGroup(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n\n var handleExited = _this.handleExited.bind(_assertThisInitialized(_this)); // Initial children should all be entering, dependent on appear\n\n\n _this.state = {\n contextValue: {\n isMounting: true\n },\n handleExited: handleExited,\n firstRender: true\n };\n return _this;\n }\n\n var _proto = TransitionGroup.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this.mounted = true;\n this.setState({\n contextValue: {\n isMounting: false\n }\n });\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.mounted = false;\n };\n\n TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {\n var prevChildMapping = _ref.children,\n handleExited = _ref.handleExited,\n firstRender = _ref.firstRender;\n return {\n children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited),\n firstRender: false\n };\n } // node is `undefined` when user provided `nodeRef` prop\n ;\n\n _proto.handleExited = function handleExited(child, node) {\n var currentChildMapping = getChildMapping(this.props.children);\n if (child.key in currentChildMapping) return;\n\n if (child.props.onExited) {\n child.props.onExited(node);\n }\n\n if (this.mounted) {\n this.setState(function (state) {\n var children = _extends({}, state.children);\n\n delete children[child.key];\n return {\n children: children\n };\n });\n }\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n Component = _this$props.component,\n childFactory = _this$props.childFactory,\n props = _objectWithoutPropertiesLoose(_this$props, [\"component\", \"childFactory\"]);\n\n var contextValue = this.state.contextValue;\n var children = values(this.state.children).map(childFactory);\n delete props.appear;\n delete props.enter;\n delete props.exit;\n\n if (Component === null) {\n return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {\n value: contextValue\n }, children);\n }\n\n return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {\n value: contextValue\n }, /*#__PURE__*/React.createElement(Component, props, children));\n };\n\n return TransitionGroup;\n}(React.Component);\n\nTransitionGroup.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * `` renders a `
` by default. You can change this\n * behavior by providing a `component` prop.\n * If you use React v16+ and would like to avoid a wrapping `
` element\n * you can pass in `component={null}`. This is useful if the wrapping div\n * borks your css styles.\n */\n component: PropTypes.any,\n\n /**\n * A set of `` components, that are toggled `in` and out as they\n * leave. the `` will inject specific transition props, so\n * remember to spread them through if you are wrapping the `` as\n * with our `` example.\n *\n * While this component is meant for multiple `Transition` or `CSSTransition`\n * children, sometimes you may want to have a single transition child with\n * content that you want to be transitioned out and in when you change it\n * (e.g. routes, images etc.) In that case you can change the `key` prop of\n * the transition child as you change its content, this will cause\n * `TransitionGroup` to transition the child out and back in.\n */\n children: PropTypes.node,\n\n /**\n * A convenience prop that enables or disables appear animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n appear: PropTypes.bool,\n\n /**\n * A convenience prop that enables or disables enter animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * A convenience prop that enables or disables exit animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * You may need to apply reactive updates to a child as it is exiting.\n * This is generally done by using `cloneElement` however in the case of an exiting\n * child the element has already been removed and not accessible to the consumer.\n *\n * If you do need to update a child as it leaves you can provide a `childFactory`\n * to wrap every child, even the ones that are leaving.\n *\n * @type Function(child: ReactElement) -> ReactElement\n */\n childFactory: PropTypes.func\n} : {};\nTransitionGroup.defaultProps = defaultProps;\nexport default TransitionGroup;","import * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport useEventCallback from '../utils/useEventCallback';\nvar useEnhancedEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;\n/**\n * @ignore - internal component.\n */\n\nfunction Ripple(props) {\n var classes = props.classes,\n _props$pulsate = props.pulsate,\n pulsate = _props$pulsate === void 0 ? false : _props$pulsate,\n rippleX = props.rippleX,\n rippleY = props.rippleY,\n rippleSize = props.rippleSize,\n inProp = props.in,\n _props$onExited = props.onExited,\n onExited = _props$onExited === void 0 ? function () {} : _props$onExited,\n timeout = props.timeout;\n\n var _React$useState = React.useState(false),\n leaving = _React$useState[0],\n setLeaving = _React$useState[1];\n\n var rippleClassName = clsx(classes.ripple, classes.rippleVisible, pulsate && classes.ripplePulsate);\n var rippleStyles = {\n width: rippleSize,\n height: rippleSize,\n top: -(rippleSize / 2) + rippleY,\n left: -(rippleSize / 2) + rippleX\n };\n var childClassName = clsx(classes.child, leaving && classes.childLeaving, pulsate && classes.childPulsate);\n var handleExited = useEventCallback(onExited); // Ripple is used for user feedback (e.g. click or press) so we want to apply styles with the highest priority\n\n useEnhancedEffect(function () {\n if (!inProp) {\n // react-transition-group#onExit\n setLeaving(true); // react-transition-group#onExited\n\n var timeoutId = setTimeout(handleExited, timeout);\n return function () {\n clearTimeout(timeoutId);\n };\n }\n\n return undefined;\n }, [handleExited, inProp, timeout]);\n return /*#__PURE__*/React.createElement(\"span\", {\n className: rippleClassName,\n style: rippleStyles\n }, /*#__PURE__*/React.createElement(\"span\", {\n className: childClassName\n }));\n}\n\nprocess.env.NODE_ENV !== \"production\" ? Ripple.propTypes = {\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore - injected from TransitionGroup\n */\n in: PropTypes.bool,\n\n /**\n * @ignore - injected from TransitionGroup\n */\n onExited: PropTypes.func,\n\n /**\n * If `true`, the ripple pulsates, typically indicating the keyboard focus state of an element.\n */\n pulsate: PropTypes.bool,\n\n /**\n * Diameter of the ripple.\n */\n rippleSize: PropTypes.number,\n\n /**\n * Horizontal position of the ripple center.\n */\n rippleX: PropTypes.number,\n\n /**\n * Vertical position of the ripple center.\n */\n rippleY: PropTypes.number,\n\n /**\n * exit delay\n */\n timeout: PropTypes.number.isRequired\n} : void 0;\nexport default Ripple;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { TransitionGroup } from 'react-transition-group';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport Ripple from './Ripple';\nvar DURATION = 550;\nexport var DELAY_RIPPLE = 80;\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n overflow: 'hidden',\n pointerEvents: 'none',\n position: 'absolute',\n zIndex: 0,\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n borderRadius: 'inherit'\n },\n\n /* Styles applied to the internal `Ripple` components `ripple` class. */\n ripple: {\n opacity: 0,\n position: 'absolute'\n },\n\n /* Styles applied to the internal `Ripple` components `rippleVisible` class. */\n rippleVisible: {\n opacity: 0.3,\n transform: 'scale(1)',\n animation: \"$enter \".concat(DURATION, \"ms \").concat(theme.transitions.easing.easeInOut)\n },\n\n /* Styles applied to the internal `Ripple` components `ripplePulsate` class. */\n ripplePulsate: {\n animationDuration: \"\".concat(theme.transitions.duration.shorter, \"ms\")\n },\n\n /* Styles applied to the internal `Ripple` components `child` class. */\n child: {\n opacity: 1,\n display: 'block',\n width: '100%',\n height: '100%',\n borderRadius: '50%',\n backgroundColor: 'currentColor'\n },\n\n /* Styles applied to the internal `Ripple` components `childLeaving` class. */\n childLeaving: {\n opacity: 0,\n animation: \"$exit \".concat(DURATION, \"ms \").concat(theme.transitions.easing.easeInOut)\n },\n\n /* Styles applied to the internal `Ripple` components `childPulsate` class. */\n childPulsate: {\n position: 'absolute',\n left: 0,\n top: 0,\n animation: \"$pulsate 2500ms \".concat(theme.transitions.easing.easeInOut, \" 200ms infinite\")\n },\n '@keyframes enter': {\n '0%': {\n transform: 'scale(0)',\n opacity: 0.1\n },\n '100%': {\n transform: 'scale(1)',\n opacity: 0.3\n }\n },\n '@keyframes exit': {\n '0%': {\n opacity: 1\n },\n '100%': {\n opacity: 0\n }\n },\n '@keyframes pulsate': {\n '0%': {\n transform: 'scale(1)'\n },\n '50%': {\n transform: 'scale(0.92)'\n },\n '100%': {\n transform: 'scale(1)'\n }\n }\n };\n};\n/**\n * @ignore - internal component.\n *\n * TODO v5: Make private\n */\n\nvar TouchRipple = /*#__PURE__*/React.forwardRef(function TouchRipple(props, ref) {\n var _props$center = props.center,\n centerProp = _props$center === void 0 ? false : _props$center,\n classes = props.classes,\n className = props.className,\n other = _objectWithoutProperties(props, [\"center\", \"classes\", \"className\"]);\n\n var _React$useState = React.useState([]),\n ripples = _React$useState[0],\n setRipples = _React$useState[1];\n\n var nextKey = React.useRef(0);\n var rippleCallback = React.useRef(null);\n React.useEffect(function () {\n if (rippleCallback.current) {\n rippleCallback.current();\n rippleCallback.current = null;\n }\n }, [ripples]); // Used to filter out mouse emulated events on mobile.\n\n var ignoringMouseDown = React.useRef(false); // We use a timer in order to only show the ripples for touch \"click\" like events.\n // We don't want to display the ripple for touch scroll events.\n\n var startTimer = React.useRef(null); // This is the hook called once the previous timeout is ready.\n\n var startTimerCommit = React.useRef(null);\n var container = React.useRef(null);\n React.useEffect(function () {\n return function () {\n clearTimeout(startTimer.current);\n };\n }, []);\n var startCommit = React.useCallback(function (params) {\n var pulsate = params.pulsate,\n rippleX = params.rippleX,\n rippleY = params.rippleY,\n rippleSize = params.rippleSize,\n cb = params.cb;\n setRipples(function (oldRipples) {\n return [].concat(_toConsumableArray(oldRipples), [/*#__PURE__*/React.createElement(Ripple, {\n key: nextKey.current,\n classes: classes,\n timeout: DURATION,\n pulsate: pulsate,\n rippleX: rippleX,\n rippleY: rippleY,\n rippleSize: rippleSize\n })]);\n });\n nextKey.current += 1;\n rippleCallback.current = cb;\n }, [classes]);\n var start = React.useCallback(function () {\n var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var cb = arguments.length > 2 ? arguments[2] : undefined;\n var _options$pulsate = options.pulsate,\n pulsate = _options$pulsate === void 0 ? false : _options$pulsate,\n _options$center = options.center,\n center = _options$center === void 0 ? centerProp || options.pulsate : _options$center,\n _options$fakeElement = options.fakeElement,\n fakeElement = _options$fakeElement === void 0 ? false : _options$fakeElement;\n\n if (event.type === 'mousedown' && ignoringMouseDown.current) {\n ignoringMouseDown.current = false;\n return;\n }\n\n if (event.type === 'touchstart') {\n ignoringMouseDown.current = true;\n }\n\n var element = fakeElement ? null : container.current;\n var rect = element ? element.getBoundingClientRect() : {\n width: 0,\n height: 0,\n left: 0,\n top: 0\n }; // Get the size of the ripple\n\n var rippleX;\n var rippleY;\n var rippleSize;\n\n if (center || event.clientX === 0 && event.clientY === 0 || !event.clientX && !event.touches) {\n rippleX = Math.round(rect.width / 2);\n rippleY = Math.round(rect.height / 2);\n } else {\n var _ref = event.touches ? event.touches[0] : event,\n clientX = _ref.clientX,\n clientY = _ref.clientY;\n\n rippleX = Math.round(clientX - rect.left);\n rippleY = Math.round(clientY - rect.top);\n }\n\n if (center) {\n rippleSize = Math.sqrt((2 * Math.pow(rect.width, 2) + Math.pow(rect.height, 2)) / 3); // For some reason the animation is broken on Mobile Chrome if the size if even.\n\n if (rippleSize % 2 === 0) {\n rippleSize += 1;\n }\n } else {\n var sizeX = Math.max(Math.abs((element ? element.clientWidth : 0) - rippleX), rippleX) * 2 + 2;\n var sizeY = Math.max(Math.abs((element ? element.clientHeight : 0) - rippleY), rippleY) * 2 + 2;\n rippleSize = Math.sqrt(Math.pow(sizeX, 2) + Math.pow(sizeY, 2));\n } // Touche devices\n\n\n if (event.touches) {\n // check that this isn't another touchstart due to multitouch\n // otherwise we will only clear a single timer when unmounting while two\n // are running\n if (startTimerCommit.current === null) {\n // Prepare the ripple effect.\n startTimerCommit.current = function () {\n startCommit({\n pulsate: pulsate,\n rippleX: rippleX,\n rippleY: rippleY,\n rippleSize: rippleSize,\n cb: cb\n });\n }; // Delay the execution of the ripple effect.\n\n\n startTimer.current = setTimeout(function () {\n if (startTimerCommit.current) {\n startTimerCommit.current();\n startTimerCommit.current = null;\n }\n }, DELAY_RIPPLE); // We have to make a tradeoff with this value.\n }\n } else {\n startCommit({\n pulsate: pulsate,\n rippleX: rippleX,\n rippleY: rippleY,\n rippleSize: rippleSize,\n cb: cb\n });\n }\n }, [centerProp, startCommit]);\n var pulsate = React.useCallback(function () {\n start({}, {\n pulsate: true\n });\n }, [start]);\n var stop = React.useCallback(function (event, cb) {\n clearTimeout(startTimer.current); // The touch interaction occurs too quickly.\n // We still want to show ripple effect.\n\n if (event.type === 'touchend' && startTimerCommit.current) {\n event.persist();\n startTimerCommit.current();\n startTimerCommit.current = null;\n startTimer.current = setTimeout(function () {\n stop(event, cb);\n });\n return;\n }\n\n startTimerCommit.current = null;\n setRipples(function (oldRipples) {\n if (oldRipples.length > 0) {\n return oldRipples.slice(1);\n }\n\n return oldRipples;\n });\n rippleCallback.current = cb;\n }, []);\n React.useImperativeHandle(ref, function () {\n return {\n pulsate: pulsate,\n start: start,\n stop: stop\n };\n }, [pulsate, start, stop]);\n return /*#__PURE__*/React.createElement(\"span\", _extends({\n className: clsx(classes.root, className),\n ref: container\n }, other), /*#__PURE__*/React.createElement(TransitionGroup, {\n component: null,\n exit: true\n }, ripples));\n});\nprocess.env.NODE_ENV !== \"production\" ? TouchRipple.propTypes = {\n /**\n * If `true`, the ripple starts at the center of the component\n * rather than at the point of interaction.\n */\n center: PropTypes.bool,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string\n} : void 0;\nexport default withStyles(styles, {\n flip: false,\n name: 'MuiTouchRipple'\n})( /*#__PURE__*/React.memo(TouchRipple));","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport * as ReactDOM from 'react-dom';\nimport clsx from 'clsx';\nimport { elementTypeAcceptingRef, refType } from '@material-ui/utils';\nimport useForkRef from '../utils/useForkRef';\nimport useEventCallback from '../utils/useEventCallback';\nimport deprecatedPropType from '../utils/deprecatedPropType';\nimport withStyles from '../styles/withStyles';\nimport useIsFocusVisible from '../utils/useIsFocusVisible';\nimport TouchRipple from './TouchRipple';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n position: 'relative',\n WebkitTapHighlightColor: 'transparent',\n backgroundColor: 'transparent',\n // Reset default value\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0,\n border: 0,\n margin: 0,\n // Remove the margin in Safari\n borderRadius: 0,\n padding: 0,\n // Remove the padding in Firefox\n cursor: 'pointer',\n userSelect: 'none',\n verticalAlign: 'middle',\n '-moz-appearance': 'none',\n // Reset\n '-webkit-appearance': 'none',\n // Reset\n textDecoration: 'none',\n // So we take precedent over the style of a native element.\n color: 'inherit',\n '&::-moz-focus-inner': {\n borderStyle: 'none' // Remove Firefox dotted outline.\n\n },\n '&$disabled': {\n pointerEvents: 'none',\n // Disable link interactions\n cursor: 'default'\n },\n '@media print': {\n colorAdjust: 'exact'\n }\n },\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Pseudo-class applied to the root element if keyboard focused. */\n focusVisible: {}\n};\n/**\n * `ButtonBase` contains as few styles as possible.\n * It aims to be a simple building block for creating a button.\n * It contains a load of style reset and some focus/ripple logic.\n */\n\nvar ButtonBase = /*#__PURE__*/React.forwardRef(function ButtonBase(props, ref) {\n var action = props.action,\n buttonRefProp = props.buttonRef,\n _props$centerRipple = props.centerRipple,\n centerRipple = _props$centerRipple === void 0 ? false : _props$centerRipple,\n children = props.children,\n classes = props.classes,\n className = props.className,\n _props$component = props.component,\n component = _props$component === void 0 ? 'button' : _props$component,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$disableRipple = props.disableRipple,\n disableRipple = _props$disableRipple === void 0 ? false : _props$disableRipple,\n _props$disableTouchRi = props.disableTouchRipple,\n disableTouchRipple = _props$disableTouchRi === void 0 ? false : _props$disableTouchRi,\n _props$focusRipple = props.focusRipple,\n focusRipple = _props$focusRipple === void 0 ? false : _props$focusRipple,\n focusVisibleClassName = props.focusVisibleClassName,\n onBlur = props.onBlur,\n onClick = props.onClick,\n onFocus = props.onFocus,\n onFocusVisible = props.onFocusVisible,\n onKeyDown = props.onKeyDown,\n onKeyUp = props.onKeyUp,\n onMouseDown = props.onMouseDown,\n onMouseLeave = props.onMouseLeave,\n onMouseUp = props.onMouseUp,\n onTouchEnd = props.onTouchEnd,\n onTouchMove = props.onTouchMove,\n onTouchStart = props.onTouchStart,\n onDragLeave = props.onDragLeave,\n _props$tabIndex = props.tabIndex,\n tabIndex = _props$tabIndex === void 0 ? 0 : _props$tabIndex,\n TouchRippleProps = props.TouchRippleProps,\n _props$type = props.type,\n type = _props$type === void 0 ? 'button' : _props$type,\n other = _objectWithoutProperties(props, [\"action\", \"buttonRef\", \"centerRipple\", \"children\", \"classes\", \"className\", \"component\", \"disabled\", \"disableRipple\", \"disableTouchRipple\", \"focusRipple\", \"focusVisibleClassName\", \"onBlur\", \"onClick\", \"onFocus\", \"onFocusVisible\", \"onKeyDown\", \"onKeyUp\", \"onMouseDown\", \"onMouseLeave\", \"onMouseUp\", \"onTouchEnd\", \"onTouchMove\", \"onTouchStart\", \"onDragLeave\", \"tabIndex\", \"TouchRippleProps\", \"type\"]);\n\n var buttonRef = React.useRef(null);\n\n function getButtonNode() {\n // #StrictMode ready\n return ReactDOM.findDOMNode(buttonRef.current);\n }\n\n var rippleRef = React.useRef(null);\n\n var _React$useState = React.useState(false),\n focusVisible = _React$useState[0],\n setFocusVisible = _React$useState[1];\n\n if (disabled && focusVisible) {\n setFocusVisible(false);\n }\n\n var _useIsFocusVisible = useIsFocusVisible(),\n isFocusVisible = _useIsFocusVisible.isFocusVisible,\n onBlurVisible = _useIsFocusVisible.onBlurVisible,\n focusVisibleRef = _useIsFocusVisible.ref;\n\n React.useImperativeHandle(action, function () {\n return {\n focusVisible: function focusVisible() {\n setFocusVisible(true);\n buttonRef.current.focus();\n }\n };\n }, []);\n React.useEffect(function () {\n if (focusVisible && focusRipple && !disableRipple) {\n rippleRef.current.pulsate();\n }\n }, [disableRipple, focusRipple, focusVisible]);\n\n function useRippleHandler(rippleAction, eventCallback) {\n var skipRippleAction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : disableTouchRipple;\n return useEventCallback(function (event) {\n if (eventCallback) {\n eventCallback(event);\n }\n\n var ignore = skipRippleAction;\n\n if (!ignore && rippleRef.current) {\n rippleRef.current[rippleAction](event);\n }\n\n return true;\n });\n }\n\n var handleMouseDown = useRippleHandler('start', onMouseDown);\n var handleDragLeave = useRippleHandler('stop', onDragLeave);\n var handleMouseUp = useRippleHandler('stop', onMouseUp);\n var handleMouseLeave = useRippleHandler('stop', function (event) {\n if (focusVisible) {\n event.preventDefault();\n }\n\n if (onMouseLeave) {\n onMouseLeave(event);\n }\n });\n var handleTouchStart = useRippleHandler('start', onTouchStart);\n var handleTouchEnd = useRippleHandler('stop', onTouchEnd);\n var handleTouchMove = useRippleHandler('stop', onTouchMove);\n var handleBlur = useRippleHandler('stop', function (event) {\n if (focusVisible) {\n onBlurVisible(event);\n setFocusVisible(false);\n }\n\n if (onBlur) {\n onBlur(event);\n }\n }, false);\n var handleFocus = useEventCallback(function (event) {\n // Fix for https://github.com/facebook/react/issues/7769\n if (!buttonRef.current) {\n buttonRef.current = event.currentTarget;\n }\n\n if (isFocusVisible(event)) {\n setFocusVisible(true);\n\n if (onFocusVisible) {\n onFocusVisible(event);\n }\n }\n\n if (onFocus) {\n onFocus(event);\n }\n });\n\n var isNonNativeButton = function isNonNativeButton() {\n var button = getButtonNode();\n return component && component !== 'button' && !(button.tagName === 'A' && button.href);\n };\n /**\n * IE 11 shim for https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat\n */\n\n\n var keydownRef = React.useRef(false);\n var handleKeyDown = useEventCallback(function (event) {\n // Check if key is already down to avoid repeats being counted as multiple activations\n if (focusRipple && !keydownRef.current && focusVisible && rippleRef.current && event.key === ' ') {\n keydownRef.current = true;\n event.persist();\n rippleRef.current.stop(event, function () {\n rippleRef.current.start(event);\n });\n }\n\n if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') {\n event.preventDefault();\n }\n\n if (onKeyDown) {\n onKeyDown(event);\n } // Keyboard accessibility for non interactive elements\n\n\n if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter' && !disabled) {\n event.preventDefault();\n\n if (onClick) {\n onClick(event);\n }\n }\n });\n var handleKeyUp = useEventCallback(function (event) {\n // calling preventDefault in keyUp on a \n *
\n * );\n * }\n * ```\n *\n * When the button is clicked the component will shift to the `'entering'` state\n * and stay there for 500ms (the value of `timeout`) before it finally switches\n * to `'entered'`.\n *\n * When `in` is `false` the same thing happens except the state moves from\n * `'exiting'` to `'exited'`.\n */\n\nvar Transition = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(Transition, _React$Component);\n\n function Transition(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n var parentGroup = context; // In the context of a TransitionGroup all enters are really appears\n\n var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;\n var initialStatus;\n _this.appearStatus = null;\n\n if (props.in) {\n if (appear) {\n initialStatus = EXITED;\n _this.appearStatus = ENTERING;\n } else {\n initialStatus = ENTERED;\n }\n } else {\n if (props.unmountOnExit || props.mountOnEnter) {\n initialStatus = UNMOUNTED;\n } else {\n initialStatus = EXITED;\n }\n }\n\n _this.state = {\n status: initialStatus\n };\n _this.nextCallback = null;\n return _this;\n }\n\n Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {\n var nextIn = _ref.in;\n\n if (nextIn && prevState.status === UNMOUNTED) {\n return {\n status: EXITED\n };\n }\n\n return null;\n } // getSnapshotBeforeUpdate(prevProps) {\n // let nextStatus = null\n // if (prevProps !== this.props) {\n // const { status } = this.state\n // if (this.props.in) {\n // if (status !== ENTERING && status !== ENTERED) {\n // nextStatus = ENTERING\n // }\n // } else {\n // if (status === ENTERING || status === ENTERED) {\n // nextStatus = EXITING\n // }\n // }\n // }\n // return { nextStatus }\n // }\n ;\n\n var _proto = Transition.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this.updateStatus(true, this.appearStatus);\n };\n\n _proto.componentDidUpdate = function componentDidUpdate(prevProps) {\n var nextStatus = null;\n\n if (prevProps !== this.props) {\n var status = this.state.status;\n\n if (this.props.in) {\n if (status !== ENTERING && status !== ENTERED) {\n nextStatus = ENTERING;\n }\n } else {\n if (status === ENTERING || status === ENTERED) {\n nextStatus = EXITING;\n }\n }\n }\n\n this.updateStatus(false, nextStatus);\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.cancelNextCallback();\n };\n\n _proto.getTimeouts = function getTimeouts() {\n var timeout = this.props.timeout;\n var exit, enter, appear;\n exit = enter = appear = timeout;\n\n if (timeout != null && typeof timeout !== 'number') {\n exit = timeout.exit;\n enter = timeout.enter; // TODO: remove fallback for next major\n\n appear = timeout.appear !== undefined ? timeout.appear : enter;\n }\n\n return {\n exit: exit,\n enter: enter,\n appear: appear\n };\n };\n\n _proto.updateStatus = function updateStatus(mounting, nextStatus) {\n if (mounting === void 0) {\n mounting = false;\n }\n\n if (nextStatus !== null) {\n // nextStatus will always be ENTERING or EXITING.\n this.cancelNextCallback();\n\n if (nextStatus === ENTERING) {\n this.performEnter(mounting);\n } else {\n this.performExit();\n }\n } else if (this.props.unmountOnExit && this.state.status === EXITED) {\n this.setState({\n status: UNMOUNTED\n });\n }\n };\n\n _proto.performEnter = function performEnter(mounting) {\n var _this2 = this;\n\n var enter = this.props.enter;\n var appearing = this.context ? this.context.isMounting : mounting;\n\n var _ref2 = this.props.nodeRef ? [appearing] : [ReactDOM.findDOMNode(this), appearing],\n maybeNode = _ref2[0],\n maybeAppearing = _ref2[1];\n\n var timeouts = this.getTimeouts();\n var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED\n // if we are mounting and running this it means appear _must_ be set\n\n if (!mounting && !enter || config.disabled) {\n this.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode);\n });\n return;\n }\n\n this.props.onEnter(maybeNode, maybeAppearing);\n this.safeSetState({\n status: ENTERING\n }, function () {\n _this2.props.onEntering(maybeNode, maybeAppearing);\n\n _this2.onTransitionEnd(enterTimeout, function () {\n _this2.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode, maybeAppearing);\n });\n });\n });\n };\n\n _proto.performExit = function performExit() {\n var _this3 = this;\n\n var exit = this.props.exit;\n var timeouts = this.getTimeouts();\n var maybeNode = this.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); // no exit animation skip right to EXITED\n\n if (!exit || config.disabled) {\n this.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n return;\n }\n\n this.props.onExit(maybeNode);\n this.safeSetState({\n status: EXITING\n }, function () {\n _this3.props.onExiting(maybeNode);\n\n _this3.onTransitionEnd(timeouts.exit, function () {\n _this3.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n });\n });\n };\n\n _proto.cancelNextCallback = function cancelNextCallback() {\n if (this.nextCallback !== null) {\n this.nextCallback.cancel();\n this.nextCallback = null;\n }\n };\n\n _proto.safeSetState = function safeSetState(nextState, callback) {\n // This shouldn't be necessary, but there are weird race conditions with\n // setState callbacks and unmounting in testing, so always make sure that\n // we can cancel any pending setState callbacks after we unmount.\n callback = this.setNextCallback(callback);\n this.setState(nextState, callback);\n };\n\n _proto.setNextCallback = function setNextCallback(callback) {\n var _this4 = this;\n\n var active = true;\n\n this.nextCallback = function (event) {\n if (active) {\n active = false;\n _this4.nextCallback = null;\n callback(event);\n }\n };\n\n this.nextCallback.cancel = function () {\n active = false;\n };\n\n return this.nextCallback;\n };\n\n _proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {\n this.setNextCallback(handler);\n var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this);\n var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;\n\n if (!node || doesNotHaveTimeoutOrListener) {\n setTimeout(this.nextCallback, 0);\n return;\n }\n\n if (this.props.addEndListener) {\n var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],\n maybeNode = _ref3[0],\n maybeNextCallback = _ref3[1];\n\n this.props.addEndListener(maybeNode, maybeNextCallback);\n }\n\n if (timeout != null) {\n setTimeout(this.nextCallback, timeout);\n }\n };\n\n _proto.render = function render() {\n var status = this.state.status;\n\n if (status === UNMOUNTED) {\n return null;\n }\n\n var _this$props = this.props,\n children = _this$props.children,\n _in = _this$props.in,\n _mountOnEnter = _this$props.mountOnEnter,\n _unmountOnExit = _this$props.unmountOnExit,\n _appear = _this$props.appear,\n _enter = _this$props.enter,\n _exit = _this$props.exit,\n _timeout = _this$props.timeout,\n _addEndListener = _this$props.addEndListener,\n _onEnter = _this$props.onEnter,\n _onEntering = _this$props.onEntering,\n _onEntered = _this$props.onEntered,\n _onExit = _this$props.onExit,\n _onExiting = _this$props.onExiting,\n _onExited = _this$props.onExited,\n _nodeRef = _this$props.nodeRef,\n childProps = _objectWithoutPropertiesLoose(_this$props, [\"children\", \"in\", \"mountOnEnter\", \"unmountOnExit\", \"appear\", \"enter\", \"exit\", \"timeout\", \"addEndListener\", \"onEnter\", \"onEntering\", \"onEntered\", \"onExit\", \"onExiting\", \"onExited\", \"nodeRef\"]);\n\n return (\n /*#__PURE__*/\n // allows for nested Transitions\n React.createElement(TransitionGroupContext.Provider, {\n value: null\n }, typeof children === 'function' ? children(status, childProps) : React.cloneElement(React.Children.only(children), childProps))\n );\n };\n\n return Transition;\n}(React.Component);\n\nTransition.contextType = TransitionGroupContext;\nTransition.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * A React reference to DOM element that need to transition:\n * https://stackoverflow.com/a/51127130/4671932\n *\n * - When `nodeRef` prop is used, `node` is not passed to callback functions\n * (e.g. `onEnter`) because user already has direct access to the node.\n * - When changing `key` prop of `Transition` in a `TransitionGroup` a new\n * `nodeRef` need to be provided to `Transition` with changed `key` prop\n * (see\n * [test/CSSTransition-test.js](https://github.com/reactjs/react-transition-group/blob/13435f897b3ab71f6e19d724f145596f5910581c/test/CSSTransition-test.js#L362-L437)).\n */\n nodeRef: PropTypes.shape({\n current: typeof Element === 'undefined' ? PropTypes.any : function (propValue, key, componentName, location, propFullName, secret) {\n var value = propValue[key];\n return PropTypes.instanceOf(value && 'ownerDocument' in value ? value.ownerDocument.defaultView.Element : Element)(propValue, key, componentName, location, propFullName, secret);\n }\n }),\n\n /**\n * A `function` child can be used instead of a React element. This function is\n * called with the current transition status (`'entering'`, `'entered'`,\n * `'exiting'`, `'exited'`), which can be used to apply context\n * specific props to a component.\n *\n * ```jsx\n * \n * {state => (\n * \n * )}\n * \n * ```\n */\n children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,\n\n /**\n * Show the component; triggers the enter or exit states\n */\n in: PropTypes.bool,\n\n /**\n * By default the child component is mounted immediately along with\n * the parent `Transition` component. If you want to \"lazy mount\" the component on the\n * first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay\n * mounted, even on \"exited\", unless you also specify `unmountOnExit`.\n */\n mountOnEnter: PropTypes.bool,\n\n /**\n * By default the child component stays mounted after it reaches the `'exited'` state.\n * Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.\n */\n unmountOnExit: PropTypes.bool,\n\n /**\n * By default the child component does not perform the enter transition when\n * it first mounts, regardless of the value of `in`. If you want this\n * behavior, set both `appear` and `in` to `true`.\n *\n * > **Note**: there are no special appear states like `appearing`/`appeared`, this prop\n * > only adds an additional enter transition. However, in the\n * > `` component that first enter transition does result in\n * > additional `.appear-*` classes, that way you can choose to style it\n * > differently.\n */\n appear: PropTypes.bool,\n\n /**\n * Enable or disable enter transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * Enable or disable exit transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * The duration of the transition, in milliseconds.\n * Required unless `addEndListener` is provided.\n *\n * You may specify a single timeout for all transitions:\n *\n * ```jsx\n * timeout={500}\n * ```\n *\n * or individually:\n *\n * ```jsx\n * timeout={{\n * appear: 500,\n * enter: 300,\n * exit: 500,\n * }}\n * ```\n *\n * - `appear` defaults to the value of `enter`\n * - `enter` defaults to `0`\n * - `exit` defaults to `0`\n *\n * @type {number | { enter?: number, exit?: number, appear?: number }}\n */\n timeout: function timeout(props) {\n var pt = timeoutsShape;\n if (!props.addEndListener) pt = pt.isRequired;\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return pt.apply(void 0, [props].concat(args));\n },\n\n /**\n * Add a custom transition end trigger. Called with the transitioning\n * DOM node and a `done` callback. Allows for more fine grained transition end\n * logic. Timeouts are still used as a fallback if provided.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * ```jsx\n * addEndListener={(node, done) => {\n * // use the css transitionend event to mark the finish of a transition\n * node.addEventListener('transitionend', done, false);\n * }}\n * ```\n */\n addEndListener: PropTypes.func,\n\n /**\n * Callback fired before the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEnter: PropTypes.func,\n\n /**\n * Callback fired after the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntering: PropTypes.func,\n\n /**\n * Callback fired after the \"entered\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEntered: PropTypes.func,\n\n /**\n * Callback fired before the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExit: PropTypes.func,\n\n /**\n * Callback fired after the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExiting: PropTypes.func,\n\n /**\n * Callback fired after the \"exited\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExited: PropTypes.func\n} : {}; // Name the function so it is clearer in the documentation\n\nfunction noop() {}\n\nTransition.defaultProps = {\n in: false,\n mountOnEnter: false,\n unmountOnExit: false,\n appear: false,\n enter: true,\n exit: true,\n onEnter: noop,\n onEntering: noop,\n onEntered: noop,\n onExit: noop,\n onExiting: noop,\n onExited: noop\n};\nTransition.UNMOUNTED = UNMOUNTED;\nTransition.EXITED = EXITED;\nTransition.ENTERING = ENTERING;\nTransition.ENTERED = ENTERED;\nTransition.EXITING = EXITING;\nexport default Transition;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport { makeStyles as makeStylesWithoutDefault } from '@material-ui/styles';\nimport defaultTheme from './defaultTheme';\n\nfunction makeStyles(stylesOrCreator) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return makeStylesWithoutDefault(stylesOrCreator, _extends({\n defaultTheme: defaultTheme\n }, options));\n}\n\nexport default makeStyles;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport { getDisplayName } from '@material-ui/utils';\nexport default function mergeClasses() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var baseClasses = options.baseClasses,\n newClasses = options.newClasses,\n Component = options.Component;\n\n if (!newClasses) {\n return baseClasses;\n }\n\n var nextClasses = _extends({}, baseClasses);\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof newClasses === 'string') {\n console.error([\"Material-UI: The value `\".concat(newClasses, \"` \") + \"provided to the classes prop of \".concat(getDisplayName(Component), \" is incorrect.\"), 'You might want to use the className prop instead.'].join('\\n'));\n return baseClasses;\n }\n }\n\n Object.keys(newClasses).forEach(function (key) {\n if (process.env.NODE_ENV !== 'production') {\n if (!baseClasses[key] && newClasses[key]) {\n console.error([\"Material-UI: The key `\".concat(key, \"` \") + \"provided to the classes prop is not implemented in \".concat(getDisplayName(Component), \".\"), \"You can only override one of the following: \".concat(Object.keys(baseClasses).join(','), \".\")].join('\\n'));\n }\n\n if (newClasses[key] && typeof newClasses[key] !== 'string') {\n console.error([\"Material-UI: The key `\".concat(key, \"` \") + \"provided to the classes prop is not valid for \".concat(getDisplayName(Component), \".\"), \"You need to provide a non empty string instead of: \".concat(newClasses[key], \".\")].join('\\n'));\n }\n }\n\n if (newClasses[key]) {\n nextClasses[key] = \"\".concat(baseClasses[key], \" \").concat(newClasses[key]);\n }\n });\n return nextClasses;\n}","import nested from '../ThemeProvider/nested';\n/**\n * This is the list of the style rule name we use as drop in replacement for the built-in\n * pseudo classes (:checked, :disabled, :focused, etc.).\n *\n * Why do they exist in the first place?\n * These classes are used at a specificity of 2.\n * It allows them to override previously definied styles as well as\n * being untouched by simple user overrides.\n */\n\nvar pseudoClasses = ['checked', 'disabled', 'error', 'focused', 'focusVisible', 'required', 'expanded', 'selected']; // Returns a function which generates unique class names based on counters.\n// When new generator function is created, rule counter is reset.\n// We need to reset the rule counter for SSR for each request.\n//\n// It's inspired by\n// https://github.com/cssinjs/jss/blob/4e6a05dd3f7b6572fdd3ab216861d9e446c20331/src/utils/createGenerateClassName.js\n\nexport default function createGenerateClassName() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var _options$disableGloba = options.disableGlobal,\n disableGlobal = _options$disableGloba === void 0 ? false : _options$disableGloba,\n _options$productionPr = options.productionPrefix,\n productionPrefix = _options$productionPr === void 0 ? 'jss' : _options$productionPr,\n _options$seed = options.seed,\n seed = _options$seed === void 0 ? '' : _options$seed;\n var seedPrefix = seed === '' ? '' : \"\".concat(seed, \"-\");\n var ruleCounter = 0;\n\n var getNextCounterId = function getNextCounterId() {\n ruleCounter += 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (ruleCounter >= 1e10) {\n console.warn(['Material-UI: You might have a memory leak.', 'The ruleCounter is not supposed to grow that much.'].join(''));\n }\n }\n\n return ruleCounter;\n };\n\n return function (rule, styleSheet) {\n var name = styleSheet.options.name; // Is a global static MUI style?\n\n if (name && name.indexOf('Mui') === 0 && !styleSheet.options.link && !disableGlobal) {\n // We can use a shorthand class name, we never use the keys to style the components.\n if (pseudoClasses.indexOf(rule.key) !== -1) {\n return \"Mui-\".concat(rule.key);\n }\n\n var prefix = \"\".concat(seedPrefix).concat(name, \"-\").concat(rule.key);\n\n if (!styleSheet.options.theme[nested] || seed !== '') {\n return prefix;\n }\n\n return \"\".concat(prefix, \"-\").concat(getNextCounterId());\n }\n\n if (process.env.NODE_ENV === 'production') {\n return \"\".concat(seedPrefix).concat(productionPrefix).concat(getNextCounterId());\n }\n\n var suffix = \"\".concat(rule.key, \"-\").concat(getNextCounterId()); // Help with debuggability.\n\n if (styleSheet.options.classNamePrefix) {\n return \"\".concat(seedPrefix).concat(styleSheet.options.classNamePrefix, \"-\").concat(suffix);\n }\n\n return \"\".concat(seedPrefix).concat(suffix);\n };\n}","export default function(values, valueof) {\n let min;\n let max;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null) {\n if (min === undefined) {\n if (value >= value) min = max = value;\n } else {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null) {\n if (min === undefined) {\n if (value >= value) min = max = value;\n } else {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n return [min, max];\n}\n","/** @typedef {import('../../types').ShaderModule} ShaderModule */\n\nconst fp32shader = `\\\n#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND\n\n// All these functions are for substituting tan() function from Intel GPU only\nconst float TWO_PI = 6.2831854820251465;\nconst float PI_2 = 1.5707963705062866;\nconst float PI_16 = 0.1963495463132858;\n\nconst float SIN_TABLE_0 = 0.19509032368659973;\nconst float SIN_TABLE_1 = 0.3826834261417389;\nconst float SIN_TABLE_2 = 0.5555702447891235;\nconst float SIN_TABLE_3 = 0.7071067690849304;\n\nconst float COS_TABLE_0 = 0.9807852506637573;\nconst float COS_TABLE_1 = 0.9238795042037964;\nconst float COS_TABLE_2 = 0.8314695954322815;\nconst float COS_TABLE_3 = 0.7071067690849304;\n\nconst float INVERSE_FACTORIAL_3 = 1.666666716337204e-01; // 1/3!\nconst float INVERSE_FACTORIAL_5 = 8.333333767950535e-03; // 1/5!\nconst float INVERSE_FACTORIAL_7 = 1.9841270113829523e-04; // 1/7!\nconst float INVERSE_FACTORIAL_9 = 2.75573188446287533e-06; // 1/9!\n\nfloat sin_taylor_fp32(float a) {\n float r, s, t, x;\n\n if (a == 0.0) {\n return 0.0;\n }\n\n x = -a * a;\n s = a;\n r = a;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_3;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_5;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_7;\n s = s + t;\n\n r = r * x;\n t = r * INVERSE_FACTORIAL_9;\n s = s + t;\n\n return s;\n}\n\nvoid sincos_taylor_fp32(float a, out float sin_t, out float cos_t) {\n if (a == 0.0) {\n sin_t = 0.0;\n cos_t = 1.0;\n }\n sin_t = sin_taylor_fp32(a);\n cos_t = sqrt(1.0 - sin_t * sin_t);\n}\n\nfloat tan_taylor_fp32(float a) {\n float sin_a;\n float cos_a;\n\n if (a == 0.0) {\n return 0.0;\n }\n\n // 2pi range reduction\n float z = floor(a / TWO_PI);\n float r = a - TWO_PI * z;\n\n float t;\n float q = floor(r / PI_2 + 0.5);\n int j = int(q);\n\n if (j < -2 || j > 2) {\n return 1.0 / 0.0;\n }\n\n t = r - PI_2 * q;\n\n q = floor(t / PI_16 + 0.5);\n int k = int(q);\n int abs_k = int(abs(float(k)));\n\n if (abs_k > 4) {\n return 1.0 / 0.0;\n } else {\n t = t - PI_16 * q;\n }\n\n float u = 0.0;\n float v = 0.0;\n\n float sin_t, cos_t;\n float s, c;\n sincos_taylor_fp32(t, sin_t, cos_t);\n\n if (k == 0) {\n s = sin_t;\n c = cos_t;\n } else {\n if (abs(float(abs_k) - 1.0) < 0.5) {\n u = COS_TABLE_0;\n v = SIN_TABLE_0;\n } else if (abs(float(abs_k) - 2.0) < 0.5) {\n u = COS_TABLE_1;\n v = SIN_TABLE_1;\n } else if (abs(float(abs_k) - 3.0) < 0.5) {\n u = COS_TABLE_2;\n v = SIN_TABLE_2;\n } else if (abs(float(abs_k) - 4.0) < 0.5) {\n u = COS_TABLE_3;\n v = SIN_TABLE_3;\n }\n if (k > 0) {\n s = u * sin_t + v * cos_t;\n c = u * cos_t - v * sin_t;\n } else {\n s = u * sin_t - v * cos_t;\n c = u * cos_t + v * sin_t;\n }\n }\n\n if (j == 0) {\n sin_a = s;\n cos_a = c;\n } else if (j == 1) {\n sin_a = c;\n cos_a = -s;\n } else if (j == -1) {\n sin_a = -c;\n cos_a = s;\n } else {\n sin_a = -s;\n cos_a = -c;\n }\n return sin_a / cos_a;\n}\n#endif\n\nfloat tan_fp32(float a) {\n#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND\n return tan_taylor_fp32(a);\n#else\n return tan(a);\n#endif\n}\n`;\n\nexport const fp32 = {\n name: 'fp32',\n vs: fp32shader,\n fs: null\n};\n","import GL from '@luma.gl/constants';\nimport {isWebGL2, assertWebGL2Context, log} from '@luma.gl/gltools';\nimport Resource from './resource';\nimport Buffer from './buffer';\nimport {isObjectEmpty} from '../utils/utils';\n\n// NOTE: The `bindOnUse` flag is a major workaround:\n// See https://github.com/KhronosGroup/WebGL/issues/2346\n\nexport default class TransformFeedback extends Resource {\n static isSupported(gl) {\n return isWebGL2(gl);\n }\n\n constructor(gl, props = {}) {\n assertWebGL2Context(gl);\n super(gl, props);\n\n this.initialize(props);\n this.stubRemovedMethods('TransformFeedback', 'v6.0', ['pause', 'resume']);\n Object.seal(this);\n }\n\n initialize(props = {}) {\n this.buffers = {};\n this.unused = {};\n this.configuration = null;\n this.bindOnUse = true;\n\n // Unbind any currently bound buffers\n if (!isObjectEmpty(this.buffers)) {\n this.bind(() => this._unbindBuffers());\n }\n\n this.setProps(props);\n return this;\n }\n\n setProps(props) {\n if ('program' in props) {\n this.configuration = props.program && props.program.configuration;\n }\n if ('configuration' in props) {\n this.configuration = props.configuration;\n }\n if ('bindOnUse' in props) {\n props = props.bindOnUse;\n }\n if ('buffers' in props) {\n this.setBuffers(props.buffers);\n }\n }\n\n setBuffers(buffers = {}) {\n this.bind(() => {\n for (const bufferName in buffers) {\n this.setBuffer(bufferName, buffers[bufferName]);\n }\n });\n return this;\n }\n\n setBuffer(locationOrName, bufferOrParams) {\n const location = this._getVaryingIndex(locationOrName);\n const {buffer, byteSize, byteOffset} = this._getBufferParams(bufferOrParams);\n\n if (location < 0) {\n this.unused[locationOrName] = buffer;\n log.warn(() => `${this.id} unused varying buffer ${locationOrName}`)();\n return this;\n }\n\n this.buffers[location] = bufferOrParams;\n\n // Need to avoid chrome bug where buffer that is already bound to a different target\n // cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target.\n if (!this.bindOnUse) {\n this._bindBuffer(location, buffer, byteOffset, byteSize);\n }\n\n return this;\n }\n\n begin(primitiveMode = GL.POINTS) {\n // @ts-ignore\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, this.handle);\n this._bindBuffers();\n // @ts-ignore\n this.gl.beginTransformFeedback(primitiveMode);\n return this;\n }\n\n end() {\n // @ts-ignore\n this.gl.endTransformFeedback();\n this._unbindBuffers();\n // @ts-ignore\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, null);\n return this;\n }\n\n // PRIVATE METHODS\n\n _getBufferParams(bufferOrParams) {\n let byteOffset;\n let byteSize;\n let buffer;\n if (bufferOrParams instanceof Buffer === false) {\n buffer = bufferOrParams.buffer;\n byteSize = bufferOrParams.byteSize;\n byteOffset = bufferOrParams.byteOffset;\n } else {\n buffer = bufferOrParams;\n }\n // to use bindBufferRange, either offset or size must be specified, use default value for the other.\n if (byteOffset !== undefined || byteSize !== undefined) {\n byteOffset = byteOffset || 0;\n byteSize = byteSize || buffer.byteLength - byteOffset;\n }\n return {buffer, byteOffset, byteSize};\n }\n\n _getVaryingInfo(locationOrName) {\n return this.configuration && this.configuration.getVaryingInfo(locationOrName);\n }\n\n _getVaryingIndex(locationOrName) {\n if (this.configuration) {\n return this.configuration.getVaryingInfo(locationOrName).location;\n }\n const location = Number(locationOrName);\n return Number.isFinite(location) ? location : -1;\n }\n\n // Need to avoid chrome bug where buffer that is already bound to a different target\n // cannot be bound to 'TRANSFORM_FEEDBACK_BUFFER' target.\n _bindBuffers() {\n if (this.bindOnUse) {\n for (const bufferIndex in this.buffers) {\n const {buffer, byteSize, byteOffset} = this._getBufferParams(this.buffers[bufferIndex]);\n this._bindBuffer(bufferIndex, buffer, byteOffset, byteSize);\n }\n }\n }\n\n _unbindBuffers() {\n if (this.bindOnUse) {\n for (const bufferIndex in this.buffers) {\n this._bindBuffer(bufferIndex, null);\n }\n }\n }\n\n _bindBuffer(index, buffer, byteOffset = 0, byteSize) {\n const handle = buffer && buffer.handle;\n if (!handle || byteSize === undefined) {\n // @ts-ignore\n this.gl.bindBufferBase(GL.TRANSFORM_FEEDBACK_BUFFER, index, handle);\n } else {\n // @ts-ignore\n this.gl.bindBufferRange(GL.TRANSFORM_FEEDBACK_BUFFER, index, handle, byteOffset, byteSize);\n }\n return this;\n }\n\n // RESOURCE METHODS\n\n _createHandle() {\n // @ts-ignore\n return this.gl.createTransformFeedback();\n }\n\n _deleteHandle() {\n // @ts-ignore\n this.gl.deleteTransformFeedback(this.handle);\n }\n\n _bindHandle(handle) {\n // @ts-ignore\n this.gl.bindTransformFeedback(GL.TRANSFORM_FEEDBACK, this.handle);\n }\n}\n","let channelHandles = 1;\nlet animationHandles = 1;\n\nexport class Timeline {\n constructor() {\n this.time = 0;\n this.channels = new Map();\n this.animations = new Map();\n this.playing = false;\n this.lastEngineTime = -1;\n }\n\n addChannel(props) {\n const {delay = 0, duration = Number.POSITIVE_INFINITY, rate = 1, repeat = 1} = props;\n\n const handle = channelHandles++;\n const channel = {\n time: 0,\n delay,\n duration,\n rate,\n repeat\n };\n this._setChannelTime(channel, this.time);\n this.channels.set(handle, channel);\n\n return handle;\n }\n\n removeChannel(handle) {\n this.channels.delete(handle);\n\n for (const [animationHandle, animation] of this.animations) {\n if (animation.channel === handle) {\n this.detachAnimation(animationHandle);\n }\n }\n }\n\n isFinished(handle) {\n const channel = this.channels.get(handle);\n if (channel === undefined) {\n return false;\n }\n\n return this.time >= channel.delay + channel.duration * channel.repeat;\n }\n\n getTime(handle) {\n if (handle === undefined) {\n return this.time;\n }\n\n const channel = this.channels.get(handle);\n\n if (channel === undefined) {\n return -1;\n }\n\n return channel.time;\n }\n\n setTime(time) {\n this.time = Math.max(0, time);\n\n const channels = this.channels.values();\n for (const channel of channels) {\n this._setChannelTime(channel, this.time);\n }\n\n const animations = this.animations.values();\n for (const animationData of animations) {\n const {animation, channel} = animationData;\n animation.setTime(this.getTime(channel));\n }\n }\n\n play() {\n this.playing = true;\n }\n\n pause() {\n this.playing = false;\n this.lastEngineTime = -1;\n }\n\n reset() {\n this.setTime(0);\n }\n\n attachAnimation(animation, channelHandle) {\n const animationHandle = animationHandles++;\n\n this.animations.set(animationHandle, {\n animation,\n channel: channelHandle\n });\n\n animation.setTime(this.getTime(channelHandle));\n\n return animationHandle;\n }\n\n detachAnimation(handle) {\n this.animations.delete(handle);\n }\n\n update(engineTime) {\n if (this.playing) {\n if (this.lastEngineTime === -1) {\n this.lastEngineTime = engineTime;\n }\n this.setTime(this.time + (engineTime - this.lastEngineTime));\n this.lastEngineTime = engineTime;\n }\n }\n\n _setChannelTime(channel, time) {\n const offsetTime = time - channel.delay;\n const totalDuration = channel.duration * channel.repeat;\n // Note(Tarek): Don't loop on final repeat.\n if (offsetTime >= totalDuration) {\n channel.time = channel.duration * channel.rate;\n } else {\n channel.time = Math.max(0, offsetTime) % channel.duration;\n channel.time *= channel.rate;\n }\n }\n}\n","var EOL = {},\n EOF = {},\n QUOTE = 34,\n NEWLINE = 10,\n RETURN = 13;\n\nfunction objectConverter(columns) {\n return new Function(\"d\", \"return {\" + columns.map(function(name, i) {\n return JSON.stringify(name) + \": d[\" + i + \"] || \\\"\\\"\";\n }).join(\",\") + \"}\");\n}\n\nfunction customConverter(columns, f) {\n var object = objectConverter(columns);\n return function(row, i) {\n return f(object(row), i, columns);\n };\n}\n\n// Compute unique columns in order of discovery.\nfunction inferColumns(rows) {\n var columnSet = Object.create(null),\n columns = [];\n\n rows.forEach(function(row) {\n for (var column in row) {\n if (!(column in columnSet)) {\n columns.push(columnSet[column] = column);\n }\n }\n });\n\n return columns;\n}\n\nfunction pad(value, width) {\n var s = value + \"\", length = s.length;\n return length < width ? new Array(width - length + 1).join(0) + s : s;\n}\n\nfunction formatYear(year) {\n return year < 0 ? \"-\" + pad(-year, 6)\n : year > 9999 ? \"+\" + pad(year, 6)\n : pad(year, 4);\n}\n\nfunction formatDate(date) {\n var hours = date.getUTCHours(),\n minutes = date.getUTCMinutes(),\n seconds = date.getUTCSeconds(),\n milliseconds = date.getUTCMilliseconds();\n return isNaN(date) ? \"Invalid Date\"\n : formatYear(date.getUTCFullYear(), 4) + \"-\" + pad(date.getUTCMonth() + 1, 2) + \"-\" + pad(date.getUTCDate(), 2)\n + (milliseconds ? \"T\" + pad(hours, 2) + \":\" + pad(minutes, 2) + \":\" + pad(seconds, 2) + \".\" + pad(milliseconds, 3) + \"Z\"\n : seconds ? \"T\" + pad(hours, 2) + \":\" + pad(minutes, 2) + \":\" + pad(seconds, 2) + \"Z\"\n : minutes || hours ? \"T\" + pad(hours, 2) + \":\" + pad(minutes, 2) + \"Z\"\n : \"\");\n}\n\nexport default function(delimiter) {\n var reFormat = new RegExp(\"[\\\"\" + delimiter + \"\\n\\r]\"),\n DELIMITER = delimiter.charCodeAt(0);\n\n function parse(text, f) {\n var convert, columns, rows = parseRows(text, function(row, i) {\n if (convert) return convert(row, i - 1);\n columns = row, convert = f ? customConverter(row, f) : objectConverter(row);\n });\n rows.columns = columns || [];\n return rows;\n }\n\n function parseRows(text, f) {\n var rows = [], // output rows\n N = text.length,\n I = 0, // current character index\n n = 0, // current line number\n t, // current token\n eof = N <= 0, // current token followed by EOF?\n eol = false; // current token followed by EOL?\n\n // Strip the trailing newline.\n if (text.charCodeAt(N - 1) === NEWLINE) --N;\n if (text.charCodeAt(N - 1) === RETURN) --N;\n\n function token() {\n if (eof) return EOF;\n if (eol) return eol = false, EOL;\n\n // Unescape quotes.\n var i, j = I, c;\n if (text.charCodeAt(j) === QUOTE) {\n while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE);\n if ((i = I) >= N) eof = true;\n else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true;\n else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }\n return text.slice(j + 1, i - 1).replace(/\"\"/g, \"\\\"\");\n }\n\n // Find next delimiter or newline.\n while (I < N) {\n if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;\n else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }\n else if (c !== DELIMITER) continue;\n return text.slice(j, i);\n }\n\n // Return last token before EOF.\n return eof = true, text.slice(j, N);\n }\n\n while ((t = token()) !== EOF) {\n var row = [];\n while (t !== EOL && t !== EOF) row.push(t), t = token();\n if (f && (row = f(row, n++)) == null) continue;\n rows.push(row);\n }\n\n return rows;\n }\n\n function preformatBody(rows, columns) {\n return rows.map(function(row) {\n return columns.map(function(column) {\n return formatValue(row[column]);\n }).join(delimiter);\n });\n }\n\n function format(rows, columns) {\n if (columns == null) columns = inferColumns(rows);\n return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, columns)).join(\"\\n\");\n }\n\n function formatBody(rows, columns) {\n if (columns == null) columns = inferColumns(rows);\n return preformatBody(rows, columns).join(\"\\n\");\n }\n\n function formatRows(rows) {\n return rows.map(formatRow).join(\"\\n\");\n }\n\n function formatRow(row) {\n return row.map(formatValue).join(delimiter);\n }\n\n function formatValue(value) {\n return value == null ? \"\"\n : value instanceof Date ? formatDate(value)\n : reFormat.test(value += \"\") ? \"\\\"\" + value.replace(/\"/g, \"\\\"\\\"\") + \"\\\"\"\n : value;\n }\n\n return {\n parse: parse,\n parseRows: parseRows,\n format: format,\n formatBody: formatBody,\n formatRows: formatRows,\n formatRow: formatRow,\n formatValue: formatValue\n };\n}\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { chainPropTypes } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nvar SIZE = 44;\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n display: 'inline-block'\n },\n\n /* Styles applied to the root element if `variant=\"static\"`. */\n static: {\n transition: theme.transitions.create('transform')\n },\n\n /* Styles applied to the root element if `variant=\"indeterminate\"`. */\n indeterminate: {\n animation: '$circular-rotate 1.4s linear infinite'\n },\n\n /* Styles applied to the root element if `variant=\"determinate\"`. */\n determinate: {\n transition: theme.transitions.create('transform')\n },\n\n /* Styles applied to the root element if `color=\"primary\"`. */\n colorPrimary: {\n color: theme.palette.primary.main\n },\n\n /* Styles applied to the root element if `color=\"secondary\"`. */\n colorSecondary: {\n color: theme.palette.secondary.main\n },\n\n /* Styles applied to the `svg` element. */\n svg: {\n display: 'block' // Keeps the progress centered\n\n },\n\n /* Styles applied to the `circle` svg path. */\n circle: {\n stroke: 'currentColor' // Use butt to follow the specification, by chance, it's already the default CSS value.\n // strokeLinecap: 'butt',\n\n },\n\n /* Styles applied to the `circle` svg path if `variant=\"static\"`. */\n circleStatic: {\n transition: theme.transitions.create('stroke-dashoffset')\n },\n\n /* Styles applied to the `circle` svg path if `variant=\"indeterminate\"`. */\n circleIndeterminate: {\n animation: '$circular-dash 1.4s ease-in-out infinite',\n // Some default value that looks fine waiting for the animation to kicks in.\n strokeDasharray: '80px, 200px',\n strokeDashoffset: '0px' // Add the unit to fix a Edge 16 and below bug.\n\n },\n\n /* Styles applied to the `circle` svg path if `variant=\"determinate\"`. */\n circleDeterminate: {\n transition: theme.transitions.create('stroke-dashoffset')\n },\n '@keyframes circular-rotate': {\n '0%': {\n // Fix IE 11 wobbly\n transformOrigin: '50% 50%'\n },\n '100%': {\n transform: 'rotate(360deg)'\n }\n },\n '@keyframes circular-dash': {\n '0%': {\n strokeDasharray: '1px, 200px',\n strokeDashoffset: '0px'\n },\n '50%': {\n strokeDasharray: '100px, 200px',\n strokeDashoffset: '-15px'\n },\n '100%': {\n strokeDasharray: '100px, 200px',\n strokeDashoffset: '-125px'\n }\n },\n\n /* Styles applied to the `circle` svg path if `disableShrink={true}`. */\n circleDisableShrink: {\n animation: 'none'\n }\n };\n};\n/**\n * ## ARIA\n *\n * If the progress bar is describing the loading progress of a particular region of a page,\n * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy`\n * attribute to `true` on that region until it has finished loading.\n */\n\nvar CircularProgress = /*#__PURE__*/React.forwardRef(function CircularProgress(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'primary' : _props$color,\n _props$disableShrink = props.disableShrink,\n disableShrink = _props$disableShrink === void 0 ? false : _props$disableShrink,\n _props$size = props.size,\n size = _props$size === void 0 ? 40 : _props$size,\n style = props.style,\n _props$thickness = props.thickness,\n thickness = _props$thickness === void 0 ? 3.6 : _props$thickness,\n _props$value = props.value,\n value = _props$value === void 0 ? 0 : _props$value,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'indeterminate' : _props$variant,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"color\", \"disableShrink\", \"size\", \"style\", \"thickness\", \"value\", \"variant\"]);\n\n var circleStyle = {};\n var rootStyle = {};\n var rootProps = {};\n\n if (variant === 'determinate' || variant === 'static') {\n var circumference = 2 * Math.PI * ((SIZE - thickness) / 2);\n circleStyle.strokeDasharray = circumference.toFixed(3);\n rootProps['aria-valuenow'] = Math.round(value);\n circleStyle.strokeDashoffset = \"\".concat(((100 - value) / 100 * circumference).toFixed(3), \"px\");\n rootStyle.transform = 'rotate(-90deg)';\n }\n\n return /*#__PURE__*/React.createElement(\"div\", _extends({\n className: clsx(classes.root, className, color !== 'inherit' && classes[\"color\".concat(capitalize(color))], {\n 'determinate': classes.determinate,\n 'indeterminate': classes.indeterminate,\n 'static': classes.static\n }[variant]),\n style: _extends({\n width: size,\n height: size\n }, rootStyle, style),\n ref: ref,\n role: \"progressbar\"\n }, rootProps, other), /*#__PURE__*/React.createElement(\"svg\", {\n className: classes.svg,\n viewBox: \"\".concat(SIZE / 2, \" \").concat(SIZE / 2, \" \").concat(SIZE, \" \").concat(SIZE)\n }, /*#__PURE__*/React.createElement(\"circle\", {\n className: clsx(classes.circle, disableShrink && classes.circleDisableShrink, {\n 'determinate': classes.circleDeterminate,\n 'indeterminate': classes.circleIndeterminate,\n 'static': classes.circleStatic\n }[variant]),\n style: circleStyle,\n cx: SIZE,\n cy: SIZE,\n r: (SIZE - thickness) / 2,\n fill: \"none\",\n strokeWidth: thickness\n })));\n});\nprocess.env.NODE_ENV !== \"production\" ? CircularProgress.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['inherit', 'primary', 'secondary']),\n\n /**\n * If `true`, the shrink animation is disabled.\n * This only works if variant is `indeterminate`.\n */\n disableShrink: chainPropTypes(PropTypes.bool, function (props) {\n if (props.disableShrink && props.variant && props.variant !== 'indeterminate') {\n return new Error('Material-UI: You have provided the `disableShrink` prop ' + 'with a variant other than `indeterminate`. This will have no effect.');\n }\n\n return null;\n }),\n\n /**\n * The size of the circle.\n * If using a number, the pixel unit is assumed.\n * If using a string, you need to provide the CSS unit, e.g '3rem'.\n */\n size: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * @ignore\n */\n style: PropTypes.object,\n\n /**\n * The thickness of the circle.\n */\n thickness: PropTypes.number,\n\n /**\n * The value of the progress indicator for the determinate variant.\n * Value between 0 and 100.\n */\n value: PropTypes.number,\n\n /**\n * The variant to use.\n * Use indeterminate when there is no progress value.\n */\n variant: chainPropTypes(PropTypes.oneOf(['determinate', 'indeterminate', 'static']), function (props) {\n var variant = props.variant;\n\n if (variant === 'static') {\n throw new Error('Material-UI: `variant=\"static\"` was deprecated. Use `variant=\"determinate\"` instead.');\n }\n\n return null;\n })\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiCircularProgress',\n flip: false\n})(CircularProgress);","/* eslint-disable no-restricted-syntax */\nexport default function getThemeProps(params) {\n var theme = params.theme,\n name = params.name,\n props = params.props;\n\n if (!theme || !theme.props || !theme.props[name]) {\n return props;\n } // Resolve default props, code borrow from React source.\n // https://github.com/facebook/react/blob/15a8f031838a553e41c0b66eb1bcf1da8448104d/packages/react/src/ReactElement.js#L221\n\n\n var defaultProps = theme.props[name];\n var propName;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n\n return props;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport PopperJs from 'popper.js';\nimport { chainPropTypes, refType, HTMLElementType } from '@material-ui/utils';\nimport { useTheme } from '@material-ui/styles';\nimport Portal from '../Portal';\nimport createChainedFunction from '../utils/createChainedFunction';\nimport setRef from '../utils/setRef';\nimport useForkRef from '../utils/useForkRef';\n\nfunction flipPlacement(placement, theme) {\n var direction = theme && theme.direction || 'ltr';\n\n if (direction === 'ltr') {\n return placement;\n }\n\n switch (placement) {\n case 'bottom-end':\n return 'bottom-start';\n\n case 'bottom-start':\n return 'bottom-end';\n\n case 'top-end':\n return 'top-start';\n\n case 'top-start':\n return 'top-end';\n\n default:\n return placement;\n }\n}\n\nfunction getAnchorEl(anchorEl) {\n return typeof anchorEl === 'function' ? anchorEl() : anchorEl;\n}\n\nvar useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\nvar defaultPopperOptions = {};\n/**\n * Poppers rely on the 3rd party library [Popper.js](https://popper.js.org/docs/v1/) for positioning.\n */\n\nvar Popper = /*#__PURE__*/React.forwardRef(function Popper(props, ref) {\n var anchorEl = props.anchorEl,\n children = props.children,\n container = props.container,\n _props$disablePortal = props.disablePortal,\n disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal,\n _props$keepMounted = props.keepMounted,\n keepMounted = _props$keepMounted === void 0 ? false : _props$keepMounted,\n modifiers = props.modifiers,\n open = props.open,\n _props$placement = props.placement,\n initialPlacement = _props$placement === void 0 ? 'bottom' : _props$placement,\n _props$popperOptions = props.popperOptions,\n popperOptions = _props$popperOptions === void 0 ? defaultPopperOptions : _props$popperOptions,\n popperRefProp = props.popperRef,\n style = props.style,\n _props$transition = props.transition,\n transition = _props$transition === void 0 ? false : _props$transition,\n other = _objectWithoutProperties(props, [\"anchorEl\", \"children\", \"container\", \"disablePortal\", \"keepMounted\", \"modifiers\", \"open\", \"placement\", \"popperOptions\", \"popperRef\", \"style\", \"transition\"]);\n\n var tooltipRef = React.useRef(null);\n var ownRef = useForkRef(tooltipRef, ref);\n var popperRef = React.useRef(null);\n var handlePopperRef = useForkRef(popperRef, popperRefProp);\n var handlePopperRefRef = React.useRef(handlePopperRef);\n useEnhancedEffect(function () {\n handlePopperRefRef.current = handlePopperRef;\n }, [handlePopperRef]);\n React.useImperativeHandle(popperRefProp, function () {\n return popperRef.current;\n }, []);\n\n var _React$useState = React.useState(true),\n exited = _React$useState[0],\n setExited = _React$useState[1];\n\n var theme = useTheme();\n var rtlPlacement = flipPlacement(initialPlacement, theme);\n /**\n * placement initialized from prop but can change during lifetime if modifiers.flip.\n * modifiers.flip is essentially a flip for controlled/uncontrolled behavior\n */\n\n var _React$useState2 = React.useState(rtlPlacement),\n placement = _React$useState2[0],\n setPlacement = _React$useState2[1];\n\n React.useEffect(function () {\n if (popperRef.current) {\n popperRef.current.update();\n }\n });\n var handleOpen = React.useCallback(function () {\n if (!tooltipRef.current || !anchorEl || !open) {\n return;\n }\n\n if (popperRef.current) {\n popperRef.current.destroy();\n handlePopperRefRef.current(null);\n }\n\n var handlePopperUpdate = function handlePopperUpdate(data) {\n setPlacement(data.placement);\n };\n\n var resolvedAnchorEl = getAnchorEl(anchorEl);\n\n if (process.env.NODE_ENV !== 'production') {\n if (resolvedAnchorEl && resolvedAnchorEl.nodeType === 1) {\n var box = resolvedAnchorEl.getBoundingClientRect();\n\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n console.warn(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n }\n }\n\n var popper = new PopperJs(getAnchorEl(anchorEl), tooltipRef.current, _extends({\n placement: rtlPlacement\n }, popperOptions, {\n modifiers: _extends({}, disablePortal ? {} : {\n // It's using scrollParent by default, we can use the viewport when using a portal.\n preventOverflow: {\n boundariesElement: 'window'\n }\n }, modifiers, popperOptions.modifiers),\n // We could have been using a custom modifier like react-popper is doing.\n // But it seems this is the best public API for this use case.\n onCreate: createChainedFunction(handlePopperUpdate, popperOptions.onCreate),\n onUpdate: createChainedFunction(handlePopperUpdate, popperOptions.onUpdate)\n }));\n handlePopperRefRef.current(popper);\n }, [anchorEl, disablePortal, modifiers, open, rtlPlacement, popperOptions]);\n var handleRef = React.useCallback(function (node) {\n setRef(ownRef, node);\n handleOpen();\n }, [ownRef, handleOpen]);\n\n var handleEnter = function handleEnter() {\n setExited(false);\n };\n\n var handleClose = function handleClose() {\n if (!popperRef.current) {\n return;\n }\n\n popperRef.current.destroy();\n handlePopperRefRef.current(null);\n };\n\n var handleExited = function handleExited() {\n setExited(true);\n handleClose();\n };\n\n React.useEffect(function () {\n return function () {\n handleClose();\n };\n }, []);\n React.useEffect(function () {\n if (!open && !transition) {\n // Otherwise handleExited will call this.\n handleClose();\n }\n }, [open, transition]);\n\n if (!keepMounted && !open && (!transition || exited)) {\n return null;\n }\n\n var childProps = {\n placement: placement\n };\n\n if (transition) {\n childProps.TransitionProps = {\n in: open,\n onEnter: handleEnter,\n onExited: handleExited\n };\n }\n\n return /*#__PURE__*/React.createElement(Portal, {\n disablePortal: disablePortal,\n container: container\n }, /*#__PURE__*/React.createElement(\"div\", _extends({\n ref: handleRef,\n role: \"tooltip\"\n }, other, {\n style: _extends({\n // Prevents scroll issue, waiting for Popper.js to add this style once initiated.\n position: 'fixed',\n // Fix Popper.js display issue\n top: 0,\n left: 0,\n display: !open && keepMounted && !transition ? 'none' : null\n }, style)\n }), typeof children === 'function' ? children(childProps) : children));\n});\nprocess.env.NODE_ENV !== \"production\" ? Popper.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A HTML element, [referenceObject](https://popper.js.org/docs/v1/#referenceObject),\n * or a function that returns either.\n * It's used to set the position of the popper.\n * The return value will passed as the reference object of the Popper instance.\n */\n anchorEl: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.object, PropTypes.func]), function (props) {\n if (props.open) {\n var resolvedAnchorEl = getAnchorEl(props.anchorEl);\n\n if (resolvedAnchorEl && resolvedAnchorEl.nodeType === 1) {\n var box = resolvedAnchorEl.getBoundingClientRect();\n\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n return new Error(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n } else if (!resolvedAnchorEl || typeof resolvedAnchorEl.clientWidth !== 'number' || typeof resolvedAnchorEl.clientHeight !== 'number' || typeof resolvedAnchorEl.getBoundingClientRect !== 'function') {\n return new Error(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'It should be an HTML element instance or a referenceObject ', '(https://popper.js.org/docs/v1/#referenceObject).'].join('\\n'));\n }\n }\n\n return null;\n }),\n\n /**\n * Popper render function or node.\n */\n children: PropTypes\n /* @typescript-to-proptypes-ignore */\n .oneOfType([PropTypes.node, PropTypes.func]).isRequired,\n\n /**\n * A HTML element, component instance, or function that returns either.\n * The `container` will have the portal children appended to it.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes\n /* @typescript-to-proptypes-ignore */\n .oneOfType([HTMLElementType, PropTypes.instanceOf(React.Component), PropTypes.func]),\n\n /**\n * Disable the portal behavior.\n * The children stay within it's parent DOM hierarchy.\n */\n disablePortal: PropTypes.bool,\n\n /**\n * Always keep the children in the DOM.\n * This prop can be useful in SEO situation or\n * when you want to maximize the responsiveness of the Popper.\n */\n keepMounted: PropTypes.bool,\n\n /**\n * Popper.js is based on a \"plugin-like\" architecture,\n * most of its features are fully encapsulated \"modifiers\".\n *\n * A modifier is a function that is called each time Popper.js needs to\n * compute the position of the popper.\n * For this reason, modifiers should be very performant to avoid bottlenecks.\n * To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v1/#modifiers).\n */\n modifiers: PropTypes.object,\n\n /**\n * If `true`, the popper is visible.\n */\n open: PropTypes.bool.isRequired,\n\n /**\n * Popper placement.\n */\n placement: PropTypes.oneOf(['bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n\n /**\n * Options provided to the [`popper.js`](https://popper.js.org/docs/v1/) instance.\n */\n popperOptions: PropTypes.object,\n\n /**\n * A ref that points to the used popper instance.\n */\n popperRef: refType,\n\n /**\n * @ignore\n */\n style: PropTypes.object,\n\n /**\n * Help supporting a react-transition-group/Transition component.\n */\n transition: PropTypes.bool\n} : void 0;\nexport default Popper;","import * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport PropTypes from 'prop-types';\nimport ownerDocument from '../utils/ownerDocument';\nimport useForkRef from '../utils/useForkRef';\nimport useEventCallback from '../utils/useEventCallback';\nimport { elementAcceptingRef, exactProp } from '@material-ui/utils';\n\nfunction mapEventPropToEvent(eventProp) {\n return eventProp.substring(2).toLowerCase();\n}\n\nfunction clickedRootScrollbar(event) {\n return document.documentElement.clientWidth < event.clientX || document.documentElement.clientHeight < event.clientY;\n}\n/**\n * Listen for click events that occur somewhere in the document, outside of the element itself.\n * For instance, if you need to hide a menu when people click anywhere else on your page.\n */\n\n\nfunction ClickAwayListener(props) {\n var children = props.children,\n _props$disableReactTr = props.disableReactTree,\n disableReactTree = _props$disableReactTr === void 0 ? false : _props$disableReactTr,\n _props$mouseEvent = props.mouseEvent,\n mouseEvent = _props$mouseEvent === void 0 ? 'onClick' : _props$mouseEvent,\n onClickAway = props.onClickAway,\n _props$touchEvent = props.touchEvent,\n touchEvent = _props$touchEvent === void 0 ? 'onTouchEnd' : _props$touchEvent;\n var movedRef = React.useRef(false);\n var nodeRef = React.useRef(null);\n var activatedRef = React.useRef(false);\n var syntheticEventRef = React.useRef(false);\n React.useEffect(function () {\n // Ensure that this component is not \"activated\" synchronously.\n // https://github.com/facebook/react/issues/20074\n setTimeout(function () {\n activatedRef.current = true;\n }, 0);\n return function () {\n activatedRef.current = false;\n };\n }, []); // can be removed once we drop support for non ref forwarding class components\n\n var handleOwnRef = React.useCallback(function (instance) {\n // #StrictMode ready\n nodeRef.current = ReactDOM.findDOMNode(instance);\n }, []);\n var handleRef = useForkRef(children.ref, handleOwnRef); // The handler doesn't take event.defaultPrevented into account:\n //\n // event.preventDefault() is meant to stop default behaviours like\n // clicking a checkbox to check it, hitting a button to submit a form,\n // and hitting left arrow to move the cursor in a text input etc.\n // Only special HTML elements have these default behaviors.\n\n var handleClickAway = useEventCallback(function (event) {\n // Given developers can stop the propagation of the synthetic event,\n // we can only be confident with a positive value.\n var insideReactTree = syntheticEventRef.current;\n syntheticEventRef.current = false; // 1. IE 11 support, which trigger the handleClickAway even after the unbind\n // 2. The child might render null.\n // 3. Behave like a blur listener.\n\n if (!activatedRef.current || !nodeRef.current || clickedRootScrollbar(event)) {\n return;\n } // Do not act if user performed touchmove\n\n\n if (movedRef.current) {\n movedRef.current = false;\n return;\n }\n\n var insideDOM; // If not enough, can use https://github.com/DieterHolvoet/event-propagation-path/blob/master/propagationPath.js\n\n if (event.composedPath) {\n insideDOM = event.composedPath().indexOf(nodeRef.current) > -1;\n } else {\n // TODO v6 remove dead logic https://caniuse.com/#search=composedPath.\n var doc = ownerDocument(nodeRef.current);\n insideDOM = !doc.documentElement.contains(event.target) || nodeRef.current.contains(event.target);\n }\n\n if (!insideDOM && (disableReactTree || !insideReactTree)) {\n onClickAway(event);\n }\n }); // Keep track of mouse/touch events that bubbled up through the portal.\n\n var createHandleSynthetic = function createHandleSynthetic(handlerName) {\n return function (event) {\n syntheticEventRef.current = true;\n var childrenPropsHandler = children.props[handlerName];\n\n if (childrenPropsHandler) {\n childrenPropsHandler(event);\n }\n };\n };\n\n var childrenProps = {\n ref: handleRef\n };\n\n if (touchEvent !== false) {\n childrenProps[touchEvent] = createHandleSynthetic(touchEvent);\n }\n\n React.useEffect(function () {\n if (touchEvent !== false) {\n var mappedTouchEvent = mapEventPropToEvent(touchEvent);\n var doc = ownerDocument(nodeRef.current);\n\n var handleTouchMove = function handleTouchMove() {\n movedRef.current = true;\n };\n\n doc.addEventListener(mappedTouchEvent, handleClickAway);\n doc.addEventListener('touchmove', handleTouchMove);\n return function () {\n doc.removeEventListener(mappedTouchEvent, handleClickAway);\n doc.removeEventListener('touchmove', handleTouchMove);\n };\n }\n\n return undefined;\n }, [handleClickAway, touchEvent]);\n\n if (mouseEvent !== false) {\n childrenProps[mouseEvent] = createHandleSynthetic(mouseEvent);\n }\n\n React.useEffect(function () {\n if (mouseEvent !== false) {\n var mappedMouseEvent = mapEventPropToEvent(mouseEvent);\n var doc = ownerDocument(nodeRef.current);\n doc.addEventListener(mappedMouseEvent, handleClickAway);\n return function () {\n doc.removeEventListener(mappedMouseEvent, handleClickAway);\n };\n }\n\n return undefined;\n }, [handleClickAway, mouseEvent]);\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.cloneElement(children, childrenProps));\n}\n\nprocess.env.NODE_ENV !== \"production\" ? ClickAwayListener.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The wrapped element.\n */\n children: elementAcceptingRef.isRequired,\n\n /**\n * If `true`, the React tree is ignored and only the DOM tree is considered.\n * This prop changes how portaled elements are handled.\n */\n disableReactTree: PropTypes.bool,\n\n /**\n * The mouse event to listen to. You can disable the listener by providing `false`.\n */\n mouseEvent: PropTypes.oneOf(['onClick', 'onMouseDown', 'onMouseUp', false]),\n\n /**\n * Callback fired when a \"click away\" event is detected.\n */\n onClickAway: PropTypes.func.isRequired,\n\n /**\n * The touch event to listen to. You can disable the listener by providing `false`.\n */\n touchEvent: PropTypes.oneOf(['onTouchEnd', 'onTouchStart', false])\n} : void 0;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line\n ClickAwayListener['propTypes' + ''] = exactProp(ClickAwayListener.propTypes);\n}\n\nexport default ClickAwayListener;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { Transition } from 'react-transition-group';\nimport { duration } from '../styles/transitions';\nimport useTheme from '../styles/useTheme';\nimport { reflow, getTransitionProps } from '../transitions/utils';\nimport useForkRef from '../utils/useForkRef';\nvar styles = {\n entering: {\n opacity: 1\n },\n entered: {\n opacity: 1\n }\n};\nvar defaultTimeout = {\n enter: duration.enteringScreen,\n exit: duration.leavingScreen\n};\n/**\n * The Fade transition is used by the [Modal](/components/modal/) component.\n * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.\n */\n\nvar Fade = /*#__PURE__*/React.forwardRef(function Fade(props, ref) {\n var children = props.children,\n _props$disableStrictM = props.disableStrictModeCompat,\n disableStrictModeCompat = _props$disableStrictM === void 0 ? false : _props$disableStrictM,\n inProp = props.in,\n onEnter = props.onEnter,\n onEntered = props.onEntered,\n onEntering = props.onEntering,\n onExit = props.onExit,\n onExited = props.onExited,\n onExiting = props.onExiting,\n style = props.style,\n _props$TransitionComp = props.TransitionComponent,\n TransitionComponent = _props$TransitionComp === void 0 ? Transition : _props$TransitionComp,\n _props$timeout = props.timeout,\n timeout = _props$timeout === void 0 ? defaultTimeout : _props$timeout,\n other = _objectWithoutProperties(props, [\"children\", \"disableStrictModeCompat\", \"in\", \"onEnter\", \"onEntered\", \"onEntering\", \"onExit\", \"onExited\", \"onExiting\", \"style\", \"TransitionComponent\", \"timeout\"]);\n\n var theme = useTheme();\n var enableStrictModeCompat = theme.unstable_strictMode && !disableStrictModeCompat;\n var nodeRef = React.useRef(null);\n var foreignRef = useForkRef(children.ref, ref);\n var handleRef = useForkRef(enableStrictModeCompat ? nodeRef : undefined, foreignRef);\n\n var normalizedTransitionCallback = function normalizedTransitionCallback(callback) {\n return function (nodeOrAppearing, maybeAppearing) {\n if (callback) {\n var _ref = enableStrictModeCompat ? [nodeRef.current, nodeOrAppearing] : [nodeOrAppearing, maybeAppearing],\n _ref2 = _slicedToArray(_ref, 2),\n node = _ref2[0],\n isAppearing = _ref2[1]; // onEnterXxx and onExitXxx callbacks have a different arguments.length value.\n\n\n if (isAppearing === undefined) {\n callback(node);\n } else {\n callback(node, isAppearing);\n }\n }\n };\n };\n\n var handleEntering = normalizedTransitionCallback(onEntering);\n var handleEnter = normalizedTransitionCallback(function (node, isAppearing) {\n reflow(node); // So the animation always start from the start.\n\n var transitionProps = getTransitionProps({\n style: style,\n timeout: timeout\n }, {\n mode: 'enter'\n });\n node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);\n node.style.transition = theme.transitions.create('opacity', transitionProps);\n\n if (onEnter) {\n onEnter(node, isAppearing);\n }\n });\n var handleEntered = normalizedTransitionCallback(onEntered);\n var handleExiting = normalizedTransitionCallback(onExiting);\n var handleExit = normalizedTransitionCallback(function (node) {\n var transitionProps = getTransitionProps({\n style: style,\n timeout: timeout\n }, {\n mode: 'exit'\n });\n node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);\n node.style.transition = theme.transitions.create('opacity', transitionProps);\n\n if (onExit) {\n onExit(node);\n }\n });\n var handleExited = normalizedTransitionCallback(onExited);\n return /*#__PURE__*/React.createElement(TransitionComponent, _extends({\n appear: true,\n in: inProp,\n nodeRef: enableStrictModeCompat ? nodeRef : undefined,\n onEnter: handleEnter,\n onEntered: handleEntered,\n onEntering: handleEntering,\n onExit: handleExit,\n onExited: handleExited,\n onExiting: handleExiting,\n timeout: timeout\n }, other), function (state, childProps) {\n return /*#__PURE__*/React.cloneElement(children, _extends({\n style: _extends({\n opacity: 0,\n visibility: state === 'exited' && !inProp ? 'hidden' : undefined\n }, styles[state], style, children.props.style),\n ref: handleRef\n }, childProps));\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Fade.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A single child content element.\n */\n children: PropTypes.element,\n\n /**\n * Enable this prop if you encounter 'Function components cannot be given refs',\n * use `unstable_createStrictModeTheme`,\n * and can't forward the ref in the child component.\n */\n disableStrictModeCompat: PropTypes.bool,\n\n /**\n * If `true`, the component will transition in.\n */\n in: PropTypes.bool,\n\n /**\n * @ignore\n */\n onEnter: PropTypes.func,\n\n /**\n * @ignore\n */\n onEntered: PropTypes.func,\n\n /**\n * @ignore\n */\n onEntering: PropTypes.func,\n\n /**\n * @ignore\n */\n onExit: PropTypes.func,\n\n /**\n * @ignore\n */\n onExited: PropTypes.func,\n\n /**\n * @ignore\n */\n onExiting: PropTypes.func,\n\n /**\n * @ignore\n */\n style: PropTypes.object,\n\n /**\n * The duration for the transition, in milliseconds.\n * You may specify a single timeout for all transitions, or individually with an object.\n */\n timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })])\n} : void 0;\nexport default Fade;","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { chainPropTypes } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nexport var styles = function styles(theme) {\n var elevations = {};\n theme.shadows.forEach(function (shadow, index) {\n elevations[\"elevation\".concat(index)] = {\n boxShadow: shadow\n };\n });\n return _extends({\n /* Styles applied to the root element. */\n root: {\n backgroundColor: theme.palette.background.paper,\n color: theme.palette.text.primary,\n transition: theme.transitions.create('box-shadow')\n },\n\n /* Styles applied to the root element if `square={false}`. */\n rounded: {\n borderRadius: theme.shape.borderRadius\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"`. */\n outlined: {\n border: \"1px solid \".concat(theme.palette.divider)\n }\n }, elevations);\n};\nvar Paper = /*#__PURE__*/React.forwardRef(function Paper(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'div' : _props$component,\n _props$square = props.square,\n square = _props$square === void 0 ? false : _props$square,\n _props$elevation = props.elevation,\n elevation = _props$elevation === void 0 ? 1 : _props$elevation,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'elevation' : _props$variant,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"component\", \"square\", \"elevation\", \"variant\"]);\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className, variant === 'outlined' ? classes.outlined : classes[\"elevation\".concat(elevation)], !square && classes.rounded),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? Paper.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * Shadow depth, corresponds to `dp` in the spec.\n * It accepts values between 0 and 24 inclusive.\n */\n elevation: chainPropTypes(PropTypes.number, function (props) {\n var classes = props.classes,\n elevation = props.elevation; // in case `withStyles` fails to inject we don't need this warning\n\n if (classes === undefined) {\n return null;\n }\n\n if (elevation != null && classes[\"elevation\".concat(elevation)] === undefined) {\n return new Error(\"Material-UI: This elevation `\".concat(elevation, \"` is not implemented.\"));\n }\n\n return null;\n }),\n\n /**\n * If `true`, rounded corners are disabled.\n */\n square: PropTypes.bool,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['elevation', 'outlined'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiPaper'\n})(Paper);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport capitalize from '../utils/capitalize';\nimport withStyles from '../styles/withStyles';\nimport { elementTypeAcceptingRef } from '@material-ui/utils';\nimport useIsFocusVisible from '../utils/useIsFocusVisible';\nimport useForkRef from '../utils/useForkRef';\nimport Typography from '../Typography';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {},\n\n /* Styles applied to the root element if `underline=\"none\"`. */\n underlineNone: {\n textDecoration: 'none'\n },\n\n /* Styles applied to the root element if `underline=\"hover\"`. */\n underlineHover: {\n textDecoration: 'none',\n '&:hover': {\n textDecoration: 'underline'\n }\n },\n\n /* Styles applied to the root element if `underline=\"always\"`. */\n underlineAlways: {\n textDecoration: 'underline'\n },\n // Same reset as ButtonBase.root\n\n /* Styles applied to the root element if `component=\"button\"`. */\n button: {\n position: 'relative',\n WebkitTapHighlightColor: 'transparent',\n backgroundColor: 'transparent',\n // Reset default value\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0,\n border: 0,\n margin: 0,\n // Remove the margin in Safari\n borderRadius: 0,\n padding: 0,\n // Remove the padding in Firefox\n cursor: 'pointer',\n userSelect: 'none',\n verticalAlign: 'middle',\n '-moz-appearance': 'none',\n // Reset\n '-webkit-appearance': 'none',\n // Reset\n '&::-moz-focus-inner': {\n borderStyle: 'none' // Remove Firefox dotted outline.\n\n },\n '&$focusVisible': {\n outline: 'auto'\n }\n },\n\n /* Pseudo-class applied to the root element if the link is keyboard focused. */\n focusVisible: {}\n};\nvar Link = /*#__PURE__*/React.forwardRef(function Link(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'primary' : _props$color,\n _props$component = props.component,\n component = _props$component === void 0 ? 'a' : _props$component,\n onBlur = props.onBlur,\n onFocus = props.onFocus,\n TypographyClasses = props.TypographyClasses,\n _props$underline = props.underline,\n underline = _props$underline === void 0 ? 'hover' : _props$underline,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'inherit' : _props$variant,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"color\", \"component\", \"onBlur\", \"onFocus\", \"TypographyClasses\", \"underline\", \"variant\"]);\n\n var _useIsFocusVisible = useIsFocusVisible(),\n isFocusVisible = _useIsFocusVisible.isFocusVisible,\n onBlurVisible = _useIsFocusVisible.onBlurVisible,\n focusVisibleRef = _useIsFocusVisible.ref;\n\n var _React$useState = React.useState(false),\n focusVisible = _React$useState[0],\n setFocusVisible = _React$useState[1];\n\n var handlerRef = useForkRef(ref, focusVisibleRef);\n\n var handleBlur = function handleBlur(event) {\n if (focusVisible) {\n onBlurVisible();\n setFocusVisible(false);\n }\n\n if (onBlur) {\n onBlur(event);\n }\n };\n\n var handleFocus = function handleFocus(event) {\n if (isFocusVisible(event)) {\n setFocusVisible(true);\n }\n\n if (onFocus) {\n onFocus(event);\n }\n };\n\n return /*#__PURE__*/React.createElement(Typography, _extends({\n className: clsx(classes.root, classes[\"underline\".concat(capitalize(underline))], className, focusVisible && classes.focusVisible, component === 'button' && classes.button),\n classes: TypographyClasses,\n color: color,\n component: component,\n onBlur: handleBlur,\n onFocus: handleFocus,\n ref: handlerRef,\n variant: variant\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? Link.propTypes = {\n /**\n * The content of the link.\n */\n children: PropTypes.node.isRequired,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the link.\n */\n color: PropTypes.oneOf(['initial', 'inherit', 'primary', 'secondary', 'textPrimary', 'textSecondary', 'error']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: elementTypeAcceptingRef,\n\n /**\n * @ignore\n */\n onBlur: PropTypes.func,\n\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n\n /**\n * `classes` prop applied to the [`Typography`](/api/typography/) element.\n */\n TypographyClasses: PropTypes.object,\n\n /**\n * Controls when the link should have an underline.\n */\n underline: PropTypes.oneOf(['none', 'hover', 'always']),\n\n /**\n * Applies the theme typography styles.\n */\n variant: PropTypes.string\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiLink'\n})(Link);","import Geometry from '../geometry/geometry';\nimport {uid} from '@luma.gl/webgl';\n\n// prettier-ignore\nconst CUBE_INDICES = new Uint16Array([\n 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13,\n 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23\n]);\n\n// prettier-ignore\nconst CUBE_POSITIONS = new Float32Array([\n -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1,\n -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1,\n -1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1,\n -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1,\n 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1,\n -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1\n]);\n\n// TODO - could be Uint8\n// prettier-ignore\nconst CUBE_NORMALS = new Float32Array([\n // Front face\n 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,\n // Back face\n 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1,\n // Top face\n 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,\n // Bottom face\n 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,\n // Right face\n 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,\n // Left face\n -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0\n]);\n\n// prettier-ignore\nconst CUBE_TEX_COORDS = new Float32Array([\n // Front face\n 0, 0, 1, 0, 1, 1, 0, 1,\n // Back face\n 1, 0, 1, 1, 0, 1, 0, 0,\n // Top face\n 0, 1, 0, 0, 1, 0, 1, 1,\n // Bottom face\n 1, 1, 0, 1, 0, 0, 1, 0,\n // Right face\n 1, 0, 1, 1, 0, 1, 0, 0,\n // Left face\n 0, 0, 1, 0, 1, 1, 0, 1\n]);\n\nconst ATTRIBUTES = {\n POSITION: {size: 3, value: new Float32Array(CUBE_POSITIONS)},\n NORMAL: {size: 3, value: new Float32Array(CUBE_NORMALS)},\n TEXCOORD_0: {size: 2, value: new Float32Array(CUBE_TEX_COORDS)}\n};\n\nexport default class CubeGeometry extends Geometry {\n constructor(props = {}) {\n const {id = uid('cube-geometry')} = props;\n super({\n ...props,\n id,\n indices: {size: 1, value: new Uint16Array(CUBE_INDICES)},\n attributes: {...ATTRIBUTES, ...props.attributes}\n });\n }\n}\n","// ClipSpace\nimport GL from '@luma.gl/constants';\nimport Model from '../lib/model';\nimport Geometry from '../geometry/geometry';\n\nconst CLIPSPACE_VERTEX_SHADER = `\\\nattribute vec2 aClipSpacePosition;\nattribute vec2 aTexCoord;\nattribute vec2 aCoordinate;\n\nvarying vec2 position;\nvarying vec2 coordinate;\nvarying vec2 uv;\n\nvoid main(void) {\n gl_Position = vec4(aClipSpacePosition, 0., 1.);\n position = aClipSpacePosition;\n coordinate = aCoordinate;\n uv = aTexCoord;\n}\n`;\n\n/* eslint-disable indent, no-multi-spaces */\nconst POSITIONS = [-1, -1, 1, -1, -1, 1, 1, 1];\n\nexport default class ClipSpace extends Model {\n constructor(gl, opts) {\n const TEX_COORDS = POSITIONS.map(coord => (coord === -1 ? 0 : coord));\n\n super(\n gl,\n Object.assign({}, opts, {\n vs: CLIPSPACE_VERTEX_SHADER,\n geometry: new Geometry({\n drawMode: GL.TRIANGLE_STRIP,\n vertexCount: 4,\n attributes: {\n aClipSpacePosition: {size: 2, value: new Float32Array(POSITIONS)},\n aTexCoord: {size: 2, value: new Float32Array(TEX_COORDS)},\n aCoordinate: {size: 2, value: new Float32Array(TEX_COORDS)}\n }\n })\n })\n );\n this.setVertexCount(4);\n }\n}\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n width: '100%',\n overflowX: 'auto'\n }\n};\nvar TableContainer = /*#__PURE__*/React.forwardRef(function TableContainer(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'div' : _props$component,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"component\"]);\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n ref: ref,\n className: clsx(classes.root, className)\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? TableContainer.propTypes = {\n /**\n * The table itself, normally ``\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTableContainer'\n})(TableContainer);","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { chainPropTypes } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nimport TableContext from './TableContext';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n display: 'table',\n width: '100%',\n borderCollapse: 'collapse',\n borderSpacing: 0,\n '& caption': _extends({}, theme.typography.body2, {\n padding: theme.spacing(2),\n color: theme.palette.text.secondary,\n textAlign: 'left',\n captionSide: 'bottom'\n })\n },\n\n /* Styles applied to the root element if `stickyHeader={true}`. */\n stickyHeader: {\n borderCollapse: 'separate'\n }\n };\n};\nvar defaultComponent = 'table';\nvar Table = /*#__PURE__*/React.forwardRef(function Table(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? defaultComponent : _props$component,\n _props$padding = props.padding,\n padding = _props$padding === void 0 ? 'normal' : _props$padding,\n _props$size = props.size,\n size = _props$size === void 0 ? 'medium' : _props$size,\n _props$stickyHeader = props.stickyHeader,\n stickyHeader = _props$stickyHeader === void 0 ? false : _props$stickyHeader,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"component\", \"padding\", \"size\", \"stickyHeader\"]);\n\n var table = React.useMemo(function () {\n return {\n padding: padding,\n size: size,\n stickyHeader: stickyHeader\n };\n }, [padding, size, stickyHeader]);\n return /*#__PURE__*/React.createElement(TableContext.Provider, {\n value: table\n }, /*#__PURE__*/React.createElement(Component, _extends({\n role: Component === defaultComponent ? null : 'table',\n ref: ref,\n className: clsx(classes.root, className, stickyHeader && classes.stickyHeader)\n }, other)));\n});\nprocess.env.NODE_ENV !== \"production\" ? Table.propTypes = {\n /**\n * The content of the table, normally `TableHead` and `TableBody`.\n */\n children: PropTypes.node.isRequired,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * Allows TableCells to inherit padding of the Table.\n * `default` is deprecated, use `normal` instead.\n */\n padding: chainPropTypes(PropTypes.oneOf(['normal', 'checkbox', 'none', 'default']), function (props) {\n if (props.padding === 'default') {\n return new Error('Material-UI: padding=\"default\" was renamed to padding=\"normal\" for consistency.');\n }\n\n return null;\n }),\n\n /**\n * Allows TableCells to inherit size of the Table.\n */\n size: PropTypes.oneOf(['small', 'medium']),\n\n /**\n * Set the header sticky.\n *\n * ⚠️ It doesn't work with IE 11.\n */\n stickyHeader: PropTypes.bool\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTable'\n})(Table);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport Tablelvl2Context from '../Table/Tablelvl2Context';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n display: 'table-row-group'\n }\n};\nvar tablelvl2 = {\n variant: 'body'\n};\nvar defaultComponent = 'tbody';\nvar TableBody = /*#__PURE__*/React.forwardRef(function TableBody(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? defaultComponent : _props$component,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"component\"]);\n\n return /*#__PURE__*/React.createElement(Tablelvl2Context.Provider, {\n value: tablelvl2\n }, /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className),\n ref: ref,\n role: Component === defaultComponent ? null : 'rowgroup'\n }, other)));\n});\nprocess.env.NODE_ENV !== \"production\" ? TableBody.propTypes = {\n /**\n * The content of the component, normally `TableRow`.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTableBody'\n})(TableBody);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport Tablelvl2Context from '../Table/Tablelvl2Context';\nimport { alpha } from '../styles/colorManipulator';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n color: 'inherit',\n display: 'table-row',\n verticalAlign: 'middle',\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0,\n '&$hover:hover': {\n backgroundColor: theme.palette.action.hover\n },\n '&$selected, &$selected:hover': {\n backgroundColor: alpha(theme.palette.secondary.main, theme.palette.action.selectedOpacity)\n }\n },\n\n /* Pseudo-class applied to the root element if `selected={true}`. */\n selected: {},\n\n /* Pseudo-class applied to the root element if `hover={true}`. */\n hover: {},\n\n /* Styles applied to the root element if table variant=\"head\". */\n head: {},\n\n /* Styles applied to the root element if table variant=\"footer\". */\n footer: {}\n };\n};\nvar defaultComponent = 'tr';\n/**\n * Will automatically set dynamic row height\n * based on the material table element parent (head, body, etc).\n */\n\nvar TableRow = /*#__PURE__*/React.forwardRef(function TableRow(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? defaultComponent : _props$component,\n _props$hover = props.hover,\n hover = _props$hover === void 0 ? false : _props$hover,\n _props$selected = props.selected,\n selected = _props$selected === void 0 ? false : _props$selected,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"component\", \"hover\", \"selected\"]);\n\n var tablelvl2 = React.useContext(Tablelvl2Context);\n return /*#__PURE__*/React.createElement(Component, _extends({\n ref: ref,\n className: clsx(classes.root, className, tablelvl2 && {\n 'head': classes.head,\n 'footer': classes.footer\n }[tablelvl2.variant], hover && classes.hover, selected && classes.selected),\n role: Component === defaultComponent ? null : 'row'\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? TableRow.propTypes = {\n /**\n * Should be valid children such as `TableCell`.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, the table row will shade on hover.\n */\n hover: PropTypes.bool,\n\n /**\n * If `true`, the table row will have the selected shading.\n */\n selected: PropTypes.bool\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTableRow'\n})(TableRow);","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { chainPropTypes } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nimport { darken, alpha, lighten } from '../styles/colorManipulator';\nimport TableContext from '../Table/TableContext';\nimport Tablelvl2Context from '../Table/Tablelvl2Context';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: _extends({}, theme.typography.body2, {\n display: 'table-cell',\n verticalAlign: 'inherit',\n // Workaround for a rendering bug with spanned columns in Chrome 62.0.\n // Removes the alpha (sets it to 1), and lightens or darkens the theme color.\n borderBottom: \"1px solid\\n \".concat(theme.palette.type === 'light' ? lighten(alpha(theme.palette.divider, 1), 0.88) : darken(alpha(theme.palette.divider, 1), 0.68)),\n textAlign: 'left',\n padding: 16\n }),\n\n /* Styles applied to the root element if `variant=\"head\"` or `context.table.head`. */\n head: {\n color: theme.palette.text.primary,\n lineHeight: theme.typography.pxToRem(24),\n fontWeight: theme.typography.fontWeightMedium\n },\n\n /* Styles applied to the root element if `variant=\"body\"` or `context.table.body`. */\n body: {\n color: theme.palette.text.primary\n },\n\n /* Styles applied to the root element if `variant=\"footer\"` or `context.table.footer`. */\n footer: {\n color: theme.palette.text.secondary,\n lineHeight: theme.typography.pxToRem(21),\n fontSize: theme.typography.pxToRem(12)\n },\n\n /* Styles applied to the root element if `size=\"small\"`. */\n sizeSmall: {\n padding: '6px 24px 6px 16px',\n '&:last-child': {\n paddingRight: 16\n },\n '&$paddingCheckbox': {\n width: 24,\n // prevent the checkbox column from growing\n padding: '0 12px 0 16px',\n '&:last-child': {\n paddingLeft: 12,\n paddingRight: 16\n },\n '& > *': {\n padding: 0\n }\n }\n },\n\n /* Styles applied to the root element if `padding=\"checkbox\"`. */\n paddingCheckbox: {\n width: 48,\n // prevent the checkbox column from growing\n padding: '0 0 0 4px',\n '&:last-child': {\n paddingLeft: 0,\n paddingRight: 4\n }\n },\n\n /* Styles applied to the root element if `padding=\"none\"`. */\n paddingNone: {\n padding: 0,\n '&:last-child': {\n padding: 0\n }\n },\n\n /* Styles applied to the root element if `align=\"left\"`. */\n alignLeft: {\n textAlign: 'left'\n },\n\n /* Styles applied to the root element if `align=\"center\"`. */\n alignCenter: {\n textAlign: 'center'\n },\n\n /* Styles applied to the root element if `align=\"right\"`. */\n alignRight: {\n textAlign: 'right',\n flexDirection: 'row-reverse'\n },\n\n /* Styles applied to the root element if `align=\"justify\"`. */\n alignJustify: {\n textAlign: 'justify'\n },\n\n /* Styles applied to the root element if `context.table.stickyHeader={true}`. */\n stickyHeader: {\n position: 'sticky',\n top: 0,\n left: 0,\n zIndex: 2,\n backgroundColor: theme.palette.background.default\n }\n };\n};\n/**\n * The component renders a `
` element when the parent context is a header\n * or otherwise a `` element.\n */\n\nvar TableCell = /*#__PURE__*/React.forwardRef(function TableCell(props, ref) {\n var _props$align = props.align,\n align = _props$align === void 0 ? 'inherit' : _props$align,\n classes = props.classes,\n className = props.className,\n component = props.component,\n paddingProp = props.padding,\n scopeProp = props.scope,\n sizeProp = props.size,\n sortDirection = props.sortDirection,\n variantProp = props.variant,\n other = _objectWithoutProperties(props, [\"align\", \"classes\", \"className\", \"component\", \"padding\", \"scope\", \"size\", \"sortDirection\", \"variant\"]);\n\n var table = React.useContext(TableContext);\n var tablelvl2 = React.useContext(Tablelvl2Context);\n var isHeadCell = tablelvl2 && tablelvl2.variant === 'head';\n var role;\n var Component;\n\n if (component) {\n Component = component;\n role = isHeadCell ? 'columnheader' : 'cell';\n } else {\n Component = isHeadCell ? 'th' : 'td';\n }\n\n var scope = scopeProp;\n\n if (!scope && isHeadCell) {\n scope = 'col';\n }\n\n var padding = paddingProp || (table && table.padding ? table.padding : 'normal');\n var size = sizeProp || (table && table.size ? table.size : 'medium');\n var variant = variantProp || tablelvl2 && tablelvl2.variant;\n var ariaSort = null;\n\n if (sortDirection) {\n ariaSort = sortDirection === 'asc' ? 'ascending' : 'descending';\n }\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n ref: ref,\n className: clsx(classes.root, classes[variant], className, align !== 'inherit' && classes[\"align\".concat(capitalize(align))], padding !== 'normal' && classes[\"padding\".concat(capitalize(padding))], size !== 'medium' && classes[\"size\".concat(capitalize(size))], variant === 'head' && table && table.stickyHeader && classes.stickyHeader),\n \"aria-sort\": ariaSort,\n role: role,\n scope: scope\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? TableCell.propTypes = {\n /**\n * Set the text-align on the table cell content.\n *\n * Monetary or generally number fields **should be right aligned** as that allows\n * you to add them up quickly in your head without having to worry about decimals.\n */\n align: PropTypes.oneOf(['center', 'inherit', 'justify', 'left', 'right']),\n\n /**\n * The table cell contents.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * Sets the padding applied to the cell.\n * By default, the Table parent component set the value (`normal`).\n * `default` is deprecated, use `normal` instead.\n */\n padding: chainPropTypes(PropTypes.oneOf(['normal', 'checkbox', 'none', 'default']), function (props) {\n if (props.padding === 'default') {\n return new Error('Material-UI: padding=\"default\" was renamed to padding=\"normal\" for consistency.');\n }\n\n return null;\n }),\n\n /**\n * Set scope attribute.\n */\n scope: PropTypes.string,\n\n /**\n * Specify the size of the cell.\n * By default, the Table parent component set the value (`medium`).\n */\n size: PropTypes.oneOf(['medium', 'small']),\n\n /**\n * Set aria-sort direction.\n */\n sortDirection: PropTypes.oneOf(['asc', 'desc', false]),\n\n /**\n * Specify the cell type.\n * By default, the TableHead, TableBody or TableFooter parent component set the value.\n */\n variant: PropTypes.oneOf(['body', 'footer', 'head'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTableCell'\n})(TableCell);","export default function max(values, valueof) {\n let max;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n }\n return max;\n}\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n display: 'flex',\n padding: theme.spacing(1, 2, 2)\n }\n };\n};\nvar AccordionDetails = /*#__PURE__*/React.forwardRef(function AccordionDetails(props, ref) {\n var classes = props.classes,\n className = props.className,\n other = _objectWithoutProperties(props, [\"classes\", \"className\"]);\n\n return /*#__PURE__*/React.createElement(\"div\", _extends({\n className: clsx(classes.root, className),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? AccordionDetails.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the accordion details.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiAccordionDetails'\n})(AccordionDetails);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\n\n/* eslint-disable jsx-a11y/aria-role */\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { chainPropTypes } from '@material-ui/utils';\nimport ButtonBase from '../ButtonBase';\nimport IconButton from '../IconButton';\nimport withStyles from '../styles/withStyles';\nimport AccordionContext from '../Accordion/AccordionContext';\nexport var styles = function styles(theme) {\n var transition = {\n duration: theme.transitions.duration.shortest\n };\n return {\n /* Styles applied to the root element. */\n root: {\n display: 'flex',\n minHeight: 8 * 6,\n transition: theme.transitions.create(['min-height', 'background-color'], transition),\n padding: theme.spacing(0, 2),\n '&:hover:not($disabled)': {\n cursor: 'pointer'\n },\n '&$expanded': {\n minHeight: 64\n },\n '&$focused, &$focusVisible': {\n backgroundColor: theme.palette.action.focus\n },\n '&$disabled': {\n opacity: theme.palette.action.disabledOpacity\n }\n },\n\n /* Pseudo-class applied to the root element, children wrapper element and `IconButton` component if `expanded={true}`. */\n expanded: {},\n\n /* Pseudo-class applied to the ButtonBase root element if the button is keyboard focused. */\n focused: {},\n\n /* Pseudo-class applied to the ButtonBase root element if the button is keyboard focused. */\n focusVisible: {},\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the children wrapper element. */\n content: {\n display: 'flex',\n flexGrow: 1,\n transition: theme.transitions.create(['margin'], transition),\n margin: '12px 0',\n '&$expanded': {\n margin: '20px 0'\n }\n },\n\n /* Styles applied to the `IconButton` component when `expandIcon` is supplied. */\n expandIcon: {\n transform: 'rotate(0deg)',\n transition: theme.transitions.create('transform', transition),\n '&:hover': {\n // Disable the hover effect for the IconButton,\n // because a hover effect should apply to the entire Expand button and\n // not only to the IconButton.\n backgroundColor: 'transparent'\n },\n '&$expanded': {\n transform: 'rotate(180deg)'\n }\n }\n };\n};\nvar AccordionSummary = /*#__PURE__*/React.forwardRef(function AccordionSummary(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n expandIcon = props.expandIcon,\n focusVisibleClassName = props.focusVisibleClassName,\n _props$IconButtonProp = props.IconButtonProps,\n IconButtonProps = _props$IconButtonProp === void 0 ? {} : _props$IconButtonProp,\n onClick = props.onClick,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"expandIcon\", \"focusVisibleClassName\", \"IconButtonProps\", \"onClick\"]);\n\n var _React$useContext = React.useContext(AccordionContext),\n _React$useContext$dis = _React$useContext.disabled,\n disabled = _React$useContext$dis === void 0 ? false : _React$useContext$dis,\n expanded = _React$useContext.expanded,\n toggle = _React$useContext.toggle;\n\n var handleChange = function handleChange(event) {\n if (toggle) {\n toggle(event);\n }\n\n if (onClick) {\n onClick(event);\n }\n };\n\n return /*#__PURE__*/React.createElement(ButtonBase, _extends({\n focusRipple: false,\n disableRipple: true,\n disabled: disabled,\n component: \"div\",\n \"aria-expanded\": expanded,\n className: clsx(classes.root, className, disabled && classes.disabled, expanded && classes.expanded),\n focusVisibleClassName: clsx(classes.focusVisible, classes.focused, focusVisibleClassName),\n onClick: handleChange,\n ref: ref\n }, other), /*#__PURE__*/React.createElement(\"div\", {\n className: clsx(classes.content, expanded && classes.expanded)\n }, children), expandIcon && /*#__PURE__*/React.createElement(IconButton, _extends({\n className: clsx(classes.expandIcon, expanded && classes.expanded),\n edge: \"end\",\n component: \"div\",\n tabIndex: null,\n role: null,\n \"aria-hidden\": true\n }, IconButtonProps), expandIcon));\n});\nprocess.env.NODE_ENV !== \"production\" ? AccordionSummary.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the accordion summary.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: chainPropTypes(PropTypes.object, function (props) {\n // Guard against when generation of classes is disabled in the stylesheets (`disableGeneration`).\n // For `disableGeneration` we don't have an accurate warning but `disableGeneration` is an advanced use case anyway.\n if (props.classes.focused !== undefined && props.classes.focused.indexOf(' ') !== -1) {\n return new Error(['Material-UI: The `classes.focused` key is deprecated.', 'Use `classes.focusVisible` instead.', 'The name of the pseudo-class was changed for consistency.'].join('\\n'));\n }\n\n return null;\n }),\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The icon to display as the expand indicator.\n */\n expandIcon: PropTypes.node,\n\n /**\n * This prop can help identify which element has keyboard focus.\n * The class name will be applied when the element gains the focus through keyboard interaction.\n * It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo).\n * The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/master/explainer.md).\n * A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components\n * if needed.\n */\n focusVisibleClassName: PropTypes.string,\n\n /**\n * Props applied to the `IconButton` element wrapping the expand icon.\n */\n IconButtonProps: PropTypes.object,\n\n /**\n * @ignore\n */\n onClick: PropTypes.func\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiAccordionSummary'\n})(AccordionSummary);","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\n// A grid component using the following libs as inspiration.\n//\n// For the implementation:\n// - https://getbootstrap.com/docs/4.3/layout/grid/\n// - https://github.com/kristoferjoseph/flexboxgrid/blob/master/src/css/flexboxgrid.css\n// - https://github.com/roylee0704/react-flexbox-grid\n// - https://material.angularjs.org/latest/layout/introduction\n//\n// Follow this flexbox Guide to better understand the underlying model:\n// - https://css-tricks.com/snippets/css/a-guide-to-flexbox/\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport requirePropFactory from '../utils/requirePropFactory';\nimport deprecatedPropType from '../utils/deprecatedPropType';\nvar SPACINGS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\nvar GRID_SIZES = ['auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n\nfunction generateGrid(globalStyles, theme, breakpoint) {\n var styles = {};\n GRID_SIZES.forEach(function (size) {\n var key = \"grid-\".concat(breakpoint, \"-\").concat(size);\n\n if (size === true) {\n // For the auto layouting\n styles[key] = {\n flexBasis: 0,\n flexGrow: 1,\n maxWidth: '100%'\n };\n return;\n }\n\n if (size === 'auto') {\n styles[key] = {\n flexBasis: 'auto',\n flexGrow: 0,\n maxWidth: 'none'\n };\n return;\n } // Keep 7 significant numbers.\n\n\n var width = \"\".concat(Math.round(size / 12 * 10e7) / 10e5, \"%\"); // Close to the bootstrap implementation:\n // https://github.com/twbs/bootstrap/blob/8fccaa2439e97ec72a4b7dc42ccc1f649790adb0/scss/mixins/_grid.scss#L41\n\n styles[key] = {\n flexBasis: width,\n flexGrow: 0,\n maxWidth: width\n };\n }); // No need for a media query for the first size.\n\n if (breakpoint === 'xs') {\n _extends(globalStyles, styles);\n } else {\n globalStyles[theme.breakpoints.up(breakpoint)] = styles;\n }\n}\n\nfunction getOffset(val) {\n var div = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n var parse = parseFloat(val);\n return \"\".concat(parse / div).concat(String(val).replace(String(parse), '') || 'px');\n}\n\nfunction generateGutter(theme, breakpoint) {\n var styles = {};\n SPACINGS.forEach(function (spacing) {\n var themeSpacing = theme.spacing(spacing);\n\n if (themeSpacing === 0) {\n return;\n }\n\n styles[\"spacing-\".concat(breakpoint, \"-\").concat(spacing)] = {\n margin: \"-\".concat(getOffset(themeSpacing, 2)),\n width: \"calc(100% + \".concat(getOffset(themeSpacing), \")\"),\n '& > $item': {\n padding: getOffset(themeSpacing, 2)\n }\n };\n });\n return styles;\n} // Default CSS values\n// flex: '0 1 auto',\n// flexDirection: 'row',\n// alignItems: 'flex-start',\n// flexWrap: 'nowrap',\n// justifyContent: 'flex-start',\n\n\nexport var styles = function styles(theme) {\n return _extends({\n /* Styles applied to the root element. */\n root: {},\n\n /* Styles applied to the root element if `container={true}`. */\n container: {\n boxSizing: 'border-box',\n display: 'flex',\n flexWrap: 'wrap',\n width: '100%'\n },\n\n /* Styles applied to the root element if `item={true}`. */\n item: {\n boxSizing: 'border-box',\n margin: '0' // For instance, it's useful when used with a `figure` element.\n\n },\n\n /* Styles applied to the root element if `zeroMinWidth={true}`. */\n zeroMinWidth: {\n minWidth: 0\n },\n\n /* Styles applied to the root element if `direction=\"column\"`. */\n 'direction-xs-column': {\n flexDirection: 'column'\n },\n\n /* Styles applied to the root element if `direction=\"column-reverse\"`. */\n 'direction-xs-column-reverse': {\n flexDirection: 'column-reverse'\n },\n\n /* Styles applied to the root element if `direction=\"row-reverse\"`. */\n 'direction-xs-row-reverse': {\n flexDirection: 'row-reverse'\n },\n\n /* Styles applied to the root element if `wrap=\"nowrap\"`. */\n 'wrap-xs-nowrap': {\n flexWrap: 'nowrap'\n },\n\n /* Styles applied to the root element if `wrap=\"reverse\"`. */\n 'wrap-xs-wrap-reverse': {\n flexWrap: 'wrap-reverse'\n },\n\n /* Styles applied to the root element if `alignItems=\"center\"`. */\n 'align-items-xs-center': {\n alignItems: 'center'\n },\n\n /* Styles applied to the root element if `alignItems=\"flex-start\"`. */\n 'align-items-xs-flex-start': {\n alignItems: 'flex-start'\n },\n\n /* Styles applied to the root element if `alignItems=\"flex-end\"`. */\n 'align-items-xs-flex-end': {\n alignItems: 'flex-end'\n },\n\n /* Styles applied to the root element if `alignItems=\"baseline\"`. */\n 'align-items-xs-baseline': {\n alignItems: 'baseline'\n },\n\n /* Styles applied to the root element if `alignContent=\"center\"`. */\n 'align-content-xs-center': {\n alignContent: 'center'\n },\n\n /* Styles applied to the root element if `alignContent=\"flex-start\"`. */\n 'align-content-xs-flex-start': {\n alignContent: 'flex-start'\n },\n\n /* Styles applied to the root element if `alignContent=\"flex-end\"`. */\n 'align-content-xs-flex-end': {\n alignContent: 'flex-end'\n },\n\n /* Styles applied to the root element if `alignContent=\"space-between\"`. */\n 'align-content-xs-space-between': {\n alignContent: 'space-between'\n },\n\n /* Styles applied to the root element if `alignContent=\"space-around\"`. */\n 'align-content-xs-space-around': {\n alignContent: 'space-around'\n },\n\n /* Styles applied to the root element if `justifyContent=\"center\"`. */\n 'justify-content-xs-center': {\n justifyContent: 'center'\n },\n\n /* Styles applied to the root element if `justifyContent=\"flex-end\"`. */\n 'justify-content-xs-flex-end': {\n justifyContent: 'flex-end'\n },\n\n /* Styles applied to the root element if `justifyContent=\"space-between\"`. */\n 'justify-content-xs-space-between': {\n justifyContent: 'space-between'\n },\n\n /* Styles applied to the root element if `justifyContent=\"space-around\"`. */\n 'justify-content-xs-space-around': {\n justifyContent: 'space-around'\n },\n\n /* Styles applied to the root element if `justifyContent=\"space-evenly\"`. */\n 'justify-content-xs-space-evenly': {\n justifyContent: 'space-evenly'\n }\n }, generateGutter(theme, 'xs'), theme.breakpoints.keys.reduce(function (accumulator, key) {\n // Use side effect over immutability for better performance.\n generateGrid(accumulator, theme, key);\n return accumulator;\n }, {}));\n};\nvar Grid = /*#__PURE__*/React.forwardRef(function Grid(props, ref) {\n var _props$alignContent = props.alignContent,\n alignContent = _props$alignContent === void 0 ? 'stretch' : _props$alignContent,\n _props$alignItems = props.alignItems,\n alignItems = _props$alignItems === void 0 ? 'stretch' : _props$alignItems,\n classes = props.classes,\n classNameProp = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'div' : _props$component,\n _props$container = props.container,\n container = _props$container === void 0 ? false : _props$container,\n _props$direction = props.direction,\n direction = _props$direction === void 0 ? 'row' : _props$direction,\n _props$item = props.item,\n item = _props$item === void 0 ? false : _props$item,\n justify = props.justify,\n _props$justifyContent = props.justifyContent,\n justifyContent = _props$justifyContent === void 0 ? 'flex-start' : _props$justifyContent,\n _props$lg = props.lg,\n lg = _props$lg === void 0 ? false : _props$lg,\n _props$md = props.md,\n md = _props$md === void 0 ? false : _props$md,\n _props$sm = props.sm,\n sm = _props$sm === void 0 ? false : _props$sm,\n _props$spacing = props.spacing,\n spacing = _props$spacing === void 0 ? 0 : _props$spacing,\n _props$wrap = props.wrap,\n wrap = _props$wrap === void 0 ? 'wrap' : _props$wrap,\n _props$xl = props.xl,\n xl = _props$xl === void 0 ? false : _props$xl,\n _props$xs = props.xs,\n xs = _props$xs === void 0 ? false : _props$xs,\n _props$zeroMinWidth = props.zeroMinWidth,\n zeroMinWidth = _props$zeroMinWidth === void 0 ? false : _props$zeroMinWidth,\n other = _objectWithoutProperties(props, [\"alignContent\", \"alignItems\", \"classes\", \"className\", \"component\", \"container\", \"direction\", \"item\", \"justify\", \"justifyContent\", \"lg\", \"md\", \"sm\", \"spacing\", \"wrap\", \"xl\", \"xs\", \"zeroMinWidth\"]);\n\n var className = clsx(classes.root, classNameProp, container && [classes.container, spacing !== 0 && classes[\"spacing-xs-\".concat(String(spacing))]], item && classes.item, zeroMinWidth && classes.zeroMinWidth, direction !== 'row' && classes[\"direction-xs-\".concat(String(direction))], wrap !== 'wrap' && classes[\"wrap-xs-\".concat(String(wrap))], alignItems !== 'stretch' && classes[\"align-items-xs-\".concat(String(alignItems))], alignContent !== 'stretch' && classes[\"align-content-xs-\".concat(String(alignContent))], (justify || justifyContent) !== 'flex-start' && classes[\"justify-content-xs-\".concat(String(justify || justifyContent))], xs !== false && classes[\"grid-xs-\".concat(String(xs))], sm !== false && classes[\"grid-sm-\".concat(String(sm))], md !== false && classes[\"grid-md-\".concat(String(md))], lg !== false && classes[\"grid-lg-\".concat(String(lg))], xl !== false && classes[\"grid-xl-\".concat(String(xl))]);\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: className,\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? Grid.propTypes = {\n /**\n * Defines the `align-content` style property.\n * It's applied for all screen sizes.\n */\n alignContent: PropTypes.oneOf(['stretch', 'center', 'flex-start', 'flex-end', 'space-between', 'space-around']),\n\n /**\n * Defines the `align-items` style property.\n * It's applied for all screen sizes.\n */\n alignItems: PropTypes.oneOf(['flex-start', 'center', 'flex-end', 'stretch', 'baseline']),\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, the component will have the flex *container* behavior.\n * You should be wrapping *items* with a *container*.\n */\n container: PropTypes.bool,\n\n /**\n * Defines the `flex-direction` style property.\n * It is applied for all screen sizes.\n */\n direction: PropTypes.oneOf(['row', 'row-reverse', 'column', 'column-reverse']),\n\n /**\n * If `true`, the component will have the flex *item* behavior.\n * You should be wrapping *items* with a *container*.\n */\n item: PropTypes.bool,\n\n /**\n * Defines the `justify-content` style property.\n * It is applied for all screen sizes.\n * @deprecated Use `justifyContent` instead, the prop was renamed\n */\n justify: deprecatedPropType(PropTypes.oneOf(['flex-start', 'center', 'flex-end', 'space-between', 'space-around', 'space-evenly']), 'Use `justifyContent` instead, the prop was renamed.'),\n\n /**\n * Defines the `justify-content` style property.\n * It is applied for all screen sizes.\n */\n justifyContent: PropTypes.oneOf(['flex-start', 'center', 'flex-end', 'space-between', 'space-around', 'space-evenly']),\n\n /**\n * Defines the number of grids the component is going to use.\n * It's applied for the `lg` breakpoint and wider screens if not overridden.\n */\n lg: PropTypes.oneOf([false, 'auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),\n\n /**\n * Defines the number of grids the component is going to use.\n * It's applied for the `md` breakpoint and wider screens if not overridden.\n */\n md: PropTypes.oneOf([false, 'auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),\n\n /**\n * Defines the number of grids the component is going to use.\n * It's applied for the `sm` breakpoint and wider screens if not overridden.\n */\n sm: PropTypes.oneOf([false, 'auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),\n\n /**\n * Defines the space between the type `item` component.\n * It can only be used on a type `container` component.\n */\n spacing: PropTypes.oneOf(SPACINGS),\n\n /**\n * Defines the `flex-wrap` style property.\n * It's applied for all screen sizes.\n */\n wrap: PropTypes.oneOf(['nowrap', 'wrap', 'wrap-reverse']),\n\n /**\n * Defines the number of grids the component is going to use.\n * It's applied for the `xl` breakpoint and wider screens.\n */\n xl: PropTypes.oneOf([false, 'auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),\n\n /**\n * Defines the number of grids the component is going to use.\n * It's applied for all the screen sizes with the lowest priority.\n */\n xs: PropTypes.oneOf([false, 'auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),\n\n /**\n * If `true`, it sets `min-width: 0` on the item.\n * Refer to the limitations section of the documentation to better understand the use case.\n */\n zeroMinWidth: PropTypes.bool\n} : void 0;\nvar StyledGrid = withStyles(styles, {\n name: 'MuiGrid'\n})(Grid);\n\nif (process.env.NODE_ENV !== 'production') {\n var requireProp = requirePropFactory('Grid');\n StyledGrid.propTypes = _extends({}, StyledGrid.propTypes, {\n alignContent: requireProp('container'),\n alignItems: requireProp('container'),\n direction: requireProp('container'),\n justifyContent: requireProp('container'),\n lg: requireProp('item'),\n md: requireProp('item'),\n sm: requireProp('item'),\n spacing: requireProp('container'),\n wrap: requireProp('container'),\n xs: requireProp('item'),\n zeroMinWidth: requireProp('item')\n });\n}\n\nexport default StyledGrid;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { isFilled, isAdornedStart } from '../InputBase/utils';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nimport isMuiElement from '../utils/isMuiElement';\nimport FormControlContext from './FormControlContext';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n display: 'inline-flex',\n flexDirection: 'column',\n position: 'relative',\n // Reset fieldset default style.\n minWidth: 0,\n padding: 0,\n margin: 0,\n border: 0,\n verticalAlign: 'top' // Fix alignment issue on Safari.\n\n },\n\n /* Styles applied to the root element if `margin=\"normal\"`. */\n marginNormal: {\n marginTop: 16,\n marginBottom: 8\n },\n\n /* Styles applied to the root element if `margin=\"dense\"`. */\n marginDense: {\n marginTop: 8,\n marginBottom: 4\n },\n\n /* Styles applied to the root element if `fullWidth={true}`. */\n fullWidth: {\n width: '100%'\n }\n};\n/**\n * Provides context such as filled/focused/error/required for form inputs.\n * Relying on the context provides high flexibility and ensures that the state always stays\n * consistent across the children of the `FormControl`.\n * This context is used by the following components:\n *\n * - FormLabel\n * - FormHelperText\n * - Input\n * - InputLabel\n *\n * You can find one composition example below and more going to [the demos](/components/text-fields/#components).\n *\n * ```jsx\n * \n * Email address\n * \n * We'll never share your email.\n * \n * ```\n *\n * ⚠️Only one input can be used within a FormControl.\n */\n\nvar FormControl = /*#__PURE__*/React.forwardRef(function FormControl(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'primary' : _props$color,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'div' : _props$component,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$error = props.error,\n error = _props$error === void 0 ? false : _props$error,\n _props$fullWidth = props.fullWidth,\n fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,\n visuallyFocused = props.focused,\n _props$hiddenLabel = props.hiddenLabel,\n hiddenLabel = _props$hiddenLabel === void 0 ? false : _props$hiddenLabel,\n _props$margin = props.margin,\n margin = _props$margin === void 0 ? 'none' : _props$margin,\n _props$required = props.required,\n required = _props$required === void 0 ? false : _props$required,\n size = props.size,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'standard' : _props$variant,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"color\", \"component\", \"disabled\", \"error\", \"fullWidth\", \"focused\", \"hiddenLabel\", \"margin\", \"required\", \"size\", \"variant\"]);\n\n var _React$useState = React.useState(function () {\n // We need to iterate through the children and find the Input in order\n // to fully support server-side rendering.\n var initialAdornedStart = false;\n\n if (children) {\n React.Children.forEach(children, function (child) {\n if (!isMuiElement(child, ['Input', 'Select'])) {\n return;\n }\n\n var input = isMuiElement(child, ['Select']) ? child.props.input : child;\n\n if (input && isAdornedStart(input.props)) {\n initialAdornedStart = true;\n }\n });\n }\n\n return initialAdornedStart;\n }),\n adornedStart = _React$useState[0],\n setAdornedStart = _React$useState[1];\n\n var _React$useState2 = React.useState(function () {\n // We need to iterate through the children and find the Input in order\n // to fully support server-side rendering.\n var initialFilled = false;\n\n if (children) {\n React.Children.forEach(children, function (child) {\n if (!isMuiElement(child, ['Input', 'Select'])) {\n return;\n }\n\n if (isFilled(child.props, true)) {\n initialFilled = true;\n }\n });\n }\n\n return initialFilled;\n }),\n filled = _React$useState2[0],\n setFilled = _React$useState2[1];\n\n var _React$useState3 = React.useState(false),\n _focused = _React$useState3[0],\n setFocused = _React$useState3[1];\n\n var focused = visuallyFocused !== undefined ? visuallyFocused : _focused;\n\n if (disabled && focused) {\n setFocused(false);\n }\n\n var registerEffect;\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n var registeredInput = React.useRef(false);\n\n registerEffect = function registerEffect() {\n if (registeredInput.current) {\n console.error(['Material-UI: There are multiple InputBase components inside a FormControl.', 'This is not supported. It might cause infinite rendering loops.', 'Only use one InputBase.'].join('\\n'));\n }\n\n registeredInput.current = true;\n return function () {\n registeredInput.current = false;\n };\n };\n }\n\n var onFilled = React.useCallback(function () {\n setFilled(true);\n }, []);\n var onEmpty = React.useCallback(function () {\n setFilled(false);\n }, []);\n var childContext = {\n adornedStart: adornedStart,\n setAdornedStart: setAdornedStart,\n color: color,\n disabled: disabled,\n error: error,\n filled: filled,\n focused: focused,\n fullWidth: fullWidth,\n hiddenLabel: hiddenLabel,\n margin: (size === 'small' ? 'dense' : undefined) || margin,\n onBlur: function onBlur() {\n setFocused(false);\n },\n onEmpty: onEmpty,\n onFilled: onFilled,\n onFocus: function onFocus() {\n setFocused(true);\n },\n registerEffect: registerEffect,\n required: required,\n variant: variant\n };\n return /*#__PURE__*/React.createElement(FormControlContext.Provider, {\n value: childContext\n }, /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className, margin !== 'none' && classes[\"margin\".concat(capitalize(margin))], fullWidth && classes.fullWidth),\n ref: ref\n }, other), children));\n});\nprocess.env.NODE_ENV !== \"production\" ? FormControl.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The contents of the form control.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, the label, input and helper text should be displayed in a disabled state.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the label should be displayed in an error state.\n */\n error: PropTypes.bool,\n\n /**\n * If `true`, the component will be displayed in focused state.\n */\n focused: PropTypes.bool,\n\n /**\n * If `true`, the component will take up the full width of its container.\n */\n fullWidth: PropTypes.bool,\n\n /**\n * If `true`, the label will be hidden.\n * This is used to increase density for a `FilledInput`.\n * Be sure to add `aria-label` to the `input` element.\n */\n hiddenLabel: PropTypes.bool,\n\n /**\n * If `dense` or `normal`, will adjust vertical spacing of this and contained components.\n */\n margin: PropTypes.oneOf(['dense', 'none', 'normal']),\n\n /**\n * If `true`, the label will indicate that the input is required.\n */\n required: PropTypes.bool,\n\n /**\n * The size of the text field.\n */\n size: PropTypes.oneOf(['medium', 'small']),\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiFormControl'\n})(FormControl);","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport { alpha } from '../styles/colorManipulator';\nimport ButtonBase from '../ButtonBase';\nimport capitalize from '../utils/capitalize';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: _extends({}, theme.typography.button, {\n boxSizing: 'border-box',\n minWidth: 64,\n padding: '6px 16px',\n borderRadius: theme.shape.borderRadius,\n color: theme.palette.text.primary,\n transition: theme.transitions.create(['background-color', 'box-shadow', 'border'], {\n duration: theme.transitions.duration.short\n }),\n '&:hover': {\n textDecoration: 'none',\n backgroundColor: alpha(theme.palette.text.primary, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n },\n '&$disabled': {\n backgroundColor: 'transparent'\n }\n },\n '&$disabled': {\n color: theme.palette.action.disabled\n }\n }),\n\n /* Styles applied to the span element that wraps the children. */\n label: {\n width: '100%',\n // Ensure the correct width for iOS Safari\n display: 'inherit',\n alignItems: 'inherit',\n justifyContent: 'inherit'\n },\n\n /* Styles applied to the root element if `variant=\"text\"`. */\n text: {\n padding: '6px 8px'\n },\n\n /* Styles applied to the root element if `variant=\"text\"` and `color=\"primary\"`. */\n textPrimary: {\n color: theme.palette.primary.main,\n '&:hover': {\n backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n }\n },\n\n /* Styles applied to the root element if `variant=\"text\"` and `color=\"secondary\"`. */\n textSecondary: {\n color: theme.palette.secondary.main,\n '&:hover': {\n backgroundColor: alpha(theme.palette.secondary.main, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"`. */\n outlined: {\n padding: '5px 15px',\n border: \"1px solid \".concat(theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'),\n '&$disabled': {\n border: \"1px solid \".concat(theme.palette.action.disabledBackground)\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"` and `color=\"primary\"`. */\n outlinedPrimary: {\n color: theme.palette.primary.main,\n border: \"1px solid \".concat(alpha(theme.palette.primary.main, 0.5)),\n '&:hover': {\n border: \"1px solid \".concat(theme.palette.primary.main),\n backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"` and `color=\"secondary\"`. */\n outlinedSecondary: {\n color: theme.palette.secondary.main,\n border: \"1px solid \".concat(alpha(theme.palette.secondary.main, 0.5)),\n '&:hover': {\n border: \"1px solid \".concat(theme.palette.secondary.main),\n backgroundColor: alpha(theme.palette.secondary.main, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n },\n '&$disabled': {\n border: \"1px solid \".concat(theme.palette.action.disabled)\n }\n },\n\n /* Styles applied to the root element if `variant=\"contained\"`. */\n contained: {\n color: theme.palette.getContrastText(theme.palette.grey[300]),\n backgroundColor: theme.palette.grey[300],\n boxShadow: theme.shadows[2],\n '&:hover': {\n backgroundColor: theme.palette.grey.A100,\n boxShadow: theme.shadows[4],\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n boxShadow: theme.shadows[2],\n backgroundColor: theme.palette.grey[300]\n },\n '&$disabled': {\n backgroundColor: theme.palette.action.disabledBackground\n }\n },\n '&$focusVisible': {\n boxShadow: theme.shadows[6]\n },\n '&:active': {\n boxShadow: theme.shadows[8]\n },\n '&$disabled': {\n color: theme.palette.action.disabled,\n boxShadow: theme.shadows[0],\n backgroundColor: theme.palette.action.disabledBackground\n }\n },\n\n /* Styles applied to the root element if `variant=\"contained\"` and `color=\"primary\"`. */\n containedPrimary: {\n color: theme.palette.primary.contrastText,\n backgroundColor: theme.palette.primary.main,\n '&:hover': {\n backgroundColor: theme.palette.primary.dark,\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: theme.palette.primary.main\n }\n }\n },\n\n /* Styles applied to the root element if `variant=\"contained\"` and `color=\"secondary\"`. */\n containedSecondary: {\n color: theme.palette.secondary.contrastText,\n backgroundColor: theme.palette.secondary.main,\n '&:hover': {\n backgroundColor: theme.palette.secondary.dark,\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: theme.palette.secondary.main\n }\n }\n },\n\n /* Styles applied to the root element if `disableElevation={true}`. */\n disableElevation: {\n boxShadow: 'none',\n '&:hover': {\n boxShadow: 'none'\n },\n '&$focusVisible': {\n boxShadow: 'none'\n },\n '&:active': {\n boxShadow: 'none'\n },\n '&$disabled': {\n boxShadow: 'none'\n }\n },\n\n /* Pseudo-class applied to the ButtonBase root element if the button is keyboard focused. */\n focusVisible: {},\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the root element if `color=\"inherit\"`. */\n colorInherit: {\n color: 'inherit',\n borderColor: 'currentColor'\n },\n\n /* Styles applied to the root element if `size=\"small\"` and `variant=\"text\"`. */\n textSizeSmall: {\n padding: '4px 5px',\n fontSize: theme.typography.pxToRem(13)\n },\n\n /* Styles applied to the root element if `size=\"large\"` and `variant=\"text\"`. */\n textSizeLarge: {\n padding: '8px 11px',\n fontSize: theme.typography.pxToRem(15)\n },\n\n /* Styles applied to the root element if `size=\"small\"` and `variant=\"outlined\"`. */\n outlinedSizeSmall: {\n padding: '3px 9px',\n fontSize: theme.typography.pxToRem(13)\n },\n\n /* Styles applied to the root element if `size=\"large\"` and `variant=\"outlined\"`. */\n outlinedSizeLarge: {\n padding: '7px 21px',\n fontSize: theme.typography.pxToRem(15)\n },\n\n /* Styles applied to the root element if `size=\"small\"` and `variant=\"contained\"`. */\n containedSizeSmall: {\n padding: '4px 10px',\n fontSize: theme.typography.pxToRem(13)\n },\n\n /* Styles applied to the root element if `size=\"large\"` and `variant=\"contained\"`. */\n containedSizeLarge: {\n padding: '8px 22px',\n fontSize: theme.typography.pxToRem(15)\n },\n\n /* Styles applied to the root element if `size=\"small\"`. */\n sizeSmall: {},\n\n /* Styles applied to the root element if `size=\"large\"`. */\n sizeLarge: {},\n\n /* Styles applied to the root element if `fullWidth={true}`. */\n fullWidth: {\n width: '100%'\n },\n\n /* Styles applied to the startIcon element if supplied. */\n startIcon: {\n display: 'inherit',\n marginRight: 8,\n marginLeft: -4,\n '&$iconSizeSmall': {\n marginLeft: -2\n }\n },\n\n /* Styles applied to the endIcon element if supplied. */\n endIcon: {\n display: 'inherit',\n marginRight: -4,\n marginLeft: 8,\n '&$iconSizeSmall': {\n marginRight: -2\n }\n },\n\n /* Styles applied to the icon element if supplied and `size=\"small\"`. */\n iconSizeSmall: {\n '& > *:first-child': {\n fontSize: 18\n }\n },\n\n /* Styles applied to the icon element if supplied and `size=\"medium\"`. */\n iconSizeMedium: {\n '& > *:first-child': {\n fontSize: 20\n }\n },\n\n /* Styles applied to the icon element if supplied and `size=\"large\"`. */\n iconSizeLarge: {\n '& > *:first-child': {\n fontSize: 22\n }\n }\n };\n};\nvar Button = /*#__PURE__*/React.forwardRef(function Button(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'default' : _props$color,\n _props$component = props.component,\n component = _props$component === void 0 ? 'button' : _props$component,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$disableElevati = props.disableElevation,\n disableElevation = _props$disableElevati === void 0 ? false : _props$disableElevati,\n _props$disableFocusRi = props.disableFocusRipple,\n disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi,\n endIconProp = props.endIcon,\n focusVisibleClassName = props.focusVisibleClassName,\n _props$fullWidth = props.fullWidth,\n fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,\n _props$size = props.size,\n size = _props$size === void 0 ? 'medium' : _props$size,\n startIconProp = props.startIcon,\n _props$type = props.type,\n type = _props$type === void 0 ? 'button' : _props$type,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'text' : _props$variant,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"color\", \"component\", \"disabled\", \"disableElevation\", \"disableFocusRipple\", \"endIcon\", \"focusVisibleClassName\", \"fullWidth\", \"size\", \"startIcon\", \"type\", \"variant\"]);\n\n var startIcon = startIconProp && /*#__PURE__*/React.createElement(\"span\", {\n className: clsx(classes.startIcon, classes[\"iconSize\".concat(capitalize(size))])\n }, startIconProp);\n var endIcon = endIconProp && /*#__PURE__*/React.createElement(\"span\", {\n className: clsx(classes.endIcon, classes[\"iconSize\".concat(capitalize(size))])\n }, endIconProp);\n return /*#__PURE__*/React.createElement(ButtonBase, _extends({\n className: clsx(classes.root, classes[variant], className, color === 'inherit' ? classes.colorInherit : color !== 'default' && classes[\"\".concat(variant).concat(capitalize(color))], size !== 'medium' && [classes[\"\".concat(variant, \"Size\").concat(capitalize(size))], classes[\"size\".concat(capitalize(size))]], disableElevation && classes.disableElevation, disabled && classes.disabled, fullWidth && classes.fullWidth),\n component: component,\n disabled: disabled,\n focusRipple: !disableFocusRipple,\n focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),\n ref: ref,\n type: type\n }, other), /*#__PURE__*/React.createElement(\"span\", {\n className: classes.label\n }, startIcon, children, endIcon));\n});\nprocess.env.NODE_ENV !== \"production\" ? Button.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the button.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, the button will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, no elevation is used.\n */\n disableElevation: PropTypes.bool,\n\n /**\n * If `true`, the keyboard focus ripple will be disabled.\n */\n disableFocusRipple: PropTypes.bool,\n\n /**\n * If `true`, the ripple effect will be disabled.\n *\n * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure\n * to highlight the element by applying separate styles with the `focusVisibleClassName`.\n */\n disableRipple: PropTypes.bool,\n\n /**\n * Element placed after the children.\n */\n endIcon: PropTypes.node,\n\n /**\n * @ignore\n */\n focusVisibleClassName: PropTypes.string,\n\n /**\n * If `true`, the button will take up the full width of its container.\n */\n fullWidth: PropTypes.bool,\n\n /**\n * The URL to link to when the button is clicked.\n * If defined, an `a` element will be used as the root node.\n */\n href: PropTypes.string,\n\n /**\n * The size of the button.\n * `small` is equivalent to the dense button styling.\n */\n size: PropTypes.oneOf(['large', 'medium', 'small']),\n\n /**\n * Element placed before the children.\n */\n startIcon: PropTypes.node,\n\n /**\n * @ignore\n */\n type: PropTypes.oneOfType([PropTypes.oneOf(['button', 'reset', 'submit']), PropTypes.string]),\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['contained', 'outlined', 'text'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiButton'\n})(Button);","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport ButtonBase from '../ButtonBase';\nimport capitalize from '../utils/capitalize';\nimport unsupportedProp from '../utils/unsupportedProp';\nexport var styles = function styles(theme) {\n var _extends2;\n\n return {\n /* Styles applied to the root element. */\n root: _extends({}, theme.typography.button, (_extends2 = {\n maxWidth: 264,\n minWidth: 72,\n position: 'relative',\n boxSizing: 'border-box',\n minHeight: 48,\n flexShrink: 0,\n padding: '6px 12px'\n }, _defineProperty(_extends2, theme.breakpoints.up('sm'), {\n padding: '6px 24px'\n }), _defineProperty(_extends2, \"overflow\", 'hidden'), _defineProperty(_extends2, \"whiteSpace\", 'normal'), _defineProperty(_extends2, \"textAlign\", 'center'), _defineProperty(_extends2, theme.breakpoints.up('sm'), {\n minWidth: 160\n }), _extends2)),\n\n /* Styles applied to the root element if both `icon` and `label` are provided. */\n labelIcon: {\n minHeight: 72,\n paddingTop: 9,\n '& $wrapper > *:first-child': {\n marginBottom: 6\n }\n },\n\n /* Styles applied to the root element if the parent [`Tabs`](/api/tabs/) has `textColor=\"inherit\"`. */\n textColorInherit: {\n color: 'inherit',\n opacity: 0.7,\n '&$selected': {\n opacity: 1\n },\n '&$disabled': {\n opacity: 0.5\n }\n },\n\n /* Styles applied to the root element if the parent [`Tabs`](/api/tabs/) has `textColor=\"primary\"`. */\n textColorPrimary: {\n color: theme.palette.text.secondary,\n '&$selected': {\n color: theme.palette.primary.main\n },\n '&$disabled': {\n color: theme.palette.text.disabled\n }\n },\n\n /* Styles applied to the root element if the parent [`Tabs`](/api/tabs/) has `textColor=\"secondary\"`. */\n textColorSecondary: {\n color: theme.palette.text.secondary,\n '&$selected': {\n color: theme.palette.secondary.main\n },\n '&$disabled': {\n color: theme.palette.text.disabled\n }\n },\n\n /* Pseudo-class applied to the root element if `selected={true}` (controlled by the Tabs component). */\n selected: {},\n\n /* Pseudo-class applied to the root element if `disabled={true}` (controlled by the Tabs component). */\n disabled: {},\n\n /* Styles applied to the root element if `fullWidth={true}` (controlled by the Tabs component). */\n fullWidth: {\n flexShrink: 1,\n flexGrow: 1,\n flexBasis: 0,\n maxWidth: 'none'\n },\n\n /* Styles applied to the root element if `wrapped={true}`. */\n wrapped: {\n fontSize: theme.typography.pxToRem(12),\n lineHeight: 1.5\n },\n\n /* Styles applied to the `icon` and `label`'s wrapper element. */\n wrapper: {\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n width: '100%',\n flexDirection: 'column'\n }\n };\n};\nvar Tab = /*#__PURE__*/React.forwardRef(function Tab(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$disableFocusRi = props.disableFocusRipple,\n disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi,\n fullWidth = props.fullWidth,\n icon = props.icon,\n indicator = props.indicator,\n label = props.label,\n onChange = props.onChange,\n onClick = props.onClick,\n onFocus = props.onFocus,\n selected = props.selected,\n selectionFollowsFocus = props.selectionFollowsFocus,\n _props$textColor = props.textColor,\n textColor = _props$textColor === void 0 ? 'inherit' : _props$textColor,\n value = props.value,\n _props$wrapped = props.wrapped,\n wrapped = _props$wrapped === void 0 ? false : _props$wrapped,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"disabled\", \"disableFocusRipple\", \"fullWidth\", \"icon\", \"indicator\", \"label\", \"onChange\", \"onClick\", \"onFocus\", \"selected\", \"selectionFollowsFocus\", \"textColor\", \"value\", \"wrapped\"]);\n\n var handleClick = function handleClick(event) {\n if (onChange) {\n onChange(event, value);\n }\n\n if (onClick) {\n onClick(event);\n }\n };\n\n var handleFocus = function handleFocus(event) {\n if (selectionFollowsFocus && !selected && onChange) {\n onChange(event, value);\n }\n\n if (onFocus) {\n onFocus(event);\n }\n };\n\n return /*#__PURE__*/React.createElement(ButtonBase, _extends({\n focusRipple: !disableFocusRipple,\n className: clsx(classes.root, classes[\"textColor\".concat(capitalize(textColor))], className, disabled && classes.disabled, selected && classes.selected, label && icon && classes.labelIcon, fullWidth && classes.fullWidth, wrapped && classes.wrapped),\n ref: ref,\n role: \"tab\",\n \"aria-selected\": selected,\n disabled: disabled,\n onClick: handleClick,\n onFocus: handleFocus,\n tabIndex: selected ? 0 : -1\n }, other), /*#__PURE__*/React.createElement(\"span\", {\n className: classes.wrapper\n }, icon, label), indicator);\n});\nprocess.env.NODE_ENV !== \"production\" ? Tab.propTypes = {\n /**\n * This prop isn't supported.\n * Use the `component` prop if you need to change the children structure.\n */\n children: unsupportedProp,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * If `true`, the tab will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the keyboard focus ripple will be disabled.\n */\n disableFocusRipple: PropTypes.bool,\n\n /**\n * If `true`, the ripple effect will be disabled.\n */\n disableRipple: PropTypes.bool,\n\n /**\n * @ignore\n */\n fullWidth: PropTypes.bool,\n\n /**\n * The icon element.\n */\n icon: PropTypes.node,\n\n /**\n * @ignore\n * For server-side rendering consideration, we let the selected tab\n * render the indicator.\n */\n indicator: PropTypes.node,\n\n /**\n * The label element.\n */\n label: PropTypes.node,\n\n /**\n * @ignore\n */\n onChange: PropTypes.func,\n\n /**\n * @ignore\n */\n onClick: PropTypes.func,\n\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n\n /**\n * @ignore\n */\n selected: PropTypes.bool,\n\n /**\n * @ignore\n */\n selectionFollowsFocus: PropTypes.bool,\n\n /**\n * @ignore\n */\n textColor: PropTypes.oneOf(['secondary', 'primary', 'inherit']),\n\n /**\n * You can provide your own value. Otherwise, we fallback to the child position index.\n */\n value: PropTypes.any,\n\n /**\n * Tab labels appear in a single row.\n * They can use a second line if needed.\n */\n wrapped: PropTypes.bool\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTab'\n})(Tab);","import interval from \"./interval.js\";\nimport {durationWeek} from \"./duration.js\";\n\nfunction utcWeekday(i) {\n return interval(function(date) {\n date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);\n date.setUTCHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setUTCDate(date.getUTCDate() + step * 7);\n }, function(start, end) {\n return (end - start) / durationWeek;\n });\n}\n\nexport var utcSunday = utcWeekday(0);\nexport var utcMonday = utcWeekday(1);\nexport var utcTuesday = utcWeekday(2);\nexport var utcWednesday = utcWeekday(3);\nexport var utcThursday = utcWeekday(4);\nexport var utcFriday = utcWeekday(5);\nexport var utcSaturday = utcWeekday(6);\n\nexport var utcSundays = utcSunday.range;\nexport var utcMondays = utcMonday.range;\nexport var utcTuesdays = utcTuesday.range;\nexport var utcWednesdays = utcWednesday.range;\nexport var utcThursdays = utcThursday.range;\nexport var utcFridays = utcFriday.range;\nexport var utcSaturdays = utcSaturday.range;\n","import interval from \"./interval.js\";\nimport {durationDay} from \"./duration.js\";\n\nvar utcDay = interval(function(date) {\n date.setUTCHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setUTCDate(date.getUTCDate() + step);\n}, function(start, end) {\n return (end - start) / durationDay;\n}, function(date) {\n return date.getUTCDate() - 1;\n});\n\nexport default utcDay;\nexport var utcDays = utcDay.range;\n","import interval from \"./interval.js\";\nimport {durationMinute, durationWeek} from \"./duration.js\";\n\nfunction weekday(i) {\n return interval(function(date) {\n date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);\n date.setHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setDate(date.getDate() + step * 7);\n }, function(start, end) {\n return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;\n });\n}\n\nexport var sunday = weekday(0);\nexport var monday = weekday(1);\nexport var tuesday = weekday(2);\nexport var wednesday = weekday(3);\nexport var thursday = weekday(4);\nexport var friday = weekday(5);\nexport var saturday = weekday(6);\n\nexport var sundays = sunday.range;\nexport var mondays = monday.range;\nexport var tuesdays = tuesday.range;\nexport var wednesdays = wednesday.range;\nexport var thursdays = thursday.range;\nexport var fridays = friday.range;\nexport var saturdays = saturday.range;\n","import interval from \"./interval.js\";\nimport {durationDay, durationMinute} from \"./duration.js\";\n\nvar day = interval(function(date) {\n date.setHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setDate(date.getDate() + step);\n}, function(start, end) {\n return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay;\n}, function(date) {\n return date.getDate() - 1;\n});\n\nexport default day;\nexport var days = day.range;\n","import interval from \"./interval.js\";\n\nvar year = interval(function(date) {\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setFullYear(date.getFullYear() + step);\n}, function(start, end) {\n return end.getFullYear() - start.getFullYear();\n}, function(date) {\n return date.getFullYear();\n});\n\n// An optimized implementation for this simple case.\nyear.every = function(k) {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : interval(function(date) {\n date.setFullYear(Math.floor(date.getFullYear() / k) * k);\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setFullYear(date.getFullYear() + step * k);\n });\n};\n\nexport default year;\nexport var years = year.range;\n","import interval from \"./interval.js\";\n\nvar utcYear = interval(function(date) {\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setUTCFullYear(date.getUTCFullYear() + step);\n}, function(start, end) {\n return end.getUTCFullYear() - start.getUTCFullYear();\n}, function(date) {\n return date.getUTCFullYear();\n});\n\n// An optimized implementation for this simple case.\nutcYear.every = function(k) {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : interval(function(date) {\n date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setUTCFullYear(date.getUTCFullYear() + step * k);\n });\n};\n\nexport default utcYear;\nexport var utcYears = utcYear.range;\n","export default function sum(values, valueof) {\n let sum = 0;\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n sum += value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n sum += value;\n }\n }\n }\n return sum;\n}\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport { exactProp } from '@material-ui/utils';\nimport ThemeContext from '../useTheme/ThemeContext';\nimport useTheme from '../useTheme';\nimport nested from './nested'; // To support composition of theme.\n\nfunction mergeOuterLocalTheme(outerTheme, localTheme) {\n if (typeof localTheme === 'function') {\n var mergedTheme = localTheme(outerTheme);\n\n if (process.env.NODE_ENV !== 'production') {\n if (!mergedTheme) {\n console.error(['Material-UI: You should return an object from your theme function, i.e.', ' ({})} />'].join('\\n'));\n }\n }\n\n return mergedTheme;\n }\n\n return _extends({}, outerTheme, localTheme);\n}\n/**\n * This component takes a `theme` prop.\n * It makes the `theme` available down the React tree thanks to React context.\n * This component should preferably be used at **the root of your component tree**.\n */\n\n\nfunction ThemeProvider(props) {\n var children = props.children,\n localTheme = props.theme;\n var outerTheme = useTheme();\n\n if (process.env.NODE_ENV !== 'production') {\n if (outerTheme === null && typeof localTheme === 'function') {\n console.error(['Material-UI: You are providing a theme function prop to the ThemeProvider component:', ' outerTheme} />', '', 'However, no outer theme is present.', 'Make sure a theme is already injected higher in the React tree ' + 'or provide a theme object.'].join('\\n'));\n }\n }\n\n var theme = React.useMemo(function () {\n var output = outerTheme === null ? localTheme : mergeOuterLocalTheme(outerTheme, localTheme);\n\n if (output != null) {\n output[nested] = outerTheme !== null;\n }\n\n return output;\n }, [localTheme, outerTheme]);\n return /*#__PURE__*/React.createElement(ThemeContext.Provider, {\n value: theme\n }, children);\n}\n\nprocess.env.NODE_ENV !== \"production\" ? ThemeProvider.propTypes = {\n /**\n * Your component tree.\n */\n children: PropTypes.node.isRequired,\n\n /**\n * A theme object. You can provide a function to extend the outer theme.\n */\n theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired\n} : void 0;\n\nif (process.env.NODE_ENV !== 'production') {\n process.env.NODE_ENV !== \"production\" ? ThemeProvider.propTypes = exactProp(ThemeProvider.propTypes) : void 0;\n}\n\nexport default ThemeProvider;","const EMPTY = {};\nexport default function shallowEqual(a = EMPTY, b = EMPTY) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return a === b || aKeys.length === bKeys.length && aKeys.every(key => a[key] === b[key]);\n}","/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2017 Joachim Wester\n * MIT license\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function hasOwnProperty(obj, key) {\n return _hasOwnProperty.call(obj, key);\n}\nexport function _objectKeys(obj) {\n if (Array.isArray(obj)) {\n var keys = new Array(obj.length);\n for (var k = 0; k < keys.length; k++) {\n keys[k] = \"\" + k;\n }\n return keys;\n }\n if (Object.keys) {\n return Object.keys(obj);\n }\n var keys = [];\n for (var i in obj) {\n if (hasOwnProperty(obj, i)) {\n keys.push(i);\n }\n }\n return keys;\n}\n;\n/**\n* Deeply clone the object.\n* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy)\n* @param {any} obj value to clone\n* @return {any} cloned obj\n*/\nexport function _deepClone(obj) {\n switch (typeof obj) {\n case \"object\":\n return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5\n case \"undefined\":\n return null; //this is how JSON.stringify behaves for array items\n default:\n return obj; //no need to clone primitives\n }\n}\n//3x faster than cached /^\\d+$/.test(str)\nexport function isInteger(str) {\n var i = 0;\n var len = str.length;\n var charCode;\n while (i < len) {\n charCode = str.charCodeAt(i);\n if (charCode >= 48 && charCode <= 57) {\n i++;\n continue;\n }\n return false;\n }\n return true;\n}\n/**\n* Escapes a json pointer path\n* @param path The raw pointer\n* @return the Escaped path\n*/\nexport function escapePathComponent(path) {\n if (path.indexOf('/') === -1 && path.indexOf('~') === -1)\n return path;\n return path.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n/**\n * Unescapes a json pointer path\n * @param path The escaped pointer\n * @return The unescaped path\n */\nexport function unescapePathComponent(path) {\n return path.replace(/~1/g, '/').replace(/~0/g, '~');\n}\nexport function _getPathRecursive(root, obj) {\n var found;\n for (var key in root) {\n if (hasOwnProperty(root, key)) {\n if (root[key] === obj) {\n return escapePathComponent(key) + '/';\n }\n else if (typeof root[key] === 'object') {\n found = _getPathRecursive(root[key], obj);\n if (found != '') {\n return escapePathComponent(key) + '/' + found;\n }\n }\n }\n }\n return '';\n}\nexport function getPath(root, obj) {\n if (root === obj) {\n return '/';\n }\n var path = _getPathRecursive(root, obj);\n if (path === '') {\n throw new Error(\"Object not found in root\");\n }\n return '/' + path;\n}\n/**\n* Recursively checks whether an object has any undefined values inside.\n*/\nexport function hasUndefined(obj) {\n if (obj === undefined) {\n return true;\n }\n if (obj) {\n if (Array.isArray(obj)) {\n for (var i = 0, len = obj.length; i < len; i++) {\n if (hasUndefined(obj[i])) {\n return true;\n }\n }\n }\n else if (typeof obj === \"object\") {\n var objKeys = _objectKeys(obj);\n var objKeysLength = objKeys.length;\n for (var i = 0; i < objKeysLength; i++) {\n if (hasUndefined(obj[objKeys[i]])) {\n return true;\n }\n }\n }\n }\n return false;\n}\nfunction patchErrorMessageFormatter(message, args) {\n var messageParts = [message];\n for (var key in args) {\n var value = typeof args[key] === 'object' ? JSON.stringify(args[key], null, 2) : args[key]; // pretty print\n if (typeof value !== 'undefined') {\n messageParts.push(key + \": \" + value);\n }\n }\n return messageParts.join('\\n');\n}\nvar PatchError = /** @class */ (function (_super) {\n __extends(PatchError, _super);\n function PatchError(message, name, index, operation, tree) {\n var _newTarget = this.constructor;\n var _this = _super.call(this, patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree })) || this;\n _this.name = name;\n _this.index = index;\n _this.operation = operation;\n _this.tree = tree;\n Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359\n _this.message = patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree });\n return _this;\n }\n return PatchError;\n}(Error));\nexport { PatchError };\n","import { PatchError, _deepClone, isInteger, unescapePathComponent, hasUndefined } from './helpers.mjs';\nexport var JsonPatchError = PatchError;\nexport var deepClone = _deepClone;\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n/* The operations applicable to an object */\nvar objOps = {\n add: function (obj, key, document) {\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed: removed };\n },\n replace: function (obj, key, document) {\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed: removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n var removed = getValueByPointer(document, this.path);\n if (removed) {\n removed = _deepClone(removed);\n }\n var originalValue = applyOperation(document, { op: \"remove\", path: this.from }).removed;\n applyOperation(document, { op: \"add\", path: this.path, value: originalValue });\n return { newDocument: document, removed: removed };\n },\n copy: function (obj, key, document) {\n var valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don't affect source (see issue #177)\n applyOperation(document, { op: \"add\", path: this.path, value: _deepClone(valueToCopy) });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n }\n};\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if (isInteger(i)) {\n arr.splice(i, 0, this.value);\n }\n else { // array props\n arr[i] = this.value;\n }\n // this may be needed when using '-' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed: removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get\n};\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nexport function getValueByPointer(document, pointer) {\n if (pointer == '') {\n return document;\n }\n var getOriginalDestination = { op: \"_get\", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nexport function applyOperation(document, operation, validateOperation, mutateDocument, banPrototypeModifications, index) {\n if (validateOperation === void 0) { validateOperation = false; }\n if (mutateDocument === void 0) { mutateDocument = true; }\n if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }\n if (index === void 0) { index = 0; }\n if (validateOperation) {\n if (typeof validateOperation == 'function') {\n validateOperation(operation, 0, document, operation.path);\n }\n else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === \"\") {\n var returnValue = { newDocument: document };\n if (operation.op === 'add') {\n returnValue.newDocument = operation.value;\n return returnValue;\n }\n else if (operation.op === 'replace') {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n }\n else if (operation.op === 'move' || operation.op === 'copy') { // it's a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === 'move') { // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n }\n else if (operation.op === 'test') {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n returnValue.newDocument = document;\n return returnValue;\n }\n else if (operation.op === 'remove') { // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n }\n else if (operation.op === '_get') {\n operation.value = document;\n return returnValue;\n }\n else { /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);\n }\n else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */\n else {\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n var path = operation.path || \"\";\n var keys = path.split('/');\n var obj = document;\n var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n var len = keys.length;\n var existingPathFragment = undefined;\n var key = void 0;\n var validateFunction = void 0;\n if (typeof validateOperation == 'function') {\n validateFunction = validateOperation;\n }\n else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf('~') != -1) {\n key = unescapePathComponent(key);\n }\n if (banPrototypeModifications && key == '__proto__') {\n throw new TypeError('JSON-Patch: modifying `__proto__` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README');\n }\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join('/');\n }\n else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === '-') {\n key = obj.length;\n }\n else {\n if (validateOperation && !isInteger(key)) {\n throw new JsonPatchError(\"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\", \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\", index, operation, document);\n } // only parse key when it's an integer for `arr.prop` to work\n else if (isInteger(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === \"add\" && key > obj.length) {\n throw new JsonPatchError(\"The specified index MUST NOT be greater than the number of elements in the array\", \"OPERATION_VALUE_OUT_OF_BOUNDS\", index, operation, document);\n }\n var returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n return returnValue;\n }\n }\n else {\n if (t >= len) {\n var returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn't a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== \"object\")) {\n throw new JsonPatchError('Cannot perform operation at the desired path', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);\n }\n }\n }\n}\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nexport function applyPatch(document, patch, validateOperation, mutateDocument, banPrototypeModifications) {\n if (mutateDocument === void 0) { mutateDocument = true; }\n if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');\n }\n }\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n var results = new Array(patch.length);\n for (var i = 0, length_1 = patch.length; i < length_1; i++) {\n // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`\n results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i);\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nexport function applyReducer(document, operation, index) {\n var operationResult = applyOperation(document, operation);\n if (operationResult.test === false) { // failed test\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n return operationResult.newDocument;\n}\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nexport function validator(operation, index, document, existingPathFragment) {\n if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) {\n throw new JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document);\n }\n else if (!objOps[operation.op]) {\n throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);\n }\n else if (typeof operation.path !== 'string') {\n throw new JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document);\n }\n else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) {\n // paths that aren't empty string should start with \"/\"\n throw new JsonPatchError('Operation `path` property must start with \"/\"', 'OPERATION_PATH_INVALID', index, operation, document);\n }\n else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') {\n throw new JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document);\n }\n else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) {\n throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document);\n }\n else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && hasUndefined(operation.value)) {\n throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document);\n }\n else if (document) {\n if (operation.op == \"add\") {\n var pathLen = operation.path.split(\"/\").length;\n var existingPathLen = existingPathFragment.split(\"/\").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document);\n }\n }\n else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);\n }\n }\n else if (operation.op === 'move' || operation.op === 'copy') {\n var existingValue = { op: \"_get\", path: operation.from, value: undefined };\n var error = validate([existingValue], document);\n if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') {\n throw new JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document);\n }\n }\n }\n}\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nexport function validate(sequence, document, externalValidator) {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true);\n }\n else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n }\n catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n }\n else {\n throw e;\n }\n }\n}\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n// Copyright (c) 2017 Evgeny Poberezkin\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nexport function _areEquals(a, b) {\n if (a === b)\n return true;\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key;\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;)\n if (!_areEquals(a[i], b[i]))\n return false;\n return true;\n }\n if (arrA != arrB)\n return false;\n var keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length)\n return false;\n for (i = length; i-- !== 0;)\n if (!b.hasOwnProperty(keys[i]))\n return false;\n for (i = length; i-- !== 0;) {\n key = keys[i];\n if (!_areEquals(a[key], b[key]))\n return false;\n }\n return true;\n }\n return a !== a && b !== b;\n}\n;\n","/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2017 Joachim Wester\n * MIT license\n */\nimport { _deepClone, _objectKeys, escapePathComponent, hasOwnProperty } from './helpers.mjs';\nimport { applyPatch } from './core.mjs';\nvar beforeDict = new WeakMap();\nvar Mirror = /** @class */ (function () {\n function Mirror(obj) {\n this.observers = new Map();\n this.obj = obj;\n }\n return Mirror;\n}());\nvar ObserverInfo = /** @class */ (function () {\n function ObserverInfo(callback, observer) {\n this.callback = callback;\n this.observer = observer;\n }\n return ObserverInfo;\n}());\nfunction getMirror(obj) {\n return beforeDict.get(obj);\n}\nfunction getObserverFromMirror(mirror, callback) {\n return mirror.observers.get(callback);\n}\nfunction removeObserverFromMirror(mirror, observer) {\n mirror.observers.delete(observer.callback);\n}\n/**\n * Detach an observer from an object\n */\nexport function unobserve(root, observer) {\n observer.unobserve();\n}\n/**\n * Observes changes made to an object, which can then be retrieved using generate\n */\nexport function observe(obj, callback) {\n var patches = [];\n var observer;\n var mirror = getMirror(obj);\n if (!mirror) {\n mirror = new Mirror(obj);\n beforeDict.set(obj, mirror);\n }\n else {\n var observerInfo = getObserverFromMirror(mirror, callback);\n observer = observerInfo && observerInfo.observer;\n }\n if (observer) {\n return observer;\n }\n observer = {};\n mirror.value = _deepClone(obj);\n if (callback) {\n observer.callback = callback;\n observer.next = null;\n var dirtyCheck = function () {\n generate(observer);\n };\n var fastCheck = function () {\n clearTimeout(observer.next);\n observer.next = setTimeout(dirtyCheck);\n };\n if (typeof window !== 'undefined') { //not Node\n window.addEventListener('mouseup', fastCheck);\n window.addEventListener('keyup', fastCheck);\n window.addEventListener('mousedown', fastCheck);\n window.addEventListener('keydown', fastCheck);\n window.addEventListener('change', fastCheck);\n }\n }\n observer.patches = patches;\n observer.object = obj;\n observer.unobserve = function () {\n generate(observer);\n clearTimeout(observer.next);\n removeObserverFromMirror(mirror, observer);\n if (typeof window !== 'undefined') {\n window.removeEventListener('mouseup', fastCheck);\n window.removeEventListener('keyup', fastCheck);\n window.removeEventListener('mousedown', fastCheck);\n window.removeEventListener('keydown', fastCheck);\n window.removeEventListener('change', fastCheck);\n }\n };\n mirror.observers.set(callback, new ObserverInfo(callback, observer));\n return observer;\n}\n/**\n * Generate an array of patches from an observer\n */\nexport function generate(observer, invertible) {\n if (invertible === void 0) { invertible = false; }\n var mirror = beforeDict.get(observer.object);\n _generate(mirror.value, observer.object, observer.patches, \"\", invertible);\n if (observer.patches.length) {\n applyPatch(mirror.value, observer.patches);\n }\n var temp = observer.patches;\n if (temp.length > 0) {\n observer.patches = [];\n if (observer.callback) {\n observer.callback(temp);\n }\n }\n return temp;\n}\n// Dirty check if obj is different from mirror, generate patches and update mirror\nfunction _generate(mirror, obj, patches, path, invertible) {\n if (obj === mirror) {\n return;\n }\n if (typeof obj.toJSON === \"function\") {\n obj = obj.toJSON();\n }\n var newKeys = _objectKeys(obj);\n var oldKeys = _objectKeys(mirror);\n var changed = false;\n var deleted = false;\n //if ever \"move\" operation is implemented here, make sure this test runs OK: \"should not generate the same patch twice (move)\"\n for (var t = oldKeys.length - 1; t >= 0; t--) {\n var key = oldKeys[t];\n var oldVal = mirror[key];\n if (hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {\n var newVal = obj[key];\n if (typeof oldVal == \"object\" && oldVal != null && typeof newVal == \"object\" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) {\n _generate(oldVal, newVal, patches, path + \"/\" + escapePathComponent(key), invertible);\n }\n else {\n if (oldVal !== newVal) {\n changed = true;\n if (invertible) {\n patches.push({ op: \"test\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(oldVal) });\n }\n patches.push({ op: \"replace\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(newVal) });\n }\n }\n }\n else if (Array.isArray(mirror) === Array.isArray(obj)) {\n if (invertible) {\n patches.push({ op: \"test\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(oldVal) });\n }\n patches.push({ op: \"remove\", path: path + \"/\" + escapePathComponent(key) });\n deleted = true; // property has been deleted\n }\n else {\n if (invertible) {\n patches.push({ op: \"test\", path: path, value: mirror });\n }\n patches.push({ op: \"replace\", path: path, value: obj });\n changed = true;\n }\n }\n if (!deleted && newKeys.length == oldKeys.length) {\n return;\n }\n for (var t = 0; t < newKeys.length; t++) {\n var key = newKeys[t];\n if (!hasOwnProperty(mirror, key) && obj[key] !== undefined) {\n patches.push({ op: \"add\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(obj[key]) });\n }\n }\n}\n/**\n * Create an array of patches from the differences in two objects\n */\nexport function compare(tree1, tree2, invertible) {\n if (invertible === void 0) { invertible = false; }\n var patches = [];\n _generate(tree1, tree2, patches, '', invertible);\n return patches;\n}\n","export * from './module/core.mjs';\nexport * from './module/duplex.mjs';\nexport {\n PatchError as JsonPatchError,\n _deepClone as deepClone,\n escapePathComponent,\n unescapePathComponent\n} from './module/helpers.mjs';\n\n\n/**\n * Default export for backwards compat\n */\n\nimport * as core from './module/core.mjs';\nimport * as duplex from './module/duplex.mjs';\nimport {\n PatchError as JsonPatchError,\n _deepClone as deepClone,\n escapePathComponent,\n unescapePathComponent\n} from './module/helpers.mjs';\n\nexport default Object.assign({}, core, duplex, {\n JsonPatchError,\n deepClone,\n escapePathComponent,\n unescapePathComponent\n});","import { identity, array, isFunction, constant, isArray, id, error, truthy, debounce, extend, visitArray, inherits, logger, Error, hasOwnProperty } from 'vega-util';\nimport { read, responseType, loader } from 'vega-loader';\nimport { defaultLocale } from 'vega-format';\n\nfunction UniqueList(idFunc) {\n const $ = idFunc || identity,\n list = [],\n ids = {};\n\n list.add = _ => {\n const id = $(_);\n\n if (!ids[id]) {\n ids[id] = 1;\n list.push(_);\n }\n\n return list;\n };\n\n list.remove = _ => {\n const id = $(_);\n\n if (ids[id]) {\n ids[id] = 0;\n const idx = list.indexOf(_);\n if (idx >= 0) list.splice(idx, 1);\n }\n\n return list;\n };\n\n return list;\n}\n\n/**\n * Invoke and await a potentially async callback function. If\n * an error occurs, trap it and route to Dataflow.error.\n * @param {Dataflow} df - The dataflow instance\n * @param {function} callback - A callback function to invoke\n * and then await. The dataflow will be passed as the single\n * argument to the function.\n */\nasync function asyncCallback (df, callback) {\n try {\n await callback(df);\n } catch (err) {\n df.error(err);\n }\n}\n\nconst TUPLE_ID_KEY = Symbol('vega_id');\nlet TUPLE_ID = 1;\n/**\n * Checks if an input value is a registered tuple.\n * @param {*} t - The value to check.\n * @return {boolean} True if the input is a tuple, false otherwise.\n */\n\nfunction isTuple(t) {\n return !!(t && tupleid(t));\n}\n/**\n * Returns the id of a tuple.\n * @param {object} t - The input tuple.\n * @return {*} the tuple id.\n */\n\nfunction tupleid(t) {\n return t[TUPLE_ID_KEY];\n}\n/**\n * Sets the id of a tuple.\n * @param {object} t - The input tuple.\n * @param {*} id - The id value to set.\n * @return {object} the input tuple.\n */\n\nfunction setid(t, id) {\n t[TUPLE_ID_KEY] = id;\n return t;\n}\n/**\n * Ingest an object or value as a data tuple.\n * If the input value is an object, an id field will be added to it. For\n * efficiency, the input object is modified directly. A copy is not made.\n * If the input value is a literal, it will be wrapped in a new object\n * instance, with the value accessible as the 'data' property.\n * @param datum - The value to ingest.\n * @return {object} The ingested data tuple.\n */\n\n\nfunction ingest$1(datum) {\n const t = datum === Object(datum) ? datum : {\n data: datum\n };\n return tupleid(t) ? t : setid(t, TUPLE_ID++);\n}\n/**\n * Given a source tuple, return a derived copy.\n * @param {object} t - The source tuple.\n * @return {object} The derived tuple.\n */\n\nfunction derive(t) {\n return rederive(t, ingest$1({}));\n}\n/**\n * Rederive a derived tuple by copying values from the source tuple.\n * @param {object} t - The source tuple.\n * @param {object} d - The derived tuple.\n * @return {object} The derived tuple.\n */\n\nfunction rederive(t, d) {\n for (const k in t) d[k] = t[k];\n\n return d;\n}\n/**\n * Replace an existing tuple with a new tuple.\n * @param {object} t - The existing data tuple.\n * @param {object} d - The new tuple that replaces the old.\n * @return {object} The new tuple.\n */\n\nfunction replace(t, d) {\n return setid(d, tupleid(t));\n}\n/**\n * Generate an augmented comparator function that provides stable\n * sorting by tuple id when the given comparator produces ties.\n * @param {function} cmp - The comparator to augment.\n * @param {function} [f] - Optional tuple accessor function.\n * @return {function} An augmented comparator function.\n */\n\nfunction stableCompare(cmp, f) {\n return !cmp ? null : f ? (a, b) => cmp(a, b) || tupleid(f(a)) - tupleid(f(b)) : (a, b) => cmp(a, b) || tupleid(a) - tupleid(b);\n}\n\nfunction isChangeSet(v) {\n return v && v.constructor === changeset;\n}\nfunction changeset() {\n const add = [],\n // insert tuples\n rem = [],\n // remove tuples\n mod = [],\n // modify tuples\n remp = [],\n // remove by predicate\n modp = []; // modify by predicate\n\n let clean = null,\n reflow = false;\n return {\n constructor: changeset,\n\n insert(t) {\n const d = array(t),\n n = d.length;\n\n for (let i = 0; i < n; ++i) add.push(d[i]);\n\n return this;\n },\n\n remove(t) {\n const a = isFunction(t) ? remp : rem,\n d = array(t),\n n = d.length;\n\n for (let i = 0; i < n; ++i) a.push(d[i]);\n\n return this;\n },\n\n modify(t, field, value) {\n const m = {\n field: field,\n value: constant(value)\n };\n\n if (isFunction(t)) {\n m.filter = t;\n modp.push(m);\n } else {\n m.tuple = t;\n mod.push(m);\n }\n\n return this;\n },\n\n encode(t, set) {\n if (isFunction(t)) modp.push({\n filter: t,\n field: set\n });else mod.push({\n tuple: t,\n field: set\n });\n return this;\n },\n\n clean(value) {\n clean = value;\n return this;\n },\n\n reflow() {\n reflow = true;\n return this;\n },\n\n pulse(pulse, tuples) {\n const cur = {},\n out = {};\n let i, n, m, f, t, id; // build lookup table of current tuples\n\n for (i = 0, n = tuples.length; i < n; ++i) {\n cur[tupleid(tuples[i])] = 1;\n } // process individual tuples to remove\n\n\n for (i = 0, n = rem.length; i < n; ++i) {\n t = rem[i];\n cur[tupleid(t)] = -1;\n } // process predicate-based removals\n\n\n for (i = 0, n = remp.length; i < n; ++i) {\n f = remp[i];\n tuples.forEach(t => {\n if (f(t)) cur[tupleid(t)] = -1;\n });\n } // process all add tuples\n\n\n for (i = 0, n = add.length; i < n; ++i) {\n t = add[i];\n id = tupleid(t);\n\n if (cur[id]) {\n // tuple already resides in dataset\n // if flagged for both add and remove, cancel\n cur[id] = 1;\n } else {\n // tuple does not reside in dataset, add\n pulse.add.push(ingest$1(add[i]));\n }\n } // populate pulse rem list\n\n\n for (i = 0, n = tuples.length; i < n; ++i) {\n t = tuples[i];\n if (cur[tupleid(t)] < 0) pulse.rem.push(t);\n } // modify helper method\n\n\n function modify(t, f, v) {\n if (v) {\n t[f] = v(t);\n } else {\n pulse.encode = f;\n }\n\n if (!reflow) out[tupleid(t)] = t;\n } // process individual tuples to modify\n\n\n for (i = 0, n = mod.length; i < n; ++i) {\n m = mod[i];\n t = m.tuple;\n f = m.field;\n id = cur[tupleid(t)];\n\n if (id > 0) {\n modify(t, f, m.value);\n pulse.modifies(f);\n }\n } // process predicate-based modifications\n\n\n for (i = 0, n = modp.length; i < n; ++i) {\n m = modp[i];\n f = m.filter;\n tuples.forEach(t => {\n if (f(t) && cur[tupleid(t)] > 0) {\n modify(t, m.field, m.value);\n }\n });\n pulse.modifies(m.field);\n } // upon reflow request, populate mod with all non-removed tuples\n // otherwise, populate mod with modified tuples only\n\n\n if (reflow) {\n pulse.mod = rem.length || remp.length ? tuples.filter(t => cur[tupleid(t)] > 0) : tuples.slice();\n } else {\n for (id in out) pulse.mod.push(out[id]);\n } // set pulse garbage collection request\n\n\n if (clean || clean == null && (rem.length || remp.length)) {\n pulse.clean(true);\n }\n\n return pulse;\n }\n\n };\n}\n\nconst CACHE = '_:mod:_';\n/**\n * Hash that tracks modifications to assigned values.\n * Callers *must* use the set method to update values.\n */\n\nfunction Parameters() {\n Object.defineProperty(this, CACHE, {\n writable: true,\n value: {}\n });\n}\nParameters.prototype = {\n /**\n * Set a parameter value. If the parameter value changes, the parameter\n * will be recorded as modified.\n * @param {string} name - The parameter name.\n * @param {number} index - The index into an array-value parameter. Ignored if\n * the argument is undefined, null or less than zero.\n * @param {*} value - The parameter value to set.\n * @param {boolean} [force=false] - If true, records the parameter as modified\n * even if the value is unchanged.\n * @return {Parameters} - This parameter object.\n */\n set(name, index, value, force) {\n const o = this,\n v = o[name],\n mod = o[CACHE];\n\n if (index != null && index >= 0) {\n if (v[index] !== value || force) {\n v[index] = value;\n mod[index + ':' + name] = -1;\n mod[name] = -1;\n }\n } else if (v !== value || force) {\n o[name] = value;\n mod[name] = isArray(value) ? 1 + value.length : -1;\n }\n\n return o;\n },\n\n /**\n * Tests if one or more parameters has been modified. If invoked with no\n * arguments, returns true if any parameter value has changed. If the first\n * argument is array, returns trues if any parameter name in the array has\n * changed. Otherwise, tests if the given name and optional array index has\n * changed.\n * @param {string} name - The parameter name to test.\n * @param {number} [index=undefined] - The parameter array index to test.\n * @return {boolean} - Returns true if a queried parameter was modified.\n */\n modified(name, index) {\n const mod = this[CACHE];\n\n if (!arguments.length) {\n for (const k in mod) {\n if (mod[k]) return true;\n }\n\n return false;\n } else if (isArray(name)) {\n for (let k = 0; k < name.length; ++k) {\n if (mod[name[k]]) return true;\n }\n\n return false;\n }\n\n return index != null && index >= 0 ? index + 1 < mod[name] || !!mod[index + ':' + name] : !!mod[name];\n },\n\n /**\n * Clears the modification records. After calling this method,\n * all parameters are considered unmodified.\n */\n clear() {\n this[CACHE] = {};\n return this;\n }\n\n};\n\nlet OP_ID = 0;\nconst PULSE = 'pulse',\n NO_PARAMS = new Parameters(); // Boolean Flags\n\nconst SKIP$1 = 1,\n MODIFIED = 2;\n/**\n * An Operator is a processing node in a dataflow graph.\n * Each operator stores a value and an optional value update function.\n * Operators can accept a hash of named parameters. Parameter values can\n * either be direct (JavaScript literals, arrays, objects) or indirect\n * (other operators whose values will be pulled dynamically). Operators\n * included as parameters will have this operator added as a dependency.\n * @constructor\n * @param {*} [init] - The initial value for this operator.\n * @param {function(object, Pulse)} [update] - An update function. Upon\n * evaluation of this operator, the update function will be invoked and the\n * return value will be used as the new value of this operator.\n * @param {object} [params] - The parameters for this operator.\n * @param {boolean} [react=true] - Flag indicating if this operator should\n * listen for changes to upstream operators included as parameters.\n * @see parameters\n */\n\nfunction Operator(init, update, params, react) {\n this.id = ++OP_ID;\n this.value = init;\n this.stamp = -1;\n this.rank = -1;\n this.qrank = -1;\n this.flags = 0;\n\n if (update) {\n this._update = update;\n }\n\n if (params) this.parameters(params, react);\n}\n\nfunction flag(bit) {\n return function (state) {\n const f = this.flags;\n if (arguments.length === 0) return !!(f & bit);\n this.flags = state ? f | bit : f & ~bit;\n return this;\n };\n}\n\nOperator.prototype = {\n /**\n * Returns a list of target operators dependent on this operator.\n * If this list does not exist, it is created and then returned.\n * @return {UniqueList}\n */\n targets() {\n return this._targets || (this._targets = UniqueList(id));\n },\n\n /**\n * Sets the value of this operator.\n * @param {*} value - the value to set.\n * @return {Number} Returns 1 if the operator value has changed\n * according to strict equality, returns 0 otherwise.\n */\n set(value) {\n if (this.value !== value) {\n this.value = value;\n return 1;\n } else {\n return 0;\n }\n },\n\n /**\n * Indicates that operator evaluation should be skipped on the next pulse.\n * This operator will still propagate incoming pulses, but its update function\n * will not be invoked. The skip flag is reset after every pulse, so calling\n * this method will affect processing of the next pulse only.\n */\n skip: flag(SKIP$1),\n\n /**\n * Indicates that this operator's value has been modified on its most recent\n * pulse. Normally modification is checked via strict equality; however, in\n * some cases it is more efficient to update the internal state of an object.\n * In those cases, the modified flag can be used to trigger propagation. Once\n * set, the modification flag persists across pulses until unset. The flag can\n * be used with the last timestamp to test if a modification is recent.\n */\n modified: flag(MODIFIED),\n\n /**\n * Sets the parameters for this operator. The parameter values are analyzed for\n * operator instances. If found, this operator will be added as a dependency\n * of the parameterizing operator. Operator values are dynamically marshalled\n * from each operator parameter prior to evaluation. If a parameter value is\n * an array, the array will also be searched for Operator instances. However,\n * the search does not recurse into sub-arrays or object properties.\n * @param {object} params - A hash of operator parameters.\n * @param {boolean} [react=true] - A flag indicating if this operator should\n * automatically update (react) when parameter values change. In other words,\n * this flag determines if the operator registers itself as a listener on\n * any upstream operators included in the parameters.\n * @param {boolean} [initonly=false] - A flag indicating if this operator\n * should calculate an update only upon its initiatal evaluation, then\n * deregister dependencies and suppress all future update invocations.\n * @return {Operator[]} - An array of upstream dependencies.\n */\n parameters(params, react, initonly) {\n react = react !== false;\n const argval = this._argval = this._argval || new Parameters(),\n argops = this._argops = this._argops || [],\n deps = [];\n let name, value, n, i;\n\n const add = (name, index, value) => {\n if (value instanceof Operator) {\n if (value !== this) {\n if (react) value.targets().add(this);\n deps.push(value);\n }\n\n argops.push({\n op: value,\n name: name,\n index: index\n });\n } else {\n argval.set(name, index, value);\n }\n };\n\n for (name in params) {\n value = params[name];\n\n if (name === PULSE) {\n array(value).forEach(op => {\n if (!(op instanceof Operator)) {\n error('Pulse parameters must be operator instances.');\n } else if (op !== this) {\n op.targets().add(this);\n deps.push(op);\n }\n });\n this.source = value;\n } else if (isArray(value)) {\n argval.set(name, -1, Array(n = value.length));\n\n for (i = 0; i < n; ++i) add(name, i, value[i]);\n } else {\n add(name, -1, value);\n }\n }\n\n this.marshall().clear(); // initialize values\n\n if (initonly) argops.initonly = true;\n return deps;\n },\n\n /**\n * Internal method for marshalling parameter values.\n * Visits each operator dependency to pull the latest value.\n * @return {Parameters} A Parameters object to pass to the update function.\n */\n marshall(stamp) {\n const argval = this._argval || NO_PARAMS,\n argops = this._argops;\n let item, i, op, mod;\n\n if (argops) {\n const n = argops.length;\n\n for (i = 0; i < n; ++i) {\n item = argops[i];\n op = item.op;\n mod = op.modified() && op.stamp === stamp;\n argval.set(item.name, item.index, op.value, mod);\n }\n\n if (argops.initonly) {\n for (i = 0; i < n; ++i) {\n item = argops[i];\n item.op.targets().remove(this);\n }\n\n this._argops = null;\n this._update = null;\n }\n }\n\n return argval;\n },\n\n /**\n * Detach this operator from the dataflow.\n * Unregisters listeners on upstream dependencies.\n */\n detach() {\n const argops = this._argops;\n let i, n, item, op;\n\n if (argops) {\n for (i = 0, n = argops.length; i < n; ++i) {\n item = argops[i];\n op = item.op;\n\n if (op._targets) {\n op._targets.remove(this);\n }\n }\n } // remove references to the source and pulse object,\n // if present, to prevent memory leaks of old data.\n\n\n this.pulse = null;\n this.source = null;\n },\n\n /**\n * Delegate method to perform operator processing.\n * Subclasses can override this method to perform custom processing.\n * By default, it marshalls parameters and calls the update function\n * if that function is defined. If the update function does not\n * change the operator value then StopPropagation is returned.\n * If no update function is defined, this method does nothing.\n * @param {Pulse} pulse - the current dataflow pulse.\n * @return The output pulse or StopPropagation. A falsy return value\n * (including undefined) will let the input pulse pass through.\n */\n evaluate(pulse) {\n const update = this._update;\n\n if (update) {\n const params = this.marshall(pulse.stamp),\n v = update.call(this, params, pulse);\n params.clear();\n\n if (v !== this.value) {\n this.value = v;\n } else if (!this.modified()) {\n return pulse.StopPropagation;\n }\n }\n },\n\n /**\n * Run this operator for the current pulse. If this operator has already\n * been run at (or after) the pulse timestamp, returns StopPropagation.\n * Internally, this method calls {@link evaluate} to perform processing.\n * If {@link evaluate} returns a falsy value, the input pulse is returned.\n * This method should NOT be overridden, instead overrride {@link evaluate}.\n * @param {Pulse} pulse - the current dataflow pulse.\n * @return the output pulse for this operator (or StopPropagation)\n */\n run(pulse) {\n if (pulse.stamp < this.stamp) return pulse.StopPropagation;\n let rv;\n\n if (this.skip()) {\n this.skip(false);\n rv = 0;\n } else {\n rv = this.evaluate(pulse);\n }\n\n return this.pulse = rv || pulse;\n }\n\n};\n\n/**\n * Add an operator to the dataflow graph. This function accepts a\n * variety of input argument types. The basic signature supports an\n * initial value, update function and parameters. If the first parameter\n * is an Operator instance, it will be added directly. If it is a\n * constructor for an Operator subclass, a new instance will be instantiated.\n * Otherwise, if the first parameter is a function instance, it will be used\n * as the update function and a null initial value is assumed.\n * @param {*} init - One of: the operator to add, the initial value of\n * the operator, an operator class to instantiate, or an update function.\n * @param {function} [update] - The operator update function.\n * @param {object} [params] - The operator parameters.\n * @param {boolean} [react=true] - Flag indicating if this operator should\n * listen for changes to upstream operators included as parameters.\n * @return {Operator} - The added operator.\n */\n\nfunction add (init, update, params, react) {\n let shift = 1,\n op;\n\n if (init instanceof Operator) {\n op = init;\n } else if (init && init.prototype instanceof Operator) {\n op = new init();\n } else if (isFunction(init)) {\n op = new Operator(null, init);\n } else {\n shift = 0;\n op = new Operator(init, update);\n }\n\n this.rank(op);\n\n if (shift) {\n react = params;\n params = update;\n }\n\n if (params) this.connect(op, op.parameters(params, react));\n this.touch(op);\n return op;\n}\n\n/**\n * Connect a target operator as a dependent of source operators.\n * If necessary, this method will rerank the target operator and its\n * dependents to ensure propagation proceeds in a topologically sorted order.\n * @param {Operator} target - The target operator.\n * @param {Array} - The source operators that should propagate\n * to the target operator.\n */\nfunction connect (target, sources) {\n const targetRank = target.rank,\n n = sources.length;\n\n for (let i = 0; i < n; ++i) {\n if (targetRank < sources[i].rank) {\n this.rerank(target);\n return;\n }\n }\n}\n\nlet STREAM_ID = 0;\n/**\n * Models an event stream.\n * @constructor\n * @param {function(Object, number): boolean} [filter] - Filter predicate.\n * Events pass through when truthy, events are suppressed when falsy.\n * @param {function(Object): *} [apply] - Applied to input events to produce\n * new event values.\n * @param {function(Object)} [receive] - Event callback function to invoke\n * upon receipt of a new event. Use to override standard event processing.\n */\n\nfunction EventStream(filter, apply, receive) {\n this.id = ++STREAM_ID;\n this.value = null;\n if (receive) this.receive = receive;\n if (filter) this._filter = filter;\n if (apply) this._apply = apply;\n}\n/**\n * Creates a new event stream instance with the provided\n * (optional) filter, apply and receive functions.\n * @param {function(Object, number): boolean} [filter] - Filter predicate.\n * Events pass through when truthy, events are suppressed when falsy.\n * @param {function(Object): *} [apply] - Applied to input events to produce\n * new event values.\n * @see EventStream\n */\n\nfunction stream(filter, apply, receive) {\n return new EventStream(filter, apply, receive);\n}\nEventStream.prototype = {\n _filter: truthy,\n _apply: identity,\n\n targets() {\n return this._targets || (this._targets = UniqueList(id));\n },\n\n consume(_) {\n if (!arguments.length) return !!this._consume;\n this._consume = !!_;\n return this;\n },\n\n receive(evt) {\n if (this._filter(evt)) {\n const val = this.value = this._apply(evt),\n trg = this._targets,\n n = trg ? trg.length : 0;\n\n for (let i = 0; i < n; ++i) trg[i].receive(val);\n\n if (this._consume) {\n evt.preventDefault();\n evt.stopPropagation();\n }\n }\n },\n\n filter(filter) {\n const s = stream(filter);\n this.targets().add(s);\n return s;\n },\n\n apply(apply) {\n const s = stream(null, apply);\n this.targets().add(s);\n return s;\n },\n\n merge() {\n const s = stream();\n this.targets().add(s);\n\n for (let i = 0, n = arguments.length; i < n; ++i) {\n arguments[i].targets().add(s);\n }\n\n return s;\n },\n\n throttle(pause) {\n let t = -1;\n return this.filter(() => {\n const now = Date.now();\n\n if (now - t > pause) {\n t = now;\n return 1;\n } else {\n return 0;\n }\n });\n },\n\n debounce(delay) {\n const s = stream();\n this.targets().add(stream(null, null, debounce(delay, e => {\n const df = e.dataflow;\n s.receive(e);\n if (df && df.run) df.run();\n })));\n return s;\n },\n\n between(a, b) {\n let active = false;\n a.targets().add(stream(null, null, () => active = true));\n b.targets().add(stream(null, null, () => active = false));\n return this.filter(() => active);\n },\n\n detach() {\n // ensures compatibility with operators (#2753)\n // remove references to other streams and filter functions that may\n // be bound to subcontexts that need to be garbage collected.\n this._filter = truthy;\n this._targets = null;\n }\n\n};\n\n/**\n * Create a new event stream from an event source.\n * @param {object} source - The event source to monitor. The input must\n * support the addEventListener method.\n * @param {string} type - The event type.\n * @param {function(object): boolean} [filter] - Event filter function.\n * @param {function(object): *} [apply] - Event application function.\n * If provided, this function will be invoked and the result will be\n * used as the downstream event value.\n * @return {EventStream}\n */\n\nfunction events (source, type, filter, apply) {\n const df = this,\n s = stream(filter, apply),\n send = function (e) {\n e.dataflow = df;\n\n try {\n s.receive(e);\n } catch (error) {\n df.error(error);\n } finally {\n df.run();\n }\n };\n\n let sources;\n\n if (typeof source === 'string' && typeof document !== 'undefined') {\n sources = document.querySelectorAll(source);\n } else {\n sources = array(source);\n }\n\n const n = sources.length;\n\n for (let i = 0; i < n; ++i) {\n sources[i].addEventListener(type, send);\n }\n\n return s;\n}\n\nfunction parse(data, format) {\n const locale = this.locale();\n return read(data, format, locale.timeParse, locale.utcParse);\n}\n/**\n * Ingests new data into the dataflow. First parses the data using the\n * vega-loader read method, then pulses a changeset to the target operator.\n * @param {Operator} target - The Operator to target with ingested data,\n * typically a Collect transform instance.\n * @param {*} data - The input data, prior to parsing. For JSON this may\n * be a string or an object. For CSV, TSV, etc should be a string.\n * @param {object} format - The data format description for parsing\n * loaded data. This object is passed to the vega-loader read method.\n * @returns {Dataflow}\n */\n\nfunction ingest(target, data, format) {\n data = this.parse(data, format);\n return this.pulse(target, this.changeset().insert(data));\n}\n/**\n * Request data from an external source, parse it, and return a Promise.\n * @param {string} url - The URL from which to load the data. This string\n * is passed to the vega-loader load method.\n * @param {object} [format] - The data format description for parsing\n * loaded data. This object is passed to the vega-loader read method.\n * @return {Promise} A Promise that resolves upon completion of the request.\n * The resolved object contains the following properties:\n * - data: an array of parsed data (or null upon error)\n * - status: a code for success (0), load fail (-1), or parse fail (-2)\n */\n\nasync function request(url, format) {\n const df = this;\n let status = 0,\n data;\n\n try {\n data = await df.loader().load(url, {\n context: 'dataflow',\n response: responseType(format && format.type)\n });\n\n try {\n data = df.parse(data, format);\n } catch (err) {\n status = -2;\n df.warn('Data ingestion failed', url, err);\n }\n } catch (err) {\n status = -1;\n df.warn('Loading failed', url, err);\n }\n\n return {\n data,\n status\n };\n}\nasync function preload(target, url, format) {\n const df = this,\n pending = df._pending || loadPending(df);\n pending.requests += 1;\n const res = await df.request(url, format);\n df.pulse(target, df.changeset().remove(truthy).insert(res.data || []));\n pending.done();\n return res;\n}\n\nfunction loadPending(df) {\n let accept;\n const pending = new Promise(a => accept = a);\n pending.requests = 0;\n\n pending.done = () => {\n if (--pending.requests === 0) {\n df._pending = null;\n accept(df);\n }\n };\n\n return df._pending = pending;\n}\n\nconst SKIP = {\n skip: true\n};\n/**\n * Perform operator updates in response to events. Applies an\n * update function to compute a new operator value. If the update function\n * returns a {@link ChangeSet}, the operator will be pulsed with those tuple\n * changes. Otherwise, the operator value will be updated to the return value.\n * @param {EventStream|Operator} source - The event source to react to.\n * This argument can be either an EventStream or an Operator.\n * @param {Operator|function(object):Operator} target - The operator to update.\n * This argument can either be an Operator instance or (if the source\n * argument is an EventStream), a function that accepts an event object as\n * input and returns an Operator to target.\n * @param {function(Parameters,Event): *} [update] - Optional update function\n * to compute the new operator value, or a literal value to set. Update\n * functions expect to receive a parameter object and event as arguments.\n * This function can either return a new operator value or (if the source\n * argument is an EventStream) a {@link ChangeSet} instance to pulse\n * the target operator with tuple changes.\n * @param {object} [params] - The update function parameters.\n * @param {object} [options] - Additional options hash. If not overridden,\n * updated operators will be skipped by default.\n * @param {boolean} [options.skip] - If true, the operator will\n * be skipped: it will not be evaluated, but its dependents will be.\n * @param {boolean} [options.force] - If true, the operator will\n * be re-evaluated even if its value has not changed.\n * @return {Dataflow}\n */\n\nfunction on (source, target, update, params, options) {\n const fn = source instanceof Operator ? onOperator : onStream;\n fn(this, source, target, update, params, options);\n return this;\n}\n\nfunction onStream(df, stream, target, update, params, options) {\n const opt = extend({}, options, SKIP);\n let func, op;\n if (!isFunction(target)) target = constant(target);\n\n if (update === undefined) {\n func = e => df.touch(target(e));\n } else if (isFunction(update)) {\n op = new Operator(null, update, params, false);\n\n func = e => {\n op.evaluate(e);\n const t = target(e),\n v = op.value;\n isChangeSet(v) ? df.pulse(t, v, options) : df.update(t, v, opt);\n };\n } else {\n func = e => df.update(target(e), update, opt);\n }\n\n stream.apply(func);\n}\n\nfunction onOperator(df, source, target, update, params, options) {\n if (update === undefined) {\n source.targets().add(target);\n } else {\n const opt = options || {},\n op = new Operator(null, updater(target, update), params, false);\n op.modified(opt.force);\n op.rank = source.rank; // immediately follow source\n\n source.targets().add(op); // add dependency\n\n if (target) {\n op.skip(true); // skip first invocation\n\n op.value = target.value; // initialize value\n\n op.targets().add(target); // chain dependencies\n\n df.connect(target, [op]); // rerank as needed, #1672\n }\n }\n}\n\nfunction updater(target, update) {\n update = isFunction(update) ? update : constant(update);\n return target ? function (_, pulse) {\n const value = update(_, pulse);\n\n if (!target.skip()) {\n target.skip(value !== this.value).value = value;\n }\n\n return value;\n } : update;\n}\n\n/**\n * Assigns a rank to an operator. Ranks are assigned in increasing order\n * by incrementing an internal rank counter.\n * @param {Operator} op - The operator to assign a rank.\n */\n\nfunction rank(op) {\n op.rank = ++this._rank;\n}\n/**\n * Re-ranks an operator and all downstream target dependencies. This\n * is necessary when upstream dependencies of higher rank are added to\n * a target operator.\n * @param {Operator} op - The operator to re-rank.\n */\n\nfunction rerank(op) {\n const queue = [op];\n let cur, list, i;\n\n while (queue.length) {\n this.rank(cur = queue.pop());\n\n if (list = cur._targets) {\n for (i = list.length; --i >= 0;) {\n queue.push(cur = list[i]);\n if (cur === op) error('Cycle detected in dataflow graph.');\n }\n }\n }\n}\n\n/**\n * Sentinel value indicating pulse propagation should stop.\n */\n\nconst StopPropagation = {}; // Pulse visit type flags\n\nconst ADD = 1 << 0,\n REM = 1 << 1,\n MOD = 1 << 2,\n ADD_REM = ADD | REM,\n ADD_MOD = ADD | MOD,\n ALL = ADD | REM | MOD,\n REFLOW = 1 << 3,\n SOURCE = 1 << 4,\n NO_SOURCE = 1 << 5,\n NO_FIELDS = 1 << 6;\n/**\n * A Pulse enables inter-operator communication during a run of the\n * dataflow graph. In addition to the current timestamp, a pulse may also\n * contain a change-set of added, removed or modified data tuples, as well as\n * a pointer to a full backing data source. Tuple change sets may not\n * be fully materialized; for example, to prevent needless array creation\n * a change set may include larger arrays and corresponding filter functions.\n * The pulse provides a {@link visit} method to enable proper and efficient\n * iteration over requested data tuples.\n *\n * In addition, each pulse can track modification flags for data tuple fields.\n * Responsible transform operators should call the {@link modifies} method to\n * indicate changes to data fields. The {@link modified} method enables\n * querying of this modification state.\n *\n * @constructor\n * @param {Dataflow} dataflow - The backing dataflow instance.\n * @param {number} stamp - The current propagation timestamp.\n * @param {string} [encode] - An optional encoding set name, which is then\n * accessible as Pulse.encode. Operators can respond to (or ignore) this\n * setting as appropriate. This parameter can be used in conjunction with\n * the Encode transform in the vega-encode module.\n */\n\nfunction Pulse(dataflow, stamp, encode) {\n this.dataflow = dataflow;\n this.stamp = stamp == null ? -1 : stamp;\n this.add = [];\n this.rem = [];\n this.mod = [];\n this.fields = null;\n this.encode = encode || null;\n}\n\nfunction materialize(data, filter) {\n const out = [];\n visitArray(data, filter, _ => out.push(_));\n return out;\n}\n\nfunction filter(pulse, flags) {\n const map = {};\n pulse.visit(flags, t => {\n map[tupleid(t)] = 1;\n });\n return t => map[tupleid(t)] ? null : t;\n}\n\nfunction addFilter(a, b) {\n return a ? (t, i) => a(t, i) && b(t, i) : b;\n}\n\nPulse.prototype = {\n /**\n * Sentinel value indicating pulse propagation should stop.\n */\n StopPropagation,\n\n /**\n * Boolean flag indicating ADD (added) tuples.\n */\n ADD,\n\n /**\n * Boolean flag indicating REM (removed) tuples.\n */\n REM,\n\n /**\n * Boolean flag indicating MOD (modified) tuples.\n */\n MOD,\n\n /**\n * Boolean flag indicating ADD (added) and REM (removed) tuples.\n */\n ADD_REM,\n\n /**\n * Boolean flag indicating ADD (added) and MOD (modified) tuples.\n */\n ADD_MOD,\n\n /**\n * Boolean flag indicating ADD, REM and MOD tuples.\n */\n ALL,\n\n /**\n * Boolean flag indicating all tuples in a data source\n * except for the ADD, REM and MOD tuples.\n */\n REFLOW,\n\n /**\n * Boolean flag indicating a 'pass-through' to a\n * backing data source, ignoring ADD, REM and MOD tuples.\n */\n SOURCE,\n\n /**\n * Boolean flag indicating that source data should be\n * suppressed when creating a forked pulse.\n */\n NO_SOURCE,\n\n /**\n * Boolean flag indicating that field modifications should be\n * suppressed when creating a forked pulse.\n */\n NO_FIELDS,\n\n /**\n * Creates a new pulse based on the values of this pulse.\n * The dataflow, time stamp and field modification values are copied over.\n * By default, new empty ADD, REM and MOD arrays are created.\n * @param {number} flags - Integer of boolean flags indicating which (if any)\n * tuple arrays should be copied to the new pulse. The supported flag values\n * are ADD, REM and MOD. Array references are copied directly: new array\n * instances are not created.\n * @return {Pulse} - The forked pulse instance.\n * @see init\n */\n fork(flags) {\n return new Pulse(this.dataflow).init(this, flags);\n },\n\n /**\n * Creates a copy of this pulse with new materialized array\n * instances for the ADD, REM, MOD, and SOURCE arrays.\n * The dataflow, time stamp and field modification values are copied over.\n * @return {Pulse} - The cloned pulse instance.\n * @see init\n */\n clone() {\n const p = this.fork(ALL);\n p.add = p.add.slice();\n p.rem = p.rem.slice();\n p.mod = p.mod.slice();\n if (p.source) p.source = p.source.slice();\n return p.materialize(ALL | SOURCE);\n },\n\n /**\n * Returns a pulse that adds all tuples from a backing source. This is\n * useful for cases where operators are added to a dataflow after an\n * upstream data pipeline has already been processed, ensuring that\n * new operators can observe all tuples within a stream.\n * @return {Pulse} - A pulse instance with all source tuples included\n * in the add array. If the current pulse already has all source\n * tuples in its add array, it is returned directly. If the current\n * pulse does not have a backing source, it is returned directly.\n */\n addAll() {\n let p = this;\n const reuse = !p.source || p.add === p.rem // special case for indexed set (e.g., crossfilter)\n || !p.rem.length && p.source.length === p.add.length;\n\n if (reuse) {\n return p;\n } else {\n p = new Pulse(this.dataflow).init(this);\n p.add = p.source;\n p.rem = []; // new operators can ignore rem #2769\n\n return p;\n }\n },\n\n /**\n * Initialize this pulse based on the values of another pulse. This method\n * is used internally by {@link fork} to initialize a new forked tuple.\n * The dataflow, time stamp and field modification values are copied over.\n * By default, new empty ADD, REM and MOD arrays are created.\n * @param {Pulse} src - The source pulse to copy from.\n * @param {number} flags - Integer of boolean flags indicating which (if any)\n * tuple arrays should be copied to the new pulse. The supported flag values\n * are ADD, REM and MOD. Array references are copied directly: new array\n * instances are not created. By default, source data arrays are copied\n * to the new pulse. Use the NO_SOURCE flag to enforce a null source.\n * @return {Pulse} - Returns this Pulse instance.\n */\n init(src, flags) {\n const p = this;\n p.stamp = src.stamp;\n p.encode = src.encode;\n\n if (src.fields && !(flags & NO_FIELDS)) {\n p.fields = src.fields;\n }\n\n if (flags & ADD) {\n p.addF = src.addF;\n p.add = src.add;\n } else {\n p.addF = null;\n p.add = [];\n }\n\n if (flags & REM) {\n p.remF = src.remF;\n p.rem = src.rem;\n } else {\n p.remF = null;\n p.rem = [];\n }\n\n if (flags & MOD) {\n p.modF = src.modF;\n p.mod = src.mod;\n } else {\n p.modF = null;\n p.mod = [];\n }\n\n if (flags & NO_SOURCE) {\n p.srcF = null;\n p.source = null;\n } else {\n p.srcF = src.srcF;\n p.source = src.source;\n if (src.cleans) p.cleans = src.cleans;\n }\n\n return p;\n },\n\n /**\n * Schedules a function to run after pulse propagation completes.\n * @param {function} func - The function to run.\n */\n runAfter(func) {\n this.dataflow.runAfter(func);\n },\n\n /**\n * Indicates if tuples have been added, removed or modified.\n * @param {number} [flags] - The tuple types (ADD, REM or MOD) to query.\n * Defaults to ALL, returning true if any tuple type has changed.\n * @return {boolean} - Returns true if one or more queried tuple types have\n * changed, false otherwise.\n */\n changed(flags) {\n const f = flags || ALL;\n return f & ADD && this.add.length || f & REM && this.rem.length || f & MOD && this.mod.length;\n },\n\n /**\n * Forces a \"reflow\" of tuple values, such that all tuples in the backing\n * source are added to the MOD set, unless already present in the ADD set.\n * @param {boolean} [fork=false] - If true, returns a forked copy of this\n * pulse, and invokes reflow on that derived pulse.\n * @return {Pulse} - The reflowed pulse instance.\n */\n reflow(fork) {\n if (fork) return this.fork(ALL).reflow();\n const len = this.add.length,\n src = this.source && this.source.length;\n\n if (src && src !== len) {\n this.mod = this.source;\n if (len) this.filter(MOD, filter(this, ADD));\n }\n\n return this;\n },\n\n /**\n * Get/set metadata to pulse requesting garbage collection\n * to reclaim currently unused resources.\n */\n clean(value) {\n if (arguments.length) {\n this.cleans = !!value;\n return this;\n } else {\n return this.cleans;\n }\n },\n\n /**\n * Marks one or more data field names as modified to assist dependency\n * tracking and incremental processing by transform operators.\n * @param {string|Array} _ - The field(s) to mark as modified.\n * @return {Pulse} - This pulse instance.\n */\n modifies(_) {\n const hash = this.fields || (this.fields = {});\n\n if (isArray(_)) {\n _.forEach(f => hash[f] = true);\n } else {\n hash[_] = true;\n }\n\n return this;\n },\n\n /**\n * Checks if one or more data fields have been modified during this pulse\n * propagation timestamp.\n * @param {string|Array} _ - The field(s) to check for modified.\n * @param {boolean} nomod - If true, will check the modified flag even if\n * no mod tuples exist. If false (default), mod tuples must be present.\n * @return {boolean} - Returns true if any of the provided fields has been\n * marked as modified, false otherwise.\n */\n modified(_, nomod) {\n const fields = this.fields;\n return !((nomod || this.mod.length) && fields) ? false : !arguments.length ? !!fields : isArray(_) ? _.some(f => fields[f]) : fields[_];\n },\n\n /**\n * Adds a filter function to one more tuple sets. Filters are applied to\n * backing tuple arrays, to determine the actual set of tuples considered\n * added, removed or modified. They can be used to delay materialization of\n * a tuple set in order to avoid expensive array copies. In addition, the\n * filter functions can serve as value transformers: unlike standard predicate\n * function (which return boolean values), Pulse filters should return the\n * actual tuple value to process. If a tuple set is already filtered, the\n * new filter function will be appended into a conjuntive ('and') query.\n * @param {number} flags - Flags indicating the tuple set(s) to filter.\n * @param {function(*):object} filter - Filter function that will be applied\n * to the tuple set array, and should return a data tuple if the value\n * should be included in the tuple set, and falsy (or null) otherwise.\n * @return {Pulse} - Returns this pulse instance.\n */\n filter(flags, filter) {\n const p = this;\n if (flags & ADD) p.addF = addFilter(p.addF, filter);\n if (flags & REM) p.remF = addFilter(p.remF, filter);\n if (flags & MOD) p.modF = addFilter(p.modF, filter);\n if (flags & SOURCE) p.srcF = addFilter(p.srcF, filter);\n return p;\n },\n\n /**\n * Materialize one or more tuple sets in this pulse. If the tuple set(s) have\n * a registered filter function, it will be applied and the tuple set(s) will\n * be replaced with materialized tuple arrays.\n * @param {number} flags - Flags indicating the tuple set(s) to materialize.\n * @return {Pulse} - Returns this pulse instance.\n */\n materialize(flags) {\n flags = flags || ALL;\n const p = this;\n\n if (flags & ADD && p.addF) {\n p.add = materialize(p.add, p.addF);\n p.addF = null;\n }\n\n if (flags & REM && p.remF) {\n p.rem = materialize(p.rem, p.remF);\n p.remF = null;\n }\n\n if (flags & MOD && p.modF) {\n p.mod = materialize(p.mod, p.modF);\n p.modF = null;\n }\n\n if (flags & SOURCE && p.srcF) {\n p.source = p.source.filter(p.srcF);\n p.srcF = null;\n }\n\n return p;\n },\n\n /**\n * Visit one or more tuple sets in this pulse.\n * @param {number} flags - Flags indicating the tuple set(s) to visit.\n * Legal values are ADD, REM, MOD and SOURCE (if a backing data source\n * has been set).\n * @param {function(object):*} - Visitor function invoked per-tuple.\n * @return {Pulse} - Returns this pulse instance.\n */\n visit(flags, visitor) {\n const p = this,\n v = visitor;\n\n if (flags & SOURCE) {\n visitArray(p.source, p.srcF, v);\n return p;\n }\n\n if (flags & ADD) visitArray(p.add, p.addF, v);\n if (flags & REM) visitArray(p.rem, p.remF, v);\n if (flags & MOD) visitArray(p.mod, p.modF, v);\n const src = p.source;\n\n if (flags & REFLOW && src) {\n const sum = p.add.length + p.mod.length;\n\n if (sum === src.length) ; else if (sum) {\n visitArray(src, filter(p, ADD_MOD), v);\n } else {\n // if no add/rem/mod tuples, visit source\n visitArray(src, p.srcF, v);\n }\n }\n\n return p;\n }\n\n};\n\n/**\n * Represents a set of multiple pulses. Used as input for operators\n * that accept multiple pulses at a time. Contained pulses are\n * accessible via the public \"pulses\" array property. This pulse doe\n * not carry added, removed or modified tuples directly. However,\n * the visit method can be used to traverse all such tuples contained\n * in sub-pulses with a timestamp matching this parent multi-pulse.\n * @constructor\n * @param {Dataflow} dataflow - The backing dataflow instance.\n * @param {number} stamp - The timestamp.\n * @param {Array} pulses - The sub-pulses for this multi-pulse.\n */\n\nfunction MultiPulse(dataflow, stamp, pulses, encode) {\n const p = this,\n n = pulses.length;\n let c = 0;\n this.dataflow = dataflow;\n this.stamp = stamp;\n this.fields = null;\n this.encode = encode || null;\n this.pulses = pulses;\n\n for (let i = 0; i < n; ++i) {\n const pulse = pulses[i];\n if (pulse.stamp !== stamp) continue;\n\n if (pulse.fields) {\n const hash = p.fields || (p.fields = {});\n\n for (const f in pulse.fields) {\n hash[f] = 1;\n }\n }\n\n if (pulse.changed(p.ADD)) c |= p.ADD;\n if (pulse.changed(p.REM)) c |= p.REM;\n if (pulse.changed(p.MOD)) c |= p.MOD;\n }\n\n this.changes = c;\n}\ninherits(MultiPulse, Pulse, {\n /**\n * Creates a new pulse based on the values of this pulse.\n * The dataflow, time stamp and field modification values are copied over.\n * @return {Pulse}\n */\n fork(flags) {\n const p = new Pulse(this.dataflow).init(this, flags & this.NO_FIELDS);\n\n if (flags !== undefined) {\n if (flags & p.ADD) this.visit(p.ADD, t => p.add.push(t));\n if (flags & p.REM) this.visit(p.REM, t => p.rem.push(t));\n if (flags & p.MOD) this.visit(p.MOD, t => p.mod.push(t));\n }\n\n return p;\n },\n\n changed(flags) {\n return this.changes & flags;\n },\n\n modified(_) {\n const p = this,\n fields = p.fields;\n return !(fields && p.changes & p.MOD) ? 0 : isArray(_) ? _.some(f => fields[f]) : fields[_];\n },\n\n filter() {\n error('MultiPulse does not support filtering.');\n },\n\n materialize() {\n error('MultiPulse does not support materialization.');\n },\n\n visit(flags, visitor) {\n const p = this,\n pulses = p.pulses,\n n = pulses.length;\n let i = 0;\n\n if (flags & p.SOURCE) {\n for (; i < n; ++i) {\n pulses[i].visit(flags, visitor);\n }\n } else {\n for (; i < n; ++i) {\n if (pulses[i].stamp === p.stamp) {\n pulses[i].visit(flags, visitor);\n }\n }\n }\n\n return p;\n }\n\n});\n\n/* eslint-disable require-atomic-updates */\n/**\n * Evaluates the dataflow and returns a Promise that resolves when pulse\n * propagation completes. This method will increment the current timestamp\n * and process all updated, pulsed and touched operators. When invoked for\n * the first time, all registered operators will be processed. This method\n * should not be invoked by third-party clients, use {@link runAsync} or\n * {@link run} instead.\n * @param {string} [encode] - The name of an encoding set to invoke during\n * propagation. This value is added to generated Pulse instances;\n * operators can then respond to (or ignore) this setting as appropriate.\n * This parameter can be used in conjunction with the Encode transform in\n * the vega-encode package.\n * @param {function} [prerun] - An optional callback function to invoke\n * immediately before dataflow evaluation commences.\n * @param {function} [postrun] - An optional callback function to invoke\n * after dataflow evaluation completes. The callback will be invoked\n * after those registered via {@link runAfter}.\n * @return {Promise} - A promise that resolves to this dataflow after\n * evaluation completes.\n */\n\nasync function evaluate(encode, prerun, postrun) {\n const df = this,\n async = []; // if the pulse value is set, this is a re-entrant call\n\n if (df._pulse) return reentrant(df); // wait for pending datasets to load\n\n if (df._pending) await df._pending; // invoke prerun function, if provided\n\n if (prerun) await asyncCallback(df, prerun); // exit early if there are no updates\n\n if (!df._touched.length) {\n df.debug('Dataflow invoked, but nothing to do.');\n return df;\n } // increment timestamp clock\n\n\n const stamp = ++df._clock; // set the current pulse\n\n df._pulse = new Pulse(df, stamp, encode); // initialize priority queue, reset touched operators\n\n df._touched.forEach(op => df._enqueue(op, true));\n\n df._touched = UniqueList(id);\n let count = 0,\n op,\n next,\n error;\n\n try {\n while (df._heap.size() > 0) {\n // dequeue operator with highest priority\n op = df._heap.pop(); // re-queue if rank changed\n\n if (op.rank !== op.qrank) {\n df._enqueue(op, true);\n\n continue;\n } // otherwise, evaluate the operator\n\n\n next = op.run(df._getPulse(op, encode));\n\n if (next.then) {\n // await if operator returns a promise directly\n next = await next;\n } else if (next.async) {\n // queue parallel asynchronous execution\n async.push(next.async);\n next = StopPropagation;\n } // propagate evaluation, enqueue dependent operators\n\n\n if (next !== StopPropagation) {\n if (op._targets) op._targets.forEach(op => df._enqueue(op));\n } // increment visit counter\n\n\n ++count;\n }\n } catch (err) {\n df._heap.clear();\n\n error = err;\n } // reset pulse map\n\n\n df._input = {};\n df._pulse = null;\n df.debug(`Pulse ${stamp}: ${count} operators`);\n\n if (error) {\n df._postrun = [];\n df.error(error);\n } // invoke callbacks queued via runAfter\n\n\n if (df._postrun.length) {\n const pr = df._postrun.sort((a, b) => b.priority - a.priority);\n\n df._postrun = [];\n\n for (let i = 0; i < pr.length; ++i) {\n await asyncCallback(df, pr[i].callback);\n }\n } // invoke postrun function, if provided\n\n\n if (postrun) await asyncCallback(df, postrun); // handle non-blocking asynchronous callbacks\n\n if (async.length) {\n Promise.all(async).then(cb => df.runAsync(null, () => {\n cb.forEach(f => {\n try {\n f(df);\n } catch (err) {\n df.error(err);\n }\n });\n }));\n }\n\n return df;\n}\n/**\n * Queues dataflow evaluation to run once any other queued evaluations have\n * completed and returns a Promise that resolves when the queued pulse\n * propagation completes. If provided, a callback function will be invoked\n * immediately before evaluation commences. This method will ensure a\n * separate evaluation is invoked for each time it is called.\n * @param {string} [encode] - The name of an encoding set to invoke during\n * propagation. This value is added to generated Pulse instances;\n * operators can then respond to (or ignore) this setting as appropriate.\n * This parameter can be used in conjunction with the Encode transform in\n * the vega-encode package.\n * @param {function} [prerun] - An optional callback function to invoke\n * immediately before dataflow evaluation commences.\n * @param {function} [postrun] - An optional callback function to invoke\n * after dataflow evaluation completes. The callback will be invoked\n * after those registered via {@link runAfter}.\n * @return {Promise} - A promise that resolves to this dataflow after\n * evaluation completes.\n */\n\nasync function runAsync(encode, prerun, postrun) {\n // await previously queued functions\n while (this._running) await this._running; // run dataflow, manage running promise\n\n\n const clear = () => this._running = null;\n\n (this._running = this.evaluate(encode, prerun, postrun)).then(clear, clear);\n return this._running;\n}\n/**\n * Requests dataflow evaluation and the immediately returns this dataflow\n * instance. If there are pending data loading or other asynchronous\n * operations, the dataflow will evaluate asynchronously after this method\n * has been invoked. To track when dataflow evaluation completes, use the\n * {@link runAsync} method instead. This method will raise an error if\n * invoked while the dataflow is already in the midst of evaluation.\n * @param {string} [encode] - The name of an encoding set to invoke during\n * propagation. This value is added to generated Pulse instances;\n * operators can then respond to (or ignore) this setting as appropriate.\n * This parameter can be used in conjunction with the Encode transform in\n * the vega-encode module.\n * @param {function} [prerun] - An optional callback function to invoke\n * immediately before dataflow evaluation commences.\n * @param {function} [postrun] - An optional callback function to invoke\n * after dataflow evaluation completes. The callback will be invoked\n * after those registered via {@link runAfter}.\n * @return {Dataflow} - This dataflow instance.\n */\n\nfunction run(encode, prerun, postrun) {\n return this._pulse ? reentrant(this) : (this.evaluate(encode, prerun, postrun), this);\n}\n/**\n * Schedules a callback function to be invoked after the current pulse\n * propagation completes. If no propagation is currently occurring,\n * the function is invoked immediately. Callbacks scheduled via runAfter\n * are invoked immediately upon completion of the current cycle, before\n * any request queued via runAsync. This method is primarily intended for\n * internal use. Third-party callers using runAfter to schedule a callback\n * that invokes {@link run} or {@link runAsync} should not use this method,\n * but instead use {@link runAsync} with prerun or postrun arguments.\n * @param {function(Dataflow)} callback - The callback function to run.\n * The callback will be invoked with this Dataflow instance as its\n * sole argument.\n * @param {boolean} enqueue - A boolean flag indicating that the\n * callback should be queued up to run after the next propagation\n * cycle, suppressing immediate invocation when propagation is not\n * currently occurring.\n * @param {number} [priority] - A priority value used to sort registered\n * callbacks to determine execution order. This argument is intended\n * for internal Vega use only.\n */\n\nfunction runAfter(callback, enqueue, priority) {\n if (this._pulse || enqueue) {\n // pulse propagation is currently running, queue to run after\n this._postrun.push({\n priority: priority || 0,\n callback: callback\n });\n } else {\n // pulse propagation already complete, invoke immediately\n try {\n callback(this);\n } catch (err) {\n this.error(err);\n }\n }\n}\n/**\n * Raise an error for re-entrant dataflow evaluation.\n */\n\nfunction reentrant(df) {\n df.error('Dataflow already running. Use runAsync() to chain invocations.');\n return df;\n}\n/**\n * Enqueue an operator into the priority queue for evaluation. The operator\n * will be enqueued if it has no registered pulse for the current cycle, or if\n * the force argument is true. Upon enqueue, this method also sets the\n * operator's qrank to the current rank value.\n * @param {Operator} op - The operator to enqueue.\n * @param {boolean} [force] - A flag indicating if the operator should be\n * forceably added to the queue, even if it has already been previously\n * enqueued during the current pulse propagation. This is useful when the\n * dataflow graph is dynamically modified and the operator rank changes.\n */\n\n\nfunction enqueue(op, force) {\n const q = op.stamp < this._clock;\n if (q) op.stamp = this._clock;\n\n if (q || force) {\n op.qrank = op.rank;\n\n this._heap.push(op);\n }\n}\n/**\n * Provide a correct pulse for evaluating an operator. If the operator has an\n * explicit source operator, we will try to pull the pulse(s) from it.\n * If there is an array of source operators, we build a multi-pulse.\n * Otherwise, we return a current pulse with correct source data.\n * If the pulse is the pulse map has an explicit target set, we use that.\n * Else if the pulse on the upstream source operator is current, we use that.\n * Else we use the pulse from the pulse map, but copy the source tuple array.\n * @param {Operator} op - The operator for which to get an input pulse.\n * @param {string} [encode] - An (optional) encoding set name with which to\n * annotate the returned pulse. See {@link run} for more information.\n */\n\nfunction getPulse(op, encode) {\n const s = op.source,\n stamp = this._clock;\n return s && isArray(s) ? new MultiPulse(this, stamp, s.map(_ => _.pulse), encode) : this._input[op.id] || singlePulse(this._pulse, s && s.pulse);\n}\n\nfunction singlePulse(p, s) {\n if (s && s.stamp === p.stamp) {\n return s;\n }\n\n p = p.fork();\n\n if (s && s !== StopPropagation) {\n p.source = s.source;\n }\n\n return p;\n}\n\nconst NO_OPT = {\n skip: false,\n force: false\n};\n/**\n * Touches an operator, scheduling it to be evaluated. If invoked outside of\n * a pulse propagation, the operator will be evaluated the next time this\n * dataflow is run. If invoked in the midst of pulse propagation, the operator\n * will be queued for evaluation if and only if the operator has not yet been\n * evaluated on the current propagation timestamp.\n * @param {Operator} op - The operator to touch.\n * @param {object} [options] - Additional options hash.\n * @param {boolean} [options.skip] - If true, the operator will\n * be skipped: it will not be evaluated, but its dependents will be.\n * @return {Dataflow}\n */\n\nfunction touch(op, options) {\n const opt = options || NO_OPT;\n\n if (this._pulse) {\n // if in midst of propagation, add to priority queue\n this._enqueue(op);\n } else {\n // otherwise, queue for next propagation\n this._touched.add(op);\n }\n\n if (opt.skip) op.skip(true);\n return this;\n}\n/**\n * Updates the value of the given operator.\n * @param {Operator} op - The operator to update.\n * @param {*} value - The value to set.\n * @param {object} [options] - Additional options hash.\n * @param {boolean} [options.force] - If true, the operator will\n * be re-evaluated even if its value has not changed.\n * @param {boolean} [options.skip] - If true, the operator will\n * be skipped: it will not be evaluated, but its dependents will be.\n * @return {Dataflow}\n */\n\nfunction update(op, value, options) {\n const opt = options || NO_OPT;\n\n if (op.set(value) || opt.force) {\n this.touch(op, opt);\n }\n\n return this;\n}\n/**\n * Pulses an operator with a changeset of tuples. If invoked outside of\n * a pulse propagation, the pulse will be applied the next time this\n * dataflow is run. If invoked in the midst of pulse propagation, the pulse\n * will be added to the set of active pulses and will be applied if and\n * only if the target operator has not yet been evaluated on the current\n * propagation timestamp.\n * @param {Operator} op - The operator to pulse.\n * @param {ChangeSet} value - The tuple changeset to apply.\n * @param {object} [options] - Additional options hash.\n * @param {boolean} [options.skip] - If true, the operator will\n * be skipped: it will not be evaluated, but its dependents will be.\n * @return {Dataflow}\n */\n\nfunction pulse(op, changeset, options) {\n this.touch(op, options || NO_OPT);\n const p = new Pulse(this, this._clock + (this._pulse ? 0 : 1)),\n t = op.pulse && op.pulse.source || [];\n p.target = op;\n this._input[op.id] = changeset.pulse(p, t);\n return this;\n}\n\nfunction Heap(cmp) {\n let nodes = [];\n return {\n clear: () => nodes = [],\n size: () => nodes.length,\n peek: () => nodes[0],\n push: x => {\n nodes.push(x);\n return siftdown(nodes, 0, nodes.length - 1, cmp);\n },\n pop: () => {\n const last = nodes.pop();\n let item;\n\n if (nodes.length) {\n item = nodes[0];\n nodes[0] = last;\n siftup(nodes, 0, cmp);\n } else {\n item = last;\n }\n\n return item;\n }\n };\n}\n\nfunction siftdown(array, start, idx, cmp) {\n let parent, pidx;\n const item = array[idx];\n\n while (idx > start) {\n pidx = idx - 1 >> 1;\n parent = array[pidx];\n\n if (cmp(item, parent) < 0) {\n array[idx] = parent;\n idx = pidx;\n continue;\n }\n\n break;\n }\n\n return array[idx] = item;\n}\n\nfunction siftup(array, idx, cmp) {\n const start = idx,\n end = array.length,\n item = array[idx];\n let cidx = (idx << 1) + 1,\n ridx;\n\n while (cidx < end) {\n ridx = cidx + 1;\n\n if (ridx < end && cmp(array[cidx], array[ridx]) >= 0) {\n cidx = ridx;\n }\n\n array[idx] = array[cidx];\n idx = cidx;\n cidx = (idx << 1) + 1;\n }\n\n array[idx] = item;\n return siftdown(array, start, idx, cmp);\n}\n\n/**\n * A dataflow graph for reactive processing of data streams.\n * @constructor\n */\n\nfunction Dataflow() {\n this.logger(logger());\n this.logLevel(Error);\n this._clock = 0;\n this._rank = 0;\n this._locale = defaultLocale();\n\n try {\n this._loader = loader();\n } catch (e) {// do nothing if loader module is unavailable\n }\n\n this._touched = UniqueList(id);\n this._input = {};\n this._pulse = null;\n this._heap = Heap((a, b) => a.qrank - b.qrank);\n this._postrun = [];\n}\n\nfunction logMethod(method) {\n return function () {\n return this._log[method].apply(this, arguments);\n };\n}\n\nDataflow.prototype = {\n /**\n * The current timestamp of this dataflow. This value reflects the\n * timestamp of the previous dataflow run. The dataflow is initialized\n * with a stamp value of 0. The initial run of the dataflow will have\n * a timestap of 1, and so on. This value will match the\n * {@link Pulse.stamp} property.\n * @return {number} - The current timestamp value.\n */\n stamp() {\n return this._clock;\n },\n\n /**\n * Gets or sets the loader instance to use for data file loading. A\n * loader object must provide a \"load\" method for loading files and a\n * \"sanitize\" method for checking URL/filename validity. Both methods\n * should accept a URI and options hash as arguments, and return a Promise\n * that resolves to the loaded file contents (load) or a hash containing\n * sanitized URI data with the sanitized url assigned to the \"href\" property\n * (sanitize).\n * @param {object} _ - The loader instance to use.\n * @return {object|Dataflow} - If no arguments are provided, returns\n * the current loader instance. Otherwise returns this Dataflow instance.\n */\n loader(_) {\n if (arguments.length) {\n this._loader = _;\n return this;\n } else {\n return this._loader;\n }\n },\n\n /**\n * Gets or sets the locale instance to use for formatting and parsing\n * string values. The locale object should be provided by the\n * vega-format library, and include methods such as format, timeFormat,\n * utcFormat, timeParse, and utcParse.\n * @param {object} _ - The locale instance to use.\n * @return {object|Dataflow} - If no arguments are provided, returns\n * the current locale instance. Otherwise returns this Dataflow instance.\n */\n locale(_) {\n if (arguments.length) {\n this._locale = _;\n return this;\n } else {\n return this._locale;\n }\n },\n\n /**\n * Get or set the logger instance used to log messages. If no arguments are\n * provided, returns the current logger instance. Otherwise, sets the logger\n * and return this Dataflow instance. Provided loggers must support the full\n * API of logger objects generated by the vega-util logger method. Note that\n * by default the log level of the new logger will be used; use the logLevel\n * method to adjust the log level as needed.\n */\n logger(logger) {\n if (arguments.length) {\n this._log = logger;\n return this;\n } else {\n return this._log;\n }\n },\n\n /**\n * Logs an error message. By default, logged messages are written to console\n * output. The message will only be logged if the current log level is high\n * enough to permit error messages.\n */\n error: logMethod('error'),\n\n /**\n * Logs a warning message. By default, logged messages are written to console\n * output. The message will only be logged if the current log level is high\n * enough to permit warning messages.\n */\n warn: logMethod('warn'),\n\n /**\n * Logs a information message. By default, logged messages are written to\n * console output. The message will only be logged if the current log level is\n * high enough to permit information messages.\n */\n info: logMethod('info'),\n\n /**\n * Logs a debug message. By default, logged messages are written to console\n * output. The message will only be logged if the current log level is high\n * enough to permit debug messages.\n */\n debug: logMethod('debug'),\n\n /**\n * Get or set the current log level. If an argument is provided, it\n * will be used as the new log level.\n * @param {number} [level] - Should be one of None, Warn, Info\n * @return {number} - The current log level.\n */\n logLevel: logMethod('level'),\n\n /**\n * Empty entry threshold for garbage cleaning. Map data structures will\n * perform cleaning once the number of empty entries exceeds this value.\n */\n cleanThreshold: 1e4,\n // OPERATOR REGISTRATION\n add,\n connect,\n rank,\n rerank,\n // OPERATOR UPDATES\n pulse,\n touch,\n update,\n changeset,\n // DATA LOADING\n ingest,\n parse,\n preload,\n request,\n // EVENT HANDLING\n events,\n on,\n // PULSE PROPAGATION\n evaluate,\n run,\n runAsync,\n runAfter,\n _enqueue: enqueue,\n _getPulse: getPulse\n};\n\n/**\n * Abstract class for operators that process data tuples.\n * Subclasses must provide a {@link transform} method for operator processing.\n * @constructor\n * @param {*} [init] - The initial value for this operator.\n * @param {object} [params] - The parameters for this operator.\n * @param {Operator} [source] - The operator from which to receive pulses.\n */\n\nfunction Transform(init, params) {\n Operator.call(this, init, null, params);\n}\ninherits(Transform, Operator, {\n /**\n * Overrides {@link Operator.evaluate} for transform operators.\n * Internally, this method calls {@link evaluate} to perform processing.\n * If {@link evaluate} returns a falsy value, the input pulse is returned.\n * This method should NOT be overridden, instead overrride {@link evaluate}.\n * @param {Pulse} pulse - the current dataflow pulse.\n * @return the output pulse for this operator (or StopPropagation)\n */\n run(pulse) {\n if (pulse.stamp < this.stamp) return pulse.StopPropagation;\n let rv;\n\n if (this.skip()) {\n this.skip(false);\n } else {\n rv = this.evaluate(pulse);\n }\n\n rv = rv || pulse;\n\n if (rv.then) {\n rv = rv.then(_ => this.pulse = _);\n } else if (rv !== pulse.StopPropagation) {\n this.pulse = rv;\n }\n\n return rv;\n },\n\n /**\n * Overrides {@link Operator.evaluate} for transform operators.\n * Marshalls parameter values and then invokes {@link transform}.\n * @param {Pulse} pulse - the current dataflow pulse.\n * @return {Pulse} The output pulse (or StopPropagation). A falsy return\n value (including undefined) will let the input pulse pass through.\n */\n evaluate(pulse) {\n const params = this.marshall(pulse.stamp),\n out = this.transform(params, pulse);\n params.clear();\n return out;\n },\n\n /**\n * Process incoming pulses.\n * Subclasses should override this method to implement transforms.\n * @param {Parameters} _ - The operator parameter values.\n * @param {Pulse} pulse - The current dataflow pulse.\n * @return {Pulse} The output pulse (or StopPropagation). A falsy return\n * value (including undefined) will let the input pulse pass through.\n */\n transform() {}\n\n});\n\nconst transforms = {};\nfunction definition(type) {\n const t = transform(type);\n return t && t.Definition || null;\n}\nfunction transform(type) {\n type = type && type.toLowerCase();\n return hasOwnProperty(transforms, type) ? transforms[type] : null;\n}\n\nexport { Dataflow, EventStream, MultiPulse, Operator, Parameters, Pulse, Transform, UniqueList, asyncCallback, changeset, definition, derive, ingest$1 as ingest, isChangeSet, isTuple, rederive, replace, stableCompare, transform, transforms, tupleid };\n","export default function(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","export default function max(values, valueof) {\n let max;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n }\n return max;\n}\n","export default function min(values, valueof) {\n let min;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n }\n return min;\n}\n","import ascending from \"./ascending.js\";\n\n// Based on https://github.com/mourner/quickselect\n// ISC license, Copyright 2018 Vladimir Agafonkin.\nexport default function quickselect(array, k, left = 0, right = array.length - 1, compare = ascending) {\n while (right > left) {\n if (right - left > 600) {\n const n = right - left + 1;\n const m = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n quickselect(array, k, newLeft, newRight, compare);\n }\n\n const t = array[k];\n let i = left;\n let j = right;\n\n swap(array, left, k);\n if (compare(array[right], t) > 0) swap(array, left, right);\n\n while (i < j) {\n swap(array, i, j), ++i, --j;\n while (compare(array[i], t) < 0) ++i;\n while (compare(array[j], t) > 0) --j;\n }\n\n if (compare(array[left], t) === 0) swap(array, left, j);\n else ++j, swap(array, j, right);\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n return array;\n}\n\nfunction swap(array, i, j) {\n const t = array[i];\n array[i] = array[j];\n array[j] = t;\n}\n","export default function(x) {\n return x === null ? NaN : +x;\n}\n\nexport function* numbers(values, valueof) {\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n yield value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n yield value;\n }\n }\n }\n}\n","import max from \"./max.js\";\nimport min from \"./min.js\";\nimport quickselect from \"./quickselect.js\";\nimport number, {numbers} from \"./number.js\";\n\nexport default function quantile(values, p, valueof) {\n values = Float64Array.from(numbers(values, valueof));\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return min(values);\n if (p >= 1) return max(values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = max(quickselect(values, i0).subarray(0, i0 + 1)),\n value1 = min(values.subarray(i0 + 1));\n return value0 + (value1 - value0) * (i - i0);\n}\n\nexport function quantileSorted(values, p, valueof = number) {\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);\n if (p >= 1) return +valueof(values[n - 1], n - 1, values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = +valueof(values[i0], i0, values),\n value1 = +valueof(values[i0 + 1], i0 + 1, values);\n return value0 + (value1 - value0) * (i - i0);\n}\n","import variance from \"./variance.js\";\n\nexport default function deviation(values, valueof) {\n const v = variance(values, valueof);\n return v ? Math.sqrt(v) : v;\n}\n","export default function variance(values, valueof) {\n let count = 0;\n let delta;\n let mean = 0;\n let sum = 0;\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n delta = value - mean;\n mean += delta / ++count;\n sum += delta * (value - mean);\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n delta = value - mean;\n mean += delta / ++count;\n sum += delta * (value - mean);\n }\n }\n }\n if (count > 1) return sum / (count - 1);\n}\n","import quantile from \"./quantile.js\";\n\nexport default function(values, valueof) {\n return quantile(values, 0.5, valueof);\n}\n","import { ascending, quantileSorted, deviation, quantile, median } from 'd3-array';\n\nfunction* numbers (values, valueof) {\n if (valueof == null) {\n for (let value of values) {\n if (value != null && value !== '' && (value = +value) >= value) {\n yield value;\n }\n }\n } else {\n let index = -1;\n\n for (let value of values) {\n value = valueof(value, ++index, values);\n\n if (value != null && value !== '' && (value = +value) >= value) {\n yield value;\n }\n }\n }\n}\n\nfunction quantiles (array, p, f) {\n const values = Float64Array.from(numbers(array, f)); // don't depend on return value from typed array sort call\n // protects against undefined sort results in Safari (vega/vega-lite#4964)\n\n values.sort(ascending);\n return p.map(_ => quantileSorted(values, _));\n}\n\nfunction quartiles (array, f) {\n return quantiles(array, [0.25, 0.50, 0.75], f);\n}\n\n// Theory, Practice, and Visualization. Wiley.\n\nfunction estimateBandwidth (array, f) {\n const n = array.length,\n d = deviation(array, f),\n q = quartiles(array, f),\n h = (q[2] - q[0]) / 1.34,\n v = Math.min(d, h) || d || Math.abs(q[0]) || 1;\n return 1.06 * v * Math.pow(n, -0.2);\n}\n\nfunction bin (_) {\n // determine range\n const maxb = _.maxbins || 20,\n base = _.base || 10,\n logb = Math.log(base),\n div = _.divide || [5, 2];\n let min = _.extent[0],\n max = _.extent[1],\n step,\n level,\n minstep,\n v,\n i,\n n;\n const span = _.span || max - min || Math.abs(min) || 1;\n\n if (_.step) {\n // if step size is explicitly given, use that\n step = _.step;\n } else if (_.steps) {\n // if provided, limit choice to acceptable step sizes\n v = span / maxb;\n\n for (i = 0, n = _.steps.length; i < n && _.steps[i] < v; ++i);\n\n step = _.steps[Math.max(0, i - 1)];\n } else {\n // else use span to determine step size\n level = Math.ceil(Math.log(maxb) / logb);\n minstep = _.minstep || 0;\n step = Math.max(minstep, Math.pow(base, Math.round(Math.log(span) / logb) - level)); // increase step size if too many bins\n\n while (Math.ceil(span / step) > maxb) {\n step *= base;\n } // decrease step size if allowed\n\n\n for (i = 0, n = div.length; i < n; ++i) {\n v = step / div[i];\n if (v >= minstep && span / v <= maxb) step = v;\n }\n } // update precision, min and max\n\n\n v = Math.log(step);\n const precision = v >= 0 ? 0 : ~~(-v / logb) + 1,\n eps = Math.pow(base, -precision - 1);\n\n if (_.nice || _.nice === undefined) {\n v = Math.floor(min / step + eps) * step;\n min = min < v ? v - step : v;\n max = Math.ceil(max / step) * step;\n }\n\n return {\n start: min,\n stop: max === min ? min + step : max,\n step: step\n };\n}\n\nvar random = Math.random;\nfunction setRandom(r) {\n random = r;\n}\n\nfunction bootstrapCI (array, samples, alpha, f) {\n if (!array.length) return [undefined, undefined];\n const values = Float64Array.from(numbers(array, f)),\n n = values.length,\n m = samples;\n let a, i, j, mu;\n\n for (j = 0, mu = Array(m); j < m; ++j) {\n for (a = 0, i = 0; i < n; ++i) {\n a += values[~~(random() * n)];\n }\n\n mu[j] = a / n;\n }\n\n mu.sort(ascending);\n return [quantile(mu, alpha / 2), quantile(mu, 1 - alpha / 2)];\n}\n\n// Dot density binning for dot plot construction.\n// Based on Leland Wilkinson, Dot Plots, The American Statistician, 1999.\n// https://www.cs.uic.edu/~wilkinson/Publications/dotplots.pdf\nfunction dotbin (array, step, smooth, f) {\n f = f || (_ => _);\n\n const n = array.length,\n v = new Float64Array(n);\n let i = 0,\n j = 1,\n a = f(array[0]),\n b = a,\n w = a + step,\n x;\n\n for (; j < n; ++j) {\n x = f(array[j]);\n\n if (x >= w) {\n b = (a + b) / 2;\n\n for (; i < j; ++i) v[i] = b;\n\n w = x + step;\n a = x;\n }\n\n b = x;\n }\n\n b = (a + b) / 2;\n\n for (; i < j; ++i) v[i] = b;\n\n return smooth ? smoothing(v, step + step / 4) : v;\n} // perform smoothing to reduce variance\n// swap points between \"adjacent\" stacks\n// Wilkinson defines adjacent as within step/4 units\n\nfunction smoothing(v, thresh) {\n const n = v.length;\n let a = 0,\n b = 1,\n c,\n d; // get left stack\n\n while (v[a] === v[b]) ++b;\n\n while (b < n) {\n // get right stack\n c = b + 1;\n\n while (v[b] === v[c]) ++c; // are stacks adjacent?\n // if so, compare sizes and swap as needed\n\n\n if (v[b] - v[b - 1] < thresh) {\n d = b + (a + c - b - b >> 1);\n\n while (d < b) v[d++] = v[b];\n\n while (d > b) v[d--] = v[a];\n } // update left stack indices\n\n\n a = b;\n b = c;\n }\n\n return v;\n}\n\nfunction lcg (seed) {\n // Random numbers using a Linear Congruential Generator with seed value\n // Uses glibc values from https://en.wikipedia.org/wiki/Linear_congruential_generator\n return function () {\n seed = (1103515245 * seed + 12345) % 2147483647;\n return seed / 2147483647;\n };\n}\n\nfunction integer (min, max) {\n if (max == null) {\n max = min;\n min = 0;\n }\n\n let a, b, d;\n const dist = {\n min(_) {\n if (arguments.length) {\n a = _ || 0;\n d = b - a;\n return dist;\n } else {\n return a;\n }\n },\n\n max(_) {\n if (arguments.length) {\n b = _ || 0;\n d = b - a;\n return dist;\n } else {\n return b;\n }\n },\n\n sample() {\n return a + Math.floor(d * random());\n },\n\n pdf(x) {\n return x === Math.floor(x) && x >= a && x < b ? 1 / d : 0;\n },\n\n cdf(x) {\n const v = Math.floor(x);\n return v < a ? 0 : v >= b ? 1 : (v - a + 1) / d;\n },\n\n icdf(p) {\n return p >= 0 && p <= 1 ? a - 1 + Math.floor(p * d) : NaN;\n }\n\n };\n return dist.min(min).max(max);\n}\n\nconst SQRT2PI = Math.sqrt(2 * Math.PI);\nconst SQRT2 = Math.SQRT2;\n\nlet nextSample = NaN;\nfunction sampleNormal(mean, stdev) {\n mean = mean || 0;\n stdev = stdev == null ? 1 : stdev;\n let x = 0,\n y = 0,\n rds,\n c;\n\n if (nextSample === nextSample) {\n x = nextSample;\n nextSample = NaN;\n } else {\n do {\n x = random() * 2 - 1;\n y = random() * 2 - 1;\n rds = x * x + y * y;\n } while (rds === 0 || rds > 1);\n\n c = Math.sqrt(-2 * Math.log(rds) / rds); // Box-Muller transform\n\n x *= c;\n nextSample = y * c;\n }\n\n return mean + x * stdev;\n}\nfunction densityNormal(value, mean, stdev) {\n stdev = stdev == null ? 1 : stdev;\n const z = (value - (mean || 0)) / stdev;\n return Math.exp(-0.5 * z * z) / (stdev * SQRT2PI);\n} // Approximation from West (2009)\n// Better Approximations to Cumulative Normal Functions\n\nfunction cumulativeNormal(value, mean, stdev) {\n mean = mean || 0;\n stdev = stdev == null ? 1 : stdev;\n const z = (value - mean) / stdev,\n Z = Math.abs(z);\n let cd;\n\n if (Z > 37) {\n cd = 0;\n } else {\n const exp = Math.exp(-Z * Z / 2);\n let sum;\n\n if (Z < 7.07106781186547) {\n sum = 3.52624965998911e-02 * Z + 0.700383064443688;\n sum = sum * Z + 6.37396220353165;\n sum = sum * Z + 33.912866078383;\n sum = sum * Z + 112.079291497871;\n sum = sum * Z + 221.213596169931;\n sum = sum * Z + 220.206867912376;\n cd = exp * sum;\n sum = 8.83883476483184e-02 * Z + 1.75566716318264;\n sum = sum * Z + 16.064177579207;\n sum = sum * Z + 86.7807322029461;\n sum = sum * Z + 296.564248779674;\n sum = sum * Z + 637.333633378831;\n sum = sum * Z + 793.826512519948;\n sum = sum * Z + 440.413735824752;\n cd = cd / sum;\n } else {\n sum = Z + 0.65;\n sum = Z + 4 / sum;\n sum = Z + 3 / sum;\n sum = Z + 2 / sum;\n sum = Z + 1 / sum;\n cd = exp / sum / 2.506628274631;\n }\n }\n\n return z > 0 ? 1 - cd : cd;\n} // Approximation of Probit function using inverse error function.\n\nfunction quantileNormal(p, mean, stdev) {\n if (p < 0 || p > 1) return NaN;\n return (mean || 0) + (stdev == null ? 1 : stdev) * SQRT2 * erfinv(2 * p - 1);\n} // Approximate inverse error function. Implementation from \"Approximating\n// the erfinv function\" by Mike Giles, GPU Computing Gems, volume 2, 2010.\n// Ported from Apache Commons Math, http://www.apache.org/licenses/LICENSE-2.0\n\nfunction erfinv(x) {\n // beware that the logarithm argument must be\n // commputed as (1.0 - x) * (1.0 + x),\n // it must NOT be simplified as 1.0 - x * x as this\n // would induce rounding errors near the boundaries +/-1\n let w = -Math.log((1 - x) * (1 + x)),\n p;\n\n if (w < 6.25) {\n w -= 3.125;\n p = -3.6444120640178196996e-21;\n p = -1.685059138182016589e-19 + p * w;\n p = 1.2858480715256400167e-18 + p * w;\n p = 1.115787767802518096e-17 + p * w;\n p = -1.333171662854620906e-16 + p * w;\n p = 2.0972767875968561637e-17 + p * w;\n p = 6.6376381343583238325e-15 + p * w;\n p = -4.0545662729752068639e-14 + p * w;\n p = -8.1519341976054721522e-14 + p * w;\n p = 2.6335093153082322977e-12 + p * w;\n p = -1.2975133253453532498e-11 + p * w;\n p = -5.4154120542946279317e-11 + p * w;\n p = 1.051212273321532285e-09 + p * w;\n p = -4.1126339803469836976e-09 + p * w;\n p = -2.9070369957882005086e-08 + p * w;\n p = 4.2347877827932403518e-07 + p * w;\n p = -1.3654692000834678645e-06 + p * w;\n p = -1.3882523362786468719e-05 + p * w;\n p = 0.0001867342080340571352 + p * w;\n p = -0.00074070253416626697512 + p * w;\n p = -0.0060336708714301490533 + p * w;\n p = 0.24015818242558961693 + p * w;\n p = 1.6536545626831027356 + p * w;\n } else if (w < 16.0) {\n w = Math.sqrt(w) - 3.25;\n p = 2.2137376921775787049e-09;\n p = 9.0756561938885390979e-08 + p * w;\n p = -2.7517406297064545428e-07 + p * w;\n p = 1.8239629214389227755e-08 + p * w;\n p = 1.5027403968909827627e-06 + p * w;\n p = -4.013867526981545969e-06 + p * w;\n p = 2.9234449089955446044e-06 + p * w;\n p = 1.2475304481671778723e-05 + p * w;\n p = -4.7318229009055733981e-05 + p * w;\n p = 6.8284851459573175448e-05 + p * w;\n p = 2.4031110387097893999e-05 + p * w;\n p = -0.0003550375203628474796 + p * w;\n p = 0.00095328937973738049703 + p * w;\n p = -0.0016882755560235047313 + p * w;\n p = 0.0024914420961078508066 + p * w;\n p = -0.0037512085075692412107 + p * w;\n p = 0.005370914553590063617 + p * w;\n p = 1.0052589676941592334 + p * w;\n p = 3.0838856104922207635 + p * w;\n } else if (Number.isFinite(w)) {\n w = Math.sqrt(w) - 5.0;\n p = -2.7109920616438573243e-11;\n p = -2.5556418169965252055e-10 + p * w;\n p = 1.5076572693500548083e-09 + p * w;\n p = -3.7894654401267369937e-09 + p * w;\n p = 7.6157012080783393804e-09 + p * w;\n p = -1.4960026627149240478e-08 + p * w;\n p = 2.9147953450901080826e-08 + p * w;\n p = -6.7711997758452339498e-08 + p * w;\n p = 2.2900482228026654717e-07 + p * w;\n p = -9.9298272942317002539e-07 + p * w;\n p = 4.5260625972231537039e-06 + p * w;\n p = -1.9681778105531670567e-05 + p * w;\n p = 7.5995277030017761139e-05 + p * w;\n p = -0.00021503011930044477347 + p * w;\n p = -0.00013871931833623122026 + p * w;\n p = 1.0103004648645343977 + p * w;\n p = 4.8499064014085844221 + p * w;\n } else {\n p = Infinity;\n }\n\n return p * x;\n}\n\nfunction gaussian (mean, stdev) {\n let mu, sigma;\n const dist = {\n mean(_) {\n if (arguments.length) {\n mu = _ || 0;\n return dist;\n } else {\n return mu;\n }\n },\n\n stdev(_) {\n if (arguments.length) {\n sigma = _ == null ? 1 : _;\n return dist;\n } else {\n return sigma;\n }\n },\n\n sample: () => sampleNormal(mu, sigma),\n pdf: value => densityNormal(value, mu, sigma),\n cdf: value => cumulativeNormal(value, mu, sigma),\n icdf: p => quantileNormal(p, mu, sigma)\n };\n return dist.mean(mean).stdev(stdev);\n}\n\nfunction kde (support, bandwidth) {\n const kernel = gaussian();\n let n = 0;\n const dist = {\n data(_) {\n if (arguments.length) {\n support = _;\n n = _ ? _.length : 0;\n return dist.bandwidth(bandwidth);\n } else {\n return support;\n }\n },\n\n bandwidth(_) {\n if (!arguments.length) return bandwidth;\n bandwidth = _;\n if (!bandwidth && support) bandwidth = estimateBandwidth(support);\n return dist;\n },\n\n sample() {\n return support[~~(random() * n)] + bandwidth * kernel.sample();\n },\n\n pdf(x) {\n let y = 0,\n i = 0;\n\n for (; i < n; ++i) {\n y += kernel.pdf((x - support[i]) / bandwidth);\n }\n\n return y / bandwidth / n;\n },\n\n cdf(x) {\n let y = 0,\n i = 0;\n\n for (; i < n; ++i) {\n y += kernel.cdf((x - support[i]) / bandwidth);\n }\n\n return y / n;\n },\n\n icdf() {\n throw Error('KDE icdf not supported.');\n }\n\n };\n return dist.data(support);\n}\n\nfunction sampleLogNormal(mean, stdev) {\n mean = mean || 0;\n stdev = stdev == null ? 1 : stdev;\n return Math.exp(mean + sampleNormal() * stdev);\n}\nfunction densityLogNormal(value, mean, stdev) {\n if (value <= 0) return 0;\n mean = mean || 0;\n stdev = stdev == null ? 1 : stdev;\n const z = (Math.log(value) - mean) / stdev;\n return Math.exp(-0.5 * z * z) / (stdev * SQRT2PI * value);\n}\nfunction cumulativeLogNormal(value, mean, stdev) {\n return cumulativeNormal(Math.log(value), mean, stdev);\n}\nfunction quantileLogNormal(p, mean, stdev) {\n return Math.exp(quantileNormal(p, mean, stdev));\n}\nfunction lognormal (mean, stdev) {\n let mu, sigma;\n const dist = {\n mean(_) {\n if (arguments.length) {\n mu = _ || 0;\n return dist;\n } else {\n return mu;\n }\n },\n\n stdev(_) {\n if (arguments.length) {\n sigma = _ == null ? 1 : _;\n return dist;\n } else {\n return sigma;\n }\n },\n\n sample: () => sampleLogNormal(mu, sigma),\n pdf: value => densityLogNormal(value, mu, sigma),\n cdf: value => cumulativeLogNormal(value, mu, sigma),\n icdf: p => quantileLogNormal(p, mu, sigma)\n };\n return dist.mean(mean).stdev(stdev);\n}\n\nfunction mixture (dists, weights) {\n let m = 0,\n w;\n\n function normalize(x) {\n const w = [];\n let sum = 0,\n i;\n\n for (i = 0; i < m; ++i) {\n sum += w[i] = x[i] == null ? 1 : +x[i];\n }\n\n for (i = 0; i < m; ++i) {\n w[i] /= sum;\n }\n\n return w;\n }\n\n const dist = {\n weights(_) {\n if (arguments.length) {\n w = normalize(weights = _ || []);\n return dist;\n }\n\n return weights;\n },\n\n distributions(_) {\n if (arguments.length) {\n if (_) {\n m = _.length;\n dists = _;\n } else {\n m = 0;\n dists = [];\n }\n\n return dist.weights(weights);\n }\n\n return dists;\n },\n\n sample() {\n const r = random();\n let d = dists[m - 1],\n v = w[0],\n i = 0; // first select distribution\n\n for (; i < m - 1; v += w[++i]) {\n if (r < v) {\n d = dists[i];\n break;\n }\n } // then sample from it\n\n\n return d.sample();\n },\n\n pdf(x) {\n let p = 0,\n i = 0;\n\n for (; i < m; ++i) {\n p += w[i] * dists[i].pdf(x);\n }\n\n return p;\n },\n\n cdf(x) {\n let p = 0,\n i = 0;\n\n for (; i < m; ++i) {\n p += w[i] * dists[i].cdf(x);\n }\n\n return p;\n },\n\n icdf() {\n throw Error('Mixture icdf not supported.');\n }\n\n };\n return dist.distributions(dists).weights(weights);\n}\n\nfunction sampleUniform(min, max) {\n if (max == null) {\n max = min == null ? 1 : min;\n min = 0;\n }\n\n return min + (max - min) * random();\n}\nfunction densityUniform(value, min, max) {\n if (max == null) {\n max = min == null ? 1 : min;\n min = 0;\n }\n\n return value >= min && value <= max ? 1 / (max - min) : 0;\n}\nfunction cumulativeUniform(value, min, max) {\n if (max == null) {\n max = min == null ? 1 : min;\n min = 0;\n }\n\n return value < min ? 0 : value > max ? 1 : (value - min) / (max - min);\n}\nfunction quantileUniform(p, min, max) {\n if (max == null) {\n max = min == null ? 1 : min;\n min = 0;\n }\n\n return p >= 0 && p <= 1 ? min + p * (max - min) : NaN;\n}\nfunction uniform (min, max) {\n let a, b;\n const dist = {\n min(_) {\n if (arguments.length) {\n a = _ || 0;\n return dist;\n } else {\n return a;\n }\n },\n\n max(_) {\n if (arguments.length) {\n b = _ == null ? 1 : _;\n return dist;\n } else {\n return b;\n }\n },\n\n sample: () => sampleUniform(a, b),\n pdf: value => densityUniform(value, a, b),\n cdf: value => cumulativeUniform(value, a, b),\n icdf: p => quantileUniform(p, a, b)\n };\n\n if (max == null) {\n max = min == null ? 1 : min;\n min = 0;\n }\n\n return dist.min(min).max(max);\n}\n\n// Ordinary Least Squares\nfunction ols (uX, uY, uXY, uX2) {\n const delta = uX2 - uX * uX,\n slope = Math.abs(delta) < 1e-24 ? 0 : (uXY - uX * uY) / delta,\n intercept = uY - slope * uX;\n return [intercept, slope];\n}\n\nfunction points(data, x, y, sort) {\n data = data.filter(d => {\n let u = x(d),\n v = y(d);\n return u != null && (u = +u) >= u && v != null && (v = +v) >= v;\n });\n\n if (sort) {\n data.sort((a, b) => x(a) - x(b));\n }\n\n const n = data.length,\n X = new Float64Array(n),\n Y = new Float64Array(n); // extract values, calculate means\n\n let i = 0,\n ux = 0,\n uy = 0,\n xv,\n yv,\n d;\n\n for (d of data) {\n X[i] = xv = +x(d);\n Y[i] = yv = +y(d);\n ++i;\n ux += (xv - ux) / i;\n uy += (yv - uy) / i;\n } // mean center the data\n\n\n for (i = 0; i < n; ++i) {\n X[i] -= ux;\n Y[i] -= uy;\n }\n\n return [X, Y, ux, uy];\n}\nfunction visitPoints(data, x, y, callback) {\n let i = -1,\n u,\n v;\n\n for (const d of data) {\n u = x(d);\n v = y(d);\n\n if (u != null && (u = +u) >= u && v != null && (v = +v) >= v) {\n callback(u, v, ++i);\n }\n }\n}\n\n// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE\n\nfunction rSquared (data, x, y, uY, predict) {\n let SSE = 0,\n SST = 0;\n visitPoints(data, x, y, (dx, dy) => {\n const sse = dy - predict(dx),\n sst = dy - uY;\n SSE += sse * sse;\n SST += sst * sst;\n });\n return 1 - SSE / SST;\n}\n\n// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE\n\nfunction linear (data, x, y) {\n let X = 0,\n Y = 0,\n XY = 0,\n X2 = 0,\n n = 0;\n visitPoints(data, x, y, (dx, dy) => {\n ++n;\n X += (dx - X) / n;\n Y += (dy - Y) / n;\n XY += (dx * dy - XY) / n;\n X2 += (dx * dx - X2) / n;\n });\n\n const coef = ols(X, Y, XY, X2),\n predict = x => coef[0] + coef[1] * x;\n\n return {\n coef: coef,\n predict: predict,\n rSquared: rSquared(data, x, y, Y, predict)\n };\n}\n\n// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE\n\nfunction log (data, x, y) {\n let X = 0,\n Y = 0,\n XY = 0,\n X2 = 0,\n n = 0;\n visitPoints(data, x, y, (dx, dy) => {\n ++n;\n dx = Math.log(dx);\n X += (dx - X) / n;\n Y += (dy - Y) / n;\n XY += (dx * dy - XY) / n;\n X2 += (dx * dx - X2) / n;\n });\n\n const coef = ols(X, Y, XY, X2),\n predict = x => coef[0] + coef[1] * Math.log(x);\n\n return {\n coef: coef,\n predict: predict,\n rSquared: rSquared(data, x, y, Y, predict)\n };\n}\n\nfunction exp (data, x, y) {\n // eslint-disable-next-line no-unused-vars\n const [xv, yv, ux, uy] = points(data, x, y);\n let YL = 0,\n XY = 0,\n XYL = 0,\n X2Y = 0,\n n = 0,\n dx,\n ly,\n xy;\n visitPoints(data, x, y, (_, dy) => {\n dx = xv[n++];\n ly = Math.log(dy);\n xy = dx * dy;\n YL += (dy * ly - YL) / n;\n XY += (xy - XY) / n;\n XYL += (xy * ly - XYL) / n;\n X2Y += (dx * xy - X2Y) / n;\n });\n\n const [c0, c1] = ols(XY / uy, YL / uy, XYL / uy, X2Y / uy),\n predict = x => Math.exp(c0 + c1 * (x - ux));\n\n return {\n coef: [Math.exp(c0 - c1 * ux), c1],\n predict: predict,\n rSquared: rSquared(data, x, y, uy, predict)\n };\n}\n\n// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE\n\nfunction pow (data, x, y) {\n let X = 0,\n Y = 0,\n XY = 0,\n X2 = 0,\n YS = 0,\n n = 0;\n visitPoints(data, x, y, (dx, dy) => {\n const lx = Math.log(dx),\n ly = Math.log(dy);\n ++n;\n X += (lx - X) / n;\n Y += (ly - Y) / n;\n XY += (lx * ly - XY) / n;\n X2 += (lx * lx - X2) / n;\n YS += (dy - YS) / n;\n });\n\n const coef = ols(X, Y, XY, X2),\n predict = x => coef[0] * Math.pow(x, coef[1]);\n\n coef[0] = Math.exp(coef[0]);\n return {\n coef: coef,\n predict: predict,\n rSquared: rSquared(data, x, y, YS, predict)\n };\n}\n\nfunction quad (data, x, y) {\n const [xv, yv, ux, uy] = points(data, x, y),\n n = xv.length;\n let X2 = 0,\n X3 = 0,\n X4 = 0,\n XY = 0,\n X2Y = 0,\n i,\n dx,\n dy,\n x2;\n\n for (i = 0; i < n;) {\n dx = xv[i];\n dy = yv[i++];\n x2 = dx * dx;\n X2 += (x2 - X2) / i;\n X3 += (x2 * dx - X3) / i;\n X4 += (x2 * x2 - X4) / i;\n XY += (dx * dy - XY) / i;\n X2Y += (x2 * dy - X2Y) / i;\n }\n\n const X2X2 = X4 - X2 * X2,\n d = X2 * X2X2 - X3 * X3,\n a = (X2Y * X2 - XY * X3) / d,\n b = (XY * X2X2 - X2Y * X3) / d,\n c = -a * X2,\n predict = x => {\n x = x - ux;\n return a * x * x + b * x + c + uy;\n }; // transform coefficients back from mean-centered space\n\n\n return {\n coef: [c - b * ux + a * ux * ux + uy, b - 2 * a * ux, a],\n predict: predict,\n rSquared: rSquared(data, x, y, uy, predict)\n };\n}\n\n// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE\n// ... which was adapted from regression-js by Tom Alexander\n// Source: https://github.com/Tom-Alexander/regression-js/blob/master/src/regression.js#L246\n// License: https://github.com/Tom-Alexander/regression-js/blob/master/LICENSE\n\nfunction poly (data, x, y, order) {\n // use more efficient methods for lower orders\n if (order === 1) return linear(data, x, y);\n if (order === 2) return quad(data, x, y);\n const [xv, yv, ux, uy] = points(data, x, y),\n n = xv.length,\n lhs = [],\n rhs = [],\n k = order + 1;\n let i, j, l, v, c;\n\n for (i = 0; i < k; ++i) {\n for (l = 0, v = 0; l < n; ++l) {\n v += Math.pow(xv[l], i) * yv[l];\n }\n\n lhs.push(v);\n c = new Float64Array(k);\n\n for (j = 0; j < k; ++j) {\n for (l = 0, v = 0; l < n; ++l) {\n v += Math.pow(xv[l], i + j);\n }\n\n c[j] = v;\n }\n\n rhs.push(c);\n }\n\n rhs.push(lhs);\n\n const coef = gaussianElimination(rhs),\n predict = x => {\n x -= ux;\n let y = uy + coef[0] + coef[1] * x + coef[2] * x * x;\n\n for (i = 3; i < k; ++i) y += coef[i] * Math.pow(x, i);\n\n return y;\n };\n\n return {\n coef: uncenter(k, coef, -ux, uy),\n predict: predict,\n rSquared: rSquared(data, x, y, uy, predict)\n };\n}\n\nfunction uncenter(k, a, x, y) {\n const z = Array(k);\n let i, j, v, c; // initialize to zero\n\n for (i = 0; i < k; ++i) z[i] = 0; // polynomial expansion\n\n\n for (i = k - 1; i >= 0; --i) {\n v = a[i];\n c = 1;\n z[i] += v;\n\n for (j = 1; j <= i; ++j) {\n c *= (i + 1 - j) / j; // binomial coefficent\n\n z[i - j] += v * Math.pow(x, j) * c;\n }\n } // bias term\n\n\n z[0] += y;\n return z;\n} // Given an array for a two-dimensional matrix and the polynomial order,\n// solve A * x = b using Gaussian elimination.\n\n\nfunction gaussianElimination(matrix) {\n const n = matrix.length - 1,\n coef = [];\n let i, j, k, r, t;\n\n for (i = 0; i < n; ++i) {\n r = i; // max row\n\n for (j = i + 1; j < n; ++j) {\n if (Math.abs(matrix[i][j]) > Math.abs(matrix[i][r])) {\n r = j;\n }\n }\n\n for (k = i; k < n + 1; ++k) {\n t = matrix[k][i];\n matrix[k][i] = matrix[k][r];\n matrix[k][r] = t;\n }\n\n for (j = i + 1; j < n; ++j) {\n for (k = n; k >= i; k--) {\n matrix[k][j] -= matrix[k][i] * matrix[i][j] / matrix[i][i];\n }\n }\n }\n\n for (j = n - 1; j >= 0; --j) {\n t = 0;\n\n for (k = j + 1; k < n; ++k) {\n t += matrix[k][j] * coef[k];\n }\n\n coef[j] = (matrix[n][j] - t) / matrix[j][j];\n }\n\n return coef;\n}\n\nconst maxiters = 2,\n epsilon = 1e-12; // Adapted from science.js by Jason Davies\n// Source: https://github.com/jasondavies/science.js/blob/master/src/stats/loess.js\n// License: https://github.com/jasondavies/science.js/blob/master/LICENSE\n\nfunction loess (data, x, y, bandwidth) {\n const [xv, yv, ux, uy] = points(data, x, y, true),\n n = xv.length,\n bw = Math.max(2, ~~(bandwidth * n)),\n // # nearest neighbors\n yhat = new Float64Array(n),\n residuals = new Float64Array(n),\n robustWeights = new Float64Array(n).fill(1);\n\n for (let iter = -1; ++iter <= maxiters;) {\n const interval = [0, bw - 1];\n\n for (let i = 0; i < n; ++i) {\n const dx = xv[i],\n i0 = interval[0],\n i1 = interval[1],\n edge = dx - xv[i0] > xv[i1] - dx ? i0 : i1;\n let W = 0,\n X = 0,\n Y = 0,\n XY = 0,\n X2 = 0;\n const denom = 1 / Math.abs(xv[edge] - dx || 1); // avoid singularity!\n\n for (let k = i0; k <= i1; ++k) {\n const xk = xv[k],\n yk = yv[k],\n w = tricube(Math.abs(dx - xk) * denom) * robustWeights[k],\n xkw = xk * w;\n W += w;\n X += xkw;\n Y += yk * w;\n XY += yk * xkw;\n X2 += xk * xkw;\n } // linear regression fit\n\n\n const [a, b] = ols(X / W, Y / W, XY / W, X2 / W);\n yhat[i] = a + b * dx;\n residuals[i] = Math.abs(yv[i] - yhat[i]);\n updateInterval(xv, i + 1, interval);\n }\n\n if (iter === maxiters) {\n break;\n }\n\n const medianResidual = median(residuals);\n if (Math.abs(medianResidual) < epsilon) break;\n\n for (let i = 0, arg, w; i < n; ++i) {\n arg = residuals[i] / (6 * medianResidual); // default to epsilon (rather than zero) for large deviations\n // keeping weights tiny but non-zero prevents singularites\n\n robustWeights[i] = arg >= 1 ? epsilon : (w = 1 - arg * arg) * w;\n }\n }\n\n return output(xv, yhat, ux, uy);\n} // weighting kernel for local regression\n\nfunction tricube(x) {\n return (x = 1 - x * x * x) * x * x;\n} // advance sliding window interval of nearest neighbors\n\n\nfunction updateInterval(xv, i, interval) {\n const val = xv[i];\n let left = interval[0],\n right = interval[1] + 1;\n if (right >= xv.length) return; // step right if distance to new right edge is <= distance to old left edge\n // step when distance is equal to ensure movement over duplicate x values\n\n while (i > left && xv[right] - val <= val - xv[left]) {\n interval[0] = ++left;\n interval[1] = right;\n ++right;\n }\n} // generate smoothed output points\n// average points with repeated x values\n\n\nfunction output(xv, yhat, ux, uy) {\n const n = xv.length,\n out = [];\n let i = 0,\n cnt = 0,\n prev = [],\n v;\n\n for (; i < n; ++i) {\n v = xv[i] + ux;\n\n if (prev[0] === v) {\n // average output values via online update\n prev[1] += (yhat[i] - prev[1]) / ++cnt;\n } else {\n // add new output point\n cnt = 0;\n prev[1] += uy;\n prev = [v, yhat[i]];\n out.push(prev);\n }\n }\n\n prev[1] += uy;\n return out;\n}\n\n// subdivide up to accuracy of 0.5 degrees\nconst MIN_RADIANS = 0.5 * Math.PI / 180; // Adaptively sample an interpolated function over a domain extent\n\nfunction sampleCurve (f, extent, minSteps, maxSteps) {\n minSteps = minSteps || 25;\n maxSteps = Math.max(minSteps, maxSteps || 200);\n\n const point = x => [x, f(x)],\n minX = extent[0],\n maxX = extent[1],\n span = maxX - minX,\n stop = span / maxSteps,\n prev = [point(minX)],\n next = [];\n\n if (minSteps === maxSteps) {\n // no adaptation, sample uniform grid directly and return\n for (let i = 1; i < maxSteps; ++i) {\n prev.push(point(minX + i / minSteps * span));\n }\n\n prev.push(point(maxX));\n return prev;\n } else {\n // sample minimum points on uniform grid\n // then move on to perform adaptive refinement\n next.push(point(maxX));\n\n for (let i = minSteps; --i > 0;) {\n next.push(point(minX + i / minSteps * span));\n }\n }\n\n let p0 = prev[0];\n let p1 = next[next.length - 1];\n const sx = 1 / span;\n const sy = scaleY(p0[1], next);\n\n while (p1) {\n // midpoint for potential curve subdivision\n const pm = point((p0[0] + p1[0]) / 2);\n const dx = pm[0] - p0[0] >= stop;\n\n if (dx && angleDelta(p0, pm, p1, sx, sy) > MIN_RADIANS) {\n // maximum resolution has not yet been met, and\n // subdivision midpoint is sufficiently different from endpoint\n // save subdivision, push midpoint onto the visitation stack\n next.push(pm);\n } else {\n // subdivision midpoint sufficiently similar to endpoint\n // skip subdivision, store endpoint, move to next point on the stack\n p0 = p1;\n prev.push(p1);\n next.pop();\n }\n\n p1 = next[next.length - 1];\n }\n\n return prev;\n}\n\nfunction scaleY(init, points) {\n let ymin = init;\n let ymax = init;\n const n = points.length;\n\n for (let i = 0; i < n; ++i) {\n const y = points[i][1];\n if (y < ymin) ymin = y;\n if (y > ymax) ymax = y;\n }\n\n return 1 / (ymax - ymin);\n}\n\nfunction angleDelta(p, q, r, sx, sy) {\n const a0 = Math.atan2(sy * (r[1] - p[1]), sx * (r[0] - p[0])),\n a1 = Math.atan2(sy * (q[1] - p[1]), sx * (q[0] - p[0]));\n return Math.abs(a0 - a1);\n}\n\nexport { estimateBandwidth as bandwidthNRD, bin, bootstrapCI, cumulativeLogNormal, cumulativeNormal, cumulativeUniform, densityLogNormal, densityNormal, densityUniform, dotbin, quantileLogNormal, quantileNormal, quantileUniform, quantiles, quartiles, random, integer as randomInteger, kde as randomKDE, lcg as randomLCG, lognormal as randomLogNormal, mixture as randomMixture, gaussian as randomNormal, uniform as randomUniform, exp as regressionExp, linear as regressionLinear, loess as regressionLoess, log as regressionLog, poly as regressionPoly, pow as regressionPow, quad as regressionQuad, sampleCurve, sampleLogNormal, sampleNormal, sampleUniform, setRandom };\n","export default function max(values, valueof) {\n let max;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n }\n return max;\n}\n","export default function min(values, valueof) {\n let min;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n }\n return min;\n}\n","export default function(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","import ascending from \"./ascending.js\";\n\n// Based on https://github.com/mourner/quickselect\n// ISC license, Copyright 2018 Vladimir Agafonkin.\nexport default function quickselect(array, k, left = 0, right = array.length - 1, compare = ascending) {\n while (right > left) {\n if (right - left > 600) {\n const n = right - left + 1;\n const m = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n quickselect(array, k, newLeft, newRight, compare);\n }\n\n const t = array[k];\n let i = left;\n let j = right;\n\n swap(array, left, k);\n if (compare(array[right], t) > 0) swap(array, left, right);\n\n while (i < j) {\n swap(array, i, j), ++i, --j;\n while (compare(array[i], t) < 0) ++i;\n while (compare(array[j], t) > 0) --j;\n }\n\n if (compare(array[left], t) === 0) swap(array, left, j);\n else ++j, swap(array, j, right);\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n return array;\n}\n\nfunction swap(array, i, j) {\n const t = array[i];\n array[i] = array[j];\n array[j] = t;\n}\n","export default function(x) {\n return x === null ? NaN : +x;\n}\n\nexport function* numbers(values, valueof) {\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n yield value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n yield value;\n }\n }\n }\n}\n","import max from \"./max.js\";\nimport min from \"./min.js\";\nimport quickselect from \"./quickselect.js\";\nimport number, {numbers} from \"./number.js\";\n\nexport default function quantile(values, p, valueof) {\n values = Float64Array.from(numbers(values, valueof));\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return min(values);\n if (p >= 1) return max(values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = max(quickselect(values, i0).subarray(0, i0 + 1)),\n value1 = min(values.subarray(i0 + 1));\n return value0 + (value1 - value0) * (i - i0);\n}\n\nexport function quantileSorted(values, p, valueof = number) {\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);\n if (p >= 1) return +valueof(values[n - 1], n - 1, values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = +valueof(values[i0], i0, values),\n value1 = +valueof(values[i0 + 1], i0 + 1, values);\n return value0 + (value1 - value0) * (i - i0);\n}\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","import ascending from \"./ascending.js\";\n\nexport default function(f) {\n let delta = f;\n let compare = f;\n\n if (f.length === 1) {\n delta = (d, x) => f(d) - x;\n compare = ascendingComparator(f);\n }\n\n function left(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (compare(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n\n function right(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (compare(a[mid], x) > 0) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n }\n\n function center(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n const i = left(a, x, lo, hi - 1);\n return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;\n }\n\n return {left, center, right};\n}\n\nfunction ascendingComparator(f) {\n return (d, x) => ascending(f(d), x);\n}\n","import { extend, identity, field, hasOwnProperty, extentIndex, inherits, array, accessorName, error, accessorFields, accessor, toNumber, merge, compare, truthy, extent, span, fastmap, isArray, key, ascending, peek, zero, constant } from 'vega-util';\nimport { tupleid, Transform, replace, ingest, stableCompare, Operator, derive, rederive } from 'vega-dataflow';\nimport { quartiles, bootstrapCI, bin, randomKDE, randomMixture, randomNormal, randomLogNormal, randomUniform, sampleCurve, dotbin, quantiles, random } from 'vega-statistics';\nimport { median, mean, min, max, range, bisector } from 'd3-array';\nimport { TIME_UNITS, utcInterval, timeInterval, timeBin, timeUnits, utcFloor, timeFloor } from 'vega-time';\n\nfunction multikey(f) {\n return x => {\n const n = f.length;\n let i = 1,\n k = String(f[0](x));\n\n for (; i < n; ++i) {\n k += '|' + f[i](x);\n }\n\n return k;\n };\n}\nfunction groupkey(fields) {\n return !fields || !fields.length ? function () {\n return '';\n } : fields.length === 1 ? fields[0] : multikey(fields);\n}\n\nfunction measureName(op, field, as) {\n return as || op + (!field ? '' : '_' + field);\n}\n\nconst noop = () => {};\n\nconst base_op = {\n init: noop,\n add: noop,\n rem: noop,\n idx: 0\n};\nconst AggregateOps = {\n values: {\n init: m => m.cell.store = true,\n value: m => m.cell.data.values(),\n idx: -1\n },\n count: {\n value: m => m.cell.num\n },\n __count__: {\n value: m => m.missing + m.valid\n },\n missing: {\n value: m => m.missing\n },\n valid: {\n value: m => m.valid\n },\n sum: {\n init: m => m.sum = 0,\n value: m => m.sum,\n add: (m, v) => m.sum += +v,\n rem: (m, v) => m.sum -= v\n },\n product: {\n init: m => m.product = 1,\n value: m => m.valid ? m.product : undefined,\n add: (m, v) => m.product *= v,\n rem: (m, v) => m.product /= v\n },\n mean: {\n init: m => m.mean = 0,\n value: m => m.valid ? m.mean : undefined,\n add: (m, v) => (m.mean_d = v - m.mean, m.mean += m.mean_d / m.valid),\n rem: (m, v) => (m.mean_d = v - m.mean, m.mean -= m.valid ? m.mean_d / m.valid : m.mean)\n },\n average: {\n value: m => m.valid ? m.mean : undefined,\n req: ['mean'],\n idx: 1\n },\n variance: {\n init: m => m.dev = 0,\n value: m => m.valid > 1 ? m.dev / (m.valid - 1) : undefined,\n add: (m, v) => m.dev += m.mean_d * (v - m.mean),\n rem: (m, v) => m.dev -= m.mean_d * (v - m.mean),\n req: ['mean'],\n idx: 1\n },\n variancep: {\n value: m => m.valid > 1 ? m.dev / m.valid : undefined,\n req: ['variance'],\n idx: 2\n },\n stdev: {\n value: m => m.valid > 1 ? Math.sqrt(m.dev / (m.valid - 1)) : undefined,\n req: ['variance'],\n idx: 2\n },\n stdevp: {\n value: m => m.valid > 1 ? Math.sqrt(m.dev / m.valid) : undefined,\n req: ['variance'],\n idx: 2\n },\n stderr: {\n value: m => m.valid > 1 ? Math.sqrt(m.dev / (m.valid * (m.valid - 1))) : undefined,\n req: ['variance'],\n idx: 2\n },\n distinct: {\n value: m => m.cell.data.distinct(m.get),\n req: ['values'],\n idx: 3\n },\n ci0: {\n value: m => m.cell.data.ci0(m.get),\n req: ['values'],\n idx: 3\n },\n ci1: {\n value: m => m.cell.data.ci1(m.get),\n req: ['values'],\n idx: 3\n },\n median: {\n value: m => m.cell.data.q2(m.get),\n req: ['values'],\n idx: 3\n },\n q1: {\n value: m => m.cell.data.q1(m.get),\n req: ['values'],\n idx: 3\n },\n q3: {\n value: m => m.cell.data.q3(m.get),\n req: ['values'],\n idx: 3\n },\n min: {\n init: m => m.min = undefined,\n value: m => m.min = Number.isNaN(m.min) ? m.cell.data.min(m.get) : m.min,\n add: (m, v) => {\n if (v < m.min || m.min === undefined) m.min = v;\n },\n rem: (m, v) => {\n if (v <= m.min) m.min = NaN;\n },\n req: ['values'],\n idx: 4\n },\n max: {\n init: m => m.max = undefined,\n value: m => m.max = Number.isNaN(m.max) ? m.cell.data.max(m.get) : m.max,\n add: (m, v) => {\n if (v > m.max || m.max === undefined) m.max = v;\n },\n rem: (m, v) => {\n if (v >= m.max) m.max = NaN;\n },\n req: ['values'],\n idx: 4\n },\n argmin: {\n init: m => m.argmin = undefined,\n value: m => m.argmin || m.cell.data.argmin(m.get),\n add: (m, v, t) => {\n if (v < m.min) m.argmin = t;\n },\n rem: (m, v) => {\n if (v <= m.min) m.argmin = undefined;\n },\n req: ['min', 'values'],\n idx: 3\n },\n argmax: {\n init: m => m.argmax = undefined,\n value: m => m.argmax || m.cell.data.argmax(m.get),\n add: (m, v, t) => {\n if (v > m.max) m.argmax = t;\n },\n rem: (m, v) => {\n if (v >= m.max) m.argmax = undefined;\n },\n req: ['max', 'values'],\n idx: 3\n }\n};\nconst ValidAggregateOps = Object.keys(AggregateOps);\n\nfunction measure(key, value) {\n return out => extend({\n name: key,\n out: out || key\n }, base_op, value);\n}\n\nValidAggregateOps.forEach(key => {\n AggregateOps[key] = measure(key, AggregateOps[key]);\n});\nfunction createMeasure(op, name) {\n return AggregateOps[op](name);\n}\n\nfunction compareIndex(a, b) {\n return a.idx - b.idx;\n}\n\nfunction resolve(agg) {\n const map = {};\n agg.forEach(a => map[a.name] = a);\n\n const getreqs = a => {\n if (!a.req) return;\n a.req.forEach(key => {\n if (!map[key]) getreqs(map[key] = AggregateOps[key]());\n });\n };\n\n agg.forEach(getreqs);\n return Object.values(map).sort(compareIndex);\n}\n\nfunction init() {\n this.valid = 0;\n this.missing = 0;\n\n this._ops.forEach(op => op.init(this));\n}\n\nfunction add(v, t) {\n if (v == null || v === '') {\n ++this.missing;\n return;\n }\n\n if (v !== v) return;\n ++this.valid;\n\n this._ops.forEach(op => op.add(this, v, t));\n}\n\nfunction rem(v, t) {\n if (v == null || v === '') {\n --this.missing;\n return;\n }\n\n if (v !== v) return;\n --this.valid;\n\n this._ops.forEach(op => op.rem(this, v, t));\n}\n\nfunction set(t) {\n this._out.forEach(op => t[op.out] = op.value(this));\n\n return t;\n}\n\nfunction compileMeasures(agg, field) {\n const get = field || identity,\n ops = resolve(agg),\n out = agg.slice().sort(compareIndex);\n\n function ctr(cell) {\n this._ops = ops;\n this._out = out;\n this.cell = cell;\n this.init();\n }\n\n ctr.prototype.init = init;\n ctr.prototype.add = add;\n ctr.prototype.rem = rem;\n ctr.prototype.set = set;\n ctr.prototype.get = get;\n ctr.fields = agg.map(op => op.out);\n return ctr;\n}\n\nfunction TupleStore(key) {\n this._key = key ? field(key) : tupleid;\n this.reset();\n}\nconst prototype$1 = TupleStore.prototype;\n\nprototype$1.reset = function () {\n this._add = [];\n this._rem = [];\n this._ext = null;\n this._get = null;\n this._q = null;\n};\n\nprototype$1.add = function (v) {\n this._add.push(v);\n};\n\nprototype$1.rem = function (v) {\n this._rem.push(v);\n};\n\nprototype$1.values = function () {\n this._get = null;\n if (this._rem.length === 0) return this._add;\n const a = this._add,\n r = this._rem,\n k = this._key,\n n = a.length,\n m = r.length,\n x = Array(n - m),\n map = {};\n let i, j, v; // use unique key field to clear removed values\n\n for (i = 0; i < m; ++i) {\n map[k(r[i])] = 1;\n }\n\n for (i = 0, j = 0; i < n; ++i) {\n if (map[k(v = a[i])]) {\n map[k(v)] = 0;\n } else {\n x[j++] = v;\n }\n }\n\n this._rem = [];\n return this._add = x;\n}; // memoizing statistics methods\n\n\nprototype$1.distinct = function (get) {\n const v = this.values(),\n map = {};\n let n = v.length,\n count = 0,\n s;\n\n while (--n >= 0) {\n s = get(v[n]) + '';\n\n if (!hasOwnProperty(map, s)) {\n map[s] = 1;\n ++count;\n }\n }\n\n return count;\n};\n\nprototype$1.extent = function (get) {\n if (this._get !== get || !this._ext) {\n const v = this.values(),\n i = extentIndex(v, get);\n this._ext = [v[i[0]], v[i[1]]];\n this._get = get;\n }\n\n return this._ext;\n};\n\nprototype$1.argmin = function (get) {\n return this.extent(get)[0] || {};\n};\n\nprototype$1.argmax = function (get) {\n return this.extent(get)[1] || {};\n};\n\nprototype$1.min = function (get) {\n const m = this.extent(get)[0];\n return m != null ? get(m) : undefined;\n};\n\nprototype$1.max = function (get) {\n const m = this.extent(get)[1];\n return m != null ? get(m) : undefined;\n};\n\nprototype$1.quartile = function (get) {\n if (this._get !== get || !this._q) {\n this._q = quartiles(this.values(), get);\n this._get = get;\n }\n\n return this._q;\n};\n\nprototype$1.q1 = function (get) {\n return this.quartile(get)[0];\n};\n\nprototype$1.q2 = function (get) {\n return this.quartile(get)[1];\n};\n\nprototype$1.q3 = function (get) {\n return this.quartile(get)[2];\n};\n\nprototype$1.ci = function (get) {\n if (this._get !== get || !this._ci) {\n this._ci = bootstrapCI(this.values(), 1000, 0.05, get);\n this._get = get;\n }\n\n return this._ci;\n};\n\nprototype$1.ci0 = function (get) {\n return this.ci(get)[0];\n};\n\nprototype$1.ci1 = function (get) {\n return this.ci(get)[1];\n};\n\n/**\n * Group-by aggregation operator.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} [params.groupby] - An array of accessors to groupby.\n * @param {Array} [params.fields] - An array of accessors to aggregate.\n * @param {Array} [params.ops] - An array of strings indicating aggregation operations.\n * @param {Array} [params.as] - An array of output field names for aggregated values.\n * @param {boolean} [params.cross=false] - A flag indicating that the full\n * cross-product of groupby values should be generated, including empty cells.\n * If true, the drop parameter is ignored and empty cells are retained.\n * @param {boolean} [params.drop=true] - A flag indicating if empty cells should be removed.\n */\n\nfunction Aggregate(params) {\n Transform.call(this, null, params);\n this._adds = []; // array of added output tuples\n\n this._mods = []; // array of modified output tuples\n\n this._alen = 0; // number of active added tuples\n\n this._mlen = 0; // number of active modified tuples\n\n this._drop = true; // should empty aggregation cells be removed\n\n this._cross = false; // produce full cross-product of group-by values\n\n this._dims = []; // group-by dimension accessors\n\n this._dnames = []; // group-by dimension names\n\n this._measures = []; // collection of aggregation monoids\n\n this._countOnly = false; // flag indicating only count aggregation\n\n this._counts = null; // collection of count fields\n\n this._prev = null; // previous aggregation cells\n\n this._inputs = null; // array of dependent input tuple field names\n\n this._outputs = null; // array of output tuple field names\n}\nAggregate.Definition = {\n 'type': 'Aggregate',\n 'metadata': {\n 'generates': true,\n 'changes': true\n },\n 'params': [{\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'ops',\n 'type': 'enum',\n 'array': true,\n 'values': ValidAggregateOps\n }, {\n 'name': 'fields',\n 'type': 'field',\n 'null': true,\n 'array': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'null': true,\n 'array': true\n }, {\n 'name': 'drop',\n 'type': 'boolean',\n 'default': true\n }, {\n 'name': 'cross',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'key',\n 'type': 'field'\n }]\n};\ninherits(Aggregate, Transform, {\n transform(_, pulse) {\n const aggr = this,\n out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),\n mod = _.modified();\n\n aggr.stamp = out.stamp;\n\n if (aggr.value && (mod || pulse.modified(aggr._inputs, true))) {\n aggr._prev = aggr.value;\n aggr.value = mod ? aggr.init(_) : {};\n pulse.visit(pulse.SOURCE, t => aggr.add(t));\n } else {\n aggr.value = aggr.value || aggr.init(_);\n pulse.visit(pulse.REM, t => aggr.rem(t));\n pulse.visit(pulse.ADD, t => aggr.add(t));\n } // Indicate output fields and return aggregate tuples.\n\n\n out.modifies(aggr._outputs); // Should empty cells be dropped?\n\n aggr._drop = _.drop !== false; // If domain cross-product requested, generate empty cells as needed\n // and ensure that empty cells are not dropped\n\n if (_.cross && aggr._dims.length > 1) {\n aggr._drop = false;\n aggr.cross();\n }\n\n if (pulse.clean() && aggr._drop) {\n out.clean(true).runAfter(() => this.clean());\n }\n\n return aggr.changes(out);\n },\n\n cross() {\n const aggr = this,\n curr = aggr.value,\n dims = aggr._dnames,\n vals = dims.map(() => ({})),\n n = dims.length; // collect all group-by domain values\n\n function collect(cells) {\n let key, i, t, v;\n\n for (key in cells) {\n t = cells[key].tuple;\n\n for (i = 0; i < n; ++i) {\n vals[i][v = t[dims[i]]] = v;\n }\n }\n }\n\n collect(aggr._prev);\n collect(curr); // iterate over key cross-product, create cells as needed\n\n function generate(base, tuple, index) {\n const name = dims[index],\n v = vals[index++];\n\n for (const k in v) {\n const key = base ? base + '|' + k : k;\n tuple[name] = v[k];\n if (index < n) generate(key, tuple, index);else if (!curr[key]) aggr.cell(key, tuple);\n }\n }\n\n generate('', {}, 0);\n },\n\n init(_) {\n // initialize input and output fields\n const inputs = this._inputs = [],\n outputs = this._outputs = [],\n inputMap = {};\n\n function inputVisit(get) {\n const fields = array(accessorFields(get)),\n n = fields.length;\n let i = 0,\n f;\n\n for (; i < n; ++i) {\n if (!inputMap[f = fields[i]]) {\n inputMap[f] = 1;\n inputs.push(f);\n }\n }\n } // initialize group-by dimensions\n\n\n this._dims = array(_.groupby);\n this._dnames = this._dims.map(d => {\n const dname = accessorName(d);\n inputVisit(d);\n outputs.push(dname);\n return dname;\n });\n this.cellkey = _.key ? _.key : groupkey(this._dims); // initialize aggregate measures\n\n this._countOnly = true;\n this._counts = [];\n this._measures = [];\n const fields = _.fields || [null],\n ops = _.ops || ['count'],\n as = _.as || [],\n n = fields.length,\n map = {};\n let field, op, m, mname, outname, i;\n\n if (n !== ops.length) {\n error('Unmatched number of fields and aggregate ops.');\n }\n\n for (i = 0; i < n; ++i) {\n field = fields[i];\n op = ops[i];\n\n if (field == null && op !== 'count') {\n error('Null aggregate field specified.');\n }\n\n mname = accessorName(field);\n outname = measureName(op, mname, as[i]);\n outputs.push(outname);\n\n if (op === 'count') {\n this._counts.push(outname);\n\n continue;\n }\n\n m = map[mname];\n\n if (!m) {\n inputVisit(field);\n m = map[mname] = [];\n m.field = field;\n\n this._measures.push(m);\n }\n\n if (op !== 'count') this._countOnly = false;\n m.push(createMeasure(op, outname));\n }\n\n this._measures = this._measures.map(m => compileMeasures(m, m.field));\n return {}; // aggregation cells (this.value)\n },\n\n // -- Cell Management -----\n cellkey: groupkey(),\n\n cell(key, t) {\n let cell = this.value[key];\n\n if (!cell) {\n cell = this.value[key] = this.newcell(key, t);\n this._adds[this._alen++] = cell;\n } else if (cell.num === 0 && this._drop && cell.stamp < this.stamp) {\n cell.stamp = this.stamp;\n this._adds[this._alen++] = cell;\n } else if (cell.stamp < this.stamp) {\n cell.stamp = this.stamp;\n this._mods[this._mlen++] = cell;\n }\n\n return cell;\n },\n\n newcell(key, t) {\n const cell = {\n key: key,\n num: 0,\n agg: null,\n tuple: this.newtuple(t, this._prev && this._prev[key]),\n stamp: this.stamp,\n store: false\n };\n\n if (!this._countOnly) {\n const measures = this._measures,\n n = measures.length;\n cell.agg = Array(n);\n\n for (let i = 0; i < n; ++i) {\n cell.agg[i] = new measures[i](cell);\n }\n }\n\n if (cell.store) {\n cell.data = new TupleStore();\n }\n\n return cell;\n },\n\n newtuple(t, p) {\n const names = this._dnames,\n dims = this._dims,\n n = dims.length,\n x = {};\n\n for (let i = 0; i < n; ++i) {\n x[names[i]] = dims[i](t);\n }\n\n return p ? replace(p.tuple, x) : ingest(x);\n },\n\n clean() {\n const cells = this.value;\n\n for (const key in cells) {\n if (cells[key].num === 0) {\n delete cells[key];\n }\n }\n },\n\n // -- Process Tuples -----\n add(t) {\n const key = this.cellkey(t),\n cell = this.cell(key, t);\n cell.num += 1;\n if (this._countOnly) return;\n if (cell.store) cell.data.add(t);\n const agg = cell.agg;\n\n for (let i = 0, n = agg.length; i < n; ++i) {\n agg[i].add(agg[i].get(t), t);\n }\n },\n\n rem(t) {\n const key = this.cellkey(t),\n cell = this.cell(key, t);\n cell.num -= 1;\n if (this._countOnly) return;\n if (cell.store) cell.data.rem(t);\n const agg = cell.agg;\n\n for (let i = 0, n = agg.length; i < n; ++i) {\n agg[i].rem(agg[i].get(t), t);\n }\n },\n\n celltuple(cell) {\n const tuple = cell.tuple,\n counts = this._counts; // consolidate stored values\n\n if (cell.store) {\n cell.data.values();\n } // update tuple properties\n\n\n for (let i = 0, n = counts.length; i < n; ++i) {\n tuple[counts[i]] = cell.num;\n }\n\n if (!this._countOnly) {\n const agg = cell.agg;\n\n for (let i = 0, n = agg.length; i < n; ++i) {\n agg[i].set(tuple);\n }\n }\n\n return tuple;\n },\n\n changes(out) {\n const adds = this._adds,\n mods = this._mods,\n prev = this._prev,\n drop = this._drop,\n add = out.add,\n rem = out.rem,\n mod = out.mod;\n let cell, key, i, n;\n if (prev) for (key in prev) {\n cell = prev[key];\n if (!drop || cell.num) rem.push(cell.tuple);\n }\n\n for (i = 0, n = this._alen; i < n; ++i) {\n add.push(this.celltuple(adds[i]));\n adds[i] = null; // for garbage collection\n }\n\n for (i = 0, n = this._mlen; i < n; ++i) {\n cell = mods[i];\n (cell.num === 0 && drop ? rem : mod).push(this.celltuple(cell));\n mods[i] = null; // for garbage collection\n }\n\n this._alen = this._mlen = 0; // reset list of active cells\n\n this._prev = null;\n return out;\n }\n\n});\n\nconst EPSILON$1 = 1e-14;\n/**\n * Generates a binning function for discretizing data.\n * @constructor\n * @param {object} params - The parameters for this operator. The\n * provided values should be valid options for the {@link bin} function.\n * @param {function(object): *} params.field - The data field to bin.\n */\n\nfunction Bin(params) {\n Transform.call(this, null, params);\n}\nBin.Definition = {\n 'type': 'Bin',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'interval',\n 'type': 'boolean',\n 'default': true\n }, {\n 'name': 'anchor',\n 'type': 'number'\n }, {\n 'name': 'maxbins',\n 'type': 'number',\n 'default': 20\n }, {\n 'name': 'base',\n 'type': 'number',\n 'default': 10\n }, {\n 'name': 'divide',\n 'type': 'number',\n 'array': true,\n 'default': [5, 2]\n }, {\n 'name': 'extent',\n 'type': 'number',\n 'array': true,\n 'length': 2,\n 'required': true\n }, {\n 'name': 'span',\n 'type': 'number'\n }, {\n 'name': 'step',\n 'type': 'number'\n }, {\n 'name': 'steps',\n 'type': 'number',\n 'array': true\n }, {\n 'name': 'minstep',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'nice',\n 'type': 'boolean',\n 'default': true\n }, {\n 'name': 'name',\n 'type': 'string'\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': 2,\n 'default': ['bin0', 'bin1']\n }]\n};\ninherits(Bin, Transform, {\n transform(_, pulse) {\n const band = _.interval !== false,\n bins = this._bins(_),\n start = bins.start,\n step = bins.step,\n as = _.as || ['bin0', 'bin1'],\n b0 = as[0],\n b1 = as[1];\n\n let flag;\n\n if (_.modified()) {\n pulse = pulse.reflow(true);\n flag = pulse.SOURCE;\n } else {\n flag = pulse.modified(accessorFields(_.field)) ? pulse.ADD_MOD : pulse.ADD;\n }\n\n pulse.visit(flag, band ? t => {\n const v = bins(t); // minimum bin value (inclusive)\n\n t[b0] = v; // maximum bin value (exclusive)\n // use convoluted math for better floating point agreement\n // see https://github.com/vega/vega/issues/830\n // infinite values propagate through this formula! #2227\n\n t[b1] = v == null ? null : start + step * (1 + (v - start) / step);\n } : t => t[b0] = bins(t));\n return pulse.modifies(band ? as : b0);\n },\n\n _bins(_) {\n if (this.value && !_.modified()) {\n return this.value;\n }\n\n const field = _.field,\n bins = bin(_),\n step = bins.step;\n let start = bins.start,\n stop = start + Math.ceil((bins.stop - start) / step) * step,\n a,\n d;\n\n if ((a = _.anchor) != null) {\n d = a - (start + step * Math.floor((a - start) / step));\n start += d;\n stop += d;\n }\n\n const f = function (t) {\n let v = toNumber(field(t));\n return v == null ? null : v < start ? -Infinity : v > stop ? +Infinity : (v = Math.max(start, Math.min(v, stop - step)), start + step * Math.floor(EPSILON$1 + (v - start) / step));\n };\n\n f.start = start;\n f.stop = bins.stop;\n f.step = step;\n return this.value = accessor(f, accessorFields(field), _.name || 'bin_' + accessorName(field));\n }\n\n});\n\nfunction SortedList (idFunc, source, input) {\n const $ = idFunc;\n let data = source || [],\n add = input || [],\n rem = {},\n cnt = 0;\n return {\n add: t => add.push(t),\n remove: t => rem[$(t)] = ++cnt,\n size: () => data.length,\n data: (compare, resort) => {\n if (cnt) {\n data = data.filter(t => !rem[$(t)]);\n rem = {};\n cnt = 0;\n }\n\n if (resort && compare) {\n data.sort(compare);\n }\n\n if (add.length) {\n data = compare ? merge(compare, data, add.sort(compare)) : data.concat(add);\n add = [];\n }\n\n return data;\n }\n };\n}\n\n/**\n * Collects all data tuples that pass through this operator.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(*,*): number} [params.sort] - An optional\n * comparator function for additionally sorting the collected tuples.\n */\n\nfunction Collect(params) {\n Transform.call(this, [], params);\n}\nCollect.Definition = {\n 'type': 'Collect',\n 'metadata': {\n 'source': true\n },\n 'params': [{\n 'name': 'sort',\n 'type': 'compare'\n }]\n};\ninherits(Collect, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.ALL),\n list = SortedList(tupleid, this.value, out.materialize(out.ADD).add),\n sort = _.sort,\n mod = pulse.changed() || sort && (_.modified('sort') || pulse.modified(sort.fields));\n out.visit(out.REM, list.remove);\n this.modified(mod);\n this.value = out.source = list.data(stableCompare(sort), mod); // propagate tree root if defined\n\n if (pulse.source && pulse.source.root) {\n this.value.root = pulse.source.root;\n }\n\n return out;\n }\n\n});\n\n/**\n * Generates a comparator function.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} params.fields - The fields to compare.\n * @param {Array} [params.orders] - The sort orders.\n * Each entry should be one of \"ascending\" (default) or \"descending\".\n */\n\nfunction Compare(params) {\n Operator.call(this, null, update$5, params);\n}\ninherits(Compare, Operator);\n\nfunction update$5(_) {\n return this.value && !_.modified() ? this.value : compare(_.fields, _.orders);\n}\n\n/**\n * Count regexp-defined pattern occurrences in a text field.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - An accessor for the text field.\n * @param {string} [params.pattern] - RegExp string defining the text pattern.\n * @param {string} [params.case] - One of 'lower', 'upper' or null (mixed) case.\n * @param {string} [params.stopwords] - RegExp string of words to ignore.\n */\n\nfunction CountPattern(params) {\n Transform.call(this, null, params);\n}\nCountPattern.Definition = {\n 'type': 'CountPattern',\n 'metadata': {\n 'generates': true,\n 'changes': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'case',\n 'type': 'enum',\n 'values': ['upper', 'lower', 'mixed'],\n 'default': 'mixed'\n }, {\n 'name': 'pattern',\n 'type': 'string',\n 'default': '[\\\\w\"]+'\n }, {\n 'name': 'stopwords',\n 'type': 'string',\n 'default': ''\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': 2,\n 'default': ['text', 'count']\n }]\n};\n\nfunction tokenize(text, tcase, match) {\n switch (tcase) {\n case 'upper':\n text = text.toUpperCase();\n break;\n\n case 'lower':\n text = text.toLowerCase();\n break;\n }\n\n return text.match(match);\n}\n\ninherits(CountPattern, Transform, {\n transform(_, pulse) {\n const process = update => tuple => {\n var tokens = tokenize(get(tuple), _.case, match) || [],\n t;\n\n for (var i = 0, n = tokens.length; i < n; ++i) {\n if (!stop.test(t = tokens[i])) update(t);\n }\n };\n\n const init = this._parameterCheck(_, pulse),\n counts = this._counts,\n match = this._match,\n stop = this._stop,\n get = _.field,\n as = _.as || ['text', 'count'],\n add = process(t => counts[t] = 1 + (counts[t] || 0)),\n rem = process(t => counts[t] -= 1);\n\n if (init) {\n pulse.visit(pulse.SOURCE, add);\n } else {\n pulse.visit(pulse.ADD, add);\n pulse.visit(pulse.REM, rem);\n }\n\n return this._finish(pulse, as); // generate output tuples\n },\n\n _parameterCheck(_, pulse) {\n let init = false;\n\n if (_.modified('stopwords') || !this._stop) {\n this._stop = new RegExp('^' + (_.stopwords || '') + '$', 'i');\n init = true;\n }\n\n if (_.modified('pattern') || !this._match) {\n this._match = new RegExp(_.pattern || '[\\\\w\\']+', 'g');\n init = true;\n }\n\n if (_.modified('field') || pulse.modified(_.field.fields)) {\n init = true;\n }\n\n if (init) this._counts = {};\n return init;\n },\n\n _finish(pulse, as) {\n const counts = this._counts,\n tuples = this._tuples || (this._tuples = {}),\n text = as[0],\n count = as[1],\n out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);\n let w, t, c;\n\n for (w in counts) {\n t = tuples[w];\n c = counts[w] || 0;\n\n if (!t && c) {\n tuples[w] = t = ingest({});\n t[text] = w;\n t[count] = c;\n out.add.push(t);\n } else if (c === 0) {\n if (t) out.rem.push(t);\n counts[w] = null;\n tuples[w] = null;\n } else if (t[count] !== c) {\n t[count] = c;\n out.mod.push(t);\n }\n }\n\n return out.modifies(as);\n }\n\n});\n\n/**\n * Perform a cross-product of a tuple stream with itself.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object):boolean} [params.filter] - An optional filter\n * function for selectively including tuples in the cross product.\n * @param {Array} [params.as] - The names of the output fields.\n */\n\nfunction Cross(params) {\n Transform.call(this, null, params);\n}\nCross.Definition = {\n 'type': 'Cross',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'filter',\n 'type': 'expr'\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': 2,\n 'default': ['a', 'b']\n }]\n};\ninherits(Cross, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE),\n as = _.as || ['a', 'b'],\n a = as[0],\n b = as[1],\n reset = !this.value || pulse.changed(pulse.ADD_REM) || _.modified('as') || _.modified('filter');\n\n let data = this.value;\n\n if (reset) {\n if (data) out.rem = data;\n data = pulse.materialize(pulse.SOURCE).source;\n out.add = this.value = cross(data, a, b, _.filter || truthy);\n } else {\n out.mod = data;\n }\n\n out.source = this.value;\n return out.modifies(as);\n }\n\n});\n\nfunction cross(input, a, b, filter) {\n var data = [],\n t = {},\n n = input.length,\n i = 0,\n j,\n left;\n\n for (; i < n; ++i) {\n t[a] = left = input[i];\n\n for (j = 0; j < n; ++j) {\n t[b] = input[j];\n\n if (filter(t)) {\n data.push(ingest(t));\n t = {};\n t[a] = left;\n }\n }\n }\n\n return data;\n}\n\nconst Distributions = {\n kde: randomKDE,\n mixture: randomMixture,\n normal: randomNormal,\n lognormal: randomLogNormal,\n uniform: randomUniform\n};\nconst DISTRIBUTIONS = 'distributions',\n FUNCTION = 'function',\n FIELD = 'field';\n/**\n * Parse a parameter object for a probability distribution.\n * @param {object} def - The distribution parameter object.\n * @param {function():Array} - A method for requesting\n * source data. Used for distributions (such as KDE) that\n * require sample data points. This method will only be\n * invoked if the 'from' parameter for a target data source\n * is not provided. Typically this method returns backing\n * source data for a Pulse object.\n * @return {object} - The output distribution object.\n */\n\nfunction parse(def, data) {\n const func = def[FUNCTION];\n\n if (!hasOwnProperty(Distributions, func)) {\n error('Unknown distribution function: ' + func);\n }\n\n const d = Distributions[func]();\n\n for (const name in def) {\n // if data field, extract values\n if (name === FIELD) {\n d.data((def.from || data()).map(def[name]));\n } // if distribution mixture, recurse to parse each definition\n else if (name === DISTRIBUTIONS) {\n d[name](def[name].map(_ => parse(_, data)));\n } // otherwise, simply set the parameter\n else if (typeof d[name] === FUNCTION) {\n d[name](def[name]);\n }\n }\n\n return d;\n}\n\n/**\n * Grid sample points for a probability density. Given a distribution and\n * a sampling extent, will generate points suitable for plotting either\n * PDF (probability density function) or CDF (cumulative distribution\n * function) curves.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {object} params.distribution - The probability distribution. This\n * is an object parameter dependent on the distribution type.\n * @param {string} [params.method='pdf'] - The distribution method to sample.\n * One of 'pdf' or 'cdf'.\n * @param {Array} [params.extent] - The [min, max] extent over which\n * to sample the distribution. This argument is required in most cases, but\n * can be omitted if the distribution (e.g., 'kde') supports a 'data' method\n * that returns numerical sample points from which the extent can be deduced.\n * @param {number} [params.minsteps=25] - The minimum number of curve samples\n * for plotting the density.\n * @param {number} [params.maxsteps=200] - The maximum number of curve samples\n * for plotting the density.\n * @param {number} [params.steps] - The exact number of curve samples for\n * plotting the density. If specified, overrides both minsteps and maxsteps\n * to set an exact number of uniform samples. Useful in conjunction with\n * a fixed extent to ensure consistent sample points for stacked densities.\n */\n\nfunction Density(params) {\n Transform.call(this, null, params);\n}\nconst distributions = [{\n 'key': {\n 'function': 'normal'\n },\n 'params': [{\n 'name': 'mean',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'stdev',\n 'type': 'number',\n 'default': 1\n }]\n}, {\n 'key': {\n 'function': 'lognormal'\n },\n 'params': [{\n 'name': 'mean',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'stdev',\n 'type': 'number',\n 'default': 1\n }]\n}, {\n 'key': {\n 'function': 'uniform'\n },\n 'params': [{\n 'name': 'min',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'max',\n 'type': 'number',\n 'default': 1\n }]\n}, {\n 'key': {\n 'function': 'kde'\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'from',\n 'type': 'data'\n }, {\n 'name': 'bandwidth',\n 'type': 'number',\n 'default': 0\n }]\n}];\nconst mixture = {\n 'key': {\n 'function': 'mixture'\n },\n 'params': [{\n 'name': 'distributions',\n 'type': 'param',\n 'array': true,\n 'params': distributions\n }, {\n 'name': 'weights',\n 'type': 'number',\n 'array': true\n }]\n};\nDensity.Definition = {\n 'type': 'Density',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'extent',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'steps',\n 'type': 'number'\n }, {\n 'name': 'minsteps',\n 'type': 'number',\n 'default': 25\n }, {\n 'name': 'maxsteps',\n 'type': 'number',\n 'default': 200\n }, {\n 'name': 'method',\n 'type': 'string',\n 'default': 'pdf',\n 'values': ['pdf', 'cdf']\n }, {\n 'name': 'distribution',\n 'type': 'param',\n 'params': distributions.concat(mixture)\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'default': ['value', 'density']\n }]\n};\ninherits(Density, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);\n\n if (!this.value || pulse.changed() || _.modified()) {\n const dist = parse(_.distribution, source(pulse)),\n minsteps = _.steps || _.minsteps || 25,\n maxsteps = _.steps || _.maxsteps || 200;\n let method = _.method || 'pdf';\n\n if (method !== 'pdf' && method !== 'cdf') {\n error('Invalid density method: ' + method);\n }\n\n if (!_.extent && !dist.data) {\n error('Missing density extent parameter.');\n }\n\n method = dist[method];\n const as = _.as || ['value', 'density'],\n domain = _.extent || extent(dist.data()),\n values = sampleCurve(method, domain, minsteps, maxsteps).map(v => {\n const tuple = {};\n tuple[as[0]] = v[0];\n tuple[as[1]] = v[1];\n return ingest(tuple);\n });\n if (this.value) out.rem = this.value;\n this.value = out.add = out.source = values;\n }\n\n return out;\n }\n\n});\n\nfunction source(pulse) {\n return () => pulse.materialize(pulse.SOURCE).source;\n}\n\nfunction fieldNames(fields, as) {\n if (!fields) return null;\n return fields.map((f, i) => as[i] || accessorName(f));\n}\nfunction partition$1(data, groupby, field) {\n const groups = [],\n get = f => f(t);\n\n let map, i, n, t, k, g; // partition data points into groups\n\n if (groupby == null) {\n groups.push(data.map(field));\n } else {\n for (map = {}, i = 0, n = data.length; i < n; ++i) {\n t = data[i];\n k = groupby.map(get);\n g = map[k];\n\n if (!g) {\n map[k] = g = [];\n g.dims = k;\n groups.push(g);\n }\n\n g.push(field(t));\n }\n }\n\n return groups;\n}\n\nconst Output = 'bin';\n/**\n * Dot density binning for dot plot construction.\n * Based on Leland Wilkinson, Dot Plots, The American Statistician, 1999.\n * https://www.cs.uic.edu/~wilkinson/Publications/dotplots.pdf\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The value field to bin.\n * @param {Array} [params.groupby] - An array of accessors to groupby.\n * @param {number} [params.step] - The step size (bin width) within which dots should be\n * stacked. Defaults to 1/30 of the extent of the data *field*.\n * @param {boolean} [params.smooth=false] - A boolean flag indicating if dot density\n * stacks should be smoothed to reduce variance.\n */\n\nfunction DotBin(params) {\n Transform.call(this, null, params);\n}\nDotBin.Definition = {\n 'type': 'DotBin',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'step',\n 'type': 'number'\n }, {\n 'name': 'smooth',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'as',\n 'type': 'string',\n 'default': Output\n }]\n};\n\nconst autostep = (data, field) => span(extent(data, field)) / 30;\n\ninherits(DotBin, Transform, {\n transform(_, pulse) {\n if (this.value && !(_.modified() || pulse.changed())) {\n return pulse; // early exit\n }\n\n const source = pulse.materialize(pulse.SOURCE).source,\n groups = partition$1(pulse.source, _.groupby, identity),\n smooth = _.smooth || false,\n field = _.field,\n step = _.step || autostep(source, field),\n sort = stableCompare((a, b) => field(a) - field(b)),\n as = _.as || Output,\n n = groups.length; // compute dotplot bins per group\n\n let min = Infinity,\n max = -Infinity,\n i = 0,\n j;\n\n for (; i < n; ++i) {\n const g = groups[i].sort(sort);\n j = -1;\n\n for (const v of dotbin(g, step, smooth, field)) {\n if (v < min) min = v;\n if (v > max) max = v;\n g[++j][as] = v;\n }\n }\n\n this.value = {\n start: min,\n stop: max,\n step: step\n };\n return pulse.reflow(true).modifies(as);\n }\n\n});\n\n/**\n * Wraps an expression function with access to external parameters.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function} params.expr - The expression function. The\n * function should accept both a datum and a parameter object.\n * This operator's value will be a new function that wraps the\n * expression function with access to this operator's parameters.\n */\n\nfunction Expression(params) {\n Operator.call(this, null, update$4, params);\n this.modified(true);\n}\ninherits(Expression, Operator);\n\nfunction update$4(_) {\n const expr = _.expr;\n return this.value && !_.modified('expr') ? this.value : accessor(datum => expr(datum, _), accessorFields(expr), accessorName(expr));\n}\n\n/**\n * Computes extents (min/max) for a data field.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The field over which to compute extends.\n */\n\nfunction Extent(params) {\n Transform.call(this, [undefined, undefined], params);\n}\nExtent.Definition = {\n 'type': 'Extent',\n 'metadata': {},\n 'params': [{\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }]\n};\ninherits(Extent, Transform, {\n transform(_, pulse) {\n const extent = this.value,\n field = _.field,\n mod = pulse.changed() || pulse.modified(field.fields) || _.modified('field');\n\n let min = extent[0],\n max = extent[1];\n\n if (mod || min == null) {\n min = +Infinity;\n max = -Infinity;\n }\n\n pulse.visit(mod ? pulse.SOURCE : pulse.ADD, t => {\n const v = toNumber(field(t));\n\n if (v != null) {\n // NaNs will fail all comparisons!\n if (v < min) min = v;\n if (v > max) max = v;\n }\n });\n\n if (!Number.isFinite(min) || !Number.isFinite(max)) {\n let name = accessorName(field);\n if (name) name = ` for field \"${name}\"`;\n pulse.dataflow.warn(`Infinite extent${name}: [${min}, ${max}]`);\n min = max = undefined;\n }\n\n this.value = [min, max];\n }\n\n});\n\n/**\n * Provides a bridge between a parent transform and a target subflow that\n * consumes only a subset of the tuples that pass through the parent.\n * @constructor\n * @param {Pulse} pulse - A pulse to use as the value of this operator.\n * @param {Transform} parent - The parent transform (typically a Facet instance).\n */\n\nfunction Subflow(pulse, parent) {\n Operator.call(this, pulse);\n this.parent = parent;\n this.count = 0;\n}\ninherits(Subflow, Operator, {\n /**\n * Routes pulses from this subflow to a target transform.\n * @param {Transform} target - A transform that receives the subflow of tuples.\n */\n connect(target) {\n this.detachSubflow = target.detachSubflow;\n this.targets().add(target);\n return target.source = this;\n },\n\n /**\n * Add an 'add' tuple to the subflow pulse.\n * @param {Tuple} t - The tuple being added.\n */\n add(t) {\n this.count += 1;\n this.value.add.push(t);\n },\n\n /**\n * Add a 'rem' tuple to the subflow pulse.\n * @param {Tuple} t - The tuple being removed.\n */\n rem(t) {\n this.count -= 1;\n this.value.rem.push(t);\n },\n\n /**\n * Add a 'mod' tuple to the subflow pulse.\n * @param {Tuple} t - The tuple being modified.\n */\n mod(t) {\n this.value.mod.push(t);\n },\n\n /**\n * Re-initialize this operator's pulse value.\n * @param {Pulse} pulse - The pulse to copy from.\n * @see Pulse.init\n */\n init(pulse) {\n this.value.init(pulse, pulse.NO_SOURCE);\n },\n\n /**\n * Evaluate this operator. This method overrides the\n * default behavior to simply return the contained pulse value.\n * @return {Pulse}\n */\n evaluate() {\n // assert: this.value.stamp === pulse.stamp\n return this.value;\n }\n\n});\n\n/**\n * Facets a dataflow into a set of subflows based on a key.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(Dataflow, string): Operator} params.subflow - A function\n * that generates a subflow of operators and returns its root operator.\n * @param {function(object): *} params.key - The key field to facet by.\n */\n\nfunction Facet(params) {\n Transform.call(this, {}, params);\n this._keys = fastmap(); // cache previously calculated key values\n // keep track of active subflows, use as targets array for listeners\n // this allows us to limit propagation to only updated subflows\n\n const a = this._targets = [];\n a.active = 0;\n\n a.forEach = f => {\n for (let i = 0, n = a.active; i < n; ++i) {\n f(a[i], i, a);\n }\n };\n}\ninherits(Facet, Transform, {\n activate(flow) {\n this._targets[this._targets.active++] = flow;\n },\n\n // parent argument provided by PreFacet subclass\n subflow(key, flow, pulse, parent) {\n const flows = this.value;\n let sf = hasOwnProperty(flows, key) && flows[key],\n df,\n p;\n\n if (!sf) {\n p = parent || (p = this._group[key]) && p.tuple;\n df = pulse.dataflow;\n sf = new Subflow(pulse.fork(pulse.NO_SOURCE), this);\n df.add(sf).connect(flow(df, key, p));\n flows[key] = sf;\n this.activate(sf);\n } else if (sf.value.stamp < pulse.stamp) {\n sf.init(pulse);\n this.activate(sf);\n }\n\n return sf;\n },\n\n clean() {\n const flows = this.value;\n let detached = 0;\n\n for (const key in flows) {\n if (flows[key].count === 0) {\n const detach = flows[key].detachSubflow;\n if (detach) detach();\n delete flows[key];\n ++detached;\n }\n } // remove inactive targets from the active targets array\n\n\n if (detached) {\n const active = this._targets.filter(sf => sf && sf.count > 0);\n\n this.initTargets(active);\n }\n },\n\n initTargets(act) {\n const a = this._targets,\n n = a.length,\n m = act ? act.length : 0;\n let i = 0;\n\n for (; i < m; ++i) {\n a[i] = act[i];\n }\n\n for (; i < n && a[i] != null; ++i) {\n a[i] = null; // ensure old flows can be garbage collected\n }\n\n a.active = m;\n },\n\n transform(_, pulse) {\n const df = pulse.dataflow,\n key = _.key,\n flow = _.subflow,\n cache = this._keys,\n rekey = _.modified('key'),\n subflow = key => this.subflow(key, flow, pulse);\n\n this._group = _.group || {};\n this.initTargets(); // reset list of active subflows\n\n pulse.visit(pulse.REM, t => {\n const id = tupleid(t),\n k = cache.get(id);\n\n if (k !== undefined) {\n cache.delete(id);\n subflow(k).rem(t);\n }\n });\n pulse.visit(pulse.ADD, t => {\n const k = key(t);\n cache.set(tupleid(t), k);\n subflow(k).add(t);\n });\n\n if (rekey || pulse.modified(key.fields)) {\n pulse.visit(pulse.MOD, t => {\n const id = tupleid(t),\n k0 = cache.get(id),\n k1 = key(t);\n\n if (k0 === k1) {\n subflow(k1).mod(t);\n } else {\n cache.set(id, k1);\n subflow(k0).rem(t);\n subflow(k1).add(t);\n }\n });\n } else if (pulse.changed(pulse.MOD)) {\n pulse.visit(pulse.MOD, t => {\n subflow(cache.get(tupleid(t))).mod(t);\n });\n }\n\n if (rekey) {\n pulse.visit(pulse.REFLOW, t => {\n const id = tupleid(t),\n k0 = cache.get(id),\n k1 = key(t);\n\n if (k0 !== k1) {\n cache.set(id, k1);\n subflow(k0).rem(t);\n subflow(k1).add(t);\n }\n });\n }\n\n if (pulse.clean()) {\n df.runAfter(() => {\n this.clean();\n cache.clean();\n });\n } else if (cache.empty > df.cleanThreshold) {\n df.runAfter(cache.clean);\n }\n\n return pulse;\n }\n\n});\n\n/**\n * Generates one or more field accessor functions.\n * If the 'name' parameter is an array, an array of field accessors\n * will be created and the 'as' parameter will be ignored.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {string} params.name - The field name(s) to access.\n * @param {string} params.as - The accessor function name.\n */\n\nfunction Field(params) {\n Operator.call(this, null, update$3, params);\n}\ninherits(Field, Operator);\n\nfunction update$3(_) {\n return this.value && !_.modified() ? this.value : isArray(_.name) ? array(_.name).map(f => field(f)) : field(_.name, _.as);\n}\n\n/**\n * Filters data tuples according to a predicate function.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.expr - The predicate expression function\n * that determines a tuple's filter status. Truthy values pass the filter.\n */\n\nfunction Filter(params) {\n Transform.call(this, fastmap(), params);\n}\nFilter.Definition = {\n 'type': 'Filter',\n 'metadata': {\n 'changes': true\n },\n 'params': [{\n 'name': 'expr',\n 'type': 'expr',\n 'required': true\n }]\n};\ninherits(Filter, Transform, {\n transform(_, pulse) {\n const df = pulse.dataflow,\n cache = this.value,\n // cache ids of filtered tuples\n output = pulse.fork(),\n add = output.add,\n rem = output.rem,\n mod = output.mod,\n test = _.expr;\n let isMod = true;\n pulse.visit(pulse.REM, t => {\n const id = tupleid(t);\n if (!cache.has(id)) rem.push(t);else cache.delete(id);\n });\n pulse.visit(pulse.ADD, t => {\n if (test(t, _)) add.push(t);else cache.set(tupleid(t), 1);\n });\n\n function revisit(t) {\n const id = tupleid(t),\n b = test(t, _),\n s = cache.get(id);\n\n if (b && s) {\n cache.delete(id);\n add.push(t);\n } else if (!b && !s) {\n cache.set(id, 1);\n rem.push(t);\n } else if (isMod && b && !s) {\n mod.push(t);\n }\n }\n\n pulse.visit(pulse.MOD, revisit);\n\n if (_.modified()) {\n isMod = false;\n pulse.visit(pulse.REFLOW, revisit);\n }\n\n if (cache.empty > df.cleanThreshold) df.runAfter(cache.clean);\n return output;\n }\n\n});\n\n/**\n * Flattens array-typed field values into new data objects.\n * If multiple fields are specified, they are treated as parallel arrays,\n * with output values included for each matching index (or null if missing).\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} params.fields - An array of field\n * accessors for the tuple fields that should be flattened.\n * @param {string} [params.index] - Optional output field name for index\n * value. If unspecified, no index field is included in the output.\n * @param {Array} [params.as] - Output field names for flattened\n * array fields. Any unspecified fields will use the field name provided\n * by the fields accessors.\n */\n\nfunction Flatten(params) {\n Transform.call(this, [], params);\n}\nFlatten.Definition = {\n 'type': 'Flatten',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'fields',\n 'type': 'field',\n 'array': true,\n 'required': true\n }, {\n 'name': 'index',\n 'type': 'string'\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true\n }]\n};\ninherits(Flatten, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE),\n fields = _.fields,\n as = fieldNames(fields, _.as || []),\n index = _.index || null,\n m = as.length; // remove any previous results\n\n out.rem = this.value; // generate flattened tuples\n\n pulse.visit(pulse.SOURCE, t => {\n const arrays = fields.map(f => f(t)),\n maxlen = arrays.reduce((l, a) => Math.max(l, a.length), 0);\n let i = 0,\n j,\n d,\n v;\n\n for (; i < maxlen; ++i) {\n d = derive(t);\n\n for (j = 0; j < m; ++j) {\n d[as[j]] = (v = arrays[j][i]) == null ? null : v;\n }\n\n if (index) {\n d[index] = i;\n }\n\n out.add.push(d);\n }\n });\n this.value = out.source = out.add;\n if (index) out.modifies(index);\n return out.modifies(as);\n }\n\n});\n\n/**\n * Folds one more tuple fields into multiple tuples in which the field\n * name and values are available under new 'key' and 'value' fields.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.fields - An array of field accessors\n * for the tuple fields that should be folded.\n * @param {Array} [params.as] - Output field names for folded key\n * and value fields, defaults to ['key', 'value'].\n */\n\nfunction Fold(params) {\n Transform.call(this, [], params);\n}\nFold.Definition = {\n 'type': 'Fold',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'fields',\n 'type': 'field',\n 'array': true,\n 'required': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': 2,\n 'default': ['key', 'value']\n }]\n};\ninherits(Fold, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE),\n fields = _.fields,\n fnames = fields.map(accessorName),\n as = _.as || ['key', 'value'],\n k = as[0],\n v = as[1],\n n = fields.length;\n out.rem = this.value;\n pulse.visit(pulse.SOURCE, t => {\n for (let i = 0, d; i < n; ++i) {\n d = derive(t);\n d[k] = fnames[i];\n d[v] = fields[i](t);\n out.add.push(d);\n }\n });\n this.value = out.source = out.add;\n return out.modifies(as);\n }\n\n});\n\n/**\n * Invokes a function for each data tuple and saves the results as a new field.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.expr - The formula function to invoke for each tuple.\n * @param {string} params.as - The field name under which to save the result.\n * @param {boolean} [params.initonly=false] - If true, the formula is applied to\n * added tuples only, and does not update in response to modifications.\n */\n\nfunction Formula(params) {\n Transform.call(this, null, params);\n}\nFormula.Definition = {\n 'type': 'Formula',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'expr',\n 'type': 'expr',\n 'required': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'required': true\n }, {\n 'name': 'initonly',\n 'type': 'boolean'\n }]\n};\ninherits(Formula, Transform, {\n transform(_, pulse) {\n const func = _.expr,\n as = _.as,\n mod = _.modified(),\n flag = _.initonly ? pulse.ADD : mod ? pulse.SOURCE : pulse.modified(func.fields) || pulse.modified(as) ? pulse.ADD_MOD : pulse.ADD;\n\n if (mod) {\n // parameters updated, need to reflow\n pulse = pulse.materialize().reflow(true);\n }\n\n if (!_.initonly) {\n pulse.modifies(as);\n }\n\n return pulse.visit(flag, t => t[as] = func(t, _));\n }\n\n});\n\n/**\n * Generates data tuples using a provided generator function.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(Parameters): object} params.generator - A tuple generator\n * function. This function is given the operator parameters as input.\n * Changes to any additional parameters will not trigger re-calculation\n * of previously generated tuples. Only future tuples are affected.\n * @param {number} params.size - The number of tuples to produce.\n */\n\nfunction Generate(params) {\n Transform.call(this, [], params);\n}\ninherits(Generate, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.ALL),\n gen = _.generator;\n let data = this.value,\n num = _.size - data.length,\n add,\n rem,\n t;\n\n if (num > 0) {\n // need more tuples, generate and add\n for (add = []; --num >= 0;) {\n add.push(t = ingest(gen(_)));\n data.push(t);\n }\n\n out.add = out.add.length ? out.materialize(out.ADD).add.concat(add) : add;\n } else {\n // need fewer tuples, remove\n rem = data.slice(0, -num);\n out.rem = out.rem.length ? out.materialize(out.REM).rem.concat(rem) : rem;\n data = data.slice(-num);\n }\n\n out.source = this.value = data;\n return out;\n }\n\n});\n\nconst Methods = {\n value: 'value',\n median: median,\n mean: mean,\n min: min,\n max: max\n};\nconst Empty = [];\n/**\n * Impute missing values.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The value field to impute.\n * @param {Array} [params.groupby] - An array of\n * accessors to determine series within which to perform imputation.\n * @param {function(object): *} params.key - An accessor for a key value.\n * Each key value should be unique within a group. New tuples will be\n * imputed for any key values that are not found within a group.\n * @param {Array<*>} [params.keyvals] - Optional array of required key\n * values. New tuples will be imputed for any key values that are not\n * found within a group. In addition, these values will be automatically\n * augmented with the key values observed in the input data.\n * @param {string} [method='value'] - The imputation method to use. One of\n * 'value', 'mean', 'median', 'max', 'min'.\n * @param {*} [value=0] - The constant value to use for imputation\n * when using method 'value'.\n */\n\nfunction Impute(params) {\n Transform.call(this, [], params);\n}\nImpute.Definition = {\n 'type': 'Impute',\n 'metadata': {\n 'changes': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'key',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'keyvals',\n 'array': true\n }, {\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'method',\n 'type': 'enum',\n 'default': 'value',\n 'values': ['value', 'mean', 'median', 'max', 'min']\n }, {\n 'name': 'value',\n 'default': 0\n }]\n};\n\nfunction getValue(_) {\n var m = _.method || Methods.value,\n v;\n\n if (Methods[m] == null) {\n error('Unrecognized imputation method: ' + m);\n } else if (m === Methods.value) {\n v = _.value !== undefined ? _.value : 0;\n return () => v;\n } else {\n return Methods[m];\n }\n}\n\nfunction getField(_) {\n const f = _.field;\n return t => t ? f(t) : NaN;\n}\n\ninherits(Impute, Transform, {\n transform(_, pulse) {\n var out = pulse.fork(pulse.ALL),\n impute = getValue(_),\n field = getField(_),\n fName = accessorName(_.field),\n kName = accessorName(_.key),\n gNames = (_.groupby || []).map(accessorName),\n groups = partition(pulse.source, _.groupby, _.key, _.keyvals),\n curr = [],\n prev = this.value,\n m = groups.domain.length,\n group,\n value,\n gVals,\n kVal,\n g,\n i,\n j,\n l,\n n,\n t;\n\n for (g = 0, l = groups.length; g < l; ++g) {\n group = groups[g];\n gVals = group.values;\n value = NaN; // add tuples for missing values\n\n for (j = 0; j < m; ++j) {\n if (group[j] != null) continue;\n kVal = groups.domain[j];\n t = {\n _impute: true\n };\n\n for (i = 0, n = gVals.length; i < n; ++i) t[gNames[i]] = gVals[i];\n\n t[kName] = kVal;\n t[fName] = Number.isNaN(value) ? value = impute(group, field) : value;\n curr.push(ingest(t));\n }\n } // update pulse with imputed tuples\n\n\n if (curr.length) out.add = out.materialize(out.ADD).add.concat(curr);\n if (prev.length) out.rem = out.materialize(out.REM).rem.concat(prev);\n this.value = curr;\n return out;\n }\n\n});\n\nfunction partition(data, groupby, key, keyvals) {\n var get = f => f(t),\n groups = [],\n domain = keyvals ? keyvals.slice() : [],\n kMap = {},\n gMap = {},\n gVals,\n gKey,\n group,\n i,\n j,\n k,\n n,\n t;\n\n domain.forEach((k, i) => kMap[k] = i + 1);\n\n for (i = 0, n = data.length; i < n; ++i) {\n t = data[i];\n k = key(t);\n j = kMap[k] || (kMap[k] = domain.push(k));\n gKey = (gVals = groupby ? groupby.map(get) : Empty) + '';\n\n if (!(group = gMap[gKey])) {\n group = gMap[gKey] = [];\n groups.push(group);\n group.values = gVals;\n }\n\n group[j - 1] = t;\n }\n\n groups.domain = domain;\n return groups;\n}\n\n/**\n * Extend input tuples with aggregate values.\n * Calcuates aggregate values and joins them with the input stream.\n * @constructor\n */\n\nfunction JoinAggregate(params) {\n Aggregate.call(this, params);\n}\nJoinAggregate.Definition = {\n 'type': 'JoinAggregate',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'fields',\n 'type': 'field',\n 'null': true,\n 'array': true\n }, {\n 'name': 'ops',\n 'type': 'enum',\n 'array': true,\n 'values': ValidAggregateOps\n }, {\n 'name': 'as',\n 'type': 'string',\n 'null': true,\n 'array': true\n }, {\n 'name': 'key',\n 'type': 'field'\n }]\n};\ninherits(JoinAggregate, Aggregate, {\n transform(_, pulse) {\n const aggr = this,\n mod = _.modified();\n\n let cells; // process all input tuples to calculate aggregates\n\n if (aggr.value && (mod || pulse.modified(aggr._inputs, true))) {\n cells = aggr.value = mod ? aggr.init(_) : {};\n pulse.visit(pulse.SOURCE, t => aggr.add(t));\n } else {\n cells = aggr.value = aggr.value || this.init(_);\n pulse.visit(pulse.REM, t => aggr.rem(t));\n pulse.visit(pulse.ADD, t => aggr.add(t));\n } // update aggregation cells\n\n\n aggr.changes(); // write aggregate values to input tuples\n\n pulse.visit(pulse.SOURCE, t => {\n extend(t, cells[aggr.cellkey(t)].tuple);\n });\n return pulse.reflow(mod).modifies(this._outputs);\n },\n\n changes() {\n const adds = this._adds,\n mods = this._mods;\n let i, n;\n\n for (i = 0, n = this._alen; i < n; ++i) {\n this.celltuple(adds[i]);\n adds[i] = null; // for garbage collection\n }\n\n for (i = 0, n = this._mlen; i < n; ++i) {\n this.celltuple(mods[i]);\n mods[i] = null; // for garbage collection\n }\n\n this._alen = this._mlen = 0; // reset list of active cells\n }\n\n});\n\n/**\n * Compute kernel density estimates (KDE) for one or more data groups.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} [params.groupby] - An array of accessors\n * to groupby.\n * @param {function(object): *} params.field - An accessor for the data field\n * to estimate.\n * @param {number} [params.bandwidth=0] - The KDE kernel bandwidth.\n * If zero or unspecified, the bandwidth is automatically determined.\n * @param {boolean} [params.counts=false] - A boolean flag indicating if the\n * output values should be probability estimates (false, default) or\n * smoothed counts (true).\n * @param {string} [params.cumulative=false] - A boolean flag indicating if a\n * density (false) or cumulative distribution (true) should be generated.\n * @param {Array} [params.extent] - The domain extent over which to\n * plot the density. If unspecified, the [min, max] data extent is used.\n * @param {string} [params.resolve='independent'] - Indicates how parameters for\n * multiple densities should be resolved. If \"independent\" (the default), each\n * density may have its own domain extent and dynamic number of curve sample\n * steps. If \"shared\", the KDE transform will ensure that all densities are\n * defined over a shared domain and curve steps, enabling stacking.\n * @param {number} [params.minsteps=25] - The minimum number of curve samples\n * for plotting the density.\n * @param {number} [params.maxsteps=200] - The maximum number of curve samples\n * for plotting the density.\n * @param {number} [params.steps] - The exact number of curve samples for\n * plotting the density. If specified, overrides both minsteps and maxsteps\n * to set an exact number of uniform samples. Useful in conjunction with\n * a fixed extent to ensure consistent sample points for stacked densities.\n */\n\nfunction KDE(params) {\n Transform.call(this, null, params);\n}\nKDE.Definition = {\n 'type': 'KDE',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'cumulative',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'counts',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'bandwidth',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'extent',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'resolve',\n 'type': 'enum',\n 'values': ['shared', 'independent'],\n 'default': 'independent'\n }, {\n 'name': 'steps',\n 'type': 'number'\n }, {\n 'name': 'minsteps',\n 'type': 'number',\n 'default': 25\n }, {\n 'name': 'maxsteps',\n 'type': 'number',\n 'default': 200\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'default': ['value', 'density']\n }]\n};\ninherits(KDE, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);\n\n if (!this.value || pulse.changed() || _.modified()) {\n const source = pulse.materialize(pulse.SOURCE).source,\n groups = partition$1(source, _.groupby, _.field),\n names = (_.groupby || []).map(accessorName),\n bandwidth = _.bandwidth,\n method = _.cumulative ? 'cdf' : 'pdf',\n as = _.as || ['value', 'density'],\n values = [];\n let domain = _.extent,\n minsteps = _.steps || _.minsteps || 25,\n maxsteps = _.steps || _.maxsteps || 200;\n\n if (method !== 'pdf' && method !== 'cdf') {\n error('Invalid density method: ' + method);\n }\n\n if (_.resolve === 'shared') {\n if (!domain) domain = extent(source, _.field);\n minsteps = maxsteps = _.steps || maxsteps;\n }\n\n groups.forEach(g => {\n const density = randomKDE(g, bandwidth)[method],\n scale = _.counts ? g.length : 1,\n local = domain || extent(g);\n sampleCurve(density, local, minsteps, maxsteps).forEach(v => {\n const t = {};\n\n for (let i = 0; i < names.length; ++i) {\n t[names[i]] = g.dims[i];\n }\n\n t[as[0]] = v[0];\n t[as[1]] = v[1] * scale;\n values.push(ingest(t));\n });\n });\n if (this.value) out.rem = this.value;\n this.value = out.add = out.source = values;\n }\n\n return out;\n }\n\n});\n\n/**\n * Generates a key function.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} params.fields - The field name(s) for the key function.\n * @param {boolean} params.flat - A boolean flag indicating if the field names\n * should be treated as flat property names, side-stepping nested field\n * lookups normally indicated by dot or bracket notation.\n */\n\nfunction Key(params) {\n Operator.call(this, null, update$2, params);\n}\ninherits(Key, Operator);\n\nfunction update$2(_) {\n return this.value && !_.modified() ? this.value : key(_.fields, _.flat);\n}\n\n/**\n * Load and parse data from an external source. Marshalls parameter\n * values and then invokes the Dataflow request method.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {string} params.url - The URL to load from.\n * @param {object} params.format - The data format options.\n */\n\nfunction Load(params) {\n Transform.call(this, [], params);\n this._pending = null;\n}\ninherits(Load, Transform, {\n transform(_, pulse) {\n const df = pulse.dataflow;\n\n if (this._pending) {\n // update state and return pulse\n return output(this, pulse, this._pending);\n }\n\n if (stop(_)) return pulse.StopPropagation;\n\n if (_.values) {\n // parse and ingest values, return output pulse\n return output(this, pulse, df.parse(_.values, _.format));\n } else if (_.async) {\n // return promise for non-blocking async loading\n const p = df.request(_.url, _.format).then(res => {\n this._pending = array(res.data);\n return df => df.touch(this);\n });\n return {\n async: p\n };\n } else {\n // return promise for synchronous loading\n return df.request(_.url, _.format).then(res => output(this, pulse, array(res.data)));\n }\n }\n\n});\n\nfunction stop(_) {\n return _.modified('async') && !(_.modified('values') || _.modified('url') || _.modified('format'));\n}\n\nfunction output(op, pulse, data) {\n data.forEach(ingest);\n const out = pulse.fork(pulse.NO_FIELDS & pulse.NO_SOURCE);\n out.rem = op.value;\n op.value = out.source = out.add = data;\n op._pending = null;\n if (out.rem.length) out.clean(true);\n return out;\n}\n\n/**\n * Extend tuples by joining them with values from a lookup table.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Map} params.index - The lookup table map.\n * @param {Array} params.as - Output field names for each lookup value.\n * @param {*} [params.default] - A default value to use if lookup fails.\n */\n\nfunction Lookup(params) {\n Transform.call(this, {}, params);\n}\nLookup.Definition = {\n 'type': 'Lookup',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'index',\n 'type': 'index',\n 'params': [{\n 'name': 'from',\n 'type': 'data',\n 'required': true\n }, {\n 'name': 'key',\n 'type': 'field',\n 'required': true\n }]\n }, {\n 'name': 'values',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'fields',\n 'type': 'field',\n 'array': true,\n 'required': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true\n }, {\n 'name': 'default',\n 'default': null\n }]\n};\ninherits(Lookup, Transform, {\n transform(_, pulse) {\n const keys = _.fields,\n index = _.index,\n values = _.values,\n defaultValue = _.default == null ? null : _.default,\n reset = _.modified(),\n n = keys.length;\n\n let flag = reset ? pulse.SOURCE : pulse.ADD,\n out = pulse,\n as = _.as,\n set,\n m,\n mods;\n\n if (values) {\n m = values.length;\n\n if (n > 1 && !as) {\n error('Multi-field lookup requires explicit \"as\" parameter.');\n }\n\n if (as && as.length !== n * m) {\n error('The \"as\" parameter has too few output field names.');\n }\n\n as = as || values.map(accessorName);\n\n set = function (t) {\n for (var i = 0, k = 0, j, v; i < n; ++i) {\n v = index.get(keys[i](t));\n if (v == null) for (j = 0; j < m; ++j, ++k) t[as[k]] = defaultValue;else for (j = 0; j < m; ++j, ++k) t[as[k]] = values[j](v);\n }\n };\n } else {\n if (!as) {\n error('Missing output field names.');\n }\n\n set = function (t) {\n for (var i = 0, v; i < n; ++i) {\n v = index.get(keys[i](t));\n t[as[i]] = v == null ? defaultValue : v;\n }\n };\n }\n\n if (reset) {\n out = pulse.reflow(true);\n } else {\n mods = keys.some(k => pulse.modified(k.fields));\n flag |= mods ? pulse.MOD : 0;\n }\n\n pulse.visit(flag, set);\n return out.modifies(as);\n }\n\n});\n\n/**\n * Computes global min/max extents over a collection of extents.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array>} params.extents - The input extents.\n */\n\nfunction MultiExtent(params) {\n Operator.call(this, null, update$1, params);\n}\ninherits(MultiExtent, Operator);\n\nfunction update$1(_) {\n if (this.value && !_.modified()) {\n return this.value;\n }\n\n const ext = _.extents,\n n = ext.length;\n let min = +Infinity,\n max = -Infinity,\n i,\n e;\n\n for (i = 0; i < n; ++i) {\n e = ext[i];\n if (e[0] < min) min = e[0];\n if (e[1] > max) max = e[1];\n }\n\n return [min, max];\n}\n\n/**\n * Merge a collection of value arrays.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array>} params.values - The input value arrrays.\n */\n\nfunction MultiValues(params) {\n Operator.call(this, null, update, params);\n}\ninherits(MultiValues, Operator);\n\nfunction update(_) {\n return this.value && !_.modified() ? this.value : _.values.reduce((data, _) => data.concat(_), []);\n}\n\n/**\n * Operator whose value is simply its parameter hash. This operator is\n * useful for enabling reactive updates to values of nested objects.\n * @constructor\n * @param {object} params - The parameters for this operator.\n */\n\nfunction Params(params) {\n Transform.call(this, null, params);\n}\ninherits(Params, Transform, {\n transform(_, pulse) {\n this.modified(_.modified());\n this.value = _;\n return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); // do not pass tuples\n }\n\n});\n\n/**\n * Aggregate and pivot selected field values to become new fields.\n * This operator is useful to construction cross-tabulations.\n * @constructor\n * @param {Array} [params.groupby] - An array of accessors\n * to groupby. These fields act just like groupby fields of an Aggregate transform.\n * @param {function(object): *} params.field - The field to pivot on. The unique\n * values of this field become new field names in the output stream.\n * @param {function(object): *} params.value - The field to populate pivoted fields.\n * The aggregate values of this field become the values of the new pivoted fields.\n * @param {string} [params.op] - The aggregation operation for the value field,\n * applied per cell in the output stream. The default is \"sum\".\n * @param {number} [params.limit] - An optional parameter indicating the maximum\n * number of pivoted fields to generate. The pivoted field names are sorted in\n * ascending order prior to enforcing the limit.\n */\n\nfunction Pivot(params) {\n Aggregate.call(this, params);\n}\nPivot.Definition = {\n 'type': 'Pivot',\n 'metadata': {\n 'generates': true,\n 'changes': true\n },\n 'params': [{\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'value',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'op',\n 'type': 'enum',\n 'values': ValidAggregateOps,\n 'default': 'sum'\n }, {\n 'name': 'limit',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'key',\n 'type': 'field'\n }]\n};\ninherits(Pivot, Aggregate, {\n _transform: Aggregate.prototype.transform,\n\n transform(_, pulse) {\n return this._transform(aggregateParams(_, pulse), pulse);\n }\n\n}); // Shoehorn a pivot transform into an aggregate transform!\n// First collect all unique pivot field values.\n// Then generate aggregate fields for each output pivot field.\n\nfunction aggregateParams(_, pulse) {\n const key = _.field,\n value = _.value,\n op = (_.op === 'count' ? '__count__' : _.op) || 'sum',\n fields = accessorFields(key).concat(accessorFields(value)),\n keys = pivotKeys(key, _.limit || 0, pulse); // if data stream content changes, pivot fields may change\n // flag parameter modification to ensure re-initialization\n\n if (pulse.changed()) _.set('__pivot__', null, null, true);\n return {\n key: _.key,\n groupby: _.groupby,\n ops: keys.map(() => op),\n fields: keys.map(k => get(k, key, value, fields)),\n as: keys.map(k => k + ''),\n modified: _.modified.bind(_)\n };\n} // Generate aggregate field accessor.\n// Output NaN for non-existent values; aggregator will ignore!\n\n\nfunction get(k, key, value, fields) {\n return accessor(d => key(d) === k ? value(d) : NaN, fields, k + '');\n} // Collect (and optionally limit) all unique pivot values.\n\n\nfunction pivotKeys(key, limit, pulse) {\n const map = {},\n list = [];\n pulse.visit(pulse.SOURCE, t => {\n const k = key(t);\n\n if (!map[k]) {\n map[k] = 1;\n list.push(k);\n }\n });\n list.sort(ascending);\n return limit ? list.slice(0, limit) : list;\n}\n\n/**\n * Partitions pre-faceted data into tuple subflows.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(Dataflow, string): Operator} params.subflow - A function\n * that generates a subflow of operators and returns its root operator.\n * @param {function(object): Array} params.field - The field\n * accessor for an array of subflow tuple objects.\n */\n\nfunction PreFacet(params) {\n Facet.call(this, params);\n}\ninherits(PreFacet, Facet, {\n transform(_, pulse) {\n const flow = _.subflow,\n field = _.field,\n subflow = t => this.subflow(tupleid(t), flow, pulse, t);\n\n if (_.modified('field') || field && pulse.modified(accessorFields(field))) {\n error('PreFacet does not support field modification.');\n }\n\n this.initTargets(); // reset list of active subflows\n\n if (field) {\n pulse.visit(pulse.MOD, t => {\n const sf = subflow(t);\n field(t).forEach(_ => sf.mod(_));\n });\n pulse.visit(pulse.ADD, t => {\n const sf = subflow(t);\n field(t).forEach(_ => sf.add(ingest(_)));\n });\n pulse.visit(pulse.REM, t => {\n const sf = subflow(t);\n field(t).forEach(_ => sf.rem(_));\n });\n } else {\n pulse.visit(pulse.MOD, t => subflow(t).mod(t));\n pulse.visit(pulse.ADD, t => subflow(t).add(t));\n pulse.visit(pulse.REM, t => subflow(t).rem(t));\n }\n\n if (pulse.clean()) {\n pulse.runAfter(() => this.clean());\n }\n\n return pulse;\n }\n\n});\n\n/**\n * Performs a relational projection, copying selected fields from source\n * tuples to a new set of derived tuples.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} [params.as] - Output field names for each projected\n * field. Any unspecified fields will use the field name provided by\n * the field accessor.\n */\n\nfunction Project(params) {\n Transform.call(this, null, params);\n}\nProject.Definition = {\n 'type': 'Project',\n 'metadata': {\n 'generates': true,\n 'changes': true\n },\n 'params': [{\n 'name': 'fields',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'null': true,\n 'array': true\n }]\n};\ninherits(Project, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE),\n fields = _.fields,\n as = fieldNames(_.fields, _.as || []),\n derive = fields ? (s, t) => project(s, t, fields, as) : rederive;\n let lut;\n\n if (this.value) {\n lut = this.value;\n } else {\n pulse = pulse.addAll();\n lut = this.value = {};\n }\n\n pulse.visit(pulse.REM, t => {\n const id = tupleid(t);\n out.rem.push(lut[id]);\n lut[id] = null;\n });\n pulse.visit(pulse.ADD, t => {\n const dt = derive(t, ingest({}));\n lut[tupleid(t)] = dt;\n out.add.push(dt);\n });\n pulse.visit(pulse.MOD, t => {\n out.mod.push(derive(t, lut[tupleid(t)]));\n });\n return out;\n }\n\n});\n\nfunction project(s, t, fields, as) {\n for (let i = 0, n = fields.length; i < n; ++i) {\n t[as[i]] = fields[i](s);\n }\n\n return t;\n}\n\n/**\n * Proxy the value of another operator as a pure signal value.\n * Ensures no tuples are propagated.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {*} params.value - The value to proxy, becomes the value of this operator.\n */\n\nfunction Proxy(params) {\n Transform.call(this, null, params);\n}\ninherits(Proxy, Transform, {\n transform(_, pulse) {\n this.value = _.value;\n return _.modified('value') ? pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS) : pulse.StopPropagation;\n }\n\n});\n\n/**\n * Generates sample quantile values from an input data stream.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - An accessor for the data field\n * over which to calculate quantile values.\n * @param {Array} [params.groupby] - An array of accessors\n * to groupby.\n * @param {Array} [params.probs] - An array of probabilities in\n * the range (0, 1) for which to compute quantile values. If not specified,\n * the *step* parameter will be used.\n * @param {Array} [params.step=0.01] - A probability step size for\n * sampling quantile values. All values from one-half the step size up to\n * 1 (exclusive) will be sampled. This parameter is only used if the\n * *quantiles* parameter is not provided.\n */\n\nfunction Quantile(params) {\n Transform.call(this, null, params);\n}\nQuantile.Definition = {\n 'type': 'Quantile',\n 'metadata': {\n 'generates': true,\n 'changes': true\n },\n 'params': [{\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'probs',\n 'type': 'number',\n 'array': true\n }, {\n 'name': 'step',\n 'type': 'number',\n 'default': 0.01\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'default': ['prob', 'value']\n }]\n};\nconst EPSILON = 1e-14;\ninherits(Quantile, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),\n as = _.as || ['prob', 'value'];\n\n if (this.value && !_.modified() && !pulse.changed()) {\n out.source = this.value;\n return out;\n }\n\n const source = pulse.materialize(pulse.SOURCE).source,\n groups = partition$1(source, _.groupby, _.field),\n names = (_.groupby || []).map(accessorName),\n values = [],\n step = _.step || 0.01,\n p = _.probs || range(step / 2, 1 - EPSILON, step),\n n = p.length;\n groups.forEach(g => {\n const q = quantiles(g, p);\n\n for (let i = 0; i < n; ++i) {\n const t = {};\n\n for (let i = 0; i < names.length; ++i) {\n t[names[i]] = g.dims[i];\n }\n\n t[as[0]] = p[i];\n t[as[1]] = q[i];\n values.push(ingest(t));\n }\n });\n if (this.value) out.rem = this.value;\n this.value = out.add = out.source = values;\n return out;\n }\n\n});\n\n/**\n * Relays a data stream between data processing pipelines.\n * If the derive parameter is set, this transform will create derived\n * copies of observed tuples. This provides derived data streams in which\n * modifications to the tuples do not pollute an upstream data source.\n * @param {object} params - The parameters for this operator.\n * @param {number} [params.derive=false] - Boolean flag indicating if\n * the transform should make derived copies of incoming tuples.\n * @constructor\n */\n\nfunction Relay(params) {\n Transform.call(this, null, params);\n}\ninherits(Relay, Transform, {\n transform(_, pulse) {\n let out, lut;\n\n if (this.value) {\n lut = this.value;\n } else {\n out = pulse = pulse.addAll();\n lut = this.value = {};\n }\n\n if (_.derive) {\n out = pulse.fork(pulse.NO_SOURCE);\n pulse.visit(pulse.REM, t => {\n const id = tupleid(t);\n out.rem.push(lut[id]);\n lut[id] = null;\n });\n pulse.visit(pulse.ADD, t => {\n const dt = derive(t);\n lut[tupleid(t)] = dt;\n out.add.push(dt);\n });\n pulse.visit(pulse.MOD, t => {\n const dt = lut[tupleid(t)];\n\n for (const k in t) {\n dt[k] = t[k]; // down stream writes may overwrite re-derived tuples\n // conservatively mark all source fields as modified\n\n out.modifies(k);\n }\n\n out.mod.push(dt);\n });\n }\n\n return out;\n }\n\n});\n\n/**\n * Samples tuples passing through this operator.\n * Uses reservoir sampling to maintain a representative sample.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {number} [params.size=1000] - The maximum number of samples.\n */\n\nfunction Sample(params) {\n Transform.call(this, [], params);\n this.count = 0;\n}\nSample.Definition = {\n 'type': 'Sample',\n 'metadata': {},\n 'params': [{\n 'name': 'size',\n 'type': 'number',\n 'default': 1000\n }]\n};\ninherits(Sample, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE),\n mod = _.modified('size'),\n num = _.size,\n map = this.value.reduce((m, t) => (m[tupleid(t)] = 1, m), {});\n\n let res = this.value,\n cnt = this.count,\n cap = 0; // sample reservoir update function\n\n function update(t) {\n let p, idx;\n\n if (res.length < num) {\n res.push(t);\n } else {\n idx = ~~((cnt + 1) * random());\n\n if (idx < res.length && idx >= cap) {\n p = res[idx];\n if (map[tupleid(p)]) out.rem.push(p); // eviction\n\n res[idx] = t;\n }\n }\n\n ++cnt;\n }\n\n if (pulse.rem.length) {\n // find all tuples that should be removed, add to output\n pulse.visit(pulse.REM, t => {\n const id = tupleid(t);\n\n if (map[id]) {\n map[id] = -1;\n out.rem.push(t);\n }\n\n --cnt;\n }); // filter removed tuples out of the sample reservoir\n\n res = res.filter(t => map[tupleid(t)] !== -1);\n }\n\n if ((pulse.rem.length || mod) && res.length < num && pulse.source) {\n // replenish sample if backing data source is available\n cap = cnt = res.length;\n pulse.visit(pulse.SOURCE, t => {\n // update, but skip previously sampled tuples\n if (!map[tupleid(t)]) update(t);\n });\n cap = -1;\n }\n\n if (mod && res.length > num) {\n const n = res.length - num;\n\n for (let i = 0; i < n; ++i) {\n map[tupleid(res[i])] = -1;\n out.rem.push(res[i]);\n }\n\n res = res.slice(n);\n }\n\n if (pulse.mod.length) {\n // propagate modified tuples in the sample reservoir\n pulse.visit(pulse.MOD, t => {\n if (map[tupleid(t)]) out.mod.push(t);\n });\n }\n\n if (pulse.add.length) {\n // update sample reservoir\n pulse.visit(pulse.ADD, update);\n }\n\n if (pulse.add.length || cap < 0) {\n // output newly added tuples\n out.add = res.filter(t => !map[tupleid(t)]);\n }\n\n this.count = cnt;\n this.value = out.source = res;\n return out;\n }\n\n});\n\n/**\n * Generates data tuples for a specified sequence range of numbers.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {number} params.start - The first number in the sequence.\n * @param {number} params.stop - The last number (exclusive) in the sequence.\n * @param {number} [params.step=1] - The step size between numbers in the sequence.\n */\n\nfunction Sequence(params) {\n Transform.call(this, null, params);\n}\nSequence.Definition = {\n 'type': 'Sequence',\n 'metadata': {\n 'generates': true,\n 'changes': true\n },\n 'params': [{\n 'name': 'start',\n 'type': 'number',\n 'required': true\n }, {\n 'name': 'stop',\n 'type': 'number',\n 'required': true\n }, {\n 'name': 'step',\n 'type': 'number',\n 'default': 1\n }, {\n 'name': 'as',\n 'type': 'string',\n 'default': 'data'\n }]\n};\ninherits(Sequence, Transform, {\n transform(_, pulse) {\n if (this.value && !_.modified()) return;\n const out = pulse.materialize().fork(pulse.MOD),\n as = _.as || 'data';\n out.rem = this.value ? pulse.rem.concat(this.value) : pulse.rem;\n this.value = range(_.start, _.stop, _.step || 1).map(v => {\n const t = {};\n t[as] = v;\n return ingest(t);\n });\n out.add = pulse.add.concat(this.value);\n return out;\n }\n\n});\n\n/**\n * Propagates a new pulse without any tuples so long as the input\n * pulse contains some added, removed or modified tuples.\n * @param {object} params - The parameters for this operator.\n * @constructor\n */\n\nfunction Sieve(params) {\n Transform.call(this, null, params);\n this.modified(true); // always treat as modified\n}\ninherits(Sieve, Transform, {\n transform(_, pulse) {\n this.value = pulse.source;\n return pulse.changed() ? pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS) : pulse.StopPropagation;\n }\n\n});\n\n/**\n * Discretize dates to specific time units.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The data field containing date/time values.\n */\n\nfunction TimeUnit(params) {\n Transform.call(this, null, params);\n}\nconst OUTPUT = ['unit0', 'unit1'];\nTimeUnit.Definition = {\n 'type': 'TimeUnit',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'interval',\n 'type': 'boolean',\n 'default': true\n }, {\n 'name': 'units',\n 'type': 'enum',\n 'values': TIME_UNITS,\n 'array': true\n }, {\n 'name': 'step',\n 'type': 'number',\n 'default': 1\n }, {\n 'name': 'maxbins',\n 'type': 'number',\n 'default': 40\n }, {\n 'name': 'extent',\n 'type': 'date',\n 'array': true\n }, {\n 'name': 'timezone',\n 'type': 'enum',\n 'default': 'local',\n 'values': ['local', 'utc']\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': 2,\n 'default': OUTPUT\n }]\n};\ninherits(TimeUnit, Transform, {\n transform(_, pulse) {\n const field = _.field,\n band = _.interval !== false,\n utc = _.timezone === 'utc',\n floor = this._floor(_, pulse),\n offset = (utc ? utcInterval : timeInterval)(floor.unit).offset,\n as = _.as || OUTPUT,\n u0 = as[0],\n u1 = as[1],\n step = floor.step;\n\n let min = floor.start || Infinity,\n max = floor.stop || -Infinity,\n flag = pulse.ADD;\n\n if (_.modified() || pulse.modified(accessorFields(field))) {\n pulse = pulse.reflow(true);\n flag = pulse.SOURCE;\n min = Infinity;\n max = -Infinity;\n }\n\n pulse.visit(flag, t => {\n const v = field(t);\n let a, b;\n\n if (v == null) {\n t[u0] = null;\n if (band) t[u1] = null;\n } else {\n t[u0] = a = b = floor(v);\n if (band) t[u1] = b = offset(a, step);\n if (a < min) min = a;\n if (b > max) max = b;\n }\n });\n floor.start = min;\n floor.stop = max;\n return pulse.modifies(band ? as : u0);\n },\n\n _floor(_, pulse) {\n const utc = _.timezone === 'utc'; // get parameters\n\n const {\n units,\n step\n } = _.units ? {\n units: _.units,\n step: _.step || 1\n } : timeBin({\n extent: _.extent || extent(pulse.materialize(pulse.SOURCE).source, _.field),\n maxbins: _.maxbins\n }); // check / standardize time units\n\n const tunits = timeUnits(units),\n prev = this.value || {},\n floor = (utc ? utcFloor : timeFloor)(tunits, step);\n floor.unit = peek(tunits);\n floor.units = tunits;\n floor.step = step;\n floor.start = prev.start;\n floor.stop = prev.stop;\n return this.value = floor;\n }\n\n});\n\n/**\n * An index that maps from unique, string-coerced, field values to tuples.\n * Assumes that the field serves as a unique key with no duplicate values.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The field accessor to index.\n */\n\nfunction TupleIndex(params) {\n Transform.call(this, fastmap(), params);\n}\ninherits(TupleIndex, Transform, {\n transform(_, pulse) {\n const df = pulse.dataflow,\n field = _.field,\n index = this.value,\n set = t => index.set(field(t), t);\n\n let mod = true;\n\n if (_.modified('field') || pulse.modified(field.fields)) {\n index.clear();\n pulse.visit(pulse.SOURCE, set);\n } else if (pulse.changed()) {\n pulse.visit(pulse.REM, t => index.delete(field(t)));\n pulse.visit(pulse.ADD, set);\n } else {\n mod = false;\n }\n\n this.modified(mod);\n if (index.empty > df.cleanThreshold) df.runAfter(index.clean);\n return pulse.fork();\n }\n\n});\n\n/**\n * Extracts an array of values. Assumes the source data has already been\n * reduced as needed (e.g., by an upstream Aggregate transform).\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The domain field to extract.\n * @param {function(*,*): number} [params.sort] - An optional\n * comparator function for sorting the values. The comparator will be\n * applied to backing tuples prior to value extraction.\n */\n\nfunction Values(params) {\n Transform.call(this, null, params);\n}\ninherits(Values, Transform, {\n transform(_, pulse) {\n const run = !this.value || _.modified('field') || _.modified('sort') || pulse.changed() || _.sort && pulse.modified(_.sort.fields);\n\n if (run) {\n this.value = (_.sort ? pulse.source.slice().sort(stableCompare(_.sort)) : pulse.source).map(_.field);\n }\n }\n\n});\n\nfunction WindowOp(op, field, param, as) {\n const fn = WindowOps[op](field, param);\n return {\n init: fn.init || zero,\n update: function (w, t) {\n t[as] = fn.next(w);\n }\n };\n}\nconst WindowOps = {\n row_number: function () {\n return {\n next: w => w.index + 1\n };\n },\n rank: function () {\n let rank;\n return {\n init: () => rank = 1,\n next: w => {\n const i = w.index,\n data = w.data;\n return i && w.compare(data[i - 1], data[i]) ? rank = i + 1 : rank;\n }\n };\n },\n dense_rank: function () {\n let drank;\n return {\n init: () => drank = 1,\n next: w => {\n const i = w.index,\n d = w.data;\n return i && w.compare(d[i - 1], d[i]) ? ++drank : drank;\n }\n };\n },\n percent_rank: function () {\n const rank = WindowOps.rank(),\n next = rank.next;\n return {\n init: rank.init,\n next: w => (next(w) - 1) / (w.data.length - 1)\n };\n },\n cume_dist: function () {\n let cume;\n return {\n init: () => cume = 0,\n next: w => {\n const d = w.data,\n c = w.compare;\n let i = w.index;\n\n if (cume < i) {\n while (i + 1 < d.length && !c(d[i], d[i + 1])) ++i;\n\n cume = i;\n }\n\n return (1 + cume) / d.length;\n }\n };\n },\n ntile: function (field, num) {\n num = +num;\n if (!(num > 0)) error('ntile num must be greater than zero.');\n const cume = WindowOps.cume_dist(),\n next = cume.next;\n return {\n init: cume.init,\n next: w => Math.ceil(num * next(w))\n };\n },\n lag: function (field, offset) {\n offset = +offset || 1;\n return {\n next: w => {\n const i = w.index - offset;\n return i >= 0 ? field(w.data[i]) : null;\n }\n };\n },\n lead: function (field, offset) {\n offset = +offset || 1;\n return {\n next: w => {\n const i = w.index + offset,\n d = w.data;\n return i < d.length ? field(d[i]) : null;\n }\n };\n },\n first_value: function (field) {\n return {\n next: w => field(w.data[w.i0])\n };\n },\n last_value: function (field) {\n return {\n next: w => field(w.data[w.i1 - 1])\n };\n },\n nth_value: function (field, nth) {\n nth = +nth;\n if (!(nth > 0)) error('nth_value nth must be greater than zero.');\n return {\n next: w => {\n const i = w.i0 + (nth - 1);\n return i < w.i1 ? field(w.data[i]) : null;\n }\n };\n },\n prev_value: function (field) {\n let prev;\n return {\n init: () => prev = null,\n next: w => {\n const v = field(w.data[w.index]);\n return v != null ? prev = v : prev;\n }\n };\n },\n next_value: function (field) {\n let v, i;\n return {\n init: () => (v = null, i = -1),\n next: w => {\n const d = w.data;\n return w.index <= i ? v : (i = find(field, d, w.index)) < 0 ? (i = d.length, v = null) : v = field(d[i]);\n }\n };\n }\n};\n\nfunction find(field, data, index) {\n for (let n = data.length; index < n; ++index) {\n const v = field(data[index]);\n if (v != null) return index;\n }\n\n return -1;\n}\n\nconst ValidWindowOps = Object.keys(WindowOps);\n\nfunction WindowState(_) {\n const ops = array(_.ops),\n fields = array(_.fields),\n params = array(_.params),\n as = array(_.as),\n outputs = this.outputs = [],\n windows = this.windows = [],\n inputs = {},\n map = {},\n counts = [],\n measures = [];\n let countOnly = true;\n\n function visitInputs(f) {\n array(accessorFields(f)).forEach(_ => inputs[_] = 1);\n }\n\n visitInputs(_.sort);\n ops.forEach((op, i) => {\n const field = fields[i],\n mname = accessorName(field),\n name = measureName(op, mname, as[i]);\n visitInputs(field);\n outputs.push(name); // Window operation\n\n if (hasOwnProperty(WindowOps, op)) {\n windows.push(WindowOp(op, fields[i], params[i], name));\n } // Aggregate operation\n else {\n if (field == null && op !== 'count') {\n error('Null aggregate field specified.');\n }\n\n if (op === 'count') {\n counts.push(name);\n return;\n }\n\n countOnly = false;\n let m = map[mname];\n\n if (!m) {\n m = map[mname] = [];\n m.field = field;\n measures.push(m);\n }\n\n m.push(createMeasure(op, name));\n }\n });\n\n if (counts.length || measures.length) {\n this.cell = cell(measures, counts, countOnly);\n }\n\n this.inputs = Object.keys(inputs);\n}\nconst prototype = WindowState.prototype;\n\nprototype.init = function () {\n this.windows.forEach(_ => _.init());\n if (this.cell) this.cell.init();\n};\n\nprototype.update = function (w, t) {\n const cell = this.cell,\n wind = this.windows,\n data = w.data,\n m = wind && wind.length;\n let j;\n\n if (cell) {\n for (j = w.p0; j < w.i0; ++j) cell.rem(data[j]);\n\n for (j = w.p1; j < w.i1; ++j) cell.add(data[j]);\n\n cell.set(t);\n }\n\n for (j = 0; j < m; ++j) wind[j].update(w, t);\n};\n\nfunction cell(measures, counts, countOnly) {\n measures = measures.map(m => compileMeasures(m, m.field));\n const cell = {\n num: 0,\n agg: null,\n store: false,\n count: counts\n };\n\n if (!countOnly) {\n var n = measures.length,\n a = cell.agg = Array(n),\n i = 0;\n\n for (; i < n; ++i) a[i] = new measures[i](cell);\n }\n\n if (cell.store) {\n var store = cell.data = new TupleStore();\n }\n\n cell.add = function (t) {\n cell.num += 1;\n if (countOnly) return;\n if (store) store.add(t);\n\n for (let i = 0; i < n; ++i) {\n a[i].add(a[i].get(t), t);\n }\n };\n\n cell.rem = function (t) {\n cell.num -= 1;\n if (countOnly) return;\n if (store) store.rem(t);\n\n for (let i = 0; i < n; ++i) {\n a[i].rem(a[i].get(t), t);\n }\n };\n\n cell.set = function (t) {\n let i, n; // consolidate stored values\n\n if (store) store.values(); // update tuple properties\n\n for (i = 0, n = counts.length; i < n; ++i) t[counts[i]] = cell.num;\n\n if (!countOnly) for (i = 0, n = a.length; i < n; ++i) a[i].set(t);\n };\n\n cell.init = function () {\n cell.num = 0;\n if (store) store.reset();\n\n for (let i = 0; i < n; ++i) a[i].init();\n };\n\n return cell;\n}\n\n/**\n * Perform window calculations and write results to the input stream.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(*,*): number} [params.sort] - A comparator function for sorting tuples within a window.\n * @param {Array} [params.groupby] - An array of accessors by which to partition tuples into separate windows.\n * @param {Array} params.ops - An array of strings indicating window operations to perform.\n * @param {Array} [params.fields] - An array of accessors\n * for data fields to use as inputs to window operations.\n * @param {Array<*>} [params.params] - An array of parameter values for window operations.\n * @param {Array} [params.as] - An array of output field names for window operations.\n * @param {Array} [params.frame] - Window frame definition as two-element array.\n * @param {boolean} [params.ignorePeers=false] - If true, base window frame boundaries on row\n * number alone, ignoring peers with identical sort values. If false (default),\n * the window boundaries will be adjusted to include peer values.\n */\n\nfunction Window(params) {\n Transform.call(this, {}, params);\n this._mlen = 0;\n this._mods = [];\n}\nWindow.Definition = {\n 'type': 'Window',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'sort',\n 'type': 'compare'\n }, {\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'ops',\n 'type': 'enum',\n 'array': true,\n 'values': ValidWindowOps.concat(ValidAggregateOps)\n }, {\n 'name': 'params',\n 'type': 'number',\n 'null': true,\n 'array': true\n }, {\n 'name': 'fields',\n 'type': 'field',\n 'null': true,\n 'array': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'null': true,\n 'array': true\n }, {\n 'name': 'frame',\n 'type': 'number',\n 'null': true,\n 'array': true,\n 'length': 2,\n 'default': [null, 0]\n }, {\n 'name': 'ignorePeers',\n 'type': 'boolean',\n 'default': false\n }]\n};\ninherits(Window, Transform, {\n transform(_, pulse) {\n this.stamp = pulse.stamp;\n\n const mod = _.modified(),\n cmp = stableCompare(_.sort),\n key = groupkey(_.groupby),\n group = t => this.group(key(t)); // initialize window state\n\n\n let state = this.state;\n\n if (!state || mod) {\n state = this.state = new WindowState(_);\n } // partition input tuples\n\n\n if (mod || pulse.modified(state.inputs)) {\n this.value = {};\n pulse.visit(pulse.SOURCE, t => group(t).add(t));\n } else {\n pulse.visit(pulse.REM, t => group(t).remove(t));\n pulse.visit(pulse.ADD, t => group(t).add(t));\n } // perform window calculations for each modified partition\n\n\n for (let i = 0, n = this._mlen; i < n; ++i) {\n processPartition(this._mods[i], state, cmp, _);\n }\n\n this._mlen = 0;\n this._mods = []; // TODO don't reflow everything?\n\n return pulse.reflow(mod).modifies(state.outputs);\n },\n\n group(key) {\n let group = this.value[key];\n\n if (!group) {\n group = this.value[key] = SortedList(tupleid);\n group.stamp = -1;\n }\n\n if (group.stamp < this.stamp) {\n group.stamp = this.stamp;\n this._mods[this._mlen++] = group;\n }\n\n return group;\n }\n\n});\n\nfunction processPartition(list, state, cmp, _) {\n const sort = _.sort,\n range = sort && !_.ignorePeers,\n frame = _.frame || [null, 0],\n data = list.data(cmp),\n // use cmp for stable sort\n n = data.length,\n b = range ? bisector(sort) : null,\n w = {\n i0: 0,\n i1: 0,\n p0: 0,\n p1: 0,\n index: 0,\n data: data,\n compare: sort || constant(-1)\n };\n state.init();\n\n for (let i = 0; i < n; ++i) {\n setWindow(w, frame, i, n);\n if (range) adjustRange(w, b);\n state.update(w, data[i]);\n }\n}\n\nfunction setWindow(w, f, i, n) {\n w.p0 = w.i0;\n w.p1 = w.i1;\n w.i0 = f[0] == null ? 0 : Math.max(0, i - Math.abs(f[0]));\n w.i1 = f[1] == null ? n : Math.min(n, i + Math.abs(f[1]) + 1);\n w.index = i;\n} // if frame type is 'range', adjust window for peer values\n\n\nfunction adjustRange(w, bisect) {\n const r0 = w.i0,\n r1 = w.i1 - 1,\n c = w.compare,\n d = w.data,\n n = d.length - 1;\n if (r0 > 0 && !c(d[r0], d[r0 - 1])) w.i0 = bisect.left(d, d[r0]);\n if (r1 < n && !c(d[r1], d[r1 + 1])) w.i1 = bisect.right(d, d[r1]);\n}\n\nexport { Aggregate as aggregate, Bin as bin, Collect as collect, Compare as compare, CountPattern as countpattern, Cross as cross, Density as density, DotBin as dotbin, Expression as expression, Extent as extent, Facet as facet, Field as field, Filter as filter, Flatten as flatten, Fold as fold, Formula as formula, Generate as generate, Impute as impute, JoinAggregate as joinaggregate, KDE as kde, Key as key, Load as load, Lookup as lookup, MultiExtent as multiextent, MultiValues as multivalues, Params as params, Pivot as pivot, PreFacet as prefacet, Project as project, Proxy as proxy, Quantile as quantile, Relay as relay, Sample as sample, Sequence as sequence, Sieve as sieve, Subflow as subflow, TimeUnit as timeunit, TupleIndex as tupleindex, Values as values, Window as window };\n","import quantile from \"./quantile.js\";\n\nexport default function(values, valueof) {\n return quantile(values, 0.5, valueof);\n}\n","export default function mean(values, valueof) {\n let count = 0;\n let sum = 0;\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n ++count, sum += value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n ++count, sum += value;\n }\n }\n }\n if (count) return sum / count;\n}\n","export function point(that, x, y) {\n that._context.bezierCurveTo(\n (2 * that._x0 + that._x1) / 3,\n (2 * that._y0 + that._y1) / 3,\n (that._x0 + 2 * that._x1) / 3,\n (that._y0 + 2 * that._y1) / 3,\n (that._x0 + 4 * that._x1 + x) / 6,\n (that._y0 + 4 * that._y1 + y) / 6\n );\n}\n\nexport function Basis(context) {\n this._context = context;\n}\n\nBasis.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 =\n this._y0 = this._y1 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 3: point(this, this._x1, this._y1); // proceed\n case 2: this._context.lineTo(this._x1, this._y1); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6); // proceed\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n }\n};\n\nexport default function(context) {\n return new Basis(context);\n}\n","export default function() {}\n","import noop from \"../noop.js\";\nimport {point} from \"./basis.js\";\n\nfunction BasisClosed(context) {\n this._context = context;\n}\n\nBasisClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._x0 = this._x1 = this._x2 = this._x3 = this._x4 =\n this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 1: {\n this._context.moveTo(this._x2, this._y2);\n this._context.closePath();\n break;\n }\n case 2: {\n this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);\n this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);\n this._context.closePath();\n break;\n }\n case 3: {\n this.point(this._x2, this._y2);\n this.point(this._x3, this._y3);\n this.point(this._x4, this._y4);\n break;\n }\n }\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._x2 = x, this._y2 = y; break;\n case 1: this._point = 2; this._x3 = x, this._y3 = y; break;\n case 2: this._point = 3; this._x4 = x, this._y4 = y; this._context.moveTo((this._x0 + 4 * this._x1 + x) / 6, (this._y0 + 4 * this._y1 + y) / 6); break;\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n }\n};\n\nexport default function(context) {\n return new BasisClosed(context);\n}\n","import {point} from \"./basis.js\";\n\nfunction BasisOpen(context) {\n this._context = context;\n}\n\nBasisOpen.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 =\n this._y0 = this._y1 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; var x0 = (this._x0 + 4 * this._x1 + x) / 6, y0 = (this._y0 + 4 * this._y1 + y) / 6; this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0); break;\n case 3: this._point = 4; // proceed\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n }\n};\n\nexport default function(context) {\n return new BasisOpen(context);\n}\n","import {Basis} from \"./basis.js\";\n\nfunction Bundle(context, beta) {\n this._basis = new Basis(context);\n this._beta = beta;\n}\n\nBundle.prototype = {\n lineStart: function() {\n this._x = [];\n this._y = [];\n this._basis.lineStart();\n },\n lineEnd: function() {\n var x = this._x,\n y = this._y,\n j = x.length - 1;\n\n if (j > 0) {\n var x0 = x[0],\n y0 = y[0],\n dx = x[j] - x0,\n dy = y[j] - y0,\n i = -1,\n t;\n\n while (++i <= j) {\n t = i / j;\n this._basis.point(\n this._beta * x[i] + (1 - this._beta) * (x0 + t * dx),\n this._beta * y[i] + (1 - this._beta) * (y0 + t * dy)\n );\n }\n }\n\n this._x = this._y = null;\n this._basis.lineEnd();\n },\n point: function(x, y) {\n this._x.push(+x);\n this._y.push(+y);\n }\n};\n\nexport default (function custom(beta) {\n\n function bundle(context) {\n return beta === 1 ? new Basis(context) : new Bundle(context, beta);\n }\n\n bundle.beta = function(beta) {\n return custom(+beta);\n };\n\n return bundle;\n})(0.85);\n","export function point(that, x, y) {\n that._context.bezierCurveTo(\n that._x1 + that._k * (that._x2 - that._x0),\n that._y1 + that._k * (that._y2 - that._y0),\n that._x2 + that._k * (that._x1 - x),\n that._y2 + that._k * (that._y1 - y),\n that._x2,\n that._y2\n );\n}\n\nexport function Cardinal(context, tension) {\n this._context = context;\n this._k = (1 - tension) / 6;\n}\n\nCardinal.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 = this._x2 =\n this._y0 = this._y1 = this._y2 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 2: this._context.lineTo(this._x2, this._y2); break;\n case 3: point(this, this._x1, this._y1); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; this._x1 = x, this._y1 = y; break;\n case 2: this._point = 3; // proceed\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(tension) {\n\n function cardinal(context) {\n return new Cardinal(context, tension);\n }\n\n cardinal.tension = function(tension) {\n return custom(+tension);\n };\n\n return cardinal;\n})(0);\n","import {point} from \"./cardinal.js\";\n\nexport function CardinalOpen(context, tension) {\n this._context = context;\n this._k = (1 - tension) / 6;\n}\n\nCardinalOpen.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 = this._x2 =\n this._y0 = this._y1 = this._y2 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;\n case 3: this._point = 4; // proceed\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(tension) {\n\n function cardinal(context) {\n return new CardinalOpen(context, tension);\n }\n\n cardinal.tension = function(tension) {\n return custom(+tension);\n };\n\n return cardinal;\n})(0);\n","import noop from \"../noop.js\";\nimport {point} from \"./cardinal.js\";\n\nexport function CardinalClosed(context, tension) {\n this._context = context;\n this._k = (1 - tension) / 6;\n}\n\nCardinalClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =\n this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 1: {\n this._context.moveTo(this._x3, this._y3);\n this._context.closePath();\n break;\n }\n case 2: {\n this._context.lineTo(this._x3, this._y3);\n this._context.closePath();\n break;\n }\n case 3: {\n this.point(this._x3, this._y3);\n this.point(this._x4, this._y4);\n this.point(this._x5, this._y5);\n break;\n }\n }\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._x3 = x, this._y3 = y; break;\n case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;\n case 2: this._point = 3; this._x5 = x, this._y5 = y; break;\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(tension) {\n\n function cardinal(context) {\n return new CardinalClosed(context, tension);\n }\n\n cardinal.tension = function(tension) {\n return custom(+tension);\n };\n\n return cardinal;\n})(0);\n","export var abs = Math.abs;\nexport var atan2 = Math.atan2;\nexport var cos = Math.cos;\nexport var max = Math.max;\nexport var min = Math.min;\nexport var sin = Math.sin;\nexport var sqrt = Math.sqrt;\n\nexport var epsilon = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var tau = 2 * pi;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x);\n}\n","import {epsilon} from \"../math.js\";\nimport {Cardinal} from \"./cardinal.js\";\n\nexport function point(that, x, y) {\n var x1 = that._x1,\n y1 = that._y1,\n x2 = that._x2,\n y2 = that._y2;\n\n if (that._l01_a > epsilon) {\n var a = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a,\n n = 3 * that._l01_a * (that._l01_a + that._l12_a);\n x1 = (x1 * a - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n;\n y1 = (y1 * a - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;\n }\n\n if (that._l23_a > epsilon) {\n var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a,\n m = 3 * that._l23_a * (that._l23_a + that._l12_a);\n x2 = (x2 * b + that._x1 * that._l23_2a - x * that._l12_2a) / m;\n y2 = (y2 * b + that._y1 * that._l23_2a - y * that._l12_2a) / m;\n }\n\n that._context.bezierCurveTo(x1, y1, x2, y2, that._x2, that._y2);\n}\n\nfunction CatmullRom(context, alpha) {\n this._context = context;\n this._alpha = alpha;\n}\n\nCatmullRom.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 = this._x2 =\n this._y0 = this._y1 = this._y2 = NaN;\n this._l01_a = this._l12_a = this._l23_a =\n this._l01_2a = this._l12_2a = this._l23_2a =\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 2: this._context.lineTo(this._x2, this._y2); break;\n case 3: this.point(this._x2, this._y2); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n\n if (this._point) {\n var x23 = this._x2 - x,\n y23 = this._y2 - y;\n this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));\n }\n\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; // proceed\n default: point(this, x, y); break;\n }\n\n this._l01_a = this._l12_a, this._l12_a = this._l23_a;\n this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(alpha) {\n\n function catmullRom(context) {\n return alpha ? new CatmullRom(context, alpha) : new Cardinal(context, 0);\n }\n\n catmullRom.alpha = function(alpha) {\n return custom(+alpha);\n };\n\n return catmullRom;\n})(0.5);\n","import {CardinalClosed} from \"./cardinalClosed.js\";\nimport noop from \"../noop.js\";\nimport {point} from \"./catmullRom.js\";\n\nfunction CatmullRomClosed(context, alpha) {\n this._context = context;\n this._alpha = alpha;\n}\n\nCatmullRomClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =\n this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;\n this._l01_a = this._l12_a = this._l23_a =\n this._l01_2a = this._l12_2a = this._l23_2a =\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 1: {\n this._context.moveTo(this._x3, this._y3);\n this._context.closePath();\n break;\n }\n case 2: {\n this._context.lineTo(this._x3, this._y3);\n this._context.closePath();\n break;\n }\n case 3: {\n this.point(this._x3, this._y3);\n this.point(this._x4, this._y4);\n this.point(this._x5, this._y5);\n break;\n }\n }\n },\n point: function(x, y) {\n x = +x, y = +y;\n\n if (this._point) {\n var x23 = this._x2 - x,\n y23 = this._y2 - y;\n this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));\n }\n\n switch (this._point) {\n case 0: this._point = 1; this._x3 = x, this._y3 = y; break;\n case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;\n case 2: this._point = 3; this._x5 = x, this._y5 = y; break;\n default: point(this, x, y); break;\n }\n\n this._l01_a = this._l12_a, this._l12_a = this._l23_a;\n this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(alpha) {\n\n function catmullRom(context) {\n return alpha ? new CatmullRomClosed(context, alpha) : new CardinalClosed(context, 0);\n }\n\n catmullRom.alpha = function(alpha) {\n return custom(+alpha);\n };\n\n return catmullRom;\n})(0.5);\n","import {CardinalOpen} from \"./cardinalOpen.js\";\nimport {point} from \"./catmullRom.js\";\n\nfunction CatmullRomOpen(context, alpha) {\n this._context = context;\n this._alpha = alpha;\n}\n\nCatmullRomOpen.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 = this._x2 =\n this._y0 = this._y1 = this._y2 = NaN;\n this._l01_a = this._l12_a = this._l23_a =\n this._l01_2a = this._l12_2a = this._l23_2a =\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n\n if (this._point) {\n var x23 = this._x2 - x,\n y23 = this._y2 - y;\n this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));\n }\n\n switch (this._point) {\n case 0: this._point = 1; break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;\n case 3: this._point = 4; // proceed\n default: point(this, x, y); break;\n }\n\n this._l01_a = this._l12_a, this._l12_a = this._l23_a;\n this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(alpha) {\n\n function catmullRom(context) {\n return alpha ? new CatmullRomOpen(context, alpha) : new CardinalOpen(context, 0);\n }\n\n catmullRom.alpha = function(alpha) {\n return custom(+alpha);\n };\n\n return catmullRom;\n})(0.5);\n","function Linear(context) {\n this._context = context;\n}\n\nLinear.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; // proceed\n default: this._context.lineTo(x, y); break;\n }\n }\n};\n\nexport default function(context) {\n return new Linear(context);\n}\n","import noop from \"../noop.js\";\n\nfunction LinearClosed(context) {\n this._context = context;\n}\n\nLinearClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._point) this._context.closePath();\n },\n point: function(x, y) {\n x = +x, y = +y;\n if (this._point) this._context.lineTo(x, y);\n else this._point = 1, this._context.moveTo(x, y);\n }\n};\n\nexport default function(context) {\n return new LinearClosed(context);\n}\n","function sign(x) {\n return x < 0 ? -1 : 1;\n}\n\n// Calculate the slopes of the tangents (Hermite-type interpolation) based on\n// the following paper: Steffen, M. 1990. A Simple Method for Monotonic\n// Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.\n// NOV(II), P. 443, 1990.\nfunction slope3(that, x2, y2) {\n var h0 = that._x1 - that._x0,\n h1 = x2 - that._x1,\n s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0),\n s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0),\n p = (s0 * h1 + s1 * h0) / (h0 + h1);\n return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;\n}\n\n// Calculate a one-sided slope.\nfunction slope2(that, t) {\n var h = that._x1 - that._x0;\n return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;\n}\n\n// According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations\n// \"you can express cubic Hermite interpolation in terms of cubic Bézier curves\n// with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1\".\nfunction point(that, t0, t1) {\n var x0 = that._x0,\n y0 = that._y0,\n x1 = that._x1,\n y1 = that._y1,\n dx = (x1 - x0) / 3;\n that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);\n}\n\nfunction MonotoneX(context) {\n this._context = context;\n}\n\nMonotoneX.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 =\n this._y0 = this._y1 =\n this._t0 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 2: this._context.lineTo(this._x1, this._y1); break;\n case 3: point(this, this._t0, slope2(this, this._t0)); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n var t1 = NaN;\n\n x = +x, y = +y;\n if (x === this._x1 && y === this._y1) return; // Ignore coincident points.\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; point(this, slope2(this, t1 = slope3(this, x, y)), t1); break;\n default: point(this, this._t0, t1 = slope3(this, x, y)); break;\n }\n\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n this._t0 = t1;\n }\n}\n\nfunction MonotoneY(context) {\n this._context = new ReflectContext(context);\n}\n\n(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) {\n MonotoneX.prototype.point.call(this, y, x);\n};\n\nfunction ReflectContext(context) {\n this._context = context;\n}\n\nReflectContext.prototype = {\n moveTo: function(x, y) { this._context.moveTo(y, x); },\n closePath: function() { this._context.closePath(); },\n lineTo: function(x, y) { this._context.lineTo(y, x); },\n bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); }\n};\n\nexport function monotoneX(context) {\n return new MonotoneX(context);\n}\n\nexport function monotoneY(context) {\n return new MonotoneY(context);\n}\n","function Natural(context) {\n this._context = context;\n}\n\nNatural.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x = [];\n this._y = [];\n },\n lineEnd: function() {\n var x = this._x,\n y = this._y,\n n = x.length;\n\n if (n) {\n this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]);\n if (n === 2) {\n this._context.lineTo(x[1], y[1]);\n } else {\n var px = controlPoints(x),\n py = controlPoints(y);\n for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {\n this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);\n }\n }\n }\n\n if (this._line || (this._line !== 0 && n === 1)) this._context.closePath();\n this._line = 1 - this._line;\n this._x = this._y = null;\n },\n point: function(x, y) {\n this._x.push(+x);\n this._y.push(+y);\n }\n};\n\n// See https://www.particleincell.com/2012/bezier-splines/ for derivation.\nfunction controlPoints(x) {\n var i,\n n = x.length - 1,\n m,\n a = new Array(n),\n b = new Array(n),\n r = new Array(n);\n a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1];\n for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];\n a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n];\n for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];\n a[n - 1] = r[n - 1] / b[n - 1];\n for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];\n b[n - 1] = (x[n] + a[n - 1]) / 2;\n for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];\n return [a, b];\n}\n\nexport default function(context) {\n return new Natural(context);\n}\n","function Step(context, t) {\n this._context = context;\n this._t = t;\n}\n\nStep.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x = this._y = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; // proceed\n default: {\n if (this._t <= 0) {\n this._context.lineTo(this._x, y);\n this._context.lineTo(x, y);\n } else {\n var x1 = this._x * (1 - this._t) + x * this._t;\n this._context.lineTo(x1, this._y);\n this._context.lineTo(x1, y);\n }\n break;\n }\n }\n this._x = x, this._y = y;\n }\n};\n\nexport default function(context) {\n return new Step(context, 0.5);\n}\n\nexport function stepBefore(context) {\n return new Step(context, 0);\n}\n\nexport function stepAfter(context) {\n return new Step(context, 1);\n}\n","const pi = Math.PI,\n tau = 2 * pi,\n epsilon = 1e-6,\n tauEpsilon = tau - epsilon;\n\nfunction Path() {\n this._x0 = this._y0 = // start of current subpath\n this._x1 = this._y1 = null; // end of current subpath\n this._ = \"\";\n}\n\nfunction path() {\n return new Path;\n}\n\nPath.prototype = path.prototype = {\n constructor: Path,\n moveTo: function(x, y) {\n this._ += \"M\" + (this._x0 = this._x1 = +x) + \",\" + (this._y0 = this._y1 = +y);\n },\n closePath: function() {\n if (this._x1 !== null) {\n this._x1 = this._x0, this._y1 = this._y0;\n this._ += \"Z\";\n }\n },\n lineTo: function(x, y) {\n this._ += \"L\" + (this._x1 = +x) + \",\" + (this._y1 = +y);\n },\n quadraticCurveTo: function(x1, y1, x, y) {\n this._ += \"Q\" + (+x1) + \",\" + (+y1) + \",\" + (this._x1 = +x) + \",\" + (this._y1 = +y);\n },\n bezierCurveTo: function(x1, y1, x2, y2, x, y) {\n this._ += \"C\" + (+x1) + \",\" + (+y1) + \",\" + (+x2) + \",\" + (+y2) + \",\" + (this._x1 = +x) + \",\" + (this._y1 = +y);\n },\n arcTo: function(x1, y1, x2, y2, r) {\n x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;\n var x0 = this._x1,\n y0 = this._y1,\n x21 = x2 - x1,\n y21 = y2 - y1,\n x01 = x0 - x1,\n y01 = y0 - y1,\n l01_2 = x01 * x01 + y01 * y01;\n\n // Is the radius negative? Error.\n if (r < 0) throw new Error(\"negative radius: \" + r);\n\n // Is this path empty? Move to (x1,y1).\n if (this._x1 === null) {\n this._ += \"M\" + (this._x1 = x1) + \",\" + (this._y1 = y1);\n }\n\n // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.\n else if (!(l01_2 > epsilon));\n\n // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?\n // Equivalently, is (x1,y1) coincident with (x2,y2)?\n // Or, is the radius zero? Line to (x1,y1).\n else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) {\n this._ += \"L\" + (this._x1 = x1) + \",\" + (this._y1 = y1);\n }\n\n // Otherwise, draw an arc!\n else {\n var x20 = x2 - x0,\n y20 = y2 - y0,\n l21_2 = x21 * x21 + y21 * y21,\n l20_2 = x20 * x20 + y20 * y20,\n l21 = Math.sqrt(l21_2),\n l01 = Math.sqrt(l01_2),\n l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),\n t01 = l / l01,\n t21 = l / l21;\n\n // If the start tangent is not coincident with (x0,y0), line to.\n if (Math.abs(t01 - 1) > epsilon) {\n this._ += \"L\" + (x1 + t01 * x01) + \",\" + (y1 + t01 * y01);\n }\n\n this._ += \"A\" + r + \",\" + r + \",0,0,\" + (+(y01 * x20 > x01 * y20)) + \",\" + (this._x1 = x1 + t21 * x21) + \",\" + (this._y1 = y1 + t21 * y21);\n }\n },\n arc: function(x, y, r, a0, a1, ccw) {\n x = +x, y = +y, r = +r, ccw = !!ccw;\n var dx = r * Math.cos(a0),\n dy = r * Math.sin(a0),\n x0 = x + dx,\n y0 = y + dy,\n cw = 1 ^ ccw,\n da = ccw ? a0 - a1 : a1 - a0;\n\n // Is the radius negative? Error.\n if (r < 0) throw new Error(\"negative radius: \" + r);\n\n // Is this path empty? Move to (x0,y0).\n if (this._x1 === null) {\n this._ += \"M\" + x0 + \",\" + y0;\n }\n\n // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).\n else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {\n this._ += \"L\" + x0 + \",\" + y0;\n }\n\n // Is this arc empty? We’re done.\n if (!r) return;\n\n // Does the angle go the wrong way? Flip the direction.\n if (da < 0) da = da % tau + tau;\n\n // Is this a complete circle? Draw two arcs to complete the circle.\n if (da > tauEpsilon) {\n this._ += \"A\" + r + \",\" + r + \",0,1,\" + cw + \",\" + (x - dx) + \",\" + (y - dy) + \"A\" + r + \",\" + r + \",0,1,\" + cw + \",\" + (this._x1 = x0) + \",\" + (this._y1 = y0);\n }\n\n // Is this arc non-empty? Draw an arc!\n else if (da > epsilon) {\n this._ += \"A\" + r + \",\" + r + \",0,\" + (+(da >= pi)) + \",\" + cw + \",\" + (this._x1 = x + r * Math.cos(a1)) + \",\" + (this._y1 = y + r * Math.sin(a1));\n }\n },\n rect: function(x, y, w, h) {\n this._ += \"M\" + (this._x0 = this._x1 = +x) + \",\" + (this._y0 = this._y1 = +y) + \"h\" + (+w) + \"v\" + (+h) + \"h\" + (-w) + \"Z\";\n },\n toString: function() {\n return this._;\n }\n};\n\nexport default path;\n","export default function(x) {\n return function constant() {\n return x;\n };\n}\n","import {path} from \"d3-path\";\nimport constant from \"./constant.js\";\nimport {abs, acos, asin, atan2, cos, epsilon, halfPi, max, min, pi, sin, sqrt, tau} from \"./math.js\";\n\nfunction arcInnerRadius(d) {\n return d.innerRadius;\n}\n\nfunction arcOuterRadius(d) {\n return d.outerRadius;\n}\n\nfunction arcStartAngle(d) {\n return d.startAngle;\n}\n\nfunction arcEndAngle(d) {\n return d.endAngle;\n}\n\nfunction arcPadAngle(d) {\n return d && d.padAngle; // Note: optional!\n}\n\nfunction intersect(x0, y0, x1, y1, x2, y2, x3, y3) {\n var x10 = x1 - x0, y10 = y1 - y0,\n x32 = x3 - x2, y32 = y3 - y2,\n t = y32 * x10 - x32 * y10;\n if (t * t < epsilon) return;\n t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;\n return [x0 + t * x10, y0 + t * y10];\n}\n\n// Compute perpendicular offset line of length rc.\n// http://mathworld.wolfram.com/Circle-LineIntersection.html\nfunction cornerTangents(x0, y0, x1, y1, r1, rc, cw) {\n var x01 = x0 - x1,\n y01 = y0 - y1,\n lo = (cw ? rc : -rc) / sqrt(x01 * x01 + y01 * y01),\n ox = lo * y01,\n oy = -lo * x01,\n x11 = x0 + ox,\n y11 = y0 + oy,\n x10 = x1 + ox,\n y10 = y1 + oy,\n x00 = (x11 + x10) / 2,\n y00 = (y11 + y10) / 2,\n dx = x10 - x11,\n dy = y10 - y11,\n d2 = dx * dx + dy * dy,\n r = r1 - rc,\n D = x11 * y10 - x10 * y11,\n d = (dy < 0 ? -1 : 1) * sqrt(max(0, r * r * d2 - D * D)),\n cx0 = (D * dy - dx * d) / d2,\n cy0 = (-D * dx - dy * d) / d2,\n cx1 = (D * dy + dx * d) / d2,\n cy1 = (-D * dx + dy * d) / d2,\n dx0 = cx0 - x00,\n dy0 = cy0 - y00,\n dx1 = cx1 - x00,\n dy1 = cy1 - y00;\n\n // Pick the closer of the two intersection points.\n // TODO Is there a faster way to determine which intersection to use?\n if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;\n\n return {\n cx: cx0,\n cy: cy0,\n x01: -ox,\n y01: -oy,\n x11: cx0 * (r1 / r - 1),\n y11: cy0 * (r1 / r - 1)\n };\n}\n\nexport default function() {\n var innerRadius = arcInnerRadius,\n outerRadius = arcOuterRadius,\n cornerRadius = constant(0),\n padRadius = null,\n startAngle = arcStartAngle,\n endAngle = arcEndAngle,\n padAngle = arcPadAngle,\n context = null;\n\n function arc() {\n var buffer,\n r,\n r0 = +innerRadius.apply(this, arguments),\n r1 = +outerRadius.apply(this, arguments),\n a0 = startAngle.apply(this, arguments) - halfPi,\n a1 = endAngle.apply(this, arguments) - halfPi,\n da = abs(a1 - a0),\n cw = a1 > a0;\n\n if (!context) context = buffer = path();\n\n // Ensure that the outer radius is always larger than the inner radius.\n if (r1 < r0) r = r1, r1 = r0, r0 = r;\n\n // Is it a point?\n if (!(r1 > epsilon)) context.moveTo(0, 0);\n\n // Or is it a circle or annulus?\n else if (da > tau - epsilon) {\n context.moveTo(r1 * cos(a0), r1 * sin(a0));\n context.arc(0, 0, r1, a0, a1, !cw);\n if (r0 > epsilon) {\n context.moveTo(r0 * cos(a1), r0 * sin(a1));\n context.arc(0, 0, r0, a1, a0, cw);\n }\n }\n\n // Or is it a circular or annular sector?\n else {\n var a01 = a0,\n a11 = a1,\n a00 = a0,\n a10 = a1,\n da0 = da,\n da1 = da,\n ap = padAngle.apply(this, arguments) / 2,\n rp = (ap > epsilon) && (padRadius ? +padRadius.apply(this, arguments) : sqrt(r0 * r0 + r1 * r1)),\n rc = min(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)),\n rc0 = rc,\n rc1 = rc,\n t0,\n t1;\n\n // Apply padding? Note that since r1 ≥ r0, da1 ≥ da0.\n if (rp > epsilon) {\n var p0 = asin(rp / r0 * sin(ap)),\n p1 = asin(rp / r1 * sin(ap));\n if ((da0 -= p0 * 2) > epsilon) p0 *= (cw ? 1 : -1), a00 += p0, a10 -= p0;\n else da0 = 0, a00 = a10 = (a0 + a1) / 2;\n if ((da1 -= p1 * 2) > epsilon) p1 *= (cw ? 1 : -1), a01 += p1, a11 -= p1;\n else da1 = 0, a01 = a11 = (a0 + a1) / 2;\n }\n\n var x01 = r1 * cos(a01),\n y01 = r1 * sin(a01),\n x10 = r0 * cos(a10),\n y10 = r0 * sin(a10);\n\n // Apply rounded corners?\n if (rc > epsilon) {\n var x11 = r1 * cos(a11),\n y11 = r1 * sin(a11),\n x00 = r0 * cos(a00),\n y00 = r0 * sin(a00),\n oc;\n\n // Restrict the corner radius according to the sector angle.\n if (da < pi && (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10))) {\n var ax = x01 - oc[0],\n ay = y01 - oc[1],\n bx = x11 - oc[0],\n by = y11 - oc[1],\n kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2),\n lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]);\n rc0 = min(rc, (r0 - lc) / (kc - 1));\n rc1 = min(rc, (r1 - lc) / (kc + 1));\n }\n }\n\n // Is the sector collapsed to a line?\n if (!(da1 > epsilon)) context.moveTo(x01, y01);\n\n // Does the sector’s outer ring have rounded corners?\n else if (rc1 > epsilon) {\n t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);\n t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);\n\n context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01);\n\n // Have the corners merged?\n if (rc1 < rc) context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);\n\n // Otherwise, draw the two corners and the ring.\n else {\n context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);\n context.arc(0, 0, r1, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw);\n context.arc(t1.cx, t1.cy, rc1, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);\n }\n }\n\n // Or is the outer ring just a circular arc?\n else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);\n\n // Is there no inner ring, and it’s a circular sector?\n // Or perhaps it’s an annular sector collapsed due to padding?\n if (!(r0 > epsilon) || !(da0 > epsilon)) context.lineTo(x10, y10);\n\n // Does the sector’s inner ring (or point) have rounded corners?\n else if (rc0 > epsilon) {\n t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);\n t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);\n\n context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01);\n\n // Have the corners merged?\n if (rc0 < rc) context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);\n\n // Otherwise, draw the two corners and the ring.\n else {\n context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);\n context.arc(0, 0, r0, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw);\n context.arc(t1.cx, t1.cy, rc0, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);\n }\n }\n\n // Or is the inner ring just a circular arc?\n else context.arc(0, 0, r0, a10, a00, cw);\n }\n\n context.closePath();\n\n if (buffer) return context = null, buffer + \"\" || null;\n }\n\n arc.centroid = function() {\n var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2,\n a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi / 2;\n return [cos(a) * r, sin(a) * r];\n };\n\n arc.innerRadius = function(_) {\n return arguments.length ? (innerRadius = typeof _ === \"function\" ? _ : constant(+_), arc) : innerRadius;\n };\n\n arc.outerRadius = function(_) {\n return arguments.length ? (outerRadius = typeof _ === \"function\" ? _ : constant(+_), arc) : outerRadius;\n };\n\n arc.cornerRadius = function(_) {\n return arguments.length ? (cornerRadius = typeof _ === \"function\" ? _ : constant(+_), arc) : cornerRadius;\n };\n\n arc.padRadius = function(_) {\n return arguments.length ? (padRadius = _ == null ? null : typeof _ === \"function\" ? _ : constant(+_), arc) : padRadius;\n };\n\n arc.startAngle = function(_) {\n return arguments.length ? (startAngle = typeof _ === \"function\" ? _ : constant(+_), arc) : startAngle;\n };\n\n arc.endAngle = function(_) {\n return arguments.length ? (endAngle = typeof _ === \"function\" ? _ : constant(+_), arc) : endAngle;\n };\n\n arc.padAngle = function(_) {\n return arguments.length ? (padAngle = typeof _ === \"function\" ? _ : constant(+_), arc) : padAngle;\n };\n\n arc.context = function(_) {\n return arguments.length ? ((context = _ == null ? null : _), arc) : context;\n };\n\n return arc;\n}\n","export var slice = Array.prototype.slice;\n\nexport default function(x) {\n return typeof x === \"object\" && \"length\" in x\n ? x // Array, TypedArray, NodeList, array-like\n : Array.from(x); // Map, Set, iterable, string, or anything else\n}\n","export function x(p) {\n return p[0];\n}\n\nexport function y(p) {\n return p[1];\n}\n","import {path} from \"d3-path\";\nimport array from \"./array.js\";\nimport constant from \"./constant.js\";\nimport curveLinear from \"./curve/linear.js\";\nimport {x as pointX, y as pointY} from \"./point.js\";\n\nexport default function(x, y) {\n var defined = constant(true),\n context = null,\n curve = curveLinear,\n output = null;\n\n x = typeof x === \"function\" ? x : (x === undefined) ? pointX : constant(x);\n y = typeof y === \"function\" ? y : (y === undefined) ? pointY : constant(y);\n\n function line(data) {\n var i,\n n = (data = array(data)).length,\n d,\n defined0 = false,\n buffer;\n\n if (context == null) output = curve(buffer = path());\n\n for (i = 0; i <= n; ++i) {\n if (!(i < n && defined(d = data[i], i, data)) === defined0) {\n if (defined0 = !defined0) output.lineStart();\n else output.lineEnd();\n }\n if (defined0) output.point(+x(d, i, data), +y(d, i, data));\n }\n\n if (buffer) return output = null, buffer + \"\" || null;\n }\n\n line.x = function(_) {\n return arguments.length ? (x = typeof _ === \"function\" ? _ : constant(+_), line) : x;\n };\n\n line.y = function(_) {\n return arguments.length ? (y = typeof _ === \"function\" ? _ : constant(+_), line) : y;\n };\n\n line.defined = function(_) {\n return arguments.length ? (defined = typeof _ === \"function\" ? _ : constant(!!_), line) : defined;\n };\n\n line.curve = function(_) {\n return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;\n };\n\n line.context = function(_) {\n return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;\n };\n\n return line;\n}\n","import {path} from \"d3-path\";\nimport array from \"./array.js\";\nimport constant from \"./constant.js\";\nimport curveLinear from \"./curve/linear.js\";\nimport line from \"./line.js\";\nimport {x as pointX, y as pointY} from \"./point.js\";\n\nexport default function(x0, y0, y1) {\n var x1 = null,\n defined = constant(true),\n context = null,\n curve = curveLinear,\n output = null;\n\n x0 = typeof x0 === \"function\" ? x0 : (x0 === undefined) ? pointX : constant(+x0);\n y0 = typeof y0 === \"function\" ? y0 : (y0 === undefined) ? constant(0) : constant(+y0);\n y1 = typeof y1 === \"function\" ? y1 : (y1 === undefined) ? pointY : constant(+y1);\n\n function area(data) {\n var i,\n j,\n k,\n n = (data = array(data)).length,\n d,\n defined0 = false,\n buffer,\n x0z = new Array(n),\n y0z = new Array(n);\n\n if (context == null) output = curve(buffer = path());\n\n for (i = 0; i <= n; ++i) {\n if (!(i < n && defined(d = data[i], i, data)) === defined0) {\n if (defined0 = !defined0) {\n j = i;\n output.areaStart();\n output.lineStart();\n } else {\n output.lineEnd();\n output.lineStart();\n for (k = i - 1; k >= j; --k) {\n output.point(x0z[k], y0z[k]);\n }\n output.lineEnd();\n output.areaEnd();\n }\n }\n if (defined0) {\n x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);\n output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);\n }\n }\n\n if (buffer) return output = null, buffer + \"\" || null;\n }\n\n function arealine() {\n return line().defined(defined).curve(curve).context(context);\n }\n\n area.x = function(_) {\n return arguments.length ? (x0 = typeof _ === \"function\" ? _ : constant(+_), x1 = null, area) : x0;\n };\n\n area.x0 = function(_) {\n return arguments.length ? (x0 = typeof _ === \"function\" ? _ : constant(+_), area) : x0;\n };\n\n area.x1 = function(_) {\n return arguments.length ? (x1 = _ == null ? null : typeof _ === \"function\" ? _ : constant(+_), area) : x1;\n };\n\n area.y = function(_) {\n return arguments.length ? (y0 = typeof _ === \"function\" ? _ : constant(+_), y1 = null, area) : y0;\n };\n\n area.y0 = function(_) {\n return arguments.length ? (y0 = typeof _ === \"function\" ? _ : constant(+_), area) : y0;\n };\n\n area.y1 = function(_) {\n return arguments.length ? (y1 = _ == null ? null : typeof _ === \"function\" ? _ : constant(+_), area) : y1;\n };\n\n area.lineX0 =\n area.lineY0 = function() {\n return arealine().x(x0).y(y0);\n };\n\n area.lineY1 = function() {\n return arealine().x(x0).y(y1);\n };\n\n area.lineX1 = function() {\n return arealine().x(x1).y(y0);\n };\n\n area.defined = function(_) {\n return arguments.length ? (defined = typeof _ === \"function\" ? _ : constant(!!_), area) : defined;\n };\n\n area.curve = function(_) {\n return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve;\n };\n\n area.context = function(_) {\n return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context;\n };\n\n return area;\n}\n","import {pi, tau} from \"../math.js\";\n\nexport default {\n draw: function(context, size) {\n var r = Math.sqrt(size / pi);\n context.moveTo(r, 0);\n context.arc(0, 0, r, 0, tau);\n }\n};\n","import {pi, tau} from \"../math.js\";\n\nvar ka = 0.89081309152928522810,\n kr = Math.sin(pi / 10) / Math.sin(7 * pi / 10),\n kx = Math.sin(tau / 10) * kr,\n ky = -Math.cos(tau / 10) * kr;\n\nexport default {\n draw: function(context, size) {\n var r = Math.sqrt(size * ka),\n x = kx * r,\n y = ky * r;\n context.moveTo(0, -r);\n context.lineTo(x, y);\n for (var i = 1; i < 5; ++i) {\n var a = tau * i / 5,\n c = Math.cos(a),\n s = Math.sin(a);\n context.lineTo(s * r, -c * r);\n context.lineTo(c * x - s * y, s * x + c * y);\n }\n context.closePath();\n }\n};\n","var tan30 = Math.sqrt(1 / 3),\n tan30_2 = tan30 * 2;\n\nexport default {\n draw: function(context, size) {\n var y = Math.sqrt(size / tan30_2),\n x = y * tan30;\n context.moveTo(0, -y);\n context.lineTo(x, 0);\n context.lineTo(0, y);\n context.lineTo(-x, 0);\n context.closePath();\n }\n};\n","var sqrt3 = Math.sqrt(3);\n\nexport default {\n draw: function(context, size) {\n var y = -Math.sqrt(size / (sqrt3 * 3));\n context.moveTo(0, y * 2);\n context.lineTo(-sqrt3 * y, -y);\n context.lineTo(sqrt3 * y, -y);\n context.closePath();\n }\n};\n","var c = -0.5,\n s = Math.sqrt(3) / 2,\n k = 1 / Math.sqrt(12),\n a = (k / 2 + 1) * 3;\n\nexport default {\n draw: function(context, size) {\n var r = Math.sqrt(size / a),\n x0 = r / 2,\n y0 = r * k,\n x1 = x0,\n y1 = r * k + r,\n x2 = -x1,\n y2 = y1;\n context.moveTo(x0, y0);\n context.lineTo(x1, y1);\n context.lineTo(x2, y2);\n context.lineTo(c * x0 - s * y0, s * x0 + c * y0);\n context.lineTo(c * x1 - s * y1, s * x1 + c * y1);\n context.lineTo(c * x2 - s * y2, s * x2 + c * y2);\n context.lineTo(c * x0 + s * y0, c * y0 - s * x0);\n context.lineTo(c * x1 + s * y1, c * y1 - s * x1);\n context.lineTo(c * x2 + s * y2, c * y2 - s * x2);\n context.closePath();\n }\n};\n","export function domCanvas(w, h) {\n if (typeof document !== 'undefined' && document.createElement) {\n const c = document.createElement('canvas');\n if (c && c.getContext) {\n c.width = w;\n c.height = h;\n return c;\n }\n }\n return null;\n}\n\nexport const domImage = () =>\n typeof Image !== 'undefined' ? Image : null;\n","export default function(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","import ascending from \"./ascending.js\";\n\nexport default function(f) {\n let delta = f;\n let compare = f;\n\n if (f.length === 1) {\n delta = (d, x) => f(d) - x;\n compare = ascendingComparator(f);\n }\n\n function left(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (compare(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n\n function right(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (compare(a[mid], x) > 0) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n }\n\n function center(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n const i = left(a, x, lo, hi - 1);\n return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;\n }\n\n return {left, center, right};\n}\n\nfunction ascendingComparator(f) {\n return (d, x) => ascending(f(d), x);\n}\n","export default function(x) {\n return x === null ? NaN : +x;\n}\n\nexport function* numbers(values, valueof) {\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n yield value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n yield value;\n }\n }\n }\n}\n","import ascending from \"./ascending.js\";\nimport bisector from \"./bisector.js\";\nimport number from \"./number.js\";\n\nconst ascendingBisect = bisector(ascending);\nexport const bisectRight = ascendingBisect.right;\nexport const bisectLeft = ascendingBisect.left;\nexport const bisectCenter = bisector(number).center;\nexport default bisectRight;\n","export function initRange(domain, range) {\n switch (arguments.length) {\n case 0: break;\n case 1: this.range(domain); break;\n default: this.range(range).domain(domain); break;\n }\n return this;\n}\n\nexport function initInterpolator(domain, interpolator) {\n switch (arguments.length) {\n case 0: break;\n case 1: {\n if (typeof domain === \"function\") this.interpolator(domain);\n else this.range(domain);\n break;\n }\n default: {\n this.domain(domain);\n if (typeof interpolator === \"function\") this.interpolator(interpolator);\n else this.range(interpolator);\n break;\n }\n }\n return this;\n}\n","import {initRange} from \"./init.js\";\n\nexport const implicit = Symbol(\"implicit\");\n\nexport default function ordinal() {\n var index = new Map(),\n domain = [],\n range = [],\n unknown = implicit;\n\n function scale(d) {\n var key = d + \"\", i = index.get(key);\n if (!i) {\n if (unknown !== implicit) return unknown;\n index.set(key, i = domain.push(d));\n }\n return range[(i - 1) % range.length];\n }\n\n scale.domain = function(_) {\n if (!arguments.length) return domain.slice();\n domain = [], index = new Map();\n for (const value of _) {\n const key = value + \"\";\n if (index.has(key)) continue;\n index.set(key, domain.push(value));\n }\n return scale;\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), scale) : range.slice();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return ordinal(domain, range).unknown(unknown);\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n","var e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nexport default function(start, stop, count) {\n var reverse,\n i = -1,\n n,\n ticks,\n step;\n\n stop = +stop, start = +start, count = +count;\n if (start === stop && count > 0) return [start];\n if (reverse = stop < start) n = start, start = stop, stop = n;\n if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];\n\n if (step > 0) {\n let r0 = Math.round(start / step), r1 = Math.round(stop / step);\n if (r0 * step < start) ++r0;\n if (r1 * step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) * step;\n } else {\n step = -step;\n let r0 = Math.round(start * step), r1 = Math.round(stop * step);\n if (r0 / step < start) ++r0;\n if (r1 / step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) / step;\n }\n\n if (reverse) ticks.reverse();\n\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n var step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log(step) / Math.LN10),\n error = step / Math.pow(10, power);\n return power >= 0\n ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)\n : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);\n}\n\nexport function tickStep(start, stop, count) {\n var step0 = Math.abs(stop - start) / Math.max(0, count),\n step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),\n error = step0 / step1;\n if (error >= e10) step1 *= 10;\n else if (error >= e5) step1 *= 5;\n else if (error >= e2) step1 *= 2;\n return stop < start ? -step1 : step1;\n}\n","// [[fill]align][sign][symbol][0][width][,][.precision][~][type]\nvar re = /^(?:(.)?([<>=^]))?([+\\-( ])?([$#])?(0)?(\\d+)?(,)?(\\.\\d+)?(~)?([a-z%])?$/i;\n\nexport default function formatSpecifier(specifier) {\n if (!(match = re.exec(specifier))) throw new Error(\"invalid format: \" + specifier);\n var match;\n return new FormatSpecifier({\n fill: match[1],\n align: match[2],\n sign: match[3],\n symbol: match[4],\n zero: match[5],\n width: match[6],\n comma: match[7],\n precision: match[8] && match[8].slice(1),\n trim: match[9],\n type: match[10]\n });\n}\n\nformatSpecifier.prototype = FormatSpecifier.prototype; // instanceof\n\nexport function FormatSpecifier(specifier) {\n this.fill = specifier.fill === undefined ? \" \" : specifier.fill + \"\";\n this.align = specifier.align === undefined ? \">\" : specifier.align + \"\";\n this.sign = specifier.sign === undefined ? \"-\" : specifier.sign + \"\";\n this.symbol = specifier.symbol === undefined ? \"\" : specifier.symbol + \"\";\n this.zero = !!specifier.zero;\n this.width = specifier.width === undefined ? undefined : +specifier.width;\n this.comma = !!specifier.comma;\n this.precision = specifier.precision === undefined ? undefined : +specifier.precision;\n this.trim = !!specifier.trim;\n this.type = specifier.type === undefined ? \"\" : specifier.type + \"\";\n}\n\nFormatSpecifier.prototype.toString = function() {\n return this.fill\n + this.align\n + this.sign\n + this.symbol\n + (this.zero ? \"0\" : \"\")\n + (this.width === undefined ? \"\" : Math.max(1, this.width | 0))\n + (this.comma ? \",\" : \"\")\n + (this.precision === undefined ? \"\" : \".\" + Math.max(0, this.precision | 0))\n + (this.trim ? \"~\" : \"\")\n + this.type;\n};\n","// Computes the decimal coefficient and exponent of the specified number x with\n// significant digits p, where x is positive and p is in [1, 21] or undefined.\n// For example, formatDecimal(1.23) returns [\"123\", 0].\nexport default function(x, p) {\n if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf(\"e\")) < 0) return null; // NaN, ±Infinity\n var i, coefficient = x.slice(0, i);\n\n // The string returned by toExponential either has the form \\d\\.\\d+e[-+]\\d+\n // (e.g., 1.2e+3) or the form \\de[-+]\\d+ (e.g., 1e+3).\n return [\n coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,\n +x.slice(i + 1)\n ];\n}\n","import formatDecimal from \"./formatDecimal.js\";\n\nexport var prefixExponent;\n\nexport default function(x, p) {\n var d = formatDecimal(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1],\n i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,\n n = coefficient.length;\n return i === n ? coefficient\n : i > n ? coefficient + new Array(i - n + 1).join(\"0\")\n : i > 0 ? coefficient.slice(0, i) + \".\" + coefficient.slice(i)\n : \"0.\" + new Array(1 - i).join(\"0\") + formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!\n}\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var format;\nexport var formatPrefix;\n\ndefaultLocale({\n decimal: \".\",\n thousands: \",\",\n grouping: [3],\n currency: [\"$\", \"\"],\n minus: \"-\"\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n format = locale.format;\n formatPrefix = locale.formatPrefix;\n return locale;\n}\n","import formatDecimal from \"./formatDecimal.js\";\n\nexport default function(x) {\n return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN;\n}\n","import formatDecimal from \"./formatDecimal.js\";\n\nexport default function(x, p) {\n var d = formatDecimal(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1];\n return exponent < 0 ? \"0.\" + new Array(-exponent).join(\"0\") + coefficient\n : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + \".\" + coefficient.slice(exponent + 1)\n : coefficient + new Array(exponent - coefficient.length + 2).join(\"0\");\n}\n","import formatPrefixAuto from \"./formatPrefixAuto.js\";\nimport formatRounded from \"./formatRounded.js\";\n\nexport default {\n \"%\": function(x, p) { return (x * 100).toFixed(p); },\n \"b\": function(x) { return Math.round(x).toString(2); },\n \"c\": function(x) { return x + \"\"; },\n \"d\": function(x) { return Math.round(x).toString(10); },\n \"e\": function(x, p) { return x.toExponential(p); },\n \"f\": function(x, p) { return x.toFixed(p); },\n \"g\": function(x, p) { return x.toPrecision(p); },\n \"o\": function(x) { return Math.round(x).toString(8); },\n \"p\": function(x, p) { return formatRounded(x * 100, p); },\n \"r\": formatRounded,\n \"s\": formatPrefixAuto,\n \"X\": function(x) { return Math.round(x).toString(16).toUpperCase(); },\n \"x\": function(x) { return Math.round(x).toString(16); }\n};\n","export default function(x) {\n return x;\n}\n","import exponent from \"./exponent.js\";\nimport formatGroup from \"./formatGroup.js\";\nimport formatNumerals from \"./formatNumerals.js\";\nimport formatSpecifier from \"./formatSpecifier.js\";\nimport formatTrim from \"./formatTrim.js\";\nimport formatTypes from \"./formatTypes.js\";\nimport {prefixExponent} from \"./formatPrefixAuto.js\";\nimport identity from \"./identity.js\";\n\nvar map = Array.prototype.map,\n prefixes = [\"y\",\"z\",\"a\",\"f\",\"p\",\"n\",\"µ\",\"m\",\"\",\"k\",\"M\",\"G\",\"T\",\"P\",\"E\",\"Z\",\"Y\"];\n\nexport default function(locale) {\n var group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + \"\"),\n currencyPrefix = locale.currency === undefined ? \"\" : locale.currency[0] + \"\",\n currencySuffix = locale.currency === undefined ? \"\" : locale.currency[1] + \"\",\n decimal = locale.decimal === undefined ? \".\" : locale.decimal + \"\",\n numerals = locale.numerals === undefined ? identity : formatNumerals(map.call(locale.numerals, String)),\n percent = locale.percent === undefined ? \"%\" : locale.percent + \"\",\n minus = locale.minus === undefined ? \"-\" : locale.minus + \"\",\n nan = locale.nan === undefined ? \"NaN\" : locale.nan + \"\";\n\n function newFormat(specifier) {\n specifier = formatSpecifier(specifier);\n\n var fill = specifier.fill,\n align = specifier.align,\n sign = specifier.sign,\n symbol = specifier.symbol,\n zero = specifier.zero,\n width = specifier.width,\n comma = specifier.comma,\n precision = specifier.precision,\n trim = specifier.trim,\n type = specifier.type;\n\n // The \"n\" type is an alias for \",g\".\n if (type === \"n\") comma = true, type = \"g\";\n\n // The \"\" type, and any invalid type, is an alias for \".12~g\".\n else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = \"g\";\n\n // If zero fill is specified, padding goes after sign and before digits.\n if (zero || (fill === \"0\" && align === \"=\")) zero = true, fill = \"0\", align = \"=\";\n\n // Compute the prefix and suffix.\n // For SI-prefix, the suffix is lazily computed.\n var prefix = symbol === \"$\" ? currencyPrefix : symbol === \"#\" && /[boxX]/.test(type) ? \"0\" + type.toLowerCase() : \"\",\n suffix = symbol === \"$\" ? currencySuffix : /[%p]/.test(type) ? percent : \"\";\n\n // What format function should we use?\n // Is this an integer type?\n // Can this type generate exponential notation?\n var formatType = formatTypes[type],\n maybeSuffix = /[defgprs%]/.test(type);\n\n // Set the default precision if not specified,\n // or clamp the specified precision to the supported range.\n // For significant precision, it must be in [1, 21].\n // For fixed precision, it must be in [0, 20].\n precision = precision === undefined ? 6\n : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))\n : Math.max(0, Math.min(20, precision));\n\n function format(value) {\n var valuePrefix = prefix,\n valueSuffix = suffix,\n i, n, c;\n\n if (type === \"c\") {\n valueSuffix = formatType(value) + valueSuffix;\n value = \"\";\n } else {\n value = +value;\n\n // Determine the sign. -0 is not less than 0, but 1 / -0 is!\n var valueNegative = value < 0 || 1 / value < 0;\n\n // Perform the initial formatting.\n value = isNaN(value) ? nan : formatType(Math.abs(value), precision);\n\n // Trim insignificant zeros.\n if (trim) value = formatTrim(value);\n\n // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.\n if (valueNegative && +value === 0 && sign !== \"+\") valueNegative = false;\n\n // Compute the prefix and suffix.\n valuePrefix = (valueNegative ? (sign === \"(\" ? sign : minus) : sign === \"-\" || sign === \"(\" ? \"\" : sign) + valuePrefix;\n valueSuffix = (type === \"s\" ? prefixes[8 + prefixExponent / 3] : \"\") + valueSuffix + (valueNegative && sign === \"(\" ? \")\" : \"\");\n\n // Break the formatted value into the integer “value” part that can be\n // grouped, and fractional or exponential “suffix” part that is not.\n if (maybeSuffix) {\n i = -1, n = value.length;\n while (++i < n) {\n if (c = value.charCodeAt(i), 48 > c || c > 57) {\n valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;\n value = value.slice(0, i);\n break;\n }\n }\n }\n }\n\n // If the fill character is not \"0\", grouping is applied before padding.\n if (comma && !zero) value = group(value, Infinity);\n\n // Compute the padding.\n var length = valuePrefix.length + value.length + valueSuffix.length,\n padding = length < width ? new Array(width - length + 1).join(fill) : \"\";\n\n // If the fill character is \"0\", grouping is applied after padding.\n if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = \"\";\n\n // Reconstruct the final output based on the desired alignment.\n switch (align) {\n case \"<\": value = valuePrefix + value + valueSuffix + padding; break;\n case \"=\": value = valuePrefix + padding + value + valueSuffix; break;\n case \"^\": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;\n default: value = padding + valuePrefix + value + valueSuffix; break;\n }\n\n return numerals(value);\n }\n\n format.toString = function() {\n return specifier + \"\";\n };\n\n return format;\n }\n\n function formatPrefix(specifier, value) {\n var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = \"f\", specifier)),\n e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,\n k = Math.pow(10, -e),\n prefix = prefixes[8 + e / 3];\n return function(value) {\n return f(k * value) + prefix;\n };\n }\n\n return {\n format: newFormat,\n formatPrefix: formatPrefix\n };\n}\n","export default function(grouping, thousands) {\n return function(value, width) {\n var i = value.length,\n t = [],\n j = 0,\n g = grouping[0],\n length = 0;\n\n while (i > 0 && g > 0) {\n if (length + g + 1 > width) g = Math.max(1, width - length);\n t.push(value.substring(i -= g, i + g));\n if ((length += g + 1) > width) break;\n g = grouping[j = (j + 1) % grouping.length];\n }\n\n return t.reverse().join(thousands);\n };\n}\n","export default function(numerals) {\n return function(value) {\n return value.replace(/[0-9]/g, function(i) {\n return numerals[+i];\n });\n };\n}\n","// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.\nexport default function(s) {\n out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {\n switch (s[i]) {\n case \".\": i0 = i1 = i; break;\n case \"0\": if (i0 === 0) i0 = i; i1 = i; break;\n default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;\n }\n }\n return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;\n}\n","import {tickStep} from \"d3-array\";\nimport {format, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound} from \"d3-format\";\n\nexport default function tickFormat(start, stop, count, specifier) {\n var step = tickStep(start, stop, count),\n precision;\n specifier = formatSpecifier(specifier == null ? \",f\" : specifier);\n switch (specifier.type) {\n case \"s\": {\n var value = Math.max(Math.abs(start), Math.abs(stop));\n if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision;\n return formatPrefix(specifier, value);\n }\n case \"\":\n case \"e\":\n case \"g\":\n case \"p\":\n case \"r\": {\n if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === \"e\");\n break;\n }\n case \"f\":\n case \"%\": {\n if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === \"%\") * 2;\n break;\n }\n }\n return format(specifier);\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step, value) {\n return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step, max) {\n step = Math.abs(step), max = Math.abs(max) - step;\n return Math.max(0, exponent(max) - exponent(step)) + 1;\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step) {\n return Math.max(0, -exponent(Math.abs(step)));\n}\n","export default function(constructor, factory, prototype) {\n constructor.prototype = factory.prototype = prototype;\n prototype.constructor = constructor;\n}\n\nexport function extend(parent, definition) {\n var prototype = Object.create(parent.prototype);\n for (var key in definition) prototype[key] = definition[key];\n return prototype;\n}\n","import define, {extend} from \"./define.js\";\n\nexport function Color() {}\n\nexport var darker = 0.7;\nexport var brighter = 1 / darker;\n\nvar reI = \"\\\\s*([+-]?\\\\d+)\\\\s*\",\n reN = \"\\\\s*([+-]?\\\\d*\\\\.?\\\\d+(?:[eE][+-]?\\\\d+)?)\\\\s*\",\n reP = \"\\\\s*([+-]?\\\\d*\\\\.?\\\\d+(?:[eE][+-]?\\\\d+)?)%\\\\s*\",\n reHex = /^#([0-9a-f]{3,8})$/,\n reRgbInteger = new RegExp(\"^rgb\\\\(\" + [reI, reI, reI] + \"\\\\)$\"),\n reRgbPercent = new RegExp(\"^rgb\\\\(\" + [reP, reP, reP] + \"\\\\)$\"),\n reRgbaInteger = new RegExp(\"^rgba\\\\(\" + [reI, reI, reI, reN] + \"\\\\)$\"),\n reRgbaPercent = new RegExp(\"^rgba\\\\(\" + [reP, reP, reP, reN] + \"\\\\)$\"),\n reHslPercent = new RegExp(\"^hsl\\\\(\" + [reN, reP, reP] + \"\\\\)$\"),\n reHslaPercent = new RegExp(\"^hsla\\\\(\" + [reN, reP, reP, reN] + \"\\\\)$\");\n\nvar named = {\n aliceblue: 0xf0f8ff,\n antiquewhite: 0xfaebd7,\n aqua: 0x00ffff,\n aquamarine: 0x7fffd4,\n azure: 0xf0ffff,\n beige: 0xf5f5dc,\n bisque: 0xffe4c4,\n black: 0x000000,\n blanchedalmond: 0xffebcd,\n blue: 0x0000ff,\n blueviolet: 0x8a2be2,\n brown: 0xa52a2a,\n burlywood: 0xdeb887,\n cadetblue: 0x5f9ea0,\n chartreuse: 0x7fff00,\n chocolate: 0xd2691e,\n coral: 0xff7f50,\n cornflowerblue: 0x6495ed,\n cornsilk: 0xfff8dc,\n crimson: 0xdc143c,\n cyan: 0x00ffff,\n darkblue: 0x00008b,\n darkcyan: 0x008b8b,\n darkgoldenrod: 0xb8860b,\n darkgray: 0xa9a9a9,\n darkgreen: 0x006400,\n darkgrey: 0xa9a9a9,\n darkkhaki: 0xbdb76b,\n darkmagenta: 0x8b008b,\n darkolivegreen: 0x556b2f,\n darkorange: 0xff8c00,\n darkorchid: 0x9932cc,\n darkred: 0x8b0000,\n darksalmon: 0xe9967a,\n darkseagreen: 0x8fbc8f,\n darkslateblue: 0x483d8b,\n darkslategray: 0x2f4f4f,\n darkslategrey: 0x2f4f4f,\n darkturquoise: 0x00ced1,\n darkviolet: 0x9400d3,\n deeppink: 0xff1493,\n deepskyblue: 0x00bfff,\n dimgray: 0x696969,\n dimgrey: 0x696969,\n dodgerblue: 0x1e90ff,\n firebrick: 0xb22222,\n floralwhite: 0xfffaf0,\n forestgreen: 0x228b22,\n fuchsia: 0xff00ff,\n gainsboro: 0xdcdcdc,\n ghostwhite: 0xf8f8ff,\n gold: 0xffd700,\n goldenrod: 0xdaa520,\n gray: 0x808080,\n green: 0x008000,\n greenyellow: 0xadff2f,\n grey: 0x808080,\n honeydew: 0xf0fff0,\n hotpink: 0xff69b4,\n indianred: 0xcd5c5c,\n indigo: 0x4b0082,\n ivory: 0xfffff0,\n khaki: 0xf0e68c,\n lavender: 0xe6e6fa,\n lavenderblush: 0xfff0f5,\n lawngreen: 0x7cfc00,\n lemonchiffon: 0xfffacd,\n lightblue: 0xadd8e6,\n lightcoral: 0xf08080,\n lightcyan: 0xe0ffff,\n lightgoldenrodyellow: 0xfafad2,\n lightgray: 0xd3d3d3,\n lightgreen: 0x90ee90,\n lightgrey: 0xd3d3d3,\n lightpink: 0xffb6c1,\n lightsalmon: 0xffa07a,\n lightseagreen: 0x20b2aa,\n lightskyblue: 0x87cefa,\n lightslategray: 0x778899,\n lightslategrey: 0x778899,\n lightsteelblue: 0xb0c4de,\n lightyellow: 0xffffe0,\n lime: 0x00ff00,\n limegreen: 0x32cd32,\n linen: 0xfaf0e6,\n magenta: 0xff00ff,\n maroon: 0x800000,\n mediumaquamarine: 0x66cdaa,\n mediumblue: 0x0000cd,\n mediumorchid: 0xba55d3,\n mediumpurple: 0x9370db,\n mediumseagreen: 0x3cb371,\n mediumslateblue: 0x7b68ee,\n mediumspringgreen: 0x00fa9a,\n mediumturquoise: 0x48d1cc,\n mediumvioletred: 0xc71585,\n midnightblue: 0x191970,\n mintcream: 0xf5fffa,\n mistyrose: 0xffe4e1,\n moccasin: 0xffe4b5,\n navajowhite: 0xffdead,\n navy: 0x000080,\n oldlace: 0xfdf5e6,\n olive: 0x808000,\n olivedrab: 0x6b8e23,\n orange: 0xffa500,\n orangered: 0xff4500,\n orchid: 0xda70d6,\n palegoldenrod: 0xeee8aa,\n palegreen: 0x98fb98,\n paleturquoise: 0xafeeee,\n palevioletred: 0xdb7093,\n papayawhip: 0xffefd5,\n peachpuff: 0xffdab9,\n peru: 0xcd853f,\n pink: 0xffc0cb,\n plum: 0xdda0dd,\n powderblue: 0xb0e0e6,\n purple: 0x800080,\n rebeccapurple: 0x663399,\n red: 0xff0000,\n rosybrown: 0xbc8f8f,\n royalblue: 0x4169e1,\n saddlebrown: 0x8b4513,\n salmon: 0xfa8072,\n sandybrown: 0xf4a460,\n seagreen: 0x2e8b57,\n seashell: 0xfff5ee,\n sienna: 0xa0522d,\n silver: 0xc0c0c0,\n skyblue: 0x87ceeb,\n slateblue: 0x6a5acd,\n slategray: 0x708090,\n slategrey: 0x708090,\n snow: 0xfffafa,\n springgreen: 0x00ff7f,\n steelblue: 0x4682b4,\n tan: 0xd2b48c,\n teal: 0x008080,\n thistle: 0xd8bfd8,\n tomato: 0xff6347,\n turquoise: 0x40e0d0,\n violet: 0xee82ee,\n wheat: 0xf5deb3,\n white: 0xffffff,\n whitesmoke: 0xf5f5f5,\n yellow: 0xffff00,\n yellowgreen: 0x9acd32\n};\n\ndefine(Color, color, {\n copy: function(channels) {\n return Object.assign(new this.constructor, this, channels);\n },\n displayable: function() {\n return this.rgb().displayable();\n },\n hex: color_formatHex, // Deprecated! Use color.formatHex.\n formatHex: color_formatHex,\n formatHsl: color_formatHsl,\n formatRgb: color_formatRgb,\n toString: color_formatRgb\n});\n\nfunction color_formatHex() {\n return this.rgb().formatHex();\n}\n\nfunction color_formatHsl() {\n return hslConvert(this).formatHsl();\n}\n\nfunction color_formatRgb() {\n return this.rgb().formatRgb();\n}\n\nexport default function color(format) {\n var m, l;\n format = (format + \"\").trim().toLowerCase();\n return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000\n : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00\n : l === 8 ? new Rgb(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000\n : l === 4 ? new Rgb((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000\n : null) // invalid hex\n : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)\n : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)\n : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)\n : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)\n : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)\n : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)\n : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins\n : format === \"transparent\" ? new Rgb(NaN, NaN, NaN, 0)\n : null;\n}\n\nfunction rgbn(n) {\n return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);\n}\n\nfunction rgba(r, g, b, a) {\n if (a <= 0) r = g = b = NaN;\n return new Rgb(r, g, b, a);\n}\n\nexport function rgbConvert(o) {\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Rgb;\n o = o.rgb();\n return new Rgb(o.r, o.g, o.b, o.opacity);\n}\n\nexport function rgb(r, g, b, opacity) {\n return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);\n}\n\nexport function Rgb(r, g, b, opacity) {\n this.r = +r;\n this.g = +g;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Rgb, rgb, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n rgb: function() {\n return this;\n },\n displayable: function() {\n return (-0.5 <= this.r && this.r < 255.5)\n && (-0.5 <= this.g && this.g < 255.5)\n && (-0.5 <= this.b && this.b < 255.5)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n hex: rgb_formatHex, // Deprecated! Use color.formatHex.\n formatHex: rgb_formatHex,\n formatRgb: rgb_formatRgb,\n toString: rgb_formatRgb\n}));\n\nfunction rgb_formatHex() {\n return \"#\" + hex(this.r) + hex(this.g) + hex(this.b);\n}\n\nfunction rgb_formatRgb() {\n var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));\n return (a === 1 ? \"rgb(\" : \"rgba(\")\n + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + \", \"\n + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + \", \"\n + Math.max(0, Math.min(255, Math.round(this.b) || 0))\n + (a === 1 ? \")\" : \", \" + a + \")\");\n}\n\nfunction hex(value) {\n value = Math.max(0, Math.min(255, Math.round(value) || 0));\n return (value < 16 ? \"0\" : \"\") + value.toString(16);\n}\n\nfunction hsla(h, s, l, a) {\n if (a <= 0) h = s = l = NaN;\n else if (l <= 0 || l >= 1) h = s = NaN;\n else if (s <= 0) h = NaN;\n return new Hsl(h, s, l, a);\n}\n\nexport function hslConvert(o) {\n if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Hsl;\n if (o instanceof Hsl) return o;\n o = o.rgb();\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n min = Math.min(r, g, b),\n max = Math.max(r, g, b),\n h = NaN,\n s = max - min,\n l = (max + min) / 2;\n if (s) {\n if (r === max) h = (g - b) / s + (g < b) * 6;\n else if (g === max) h = (b - r) / s + 2;\n else h = (r - g) / s + 4;\n s /= l < 0.5 ? max + min : 2 - max - min;\n h *= 60;\n } else {\n s = l > 0 && l < 1 ? 0 : h;\n }\n return new Hsl(h, s, l, o.opacity);\n}\n\nexport function hsl(h, s, l, opacity) {\n return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);\n}\n\nfunction Hsl(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Hsl, hsl, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n rgb: function() {\n var h = this.h % 360 + (this.h < 0) * 360,\n s = isNaN(h) || isNaN(this.s) ? 0 : this.s,\n l = this.l,\n m2 = l + (l < 0.5 ? l : 1 - l) * s,\n m1 = 2 * l - m2;\n return new Rgb(\n hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),\n hsl2rgb(h, m1, m2),\n hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),\n this.opacity\n );\n },\n displayable: function() {\n return (0 <= this.s && this.s <= 1 || isNaN(this.s))\n && (0 <= this.l && this.l <= 1)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n formatHsl: function() {\n var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));\n return (a === 1 ? \"hsl(\" : \"hsla(\")\n + (this.h || 0) + \", \"\n + (this.s || 0) * 100 + \"%, \"\n + (this.l || 0) * 100 + \"%\"\n + (a === 1 ? \")\" : \", \" + a + \")\");\n }\n}));\n\n/* From FvD 13.37, CSS Color Module Level 3 */\nfunction hsl2rgb(h, m1, m2) {\n return (h < 60 ? m1 + (m2 - m1) * h / 60\n : h < 180 ? m2\n : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60\n : m1) * 255;\n}\n","export function basis(t1, v0, v1, v2, v3) {\n var t2 = t1 * t1, t3 = t2 * t1;\n return ((1 - 3 * t1 + 3 * t2 - t3) * v0\n + (4 - 6 * t2 + 3 * t3) * v1\n + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2\n + t3 * v3) / 6;\n}\n\nexport default function(values) {\n var n = values.length - 1;\n return function(t) {\n var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),\n v1 = values[i],\n v2 = values[i + 1],\n v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,\n v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","import {basis} from \"./basis.js\";\n\nexport default function(values) {\n var n = values.length;\n return function(t) {\n var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),\n v0 = values[(i + n - 1) % n],\n v1 = values[i % n],\n v2 = values[(i + 1) % n],\n v3 = values[(i + 2) % n];\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","export default x => () => x;\n","import constant from \"./constant.js\";\n\nfunction linear(a, d) {\n return function(t) {\n return a + t * d;\n };\n}\n\nfunction exponential(a, b, y) {\n return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {\n return Math.pow(a + t * b, y);\n };\n}\n\nexport function hue(a, b) {\n var d = b - a;\n return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);\n}\n\nexport function gamma(y) {\n return (y = +y) === 1 ? nogamma : function(a, b) {\n return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);\n };\n}\n\nexport default function nogamma(a, b) {\n var d = b - a;\n return d ? linear(a, d) : constant(isNaN(a) ? b : a);\n}\n","import {rgb as colorRgb} from \"d3-color\";\nimport basis from \"./basis.js\";\nimport basisClosed from \"./basisClosed.js\";\nimport nogamma, {gamma} from \"./color.js\";\n\nexport default (function rgbGamma(y) {\n var color = gamma(y);\n\n function rgb(start, end) {\n var r = color((start = colorRgb(start)).r, (end = colorRgb(end)).r),\n g = color(start.g, end.g),\n b = color(start.b, end.b),\n opacity = nogamma(start.opacity, end.opacity);\n return function(t) {\n start.r = r(t);\n start.g = g(t);\n start.b = b(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n rgb.gamma = rgbGamma;\n\n return rgb;\n})(1);\n\nfunction rgbSpline(spline) {\n return function(colors) {\n var n = colors.length,\n r = new Array(n),\n g = new Array(n),\n b = new Array(n),\n i, color;\n for (i = 0; i < n; ++i) {\n color = colorRgb(colors[i]);\n r[i] = color.r || 0;\n g[i] = color.g || 0;\n b[i] = color.b || 0;\n }\n r = spline(r);\n g = spline(g);\n b = spline(b);\n color.opacity = 1;\n return function(t) {\n color.r = r(t);\n color.g = g(t);\n color.b = b(t);\n return color + \"\";\n };\n };\n}\n\nexport var rgbBasis = rgbSpline(basis);\nexport var rgbBasisClosed = rgbSpline(basisClosed);\n","export default function(a, b) {\n if (!b) b = [];\n var n = a ? Math.min(b.length, a.length) : 0,\n c = b.slice(),\n i;\n return function(t) {\n for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;\n return c;\n };\n}\n\nexport function isNumberArray(x) {\n return ArrayBuffer.isView(x) && !(x instanceof DataView);\n}\n","import value from \"./value.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n return (isNumberArray(b) ? numberArray : genericArray)(a, b);\n}\n\nexport function genericArray(a, b) {\n var nb = b ? b.length : 0,\n na = a ? Math.min(nb, a.length) : 0,\n x = new Array(na),\n c = new Array(nb),\n i;\n\n for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);\n for (; i < nb; ++i) c[i] = b[i];\n\n return function(t) {\n for (i = 0; i < na; ++i) c[i] = x[i](t);\n return c;\n };\n}\n","export default function(a, b) {\n var d = new Date;\n return a = +a, b = +b, function(t) {\n return d.setTime(a * (1 - t) + b * t), d;\n };\n}\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return a * (1 - t) + b * t;\n };\n}\n","import value from \"./value.js\";\n\nexport default function(a, b) {\n var i = {},\n c = {},\n k;\n\n if (a === null || typeof a !== \"object\") a = {};\n if (b === null || typeof b !== \"object\") b = {};\n\n for (k in b) {\n if (k in a) {\n i[k] = value(a[k], b[k]);\n } else {\n c[k] = b[k];\n }\n }\n\n return function(t) {\n for (k in i) c[k] = i[k](t);\n return c;\n };\n}\n","import number from \"./number.js\";\n\nvar reA = /[-+]?(?:\\d+\\.?\\d*|\\.?\\d+)(?:[eE][-+]?\\d+)?/g,\n reB = new RegExp(reA.source, \"g\");\n\nfunction zero(b) {\n return function() {\n return b;\n };\n}\n\nfunction one(b) {\n return function(t) {\n return b(t) + \"\";\n };\n}\n\nexport default function(a, b) {\n var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b\n am, // current match in a\n bm, // current match in b\n bs, // string preceding current number in b, if any\n i = -1, // index in s\n s = [], // string constants and placeholders\n q = []; // number interpolators\n\n // Coerce inputs to strings.\n a = a + \"\", b = b + \"\";\n\n // Interpolate pairs of numbers in a & b.\n while ((am = reA.exec(a))\n && (bm = reB.exec(b))) {\n if ((bs = bm.index) > bi) { // a string precedes the next number in b\n bs = b.slice(bi, bs);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match\n if (s[i]) s[i] += bm; // coalesce with previous string\n else s[++i] = bm;\n } else { // interpolate non-matching numbers\n s[++i] = null;\n q.push({i: i, x: number(am, bm)});\n }\n bi = reB.lastIndex;\n }\n\n // Add remains of b.\n if (bi < b.length) {\n bs = b.slice(bi);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n\n // Special optimization for only a single match.\n // Otherwise, interpolate each of the numbers and rejoin the string.\n return s.length < 2 ? (q[0]\n ? one(q[0].x)\n : zero(b))\n : (b = q.length, function(t) {\n for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);\n return s.join(\"\");\n });\n}\n","import {color} from \"d3-color\";\nimport rgb from \"./rgb.js\";\nimport {genericArray} from \"./array.js\";\nimport date from \"./date.js\";\nimport number from \"./number.js\";\nimport object from \"./object.js\";\nimport string from \"./string.js\";\nimport constant from \"./constant.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n var t = typeof b, c;\n return b == null || t === \"boolean\" ? constant(b)\n : (t === \"number\" ? number\n : t === \"string\" ? ((c = color(b)) ? (b = c, rgb) : string)\n : b instanceof color ? rgb\n : b instanceof Date ? date\n : isNumberArray(b) ? numberArray\n : Array.isArray(b) ? genericArray\n : typeof b.valueOf !== \"function\" && typeof b.toString !== \"function\" || isNaN(b) ? object\n : number)(a, b);\n}\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return Math.round(a * (1 - t) + b * t);\n };\n}\n","export default function number(x) {\n return +x;\n}\n","import {bisect} from \"d3-array\";\nimport {interpolate as interpolateValue, interpolateNumber, interpolateRound} from \"d3-interpolate\";\nimport constant from \"./constant.js\";\nimport number from \"./number.js\";\n\nvar unit = [0, 1];\n\nexport function identity(x) {\n return x;\n}\n\nfunction normalize(a, b) {\n return (b -= (a = +a))\n ? function(x) { return (x - a) / b; }\n : constant(isNaN(b) ? NaN : 0.5);\n}\n\nfunction clamper(a, b) {\n var t;\n if (a > b) t = a, a = b, b = t;\n return function(x) { return Math.max(a, Math.min(b, x)); };\n}\n\n// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].\n// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].\nfunction bimap(domain, range, interpolate) {\n var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];\n if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);\n else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);\n return function(x) { return r0(d0(x)); };\n}\n\nfunction polymap(domain, range, interpolate) {\n var j = Math.min(domain.length, range.length) - 1,\n d = new Array(j),\n r = new Array(j),\n i = -1;\n\n // Reverse descending domains.\n if (domain[j] < domain[0]) {\n domain = domain.slice().reverse();\n range = range.slice().reverse();\n }\n\n while (++i < j) {\n d[i] = normalize(domain[i], domain[i + 1]);\n r[i] = interpolate(range[i], range[i + 1]);\n }\n\n return function(x) {\n var i = bisect(domain, x, 1, j) - 1;\n return r[i](d[i](x));\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .range(source.range())\n .interpolate(source.interpolate())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport function transformer() {\n var domain = unit,\n range = unit,\n interpolate = interpolateValue,\n transform,\n untransform,\n unknown,\n clamp = identity,\n piecewise,\n output,\n input;\n\n function rescale() {\n var n = Math.min(domain.length, range.length);\n if (clamp !== identity) clamp = clamper(domain[0], domain[n - 1]);\n piecewise = n > 2 ? polymap : bimap;\n output = input = null;\n return scale;\n }\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x)));\n }\n\n scale.invert = function(y) {\n return clamp(untransform((input || (input = piecewise(range, domain.map(transform), interpolateNumber)))(y)));\n };\n\n scale.domain = function(_) {\n return arguments.length ? (domain = Array.from(_, number), rescale()) : domain.slice();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), rescale()) : range.slice();\n };\n\n scale.rangeRound = function(_) {\n return range = Array.from(_), interpolate = interpolateRound, rescale();\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = _ ? true : identity, rescale()) : clamp !== identity;\n };\n\n scale.interpolate = function(_) {\n return arguments.length ? (interpolate = _, rescale()) : interpolate;\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t, u) {\n transform = t, untransform = u;\n return rescale();\n };\n}\n\nexport default function continuous() {\n return transformer()(identity, identity);\n}\n","export default function constants(x) {\n return function() {\n return x;\n };\n}\n","import {ticks, tickIncrement} from \"d3-array\";\nimport continuous, {copy} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\nimport tickFormat from \"./tickFormat.js\";\n\nexport function linearish(scale) {\n var domain = scale.domain;\n\n scale.ticks = function(count) {\n var d = domain();\n return ticks(d[0], d[d.length - 1], count == null ? 10 : count);\n };\n\n scale.tickFormat = function(count, specifier) {\n var d = domain();\n return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);\n };\n\n scale.nice = function(count) {\n if (count == null) count = 10;\n\n var d = domain();\n var i0 = 0;\n var i1 = d.length - 1;\n var start = d[i0];\n var stop = d[i1];\n var prestep;\n var step;\n var maxIter = 10;\n\n if (stop < start) {\n step = start, start = stop, stop = step;\n step = i0, i0 = i1, i1 = step;\n }\n \n while (maxIter-- > 0) {\n step = tickIncrement(start, stop, count);\n if (step === prestep) {\n d[i0] = start\n d[i1] = stop\n return domain(d);\n } else if (step > 0) {\n start = Math.floor(start / step) * step;\n stop = Math.ceil(stop / step) * step;\n } else if (step < 0) {\n start = Math.ceil(start * step) / step;\n stop = Math.floor(stop * step) / step;\n } else {\n break;\n }\n prestep = step;\n }\n\n return scale;\n };\n\n return scale;\n}\n\nexport default function linear() {\n var scale = continuous();\n\n scale.copy = function() {\n return copy(scale, linear());\n };\n\n initRange.apply(scale, arguments);\n\n return linearish(scale);\n}\n","export default function nice(domain, interval) {\n domain = domain.slice();\n\n var i0 = 0,\n i1 = domain.length - 1,\n x0 = domain[i0],\n x1 = domain[i1],\n t;\n\n if (x1 < x0) {\n t = i0, i0 = i1, i1 = t;\n t = x0, x0 = x1, x1 = t;\n }\n\n domain[i0] = interval.floor(x0);\n domain[i1] = interval.ceil(x1);\n return domain;\n}\n","import {ticks} from \"d3-array\";\nimport {format} from \"d3-format\";\nimport nice from \"./nice.js\";\nimport {copy, transformer} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\n\nfunction transformLog(x) {\n return Math.log(x);\n}\n\nfunction transformExp(x) {\n return Math.exp(x);\n}\n\nfunction transformLogn(x) {\n return -Math.log(-x);\n}\n\nfunction transformExpn(x) {\n return -Math.exp(-x);\n}\n\nfunction pow10(x) {\n return isFinite(x) ? +(\"1e\" + x) : x < 0 ? 0 : x;\n}\n\nfunction powp(base) {\n return base === 10 ? pow10\n : base === Math.E ? Math.exp\n : function(x) { return Math.pow(base, x); };\n}\n\nfunction logp(base) {\n return base === Math.E ? Math.log\n : base === 10 && Math.log10\n || base === 2 && Math.log2\n || (base = Math.log(base), function(x) { return Math.log(x) / base; });\n}\n\nfunction reflect(f) {\n return function(x) {\n return -f(-x);\n };\n}\n\nexport function loggish(transform) {\n var scale = transform(transformLog, transformExp),\n domain = scale.domain,\n base = 10,\n logs,\n pows;\n\n function rescale() {\n logs = logp(base), pows = powp(base);\n if (domain()[0] < 0) {\n logs = reflect(logs), pows = reflect(pows);\n transform(transformLogn, transformExpn);\n } else {\n transform(transformLog, transformExp);\n }\n return scale;\n }\n\n scale.base = function(_) {\n return arguments.length ? (base = +_, rescale()) : base;\n };\n\n scale.domain = function(_) {\n return arguments.length ? (domain(_), rescale()) : domain();\n };\n\n scale.ticks = function(count) {\n var d = domain(),\n u = d[0],\n v = d[d.length - 1],\n r;\n\n if (r = v < u) i = u, u = v, v = i;\n\n var i = logs(u),\n j = logs(v),\n p,\n k,\n t,\n n = count == null ? 10 : +count,\n z = [];\n\n if (!(base % 1) && j - i < n) {\n i = Math.floor(i), j = Math.ceil(j);\n if (u > 0) for (; i <= j; ++i) {\n for (k = 1, p = pows(i); k < base; ++k) {\n t = p * k;\n if (t < u) continue;\n if (t > v) break;\n z.push(t);\n }\n } else for (; i <= j; ++i) {\n for (k = base - 1, p = pows(i); k >= 1; --k) {\n t = p * k;\n if (t < u) continue;\n if (t > v) break;\n z.push(t);\n }\n }\n if (z.length * 2 < n) z = ticks(u, v, n);\n } else {\n z = ticks(i, j, Math.min(j - i, n)).map(pows);\n }\n\n return r ? z.reverse() : z;\n };\n\n scale.tickFormat = function(count, specifier) {\n if (specifier == null) specifier = base === 10 ? \".0e\" : \",\";\n if (typeof specifier !== \"function\") specifier = format(specifier);\n if (count === Infinity) return specifier;\n if (count == null) count = 10;\n var k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate?\n return function(d) {\n var i = d / pows(Math.round(logs(d)));\n if (i * base < base - 0.5) i *= base;\n return i <= k ? specifier(d) : \"\";\n };\n };\n\n scale.nice = function() {\n return domain(nice(domain(), {\n floor: function(x) { return pows(Math.floor(logs(x))); },\n ceil: function(x) { return pows(Math.ceil(logs(x))); }\n }));\n };\n\n return scale;\n}\n\nexport default function log() {\n var scale = loggish(transformer()).domain([1, 10]);\n\n scale.copy = function() {\n return copy(scale, log()).base(scale.base());\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n","import {linearish} from \"./linear.js\";\nimport {copy, identity, transformer} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\n\nfunction transformPow(exponent) {\n return function(x) {\n return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);\n };\n}\n\nfunction transformSqrt(x) {\n return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);\n}\n\nfunction transformSquare(x) {\n return x < 0 ? -x * x : x * x;\n}\n\nexport function powish(transform) {\n var scale = transform(identity, identity),\n exponent = 1;\n\n function rescale() {\n return exponent === 1 ? transform(identity, identity)\n : exponent === 0.5 ? transform(transformSqrt, transformSquare)\n : transform(transformPow(exponent), transformPow(1 / exponent));\n }\n\n scale.exponent = function(_) {\n return arguments.length ? (exponent = +_, rescale()) : exponent;\n };\n\n return linearish(scale);\n}\n\nexport default function pow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, pow()).exponent(scale.exponent());\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n\nexport function sqrt() {\n return pow.apply(null, arguments).exponent(0.5);\n}\n","import {linearish} from \"./linear.js\";\nimport {copy, transformer} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\n\nfunction transformSymlog(c) {\n return function(x) {\n return Math.sign(x) * Math.log1p(Math.abs(x / c));\n };\n}\n\nfunction transformSymexp(c) {\n return function(x) {\n return Math.sign(x) * Math.expm1(Math.abs(x)) * c;\n };\n}\n\nexport function symlogish(transform) {\n var c = 1, scale = transform(transformSymlog(c), transformSymexp(c));\n\n scale.constant = function(_) {\n return arguments.length ? transform(transformSymlog(c = +_), transformSymexp(c)) : c;\n };\n\n return linearish(scale);\n}\n\nexport default function symlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, symlog()).constant(scale.constant());\n };\n\n return initRange.apply(scale, arguments);\n}\n","export const durationSecond = 1000;\nexport const durationMinute = durationSecond * 60;\nexport const durationHour = durationMinute * 60;\nexport const durationDay = durationHour * 24;\nexport const durationWeek = durationDay * 7;\nexport const durationMonth = durationDay * 30;\nexport const durationYear = durationDay * 365;\n","var t0 = new Date,\n t1 = new Date;\n\nexport default function newInterval(floori, offseti, count, field) {\n\n function interval(date) {\n return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date;\n }\n\n interval.floor = function(date) {\n return floori(date = new Date(+date)), date;\n };\n\n interval.ceil = function(date) {\n return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;\n };\n\n interval.round = function(date) {\n var d0 = interval(date),\n d1 = interval.ceil(date);\n return date - d0 < d1 - date ? d0 : d1;\n };\n\n interval.offset = function(date, step) {\n return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;\n };\n\n interval.range = function(start, stop, step) {\n var range = [], previous;\n start = interval.ceil(start);\n step = step == null ? 1 : Math.floor(step);\n if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date\n do range.push(previous = new Date(+start)), offseti(start, step), floori(start);\n while (previous < start && start < stop);\n return range;\n };\n\n interval.filter = function(test) {\n return newInterval(function(date) {\n if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);\n }, function(date, step) {\n if (date >= date) {\n if (step < 0) while (++step <= 0) {\n while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty\n } else while (--step >= 0) {\n while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty\n }\n }\n });\n };\n\n if (count) {\n interval.count = function(start, end) {\n t0.setTime(+start), t1.setTime(+end);\n floori(t0), floori(t1);\n return Math.floor(count(t0, t1));\n };\n\n interval.every = function(step) {\n step = Math.floor(step);\n return !isFinite(step) || !(step > 0) ? null\n : !(step > 1) ? interval\n : interval.filter(field\n ? function(d) { return field(d) % step === 0; }\n : function(d) { return interval.count(0, d) % step === 0; });\n };\n }\n\n return interval;\n}\n","import interval from \"./interval.js\";\n\nvar millisecond = interval(function() {\n // noop\n}, function(date, step) {\n date.setTime(+date + step);\n}, function(start, end) {\n return end - start;\n});\n\n// An optimized implementation for this simple case.\nmillisecond.every = function(k) {\n k = Math.floor(k);\n if (!isFinite(k) || !(k > 0)) return null;\n if (!(k > 1)) return millisecond;\n return interval(function(date) {\n date.setTime(Math.floor(date / k) * k);\n }, function(date, step) {\n date.setTime(+date + step * k);\n }, function(start, end) {\n return (end - start) / k;\n });\n};\n\nexport default millisecond;\nexport var milliseconds = millisecond.range;\n","import interval from \"./interval.js\";\nimport {durationSecond} from \"./duration.js\";\n\nvar second = interval(function(date) {\n date.setTime(date - date.getMilliseconds());\n}, function(date, step) {\n date.setTime(+date + step * durationSecond);\n}, function(start, end) {\n return (end - start) / durationSecond;\n}, function(date) {\n return date.getUTCSeconds();\n});\n\nexport default second;\nexport var seconds = second.range;\n","import interval from \"./interval.js\";\nimport {durationMinute, durationSecond} from \"./duration.js\";\n\nvar minute = interval(function(date) {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond);\n}, function(date, step) {\n date.setTime(+date + step * durationMinute);\n}, function(start, end) {\n return (end - start) / durationMinute;\n}, function(date) {\n return date.getMinutes();\n});\n\nexport default minute;\nexport var minutes = minute.range;\n","import interval from \"./interval.js\";\nimport {durationHour, durationMinute, durationSecond} from \"./duration.js\";\n\nvar hour = interval(function(date) {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);\n}, function(date, step) {\n date.setTime(+date + step * durationHour);\n}, function(start, end) {\n return (end - start) / durationHour;\n}, function(date) {\n return date.getHours();\n});\n\nexport default hour;\nexport var hours = hour.range;\n","import interval from \"./interval.js\";\nimport {durationDay, durationMinute} from \"./duration.js\";\n\nvar day = interval(\n date => date.setHours(0, 0, 0, 0),\n (date, step) => date.setDate(date.getDate() + step),\n (start, end) => (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay,\n date => date.getDate() - 1\n);\n\nexport default day;\nexport var days = day.range;\n","import interval from \"./interval.js\";\nimport {durationMinute, durationWeek} from \"./duration.js\";\n\nfunction weekday(i) {\n return interval(function(date) {\n date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);\n date.setHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setDate(date.getDate() + step * 7);\n }, function(start, end) {\n return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;\n });\n}\n\nexport var sunday = weekday(0);\nexport var monday = weekday(1);\nexport var tuesday = weekday(2);\nexport var wednesday = weekday(3);\nexport var thursday = weekday(4);\nexport var friday = weekday(5);\nexport var saturday = weekday(6);\n\nexport var sundays = sunday.range;\nexport var mondays = monday.range;\nexport var tuesdays = tuesday.range;\nexport var wednesdays = wednesday.range;\nexport var thursdays = thursday.range;\nexport var fridays = friday.range;\nexport var saturdays = saturday.range;\n","import interval from \"./interval.js\";\n\nvar month = interval(function(date) {\n date.setDate(1);\n date.setHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setMonth(date.getMonth() + step);\n}, function(start, end) {\n return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;\n}, function(date) {\n return date.getMonth();\n});\n\nexport default month;\nexport var months = month.range;\n","import interval from \"./interval.js\";\n\nvar year = interval(function(date) {\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setFullYear(date.getFullYear() + step);\n}, function(start, end) {\n return end.getFullYear() - start.getFullYear();\n}, function(date) {\n return date.getFullYear();\n});\n\n// An optimized implementation for this simple case.\nyear.every = function(k) {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : interval(function(date) {\n date.setFullYear(Math.floor(date.getFullYear() / k) * k);\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setFullYear(date.getFullYear() + step * k);\n });\n};\n\nexport default year;\nexport var years = year.range;\n","import interval from \"./interval.js\";\nimport {durationMinute} from \"./duration.js\";\n\nvar utcMinute = interval(function(date) {\n date.setUTCSeconds(0, 0);\n}, function(date, step) {\n date.setTime(+date + step * durationMinute);\n}, function(start, end) {\n return (end - start) / durationMinute;\n}, function(date) {\n return date.getUTCMinutes();\n});\n\nexport default utcMinute;\nexport var utcMinutes = utcMinute.range;\n","import interval from \"./interval.js\";\nimport {durationHour} from \"./duration.js\";\n\nvar utcHour = interval(function(date) {\n date.setUTCMinutes(0, 0, 0);\n}, function(date, step) {\n date.setTime(+date + step * durationHour);\n}, function(start, end) {\n return (end - start) / durationHour;\n}, function(date) {\n return date.getUTCHours();\n});\n\nexport default utcHour;\nexport var utcHours = utcHour.range;\n","import interval from \"./interval.js\";\nimport {durationDay} from \"./duration.js\";\n\nvar utcDay = interval(function(date) {\n date.setUTCHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setUTCDate(date.getUTCDate() + step);\n}, function(start, end) {\n return (end - start) / durationDay;\n}, function(date) {\n return date.getUTCDate() - 1;\n});\n\nexport default utcDay;\nexport var utcDays = utcDay.range;\n","import interval from \"./interval.js\";\nimport {durationWeek} from \"./duration.js\";\n\nfunction utcWeekday(i) {\n return interval(function(date) {\n date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);\n date.setUTCHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setUTCDate(date.getUTCDate() + step * 7);\n }, function(start, end) {\n return (end - start) / durationWeek;\n });\n}\n\nexport var utcSunday = utcWeekday(0);\nexport var utcMonday = utcWeekday(1);\nexport var utcTuesday = utcWeekday(2);\nexport var utcWednesday = utcWeekday(3);\nexport var utcThursday = utcWeekday(4);\nexport var utcFriday = utcWeekday(5);\nexport var utcSaturday = utcWeekday(6);\n\nexport var utcSundays = utcSunday.range;\nexport var utcMondays = utcMonday.range;\nexport var utcTuesdays = utcTuesday.range;\nexport var utcWednesdays = utcWednesday.range;\nexport var utcThursdays = utcThursday.range;\nexport var utcFridays = utcFriday.range;\nexport var utcSaturdays = utcSaturday.range;\n","import interval from \"./interval.js\";\n\nvar utcMonth = interval(function(date) {\n date.setUTCDate(1);\n date.setUTCHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setUTCMonth(date.getUTCMonth() + step);\n}, function(start, end) {\n return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;\n}, function(date) {\n return date.getUTCMonth();\n});\n\nexport default utcMonth;\nexport var utcMonths = utcMonth.range;\n","import interval from \"./interval.js\";\n\nvar utcYear = interval(function(date) {\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setUTCFullYear(date.getUTCFullYear() + step);\n}, function(start, end) {\n return end.getUTCFullYear() - start.getUTCFullYear();\n}, function(date) {\n return date.getUTCFullYear();\n});\n\n// An optimized implementation for this simple case.\nutcYear.every = function(k) {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : interval(function(date) {\n date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setUTCFullYear(date.getUTCFullYear() + step * k);\n });\n};\n\nexport default utcYear;\nexport var utcYears = utcYear.range;\n","import {bisector, tickStep} from \"d3-array\";\nimport {durationDay, durationHour, durationMinute, durationMonth, durationSecond, durationWeek, durationYear} from \"./duration.js\";\nimport millisecond from \"./millisecond.js\";\nimport second from \"./second.js\";\nimport minute from \"./minute.js\";\nimport hour from \"./hour.js\";\nimport day from \"./day.js\";\nimport {sunday as week} from \"./week.js\";\nimport month from \"./month.js\";\nimport year from \"./year.js\";\nimport utcMinute from \"./utcMinute.js\";\nimport utcHour from \"./utcHour.js\";\nimport utcDay from \"./utcDay.js\";\nimport {utcSunday as utcWeek} from \"./utcWeek.js\";\nimport utcMonth from \"./utcMonth.js\";\nimport utcYear from \"./utcYear.js\";\n\nfunction ticker(year, month, week, day, hour, minute) {\n\n const tickIntervals = [\n [second, 1, durationSecond],\n [second, 5, 5 * durationSecond],\n [second, 15, 15 * durationSecond],\n [second, 30, 30 * durationSecond],\n [minute, 1, durationMinute],\n [minute, 5, 5 * durationMinute],\n [minute, 15, 15 * durationMinute],\n [minute, 30, 30 * durationMinute],\n [ hour, 1, durationHour ],\n [ hour, 3, 3 * durationHour ],\n [ hour, 6, 6 * durationHour ],\n [ hour, 12, 12 * durationHour ],\n [ day, 1, durationDay ],\n [ day, 2, 2 * durationDay ],\n [ week, 1, durationWeek ],\n [ month, 1, durationMonth ],\n [ month, 3, 3 * durationMonth ],\n [ year, 1, durationYear ]\n ];\n\n function ticks(start, stop, count) {\n const reverse = stop < start;\n if (reverse) [start, stop] = [stop, start];\n const interval = count && typeof count.range === \"function\" ? count : tickInterval(start, stop, count);\n const ticks = interval ? interval.range(start, +stop + 1) : []; // inclusive stop\n return reverse ? ticks.reverse() : ticks;\n }\n\n function tickInterval(start, stop, count) {\n const target = Math.abs(stop - start) / count;\n const i = bisector(([,, step]) => step).right(tickIntervals, target);\n if (i === tickIntervals.length) return year.every(tickStep(start / durationYear, stop / durationYear, count));\n if (i === 0) return millisecond.every(Math.max(tickStep(start, stop, count), 1));\n const [t, step] = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];\n return t.every(step);\n }\n\n return [ticks, tickInterval];\n}\n\nconst [utcTicks, utcTickInterval] = ticker(utcYear, utcMonth, utcWeek, utcDay, utcHour, utcMinute);\nconst [timeTicks, timeTickInterval] = ticker(year, month, week, day, hour, minute);\n\nexport {utcTicks, utcTickInterval, timeTicks, timeTickInterval};\n","import {\n timeDay,\n timeSunday,\n timeMonday,\n timeThursday,\n timeYear,\n utcDay,\n utcSunday,\n utcMonday,\n utcThursday,\n utcYear\n} from \"d3-time\";\n\nfunction localDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);\n date.setFullYear(d.y);\n return date;\n }\n return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);\n}\n\nfunction utcDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));\n date.setUTCFullYear(d.y);\n return date;\n }\n return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));\n}\n\nfunction newDate(y, m, d) {\n return {y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0};\n}\n\nexport default function formatLocale(locale) {\n var locale_dateTime = locale.dateTime,\n locale_date = locale.date,\n locale_time = locale.time,\n locale_periods = locale.periods,\n locale_weekdays = locale.days,\n locale_shortWeekdays = locale.shortDays,\n locale_months = locale.months,\n locale_shortMonths = locale.shortMonths;\n\n var periodRe = formatRe(locale_periods),\n periodLookup = formatLookup(locale_periods),\n weekdayRe = formatRe(locale_weekdays),\n weekdayLookup = formatLookup(locale_weekdays),\n shortWeekdayRe = formatRe(locale_shortWeekdays),\n shortWeekdayLookup = formatLookup(locale_shortWeekdays),\n monthRe = formatRe(locale_months),\n monthLookup = formatLookup(locale_months),\n shortMonthRe = formatRe(locale_shortMonths),\n shortMonthLookup = formatLookup(locale_shortMonths);\n\n var formats = {\n \"a\": formatShortWeekday,\n \"A\": formatWeekday,\n \"b\": formatShortMonth,\n \"B\": formatMonth,\n \"c\": null,\n \"d\": formatDayOfMonth,\n \"e\": formatDayOfMonth,\n \"f\": formatMicroseconds,\n \"H\": formatHour24,\n \"I\": formatHour12,\n \"j\": formatDayOfYear,\n \"L\": formatMilliseconds,\n \"m\": formatMonthNumber,\n \"M\": formatMinutes,\n \"p\": formatPeriod,\n \"q\": formatQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatSeconds,\n \"u\": formatWeekdayNumberMonday,\n \"U\": formatWeekNumberSunday,\n \"V\": formatWeekNumberISO,\n \"w\": formatWeekdayNumberSunday,\n \"W\": formatWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatYear,\n \"Y\": formatFullYear,\n \"Z\": formatZone,\n \"%\": formatLiteralPercent\n };\n\n var utcFormats = {\n \"a\": formatUTCShortWeekday,\n \"A\": formatUTCWeekday,\n \"b\": formatUTCShortMonth,\n \"B\": formatUTCMonth,\n \"c\": null,\n \"d\": formatUTCDayOfMonth,\n \"e\": formatUTCDayOfMonth,\n \"f\": formatUTCMicroseconds,\n \"H\": formatUTCHour24,\n \"I\": formatUTCHour12,\n \"j\": formatUTCDayOfYear,\n \"L\": formatUTCMilliseconds,\n \"m\": formatUTCMonthNumber,\n \"M\": formatUTCMinutes,\n \"p\": formatUTCPeriod,\n \"q\": formatUTCQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatUTCSeconds,\n \"u\": formatUTCWeekdayNumberMonday,\n \"U\": formatUTCWeekNumberSunday,\n \"V\": formatUTCWeekNumberISO,\n \"w\": formatUTCWeekdayNumberSunday,\n \"W\": formatUTCWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatUTCYear,\n \"Y\": formatUTCFullYear,\n \"Z\": formatUTCZone,\n \"%\": formatLiteralPercent\n };\n\n var parses = {\n \"a\": parseShortWeekday,\n \"A\": parseWeekday,\n \"b\": parseShortMonth,\n \"B\": parseMonth,\n \"c\": parseLocaleDateTime,\n \"d\": parseDayOfMonth,\n \"e\": parseDayOfMonth,\n \"f\": parseMicroseconds,\n \"H\": parseHour24,\n \"I\": parseHour24,\n \"j\": parseDayOfYear,\n \"L\": parseMilliseconds,\n \"m\": parseMonthNumber,\n \"M\": parseMinutes,\n \"p\": parsePeriod,\n \"q\": parseQuarter,\n \"Q\": parseUnixTimestamp,\n \"s\": parseUnixTimestampSeconds,\n \"S\": parseSeconds,\n \"u\": parseWeekdayNumberMonday,\n \"U\": parseWeekNumberSunday,\n \"V\": parseWeekNumberISO,\n \"w\": parseWeekdayNumberSunday,\n \"W\": parseWeekNumberMonday,\n \"x\": parseLocaleDate,\n \"X\": parseLocaleTime,\n \"y\": parseYear,\n \"Y\": parseFullYear,\n \"Z\": parseZone,\n \"%\": parseLiteralPercent\n };\n\n // These recursive directive definitions must be deferred.\n formats.x = newFormat(locale_date, formats);\n formats.X = newFormat(locale_time, formats);\n formats.c = newFormat(locale_dateTime, formats);\n utcFormats.x = newFormat(locale_date, utcFormats);\n utcFormats.X = newFormat(locale_time, utcFormats);\n utcFormats.c = newFormat(locale_dateTime, utcFormats);\n\n function newFormat(specifier, formats) {\n return function(date) {\n var string = [],\n i = -1,\n j = 0,\n n = specifier.length,\n c,\n pad,\n format;\n\n if (!(date instanceof Date)) date = new Date(+date);\n\n while (++i < n) {\n if (specifier.charCodeAt(i) === 37) {\n string.push(specifier.slice(j, i));\n if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);\n else pad = c === \"e\" ? \" \" : \"0\";\n if (format = formats[c]) c = format(date, pad);\n string.push(c);\n j = i + 1;\n }\n }\n\n string.push(specifier.slice(j, i));\n return string.join(\"\");\n };\n }\n\n function newParse(specifier, Z) {\n return function(string) {\n var d = newDate(1900, undefined, 1),\n i = parseSpecifier(d, specifier, string += \"\", 0),\n week, day;\n if (i != string.length) return null;\n\n // If a UNIX timestamp is specified, return it.\n if (\"Q\" in d) return new Date(d.Q);\n if (\"s\" in d) return new Date(d.s * 1000 + (\"L\" in d ? d.L : 0));\n\n // If this is utcParse, never use the local timezone.\n if (Z && !(\"Z\" in d)) d.Z = 0;\n\n // The am-pm flag is 0 for AM, and 1 for PM.\n if (\"p\" in d) d.H = d.H % 12 + d.p * 12;\n\n // If the month was not specified, inherit from the quarter.\n if (d.m === undefined) d.m = \"q\" in d ? d.q : 0;\n\n // Convert day-of-week and week-of-year to day-of-year.\n if (\"V\" in d) {\n if (d.V < 1 || d.V > 53) return null;\n if (!(\"w\" in d)) d.w = 1;\n if (\"Z\" in d) {\n week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay();\n week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week);\n week = utcDay.offset(week, (d.V - 1) * 7);\n d.y = week.getUTCFullYear();\n d.m = week.getUTCMonth();\n d.d = week.getUTCDate() + (d.w + 6) % 7;\n } else {\n week = localDate(newDate(d.y, 0, 1)), day = week.getDay();\n week = day > 4 || day === 0 ? timeMonday.ceil(week) : timeMonday(week);\n week = timeDay.offset(week, (d.V - 1) * 7);\n d.y = week.getFullYear();\n d.m = week.getMonth();\n d.d = week.getDate() + (d.w + 6) % 7;\n }\n } else if (\"W\" in d || \"U\" in d) {\n if (!(\"w\" in d)) d.w = \"u\" in d ? d.u % 7 : \"W\" in d ? 1 : 0;\n day = \"Z\" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();\n d.m = 0;\n d.d = \"W\" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;\n }\n\n // If a time zone is specified, all fields are interpreted as UTC and then\n // offset according to the specified time zone.\n if (\"Z\" in d) {\n d.H += d.Z / 100 | 0;\n d.M += d.Z % 100;\n return utcDate(d);\n }\n\n // Otherwise, all fields are in local time.\n return localDate(d);\n };\n }\n\n function parseSpecifier(d, specifier, string, j) {\n var i = 0,\n n = specifier.length,\n m = string.length,\n c,\n parse;\n\n while (i < n) {\n if (j >= m) return -1;\n c = specifier.charCodeAt(i++);\n if (c === 37) {\n c = specifier.charAt(i++);\n parse = parses[c in pads ? specifier.charAt(i++) : c];\n if (!parse || ((j = parse(d, string, j)) < 0)) return -1;\n } else if (c != string.charCodeAt(j++)) {\n return -1;\n }\n }\n\n return j;\n }\n\n function parsePeriod(d, string, i) {\n var n = periodRe.exec(string.slice(i));\n return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseShortWeekday(d, string, i) {\n var n = shortWeekdayRe.exec(string.slice(i));\n return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseWeekday(d, string, i) {\n var n = weekdayRe.exec(string.slice(i));\n return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseShortMonth(d, string, i) {\n var n = shortMonthRe.exec(string.slice(i));\n return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseMonth(d, string, i) {\n var n = monthRe.exec(string.slice(i));\n return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseLocaleDateTime(d, string, i) {\n return parseSpecifier(d, locale_dateTime, string, i);\n }\n\n function parseLocaleDate(d, string, i) {\n return parseSpecifier(d, locale_date, string, i);\n }\n\n function parseLocaleTime(d, string, i) {\n return parseSpecifier(d, locale_time, string, i);\n }\n\n function formatShortWeekday(d) {\n return locale_shortWeekdays[d.getDay()];\n }\n\n function formatWeekday(d) {\n return locale_weekdays[d.getDay()];\n }\n\n function formatShortMonth(d) {\n return locale_shortMonths[d.getMonth()];\n }\n\n function formatMonth(d) {\n return locale_months[d.getMonth()];\n }\n\n function formatPeriod(d) {\n return locale_periods[+(d.getHours() >= 12)];\n }\n\n function formatQuarter(d) {\n return 1 + ~~(d.getMonth() / 3);\n }\n\n function formatUTCShortWeekday(d) {\n return locale_shortWeekdays[d.getUTCDay()];\n }\n\n function formatUTCWeekday(d) {\n return locale_weekdays[d.getUTCDay()];\n }\n\n function formatUTCShortMonth(d) {\n return locale_shortMonths[d.getUTCMonth()];\n }\n\n function formatUTCMonth(d) {\n return locale_months[d.getUTCMonth()];\n }\n\n function formatUTCPeriod(d) {\n return locale_periods[+(d.getUTCHours() >= 12)];\n }\n\n function formatUTCQuarter(d) {\n return 1 + ~~(d.getUTCMonth() / 3);\n }\n\n return {\n format: function(specifier) {\n var f = newFormat(specifier += \"\", formats);\n f.toString = function() { return specifier; };\n return f;\n },\n parse: function(specifier) {\n var p = newParse(specifier += \"\", false);\n p.toString = function() { return specifier; };\n return p;\n },\n utcFormat: function(specifier) {\n var f = newFormat(specifier += \"\", utcFormats);\n f.toString = function() { return specifier; };\n return f;\n },\n utcParse: function(specifier) {\n var p = newParse(specifier += \"\", true);\n p.toString = function() { return specifier; };\n return p;\n }\n };\n}\n\nvar pads = {\"-\": \"\", \"_\": \" \", \"0\": \"0\"},\n numberRe = /^\\s*\\d+/, // note: ignores next directive\n percentRe = /^%/,\n requoteRe = /[\\\\^$*+?|[\\]().{}]/g;\n\nfunction pad(value, fill, width) {\n var sign = value < 0 ? \"-\" : \"\",\n string = (sign ? -value : value) + \"\",\n length = string.length;\n return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);\n}\n\nfunction requote(s) {\n return s.replace(requoteRe, \"\\\\$&\");\n}\n\nfunction formatRe(names) {\n return new RegExp(\"^(?:\" + names.map(requote).join(\"|\") + \")\", \"i\");\n}\n\nfunction formatLookup(names) {\n var map = {}, i = -1, n = names.length;\n while (++i < n) map[names[i].toLowerCase()] = i;\n return map;\n}\n\nfunction parseWeekdayNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.w = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekdayNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.u = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.U = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberISO(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.V = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.W = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseFullYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 4));\n return n ? (d.y = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;\n}\n\nfunction parseZone(d, string, i) {\n var n = /^(Z)|([+-]\\d\\d)(?::?(\\d\\d))?/.exec(string.slice(i, i + 6));\n return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || \"00\")), i + n[0].length) : -1;\n}\n\nfunction parseQuarter(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;\n}\n\nfunction parseMonthNumber(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.m = n[0] - 1, i + n[0].length) : -1;\n}\n\nfunction parseDayOfMonth(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseDayOfYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseHour24(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.H = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMinutes(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.M = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.S = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMilliseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.L = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMicroseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 6));\n return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;\n}\n\nfunction parseLiteralPercent(d, string, i) {\n var n = percentRe.exec(string.slice(i, i + 1));\n return n ? i + n[0].length : -1;\n}\n\nfunction parseUnixTimestamp(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.Q = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseUnixTimestampSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.s = +n[0], i + n[0].length) : -1;\n}\n\nfunction formatDayOfMonth(d, p) {\n return pad(d.getDate(), p, 2);\n}\n\nfunction formatHour24(d, p) {\n return pad(d.getHours(), p, 2);\n}\n\nfunction formatHour12(d, p) {\n return pad(d.getHours() % 12 || 12, p, 2);\n}\n\nfunction formatDayOfYear(d, p) {\n return pad(1 + timeDay.count(timeYear(d), d), p, 3);\n}\n\nfunction formatMilliseconds(d, p) {\n return pad(d.getMilliseconds(), p, 3);\n}\n\nfunction formatMicroseconds(d, p) {\n return formatMilliseconds(d, p) + \"000\";\n}\n\nfunction formatMonthNumber(d, p) {\n return pad(d.getMonth() + 1, p, 2);\n}\n\nfunction formatMinutes(d, p) {\n return pad(d.getMinutes(), p, 2);\n}\n\nfunction formatSeconds(d, p) {\n return pad(d.getSeconds(), p, 2);\n}\n\nfunction formatWeekdayNumberMonday(d) {\n var day = d.getDay();\n return day === 0 ? 7 : day;\n}\n\nfunction formatWeekNumberSunday(d, p) {\n return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction formatWeekNumberISO(d, p) {\n var day = d.getDay();\n d = (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);\n}\n\nfunction formatWeekdayNumberSunday(d) {\n return d.getDay();\n}\n\nfunction formatWeekNumberMonday(d, p) {\n return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction formatYear(d, p) {\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatFullYear(d, p) {\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatZone(d) {\n var z = d.getTimezoneOffset();\n return (z > 0 ? \"-\" : (z *= -1, \"+\"))\n + pad(z / 60 | 0, \"0\", 2)\n + pad(z % 60, \"0\", 2);\n}\n\nfunction formatUTCDayOfMonth(d, p) {\n return pad(d.getUTCDate(), p, 2);\n}\n\nfunction formatUTCHour24(d, p) {\n return pad(d.getUTCHours(), p, 2);\n}\n\nfunction formatUTCHour12(d, p) {\n return pad(d.getUTCHours() % 12 || 12, p, 2);\n}\n\nfunction formatUTCDayOfYear(d, p) {\n return pad(1 + utcDay.count(utcYear(d), d), p, 3);\n}\n\nfunction formatUTCMilliseconds(d, p) {\n return pad(d.getUTCMilliseconds(), p, 3);\n}\n\nfunction formatUTCMicroseconds(d, p) {\n return formatUTCMilliseconds(d, p) + \"000\";\n}\n\nfunction formatUTCMonthNumber(d, p) {\n return pad(d.getUTCMonth() + 1, p, 2);\n}\n\nfunction formatUTCMinutes(d, p) {\n return pad(d.getUTCMinutes(), p, 2);\n}\n\nfunction formatUTCSeconds(d, p) {\n return pad(d.getUTCSeconds(), p, 2);\n}\n\nfunction formatUTCWeekdayNumberMonday(d) {\n var dow = d.getUTCDay();\n return dow === 0 ? 7 : dow;\n}\n\nfunction formatUTCWeekNumberSunday(d, p) {\n return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction formatUTCWeekNumberISO(d, p) {\n var day = d.getUTCDay();\n d = (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);\n}\n\nfunction formatUTCWeekdayNumberSunday(d) {\n return d.getUTCDay();\n}\n\nfunction formatUTCWeekNumberMonday(d, p) {\n return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction formatUTCYear(d, p) {\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCFullYear(d, p) {\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCZone() {\n return \"+0000\";\n}\n\nfunction formatLiteralPercent() {\n return \"%\";\n}\n\nfunction formatUnixTimestamp(d) {\n return +d;\n}\n\nfunction formatUnixTimestampSeconds(d) {\n return Math.floor(+d / 1000);\n}\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var timeFormat;\nexport var timeParse;\nexport var utcFormat;\nexport var utcParse;\n\ndefaultLocale({\n dateTime: \"%x, %X\",\n date: \"%-m/%-d/%Y\",\n time: \"%-I:%M:%S %p\",\n periods: [\"AM\", \"PM\"],\n days: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n shortDays: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n months: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n shortMonths: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n timeFormat = locale.format;\n timeParse = locale.parse;\n utcFormat = locale.utcFormat;\n utcParse = locale.utcParse;\n return locale;\n}\n","import {timeYear, timeMonth, timeWeek, timeDay, timeHour, timeMinute, timeSecond, timeTicks, timeTickInterval} from \"d3-time\";\nimport {timeFormat} from \"d3-time-format\";\nimport continuous, {copy} from \"./continuous.js\";\nimport {initRange} from \"./init.js\";\nimport nice from \"./nice.js\";\n\nfunction date(t) {\n return new Date(t);\n}\n\nfunction number(t) {\n return t instanceof Date ? +t : +new Date(+t);\n}\n\nexport function calendar(ticks, tickInterval, year, month, week, day, hour, minute, second, format) {\n var scale = continuous(),\n invert = scale.invert,\n domain = scale.domain;\n\n var formatMillisecond = format(\".%L\"),\n formatSecond = format(\":%S\"),\n formatMinute = format(\"%I:%M\"),\n formatHour = format(\"%I %p\"),\n formatDay = format(\"%a %d\"),\n formatWeek = format(\"%b %d\"),\n formatMonth = format(\"%B\"),\n formatYear = format(\"%Y\");\n\n function tickFormat(date) {\n return (second(date) < date ? formatMillisecond\n : minute(date) < date ? formatSecond\n : hour(date) < date ? formatMinute\n : day(date) < date ? formatHour\n : month(date) < date ? (week(date) < date ? formatDay : formatWeek)\n : year(date) < date ? formatMonth\n : formatYear)(date);\n }\n\n scale.invert = function(y) {\n return new Date(invert(y));\n };\n\n scale.domain = function(_) {\n return arguments.length ? domain(Array.from(_, number)) : domain().map(date);\n };\n\n scale.ticks = function(interval) {\n var d = domain();\n return ticks(d[0], d[d.length - 1], interval == null ? 10 : interval);\n };\n\n scale.tickFormat = function(count, specifier) {\n return specifier == null ? tickFormat : format(specifier);\n };\n\n scale.nice = function(interval) {\n var d = domain();\n if (!interval || typeof interval.range !== \"function\") interval = tickInterval(d[0], d[d.length - 1], interval == null ? 10 : interval);\n return interval ? domain(nice(d, interval)) : scale;\n };\n\n scale.copy = function() {\n return copy(scale, calendar(ticks, tickInterval, year, month, week, day, hour, minute, second, format));\n };\n\n return scale;\n}\n\nexport default function time() {\n return initRange.apply(calendar(timeTicks, timeTickInterval, timeYear, timeMonth, timeWeek, timeDay, timeHour, timeMinute, timeSecond, timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]), arguments);\n}\n","import {interpolate, interpolateRound} from \"d3-interpolate\";\nimport {identity} from \"./continuous.js\";\nimport {initInterpolator} from \"./init.js\";\nimport {linearish} from \"./linear.js\";\nimport {loggish} from \"./log.js\";\nimport {symlogish} from \"./symlog.js\";\nimport {powish} from \"./pow.js\";\n\nfunction transformer() {\n var x0 = 0,\n x1 = 1,\n t0,\n t1,\n k10,\n transform,\n interpolator = identity,\n clamp = false,\n unknown;\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : interpolator(k10 === 0 ? 0.5 : (x = (transform(x) - t0) * k10, clamp ? Math.max(0, Math.min(1, x)) : x));\n }\n\n scale.domain = function(_) {\n return arguments.length ? ([x0, x1] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale) : [x0, x1];\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = !!_, scale) : clamp;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n function range(interpolate) {\n return function(_) {\n var r0, r1;\n return arguments.length ? ([r0, r1] = _, interpolator = interpolate(r0, r1), scale) : [interpolator(0), interpolator(1)];\n };\n }\n\n scale.range = range(interpolate);\n\n scale.rangeRound = range(interpolateRound);\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t) {\n transform = t, t0 = t(x0), t1 = t(x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0);\n return scale;\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .interpolator(source.interpolator())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport default function sequential() {\n var scale = linearish(transformer()(identity));\n\n scale.copy = function() {\n return copy(scale, sequential());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialLog() {\n var scale = loggish(transformer()).domain([1, 10]);\n\n scale.copy = function() {\n return copy(scale, sequentialLog()).base(scale.base());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSymlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialSymlog()).constant(scale.constant());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialPow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialPow()).exponent(scale.exponent());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSqrt() {\n return sequentialPow.apply(null, arguments).exponent(0.5);\n}\n","import {default as value} from \"./value.js\";\n\nexport default function piecewise(interpolate, values) {\n if (values === undefined) values = interpolate, interpolate = value;\n var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);\n while (i < n) I[i] = interpolate(v, v = values[++i]);\n return function(t) {\n var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));\n return I[i](t - i);\n };\n}\n","import {interpolate, interpolateRound, piecewise} from \"d3-interpolate\";\nimport {identity} from \"./continuous.js\";\nimport {initInterpolator} from \"./init.js\";\nimport {linearish} from \"./linear.js\";\nimport {loggish} from \"./log.js\";\nimport {copy} from \"./sequential.js\";\nimport {symlogish} from \"./symlog.js\";\nimport {powish} from \"./pow.js\";\n\nfunction transformer() {\n var x0 = 0,\n x1 = 0.5,\n x2 = 1,\n s = 1,\n t0,\n t1,\n t2,\n k10,\n k21,\n interpolator = identity,\n transform,\n clamp = false,\n unknown;\n\n function scale(x) {\n return isNaN(x = +x) ? unknown : (x = 0.5 + ((x = +transform(x)) - t1) * (s * x < s * t1 ? k10 : k21), interpolator(clamp ? Math.max(0, Math.min(1, x)) : x));\n }\n\n scale.domain = function(_) {\n return arguments.length ? ([x0, x1, x2] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), t2 = transform(x2 = +x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1, scale) : [x0, x1, x2];\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = !!_, scale) : clamp;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n function range(interpolate) {\n return function(_) {\n var r0, r1, r2;\n return arguments.length ? ([r0, r1, r2] = _, interpolator = piecewise(interpolate, [r0, r1, r2]), scale) : [interpolator(0), interpolator(0.5), interpolator(1)];\n };\n }\n\n scale.range = range(interpolate);\n\n scale.rangeRound = range(interpolateRound);\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t) {\n transform = t, t0 = t(x0), t1 = t(x1), t2 = t(x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1;\n return scale;\n };\n}\n\nexport default function diverging() {\n var scale = linearish(transformer()(identity));\n\n scale.copy = function() {\n return copy(scale, diverging());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingLog() {\n var scale = loggish(transformer()).domain([0.1, 1, 10]);\n\n scale.copy = function() {\n return copy(scale, divergingLog()).base(scale.base());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingSymlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, divergingSymlog()).constant(scale.constant());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingPow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, divergingPow()).exponent(scale.exponent());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingSqrt() {\n return divergingPow.apply(null, arguments).exponent(0.5);\n}\n","import max from \"./max.js\";\nimport min from \"./min.js\";\nimport quickselect from \"./quickselect.js\";\nimport number, {numbers} from \"./number.js\";\n\nexport default function quantile(values, p, valueof) {\n values = Float64Array.from(numbers(values, valueof));\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return min(values);\n if (p >= 1) return max(values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = max(quickselect(values, i0).subarray(0, i0 + 1)),\n value1 = min(values.subarray(i0 + 1));\n return value0 + (value1 - value0) * (i - i0);\n}\n\nexport function quantileSorted(values, p, valueof = number) {\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);\n if (p >= 1) return +valueof(values[n - 1], n - 1, values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = +valueof(values[i0], i0, values),\n value1 = +valueof(values[i0 + 1], i0 + 1, values);\n return value0 + (value1 - value0) * (i - i0);\n}\n","export default function(range) {\n var n = range.length;\n return function(t) {\n return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];\n };\n}\n","import decompose, {identity} from \"./decompose.js\";\n\nvar svgNode;\n\n/* eslint-disable no-undef */\nexport function parseCss(value) {\n const m = new (typeof DOMMatrix === \"function\" ? DOMMatrix : WebKitCSSMatrix)(value + \"\");\n return m.isIdentity ? identity : decompose(m.a, m.b, m.c, m.d, m.e, m.f);\n}\n\nexport function parseSvg(value) {\n if (value == null) return identity;\n if (!svgNode) svgNode = document.createElementNS(\"http://www.w3.org/2000/svg\", \"g\");\n svgNode.setAttribute(\"transform\", value);\n if (!(value = svgNode.transform.baseVal.consolidate())) return identity;\n value = value.matrix;\n return decompose(value.a, value.b, value.c, value.d, value.e, value.f);\n}\n","import {hue} from \"./color.js\";\n\nexport default function(a, b) {\n var i = hue(+a, +b);\n return function(t) {\n var x = i(t);\n return x - 360 * Math.floor(x / 360);\n };\n}\n","var degrees = 180 / Math.PI;\n\nexport var identity = {\n translateX: 0,\n translateY: 0,\n rotate: 0,\n skewX: 0,\n scaleX: 1,\n scaleY: 1\n};\n\nexport default function(a, b, c, d, e, f) {\n var scaleX, scaleY, skewX;\n if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;\n if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;\n if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;\n if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;\n return {\n translateX: e,\n translateY: f,\n rotate: Math.atan2(b, a) * degrees,\n skewX: Math.atan(skewX) * degrees,\n scaleX: scaleX,\n scaleY: scaleY\n };\n}\n","import number from \"../number.js\";\nimport {parseCss, parseSvg} from \"./parse.js\";\n\nfunction interpolateTransform(parse, pxComma, pxParen, degParen) {\n\n function pop(s) {\n return s.length ? s.pop() + \" \" : \"\";\n }\n\n function translate(xa, ya, xb, yb, s, q) {\n if (xa !== xb || ya !== yb) {\n var i = s.push(\"translate(\", null, pxComma, null, pxParen);\n q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});\n } else if (xb || yb) {\n s.push(\"translate(\" + xb + pxComma + yb + pxParen);\n }\n }\n\n function rotate(a, b, s, q) {\n if (a !== b) {\n if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path\n q.push({i: s.push(pop(s) + \"rotate(\", null, degParen) - 2, x: number(a, b)});\n } else if (b) {\n s.push(pop(s) + \"rotate(\" + b + degParen);\n }\n }\n\n function skewX(a, b, s, q) {\n if (a !== b) {\n q.push({i: s.push(pop(s) + \"skewX(\", null, degParen) - 2, x: number(a, b)});\n } else if (b) {\n s.push(pop(s) + \"skewX(\" + b + degParen);\n }\n }\n\n function scale(xa, ya, xb, yb, s, q) {\n if (xa !== xb || ya !== yb) {\n var i = s.push(pop(s) + \"scale(\", null, \",\", null, \")\");\n q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});\n } else if (xb !== 1 || yb !== 1) {\n s.push(pop(s) + \"scale(\" + xb + \",\" + yb + \")\");\n }\n }\n\n return function(a, b) {\n var s = [], // string constants and placeholders\n q = []; // number interpolators\n a = parse(a), b = parse(b);\n translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);\n rotate(a.rotate, b.rotate, s, q);\n skewX(a.skewX, b.skewX, s, q);\n scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);\n a = b = null; // gc\n return function(t) {\n var i = -1, n = q.length, o;\n while (++i < n) s[(o = q[i]).i] = o.x(t);\n return s.join(\"\");\n };\n };\n}\n\nexport var interpolateTransformCss = interpolateTransform(parseCss, \"px, \", \"px)\", \"deg)\");\nexport var interpolateTransformSvg = interpolateTransform(parseSvg, \", \", \")\", \")\");\n","var epsilon2 = 1e-12;\n\nfunction cosh(x) {\n return ((x = Math.exp(x)) + 1 / x) / 2;\n}\n\nfunction sinh(x) {\n return ((x = Math.exp(x)) - 1 / x) / 2;\n}\n\nfunction tanh(x) {\n return ((x = Math.exp(2 * x)) - 1) / (x + 1);\n}\n\nexport default (function zoomRho(rho, rho2, rho4) {\n\n // p0 = [ux0, uy0, w0]\n // p1 = [ux1, uy1, w1]\n function zoom(p0, p1) {\n var ux0 = p0[0], uy0 = p0[1], w0 = p0[2],\n ux1 = p1[0], uy1 = p1[1], w1 = p1[2],\n dx = ux1 - ux0,\n dy = uy1 - uy0,\n d2 = dx * dx + dy * dy,\n i,\n S;\n\n // Special case for u0 ≅ u1.\n if (d2 < epsilon2) {\n S = Math.log(w1 / w0) / rho;\n i = function(t) {\n return [\n ux0 + t * dx,\n uy0 + t * dy,\n w0 * Math.exp(rho * t * S)\n ];\n }\n }\n\n // General case.\n else {\n var d1 = Math.sqrt(d2),\n b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1),\n b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1),\n r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0),\n r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);\n S = (r1 - r0) / rho;\n i = function(t) {\n var s = t * S,\n coshr0 = cosh(r0),\n u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0));\n return [\n ux0 + u * dx,\n uy0 + u * dy,\n w0 * coshr0 / cosh(rho * s + r0)\n ];\n }\n }\n\n i.duration = S * 1000 * rho / Math.SQRT2;\n\n return i;\n }\n\n zoom.rho = function(_) {\n var _1 = Math.max(1e-3, +_), _2 = _1 * _1, _4 = _2 * _2;\n return zoomRho(_1, _2, _4);\n };\n\n return zoom;\n})(Math.SQRT2, 2, 4);\n","import {hsl as colorHsl} from \"d3-color\";\nimport color, {hue} from \"./color.js\";\n\nfunction hsl(hue) {\n return function(start, end) {\n var h = hue((start = colorHsl(start)).h, (end = colorHsl(end)).h),\n s = color(start.s, end.s),\n l = color(start.l, end.l),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.h = h(t);\n start.s = s(t);\n start.l = l(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n}\n\nexport default hsl(hue);\nexport var hslLong = hsl(color);\n","export var deg2rad = Math.PI / 180;\nexport var rad2deg = 180 / Math.PI;\n","import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb} from \"./color.js\";\nimport {deg2rad, rad2deg} from \"./math.js\";\n\n// https://observablehq.com/@mbostock/lab-and-rgb\nvar K = 18,\n Xn = 0.96422,\n Yn = 1,\n Zn = 0.82521,\n t0 = 4 / 29,\n t1 = 6 / 29,\n t2 = 3 * t1 * t1,\n t3 = t1 * t1 * t1;\n\nfunction labConvert(o) {\n if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);\n if (o instanceof Hcl) return hcl2lab(o);\n if (!(o instanceof Rgb)) o = rgbConvert(o);\n var r = rgb2lrgb(o.r),\n g = rgb2lrgb(o.g),\n b = rgb2lrgb(o.b),\n y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;\n if (r === g && g === b) x = z = y; else {\n x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);\n z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);\n }\n return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);\n}\n\nexport function gray(l, opacity) {\n return new Lab(l, 0, 0, opacity == null ? 1 : opacity);\n}\n\nexport default function lab(l, a, b, opacity) {\n return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);\n}\n\nexport function Lab(l, a, b, opacity) {\n this.l = +l;\n this.a = +a;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Lab, lab, extend(Color, {\n brighter: function(k) {\n return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n darker: function(k) {\n return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n rgb: function() {\n var y = (this.l + 16) / 116,\n x = isNaN(this.a) ? y : y + this.a / 500,\n z = isNaN(this.b) ? y : y - this.b / 200;\n x = Xn * lab2xyz(x);\n y = Yn * lab2xyz(y);\n z = Zn * lab2xyz(z);\n return new Rgb(\n lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),\n lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),\n lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),\n this.opacity\n );\n }\n}));\n\nfunction xyz2lab(t) {\n return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\n\nfunction lab2xyz(t) {\n return t > t1 ? t * t * t : t2 * (t - t0);\n}\n\nfunction lrgb2rgb(x) {\n return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);\n}\n\nfunction rgb2lrgb(x) {\n return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\n\nfunction hclConvert(o) {\n if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);\n if (!(o instanceof Lab)) o = labConvert(o);\n if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);\n var h = Math.atan2(o.b, o.a) * rad2deg;\n return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);\n}\n\nexport function lch(l, c, h, opacity) {\n return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function hcl(h, c, l, opacity) {\n return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function Hcl(h, c, l, opacity) {\n this.h = +h;\n this.c = +c;\n this.l = +l;\n this.opacity = +opacity;\n}\n\nfunction hcl2lab(o) {\n if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);\n var h = o.h * deg2rad;\n return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);\n}\n\ndefine(Hcl, hcl, extend(Color, {\n brighter: function(k) {\n return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);\n },\n darker: function(k) {\n return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);\n },\n rgb: function() {\n return hcl2lab(this).rgb();\n }\n}));\n","import {lab as colorLab} from \"d3-color\";\nimport color from \"./color.js\";\n\nexport default function lab(start, end) {\n var l = color((start = colorLab(start)).l, (end = colorLab(end)).l),\n a = color(start.a, end.a),\n b = color(start.b, end.b),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.l = l(t);\n start.a = a(t);\n start.b = b(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n}\n","import {hcl as colorHcl} from \"d3-color\";\nimport color, {hue} from \"./color.js\";\n\nfunction hcl(hue) {\n return function(start, end) {\n var h = hue((start = colorHcl(start)).h, (end = colorHcl(end)).h),\n c = color(start.c, end.c),\n l = color(start.l, end.l),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.h = h(t);\n start.c = c(t);\n start.l = l(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n}\n\nexport default hcl(hue);\nexport var hclLong = hcl(color);\n","import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb, darker, brighter} from \"./color.js\";\nimport {deg2rad, rad2deg} from \"./math.js\";\n\nvar A = -0.14861,\n B = +1.78277,\n C = -0.29227,\n D = -0.90649,\n E = +1.97294,\n ED = E * D,\n EB = E * B,\n BC_DA = B * C - D * A;\n\nfunction cubehelixConvert(o) {\n if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Rgb)) o = rgbConvert(o);\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),\n bl = b - l,\n k = (E * (g - l) - C * bl) / D,\n s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1\n h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;\n return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);\n}\n\nexport default function cubehelix(h, s, l, opacity) {\n return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);\n}\n\nexport function Cubehelix(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Cubehelix, cubehelix, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Cubehelix(this.h, this.s, this.l * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Cubehelix(this.h, this.s, this.l * k, this.opacity);\n },\n rgb: function() {\n var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,\n l = +this.l,\n a = isNaN(this.s) ? 0 : this.s * l * (1 - l),\n cosh = Math.cos(h),\n sinh = Math.sin(h);\n return new Rgb(\n 255 * (l + a * (A * cosh + B * sinh)),\n 255 * (l + a * (C * cosh + D * sinh)),\n 255 * (l + a * (E * cosh)),\n this.opacity\n );\n }\n}));\n","import {cubehelix as colorCubehelix} from \"d3-color\";\nimport color, {hue} from \"./color.js\";\n\nfunction cubehelix(hue) {\n return (function cubehelixGamma(y) {\n y = +y;\n\n function cubehelix(start, end) {\n var h = hue((start = colorCubehelix(start)).h, (end = colorCubehelix(end)).h),\n s = color(start.s, end.s),\n l = color(start.l, end.l),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.h = h(t);\n start.s = s(t);\n start.l = l(Math.pow(t, y));\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n cubehelix.gamma = cubehelixGamma;\n\n return cubehelix;\n })(1);\n}\n\nexport default cubehelix(hue);\nexport var cubehelixLong = cubehelix(color);\n","export default function(interpolator, n) {\n var samples = new Array(n);\n for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1));\n return samples;\n}\n","import { toNumber, peek, hasOwnProperty, toSet, array, constant, isNumber, span, isObject, isString, error, isArray } from 'vega-util';\nimport { bisectRight, range, bisect } from 'd3-array';\nimport { scaleOrdinal, tickFormat as tickFormat$1, scaleIdentity, scaleLinear, scaleLog, scalePow, scaleSqrt, scaleSymlog, scaleTime, scaleUtc, scaleSequential, scaleSequentialLog, scaleSequentialPow, scaleSequentialSqrt, scaleSequentialSymlog, scaleDiverging, scaleDivergingLog, scaleDivergingPow, scaleDivergingSqrt, scaleDivergingSymlog, scaleQuantile, scaleQuantize, scaleThreshold } from 'd3-scale';\nexport { scaleImplicit } from 'd3-scale';\nimport * as $ from 'd3-interpolate';\nimport { piecewise } from 'd3-interpolate';\nimport { timeInterval, utcInterval } from 'vega-time';\n\nfunction bandSpace (count, paddingInner, paddingOuter) {\n const space = count - paddingInner + paddingOuter * 2;\n return count ? space > 0 ? space : 1 : 0;\n}\n\nconst Identity = 'identity';\nconst Linear = 'linear';\nconst Log = 'log';\nconst Pow = 'pow';\nconst Sqrt = 'sqrt';\nconst Symlog = 'symlog';\nconst Time = 'time';\nconst UTC = 'utc';\nconst Sequential = 'sequential';\nconst Diverging = 'diverging';\nconst Quantile = 'quantile';\nconst Quantize = 'quantize';\nconst Threshold = 'threshold';\nconst Ordinal = 'ordinal';\nconst Point = 'point';\nconst Band = 'band';\nconst BinOrdinal = 'bin-ordinal'; // categories\n\nconst Continuous = 'continuous';\nconst Discrete = 'discrete';\nconst Discretizing = 'discretizing';\nconst Interpolating = 'interpolating';\nconst Temporal = 'temporal';\n\nfunction invertRange (scale) {\n return function (_) {\n let lo = _[0],\n hi = _[1],\n t;\n\n if (hi < lo) {\n t = lo;\n lo = hi;\n hi = t;\n }\n\n return [scale.invert(lo), scale.invert(hi)];\n };\n}\n\nfunction invertRangeExtent (scale) {\n return function (_) {\n const range = scale.range();\n let lo = _[0],\n hi = _[1],\n min = -1,\n max,\n t,\n i,\n n;\n\n if (hi < lo) {\n t = lo;\n lo = hi;\n hi = t;\n }\n\n for (i = 0, n = range.length; i < n; ++i) {\n if (range[i] >= lo && range[i] <= hi) {\n if (min < 0) min = i;\n max = i;\n }\n }\n\n if (min < 0) return undefined;\n lo = scale.invertExtent(range[min]);\n hi = scale.invertExtent(range[max]);\n return [lo[0] === undefined ? lo[1] : lo[0], hi[1] === undefined ? hi[0] : hi[1]];\n };\n}\n\nfunction band() {\n const scale = scaleOrdinal().unknown(undefined),\n domain = scale.domain,\n ordinalRange = scale.range;\n let range$1 = [0, 1],\n step,\n bandwidth,\n round = false,\n paddingInner = 0,\n paddingOuter = 0,\n align = 0.5;\n delete scale.unknown;\n\n function rescale() {\n const n = domain().length,\n reverse = range$1[1] < range$1[0],\n stop = range$1[1 - reverse],\n space = bandSpace(n, paddingInner, paddingOuter);\n let start = range$1[reverse - 0];\n step = (stop - start) / (space || 1);\n\n if (round) {\n step = Math.floor(step);\n }\n\n start += (stop - start - step * (n - paddingInner)) * align;\n bandwidth = step * (1 - paddingInner);\n\n if (round) {\n start = Math.round(start);\n bandwidth = Math.round(bandwidth);\n }\n\n const values = range(n).map(i => start + step * i);\n return ordinalRange(reverse ? values.reverse() : values);\n }\n\n scale.domain = function (_) {\n if (arguments.length) {\n domain(_);\n return rescale();\n } else {\n return domain();\n }\n };\n\n scale.range = function (_) {\n if (arguments.length) {\n range$1 = [+_[0], +_[1]];\n return rescale();\n } else {\n return range$1.slice();\n }\n };\n\n scale.rangeRound = function (_) {\n range$1 = [+_[0], +_[1]];\n round = true;\n return rescale();\n };\n\n scale.bandwidth = function () {\n return bandwidth;\n };\n\n scale.step = function () {\n return step;\n };\n\n scale.round = function (_) {\n if (arguments.length) {\n round = !!_;\n return rescale();\n } else {\n return round;\n }\n };\n\n scale.padding = function (_) {\n if (arguments.length) {\n paddingOuter = Math.max(0, Math.min(1, _));\n paddingInner = paddingOuter;\n return rescale();\n } else {\n return paddingInner;\n }\n };\n\n scale.paddingInner = function (_) {\n if (arguments.length) {\n paddingInner = Math.max(0, Math.min(1, _));\n return rescale();\n } else {\n return paddingInner;\n }\n };\n\n scale.paddingOuter = function (_) {\n if (arguments.length) {\n paddingOuter = Math.max(0, Math.min(1, _));\n return rescale();\n } else {\n return paddingOuter;\n }\n };\n\n scale.align = function (_) {\n if (arguments.length) {\n align = Math.max(0, Math.min(1, _));\n return rescale();\n } else {\n return align;\n }\n };\n\n scale.invertRange = function (_) {\n // bail if range has null or undefined values\n if (_[0] == null || _[1] == null) return;\n const reverse = range$1[1] < range$1[0],\n values = reverse ? ordinalRange().reverse() : ordinalRange(),\n n = values.length - 1;\n let lo = +_[0],\n hi = +_[1],\n a,\n b,\n t; // bail if either range endpoint is invalid\n\n if (lo !== lo || hi !== hi) return; // order range inputs, bail if outside of scale range\n\n if (hi < lo) {\n t = lo;\n lo = hi;\n hi = t;\n }\n\n if (hi < values[0] || lo > range$1[1 - reverse]) return; // binary search to index into scale range\n\n a = Math.max(0, bisectRight(values, lo) - 1);\n b = lo === hi ? a : bisectRight(values, hi) - 1; // increment index a if lo is within padding gap\n\n if (lo - values[a] > bandwidth + 1e-10) ++a;\n\n if (reverse) {\n // map + swap\n t = a;\n a = n - b;\n b = n - t;\n }\n\n return a > b ? undefined : domain().slice(a, b + 1);\n };\n\n scale.invert = function (_) {\n const value = scale.invertRange([_, _]);\n return value ? value[0] : value;\n };\n\n scale.copy = function () {\n return band().domain(domain()).range(range$1).round(round).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align);\n };\n\n return rescale();\n}\n\nfunction pointish(scale) {\n const copy = scale.copy;\n scale.padding = scale.paddingOuter;\n delete scale.paddingInner;\n\n scale.copy = function () {\n return pointish(copy());\n };\n\n return scale;\n}\n\nfunction point() {\n return pointish(band().paddingInner(1));\n}\n\nvar map = Array.prototype.map;\nfunction numbers(_) {\n return map.call(_, toNumber);\n}\n\nconst slice = Array.prototype.slice;\n\nfunction scaleBinOrdinal() {\n let domain = [],\n range = [];\n\n function scale(x) {\n return x == null || x !== x ? undefined : range[(bisect(domain, x) - 1) % range.length];\n }\n\n scale.domain = function (_) {\n if (arguments.length) {\n domain = numbers(_);\n return scale;\n } else {\n return domain.slice();\n }\n };\n\n scale.range = function (_) {\n if (arguments.length) {\n range = slice.call(_);\n return scale;\n } else {\n return range.slice();\n }\n };\n\n scale.tickFormat = function (count, specifier) {\n return tickFormat$1(domain[0], peek(domain), count == null ? 10 : count, specifier);\n };\n\n scale.copy = function () {\n return scaleBinOrdinal().domain(scale.domain()).range(scale.range());\n };\n\n return scale;\n}\n\nconst scales = {};\n/**\n * Augment scales with their type and needed inverse methods.\n */\n\nfunction create(type, constructor, metadata) {\n const ctr = function scale() {\n const s = constructor();\n\n if (!s.invertRange) {\n s.invertRange = s.invert ? invertRange(s) : s.invertExtent ? invertRangeExtent(s) : undefined;\n }\n\n s.type = type;\n return s;\n };\n\n ctr.metadata = toSet(array(metadata));\n return ctr;\n}\n\nfunction scale(type, scale, metadata) {\n if (arguments.length > 1) {\n scales[type] = create(type, scale, metadata);\n return this;\n } else {\n return isValidScaleType(type) ? scales[type] : undefined;\n }\n} // identity scale\n\nscale(Identity, scaleIdentity); // continuous scales\n\nscale(Linear, scaleLinear, Continuous);\nscale(Log, scaleLog, [Continuous, Log]);\nscale(Pow, scalePow, Continuous);\nscale(Sqrt, scaleSqrt, Continuous);\nscale(Symlog, scaleSymlog, Continuous);\nscale(Time, scaleTime, [Continuous, Temporal]);\nscale(UTC, scaleUtc, [Continuous, Temporal]); // sequential scales\n\nscale(Sequential, scaleSequential, [Continuous, Interpolating]); // backwards compat\n\nscale(\"\".concat(Sequential, \"-\").concat(Linear), scaleSequential, [Continuous, Interpolating]);\nscale(\"\".concat(Sequential, \"-\").concat(Log), scaleSequentialLog, [Continuous, Interpolating, Log]);\nscale(\"\".concat(Sequential, \"-\").concat(Pow), scaleSequentialPow, [Continuous, Interpolating]);\nscale(\"\".concat(Sequential, \"-\").concat(Sqrt), scaleSequentialSqrt, [Continuous, Interpolating]);\nscale(\"\".concat(Sequential, \"-\").concat(Symlog), scaleSequentialSymlog, [Continuous, Interpolating]); // diverging scales\n\nscale(\"\".concat(Diverging, \"-\").concat(Linear), scaleDiverging, [Continuous, Interpolating]);\nscale(\"\".concat(Diverging, \"-\").concat(Log), scaleDivergingLog, [Continuous, Interpolating, Log]);\nscale(\"\".concat(Diverging, \"-\").concat(Pow), scaleDivergingPow, [Continuous, Interpolating]);\nscale(\"\".concat(Diverging, \"-\").concat(Sqrt), scaleDivergingSqrt, [Continuous, Interpolating]);\nscale(\"\".concat(Diverging, \"-\").concat(Symlog), scaleDivergingSymlog, [Continuous, Interpolating]); // discretizing scales\n\nscale(Quantile, scaleQuantile, [Discretizing, Quantile]);\nscale(Quantize, scaleQuantize, Discretizing);\nscale(Threshold, scaleThreshold, Discretizing); // discrete scales\n\nscale(BinOrdinal, scaleBinOrdinal, [Discrete, Discretizing]);\nscale(Ordinal, scaleOrdinal, Discrete);\nscale(Band, band, Discrete);\nscale(Point, point, Discrete);\nfunction isValidScaleType(type) {\n return hasOwnProperty(scales, type);\n}\n\nfunction hasType(key, type) {\n const s = scales[key];\n return s && s.metadata[type];\n}\n\nfunction isContinuous(key) {\n return hasType(key, Continuous);\n}\nfunction isDiscrete(key) {\n return hasType(key, Discrete);\n}\nfunction isDiscretizing(key) {\n return hasType(key, Discretizing);\n}\nfunction isLogarithmic(key) {\n return hasType(key, Log);\n}\nfunction isTemporal(key) {\n return hasType(key, Temporal);\n}\nfunction isInterpolating(key) {\n return hasType(key, Interpolating);\n}\nfunction isQuantile(key) {\n return hasType(key, Quantile);\n}\n\nconst scaleProps = ['clamp', 'base', 'constant', 'exponent'];\nfunction interpolateRange(interpolator, range) {\n const start = range[0],\n span = peek(range) - start;\n return function (i) {\n return interpolator(start + i * span);\n };\n}\nfunction interpolateColors(colors, type, gamma) {\n return piecewise(interpolate(type || 'rgb', gamma), colors);\n}\nfunction quantizeInterpolator(interpolator, count) {\n const samples = new Array(count),\n n = count + 1;\n\n for (let i = 0; i < count;) samples[i] = interpolator(++i / n);\n\n return samples;\n}\nfunction scaleCopy(scale) {\n const t = scale.type,\n s = scale.copy();\n s.type = t;\n return s;\n}\nfunction scaleFraction(scale$1, min, max) {\n const delta = max - min;\n let i, t, s;\n\n if (!delta || !Number.isFinite(delta)) {\n return constant(0.5);\n } else {\n i = (t = scale$1.type).indexOf('-');\n t = i < 0 ? t : t.slice(i + 1);\n s = scale(t)().domain([min, max]).range([0, 1]);\n scaleProps.forEach(m => scale$1[m] ? s[m](scale$1[m]()) : 0);\n return s;\n }\n}\nfunction interpolate(type, gamma) {\n const interp = $[method(type)];\n return gamma != null && interp && interp.gamma ? interp.gamma(gamma) : interp;\n}\n\nfunction method(type) {\n return 'interpolate' + type.toLowerCase().split('-').map(s => s[0].toUpperCase() + s.slice(1)).join('');\n}\n\nconst continuous = {\n blues: 'cfe1f2bed8eca8cee58fc1de74b2d75ba3cf4592c63181bd206fb2125ca40a4a90',\n greens: 'd3eecdc0e6baabdda594d3917bc77d60ba6c46ab5e329a512089430e7735036429',\n greys: 'e2e2e2d4d4d4c4c4c4b1b1b19d9d9d8888887575756262624d4d4d3535351e1e1e',\n oranges: 'fdd8b3fdc998fdb87bfda55efc9244f87f2cf06b18e4580bd14904b93d029f3303',\n purples: 'e2e1efd4d4e8c4c5e0b4b3d6a3a0cc928ec3827cb97566ae684ea25c3696501f8c',\n reds: 'fdc9b4fcb49afc9e80fc8767fa7051f6573fec3f2fdc2a25c81b1db21218970b13',\n blueGreen: 'd5efedc1e8e0a7ddd18bd2be70c6a958ba9144ad77319c5d2089460e7736036429',\n bluePurple: 'ccddecbad0e4a8c2dd9ab0d4919cc98d85be8b6db28a55a6873c99822287730f71',\n greenBlue: 'd3eecec5e8c3b1e1bb9bd8bb82cec269c2ca51b2cd3c9fc7288abd1675b10b60a1',\n orangeRed: 'fddcaffdcf9bfdc18afdad77fb9562f67d53ee6545e24932d32d1ebf130da70403',\n purpleBlue: 'dbdaebc8cee4b1c3de97b7d87bacd15b9fc93a90c01e7fb70b70ab056199045281',\n purpleBlueGreen: 'dbd8eac8cee4b0c3de93b7d872acd1549fc83892bb1c88a3097f8702736b016353',\n purpleRed: 'dcc9e2d3b3d7ce9eccd186c0da6bb2e14da0e23189d91e6fc61159ab07498f023a',\n redPurple: 'fccfccfcbec0faa9b8f98faff571a5ec539ddb3695c41b8aa908808d0179700174',\n yellowGreen: 'e4f4acd1eca0b9e2949ed68880c97c62bb6e47aa5e3297502083440e723b036034',\n yellowOrangeBrown: 'feeaa1fedd84fecc63feb746fca031f68921eb7215db5e0bc54c05ab3d038f3204',\n yellowOrangeRed: 'fee087fed16ffebd59fea849fd903efc7335f9522bee3423de1b20ca0b22af0225',\n blueOrange: '134b852f78b35da2cb9dcae1d2e5eff2f0ebfce0bafbbf74e8932fc5690d994a07',\n brownBlueGreen: '704108a0651ac79548e3c78af3e6c6eef1eac9e9e48ed1c74da79e187a72025147',\n purpleGreen: '5b1667834792a67fb6c9aed3e6d6e8eff0efd9efd5aedda971bb75368e490e5e29',\n purpleOrange: '4114696647968f83b7b9b4d6dadbebf3eeeafce0bafbbf74e8932fc5690d994a07',\n redBlue: '8c0d25bf363adf745ef4ae91fbdbc9f2efeed2e5ef9dcae15da2cb2f78b3134b85',\n redGrey: '8c0d25bf363adf745ef4ae91fcdccbfaf4f1e2e2e2c0c0c0969696646464343434',\n yellowGreenBlue: 'eff9bddbf1b4bde5b594d5b969c5be45b4c22c9ec02182b82163aa23479c1c3185',\n redYellowBlue: 'a50026d4322cf16e43fcac64fedd90faf8c1dcf1ecabd6e875abd04a74b4313695',\n redYellowGreen: 'a50026d4322cf16e43fcac63fedd8df9f7aed7ee8ea4d86e64bc6122964f006837',\n pinkYellowGreen: '8e0152c0267edd72adf0b3d6faddedf5f3efe1f2cab6de8780bb474f9125276419',\n spectral: '9e0142d13c4bf0704afcac63fedd8dfbf8b0e0f3a1a9dda269bda94288b55e4fa2',\n viridis: '440154470e61481a6c482575472f7d443a834144873d4e8a39568c35608d31688e2d708e2a788e27818e23888e21918d1f988b1fa08822a8842ab07f35b77943bf7154c56866cc5d7ad1518fd744a5db36bcdf27d2e21be9e51afde725',\n magma: '0000040404130b0924150e3720114b2c11603b0f704a107957157e651a80721f817f24828c29819a2e80a8327db6377ac43c75d1426fde4968e95462f1605df76f5cfa7f5efc8f65fe9f6dfeaf78febf84fece91fddea0fcedaffcfdbf',\n inferno: '0000040403130c0826170c3b240c4f330a5f420a68500d6c5d126e6b176e781c6d86216b932667a12b62ae305cbb3755c73e4cd24644dd513ae65c30ed6925f3771af8850ffb9506fca50afcb519fac62df6d645f2e661f3f484fcffa4',\n plasma: '0d088723069033059742039d5002a25d01a66a00a87801a88405a7900da49c179ea72198b12a90ba3488c33d80cb4779d35171da5a69e16462e76e5bed7953f2834cf68f44fa9a3dfca636fdb32ffec029fcce25f9dc24f5ea27f0f921',\n cividis: '00205100235800265d002961012b65042e670831690d346b11366c16396d1c3c6e213f6e26426e2c456e31476e374a6e3c4d6e42506e47536d4c566d51586e555b6e5a5e6e5e616e62646f66676f6a6a706e6d717270717573727976737c79747f7c75827f758682768985778c8877908b78938e789691789a94789e9778a19b78a59e77a9a177aea575b2a874b6ab73bbaf71c0b26fc5b66dc9b96acebd68d3c065d8c462ddc85fe2cb5ce7cf58ebd355f0d652f3da4ff7de4cfae249fce647',\n rainbow: '6e40aa883eb1a43db3bf3cafd83fa4ee4395fe4b83ff576eff6659ff7847ff8c38f3a130e2b72fcfcc36bee044aff05b8ff4576ff65b52f6673af27828ea8d1ddfa319d0b81cbecb23abd82f96e03d82e14c6edb5a5dd0664dbf6e40aa',\n sinebow: 'ff4040fc582af47218e78d0bd5a703bfbf00a7d5038de70b72f41858fc2a40ff402afc5818f4720be78d03d5a700bfbf03a7d50b8de71872f42a58fc4040ff582afc7218f48d0be7a703d5bf00bfd503a7e70b8df41872fc2a58ff4040',\n turbo: '23171b32204a3e2a71453493493eae4b49c54a53d7485ee44569ee4074f53c7ff8378af93295f72e9ff42ba9ef28b3e926bce125c5d925cdcf27d5c629dcbc2de3b232e9a738ee9d3ff39347f68950f9805afc7765fd6e70fe667cfd5e88fc5795fb51a1f84badf545b9f140c5ec3cd0e637dae034e4d931ecd12ef4c92bfac029ffb626ffad24ffa223ff9821ff8d1fff821dff771cfd6c1af76118f05616e84b14df4111d5380fcb2f0dc0260ab61f07ac1805a313029b0f00950c00910b00',\n browns: 'eedbbdecca96e9b97ae4a865dc9856d18954c7784cc0673fb85536ad44339f3632',\n tealBlues: 'bce4d89dd3d181c3cb65b3c245a2b9368fae347da0306a932c5985',\n teals: 'bbdfdfa2d4d58ac9c975bcbb61b0af4da5a43799982b8b8c1e7f7f127273006667',\n warmGreys: 'dcd4d0cec5c1c0b8b4b3aaa7a59c9998908c8b827f7e7673726866665c5a59504e',\n goldGreen: 'f4d166d5ca60b6c35c98bb597cb25760a6564b9c533f8f4f33834a257740146c36',\n goldOrange: 'f4d166f8be5cf8aa4cf5983bf3852aef701be2621fd65322c54923b142239e3a26',\n goldRed: 'f4d166f6be59f9aa51fc964ef6834bee734ae56249db5247cf4244c43141b71d3e',\n lightGreyRed: 'efe9e6e1dad7d5cbc8c8bdb9bbaea9cd967ddc7b43e15f19df4011dc000b',\n lightGreyTeal: 'e4eaead6dcddc8ced2b7c2c7a6b4bc64b0bf22a6c32295c11f85be1876bc',\n lightMulti: 'e0f1f2c4e9d0b0de9fd0e181f6e072f6c053f3993ef77440ef4a3c',\n lightOrange: 'f2e7daf7d5baf9c499fab184fa9c73f68967ef7860e8645bde515bd43d5b',\n lightTealBlue: 'e3e9e0c0dccf9aceca7abfc859afc0389fb9328dad2f7ca0276b95255988',\n darkBlue: '3232322d46681a5c930074af008cbf05a7ce25c0dd38daed50f3faffffff',\n darkGold: '3c3c3c584b37725e348c7631ae8b2bcfa424ecc31ef9de30fff184ffffff',\n darkGreen: '3a3a3a215748006f4d048942489e4276b340a6c63dd2d836ffeb2cffffaa',\n darkMulti: '3737371f5287197d8c29a86995ce3fffe800ffffff',\n darkRed: '3434347036339e3c38cc4037e75d1eec8620eeab29f0ce32ffeb2c'\n};\nconst discrete = {\n category10: '1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf',\n category20: '1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5',\n category20b: '393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6',\n category20c: '3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9',\n tableau10: '4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac',\n tableau20: '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5',\n accent: '7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666',\n dark2: '1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666',\n paired: 'a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928',\n pastel1: 'fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2',\n pastel2: 'b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc',\n set1: 'e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999',\n set2: '66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3',\n set3: '8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f'\n};\n\nfunction colors(palette) {\n const n = palette.length / 6 | 0,\n c = new Array(n);\n\n for (let i = 0; i < n;) {\n c[i] = '#' + palette.slice(i * 6, ++i * 6);\n }\n\n return c;\n}\n\nfunction apply(_, f) {\n for (const k in _) scheme(k, f(_[k]));\n}\n\nconst schemes = {};\napply(discrete, colors);\napply(continuous, _ => interpolateColors(colors(_)));\nfunction scheme(name, scheme) {\n name = name && name.toLowerCase();\n\n if (arguments.length > 1) {\n schemes[name] = scheme;\n return this;\n } else {\n return schemes[name];\n }\n}\n\nconst SymbolLegend = 'symbol';\nconst DiscreteLegend = 'discrete';\nconst GradientLegend = 'gradient';\n\nconst defaultFormatter = value => isArray(value) ? value.map(v => String(v)) : String(value);\n\nconst ascending = (a, b) => a[1] - b[1];\n\nconst descending = (a, b) => b[1] - a[1];\n/**\n * Determine the tick count or interval function.\n * @param {Scale} scale - The scale for which to generate tick values.\n * @param {*} count - The desired tick count or interval specifier.\n * @param {number} minStep - The desired minimum step between tick values.\n * @return {*} - The tick count or interval function.\n */\n\n\nfunction tickCount(scale, count, minStep) {\n let step;\n\n if (isNumber(count)) {\n if (scale.bins) {\n count = Math.max(count, scale.bins.length);\n }\n\n if (minStep != null) {\n count = Math.min(count, Math.floor(span(scale.domain()) / minStep || 1));\n }\n }\n\n if (isObject(count)) {\n step = count.step;\n count = count.interval;\n }\n\n if (isString(count)) {\n count = scale.type === Time ? timeInterval(count) : scale.type == UTC ? utcInterval(count) : error('Only time and utc scales accept interval strings.');\n if (step) count = count.every(step);\n }\n\n return count;\n}\n/**\n * Filter a set of candidate tick values, ensuring that only tick values\n * that lie within the scale range are included.\n * @param {Scale} scale - The scale for which to generate tick values.\n * @param {Array<*>} ticks - The candidate tick values.\n * @param {*} count - The tick count or interval function.\n * @return {Array<*>} - The filtered tick values.\n */\n\nfunction validTicks(scale, ticks, count) {\n let range = scale.range(),\n lo = range[0],\n hi = peek(range),\n cmp = ascending;\n\n if (lo > hi) {\n range = hi;\n hi = lo;\n lo = range;\n cmp = descending;\n }\n\n lo = Math.floor(lo);\n hi = Math.ceil(hi); // filter ticks to valid values within the range\n // additionally sort ticks in range order (#2579)\n\n ticks = ticks.map(v => [v, scale(v)]).filter(_ => lo <= _[1] && _[1] <= hi).sort(cmp).map(_ => _[0]);\n\n if (count > 0 && ticks.length > 1) {\n const endpoints = [ticks[0], peek(ticks)];\n\n while (ticks.length > count && ticks.length >= 3) {\n ticks = ticks.filter((_, i) => !(i % 2));\n }\n\n if (ticks.length < 3) {\n ticks = endpoints;\n }\n }\n\n return ticks;\n}\n/**\n * Generate tick values for the given scale and approximate tick count or\n * interval value. If the scale has a 'ticks' method, it will be used to\n * generate the ticks, with the count argument passed as a parameter. If the\n * scale lacks a 'ticks' method, the full scale domain will be returned.\n * @param {Scale} scale - The scale for which to generate tick values.\n * @param {*} [count] - The approximate number of desired ticks.\n * @return {Array<*>} - The generated tick values.\n */\n\nfunction tickValues(scale, count) {\n return scale.bins ? validTicks(scale, scale.bins) : scale.ticks ? scale.ticks(count) : scale.domain();\n}\n/**\n * Generate a label format function for a scale. If the scale has a\n * 'tickFormat' method, it will be used to generate the formatter, with the\n * count and specifier arguments passed as parameters. If the scale lacks a\n * 'tickFormat' method, the returned formatter performs simple string coercion.\n * If the input scale is a logarithmic scale and the format specifier does not\n * indicate a desired decimal precision, a special variable precision formatter\n * that automatically trims trailing zeroes will be generated.\n * @param {Scale} scale - The scale for which to generate the label formatter.\n * @param {*} [count] - The approximate number of desired ticks.\n * @param {string} [specifier] - The format specifier. Must be a legal d3\n * specifier string (see https://github.com/d3/d3-format#formatSpecifier) or\n * time multi-format specifier object.\n * @return {function(*):string} - The generated label formatter.\n */\n\nfunction tickFormat(locale, scale, count, specifier, formatType, noSkip) {\n const type = scale.type;\n let format = defaultFormatter;\n\n if (type === Time || formatType === Time) {\n format = locale.timeFormat(specifier);\n } else if (type === UTC || formatType === UTC) {\n format = locale.utcFormat(specifier);\n } else if (isLogarithmic(type)) {\n const varfmt = locale.formatFloat(specifier);\n\n if (noSkip || scale.bins) {\n format = varfmt;\n } else {\n const test = tickLog(scale, count, false);\n\n format = _ => test(_) ? varfmt(_) : '';\n }\n } else if (scale.tickFormat) {\n // if d3 scale has tickFormat, it must be continuous\n const d = scale.domain();\n format = locale.formatSpan(d[0], d[d.length - 1], count, specifier);\n } else if (specifier) {\n format = locale.format(specifier);\n }\n\n return format;\n}\nfunction tickLog(scale, count, values) {\n const ticks = tickValues(scale, count),\n base = scale.base(),\n logb = Math.log(base),\n k = Math.max(1, base * count / ticks.length); // apply d3-scale's log format filter criteria\n\n const test = d => {\n let i = d / Math.pow(base, Math.round(Math.log(d) / logb));\n if (i * base < base - 0.5) i *= base;\n return i <= k;\n };\n\n return values ? ticks.filter(test) : test;\n}\n\nconst symbols = {\n [Quantile]: 'quantiles',\n [Quantize]: 'thresholds',\n [Threshold]: 'domain'\n};\nconst formats = {\n [Quantile]: 'quantiles',\n [Quantize]: 'domain'\n};\nfunction labelValues(scale, count) {\n return scale.bins ? binValues(scale.bins) : scale.type === Log ? tickLog(scale, count, true) : symbols[scale.type] ? thresholdValues(scale[symbols[scale.type]]()) : tickValues(scale, count);\n}\nfunction thresholdFormat(locale, scale, specifier) {\n const _ = scale[formats[scale.type]](),\n n = _.length;\n\n let d = n > 1 ? _[1] - _[0] : _[0],\n i;\n\n for (i = 1; i < n; ++i) {\n d = Math.min(d, _[i] - _[i - 1]);\n } // tickCount = 3 ticks times 10 for increased resolution\n\n\n return locale.formatSpan(0, d, 3 * 10, specifier);\n}\n\nfunction thresholdValues(thresholds) {\n const values = [-Infinity].concat(thresholds);\n values.max = +Infinity;\n return values;\n}\n\nfunction binValues(bins) {\n const values = bins.slice(0, -1);\n values.max = peek(bins);\n return values;\n}\n\nconst isDiscreteRange = scale => symbols[scale.type] || scale.bins;\n\nfunction labelFormat(locale, scale, count, type, specifier, formatType, noSkip) {\n const format = formats[scale.type] && formatType !== Time && formatType !== UTC ? thresholdFormat(locale, scale, specifier) : tickFormat(locale, scale, count, specifier, formatType, noSkip);\n return type === SymbolLegend && isDiscreteRange(scale) ? formatRange(format) : type === DiscreteLegend ? formatDiscrete(format) : formatPoint(format);\n}\n\nconst formatRange = format => (value, index, array) => {\n const limit = get(array[index + 1], get(array.max, +Infinity)),\n lo = formatValue(value, format),\n hi = formatValue(limit, format);\n return lo && hi ? lo + ' \\u2013 ' + hi : hi ? '< ' + hi : '\\u2265 ' + lo;\n};\n\nconst get = (value, dflt) => value != null ? value : dflt;\n\nconst formatDiscrete = format => (value, index) => index ? format(value) : null;\n\nconst formatPoint = format => value => format(value);\n\nconst formatValue = (value, format) => Number.isFinite(value) ? format(value) : null;\n\nfunction labelFraction(scale) {\n const domain = scale.domain(),\n count = domain.length - 1;\n let lo = +domain[0],\n hi = +peek(domain),\n span = hi - lo;\n\n if (scale.type === Threshold) {\n const adjust = count ? span / count : 0.1;\n lo -= adjust;\n hi += adjust;\n span = hi - lo;\n }\n\n return value => (value - lo) / span;\n}\n\nfunction format(locale, scale, specifier, formatType) {\n const type = formatType || scale.type; // replace abbreviated time specifiers to improve screen reader experience\n\n if (isString(specifier) && isTemporal(type)) {\n specifier = specifier.replace(/%a/g, '%A').replace(/%b/g, '%B');\n }\n\n return !specifier && type === Time ? locale.timeFormat('%A, %d %B %Y, %X') : !specifier && type === UTC ? locale.utcFormat('%A, %d %B %Y, %X UTC') : labelFormat(locale, scale, 5, null, specifier, formatType, true);\n}\n\nfunction domainCaption(locale, scale, opt) {\n opt = opt || {};\n const max = Math.max(3, opt.maxlen || 7),\n fmt = format(locale, scale, opt.format, opt.formatType); // if scale breaks domain into bins, describe boundaries\n\n if (isDiscretizing(scale.type)) {\n const v = labelValues(scale).slice(1).map(fmt),\n n = v.length;\n return \"\".concat(n, \" boundar\").concat(n === 1 ? 'y' : 'ies', \": \").concat(v.join(', '));\n } // if scale domain is discrete, list values\n else if (isDiscrete(scale.type)) {\n const d = scale.domain(),\n n = d.length,\n v = n > max ? d.slice(0, max - 2).map(fmt).join(', ') + ', ending with ' + d.slice(-1).map(fmt) : d.map(fmt).join(', ');\n return \"\".concat(n, \" value\").concat(n === 1 ? '' : 's', \": \").concat(v);\n } // if scale domain is continuous, describe value range\n else {\n const d = scale.domain();\n return \"values from \".concat(fmt(d[0]), \" to \").concat(fmt(peek(d)));\n }\n}\n\nexport { Band, BinOrdinal, DiscreteLegend, Diverging, GradientLegend, Identity, Linear, Log, Ordinal, Point, Pow, Quantile, Quantize, Sequential, Sqrt, SymbolLegend, Symlog, Threshold, Time, UTC, bandSpace, domainCaption, interpolate, interpolateColors, interpolateRange, isContinuous, isDiscrete, isDiscretizing, isInterpolating, isLogarithmic, isQuantile, isTemporal, isValidScaleType, labelFormat, labelFraction, labelValues, quantizeInterpolator, scale, scaleCopy, scaleFraction, scheme, tickCount, tickFormat, tickValues, validTicks };\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","import {linearish} from \"./linear.js\";\nimport number from \"./number.js\";\n\nexport default function identity(domain) {\n var unknown;\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : x;\n }\n\n scale.invert = scale;\n\n scale.domain = scale.range = function(_) {\n return arguments.length ? (domain = Array.from(_, number), scale) : domain.slice();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return identity(domain).unknown(unknown);\n };\n\n domain = arguments.length ? Array.from(domain, number) : [0, 1];\n\n return linearish(scale);\n}\n","import {utcYear, utcMonth, utcWeek, utcDay, utcHour, utcMinute, utcSecond, utcTicks, utcTickInterval} from \"d3-time\";\nimport {utcFormat} from \"d3-time-format\";\nimport {calendar} from \"./time.js\";\nimport {initRange} from \"./init.js\";\n\nexport default function utcTime() {\n return initRange.apply(calendar(utcTicks, utcTickInterval, utcYear, utcMonth, utcWeek, utcDay, utcHour, utcMinute, utcSecond, utcFormat).domain([Date.UTC(2000, 0, 1), Date.UTC(2000, 0, 2)]), arguments);\n}\n","import {ascending, bisect, quantileSorted as threshold} from \"d3-array\";\nimport {initRange} from \"./init.js\";\n\nexport default function quantile() {\n var domain = [],\n range = [],\n thresholds = [],\n unknown;\n\n function rescale() {\n var i = 0, n = Math.max(1, range.length);\n thresholds = new Array(n - 1);\n while (++i < n) thresholds[i - 1] = threshold(domain, i / n);\n return scale;\n }\n\n function scale(x) {\n return x == null || isNaN(x = +x) ? unknown : range[bisect(thresholds, x)];\n }\n\n scale.invertExtent = function(y) {\n var i = range.indexOf(y);\n return i < 0 ? [NaN, NaN] : [\n i > 0 ? thresholds[i - 1] : domain[0],\n i < thresholds.length ? thresholds[i] : domain[domain.length - 1]\n ];\n };\n\n scale.domain = function(_) {\n if (!arguments.length) return domain.slice();\n domain = [];\n for (let d of _) if (d != null && !isNaN(d = +d)) domain.push(d);\n domain.sort(ascending);\n return rescale();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), rescale()) : range.slice();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.quantiles = function() {\n return thresholds.slice();\n };\n\n scale.copy = function() {\n return quantile()\n .domain(domain)\n .range(range)\n .unknown(unknown);\n };\n\n return initRange.apply(scale, arguments);\n}\n","import {bisect} from \"d3-array\";\nimport {linearish} from \"./linear.js\";\nimport {initRange} from \"./init.js\";\n\nexport default function quantize() {\n var x0 = 0,\n x1 = 1,\n n = 1,\n domain = [0.5],\n range = [0, 1],\n unknown;\n\n function scale(x) {\n return x != null && x <= x ? range[bisect(domain, x, 0, n)] : unknown;\n }\n\n function rescale() {\n var i = -1;\n domain = new Array(n);\n while (++i < n) domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1);\n return scale;\n }\n\n scale.domain = function(_) {\n return arguments.length ? ([x0, x1] = _, x0 = +x0, x1 = +x1, rescale()) : [x0, x1];\n };\n\n scale.range = function(_) {\n return arguments.length ? (n = (range = Array.from(_)).length - 1, rescale()) : range.slice();\n };\n\n scale.invertExtent = function(y) {\n var i = range.indexOf(y);\n return i < 0 ? [NaN, NaN]\n : i < 1 ? [x0, domain[0]]\n : i >= n ? [domain[n - 1], x1]\n : [domain[i - 1], domain[i]];\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : scale;\n };\n\n scale.thresholds = function() {\n return domain.slice();\n };\n\n scale.copy = function() {\n return quantize()\n .domain([x0, x1])\n .range(range)\n .unknown(unknown);\n };\n\n return initRange.apply(linearish(scale), arguments);\n}\n","import {bisect} from \"d3-array\";\nimport {initRange} from \"./init.js\";\n\nexport default function threshold() {\n var domain = [0.5],\n range = [0, 1],\n unknown,\n n = 1;\n\n function scale(x) {\n return x != null && x <= x ? range[bisect(domain, x, 0, n)] : unknown;\n }\n\n scale.domain = function(_) {\n return arguments.length ? (domain = Array.from(_), n = Math.min(domain.length, range.length - 1), scale) : domain.slice();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = Array.from(_), n = Math.min(domain.length, range.length - 1), scale) : range.slice();\n };\n\n scale.invertExtent = function(y) {\n var i = range.indexOf(y);\n return [domain[i - 1], domain[i]];\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return threshold()\n .domain(domain)\n .range(range)\n .unknown(unknown);\n };\n\n return initRange.apply(scale, arguments);\n}\n","import { hasOwnProperty, isFunction, inherits, truthy, lruCache, isArray, error, toSet, array, peek, extend, isNumber, isObject } from 'vega-util';\nimport { curveBasis, curveBasisClosed, curveBasisOpen, curveBundle, curveCardinal, curveCardinalOpen, curveCardinalClosed, curveCatmullRom, curveCatmullRomClosed, curveCatmullRomOpen, curveLinear, curveLinearClosed, curveMonotoneY, curveMonotoneX, curveNatural, curveStep, curveStepAfter, curveStepBefore, arc as arc$2, area as area$2, line as line$2, symbol as symbol$2 } from 'd3-shape';\nimport { path as path$3 } from 'd3-path';\nimport { image as image$1, canvas } from 'vega-canvas';\nimport { loader } from 'vega-loader';\nimport { isDiscrete, domainCaption } from 'vega-scale';\n\nlet gradient_id = 0;\nfunction resetSVGGradientId() {\n gradient_id = 0;\n}\nconst patternPrefix = 'p_';\nfunction isGradient(value) {\n return value && value.gradient;\n}\nfunction gradientRef(g, defs, base) {\n const type = g.gradient;\n let id = g.id,\n prefix = type === 'radial' ? patternPrefix : ''; // check id, assign default values as needed\n\n if (!id) {\n id = g.id = 'gradient_' + gradient_id++;\n\n if (type === 'radial') {\n g.x1 = get(g.x1, 0.5);\n g.y1 = get(g.y1, 0.5);\n g.r1 = get(g.r1, 0);\n g.x2 = get(g.x2, 0.5);\n g.y2 = get(g.y2, 0.5);\n g.r2 = get(g.r2, 0.5);\n prefix = patternPrefix;\n } else {\n g.x1 = get(g.x1, 0);\n g.y1 = get(g.y1, 0);\n g.x2 = get(g.x2, 1);\n g.y2 = get(g.y2, 0);\n }\n } // register definition\n\n\n defs[id] = g; // return url reference\n\n return 'url(' + (base || '') + '#' + prefix + id + ')';\n}\n\nfunction get(val, def) {\n return val != null ? val : def;\n}\n\nfunction Gradient (p0, p1) {\n var stops = [],\n gradient;\n return gradient = {\n gradient: 'linear',\n x1: p0 ? p0[0] : 0,\n y1: p0 ? p0[1] : 0,\n x2: p1 ? p1[0] : 1,\n y2: p1 ? p1[1] : 0,\n stops: stops,\n stop: function (offset, color) {\n stops.push({\n offset: offset,\n color: color\n });\n return gradient;\n }\n };\n}\n\nconst lookup = {\n 'basis': {\n curve: curveBasis\n },\n 'basis-closed': {\n curve: curveBasisClosed\n },\n 'basis-open': {\n curve: curveBasisOpen\n },\n 'bundle': {\n curve: curveBundle,\n tension: 'beta',\n value: 0.85\n },\n 'cardinal': {\n curve: curveCardinal,\n tension: 'tension',\n value: 0\n },\n 'cardinal-open': {\n curve: curveCardinalOpen,\n tension: 'tension',\n value: 0\n },\n 'cardinal-closed': {\n curve: curveCardinalClosed,\n tension: 'tension',\n value: 0\n },\n 'catmull-rom': {\n curve: curveCatmullRom,\n tension: 'alpha',\n value: 0.5\n },\n 'catmull-rom-closed': {\n curve: curveCatmullRomClosed,\n tension: 'alpha',\n value: 0.5\n },\n 'catmull-rom-open': {\n curve: curveCatmullRomOpen,\n tension: 'alpha',\n value: 0.5\n },\n 'linear': {\n curve: curveLinear\n },\n 'linear-closed': {\n curve: curveLinearClosed\n },\n 'monotone': {\n horizontal: curveMonotoneY,\n vertical: curveMonotoneX\n },\n 'natural': {\n curve: curveNatural\n },\n 'step': {\n curve: curveStep\n },\n 'step-after': {\n curve: curveStepAfter\n },\n 'step-before': {\n curve: curveStepBefore\n }\n};\nfunction curves(type, orientation, tension) {\n var entry = hasOwnProperty(lookup, type) && lookup[type],\n curve = null;\n\n if (entry) {\n curve = entry.curve || entry[orientation || 'vertical'];\n\n if (entry.tension && tension != null) {\n curve = curve[entry.tension](tension);\n }\n }\n\n return curve;\n}\n\n// Path parsing and rendering code adapted from fabric.js -- Thanks!\nconst cmdlen = {\n m: 2,\n l: 2,\n h: 1,\n v: 1,\n c: 6,\n s: 4,\n q: 4,\n t: 2,\n a: 7\n},\n regexp = [/([MLHVCSQTAZmlhvcsqtaz])/g, /###/, /(\\.\\d+)(\\.\\d)/g, /(\\d)([-+])/g, /\\s|,|###/];\nfunction pathParse (pathstr) {\n const result = [];\n let curr, chunks, parsed, param, cmd, len, i, j, n, m; // First, break path into command sequence\n\n const path = pathstr.slice().replace(regexp[0], '###$1').split(regexp[1]).slice(1); // Next, parse each command in turn\n\n for (i = 0, n = path.length; i < n; ++i) {\n curr = path[i];\n chunks = curr.slice(1).trim().replace(regexp[2], '$1###$2').replace(regexp[3], '$1###$2').split(regexp[4]);\n cmd = curr.charAt(0);\n parsed = [cmd];\n\n for (j = 0, m = chunks.length; j < m; ++j) {\n if ((param = +chunks[j]) === param) {\n // not NaN\n parsed.push(param);\n }\n }\n\n len = cmdlen[cmd.toLowerCase()];\n\n if (parsed.length - 1 > len) {\n const m = parsed.length;\n j = 1;\n result.push([cmd].concat(parsed.slice(j, j += len))); // handle implicit lineTo (#2803)\n\n cmd = cmd === 'M' ? 'L' : cmd === 'm' ? 'l' : cmd;\n\n for (; j < m; j += len) {\n result.push([cmd].concat(parsed.slice(j, j + len)));\n }\n } else {\n result.push(parsed);\n }\n }\n\n return result;\n}\n\nconst DegToRad = Math.PI / 180;\nconst Epsilon = 1e-14;\nconst HalfPi = Math.PI / 2;\nconst Tau = Math.PI * 2;\nconst HalfSqrt3 = Math.sqrt(3) / 2;\n\nvar segmentCache = {};\nvar bezierCache = {};\nvar join = [].join; // Copied from Inkscape svgtopdf, thanks!\n\nfunction segments(x, y, rx, ry, large, sweep, rotateX, ox, oy) {\n const key = join.call(arguments);\n\n if (segmentCache[key]) {\n return segmentCache[key];\n }\n\n const th = rotateX * DegToRad;\n const sin_th = Math.sin(th);\n const cos_th = Math.cos(th);\n rx = Math.abs(rx);\n ry = Math.abs(ry);\n const px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5;\n const py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5;\n let pl = px * px / (rx * rx) + py * py / (ry * ry);\n\n if (pl > 1) {\n pl = Math.sqrt(pl);\n rx *= pl;\n ry *= pl;\n }\n\n const a00 = cos_th / rx;\n const a01 = sin_th / rx;\n const a10 = -sin_th / ry;\n const a11 = cos_th / ry;\n const x0 = a00 * ox + a01 * oy;\n const y0 = a10 * ox + a11 * oy;\n const x1 = a00 * x + a01 * y;\n const y1 = a10 * x + a11 * y;\n const d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);\n let sfactor_sq = 1 / d - 0.25;\n if (sfactor_sq < 0) sfactor_sq = 0;\n let sfactor = Math.sqrt(sfactor_sq);\n if (sweep == large) sfactor = -sfactor;\n const xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);\n const yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);\n const th0 = Math.atan2(y0 - yc, x0 - xc);\n const th1 = Math.atan2(y1 - yc, x1 - xc);\n let th_arc = th1 - th0;\n\n if (th_arc < 0 && sweep === 1) {\n th_arc += Tau;\n } else if (th_arc > 0 && sweep === 0) {\n th_arc -= Tau;\n }\n\n const segs = Math.ceil(Math.abs(th_arc / (HalfPi + 0.001)));\n const result = [];\n\n for (let i = 0; i < segs; ++i) {\n const th2 = th0 + i * th_arc / segs;\n const th3 = th0 + (i + 1) * th_arc / segs;\n result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th];\n }\n\n return segmentCache[key] = result;\n}\nfunction bezier(params) {\n const key = join.call(params);\n\n if (bezierCache[key]) {\n return bezierCache[key];\n }\n\n var cx = params[0],\n cy = params[1],\n th0 = params[2],\n th1 = params[3],\n rx = params[4],\n ry = params[5],\n sin_th = params[6],\n cos_th = params[7];\n const a00 = cos_th * rx;\n const a01 = -sin_th * ry;\n const a10 = sin_th * rx;\n const a11 = cos_th * ry;\n const cos_th0 = Math.cos(th0);\n const sin_th0 = Math.sin(th0);\n const cos_th1 = Math.cos(th1);\n const sin_th1 = Math.sin(th1);\n const th_half = 0.5 * (th1 - th0);\n const sin_th_h2 = Math.sin(th_half * 0.5);\n const t = 8 / 3 * sin_th_h2 * sin_th_h2 / Math.sin(th_half);\n const x1 = cx + cos_th0 - t * sin_th0;\n const y1 = cy + sin_th0 + t * cos_th0;\n const x3 = cx + cos_th1;\n const y3 = cy + sin_th1;\n const x2 = x3 + t * sin_th1;\n const y2 = y3 - t * cos_th1;\n return bezierCache[key] = [a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3];\n}\n\nconst temp = ['l', 0, 0, 0, 0, 0, 0, 0];\n\nfunction scale$1(current, sX, sY) {\n const c = temp[0] = current[0];\n\n if (c === 'a' || c === 'A') {\n temp[1] = sX * current[1];\n temp[2] = sY * current[2];\n temp[3] = current[3];\n temp[4] = current[4];\n temp[5] = current[5];\n temp[6] = sX * current[6];\n temp[7] = sY * current[7];\n } else if (c === 'h' || c === 'H') {\n temp[1] = sX * current[1];\n } else if (c === 'v' || c === 'V') {\n temp[1] = sY * current[1];\n } else {\n for (var i = 1, n = current.length; i < n; ++i) {\n temp[i] = (i % 2 == 1 ? sX : sY) * current[i];\n }\n }\n\n return temp;\n}\n\nfunction pathRender (context, path, l, t, sX, sY) {\n var current,\n // current instruction\n previous = null,\n x = 0,\n // current x\n y = 0,\n // current y\n controlX = 0,\n // current control point x\n controlY = 0,\n // current control point y\n tempX,\n tempY,\n tempControlX,\n tempControlY;\n if (l == null) l = 0;\n if (t == null) t = 0;\n if (sX == null) sX = 1;\n if (sY == null) sY = sX;\n if (context.beginPath) context.beginPath();\n\n for (var i = 0, len = path.length; i < len; ++i) {\n current = path[i];\n\n if (sX !== 1 || sY !== 1) {\n current = scale$1(current, sX, sY);\n }\n\n switch (current[0]) {\n // first letter\n case 'l':\n // lineto, relative\n x += current[1];\n y += current[2];\n context.lineTo(x + l, y + t);\n break;\n\n case 'L':\n // lineto, absolute\n x = current[1];\n y = current[2];\n context.lineTo(x + l, y + t);\n break;\n\n case 'h':\n // horizontal lineto, relative\n x += current[1];\n context.lineTo(x + l, y + t);\n break;\n\n case 'H':\n // horizontal lineto, absolute\n x = current[1];\n context.lineTo(x + l, y + t);\n break;\n\n case 'v':\n // vertical lineto, relative\n y += current[1];\n context.lineTo(x + l, y + t);\n break;\n\n case 'V':\n // verical lineto, absolute\n y = current[1];\n context.lineTo(x + l, y + t);\n break;\n\n case 'm':\n // moveTo, relative\n x += current[1];\n y += current[2];\n context.moveTo(x + l, y + t);\n break;\n\n case 'M':\n // moveTo, absolute\n x = current[1];\n y = current[2];\n context.moveTo(x + l, y + t);\n break;\n\n case 'c':\n // bezierCurveTo, relative\n tempX = x + current[5];\n tempY = y + current[6];\n controlX = x + current[3];\n controlY = y + current[4];\n context.bezierCurveTo(x + current[1] + l, // x1\n y + current[2] + t, // y1\n controlX + l, // x2\n controlY + t, // y2\n tempX + l, tempY + t);\n x = tempX;\n y = tempY;\n break;\n\n case 'C':\n // bezierCurveTo, absolute\n x = current[5];\n y = current[6];\n controlX = current[3];\n controlY = current[4];\n context.bezierCurveTo(current[1] + l, current[2] + t, controlX + l, controlY + t, x + l, y + t);\n break;\n\n case 's':\n // shorthand cubic bezierCurveTo, relative\n // transform to absolute x,y\n tempX = x + current[3];\n tempY = y + current[4]; // calculate reflection of previous control points\n\n controlX = 2 * x - controlX;\n controlY = 2 * y - controlY;\n context.bezierCurveTo(controlX + l, controlY + t, x + current[1] + l, y + current[2] + t, tempX + l, tempY + t); // set control point to 2nd one of this command\n // the first control point is assumed to be the reflection of\n // the second control point on the previous command relative\n // to the current point.\n\n controlX = x + current[1];\n controlY = y + current[2];\n x = tempX;\n y = tempY;\n break;\n\n case 'S':\n // shorthand cubic bezierCurveTo, absolute\n tempX = current[3];\n tempY = current[4]; // calculate reflection of previous control points\n\n controlX = 2 * x - controlX;\n controlY = 2 * y - controlY;\n context.bezierCurveTo(controlX + l, controlY + t, current[1] + l, current[2] + t, tempX + l, tempY + t);\n x = tempX;\n y = tempY; // set control point to 2nd one of this command\n // the first control point is assumed to be the reflection of\n // the second control point on the previous command relative\n // to the current point.\n\n controlX = current[1];\n controlY = current[2];\n break;\n\n case 'q':\n // quadraticCurveTo, relative\n // transform to absolute x,y\n tempX = x + current[3];\n tempY = y + current[4];\n controlX = x + current[1];\n controlY = y + current[2];\n context.quadraticCurveTo(controlX + l, controlY + t, tempX + l, tempY + t);\n x = tempX;\n y = tempY;\n break;\n\n case 'Q':\n // quadraticCurveTo, absolute\n tempX = current[3];\n tempY = current[4];\n context.quadraticCurveTo(current[1] + l, current[2] + t, tempX + l, tempY + t);\n x = tempX;\n y = tempY;\n controlX = current[1];\n controlY = current[2];\n break;\n\n case 't':\n // shorthand quadraticCurveTo, relative\n // transform to absolute x,y\n tempX = x + current[1];\n tempY = y + current[2];\n\n if (previous[0].match(/[QqTt]/) === null) {\n // If there is no previous command or if the previous command was not a Q, q, T or t,\n // assume the control point is coincident with the current point\n controlX = x;\n controlY = y;\n } else if (previous[0] === 't') {\n // calculate reflection of previous control points for t\n controlX = 2 * x - tempControlX;\n controlY = 2 * y - tempControlY;\n } else if (previous[0] === 'q') {\n // calculate reflection of previous control points for q\n controlX = 2 * x - controlX;\n controlY = 2 * y - controlY;\n }\n\n tempControlX = controlX;\n tempControlY = controlY;\n context.quadraticCurveTo(controlX + l, controlY + t, tempX + l, tempY + t);\n x = tempX;\n y = tempY;\n controlX = x + current[1];\n controlY = y + current[2];\n break;\n\n case 'T':\n tempX = current[1];\n tempY = current[2]; // calculate reflection of previous control points\n\n controlX = 2 * x - controlX;\n controlY = 2 * y - controlY;\n context.quadraticCurveTo(controlX + l, controlY + t, tempX + l, tempY + t);\n x = tempX;\n y = tempY;\n break;\n\n case 'a':\n drawArc(context, x + l, y + t, [current[1], current[2], current[3], current[4], current[5], current[6] + x + l, current[7] + y + t]);\n x += current[6];\n y += current[7];\n break;\n\n case 'A':\n drawArc(context, x + l, y + t, [current[1], current[2], current[3], current[4], current[5], current[6] + l, current[7] + t]);\n x = current[6];\n y = current[7];\n break;\n\n case 'z':\n case 'Z':\n context.closePath();\n break;\n }\n\n previous = current;\n }\n}\n\nfunction drawArc(context, x, y, coords) {\n const seg = segments(coords[5], // end x\n coords[6], // end y\n coords[0], // radius x\n coords[1], // radius y\n coords[3], // large flag\n coords[4], // sweep flag\n coords[2], // rotation\n x, y);\n\n for (let i = 0; i < seg.length; ++i) {\n const bez = bezier(seg[i]);\n context.bezierCurveTo(bez[0], bez[1], bez[2], bez[3], bez[4], bez[5]);\n }\n}\n\nconst Tan30 = 0.5773502691896257;\nconst builtins = {\n 'circle': {\n draw: function (context, size) {\n const r = Math.sqrt(size) / 2;\n context.moveTo(r, 0);\n context.arc(0, 0, r, 0, Tau);\n }\n },\n 'cross': {\n draw: function (context, size) {\n var r = Math.sqrt(size) / 2,\n s = r / 2.5;\n context.moveTo(-r, -s);\n context.lineTo(-r, s);\n context.lineTo(-s, s);\n context.lineTo(-s, r);\n context.lineTo(s, r);\n context.lineTo(s, s);\n context.lineTo(r, s);\n context.lineTo(r, -s);\n context.lineTo(s, -s);\n context.lineTo(s, -r);\n context.lineTo(-s, -r);\n context.lineTo(-s, -s);\n context.closePath();\n }\n },\n 'diamond': {\n draw: function (context, size) {\n const r = Math.sqrt(size) / 2;\n context.moveTo(-r, 0);\n context.lineTo(0, -r);\n context.lineTo(r, 0);\n context.lineTo(0, r);\n context.closePath();\n }\n },\n 'square': {\n draw: function (context, size) {\n var w = Math.sqrt(size),\n x = -w / 2;\n context.rect(x, x, w, w);\n }\n },\n 'arrow': {\n draw: function (context, size) {\n var r = Math.sqrt(size) / 2,\n s = r / 7,\n t = r / 2.5,\n v = r / 8;\n context.moveTo(-s, r);\n context.lineTo(s, r);\n context.lineTo(s, -v);\n context.lineTo(t, -v);\n context.lineTo(0, -r);\n context.lineTo(-t, -v);\n context.lineTo(-s, -v);\n context.closePath();\n }\n },\n 'wedge': {\n draw: function (context, size) {\n var r = Math.sqrt(size) / 2,\n h = HalfSqrt3 * r,\n o = h - r * Tan30,\n b = r / 4;\n context.moveTo(0, -h - o);\n context.lineTo(-b, h - o);\n context.lineTo(b, h - o);\n context.closePath();\n }\n },\n 'triangle': {\n draw: function (context, size) {\n var r = Math.sqrt(size) / 2,\n h = HalfSqrt3 * r,\n o = h - r * Tan30;\n context.moveTo(0, -h - o);\n context.lineTo(-r, h - o);\n context.lineTo(r, h - o);\n context.closePath();\n }\n },\n 'triangle-up': {\n draw: function (context, size) {\n var r = Math.sqrt(size) / 2,\n h = HalfSqrt3 * r;\n context.moveTo(0, -h);\n context.lineTo(-r, h);\n context.lineTo(r, h);\n context.closePath();\n }\n },\n 'triangle-down': {\n draw: function (context, size) {\n var r = Math.sqrt(size) / 2,\n h = HalfSqrt3 * r;\n context.moveTo(0, h);\n context.lineTo(-r, -h);\n context.lineTo(r, -h);\n context.closePath();\n }\n },\n 'triangle-right': {\n draw: function (context, size) {\n var r = Math.sqrt(size) / 2,\n h = HalfSqrt3 * r;\n context.moveTo(h, 0);\n context.lineTo(-h, -r);\n context.lineTo(-h, r);\n context.closePath();\n }\n },\n 'triangle-left': {\n draw: function (context, size) {\n var r = Math.sqrt(size) / 2,\n h = HalfSqrt3 * r;\n context.moveTo(-h, 0);\n context.lineTo(h, -r);\n context.lineTo(h, r);\n context.closePath();\n }\n },\n 'stroke': {\n draw: function (context, size) {\n const r = Math.sqrt(size) / 2;\n context.moveTo(-r, 0);\n context.lineTo(r, 0);\n }\n }\n};\nfunction symbols(_) {\n return hasOwnProperty(builtins, _) ? builtins[_] : customSymbol(_);\n}\nvar custom = {};\n\nfunction customSymbol(path) {\n if (!hasOwnProperty(custom, path)) {\n const parsed = pathParse(path);\n custom[path] = {\n draw: function (context, size) {\n pathRender(context, parsed, 0, 0, Math.sqrt(size) / 2);\n }\n };\n }\n\n return custom[path];\n}\n\nconst C = 0.448084975506; // C = 1 - c\n\nfunction rectangleX(d) {\n return d.x;\n}\n\nfunction rectangleY(d) {\n return d.y;\n}\n\nfunction rectangleWidth(d) {\n return d.width;\n}\n\nfunction rectangleHeight(d) {\n return d.height;\n}\n\nfunction number(_) {\n return typeof _ === 'function' ? _ : () => +_;\n}\n\nfunction clamp(value, min, max) {\n return Math.max(min, Math.min(value, max));\n}\n\nfunction vg_rect () {\n var x = rectangleX,\n y = rectangleY,\n width = rectangleWidth,\n height = rectangleHeight,\n crTL = number(0),\n crTR = crTL,\n crBL = crTL,\n crBR = crTL,\n context = null;\n\n function rectangle(_, x0, y0) {\n var buffer,\n x1 = x0 != null ? x0 : +x.call(this, _),\n y1 = y0 != null ? y0 : +y.call(this, _),\n w = +width.call(this, _),\n h = +height.call(this, _),\n s = Math.min(w, h) / 2,\n tl = clamp(+crTL.call(this, _), 0, s),\n tr = clamp(+crTR.call(this, _), 0, s),\n bl = clamp(+crBL.call(this, _), 0, s),\n br = clamp(+crBR.call(this, _), 0, s);\n if (!context) context = buffer = path$3();\n\n if (tl <= 0 && tr <= 0 && bl <= 0 && br <= 0) {\n context.rect(x1, y1, w, h);\n } else {\n var x2 = x1 + w,\n y2 = y1 + h;\n context.moveTo(x1 + tl, y1);\n context.lineTo(x2 - tr, y1);\n context.bezierCurveTo(x2 - C * tr, y1, x2, y1 + C * tr, x2, y1 + tr);\n context.lineTo(x2, y2 - br);\n context.bezierCurveTo(x2, y2 - C * br, x2 - C * br, y2, x2 - br, y2);\n context.lineTo(x1 + bl, y2);\n context.bezierCurveTo(x1 + C * bl, y2, x1, y2 - C * bl, x1, y2 - bl);\n context.lineTo(x1, y1 + tl);\n context.bezierCurveTo(x1, y1 + C * tl, x1 + C * tl, y1, x1 + tl, y1);\n context.closePath();\n }\n\n if (buffer) {\n context = null;\n return buffer + '' || null;\n }\n }\n\n rectangle.x = function (_) {\n if (arguments.length) {\n x = number(_);\n return rectangle;\n } else {\n return x;\n }\n };\n\n rectangle.y = function (_) {\n if (arguments.length) {\n y = number(_);\n return rectangle;\n } else {\n return y;\n }\n };\n\n rectangle.width = function (_) {\n if (arguments.length) {\n width = number(_);\n return rectangle;\n } else {\n return width;\n }\n };\n\n rectangle.height = function (_) {\n if (arguments.length) {\n height = number(_);\n return rectangle;\n } else {\n return height;\n }\n };\n\n rectangle.cornerRadius = function (tl, tr, br, bl) {\n if (arguments.length) {\n crTL = number(tl);\n crTR = tr != null ? number(tr) : crTL;\n crBR = br != null ? number(br) : crTL;\n crBL = bl != null ? number(bl) : crTR;\n return rectangle;\n } else {\n return crTL;\n }\n };\n\n rectangle.context = function (_) {\n if (arguments.length) {\n context = _ == null ? null : _;\n return rectangle;\n } else {\n return context;\n }\n };\n\n return rectangle;\n}\n\nfunction vg_trail () {\n var x,\n y,\n size,\n defined,\n context = null,\n ready,\n x1,\n y1,\n r1;\n\n function point(x2, y2, w2) {\n const r2 = w2 / 2;\n\n if (ready) {\n var ux = y1 - y2,\n uy = x2 - x1;\n\n if (ux || uy) {\n // get normal vector\n var ud = Math.sqrt(ux * ux + uy * uy),\n rx = (ux /= ud) * r1,\n ry = (uy /= ud) * r1,\n t = Math.atan2(uy, ux); // draw segment\n\n context.moveTo(x1 - rx, y1 - ry);\n context.lineTo(x2 - ux * r2, y2 - uy * r2);\n context.arc(x2, y2, r2, t - Math.PI, t);\n context.lineTo(x1 + rx, y1 + ry);\n context.arc(x1, y1, r1, t, t + Math.PI);\n } else {\n context.arc(x2, y2, r2, 0, Tau);\n }\n\n context.closePath();\n } else {\n ready = 1;\n }\n\n x1 = x2;\n y1 = y2;\n r1 = r2;\n }\n\n function trail(data) {\n var i,\n n = data.length,\n d,\n defined0 = false,\n buffer;\n if (context == null) context = buffer = path$3();\n\n for (i = 0; i <= n; ++i) {\n if (!(i < n && defined(d = data[i], i, data)) === defined0) {\n if (defined0 = !defined0) ready = 0;\n }\n\n if (defined0) point(+x(d, i, data), +y(d, i, data), +size(d, i, data));\n }\n\n if (buffer) {\n context = null;\n return buffer + '' || null;\n }\n }\n\n trail.x = function (_) {\n if (arguments.length) {\n x = _;\n return trail;\n } else {\n return x;\n }\n };\n\n trail.y = function (_) {\n if (arguments.length) {\n y = _;\n return trail;\n } else {\n return y;\n }\n };\n\n trail.size = function (_) {\n if (arguments.length) {\n size = _;\n return trail;\n } else {\n return size;\n }\n };\n\n trail.defined = function (_) {\n if (arguments.length) {\n defined = _;\n return trail;\n } else {\n return defined;\n }\n };\n\n trail.context = function (_) {\n if (arguments.length) {\n if (_ == null) {\n context = null;\n } else {\n context = _;\n }\n\n return trail;\n } else {\n return context;\n }\n };\n\n return trail;\n}\n\nfunction value$1(a, b) {\n return a != null ? a : b;\n}\n\nconst x = item => item.x || 0,\n y = item => item.y || 0,\n w = item => item.width || 0,\n h = item => item.height || 0,\n xw = item => (item.x || 0) + (item.width || 0),\n yh = item => (item.y || 0) + (item.height || 0),\n sa = item => item.startAngle || 0,\n ea = item => item.endAngle || 0,\n pa = item => item.padAngle || 0,\n ir = item => item.innerRadius || 0,\n or = item => item.outerRadius || 0,\n cr = item => item.cornerRadius || 0,\n tl = item => value$1(item.cornerRadiusTopLeft, item.cornerRadius) || 0,\n tr = item => value$1(item.cornerRadiusTopRight, item.cornerRadius) || 0,\n br = item => value$1(item.cornerRadiusBottomRight, item.cornerRadius) || 0,\n bl = item => value$1(item.cornerRadiusBottomLeft, item.cornerRadius) || 0,\n sz = item => value$1(item.size, 64),\n ts = item => item.size || 1,\n def = item => !(item.defined === false),\n type = item => symbols(item.shape || 'circle');\n\nconst arcShape = arc$2().startAngle(sa).endAngle(ea).padAngle(pa).innerRadius(ir).outerRadius(or).cornerRadius(cr),\n areavShape = area$2().x(x).y1(y).y0(yh).defined(def),\n areahShape = area$2().y(y).x1(x).x0(xw).defined(def),\n lineShape = line$2().x(x).y(y).defined(def),\n rectShape = vg_rect().x(x).y(y).width(w).height(h).cornerRadius(tl, tr, br, bl),\n symbolShape = symbol$2().type(type).size(sz),\n trailShape = vg_trail().x(x).y(y).defined(def).size(ts);\nfunction hasCornerRadius(item) {\n return item.cornerRadius || item.cornerRadiusTopLeft || item.cornerRadiusTopRight || item.cornerRadiusBottomRight || item.cornerRadiusBottomLeft;\n}\nfunction arc$1(context, item) {\n return arcShape.context(context)(item);\n}\nfunction area$1(context, items) {\n const item = items[0],\n interp = item.interpolate || 'linear';\n return (item.orient === 'horizontal' ? areahShape : areavShape).curve(curves(interp, item.orient, item.tension)).context(context)(items);\n}\nfunction line$1(context, items) {\n const item = items[0],\n interp = item.interpolate || 'linear';\n return lineShape.curve(curves(interp, item.orient, item.tension)).context(context)(items);\n}\nfunction rectangle(context, item, x, y) {\n return rectShape.context(context)(item, x, y);\n}\nfunction shape$1(context, item) {\n return (item.mark.shape || item.shape).context(context)(item);\n}\nfunction symbol$1(context, item) {\n return symbolShape.context(context)(item);\n}\nfunction trail$1(context, items) {\n return trailShape.context(context)(items);\n}\n\nvar clip_id = 1;\nfunction resetSVGClipId() {\n clip_id = 1;\n}\nfunction clip$1 (renderer, item, size) {\n var clip = item.clip,\n defs = renderer._defs,\n id = item.clip_id || (item.clip_id = 'clip' + clip_id++),\n c = defs.clipping[id] || (defs.clipping[id] = {\n id: id\n });\n\n if (isFunction(clip)) {\n c.path = clip(null);\n } else if (hasCornerRadius(size)) {\n c.path = rectangle(null, size, 0, 0);\n } else {\n c.width = size.width || 0;\n c.height = size.height || 0;\n }\n\n return 'url(#' + id + ')';\n}\n\nfunction Bounds(b) {\n this.clear();\n if (b) this.union(b);\n}\nBounds.prototype = {\n clone() {\n return new Bounds(this);\n },\n\n clear() {\n this.x1 = +Number.MAX_VALUE;\n this.y1 = +Number.MAX_VALUE;\n this.x2 = -Number.MAX_VALUE;\n this.y2 = -Number.MAX_VALUE;\n return this;\n },\n\n empty() {\n return this.x1 === +Number.MAX_VALUE && this.y1 === +Number.MAX_VALUE && this.x2 === -Number.MAX_VALUE && this.y2 === -Number.MAX_VALUE;\n },\n\n equals(b) {\n return this.x1 === b.x1 && this.y1 === b.y1 && this.x2 === b.x2 && this.y2 === b.y2;\n },\n\n set(x1, y1, x2, y2) {\n if (x2 < x1) {\n this.x2 = x1;\n this.x1 = x2;\n } else {\n this.x1 = x1;\n this.x2 = x2;\n }\n\n if (y2 < y1) {\n this.y2 = y1;\n this.y1 = y2;\n } else {\n this.y1 = y1;\n this.y2 = y2;\n }\n\n return this;\n },\n\n add(x, y) {\n if (x < this.x1) this.x1 = x;\n if (y < this.y1) this.y1 = y;\n if (x > this.x2) this.x2 = x;\n if (y > this.y2) this.y2 = y;\n return this;\n },\n\n expand(d) {\n this.x1 -= d;\n this.y1 -= d;\n this.x2 += d;\n this.y2 += d;\n return this;\n },\n\n round() {\n this.x1 = Math.floor(this.x1);\n this.y1 = Math.floor(this.y1);\n this.x2 = Math.ceil(this.x2);\n this.y2 = Math.ceil(this.y2);\n return this;\n },\n\n scale(s) {\n this.x1 *= s;\n this.y1 *= s;\n this.x2 *= s;\n this.y2 *= s;\n return this;\n },\n\n translate(dx, dy) {\n this.x1 += dx;\n this.x2 += dx;\n this.y1 += dy;\n this.y2 += dy;\n return this;\n },\n\n rotate(angle, x, y) {\n const p = this.rotatedPoints(angle, x, y);\n return this.clear().add(p[0], p[1]).add(p[2], p[3]).add(p[4], p[5]).add(p[6], p[7]);\n },\n\n rotatedPoints(angle, x, y) {\n var {\n x1,\n y1,\n x2,\n y2\n } = this,\n cos = Math.cos(angle),\n sin = Math.sin(angle),\n cx = x - x * cos + y * sin,\n cy = y - x * sin - y * cos;\n return [cos * x1 - sin * y1 + cx, sin * x1 + cos * y1 + cy, cos * x1 - sin * y2 + cx, sin * x1 + cos * y2 + cy, cos * x2 - sin * y1 + cx, sin * x2 + cos * y1 + cy, cos * x2 - sin * y2 + cx, sin * x2 + cos * y2 + cy];\n },\n\n union(b) {\n if (b.x1 < this.x1) this.x1 = b.x1;\n if (b.y1 < this.y1) this.y1 = b.y1;\n if (b.x2 > this.x2) this.x2 = b.x2;\n if (b.y2 > this.y2) this.y2 = b.y2;\n return this;\n },\n\n intersect(b) {\n if (b.x1 > this.x1) this.x1 = b.x1;\n if (b.y1 > this.y1) this.y1 = b.y1;\n if (b.x2 < this.x2) this.x2 = b.x2;\n if (b.y2 < this.y2) this.y2 = b.y2;\n return this;\n },\n\n encloses(b) {\n return b && this.x1 <= b.x1 && this.x2 >= b.x2 && this.y1 <= b.y1 && this.y2 >= b.y2;\n },\n\n alignsWith(b) {\n return b && (this.x1 == b.x1 || this.x2 == b.x2 || this.y1 == b.y1 || this.y2 == b.y2);\n },\n\n intersects(b) {\n return b && !(this.x2 < b.x1 || this.x1 > b.x2 || this.y2 < b.y1 || this.y1 > b.y2);\n },\n\n contains(x, y) {\n return !(x < this.x1 || x > this.x2 || y < this.y1 || y > this.y2);\n },\n\n width() {\n return this.x2 - this.x1;\n },\n\n height() {\n return this.y2 - this.y1;\n }\n\n};\n\nfunction Item(mark) {\n this.mark = mark;\n this.bounds = this.bounds || new Bounds();\n}\n\nfunction GroupItem(mark) {\n Item.call(this, mark);\n this.items = this.items || [];\n}\ninherits(GroupItem, Item);\n\nfunction ResourceLoader(customLoader) {\n this._pending = 0;\n this._loader = customLoader || loader();\n}\n\nfunction increment(loader) {\n loader._pending += 1;\n}\n\nfunction decrement(loader) {\n loader._pending -= 1;\n}\n\nResourceLoader.prototype = {\n pending() {\n return this._pending;\n },\n\n sanitizeURL(uri) {\n const loader = this;\n increment(loader);\n return loader._loader.sanitize(uri, {\n context: 'href'\n }).then(opt => {\n decrement(loader);\n return opt;\n }).catch(() => {\n decrement(loader);\n return null;\n });\n },\n\n loadImage(uri) {\n const loader = this,\n Image = image$1();\n increment(loader);\n return loader._loader.sanitize(uri, {\n context: 'image'\n }).then(opt => {\n const url = opt.href;\n if (!url || !Image) throw {\n url: url\n };\n const img = new Image(); // set crossOrigin only if cors is defined; empty string sets anonymous mode\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/crossOrigin\n\n const cors = hasOwnProperty(opt, 'crossOrigin') ? opt.crossOrigin : 'anonymous';\n if (cors != null) img.crossOrigin = cors; // attempt to load image resource\n\n img.onload = () => decrement(loader);\n\n img.onerror = () => decrement(loader);\n\n img.src = url;\n return img;\n }).catch(e => {\n decrement(loader);\n return {\n complete: false,\n width: 0,\n height: 0,\n src: e && e.url || ''\n };\n });\n },\n\n ready() {\n const loader = this;\n return new Promise(accept => {\n function poll(value) {\n if (!loader.pending()) accept(value);else setTimeout(() => {\n poll(true);\n }, 10);\n }\n\n poll(false);\n });\n }\n\n};\n\nfunction boundStroke (bounds, item, miter) {\n if (item.stroke && item.opacity !== 0 && item.strokeOpacity !== 0) {\n const sw = item.strokeWidth != null ? +item.strokeWidth : 1;\n bounds.expand(sw + (miter ? miterAdjustment(item, sw) : 0));\n }\n\n return bounds;\n}\n\nfunction miterAdjustment(item, strokeWidth) {\n // TODO: more sophisticated adjustment? Or miter support in boundContext?\n return item.strokeJoin && item.strokeJoin !== 'miter' ? 0 : strokeWidth;\n}\n\nconst circleThreshold = Tau - 1e-8;\nlet bounds, lx, ly, rot, ma, mb, mc, md;\n\nconst add = (x, y) => bounds.add(x, y);\n\nconst addL = (x, y) => add(lx = x, ly = y);\n\nconst addX = x => add(x, bounds.y1);\n\nconst addY = y => add(bounds.x1, y);\n\nconst px = (x, y) => ma * x + mc * y;\n\nconst py = (x, y) => mb * x + md * y;\n\nconst addp = (x, y) => add(px(x, y), py(x, y));\n\nconst addpL = (x, y) => addL(px(x, y), py(x, y));\n\nfunction boundContext (_, deg) {\n bounds = _;\n\n if (deg) {\n rot = deg * DegToRad;\n ma = md = Math.cos(rot);\n mb = Math.sin(rot);\n mc = -mb;\n } else {\n ma = md = 1;\n rot = mb = mc = 0;\n }\n\n return context$1;\n}\nconst context$1 = {\n beginPath() {},\n\n closePath() {},\n\n moveTo: addpL,\n lineTo: addpL,\n\n rect(x, y, w, h) {\n if (rot) {\n addp(x + w, y);\n addp(x + w, y + h);\n addp(x, y + h);\n addpL(x, y);\n } else {\n add(x + w, y + h);\n addL(x, y);\n }\n },\n\n quadraticCurveTo(x1, y1, x2, y2) {\n const px1 = px(x1, y1),\n py1 = py(x1, y1),\n px2 = px(x2, y2),\n py2 = py(x2, y2);\n quadExtrema(lx, px1, px2, addX);\n quadExtrema(ly, py1, py2, addY);\n addL(px2, py2);\n },\n\n bezierCurveTo(x1, y1, x2, y2, x3, y3) {\n const px1 = px(x1, y1),\n py1 = py(x1, y1),\n px2 = px(x2, y2),\n py2 = py(x2, y2),\n px3 = px(x3, y3),\n py3 = py(x3, y3);\n cubicExtrema(lx, px1, px2, px3, addX);\n cubicExtrema(ly, py1, py2, py3, addY);\n addL(px3, py3);\n },\n\n arc(cx, cy, r, sa, ea, ccw) {\n sa += rot;\n ea += rot; // store last point on path\n\n lx = r * Math.cos(ea) + cx;\n ly = r * Math.sin(ea) + cy;\n\n if (Math.abs(ea - sa) > circleThreshold) {\n // treat as full circle\n add(cx - r, cy - r);\n add(cx + r, cy + r);\n } else {\n const update = a => add(r * Math.cos(a) + cx, r * Math.sin(a) + cy);\n\n let s, i; // sample end points\n\n update(sa);\n update(ea); // sample interior points aligned with 90 degrees\n\n if (ea !== sa) {\n sa = sa % Tau;\n if (sa < 0) sa += Tau;\n ea = ea % Tau;\n if (ea < 0) ea += Tau;\n\n if (ea < sa) {\n ccw = !ccw; // flip direction\n\n s = sa;\n sa = ea;\n ea = s; // swap end-points\n }\n\n if (ccw) {\n ea -= Tau;\n s = sa - sa % HalfPi;\n\n for (i = 0; i < 4 && s > ea; ++i, s -= HalfPi) update(s);\n } else {\n s = sa - sa % HalfPi + HalfPi;\n\n for (i = 0; i < 4 && s < ea; ++i, s = s + HalfPi) update(s);\n }\n }\n }\n }\n\n};\n\nfunction quadExtrema(x0, x1, x2, cb) {\n const t = (x0 - x1) / (x0 + x2 - 2 * x1);\n if (0 < t && t < 1) cb(x0 + (x1 - x0) * t);\n}\n\nfunction cubicExtrema(x0, x1, x2, x3, cb) {\n const a = x3 - x0 + 3 * x1 - 3 * x2,\n b = x0 + x2 - 2 * x1,\n c = x0 - x1;\n let t0 = 0,\n t1 = 0,\n r; // solve for parameter t\n\n if (Math.abs(a) > Epsilon) {\n // quadratic equation\n r = b * b + c * a;\n\n if (r >= 0) {\n r = Math.sqrt(r);\n t0 = (-b + r) / a;\n t1 = (-b - r) / a;\n }\n } else {\n // linear equation\n t0 = 0.5 * c / b;\n } // calculate position\n\n\n if (0 < t0 && t0 < 1) cb(cubic(t0, x0, x1, x2, x3));\n if (0 < t1 && t1 < 1) cb(cubic(t1, x0, x1, x2, x3));\n}\n\nfunction cubic(t, x0, x1, x2, x3) {\n const s = 1 - t,\n s2 = s * s,\n t2 = t * t;\n return s2 * s * x0 + 3 * s2 * t * x1 + 3 * s * t2 * x2 + t2 * t * x3;\n}\n\nvar context = (context = canvas(1, 1)) ? context.getContext('2d') : null;\n\nconst b = new Bounds();\nfunction intersectPath(draw) {\n return function (item, brush) {\n // rely on (inaccurate) bounds intersection if no context\n if (!context) return true; // add path to offscreen graphics context\n\n draw(context, item); // get bounds intersection region\n\n b.clear().union(item.bounds).intersect(brush).round();\n const {\n x1,\n y1,\n x2,\n y2\n } = b; // iterate over intersection region\n // perform fine grained inclusion test\n\n for (let y = y1; y <= y2; ++y) {\n for (let x = x1; x <= x2; ++x) {\n if (context.isPointInPath(x, y)) {\n return true;\n }\n }\n } // false if no hits in intersection region\n\n\n return false;\n };\n}\nfunction intersectPoint(item, box) {\n return box.contains(item.x || 0, item.y || 0);\n}\nfunction intersectRect(item, box) {\n const x = item.x || 0,\n y = item.y || 0,\n w = item.width || 0,\n h = item.height || 0;\n return box.intersects(b.set(x, y, x + w, y + h));\n}\nfunction intersectRule(item, box) {\n const x = item.x || 0,\n y = item.y || 0,\n x2 = item.x2 != null ? item.x2 : x,\n y2 = item.y2 != null ? item.y2 : y;\n return intersectBoxLine(box, x, y, x2, y2);\n}\nfunction intersectBoxLine(box, x, y, u, v) {\n const {\n x1,\n y1,\n x2,\n y2\n } = box,\n dx = u - x,\n dy = v - y;\n let t0 = 0,\n t1 = 1,\n p,\n q,\n r,\n e;\n\n for (e = 0; e < 4; ++e) {\n if (e === 0) {\n p = -dx;\n q = -(x1 - x);\n }\n\n if (e === 1) {\n p = dx;\n q = x2 - x;\n }\n\n if (e === 2) {\n p = -dy;\n q = -(y1 - y);\n }\n\n if (e === 3) {\n p = dy;\n q = y2 - y;\n }\n\n if (Math.abs(p) < 1e-10 && q < 0) return false;\n r = q / p;\n\n if (p < 0) {\n if (r > t1) return false;else if (r > t0) t0 = r;\n } else if (p > 0) {\n if (r < t0) return false;else if (r < t1) t1 = r;\n }\n }\n\n return true;\n}\n\nfunction blend (context, item) {\n context.globalCompositeOperation = item.blend || 'source-over';\n}\n\nfunction value (value, dflt) {\n return value == null ? dflt : value;\n}\n\nfunction addStops(gradient, stops) {\n const n = stops.length;\n\n for (let i = 0; i < n; ++i) {\n gradient.addColorStop(stops[i].offset, stops[i].color);\n }\n\n return gradient;\n}\n\nfunction gradient (context, spec, bounds) {\n const w = bounds.width(),\n h = bounds.height();\n let gradient;\n\n if (spec.gradient === 'radial') {\n gradient = context.createRadialGradient(bounds.x1 + value(spec.x1, 0.5) * w, bounds.y1 + value(spec.y1, 0.5) * h, Math.max(w, h) * value(spec.r1, 0), bounds.x1 + value(spec.x2, 0.5) * w, bounds.y1 + value(spec.y2, 0.5) * h, Math.max(w, h) * value(spec.r2, 0.5));\n } else {\n // linear gradient\n const x1 = value(spec.x1, 0),\n y1 = value(spec.y1, 0),\n x2 = value(spec.x2, 1),\n y2 = value(spec.y2, 0);\n\n if (x1 === x2 || y1 === y2 || w === h) {\n // axis aligned: use normal gradient\n gradient = context.createLinearGradient(bounds.x1 + x1 * w, bounds.y1 + y1 * h, bounds.x1 + x2 * w, bounds.y1 + y2 * h);\n } else {\n // not axis aligned: render gradient into a pattern (#2365)\n // this allows us to use normalized bounding box coordinates\n const image = canvas(Math.ceil(w), Math.ceil(h)),\n ictx = image.getContext('2d');\n ictx.scale(w, h);\n ictx.fillStyle = addStops(ictx.createLinearGradient(x1, y1, x2, y2), spec.stops);\n ictx.fillRect(0, 0, w, h);\n return context.createPattern(image, 'no-repeat');\n }\n }\n\n return addStops(gradient, spec.stops);\n}\n\nfunction color (context, item, value) {\n return isGradient(value) ? gradient(context, value, item.bounds) : value;\n}\n\nfunction fill (context, item, opacity) {\n opacity *= item.fillOpacity == null ? 1 : item.fillOpacity;\n\n if (opacity > 0) {\n context.globalAlpha = opacity;\n context.fillStyle = color(context, item, item.fill);\n return true;\n } else {\n return false;\n }\n}\n\nvar Empty = [];\nfunction stroke (context, item, opacity) {\n var lw = (lw = item.strokeWidth) != null ? lw : 1;\n if (lw <= 0) return false;\n opacity *= item.strokeOpacity == null ? 1 : item.strokeOpacity;\n\n if (opacity > 0) {\n context.globalAlpha = opacity;\n context.strokeStyle = color(context, item, item.stroke);\n context.lineWidth = lw;\n context.lineCap = item.strokeCap || 'butt';\n context.lineJoin = item.strokeJoin || 'miter';\n context.miterLimit = item.strokeMiterLimit || 10;\n\n if (context.setLineDash) {\n context.setLineDash(item.strokeDash || Empty);\n context.lineDashOffset = item.strokeDashOffset || 0;\n }\n\n return true;\n } else {\n return false;\n }\n}\n\nfunction compare(a, b) {\n return a.zindex - b.zindex || a.index - b.index;\n}\n\nfunction zorder(scene) {\n if (!scene.zdirty) return scene.zitems;\n var items = scene.items,\n output = [],\n item,\n i,\n n;\n\n for (i = 0, n = items.length; i < n; ++i) {\n item = items[i];\n item.index = i;\n if (item.zindex) output.push(item);\n }\n\n scene.zdirty = false;\n return scene.zitems = output.sort(compare);\n}\nfunction visit(scene, visitor) {\n var items = scene.items,\n i,\n n;\n if (!items || !items.length) return;\n const zitems = zorder(scene);\n\n if (zitems && zitems.length) {\n for (i = 0, n = items.length; i < n; ++i) {\n if (!items[i].zindex) visitor(items[i]);\n }\n\n items = zitems;\n }\n\n for (i = 0, n = items.length; i < n; ++i) {\n visitor(items[i]);\n }\n}\nfunction pickVisit(scene, visitor) {\n var items = scene.items,\n hit,\n i;\n if (!items || !items.length) return null;\n const zitems = zorder(scene);\n if (zitems && zitems.length) items = zitems;\n\n for (i = items.length; --i >= 0;) {\n if (hit = visitor(items[i])) return hit;\n }\n\n if (items === zitems) {\n for (items = scene.items, i = items.length; --i >= 0;) {\n if (!items[i].zindex) {\n if (hit = visitor(items[i])) return hit;\n }\n }\n }\n\n return null;\n}\n\nfunction drawAll(path) {\n return function (context, scene, bounds) {\n visit(scene, item => {\n if (!bounds || bounds.intersects(item.bounds)) {\n drawPath(path, context, item, item);\n }\n });\n };\n}\nfunction drawOne(path) {\n return function (context, scene, bounds) {\n if (scene.items.length && (!bounds || bounds.intersects(scene.bounds))) {\n drawPath(path, context, scene.items[0], scene.items);\n }\n };\n}\n\nfunction drawPath(path, context, item, items) {\n var opacity = item.opacity == null ? 1 : item.opacity;\n if (opacity === 0) return;\n if (path(context, items)) return;\n blend(context, item);\n\n if (item.fill && fill(context, item, opacity)) {\n context.fill();\n }\n\n if (item.stroke && stroke(context, item, opacity)) {\n context.stroke();\n }\n}\n\nfunction pick$1(test) {\n test = test || truthy;\n return function (context, scene, x, y, gx, gy) {\n x *= context.pixelRatio;\n y *= context.pixelRatio;\n return pickVisit(scene, item => {\n const b = item.bounds; // first hit test against bounding box\n\n if (b && !b.contains(gx, gy) || !b) return; // if in bounding box, perform more careful test\n\n if (test(context, item, x, y, gx, gy)) return item;\n });\n };\n}\nfunction hitPath(path, filled) {\n return function (context, o, x, y) {\n var item = Array.isArray(o) ? o[0] : o,\n fill = filled == null ? item.fill : filled,\n stroke = item.stroke && context.isPointInStroke,\n lw,\n lc;\n\n if (stroke) {\n lw = item.strokeWidth;\n lc = item.strokeCap;\n context.lineWidth = lw != null ? lw : 1;\n context.lineCap = lc != null ? lc : 'butt';\n }\n\n return path(context, o) ? false : fill && context.isPointInPath(x, y) || stroke && context.isPointInStroke(x, y);\n };\n}\nfunction pickPath(path) {\n return pick$1(hitPath(path));\n}\n\nfunction translate(x, y) {\n return 'translate(' + x + ',' + y + ')';\n}\nfunction rotate(a) {\n return 'rotate(' + a + ')';\n}\nfunction scale(scaleX, scaleY) {\n return 'scale(' + scaleX + ',' + scaleY + ')';\n}\nfunction translateItem(item) {\n return translate(item.x || 0, item.y || 0);\n}\nfunction rotateItem(item) {\n return translate(item.x || 0, item.y || 0) + (item.angle ? ' ' + rotate(item.angle) : '');\n}\nfunction transformItem(item) {\n return translate(item.x || 0, item.y || 0) + (item.angle ? ' ' + rotate(item.angle) : '') + (item.scaleX || item.scaleY ? ' ' + scale(item.scaleX || 1, item.scaleY || 1) : '');\n}\n\nfunction markItemPath (type, shape, isect) {\n function attr(emit, item) {\n emit('transform', rotateItem(item));\n emit('d', shape(null, item));\n }\n\n function bound(bounds, item) {\n shape(boundContext(bounds, item.angle), item);\n return boundStroke(bounds, item).translate(item.x || 0, item.y || 0);\n }\n\n function draw(context, item) {\n var x = item.x || 0,\n y = item.y || 0,\n a = item.angle || 0;\n context.translate(x, y);\n if (a) context.rotate(a *= DegToRad);\n context.beginPath();\n shape(context, item);\n if (a) context.rotate(-a);\n context.translate(-x, -y);\n }\n\n return {\n type: type,\n tag: 'path',\n nested: false,\n attr: attr,\n bound: bound,\n draw: drawAll(draw),\n pick: pickPath(draw),\n isect: isect || intersectPath(draw)\n };\n}\n\nvar arc = markItemPath('arc', arc$1);\n\nfunction pickArea(a, p) {\n var v = a[0].orient === 'horizontal' ? p[1] : p[0],\n z = a[0].orient === 'horizontal' ? 'y' : 'x',\n i = a.length,\n min = +Infinity,\n hit,\n d;\n\n while (--i >= 0) {\n if (a[i].defined === false) continue;\n d = Math.abs(a[i][z] - v);\n\n if (d < min) {\n min = d;\n hit = a[i];\n }\n }\n\n return hit;\n}\nfunction pickLine(a, p) {\n var t = Math.pow(a[0].strokeWidth || 1, 2),\n i = a.length,\n dx,\n dy,\n dd;\n\n while (--i >= 0) {\n if (a[i].defined === false) continue;\n dx = a[i].x - p[0];\n dy = a[i].y - p[1];\n dd = dx * dx + dy * dy;\n if (dd < t) return a[i];\n }\n\n return null;\n}\nfunction pickTrail(a, p) {\n var i = a.length,\n dx,\n dy,\n dd;\n\n while (--i >= 0) {\n if (a[i].defined === false) continue;\n dx = a[i].x - p[0];\n dy = a[i].y - p[1];\n dd = dx * dx + dy * dy;\n dx = a[i].size || 1;\n if (dd < dx * dx) return a[i];\n }\n\n return null;\n}\n\nfunction markMultiItemPath (type, shape, tip) {\n function attr(emit, item) {\n var items = item.mark.items;\n if (items.length) emit('d', shape(null, items));\n }\n\n function bound(bounds, mark) {\n var items = mark.items;\n\n if (items.length === 0) {\n return bounds;\n } else {\n shape(boundContext(bounds), items);\n return boundStroke(bounds, items[0]);\n }\n }\n\n function draw(context, items) {\n context.beginPath();\n shape(context, items);\n }\n\n const hit = hitPath(draw);\n\n function pick(context, scene, x, y, gx, gy) {\n var items = scene.items,\n b = scene.bounds;\n\n if (!items || !items.length || b && !b.contains(gx, gy)) {\n return null;\n }\n\n x *= context.pixelRatio;\n y *= context.pixelRatio;\n return hit(context, items, x, y) ? items[0] : null;\n }\n\n return {\n type: type,\n tag: 'path',\n nested: true,\n attr: attr,\n bound: bound,\n draw: drawOne(draw),\n pick: pick,\n isect: intersectPoint,\n tip: tip\n };\n}\n\nvar area = markMultiItemPath('area', area$1, pickArea);\n\nfunction clip (context, scene) {\n var clip = scene.clip;\n context.save();\n\n if (isFunction(clip)) {\n context.beginPath();\n clip(context);\n context.clip();\n } else {\n clipGroup(context, scene.group);\n }\n}\nfunction clipGroup(context, group) {\n context.beginPath();\n hasCornerRadius(group) ? rectangle(context, group, 0, 0) : context.rect(0, 0, group.width || 0, group.height || 0);\n context.clip();\n}\n\nfunction offset$1(item) {\n const sw = value(item.strokeWidth, 1);\n return item.strokeOffset != null ? item.strokeOffset : item.stroke && sw > 0.5 && sw < 1.5 ? 0.5 - Math.abs(sw - 1) : 0;\n}\n\nfunction attr$5(emit, item) {\n emit('transform', translateItem(item));\n}\n\nfunction emitRectangle(emit, item) {\n const off = offset$1(item);\n emit('d', rectangle(null, item, off, off));\n}\n\nfunction background(emit, item) {\n emit('class', 'background');\n emit('aria-hidden', true);\n emitRectangle(emit, item);\n}\n\nfunction foreground(emit, item) {\n emit('class', 'foreground');\n emit('aria-hidden', true);\n\n if (item.strokeForeground) {\n emitRectangle(emit, item);\n } else {\n emit('d', '');\n }\n}\n\nfunction content(emit, item, renderer) {\n const url = item.clip ? clip$1(renderer, item, item) : null;\n emit('clip-path', url);\n}\n\nfunction bound$5(bounds, group) {\n if (!group.clip && group.items) {\n const items = group.items,\n m = items.length;\n\n for (let j = 0; j < m; ++j) {\n bounds.union(items[j].bounds);\n }\n }\n\n if ((group.clip || group.width || group.height) && !group.noBound) {\n bounds.add(0, 0).add(group.width || 0, group.height || 0);\n }\n\n boundStroke(bounds, group);\n return bounds.translate(group.x || 0, group.y || 0);\n}\n\nfunction rectanglePath(context, group, x, y) {\n const off = offset$1(group);\n context.beginPath();\n rectangle(context, group, (x || 0) + off, (y || 0) + off);\n}\n\nconst hitBackground = hitPath(rectanglePath);\nconst hitForeground = hitPath(rectanglePath, false);\nconst hitCorner = hitPath(rectanglePath, true);\n\nfunction draw$4(context, scene, bounds) {\n visit(scene, group => {\n const gx = group.x || 0,\n gy = group.y || 0,\n fore = group.strokeForeground,\n opacity = group.opacity == null ? 1 : group.opacity; // draw group background\n\n if ((group.stroke || group.fill) && opacity) {\n rectanglePath(context, group, gx, gy);\n blend(context, group);\n\n if (group.fill && fill(context, group, opacity)) {\n context.fill();\n }\n\n if (group.stroke && !fore && stroke(context, group, opacity)) {\n context.stroke();\n }\n } // setup graphics context, set clip and bounds\n\n\n context.save();\n context.translate(gx, gy);\n if (group.clip) clipGroup(context, group);\n if (bounds) bounds.translate(-gx, -gy); // draw group contents\n\n visit(group, item => {\n this.draw(context, item, bounds);\n }); // restore graphics context\n\n if (bounds) bounds.translate(gx, gy);\n context.restore(); // draw group foreground\n\n if (fore && group.stroke && opacity) {\n rectanglePath(context, group, gx, gy);\n blend(context, group);\n\n if (stroke(context, group, opacity)) {\n context.stroke();\n }\n }\n });\n}\n\nfunction pick(context, scene, x, y, gx, gy) {\n if (scene.bounds && !scene.bounds.contains(gx, gy) || !scene.items) {\n return null;\n }\n\n const cx = x * context.pixelRatio,\n cy = y * context.pixelRatio;\n return pickVisit(scene, group => {\n let hit, dx, dy; // first hit test bounding box\n\n const b = group.bounds;\n if (b && !b.contains(gx, gy)) return; // passed bounds check, test rectangular clip\n\n dx = group.x || 0;\n dy = group.y || 0;\n const dw = dx + (group.width || 0),\n dh = dy + (group.height || 0),\n c = group.clip;\n if (c && (gx < dx || gx > dw || gy < dy || gy > dh)) return; // adjust coordinate system\n\n context.save();\n context.translate(dx, dy);\n dx = gx - dx;\n dy = gy - dy; // test background for rounded corner clip\n\n if (c && hasCornerRadius(group) && !hitCorner(context, group, cx, cy)) {\n context.restore();\n return null;\n }\n\n const fore = group.strokeForeground,\n ix = scene.interactive !== false; // hit test against group foreground\n\n if (ix && fore && group.stroke && hitForeground(context, group, cx, cy)) {\n context.restore();\n return group;\n } // hit test against contained marks\n\n\n hit = pickVisit(group, mark => pickMark(mark, dx, dy) ? this.pick(mark, x, y, dx, dy) : null); // hit test against group background\n\n if (!hit && ix && (group.fill || !fore && group.stroke) && hitBackground(context, group, cx, cy)) {\n hit = group;\n } // restore state and return\n\n\n context.restore();\n return hit || null;\n });\n}\n\nfunction pickMark(mark, x, y) {\n return (mark.interactive !== false || mark.marktype === 'group') && mark.bounds && mark.bounds.contains(x, y);\n}\n\nvar group = {\n type: 'group',\n tag: 'g',\n nested: false,\n attr: attr$5,\n bound: bound$5,\n draw: draw$4,\n pick: pick,\n isect: intersectRect,\n content: content,\n background: background,\n foreground: foreground\n};\n\nvar metadata = {\n 'xmlns': 'http://www.w3.org/2000/svg',\n 'xmlns:xlink': 'http://www.w3.org/1999/xlink',\n 'version': '1.1'\n};\n\nfunction getImage(item, renderer) {\n var image = item.image;\n\n if (!image || item.url && item.url !== image.url) {\n image = {\n complete: false,\n width: 0,\n height: 0\n };\n renderer.loadImage(item.url).then(image => {\n item.image = image;\n item.image.url = item.url;\n });\n }\n\n return image;\n}\n\nfunction imageWidth(item, image) {\n return item.width != null ? item.width : !image || !image.width ? 0 : item.aspect !== false && item.height ? item.height * image.width / image.height : image.width;\n}\n\nfunction imageHeight(item, image) {\n return item.height != null ? item.height : !image || !image.height ? 0 : item.aspect !== false && item.width ? item.width * image.height / image.width : image.height;\n}\n\nfunction imageXOffset(align, w) {\n return align === 'center' ? w / 2 : align === 'right' ? w : 0;\n}\n\nfunction imageYOffset(baseline, h) {\n return baseline === 'middle' ? h / 2 : baseline === 'bottom' ? h : 0;\n}\n\nfunction attr$4(emit, item, renderer) {\n const img = getImage(item, renderer),\n w = imageWidth(item, img),\n h = imageHeight(item, img),\n x = (item.x || 0) - imageXOffset(item.align, w),\n y = (item.y || 0) - imageYOffset(item.baseline, h),\n i = !img.src && img.toDataURL ? img.toDataURL() : img.src || '';\n emit('href', i, metadata['xmlns:xlink'], 'xlink:href');\n emit('transform', translate(x, y));\n emit('width', w);\n emit('height', h);\n emit('preserveAspectRatio', item.aspect === false ? 'none' : 'xMidYMid');\n}\n\nfunction bound$4(bounds, item) {\n const img = item.image,\n w = imageWidth(item, img),\n h = imageHeight(item, img),\n x = (item.x || 0) - imageXOffset(item.align, w),\n y = (item.y || 0) - imageYOffset(item.baseline, h);\n return bounds.set(x, y, x + w, y + h);\n}\n\nfunction draw$3(context, scene, bounds) {\n visit(scene, item => {\n if (bounds && !bounds.intersects(item.bounds)) return; // bounds check\n\n const img = getImage(item, this);\n let w = imageWidth(item, img);\n let h = imageHeight(item, img);\n if (w === 0 || h === 0) return; // early exit\n\n let x = (item.x || 0) - imageXOffset(item.align, w),\n y = (item.y || 0) - imageYOffset(item.baseline, h),\n opacity,\n ar0,\n ar1,\n t;\n\n if (item.aspect !== false) {\n ar0 = img.width / img.height;\n ar1 = item.width / item.height;\n\n if (ar0 === ar0 && ar1 === ar1 && ar0 !== ar1) {\n if (ar1 < ar0) {\n t = w / ar0;\n y += (h - t) / 2;\n h = t;\n } else {\n t = h * ar0;\n x += (w - t) / 2;\n w = t;\n }\n }\n }\n\n if (img.complete || img.toDataURL) {\n blend(context, item);\n context.globalAlpha = (opacity = item.opacity) != null ? opacity : 1;\n context.imageSmoothingEnabled = item.smooth !== false;\n context.drawImage(img, x, y, w, h);\n }\n });\n}\n\nvar image = {\n type: 'image',\n tag: 'image',\n nested: false,\n attr: attr$4,\n bound: bound$4,\n draw: draw$3,\n pick: pick$1(),\n isect: truthy,\n // bounds check is sufficient\n get: getImage,\n xOffset: imageXOffset,\n yOffset: imageYOffset\n};\n\nvar line = markMultiItemPath('line', line$1, pickLine);\n\nfunction attr$3(emit, item) {\n var sx = item.scaleX || 1,\n sy = item.scaleY || 1;\n\n if (sx !== 1 || sy !== 1) {\n emit('vector-effect', 'non-scaling-stroke');\n }\n\n emit('transform', transformItem(item));\n emit('d', item.path);\n}\n\nfunction path$1(context, item) {\n var path = item.path;\n if (path == null) return true;\n var x = item.x || 0,\n y = item.y || 0,\n sx = item.scaleX || 1,\n sy = item.scaleY || 1,\n a = (item.angle || 0) * DegToRad,\n cache = item.pathCache;\n\n if (!cache || cache.path !== path) {\n (item.pathCache = cache = pathParse(path)).path = path;\n }\n\n if (a && context.rotate && context.translate) {\n context.translate(x, y);\n context.rotate(a);\n pathRender(context, cache, 0, 0, sx, sy);\n context.rotate(-a);\n context.translate(-x, -y);\n } else {\n pathRender(context, cache, x, y, sx, sy);\n }\n}\n\nfunction bound$3(bounds, item) {\n return path$1(boundContext(bounds, item.angle), item) ? bounds.set(0, 0, 0, 0) : boundStroke(bounds, item, true);\n}\n\nvar path$2 = {\n type: 'path',\n tag: 'path',\n nested: false,\n attr: attr$3,\n bound: bound$3,\n draw: drawAll(path$1),\n pick: pickPath(path$1),\n isect: intersectPath(path$1)\n};\n\nfunction attr$2(emit, item) {\n emit('d', rectangle(null, item));\n}\n\nfunction bound$2(bounds, item) {\n var x, y;\n return boundStroke(bounds.set(x = item.x || 0, y = item.y || 0, x + item.width || 0, y + item.height || 0), item);\n}\n\nfunction draw$2(context, item) {\n context.beginPath();\n rectangle(context, item);\n}\n\nvar rect = {\n type: 'rect',\n tag: 'path',\n nested: false,\n attr: attr$2,\n bound: bound$2,\n draw: drawAll(draw$2),\n pick: pickPath(draw$2),\n isect: intersectRect\n};\n\nfunction attr$1(emit, item) {\n emit('transform', translateItem(item));\n emit('x2', item.x2 != null ? item.x2 - (item.x || 0) : 0);\n emit('y2', item.y2 != null ? item.y2 - (item.y || 0) : 0);\n}\n\nfunction bound$1(bounds, item) {\n var x1, y1;\n return boundStroke(bounds.set(x1 = item.x || 0, y1 = item.y || 0, item.x2 != null ? item.x2 : x1, item.y2 != null ? item.y2 : y1), item);\n}\n\nfunction path(context, item, opacity) {\n var x1, y1, x2, y2;\n\n if (item.stroke && stroke(context, item, opacity)) {\n x1 = item.x || 0;\n y1 = item.y || 0;\n x2 = item.x2 != null ? item.x2 : x1;\n y2 = item.y2 != null ? item.y2 : y1;\n context.beginPath();\n context.moveTo(x1, y1);\n context.lineTo(x2, y2);\n return true;\n }\n\n return false;\n}\n\nfunction draw$1(context, scene, bounds) {\n visit(scene, item => {\n if (bounds && !bounds.intersects(item.bounds)) return; // bounds check\n\n var opacity = item.opacity == null ? 1 : item.opacity;\n\n if (opacity && path(context, item, opacity)) {\n blend(context, item);\n context.stroke();\n }\n });\n}\n\nfunction hit$1(context, item, x, y) {\n if (!context.isPointInStroke) return false;\n return path(context, item, 1) && context.isPointInStroke(x, y);\n}\n\nvar rule = {\n type: 'rule',\n tag: 'line',\n nested: false,\n attr: attr$1,\n bound: bound$1,\n draw: draw$1,\n pick: pick$1(hit$1),\n isect: intersectRule\n};\n\nvar shape = markItemPath('shape', shape$1);\n\nvar symbol = markItemPath('symbol', symbol$1, intersectPoint);\n\nconst widthCache = lruCache();\nvar textMetrics = {\n height: fontSize,\n measureWidth: measureWidth,\n estimateWidth: estimateWidth,\n width: estimateWidth,\n canvas: useCanvas\n};\nuseCanvas(true);\n\nfunction useCanvas(use) {\n textMetrics.width = use && context ? measureWidth : estimateWidth;\n} // make simple estimate if no canvas is available\n\n\nfunction estimateWidth(item, text) {\n return _estimateWidth(textValue(item, text), fontSize(item));\n}\n\nfunction _estimateWidth(text, currentFontHeight) {\n return ~~(0.8 * text.length * currentFontHeight);\n} // measure text width if canvas is available\n\n\nfunction measureWidth(item, text) {\n return fontSize(item) <= 0 || !(text = textValue(item, text)) ? 0 : _measureWidth(text, font(item));\n}\n\nfunction _measureWidth(text, currentFont) {\n const key = `(${currentFont}) ${text}`;\n let width = widthCache.get(key);\n\n if (width === undefined) {\n context.font = currentFont;\n width = context.measureText(text).width;\n widthCache.set(key, width);\n }\n\n return width;\n}\n\nfunction fontSize(item) {\n return item.fontSize != null ? +item.fontSize || 0 : 11;\n}\nfunction lineHeight(item) {\n return item.lineHeight != null ? item.lineHeight : fontSize(item) + 2;\n}\n\nfunction lineArray(_) {\n return isArray(_) ? _.length > 1 ? _ : _[0] : _;\n}\n\nfunction textLines(item) {\n return lineArray(item.lineBreak && item.text && !isArray(item.text) ? item.text.split(item.lineBreak) : item.text);\n}\nfunction multiLineOffset(item) {\n const tl = textLines(item);\n return (isArray(tl) ? tl.length - 1 : 0) * lineHeight(item);\n}\nfunction textValue(item, line) {\n const text = line == null ? '' : (line + '').trim();\n return item.limit > 0 && text.length ? truncate(item, text) : text;\n}\n\nfunction widthGetter(item) {\n if (textMetrics.width === measureWidth) {\n // we are using canvas\n const currentFont = font(item);\n return text => _measureWidth(text, currentFont);\n } else {\n // we are relying on estimates\n const currentFontHeight = fontSize(item);\n return text => _estimateWidth(text, currentFontHeight);\n }\n}\n\nfunction truncate(item, text) {\n var limit = +item.limit,\n width = widthGetter(item);\n if (width(text) < limit) return text;\n var ellipsis = item.ellipsis || '\\u2026',\n rtl = item.dir === 'rtl',\n lo = 0,\n hi = text.length,\n mid;\n limit -= width(ellipsis);\n\n if (rtl) {\n while (lo < hi) {\n mid = lo + hi >>> 1;\n if (width(text.slice(mid)) > limit) lo = mid + 1;else hi = mid;\n }\n\n return ellipsis + text.slice(lo);\n } else {\n while (lo < hi) {\n mid = 1 + (lo + hi >>> 1);\n if (width(text.slice(0, mid)) < limit) lo = mid;else hi = mid - 1;\n }\n\n return text.slice(0, lo) + ellipsis;\n }\n}\n\nfunction fontFamily(item, quote) {\n var font = item.font;\n return (quote && font ? String(font).replace(/\"/g, '\\'') : font) || 'sans-serif';\n}\nfunction font(item, quote) {\n return '' + (item.fontStyle ? item.fontStyle + ' ' : '') + (item.fontVariant ? item.fontVariant + ' ' : '') + (item.fontWeight ? item.fontWeight + ' ' : '') + fontSize(item) + 'px ' + fontFamily(item, quote);\n}\nfunction offset(item) {\n // perform our own font baseline calculation\n // why? not all browsers support SVG 1.1 'alignment-baseline' :(\n // this also ensures consistent layout across renderers\n var baseline = item.baseline,\n h = fontSize(item);\n return Math.round(baseline === 'top' ? 0.79 * h : baseline === 'middle' ? 0.30 * h : baseline === 'bottom' ? -0.21 * h : baseline === 'line-top' ? 0.29 * h + 0.5 * lineHeight(item) : baseline === 'line-bottom' ? 0.29 * h - 0.5 * lineHeight(item) : 0);\n}\n\nconst textAlign = {\n 'left': 'start',\n 'center': 'middle',\n 'right': 'end'\n};\nconst tempBounds = new Bounds();\n\nfunction anchorPoint(item) {\n var x = item.x || 0,\n y = item.y || 0,\n r = item.radius || 0,\n t;\n\n if (r) {\n t = (item.theta || 0) - HalfPi;\n x += r * Math.cos(t);\n y += r * Math.sin(t);\n }\n\n tempBounds.x1 = x;\n tempBounds.y1 = y;\n return tempBounds;\n}\n\nfunction attr(emit, item) {\n var dx = item.dx || 0,\n dy = (item.dy || 0) + offset(item),\n p = anchorPoint(item),\n x = p.x1,\n y = p.y1,\n a = item.angle || 0,\n t;\n emit('text-anchor', textAlign[item.align] || 'start');\n\n if (a) {\n t = translate(x, y) + ' ' + rotate(a);\n if (dx || dy) t += ' ' + translate(dx, dy);\n } else {\n t = translate(x + dx, y + dy);\n }\n\n emit('transform', t);\n}\n\nfunction bound(bounds, item, mode) {\n var h = textMetrics.height(item),\n a = item.align,\n p = anchorPoint(item),\n x = p.x1,\n y = p.y1,\n dx = item.dx || 0,\n dy = (item.dy || 0) + offset(item) - Math.round(0.8 * h),\n // use 4/5 offset\n tl = textLines(item),\n w; // get dimensions\n\n if (isArray(tl)) {\n // multi-line text\n h += lineHeight(item) * (tl.length - 1);\n w = tl.reduce((w, t) => Math.max(w, textMetrics.width(item, t)), 0);\n } else {\n // single-line text\n w = textMetrics.width(item, tl);\n } // horizontal alignment\n\n\n if (a === 'center') {\n dx -= w / 2;\n } else if (a === 'right') {\n dx -= w;\n } else ;\n\n bounds.set(dx += x, dy += y, dx + w, dy + h);\n\n if (item.angle && !mode) {\n bounds.rotate(item.angle * DegToRad, x, y);\n } else if (mode === 2) {\n return bounds.rotatedPoints(item.angle * DegToRad, x, y);\n }\n\n return bounds;\n}\n\nfunction draw(context, scene, bounds) {\n visit(scene, item => {\n var opacity = item.opacity == null ? 1 : item.opacity,\n p,\n x,\n y,\n i,\n lh,\n tl,\n str;\n if (bounds && !bounds.intersects(item.bounds) || // bounds check\n opacity === 0 || item.fontSize <= 0 || item.text == null || item.text.length === 0) return;\n context.font = font(item);\n context.textAlign = item.align || 'left';\n p = anchorPoint(item);\n x = p.x1, y = p.y1;\n\n if (item.angle) {\n context.save();\n context.translate(x, y);\n context.rotate(item.angle * DegToRad);\n x = y = 0; // reset x, y\n }\n\n x += item.dx || 0;\n y += (item.dy || 0) + offset(item);\n tl = textLines(item);\n blend(context, item);\n\n if (isArray(tl)) {\n lh = lineHeight(item);\n\n for (i = 0; i < tl.length; ++i) {\n str = textValue(item, tl[i]);\n\n if (item.fill && fill(context, item, opacity)) {\n context.fillText(str, x, y);\n }\n\n if (item.stroke && stroke(context, item, opacity)) {\n context.strokeText(str, x, y);\n }\n\n y += lh;\n }\n } else {\n str = textValue(item, tl);\n\n if (item.fill && fill(context, item, opacity)) {\n context.fillText(str, x, y);\n }\n\n if (item.stroke && stroke(context, item, opacity)) {\n context.strokeText(str, x, y);\n }\n }\n\n if (item.angle) context.restore();\n });\n}\n\nfunction hit(context, item, x, y, gx, gy) {\n if (item.fontSize <= 0) return false;\n if (!item.angle) return true; // bounds sufficient if no rotation\n // project point into space of unrotated bounds\n\n var p = anchorPoint(item),\n ax = p.x1,\n ay = p.y1,\n b = bound(tempBounds, item, 1),\n a = -item.angle * DegToRad,\n cos = Math.cos(a),\n sin = Math.sin(a),\n px = cos * gx - sin * gy + (ax - cos * ax + sin * ay),\n py = sin * gx + cos * gy + (ay - sin * ax - cos * ay);\n return b.contains(px, py);\n}\n\nfunction intersectText(item, box) {\n const p = bound(tempBounds, item, 2);\n return intersectBoxLine(box, p[0], p[1], p[2], p[3]) || intersectBoxLine(box, p[0], p[1], p[4], p[5]) || intersectBoxLine(box, p[4], p[5], p[6], p[7]) || intersectBoxLine(box, p[2], p[3], p[6], p[7]);\n}\n\nvar text = {\n type: 'text',\n tag: 'text',\n nested: false,\n attr: attr,\n bound: bound,\n draw: draw,\n pick: pick$1(hit),\n isect: intersectText\n};\n\nvar trail = markMultiItemPath('trail', trail$1, pickTrail);\n\nvar Marks = {\n arc: arc,\n area: area,\n group: group,\n image: image,\n line: line,\n path: path$2,\n rect: rect,\n rule: rule,\n shape: shape,\n symbol: symbol,\n text: text,\n trail: trail\n};\n\nfunction boundItem (item, func, opt) {\n var type = Marks[item.mark.marktype],\n bound = func || type.bound;\n if (type.nested) item = item.mark;\n return bound(item.bounds || (item.bounds = new Bounds()), item, opt);\n}\n\nvar DUMMY = {\n mark: null\n};\nfunction boundMark (mark, bounds, opt) {\n var type = Marks[mark.marktype],\n bound = type.bound,\n items = mark.items,\n hasItems = items && items.length,\n i,\n n,\n item,\n b;\n\n if (type.nested) {\n if (hasItems) {\n item = items[0];\n } else {\n // no items, fake it\n DUMMY.mark = mark;\n item = DUMMY;\n }\n\n b = boundItem(item, bound, opt);\n bounds = bounds && bounds.union(b) || b;\n return bounds;\n }\n\n bounds = bounds || mark.bounds && mark.bounds.clear() || new Bounds();\n\n if (hasItems) {\n for (i = 0, n = items.length; i < n; ++i) {\n bounds.union(boundItem(items[i], bound, opt));\n }\n }\n\n return mark.bounds = bounds;\n}\n\nconst keys = ['marktype', 'name', 'role', 'interactive', 'clip', 'items', 'zindex', 'x', 'y', 'width', 'height', 'align', 'baseline', // layout\n'fill', 'fillOpacity', 'opacity', 'blend', // fill\n'stroke', 'strokeOpacity', 'strokeWidth', 'strokeCap', // stroke\n'strokeDash', 'strokeDashOffset', // stroke dash\n'strokeForeground', 'strokeOffset', // group\n'startAngle', 'endAngle', 'innerRadius', 'outerRadius', // arc\n'cornerRadius', 'padAngle', // arc, rect\n'cornerRadiusTopLeft', 'cornerRadiusTopRight', // rect, group\n'cornerRadiusBottomLeft', 'cornerRadiusBottomRight', 'interpolate', 'tension', 'orient', 'defined', // area, line\n'url', 'aspect', 'smooth', // image\n'path', 'scaleX', 'scaleY', // path\n'x2', 'y2', // rule\n'size', 'shape', // symbol\n'text', 'angle', 'theta', 'radius', 'dir', 'dx', 'dy', // text\n'ellipsis', 'limit', 'lineBreak', 'lineHeight', 'font', 'fontSize', 'fontWeight', 'fontStyle', 'fontVariant', // font\n'description', 'aria', 'ariaRole', 'ariaRoleDescription' // aria\n];\nfunction sceneToJSON(scene, indent) {\n return JSON.stringify(scene, keys, indent);\n}\nfunction sceneFromJSON(json) {\n const scene = typeof json === 'string' ? JSON.parse(json) : json;\n return initialize(scene);\n}\n\nfunction initialize(scene) {\n var type = scene.marktype,\n items = scene.items,\n parent,\n i,\n n;\n\n if (items) {\n for (i = 0, n = items.length; i < n; ++i) {\n parent = type ? 'mark' : 'group';\n items[i][parent] = scene;\n if (items[i].zindex) items[i][parent].zdirty = true;\n if ('group' === (type || parent)) initialize(items[i]);\n }\n }\n\n if (type) boundMark(scene);\n return scene;\n}\n\nfunction Scenegraph(scene) {\n if (arguments.length) {\n this.root = sceneFromJSON(scene);\n } else {\n this.root = createMark({\n marktype: 'group',\n name: 'root',\n role: 'frame'\n });\n this.root.items = [new GroupItem(this.root)];\n }\n}\nScenegraph.prototype = {\n toJSON(indent) {\n return sceneToJSON(this.root, indent || 0);\n },\n\n mark(markdef, group, index) {\n group = group || this.root.items[0];\n const mark = createMark(markdef, group);\n group.items[index] = mark;\n if (mark.zindex) mark.group.zdirty = true;\n return mark;\n }\n\n};\n\nfunction createMark(def, group) {\n const mark = {\n bounds: new Bounds(),\n clip: !!def.clip,\n group: group,\n interactive: def.interactive === false ? false : true,\n items: [],\n marktype: def.marktype,\n name: def.name || undefined,\n role: def.role || undefined,\n zindex: def.zindex || 0\n }; // add accessibility properties if defined\n\n if (def.aria != null) {\n mark.aria = def.aria;\n }\n\n if (def.description) {\n mark.description = def.description;\n }\n\n return mark;\n}\n\n// create a new DOM element\nfunction domCreate(doc, tag, ns) {\n if (!doc && typeof document !== 'undefined' && document.createElement) {\n doc = document;\n }\n\n return doc ? ns ? doc.createElementNS(ns, tag) : doc.createElement(tag) : null;\n} // find first child element with matching tag\n\nfunction domFind(el, tag) {\n tag = tag.toLowerCase();\n var nodes = el.childNodes,\n i = 0,\n n = nodes.length;\n\n for (; i < n; ++i) if (nodes[i].tagName.toLowerCase() === tag) {\n return nodes[i];\n }\n} // retrieve child element at given index\n// create & insert if doesn't exist or if tags do not match\n\nfunction domChild(el, index, tag, ns) {\n var a = el.childNodes[index],\n b;\n\n if (!a || a.tagName.toLowerCase() !== tag.toLowerCase()) {\n b = a || null;\n a = domCreate(el.ownerDocument, tag, ns);\n el.insertBefore(a, b);\n }\n\n return a;\n} // remove all child elements at or above the given index\n\nfunction domClear(el, index) {\n var nodes = el.childNodes,\n curr = nodes.length;\n\n while (curr > index) el.removeChild(nodes[--curr]);\n\n return el;\n} // generate css class name for mark\n\nfunction cssClass(mark) {\n return 'mark-' + mark.marktype + (mark.role ? ' role-' + mark.role : '') + (mark.name ? ' ' + mark.name : '');\n}\n\nfunction point (event, el) {\n const rect = el.getBoundingClientRect();\n return [event.clientX - rect.left - (el.clientLeft || 0), event.clientY - rect.top - (el.clientTop || 0)];\n}\n\nfunction resolveItem (item, event, el, origin) {\n var mark = item && item.mark,\n mdef,\n p;\n\n if (mark && (mdef = Marks[mark.marktype]).tip) {\n p = point(event, el);\n p[0] -= origin[0];\n p[1] -= origin[1];\n\n while (item = item.mark.group) {\n p[0] -= item.x || 0;\n p[1] -= item.y || 0;\n }\n\n item = mdef.tip(mark.items, p);\n }\n\n return item;\n}\n\n/**\n * Create a new Handler instance.\n * @param {object} [customLoader] - Optional loader instance for\n * href URL sanitization. If not specified, a standard loader\n * instance will be generated.\n * @param {function} [customTooltip] - Optional tooltip handler\n * function for custom tooltip display.\n * @constructor\n */\n\nfunction Handler(customLoader, customTooltip) {\n this._active = null;\n this._handlers = {};\n this._loader = customLoader || loader();\n this._tooltip = customTooltip || defaultTooltip;\n} // The default tooltip display handler.\n// Sets the HTML title attribute on the visualization container.\n\nfunction defaultTooltip(handler, event, item, value) {\n handler.element().setAttribute('title', value || '');\n}\n\nHandler.prototype = {\n /**\n * Initialize a new Handler instance.\n * @param {DOMElement} el - The containing DOM element for the display.\n * @param {Array} origin - The origin of the display, in pixels.\n * The coordinate system will be translated to this point.\n * @param {object} [obj] - Optional context object that should serve as\n * the \"this\" context for event callbacks.\n * @return {Handler} - This handler instance.\n */\n initialize(el, origin, obj) {\n this._el = el;\n this._obj = obj || null;\n return this.origin(origin);\n },\n\n /**\n * Returns the parent container element for a visualization.\n * @return {DOMElement} - The containing DOM element.\n */\n element() {\n return this._el;\n },\n\n /**\n * Returns the scene element (e.g., canvas or SVG) of the visualization\n * Subclasses must override if the first child is not the scene element.\n * @return {DOMElement} - The scene (e.g., canvas or SVG) element.\n */\n canvas() {\n return this._el && this._el.firstChild;\n },\n\n /**\n * Get / set the origin coordinates of the visualization.\n */\n origin(origin) {\n if (arguments.length) {\n this._origin = origin || [0, 0];\n return this;\n } else {\n return this._origin.slice();\n }\n },\n\n /**\n * Get / set the scenegraph root.\n */\n scene(scene) {\n if (!arguments.length) return this._scene;\n this._scene = scene;\n return this;\n },\n\n /**\n * Add an event handler. Subclasses should override this method.\n */\n on()\n /*type, handler*/\n {},\n\n /**\n * Remove an event handler. Subclasses should override this method.\n */\n off()\n /*type, handler*/\n {},\n\n /**\n * Utility method for finding the array index of an event handler.\n * @param {Array} h - An array of registered event handlers.\n * @param {string} type - The event type.\n * @param {function} handler - The event handler instance to find.\n * @return {number} - The handler's array index or -1 if not registered.\n */\n _handlerIndex(h, type, handler) {\n for (let i = h ? h.length : 0; --i >= 0;) {\n if (h[i].type === type && (!handler || h[i].handler === handler)) {\n return i;\n }\n }\n\n return -1;\n },\n\n /**\n * Returns an array with registered event handlers.\n * @param {string} [type] - The event type to query. Any annotations\n * are ignored; for example, for the argument \"click.foo\", \".foo\" will\n * be ignored and the method returns all \"click\" handlers. If type is\n * null or unspecified, this method returns handlers for all types.\n * @return {Array} - A new array containing all registered event handlers.\n */\n handlers(type) {\n const h = this._handlers,\n a = [];\n\n if (type) {\n a.push(...h[this.eventName(type)]);\n } else {\n for (const k in h) {\n a.push(...h[k]);\n }\n }\n\n return a;\n },\n\n /**\n * Parses an event name string to return the specific event type.\n * For example, given \"click.foo\" returns \"click\"\n * @param {string} name - The input event type string.\n * @return {string} - A string with the event type only.\n */\n eventName(name) {\n const i = name.indexOf('.');\n return i < 0 ? name : name.slice(0, i);\n },\n\n /**\n * Handle hyperlink navigation in response to an item.href value.\n * @param {Event} event - The event triggering hyperlink navigation.\n * @param {Item} item - The scenegraph item.\n * @param {string} href - The URL to navigate to.\n */\n handleHref(event, item, href) {\n this._loader.sanitize(href, {\n context: 'href'\n }).then(opt => {\n const e = new MouseEvent(event.type, event),\n a = domCreate(null, 'a');\n\n for (const name in opt) a.setAttribute(name, opt[name]);\n\n a.dispatchEvent(e);\n }).catch(() => {\n /* do nothing */\n });\n },\n\n /**\n * Handle tooltip display in response to an item.tooltip value.\n * @param {Event} event - The event triggering tooltip display.\n * @param {Item} item - The scenegraph item.\n * @param {boolean} show - A boolean flag indicating whether\n * to show or hide a tooltip for the given item.\n */\n handleTooltip(event, item, show) {\n if (item && item.tooltip != null) {\n item = resolveItem(item, event, this.canvas(), this._origin);\n const value = show && item && item.tooltip || null;\n\n this._tooltip.call(this._obj, this, event, item, value);\n }\n },\n\n /**\n * Returns the size of a scenegraph item and its position relative\n * to the viewport.\n * @param {Item} item - The scenegraph item.\n * @return {object} - A bounding box object (compatible with the\n * DOMRect type) consisting of x, y, width, heigh, top, left,\n * right, and bottom properties.\n */\n getItemBoundingClientRect(item) {\n const el = this.canvas();\n if (!el) return;\n const rect = el.getBoundingClientRect(),\n origin = this._origin,\n bounds = item.bounds,\n width = bounds.width(),\n height = bounds.height();\n let x = bounds.x1 + origin[0] + rect.left,\n y = bounds.y1 + origin[1] + rect.top; // translate coordinate for each parent group\n\n while (item.mark && (item = item.mark.group)) {\n x += item.x || 0;\n y += item.y || 0;\n } // return DOMRect-compatible bounding box\n\n\n return {\n x,\n y,\n width,\n height,\n left: x,\n top: y,\n right: x + width,\n bottom: y + height\n };\n }\n\n};\n\n/**\n * Create a new Renderer instance.\n * @param {object} [loader] - Optional loader instance for\n * image and href URL sanitization. If not specified, a\n * standard loader instance will be generated.\n * @constructor\n */\n\nfunction Renderer(loader) {\n this._el = null;\n this._bgcolor = null;\n this._loader = new ResourceLoader(loader);\n}\nRenderer.prototype = {\n /**\n * Initialize a new Renderer instance.\n * @param {DOMElement} el - The containing DOM element for the display.\n * @param {number} width - The coordinate width of the display, in pixels.\n * @param {number} height - The coordinate height of the display, in pixels.\n * @param {Array} origin - The origin of the display, in pixels.\n * The coordinate system will be translated to this point.\n * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply\n * the width and height to determine the final pixel size.\n * @return {Renderer} - This renderer instance.\n */\n initialize(el, width, height, origin, scaleFactor) {\n this._el = el;\n return this.resize(width, height, origin, scaleFactor);\n },\n\n /**\n * Returns the parent container element for a visualization.\n * @return {DOMElement} - The containing DOM element.\n */\n element() {\n return this._el;\n },\n\n /**\n * Returns the scene element (e.g., canvas or SVG) of the visualization\n * Subclasses must override if the first child is not the scene element.\n * @return {DOMElement} - The scene (e.g., canvas or SVG) element.\n */\n canvas() {\n return this._el && this._el.firstChild;\n },\n\n /**\n * Get / set the background color.\n */\n background(bgcolor) {\n if (arguments.length === 0) return this._bgcolor;\n this._bgcolor = bgcolor;\n return this;\n },\n\n /**\n * Resize the display.\n * @param {number} width - The new coordinate width of the display, in pixels.\n * @param {number} height - The new coordinate height of the display, in pixels.\n * @param {Array} origin - The new origin of the display, in pixels.\n * The coordinate system will be translated to this point.\n * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply\n * the width and height to determine the final pixel size.\n * @return {Renderer} - This renderer instance;\n */\n resize(width, height, origin, scaleFactor) {\n this._width = width;\n this._height = height;\n this._origin = origin || [0, 0];\n this._scale = scaleFactor || 1;\n return this;\n },\n\n /**\n * Report a dirty item whose bounds should be redrawn.\n * This base class method does nothing. Subclasses that perform\n * incremental should implement this method.\n * @param {Item} item - The dirty item whose bounds should be redrawn.\n */\n dirty()\n /*item*/\n {},\n\n /**\n * Render an input scenegraph, potentially with a set of dirty items.\n * This method will perform an immediate rendering with available resources.\n * The renderer may also need to perform image loading to perform a complete\n * render. This process can lead to asynchronous re-rendering of the scene\n * after this method returns. To receive notification when rendering is\n * complete, use the renderAsync method instead.\n * @param {object} scene - The root mark of a scenegraph to render.\n * @return {Renderer} - This renderer instance.\n */\n render(scene) {\n const r = this; // bind arguments into a render call, and cache it\n // this function may be subsequently called for async redraw\n\n r._call = function () {\n r._render(scene);\n }; // invoke the renderer\n\n\n r._call(); // clear the cached call for garbage collection\n // async redraws will stash their own copy\n\n\n r._call = null;\n return r;\n },\n\n /**\n * Internal rendering method. Renderer subclasses should override this\n * method to actually perform rendering.\n * @param {object} scene - The root mark of a scenegraph to render.\n */\n _render()\n /*scene*/\n {// subclasses to override\n },\n\n /**\n * Asynchronous rendering method. Similar to render, but returns a Promise\n * that resolves when all rendering is completed. Sometimes a renderer must\n * perform image loading to get a complete rendering. The returned\n * Promise will not resolve until this process completes.\n * @param {object} scene - The root mark of a scenegraph to render.\n * @return {Promise} - A Promise that resolves when rendering is complete.\n */\n renderAsync(scene) {\n const r = this.render(scene);\n return this._ready ? this._ready.then(() => r) : Promise.resolve(r);\n },\n\n /**\n * Internal method for asynchronous resource loading.\n * Proxies method calls to the ImageLoader, and tracks loading\n * progress to invoke a re-render once complete.\n * @param {string} method - The method name to invoke on the ImageLoader.\n * @param {string} uri - The URI for the requested resource.\n * @return {Promise} - A Promise that resolves to the requested resource.\n */\n _load(method, uri) {\n var r = this,\n p = r._loader[method](uri);\n\n if (!r._ready) {\n // re-render the scene when loading completes\n const call = r._call;\n r._ready = r._loader.ready().then(redraw => {\n if (redraw) call();\n r._ready = null;\n });\n }\n\n return p;\n },\n\n /**\n * Sanitize a URL to include as a hyperlink in the rendered scene.\n * This method proxies a call to ImageLoader.sanitizeURL, but also tracks\n * image loading progress and invokes a re-render once complete.\n * @param {string} uri - The URI string to sanitize.\n * @return {Promise} - A Promise that resolves to the sanitized URL.\n */\n sanitizeURL(uri) {\n return this._load('sanitizeURL', uri);\n },\n\n /**\n * Requests an image to include in the rendered scene.\n * This method proxies a call to ImageLoader.loadImage, but also tracks\n * image loading progress and invokes a re-render once complete.\n * @param {string} uri - The URI string of the image.\n * @return {Promise} - A Promise that resolves to the loaded Image.\n */\n loadImage(uri) {\n return this._load('loadImage', uri);\n }\n\n};\n\nconst KeyDownEvent = 'keydown';\nconst KeyPressEvent = 'keypress';\nconst KeyUpEvent = 'keyup';\nconst DragEnterEvent = 'dragenter';\nconst DragLeaveEvent = 'dragleave';\nconst DragOverEvent = 'dragover';\nconst MouseDownEvent = 'mousedown';\nconst MouseUpEvent = 'mouseup';\nconst MouseMoveEvent = 'mousemove';\nconst MouseOutEvent = 'mouseout';\nconst MouseOverEvent = 'mouseover';\nconst ClickEvent = 'click';\nconst DoubleClickEvent = 'dblclick';\nconst WheelEvent = 'wheel';\nconst MouseWheelEvent = 'mousewheel';\nconst TouchStartEvent = 'touchstart';\nconst TouchMoveEvent = 'touchmove';\nconst TouchEndEvent = 'touchend';\nconst Events = [KeyDownEvent, KeyPressEvent, KeyUpEvent, DragEnterEvent, DragLeaveEvent, DragOverEvent, MouseDownEvent, MouseUpEvent, MouseMoveEvent, MouseOutEvent, MouseOverEvent, ClickEvent, DoubleClickEvent, WheelEvent, MouseWheelEvent, TouchStartEvent, TouchMoveEvent, TouchEndEvent];\nconst TooltipShowEvent = MouseMoveEvent;\nconst TooltipHideEvent = MouseOutEvent;\nconst HrefEvent = ClickEvent;\n\nfunction CanvasHandler(loader, tooltip) {\n Handler.call(this, loader, tooltip);\n this._down = null;\n this._touch = null;\n this._first = true;\n this._events = {};\n}\n\nconst eventBundle = type => type === TouchStartEvent || type === TouchMoveEvent || type === TouchEndEvent ? [TouchStartEvent, TouchMoveEvent, TouchEndEvent] : [type]; // lazily add listeners to the canvas as needed\n\n\nfunction eventListenerCheck(handler, type) {\n eventBundle(type).forEach(_ => addEventListener(handler, _));\n}\n\nfunction addEventListener(handler, type) {\n const canvas = handler.canvas();\n\n if (canvas && !handler._events[type]) {\n handler._events[type] = 1;\n canvas.addEventListener(type, handler[type] ? evt => handler[type](evt) : evt => handler.fire(type, evt));\n }\n}\n\nfunction move(moveEvent, overEvent, outEvent) {\n return function (evt) {\n const a = this._active,\n p = this.pickEvent(evt);\n\n if (p === a) {\n // active item and picked item are the same\n this.fire(moveEvent, evt); // fire move\n } else {\n // active item and picked item are different\n if (!a || !a.exit) {\n // fire out for prior active item\n // suppress if active item was removed from scene\n this.fire(outEvent, evt);\n }\n\n this._active = p; // set new active item\n\n this.fire(overEvent, evt); // fire over for new active item\n\n this.fire(moveEvent, evt); // fire move for new active item\n }\n };\n}\n\nfunction inactive(type) {\n return function (evt) {\n this.fire(type, evt);\n this._active = null;\n };\n}\n\ninherits(CanvasHandler, Handler, {\n initialize(el, origin, obj) {\n this._canvas = el && domFind(el, 'canvas'); // add minimal events required for proper state management\n\n [ClickEvent, MouseDownEvent, MouseMoveEvent, MouseOutEvent, DragLeaveEvent].forEach(type => eventListenerCheck(this, type));\n return Handler.prototype.initialize.call(this, el, origin, obj);\n },\n\n // return the backing canvas instance\n canvas() {\n return this._canvas;\n },\n\n // retrieve the current canvas context\n context() {\n return this._canvas.getContext('2d');\n },\n\n // supported events\n events: Events,\n\n // to keep old versions of firefox happy\n DOMMouseScroll(evt) {\n this.fire(MouseWheelEvent, evt);\n },\n\n mousemove: move(MouseMoveEvent, MouseOverEvent, MouseOutEvent),\n dragover: move(DragOverEvent, DragEnterEvent, DragLeaveEvent),\n mouseout: inactive(MouseOutEvent),\n dragleave: inactive(DragLeaveEvent),\n\n mousedown(evt) {\n this._down = this._active;\n this.fire(MouseDownEvent, evt);\n },\n\n click(evt) {\n if (this._down === this._active) {\n this.fire(ClickEvent, evt);\n this._down = null;\n }\n },\n\n touchstart(evt) {\n this._touch = this.pickEvent(evt.changedTouches[0]);\n\n if (this._first) {\n this._active = this._touch;\n this._first = false;\n }\n\n this.fire(TouchStartEvent, evt, true);\n },\n\n touchmove(evt) {\n this.fire(TouchMoveEvent, evt, true);\n },\n\n touchend(evt) {\n this.fire(TouchEndEvent, evt, true);\n this._touch = null;\n },\n\n // fire an event\n fire(type, evt, touch) {\n const a = touch ? this._touch : this._active,\n h = this._handlers[type]; // set event type relative to scenegraph items\n\n evt.vegaType = type; // handle hyperlinks and tooltips first\n\n if (type === HrefEvent && a && a.href) {\n this.handleHref(evt, a, a.href);\n } else if (type === TooltipShowEvent || type === TooltipHideEvent) {\n this.handleTooltip(evt, a, type !== TooltipHideEvent);\n } // invoke all registered handlers\n\n\n if (h) {\n for (let i = 0, len = h.length; i < len; ++i) {\n h[i].handler.call(this._obj, evt, a);\n }\n }\n },\n\n // add an event handler\n on(type, handler) {\n const name = this.eventName(type),\n h = this._handlers,\n i = this._handlerIndex(h[name], type, handler);\n\n if (i < 0) {\n eventListenerCheck(this, type);\n (h[name] || (h[name] = [])).push({\n type: type,\n handler: handler\n });\n }\n\n return this;\n },\n\n // remove an event handler\n off(type, handler) {\n const name = this.eventName(type),\n h = this._handlers[name],\n i = this._handlerIndex(h, type, handler);\n\n if (i >= 0) {\n h.splice(i, 1);\n }\n\n return this;\n },\n\n pickEvent(evt) {\n const p = point(evt, this._canvas),\n o = this._origin;\n return this.pick(this._scene, p[0], p[1], p[0] - o[0], p[1] - o[1]);\n },\n\n // find the scenegraph item at the current mouse position\n // x, y -- the absolute x, y mouse coordinates on the canvas element\n // gx, gy -- the relative coordinates within the current group\n pick(scene, x, y, gx, gy) {\n const g = this.context(),\n mark = Marks[scene.marktype];\n return mark.pick.call(this, g, scene, x, y, gx, gy);\n }\n\n});\n\nfunction devicePixelRatio() {\n return typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;\n}\n\nvar pixelRatio = devicePixelRatio();\nfunction resize (canvas, width, height, origin, scaleFactor, opt) {\n const inDOM = typeof HTMLElement !== 'undefined' && canvas instanceof HTMLElement && canvas.parentNode != null,\n context = canvas.getContext('2d'),\n ratio = inDOM ? pixelRatio : scaleFactor;\n canvas.width = width * ratio;\n canvas.height = height * ratio;\n\n for (const key in opt) {\n context[key] = opt[key];\n }\n\n if (inDOM && ratio !== 1) {\n canvas.style.width = width + 'px';\n canvas.style.height = height + 'px';\n }\n\n context.pixelRatio = ratio;\n context.setTransform(ratio, 0, 0, ratio, ratio * origin[0], ratio * origin[1]);\n return canvas;\n}\n\nfunction CanvasRenderer(loader) {\n Renderer.call(this, loader);\n this._options = {};\n this._redraw = false;\n this._dirty = new Bounds();\n this._tempb = new Bounds();\n}\nconst base$1 = Renderer.prototype;\n\nconst viewBounds = (origin, width, height) => new Bounds().set(0, 0, width, height).translate(-origin[0], -origin[1]);\n\nfunction clipToBounds(g, b, origin) {\n // expand bounds by 1 pixel, then round to pixel boundaries\n b.expand(1).round(); // align to base pixel grid in case of non-integer scaling (#2425)\n\n if (g.pixelRatio % 1) {\n b.scale(g.pixelRatio).round().scale(1 / g.pixelRatio);\n } // to avoid artifacts translate if origin has fractional pixels\n\n\n b.translate(-(origin[0] % 1), -(origin[1] % 1)); // set clip path\n\n g.beginPath();\n g.rect(b.x1, b.y1, b.width(), b.height());\n g.clip();\n return b;\n}\n\ninherits(CanvasRenderer, Renderer, {\n initialize(el, width, height, origin, scaleFactor, options) {\n this._options = options || {};\n this._canvas = this._options.externalContext ? null : canvas(1, 1, this._options.type); // instantiate a small canvas\n\n if (el && this._canvas) {\n domClear(el, 0).appendChild(this._canvas);\n\n this._canvas.setAttribute('class', 'marks');\n } // this method will invoke resize to size the canvas appropriately\n\n\n return base$1.initialize.call(this, el, width, height, origin, scaleFactor);\n },\n\n resize(width, height, origin, scaleFactor) {\n base$1.resize.call(this, width, height, origin, scaleFactor);\n\n if (this._canvas) {\n // configure canvas size and transform\n resize(this._canvas, this._width, this._height, this._origin, this._scale, this._options.context);\n } else {\n // external context needs to be scaled and positioned to origin\n const ctx = this._options.externalContext;\n if (!ctx) error('CanvasRenderer is missing a valid canvas or context');\n ctx.scale(this._scale, this._scale);\n ctx.translate(this._origin[0], this._origin[1]);\n }\n\n this._redraw = true;\n return this;\n },\n\n canvas() {\n return this._canvas;\n },\n\n context() {\n return this._options.externalContext || (this._canvas ? this._canvas.getContext('2d') : null);\n },\n\n dirty(item) {\n const b = this._tempb.clear().union(item.bounds);\n\n let g = item.mark.group;\n\n while (g) {\n b.translate(g.x || 0, g.y || 0);\n g = g.mark.group;\n }\n\n this._dirty.union(b);\n },\n\n _render(scene) {\n const g = this.context(),\n o = this._origin,\n w = this._width,\n h = this._height,\n db = this._dirty,\n vb = viewBounds(o, w, h); // setup\n\n g.save();\n const b = this._redraw || db.empty() ? (this._redraw = false, vb.expand(1)) : clipToBounds(g, vb.intersect(db), o);\n this.clear(-o[0], -o[1], w, h); // render\n\n this.draw(g, scene, b); // takedown\n\n g.restore();\n db.clear();\n return this;\n },\n\n draw(ctx, scene, bounds) {\n const mark = Marks[scene.marktype];\n if (scene.clip) clip(ctx, scene);\n mark.draw.call(this, ctx, scene, bounds);\n if (scene.clip) ctx.restore();\n },\n\n clear(x, y, w, h) {\n const opt = this._options,\n g = this.context();\n\n if (opt.type !== 'pdf' && !opt.externalContext) {\n // calling clear rect voids vector output in pdf mode\n // and could remove external context content (#2615)\n g.clearRect(x, y, w, h);\n }\n\n if (this._bgcolor != null) {\n g.fillStyle = this._bgcolor;\n g.fillRect(x, y, w, h);\n }\n }\n\n});\n\nfunction SVGHandler(loader, tooltip) {\n Handler.call(this, loader, tooltip);\n const h = this;\n h._hrefHandler = listener(h, (evt, item) => {\n if (item && item.href) h.handleHref(evt, item, item.href);\n });\n h._tooltipHandler = listener(h, (evt, item) => {\n h.handleTooltip(evt, item, evt.type !== TooltipHideEvent);\n });\n} // wrap an event listener for the SVG DOM\n\nconst listener = (context, handler) => evt => {\n let item = evt.target.__data__;\n item = Array.isArray(item) ? item[0] : item;\n evt.vegaType = evt.type;\n handler.call(context._obj, evt, item);\n};\n\ninherits(SVGHandler, Handler, {\n initialize(el, origin, obj) {\n let svg = this._svg;\n\n if (svg) {\n svg.removeEventListener(HrefEvent, this._hrefHandler);\n svg.removeEventListener(TooltipShowEvent, this._tooltipHandler);\n svg.removeEventListener(TooltipHideEvent, this._tooltipHandler);\n }\n\n this._svg = svg = el && domFind(el, 'svg');\n\n if (svg) {\n svg.addEventListener(HrefEvent, this._hrefHandler);\n svg.addEventListener(TooltipShowEvent, this._tooltipHandler);\n svg.addEventListener(TooltipHideEvent, this._tooltipHandler);\n }\n\n return Handler.prototype.initialize.call(this, el, origin, obj);\n },\n\n canvas() {\n return this._svg;\n },\n\n // add an event handler\n on(type, handler) {\n const name = this.eventName(type),\n h = this._handlers,\n i = this._handlerIndex(h[name], type, handler);\n\n if (i < 0) {\n const x = {\n type,\n handler,\n listener: listener(this, handler)\n };\n (h[name] || (h[name] = [])).push(x);\n\n if (this._svg) {\n this._svg.addEventListener(name, x.listener);\n }\n }\n\n return this;\n },\n\n // remove an event handler\n off(type, handler) {\n const name = this.eventName(type),\n h = this._handlers[name],\n i = this._handlerIndex(h, type, handler);\n\n if (i >= 0) {\n if (this._svg) {\n this._svg.removeEventListener(name, h[i].listener);\n }\n\n h.splice(i, 1);\n }\n\n return this;\n }\n\n});\n\nconst ARIA_HIDDEN = 'aria-hidden';\nconst ARIA_LABEL = 'aria-label';\nconst ARIA_ROLE = 'role';\nconst ARIA_ROLEDESCRIPTION = 'aria-roledescription';\nconst GRAPHICS_OBJECT = 'graphics-object';\nconst GRAPHICS_SYMBOL = 'graphics-symbol';\n\nconst bundle = (role, roledesc, label) => ({\n [ARIA_ROLE]: role,\n [ARIA_ROLEDESCRIPTION]: roledesc,\n [ARIA_LABEL]: label || undefined\n}); // these roles are covered by related roles\n// we can ignore them, no need to generate attributes\n\n\nconst AriaIgnore = toSet(['axis-domain', 'axis-grid', 'axis-label', 'axis-tick', 'axis-title', 'legend-band', 'legend-entry', 'legend-gradient', 'legend-label', 'legend-title', 'legend-symbol', 'title']); // aria attribute generators for guide roles\n\nconst AriaGuides = {\n 'axis': {\n desc: 'axis',\n caption: axisCaption\n },\n 'legend': {\n desc: 'legend',\n caption: legendCaption\n },\n 'title-text': {\n desc: 'title',\n caption: item => `Title text '${titleCaption(item)}'`\n },\n 'title-subtitle': {\n desc: 'subtitle',\n caption: item => `Subtitle text '${titleCaption(item)}'`\n }\n}; // aria properties generated for mark item encoding channels\n\nconst AriaEncode = {\n ariaRole: ARIA_ROLE,\n ariaRoleDescription: ARIA_ROLEDESCRIPTION,\n description: ARIA_LABEL\n};\nfunction ariaItemAttributes(emit, item) {\n const hide = item.aria === false;\n emit(ARIA_HIDDEN, hide || undefined);\n\n if (hide || item.description == null) {\n for (const prop in AriaEncode) {\n emit(AriaEncode[prop], undefined);\n }\n } else {\n const type = item.mark.marktype;\n emit(ARIA_LABEL, item.description);\n emit(ARIA_ROLE, item.ariaRole || (type === 'group' ? GRAPHICS_OBJECT : GRAPHICS_SYMBOL));\n emit(ARIA_ROLEDESCRIPTION, item.ariaRoleDescription || `${type} mark`);\n }\n}\nfunction ariaMarkAttributes(mark) {\n return mark.aria === false ? {\n [ARIA_HIDDEN]: true\n } : AriaIgnore[mark.role] ? null : AriaGuides[mark.role] ? ariaGuide(mark, AriaGuides[mark.role]) : ariaMark(mark);\n}\n\nfunction ariaMark(mark) {\n const type = mark.marktype;\n const recurse = type === 'group' || type === 'text' || mark.items.some(_ => _.description != null && _.aria !== false);\n return bundle(recurse ? GRAPHICS_OBJECT : GRAPHICS_SYMBOL, `${type} mark container`, mark.description);\n}\n\nfunction ariaGuide(mark, opt) {\n try {\n const item = mark.items[0],\n caption = opt.caption || (() => '');\n\n return bundle(opt.role || GRAPHICS_SYMBOL, opt.desc, item.description || caption(item));\n } catch (err) {\n return null;\n }\n}\n\nfunction titleCaption(item) {\n return array(item.text).join(' ');\n}\n\nfunction axisCaption(item) {\n const datum = item.datum,\n orient = item.orient,\n title = datum.title ? extractTitle(item) : null,\n ctx = item.context,\n scale = ctx.scales[datum.scale].value,\n locale = ctx.dataflow.locale(),\n type = scale.type,\n xy = orient === 'left' || orient === 'right' ? 'Y' : 'X';\n return `${xy}-axis` + (title ? ` titled '${title}'` : '') + ` for a ${isDiscrete(type) ? 'discrete' : type} scale` + ` with ${domainCaption(locale, scale, item)}`;\n}\n\nfunction legendCaption(item) {\n const datum = item.datum,\n title = datum.title ? extractTitle(item) : null,\n type = `${datum.type || ''} legend`.trim(),\n scales = datum.scales,\n props = Object.keys(scales),\n ctx = item.context,\n scale = ctx.scales[scales[props[0]]].value,\n locale = ctx.dataflow.locale();\n return capitalize(type) + (title ? ` titled '${title}'` : '') + ` for ${channelCaption(props)}` + ` with ${domainCaption(locale, scale, item)}`;\n}\n\nfunction extractTitle(item) {\n try {\n return array(peek(item.items).items[0].text).join(' ');\n } catch (err) {\n return null;\n }\n}\n\nfunction channelCaption(props) {\n props = props.map(p => p + (p === 'fill' || p === 'stroke' ? ' color' : ''));\n return props.length < 2 ? props[0] : props.slice(0, -1).join(', ') + ' and ' + peek(props);\n}\n\nfunction capitalize(s) {\n return s.length ? s[0].toUpperCase() + s.slice(1) : s;\n}\n\nconst innerText = val => (val + '').replace(/&/g, '&').replace(//g, '>');\n\nconst attrText = val => innerText(val).replace(/\"/g, '"').replace(/\\t/g, ' ').replace(/\\n/g, ' ').replace(/\\r/g, ' ');\n\nfunction markup() {\n let buf = '',\n outer = '',\n inner = '';\n\n const stack = [],\n clear = () => outer = inner = '',\n push = tag => {\n if (outer) {\n buf += `${outer}>${inner}`;\n clear();\n }\n\n stack.push(tag);\n },\n attr = (name, value) => {\n if (value != null) outer += ` ${name}=\"${attrText(value)}\"`;\n return m;\n },\n m = {\n open(tag, ...attrs) {\n push(tag);\n outer = '<' + tag;\n\n for (const set of attrs) {\n for (const key in set) attr(key, set[key]);\n }\n\n return m;\n },\n\n close() {\n const tag = stack.pop();\n\n if (outer) {\n buf += outer + (inner ? `>${inner}` : '/>');\n } else {\n buf += ``;\n }\n\n clear();\n return m;\n },\n\n attr,\n text: t => (inner += innerText(t), m),\n toString: () => buf\n };\n\n return m;\n}\nconst serializeXML = node => _serialize(markup(), node) + '';\n\nfunction _serialize(m, node) {\n m.open(node.tagName);\n\n if (node.hasAttributes()) {\n const attrs = node.attributes,\n n = attrs.length;\n\n for (let i = 0; i < n; ++i) {\n m.attr(attrs[i].name, attrs[i].value);\n }\n }\n\n if (node.hasChildNodes()) {\n const children = node.childNodes,\n n = children.length;\n\n for (let i = 0; i < n; i++) {\n const child = children[i];\n child.nodeType === 3 // text node\n ? m.text(child.nodeValue) : _serialize(m, child);\n }\n }\n\n return m.close();\n}\n\nconst styles = {\n fill: 'fill',\n fillOpacity: 'fill-opacity',\n stroke: 'stroke',\n strokeOpacity: 'stroke-opacity',\n strokeWidth: 'stroke-width',\n strokeCap: 'stroke-linecap',\n strokeJoin: 'stroke-linejoin',\n strokeDash: 'stroke-dasharray',\n strokeDashOffset: 'stroke-dashoffset',\n strokeMiterLimit: 'stroke-miterlimit',\n opacity: 'opacity',\n blend: 'mix-blend-mode'\n}; // ensure miter limit default is consistent with canvas (#2498)\n\nconst rootAttributes = {\n 'fill': 'none',\n 'stroke-miterlimit': 10\n};\n\nconst RootIndex = 0,\n xmlns = 'http://www.w3.org/2000/xmlns/',\n svgns = metadata.xmlns;\nfunction SVGRenderer(loader) {\n Renderer.call(this, loader);\n this._dirtyID = 0;\n this._dirty = [];\n this._svg = null;\n this._root = null;\n this._defs = null;\n}\nconst base = Renderer.prototype;\ninherits(SVGRenderer, Renderer, {\n /**\n * Initialize a new SVGRenderer instance.\n * @param {DOMElement} el - The containing DOM element for the display.\n * @param {number} width - The coordinate width of the display, in pixels.\n * @param {number} height - The coordinate height of the display, in pixels.\n * @param {Array} origin - The origin of the display, in pixels.\n * The coordinate system will be translated to this point.\n * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply\n * the width and height to determine the final pixel size.\n * @return {SVGRenderer} - This renderer instance.\n */\n initialize(el, width, height, origin, scaleFactor) {\n // create the svg definitions cache\n this._defs = {};\n\n this._clearDefs();\n\n if (el) {\n this._svg = domChild(el, 0, 'svg', svgns);\n\n this._svg.setAttributeNS(xmlns, 'xmlns', svgns);\n\n this._svg.setAttributeNS(xmlns, 'xmlns:xlink', metadata['xmlns:xlink']);\n\n this._svg.setAttribute('version', metadata['version']);\n\n this._svg.setAttribute('class', 'marks');\n\n domClear(el, 1); // set the svg root group\n\n this._root = domChild(this._svg, RootIndex, 'g', svgns);\n setAttributes(this._root, rootAttributes); // ensure no additional child elements\n\n domClear(this._svg, RootIndex + 1);\n } // set background color if defined\n\n\n this.background(this._bgcolor);\n return base.initialize.call(this, el, width, height, origin, scaleFactor);\n },\n\n /**\n * Get / set the background color.\n */\n background(bgcolor) {\n if (arguments.length && this._svg) {\n this._svg.style.setProperty('background-color', bgcolor);\n }\n\n return base.background.apply(this, arguments);\n },\n\n /**\n * Resize the display.\n * @param {number} width - The new coordinate width of the display, in pixels.\n * @param {number} height - The new coordinate height of the display, in pixels.\n * @param {Array} origin - The new origin of the display, in pixels.\n * The coordinate system will be translated to this point.\n * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply\n * the width and height to determine the final pixel size.\n * @return {SVGRenderer} - This renderer instance;\n */\n resize(width, height, origin, scaleFactor) {\n base.resize.call(this, width, height, origin, scaleFactor);\n\n if (this._svg) {\n setAttributes(this._svg, {\n width: this._width * this._scale,\n height: this._height * this._scale,\n viewBox: `0 0 ${this._width} ${this._height}`\n });\n\n this._root.setAttribute('transform', `translate(${this._origin})`);\n }\n\n this._dirty = [];\n return this;\n },\n\n /**\n * Returns the SVG element of the visualization.\n * @return {DOMElement} - The SVG element.\n */\n canvas() {\n return this._svg;\n },\n\n /**\n * Returns an SVG text string for the rendered content,\n * or null if this renderer is currently headless.\n */\n svg() {\n const svg = this._svg,\n bg = this._bgcolor;\n if (!svg) return null;\n let node;\n\n if (bg) {\n svg.removeAttribute('style');\n node = domChild(svg, RootIndex, 'rect', svgns);\n setAttributes(node, {\n width: this._width,\n height: this._height,\n fill: bg\n });\n }\n\n const text = serializeXML(svg);\n\n if (bg) {\n svg.removeChild(node);\n\n this._svg.style.setProperty('background-color', bg);\n }\n\n return text;\n },\n\n /**\n * Internal rendering method.\n * @param {object} scene - The root mark of a scenegraph to render.\n */\n _render(scene) {\n // perform spot updates and re-render markup\n if (this._dirtyCheck()) {\n if (this._dirtyAll) this._clearDefs();\n this.mark(this._root, scene);\n domClear(this._root, 1);\n }\n\n this.defs();\n this._dirty = [];\n ++this._dirtyID;\n return this;\n },\n\n // -- Manage rendering of items marked as dirty --\n\n /**\n * Flag a mark item as dirty.\n * @param {Item} item - The mark item.\n */\n dirty(item) {\n if (item.dirty !== this._dirtyID) {\n item.dirty = this._dirtyID;\n\n this._dirty.push(item);\n }\n },\n\n /**\n * Check if a mark item is considered dirty.\n * @param {Item} item - The mark item.\n */\n isDirty(item) {\n return this._dirtyAll || !item._svg || item.dirty === this._dirtyID;\n },\n\n /**\n * Internal method to check dirty status and, if possible,\n * make targetted updates without a full rendering pass.\n */\n _dirtyCheck() {\n this._dirtyAll = true;\n const items = this._dirty;\n if (!items.length || !this._dirtyID) return true;\n const id = ++this._dirtyID;\n let item, mark, type, mdef, i, n, o;\n\n for (i = 0, n = items.length; i < n; ++i) {\n item = items[i];\n mark = item.mark;\n\n if (mark.marktype !== type) {\n // memoize mark instance lookup\n type = mark.marktype;\n mdef = Marks[type];\n }\n\n if (mark.zdirty && mark.dirty !== id) {\n this._dirtyAll = false;\n dirtyParents(item, id);\n mark.items.forEach(i => {\n i.dirty = id;\n });\n }\n\n if (mark.zdirty) continue; // handle in standard drawing pass\n\n if (item.exit) {\n // EXIT\n if (mdef.nested && mark.items.length) {\n // if nested mark with remaining points, update instead\n o = mark.items[0];\n if (o._svg) this._update(mdef, o._svg, o);\n } else if (item._svg) {\n // otherwise remove from DOM\n o = item._svg.parentNode;\n if (o) o.removeChild(item._svg);\n }\n\n item._svg = null;\n continue;\n }\n\n item = mdef.nested ? mark.items[0] : item;\n if (item._update === id) continue; // already visited\n\n if (!item._svg || !item._svg.ownerSVGElement) {\n // ENTER\n this._dirtyAll = false;\n dirtyParents(item, id);\n } else {\n // IN-PLACE UPDATE\n this._update(mdef, item._svg, item);\n }\n\n item._update = id;\n }\n\n return !this._dirtyAll;\n },\n\n // -- Construct & maintain scenegraph to SVG mapping ---\n\n /**\n * Render a set of mark items.\n * @param {SVGElement} el - The parent element in the SVG tree.\n * @param {object} scene - The mark parent to render.\n * @param {SVGElement} prev - The previous sibling in the SVG tree.\n */\n mark(el, scene, prev) {\n if (!this.isDirty(scene)) return scene._svg;\n const svg = this._svg,\n mdef = Marks[scene.marktype],\n events = scene.interactive === false ? 'none' : null,\n isGroup = mdef.tag === 'g';\n let sibling = null,\n i = 0;\n const parent = bind(scene, el, prev, 'g', svg);\n parent.setAttribute('class', cssClass(scene)); // apply aria attributes to parent container element\n\n const aria = ariaMarkAttributes(scene);\n\n for (const key in aria) setAttribute(parent, key, aria[key]);\n\n if (!isGroup) {\n setAttribute(parent, 'pointer-events', events);\n }\n\n setAttribute(parent, 'clip-path', scene.clip ? clip$1(this, scene, scene.group) : null);\n\n const process = item => {\n const dirty = this.isDirty(item),\n node = bind(item, parent, sibling, mdef.tag, svg);\n\n if (dirty) {\n this._update(mdef, node, item);\n\n if (isGroup) recurse(this, node, item);\n }\n\n sibling = node;\n ++i;\n };\n\n if (mdef.nested) {\n if (scene.items.length) process(scene.items[0]);\n } else {\n visit(scene, process);\n }\n\n domClear(parent, i);\n return parent;\n },\n\n /**\n * Update the attributes of an SVG element for a mark item.\n * @param {object} mdef - The mark definition object\n * @param {SVGElement} el - The SVG element.\n * @param {Item} item - The mark item.\n */\n _update(mdef, el, item) {\n // set dom element and values cache\n // provides access to emit method\n element = el;\n values = el.__values__; // apply aria-specific properties\n\n ariaItemAttributes(emit, item); // apply svg attributes\n\n mdef.attr(emit, item, this); // some marks need special treatment\n\n const extra = mark_extras[mdef.type];\n if (extra) extra.call(this, mdef, el, item); // apply svg style attributes\n // note: element state may have been modified by 'extra' method\n\n if (element) this.style(element, item);\n },\n\n /**\n * Update the presentation attributes of an SVG element for a mark item.\n * @param {SVGElement} el - The SVG element.\n * @param {Item} item - The mark item.\n */\n style(el, item) {\n if (item == null) return;\n\n for (const prop in styles) {\n let value = prop === 'font' ? fontFamily(item) : item[prop];\n if (value === values[prop]) continue;\n const name = styles[prop];\n\n if (value == null) {\n el.removeAttribute(name);\n } else {\n if (isGradient(value)) {\n value = gradientRef(value, this._defs.gradient, href());\n }\n\n el.setAttribute(name, value + '');\n }\n\n values[prop] = value;\n }\n },\n\n /**\n * Render SVG defs, as needed.\n * Must be called *after* marks have been processed to ensure the\n * collected state is current and accurate.\n */\n defs() {\n const svg = this._svg,\n defs = this._defs;\n let el = defs.el,\n index = 0;\n\n for (const id in defs.gradient) {\n if (!el) defs.el = el = domChild(svg, RootIndex + 1, 'defs', svgns);\n index = updateGradient(el, defs.gradient[id], index);\n }\n\n for (const id in defs.clipping) {\n if (!el) defs.el = el = domChild(svg, RootIndex + 1, 'defs', svgns);\n index = updateClipping(el, defs.clipping[id], index);\n } // clean-up\n\n\n if (el) {\n index === 0 ? (svg.removeChild(el), defs.el = null) : domClear(el, index);\n }\n },\n\n /**\n * Clear defs caches.\n */\n _clearDefs() {\n const def = this._defs;\n def.gradient = {};\n def.clipping = {};\n }\n\n}); // mark ancestor chain with a dirty id\n\nfunction dirtyParents(item, id) {\n for (; item && item.dirty !== id; item = item.mark.group) {\n item.dirty = id;\n\n if (item.mark && item.mark.dirty !== id) {\n item.mark.dirty = id;\n } else return;\n }\n} // update gradient definitions\n\n\nfunction updateGradient(el, grad, index) {\n let i, n, stop;\n\n if (grad.gradient === 'radial') {\n // SVG radial gradients automatically transform to normalized bbox\n // coordinates, in a way that is cumbersome to replicate in canvas.\n // We wrap the radial gradient in a pattern element, allowing us to\n // maintain a circular gradient that matches what canvas provides.\n let pt = domChild(el, index++, 'pattern', svgns);\n setAttributes(pt, {\n id: patternPrefix + grad.id,\n viewBox: '0,0,1,1',\n width: '100%',\n height: '100%',\n preserveAspectRatio: 'xMidYMid slice'\n });\n pt = domChild(pt, 0, 'rect', svgns);\n setAttributes(pt, {\n width: 1,\n height: 1,\n fill: `url(${href()}#${grad.id})`\n });\n el = domChild(el, index++, 'radialGradient', svgns);\n setAttributes(el, {\n id: grad.id,\n fx: grad.x1,\n fy: grad.y1,\n fr: grad.r1,\n cx: grad.x2,\n cy: grad.y2,\n r: grad.r2\n });\n } else {\n el = domChild(el, index++, 'linearGradient', svgns);\n setAttributes(el, {\n id: grad.id,\n x1: grad.x1,\n x2: grad.x2,\n y1: grad.y1,\n y2: grad.y2\n });\n }\n\n for (i = 0, n = grad.stops.length; i < n; ++i) {\n stop = domChild(el, i, 'stop', svgns);\n stop.setAttribute('offset', grad.stops[i].offset);\n stop.setAttribute('stop-color', grad.stops[i].color);\n }\n\n domClear(el, i);\n return index;\n} // update clipping path definitions\n\n\nfunction updateClipping(el, clip, index) {\n let mask;\n el = domChild(el, index, 'clipPath', svgns);\n el.setAttribute('id', clip.id);\n\n if (clip.path) {\n mask = domChild(el, 0, 'path', svgns);\n mask.setAttribute('d', clip.path);\n } else {\n mask = domChild(el, 0, 'rect', svgns);\n setAttributes(mask, {\n x: 0,\n y: 0,\n width: clip.width,\n height: clip.height\n });\n }\n\n domClear(el, 1);\n return index + 1;\n} // Recursively process group contents.\n\n\nfunction recurse(renderer, el, group) {\n el = el.lastChild.previousSibling;\n let prev,\n idx = 0;\n visit(group, item => {\n prev = renderer.mark(el, item, prev);\n ++idx;\n }); // remove any extraneous DOM elements\n\n domClear(el, 1 + idx);\n} // Bind a scenegraph item to an SVG DOM element.\n// Create new SVG elements as needed.\n\n\nfunction bind(item, el, sibling, tag, svg) {\n let node = item._svg,\n doc; // create a new dom node if needed\n\n if (!node) {\n doc = el.ownerDocument;\n node = domCreate(doc, tag, svgns);\n item._svg = node;\n\n if (item.mark) {\n node.__data__ = item;\n node.__values__ = {\n fill: 'default'\n }; // if group, create background, content, and foreground elements\n\n if (tag === 'g') {\n const bg = domCreate(doc, 'path', svgns);\n node.appendChild(bg);\n bg.__data__ = item;\n const cg = domCreate(doc, 'g', svgns);\n node.appendChild(cg);\n cg.__data__ = item;\n const fg = domCreate(doc, 'path', svgns);\n node.appendChild(fg);\n fg.__data__ = item;\n fg.__values__ = {\n fill: 'default'\n };\n }\n }\n } // (re-)insert if (a) not contained in SVG or (b) sibling order has changed\n\n\n if (node.ownerSVGElement !== svg || siblingCheck(node, sibling)) {\n el.insertBefore(node, sibling ? sibling.nextSibling : el.firstChild);\n }\n\n return node;\n} // check if two nodes are ordered siblings\n\n\nfunction siblingCheck(node, sibling) {\n return node.parentNode && node.parentNode.childNodes.length > 1 && node.previousSibling != sibling; // treat null/undefined the same\n} // -- Set attributes & styles on SVG elements ---\n\n\nlet element = null,\n // temp var for current SVG element\nvalues = null; // temp var for current values hash\n// Extra configuration for certain mark types\n\nconst mark_extras = {\n group(mdef, el, item) {\n const fg = element = el.childNodes[2];\n values = fg.__values__;\n mdef.foreground(emit, item, this);\n values = el.__values__; // use parent's values hash\n\n element = el.childNodes[1];\n mdef.content(emit, item, this);\n const bg = element = el.childNodes[0];\n mdef.background(emit, item, this);\n const value = item.mark.interactive === false ? 'none' : null;\n\n if (value !== values.events) {\n setAttribute(fg, 'pointer-events', value);\n setAttribute(bg, 'pointer-events', value);\n values.events = value;\n }\n\n if (item.strokeForeground && item.stroke) {\n const fill = item.fill;\n setAttribute(fg, 'display', null); // set style of background\n\n this.style(bg, item);\n setAttribute(bg, 'stroke', null); // set style of foreground\n\n if (fill) item.fill = null;\n values = fg.__values__;\n this.style(fg, item);\n if (fill) item.fill = fill; // leave element null to prevent downstream styling\n\n element = null;\n } else {\n // ensure foreground is ignored\n setAttribute(fg, 'display', 'none');\n }\n },\n\n image(mdef, el, item) {\n if (item.smooth === false) {\n setStyle(el, 'image-rendering', 'optimizeSpeed');\n setStyle(el, 'image-rendering', 'pixelated');\n } else {\n setStyle(el, 'image-rendering', null);\n }\n },\n\n text(mdef, el, item) {\n const tl = textLines(item);\n let key, value, doc, lh;\n\n if (isArray(tl)) {\n // multi-line text\n value = tl.map(_ => textValue(item, _));\n key = value.join('\\n'); // content cache key\n\n if (key !== values.text) {\n domClear(el, 0);\n doc = el.ownerDocument;\n lh = lineHeight(item);\n value.forEach((t, i) => {\n const ts = domCreate(doc, 'tspan', svgns);\n ts.__data__ = item; // data binding\n\n ts.textContent = t;\n\n if (i) {\n ts.setAttribute('x', 0);\n ts.setAttribute('dy', lh);\n }\n\n el.appendChild(ts);\n });\n values.text = key;\n }\n } else {\n // single-line text\n value = textValue(item, tl);\n\n if (value !== values.text) {\n el.textContent = value;\n values.text = value;\n }\n }\n\n setAttribute(el, 'font-family', fontFamily(item));\n setAttribute(el, 'font-size', fontSize(item) + 'px');\n setAttribute(el, 'font-style', item.fontStyle);\n setAttribute(el, 'font-variant', item.fontVariant);\n setAttribute(el, 'font-weight', item.fontWeight);\n }\n\n};\n\nfunction emit(name, value, ns) {\n // early exit if value is unchanged\n if (value === values[name]) return; // use appropriate method given namespace (ns)\n\n if (ns) {\n setAttributeNS(element, name, value, ns);\n } else {\n setAttribute(element, name, value);\n } // note current value for future comparison\n\n\n values[name] = value;\n}\n\nfunction setStyle(el, name, value) {\n if (value !== values[name]) {\n if (value == null) {\n el.style.removeProperty(name);\n } else {\n el.style.setProperty(name, value + '');\n }\n\n values[name] = value;\n }\n}\n\nfunction setAttributes(el, attrs) {\n for (const key in attrs) {\n setAttribute(el, key, attrs[key]);\n }\n}\n\nfunction setAttribute(el, name, value) {\n if (value != null) {\n // if value is provided, update DOM attribute\n el.setAttribute(name, value);\n } else {\n // else remove DOM attribute\n el.removeAttribute(name);\n }\n}\n\nfunction setAttributeNS(el, name, value, ns) {\n if (value != null) {\n // if value is provided, update DOM attribute\n el.setAttributeNS(ns, name, value);\n } else {\n // else remove DOM attribute\n el.removeAttributeNS(ns, name);\n }\n}\n\nfunction href() {\n let loc;\n return typeof window === 'undefined' ? '' : (loc = window.location).hash ? loc.href.slice(0, -loc.hash.length) : loc.href;\n}\n\nfunction SVGStringRenderer(loader) {\n Renderer.call(this, loader);\n this._text = null;\n this._defs = {\n gradient: {},\n clipping: {}\n };\n}\ninherits(SVGStringRenderer, Renderer, {\n /**\n * Returns the rendered SVG text string,\n * or null if rendering has not yet occurred.\n */\n svg() {\n return this._text;\n },\n\n /**\n * Internal rendering method.\n * @param {object} scene - The root mark of a scenegraph to render.\n */\n _render(scene) {\n const m = markup(); // svg tag\n\n m.open('svg', extend({}, metadata, {\n class: 'marks',\n width: this._width * this._scale,\n height: this._height * this._scale,\n viewBox: `0 0 ${this._width} ${this._height}`\n })); // background, if defined\n\n const bg = this._bgcolor;\n\n if (bg && bg !== 'transparent' && bg !== 'none') {\n m.open('rect', {\n width: this._width,\n height: this._height,\n fill: bg\n }).close();\n } // root content group\n\n\n m.open('g', rootAttributes, {\n transform: 'translate(' + this._origin + ')'\n });\n this.mark(m, scene);\n m.close(); // \n // defs\n\n this.defs(m); // get SVG text string\n\n this._text = m.close() + '';\n return this;\n },\n\n /**\n * Render a set of mark items.\n * @param {object} m - The markup context.\n * @param {object} scene - The mark parent to render.\n */\n mark(m, scene) {\n const mdef = Marks[scene.marktype],\n tag = mdef.tag,\n attrList = [ariaItemAttributes, mdef.attr]; // render opening group tag\n\n m.open('g', {\n 'class': cssClass(scene),\n 'clip-path': scene.clip ? clip$1(this, scene, scene.group) : null\n }, ariaMarkAttributes(scene), {\n 'pointer-events': tag !== 'g' && scene.interactive === false ? 'none' : null\n }); // render contained elements\n\n const process = item => {\n const href = this.href(item);\n if (href) m.open('a', href);\n m.open(tag, this.attr(scene, item, attrList, tag !== 'g' ? tag : null));\n\n if (tag === 'text') {\n const tl = textLines(item);\n\n if (isArray(tl)) {\n // multi-line text\n const attrs = {\n x: 0,\n dy: lineHeight(item)\n };\n\n for (let i = 0; i < tl.length; ++i) {\n m.open('tspan', i ? attrs : null).text(textValue(item, tl[i])).close();\n }\n } else {\n // single-line text\n m.text(textValue(item, tl));\n }\n } else if (tag === 'g') {\n const fore = item.strokeForeground,\n fill = item.fill,\n stroke = item.stroke;\n\n if (fore && stroke) {\n item.stroke = null;\n }\n\n m.open('path', this.attr(scene, item, mdef.background, 'bgrect')).close(); // recurse for group content\n\n m.open('g', this.attr(scene, item, mdef.content));\n visit(item, scene => this.mark(m, scene));\n m.close();\n\n if (fore && stroke) {\n if (fill) item.fill = null;\n item.stroke = stroke;\n m.open('path', this.attr(scene, item, mdef.foreground, 'bgrect')).close();\n if (fill) item.fill = fill;\n } else {\n m.open('path', this.attr(scene, item, mdef.foreground, 'bgfore')).close();\n }\n }\n\n m.close(); // \n\n if (href) m.close(); // \n };\n\n if (mdef.nested) {\n if (scene.items && scene.items.length) process(scene.items[0]);\n } else {\n visit(scene, process);\n } // render closing group tag\n\n\n return m.close(); // \n },\n\n /**\n * Get href attributes for a hyperlinked mark item.\n * @param {Item} item - The mark item.\n */\n href(item) {\n const href = item.href;\n let attr;\n\n if (href) {\n if (attr = this._hrefs && this._hrefs[href]) {\n return attr;\n } else {\n this.sanitizeURL(href).then(attr => {\n // rewrite to use xlink namespace\n attr['xlink:href'] = attr.href;\n attr.href = null;\n (this._hrefs || (this._hrefs = {}))[href] = attr;\n });\n }\n }\n\n return null;\n },\n\n /**\n * Get an object of SVG attributes for a mark item.\n * @param {object} scene - The mark parent.\n * @param {Item} item - The mark item.\n * @param {array|function} attrs - One or more attribute emitters.\n * @param {string} tag - The tag being rendered.\n */\n attr(scene, item, attrs, tag) {\n const object = {},\n emit = (name, value, ns, prefixed) => {\n object[prefixed || name] = value;\n }; // apply mark specific attributes\n\n\n if (Array.isArray(attrs)) {\n attrs.forEach(fn => fn(emit, item, this));\n } else {\n attrs(emit, item, this);\n } // apply style attributes\n\n\n if (tag) {\n style(object, item, scene, tag, this._defs);\n }\n\n return object;\n },\n\n /**\n * Render SVG defs, as needed.\n * Must be called *after* marks have been processed to ensure the\n * collected state is current and accurate.\n * @param {object} m - The markup context.\n */\n defs(m) {\n const gradient = this._defs.gradient,\n clipping = this._defs.clipping,\n count = Object.keys(gradient).length + Object.keys(clipping).length;\n if (count === 0) return; // nothing to do\n\n m.open('defs');\n\n for (const id in gradient) {\n const def = gradient[id],\n stops = def.stops;\n\n if (def.gradient === 'radial') {\n // SVG radial gradients automatically transform to normalized bbox\n // coordinates, in a way that is cumbersome to replicate in canvas.\n // We wrap the radial gradient in a pattern element, allowing us to\n // maintain a circular gradient that matches what canvas provides.\n m.open('pattern', {\n id: patternPrefix + id,\n viewBox: '0,0,1,1',\n width: '100%',\n height: '100%',\n preserveAspectRatio: 'xMidYMid slice'\n });\n m.open('rect', {\n width: '1',\n height: '1',\n fill: 'url(#' + id + ')'\n }).close();\n m.close(); // \n\n m.open('radialGradient', {\n id: id,\n fx: def.x1,\n fy: def.y1,\n fr: def.r1,\n cx: def.x2,\n cy: def.y2,\n r: def.r2\n });\n } else {\n m.open('linearGradient', {\n id: id,\n x1: def.x1,\n x2: def.x2,\n y1: def.y1,\n y2: def.y2\n });\n }\n\n for (let i = 0; i < stops.length; ++i) {\n m.open('stop', {\n offset: stops[i].offset,\n 'stop-color': stops[i].color\n }).close();\n }\n\n m.close();\n }\n\n for (const id in clipping) {\n const def = clipping[id];\n m.open('clipPath', {\n id: id\n });\n\n if (def.path) {\n m.open('path', {\n d: def.path\n }).close();\n } else {\n m.open('rect', {\n x: 0,\n y: 0,\n width: def.width,\n height: def.height\n }).close();\n }\n\n m.close();\n }\n\n m.close();\n }\n\n}); // Helper function for attr for style presentation attributes\n\nfunction style(s, item, scene, tag, defs) {\n if (item == null) return s;\n\n if (tag === 'bgrect' && scene.interactive === false) {\n s['pointer-events'] = 'none';\n }\n\n if (tag === 'bgfore') {\n if (scene.interactive === false) {\n s['pointer-events'] = 'none';\n }\n\n s.display = 'none';\n if (item.fill !== null) return s;\n }\n\n if (tag === 'image' && item.smooth === false) {\n s.style = 'image-rendering: optimizeSpeed; image-rendering: pixelated;';\n }\n\n if (tag === 'text') {\n s['font-family'] = fontFamily(item);\n s['font-size'] = fontSize(item) + 'px';\n s['font-style'] = item.fontStyle;\n s['font-variant'] = item.fontVariant;\n s['font-weight'] = item.fontWeight;\n }\n\n for (const prop in styles) {\n let value = item[prop];\n const name = styles[prop];\n\n if (value === 'transparent' && (name === 'fill' || name === 'stroke')) ; else if (value != null) {\n if (isGradient(value)) {\n value = gradientRef(value, defs.gradient, '');\n }\n\n s[name] = value;\n }\n }\n\n return s;\n}\n\nconst Canvas = 'canvas';\nconst PNG = 'png';\nconst SVG = 'svg';\nconst None = 'none';\nconst RenderType = {\n Canvas: Canvas,\n PNG: PNG,\n SVG: SVG,\n None: None\n};\nconst modules = {};\nmodules[Canvas] = modules[PNG] = {\n renderer: CanvasRenderer,\n headless: CanvasRenderer,\n handler: CanvasHandler\n};\nmodules[SVG] = {\n renderer: SVGRenderer,\n headless: SVGStringRenderer,\n handler: SVGHandler\n};\nmodules[None] = {};\nfunction renderModule(name, _) {\n name = String(name || '').toLowerCase();\n\n if (arguments.length > 1) {\n modules[name] = _;\n return this;\n } else {\n return modules[name];\n }\n}\n\nfunction intersect(scene, bounds, filter) {\n const hits = [],\n // intersection results\n box = new Bounds().union(bounds),\n // defensive copy\n type = scene.marktype;\n return type ? intersectMark(scene, box, filter, hits) : type === 'group' ? intersectGroup(scene, box, filter, hits) : error('Intersect scene must be mark node or group item.');\n}\n\nfunction intersectMark(mark, box, filter, hits) {\n if (visitMark(mark, box, filter)) {\n const items = mark.items,\n type = mark.marktype,\n n = items.length;\n let i = 0;\n\n if (type === 'group') {\n for (; i < n; ++i) {\n intersectGroup(items[i], box, filter, hits);\n }\n } else {\n for (const test = Marks[type].isect; i < n; ++i) {\n const item = items[i];\n if (intersectItem(item, box, test)) hits.push(item);\n }\n }\n }\n\n return hits;\n}\n\nfunction visitMark(mark, box, filter) {\n // process if bounds intersect and if\n // (1) mark is a group mark (so we must recurse), or\n // (2) mark is interactive and passes filter\n return mark.bounds && box.intersects(mark.bounds) && (mark.marktype === 'group' || mark.interactive !== false && (!filter || filter(mark)));\n}\n\nfunction intersectGroup(group, box, filter, hits) {\n // test intersect against group\n // skip groups by default unless filter says otherwise\n if (filter && filter(group.mark) && intersectItem(group, box, Marks.group.isect)) {\n hits.push(group);\n } // recursively test children marks\n // translate box to group coordinate space\n\n\n const marks = group.items,\n n = marks && marks.length;\n\n if (n) {\n const x = group.x || 0,\n y = group.y || 0;\n box.translate(-x, -y);\n\n for (let i = 0; i < n; ++i) {\n intersectMark(marks[i], box, filter, hits);\n }\n\n box.translate(x, y);\n }\n\n return hits;\n}\n\nfunction intersectItem(item, box, test) {\n // test bounds enclosure, bounds intersection, then detailed test\n const bounds = item.bounds;\n return box.encloses(bounds) || box.intersects(bounds) && test(item, box);\n}\n\nconst clipBounds = new Bounds();\nfunction boundClip (mark) {\n const clip = mark.clip;\n\n if (isFunction(clip)) {\n clip(boundContext(clipBounds.clear()));\n } else if (clip) {\n clipBounds.set(0, 0, mark.group.width, mark.group.height);\n } else return;\n\n mark.bounds.intersect(clipBounds);\n}\n\nconst TOLERANCE = 1e-9;\nfunction sceneEqual(a, b, key) {\n return a === b ? true : key === 'path' ? pathEqual(a, b) : a instanceof Date && b instanceof Date ? +a === +b : isNumber(a) && isNumber(b) ? Math.abs(a - b) <= TOLERANCE : !a || !b || !isObject(a) && !isObject(b) ? a == b : objectEqual(a, b);\n}\nfunction pathEqual(a, b) {\n return sceneEqual(pathParse(a), pathParse(b));\n}\n\nfunction objectEqual(a, b) {\n var ka = Object.keys(a),\n kb = Object.keys(b),\n key,\n i;\n if (ka.length !== kb.length) return false;\n ka.sort();\n kb.sort();\n\n for (i = ka.length - 1; i >= 0; i--) {\n if (ka[i] != kb[i]) return false;\n }\n\n for (i = ka.length - 1; i >= 0; i--) {\n key = ka[i];\n if (!sceneEqual(a[key], b[key], key)) return false;\n }\n\n return typeof a === typeof b;\n}\n\nfunction resetSVGDefIds() {\n resetSVGClipId();\n resetSVGGradientId();\n}\n\nexport { Bounds, CanvasHandler, CanvasRenderer, Gradient, GroupItem, Handler, Item, Marks, RenderType, Renderer, ResourceLoader, SVGHandler, SVGRenderer, SVGStringRenderer, Scenegraph, boundClip, boundContext, boundItem, boundMark, boundStroke, domChild, domClear, domCreate, domFind, font, fontFamily, fontSize, intersect, intersectBoxLine, intersectPath, intersectPoint, intersectRule, lineHeight, markup, multiLineOffset, curves as pathCurves, pathEqual, pathParse, vg_rect as pathRectangle, pathRender, symbols as pathSymbols, vg_trail as pathTrail, point, renderModule, resetSVGClipId, resetSVGDefIds, sceneEqual, sceneFromJSON, pickVisit as scenePickVisit, sceneToJSON, visit as sceneVisit, zorder as sceneZOrder, serializeXML, textMetrics };\n","import {path} from \"d3-path\";\nimport circle from \"./symbol/circle.js\";\nimport cross from \"./symbol/cross.js\";\nimport diamond from \"./symbol/diamond.js\";\nimport star from \"./symbol/star.js\";\nimport square from \"./symbol/square.js\";\nimport triangle from \"./symbol/triangle.js\";\nimport wye from \"./symbol/wye.js\";\nimport constant from \"./constant.js\";\n\nexport var symbols = [\n circle,\n cross,\n diamond,\n square,\n star,\n triangle,\n wye\n];\n\nexport default function(type, size) {\n var context = null;\n type = typeof type === \"function\" ? type : constant(type || circle);\n size = typeof size === \"function\" ? size : constant(size === undefined ? 64 : +size);\n\n function symbol() {\n var buffer;\n if (!context) context = buffer = path();\n type.apply(this, arguments).draw(context, +size.apply(this, arguments));\n if (buffer) return context = null, buffer + \"\" || null;\n }\n\n symbol.type = function(_) {\n return arguments.length ? (type = typeof _ === \"function\" ? _ : constant(_), symbol) : type;\n };\n\n symbol.size = function(_) {\n return arguments.length ? (size = typeof _ === \"function\" ? _ : constant(+_), symbol) : size;\n };\n\n symbol.context = function(_) {\n return arguments.length ? (context = _ == null ? null : _, symbol) : context;\n };\n\n return symbol;\n}\n","import { Transform } from 'vega-dataflow';\nimport { Marks, boundClip, GroupItem, Item, Bounds, multiLineOffset, boundStroke } from 'vega-scenegraph';\nimport { inherits, peek, isObject } from 'vega-util';\n\nconst Top = 'top';\nconst Left = 'left';\nconst Right = 'right';\nconst Bottom = 'bottom';\nconst TopLeft = 'top-left';\nconst TopRight = 'top-right';\nconst BottomLeft = 'bottom-left';\nconst BottomRight = 'bottom-right';\nconst Start = 'start';\nconst Middle = 'middle';\nconst End = 'end';\nconst X = 'x';\nconst Y = 'y';\nconst Group = 'group';\nconst AxisRole = 'axis';\nconst TitleRole = 'title';\nconst FrameRole = 'frame';\nconst ScopeRole = 'scope';\nconst LegendRole = 'legend';\nconst RowHeader = 'row-header';\nconst RowFooter = 'row-footer';\nconst RowTitle = 'row-title';\nconst ColHeader = 'column-header';\nconst ColFooter = 'column-footer';\nconst ColTitle = 'column-title';\nconst Padding = 'padding';\nconst Symbols = 'symbol';\nconst Fit = 'fit';\nconst FitX = 'fit-x';\nconst FitY = 'fit-y';\nconst Pad = 'pad';\nconst None = 'none';\nconst All = 'all';\nconst Each = 'each';\nconst Flush = 'flush';\nconst Column = 'column';\nconst Row = 'row';\n\n/**\n * Calculate bounding boxes for scenegraph items.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {object} params.mark - The scenegraph mark instance to bound.\n */\n\nfunction Bound(params) {\n Transform.call(this, null, params);\n}\ninherits(Bound, Transform, {\n transform(_, pulse) {\n const view = pulse.dataflow,\n mark = _.mark,\n type = mark.marktype,\n entry = Marks[type],\n bound = entry.bound;\n let markBounds = mark.bounds,\n rebound;\n\n if (entry.nested) {\n // multi-item marks have a single bounds instance\n if (mark.items.length) view.dirty(mark.items[0]);\n markBounds = boundItem(mark, bound);\n mark.items.forEach(item => {\n item.bounds.clear().union(markBounds);\n });\n } else if (type === Group || _.modified()) {\n // operator parameters modified -> re-bound all items\n // updates group bounds in response to modified group content\n pulse.visit(pulse.MOD, item => view.dirty(item));\n markBounds.clear();\n mark.items.forEach(item => markBounds.union(boundItem(item, bound))); // force reflow for axes/legends/titles to propagate any layout changes\n\n switch (mark.role) {\n case AxisRole:\n case LegendRole:\n case TitleRole:\n pulse.reflow();\n }\n } else {\n // incrementally update bounds, re-bound mark as needed\n rebound = pulse.changed(pulse.REM);\n pulse.visit(pulse.ADD, item => {\n markBounds.union(boundItem(item, bound));\n });\n pulse.visit(pulse.MOD, item => {\n rebound = rebound || markBounds.alignsWith(item.bounds);\n view.dirty(item);\n markBounds.union(boundItem(item, bound));\n });\n\n if (rebound) {\n markBounds.clear();\n mark.items.forEach(item => markBounds.union(item.bounds));\n }\n } // ensure mark bounds do not exceed any clipping region\n\n\n boundClip(mark);\n return pulse.modifies('bounds');\n }\n\n});\n\nfunction boundItem(item, bound, opt) {\n return bound(item.bounds.clear(), item, opt);\n}\n\nconst COUNTER_NAME = ':vega_identifier:';\n/**\n * Adds a unique identifier to all added tuples.\n * This transform creates a new signal that serves as an id counter.\n * As a result, the id counter is shared across all instances of this\n * transform, generating unique ids across multiple data streams. In\n * addition, this signal value can be included in a snapshot of the\n * dataflow state, enabling correct resumption of id allocation.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {string} params.as - The field name for the generated identifier.\n */\n\nfunction Identifier(params) {\n Transform.call(this, 0, params);\n}\nIdentifier.Definition = {\n 'type': 'Identifier',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'as',\n 'type': 'string',\n 'required': true\n }]\n};\ninherits(Identifier, Transform, {\n transform(_, pulse) {\n const counter = getCounter(pulse.dataflow),\n as = _.as;\n let id = counter.value;\n pulse.visit(pulse.ADD, t => t[as] = t[as] || ++id);\n counter.set(this.value = id);\n return pulse;\n }\n\n});\n\nfunction getCounter(view) {\n return view._signals[COUNTER_NAME] || (view._signals[COUNTER_NAME] = view.add(0));\n}\n\n/**\n * Bind scenegraph items to a scenegraph mark instance.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {object} params.markdef - The mark definition for creating the mark.\n * This is an object of legal scenegraph mark properties which *must* include\n * the 'marktype' property.\n */\n\nfunction Mark(params) {\n Transform.call(this, null, params);\n}\ninherits(Mark, Transform, {\n transform(_, pulse) {\n let mark = this.value; // acquire mark on first invocation, bind context and group\n\n if (!mark) {\n mark = pulse.dataflow.scenegraph().mark(_.markdef, lookup(_), _.index);\n mark.group.context = _.context;\n if (!_.context.group) _.context.group = mark.group;\n mark.source = this.source; // point to upstream collector\n\n mark.clip = _.clip;\n mark.interactive = _.interactive;\n this.value = mark;\n } // initialize entering items\n\n\n const Init = mark.marktype === Group ? GroupItem : Item;\n pulse.visit(pulse.ADD, item => Init.call(item, mark)); // update clipping and/or interactive status\n\n if (_.modified('clip') || _.modified('interactive')) {\n mark.clip = _.clip;\n mark.interactive = !!_.interactive;\n mark.zdirty = true; // force scenegraph re-eval\n\n pulse.reflow();\n } // bind items array to scenegraph mark\n\n\n mark.items = pulse.source;\n return pulse;\n }\n\n});\n\nfunction lookup(_) {\n const g = _.groups,\n p = _.parent;\n return g && g.size === 1 ? g.get(Object.keys(g.object)[0]) : g && p ? g.lookup(p) : null;\n}\n\n/**\n * Analyze items for overlap, changing opacity to hide items with\n * overlapping bounding boxes. This transform will preserve at least\n * two items (e.g., first and last) even if overlap persists.\n * @param {object} params - The parameters for this operator.\n * @param {function(*,*): number} [params.sort] - A comparator\n * function for sorting items.\n * @param {object} [params.method] - The overlap removal method to apply.\n * One of 'parity' (default, hide every other item until there is no\n * more overlap) or 'greedy' (sequentially scan and hide and items that\n * overlap with the last visible item).\n * @param {object} [params.boundScale] - A scale whose range should be used\n * to bound the items. Items exceeding the bounds of the scale range\n * will be treated as overlapping. If null or undefined, no bounds check\n * will be applied.\n * @param {object} [params.boundOrient] - The orientation of the scale\n * (top, bottom, left, or right) used to bound items. This parameter is\n * ignored if boundScale is null or undefined.\n * @param {object} [params.boundTolerance] - The tolerance in pixels for\n * bound inclusion testing (default 1). This specifies by how many pixels\n * an item's bounds may exceed the scale range bounds and not be culled.\n * @constructor\n */\n\nfunction Overlap(params) {\n Transform.call(this, null, params);\n}\nconst methods = {\n parity: items => items.filter((item, i) => i % 2 ? item.opacity = 0 : 1),\n greedy: (items, sep) => {\n let a;\n return items.filter((b, i) => !i || !intersect(a.bounds, b.bounds, sep) ? (a = b, 1) : b.opacity = 0);\n }\n}; // compute bounding box intersection\n// including padding pixels of separation\n\nconst intersect = (a, b, sep) => sep > Math.max(b.x1 - a.x2, a.x1 - b.x2, b.y1 - a.y2, a.y1 - b.y2);\n\nconst hasOverlap = (items, pad) => {\n for (var i = 1, n = items.length, a = items[0].bounds, b; i < n; a = b, ++i) {\n if (intersect(a, b = items[i].bounds, pad)) return true;\n }\n};\n\nconst hasBounds = item => {\n const b = item.bounds;\n return b.width() > 1 && b.height() > 1;\n};\n\nconst boundTest = (scale, orient, tolerance) => {\n var range = scale.range(),\n b = new Bounds();\n\n if (orient === Top || orient === Bottom) {\n b.set(range[0], -Infinity, range[1], +Infinity);\n } else {\n b.set(-Infinity, range[0], +Infinity, range[1]);\n }\n\n b.expand(tolerance || 1);\n return item => b.encloses(item.bounds);\n}; // reset all items to be fully opaque\n\n\nconst reset = source => {\n source.forEach(item => item.opacity = 1);\n return source;\n}; // add all tuples to mod, fork pulse if parameters were modified\n// fork prevents cross-stream tuple pollution (e.g., pulse from scale)\n\n\nconst reflow = (pulse, _) => pulse.reflow(_.modified()).modifies('opacity');\n\ninherits(Overlap, Transform, {\n transform(_, pulse) {\n const reduce = methods[_.method] || methods.parity,\n sep = _.separation || 0;\n let source = pulse.materialize(pulse.SOURCE).source,\n items,\n test;\n if (!source || !source.length) return;\n\n if (!_.method) {\n // early exit if method is falsy\n if (_.modified('method')) {\n reset(source);\n pulse = reflow(pulse, _);\n }\n\n return pulse;\n } // skip labels with no content\n\n\n source = source.filter(hasBounds); // early exit, nothing to do\n\n if (!source.length) return;\n\n if (_.sort) {\n source = source.slice().sort(_.sort);\n }\n\n items = reset(source);\n pulse = reflow(pulse, _);\n\n if (items.length >= 3 && hasOverlap(items, sep)) {\n do {\n items = reduce(items, sep);\n } while (items.length >= 3 && hasOverlap(items, sep));\n\n if (items.length < 3 && !peek(source).opacity) {\n if (items.length > 1) peek(items).opacity = 0;\n peek(source).opacity = 1;\n }\n }\n\n if (_.boundScale && _.boundTolerance >= 0) {\n test = boundTest(_.boundScale, _.boundOrient, +_.boundTolerance);\n source.forEach(item => {\n if (!test(item)) item.opacity = 0;\n });\n } // re-calculate mark bounds\n\n\n const bounds = items[0].mark.bounds.clear();\n source.forEach(item => {\n if (item.opacity) bounds.union(item.bounds);\n });\n return pulse;\n }\n\n});\n\n/**\n * Queue modified scenegraph items for rendering.\n * @constructor\n */\n\nfunction Render(params) {\n Transform.call(this, null, params);\n}\ninherits(Render, Transform, {\n transform(_, pulse) {\n const view = pulse.dataflow;\n pulse.visit(pulse.ALL, item => view.dirty(item)); // set z-index dirty flag as needed\n\n if (pulse.fields && pulse.fields['zindex']) {\n const item = pulse.source && pulse.source[0];\n if (item) item.mark.zdirty = true;\n }\n }\n\n});\n\nconst tempBounds = new Bounds();\nfunction set(item, property, value) {\n return item[property] === value ? 0 : (item[property] = value, 1);\n}\n\nfunction isYAxis(mark) {\n var orient = mark.items[0].orient;\n return orient === Left || orient === Right;\n}\n\nfunction axisIndices(datum) {\n let index = +datum.grid;\n return [datum.ticks ? index++ : -1, // ticks index\n datum.labels ? index++ : -1, // labels index\n index + +datum.domain // title index\n ];\n}\n\nfunction axisLayout(view, axis, width, height) {\n var item = axis.items[0],\n datum = item.datum,\n delta = item.translate != null ? item.translate : 0.5,\n orient = item.orient,\n indices = axisIndices(datum),\n range = item.range,\n offset = item.offset,\n position = item.position,\n minExtent = item.minExtent,\n maxExtent = item.maxExtent,\n title = datum.title && item.items[indices[2]].items[0],\n titlePadding = item.titlePadding,\n bounds = item.bounds,\n dl = title && multiLineOffset(title),\n x = 0,\n y = 0,\n i,\n s;\n tempBounds.clear().union(bounds);\n bounds.clear();\n if ((i = indices[0]) > -1) bounds.union(item.items[i].bounds);\n if ((i = indices[1]) > -1) bounds.union(item.items[i].bounds); // position axis group and title\n\n switch (orient) {\n case Top:\n x = position || 0;\n y = -offset;\n s = Math.max(minExtent, Math.min(maxExtent, -bounds.y1));\n bounds.add(0, -s).add(range, 0);\n if (title) axisTitleLayout(view, title, s, titlePadding, dl, 0, -1, bounds);\n break;\n\n case Left:\n x = -offset;\n y = position || 0;\n s = Math.max(minExtent, Math.min(maxExtent, -bounds.x1));\n bounds.add(-s, 0).add(0, range);\n if (title) axisTitleLayout(view, title, s, titlePadding, dl, 1, -1, bounds);\n break;\n\n case Right:\n x = width + offset;\n y = position || 0;\n s = Math.max(minExtent, Math.min(maxExtent, bounds.x2));\n bounds.add(0, 0).add(s, range);\n if (title) axisTitleLayout(view, title, s, titlePadding, dl, 1, 1, bounds);\n break;\n\n case Bottom:\n x = position || 0;\n y = height + offset;\n s = Math.max(minExtent, Math.min(maxExtent, bounds.y2));\n bounds.add(0, 0).add(range, s);\n if (title) axisTitleLayout(view, title, s, titlePadding, 0, 0, 1, bounds);\n break;\n\n default:\n x = item.x;\n y = item.y;\n } // update bounds\n\n\n boundStroke(bounds.translate(x, y), item);\n\n if (set(item, 'x', x + delta) | set(item, 'y', y + delta)) {\n item.bounds = tempBounds;\n view.dirty(item);\n item.bounds = bounds;\n view.dirty(item);\n }\n\n return item.mark.bounds.clear().union(bounds);\n}\n\nfunction axisTitleLayout(view, title, offset, pad, dl, isYAxis, sign, bounds) {\n const b = title.bounds;\n\n if (title.auto) {\n const v = sign * (offset + dl + pad);\n let dx = 0,\n dy = 0;\n view.dirty(title);\n isYAxis ? dx = (title.x || 0) - (title.x = v) : dy = (title.y || 0) - (title.y = v);\n title.mark.bounds.clear().union(b.translate(-dx, -dy));\n view.dirty(title);\n }\n\n bounds.union(b);\n}\n\nconst min = (a, b) => Math.floor(Math.min(a, b));\n\nconst max = (a, b) => Math.ceil(Math.max(a, b));\n\nfunction gridLayoutGroups(group) {\n var groups = group.items,\n n = groups.length,\n i = 0,\n mark,\n items;\n const views = {\n marks: [],\n rowheaders: [],\n rowfooters: [],\n colheaders: [],\n colfooters: [],\n rowtitle: null,\n coltitle: null\n }; // layout axes, gather legends, collect bounds\n\n for (; i < n; ++i) {\n mark = groups[i];\n items = mark.items;\n\n if (mark.marktype === Group) {\n switch (mark.role) {\n case AxisRole:\n case LegendRole:\n case TitleRole:\n break;\n\n case RowHeader:\n views.rowheaders.push(...items);\n break;\n\n case RowFooter:\n views.rowfooters.push(...items);\n break;\n\n case ColHeader:\n views.colheaders.push(...items);\n break;\n\n case ColFooter:\n views.colfooters.push(...items);\n break;\n\n case RowTitle:\n views.rowtitle = items[0];\n break;\n\n case ColTitle:\n views.coltitle = items[0];\n break;\n\n default:\n views.marks.push(...items);\n }\n }\n }\n\n return views;\n}\n\nfunction bboxFlush(item) {\n return new Bounds().set(0, 0, item.width || 0, item.height || 0);\n}\n\nfunction bboxFull(item) {\n const b = item.bounds.clone();\n return b.empty() ? b.set(0, 0, 0, 0) : b.translate(-(item.x || 0), -(item.y || 0));\n}\n\nfunction get(opt, key, d) {\n const v = isObject(opt) ? opt[key] : opt;\n return v != null ? v : d !== undefined ? d : 0;\n}\n\nfunction offsetValue(v) {\n return v < 0 ? Math.ceil(-v) : 0;\n}\n\nfunction gridLayout(view, groups, opt) {\n var dirty = !opt.nodirty,\n bbox = opt.bounds === Flush ? bboxFlush : bboxFull,\n bounds = tempBounds.set(0, 0, 0, 0),\n alignCol = get(opt.align, Column),\n alignRow = get(opt.align, Row),\n padCol = get(opt.padding, Column),\n padRow = get(opt.padding, Row),\n ncols = opt.columns || groups.length,\n nrows = ncols <= 0 ? 1 : Math.ceil(groups.length / ncols),\n n = groups.length,\n xOffset = Array(n),\n xExtent = Array(ncols),\n xMax = 0,\n yOffset = Array(n),\n yExtent = Array(nrows),\n yMax = 0,\n dx = Array(n),\n dy = Array(n),\n boxes = Array(n),\n m,\n i,\n c,\n r,\n b,\n g,\n px,\n py,\n x,\n y,\n offset;\n\n for (i = 0; i < ncols; ++i) xExtent[i] = 0;\n\n for (i = 0; i < nrows; ++i) yExtent[i] = 0; // determine offsets for each group\n\n\n for (i = 0; i < n; ++i) {\n g = groups[i];\n b = boxes[i] = bbox(g);\n g.x = g.x || 0;\n dx[i] = 0;\n g.y = g.y || 0;\n dy[i] = 0;\n c = i % ncols;\n r = ~~(i / ncols);\n xMax = Math.max(xMax, px = Math.ceil(b.x2));\n yMax = Math.max(yMax, py = Math.ceil(b.y2));\n xExtent[c] = Math.max(xExtent[c], px);\n yExtent[r] = Math.max(yExtent[r], py);\n xOffset[i] = padCol + offsetValue(b.x1);\n yOffset[i] = padRow + offsetValue(b.y1);\n if (dirty) view.dirty(groups[i]);\n } // set initial alignment offsets\n\n\n for (i = 0; i < n; ++i) {\n if (i % ncols === 0) xOffset[i] = 0;\n if (i < ncols) yOffset[i] = 0;\n } // enforce column alignment constraints\n\n\n if (alignCol === Each) {\n for (c = 1; c < ncols; ++c) {\n for (offset = 0, i = c; i < n; i += ncols) {\n if (offset < xOffset[i]) offset = xOffset[i];\n }\n\n for (i = c; i < n; i += ncols) {\n xOffset[i] = offset + xExtent[c - 1];\n }\n }\n } else if (alignCol === All) {\n for (offset = 0, i = 0; i < n; ++i) {\n if (i % ncols && offset < xOffset[i]) offset = xOffset[i];\n }\n\n for (i = 0; i < n; ++i) {\n if (i % ncols) xOffset[i] = offset + xMax;\n }\n } else {\n for (alignCol = false, c = 1; c < ncols; ++c) {\n for (i = c; i < n; i += ncols) {\n xOffset[i] += xExtent[c - 1];\n }\n }\n } // enforce row alignment constraints\n\n\n if (alignRow === Each) {\n for (r = 1; r < nrows; ++r) {\n for (offset = 0, i = r * ncols, m = i + ncols; i < m; ++i) {\n if (offset < yOffset[i]) offset = yOffset[i];\n }\n\n for (i = r * ncols; i < m; ++i) {\n yOffset[i] = offset + yExtent[r - 1];\n }\n }\n } else if (alignRow === All) {\n for (offset = 0, i = ncols; i < n; ++i) {\n if (offset < yOffset[i]) offset = yOffset[i];\n }\n\n for (i = ncols; i < n; ++i) {\n yOffset[i] = offset + yMax;\n }\n } else {\n for (alignRow = false, r = 1; r < nrows; ++r) {\n for (i = r * ncols, m = i + ncols; i < m; ++i) {\n yOffset[i] += yExtent[r - 1];\n }\n }\n } // perform horizontal grid layout\n\n\n for (x = 0, i = 0; i < n; ++i) {\n x = xOffset[i] + (i % ncols ? x : 0);\n dx[i] += x - groups[i].x;\n } // perform vertical grid layout\n\n\n for (c = 0; c < ncols; ++c) {\n for (y = 0, i = c; i < n; i += ncols) {\n y += yOffset[i];\n dy[i] += y - groups[i].y;\n }\n } // perform horizontal centering\n\n\n if (alignCol && get(opt.center, Column) && nrows > 1) {\n for (i = 0; i < n; ++i) {\n b = alignCol === All ? xMax : xExtent[i % ncols];\n x = b - boxes[i].x2 - groups[i].x - dx[i];\n if (x > 0) dx[i] += x / 2;\n }\n } // perform vertical centering\n\n\n if (alignRow && get(opt.center, Row) && ncols !== 1) {\n for (i = 0; i < n; ++i) {\n b = alignRow === All ? yMax : yExtent[~~(i / ncols)];\n y = b - boxes[i].y2 - groups[i].y - dy[i];\n if (y > 0) dy[i] += y / 2;\n }\n } // position grid relative to anchor\n\n\n for (i = 0; i < n; ++i) {\n bounds.union(boxes[i].translate(dx[i], dy[i]));\n }\n\n x = get(opt.anchor, X);\n y = get(opt.anchor, Y);\n\n switch (get(opt.anchor, Column)) {\n case End:\n x -= bounds.width();\n break;\n\n case Middle:\n x -= bounds.width() / 2;\n }\n\n switch (get(opt.anchor, Row)) {\n case End:\n y -= bounds.height();\n break;\n\n case Middle:\n y -= bounds.height() / 2;\n }\n\n x = Math.round(x);\n y = Math.round(y); // update mark positions, bounds, dirty\n\n bounds.clear();\n\n for (i = 0; i < n; ++i) {\n groups[i].mark.bounds.clear();\n }\n\n for (i = 0; i < n; ++i) {\n g = groups[i];\n g.x += dx[i] += x;\n g.y += dy[i] += y;\n bounds.union(g.mark.bounds.union(g.bounds.translate(dx[i], dy[i])));\n if (dirty) view.dirty(g);\n }\n\n return bounds;\n}\nfunction trellisLayout(view, group, opt) {\n var views = gridLayoutGroups(group),\n groups = views.marks,\n bbox = opt.bounds === Flush ? boundFlush : boundFull,\n off = opt.offset,\n ncols = opt.columns || groups.length,\n nrows = ncols <= 0 ? 1 : Math.ceil(groups.length / ncols),\n cells = nrows * ncols,\n x,\n y,\n x2,\n y2,\n anchor,\n band,\n offset; // -- initial grid layout\n\n const bounds = gridLayout(view, groups, opt);\n if (bounds.empty()) bounds.set(0, 0, 0, 0); // empty grid\n // -- layout grid headers and footers --\n // perform row header layout\n\n if (views.rowheaders) {\n band = get(opt.headerBand, Row, null);\n x = layoutHeaders(view, views.rowheaders, groups, ncols, nrows, -get(off, 'rowHeader'), min, 0, bbox, 'x1', 0, ncols, 1, band);\n } // perform column header layout\n\n\n if (views.colheaders) {\n band = get(opt.headerBand, Column, null);\n y = layoutHeaders(view, views.colheaders, groups, ncols, ncols, -get(off, 'columnHeader'), min, 1, bbox, 'y1', 0, 1, ncols, band);\n } // perform row footer layout\n\n\n if (views.rowfooters) {\n band = get(opt.footerBand, Row, null);\n x2 = layoutHeaders(view, views.rowfooters, groups, ncols, nrows, get(off, 'rowFooter'), max, 0, bbox, 'x2', ncols - 1, ncols, 1, band);\n } // perform column footer layout\n\n\n if (views.colfooters) {\n band = get(opt.footerBand, Column, null);\n y2 = layoutHeaders(view, views.colfooters, groups, ncols, ncols, get(off, 'columnFooter'), max, 1, bbox, 'y2', cells - ncols, 1, ncols, band);\n } // perform row title layout\n\n\n if (views.rowtitle) {\n anchor = get(opt.titleAnchor, Row);\n offset = get(off, 'rowTitle');\n offset = anchor === End ? x2 + offset : x - offset;\n band = get(opt.titleBand, Row, 0.5);\n layoutTitle(view, views.rowtitle, offset, 0, bounds, band);\n } // perform column title layout\n\n\n if (views.coltitle) {\n anchor = get(opt.titleAnchor, Column);\n offset = get(off, 'columnTitle');\n offset = anchor === End ? y2 + offset : y - offset;\n band = get(opt.titleBand, Column, 0.5);\n layoutTitle(view, views.coltitle, offset, 1, bounds, band);\n }\n}\n\nfunction boundFlush(item, field) {\n return field === 'x1' ? item.x || 0 : field === 'y1' ? item.y || 0 : field === 'x2' ? (item.x || 0) + (item.width || 0) : field === 'y2' ? (item.y || 0) + (item.height || 0) : undefined;\n}\n\nfunction boundFull(item, field) {\n return item.bounds[field];\n}\n\nfunction layoutHeaders(view, headers, groups, ncols, limit, offset, agg, isX, bound, bf, start, stride, back, band) {\n var n = groups.length,\n init = 0,\n edge = 0,\n i,\n j,\n k,\n m,\n b,\n h,\n g,\n x,\n y; // if no groups, early exit and return 0\n\n if (!n) return init; // compute margin\n\n for (i = start; i < n; i += stride) {\n if (groups[i]) init = agg(init, bound(groups[i], bf));\n } // if no headers, return margin calculation\n\n\n if (!headers.length) return init; // check if number of headers exceeds number of rows or columns\n\n if (headers.length > limit) {\n view.warn('Grid headers exceed limit: ' + limit);\n headers = headers.slice(0, limit);\n } // apply offset\n\n\n init += offset; // clear mark bounds for all headers\n\n for (j = 0, m = headers.length; j < m; ++j) {\n view.dirty(headers[j]);\n headers[j].mark.bounds.clear();\n } // layout each header\n\n\n for (i = start, j = 0, m = headers.length; j < m; ++j, i += stride) {\n h = headers[j];\n b = h.mark.bounds; // search for nearest group to align to\n // necessary if table has empty cells\n\n for (k = i; k >= 0 && (g = groups[k]) == null; k -= back); // assign coordinates and update bounds\n\n\n if (isX) {\n x = band == null ? g.x : Math.round(g.bounds.x1 + band * g.bounds.width());\n y = init;\n } else {\n x = init;\n y = band == null ? g.y : Math.round(g.bounds.y1 + band * g.bounds.height());\n }\n\n b.union(h.bounds.translate(x - (h.x || 0), y - (h.y || 0)));\n h.x = x;\n h.y = y;\n view.dirty(h); // update current edge of layout bounds\n\n edge = agg(edge, b[bf]);\n }\n\n return edge;\n}\n\nfunction layoutTitle(view, g, offset, isX, bounds, band) {\n if (!g) return;\n view.dirty(g); // compute title coordinates\n\n var x = offset,\n y = offset;\n isX ? x = Math.round(bounds.x1 + band * bounds.width()) : y = Math.round(bounds.y1 + band * bounds.height()); // assign coordinates and update bounds\n\n g.bounds.translate(x - (g.x || 0), y - (g.y || 0));\n g.mark.bounds.clear().union(g.bounds);\n g.x = x;\n g.y = y; // queue title for redraw\n\n view.dirty(g);\n}\n\nfunction lookup$1(config, orient) {\n const opt = config[orient] || {};\n return (key, d) => opt[key] != null ? opt[key] : config[key] != null ? config[key] : d;\n} // if legends specify offset directly, use the maximum specified value\n\n\nfunction offsets(legends, value) {\n let max = -Infinity;\n legends.forEach(item => {\n if (item.offset != null) max = Math.max(max, item.offset);\n });\n return max > -Infinity ? max : value;\n}\n\nfunction legendParams(g, orient, config, xb, yb, w, h) {\n const _ = lookup$1(config, orient),\n offset = offsets(g, _('offset', 0)),\n anchor = _('anchor', Start),\n mult = anchor === End ? 1 : anchor === Middle ? 0.5 : 0;\n\n const p = {\n align: Each,\n bounds: _('bounds', Flush),\n columns: _('direction') === 'vertical' ? 1 : g.length,\n padding: _('margin', 8),\n center: _('center'),\n nodirty: true\n };\n\n switch (orient) {\n case Left:\n p.anchor = {\n x: Math.floor(xb.x1) - offset,\n column: End,\n y: mult * (h || xb.height() + 2 * xb.y1),\n row: anchor\n };\n break;\n\n case Right:\n p.anchor = {\n x: Math.ceil(xb.x2) + offset,\n y: mult * (h || xb.height() + 2 * xb.y1),\n row: anchor\n };\n break;\n\n case Top:\n p.anchor = {\n y: Math.floor(yb.y1) - offset,\n row: End,\n x: mult * (w || yb.width() + 2 * yb.x1),\n column: anchor\n };\n break;\n\n case Bottom:\n p.anchor = {\n y: Math.ceil(yb.y2) + offset,\n x: mult * (w || yb.width() + 2 * yb.x1),\n column: anchor\n };\n break;\n\n case TopLeft:\n p.anchor = {\n x: offset,\n y: offset\n };\n break;\n\n case TopRight:\n p.anchor = {\n x: w - offset,\n y: offset,\n column: End\n };\n break;\n\n case BottomLeft:\n p.anchor = {\n x: offset,\n y: h - offset,\n row: End\n };\n break;\n\n case BottomRight:\n p.anchor = {\n x: w - offset,\n y: h - offset,\n column: End,\n row: End\n };\n break;\n }\n\n return p;\n}\nfunction legendLayout(view, legend) {\n var item = legend.items[0],\n datum = item.datum,\n orient = item.orient,\n bounds = item.bounds,\n x = item.x,\n y = item.y,\n w,\n h; // cache current bounds for later comparison\n\n item._bounds ? item._bounds.clear().union(bounds) : item._bounds = bounds.clone();\n bounds.clear(); // adjust legend to accommodate padding and title\n\n legendGroupLayout(view, item, item.items[0].items[0]); // aggregate bounds to determine size, and include origin\n\n bounds = legendBounds(item, bounds);\n w = 2 * item.padding;\n h = 2 * item.padding;\n\n if (!bounds.empty()) {\n w = Math.ceil(bounds.width() + w);\n h = Math.ceil(bounds.height() + h);\n }\n\n if (datum.type === Symbols) {\n legendEntryLayout(item.items[0].items[0].items[0].items);\n }\n\n if (orient !== None) {\n item.x = x = 0;\n item.y = y = 0;\n }\n\n item.width = w;\n item.height = h;\n boundStroke(bounds.set(x, y, x + w, y + h), item);\n item.mark.bounds.clear().union(bounds);\n return item;\n}\n\nfunction legendBounds(item, b) {\n // aggregate item bounds\n item.items.forEach(_ => b.union(_.bounds)); // anchor to legend origin\n\n b.x1 = item.padding;\n b.y1 = item.padding;\n return b;\n}\n\nfunction legendGroupLayout(view, item, entry) {\n var pad = item.padding,\n ex = pad - entry.x,\n ey = pad - entry.y;\n\n if (!item.datum.title) {\n if (ex || ey) translate(view, entry, ex, ey);\n } else {\n var title = item.items[1].items[0],\n anchor = title.anchor,\n tpad = item.titlePadding || 0,\n tx = pad - title.x,\n ty = pad - title.y;\n\n switch (title.orient) {\n case Left:\n ex += Math.ceil(title.bounds.width()) + tpad;\n break;\n\n case Right:\n case Bottom:\n break;\n\n default:\n ey += title.bounds.height() + tpad;\n }\n\n if (ex || ey) translate(view, entry, ex, ey);\n\n switch (title.orient) {\n case Left:\n ty += legendTitleOffset(item, entry, title, anchor, 1, 1);\n break;\n\n case Right:\n tx += legendTitleOffset(item, entry, title, End, 0, 0) + tpad;\n ty += legendTitleOffset(item, entry, title, anchor, 1, 1);\n break;\n\n case Bottom:\n tx += legendTitleOffset(item, entry, title, anchor, 0, 0);\n ty += legendTitleOffset(item, entry, title, End, -1, 0, 1) + tpad;\n break;\n\n default:\n tx += legendTitleOffset(item, entry, title, anchor, 0, 0);\n }\n\n if (tx || ty) translate(view, title, tx, ty); // translate legend if title pushes into negative coordinates\n\n if ((tx = Math.round(title.bounds.x1 - pad)) < 0) {\n translate(view, entry, -tx, 0);\n translate(view, title, -tx, 0);\n }\n }\n}\n\nfunction legendTitleOffset(item, entry, title, anchor, y, lr, noBar) {\n const grad = item.datum.type !== 'symbol',\n vgrad = title.datum.vgrad,\n e = grad && (lr || !vgrad) && !noBar ? entry.items[0] : entry,\n s = e.bounds[y ? 'y2' : 'x2'] - item.padding,\n u = vgrad && lr ? s : 0,\n v = vgrad && lr ? 0 : s,\n o = y <= 0 ? 0 : multiLineOffset(title);\n return Math.round(anchor === Start ? u : anchor === End ? v - o : 0.5 * (s - o));\n}\n\nfunction translate(view, item, dx, dy) {\n item.x += dx;\n item.y += dy;\n item.bounds.translate(dx, dy);\n item.mark.bounds.translate(dx, dy);\n view.dirty(item);\n}\n\nfunction legendEntryLayout(entries) {\n // get max widths for each column\n const widths = entries.reduce((w, g) => {\n w[g.column] = Math.max(g.bounds.x2 - g.x, w[g.column] || 0);\n return w;\n }, {}); // set dimensions of legend entry groups\n\n entries.forEach(g => {\n g.width = widths[g.column];\n g.height = g.bounds.y2 - g.y;\n });\n}\n\nfunction titleLayout(view, mark, width, height, viewBounds) {\n var group = mark.items[0],\n frame = group.frame,\n orient = group.orient,\n anchor = group.anchor,\n offset = group.offset,\n padding = group.padding,\n title = group.items[0].items[0],\n subtitle = group.items[1] && group.items[1].items[0],\n end = orient === Left || orient === Right ? height : width,\n start = 0,\n x = 0,\n y = 0,\n sx = 0,\n sy = 0,\n pos;\n\n if (frame !== Group) {\n orient === Left ? (start = viewBounds.y2, end = viewBounds.y1) : orient === Right ? (start = viewBounds.y1, end = viewBounds.y2) : (start = viewBounds.x1, end = viewBounds.x2);\n } else if (orient === Left) {\n start = height, end = 0;\n }\n\n pos = anchor === Start ? start : anchor === End ? end : (start + end) / 2;\n\n if (subtitle && subtitle.text) {\n // position subtitle\n switch (orient) {\n case Top:\n case Bottom:\n sy = title.bounds.height() + padding;\n break;\n\n case Left:\n sx = title.bounds.width() + padding;\n break;\n\n case Right:\n sx = -title.bounds.width() - padding;\n break;\n }\n\n tempBounds.clear().union(subtitle.bounds);\n tempBounds.translate(sx - (subtitle.x || 0), sy - (subtitle.y || 0));\n\n if (set(subtitle, 'x', sx) | set(subtitle, 'y', sy)) {\n view.dirty(subtitle);\n subtitle.bounds.clear().union(tempBounds);\n subtitle.mark.bounds.clear().union(tempBounds);\n view.dirty(subtitle);\n }\n\n tempBounds.clear().union(subtitle.bounds);\n } else {\n tempBounds.clear();\n }\n\n tempBounds.union(title.bounds); // position title group\n\n switch (orient) {\n case Top:\n x = pos;\n y = viewBounds.y1 - tempBounds.height() - offset;\n break;\n\n case Left:\n x = viewBounds.x1 - tempBounds.width() - offset;\n y = pos;\n break;\n\n case Right:\n x = viewBounds.x2 + tempBounds.width() + offset;\n y = pos;\n break;\n\n case Bottom:\n x = pos;\n y = viewBounds.y2 + offset;\n break;\n\n default:\n x = group.x;\n y = group.y;\n }\n\n if (set(group, 'x', x) | set(group, 'y', y)) {\n tempBounds.translate(x, y);\n view.dirty(group);\n group.bounds.clear().union(tempBounds);\n mark.bounds.clear().union(tempBounds);\n view.dirty(group);\n }\n\n return group.bounds;\n}\n\n/**\n * Layout view elements such as axes and legends.\n * Also performs size adjustments.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {object} params.mark - Scenegraph mark of groups to layout.\n */\n\nfunction ViewLayout(params) {\n Transform.call(this, null, params);\n}\ninherits(ViewLayout, Transform, {\n transform(_, pulse) {\n const view = pulse.dataflow;\n\n _.mark.items.forEach(group => {\n if (_.layout) trellisLayout(view, group, _.layout);\n layoutGroup(view, group, _);\n });\n\n return shouldReflow(_.mark.group) ? pulse.reflow() : pulse;\n }\n\n});\n\nfunction shouldReflow(group) {\n // We typically should reflow if layout is invoked (#2568), as child items\n // may have resized and reflow ensures group bounds are re-calculated.\n // However, legend entries have a special exception to avoid instability.\n // For example, if a selected legend symbol gains a stroke on hover,\n // we don't want to re-position subsequent elements in the legend.\n return group && group.mark.role !== 'legend-entry';\n}\n\nfunction layoutGroup(view, group, _) {\n var items = group.items,\n width = Math.max(0, group.width || 0),\n height = Math.max(0, group.height || 0),\n viewBounds = new Bounds().set(0, 0, width, height),\n xBounds = viewBounds.clone(),\n yBounds = viewBounds.clone(),\n legends = [],\n title,\n mark,\n orient,\n b,\n i,\n n; // layout axes, gather legends, collect bounds\n\n for (i = 0, n = items.length; i < n; ++i) {\n mark = items[i];\n\n switch (mark.role) {\n case AxisRole:\n b = isYAxis(mark) ? xBounds : yBounds;\n b.union(axisLayout(view, mark, width, height));\n break;\n\n case TitleRole:\n title = mark;\n break;\n\n case LegendRole:\n legends.push(legendLayout(view, mark));\n break;\n\n case FrameRole:\n case ScopeRole:\n case RowHeader:\n case RowFooter:\n case RowTitle:\n case ColHeader:\n case ColFooter:\n case ColTitle:\n xBounds.union(mark.bounds);\n yBounds.union(mark.bounds);\n break;\n\n default:\n viewBounds.union(mark.bounds);\n }\n } // layout legends, adjust viewBounds\n\n\n if (legends.length) {\n // group legends by orient\n const l = {};\n legends.forEach(item => {\n orient = item.orient || Right;\n if (orient !== None) (l[orient] || (l[orient] = [])).push(item);\n }); // perform grid layout for each orient group\n\n for (const orient in l) {\n const g = l[orient];\n gridLayout(view, g, legendParams(g, orient, _.legends, xBounds, yBounds, width, height));\n } // update view bounds\n\n\n legends.forEach(item => {\n const b = item.bounds;\n\n if (!b.equals(item._bounds)) {\n item.bounds = item._bounds;\n view.dirty(item); // dirty previous location\n\n item.bounds = b;\n view.dirty(item);\n }\n\n if (_.autosize && _.autosize.type === Fit) {\n // For autosize fit, incorporate the orthogonal dimension only.\n // Legends that overrun the chart area will then be clipped;\n // otherwise the chart area gets reduced to nothing!\n switch (item.orient) {\n case Left:\n case Right:\n viewBounds.add(b.x1, 0).add(b.x2, 0);\n break;\n\n case Top:\n case Bottom:\n viewBounds.add(0, b.y1).add(0, b.y2);\n }\n } else {\n viewBounds.union(b);\n }\n });\n } // combine bounding boxes\n\n\n viewBounds.union(xBounds).union(yBounds); // layout title, adjust bounds\n\n if (title) {\n viewBounds.union(titleLayout(view, title, width, height, viewBounds));\n } // override aggregated view bounds if content is clipped\n\n\n if (group.clip) {\n viewBounds.set(0, 0, group.width || 0, group.height || 0);\n } // perform size adjustment\n\n\n viewSizeLayout(view, group, viewBounds, _);\n}\n\nfunction viewSizeLayout(view, group, viewBounds, _) {\n const auto = _.autosize || {},\n type = auto.type;\n if (view._autosize < 1 || !type) return;\n let viewWidth = view._width,\n viewHeight = view._height,\n width = Math.max(0, group.width || 0),\n left = Math.max(0, Math.ceil(-viewBounds.x1)),\n height = Math.max(0, group.height || 0),\n top = Math.max(0, Math.ceil(-viewBounds.y1));\n const right = Math.max(0, Math.ceil(viewBounds.x2 - width)),\n bottom = Math.max(0, Math.ceil(viewBounds.y2 - height));\n\n if (auto.contains === Padding) {\n const padding = view.padding();\n viewWidth -= padding.left + padding.right;\n viewHeight -= padding.top + padding.bottom;\n }\n\n if (type === None) {\n left = 0;\n top = 0;\n width = viewWidth;\n height = viewHeight;\n } else if (type === Fit) {\n width = Math.max(0, viewWidth - left - right);\n height = Math.max(0, viewHeight - top - bottom);\n } else if (type === FitX) {\n width = Math.max(0, viewWidth - left - right);\n viewHeight = height + top + bottom;\n } else if (type === FitY) {\n viewWidth = width + left + right;\n height = Math.max(0, viewHeight - top - bottom);\n } else if (type === Pad) {\n viewWidth = width + left + right;\n viewHeight = height + top + bottom;\n }\n\n view._resizeView(viewWidth, viewHeight, width, height, [left, top], auto.resize);\n}\n\nexport { Bound as bound, Identifier as identifier, Mark as mark, Overlap as overlap, Render as render, ViewLayout as viewlayout };\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return Math.round(a * (1 - t) + b * t);\n };\n}\n","export function basis(t1, v0, v1, v2, v3) {\n var t2 = t1 * t1, t3 = t2 * t1;\n return ((1 - 3 * t1 + 3 * t2 - t3) * v0\n + (4 - 6 * t2 + 3 * t3) * v1\n + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2\n + t3 * v3) / 6;\n}\n\nexport default function(values) {\n var n = values.length - 1;\n return function(t) {\n var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),\n v1 = values[i],\n v2 = values[i + 1],\n v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,\n v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","export default x => () => x;\n","import constant from \"./constant.js\";\n\nfunction linear(a, d) {\n return function(t) {\n return a + t * d;\n };\n}\n\nfunction exponential(a, b, y) {\n return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {\n return Math.pow(a + t * b, y);\n };\n}\n\nexport function hue(a, b) {\n var d = b - a;\n return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);\n}\n\nexport function gamma(y) {\n return (y = +y) === 1 ? nogamma : function(a, b) {\n return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);\n };\n}\n\nexport default function nogamma(a, b) {\n var d = b - a;\n return d ? linear(a, d) : constant(isNaN(a) ? b : a);\n}\n","import {rgb as colorRgb} from \"d3-color\";\nimport basis from \"./basis.js\";\nimport basisClosed from \"./basisClosed.js\";\nimport nogamma, {gamma} from \"./color.js\";\n\nexport default (function rgbGamma(y) {\n var color = gamma(y);\n\n function rgb(start, end) {\n var r = color((start = colorRgb(start)).r, (end = colorRgb(end)).r),\n g = color(start.g, end.g),\n b = color(start.b, end.b),\n opacity = nogamma(start.opacity, end.opacity);\n return function(t) {\n start.r = r(t);\n start.g = g(t);\n start.b = b(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n rgb.gamma = rgbGamma;\n\n return rgb;\n})(1);\n\nfunction rgbSpline(spline) {\n return function(colors) {\n var n = colors.length,\n r = new Array(n),\n g = new Array(n),\n b = new Array(n),\n i, color;\n for (i = 0; i < n; ++i) {\n color = colorRgb(colors[i]);\n r[i] = color.r || 0;\n g[i] = color.g || 0;\n b[i] = color.b || 0;\n }\n r = spline(r);\n g = spline(g);\n b = spline(b);\n color.opacity = 1;\n return function(t) {\n color.r = r(t);\n color.g = g(t);\n color.b = b(t);\n return color + \"\";\n };\n };\n}\n\nexport var rgbBasis = rgbSpline(basis);\nexport var rgbBasisClosed = rgbSpline(basisClosed);\n","import {basis} from \"./basis.js\";\n\nexport default function(values) {\n var n = values.length;\n return function(t) {\n var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),\n v0 = values[(i + n - 1) % n],\n v1 = values[i % n],\n v2 = values[(i + 1) % n],\n v3 = values[(i + 2) % n];\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","export default function(a, b) {\n if (!b) b = [];\n var n = a ? Math.min(b.length, a.length) : 0,\n c = b.slice(),\n i;\n return function(t) {\n for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;\n return c;\n };\n}\n\nexport function isNumberArray(x) {\n return ArrayBuffer.isView(x) && !(x instanceof DataView);\n}\n","import value from \"./value.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n return (isNumberArray(b) ? numberArray : genericArray)(a, b);\n}\n\nexport function genericArray(a, b) {\n var nb = b ? b.length : 0,\n na = a ? Math.min(nb, a.length) : 0,\n x = new Array(na),\n c = new Array(nb),\n i;\n\n for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);\n for (; i < nb; ++i) c[i] = b[i];\n\n return function(t) {\n for (i = 0; i < na; ++i) c[i] = x[i](t);\n return c;\n };\n}\n","export default function(a, b) {\n var d = new Date;\n return a = +a, b = +b, function(t) {\n return d.setTime(a * (1 - t) + b * t), d;\n };\n}\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return a * (1 - t) + b * t;\n };\n}\n","import value from \"./value.js\";\n\nexport default function(a, b) {\n var i = {},\n c = {},\n k;\n\n if (a === null || typeof a !== \"object\") a = {};\n if (b === null || typeof b !== \"object\") b = {};\n\n for (k in b) {\n if (k in a) {\n i[k] = value(a[k], b[k]);\n } else {\n c[k] = b[k];\n }\n }\n\n return function(t) {\n for (k in i) c[k] = i[k](t);\n return c;\n };\n}\n","import number from \"./number.js\";\n\nvar reA = /[-+]?(?:\\d+\\.?\\d*|\\.?\\d+)(?:[eE][-+]?\\d+)?/g,\n reB = new RegExp(reA.source, \"g\");\n\nfunction zero(b) {\n return function() {\n return b;\n };\n}\n\nfunction one(b) {\n return function(t) {\n return b(t) + \"\";\n };\n}\n\nexport default function(a, b) {\n var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b\n am, // current match in a\n bm, // current match in b\n bs, // string preceding current number in b, if any\n i = -1, // index in s\n s = [], // string constants and placeholders\n q = []; // number interpolators\n\n // Coerce inputs to strings.\n a = a + \"\", b = b + \"\";\n\n // Interpolate pairs of numbers in a & b.\n while ((am = reA.exec(a))\n && (bm = reB.exec(b))) {\n if ((bs = bm.index) > bi) { // a string precedes the next number in b\n bs = b.slice(bi, bs);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match\n if (s[i]) s[i] += bm; // coalesce with previous string\n else s[++i] = bm;\n } else { // interpolate non-matching numbers\n s[++i] = null;\n q.push({i: i, x: number(am, bm)});\n }\n bi = reB.lastIndex;\n }\n\n // Add remains of b.\n if (bi < b.length) {\n bs = b.slice(bi);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n\n // Special optimization for only a single match.\n // Otherwise, interpolate each of the numbers and rejoin the string.\n return s.length < 2 ? (q[0]\n ? one(q[0].x)\n : zero(b))\n : (b = q.length, function(t) {\n for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);\n return s.join(\"\");\n });\n}\n","import {color} from \"d3-color\";\nimport rgb from \"./rgb.js\";\nimport {genericArray} from \"./array.js\";\nimport date from \"./date.js\";\nimport number from \"./number.js\";\nimport object from \"./object.js\";\nimport string from \"./string.js\";\nimport constant from \"./constant.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n var t = typeof b, c;\n return b == null || t === \"boolean\" ? constant(b)\n : (t === \"number\" ? number\n : t === \"string\" ? ((c = color(b)) ? (b = c, rgb) : string)\n : b instanceof color ? rgb\n : b instanceof Date ? date\n : isNumberArray(b) ? numberArray\n : Array.isArray(b) ? genericArray\n : typeof b.valueOf !== \"function\" && typeof b.toString !== \"function\" || isNaN(b) ? object\n : number)(a, b);\n}\n","import { Transform, ingest, tupleid, stableCompare } from 'vega-dataflow';\nimport { tickCount, tickFormat, validTicks, tickValues, SymbolLegend, labelFormat, labelValues, GradientLegend, scaleFraction, labelFraction, scale, isContinuous, Sequential, Linear, Time, UTC, Pow, Sqrt, Ordinal, scaleImplicit, Log, Symlog, isLogarithmic, BinOrdinal, bandSpace, isInterpolating, interpolateRange, quantizeInterpolator, interpolateColors, interpolate, Band, Point, scheme, Threshold, Quantile, Quantize, Diverging } from 'vega-scale';\nimport { inherits, isArray, error, fastmap, falsy, isFunction, constant, peek, one, toSet, isString, zoomLog, zoomPow, zoomSymlog, zoomLinear, stringValue } from 'vega-util';\nimport { sum, range } from 'd3-array';\nimport { interpolateRound, interpolate as interpolate$1 } from 'd3-interpolate';\n\n/**\n * Generates axis ticks for visualizing a spatial scale.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Scale} params.scale - The scale to generate ticks for.\n * @param {*} [params.count=10] - The approximate number of ticks, or\n * desired tick interval, to use.\n * @param {Array<*>} [params.values] - The exact tick values to use.\n * These must be legal domain values for the provided scale.\n * If provided, the count argument is ignored.\n * @param {function(*):string} [params.formatSpecifier] - A format specifier\n * to use in conjunction with scale.tickFormat. Legal values are\n * any valid d3 4.0 format specifier.\n * @param {function(*):string} [params.format] - The format function to use.\n * If provided, the formatSpecifier argument is ignored.\n */\n\nfunction AxisTicks(params) {\n Transform.call(this, null, params);\n}\ninherits(AxisTicks, Transform, {\n transform(_, pulse) {\n if (this.value && !_.modified()) {\n return pulse.StopPropagation;\n }\n\n var locale = pulse.dataflow.locale(),\n out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),\n ticks = this.value,\n scale = _.scale,\n tally = _.count == null ? _.values ? _.values.length : 10 : _.count,\n count = tickCount(scale, tally, _.minstep),\n format = _.format || tickFormat(locale, scale, count, _.formatSpecifier, _.formatType, !!_.values),\n values = _.values ? validTicks(scale, _.values, count) : tickValues(scale, count);\n if (ticks) out.rem = ticks;\n ticks = values.map((value, i) => ingest({\n index: i / (values.length - 1 || 1),\n value: value,\n label: format(value)\n }));\n\n if (_.extra && ticks.length) {\n // add an extra tick pegged to the initial domain value\n // this is used to generate axes with 'binned' domains\n ticks.push(ingest({\n index: -1,\n extra: {\n value: ticks[0].value\n },\n label: ''\n }));\n }\n\n out.source = ticks;\n out.add = ticks;\n this.value = ticks;\n return out;\n }\n\n});\n\n/**\n * Joins a set of data elements against a set of visual items.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): object} [params.item] - An item generator function.\n * @param {function(object): *} [params.key] - The key field associating data and visual items.\n */\n\nfunction DataJoin(params) {\n Transform.call(this, null, params);\n}\n\nfunction defaultItemCreate() {\n return ingest({});\n}\n\nfunction newMap(key) {\n const map = fastmap().test(t => t.exit);\n\n map.lookup = t => map.get(key(t));\n\n return map;\n}\n\ninherits(DataJoin, Transform, {\n transform(_, pulse) {\n var df = pulse.dataflow,\n out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),\n item = _.item || defaultItemCreate,\n key = _.key || tupleid,\n map = this.value; // prevent transient (e.g., hover) requests from\n // cascading across marks derived from marks\n\n if (isArray(out.encode)) {\n out.encode = null;\n }\n\n if (map && (_.modified('key') || pulse.modified(key))) {\n error('DataJoin does not support modified key function or fields.');\n }\n\n if (!map) {\n pulse = pulse.addAll();\n this.value = map = newMap(key);\n }\n\n pulse.visit(pulse.ADD, t => {\n const k = key(t);\n let x = map.get(k);\n\n if (x) {\n if (x.exit) {\n map.empty--;\n out.add.push(x);\n } else {\n out.mod.push(x);\n }\n } else {\n x = item(t);\n map.set(k, x);\n out.add.push(x);\n }\n\n x.datum = t;\n x.exit = false;\n });\n pulse.visit(pulse.MOD, t => {\n const k = key(t),\n x = map.get(k);\n\n if (x) {\n x.datum = t;\n out.mod.push(x);\n }\n });\n pulse.visit(pulse.REM, t => {\n const k = key(t),\n x = map.get(k);\n\n if (t === x.datum && !x.exit) {\n out.rem.push(x);\n x.exit = true;\n ++map.empty;\n }\n });\n if (pulse.changed(pulse.ADD_MOD)) out.modifies('datum');\n\n if (pulse.clean() || _.clean && map.empty > df.cleanThreshold) {\n df.runAfter(map.clean);\n }\n\n return out;\n }\n\n});\n\n/**\n * Invokes encoding functions for visual items.\n * @constructor\n * @param {object} params - The parameters to the encoding functions. This\n * parameter object will be passed through to all invoked encoding functions.\n * @param {object} [params.mod=false] - Flag indicating if tuples in the input\n * mod set that are unmodified by encoders should be included in the output.\n * @param {object} param.encoders - The encoding functions\n * @param {function(object, object): boolean} [param.encoders.update] - Update encoding set\n * @param {function(object, object): boolean} [param.encoders.enter] - Enter encoding set\n * @param {function(object, object): boolean} [param.encoders.exit] - Exit encoding set\n */\n\nfunction Encode(params) {\n Transform.call(this, null, params);\n}\ninherits(Encode, Transform, {\n transform(_, pulse) {\n var out = pulse.fork(pulse.ADD_REM),\n fmod = _.mod || false,\n encoders = _.encoders,\n encode = pulse.encode; // if an array, the encode directive includes additional sets\n // that must be defined in order for the primary set to be invoked\n // e.g., only run the update set if the hover set is defined\n\n if (isArray(encode)) {\n if (out.changed() || encode.every(e => encoders[e])) {\n encode = encode[0];\n out.encode = null; // consume targeted encode directive\n } else {\n return pulse.StopPropagation;\n }\n } // marshall encoder functions\n\n\n var reenter = encode === 'enter',\n update = encoders.update || falsy,\n enter = encoders.enter || falsy,\n exit = encoders.exit || falsy,\n set = (encode && !reenter ? encoders[encode] : update) || falsy;\n\n if (pulse.changed(pulse.ADD)) {\n pulse.visit(pulse.ADD, t => {\n enter(t, _);\n update(t, _);\n });\n out.modifies(enter.output);\n out.modifies(update.output);\n\n if (set !== falsy && set !== update) {\n pulse.visit(pulse.ADD, t => {\n set(t, _);\n });\n out.modifies(set.output);\n }\n }\n\n if (pulse.changed(pulse.REM) && exit !== falsy) {\n pulse.visit(pulse.REM, t => {\n exit(t, _);\n });\n out.modifies(exit.output);\n }\n\n if (reenter || set !== falsy) {\n const flag = pulse.MOD | (_.modified() ? pulse.REFLOW : 0);\n\n if (reenter) {\n pulse.visit(flag, t => {\n const mod = enter(t, _) || fmod;\n if (set(t, _) || mod) out.mod.push(t);\n });\n if (out.mod.length) out.modifies(enter.output);\n } else {\n pulse.visit(flag, t => {\n if (set(t, _) || fmod) out.mod.push(t);\n });\n }\n\n if (out.mod.length) out.modifies(set.output);\n }\n\n return out.changed() ? out : pulse.StopPropagation;\n }\n\n});\n\n/**\n * Generates legend entries for visualizing a scale.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Scale} params.scale - The scale to generate items for.\n * @param {*} [params.count=5] - The approximate number of items, or\n * desired tick interval, to use.\n * @param {*} [params.limit] - The maximum number of entries to\n * include in a symbol legend.\n * @param {Array<*>} [params.values] - The exact tick values to use.\n * These must be legal domain values for the provided scale.\n * If provided, the count argument is ignored.\n * @param {string} [params.formatSpecifier] - A format specifier\n * to use in conjunction with scale.tickFormat. Legal values are\n * any valid D3 format specifier string.\n * @param {function(*):string} [params.format] - The format function to use.\n * If provided, the formatSpecifier argument is ignored.\n */\n\nfunction LegendEntries(params) {\n Transform.call(this, [], params);\n}\ninherits(LegendEntries, Transform, {\n transform(_, pulse) {\n if (this.value != null && !_.modified()) {\n return pulse.StopPropagation;\n }\n\n var locale = pulse.dataflow.locale(),\n out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),\n items = this.value,\n type = _.type || SymbolLegend,\n scale = _.scale,\n limit = +_.limit,\n count = tickCount(scale, _.count == null ? 5 : _.count, _.minstep),\n lskip = !!_.values || type === SymbolLegend,\n format = _.format || labelFormat(locale, scale, count, type, _.formatSpecifier, _.formatType, lskip),\n values = _.values || labelValues(scale, count),\n domain,\n fraction,\n size,\n offset,\n ellipsis;\n if (items) out.rem = items;\n\n if (type === SymbolLegend) {\n if (limit && values.length > limit) {\n pulse.dataflow.warn('Symbol legend count exceeds limit, filtering items.');\n items = values.slice(0, limit - 1);\n ellipsis = true;\n } else {\n items = values;\n }\n\n if (isFunction(size = _.size)) {\n // if first value maps to size zero, remove from list (vega#717)\n if (!_.values && scale(items[0]) === 0) {\n items = items.slice(1);\n } // compute size offset for legend entries\n\n\n offset = items.reduce((max, value) => Math.max(max, size(value, _)), 0);\n } else {\n size = constant(offset = size || 8);\n }\n\n items = items.map((value, index) => ingest({\n index: index,\n label: format(value, index, items),\n value: value,\n offset: offset,\n size: size(value, _)\n }));\n\n if (ellipsis) {\n ellipsis = values[items.length];\n items.push(ingest({\n index: items.length,\n label: \"\\u2026\".concat(values.length - items.length, \" entries\"),\n value: ellipsis,\n offset: offset,\n size: size(ellipsis, _)\n }));\n }\n } else if (type === GradientLegend) {\n domain = scale.domain(), fraction = scaleFraction(scale, domain[0], peek(domain)); // if automatic label generation produces 2 or fewer values,\n // use the domain end points instead (fixes vega/vega#1364)\n\n if (values.length < 3 && !_.values && domain[0] !== peek(domain)) {\n values = [domain[0], peek(domain)];\n }\n\n items = values.map((value, index) => ingest({\n index: index,\n label: format(value, index, values),\n value: value,\n perc: fraction(value)\n }));\n } else {\n size = values.length - 1;\n fraction = labelFraction(scale);\n items = values.map((value, index) => ingest({\n index: index,\n label: format(value, index, values),\n value: value,\n perc: index ? fraction(value) : 0,\n perc2: index === size ? 1 : fraction(values[index + 1])\n }));\n }\n\n out.source = items;\n out.add = items;\n this.value = items;\n return out;\n }\n\n});\n\nconst sourceX = t => t.source.x;\n\nconst sourceY = t => t.source.y;\n\nconst targetX = t => t.target.x;\n\nconst targetY = t => t.target.y;\n/**\n * Layout paths linking source and target elements.\n * @constructor\n * @param {object} params - The parameters for this operator.\n */\n\n\nfunction LinkPath(params) {\n Transform.call(this, {}, params);\n}\nLinkPath.Definition = {\n 'type': 'LinkPath',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'sourceX',\n 'type': 'field',\n 'default': 'source.x'\n }, {\n 'name': 'sourceY',\n 'type': 'field',\n 'default': 'source.y'\n }, {\n 'name': 'targetX',\n 'type': 'field',\n 'default': 'target.x'\n }, {\n 'name': 'targetY',\n 'type': 'field',\n 'default': 'target.y'\n }, {\n 'name': 'orient',\n 'type': 'enum',\n 'default': 'vertical',\n 'values': ['horizontal', 'vertical', 'radial']\n }, {\n 'name': 'shape',\n 'type': 'enum',\n 'default': 'line',\n 'values': ['line', 'arc', 'curve', 'diagonal', 'orthogonal']\n }, {\n 'name': 'require',\n 'type': 'signal'\n }, {\n 'name': 'as',\n 'type': 'string',\n 'default': 'path'\n }]\n};\ninherits(LinkPath, Transform, {\n transform(_, pulse) {\n var sx = _.sourceX || sourceX,\n sy = _.sourceY || sourceY,\n tx = _.targetX || targetX,\n ty = _.targetY || targetY,\n as = _.as || 'path',\n orient = _.orient || 'vertical',\n shape = _.shape || 'line',\n path = Paths.get(shape + '-' + orient) || Paths.get(shape);\n\n if (!path) {\n error('LinkPath unsupported type: ' + _.shape + (_.orient ? '-' + _.orient : ''));\n }\n\n pulse.visit(pulse.SOURCE, t => {\n t[as] = path(sx(t), sy(t), tx(t), ty(t));\n });\n return pulse.reflow(_.modified()).modifies(as);\n }\n\n});\n\nconst line = (sx, sy, tx, ty) => 'M' + sx + ',' + sy + 'L' + tx + ',' + ty;\n\nconst lineR = (sa, sr, ta, tr) => line(sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta));\n\nconst arc = (sx, sy, tx, ty) => {\n var dx = tx - sx,\n dy = ty - sy,\n rr = Math.sqrt(dx * dx + dy * dy) / 2,\n ra = 180 * Math.atan2(dy, dx) / Math.PI;\n return 'M' + sx + ',' + sy + 'A' + rr + ',' + rr + ' ' + ra + ' 0 1' + ' ' + tx + ',' + ty;\n};\n\nconst arcR = (sa, sr, ta, tr) => arc(sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta));\n\nconst curve = (sx, sy, tx, ty) => {\n const dx = tx - sx,\n dy = ty - sy,\n ix = 0.2 * (dx + dy),\n iy = 0.2 * (dy - dx);\n return 'M' + sx + ',' + sy + 'C' + (sx + ix) + ',' + (sy + iy) + ' ' + (tx + iy) + ',' + (ty - ix) + ' ' + tx + ',' + ty;\n};\n\nconst curveR = (sa, sr, ta, tr) => curve(sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta));\n\nconst orthoX = (sx, sy, tx, ty) => 'M' + sx + ',' + sy + 'V' + ty + 'H' + tx;\n\nconst orthoY = (sx, sy, tx, ty) => 'M' + sx + ',' + sy + 'H' + tx + 'V' + ty;\n\nconst orthoR = (sa, sr, ta, tr) => {\n const sc = Math.cos(sa),\n ss = Math.sin(sa),\n tc = Math.cos(ta),\n ts = Math.sin(ta),\n sf = Math.abs(ta - sa) > Math.PI ? ta <= sa : ta > sa;\n return 'M' + sr * sc + ',' + sr * ss + 'A' + sr + ',' + sr + ' 0 0,' + (sf ? 1 : 0) + ' ' + sr * tc + ',' + sr * ts + 'L' + tr * tc + ',' + tr * ts;\n};\n\nconst diagonalX = (sx, sy, tx, ty) => {\n const m = (sx + tx) / 2;\n return 'M' + sx + ',' + sy + 'C' + m + ',' + sy + ' ' + m + ',' + ty + ' ' + tx + ',' + ty;\n};\n\nconst diagonalY = (sx, sy, tx, ty) => {\n const m = (sy + ty) / 2;\n return 'M' + sx + ',' + sy + 'C' + sx + ',' + m + ' ' + tx + ',' + m + ' ' + tx + ',' + ty;\n};\n\nconst diagonalR = (sa, sr, ta, tr) => {\n const sc = Math.cos(sa),\n ss = Math.sin(sa),\n tc = Math.cos(ta),\n ts = Math.sin(ta),\n mr = (sr + tr) / 2;\n return 'M' + sr * sc + ',' + sr * ss + 'C' + mr * sc + ',' + mr * ss + ' ' + mr * tc + ',' + mr * ts + ' ' + tr * tc + ',' + tr * ts;\n};\n\nconst Paths = fastmap({\n 'line': line,\n 'line-radial': lineR,\n 'arc': arc,\n 'arc-radial': arcR,\n 'curve': curve,\n 'curve-radial': curveR,\n 'orthogonal-horizontal': orthoX,\n 'orthogonal-vertical': orthoY,\n 'orthogonal-radial': orthoR,\n 'diagonal-horizontal': diagonalX,\n 'diagonal-vertical': diagonalY,\n 'diagonal-radial': diagonalR\n});\n\n/**\n * Pie and donut chart layout.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The value field to size pie segments.\n * @param {number} [params.startAngle=0] - The start angle (in radians) of the layout.\n * @param {number} [params.endAngle=2π] - The end angle (in radians) of the layout.\n * @param {boolean} [params.sort] - Boolean flag for sorting sectors by value.\n */\n\nfunction Pie(params) {\n Transform.call(this, null, params);\n}\nPie.Definition = {\n 'type': 'Pie',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field'\n }, {\n 'name': 'startAngle',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'endAngle',\n 'type': 'number',\n 'default': 6.283185307179586\n }, {\n 'name': 'sort',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': 2,\n 'default': ['startAngle', 'endAngle']\n }]\n};\ninherits(Pie, Transform, {\n transform(_, pulse) {\n var as = _.as || ['startAngle', 'endAngle'],\n startAngle = as[0],\n endAngle = as[1],\n field = _.field || one,\n start = _.startAngle || 0,\n stop = _.endAngle != null ? _.endAngle : 2 * Math.PI,\n data = pulse.source,\n values = data.map(field),\n n = values.length,\n a = start,\n k = (stop - start) / sum(values),\n index = range(n),\n i,\n t,\n v;\n\n if (_.sort) {\n index.sort((a, b) => values[a] - values[b]);\n }\n\n for (i = 0; i < n; ++i) {\n v = values[index[i]];\n t = data[index[i]];\n t[startAngle] = a;\n t[endAngle] = a += v * k;\n }\n\n this.value = values;\n return pulse.reflow(_.modified()).modifies(as);\n }\n\n});\n\nconst DEFAULT_COUNT = 5;\n\nfunction includeZero(scale) {\n const type = scale.type;\n return !scale.bins && (type === Linear || type === Pow || type === Sqrt);\n}\n\nfunction includePad(type) {\n return isContinuous(type) && type !== Sequential;\n}\n\nconst SKIP = toSet(['set', 'modified', 'clear', 'type', 'scheme', 'schemeExtent', 'schemeCount', 'domain', 'domainMin', 'domainMid', 'domainMax', 'domainRaw', 'domainImplicit', 'nice', 'zero', 'bins', 'range', 'rangeStep', 'round', 'reverse', 'interpolate', 'interpolateGamma']);\n/**\n * Maintains a scale function mapping data values to visual channels.\n * @constructor\n * @param {object} params - The parameters for this operator.\n */\n\nfunction Scale(params) {\n Transform.call(this, null, params);\n this.modified(true); // always treat as modified\n}\ninherits(Scale, Transform, {\n transform(_, pulse) {\n var df = pulse.dataflow,\n scale$1 = this.value,\n key = scaleKey(_);\n\n if (!scale$1 || key !== scale$1.type) {\n this.value = scale$1 = scale(key)();\n }\n\n for (key in _) if (!SKIP[key]) {\n // padding is a scale property for band/point but not others\n if (key === 'padding' && includePad(scale$1.type)) continue; // invoke scale property setter, raise warning if not found\n\n isFunction(scale$1[key]) ? scale$1[key](_[key]) : df.warn('Unsupported scale property: ' + key);\n }\n\n configureRange(scale$1, _, configureBins(scale$1, _, configureDomain(scale$1, _, df)));\n return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);\n }\n\n});\n\nfunction scaleKey(_) {\n var t = _.type,\n d = '',\n n; // backwards compatibility pre Vega 5.\n\n if (t === Sequential) return Sequential + '-' + Linear;\n\n if (isContinuousColor(_)) {\n n = _.rawDomain ? _.rawDomain.length : _.domain ? _.domain.length + +(_.domainMid != null) : 0;\n d = n === 2 ? Sequential + '-' : n === 3 ? Diverging + '-' : '';\n }\n\n return (d + t || Linear).toLowerCase();\n}\n\nfunction isContinuousColor(_) {\n const t = _.type;\n return isContinuous(t) && t !== Time && t !== UTC && (_.scheme || _.range && _.range.length && _.range.every(isString));\n}\n\nfunction configureDomain(scale, _, df) {\n // check raw domain, if provided use that and exit early\n const raw = rawDomain(scale, _.domainRaw, df);\n if (raw > -1) return raw;\n var domain = _.domain,\n type = scale.type,\n zero = _.zero || _.zero === undefined && includeZero(scale),\n n,\n mid;\n if (!domain) return 0; // adjust continuous domain for minimum pixel padding\n\n if (includePad(type) && _.padding && domain[0] !== peek(domain)) {\n domain = padDomain(type, domain, _.range, _.padding, _.exponent, _.constant);\n } // adjust domain based on zero, min, max settings\n\n\n if (zero || _.domainMin != null || _.domainMax != null || _.domainMid != null) {\n n = (domain = domain.slice()).length - 1 || 1;\n\n if (zero) {\n if (domain[0] > 0) domain[0] = 0;\n if (domain[n] < 0) domain[n] = 0;\n }\n\n if (_.domainMin != null) domain[0] = _.domainMin;\n if (_.domainMax != null) domain[n] = _.domainMax;\n\n if (_.domainMid != null) {\n mid = _.domainMid;\n const i = mid > domain[n] ? n + 1 : mid < domain[0] ? 0 : n;\n if (i !== n) df.warn('Scale domainMid exceeds domain min or max.', mid);\n domain.splice(i, 0, mid);\n }\n } // set the scale domain\n\n\n scale.domain(domainCheck(type, domain, df)); // if ordinal scale domain is defined, prevent implicit\n // domain construction as side-effect of scale lookup\n\n if (type === Ordinal) {\n scale.unknown(_.domainImplicit ? scaleImplicit : undefined);\n } // perform 'nice' adjustment as requested\n\n\n if (_.nice && scale.nice) {\n scale.nice(_.nice !== true && tickCount(scale, _.nice) || null);\n } // return the cardinality of the domain\n\n\n return domain.length;\n}\n\nfunction rawDomain(scale, raw, df) {\n if (raw) {\n scale.domain(domainCheck(scale.type, raw, df));\n return raw.length;\n } else {\n return -1;\n }\n}\n\nfunction padDomain(type, domain, range, pad, exponent, constant) {\n var span = Math.abs(peek(range) - range[0]),\n frac = span / (span - 2 * pad),\n d = type === Log ? zoomLog(domain, null, frac) : type === Sqrt ? zoomPow(domain, null, frac, 0.5) : type === Pow ? zoomPow(domain, null, frac, exponent || 1) : type === Symlog ? zoomSymlog(domain, null, frac, constant || 1) : zoomLinear(domain, null, frac);\n domain = domain.slice();\n domain[0] = d[0];\n domain[domain.length - 1] = d[1];\n return domain;\n}\n\nfunction domainCheck(type, domain, df) {\n if (isLogarithmic(type)) {\n // sum signs of domain values\n // if all pos or all neg, abs(sum) === domain.length\n var s = Math.abs(domain.reduce((s, v) => s + (v < 0 ? -1 : v > 0 ? 1 : 0), 0));\n\n if (s !== domain.length) {\n df.warn('Log scale domain includes zero: ' + stringValue(domain));\n }\n }\n\n return domain;\n}\n\nfunction configureBins(scale, _, count) {\n let bins = _.bins;\n\n if (bins && !isArray(bins)) {\n // generate bin boundary array\n const domain = scale.domain(),\n lo = domain[0],\n hi = peek(domain),\n step = bins.step;\n let start = bins.start == null ? lo : bins.start,\n stop = bins.stop == null ? hi : bins.stop;\n if (!step) error('Scale bins parameter missing step property.');\n if (start < lo) start = step * Math.ceil(lo / step);\n if (stop > hi) stop = step * Math.floor(hi / step);\n bins = range(start, stop + step / 2, step);\n }\n\n if (bins) {\n // assign bin boundaries to scale instance\n scale.bins = bins;\n } else if (scale.bins) {\n // no current bins, remove bins if previously set\n delete scale.bins;\n } // special handling for bin-ordinal scales\n\n\n if (scale.type === BinOrdinal) {\n if (!bins) {\n // the domain specifies the bins\n scale.bins = scale.domain();\n } else if (!_.domain && !_.domainRaw) {\n // the bins specify the domain\n scale.domain(bins);\n count = bins.length;\n }\n } // return domain cardinality\n\n\n return count;\n}\n\nfunction configureRange(scale, _, count) {\n var type = scale.type,\n round = _.round || false,\n range = _.range; // if range step specified, calculate full range extent\n\n if (_.rangeStep != null) {\n range = configureRangeStep(type, _, count);\n } // else if a range scheme is defined, use that\n else if (_.scheme) {\n range = configureScheme(type, _, count);\n\n if (isFunction(range)) {\n if (scale.interpolator) {\n return scale.interpolator(range);\n } else {\n error(\"Scale type \".concat(type, \" does not support interpolating color schemes.\"));\n }\n }\n } // given a range array for an interpolating scale, convert to interpolator\n\n\n if (range && isInterpolating(type)) {\n return scale.interpolator(interpolateColors(flip(range, _.reverse), _.interpolate, _.interpolateGamma));\n } // configure rounding / interpolation\n\n\n if (range && _.interpolate && scale.interpolate) {\n scale.interpolate(interpolate(_.interpolate, _.interpolateGamma));\n } else if (isFunction(scale.round)) {\n scale.round(round);\n } else if (isFunction(scale.rangeRound)) {\n scale.interpolate(round ? interpolateRound : interpolate$1);\n }\n\n if (range) scale.range(flip(range, _.reverse));\n}\n\nfunction configureRangeStep(type, _, count) {\n if (type !== Band && type !== Point) {\n error('Only band and point scales support rangeStep.');\n } // calculate full range based on requested step size and padding\n\n\n var outer = (_.paddingOuter != null ? _.paddingOuter : _.padding) || 0,\n inner = type === Point ? 1 : (_.paddingInner != null ? _.paddingInner : _.padding) || 0;\n return [0, _.rangeStep * bandSpace(count, inner, outer)];\n}\n\nfunction configureScheme(type, _, count) {\n var extent = _.schemeExtent,\n name,\n scheme$1;\n\n if (isArray(_.scheme)) {\n scheme$1 = interpolateColors(_.scheme, _.interpolate, _.interpolateGamma);\n } else {\n name = _.scheme.toLowerCase();\n scheme$1 = scheme(name);\n if (!scheme$1) error(\"Unrecognized scheme name: \".concat(_.scheme));\n } // determine size for potential discrete range\n\n\n count = type === Threshold ? count + 1 : type === BinOrdinal ? count - 1 : type === Quantile || type === Quantize ? +_.schemeCount || DEFAULT_COUNT : count; // adjust and/or quantize scheme as appropriate\n\n return isInterpolating(type) ? adjustScheme(scheme$1, extent, _.reverse) : isFunction(scheme$1) ? quantizeInterpolator(adjustScheme(scheme$1, extent), count) : type === Ordinal ? scheme$1 : scheme$1.slice(0, count);\n}\n\nfunction adjustScheme(scheme, extent, reverse) {\n return isFunction(scheme) && (extent || reverse) ? interpolateRange(scheme, flip(extent || [0, 1], reverse)) : scheme;\n}\n\nfunction flip(array, reverse) {\n return reverse ? array.slice().reverse() : array;\n}\n\n/**\n * Sorts scenegraph items in the pulse source array.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(*,*): number} [params.sort] - A comparator\n * function for sorting tuples.\n */\n\nfunction SortItems(params) {\n Transform.call(this, null, params);\n}\ninherits(SortItems, Transform, {\n transform(_, pulse) {\n const mod = _.modified('sort') || pulse.changed(pulse.ADD) || pulse.modified(_.sort.fields) || pulse.modified('datum');\n if (mod) pulse.source.sort(stableCompare(_.sort));\n this.modified(mod);\n return pulse;\n }\n\n});\n\nconst Zero = 'zero',\n Center = 'center',\n Normalize = 'normalize',\n DefOutput = ['y0', 'y1'];\n/**\n * Stack layout for visualization elements.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The value field to stack.\n * @param {Array} [params.groupby] - An array of accessors to groupby.\n * @param {function(object,object): number} [params.sort] - A comparator for stack sorting.\n * @param {string} [offset='zero'] - Stack baseline offset. One of 'zero', 'center', 'normalize'.\n */\n\nfunction Stack(params) {\n Transform.call(this, null, params);\n}\nStack.Definition = {\n 'type': 'Stack',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field'\n }, {\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'sort',\n 'type': 'compare'\n }, {\n 'name': 'offset',\n 'type': 'enum',\n 'default': Zero,\n 'values': [Zero, Center, Normalize]\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': 2,\n 'default': DefOutput\n }]\n};\ninherits(Stack, Transform, {\n transform(_, pulse) {\n var as = _.as || DefOutput,\n y0 = as[0],\n y1 = as[1],\n sort = stableCompare(_.sort),\n field = _.field || one,\n stack = _.offset === Center ? stackCenter : _.offset === Normalize ? stackNormalize : stackZero,\n groups,\n i,\n n,\n max; // partition, sum, and sort the stack groups\n\n groups = partition(pulse.source, _.groupby, sort, field); // compute stack layouts per group\n\n for (i = 0, n = groups.length, max = groups.max; i < n; ++i) {\n stack(groups[i], max, field, y0, y1);\n }\n\n return pulse.reflow(_.modified()).modifies(as);\n }\n\n});\n\nfunction stackCenter(group, max, field, y0, y1) {\n var last = (max - group.sum) / 2,\n m = group.length,\n j = 0,\n t;\n\n for (; j < m; ++j) {\n t = group[j];\n t[y0] = last;\n t[y1] = last += Math.abs(field(t));\n }\n}\n\nfunction stackNormalize(group, max, field, y0, y1) {\n var scale = 1 / group.sum,\n last = 0,\n m = group.length,\n j = 0,\n v = 0,\n t;\n\n for (; j < m; ++j) {\n t = group[j];\n t[y0] = last;\n t[y1] = last = scale * (v += Math.abs(field(t)));\n }\n}\n\nfunction stackZero(group, max, field, y0, y1) {\n var lastPos = 0,\n lastNeg = 0,\n m = group.length,\n j = 0,\n v,\n t;\n\n for (; j < m; ++j) {\n t = group[j];\n v = +field(t);\n\n if (v < 0) {\n t[y0] = lastNeg;\n t[y1] = lastNeg += v;\n } else {\n t[y0] = lastPos;\n t[y1] = lastPos += v;\n }\n }\n}\n\nfunction partition(data, groupby, sort, field) {\n var groups = [],\n get = f => f(t),\n map,\n i,\n n,\n m,\n t,\n k,\n g,\n s,\n max; // partition data points into stack groups\n\n\n if (groupby == null) {\n groups.push(data.slice());\n } else {\n for (map = {}, i = 0, n = data.length; i < n; ++i) {\n t = data[i];\n k = groupby.map(get);\n g = map[k];\n\n if (!g) {\n map[k] = g = [];\n groups.push(g);\n }\n\n g.push(t);\n }\n } // compute sums of groups, sort groups as needed\n\n\n for (k = 0, max = 0, m = groups.length; k < m; ++k) {\n g = groups[k];\n\n for (i = 0, s = 0, n = g.length; i < n; ++i) {\n s += Math.abs(field(g[i]));\n }\n\n g.sum = s;\n if (s > max) max = s;\n if (sort) g.sort(sort);\n }\n\n groups.max = max;\n return groups;\n}\n\nexport { AxisTicks as axisticks, DataJoin as datajoin, Encode as encode, LegendEntries as legendentries, LinkPath as linkpath, Pie as pie, Scale as scale, SortItems as sortitems, Stack as stack };\n","export default function sum(values, valueof) {\n let sum = 0;\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n sum += value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n sum += value;\n }\n }\n }\n return sum;\n}\n","var e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nexport default function(start, stop, count) {\n var reverse,\n i = -1,\n n,\n ticks,\n step;\n\n stop = +stop, start = +start, count = +count;\n if (start === stop && count > 0) return [start];\n if (reverse = stop < start) n = start, start = stop, stop = n;\n if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];\n\n if (step > 0) {\n let r0 = Math.round(start / step), r1 = Math.round(stop / step);\n if (r0 * step < start) ++r0;\n if (r1 * step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) * step;\n } else {\n step = -step;\n let r0 = Math.round(start * step), r1 = Math.round(stop * step);\n if (r0 / step < start) ++r0;\n if (r1 / step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) / step;\n }\n\n if (reverse) ticks.reverse();\n\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n var step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log(step) / Math.LN10),\n error = step / Math.pow(10, power);\n return power >= 0\n ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)\n : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);\n}\n\nexport function tickStep(start, stop, count) {\n var step0 = Math.abs(stop - start) / Math.max(0, count),\n step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),\n error = step0 / step1;\n if (error >= e10) step1 *= 10;\n else if (error >= e5) step1 *= 5;\n else if (error >= e2) step1 *= 2;\n return stop < start ? -step1 : step1;\n}\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","export default function max(values, valueof) {\n let max;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n }\n return max;\n}\n","export default x => x;\n","function streamGeometry(geometry, stream) {\n if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {\n streamGeometryType[geometry.type](geometry, stream);\n }\n}\n\nvar streamObjectType = {\n Feature: function(object, stream) {\n streamGeometry(object.geometry, stream);\n },\n FeatureCollection: function(object, stream) {\n var features = object.features, i = -1, n = features.length;\n while (++i < n) streamGeometry(features[i].geometry, stream);\n }\n};\n\nvar streamGeometryType = {\n Sphere: function(object, stream) {\n stream.sphere();\n },\n Point: function(object, stream) {\n object = object.coordinates;\n stream.point(object[0], object[1], object[2]);\n },\n MultiPoint: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);\n },\n LineString: function(object, stream) {\n streamLine(object.coordinates, stream, 0);\n },\n MultiLineString: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamLine(coordinates[i], stream, 0);\n },\n Polygon: function(object, stream) {\n streamPolygon(object.coordinates, stream);\n },\n MultiPolygon: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamPolygon(coordinates[i], stream);\n },\n GeometryCollection: function(object, stream) {\n var geometries = object.geometries, i = -1, n = geometries.length;\n while (++i < n) streamGeometry(geometries[i], stream);\n }\n};\n\nfunction streamLine(coordinates, stream, closed) {\n var i = -1, n = coordinates.length - closed, coordinate;\n stream.lineStart();\n while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);\n stream.lineEnd();\n}\n\nfunction streamPolygon(coordinates, stream) {\n var i = -1, n = coordinates.length;\n stream.polygonStart();\n while (++i < n) streamLine(coordinates[i], stream, 1);\n stream.polygonEnd();\n}\n\nexport default function(object, stream) {\n if (object && streamObjectType.hasOwnProperty(object.type)) {\n streamObjectType[object.type](object, stream);\n } else {\n streamGeometry(object, stream);\n }\n}\n","// https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423\nexport class Adder {\n constructor() {\n this._partials = new Float64Array(32);\n this._n = 0;\n }\n add(x) {\n const p = this._partials;\n let i = 0;\n for (let j = 0; j < this._n && j < 32; j++) {\n const y = p[j],\n hi = x + y,\n lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);\n if (lo) p[i++] = lo;\n x = hi;\n }\n p[i] = x;\n this._n = i + 1;\n return this;\n }\n valueOf() {\n const p = this._partials;\n let n = this._n, x, y, lo, hi = 0;\n if (n > 0) {\n hi = p[--n];\n while (n > 0) {\n x = hi;\n y = p[--n];\n hi = x + y;\n lo = y - (hi - x);\n if (lo) break;\n }\n if (n > 0 && ((lo < 0 && p[n - 1] < 0) || (lo > 0 && p[n - 1] > 0))) {\n y = lo * 2;\n x = hi + y;\n if (y == x - hi) hi = x;\n }\n }\n return hi;\n }\n}\n\nexport function fsum(values, valueof) {\n const adder = new Adder();\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n adder.add(value);\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n adder.add(value);\n }\n }\n }\n return +adder;\n}\n\nexport function fcumsum(values, valueof) {\n const adder = new Adder();\n let index = -1;\n return Float64Array.from(values, valueof === undefined\n ? v => adder.add(+v || 0)\n : v => adder.add(+valueof(v, ++index, values) || 0)\n );\n}\n","export var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var quarterPi = pi / 4;\nexport var tau = pi * 2;\n\nexport var degrees = 180 / pi;\nexport var radians = pi / 180;\n\nexport var abs = Math.abs;\nexport var atan = Math.atan;\nexport var atan2 = Math.atan2;\nexport var cos = Math.cos;\nexport var ceil = Math.ceil;\nexport var exp = Math.exp;\nexport var floor = Math.floor;\nexport var hypot = Math.hypot;\nexport var log = Math.log;\nexport var pow = Math.pow;\nexport var sin = Math.sin;\nexport var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };\nexport var sqrt = Math.sqrt;\nexport var tan = Math.tan;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);\n}\n\nexport function haversin(x) {\n return (x = sin(x / 2)) * x;\n}\n","export default function noop() {}\n","import {Adder} from \"d3-array\";\nimport {abs} from \"../math.js\";\nimport noop from \"../noop.js\";\n\nvar areaSum = new Adder(),\n areaRingSum = new Adder(),\n x00,\n y00,\n x0,\n y0;\n\nvar areaStream = {\n point: noop,\n lineStart: noop,\n lineEnd: noop,\n polygonStart: function() {\n areaStream.lineStart = areaRingStart;\n areaStream.lineEnd = areaRingEnd;\n },\n polygonEnd: function() {\n areaStream.lineStart = areaStream.lineEnd = areaStream.point = noop;\n areaSum.add(abs(areaRingSum));\n areaRingSum = new Adder();\n },\n result: function() {\n var area = areaSum / 2;\n areaSum = new Adder();\n return area;\n }\n};\n\nfunction areaRingStart() {\n areaStream.point = areaPointFirst;\n}\n\nfunction areaPointFirst(x, y) {\n areaStream.point = areaPoint;\n x00 = x0 = x, y00 = y0 = y;\n}\n\nfunction areaPoint(x, y) {\n areaRingSum.add(y0 * x - x0 * y);\n x0 = x, y0 = y;\n}\n\nfunction areaRingEnd() {\n areaPoint(x00, y00);\n}\n\nexport default areaStream;\n","import noop from \"../noop.js\";\n\nvar x0 = Infinity,\n y0 = x0,\n x1 = -x0,\n y1 = x1;\n\nvar boundsStream = {\n point: boundsPoint,\n lineStart: noop,\n lineEnd: noop,\n polygonStart: noop,\n polygonEnd: noop,\n result: function() {\n var bounds = [[x0, y0], [x1, y1]];\n x1 = y1 = -(y0 = x0 = Infinity);\n return bounds;\n }\n};\n\nfunction boundsPoint(x, y) {\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n}\n\nexport default boundsStream;\n","import {sqrt} from \"../math.js\";\n\n// TODO Enforce positive area for exterior, negative area for interior?\n\nvar X0 = 0,\n Y0 = 0,\n Z0 = 0,\n X1 = 0,\n Y1 = 0,\n Z1 = 0,\n X2 = 0,\n Y2 = 0,\n Z2 = 0,\n x00,\n y00,\n x0,\n y0;\n\nvar centroidStream = {\n point: centroidPoint,\n lineStart: centroidLineStart,\n lineEnd: centroidLineEnd,\n polygonStart: function() {\n centroidStream.lineStart = centroidRingStart;\n centroidStream.lineEnd = centroidRingEnd;\n },\n polygonEnd: function() {\n centroidStream.point = centroidPoint;\n centroidStream.lineStart = centroidLineStart;\n centroidStream.lineEnd = centroidLineEnd;\n },\n result: function() {\n var centroid = Z2 ? [X2 / Z2, Y2 / Z2]\n : Z1 ? [X1 / Z1, Y1 / Z1]\n : Z0 ? [X0 / Z0, Y0 / Z0]\n : [NaN, NaN];\n X0 = Y0 = Z0 =\n X1 = Y1 = Z1 =\n X2 = Y2 = Z2 = 0;\n return centroid;\n }\n};\n\nfunction centroidPoint(x, y) {\n X0 += x;\n Y0 += y;\n ++Z0;\n}\n\nfunction centroidLineStart() {\n centroidStream.point = centroidPointFirstLine;\n}\n\nfunction centroidPointFirstLine(x, y) {\n centroidStream.point = centroidPointLine;\n centroidPoint(x0 = x, y0 = y);\n}\n\nfunction centroidPointLine(x, y) {\n var dx = x - x0, dy = y - y0, z = sqrt(dx * dx + dy * dy);\n X1 += z * (x0 + x) / 2;\n Y1 += z * (y0 + y) / 2;\n Z1 += z;\n centroidPoint(x0 = x, y0 = y);\n}\n\nfunction centroidLineEnd() {\n centroidStream.point = centroidPoint;\n}\n\nfunction centroidRingStart() {\n centroidStream.point = centroidPointFirstRing;\n}\n\nfunction centroidRingEnd() {\n centroidPointRing(x00, y00);\n}\n\nfunction centroidPointFirstRing(x, y) {\n centroidStream.point = centroidPointRing;\n centroidPoint(x00 = x0 = x, y00 = y0 = y);\n}\n\nfunction centroidPointRing(x, y) {\n var dx = x - x0,\n dy = y - y0,\n z = sqrt(dx * dx + dy * dy);\n\n X1 += z * (x0 + x) / 2;\n Y1 += z * (y0 + y) / 2;\n Z1 += z;\n\n z = y0 * x - x0 * y;\n X2 += z * (x0 + x);\n Y2 += z * (y0 + y);\n Z2 += z * 3;\n centroidPoint(x0 = x, y0 = y);\n}\n\nexport default centroidStream;\n","import {tau} from \"../math.js\";\nimport noop from \"../noop.js\";\n\nexport default function PathContext(context) {\n this._context = context;\n}\n\nPathContext.prototype = {\n _radius: 4.5,\n pointRadius: function(_) {\n return this._radius = _, this;\n },\n polygonStart: function() {\n this._line = 0;\n },\n polygonEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line === 0) this._context.closePath();\n this._point = NaN;\n },\n point: function(x, y) {\n switch (this._point) {\n case 0: {\n this._context.moveTo(x, y);\n this._point = 1;\n break;\n }\n case 1: {\n this._context.lineTo(x, y);\n break;\n }\n default: {\n this._context.moveTo(x + this._radius, y);\n this._context.arc(x, y, this._radius, 0, tau);\n break;\n }\n }\n },\n result: noop\n};\n","import {Adder} from \"d3-array\";\nimport {sqrt} from \"../math.js\";\nimport noop from \"../noop.js\";\n\nvar lengthSum = new Adder(),\n lengthRing,\n x00,\n y00,\n x0,\n y0;\n\nvar lengthStream = {\n point: noop,\n lineStart: function() {\n lengthStream.point = lengthPointFirst;\n },\n lineEnd: function() {\n if (lengthRing) lengthPoint(x00, y00);\n lengthStream.point = noop;\n },\n polygonStart: function() {\n lengthRing = true;\n },\n polygonEnd: function() {\n lengthRing = null;\n },\n result: function() {\n var length = +lengthSum;\n lengthSum = new Adder();\n return length;\n }\n};\n\nfunction lengthPointFirst(x, y) {\n lengthStream.point = lengthPoint;\n x00 = x0 = x, y00 = y0 = y;\n}\n\nfunction lengthPoint(x, y) {\n x0 -= x, y0 -= y;\n lengthSum.add(sqrt(x0 * x0 + y0 * y0));\n x0 = x, y0 = y;\n}\n\nexport default lengthStream;\n","export default function PathString() {\n this._string = [];\n}\n\nPathString.prototype = {\n _radius: 4.5,\n _circle: circle(4.5),\n pointRadius: function(_) {\n if ((_ = +_) !== this._radius) this._radius = _, this._circle = null;\n return this;\n },\n polygonStart: function() {\n this._line = 0;\n },\n polygonEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line === 0) this._string.push(\"Z\");\n this._point = NaN;\n },\n point: function(x, y) {\n switch (this._point) {\n case 0: {\n this._string.push(\"M\", x, \",\", y);\n this._point = 1;\n break;\n }\n case 1: {\n this._string.push(\"L\", x, \",\", y);\n break;\n }\n default: {\n if (this._circle == null) this._circle = circle(this._radius);\n this._string.push(\"M\", x, \",\", y, this._circle);\n break;\n }\n }\n },\n result: function() {\n if (this._string.length) {\n var result = this._string.join(\"\");\n this._string = [];\n return result;\n } else {\n return null;\n }\n }\n};\n\nfunction circle(radius) {\n return \"m0,\" + radius\n + \"a\" + radius + \",\" + radius + \" 0 1,1 0,\" + -2 * radius\n + \"a\" + radius + \",\" + radius + \" 0 1,1 0,\" + 2 * radius\n + \"z\";\n}\n","import identity from \"../identity.js\";\nimport stream from \"../stream.js\";\nimport pathArea from \"./area.js\";\nimport pathBounds from \"./bounds.js\";\nimport pathCentroid from \"./centroid.js\";\nimport PathContext from \"./context.js\";\nimport pathMeasure from \"./measure.js\";\nimport PathString from \"./string.js\";\n\nexport default function(projection, context) {\n var pointRadius = 4.5,\n projectionStream,\n contextStream;\n\n function path(object) {\n if (object) {\n if (typeof pointRadius === \"function\") contextStream.pointRadius(+pointRadius.apply(this, arguments));\n stream(object, projectionStream(contextStream));\n }\n return contextStream.result();\n }\n\n path.area = function(object) {\n stream(object, projectionStream(pathArea));\n return pathArea.result();\n };\n\n path.measure = function(object) {\n stream(object, projectionStream(pathMeasure));\n return pathMeasure.result();\n };\n\n path.bounds = function(object) {\n stream(object, projectionStream(pathBounds));\n return pathBounds.result();\n };\n\n path.centroid = function(object) {\n stream(object, projectionStream(pathCentroid));\n return pathCentroid.result();\n };\n\n path.projection = function(_) {\n return arguments.length ? (projectionStream = _ == null ? (projection = null, identity) : (projection = _).stream, path) : projection;\n };\n\n path.context = function(_) {\n if (!arguments.length) return context;\n contextStream = _ == null ? (context = null, new PathString) : new PathContext(context = _);\n if (typeof pointRadius !== \"function\") contextStream.pointRadius(pointRadius);\n return path;\n };\n\n path.pointRadius = function(_) {\n if (!arguments.length) return pointRadius;\n pointRadius = typeof _ === \"function\" ? _ : (contextStream.pointRadius(+_), +_);\n return path;\n };\n\n return path.projection(projection).context(context);\n}\n","import noop from \"../noop.js\";\n\nexport default function() {\n var lines = [],\n line;\n return {\n point: function(x, y, m) {\n line.push([x, y, m]);\n },\n lineStart: function() {\n lines.push(line = []);\n },\n lineEnd: noop,\n rejoin: function() {\n if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));\n },\n result: function() {\n var result = lines;\n lines = [];\n line = null;\n return result;\n }\n };\n}\n","import {abs, epsilon} from \"./math.js\";\n\nexport default function(a, b) {\n return abs(a[0] - b[0]) < epsilon && abs(a[1] - b[1]) < epsilon;\n}\n","import pointEqual from \"../pointEqual.js\";\nimport {epsilon} from \"../math.js\";\n\nfunction Intersection(point, points, other, entry) {\n this.x = point;\n this.z = points;\n this.o = other; // another intersection\n this.e = entry; // is an entry?\n this.v = false; // visited\n this.n = this.p = null; // next & previous\n}\n\n// A generalized polygon clipping algorithm: given a polygon that has been cut\n// into its visible line segments, and rejoins the segments by interpolating\n// along the clip edge.\nexport default function(segments, compareIntersection, startInside, interpolate, stream) {\n var subject = [],\n clip = [],\n i,\n n;\n\n segments.forEach(function(segment) {\n if ((n = segment.length - 1) <= 0) return;\n var n, p0 = segment[0], p1 = segment[n], x;\n\n if (pointEqual(p0, p1)) {\n if (!p0[2] && !p1[2]) {\n stream.lineStart();\n for (i = 0; i < n; ++i) stream.point((p0 = segment[i])[0], p0[1]);\n stream.lineEnd();\n return;\n }\n // handle degenerate cases by moving the point\n p1[0] += 2 * epsilon;\n }\n\n subject.push(x = new Intersection(p0, segment, null, true));\n clip.push(x.o = new Intersection(p0, null, x, false));\n subject.push(x = new Intersection(p1, segment, null, false));\n clip.push(x.o = new Intersection(p1, null, x, true));\n });\n\n if (!subject.length) return;\n\n clip.sort(compareIntersection);\n link(subject);\n link(clip);\n\n for (i = 0, n = clip.length; i < n; ++i) {\n clip[i].e = startInside = !startInside;\n }\n\n var start = subject[0],\n points,\n point;\n\n while (1) {\n // Find first unvisited intersection.\n var current = start,\n isSubject = true;\n while (current.v) if ((current = current.n) === start) return;\n points = current.z;\n stream.lineStart();\n do {\n current.v = current.o.v = true;\n if (current.e) {\n if (isSubject) {\n for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]);\n } else {\n interpolate(current.x, current.n.x, 1, stream);\n }\n current = current.n;\n } else {\n if (isSubject) {\n points = current.p.z;\n for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]);\n } else {\n interpolate(current.x, current.p.x, -1, stream);\n }\n current = current.p;\n }\n current = current.o;\n points = current.z;\n isSubject = !isSubject;\n } while (!current.v);\n stream.lineEnd();\n }\n}\n\nfunction link(array) {\n if (!(n = array.length)) return;\n var n,\n i = 0,\n a = array[0],\n b;\n while (++i < n) {\n a.n = b = array[i];\n b.p = a;\n a = b;\n }\n a.n = b = array[0];\n b.p = a;\n}\n","import {asin, atan2, cos, sin, sqrt} from \"./math.js\";\n\nexport function spherical(cartesian) {\n return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];\n}\n\nexport function cartesian(spherical) {\n var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi);\n return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];\n}\n\nexport function cartesianDot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\nexport function cartesianCross(a, b) {\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\n}\n\n// TODO return a\nexport function cartesianAddInPlace(a, b) {\n a[0] += b[0], a[1] += b[1], a[2] += b[2];\n}\n\nexport function cartesianScale(vector, k) {\n return [vector[0] * k, vector[1] * k, vector[2] * k];\n}\n\n// TODO return d\nexport function cartesianNormalizeInPlace(d) {\n var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);\n d[0] /= l, d[1] /= l, d[2] /= l;\n}\n","import {Adder} from \"d3-array\";\nimport {cartesian, cartesianCross, cartesianNormalizeInPlace} from \"./cartesian.js\";\nimport {abs, asin, atan2, cos, epsilon, epsilon2, halfPi, pi, quarterPi, sign, sin, tau} from \"./math.js\";\n\nfunction longitude(point) {\n if (abs(point[0]) <= pi)\n return point[0];\n else\n return sign(point[0]) * ((abs(point[0]) + pi) % tau - pi);\n}\n\nexport default function(polygon, point) {\n var lambda = longitude(point),\n phi = point[1],\n sinPhi = sin(phi),\n normal = [sin(lambda), -cos(lambda), 0],\n angle = 0,\n winding = 0;\n\n var sum = new Adder();\n\n if (sinPhi === 1) phi = halfPi + epsilon;\n else if (sinPhi === -1) phi = -halfPi - epsilon;\n\n for (var i = 0, n = polygon.length; i < n; ++i) {\n if (!(m = (ring = polygon[i]).length)) continue;\n var ring,\n m,\n point0 = ring[m - 1],\n lambda0 = longitude(point0),\n phi0 = point0[1] / 2 + quarterPi,\n sinPhi0 = sin(phi0),\n cosPhi0 = cos(phi0);\n\n for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) {\n var point1 = ring[j],\n lambda1 = longitude(point1),\n phi1 = point1[1] / 2 + quarterPi,\n sinPhi1 = sin(phi1),\n cosPhi1 = cos(phi1),\n delta = lambda1 - lambda0,\n sign = delta >= 0 ? 1 : -1,\n absDelta = sign * delta,\n antimeridian = absDelta > pi,\n k = sinPhi0 * sinPhi1;\n\n sum.add(atan2(k * sign * sin(absDelta), cosPhi0 * cosPhi1 + k * cos(absDelta)));\n angle += antimeridian ? delta + sign * tau : delta;\n\n // Are the longitudes either side of the point’s meridian (lambda),\n // and are the latitudes smaller than the parallel (phi)?\n if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {\n var arc = cartesianCross(cartesian(point0), cartesian(point1));\n cartesianNormalizeInPlace(arc);\n var intersection = cartesianCross(normal, arc);\n cartesianNormalizeInPlace(intersection);\n var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]);\n if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {\n winding += antimeridian ^ delta >= 0 ? 1 : -1;\n }\n }\n }\n }\n\n // First, determine whether the South pole is inside or outside:\n //\n // It is inside if:\n // * the polygon winds around it in a clockwise direction.\n // * the polygon does not (cumulatively) wind around it, but has a negative\n // (counter-clockwise) area.\n //\n // Second, count the (signed) number of times a segment crosses a lambda\n // from the point to the South pole. If it is zero, then the point is the\n // same side as the South pole.\n\n return (angle < -epsilon || angle < epsilon && sum < -epsilon2) ^ (winding & 1);\n}\n","function* flatten(arrays) {\n for (const array of arrays) {\n yield* array;\n }\n}\n\nexport default function merge(arrays) {\n return Array.from(flatten(arrays));\n}\n","import clipBuffer from \"./buffer.js\";\nimport clipRejoin from \"./rejoin.js\";\nimport {epsilon, halfPi} from \"../math.js\";\nimport polygonContains from \"../polygonContains.js\";\nimport {merge} from \"d3-array\";\n\nexport default function(pointVisible, clipLine, interpolate, start) {\n return function(sink) {\n var line = clipLine(sink),\n ringBuffer = clipBuffer(),\n ringSink = clipLine(ringBuffer),\n polygonStarted = false,\n polygon,\n segments,\n ring;\n\n var clip = {\n point: point,\n lineStart: lineStart,\n lineEnd: lineEnd,\n polygonStart: function() {\n clip.point = pointRing;\n clip.lineStart = ringStart;\n clip.lineEnd = ringEnd;\n segments = [];\n polygon = [];\n },\n polygonEnd: function() {\n clip.point = point;\n clip.lineStart = lineStart;\n clip.lineEnd = lineEnd;\n segments = merge(segments);\n var startInside = polygonContains(polygon, start);\n if (segments.length) {\n if (!polygonStarted) sink.polygonStart(), polygonStarted = true;\n clipRejoin(segments, compareIntersection, startInside, interpolate, sink);\n } else if (startInside) {\n if (!polygonStarted) sink.polygonStart(), polygonStarted = true;\n sink.lineStart();\n interpolate(null, null, 1, sink);\n sink.lineEnd();\n }\n if (polygonStarted) sink.polygonEnd(), polygonStarted = false;\n segments = polygon = null;\n },\n sphere: function() {\n sink.polygonStart();\n sink.lineStart();\n interpolate(null, null, 1, sink);\n sink.lineEnd();\n sink.polygonEnd();\n }\n };\n\n function point(lambda, phi) {\n if (pointVisible(lambda, phi)) sink.point(lambda, phi);\n }\n\n function pointLine(lambda, phi) {\n line.point(lambda, phi);\n }\n\n function lineStart() {\n clip.point = pointLine;\n line.lineStart();\n }\n\n function lineEnd() {\n clip.point = point;\n line.lineEnd();\n }\n\n function pointRing(lambda, phi) {\n ring.push([lambda, phi]);\n ringSink.point(lambda, phi);\n }\n\n function ringStart() {\n ringSink.lineStart();\n ring = [];\n }\n\n function ringEnd() {\n pointRing(ring[0][0], ring[0][1]);\n ringSink.lineEnd();\n\n var clean = ringSink.clean(),\n ringSegments = ringBuffer.result(),\n i, n = ringSegments.length, m,\n segment,\n point;\n\n ring.pop();\n polygon.push(ring);\n ring = null;\n\n if (!n) return;\n\n // No intersections.\n if (clean & 1) {\n segment = ringSegments[0];\n if ((m = segment.length - 1) > 0) {\n if (!polygonStarted) sink.polygonStart(), polygonStarted = true;\n sink.lineStart();\n for (i = 0; i < m; ++i) sink.point((point = segment[i])[0], point[1]);\n sink.lineEnd();\n }\n return;\n }\n\n // Rejoin connected segments.\n // TODO reuse ringBuffer.rejoin()?\n if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));\n\n segments.push(ringSegments.filter(validSegment));\n }\n\n return clip;\n };\n}\n\nfunction validSegment(segment) {\n return segment.length > 1;\n}\n\n// Intersections are sorted along the clip edge. For both antimeridian cutting\n// and circle clipping, the same comparison is used.\nfunction compareIntersection(a, b) {\n return ((a = a.x)[0] < 0 ? a[1] - halfPi - epsilon : halfPi - a[1])\n - ((b = b.x)[0] < 0 ? b[1] - halfPi - epsilon : halfPi - b[1]);\n}\n","import clip from \"./index.js\";\nimport {abs, atan, cos, epsilon, halfPi, pi, sin} from \"../math.js\";\n\nexport default clip(\n function() { return true; },\n clipAntimeridianLine,\n clipAntimeridianInterpolate,\n [-pi, -halfPi]\n);\n\n// Takes a line and cuts into visible segments. Return values: 0 - there were\n// intersections or the line was empty; 1 - no intersections; 2 - there were\n// intersections, and the first and last segments should be rejoined.\nfunction clipAntimeridianLine(stream) {\n var lambda0 = NaN,\n phi0 = NaN,\n sign0 = NaN,\n clean; // no intersections\n\n return {\n lineStart: function() {\n stream.lineStart();\n clean = 1;\n },\n point: function(lambda1, phi1) {\n var sign1 = lambda1 > 0 ? pi : -pi,\n delta = abs(lambda1 - lambda0);\n if (abs(delta - pi) < epsilon) { // line crosses a pole\n stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? halfPi : -halfPi);\n stream.point(sign0, phi0);\n stream.lineEnd();\n stream.lineStart();\n stream.point(sign1, phi0);\n stream.point(lambda1, phi0);\n clean = 0;\n } else if (sign0 !== sign1 && delta >= pi) { // line crosses antimeridian\n if (abs(lambda0 - sign0) < epsilon) lambda0 -= sign0 * epsilon; // handle degeneracies\n if (abs(lambda1 - sign1) < epsilon) lambda1 -= sign1 * epsilon;\n phi0 = clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1);\n stream.point(sign0, phi0);\n stream.lineEnd();\n stream.lineStart();\n stream.point(sign1, phi0);\n clean = 0;\n }\n stream.point(lambda0 = lambda1, phi0 = phi1);\n sign0 = sign1;\n },\n lineEnd: function() {\n stream.lineEnd();\n lambda0 = phi0 = NaN;\n },\n clean: function() {\n return 2 - clean; // if intersections, rejoin first and last segments\n }\n };\n}\n\nfunction clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) {\n var cosPhi0,\n cosPhi1,\n sinLambda0Lambda1 = sin(lambda0 - lambda1);\n return abs(sinLambda0Lambda1) > epsilon\n ? atan((sin(phi0) * (cosPhi1 = cos(phi1)) * sin(lambda1)\n - sin(phi1) * (cosPhi0 = cos(phi0)) * sin(lambda0))\n / (cosPhi0 * cosPhi1 * sinLambda0Lambda1))\n : (phi0 + phi1) / 2;\n}\n\nfunction clipAntimeridianInterpolate(from, to, direction, stream) {\n var phi;\n if (from == null) {\n phi = direction * halfPi;\n stream.point(-pi, phi);\n stream.point(0, phi);\n stream.point(pi, phi);\n stream.point(pi, 0);\n stream.point(pi, -phi);\n stream.point(0, -phi);\n stream.point(-pi, -phi);\n stream.point(-pi, 0);\n stream.point(-pi, phi);\n } else if (abs(from[0] - to[0]) > epsilon) {\n var lambda = from[0] < to[0] ? pi : -pi;\n phi = direction * lambda / 2;\n stream.point(-lambda, phi);\n stream.point(0, phi);\n stream.point(lambda, phi);\n } else {\n stream.point(to[0], to[1]);\n }\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","export default function(a, b) {\n\n function compose(x, y) {\n return x = a(x, y), b(x[0], x[1]);\n }\n\n if (a.invert && b.invert) compose.invert = function(x, y) {\n return x = b.invert(x, y), x && a.invert(x[0], x[1]);\n };\n\n return compose;\n}\n","import compose from \"./compose.js\";\nimport {abs, asin, atan2, cos, degrees, pi, radians, sin, tau} from \"./math.js\";\n\nfunction rotationIdentity(lambda, phi) {\n return [abs(lambda) > pi ? lambda + Math.round(-lambda / tau) * tau : lambda, phi];\n}\n\nrotationIdentity.invert = rotationIdentity;\n\nexport function rotateRadians(deltaLambda, deltaPhi, deltaGamma) {\n return (deltaLambda %= tau) ? (deltaPhi || deltaGamma ? compose(rotationLambda(deltaLambda), rotationPhiGamma(deltaPhi, deltaGamma))\n : rotationLambda(deltaLambda))\n : (deltaPhi || deltaGamma ? rotationPhiGamma(deltaPhi, deltaGamma)\n : rotationIdentity);\n}\n\nfunction forwardRotationLambda(deltaLambda) {\n return function(lambda, phi) {\n return lambda += deltaLambda, [lambda > pi ? lambda - tau : lambda < -pi ? lambda + tau : lambda, phi];\n };\n}\n\nfunction rotationLambda(deltaLambda) {\n var rotation = forwardRotationLambda(deltaLambda);\n rotation.invert = forwardRotationLambda(-deltaLambda);\n return rotation;\n}\n\nfunction rotationPhiGamma(deltaPhi, deltaGamma) {\n var cosDeltaPhi = cos(deltaPhi),\n sinDeltaPhi = sin(deltaPhi),\n cosDeltaGamma = cos(deltaGamma),\n sinDeltaGamma = sin(deltaGamma);\n\n function rotation(lambda, phi) {\n var cosPhi = cos(phi),\n x = cos(lambda) * cosPhi,\n y = sin(lambda) * cosPhi,\n z = sin(phi),\n k = z * cosDeltaPhi + x * sinDeltaPhi;\n return [\n atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi),\n asin(k * cosDeltaGamma + y * sinDeltaGamma)\n ];\n }\n\n rotation.invert = function(lambda, phi) {\n var cosPhi = cos(phi),\n x = cos(lambda) * cosPhi,\n y = sin(lambda) * cosPhi,\n z = sin(phi),\n k = z * cosDeltaGamma - y * sinDeltaGamma;\n return [\n atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi),\n asin(k * cosDeltaPhi - x * sinDeltaPhi)\n ];\n };\n\n return rotation;\n}\n\nexport default function(rotate) {\n rotate = rotateRadians(rotate[0] * radians, rotate[1] * radians, rotate.length > 2 ? rotate[2] * radians : 0);\n\n function forward(coordinates) {\n coordinates = rotate(coordinates[0] * radians, coordinates[1] * radians);\n return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;\n }\n\n forward.invert = function(coordinates) {\n coordinates = rotate.invert(coordinates[0] * radians, coordinates[1] * radians);\n return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;\n };\n\n return forward;\n}\n","import {cartesian, cartesianNormalizeInPlace, spherical} from \"./cartesian.js\";\nimport constant from \"./constant.js\";\nimport {acos, cos, degrees, epsilon, radians, sin, tau} from \"./math.js\";\nimport {rotateRadians} from \"./rotation.js\";\n\n// Generates a circle centered at [0°, 0°], with a given radius and precision.\nexport function circleStream(stream, radius, delta, direction, t0, t1) {\n if (!delta) return;\n var cosRadius = cos(radius),\n sinRadius = sin(radius),\n step = direction * delta;\n if (t0 == null) {\n t0 = radius + direction * tau;\n t1 = radius - step / 2;\n } else {\n t0 = circleRadius(cosRadius, t0);\n t1 = circleRadius(cosRadius, t1);\n if (direction > 0 ? t0 < t1 : t0 > t1) t0 += direction * tau;\n }\n for (var point, t = t0; direction > 0 ? t > t1 : t < t1; t -= step) {\n point = spherical([cosRadius, -sinRadius * cos(t), -sinRadius * sin(t)]);\n stream.point(point[0], point[1]);\n }\n}\n\n// Returns the signed angle of a cartesian point relative to [cosRadius, 0, 0].\nfunction circleRadius(cosRadius, point) {\n point = cartesian(point), point[0] -= cosRadius;\n cartesianNormalizeInPlace(point);\n var radius = acos(-point[1]);\n return ((-point[2] < 0 ? -radius : radius) + tau - epsilon) % tau;\n}\n\nexport default function() {\n var center = constant([0, 0]),\n radius = constant(90),\n precision = constant(6),\n ring,\n rotate,\n stream = {point: point};\n\n function point(x, y) {\n ring.push(x = rotate(x, y));\n x[0] *= degrees, x[1] *= degrees;\n }\n\n function circle() {\n var c = center.apply(this, arguments),\n r = radius.apply(this, arguments) * radians,\n p = precision.apply(this, arguments) * radians;\n ring = [];\n rotate = rotateRadians(-c[0] * radians, -c[1] * radians, 0).invert;\n circleStream(stream, r, p, 1);\n c = {type: \"Polygon\", coordinates: [ring]};\n ring = rotate = null;\n return c;\n }\n\n circle.center = function(_) {\n return arguments.length ? (center = typeof _ === \"function\" ? _ : constant([+_[0], +_[1]]), circle) : center;\n };\n\n circle.radius = function(_) {\n return arguments.length ? (radius = typeof _ === \"function\" ? _ : constant(+_), circle) : radius;\n };\n\n circle.precision = function(_) {\n return arguments.length ? (precision = typeof _ === \"function\" ? _ : constant(+_), circle) : precision;\n };\n\n return circle;\n}\n","import {cartesian, cartesianAddInPlace, cartesianCross, cartesianDot, cartesianScale, spherical} from \"../cartesian.js\";\nimport {circleStream} from \"../circle.js\";\nimport {abs, cos, epsilon, pi, radians, sqrt} from \"../math.js\";\nimport pointEqual from \"../pointEqual.js\";\nimport clip from \"./index.js\";\n\nexport default function(radius) {\n var cr = cos(radius),\n delta = 6 * radians,\n smallRadius = cr > 0,\n notHemisphere = abs(cr) > epsilon; // TODO optimise for this common case\n\n function interpolate(from, to, direction, stream) {\n circleStream(stream, radius, delta, direction, from, to);\n }\n\n function visible(lambda, phi) {\n return cos(lambda) * cos(phi) > cr;\n }\n\n // Takes a line and cuts into visible segments. Return values used for polygon\n // clipping: 0 - there were intersections or the line was empty; 1 - no\n // intersections 2 - there were intersections, and the first and last segments\n // should be rejoined.\n function clipLine(stream) {\n var point0, // previous point\n c0, // code for previous point\n v0, // visibility of previous point\n v00, // visibility of first point\n clean; // no intersections\n return {\n lineStart: function() {\n v00 = v0 = false;\n clean = 1;\n },\n point: function(lambda, phi) {\n var point1 = [lambda, phi],\n point2,\n v = visible(lambda, phi),\n c = smallRadius\n ? v ? 0 : code(lambda, phi)\n : v ? code(lambda + (lambda < 0 ? pi : -pi), phi) : 0;\n if (!point0 && (v00 = v0 = v)) stream.lineStart();\n if (v !== v0) {\n point2 = intersect(point0, point1);\n if (!point2 || pointEqual(point0, point2) || pointEqual(point1, point2))\n point1[2] = 1;\n }\n if (v !== v0) {\n clean = 0;\n if (v) {\n // outside going in\n stream.lineStart();\n point2 = intersect(point1, point0);\n stream.point(point2[0], point2[1]);\n } else {\n // inside going out\n point2 = intersect(point0, point1);\n stream.point(point2[0], point2[1], 2);\n stream.lineEnd();\n }\n point0 = point2;\n } else if (notHemisphere && point0 && smallRadius ^ v) {\n var t;\n // If the codes for two points are different, or are both zero,\n // and there this segment intersects with the small circle.\n if (!(c & c0) && (t = intersect(point1, point0, true))) {\n clean = 0;\n if (smallRadius) {\n stream.lineStart();\n stream.point(t[0][0], t[0][1]);\n stream.point(t[1][0], t[1][1]);\n stream.lineEnd();\n } else {\n stream.point(t[1][0], t[1][1]);\n stream.lineEnd();\n stream.lineStart();\n stream.point(t[0][0], t[0][1], 3);\n }\n }\n }\n if (v && (!point0 || !pointEqual(point0, point1))) {\n stream.point(point1[0], point1[1]);\n }\n point0 = point1, v0 = v, c0 = c;\n },\n lineEnd: function() {\n if (v0) stream.lineEnd();\n point0 = null;\n },\n // Rejoin first and last segments if there were intersections and the first\n // and last points were visible.\n clean: function() {\n return clean | ((v00 && v0) << 1);\n }\n };\n }\n\n // Intersects the great circle between a and b with the clip circle.\n function intersect(a, b, two) {\n var pa = cartesian(a),\n pb = cartesian(b);\n\n // We have two planes, n1.p = d1 and n2.p = d2.\n // Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2).\n var n1 = [1, 0, 0], // normal\n n2 = cartesianCross(pa, pb),\n n2n2 = cartesianDot(n2, n2),\n n1n2 = n2[0], // cartesianDot(n1, n2),\n determinant = n2n2 - n1n2 * n1n2;\n\n // Two polar points.\n if (!determinant) return !two && a;\n\n var c1 = cr * n2n2 / determinant,\n c2 = -cr * n1n2 / determinant,\n n1xn2 = cartesianCross(n1, n2),\n A = cartesianScale(n1, c1),\n B = cartesianScale(n2, c2);\n cartesianAddInPlace(A, B);\n\n // Solve |p(t)|^2 = 1.\n var u = n1xn2,\n w = cartesianDot(A, u),\n uu = cartesianDot(u, u),\n t2 = w * w - uu * (cartesianDot(A, A) - 1);\n\n if (t2 < 0) return;\n\n var t = sqrt(t2),\n q = cartesianScale(u, (-w - t) / uu);\n cartesianAddInPlace(q, A);\n q = spherical(q);\n\n if (!two) return q;\n\n // Two intersection points.\n var lambda0 = a[0],\n lambda1 = b[0],\n phi0 = a[1],\n phi1 = b[1],\n z;\n\n if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;\n\n var delta = lambda1 - lambda0,\n polar = abs(delta - pi) < epsilon,\n meridian = polar || delta < epsilon;\n\n if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;\n\n // Check that the first point is between a and b.\n if (meridian\n ? polar\n ? phi0 + phi1 > 0 ^ q[1] < (abs(q[0] - lambda0) < epsilon ? phi0 : phi1)\n : phi0 <= q[1] && q[1] <= phi1\n : delta > pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) {\n var q1 = cartesianScale(u, (-w + t) / uu);\n cartesianAddInPlace(q1, A);\n return [q, spherical(q1)];\n }\n }\n\n // Generates a 4-bit vector representing the location of a point relative to\n // the small circle's bounding box.\n function code(lambda, phi) {\n var r = smallRadius ? radius : pi - radius,\n code = 0;\n if (lambda < -r) code |= 1; // left\n else if (lambda > r) code |= 2; // right\n if (phi < -r) code |= 4; // below\n else if (phi > r) code |= 8; // above\n return code;\n }\n\n return clip(visible, clipLine, interpolate, smallRadius ? [0, -radius] : [-pi, radius - pi]);\n}\n","import {abs, epsilon} from \"../math.js\";\nimport clipBuffer from \"./buffer.js\";\nimport clipLine from \"./line.js\";\nimport clipRejoin from \"./rejoin.js\";\nimport {merge} from \"d3-array\";\n\nvar clipMax = 1e9, clipMin = -clipMax;\n\n// TODO Use d3-polygon’s polygonContains here for the ring check?\n// TODO Eliminate duplicate buffering in clipBuffer and polygon.push?\n\nexport default function clipRectangle(x0, y0, x1, y1) {\n\n function visible(x, y) {\n return x0 <= x && x <= x1 && y0 <= y && y <= y1;\n }\n\n function interpolate(from, to, direction, stream) {\n var a = 0, a1 = 0;\n if (from == null\n || (a = corner(from, direction)) !== (a1 = corner(to, direction))\n || comparePoint(from, to) < 0 ^ direction > 0) {\n do stream.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);\n while ((a = (a + direction + 4) % 4) !== a1);\n } else {\n stream.point(to[0], to[1]);\n }\n }\n\n function corner(p, direction) {\n return abs(p[0] - x0) < epsilon ? direction > 0 ? 0 : 3\n : abs(p[0] - x1) < epsilon ? direction > 0 ? 2 : 1\n : abs(p[1] - y0) < epsilon ? direction > 0 ? 1 : 0\n : direction > 0 ? 3 : 2; // abs(p[1] - y1) < epsilon\n }\n\n function compareIntersection(a, b) {\n return comparePoint(a.x, b.x);\n }\n\n function comparePoint(a, b) {\n var ca = corner(a, 1),\n cb = corner(b, 1);\n return ca !== cb ? ca - cb\n : ca === 0 ? b[1] - a[1]\n : ca === 1 ? a[0] - b[0]\n : ca === 2 ? a[1] - b[1]\n : b[0] - a[0];\n }\n\n return function(stream) {\n var activeStream = stream,\n bufferStream = clipBuffer(),\n segments,\n polygon,\n ring,\n x__, y__, v__, // first point\n x_, y_, v_, // previous point\n first,\n clean;\n\n var clipStream = {\n point: point,\n lineStart: lineStart,\n lineEnd: lineEnd,\n polygonStart: polygonStart,\n polygonEnd: polygonEnd\n };\n\n function point(x, y) {\n if (visible(x, y)) activeStream.point(x, y);\n }\n\n function polygonInside() {\n var winding = 0;\n\n for (var i = 0, n = polygon.length; i < n; ++i) {\n for (var ring = polygon[i], j = 1, m = ring.length, point = ring[0], a0, a1, b0 = point[0], b1 = point[1]; j < m; ++j) {\n a0 = b0, a1 = b1, point = ring[j], b0 = point[0], b1 = point[1];\n if (a1 <= y1) { if (b1 > y1 && (b0 - a0) * (y1 - a1) > (b1 - a1) * (x0 - a0)) ++winding; }\n else { if (b1 <= y1 && (b0 - a0) * (y1 - a1) < (b1 - a1) * (x0 - a0)) --winding; }\n }\n }\n\n return winding;\n }\n\n // Buffer geometry within a polygon and then clip it en masse.\n function polygonStart() {\n activeStream = bufferStream, segments = [], polygon = [], clean = true;\n }\n\n function polygonEnd() {\n var startInside = polygonInside(),\n cleanInside = clean && startInside,\n visible = (segments = merge(segments)).length;\n if (cleanInside || visible) {\n stream.polygonStart();\n if (cleanInside) {\n stream.lineStart();\n interpolate(null, null, 1, stream);\n stream.lineEnd();\n }\n if (visible) {\n clipRejoin(segments, compareIntersection, startInside, interpolate, stream);\n }\n stream.polygonEnd();\n }\n activeStream = stream, segments = polygon = ring = null;\n }\n\n function lineStart() {\n clipStream.point = linePoint;\n if (polygon) polygon.push(ring = []);\n first = true;\n v_ = false;\n x_ = y_ = NaN;\n }\n\n // TODO rather than special-case polygons, simply handle them separately.\n // Ideally, coincident intersection points should be jittered to avoid\n // clipping issues.\n function lineEnd() {\n if (segments) {\n linePoint(x__, y__);\n if (v__ && v_) bufferStream.rejoin();\n segments.push(bufferStream.result());\n }\n clipStream.point = point;\n if (v_) activeStream.lineEnd();\n }\n\n function linePoint(x, y) {\n var v = visible(x, y);\n if (polygon) ring.push([x, y]);\n if (first) {\n x__ = x, y__ = y, v__ = v;\n first = false;\n if (v) {\n activeStream.lineStart();\n activeStream.point(x, y);\n }\n } else {\n if (v && v_) activeStream.point(x, y);\n else {\n var a = [x_ = Math.max(clipMin, Math.min(clipMax, x_)), y_ = Math.max(clipMin, Math.min(clipMax, y_))],\n b = [x = Math.max(clipMin, Math.min(clipMax, x)), y = Math.max(clipMin, Math.min(clipMax, y))];\n if (clipLine(a, b, x0, y0, x1, y1)) {\n if (!v_) {\n activeStream.lineStart();\n activeStream.point(a[0], a[1]);\n }\n activeStream.point(b[0], b[1]);\n if (!v) activeStream.lineEnd();\n clean = false;\n } else if (v) {\n activeStream.lineStart();\n activeStream.point(x, y);\n clean = false;\n }\n }\n }\n x_ = x, y_ = y, v_ = v;\n }\n\n return clipStream;\n };\n}\n","export default function(a, b, x0, y0, x1, y1) {\n var ax = a[0],\n ay = a[1],\n bx = b[0],\n by = b[1],\n t0 = 0,\n t1 = 1,\n dx = bx - ax,\n dy = by - ay,\n r;\n\n r = x0 - ax;\n if (!dx && r > 0) return;\n r /= dx;\n if (dx < 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n } else if (dx > 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n }\n\n r = x1 - ax;\n if (!dx && r < 0) return;\n r /= dx;\n if (dx < 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n } else if (dx > 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n }\n\n r = y0 - ay;\n if (!dy && r > 0) return;\n r /= dy;\n if (dy < 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n } else if (dy > 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n }\n\n r = y1 - ay;\n if (!dy && r < 0) return;\n r /= dy;\n if (dy < 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n } else if (dy > 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n }\n\n if (t0 > 0) a[0] = ax + t0 * dx, a[1] = ay + t0 * dy;\n if (t1 < 1) b[0] = ax + t1 * dx, b[1] = ay + t1 * dy;\n return true;\n}\n","export default function(methods) {\n return {\n stream: transformer(methods)\n };\n}\n\nexport function transformer(methods) {\n return function(stream) {\n var s = new TransformStream;\n for (var key in methods) s[key] = methods[key];\n s.stream = stream;\n return s;\n };\n}\n\nfunction TransformStream() {}\n\nTransformStream.prototype = {\n constructor: TransformStream,\n point: function(x, y) { this.stream.point(x, y); },\n sphere: function() { this.stream.sphere(); },\n lineStart: function() { this.stream.lineStart(); },\n lineEnd: function() { this.stream.lineEnd(); },\n polygonStart: function() { this.stream.polygonStart(); },\n polygonEnd: function() { this.stream.polygonEnd(); }\n};\n","import {default as geoStream} from \"../stream.js\";\nimport boundsStream from \"../path/bounds.js\";\n\nfunction fit(projection, fitBounds, object) {\n var clip = projection.clipExtent && projection.clipExtent();\n projection.scale(150).translate([0, 0]);\n if (clip != null) projection.clipExtent(null);\n geoStream(object, projection.stream(boundsStream));\n fitBounds(boundsStream.result());\n if (clip != null) projection.clipExtent(clip);\n return projection;\n}\n\nexport function fitExtent(projection, extent, object) {\n return fit(projection, function(b) {\n var w = extent[1][0] - extent[0][0],\n h = extent[1][1] - extent[0][1],\n k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])),\n x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2,\n y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;\n projection.scale(150 * k).translate([x, y]);\n }, object);\n}\n\nexport function fitSize(projection, size, object) {\n return fitExtent(projection, [[0, 0], size], object);\n}\n\nexport function fitWidth(projection, width, object) {\n return fit(projection, function(b) {\n var w = +width,\n k = w / (b[1][0] - b[0][0]),\n x = (w - k * (b[1][0] + b[0][0])) / 2,\n y = -k * b[0][1];\n projection.scale(150 * k).translate([x, y]);\n }, object);\n}\n\nexport function fitHeight(projection, height, object) {\n return fit(projection, function(b) {\n var h = +height,\n k = h / (b[1][1] - b[0][1]),\n x = -k * b[0][0],\n y = (h - k * (b[1][1] + b[0][1])) / 2;\n projection.scale(150 * k).translate([x, y]);\n }, object);\n}\n","import {cartesian} from \"../cartesian.js\";\nimport {abs, asin, atan2, cos, epsilon, radians, sqrt} from \"../math.js\";\nimport {transformer} from \"../transform.js\";\n\nvar maxDepth = 16, // maximum depth of subdivision\n cosMinDistance = cos(30 * radians); // cos(minimum angular distance)\n\nexport default function(project, delta2) {\n return +delta2 ? resample(project, delta2) : resampleNone(project);\n}\n\nfunction resampleNone(project) {\n return transformer({\n point: function(x, y) {\n x = project(x, y);\n this.stream.point(x[0], x[1]);\n }\n });\n}\n\nfunction resample(project, delta2) {\n\n function resampleLineTo(x0, y0, lambda0, a0, b0, c0, x1, y1, lambda1, a1, b1, c1, depth, stream) {\n var dx = x1 - x0,\n dy = y1 - y0,\n d2 = dx * dx + dy * dy;\n if (d2 > 4 * delta2 && depth--) {\n var a = a0 + a1,\n b = b0 + b1,\n c = c0 + c1,\n m = sqrt(a * a + b * b + c * c),\n phi2 = asin(c /= m),\n lambda2 = abs(abs(c) - 1) < epsilon || abs(lambda0 - lambda1) < epsilon ? (lambda0 + lambda1) / 2 : atan2(b, a),\n p = project(lambda2, phi2),\n x2 = p[0],\n y2 = p[1],\n dx2 = x2 - x0,\n dy2 = y2 - y0,\n dz = dy * dx2 - dx * dy2;\n if (dz * dz / d2 > delta2 // perpendicular projected distance\n || abs((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 // midpoint close to an end\n || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { // angular distance\n resampleLineTo(x0, y0, lambda0, a0, b0, c0, x2, y2, lambda2, a /= m, b /= m, c, depth, stream);\n stream.point(x2, y2);\n resampleLineTo(x2, y2, lambda2, a, b, c, x1, y1, lambda1, a1, b1, c1, depth, stream);\n }\n }\n }\n return function(stream) {\n var lambda00, x00, y00, a00, b00, c00, // first point\n lambda0, x0, y0, a0, b0, c0; // previous point\n\n var resampleStream = {\n point: point,\n lineStart: lineStart,\n lineEnd: lineEnd,\n polygonStart: function() { stream.polygonStart(); resampleStream.lineStart = ringStart; },\n polygonEnd: function() { stream.polygonEnd(); resampleStream.lineStart = lineStart; }\n };\n\n function point(x, y) {\n x = project(x, y);\n stream.point(x[0], x[1]);\n }\n\n function lineStart() {\n x0 = NaN;\n resampleStream.point = linePoint;\n stream.lineStart();\n }\n\n function linePoint(lambda, phi) {\n var c = cartesian([lambda, phi]), p = project(lambda, phi);\n resampleLineTo(x0, y0, lambda0, a0, b0, c0, x0 = p[0], y0 = p[1], lambda0 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);\n stream.point(x0, y0);\n }\n\n function lineEnd() {\n resampleStream.point = point;\n stream.lineEnd();\n }\n\n function ringStart() {\n lineStart();\n resampleStream.point = ringPoint;\n resampleStream.lineEnd = ringEnd;\n }\n\n function ringPoint(lambda, phi) {\n linePoint(lambda00 = lambda, phi), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;\n resampleStream.point = linePoint;\n }\n\n function ringEnd() {\n resampleLineTo(x0, y0, lambda0, a0, b0, c0, x00, y00, lambda00, a00, b00, c00, maxDepth, stream);\n resampleStream.lineEnd = lineEnd;\n lineEnd();\n }\n\n return resampleStream;\n };\n}\n","import clipAntimeridian from \"../clip/antimeridian.js\";\nimport clipCircle from \"../clip/circle.js\";\nimport clipRectangle from \"../clip/rectangle.js\";\nimport compose from \"../compose.js\";\nimport identity from \"../identity.js\";\nimport {cos, degrees, radians, sin, sqrt} from \"../math.js\";\nimport {rotateRadians} from \"../rotation.js\";\nimport {transformer} from \"../transform.js\";\nimport {fitExtent, fitSize, fitWidth, fitHeight} from \"./fit.js\";\nimport resample from \"./resample.js\";\n\nvar transformRadians = transformer({\n point: function(x, y) {\n this.stream.point(x * radians, y * radians);\n }\n});\n\nfunction transformRotate(rotate) {\n return transformer({\n point: function(x, y) {\n var r = rotate(x, y);\n return this.stream.point(r[0], r[1]);\n }\n });\n}\n\nfunction scaleTranslate(k, dx, dy, sx, sy) {\n function transform(x, y) {\n x *= sx; y *= sy;\n return [dx + k * x, dy - k * y];\n }\n transform.invert = function(x, y) {\n return [(x - dx) / k * sx, (dy - y) / k * sy];\n };\n return transform;\n}\n\nfunction scaleTranslateRotate(k, dx, dy, sx, sy, alpha) {\n if (!alpha) return scaleTranslate(k, dx, dy, sx, sy);\n var cosAlpha = cos(alpha),\n sinAlpha = sin(alpha),\n a = cosAlpha * k,\n b = sinAlpha * k,\n ai = cosAlpha / k,\n bi = sinAlpha / k,\n ci = (sinAlpha * dy - cosAlpha * dx) / k,\n fi = (sinAlpha * dx + cosAlpha * dy) / k;\n function transform(x, y) {\n x *= sx; y *= sy;\n return [a * x - b * y + dx, dy - b * x - a * y];\n }\n transform.invert = function(x, y) {\n return [sx * (ai * x - bi * y + ci), sy * (fi - bi * x - ai * y)];\n };\n return transform;\n}\n\nexport default function projection(project) {\n return projectionMutator(function() { return project; })();\n}\n\nexport function projectionMutator(projectAt) {\n var project,\n k = 150, // scale\n x = 480, y = 250, // translate\n lambda = 0, phi = 0, // center\n deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, // pre-rotate\n alpha = 0, // post-rotate angle\n sx = 1, // reflectX\n sy = 1, // reflectX\n theta = null, preclip = clipAntimeridian, // pre-clip angle\n x0 = null, y0, x1, y1, postclip = identity, // post-clip extent\n delta2 = 0.5, // precision\n projectResample,\n projectTransform,\n projectRotateTransform,\n cache,\n cacheStream;\n\n function projection(point) {\n return projectRotateTransform(point[0] * radians, point[1] * radians);\n }\n\n function invert(point) {\n point = projectRotateTransform.invert(point[0], point[1]);\n return point && [point[0] * degrees, point[1] * degrees];\n }\n\n projection.stream = function(stream) {\n return cache && cacheStream === stream ? cache : cache = transformRadians(transformRotate(rotate)(preclip(projectResample(postclip(cacheStream = stream)))));\n };\n\n projection.preclip = function(_) {\n return arguments.length ? (preclip = _, theta = undefined, reset()) : preclip;\n };\n\n projection.postclip = function(_) {\n return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;\n };\n\n projection.clipAngle = function(_) {\n return arguments.length ? (preclip = +_ ? clipCircle(theta = _ * radians) : (theta = null, clipAntimeridian), reset()) : theta * degrees;\n };\n\n projection.clipExtent = function(_) {\n return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];\n };\n\n projection.scale = function(_) {\n return arguments.length ? (k = +_, recenter()) : k;\n };\n\n projection.translate = function(_) {\n return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [x, y];\n };\n\n projection.center = function(_) {\n return arguments.length ? (lambda = _[0] % 360 * radians, phi = _[1] % 360 * radians, recenter()) : [lambda * degrees, phi * degrees];\n };\n\n projection.rotate = function(_) {\n return arguments.length ? (deltaLambda = _[0] % 360 * radians, deltaPhi = _[1] % 360 * radians, deltaGamma = _.length > 2 ? _[2] % 360 * radians : 0, recenter()) : [deltaLambda * degrees, deltaPhi * degrees, deltaGamma * degrees];\n };\n\n projection.angle = function(_) {\n return arguments.length ? (alpha = _ % 360 * radians, recenter()) : alpha * degrees;\n };\n\n projection.reflectX = function(_) {\n return arguments.length ? (sx = _ ? -1 : 1, recenter()) : sx < 0;\n };\n\n projection.reflectY = function(_) {\n return arguments.length ? (sy = _ ? -1 : 1, recenter()) : sy < 0;\n };\n\n projection.precision = function(_) {\n return arguments.length ? (projectResample = resample(projectTransform, delta2 = _ * _), reset()) : sqrt(delta2);\n };\n\n projection.fitExtent = function(extent, object) {\n return fitExtent(projection, extent, object);\n };\n\n projection.fitSize = function(size, object) {\n return fitSize(projection, size, object);\n };\n\n projection.fitWidth = function(width, object) {\n return fitWidth(projection, width, object);\n };\n\n projection.fitHeight = function(height, object) {\n return fitHeight(projection, height, object);\n };\n\n function recenter() {\n var center = scaleTranslateRotate(k, 0, 0, sx, sy, alpha).apply(null, project(lambda, phi)),\n transform = scaleTranslateRotate(k, x - center[0], y - center[1], sx, sy, alpha);\n rotate = rotateRadians(deltaLambda, deltaPhi, deltaGamma);\n projectTransform = compose(project, transform);\n projectRotateTransform = compose(rotate, projectTransform);\n projectResample = resample(projectTransform, delta2);\n return reset();\n }\n\n function reset() {\n cache = cacheStream = null;\n return projection;\n }\n\n return function() {\n project = projectAt.apply(this, arguments);\n projection.invert = project.invert && invert;\n return recenter();\n };\n}\n","import {degrees, pi, radians} from \"../math.js\";\nimport {projectionMutator} from \"./index.js\";\n\nexport function conicProjection(projectAt) {\n var phi0 = 0,\n phi1 = pi / 3,\n m = projectionMutator(projectAt),\n p = m(phi0, phi1);\n\n p.parallels = function(_) {\n return arguments.length ? m(phi0 = _[0] * radians, phi1 = _[1] * radians) : [phi0 * degrees, phi1 * degrees];\n };\n\n return p;\n}\n","import {abs, asin, atan2, cos, epsilon, pi, sign, sin, sqrt} from \"../math.js\";\nimport {conicProjection} from \"./conic.js\";\nimport {cylindricalEqualAreaRaw} from \"./cylindricalEqualArea.js\";\n\nexport function conicEqualAreaRaw(y0, y1) {\n var sy0 = sin(y0), n = (sy0 + sin(y1)) / 2;\n\n // Are the parallels symmetrical around the Equator?\n if (abs(n) < epsilon) return cylindricalEqualAreaRaw(y0);\n\n var c = 1 + sy0 * (2 * n - sy0), r0 = sqrt(c) / n;\n\n function project(x, y) {\n var r = sqrt(c - 2 * n * sin(y)) / n;\n return [r * sin(x *= n), r0 - r * cos(x)];\n }\n\n project.invert = function(x, y) {\n var r0y = r0 - y,\n l = atan2(x, abs(r0y)) * sign(r0y);\n if (r0y * n < 0)\n l -= pi * sign(x) * sign(r0y);\n return [l / n, asin((c - (x * x + r0y * r0y) * n * n) / (2 * n))];\n };\n\n return project;\n}\n\nexport default function() {\n return conicProjection(conicEqualAreaRaw)\n .scale(155.424)\n .center([0, 33.6442]);\n}\n","import {asin, cos, sin} from \"../math.js\";\n\nexport function cylindricalEqualAreaRaw(phi0) {\n var cosPhi0 = cos(phi0);\n\n function forward(lambda, phi) {\n return [lambda * cosPhi0, sin(phi) / cosPhi0];\n }\n\n forward.invert = function(x, y) {\n return [x / cosPhi0, asin(y * cosPhi0)];\n };\n\n return forward;\n}\n","import conicEqualArea from \"./conicEqualArea.js\";\n\nexport default function() {\n return conicEqualArea()\n .parallels([29.5, 45.5])\n .scale(1070)\n .translate([480, 250])\n .rotate([96, 0])\n .center([-0.6, 38.7]);\n}\n","import {asin, atan2, cos, sin, sqrt} from \"../math.js\";\n\nexport function azimuthalRaw(scale) {\n return function(x, y) {\n var cx = cos(x),\n cy = cos(y),\n k = scale(cx * cy);\n if (k === Infinity) return [2, 0];\n return [\n k * cy * sin(x),\n k * sin(y)\n ];\n }\n}\n\nexport function azimuthalInvert(angle) {\n return function(x, y) {\n var z = sqrt(x * x + y * y),\n c = angle(z),\n sc = sin(c),\n cc = cos(c);\n return [\n atan2(x * sc, z * cc),\n asin(z && y * sc / z)\n ];\n }\n}\n","import {asin, sqrt} from \"../math.js\";\nimport {azimuthalRaw, azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) {\n return sqrt(2 / (1 + cxcy));\n});\n\nazimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) {\n return 2 * asin(z / 2);\n});\n\nexport default function() {\n return projection(azimuthalEqualAreaRaw)\n .scale(124.75)\n .clipAngle(180 - 1e-3);\n}\n","import {acos, sin} from \"../math.js\";\nimport {azimuthalRaw, azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport var azimuthalEquidistantRaw = azimuthalRaw(function(c) {\n return (c = acos(c)) && c / sin(c);\n});\n\nazimuthalEquidistantRaw.invert = azimuthalInvert(function(z) {\n return z;\n});\n\nexport default function() {\n return projection(azimuthalEquidistantRaw)\n .scale(79.4188)\n .clipAngle(180 - 1e-3);\n}\n","import {atan, exp, halfPi, log, pi, tan, tau} from \"../math.js\";\nimport rotation from \"../rotation.js\";\nimport projection from \"./index.js\";\n\nexport function mercatorRaw(lambda, phi) {\n return [lambda, log(tan((halfPi + phi) / 2))];\n}\n\nmercatorRaw.invert = function(x, y) {\n return [x, 2 * atan(exp(y)) - halfPi];\n};\n\nexport default function() {\n return mercatorProjection(mercatorRaw)\n .scale(961 / tau);\n}\n\nexport function mercatorProjection(project) {\n var m = projection(project),\n center = m.center,\n scale = m.scale,\n translate = m.translate,\n clipExtent = m.clipExtent,\n x0 = null, y0, x1, y1; // clip extent\n\n m.scale = function(_) {\n return arguments.length ? (scale(_), reclip()) : scale();\n };\n\n m.translate = function(_) {\n return arguments.length ? (translate(_), reclip()) : translate();\n };\n\n m.center = function(_) {\n return arguments.length ? (center(_), reclip()) : center();\n };\n\n m.clipExtent = function(_) {\n return arguments.length ? ((_ == null ? x0 = y0 = x1 = y1 = null : (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1])), reclip()) : x0 == null ? null : [[x0, y0], [x1, y1]];\n };\n\n function reclip() {\n var k = pi * scale(),\n t = m(rotation(m.rotate()).invert([0, 0]));\n return clipExtent(x0 == null\n ? [[t[0] - k, t[1] - k], [t[0] + k, t[1] + k]] : project === mercatorRaw\n ? [[Math.max(t[0] - k, x0), y0], [Math.min(t[0] + k, x1), y1]]\n : [[x0, Math.max(t[1] - k, y0)], [x1, Math.min(t[1] + k, y1)]]);\n }\n\n return reclip();\n}\n","import {abs, atan, atan2, cos, epsilon, halfPi, log, pi, pow, sign, sin, sqrt, tan} from \"../math.js\";\nimport {conicProjection} from \"./conic.js\";\nimport {mercatorRaw} from \"./mercator.js\";\n\nfunction tany(y) {\n return tan((halfPi + y) / 2);\n}\n\nexport function conicConformalRaw(y0, y1) {\n var cy0 = cos(y0),\n n = y0 === y1 ? sin(y0) : log(cy0 / cos(y1)) / log(tany(y1) / tany(y0)),\n f = cy0 * pow(tany(y0), n) / n;\n\n if (!n) return mercatorRaw;\n\n function project(x, y) {\n if (f > 0) { if (y < -halfPi + epsilon) y = -halfPi + epsilon; }\n else { if (y > halfPi - epsilon) y = halfPi - epsilon; }\n var r = f / pow(tany(y), n);\n return [r * sin(n * x), f - r * cos(n * x)];\n }\n\n project.invert = function(x, y) {\n var fy = f - y, r = sign(n) * sqrt(x * x + fy * fy),\n l = atan2(x, abs(fy)) * sign(fy);\n if (fy * n < 0)\n l -= pi * sign(x) * sign(fy);\n return [l / n, 2 * atan(pow(f / r, 1 / n)) - halfPi];\n };\n\n return project;\n}\n\nexport default function() {\n return conicProjection(conicConformalRaw)\n .scale(109.5)\n .parallels([30, 30]);\n}\n","import projection from \"./index.js\";\n\nexport function equirectangularRaw(lambda, phi) {\n return [lambda, phi];\n}\n\nequirectangularRaw.invert = equirectangularRaw;\n\nexport default function() {\n return projection(equirectangularRaw)\n .scale(152.63);\n}\n","import {abs, atan2, cos, epsilon, pi, sign, sin, sqrt} from \"../math.js\";\nimport {conicProjection} from \"./conic.js\";\nimport {equirectangularRaw} from \"./equirectangular.js\";\n\nexport function conicEquidistantRaw(y0, y1) {\n var cy0 = cos(y0),\n n = y0 === y1 ? sin(y0) : (cy0 - cos(y1)) / (y1 - y0),\n g = cy0 / n + y0;\n\n if (abs(n) < epsilon) return equirectangularRaw;\n\n function project(x, y) {\n var gy = g - y, nx = n * x;\n return [gy * sin(nx), g - gy * cos(nx)];\n }\n\n project.invert = function(x, y) {\n var gy = g - y,\n l = atan2(x, abs(gy)) * sign(gy);\n if (gy * n < 0)\n l -= pi * sign(x) * sign(gy);\n return [l / n, g - sign(n) * sqrt(x * x + gy * gy)];\n };\n\n return project;\n}\n\nexport default function() {\n return conicProjection(conicEquidistantRaw)\n .scale(131.154)\n .center([0, 13.9389]);\n}\n","import projection from \"./index.js\";\nimport {abs, asin, cos, epsilon2, sin, sqrt} from \"../math.js\";\n\nvar A1 = 1.340264,\n A2 = -0.081106,\n A3 = 0.000893,\n A4 = 0.003796,\n M = sqrt(3) / 2,\n iterations = 12;\n\nexport function equalEarthRaw(lambda, phi) {\n var l = asin(M * sin(phi)), l2 = l * l, l6 = l2 * l2 * l2;\n return [\n lambda * cos(l) / (M * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2))),\n l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2))\n ];\n}\n\nequalEarthRaw.invert = function(x, y) {\n var l = y, l2 = l * l, l6 = l2 * l2 * l2;\n for (var i = 0, delta, fy, fpy; i < iterations; ++i) {\n fy = l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2)) - y;\n fpy = A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2);\n l -= delta = fy / fpy, l2 = l * l, l6 = l2 * l2 * l2;\n if (abs(delta) < epsilon2) break;\n }\n return [\n M * x * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2)) / cos(l),\n asin(sin(l) / M)\n ];\n};\n\nexport default function() {\n return projection(equalEarthRaw)\n .scale(177.158);\n}\n","import {atan, cos, sin} from \"../math.js\";\nimport {azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport function gnomonicRaw(x, y) {\n var cy = cos(y), k = cos(x) * cy;\n return [cy * sin(x) / k, sin(y) / k];\n}\n\ngnomonicRaw.invert = azimuthalInvert(atan);\n\nexport default function() {\n return projection(gnomonicRaw)\n .scale(144.049)\n .clipAngle(60);\n}\n","import projection from \"./index.js\";\nimport {abs, epsilon} from \"../math.js\";\n\nexport function naturalEarth1Raw(lambda, phi) {\n var phi2 = phi * phi, phi4 = phi2 * phi2;\n return [\n lambda * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (0.003971 * phi2 - 0.001529 * phi4))),\n phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4)))\n ];\n}\n\nnaturalEarth1Raw.invert = function(x, y) {\n var phi = y, i = 25, delta;\n do {\n var phi2 = phi * phi, phi4 = phi2 * phi2;\n phi -= delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4))) - y) /\n (1.007226 + phi2 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi2 - 0.005916 * 11 * phi4)));\n } while (abs(delta) > epsilon && --i > 0);\n return [\n x / (0.8707 + (phi2 = phi * phi) * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (0.003971 - 0.001529 * phi2)))),\n phi\n ];\n};\n\nexport default function() {\n return projection(naturalEarth1Raw)\n .scale(175.295);\n}\n","import {asin, cos, epsilon, sin} from \"../math.js\";\nimport {azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport function orthographicRaw(x, y) {\n return [cos(y) * sin(x), sin(y)];\n}\n\northographicRaw.invert = azimuthalInvert(asin);\n\nexport default function() {\n return projection(orthographicRaw)\n .scale(249.5)\n .clipAngle(90 + epsilon);\n}\n","import {atan, cos, sin} from \"../math.js\";\nimport {azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport function stereographicRaw(x, y) {\n var cy = cos(y), k = 1 + cos(x) * cy;\n return [cy * sin(x) / k, sin(y) / k];\n}\n\nstereographicRaw.invert = azimuthalInvert(function(z) {\n return 2 * atan(z);\n});\n\nexport default function() {\n return projection(stereographicRaw)\n .scale(250)\n .clipAngle(142);\n}\n","import {atan, exp, halfPi, log, tan} from \"../math.js\";\nimport {mercatorProjection} from \"./mercator.js\";\n\nexport function transverseMercatorRaw(lambda, phi) {\n return [log(tan((halfPi + phi) / 2)), -lambda];\n}\n\ntransverseMercatorRaw.invert = function(x, y) {\n return [-y, 2 * atan(exp(x)) - halfPi];\n};\n\nexport default function() {\n var m = mercatorProjection(transverseMercatorRaw),\n center = m.center,\n rotate = m.rotate;\n\n m.center = function(_) {\n return arguments.length ? center([-_[1], _[0]]) : (_ = center(), [_[1], -_[0]]);\n };\n\n m.rotate = function(_) {\n return arguments.length ? rotate([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate(), [_[0], _[1], _[2] - 90]);\n };\n\n return rotate([0, 0, 90])\n .scale(159.155);\n}\n","export default function noop() {}\n","import noop from \"../noop.js\";\n\nexport default function() {\n var lines = [],\n line;\n return {\n point: function(x, y, m) {\n line.push([x, y, m]);\n },\n lineStart: function() {\n lines.push(line = []);\n },\n lineEnd: noop,\n rejoin: function() {\n if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));\n },\n result: function() {\n var result = lines;\n lines = [];\n line = null;\n return result;\n }\n };\n}\n","export var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var quarterPi = pi / 4;\nexport var tau = pi * 2;\n\nexport var degrees = 180 / pi;\nexport var radians = pi / 180;\n\nexport var abs = Math.abs;\nexport var atan = Math.atan;\nexport var atan2 = Math.atan2;\nexport var cos = Math.cos;\nexport var ceil = Math.ceil;\nexport var exp = Math.exp;\nexport var floor = Math.floor;\nexport var hypot = Math.hypot;\nexport var log = Math.log;\nexport var pow = Math.pow;\nexport var sin = Math.sin;\nexport var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };\nexport var sqrt = Math.sqrt;\nexport var tan = Math.tan;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);\n}\n\nexport function haversin(x) {\n return (x = sin(x / 2)) * x;\n}\n","import {abs, epsilon} from \"./math.js\";\n\nexport default function(a, b) {\n return abs(a[0] - b[0]) < epsilon && abs(a[1] - b[1]) < epsilon;\n}\n","import pointEqual from \"../pointEqual.js\";\nimport {epsilon} from \"../math.js\";\n\nfunction Intersection(point, points, other, entry) {\n this.x = point;\n this.z = points;\n this.o = other; // another intersection\n this.e = entry; // is an entry?\n this.v = false; // visited\n this.n = this.p = null; // next & previous\n}\n\n// A generalized polygon clipping algorithm: given a polygon that has been cut\n// into its visible line segments, and rejoins the segments by interpolating\n// along the clip edge.\nexport default function(segments, compareIntersection, startInside, interpolate, stream) {\n var subject = [],\n clip = [],\n i,\n n;\n\n segments.forEach(function(segment) {\n if ((n = segment.length - 1) <= 0) return;\n var n, p0 = segment[0], p1 = segment[n], x;\n\n if (pointEqual(p0, p1)) {\n if (!p0[2] && !p1[2]) {\n stream.lineStart();\n for (i = 0; i < n; ++i) stream.point((p0 = segment[i])[0], p0[1]);\n stream.lineEnd();\n return;\n }\n // handle degenerate cases by moving the point\n p1[0] += 2 * epsilon;\n }\n\n subject.push(x = new Intersection(p0, segment, null, true));\n clip.push(x.o = new Intersection(p0, null, x, false));\n subject.push(x = new Intersection(p1, segment, null, false));\n clip.push(x.o = new Intersection(p1, null, x, true));\n });\n\n if (!subject.length) return;\n\n clip.sort(compareIntersection);\n link(subject);\n link(clip);\n\n for (i = 0, n = clip.length; i < n; ++i) {\n clip[i].e = startInside = !startInside;\n }\n\n var start = subject[0],\n points,\n point;\n\n while (1) {\n // Find first unvisited intersection.\n var current = start,\n isSubject = true;\n while (current.v) if ((current = current.n) === start) return;\n points = current.z;\n stream.lineStart();\n do {\n current.v = current.o.v = true;\n if (current.e) {\n if (isSubject) {\n for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]);\n } else {\n interpolate(current.x, current.n.x, 1, stream);\n }\n current = current.n;\n } else {\n if (isSubject) {\n points = current.p.z;\n for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]);\n } else {\n interpolate(current.x, current.p.x, -1, stream);\n }\n current = current.p;\n }\n current = current.o;\n points = current.z;\n isSubject = !isSubject;\n } while (!current.v);\n stream.lineEnd();\n }\n}\n\nfunction link(array) {\n if (!(n = array.length)) return;\n var n,\n i = 0,\n a = array[0],\n b;\n while (++i < n) {\n a.n = b = array[i];\n b.p = a;\n a = b;\n }\n a.n = b = array[0];\n b.p = a;\n}\n","// https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423\nexport class Adder {\n constructor() {\n this._partials = new Float64Array(32);\n this._n = 0;\n }\n add(x) {\n const p = this._partials;\n let i = 0;\n for (let j = 0; j < this._n && j < 32; j++) {\n const y = p[j],\n hi = x + y,\n lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);\n if (lo) p[i++] = lo;\n x = hi;\n }\n p[i] = x;\n this._n = i + 1;\n return this;\n }\n valueOf() {\n const p = this._partials;\n let n = this._n, x, y, lo, hi = 0;\n if (n > 0) {\n hi = p[--n];\n while (n > 0) {\n x = hi;\n y = p[--n];\n hi = x + y;\n lo = y - (hi - x);\n if (lo) break;\n }\n if (n > 0 && ((lo < 0 && p[n - 1] < 0) || (lo > 0 && p[n - 1] > 0))) {\n y = lo * 2;\n x = hi + y;\n if (y == x - hi) hi = x;\n }\n }\n return hi;\n }\n}\n\nexport function fsum(values, valueof) {\n const adder = new Adder();\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n adder.add(value);\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n adder.add(value);\n }\n }\n }\n return +adder;\n}\n\nexport function fcumsum(values, valueof) {\n const adder = new Adder();\n let index = -1;\n return Float64Array.from(values, valueof === undefined\n ? v => adder.add(+v || 0)\n : v => adder.add(+valueof(v, ++index, values) || 0)\n );\n}\n","import {asin, atan2, cos, sin, sqrt} from \"./math.js\";\n\nexport function spherical(cartesian) {\n return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];\n}\n\nexport function cartesian(spherical) {\n var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi);\n return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];\n}\n\nexport function cartesianDot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\nexport function cartesianCross(a, b) {\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\n}\n\n// TODO return a\nexport function cartesianAddInPlace(a, b) {\n a[0] += b[0], a[1] += b[1], a[2] += b[2];\n}\n\nexport function cartesianScale(vector, k) {\n return [vector[0] * k, vector[1] * k, vector[2] * k];\n}\n\n// TODO return d\nexport function cartesianNormalizeInPlace(d) {\n var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);\n d[0] /= l, d[1] /= l, d[2] /= l;\n}\n","import {Adder} from \"d3-array\";\nimport {cartesian, cartesianCross, cartesianNormalizeInPlace} from \"./cartesian.js\";\nimport {abs, asin, atan2, cos, epsilon, epsilon2, halfPi, pi, quarterPi, sign, sin, tau} from \"./math.js\";\n\nfunction longitude(point) {\n if (abs(point[0]) <= pi)\n return point[0];\n else\n return sign(point[0]) * ((abs(point[0]) + pi) % tau - pi);\n}\n\nexport default function(polygon, point) {\n var lambda = longitude(point),\n phi = point[1],\n sinPhi = sin(phi),\n normal = [sin(lambda), -cos(lambda), 0],\n angle = 0,\n winding = 0;\n\n var sum = new Adder();\n\n if (sinPhi === 1) phi = halfPi + epsilon;\n else if (sinPhi === -1) phi = -halfPi - epsilon;\n\n for (var i = 0, n = polygon.length; i < n; ++i) {\n if (!(m = (ring = polygon[i]).length)) continue;\n var ring,\n m,\n point0 = ring[m - 1],\n lambda0 = longitude(point0),\n phi0 = point0[1] / 2 + quarterPi,\n sinPhi0 = sin(phi0),\n cosPhi0 = cos(phi0);\n\n for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) {\n var point1 = ring[j],\n lambda1 = longitude(point1),\n phi1 = point1[1] / 2 + quarterPi,\n sinPhi1 = sin(phi1),\n cosPhi1 = cos(phi1),\n delta = lambda1 - lambda0,\n sign = delta >= 0 ? 1 : -1,\n absDelta = sign * delta,\n antimeridian = absDelta > pi,\n k = sinPhi0 * sinPhi1;\n\n sum.add(atan2(k * sign * sin(absDelta), cosPhi0 * cosPhi1 + k * cos(absDelta)));\n angle += antimeridian ? delta + sign * tau : delta;\n\n // Are the longitudes either side of the point’s meridian (lambda),\n // and are the latitudes smaller than the parallel (phi)?\n if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {\n var arc = cartesianCross(cartesian(point0), cartesian(point1));\n cartesianNormalizeInPlace(arc);\n var intersection = cartesianCross(normal, arc);\n cartesianNormalizeInPlace(intersection);\n var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]);\n if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {\n winding += antimeridian ^ delta >= 0 ? 1 : -1;\n }\n }\n }\n }\n\n // First, determine whether the South pole is inside or outside:\n //\n // It is inside if:\n // * the polygon winds around it in a clockwise direction.\n // * the polygon does not (cumulatively) wind around it, but has a negative\n // (counter-clockwise) area.\n //\n // Second, count the (signed) number of times a segment crosses a lambda\n // from the point to the South pole. If it is zero, then the point is the\n // same side as the South pole.\n\n return (angle < -epsilon || angle < epsilon && sum < -epsilon2) ^ (winding & 1);\n}\n","function* flatten(arrays) {\n for (const array of arrays) {\n yield* array;\n }\n}\n\nexport default function merge(arrays) {\n return Array.from(flatten(arrays));\n}\n","import clipBuffer from \"./buffer.js\";\nimport clipRejoin from \"./rejoin.js\";\nimport {epsilon, halfPi} from \"../math.js\";\nimport polygonContains from \"../polygonContains.js\";\nimport {merge} from \"d3-array\";\n\nexport default function(pointVisible, clipLine, interpolate, start) {\n return function(sink) {\n var line = clipLine(sink),\n ringBuffer = clipBuffer(),\n ringSink = clipLine(ringBuffer),\n polygonStarted = false,\n polygon,\n segments,\n ring;\n\n var clip = {\n point: point,\n lineStart: lineStart,\n lineEnd: lineEnd,\n polygonStart: function() {\n clip.point = pointRing;\n clip.lineStart = ringStart;\n clip.lineEnd = ringEnd;\n segments = [];\n polygon = [];\n },\n polygonEnd: function() {\n clip.point = point;\n clip.lineStart = lineStart;\n clip.lineEnd = lineEnd;\n segments = merge(segments);\n var startInside = polygonContains(polygon, start);\n if (segments.length) {\n if (!polygonStarted) sink.polygonStart(), polygonStarted = true;\n clipRejoin(segments, compareIntersection, startInside, interpolate, sink);\n } else if (startInside) {\n if (!polygonStarted) sink.polygonStart(), polygonStarted = true;\n sink.lineStart();\n interpolate(null, null, 1, sink);\n sink.lineEnd();\n }\n if (polygonStarted) sink.polygonEnd(), polygonStarted = false;\n segments = polygon = null;\n },\n sphere: function() {\n sink.polygonStart();\n sink.lineStart();\n interpolate(null, null, 1, sink);\n sink.lineEnd();\n sink.polygonEnd();\n }\n };\n\n function point(lambda, phi) {\n if (pointVisible(lambda, phi)) sink.point(lambda, phi);\n }\n\n function pointLine(lambda, phi) {\n line.point(lambda, phi);\n }\n\n function lineStart() {\n clip.point = pointLine;\n line.lineStart();\n }\n\n function lineEnd() {\n clip.point = point;\n line.lineEnd();\n }\n\n function pointRing(lambda, phi) {\n ring.push([lambda, phi]);\n ringSink.point(lambda, phi);\n }\n\n function ringStart() {\n ringSink.lineStart();\n ring = [];\n }\n\n function ringEnd() {\n pointRing(ring[0][0], ring[0][1]);\n ringSink.lineEnd();\n\n var clean = ringSink.clean(),\n ringSegments = ringBuffer.result(),\n i, n = ringSegments.length, m,\n segment,\n point;\n\n ring.pop();\n polygon.push(ring);\n ring = null;\n\n if (!n) return;\n\n // No intersections.\n if (clean & 1) {\n segment = ringSegments[0];\n if ((m = segment.length - 1) > 0) {\n if (!polygonStarted) sink.polygonStart(), polygonStarted = true;\n sink.lineStart();\n for (i = 0; i < m; ++i) sink.point((point = segment[i])[0], point[1]);\n sink.lineEnd();\n }\n return;\n }\n\n // Rejoin connected segments.\n // TODO reuse ringBuffer.rejoin()?\n if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));\n\n segments.push(ringSegments.filter(validSegment));\n }\n\n return clip;\n };\n}\n\nfunction validSegment(segment) {\n return segment.length > 1;\n}\n\n// Intersections are sorted along the clip edge. For both antimeridian cutting\n// and circle clipping, the same comparison is used.\nfunction compareIntersection(a, b) {\n return ((a = a.x)[0] < 0 ? a[1] - halfPi - epsilon : halfPi - a[1])\n - ((b = b.x)[0] < 0 ? b[1] - halfPi - epsilon : halfPi - b[1]);\n}\n","import clip from \"./index.js\";\nimport {abs, atan, cos, epsilon, halfPi, pi, sin} from \"../math.js\";\n\nexport default clip(\n function() { return true; },\n clipAntimeridianLine,\n clipAntimeridianInterpolate,\n [-pi, -halfPi]\n);\n\n// Takes a line and cuts into visible segments. Return values: 0 - there were\n// intersections or the line was empty; 1 - no intersections; 2 - there were\n// intersections, and the first and last segments should be rejoined.\nfunction clipAntimeridianLine(stream) {\n var lambda0 = NaN,\n phi0 = NaN,\n sign0 = NaN,\n clean; // no intersections\n\n return {\n lineStart: function() {\n stream.lineStart();\n clean = 1;\n },\n point: function(lambda1, phi1) {\n var sign1 = lambda1 > 0 ? pi : -pi,\n delta = abs(lambda1 - lambda0);\n if (abs(delta - pi) < epsilon) { // line crosses a pole\n stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? halfPi : -halfPi);\n stream.point(sign0, phi0);\n stream.lineEnd();\n stream.lineStart();\n stream.point(sign1, phi0);\n stream.point(lambda1, phi0);\n clean = 0;\n } else if (sign0 !== sign1 && delta >= pi) { // line crosses antimeridian\n if (abs(lambda0 - sign0) < epsilon) lambda0 -= sign0 * epsilon; // handle degeneracies\n if (abs(lambda1 - sign1) < epsilon) lambda1 -= sign1 * epsilon;\n phi0 = clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1);\n stream.point(sign0, phi0);\n stream.lineEnd();\n stream.lineStart();\n stream.point(sign1, phi0);\n clean = 0;\n }\n stream.point(lambda0 = lambda1, phi0 = phi1);\n sign0 = sign1;\n },\n lineEnd: function() {\n stream.lineEnd();\n lambda0 = phi0 = NaN;\n },\n clean: function() {\n return 2 - clean; // if intersections, rejoin first and last segments\n }\n };\n}\n\nfunction clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) {\n var cosPhi0,\n cosPhi1,\n sinLambda0Lambda1 = sin(lambda0 - lambda1);\n return abs(sinLambda0Lambda1) > epsilon\n ? atan((sin(phi0) * (cosPhi1 = cos(phi1)) * sin(lambda1)\n - sin(phi1) * (cosPhi0 = cos(phi0)) * sin(lambda0))\n / (cosPhi0 * cosPhi1 * sinLambda0Lambda1))\n : (phi0 + phi1) / 2;\n}\n\nfunction clipAntimeridianInterpolate(from, to, direction, stream) {\n var phi;\n if (from == null) {\n phi = direction * halfPi;\n stream.point(-pi, phi);\n stream.point(0, phi);\n stream.point(pi, phi);\n stream.point(pi, 0);\n stream.point(pi, -phi);\n stream.point(0, -phi);\n stream.point(-pi, -phi);\n stream.point(-pi, 0);\n stream.point(-pi, phi);\n } else if (abs(from[0] - to[0]) > epsilon) {\n var lambda = from[0] < to[0] ? pi : -pi;\n phi = direction * lambda / 2;\n stream.point(-lambda, phi);\n stream.point(0, phi);\n stream.point(lambda, phi);\n } else {\n stream.point(to[0], to[1]);\n }\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","export default function(a, b) {\n\n function compose(x, y) {\n return x = a(x, y), b(x[0], x[1]);\n }\n\n if (a.invert && b.invert) compose.invert = function(x, y) {\n return x = b.invert(x, y), x && a.invert(x[0], x[1]);\n };\n\n return compose;\n}\n","import compose from \"./compose.js\";\nimport {abs, asin, atan2, cos, degrees, pi, radians, sin, tau} from \"./math.js\";\n\nfunction rotationIdentity(lambda, phi) {\n return [abs(lambda) > pi ? lambda + Math.round(-lambda / tau) * tau : lambda, phi];\n}\n\nrotationIdentity.invert = rotationIdentity;\n\nexport function rotateRadians(deltaLambda, deltaPhi, deltaGamma) {\n return (deltaLambda %= tau) ? (deltaPhi || deltaGamma ? compose(rotationLambda(deltaLambda), rotationPhiGamma(deltaPhi, deltaGamma))\n : rotationLambda(deltaLambda))\n : (deltaPhi || deltaGamma ? rotationPhiGamma(deltaPhi, deltaGamma)\n : rotationIdentity);\n}\n\nfunction forwardRotationLambda(deltaLambda) {\n return function(lambda, phi) {\n return lambda += deltaLambda, [lambda > pi ? lambda - tau : lambda < -pi ? lambda + tau : lambda, phi];\n };\n}\n\nfunction rotationLambda(deltaLambda) {\n var rotation = forwardRotationLambda(deltaLambda);\n rotation.invert = forwardRotationLambda(-deltaLambda);\n return rotation;\n}\n\nfunction rotationPhiGamma(deltaPhi, deltaGamma) {\n var cosDeltaPhi = cos(deltaPhi),\n sinDeltaPhi = sin(deltaPhi),\n cosDeltaGamma = cos(deltaGamma),\n sinDeltaGamma = sin(deltaGamma);\n\n function rotation(lambda, phi) {\n var cosPhi = cos(phi),\n x = cos(lambda) * cosPhi,\n y = sin(lambda) * cosPhi,\n z = sin(phi),\n k = z * cosDeltaPhi + x * sinDeltaPhi;\n return [\n atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi),\n asin(k * cosDeltaGamma + y * sinDeltaGamma)\n ];\n }\n\n rotation.invert = function(lambda, phi) {\n var cosPhi = cos(phi),\n x = cos(lambda) * cosPhi,\n y = sin(lambda) * cosPhi,\n z = sin(phi),\n k = z * cosDeltaGamma - y * sinDeltaGamma;\n return [\n atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi),\n asin(k * cosDeltaPhi - x * sinDeltaPhi)\n ];\n };\n\n return rotation;\n}\n\nexport default function(rotate) {\n rotate = rotateRadians(rotate[0] * radians, rotate[1] * radians, rotate.length > 2 ? rotate[2] * radians : 0);\n\n function forward(coordinates) {\n coordinates = rotate(coordinates[0] * radians, coordinates[1] * radians);\n return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;\n }\n\n forward.invert = function(coordinates) {\n coordinates = rotate.invert(coordinates[0] * radians, coordinates[1] * radians);\n return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;\n };\n\n return forward;\n}\n","import {cartesian, cartesianNormalizeInPlace, spherical} from \"./cartesian.js\";\nimport constant from \"./constant.js\";\nimport {acos, cos, degrees, epsilon, radians, sin, tau} from \"./math.js\";\nimport {rotateRadians} from \"./rotation.js\";\n\n// Generates a circle centered at [0°, 0°], with a given radius and precision.\nexport function circleStream(stream, radius, delta, direction, t0, t1) {\n if (!delta) return;\n var cosRadius = cos(radius),\n sinRadius = sin(radius),\n step = direction * delta;\n if (t0 == null) {\n t0 = radius + direction * tau;\n t1 = radius - step / 2;\n } else {\n t0 = circleRadius(cosRadius, t0);\n t1 = circleRadius(cosRadius, t1);\n if (direction > 0 ? t0 < t1 : t0 > t1) t0 += direction * tau;\n }\n for (var point, t = t0; direction > 0 ? t > t1 : t < t1; t -= step) {\n point = spherical([cosRadius, -sinRadius * cos(t), -sinRadius * sin(t)]);\n stream.point(point[0], point[1]);\n }\n}\n\n// Returns the signed angle of a cartesian point relative to [cosRadius, 0, 0].\nfunction circleRadius(cosRadius, point) {\n point = cartesian(point), point[0] -= cosRadius;\n cartesianNormalizeInPlace(point);\n var radius = acos(-point[1]);\n return ((-point[2] < 0 ? -radius : radius) + tau - epsilon) % tau;\n}\n\nexport default function() {\n var center = constant([0, 0]),\n radius = constant(90),\n precision = constant(6),\n ring,\n rotate,\n stream = {point: point};\n\n function point(x, y) {\n ring.push(x = rotate(x, y));\n x[0] *= degrees, x[1] *= degrees;\n }\n\n function circle() {\n var c = center.apply(this, arguments),\n r = radius.apply(this, arguments) * radians,\n p = precision.apply(this, arguments) * radians;\n ring = [];\n rotate = rotateRadians(-c[0] * radians, -c[1] * radians, 0).invert;\n circleStream(stream, r, p, 1);\n c = {type: \"Polygon\", coordinates: [ring]};\n ring = rotate = null;\n return c;\n }\n\n circle.center = function(_) {\n return arguments.length ? (center = typeof _ === \"function\" ? _ : constant([+_[0], +_[1]]), circle) : center;\n };\n\n circle.radius = function(_) {\n return arguments.length ? (radius = typeof _ === \"function\" ? _ : constant(+_), circle) : radius;\n };\n\n circle.precision = function(_) {\n return arguments.length ? (precision = typeof _ === \"function\" ? _ : constant(+_), circle) : precision;\n };\n\n return circle;\n}\n","import {cartesian, cartesianAddInPlace, cartesianCross, cartesianDot, cartesianScale, spherical} from \"../cartesian.js\";\nimport {circleStream} from \"../circle.js\";\nimport {abs, cos, epsilon, pi, radians, sqrt} from \"../math.js\";\nimport pointEqual from \"../pointEqual.js\";\nimport clip from \"./index.js\";\n\nexport default function(radius) {\n var cr = cos(radius),\n delta = 6 * radians,\n smallRadius = cr > 0,\n notHemisphere = abs(cr) > epsilon; // TODO optimise for this common case\n\n function interpolate(from, to, direction, stream) {\n circleStream(stream, radius, delta, direction, from, to);\n }\n\n function visible(lambda, phi) {\n return cos(lambda) * cos(phi) > cr;\n }\n\n // Takes a line and cuts into visible segments. Return values used for polygon\n // clipping: 0 - there were intersections or the line was empty; 1 - no\n // intersections 2 - there were intersections, and the first and last segments\n // should be rejoined.\n function clipLine(stream) {\n var point0, // previous point\n c0, // code for previous point\n v0, // visibility of previous point\n v00, // visibility of first point\n clean; // no intersections\n return {\n lineStart: function() {\n v00 = v0 = false;\n clean = 1;\n },\n point: function(lambda, phi) {\n var point1 = [lambda, phi],\n point2,\n v = visible(lambda, phi),\n c = smallRadius\n ? v ? 0 : code(lambda, phi)\n : v ? code(lambda + (lambda < 0 ? pi : -pi), phi) : 0;\n if (!point0 && (v00 = v0 = v)) stream.lineStart();\n if (v !== v0) {\n point2 = intersect(point0, point1);\n if (!point2 || pointEqual(point0, point2) || pointEqual(point1, point2))\n point1[2] = 1;\n }\n if (v !== v0) {\n clean = 0;\n if (v) {\n // outside going in\n stream.lineStart();\n point2 = intersect(point1, point0);\n stream.point(point2[0], point2[1]);\n } else {\n // inside going out\n point2 = intersect(point0, point1);\n stream.point(point2[0], point2[1], 2);\n stream.lineEnd();\n }\n point0 = point2;\n } else if (notHemisphere && point0 && smallRadius ^ v) {\n var t;\n // If the codes for two points are different, or are both zero,\n // and there this segment intersects with the small circle.\n if (!(c & c0) && (t = intersect(point1, point0, true))) {\n clean = 0;\n if (smallRadius) {\n stream.lineStart();\n stream.point(t[0][0], t[0][1]);\n stream.point(t[1][0], t[1][1]);\n stream.lineEnd();\n } else {\n stream.point(t[1][0], t[1][1]);\n stream.lineEnd();\n stream.lineStart();\n stream.point(t[0][0], t[0][1], 3);\n }\n }\n }\n if (v && (!point0 || !pointEqual(point0, point1))) {\n stream.point(point1[0], point1[1]);\n }\n point0 = point1, v0 = v, c0 = c;\n },\n lineEnd: function() {\n if (v0) stream.lineEnd();\n point0 = null;\n },\n // Rejoin first and last segments if there were intersections and the first\n // and last points were visible.\n clean: function() {\n return clean | ((v00 && v0) << 1);\n }\n };\n }\n\n // Intersects the great circle between a and b with the clip circle.\n function intersect(a, b, two) {\n var pa = cartesian(a),\n pb = cartesian(b);\n\n // We have two planes, n1.p = d1 and n2.p = d2.\n // Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2).\n var n1 = [1, 0, 0], // normal\n n2 = cartesianCross(pa, pb),\n n2n2 = cartesianDot(n2, n2),\n n1n2 = n2[0], // cartesianDot(n1, n2),\n determinant = n2n2 - n1n2 * n1n2;\n\n // Two polar points.\n if (!determinant) return !two && a;\n\n var c1 = cr * n2n2 / determinant,\n c2 = -cr * n1n2 / determinant,\n n1xn2 = cartesianCross(n1, n2),\n A = cartesianScale(n1, c1),\n B = cartesianScale(n2, c2);\n cartesianAddInPlace(A, B);\n\n // Solve |p(t)|^2 = 1.\n var u = n1xn2,\n w = cartesianDot(A, u),\n uu = cartesianDot(u, u),\n t2 = w * w - uu * (cartesianDot(A, A) - 1);\n\n if (t2 < 0) return;\n\n var t = sqrt(t2),\n q = cartesianScale(u, (-w - t) / uu);\n cartesianAddInPlace(q, A);\n q = spherical(q);\n\n if (!two) return q;\n\n // Two intersection points.\n var lambda0 = a[0],\n lambda1 = b[0],\n phi0 = a[1],\n phi1 = b[1],\n z;\n\n if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;\n\n var delta = lambda1 - lambda0,\n polar = abs(delta - pi) < epsilon,\n meridian = polar || delta < epsilon;\n\n if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;\n\n // Check that the first point is between a and b.\n if (meridian\n ? polar\n ? phi0 + phi1 > 0 ^ q[1] < (abs(q[0] - lambda0) < epsilon ? phi0 : phi1)\n : phi0 <= q[1] && q[1] <= phi1\n : delta > pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) {\n var q1 = cartesianScale(u, (-w + t) / uu);\n cartesianAddInPlace(q1, A);\n return [q, spherical(q1)];\n }\n }\n\n // Generates a 4-bit vector representing the location of a point relative to\n // the small circle's bounding box.\n function code(lambda, phi) {\n var r = smallRadius ? radius : pi - radius,\n code = 0;\n if (lambda < -r) code |= 1; // left\n else if (lambda > r) code |= 2; // right\n if (phi < -r) code |= 4; // below\n else if (phi > r) code |= 8; // above\n return code;\n }\n\n return clip(visible, clipLine, interpolate, smallRadius ? [0, -radius] : [-pi, radius - pi]);\n}\n","import {abs, epsilon} from \"../math.js\";\nimport clipBuffer from \"./buffer.js\";\nimport clipLine from \"./line.js\";\nimport clipRejoin from \"./rejoin.js\";\nimport {merge} from \"d3-array\";\n\nvar clipMax = 1e9, clipMin = -clipMax;\n\n// TODO Use d3-polygon’s polygonContains here for the ring check?\n// TODO Eliminate duplicate buffering in clipBuffer and polygon.push?\n\nexport default function clipRectangle(x0, y0, x1, y1) {\n\n function visible(x, y) {\n return x0 <= x && x <= x1 && y0 <= y && y <= y1;\n }\n\n function interpolate(from, to, direction, stream) {\n var a = 0, a1 = 0;\n if (from == null\n || (a = corner(from, direction)) !== (a1 = corner(to, direction))\n || comparePoint(from, to) < 0 ^ direction > 0) {\n do stream.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);\n while ((a = (a + direction + 4) % 4) !== a1);\n } else {\n stream.point(to[0], to[1]);\n }\n }\n\n function corner(p, direction) {\n return abs(p[0] - x0) < epsilon ? direction > 0 ? 0 : 3\n : abs(p[0] - x1) < epsilon ? direction > 0 ? 2 : 1\n : abs(p[1] - y0) < epsilon ? direction > 0 ? 1 : 0\n : direction > 0 ? 3 : 2; // abs(p[1] - y1) < epsilon\n }\n\n function compareIntersection(a, b) {\n return comparePoint(a.x, b.x);\n }\n\n function comparePoint(a, b) {\n var ca = corner(a, 1),\n cb = corner(b, 1);\n return ca !== cb ? ca - cb\n : ca === 0 ? b[1] - a[1]\n : ca === 1 ? a[0] - b[0]\n : ca === 2 ? a[1] - b[1]\n : b[0] - a[0];\n }\n\n return function(stream) {\n var activeStream = stream,\n bufferStream = clipBuffer(),\n segments,\n polygon,\n ring,\n x__, y__, v__, // first point\n x_, y_, v_, // previous point\n first,\n clean;\n\n var clipStream = {\n point: point,\n lineStart: lineStart,\n lineEnd: lineEnd,\n polygonStart: polygonStart,\n polygonEnd: polygonEnd\n };\n\n function point(x, y) {\n if (visible(x, y)) activeStream.point(x, y);\n }\n\n function polygonInside() {\n var winding = 0;\n\n for (var i = 0, n = polygon.length; i < n; ++i) {\n for (var ring = polygon[i], j = 1, m = ring.length, point = ring[0], a0, a1, b0 = point[0], b1 = point[1]; j < m; ++j) {\n a0 = b0, a1 = b1, point = ring[j], b0 = point[0], b1 = point[1];\n if (a1 <= y1) { if (b1 > y1 && (b0 - a0) * (y1 - a1) > (b1 - a1) * (x0 - a0)) ++winding; }\n else { if (b1 <= y1 && (b0 - a0) * (y1 - a1) < (b1 - a1) * (x0 - a0)) --winding; }\n }\n }\n\n return winding;\n }\n\n // Buffer geometry within a polygon and then clip it en masse.\n function polygonStart() {\n activeStream = bufferStream, segments = [], polygon = [], clean = true;\n }\n\n function polygonEnd() {\n var startInside = polygonInside(),\n cleanInside = clean && startInside,\n visible = (segments = merge(segments)).length;\n if (cleanInside || visible) {\n stream.polygonStart();\n if (cleanInside) {\n stream.lineStart();\n interpolate(null, null, 1, stream);\n stream.lineEnd();\n }\n if (visible) {\n clipRejoin(segments, compareIntersection, startInside, interpolate, stream);\n }\n stream.polygonEnd();\n }\n activeStream = stream, segments = polygon = ring = null;\n }\n\n function lineStart() {\n clipStream.point = linePoint;\n if (polygon) polygon.push(ring = []);\n first = true;\n v_ = false;\n x_ = y_ = NaN;\n }\n\n // TODO rather than special-case polygons, simply handle them separately.\n // Ideally, coincident intersection points should be jittered to avoid\n // clipping issues.\n function lineEnd() {\n if (segments) {\n linePoint(x__, y__);\n if (v__ && v_) bufferStream.rejoin();\n segments.push(bufferStream.result());\n }\n clipStream.point = point;\n if (v_) activeStream.lineEnd();\n }\n\n function linePoint(x, y) {\n var v = visible(x, y);\n if (polygon) ring.push([x, y]);\n if (first) {\n x__ = x, y__ = y, v__ = v;\n first = false;\n if (v) {\n activeStream.lineStart();\n activeStream.point(x, y);\n }\n } else {\n if (v && v_) activeStream.point(x, y);\n else {\n var a = [x_ = Math.max(clipMin, Math.min(clipMax, x_)), y_ = Math.max(clipMin, Math.min(clipMax, y_))],\n b = [x = Math.max(clipMin, Math.min(clipMax, x)), y = Math.max(clipMin, Math.min(clipMax, y))];\n if (clipLine(a, b, x0, y0, x1, y1)) {\n if (!v_) {\n activeStream.lineStart();\n activeStream.point(a[0], a[1]);\n }\n activeStream.point(b[0], b[1]);\n if (!v) activeStream.lineEnd();\n clean = false;\n } else if (v) {\n activeStream.lineStart();\n activeStream.point(x, y);\n clean = false;\n }\n }\n }\n x_ = x, y_ = y, v_ = v;\n }\n\n return clipStream;\n };\n}\n","export default function(a, b, x0, y0, x1, y1) {\n var ax = a[0],\n ay = a[1],\n bx = b[0],\n by = b[1],\n t0 = 0,\n t1 = 1,\n dx = bx - ax,\n dy = by - ay,\n r;\n\n r = x0 - ax;\n if (!dx && r > 0) return;\n r /= dx;\n if (dx < 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n } else if (dx > 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n }\n\n r = x1 - ax;\n if (!dx && r < 0) return;\n r /= dx;\n if (dx < 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n } else if (dx > 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n }\n\n r = y0 - ay;\n if (!dy && r > 0) return;\n r /= dy;\n if (dy < 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n } else if (dy > 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n }\n\n r = y1 - ay;\n if (!dy && r < 0) return;\n r /= dy;\n if (dy < 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n } else if (dy > 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n }\n\n if (t0 > 0) a[0] = ax + t0 * dx, a[1] = ay + t0 * dy;\n if (t1 < 1) b[0] = ax + t1 * dx, b[1] = ay + t1 * dy;\n return true;\n}\n","export default x => x;\n","export default function(methods) {\n return {\n stream: transformer(methods)\n };\n}\n\nexport function transformer(methods) {\n return function(stream) {\n var s = new TransformStream;\n for (var key in methods) s[key] = methods[key];\n s.stream = stream;\n return s;\n };\n}\n\nfunction TransformStream() {}\n\nTransformStream.prototype = {\n constructor: TransformStream,\n point: function(x, y) { this.stream.point(x, y); },\n sphere: function() { this.stream.sphere(); },\n lineStart: function() { this.stream.lineStart(); },\n lineEnd: function() { this.stream.lineEnd(); },\n polygonStart: function() { this.stream.polygonStart(); },\n polygonEnd: function() { this.stream.polygonEnd(); }\n};\n","function streamGeometry(geometry, stream) {\n if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {\n streamGeometryType[geometry.type](geometry, stream);\n }\n}\n\nvar streamObjectType = {\n Feature: function(object, stream) {\n streamGeometry(object.geometry, stream);\n },\n FeatureCollection: function(object, stream) {\n var features = object.features, i = -1, n = features.length;\n while (++i < n) streamGeometry(features[i].geometry, stream);\n }\n};\n\nvar streamGeometryType = {\n Sphere: function(object, stream) {\n stream.sphere();\n },\n Point: function(object, stream) {\n object = object.coordinates;\n stream.point(object[0], object[1], object[2]);\n },\n MultiPoint: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);\n },\n LineString: function(object, stream) {\n streamLine(object.coordinates, stream, 0);\n },\n MultiLineString: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamLine(coordinates[i], stream, 0);\n },\n Polygon: function(object, stream) {\n streamPolygon(object.coordinates, stream);\n },\n MultiPolygon: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamPolygon(coordinates[i], stream);\n },\n GeometryCollection: function(object, stream) {\n var geometries = object.geometries, i = -1, n = geometries.length;\n while (++i < n) streamGeometry(geometries[i], stream);\n }\n};\n\nfunction streamLine(coordinates, stream, closed) {\n var i = -1, n = coordinates.length - closed, coordinate;\n stream.lineStart();\n while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);\n stream.lineEnd();\n}\n\nfunction streamPolygon(coordinates, stream) {\n var i = -1, n = coordinates.length;\n stream.polygonStart();\n while (++i < n) streamLine(coordinates[i], stream, 1);\n stream.polygonEnd();\n}\n\nexport default function(object, stream) {\n if (object && streamObjectType.hasOwnProperty(object.type)) {\n streamObjectType[object.type](object, stream);\n } else {\n streamGeometry(object, stream);\n }\n}\n","import noop from \"../noop.js\";\n\nvar x0 = Infinity,\n y0 = x0,\n x1 = -x0,\n y1 = x1;\n\nvar boundsStream = {\n point: boundsPoint,\n lineStart: noop,\n lineEnd: noop,\n polygonStart: noop,\n polygonEnd: noop,\n result: function() {\n var bounds = [[x0, y0], [x1, y1]];\n x1 = y1 = -(y0 = x0 = Infinity);\n return bounds;\n }\n};\n\nfunction boundsPoint(x, y) {\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n}\n\nexport default boundsStream;\n","import {default as geoStream} from \"../stream.js\";\nimport boundsStream from \"../path/bounds.js\";\n\nfunction fit(projection, fitBounds, object) {\n var clip = projection.clipExtent && projection.clipExtent();\n projection.scale(150).translate([0, 0]);\n if (clip != null) projection.clipExtent(null);\n geoStream(object, projection.stream(boundsStream));\n fitBounds(boundsStream.result());\n if (clip != null) projection.clipExtent(clip);\n return projection;\n}\n\nexport function fitExtent(projection, extent, object) {\n return fit(projection, function(b) {\n var w = extent[1][0] - extent[0][0],\n h = extent[1][1] - extent[0][1],\n k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])),\n x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2,\n y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;\n projection.scale(150 * k).translate([x, y]);\n }, object);\n}\n\nexport function fitSize(projection, size, object) {\n return fitExtent(projection, [[0, 0], size], object);\n}\n\nexport function fitWidth(projection, width, object) {\n return fit(projection, function(b) {\n var w = +width,\n k = w / (b[1][0] - b[0][0]),\n x = (w - k * (b[1][0] + b[0][0])) / 2,\n y = -k * b[0][1];\n projection.scale(150 * k).translate([x, y]);\n }, object);\n}\n\nexport function fitHeight(projection, height, object) {\n return fit(projection, function(b) {\n var h = +height,\n k = h / (b[1][1] - b[0][1]),\n x = -k * b[0][0],\n y = (h - k * (b[1][1] + b[0][1])) / 2;\n projection.scale(150 * k).translate([x, y]);\n }, object);\n}\n","import {cartesian} from \"../cartesian.js\";\nimport {abs, asin, atan2, cos, epsilon, radians, sqrt} from \"../math.js\";\nimport {transformer} from \"../transform.js\";\n\nvar maxDepth = 16, // maximum depth of subdivision\n cosMinDistance = cos(30 * radians); // cos(minimum angular distance)\n\nexport default function(project, delta2) {\n return +delta2 ? resample(project, delta2) : resampleNone(project);\n}\n\nfunction resampleNone(project) {\n return transformer({\n point: function(x, y) {\n x = project(x, y);\n this.stream.point(x[0], x[1]);\n }\n });\n}\n\nfunction resample(project, delta2) {\n\n function resampleLineTo(x0, y0, lambda0, a0, b0, c0, x1, y1, lambda1, a1, b1, c1, depth, stream) {\n var dx = x1 - x0,\n dy = y1 - y0,\n d2 = dx * dx + dy * dy;\n if (d2 > 4 * delta2 && depth--) {\n var a = a0 + a1,\n b = b0 + b1,\n c = c0 + c1,\n m = sqrt(a * a + b * b + c * c),\n phi2 = asin(c /= m),\n lambda2 = abs(abs(c) - 1) < epsilon || abs(lambda0 - lambda1) < epsilon ? (lambda0 + lambda1) / 2 : atan2(b, a),\n p = project(lambda2, phi2),\n x2 = p[0],\n y2 = p[1],\n dx2 = x2 - x0,\n dy2 = y2 - y0,\n dz = dy * dx2 - dx * dy2;\n if (dz * dz / d2 > delta2 // perpendicular projected distance\n || abs((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 // midpoint close to an end\n || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { // angular distance\n resampleLineTo(x0, y0, lambda0, a0, b0, c0, x2, y2, lambda2, a /= m, b /= m, c, depth, stream);\n stream.point(x2, y2);\n resampleLineTo(x2, y2, lambda2, a, b, c, x1, y1, lambda1, a1, b1, c1, depth, stream);\n }\n }\n }\n return function(stream) {\n var lambda00, x00, y00, a00, b00, c00, // first point\n lambda0, x0, y0, a0, b0, c0; // previous point\n\n var resampleStream = {\n point: point,\n lineStart: lineStart,\n lineEnd: lineEnd,\n polygonStart: function() { stream.polygonStart(); resampleStream.lineStart = ringStart; },\n polygonEnd: function() { stream.polygonEnd(); resampleStream.lineStart = lineStart; }\n };\n\n function point(x, y) {\n x = project(x, y);\n stream.point(x[0], x[1]);\n }\n\n function lineStart() {\n x0 = NaN;\n resampleStream.point = linePoint;\n stream.lineStart();\n }\n\n function linePoint(lambda, phi) {\n var c = cartesian([lambda, phi]), p = project(lambda, phi);\n resampleLineTo(x0, y0, lambda0, a0, b0, c0, x0 = p[0], y0 = p[1], lambda0 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);\n stream.point(x0, y0);\n }\n\n function lineEnd() {\n resampleStream.point = point;\n stream.lineEnd();\n }\n\n function ringStart() {\n lineStart();\n resampleStream.point = ringPoint;\n resampleStream.lineEnd = ringEnd;\n }\n\n function ringPoint(lambda, phi) {\n linePoint(lambda00 = lambda, phi), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;\n resampleStream.point = linePoint;\n }\n\n function ringEnd() {\n resampleLineTo(x0, y0, lambda0, a0, b0, c0, x00, y00, lambda00, a00, b00, c00, maxDepth, stream);\n resampleStream.lineEnd = lineEnd;\n lineEnd();\n }\n\n return resampleStream;\n };\n}\n","import clipAntimeridian from \"../clip/antimeridian.js\";\nimport clipCircle from \"../clip/circle.js\";\nimport clipRectangle from \"../clip/rectangle.js\";\nimport compose from \"../compose.js\";\nimport identity from \"../identity.js\";\nimport {cos, degrees, radians, sin, sqrt} from \"../math.js\";\nimport {rotateRadians} from \"../rotation.js\";\nimport {transformer} from \"../transform.js\";\nimport {fitExtent, fitSize, fitWidth, fitHeight} from \"./fit.js\";\nimport resample from \"./resample.js\";\n\nvar transformRadians = transformer({\n point: function(x, y) {\n this.stream.point(x * radians, y * radians);\n }\n});\n\nfunction transformRotate(rotate) {\n return transformer({\n point: function(x, y) {\n var r = rotate(x, y);\n return this.stream.point(r[0], r[1]);\n }\n });\n}\n\nfunction scaleTranslate(k, dx, dy, sx, sy) {\n function transform(x, y) {\n x *= sx; y *= sy;\n return [dx + k * x, dy - k * y];\n }\n transform.invert = function(x, y) {\n return [(x - dx) / k * sx, (dy - y) / k * sy];\n };\n return transform;\n}\n\nfunction scaleTranslateRotate(k, dx, dy, sx, sy, alpha) {\n if (!alpha) return scaleTranslate(k, dx, dy, sx, sy);\n var cosAlpha = cos(alpha),\n sinAlpha = sin(alpha),\n a = cosAlpha * k,\n b = sinAlpha * k,\n ai = cosAlpha / k,\n bi = sinAlpha / k,\n ci = (sinAlpha * dy - cosAlpha * dx) / k,\n fi = (sinAlpha * dx + cosAlpha * dy) / k;\n function transform(x, y) {\n x *= sx; y *= sy;\n return [a * x - b * y + dx, dy - b * x - a * y];\n }\n transform.invert = function(x, y) {\n return [sx * (ai * x - bi * y + ci), sy * (fi - bi * x - ai * y)];\n };\n return transform;\n}\n\nexport default function projection(project) {\n return projectionMutator(function() { return project; })();\n}\n\nexport function projectionMutator(projectAt) {\n var project,\n k = 150, // scale\n x = 480, y = 250, // translate\n lambda = 0, phi = 0, // center\n deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, // pre-rotate\n alpha = 0, // post-rotate angle\n sx = 1, // reflectX\n sy = 1, // reflectX\n theta = null, preclip = clipAntimeridian, // pre-clip angle\n x0 = null, y0, x1, y1, postclip = identity, // post-clip extent\n delta2 = 0.5, // precision\n projectResample,\n projectTransform,\n projectRotateTransform,\n cache,\n cacheStream;\n\n function projection(point) {\n return projectRotateTransform(point[0] * radians, point[1] * radians);\n }\n\n function invert(point) {\n point = projectRotateTransform.invert(point[0], point[1]);\n return point && [point[0] * degrees, point[1] * degrees];\n }\n\n projection.stream = function(stream) {\n return cache && cacheStream === stream ? cache : cache = transformRadians(transformRotate(rotate)(preclip(projectResample(postclip(cacheStream = stream)))));\n };\n\n projection.preclip = function(_) {\n return arguments.length ? (preclip = _, theta = undefined, reset()) : preclip;\n };\n\n projection.postclip = function(_) {\n return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;\n };\n\n projection.clipAngle = function(_) {\n return arguments.length ? (preclip = +_ ? clipCircle(theta = _ * radians) : (theta = null, clipAntimeridian), reset()) : theta * degrees;\n };\n\n projection.clipExtent = function(_) {\n return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];\n };\n\n projection.scale = function(_) {\n return arguments.length ? (k = +_, recenter()) : k;\n };\n\n projection.translate = function(_) {\n return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [x, y];\n };\n\n projection.center = function(_) {\n return arguments.length ? (lambda = _[0] % 360 * radians, phi = _[1] % 360 * radians, recenter()) : [lambda * degrees, phi * degrees];\n };\n\n projection.rotate = function(_) {\n return arguments.length ? (deltaLambda = _[0] % 360 * radians, deltaPhi = _[1] % 360 * radians, deltaGamma = _.length > 2 ? _[2] % 360 * radians : 0, recenter()) : [deltaLambda * degrees, deltaPhi * degrees, deltaGamma * degrees];\n };\n\n projection.angle = function(_) {\n return arguments.length ? (alpha = _ % 360 * radians, recenter()) : alpha * degrees;\n };\n\n projection.reflectX = function(_) {\n return arguments.length ? (sx = _ ? -1 : 1, recenter()) : sx < 0;\n };\n\n projection.reflectY = function(_) {\n return arguments.length ? (sy = _ ? -1 : 1, recenter()) : sy < 0;\n };\n\n projection.precision = function(_) {\n return arguments.length ? (projectResample = resample(projectTransform, delta2 = _ * _), reset()) : sqrt(delta2);\n };\n\n projection.fitExtent = function(extent, object) {\n return fitExtent(projection, extent, object);\n };\n\n projection.fitSize = function(size, object) {\n return fitSize(projection, size, object);\n };\n\n projection.fitWidth = function(width, object) {\n return fitWidth(projection, width, object);\n };\n\n projection.fitHeight = function(height, object) {\n return fitHeight(projection, height, object);\n };\n\n function recenter() {\n var center = scaleTranslateRotate(k, 0, 0, sx, sy, alpha).apply(null, project(lambda, phi)),\n transform = scaleTranslateRotate(k, x - center[0], y - center[1], sx, sy, alpha);\n rotate = rotateRadians(deltaLambda, deltaPhi, deltaGamma);\n projectTransform = compose(project, transform);\n projectRotateTransform = compose(rotate, projectTransform);\n projectResample = resample(projectTransform, delta2);\n return reset();\n }\n\n function reset() {\n cache = cacheStream = null;\n return projection;\n }\n\n return function() {\n project = projectAt.apply(this, arguments);\n projection.invert = project.invert && invert;\n return recenter();\n };\n}\n","export var abs = Math.abs;\nexport var atan = Math.atan;\nexport var atan2 = Math.atan2;\nexport var ceil = Math.ceil;\nexport var cos = Math.cos;\nexport var exp = Math.exp;\nexport var floor = Math.floor;\nexport var log = Math.log;\nexport var max = Math.max;\nexport var min = Math.min;\nexport var pow = Math.pow;\nexport var round = Math.round;\nexport var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };\nexport var sin = Math.sin;\nexport var tan = Math.tan;\n\nexport var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var quarterPi = pi / 4;\nexport var sqrt1_2 = Math.SQRT1_2;\nexport var sqrt2 = sqrt(2);\nexport var sqrtPi = sqrt(pi);\nexport var tau = pi * 2;\nexport var degrees = 180 / pi;\nexport var radians = pi / 180;\n\nexport function sinci(x) {\n return x ? x / Math.sin(x) : 1;\n}\n\nexport function asin(x) {\n return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);\n}\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function sqrt(x) {\n return x > 0 ? Math.sqrt(x) : 0;\n}\n\nexport function tanh(x) {\n x = exp(2 * x);\n return (x - 1) / (x + 1);\n}\n\nexport function sinh(x) {\n return (exp(x) - exp(-x)) / 2;\n}\n\nexport function cosh(x) {\n return (exp(x) + exp(-x)) / 2;\n}\n\nexport function arsinh(x) {\n return log(x + sqrt(x * x + 1));\n}\n\nexport function arcosh(x) {\n return log(x + sqrt(x * x - 1));\n}\n","import {geoProjection as projection} from \"d3-geo\";\nimport {abs, asin, cos, epsilon, halfPi, pi, sin, sqrt2} from \"./math.js\";\n\nexport function mollweideBromleyTheta(cp, phi) {\n var cpsinPhi = cp * sin(phi), i = 30, delta;\n do phi -= delta = (phi + sin(phi) - cpsinPhi) / (1 + cos(phi));\n while (abs(delta) > epsilon && --i > 0);\n return phi / 2;\n}\n\nexport function mollweideBromleyRaw(cx, cy, cp) {\n\n function forward(lambda, phi) {\n return [cx * lambda * cos(phi = mollweideBromleyTheta(cp, phi)), cy * sin(phi)];\n }\n\n forward.invert = function(x, y) {\n return y = asin(y / cy), [x / (cx * cos(y)), asin((2 * y + sin(2 * y)) / cp)];\n };\n\n return forward;\n}\n\nexport var mollweideRaw = mollweideBromleyRaw(sqrt2 / halfPi, sqrt2, pi);\n\nexport default function() {\n return projection(mollweideRaw)\n .scale(169.529);\n}\n","import { geoPath, geoAlbers, geoAlbersUsa, geoAzimuthalEqualArea, geoAzimuthalEquidistant, geoConicConformal, geoConicEqualArea, geoConicEquidistant, geoEqualEarth, geoEquirectangular, geoGnomonic, geoIdentity, geoMercator, geoNaturalEarth1, geoOrthographic, geoStereographic, geoTransverseMercator } from 'd3-geo';\nimport { geoMollweide } from 'd3-geo-projection';\n\nconst defaultPath = geoPath();\nconst projectionProperties = [// standard properties in d3-geo\n'clipAngle', 'clipExtent', 'scale', 'translate', 'center', 'rotate', 'parallels', 'precision', 'reflectX', 'reflectY', // extended properties in d3-geo-projections\n'coefficient', 'distance', 'fraction', 'lobes', 'parallel', 'radius', 'ratio', 'spacing', 'tilt'];\n/**\n * Augment projections with their type and a copy method.\n */\n\nfunction create(type, constructor) {\n return function projection() {\n const p = constructor();\n p.type = type;\n p.path = geoPath().projection(p);\n\n p.copy = p.copy || function () {\n const c = projection();\n projectionProperties.forEach(prop => {\n if (p[prop]) c[prop](p[prop]());\n });\n c.path.pointRadius(p.path.pointRadius());\n return c;\n };\n\n return p;\n };\n}\n\nfunction projection(type, proj) {\n if (!type || typeof type !== 'string') {\n throw new Error('Projection type must be a name string.');\n }\n\n type = type.toLowerCase();\n\n if (arguments.length > 1) {\n projections[type] = create(type, proj);\n return this;\n } else {\n return projections[type] || null;\n }\n}\nfunction getProjectionPath(proj) {\n return proj && proj.path || defaultPath;\n}\nconst projections = {\n // base d3-geo projection types\n albers: geoAlbers,\n albersusa: geoAlbersUsa,\n azimuthalequalarea: geoAzimuthalEqualArea,\n azimuthalequidistant: geoAzimuthalEquidistant,\n conicconformal: geoConicConformal,\n conicequalarea: geoConicEqualArea,\n conicequidistant: geoConicEquidistant,\n equalEarth: geoEqualEarth,\n equirectangular: geoEquirectangular,\n gnomonic: geoGnomonic,\n identity: geoIdentity,\n mercator: geoMercator,\n mollweide: geoMollweide,\n naturalEarth1: geoNaturalEarth1,\n orthographic: geoOrthographic,\n stereographic: geoStereographic,\n transversemercator: geoTransverseMercator\n};\n\nfor (const key in projections) {\n projection(key, projections[key]);\n}\n\nexport { getProjectionPath, projection, projectionProperties };\n","import {epsilon} from \"../math.js\";\nimport albers from \"./albers.js\";\nimport conicEqualArea from \"./conicEqualArea.js\";\nimport {fitExtent, fitSize, fitWidth, fitHeight} from \"./fit.js\";\n\n// The projections must have mutually exclusive clip regions on the sphere,\n// as this will avoid emitting interleaving lines and polygons.\nfunction multiplex(streams) {\n var n = streams.length;\n return {\n point: function(x, y) { var i = -1; while (++i < n) streams[i].point(x, y); },\n sphere: function() { var i = -1; while (++i < n) streams[i].sphere(); },\n lineStart: function() { var i = -1; while (++i < n) streams[i].lineStart(); },\n lineEnd: function() { var i = -1; while (++i < n) streams[i].lineEnd(); },\n polygonStart: function() { var i = -1; while (++i < n) streams[i].polygonStart(); },\n polygonEnd: function() { var i = -1; while (++i < n) streams[i].polygonEnd(); }\n };\n}\n\n// A composite projection for the United States, configured by default for\n// 960×500. The projection also works quite well at 960×600 if you change the\n// scale to 1285 and adjust the translate accordingly. The set of standard\n// parallels for each region comes from USGS, which is published here:\n// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers\nexport default function() {\n var cache,\n cacheStream,\n lower48 = albers(), lower48Point,\n alaska = conicEqualArea().rotate([154, 0]).center([-2, 58.5]).parallels([55, 65]), alaskaPoint, // EPSG:3338\n hawaii = conicEqualArea().rotate([157, 0]).center([-3, 19.9]).parallels([8, 18]), hawaiiPoint, // ESRI:102007\n point, pointStream = {point: function(x, y) { point = [x, y]; }};\n\n function albersUsa(coordinates) {\n var x = coordinates[0], y = coordinates[1];\n return point = null,\n (lower48Point.point(x, y), point)\n || (alaskaPoint.point(x, y), point)\n || (hawaiiPoint.point(x, y), point);\n }\n\n albersUsa.invert = function(coordinates) {\n var k = lower48.scale(),\n t = lower48.translate(),\n x = (coordinates[0] - t[0]) / k,\n y = (coordinates[1] - t[1]) / k;\n return (y >= 0.120 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska\n : y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii\n : lower48).invert(coordinates);\n };\n\n albersUsa.stream = function(stream) {\n return cache && cacheStream === stream ? cache : cache = multiplex([lower48.stream(cacheStream = stream), alaska.stream(stream), hawaii.stream(stream)]);\n };\n\n albersUsa.precision = function(_) {\n if (!arguments.length) return lower48.precision();\n lower48.precision(_), alaska.precision(_), hawaii.precision(_);\n return reset();\n };\n\n albersUsa.scale = function(_) {\n if (!arguments.length) return lower48.scale();\n lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_);\n return albersUsa.translate(lower48.translate());\n };\n\n albersUsa.translate = function(_) {\n if (!arguments.length) return lower48.translate();\n var k = lower48.scale(), x = +_[0], y = +_[1];\n\n lower48Point = lower48\n .translate(_)\n .clipExtent([[x - 0.455 * k, y - 0.238 * k], [x + 0.455 * k, y + 0.238 * k]])\n .stream(pointStream);\n\n alaskaPoint = alaska\n .translate([x - 0.307 * k, y + 0.201 * k])\n .clipExtent([[x - 0.425 * k + epsilon, y + 0.120 * k + epsilon], [x - 0.214 * k - epsilon, y + 0.234 * k - epsilon]])\n .stream(pointStream);\n\n hawaiiPoint = hawaii\n .translate([x - 0.205 * k, y + 0.212 * k])\n .clipExtent([[x - 0.214 * k + epsilon, y + 0.166 * k + epsilon], [x - 0.115 * k - epsilon, y + 0.234 * k - epsilon]])\n .stream(pointStream);\n\n return reset();\n };\n\n albersUsa.fitExtent = function(extent, object) {\n return fitExtent(albersUsa, extent, object);\n };\n\n albersUsa.fitSize = function(size, object) {\n return fitSize(albersUsa, size, object);\n };\n\n albersUsa.fitWidth = function(width, object) {\n return fitWidth(albersUsa, width, object);\n };\n\n albersUsa.fitHeight = function(height, object) {\n return fitHeight(albersUsa, height, object);\n };\n\n function reset() {\n cache = cacheStream = null;\n return albersUsa;\n }\n\n return albersUsa.scale(1070);\n}\n","import clipRectangle from \"../clip/rectangle.js\";\nimport identity from \"../identity.js\";\nimport {transformer} from \"../transform.js\";\nimport {fitExtent, fitSize, fitWidth, fitHeight} from \"./fit.js\";\nimport {cos, degrees, radians, sin} from \"../math.js\";\n\nexport default function() {\n var k = 1, tx = 0, ty = 0, sx = 1, sy = 1, // scale, translate and reflect\n alpha = 0, ca, sa, // angle\n x0 = null, y0, x1, y1, // clip extent\n kx = 1, ky = 1,\n transform = transformer({\n point: function(x, y) {\n var p = projection([x, y])\n this.stream.point(p[0], p[1]);\n }\n }),\n postclip = identity,\n cache,\n cacheStream;\n\n function reset() {\n kx = k * sx;\n ky = k * sy;\n cache = cacheStream = null;\n return projection;\n }\n\n function projection (p) {\n var x = p[0] * kx, y = p[1] * ky;\n if (alpha) {\n var t = y * ca - x * sa;\n x = x * ca + y * sa;\n y = t;\n } \n return [x + tx, y + ty];\n }\n projection.invert = function(p) {\n var x = p[0] - tx, y = p[1] - ty;\n if (alpha) {\n var t = y * ca + x * sa;\n x = x * ca - y * sa;\n y = t;\n }\n return [x / kx, y / ky];\n };\n projection.stream = function(stream) {\n return cache && cacheStream === stream ? cache : cache = transform(postclip(cacheStream = stream));\n };\n projection.postclip = function(_) {\n return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;\n };\n projection.clipExtent = function(_) {\n return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];\n };\n projection.scale = function(_) {\n return arguments.length ? (k = +_, reset()) : k;\n };\n projection.translate = function(_) {\n return arguments.length ? (tx = +_[0], ty = +_[1], reset()) : [tx, ty];\n }\n projection.angle = function(_) {\n return arguments.length ? (alpha = _ % 360 * radians, sa = sin(alpha), ca = cos(alpha), reset()) : alpha * degrees;\n };\n projection.reflectX = function(_) {\n return arguments.length ? (sx = _ ? -1 : 1, reset()) : sx < 0;\n };\n projection.reflectY = function(_) {\n return arguments.length ? (sy = _ ? -1 : 1, reset()) : sy < 0;\n };\n projection.fitExtent = function(extent, object) {\n return fitExtent(projection, extent, object);\n };\n projection.fitSize = function(size, object) {\n return fitSize(projection, size, object);\n };\n projection.fitWidth = function(width, object) {\n return fitWidth(projection, width, object);\n };\n projection.fitHeight = function(height, object) {\n return fitHeight(projection, height, object);\n };\n\n return projection;\n}\n","export var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var quarterPi = pi / 4;\nexport var tau = pi * 2;\n\nexport var degrees = 180 / pi;\nexport var radians = pi / 180;\n\nexport var abs = Math.abs;\nexport var atan = Math.atan;\nexport var atan2 = Math.atan2;\nexport var cos = Math.cos;\nexport var ceil = Math.ceil;\nexport var exp = Math.exp;\nexport var floor = Math.floor;\nexport var hypot = Math.hypot;\nexport var log = Math.log;\nexport var pow = Math.pow;\nexport var sin = Math.sin;\nexport var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };\nexport var sqrt = Math.sqrt;\nexport var tan = Math.tan;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);\n}\n\nexport function haversin(x) {\n return (x = sin(x / 2)) * x;\n}\n","import {range} from \"d3-array\";\nimport {abs, ceil, epsilon} from \"./math.js\";\n\nfunction graticuleX(y0, y1, dy) {\n var y = range(y0, y1 - epsilon, dy).concat(y1);\n return function(x) { return y.map(function(y) { return [x, y]; }); };\n}\n\nfunction graticuleY(x0, x1, dx) {\n var x = range(x0, x1 - epsilon, dx).concat(x1);\n return function(y) { return x.map(function(x) { return [x, y]; }); };\n}\n\nexport default function graticule() {\n var x1, x0, X1, X0,\n y1, y0, Y1, Y0,\n dx = 10, dy = dx, DX = 90, DY = 360,\n x, y, X, Y,\n precision = 2.5;\n\n function graticule() {\n return {type: \"MultiLineString\", coordinates: lines()};\n }\n\n function lines() {\n return range(ceil(X0 / DX) * DX, X1, DX).map(X)\n .concat(range(ceil(Y0 / DY) * DY, Y1, DY).map(Y))\n .concat(range(ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return abs(x % DX) > epsilon; }).map(x))\n .concat(range(ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return abs(y % DY) > epsilon; }).map(y));\n }\n\n graticule.lines = function() {\n return lines().map(function(coordinates) { return {type: \"LineString\", coordinates: coordinates}; });\n };\n\n graticule.outline = function() {\n return {\n type: \"Polygon\",\n coordinates: [\n X(X0).concat(\n Y(Y1).slice(1),\n X(X1).reverse().slice(1),\n Y(Y0).reverse().slice(1))\n ]\n };\n };\n\n graticule.extent = function(_) {\n if (!arguments.length) return graticule.extentMinor();\n return graticule.extentMajor(_).extentMinor(_);\n };\n\n graticule.extentMajor = function(_) {\n if (!arguments.length) return [[X0, Y0], [X1, Y1]];\n X0 = +_[0][0], X1 = +_[1][0];\n Y0 = +_[0][1], Y1 = +_[1][1];\n if (X0 > X1) _ = X0, X0 = X1, X1 = _;\n if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;\n return graticule.precision(precision);\n };\n\n graticule.extentMinor = function(_) {\n if (!arguments.length) return [[x0, y0], [x1, y1]];\n x0 = +_[0][0], x1 = +_[1][0];\n y0 = +_[0][1], y1 = +_[1][1];\n if (x0 > x1) _ = x0, x0 = x1, x1 = _;\n if (y0 > y1) _ = y0, y0 = y1, y1 = _;\n return graticule.precision(precision);\n };\n\n graticule.step = function(_) {\n if (!arguments.length) return graticule.stepMinor();\n return graticule.stepMajor(_).stepMinor(_);\n };\n\n graticule.stepMajor = function(_) {\n if (!arguments.length) return [DX, DY];\n DX = +_[0], DY = +_[1];\n return graticule;\n };\n\n graticule.stepMinor = function(_) {\n if (!arguments.length) return [dx, dy];\n dx = +_[0], dy = +_[1];\n return graticule;\n };\n\n graticule.precision = function(_) {\n if (!arguments.length) return precision;\n precision = +_;\n x = graticuleX(y0, y1, 90);\n y = graticuleY(x0, x1, precision);\n X = graticuleX(Y0, Y1, 90);\n Y = graticuleY(X0, X1, precision);\n return graticule;\n };\n\n return graticule\n .extentMajor([[-180, -90 + epsilon], [180, 90 - epsilon]])\n .extentMinor([[-180, -80 - epsilon], [180, 80 + epsilon]]);\n}\n\nexport function graticule10() {\n return graticule()();\n}\n","export default function(constructor, factory, prototype) {\n constructor.prototype = factory.prototype = prototype;\n prototype.constructor = constructor;\n}\n\nexport function extend(parent, definition) {\n var prototype = Object.create(parent.prototype);\n for (var key in definition) prototype[key] = definition[key];\n return prototype;\n}\n","import define, {extend} from \"./define.js\";\n\nexport function Color() {}\n\nexport var darker = 0.7;\nexport var brighter = 1 / darker;\n\nvar reI = \"\\\\s*([+-]?\\\\d+)\\\\s*\",\n reN = \"\\\\s*([+-]?\\\\d*\\\\.?\\\\d+(?:[eE][+-]?\\\\d+)?)\\\\s*\",\n reP = \"\\\\s*([+-]?\\\\d*\\\\.?\\\\d+(?:[eE][+-]?\\\\d+)?)%\\\\s*\",\n reHex = /^#([0-9a-f]{3,8})$/,\n reRgbInteger = new RegExp(\"^rgb\\\\(\" + [reI, reI, reI] + \"\\\\)$\"),\n reRgbPercent = new RegExp(\"^rgb\\\\(\" + [reP, reP, reP] + \"\\\\)$\"),\n reRgbaInteger = new RegExp(\"^rgba\\\\(\" + [reI, reI, reI, reN] + \"\\\\)$\"),\n reRgbaPercent = new RegExp(\"^rgba\\\\(\" + [reP, reP, reP, reN] + \"\\\\)$\"),\n reHslPercent = new RegExp(\"^hsl\\\\(\" + [reN, reP, reP] + \"\\\\)$\"),\n reHslaPercent = new RegExp(\"^hsla\\\\(\" + [reN, reP, reP, reN] + \"\\\\)$\");\n\nvar named = {\n aliceblue: 0xf0f8ff,\n antiquewhite: 0xfaebd7,\n aqua: 0x00ffff,\n aquamarine: 0x7fffd4,\n azure: 0xf0ffff,\n beige: 0xf5f5dc,\n bisque: 0xffe4c4,\n black: 0x000000,\n blanchedalmond: 0xffebcd,\n blue: 0x0000ff,\n blueviolet: 0x8a2be2,\n brown: 0xa52a2a,\n burlywood: 0xdeb887,\n cadetblue: 0x5f9ea0,\n chartreuse: 0x7fff00,\n chocolate: 0xd2691e,\n coral: 0xff7f50,\n cornflowerblue: 0x6495ed,\n cornsilk: 0xfff8dc,\n crimson: 0xdc143c,\n cyan: 0x00ffff,\n darkblue: 0x00008b,\n darkcyan: 0x008b8b,\n darkgoldenrod: 0xb8860b,\n darkgray: 0xa9a9a9,\n darkgreen: 0x006400,\n darkgrey: 0xa9a9a9,\n darkkhaki: 0xbdb76b,\n darkmagenta: 0x8b008b,\n darkolivegreen: 0x556b2f,\n darkorange: 0xff8c00,\n darkorchid: 0x9932cc,\n darkred: 0x8b0000,\n darksalmon: 0xe9967a,\n darkseagreen: 0x8fbc8f,\n darkslateblue: 0x483d8b,\n darkslategray: 0x2f4f4f,\n darkslategrey: 0x2f4f4f,\n darkturquoise: 0x00ced1,\n darkviolet: 0x9400d3,\n deeppink: 0xff1493,\n deepskyblue: 0x00bfff,\n dimgray: 0x696969,\n dimgrey: 0x696969,\n dodgerblue: 0x1e90ff,\n firebrick: 0xb22222,\n floralwhite: 0xfffaf0,\n forestgreen: 0x228b22,\n fuchsia: 0xff00ff,\n gainsboro: 0xdcdcdc,\n ghostwhite: 0xf8f8ff,\n gold: 0xffd700,\n goldenrod: 0xdaa520,\n gray: 0x808080,\n green: 0x008000,\n greenyellow: 0xadff2f,\n grey: 0x808080,\n honeydew: 0xf0fff0,\n hotpink: 0xff69b4,\n indianred: 0xcd5c5c,\n indigo: 0x4b0082,\n ivory: 0xfffff0,\n khaki: 0xf0e68c,\n lavender: 0xe6e6fa,\n lavenderblush: 0xfff0f5,\n lawngreen: 0x7cfc00,\n lemonchiffon: 0xfffacd,\n lightblue: 0xadd8e6,\n lightcoral: 0xf08080,\n lightcyan: 0xe0ffff,\n lightgoldenrodyellow: 0xfafad2,\n lightgray: 0xd3d3d3,\n lightgreen: 0x90ee90,\n lightgrey: 0xd3d3d3,\n lightpink: 0xffb6c1,\n lightsalmon: 0xffa07a,\n lightseagreen: 0x20b2aa,\n lightskyblue: 0x87cefa,\n lightslategray: 0x778899,\n lightslategrey: 0x778899,\n lightsteelblue: 0xb0c4de,\n lightyellow: 0xffffe0,\n lime: 0x00ff00,\n limegreen: 0x32cd32,\n linen: 0xfaf0e6,\n magenta: 0xff00ff,\n maroon: 0x800000,\n mediumaquamarine: 0x66cdaa,\n mediumblue: 0x0000cd,\n mediumorchid: 0xba55d3,\n mediumpurple: 0x9370db,\n mediumseagreen: 0x3cb371,\n mediumslateblue: 0x7b68ee,\n mediumspringgreen: 0x00fa9a,\n mediumturquoise: 0x48d1cc,\n mediumvioletred: 0xc71585,\n midnightblue: 0x191970,\n mintcream: 0xf5fffa,\n mistyrose: 0xffe4e1,\n moccasin: 0xffe4b5,\n navajowhite: 0xffdead,\n navy: 0x000080,\n oldlace: 0xfdf5e6,\n olive: 0x808000,\n olivedrab: 0x6b8e23,\n orange: 0xffa500,\n orangered: 0xff4500,\n orchid: 0xda70d6,\n palegoldenrod: 0xeee8aa,\n palegreen: 0x98fb98,\n paleturquoise: 0xafeeee,\n palevioletred: 0xdb7093,\n papayawhip: 0xffefd5,\n peachpuff: 0xffdab9,\n peru: 0xcd853f,\n pink: 0xffc0cb,\n plum: 0xdda0dd,\n powderblue: 0xb0e0e6,\n purple: 0x800080,\n rebeccapurple: 0x663399,\n red: 0xff0000,\n rosybrown: 0xbc8f8f,\n royalblue: 0x4169e1,\n saddlebrown: 0x8b4513,\n salmon: 0xfa8072,\n sandybrown: 0xf4a460,\n seagreen: 0x2e8b57,\n seashell: 0xfff5ee,\n sienna: 0xa0522d,\n silver: 0xc0c0c0,\n skyblue: 0x87ceeb,\n slateblue: 0x6a5acd,\n slategray: 0x708090,\n slategrey: 0x708090,\n snow: 0xfffafa,\n springgreen: 0x00ff7f,\n steelblue: 0x4682b4,\n tan: 0xd2b48c,\n teal: 0x008080,\n thistle: 0xd8bfd8,\n tomato: 0xff6347,\n turquoise: 0x40e0d0,\n violet: 0xee82ee,\n wheat: 0xf5deb3,\n white: 0xffffff,\n whitesmoke: 0xf5f5f5,\n yellow: 0xffff00,\n yellowgreen: 0x9acd32\n};\n\ndefine(Color, color, {\n copy: function(channels) {\n return Object.assign(new this.constructor, this, channels);\n },\n displayable: function() {\n return this.rgb().displayable();\n },\n hex: color_formatHex, // Deprecated! Use color.formatHex.\n formatHex: color_formatHex,\n formatHsl: color_formatHsl,\n formatRgb: color_formatRgb,\n toString: color_formatRgb\n});\n\nfunction color_formatHex() {\n return this.rgb().formatHex();\n}\n\nfunction color_formatHsl() {\n return hslConvert(this).formatHsl();\n}\n\nfunction color_formatRgb() {\n return this.rgb().formatRgb();\n}\n\nexport default function color(format) {\n var m, l;\n format = (format + \"\").trim().toLowerCase();\n return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000\n : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00\n : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000\n : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000\n : null) // invalid hex\n : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)\n : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)\n : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)\n : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)\n : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)\n : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)\n : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins\n : format === \"transparent\" ? new Rgb(NaN, NaN, NaN, 0)\n : null;\n}\n\nfunction rgbn(n) {\n return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);\n}\n\nfunction rgba(r, g, b, a) {\n if (a <= 0) r = g = b = NaN;\n return new Rgb(r, g, b, a);\n}\n\nexport function rgbConvert(o) {\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Rgb;\n o = o.rgb();\n return new Rgb(o.r, o.g, o.b, o.opacity);\n}\n\nexport function rgb(r, g, b, opacity) {\n return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);\n}\n\nexport function Rgb(r, g, b, opacity) {\n this.r = +r;\n this.g = +g;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Rgb, rgb, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n rgb: function() {\n return this;\n },\n displayable: function() {\n return (-0.5 <= this.r && this.r < 255.5)\n && (-0.5 <= this.g && this.g < 255.5)\n && (-0.5 <= this.b && this.b < 255.5)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n hex: rgb_formatHex, // Deprecated! Use color.formatHex.\n formatHex: rgb_formatHex,\n formatRgb: rgb_formatRgb,\n toString: rgb_formatRgb\n}));\n\nfunction rgb_formatHex() {\n return \"#\" + hex(this.r) + hex(this.g) + hex(this.b);\n}\n\nfunction rgb_formatRgb() {\n var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));\n return (a === 1 ? \"rgb(\" : \"rgba(\")\n + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + \", \"\n + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + \", \"\n + Math.max(0, Math.min(255, Math.round(this.b) || 0))\n + (a === 1 ? \")\" : \", \" + a + \")\");\n}\n\nfunction hex(value) {\n value = Math.max(0, Math.min(255, Math.round(value) || 0));\n return (value < 16 ? \"0\" : \"\") + value.toString(16);\n}\n\nfunction hsla(h, s, l, a) {\n if (a <= 0) h = s = l = NaN;\n else if (l <= 0 || l >= 1) h = s = NaN;\n else if (s <= 0) h = NaN;\n return new Hsl(h, s, l, a);\n}\n\nexport function hslConvert(o) {\n if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Hsl;\n if (o instanceof Hsl) return o;\n o = o.rgb();\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n min = Math.min(r, g, b),\n max = Math.max(r, g, b),\n h = NaN,\n s = max - min,\n l = (max + min) / 2;\n if (s) {\n if (r === max) h = (g - b) / s + (g < b) * 6;\n else if (g === max) h = (b - r) / s + 2;\n else h = (r - g) / s + 4;\n s /= l < 0.5 ? max + min : 2 - max - min;\n h *= 60;\n } else {\n s = l > 0 && l < 1 ? 0 : h;\n }\n return new Hsl(h, s, l, o.opacity);\n}\n\nexport function hsl(h, s, l, opacity) {\n return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);\n}\n\nfunction Hsl(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Hsl, hsl, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n rgb: function() {\n var h = this.h % 360 + (this.h < 0) * 360,\n s = isNaN(h) || isNaN(this.s) ? 0 : this.s,\n l = this.l,\n m2 = l + (l < 0.5 ? l : 1 - l) * s,\n m1 = 2 * l - m2;\n return new Rgb(\n hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),\n hsl2rgb(h, m1, m2),\n hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),\n this.opacity\n );\n },\n displayable: function() {\n return (0 <= this.s && this.s <= 1 || isNaN(this.s))\n && (0 <= this.l && this.l <= 1)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n formatHsl: function() {\n var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));\n return (a === 1 ? \"hsl(\" : \"hsla(\")\n + (this.h || 0) + \", \"\n + (this.s || 0) * 100 + \"%, \"\n + (this.l || 0) * 100 + \"%\"\n + (a === 1 ? \")\" : \", \" + a + \")\");\n }\n}));\n\n/* From FvD 13.37, CSS Color Module Level 3 */\nfunction hsl2rgb(h, m1, m2) {\n return (h < 60 ? m1 + (m2 - m1) * h / 60\n : h < 180 ? m2\n : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60\n : m1) * 255;\n}\n","import { Transform, rederive, ingest, replace } from 'vega-dataflow';\nimport { error, extent, inherits, identity, isArray, isFunction, isNumber, constant, array, one, accessorName, accessorFields, field, extend, toSet, zero } from 'vega-util';\nimport { range, tickStep, max, sum } from 'd3-array';\nimport { bandwidthNRD } from 'vega-statistics';\nimport { getProjectionPath, projectionProperties, projection } from 'vega-projection';\nimport { geoGraticule } from 'd3-geo';\nimport { rgb } from 'd3-color';\nimport { canvas } from 'vega-canvas';\n\nfunction noop() {}\n\nconst cases = [[], [[[1.0, 1.5], [0.5, 1.0]]], [[[1.5, 1.0], [1.0, 1.5]]], [[[1.5, 1.0], [0.5, 1.0]]], [[[1.0, 0.5], [1.5, 1.0]]], [[[1.0, 1.5], [0.5, 1.0]], [[1.0, 0.5], [1.5, 1.0]]], [[[1.0, 0.5], [1.0, 1.5]]], [[[1.0, 0.5], [0.5, 1.0]]], [[[0.5, 1.0], [1.0, 0.5]]], [[[1.0, 1.5], [1.0, 0.5]]], [[[0.5, 1.0], [1.0, 0.5]], [[1.5, 1.0], [1.0, 1.5]]], [[[1.5, 1.0], [1.0, 0.5]]], [[[0.5, 1.0], [1.5, 1.0]]], [[[1.0, 1.5], [1.5, 1.0]]], [[[0.5, 1.0], [1.0, 1.5]]], []]; // Implementation adapted from d3/d3-contour. Thanks!\n\nfunction contours () {\n var dx = 1,\n dy = 1,\n smooth = smoothLinear;\n\n function contours(values, tz) {\n return tz.map(value => contour(values, value));\n } // Accumulate, smooth contour rings, assign holes to exterior rings.\n // Based on https://github.com/mbostock/shapefile/blob/v0.6.2/shp/polygon.js\n\n\n function contour(values, value) {\n var polygons = [],\n holes = [];\n isorings(values, value, ring => {\n smooth(ring, values, value);\n if (area(ring) > 0) polygons.push([ring]);else holes.push(ring);\n });\n holes.forEach(hole => {\n for (var i = 0, n = polygons.length, polygon; i < n; ++i) {\n if (contains((polygon = polygons[i])[0], hole) !== -1) {\n polygon.push(hole);\n return;\n }\n }\n });\n return {\n type: 'MultiPolygon',\n value: value,\n coordinates: polygons\n };\n } // Marching squares with isolines stitched into rings.\n // Based on https://github.com/topojson/topojson-client/blob/v3.0.0/src/stitch.js\n\n\n function isorings(values, value, callback) {\n var fragmentByStart = new Array(),\n fragmentByEnd = new Array(),\n x,\n y,\n t0,\n t1,\n t2,\n t3; // Special case for the first row (y = -1, t2 = t3 = 0).\n\n x = y = -1;\n t1 = values[0] >= value;\n cases[t1 << 1].forEach(stitch);\n\n while (++x < dx - 1) {\n t0 = t1, t1 = values[x + 1] >= value;\n cases[t0 | t1 << 1].forEach(stitch);\n }\n\n cases[t1 << 0].forEach(stitch); // General case for the intermediate rows.\n\n while (++y < dy - 1) {\n x = -1;\n t1 = values[y * dx + dx] >= value;\n t2 = values[y * dx] >= value;\n cases[t1 << 1 | t2 << 2].forEach(stitch);\n\n while (++x < dx - 1) {\n t0 = t1, t1 = values[y * dx + dx + x + 1] >= value;\n t3 = t2, t2 = values[y * dx + x + 1] >= value;\n cases[t0 | t1 << 1 | t2 << 2 | t3 << 3].forEach(stitch);\n }\n\n cases[t1 | t2 << 3].forEach(stitch);\n } // Special case for the last row (y = dy - 1, t0 = t1 = 0).\n\n\n x = -1;\n t2 = values[y * dx] >= value;\n cases[t2 << 2].forEach(stitch);\n\n while (++x < dx - 1) {\n t3 = t2, t2 = values[y * dx + x + 1] >= value;\n cases[t2 << 2 | t3 << 3].forEach(stitch);\n }\n\n cases[t2 << 3].forEach(stitch);\n\n function stitch(line) {\n var start = [line[0][0] + x, line[0][1] + y],\n end = [line[1][0] + x, line[1][1] + y],\n startIndex = index(start),\n endIndex = index(end),\n f,\n g;\n\n if (f = fragmentByEnd[startIndex]) {\n if (g = fragmentByStart[endIndex]) {\n delete fragmentByEnd[f.end];\n delete fragmentByStart[g.start];\n\n if (f === g) {\n f.ring.push(end);\n callback(f.ring);\n } else {\n fragmentByStart[f.start] = fragmentByEnd[g.end] = {\n start: f.start,\n end: g.end,\n ring: f.ring.concat(g.ring)\n };\n }\n } else {\n delete fragmentByEnd[f.end];\n f.ring.push(end);\n fragmentByEnd[f.end = endIndex] = f;\n }\n } else if (f = fragmentByStart[endIndex]) {\n if (g = fragmentByEnd[startIndex]) {\n delete fragmentByStart[f.start];\n delete fragmentByEnd[g.end];\n\n if (f === g) {\n f.ring.push(end);\n callback(f.ring);\n } else {\n fragmentByStart[g.start] = fragmentByEnd[f.end] = {\n start: g.start,\n end: f.end,\n ring: g.ring.concat(f.ring)\n };\n }\n } else {\n delete fragmentByStart[f.start];\n f.ring.unshift(start);\n fragmentByStart[f.start = startIndex] = f;\n }\n } else {\n fragmentByStart[startIndex] = fragmentByEnd[endIndex] = {\n start: startIndex,\n end: endIndex,\n ring: [start, end]\n };\n }\n }\n }\n\n function index(point) {\n return point[0] * 2 + point[1] * (dx + 1) * 4;\n }\n\n function smoothLinear(ring, values, value) {\n ring.forEach(point => {\n var x = point[0],\n y = point[1],\n xt = x | 0,\n yt = y | 0,\n v0,\n v1 = values[yt * dx + xt];\n\n if (x > 0 && x < dx && xt === x) {\n v0 = values[yt * dx + xt - 1];\n point[0] = x + (value - v0) / (v1 - v0) - 0.5;\n }\n\n if (y > 0 && y < dy && yt === y) {\n v0 = values[(yt - 1) * dx + xt];\n point[1] = y + (value - v0) / (v1 - v0) - 0.5;\n }\n });\n }\n\n contours.contour = contour;\n\n contours.size = function (_) {\n if (!arguments.length) return [dx, dy];\n\n var _0 = Math.floor(_[0]),\n _1 = Math.floor(_[1]);\n\n if (!(_0 >= 0 && _1 >= 0)) error('invalid size');\n return dx = _0, dy = _1, contours;\n };\n\n contours.smooth = function (_) {\n return arguments.length ? (smooth = _ ? smoothLinear : noop, contours) : smooth === smoothLinear;\n };\n\n return contours;\n}\n\nfunction area(ring) {\n var i = 0,\n n = ring.length,\n area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];\n\n while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];\n\n return area;\n}\n\nfunction contains(ring, hole) {\n var i = -1,\n n = hole.length,\n c;\n\n while (++i < n) if (c = ringContains(ring, hole[i])) return c;\n\n return 0;\n}\n\nfunction ringContains(ring, point) {\n var x = point[0],\n y = point[1],\n contains = -1;\n\n for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {\n var pi = ring[i],\n xi = pi[0],\n yi = pi[1],\n pj = ring[j],\n xj = pj[0],\n yj = pj[1];\n if (segmentContains(pi, pj, point)) return 0;\n if (yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) contains = -contains;\n }\n\n return contains;\n}\n\nfunction segmentContains(a, b, c) {\n var i;\n return collinear(a, b, c) && within(a[i = +(a[0] === b[0])], c[i], b[i]);\n}\n\nfunction collinear(a, b, c) {\n return (b[0] - a[0]) * (c[1] - a[1]) === (c[0] - a[0]) * (b[1] - a[1]);\n}\n\nfunction within(p, q, r) {\n return p <= q && q <= r || r <= q && q <= p;\n}\n\nfunction quantize (k, nice, zero) {\n return function (values) {\n var ex = extent(values),\n start = zero ? Math.min(ex[0], 0) : ex[0],\n stop = ex[1],\n span = stop - start,\n step = nice ? tickStep(start, stop, k) : span / (k + 1);\n return range(start + step, stop, step);\n };\n}\n\n/**\n * Generate isocontours (level sets) based on input raster grid data.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} [params.field] - The field with raster grid\n * data. If unspecified, the tuple itself is interpreted as a raster grid.\n * @param {Array} [params.thresholds] - Contour threshold array. If\n * specified, the levels, nice, resolve, and zero parameters are ignored.\n * @param {number} [params.levels] - The desired number of contour levels.\n * @param {boolean} [params.nice] - Boolean flag indicating if the contour\n * threshold values should be automatically aligned to \"nice\"\n * human-friendly values. Setting this flag may cause the number of\n * thresholds to deviate from the specified levels.\n * @param {string} [params.resolve] - The method for resolving thresholds\n * across multiple input grids. If 'independent' (the default), threshold\n * calculation will be performed separately for each grid. If 'shared', a\n * single set of threshold values will be used for all input grids.\n * @param {boolean} [params.zero] - Boolean flag indicating if the contour\n * threshold values should include zero.\n * @param {boolean} [params.smooth] - Boolean flag indicating if the contour\n * polygons should be smoothed using linear interpolation. The default is\n * true. The parameter is ignored when using density estimation.\n * @param {boolean} [params.scale] - Optional numerical value by which to\n * scale the output isocontour coordinates. This parameter can be useful\n * to scale the contours to match a desired output resolution.\n * @param {string} [params.as='contour'] - The output field in which to store\n * the generated isocontour data (default 'contour').\n */\n\nfunction Isocontour(params) {\n Transform.call(this, null, params);\n}\nIsocontour.Definition = {\n 'type': 'Isocontour',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field'\n }, {\n 'name': 'thresholds',\n 'type': 'number',\n 'array': true\n }, {\n 'name': 'levels',\n 'type': 'number'\n }, {\n 'name': 'nice',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'resolve',\n 'type': 'enum',\n 'values': ['shared', 'independent'],\n 'default': 'independent'\n }, {\n 'name': 'zero',\n 'type': 'boolean',\n 'default': true\n }, {\n 'name': 'smooth',\n 'type': 'boolean',\n 'default': true\n }, {\n 'name': 'scale',\n 'type': 'number',\n 'expr': true\n }, {\n 'name': 'translate',\n 'type': 'number',\n 'array': true,\n 'expr': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'null': true,\n 'default': 'contour'\n }]\n};\ninherits(Isocontour, Transform, {\n transform(_, pulse) {\n if (this.value && !pulse.changed() && !_.modified()) {\n return pulse.StopPropagation;\n }\n\n var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),\n source = pulse.materialize(pulse.SOURCE).source,\n field = _.field || identity,\n contour = contours().smooth(_.smooth !== false),\n tz = _.thresholds || levels(source, field, _),\n as = _.as === null ? null : _.as || 'contour',\n values = [];\n source.forEach(t => {\n const grid = field(t); // generate contour paths in GeoJSON format\n\n const paths = contour.size([grid.width, grid.height])(grid.values, isArray(tz) ? tz : tz(grid.values)); // adjust contour path coordinates as needed\n\n transformPaths(paths, grid, t, _); // ingest; copy source data properties to output\n\n paths.forEach(p => {\n values.push(rederive(t, ingest(as != null ? {\n [as]: p\n } : p)));\n });\n });\n if (this.value) out.rem = this.value;\n this.value = out.source = out.add = values;\n return out;\n }\n\n});\n\nfunction levels(values, f, _) {\n const q = quantize(_.levels || 10, _.nice, _.zero !== false);\n return _.resolve !== 'shared' ? q : q(values.map(t => max(f(t).values)));\n}\n\nfunction transformPaths(paths, grid, datum, _) {\n let s = _.scale || grid.scale,\n t = _.translate || grid.translate;\n if (isFunction(s)) s = s(datum, _);\n if (isFunction(t)) t = t(datum, _);\n if ((s === 1 || s == null) && !t) return;\n const sx = (isNumber(s) ? s : s[0]) || 1,\n sy = (isNumber(s) ? s : s[1]) || 1,\n tx = t && t[0] || 0,\n ty = t && t[1] || 0;\n paths.forEach(transform(grid, sx, sy, tx, ty));\n}\n\nfunction transform(grid, sx, sy, tx, ty) {\n const x1 = grid.x1 || 0,\n y1 = grid.y1 || 0,\n flip = sx * sy < 0;\n\n function transformPolygon(coordinates) {\n coordinates.forEach(transformRing);\n }\n\n function transformRing(coordinates) {\n if (flip) coordinates.reverse(); // maintain winding order\n\n coordinates.forEach(transformPoint);\n }\n\n function transformPoint(coordinates) {\n coordinates[0] = (coordinates[0] - x1) * sx + tx;\n coordinates[1] = (coordinates[1] - y1) * sy + ty;\n }\n\n return function (geometry) {\n geometry.coordinates.forEach(transformPolygon);\n return geometry;\n };\n}\n\nfunction radius(bw, data, f) {\n const v = bw >= 0 ? bw : bandwidthNRD(data, f);\n return Math.round((Math.sqrt(4 * v * v + 1) - 1) / 2);\n}\n\nfunction number(_) {\n return isFunction(_) ? _ : constant(+_);\n} // Implementation adapted from d3/d3-contour. Thanks!\n\n\nfunction density2D () {\n var x = d => d[0],\n y = d => d[1],\n weight = one,\n bandwidth = [-1, -1],\n dx = 960,\n dy = 500,\n k = 2; // log2(cellSize)\n\n\n function density(data, counts) {\n const rx = radius(bandwidth[0], data, x) >> k,\n // blur x-radius\n ry = radius(bandwidth[1], data, y) >> k,\n // blur y-radius\n ox = rx ? rx + 2 : 0,\n // x-offset padding for blur\n oy = ry ? ry + 2 : 0,\n // y-offset padding for blur\n n = 2 * ox + (dx >> k),\n // grid width\n m = 2 * oy + (dy >> k),\n // grid height\n values0 = new Float32Array(n * m),\n values1 = new Float32Array(n * m);\n let values = values0;\n data.forEach(d => {\n const xi = ox + (+x(d) >> k),\n yi = oy + (+y(d) >> k);\n\n if (xi >= 0 && xi < n && yi >= 0 && yi < m) {\n values0[xi + yi * n] += +weight(d);\n }\n });\n\n if (rx > 0 && ry > 0) {\n blurX(n, m, values0, values1, rx);\n blurY(n, m, values1, values0, ry);\n blurX(n, m, values0, values1, rx);\n blurY(n, m, values1, values0, ry);\n blurX(n, m, values0, values1, rx);\n blurY(n, m, values1, values0, ry);\n } else if (rx > 0) {\n blurX(n, m, values0, values1, rx);\n blurX(n, m, values1, values0, rx);\n blurX(n, m, values0, values1, rx);\n values = values1;\n } else if (ry > 0) {\n blurY(n, m, values0, values1, ry);\n blurY(n, m, values1, values0, ry);\n blurY(n, m, values0, values1, ry);\n values = values1;\n } // scale density estimates\n // density in points per square pixel or probability density\n\n\n const s = counts ? Math.pow(2, -2 * k) : 1 / sum(values);\n\n for (let i = 0, sz = n * m; i < sz; ++i) values[i] *= s;\n\n return {\n values: values,\n scale: 1 << k,\n width: n,\n height: m,\n x1: ox,\n y1: oy,\n x2: ox + (dx >> k),\n y2: oy + (dy >> k)\n };\n }\n\n density.x = function (_) {\n return arguments.length ? (x = number(_), density) : x;\n };\n\n density.y = function (_) {\n return arguments.length ? (y = number(_), density) : y;\n };\n\n density.weight = function (_) {\n return arguments.length ? (weight = number(_), density) : weight;\n };\n\n density.size = function (_) {\n if (!arguments.length) return [dx, dy];\n\n var _0 = +_[0],\n _1 = +_[1];\n\n if (!(_0 >= 0 && _1 >= 0)) error('invalid size');\n return dx = _0, dy = _1, density;\n };\n\n density.cellSize = function (_) {\n if (!arguments.length) return 1 << k;\n if (!((_ = +_) >= 1)) error('invalid cell size');\n k = Math.floor(Math.log(_) / Math.LN2);\n return density;\n };\n\n density.bandwidth = function (_) {\n if (!arguments.length) return bandwidth;\n _ = array(_);\n if (_.length === 1) _ = [+_[0], +_[0]];\n if (_.length !== 2) error('invalid bandwidth');\n return bandwidth = _, density;\n };\n\n return density;\n}\n\nfunction blurX(n, m, source, target, r) {\n const w = (r << 1) + 1;\n\n for (let j = 0; j < m; ++j) {\n for (let i = 0, sr = 0; i < n + r; ++i) {\n if (i < n) {\n sr += source[i + j * n];\n }\n\n if (i >= r) {\n if (i >= w) {\n sr -= source[i - w + j * n];\n }\n\n target[i - r + j * n] = sr / Math.min(i + 1, n - 1 + w - i, w);\n }\n }\n }\n}\n\nfunction blurY(n, m, source, target, r) {\n const w = (r << 1) + 1;\n\n for (let i = 0; i < n; ++i) {\n for (let j = 0, sr = 0; j < m + r; ++j) {\n if (j < m) {\n sr += source[i + j * n];\n }\n\n if (j >= r) {\n if (j >= w) {\n sr -= source[i + (j - w) * n];\n }\n\n target[i + (j - r) * n] = sr / Math.min(j + 1, m - 1 + w - j, w);\n }\n }\n }\n}\n\n/**\n * Perform 2D kernel-density estimation of point data.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} params.size - The [width, height] extent (in\n * units of input pixels) over which to perform density estimation.\n * @param {function(object): number} params.x - The x-coordinate accessor.\n * @param {function(object): number} params.y - The y-coordinate accessor.\n * @param {function(object): number} [params.weight] - The weight accessor.\n * @param {Array} [params.groupby] - An array of accessors\n * to groupby.\n * @param {number} [params.cellSize] - Contour density calculation cell size.\n * This parameter determines the level of spatial approximation. For example,\n * the default value of 4 maps to 2x reductions in both x- and y- dimensions.\n * A value of 1 will result in an output raster grid whose dimensions exactly\n * matches the size parameter.\n * @param {Array} [params.bandwidth] - The KDE kernel bandwidths,\n * in pixels. The input can be a two-element array specifying separate\n * x and y bandwidths, or a single-element array specifying both. If the\n * bandwidth is unspecified or less than zero, the bandwidth will be\n * automatically determined.\n * @param {boolean} [params.counts=false] - A boolean flag indicating if the\n * output values should be probability estimates (false, default) or\n * smoothed counts (true).\n * @param {string} [params.as='grid'] - The output field in which to store\n * the generated raster grid (default 'grid').\n */\n\nfunction KDE2D(params) {\n Transform.call(this, null, params);\n}\nKDE2D.Definition = {\n 'type': 'KDE2D',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'size',\n 'type': 'number',\n 'array': true,\n 'length': 2,\n 'required': true\n }, {\n 'name': 'x',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'y',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'weight',\n 'type': 'field'\n }, {\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'cellSize',\n 'type': 'number'\n }, {\n 'name': 'bandwidth',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'counts',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'as',\n 'type': 'string',\n 'default': 'grid'\n }]\n};\nconst PARAMS = ['x', 'y', 'weight', 'size', 'cellSize', 'bandwidth'];\nfunction params(obj, _) {\n PARAMS.forEach(param => _[param] != null ? obj[param](_[param]) : 0);\n return obj;\n}\ninherits(KDE2D, Transform, {\n transform(_, pulse) {\n if (this.value && !pulse.changed() && !_.modified()) return pulse.StopPropagation;\n var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),\n source = pulse.materialize(pulse.SOURCE).source,\n groups = partition(source, _.groupby),\n names = (_.groupby || []).map(accessorName),\n kde = params(density2D(), _),\n as = _.as || 'grid',\n values = [];\n\n function set(t, vals) {\n for (let i = 0; i < names.length; ++i) t[names[i]] = vals[i];\n\n return t;\n } // generate density raster grids\n\n\n values = groups.map(g => ingest(set({\n [as]: kde(g, _.counts)\n }, g.dims)));\n if (this.value) out.rem = this.value;\n this.value = out.source = out.add = values;\n return out;\n }\n\n});\nfunction partition(data, groupby) {\n var groups = [],\n get = f => f(t),\n map,\n i,\n n,\n t,\n k,\n g; // partition data points into groups\n\n\n if (groupby == null) {\n groups.push(data);\n } else {\n for (map = {}, i = 0, n = data.length; i < n; ++i) {\n t = data[i];\n k = groupby.map(get);\n g = map[k];\n\n if (!g) {\n map[k] = g = [];\n g.dims = k;\n groups.push(g);\n }\n\n g.push(t);\n }\n }\n\n return groups;\n}\n\n/**\n * Generate contours based on kernel-density estimation of point data.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} params.size - The dimensions [width, height] over which to compute contours.\n * If the values parameter is provided, this must be the dimensions of the input data.\n * If density estimation is performed, this is the output view dimensions in pixels.\n * @param {Array} [params.values] - An array of numeric values representing an\n * width x height grid of values over which to compute contours. If unspecified, this\n * transform will instead attempt to compute contours for the kernel density estimate\n * using values drawn from data tuples in the input pulse.\n * @param {function(object): number} [params.x] - The pixel x-coordinate accessor for density estimation.\n * @param {function(object): number} [params.y] - The pixel y-coordinate accessor for density estimation.\n * @param {function(object): number} [params.weight] - The data point weight accessor for density estimation.\n * @param {number} [params.cellSize] - Contour density calculation cell size.\n * @param {number} [params.bandwidth] - Kernel density estimation bandwidth.\n * @param {Array} [params.thresholds] - Contour threshold array. If\n * this parameter is set, the count and nice parameters will be ignored.\n * @param {number} [params.count] - The desired number of contours.\n * @param {boolean} [params.nice] - Boolean flag indicating if the contour\n * threshold values should be automatically aligned to \"nice\"\n * human-friendly values. Setting this flag may cause the number of\n * thresholds to deviate from the specified count.\n * @param {boolean} [params.smooth] - Boolean flag indicating if the contour\n * polygons should be smoothed using linear interpolation. The default is\n * true. The parameter is ignored when using density estimation.\n */\n\nfunction Contour(params) {\n Transform.call(this, null, params);\n}\nContour.Definition = {\n 'type': 'Contour',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'size',\n 'type': 'number',\n 'array': true,\n 'length': 2,\n 'required': true\n }, {\n 'name': 'values',\n 'type': 'number',\n 'array': true\n }, {\n 'name': 'x',\n 'type': 'field'\n }, {\n 'name': 'y',\n 'type': 'field'\n }, {\n 'name': 'weight',\n 'type': 'field'\n }, {\n 'name': 'cellSize',\n 'type': 'number'\n }, {\n 'name': 'bandwidth',\n 'type': 'number'\n }, {\n 'name': 'count',\n 'type': 'number'\n }, {\n 'name': 'nice',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'thresholds',\n 'type': 'number',\n 'array': true\n }, {\n 'name': 'smooth',\n 'type': 'boolean',\n 'default': true\n }]\n};\ninherits(Contour, Transform, {\n transform(_, pulse) {\n if (this.value && !pulse.changed() && !_.modified()) {\n return pulse.StopPropagation;\n }\n\n var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),\n contour = contours().smooth(_.smooth !== false),\n values = _.values,\n thresh = _.thresholds || quantize(_.count || 10, _.nice, !!values),\n size = _.size,\n grid,\n post;\n\n if (!values) {\n values = pulse.materialize(pulse.SOURCE).source;\n grid = params(density2D(), _)(values, true);\n post = transform(grid, grid.scale || 1, grid.scale || 1, 0, 0);\n size = [grid.width, grid.height];\n values = grid.values;\n }\n\n thresh = isArray(thresh) ? thresh : thresh(values);\n values = contour.size(size)(values, thresh);\n if (post) values.forEach(post);\n if (this.value) out.rem = this.value;\n this.value = out.source = out.add = (values || []).map(ingest);\n return out;\n }\n\n});\n\nconst Feature = 'Feature';\nconst FeatureCollection = 'FeatureCollection';\nconst MultiPoint = 'MultiPoint';\n\n/**\n * Consolidate an array of [longitude, latitude] points or GeoJSON features\n * into a combined GeoJSON object. This transform is particularly useful for\n * combining geo data for a Projection's fit argument. The resulting GeoJSON\n * data is available as this transform's value. Input pulses are unchanged.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} [params.fields] - A two-element array\n * of field accessors for the longitude and latitude values.\n * @param {function(object): *} params.geojson - A field accessor for\n * retrieving GeoJSON feature data.\n */\n\nfunction GeoJSON(params) {\n Transform.call(this, null, params);\n}\nGeoJSON.Definition = {\n 'type': 'GeoJSON',\n 'metadata': {},\n 'params': [{\n 'name': 'fields',\n 'type': 'field',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'geojson',\n 'type': 'field'\n }]\n};\ninherits(GeoJSON, Transform, {\n transform(_, pulse) {\n var features = this._features,\n points = this._points,\n fields = _.fields,\n lon = fields && fields[0],\n lat = fields && fields[1],\n geojson = _.geojson || !fields && identity,\n flag = pulse.ADD,\n mod;\n mod = _.modified() || pulse.changed(pulse.REM) || pulse.modified(accessorFields(geojson)) || lon && pulse.modified(accessorFields(lon)) || lat && pulse.modified(accessorFields(lat));\n\n if (!this.value || mod) {\n flag = pulse.SOURCE;\n this._features = features = [];\n this._points = points = [];\n }\n\n if (geojson) {\n pulse.visit(flag, t => features.push(geojson(t)));\n }\n\n if (lon && lat) {\n pulse.visit(flag, t => {\n var x = lon(t),\n y = lat(t);\n\n if (x != null && y != null && (x = +x) === x && (y = +y) === y) {\n points.push([x, y]);\n }\n });\n features = features.concat({\n type: Feature,\n geometry: {\n type: MultiPoint,\n coordinates: points\n }\n });\n }\n\n this.value = {\n type: FeatureCollection,\n features: features\n };\n }\n\n});\n\n/**\n * Map GeoJSON data to an SVG path string.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(number, number): *} params.projection - The cartographic\n * projection to apply.\n * @param {function(object): *} [params.field] - The field with GeoJSON data,\n * or null if the tuple itself is a GeoJSON feature.\n * @param {string} [params.as='path'] - The output field in which to store\n * the generated path data (default 'path').\n */\n\nfunction GeoPath(params) {\n Transform.call(this, null, params);\n}\nGeoPath.Definition = {\n 'type': 'GeoPath',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'projection',\n 'type': 'projection'\n }, {\n 'name': 'field',\n 'type': 'field'\n }, {\n 'name': 'pointRadius',\n 'type': 'number',\n 'expr': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'default': 'path'\n }]\n};\ninherits(GeoPath, Transform, {\n transform(_, pulse) {\n var out = pulse.fork(pulse.ALL),\n path = this.value,\n field = _.field || identity,\n as = _.as || 'path',\n flag = out.SOURCE;\n\n if (!path || _.modified()) {\n // parameters updated, reset and reflow\n this.value = path = getProjectionPath(_.projection);\n out.materialize().reflow();\n } else {\n flag = field === identity || pulse.modified(field.fields) ? out.ADD_MOD : out.ADD;\n }\n\n const prev = initPath(path, _.pointRadius);\n out.visit(flag, t => t[as] = path(field(t)));\n path.pointRadius(prev);\n return out.modifies(as);\n }\n\n});\n\nfunction initPath(path, pointRadius) {\n const prev = path.pointRadius();\n path.context(null);\n\n if (pointRadius != null) {\n path.pointRadius(pointRadius);\n }\n\n return prev;\n}\n\n/**\n * Geo-code a longitude/latitude point to an x/y coordinate.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(number, number): *} params.projection - The cartographic\n * projection to apply.\n * @param {Array} params.fields - A two-element array of\n * field accessors for the longitude and latitude values.\n * @param {Array} [params.as] - A two-element array of field names\n * under which to store the result. Defaults to ['x','y'].\n */\n\nfunction GeoPoint(params) {\n Transform.call(this, null, params);\n}\nGeoPoint.Definition = {\n 'type': 'GeoPoint',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'projection',\n 'type': 'projection',\n 'required': true\n }, {\n 'name': 'fields',\n 'type': 'field',\n 'array': true,\n 'required': true,\n 'length': 2\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': 2,\n 'default': ['x', 'y']\n }]\n};\ninherits(GeoPoint, Transform, {\n transform(_, pulse) {\n var proj = _.projection,\n lon = _.fields[0],\n lat = _.fields[1],\n as = _.as || ['x', 'y'],\n x = as[0],\n y = as[1],\n mod;\n\n function set(t) {\n const xy = proj([lon(t), lat(t)]);\n\n if (xy) {\n t[x] = xy[0];\n t[y] = xy[1];\n } else {\n t[x] = undefined;\n t[y] = undefined;\n }\n }\n\n if (_.modified()) {\n // parameters updated, reflow\n pulse = pulse.materialize().reflow(true).visit(pulse.SOURCE, set);\n } else {\n mod = pulse.modified(lon.fields) || pulse.modified(lat.fields);\n pulse.visit(mod ? pulse.ADD_MOD : pulse.ADD, set);\n }\n\n return pulse.modifies(as);\n }\n\n});\n\n/**\n * Annotate items with a geopath shape generator.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(number, number): *} params.projection - The cartographic\n * projection to apply.\n * @param {function(object): *} [params.field] - The field with GeoJSON data,\n * or null if the tuple itself is a GeoJSON feature.\n * @param {string} [params.as='shape'] - The output field in which to store\n * the generated path data (default 'shape').\n */\n\nfunction GeoShape(params) {\n Transform.call(this, null, params);\n}\nGeoShape.Definition = {\n 'type': 'GeoShape',\n 'metadata': {\n 'modifies': true,\n 'nomod': true\n },\n 'params': [{\n 'name': 'projection',\n 'type': 'projection'\n }, {\n 'name': 'field',\n 'type': 'field',\n 'default': 'datum'\n }, {\n 'name': 'pointRadius',\n 'type': 'number',\n 'expr': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'default': 'shape'\n }]\n};\ninherits(GeoShape, Transform, {\n transform(_, pulse) {\n var out = pulse.fork(pulse.ALL),\n shape = this.value,\n as = _.as || 'shape',\n flag = out.ADD;\n\n if (!shape || _.modified()) {\n // parameters updated, reset and reflow\n this.value = shape = shapeGenerator(getProjectionPath(_.projection), _.field || field('datum'), _.pointRadius);\n out.materialize().reflow();\n flag = out.SOURCE;\n }\n\n out.visit(flag, t => t[as] = shape);\n return out.modifies(as);\n }\n\n});\n\nfunction shapeGenerator(path, field, pointRadius) {\n const shape = pointRadius == null ? _ => path(field(_)) : _ => {\n var prev = path.pointRadius(),\n value = path.pointRadius(pointRadius)(field(_));\n path.pointRadius(prev);\n return value;\n };\n\n shape.context = _ => {\n path.context(_);\n return shape;\n };\n\n return shape;\n}\n\n/**\n * GeoJSON feature generator for creating graticules.\n * @constructor\n */\n\nfunction Graticule(params) {\n Transform.call(this, [], params);\n this.generator = geoGraticule();\n}\nGraticule.Definition = {\n 'type': 'Graticule',\n 'metadata': {\n 'changes': true,\n 'generates': true\n },\n 'params': [{\n 'name': 'extent',\n 'type': 'array',\n 'array': true,\n 'length': 2,\n 'content': {\n 'type': 'number',\n 'array': true,\n 'length': 2\n }\n }, {\n 'name': 'extentMajor',\n 'type': 'array',\n 'array': true,\n 'length': 2,\n 'content': {\n 'type': 'number',\n 'array': true,\n 'length': 2\n }\n }, {\n 'name': 'extentMinor',\n 'type': 'array',\n 'array': true,\n 'length': 2,\n 'content': {\n 'type': 'number',\n 'array': true,\n 'length': 2\n }\n }, {\n 'name': 'step',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'stepMajor',\n 'type': 'number',\n 'array': true,\n 'length': 2,\n 'default': [90, 360]\n }, {\n 'name': 'stepMinor',\n 'type': 'number',\n 'array': true,\n 'length': 2,\n 'default': [10, 10]\n }, {\n 'name': 'precision',\n 'type': 'number',\n 'default': 2.5\n }]\n};\ninherits(Graticule, Transform, {\n transform(_, pulse) {\n var src = this.value,\n gen = this.generator,\n t;\n\n if (!src.length || _.modified()) {\n for (const prop in _) {\n if (isFunction(gen[prop])) {\n gen[prop](_[prop]);\n }\n }\n }\n\n t = gen();\n\n if (src.length) {\n pulse.mod.push(replace(src[0], t));\n } else {\n pulse.add.push(ingest(t));\n }\n\n src[0] = t;\n return pulse;\n }\n\n});\n\n/**\n * Render a heatmap image for input raster grid data.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} [params.field] - The field with raster grid\n * data. If unspecified, the tuple itself is interpreted as a raster grid.\n * @param {string} [params.color] - A constant color value or function for\n * individual pixel color. If a function, it will be invoked with an input\n * object that includes $x, $y, $value, and $max fields for the grid.\n * @param {number} [params.opacity] - A constant opacity value or function for\n * individual pixel opacity. If a function, it will be invoked with an input\n * object that includes $x, $y, $value, and $max fields for the grid.\n * @param {string} [params.resolve] - The method for resolving maximum values\n * across multiple input grids. If 'independent' (the default), maximum\n * calculation will be performed separately for each grid. If 'shared',\n * a single global maximum will be used for all input grids.\n * @param {string} [params.as='image'] - The output field in which to store\n * the generated bitmap canvas images (default 'image').\n */\n\nfunction Heatmap(params) {\n Transform.call(this, null, params);\n}\nHeatmap.Definition = {\n 'type': 'heatmap',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field'\n }, {\n 'name': 'color',\n 'type': 'string',\n 'expr': true\n }, {\n 'name': 'opacity',\n 'type': 'number',\n 'expr': true\n }, {\n 'name': 'resolve',\n 'type': 'enum',\n 'values': ['shared', 'independent'],\n 'default': 'independent'\n }, {\n 'name': 'as',\n 'type': 'string',\n 'default': 'image'\n }]\n};\ninherits(Heatmap, Transform, {\n transform(_, pulse) {\n if (!pulse.changed() && !_.modified()) {\n return pulse.StopPropagation;\n }\n\n var source = pulse.materialize(pulse.SOURCE).source,\n shared = _.resolve === 'shared',\n field = _.field || identity,\n opacity = opacity_(_.opacity, _),\n color = color_(_.color, _),\n as = _.as || 'image',\n obj = {\n $x: 0,\n $y: 0,\n $value: 0,\n $max: shared ? max(source.map(t => max(field(t).values))) : 0\n };\n source.forEach(t => {\n const v = field(t); // build proxy data object\n\n const o = extend({}, t, obj); // set maximum value if not globally shared\n\n if (!shared) o.$max = max(v.values || []); // generate canvas image\n // optimize color/opacity if not pixel-dependent\n\n t[as] = toCanvas(v, o, color.dep ? color : constant(color(o)), opacity.dep ? opacity : constant(opacity(o)));\n });\n return pulse.reflow(true).modifies(as);\n }\n\n}); // get image color function\n\nfunction color_(color, _) {\n let f;\n\n if (isFunction(color)) {\n f = obj => rgb(color(obj, _));\n\n f.dep = dependency(color);\n } else {\n // default to mid-grey\n f = constant(rgb(color || '#888'));\n }\n\n return f;\n} // get image opacity function\n\n\nfunction opacity_(opacity, _) {\n let f;\n\n if (isFunction(opacity)) {\n f = obj => opacity(obj, _);\n\n f.dep = dependency(opacity);\n } else if (opacity) {\n f = constant(opacity);\n } else {\n // default to [0, max] opacity gradient\n f = obj => obj.$value / obj.$max || 0;\n\n f.dep = true;\n }\n\n return f;\n} // check if function depends on individual pixel data\n\n\nfunction dependency(f) {\n if (!isFunction(f)) return false;\n const set = toSet(accessorFields(f));\n return set.$x || set.$y || set.$value || set.$max;\n} // render raster grid to canvas\n\n\nfunction toCanvas(grid, obj, color, opacity) {\n const n = grid.width,\n m = grid.height,\n x1 = grid.x1 || 0,\n y1 = grid.y1 || 0,\n x2 = grid.x2 || n,\n y2 = grid.y2 || m,\n val = grid.values,\n value = val ? i => val[i] : zero,\n can = canvas(x2 - x1, y2 - y1),\n ctx = can.getContext('2d'),\n img = ctx.getImageData(0, 0, x2 - x1, y2 - y1),\n pix = img.data;\n\n for (let j = y1, k = 0; j < y2; ++j) {\n obj.$y = j - y1;\n\n for (let i = x1, r = j * n; i < x2; ++i, k += 4) {\n obj.$x = i - x1;\n obj.$value = value(i + r);\n const v = color(obj);\n pix[k + 0] = v.r;\n pix[k + 1] = v.g;\n pix[k + 2] = v.b;\n pix[k + 3] = ~~(255 * opacity(obj));\n }\n }\n\n ctx.putImageData(img, 0, 0);\n return can;\n}\n\n/**\n * Maintains a cartographic projection.\n * @constructor\n * @param {object} params - The parameters for this operator.\n */\n\nfunction Projection(params) {\n Transform.call(this, null, params);\n this.modified(true); // always treat as modified\n}\ninherits(Projection, Transform, {\n transform(_, pulse) {\n let proj = this.value;\n\n if (!proj || _.modified('type')) {\n this.value = proj = create(_.type);\n projectionProperties.forEach(prop => {\n if (_[prop] != null) set(proj, prop, _[prop]);\n });\n } else {\n projectionProperties.forEach(prop => {\n if (_.modified(prop)) set(proj, prop, _[prop]);\n });\n }\n\n if (_.pointRadius != null) proj.path.pointRadius(_.pointRadius);\n if (_.fit) fit(proj, _);\n return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);\n }\n\n});\n\nfunction fit(proj, _) {\n const data = collectGeoJSON(_.fit);\n _.extent ? proj.fitExtent(_.extent, data) : _.size ? proj.fitSize(_.size, data) : 0;\n}\n\nfunction create(type) {\n const constructor = projection((type || 'mercator').toLowerCase());\n if (!constructor) error('Unrecognized projection type: ' + type);\n return constructor();\n}\n\nfunction set(proj, key, value) {\n if (isFunction(proj[key])) proj[key](value);\n}\n\nfunction collectGeoJSON(data) {\n data = array(data);\n return data.length === 1 ? data[0] : {\n type: FeatureCollection,\n features: data.reduce((a, f) => a.concat(featurize(f)), [])\n };\n}\n\nfunction featurize(f) {\n return f.type === FeatureCollection ? f.features : array(f).filter(d => d != null).map(d => d.type === Feature ? d : {\n type: Feature,\n geometry: d\n });\n}\n\nexport { Contour as contour, GeoJSON as geojson, GeoPath as geopath, GeoPoint as geopoint, GeoShape as geoshape, Graticule as graticule, Heatmap as heatmap, Isocontour as isocontour, KDE2D as kde2d, Projection as projection };\n","export default function sum(values, valueof) {\n let sum = 0;\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n sum += value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n sum += value;\n }\n }\n }\n return sum;\n}\n","export default function(x, y) {\n var nodes, strength = 1;\n\n if (x == null) x = 0;\n if (y == null) y = 0;\n\n function force() {\n var i,\n n = nodes.length,\n node,\n sx = 0,\n sy = 0;\n\n for (i = 0; i < n; ++i) {\n node = nodes[i], sx += node.x, sy += node.y;\n }\n\n for (sx = (sx / n - x) * strength, sy = (sy / n - y) * strength, i = 0; i < n; ++i) {\n node = nodes[i], node.x -= sx, node.y -= sy;\n }\n }\n\n force.initialize = function(_) {\n nodes = _;\n };\n\n force.x = function(_) {\n return arguments.length ? (x = +_, force) : x;\n };\n\n force.y = function(_) {\n return arguments.length ? (y = +_, force) : y;\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = +_, force) : strength;\n };\n\n return force;\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","export default function(random) {\n return (random() - 0.5) * 1e-6;\n}\n","import {quadtree} from \"d3-quadtree\";\nimport constant from \"./constant.js\";\nimport jiggle from \"./jiggle.js\";\n\nfunction x(d) {\n return d.x + d.vx;\n}\n\nfunction y(d) {\n return d.y + d.vy;\n}\n\nexport default function(radius) {\n var nodes,\n radii,\n random,\n strength = 1,\n iterations = 1;\n\n if (typeof radius !== \"function\") radius = constant(radius == null ? 1 : +radius);\n\n function force() {\n var i, n = nodes.length,\n tree,\n node,\n xi,\n yi,\n ri,\n ri2;\n\n for (var k = 0; k < iterations; ++k) {\n tree = quadtree(nodes, x, y).visitAfter(prepare);\n for (i = 0; i < n; ++i) {\n node = nodes[i];\n ri = radii[node.index], ri2 = ri * ri;\n xi = node.x + node.vx;\n yi = node.y + node.vy;\n tree.visit(apply);\n }\n }\n\n function apply(quad, x0, y0, x1, y1) {\n var data = quad.data, rj = quad.r, r = ri + rj;\n if (data) {\n if (data.index > node.index) {\n var x = xi - data.x - data.vx,\n y = yi - data.y - data.vy,\n l = x * x + y * y;\n if (l < r * r) {\n if (x === 0) x = jiggle(random), l += x * x;\n if (y === 0) y = jiggle(random), l += y * y;\n l = (r - (l = Math.sqrt(l))) / l * strength;\n node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj));\n node.vy += (y *= l) * r;\n data.vx -= x * (r = 1 - r);\n data.vy -= y * r;\n }\n }\n return;\n }\n return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;\n }\n }\n\n function prepare(quad) {\n if (quad.data) return quad.r = radii[quad.data.index];\n for (var i = quad.r = 0; i < 4; ++i) {\n if (quad[i] && quad[i].r > quad.r) {\n quad.r = quad[i].r;\n }\n }\n }\n\n function initialize() {\n if (!nodes) return;\n var i, n = nodes.length, node;\n radii = new Array(n);\n for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes);\n }\n\n force.initialize = function(_nodes, _random) {\n nodes = _nodes;\n random = _random;\n initialize();\n };\n\n force.iterations = function(_) {\n return arguments.length ? (iterations = +_, force) : iterations;\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = +_, force) : strength;\n };\n\n force.radius = function(_) {\n return arguments.length ? (radius = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : radius;\n };\n\n return force;\n}\n","import constant from \"./constant.js\";\nimport jiggle from \"./jiggle.js\";\n\nfunction index(d) {\n return d.index;\n}\n\nfunction find(nodeById, nodeId) {\n var node = nodeById.get(nodeId);\n if (!node) throw new Error(\"node not found: \" + nodeId);\n return node;\n}\n\nexport default function(links) {\n var id = index,\n strength = defaultStrength,\n strengths,\n distance = constant(30),\n distances,\n nodes,\n count,\n bias,\n random,\n iterations = 1;\n\n if (links == null) links = [];\n\n function defaultStrength(link) {\n return 1 / Math.min(count[link.source.index], count[link.target.index]);\n }\n\n function force(alpha) {\n for (var k = 0, n = links.length; k < iterations; ++k) {\n for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {\n link = links[i], source = link.source, target = link.target;\n x = target.x + target.vx - source.x - source.vx || jiggle(random);\n y = target.y + target.vy - source.y - source.vy || jiggle(random);\n l = Math.sqrt(x * x + y * y);\n l = (l - distances[i]) / l * alpha * strengths[i];\n x *= l, y *= l;\n target.vx -= x * (b = bias[i]);\n target.vy -= y * b;\n source.vx += x * (b = 1 - b);\n source.vy += y * b;\n }\n }\n }\n\n function initialize() {\n if (!nodes) return;\n\n var i,\n n = nodes.length,\n m = links.length,\n nodeById = new Map(nodes.map((d, i) => [id(d, i, nodes), d])),\n link;\n\n for (i = 0, count = new Array(n); i < m; ++i) {\n link = links[i], link.index = i;\n if (typeof link.source !== \"object\") link.source = find(nodeById, link.source);\n if (typeof link.target !== \"object\") link.target = find(nodeById, link.target);\n count[link.source.index] = (count[link.source.index] || 0) + 1;\n count[link.target.index] = (count[link.target.index] || 0) + 1;\n }\n\n for (i = 0, bias = new Array(m); i < m; ++i) {\n link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);\n }\n\n strengths = new Array(m), initializeStrength();\n distances = new Array(m), initializeDistance();\n }\n\n function initializeStrength() {\n if (!nodes) return;\n\n for (var i = 0, n = links.length; i < n; ++i) {\n strengths[i] = +strength(links[i], i, links);\n }\n }\n\n function initializeDistance() {\n if (!nodes) return;\n\n for (var i = 0, n = links.length; i < n; ++i) {\n distances[i] = +distance(links[i], i, links);\n }\n }\n\n force.initialize = function(_nodes, _random) {\n nodes = _nodes;\n random = _random;\n initialize();\n };\n\n force.links = function(_) {\n return arguments.length ? (links = _, initialize(), force) : links;\n };\n\n force.id = function(_) {\n return arguments.length ? (id = _, force) : id;\n };\n\n force.iterations = function(_) {\n return arguments.length ? (iterations = +_, force) : iterations;\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = typeof _ === \"function\" ? _ : constant(+_), initializeStrength(), force) : strength;\n };\n\n force.distance = function(_) {\n return arguments.length ? (distance = typeof _ === \"function\" ? _ : constant(+_), initializeDistance(), force) : distance;\n };\n\n return force;\n}\n","import { Transform } from 'vega-dataflow';\nimport { inherits, array, isFunction, accessorFields, hasOwnProperty, error } from 'vega-util';\nimport { forceSimulation, forceCenter, forceCollide, forceManyBody, forceLink, forceX, forceY } from 'd3-force';\n\nconst ForceMap = {\n center: forceCenter,\n collide: forceCollide,\n nbody: forceManyBody,\n link: forceLink,\n x: forceX,\n y: forceY\n};\nconst Forces = 'forces',\n ForceParams = ['alpha', 'alphaMin', 'alphaTarget', 'velocityDecay', 'forces'],\n ForceConfig = ['static', 'iterations'],\n ForceOutput = ['x', 'y', 'vx', 'vy'];\n/**\n * Force simulation layout.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} params.forces - The forces to apply.\n */\n\nfunction Force(params) {\n Transform.call(this, null, params);\n}\nForce.Definition = {\n 'type': 'Force',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'static',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'restart',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'iterations',\n 'type': 'number',\n 'default': 300\n }, {\n 'name': 'alpha',\n 'type': 'number',\n 'default': 1\n }, {\n 'name': 'alphaMin',\n 'type': 'number',\n 'default': 0.001\n }, {\n 'name': 'alphaTarget',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'velocityDecay',\n 'type': 'number',\n 'default': 0.4\n }, {\n 'name': 'forces',\n 'type': 'param',\n 'array': true,\n 'params': [{\n 'key': {\n 'force': 'center'\n },\n 'params': [{\n 'name': 'x',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'y',\n 'type': 'number',\n 'default': 0\n }]\n }, {\n 'key': {\n 'force': 'collide'\n },\n 'params': [{\n 'name': 'radius',\n 'type': 'number',\n 'expr': true\n }, {\n 'name': 'strength',\n 'type': 'number',\n 'default': 0.7\n }, {\n 'name': 'iterations',\n 'type': 'number',\n 'default': 1\n }]\n }, {\n 'key': {\n 'force': 'nbody'\n },\n 'params': [{\n 'name': 'strength',\n 'type': 'number',\n 'default': -30\n }, {\n 'name': 'theta',\n 'type': 'number',\n 'default': 0.9\n }, {\n 'name': 'distanceMin',\n 'type': 'number',\n 'default': 1\n }, {\n 'name': 'distanceMax',\n 'type': 'number'\n }]\n }, {\n 'key': {\n 'force': 'link'\n },\n 'params': [{\n 'name': 'links',\n 'type': 'data'\n }, {\n 'name': 'id',\n 'type': 'field'\n }, {\n 'name': 'distance',\n 'type': 'number',\n 'default': 30,\n 'expr': true\n }, {\n 'name': 'strength',\n 'type': 'number',\n 'expr': true\n }, {\n 'name': 'iterations',\n 'type': 'number',\n 'default': 1\n }]\n }, {\n 'key': {\n 'force': 'x'\n },\n 'params': [{\n 'name': 'strength',\n 'type': 'number',\n 'default': 0.1\n }, {\n 'name': 'x',\n 'type': 'field'\n }]\n }, {\n 'key': {\n 'force': 'y'\n },\n 'params': [{\n 'name': 'strength',\n 'type': 'number',\n 'default': 0.1\n }, {\n 'name': 'y',\n 'type': 'field'\n }]\n }]\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'modify': false,\n 'default': ForceOutput\n }]\n};\ninherits(Force, Transform, {\n transform(_, pulse) {\n var sim = this.value,\n change = pulse.changed(pulse.ADD_REM),\n params = _.modified(ForceParams),\n iters = _.iterations || 300; // configure simulation\n\n\n if (!sim) {\n this.value = sim = simulation(pulse.source, _);\n sim.on('tick', rerun(pulse.dataflow, this));\n\n if (!_.static) {\n change = true;\n sim.tick(); // ensure we run on init\n }\n\n pulse.modifies('index');\n } else {\n if (change) {\n pulse.modifies('index');\n sim.nodes(pulse.source);\n }\n\n if (params || pulse.changed(pulse.MOD)) {\n setup(sim, _, 0, pulse);\n }\n } // run simulation\n\n\n if (params || change || _.modified(ForceConfig) || pulse.changed() && _.restart) {\n sim.alpha(Math.max(sim.alpha(), _.alpha || 1)).alphaDecay(1 - Math.pow(sim.alphaMin(), 1 / iters));\n\n if (_.static) {\n for (sim.stop(); --iters >= 0;) sim.tick();\n } else {\n if (sim.stopped()) sim.restart();\n if (!change) return pulse.StopPropagation; // defer to sim ticks\n }\n }\n\n return this.finish(_, pulse);\n },\n\n finish(_, pulse) {\n const dataflow = pulse.dataflow; // inspect dependencies, touch link source data\n\n for (let args = this._argops, j = 0, m = args.length, arg; j < m; ++j) {\n arg = args[j];\n\n if (arg.name !== Forces || arg.op._argval.force !== 'link') {\n continue;\n }\n\n for (var ops = arg.op._argops, i = 0, n = ops.length, op; i < n; ++i) {\n if (ops[i].name === 'links' && (op = ops[i].op.source)) {\n dataflow.pulse(op, dataflow.changeset().reflow());\n break;\n }\n }\n } // reflow all nodes\n\n\n return pulse.reflow(_.modified()).modifies(ForceOutput);\n }\n\n});\n\nfunction rerun(df, op) {\n return () => df.touch(op).run();\n}\n\nfunction simulation(nodes, _) {\n const sim = forceSimulation(nodes),\n stop = sim.stop,\n restart = sim.restart;\n let stopped = false;\n\n sim.stopped = () => stopped;\n\n sim.restart = () => (stopped = false, restart());\n\n sim.stop = () => (stopped = true, stop());\n\n return setup(sim, _, true).on('end', () => stopped = true);\n}\n\nfunction setup(sim, _, init, pulse) {\n var f = array(_.forces),\n i,\n n,\n p,\n name;\n\n for (i = 0, n = ForceParams.length; i < n; ++i) {\n p = ForceParams[i];\n if (p !== Forces && _.modified(p)) sim[p](_[p]);\n }\n\n for (i = 0, n = f.length; i < n; ++i) {\n name = Forces + i;\n p = init || _.modified(Forces, i) ? getForce(f[i]) : pulse && modified(f[i], pulse) ? sim.force(name) : null;\n if (p) sim.force(name, p);\n }\n\n for (n = sim.numForces || 0; i < n; ++i) {\n sim.force(Forces + i, null); // remove\n }\n\n sim.numForces = f.length;\n return sim;\n}\n\nfunction modified(f, pulse) {\n var k, v;\n\n for (k in f) {\n if (isFunction(v = f[k]) && pulse.modified(accessorFields(v))) return 1;\n }\n\n return 0;\n}\n\nfunction getForce(_) {\n var f, p;\n\n if (!hasOwnProperty(ForceMap, _.force)) {\n error('Unrecognized force: ' + _.force);\n }\n\n f = ForceMap[_.force]();\n\n for (p in _) {\n if (isFunction(f[p])) setForceParam(f[p], _[p], _);\n }\n\n return f;\n}\n\nfunction setForceParam(f, v, _) {\n f(isFunction(v) ? d => v(d, _) : v);\n}\n\nexport { Force as force };\n","import {quadtree} from \"d3-quadtree\";\nimport constant from \"./constant.js\";\nimport jiggle from \"./jiggle.js\";\nimport {x, y} from \"./simulation.js\";\n\nexport default function() {\n var nodes,\n node,\n random,\n alpha,\n strength = constant(-30),\n strengths,\n distanceMin2 = 1,\n distanceMax2 = Infinity,\n theta2 = 0.81;\n\n function force(_) {\n var i, n = nodes.length, tree = quadtree(nodes, x, y).visitAfter(accumulate);\n for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply);\n }\n\n function initialize() {\n if (!nodes) return;\n var i, n = nodes.length, node;\n strengths = new Array(n);\n for (i = 0; i < n; ++i) node = nodes[i], strengths[node.index] = +strength(node, i, nodes);\n }\n\n function accumulate(quad) {\n var strength = 0, q, c, weight = 0, x, y, i;\n\n // For internal nodes, accumulate forces from child quadrants.\n if (quad.length) {\n for (x = y = i = 0; i < 4; ++i) {\n if ((q = quad[i]) && (c = Math.abs(q.value))) {\n strength += q.value, weight += c, x += c * q.x, y += c * q.y;\n }\n }\n quad.x = x / weight;\n quad.y = y / weight;\n }\n\n // For leaf nodes, accumulate forces from coincident quadrants.\n else {\n q = quad;\n q.x = q.data.x;\n q.y = q.data.y;\n do strength += strengths[q.data.index];\n while (q = q.next);\n }\n\n quad.value = strength;\n }\n\n function apply(quad, x1, _, x2) {\n if (!quad.value) return true;\n\n var x = quad.x - node.x,\n y = quad.y - node.y,\n w = x2 - x1,\n l = x * x + y * y;\n\n // Apply the Barnes-Hut approximation if possible.\n // Limit forces for very close nodes; randomize direction if coincident.\n if (w * w / theta2 < l) {\n if (l < distanceMax2) {\n if (x === 0) x = jiggle(random), l += x * x;\n if (y === 0) y = jiggle(random), l += y * y;\n if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);\n node.vx += x * quad.value * alpha / l;\n node.vy += y * quad.value * alpha / l;\n }\n return true;\n }\n\n // Otherwise, process points directly.\n else if (quad.length || l >= distanceMax2) return;\n\n // Limit forces for very close nodes; randomize direction if coincident.\n if (quad.data !== node || quad.next) {\n if (x === 0) x = jiggle(random), l += x * x;\n if (y === 0) y = jiggle(random), l += y * y;\n if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);\n }\n\n do if (quad.data !== node) {\n w = strengths[quad.data.index] * alpha / l;\n node.vx += x * w;\n node.vy += y * w;\n } while (quad = quad.next);\n }\n\n force.initialize = function(_nodes, _random) {\n nodes = _nodes;\n random = _random;\n initialize();\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : strength;\n };\n\n force.distanceMin = function(_) {\n return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);\n };\n\n force.distanceMax = function(_) {\n return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);\n };\n\n force.theta = function(_) {\n return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);\n };\n\n return force;\n}\n","import constant from \"./constant.js\";\n\nexport default function(x) {\n var strength = constant(0.1),\n nodes,\n strengths,\n xz;\n\n if (typeof x !== \"function\") x = constant(x == null ? 0 : +x);\n\n function force(alpha) {\n for (var i = 0, n = nodes.length, node; i < n; ++i) {\n node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha;\n }\n }\n\n function initialize() {\n if (!nodes) return;\n var i, n = nodes.length;\n strengths = new Array(n);\n xz = new Array(n);\n for (i = 0; i < n; ++i) {\n strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);\n }\n }\n\n force.initialize = function(_) {\n nodes = _;\n initialize();\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : strength;\n };\n\n force.x = function(_) {\n return arguments.length ? (x = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : x;\n };\n\n return force;\n}\n","import constant from \"./constant.js\";\n\nexport default function(y) {\n var strength = constant(0.1),\n nodes,\n strengths,\n yz;\n\n if (typeof y !== \"function\") y = constant(y == null ? 0 : +y);\n\n function force(alpha) {\n for (var i = 0, n = nodes.length, node; i < n; ++i) {\n node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;\n }\n }\n\n function initialize() {\n if (!nodes) return;\n var i, n = nodes.length;\n strengths = new Array(n);\n yz = new Array(n);\n for (i = 0; i < n; ++i) {\n strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);\n }\n }\n\n force.initialize = function(_) {\n nodes = _;\n initialize();\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : strength;\n };\n\n force.y = function(_) {\n return arguments.length ? (y = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : y;\n };\n\n return force;\n}\n","function count(node) {\n var sum = 0,\n children = node.children,\n i = children && children.length;\n if (!i) sum = 1;\n else while (--i >= 0) sum += children[i].value;\n node.value = sum;\n}\n\nexport default function() {\n return this.eachAfter(count);\n}\n","export default function() {\n var node = this, nodes = [node];\n while (node = node.parent) {\n nodes.push(node);\n }\n return nodes;\n}\n","export default function*() {\n var node = this, current, next = [node], children, i, n;\n do {\n current = next.reverse(), next = [];\n while (node = current.pop()) {\n yield node;\n if (children = node.children) {\n for (i = 0, n = children.length; i < n; ++i) {\n next.push(children[i]);\n }\n }\n }\n } while (next.length);\n}\n","import node_count from \"./count.js\";\nimport node_each from \"./each.js\";\nimport node_eachBefore from \"./eachBefore.js\";\nimport node_eachAfter from \"./eachAfter.js\";\nimport node_find from \"./find.js\";\nimport node_sum from \"./sum.js\";\nimport node_sort from \"./sort.js\";\nimport node_path from \"./path.js\";\nimport node_ancestors from \"./ancestors.js\";\nimport node_descendants from \"./descendants.js\";\nimport node_leaves from \"./leaves.js\";\nimport node_links from \"./links.js\";\nimport node_iterator from \"./iterator.js\";\n\nexport default function hierarchy(data, children) {\n if (data instanceof Map) {\n data = [undefined, data];\n if (children === undefined) children = mapChildren;\n } else if (children === undefined) {\n children = objectChildren;\n }\n\n var root = new Node(data),\n node,\n nodes = [root],\n child,\n childs,\n i,\n n;\n\n while (node = nodes.pop()) {\n if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) {\n node.children = childs;\n for (i = n - 1; i >= 0; --i) {\n nodes.push(child = childs[i] = new Node(childs[i]));\n child.parent = node;\n child.depth = node.depth + 1;\n }\n }\n }\n\n return root.eachBefore(computeHeight);\n}\n\nfunction node_copy() {\n return hierarchy(this).eachBefore(copyData);\n}\n\nfunction objectChildren(d) {\n return d.children;\n}\n\nfunction mapChildren(d) {\n return Array.isArray(d) ? d[1] : null;\n}\n\nfunction copyData(node) {\n if (node.data.value !== undefined) node.value = node.data.value;\n node.data = node.data.data;\n}\n\nexport function computeHeight(node) {\n var height = 0;\n do node.height = height;\n while ((node = node.parent) && (node.height < ++height));\n}\n\nexport function Node(data) {\n this.data = data;\n this.depth =\n this.height = 0;\n this.parent = null;\n}\n\nNode.prototype = hierarchy.prototype = {\n constructor: Node,\n count: node_count,\n each: node_each,\n eachAfter: node_eachAfter,\n eachBefore: node_eachBefore,\n find: node_find,\n sum: node_sum,\n sort: node_sort,\n path: node_path,\n ancestors: node_ancestors,\n descendants: node_descendants,\n leaves: node_leaves,\n links: node_links,\n copy: node_copy,\n [Symbol.iterator]: node_iterator\n};\n","export default function(callback, that) {\n let index = -1;\n for (const node of this) {\n callback.call(that, node, ++index, this);\n }\n return this;\n}\n","export default function(callback, that) {\n var node = this, nodes = [node], next = [], children, i, n, index = -1;\n while (node = nodes.pop()) {\n next.push(node);\n if (children = node.children) {\n for (i = 0, n = children.length; i < n; ++i) {\n nodes.push(children[i]);\n }\n }\n }\n while (node = next.pop()) {\n callback.call(that, node, ++index, this);\n }\n return this;\n}\n","export default function(callback, that) {\n var node = this, nodes = [node], children, i, index = -1;\n while (node = nodes.pop()) {\n callback.call(that, node, ++index, this);\n if (children = node.children) {\n for (i = children.length - 1; i >= 0; --i) {\n nodes.push(children[i]);\n }\n }\n }\n return this;\n}\n","export default function(callback, that) {\n let index = -1;\n for (const node of this) {\n if (callback.call(that, node, ++index, this)) {\n return node;\n }\n }\n}\n","export default function(value) {\n return this.eachAfter(function(node) {\n var sum = +value(node.data) || 0,\n children = node.children,\n i = children && children.length;\n while (--i >= 0) sum += children[i].value;\n node.value = sum;\n });\n}\n","export default function(compare) {\n return this.eachBefore(function(node) {\n if (node.children) {\n node.children.sort(compare);\n }\n });\n}\n","export default function(end) {\n var start = this,\n ancestor = leastCommonAncestor(start, end),\n nodes = [start];\n while (start !== ancestor) {\n start = start.parent;\n nodes.push(start);\n }\n var k = nodes.length;\n while (end !== ancestor) {\n nodes.splice(k, 0, end);\n end = end.parent;\n }\n return nodes;\n}\n\nfunction leastCommonAncestor(a, b) {\n if (a === b) return a;\n var aNodes = a.ancestors(),\n bNodes = b.ancestors(),\n c = null;\n a = aNodes.pop();\n b = bNodes.pop();\n while (a === b) {\n c = a;\n a = aNodes.pop();\n b = bNodes.pop();\n }\n return c;\n}\n","export default function() {\n return Array.from(this);\n}\n","export default function() {\n var leaves = [];\n this.eachBefore(function(node) {\n if (!node.children) {\n leaves.push(node);\n }\n });\n return leaves;\n}\n","export default function() {\n var root = this, links = [];\n root.each(function(node) {\n if (node !== root) { // Don’t include the root’s parent, if any.\n links.push({source: node.parent, target: node});\n }\n });\n return links;\n}\n","import {shuffle} from \"../array.js\";\n\nexport default function(circles) {\n var i = 0, n = (circles = shuffle(Array.from(circles))).length, B = [], p, e;\n\n while (i < n) {\n p = circles[i];\n if (e && enclosesWeak(e, p)) ++i;\n else e = encloseBasis(B = extendBasis(B, p)), i = 0;\n }\n\n return e;\n}\n\nfunction extendBasis(B, p) {\n var i, j;\n\n if (enclosesWeakAll(p, B)) return [p];\n\n // If we get here then B must have at least one element.\n for (i = 0; i < B.length; ++i) {\n if (enclosesNot(p, B[i])\n && enclosesWeakAll(encloseBasis2(B[i], p), B)) {\n return [B[i], p];\n }\n }\n\n // If we get here then B must have at least two elements.\n for (i = 0; i < B.length - 1; ++i) {\n for (j = i + 1; j < B.length; ++j) {\n if (enclosesNot(encloseBasis2(B[i], B[j]), p)\n && enclosesNot(encloseBasis2(B[i], p), B[j])\n && enclosesNot(encloseBasis2(B[j], p), B[i])\n && enclosesWeakAll(encloseBasis3(B[i], B[j], p), B)) {\n return [B[i], B[j], p];\n }\n }\n }\n\n // If we get here then something is very wrong.\n throw new Error;\n}\n\nfunction enclosesNot(a, b) {\n var dr = a.r - b.r, dx = b.x - a.x, dy = b.y - a.y;\n return dr < 0 || dr * dr < dx * dx + dy * dy;\n}\n\nfunction enclosesWeak(a, b) {\n var dr = a.r - b.r + Math.max(a.r, b.r, 1) * 1e-9, dx = b.x - a.x, dy = b.y - a.y;\n return dr > 0 && dr * dr > dx * dx + dy * dy;\n}\n\nfunction enclosesWeakAll(a, B) {\n for (var i = 0; i < B.length; ++i) {\n if (!enclosesWeak(a, B[i])) {\n return false;\n }\n }\n return true;\n}\n\nfunction encloseBasis(B) {\n switch (B.length) {\n case 1: return encloseBasis1(B[0]);\n case 2: return encloseBasis2(B[0], B[1]);\n case 3: return encloseBasis3(B[0], B[1], B[2]);\n }\n}\n\nfunction encloseBasis1(a) {\n return {\n x: a.x,\n y: a.y,\n r: a.r\n };\n}\n\nfunction encloseBasis2(a, b) {\n var x1 = a.x, y1 = a.y, r1 = a.r,\n x2 = b.x, y2 = b.y, r2 = b.r,\n x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1,\n l = Math.sqrt(x21 * x21 + y21 * y21);\n return {\n x: (x1 + x2 + x21 / l * r21) / 2,\n y: (y1 + y2 + y21 / l * r21) / 2,\n r: (l + r1 + r2) / 2\n };\n}\n\nfunction encloseBasis3(a, b, c) {\n var x1 = a.x, y1 = a.y, r1 = a.r,\n x2 = b.x, y2 = b.y, r2 = b.r,\n x3 = c.x, y3 = c.y, r3 = c.r,\n a2 = x1 - x2,\n a3 = x1 - x3,\n b2 = y1 - y2,\n b3 = y1 - y3,\n c2 = r2 - r1,\n c3 = r3 - r1,\n d1 = x1 * x1 + y1 * y1 - r1 * r1,\n d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2,\n d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3,\n ab = a3 * b2 - a2 * b3,\n xa = (b2 * d3 - b3 * d2) / (ab * 2) - x1,\n xb = (b3 * c2 - b2 * c3) / ab,\n ya = (a3 * d2 - a2 * d3) / (ab * 2) - y1,\n yb = (a2 * c3 - a3 * c2) / ab,\n A = xb * xb + yb * yb - 1,\n B = 2 * (r1 + xa * xb + ya * yb),\n C = xa * xa + ya * ya - r1 * r1,\n r = -(A ? (B + Math.sqrt(B * B - 4 * A * C)) / (2 * A) : C / B);\n return {\n x: x1 + xa + xb * r,\n y: y1 + ya + yb * r,\n r: r\n };\n}\n","export default function(x) {\n return typeof x === \"object\" && \"length\" in x\n ? x // Array, TypedArray, NodeList, array-like\n : Array.from(x); // Map, Set, iterable, string, or anything else\n}\n\nexport function shuffle(array) {\n var m = array.length,\n t,\n i;\n\n while (m) {\n i = Math.random() * m-- | 0;\n t = array[m];\n array[m] = array[i];\n array[i] = t;\n }\n\n return array;\n}\n","import array from \"../array.js\";\nimport enclose from \"./enclose.js\";\n\nfunction place(b, a, c) {\n var dx = b.x - a.x, x, a2,\n dy = b.y - a.y, y, b2,\n d2 = dx * dx + dy * dy;\n if (d2) {\n a2 = a.r + c.r, a2 *= a2;\n b2 = b.r + c.r, b2 *= b2;\n if (a2 > b2) {\n x = (d2 + b2 - a2) / (2 * d2);\n y = Math.sqrt(Math.max(0, b2 / d2 - x * x));\n c.x = b.x - x * dx - y * dy;\n c.y = b.y - x * dy + y * dx;\n } else {\n x = (d2 + a2 - b2) / (2 * d2);\n y = Math.sqrt(Math.max(0, a2 / d2 - x * x));\n c.x = a.x + x * dx - y * dy;\n c.y = a.y + x * dy + y * dx;\n }\n } else {\n c.x = a.x + c.r;\n c.y = a.y;\n }\n}\n\nfunction intersects(a, b) {\n var dr = a.r + b.r - 1e-6, dx = b.x - a.x, dy = b.y - a.y;\n return dr > 0 && dr * dr > dx * dx + dy * dy;\n}\n\nfunction score(node) {\n var a = node._,\n b = node.next._,\n ab = a.r + b.r,\n dx = (a.x * b.r + b.x * a.r) / ab,\n dy = (a.y * b.r + b.y * a.r) / ab;\n return dx * dx + dy * dy;\n}\n\nfunction Node(circle) {\n this._ = circle;\n this.next = null;\n this.previous = null;\n}\n\nexport function packEnclose(circles) {\n if (!(n = (circles = array(circles)).length)) return 0;\n\n var a, b, c, n, aa, ca, i, j, k, sj, sk;\n\n // Place the first circle.\n a = circles[0], a.x = 0, a.y = 0;\n if (!(n > 1)) return a.r;\n\n // Place the second circle.\n b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0;\n if (!(n > 2)) return a.r + b.r;\n\n // Place the third circle.\n place(b, a, c = circles[2]);\n\n // Initialize the front-chain using the first three circles a, b and c.\n a = new Node(a), b = new Node(b), c = new Node(c);\n a.next = c.previous = b;\n b.next = a.previous = c;\n c.next = b.previous = a;\n\n // Attempt to place each remaining circle…\n pack: for (i = 3; i < n; ++i) {\n place(a._, b._, c = circles[i]), c = new Node(c);\n\n // Find the closest intersecting circle on the front-chain, if any.\n // “Closeness” is determined by linear distance along the front-chain.\n // “Ahead” or “behind” is likewise determined by linear distance.\n j = b.next, k = a.previous, sj = b._.r, sk = a._.r;\n do {\n if (sj <= sk) {\n if (intersects(j._, c._)) {\n b = j, a.next = b, b.previous = a, --i;\n continue pack;\n }\n sj += j._.r, j = j.next;\n } else {\n if (intersects(k._, c._)) {\n a = k, a.next = b, b.previous = a, --i;\n continue pack;\n }\n sk += k._.r, k = k.previous;\n }\n } while (j !== k.next);\n\n // Success! Insert the new circle c between a and b.\n c.previous = a, c.next = b, a.next = b.previous = b = c;\n\n // Compute the new closest circle pair to the centroid.\n aa = score(a);\n while ((c = c.next) !== b) {\n if ((ca = score(c)) < aa) {\n a = c, aa = ca;\n }\n }\n b = a.next;\n }\n\n // Compute the enclosing circle of the front chain.\n a = [b._], c = b; while ((c = c.next) !== b) a.push(c._); c = enclose(a);\n\n // Translate the circles to put the enclosing circle around the origin.\n for (i = 0; i < n; ++i) a = circles[i], a.x -= c.x, a.y -= c.y;\n\n return c.r;\n}\n\nexport default function(circles) {\n packEnclose(circles);\n return circles;\n}\n","export function optional(f) {\n return f == null ? null : required(f);\n}\n\nexport function required(f) {\n if (typeof f !== \"function\") throw new Error;\n return f;\n}\n","export function constantZero() {\n return 0;\n}\n\nexport default function(x) {\n return function() {\n return x;\n };\n}\n","import {packEnclose} from \"./siblings.js\";\nimport {optional} from \"../accessors.js\";\nimport constant, {constantZero} from \"../constant.js\";\n\nfunction defaultRadius(d) {\n return Math.sqrt(d.value);\n}\n\nexport default function() {\n var radius = null,\n dx = 1,\n dy = 1,\n padding = constantZero;\n\n function pack(root) {\n root.x = dx / 2, root.y = dy / 2;\n if (radius) {\n root.eachBefore(radiusLeaf(radius))\n .eachAfter(packChildren(padding, 0.5))\n .eachBefore(translateChild(1));\n } else {\n root.eachBefore(radiusLeaf(defaultRadius))\n .eachAfter(packChildren(constantZero, 1))\n .eachAfter(packChildren(padding, root.r / Math.min(dx, dy)))\n .eachBefore(translateChild(Math.min(dx, dy) / (2 * root.r)));\n }\n return root;\n }\n\n pack.radius = function(x) {\n return arguments.length ? (radius = optional(x), pack) : radius;\n };\n\n pack.size = function(x) {\n return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [dx, dy];\n };\n\n pack.padding = function(x) {\n return arguments.length ? (padding = typeof x === \"function\" ? x : constant(+x), pack) : padding;\n };\n\n return pack;\n}\n\nfunction radiusLeaf(radius) {\n return function(node) {\n if (!node.children) {\n node.r = Math.max(0, +radius(node) || 0);\n }\n };\n}\n\nfunction packChildren(padding, k) {\n return function(node) {\n if (children = node.children) {\n var children,\n i,\n n = children.length,\n r = padding(node) * k || 0,\n e;\n\n if (r) for (i = 0; i < n; ++i) children[i].r += r;\n e = packEnclose(children);\n if (r) for (i = 0; i < n; ++i) children[i].r -= r;\n node.r = e + r;\n }\n };\n}\n\nfunction translateChild(k) {\n return function(node) {\n var parent = node.parent;\n node.r *= k;\n if (parent) {\n node.x = parent.x + k * node.x;\n node.y = parent.y + k * node.y;\n }\n };\n}\n","export default function(node) {\n node.x0 = Math.round(node.x0);\n node.y0 = Math.round(node.y0);\n node.x1 = Math.round(node.x1);\n node.y1 = Math.round(node.y1);\n}\n","export default function(parent, x0, y0, x1, y1) {\n var nodes = parent.children,\n node,\n i = -1,\n n = nodes.length,\n k = parent.value && (x1 - x0) / parent.value;\n\n while (++i < n) {\n node = nodes[i], node.y0 = y0, node.y1 = y1;\n node.x0 = x0, node.x1 = x0 += node.value * k;\n }\n}\n","import {required} from \"./accessors.js\";\nimport {Node, computeHeight} from \"./hierarchy/index.js\";\n\nvar preroot = {depth: -1},\n ambiguous = {};\n\nfunction defaultId(d) {\n return d.id;\n}\n\nfunction defaultParentId(d) {\n return d.parentId;\n}\n\nexport default function() {\n var id = defaultId,\n parentId = defaultParentId;\n\n function stratify(data) {\n var nodes = Array.from(data),\n n = nodes.length,\n d,\n i,\n root,\n parent,\n node,\n nodeId,\n nodeKey,\n nodeByKey = new Map;\n\n for (i = 0; i < n; ++i) {\n d = nodes[i], node = nodes[i] = new Node(d);\n if ((nodeId = id(d, i, data)) != null && (nodeId += \"\")) {\n nodeKey = node.id = nodeId;\n nodeByKey.set(nodeKey, nodeByKey.has(nodeKey) ? ambiguous : node);\n }\n if ((nodeId = parentId(d, i, data)) != null && (nodeId += \"\")) {\n node.parent = nodeId;\n }\n }\n\n for (i = 0; i < n; ++i) {\n node = nodes[i];\n if (nodeId = node.parent) {\n parent = nodeByKey.get(nodeId);\n if (!parent) throw new Error(\"missing: \" + nodeId);\n if (parent === ambiguous) throw new Error(\"ambiguous: \" + nodeId);\n if (parent.children) parent.children.push(node);\n else parent.children = [node];\n node.parent = parent;\n } else {\n if (root) throw new Error(\"multiple roots\");\n root = node;\n }\n }\n\n if (!root) throw new Error(\"no root\");\n root.parent = preroot;\n root.eachBefore(function(node) { node.depth = node.parent.depth + 1; --n; }).eachBefore(computeHeight);\n root.parent = null;\n if (n > 0) throw new Error(\"cycle\");\n\n return root;\n }\n\n stratify.id = function(x) {\n return arguments.length ? (id = required(x), stratify) : id;\n };\n\n stratify.parentId = function(x) {\n return arguments.length ? (parentId = required(x), stratify) : parentId;\n };\n\n return stratify;\n}\n","import {Node} from \"./hierarchy/index.js\";\n\nfunction defaultSeparation(a, b) {\n return a.parent === b.parent ? 1 : 2;\n}\n\n// function radialSeparation(a, b) {\n// return (a.parent === b.parent ? 1 : 2) / a.depth;\n// }\n\n// This function is used to traverse the left contour of a subtree (or\n// subforest). It returns the successor of v on this contour. This successor is\n// either given by the leftmost child of v or by the thread of v. The function\n// returns null if and only if v is on the highest level of its subtree.\nfunction nextLeft(v) {\n var children = v.children;\n return children ? children[0] : v.t;\n}\n\n// This function works analogously to nextLeft.\nfunction nextRight(v) {\n var children = v.children;\n return children ? children[children.length - 1] : v.t;\n}\n\n// Shifts the current subtree rooted at w+. This is done by increasing\n// prelim(w+) and mod(w+) by shift.\nfunction moveSubtree(wm, wp, shift) {\n var change = shift / (wp.i - wm.i);\n wp.c -= change;\n wp.s += shift;\n wm.c += change;\n wp.z += shift;\n wp.m += shift;\n}\n\n// All other shifts, applied to the smaller subtrees between w- and w+, are\n// performed by this function. To prepare the shifts, we have to adjust\n// change(w+), shift(w+), and change(w-).\nfunction executeShifts(v) {\n var shift = 0,\n change = 0,\n children = v.children,\n i = children.length,\n w;\n while (--i >= 0) {\n w = children[i];\n w.z += shift;\n w.m += shift;\n shift += w.s + (change += w.c);\n }\n}\n\n// If vi-’s ancestor is a sibling of v, returns vi-’s ancestor. Otherwise,\n// returns the specified (default) ancestor.\nfunction nextAncestor(vim, v, ancestor) {\n return vim.a.parent === v.parent ? vim.a : ancestor;\n}\n\nfunction TreeNode(node, i) {\n this._ = node;\n this.parent = null;\n this.children = null;\n this.A = null; // default ancestor\n this.a = this; // ancestor\n this.z = 0; // prelim\n this.m = 0; // mod\n this.c = 0; // change\n this.s = 0; // shift\n this.t = null; // thread\n this.i = i; // number\n}\n\nTreeNode.prototype = Object.create(Node.prototype);\n\nfunction treeRoot(root) {\n var tree = new TreeNode(root, 0),\n node,\n nodes = [tree],\n child,\n children,\n i,\n n;\n\n while (node = nodes.pop()) {\n if (children = node._.children) {\n node.children = new Array(n = children.length);\n for (i = n - 1; i >= 0; --i) {\n nodes.push(child = node.children[i] = new TreeNode(children[i], i));\n child.parent = node;\n }\n }\n }\n\n (tree.parent = new TreeNode(null, 0)).children = [tree];\n return tree;\n}\n\n// Node-link tree diagram using the Reingold-Tilford \"tidy\" algorithm\nexport default function() {\n var separation = defaultSeparation,\n dx = 1,\n dy = 1,\n nodeSize = null;\n\n function tree(root) {\n var t = treeRoot(root);\n\n // Compute the layout using Buchheim et al.’s algorithm.\n t.eachAfter(firstWalk), t.parent.m = -t.z;\n t.eachBefore(secondWalk);\n\n // If a fixed node size is specified, scale x and y.\n if (nodeSize) root.eachBefore(sizeNode);\n\n // If a fixed tree size is specified, scale x and y based on the extent.\n // Compute the left-most, right-most, and depth-most nodes for extents.\n else {\n var left = root,\n right = root,\n bottom = root;\n root.eachBefore(function(node) {\n if (node.x < left.x) left = node;\n if (node.x > right.x) right = node;\n if (node.depth > bottom.depth) bottom = node;\n });\n var s = left === right ? 1 : separation(left, right) / 2,\n tx = s - left.x,\n kx = dx / (right.x + s + tx),\n ky = dy / (bottom.depth || 1);\n root.eachBefore(function(node) {\n node.x = (node.x + tx) * kx;\n node.y = node.depth * ky;\n });\n }\n\n return root;\n }\n\n // Computes a preliminary x-coordinate for v. Before that, FIRST WALK is\n // applied recursively to the children of v, as well as the function\n // APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the\n // node v is placed to the midpoint of its outermost children.\n function firstWalk(v) {\n var children = v.children,\n siblings = v.parent.children,\n w = v.i ? siblings[v.i - 1] : null;\n if (children) {\n executeShifts(v);\n var midpoint = (children[0].z + children[children.length - 1].z) / 2;\n if (w) {\n v.z = w.z + separation(v._, w._);\n v.m = v.z - midpoint;\n } else {\n v.z = midpoint;\n }\n } else if (w) {\n v.z = w.z + separation(v._, w._);\n }\n v.parent.A = apportion(v, w, v.parent.A || siblings[0]);\n }\n\n // Computes all real x-coordinates by summing up the modifiers recursively.\n function secondWalk(v) {\n v._.x = v.z + v.parent.m;\n v.m += v.parent.m;\n }\n\n // The core of the algorithm. Here, a new subtree is combined with the\n // previous subtrees. Threads are used to traverse the inside and outside\n // contours of the left and right subtree up to the highest common level. The\n // vertices used for the traversals are vi+, vi-, vo-, and vo+, where the\n // superscript o means outside and i means inside, the subscript - means left\n // subtree and + means right subtree. For summing up the modifiers along the\n // contour, we use respective variables si+, si-, so-, and so+. Whenever two\n // nodes of the inside contours conflict, we compute the left one of the\n // greatest uncommon ancestors using the function ANCESTOR and call MOVE\n // SUBTREE to shift the subtree and prepare the shifts of smaller subtrees.\n // Finally, we add a new thread (if necessary).\n function apportion(v, w, ancestor) {\n if (w) {\n var vip = v,\n vop = v,\n vim = w,\n vom = vip.parent.children[0],\n sip = vip.m,\n sop = vop.m,\n sim = vim.m,\n som = vom.m,\n shift;\n while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) {\n vom = nextLeft(vom);\n vop = nextRight(vop);\n vop.a = v;\n shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);\n if (shift > 0) {\n moveSubtree(nextAncestor(vim, v, ancestor), v, shift);\n sip += shift;\n sop += shift;\n }\n sim += vim.m;\n sip += vip.m;\n som += vom.m;\n sop += vop.m;\n }\n if (vim && !nextRight(vop)) {\n vop.t = vim;\n vop.m += sim - sop;\n }\n if (vip && !nextLeft(vom)) {\n vom.t = vip;\n vom.m += sip - som;\n ancestor = v;\n }\n }\n return ancestor;\n }\n\n function sizeNode(node) {\n node.x *= dx;\n node.y = node.depth * dy;\n }\n\n tree.separation = function(x) {\n return arguments.length ? (separation = x, tree) : separation;\n };\n\n tree.size = function(x) {\n return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree) : (nodeSize ? null : [dx, dy]);\n };\n\n tree.nodeSize = function(x) {\n return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree) : (nodeSize ? [dx, dy] : null);\n };\n\n return tree;\n}\n","function defaultSeparation(a, b) {\n return a.parent === b.parent ? 1 : 2;\n}\n\nfunction meanX(children) {\n return children.reduce(meanXReduce, 0) / children.length;\n}\n\nfunction meanXReduce(x, c) {\n return x + c.x;\n}\n\nfunction maxY(children) {\n return 1 + children.reduce(maxYReduce, 0);\n}\n\nfunction maxYReduce(y, c) {\n return Math.max(y, c.y);\n}\n\nfunction leafLeft(node) {\n var children;\n while (children = node.children) node = children[0];\n return node;\n}\n\nfunction leafRight(node) {\n var children;\n while (children = node.children) node = children[children.length - 1];\n return node;\n}\n\nexport default function() {\n var separation = defaultSeparation,\n dx = 1,\n dy = 1,\n nodeSize = false;\n\n function cluster(root) {\n var previousNode,\n x = 0;\n\n // First walk, computing the initial x & y values.\n root.eachAfter(function(node) {\n var children = node.children;\n if (children) {\n node.x = meanX(children);\n node.y = maxY(children);\n } else {\n node.x = previousNode ? x += separation(node, previousNode) : 0;\n node.y = 0;\n previousNode = node;\n }\n });\n\n var left = leafLeft(root),\n right = leafRight(root),\n x0 = left.x - separation(left, right) / 2,\n x1 = right.x + separation(right, left) / 2;\n\n // Second walk, normalizing x & y to the desired size.\n return root.eachAfter(nodeSize ? function(node) {\n node.x = (node.x - root.x) * dx;\n node.y = (root.y - node.y) * dy;\n } : function(node) {\n node.x = (node.x - x0) / (x1 - x0) * dx;\n node.y = (1 - (root.y ? node.y / root.y : 1)) * dy;\n });\n }\n\n cluster.separation = function(x) {\n return arguments.length ? (separation = x, cluster) : separation;\n };\n\n cluster.size = function(x) {\n return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? null : [dx, dy]);\n };\n\n cluster.nodeSize = function(x) {\n return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? [dx, dy] : null);\n };\n\n return cluster;\n}\n","export default function(parent, x0, y0, x1, y1) {\n var nodes = parent.children,\n node,\n i = -1,\n n = nodes.length,\n k = parent.value && (y1 - y0) / parent.value;\n\n while (++i < n) {\n node = nodes[i], node.x0 = x0, node.x1 = x1;\n node.y0 = y0, node.y1 = y0 += node.value * k;\n }\n}\n","import treemapDice from \"./dice.js\";\nimport treemapSlice from \"./slice.js\";\n\nexport var phi = (1 + Math.sqrt(5)) / 2;\n\nexport function squarifyRatio(ratio, parent, x0, y0, x1, y1) {\n var rows = [],\n nodes = parent.children,\n row,\n nodeValue,\n i0 = 0,\n i1 = 0,\n n = nodes.length,\n dx, dy,\n value = parent.value,\n sumValue,\n minValue,\n maxValue,\n newRatio,\n minRatio,\n alpha,\n beta;\n\n while (i0 < n) {\n dx = x1 - x0, dy = y1 - y0;\n\n // Find the next non-empty node.\n do sumValue = nodes[i1++].value; while (!sumValue && i1 < n);\n minValue = maxValue = sumValue;\n alpha = Math.max(dy / dx, dx / dy) / (value * ratio);\n beta = sumValue * sumValue * alpha;\n minRatio = Math.max(maxValue / beta, beta / minValue);\n\n // Keep adding nodes while the aspect ratio maintains or improves.\n for (; i1 < n; ++i1) {\n sumValue += nodeValue = nodes[i1].value;\n if (nodeValue < minValue) minValue = nodeValue;\n if (nodeValue > maxValue) maxValue = nodeValue;\n beta = sumValue * sumValue * alpha;\n newRatio = Math.max(maxValue / beta, beta / minValue);\n if (newRatio > minRatio) { sumValue -= nodeValue; break; }\n minRatio = newRatio;\n }\n\n // Position and record the row orientation.\n rows.push(row = {value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1)});\n if (row.dice) treemapDice(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);\n else treemapSlice(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);\n value -= sumValue, i0 = i1;\n }\n\n return rows;\n}\n\nexport default (function custom(ratio) {\n\n function squarify(parent, x0, y0, x1, y1) {\n squarifyRatio(ratio, parent, x0, y0, x1, y1);\n }\n\n squarify.ratio = function(x) {\n return custom((x = +x) > 1 ? x : 1);\n };\n\n return squarify;\n})(phi);\n","import treemapDice from \"./dice.js\";\nimport treemapSlice from \"./slice.js\";\nimport {phi, squarifyRatio} from \"./squarify.js\";\n\nexport default (function custom(ratio) {\n\n function resquarify(parent, x0, y0, x1, y1) {\n if ((rows = parent._squarify) && (rows.ratio === ratio)) {\n var rows,\n row,\n nodes,\n i,\n j = -1,\n n,\n m = rows.length,\n value = parent.value;\n\n while (++j < m) {\n row = rows[j], nodes = row.children;\n for (i = row.value = 0, n = nodes.length; i < n; ++i) row.value += nodes[i].value;\n if (row.dice) treemapDice(row, x0, y0, x1, value ? y0 += (y1 - y0) * row.value / value : y1);\n else treemapSlice(row, x0, y0, value ? x0 += (x1 - x0) * row.value / value : x1, y1);\n value -= row.value;\n }\n } else {\n parent._squarify = rows = squarifyRatio(ratio, parent, x0, y0, x1, y1);\n rows.ratio = ratio;\n }\n }\n\n resquarify.ratio = function(x) {\n return custom((x = +x) > 1 ? x : 1);\n };\n\n return resquarify;\n})(phi);\n","import { Transform, isTuple, ingest, tupleid, stableCompare } from 'vega-dataflow';\nimport { inherits, error, array, one, truthy, hasOwnProperty } from 'vega-util';\nimport { hierarchy, pack, partition, stratify, tree, cluster, treemap, treemapBinary, treemapDice, treemapSlice, treemapSliceDice, treemapSquarify, treemapResquarify } from 'd3-hierarchy';\n\n// Build lookup table mapping tuple keys to tree node instances\nfunction lookup (tree, key, filter) {\n const map = {};\n tree.each(node => {\n const t = node.data;\n if (filter(t)) map[key(t)] = node;\n });\n tree.lookup = map;\n return tree;\n}\n\n/**\n * Nest tuples into a tree structure, grouped by key values.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} params.keys - The key fields to nest by, in order.\n * @param {boolean} [params.generate=false] - A boolean flag indicating if\n * non-leaf nodes generated by this transform should be included in the\n * output. The default (false) includes only the input data (leaf nodes)\n * in the data stream.\n */\n\nfunction Nest(params) {\n Transform.call(this, null, params);\n}\nNest.Definition = {\n 'type': 'Nest',\n 'metadata': {\n 'treesource': true,\n 'changes': true\n },\n 'params': [{\n 'name': 'keys',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'generate',\n 'type': 'boolean'\n }]\n};\n\nconst children = n => n.values;\n\ninherits(Nest, Transform, {\n transform(_, pulse) {\n if (!pulse.source) {\n error('Nest transform requires an upstream data source.');\n }\n\n var gen = _.generate,\n mod = _.modified(),\n out = pulse.clone(),\n tree = this.value;\n\n if (!tree || mod || pulse.changed()) {\n // collect nodes to remove\n if (tree) {\n tree.each(node => {\n if (node.children && isTuple(node.data)) {\n out.rem.push(node.data);\n }\n });\n } // generate new tree structure\n\n\n this.value = tree = hierarchy({\n values: array(_.keys).reduce((n, k) => {\n n.key(k);\n return n;\n }, nest()).entries(out.source)\n }, children); // collect nodes to add\n\n if (gen) {\n tree.each(node => {\n if (node.children) {\n node = ingest(node.data);\n out.add.push(node);\n out.source.push(node);\n }\n });\n } // build lookup table\n\n\n lookup(tree, tupleid, tupleid);\n }\n\n out.source.root = tree;\n return out;\n }\n\n});\n\nfunction nest() {\n const keys = [],\n nest = {\n entries: array => entries(apply(array, 0), 0),\n key: d => (keys.push(d), nest)\n };\n\n function apply(array, depth) {\n if (depth >= keys.length) {\n return array;\n }\n\n const n = array.length,\n key = keys[depth++],\n valuesByKey = {},\n result = {};\n let i = -1,\n keyValue,\n value,\n values;\n\n while (++i < n) {\n keyValue = key(value = array[i]) + '';\n\n if (values = valuesByKey[keyValue]) {\n values.push(value);\n } else {\n valuesByKey[keyValue] = [value];\n }\n }\n\n for (keyValue in valuesByKey) {\n result[keyValue] = apply(valuesByKey[keyValue], depth);\n }\n\n return result;\n }\n\n function entries(map, depth) {\n if (++depth > keys.length) return map;\n const array = [];\n\n for (const key in map) {\n array.push({\n key,\n values: entries(map[key], depth)\n });\n }\n\n return array;\n }\n\n return nest;\n}\n\n/**\n * Abstract class for tree layout.\n * @constructor\n * @param {object} params - The parameters for this operator.\n */\n\nfunction HierarchyLayout(params) {\n Transform.call(this, null, params);\n}\n\nconst defaultSeparation = (a, b) => a.parent === b.parent ? 1 : 2;\n\ninherits(HierarchyLayout, Transform, {\n transform(_, pulse) {\n if (!pulse.source || !pulse.source.root) {\n error(this.constructor.name + ' transform requires a backing tree data source.');\n }\n\n const layout = this.layout(_.method),\n fields = this.fields,\n root = pulse.source.root,\n as = _.as || fields;\n if (_.field) root.sum(_.field);else root.count();\n if (_.sort) root.sort(stableCompare(_.sort, d => d.data));\n setParams(layout, this.params, _);\n\n if (layout.separation) {\n layout.separation(_.separation !== false ? defaultSeparation : one);\n }\n\n try {\n this.value = layout(root);\n } catch (err) {\n error(err);\n }\n\n root.each(node => setFields(node, fields, as));\n return pulse.reflow(_.modified()).modifies(as).modifies('leaf');\n }\n\n});\n\nfunction setParams(layout, params, _) {\n for (let p, i = 0, n = params.length; i < n; ++i) {\n p = params[i];\n if (p in _) layout[p](_[p]);\n }\n}\n\nfunction setFields(node, fields, as) {\n const t = node.data,\n n = fields.length - 1;\n\n for (let i = 0; i < n; ++i) {\n t[as[i]] = node[fields[i]];\n }\n\n t[as[n]] = node.children ? node.children.length : 0;\n}\n\nconst Output = ['x', 'y', 'r', 'depth', 'children'];\n/**\n * Packed circle tree layout.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The value field to size nodes.\n */\n\nfunction Pack(params) {\n HierarchyLayout.call(this, params);\n}\nPack.Definition = {\n 'type': 'Pack',\n 'metadata': {\n 'tree': true,\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field'\n }, {\n 'name': 'sort',\n 'type': 'compare'\n }, {\n 'name': 'padding',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'radius',\n 'type': 'field',\n 'default': null\n }, {\n 'name': 'size',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': Output.length,\n 'default': Output\n }]\n};\ninherits(Pack, HierarchyLayout, {\n layout: pack,\n params: ['radius', 'size', 'padding'],\n fields: Output\n});\n\nconst Output$1 = ['x0', 'y0', 'x1', 'y1', 'depth', 'children'];\n/**\n * Partition tree layout.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The value field to size nodes.\n */\n\nfunction Partition(params) {\n HierarchyLayout.call(this, params);\n}\nPartition.Definition = {\n 'type': 'Partition',\n 'metadata': {\n 'tree': true,\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field'\n }, {\n 'name': 'sort',\n 'type': 'compare'\n }, {\n 'name': 'padding',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'round',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'size',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': Output$1.length,\n 'default': Output$1\n }]\n};\ninherits(Partition, HierarchyLayout, {\n layout: partition,\n params: ['size', 'round', 'padding'],\n fields: Output$1\n});\n\n/**\n * Stratify a collection of tuples into a tree structure based on\n * id and parent id fields.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.key - Unique key field for each tuple.\n * @param {function(object): *} params.parentKey - Field with key for parent tuple.\n */\n\nfunction Stratify(params) {\n Transform.call(this, null, params);\n}\nStratify.Definition = {\n 'type': 'Stratify',\n 'metadata': {\n 'treesource': true\n },\n 'params': [{\n 'name': 'key',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'parentKey',\n 'type': 'field',\n 'required': true\n }]\n};\ninherits(Stratify, Transform, {\n transform(_, pulse) {\n if (!pulse.source) {\n error('Stratify transform requires an upstream data source.');\n }\n\n let tree = this.value;\n\n const mod = _.modified(),\n out = pulse.fork(pulse.ALL).materialize(pulse.SOURCE),\n run = !tree || mod || pulse.changed(pulse.ADD_REM) || pulse.modified(_.key.fields) || pulse.modified(_.parentKey.fields); // prevent upstream source pollution\n\n\n out.source = out.source.slice();\n\n if (run) {\n tree = out.source.length ? lookup(stratify().id(_.key).parentId(_.parentKey)(out.source), _.key, truthy) : lookup(stratify()([{}]), _.key, _.key);\n }\n\n out.source.root = this.value = tree;\n return out;\n }\n\n});\n\nconst Layouts = {\n tidy: tree,\n cluster: cluster\n};\nconst Output$2 = ['x', 'y', 'depth', 'children'];\n/**\n * Tree layout. Depending on the method parameter, performs either\n * Reingold-Tilford 'tidy' layout or dendrogram 'cluster' layout.\n * @constructor\n * @param {object} params - The parameters for this operator.\n */\n\nfunction Tree(params) {\n HierarchyLayout.call(this, params);\n}\nTree.Definition = {\n 'type': 'Tree',\n 'metadata': {\n 'tree': true,\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field'\n }, {\n 'name': 'sort',\n 'type': 'compare'\n }, {\n 'name': 'method',\n 'type': 'enum',\n 'default': 'tidy',\n 'values': ['tidy', 'cluster']\n }, {\n 'name': 'size',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'nodeSize',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'separation',\n 'type': 'boolean',\n 'default': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': Output$2.length,\n 'default': Output$2\n }]\n};\ninherits(Tree, HierarchyLayout, {\n /**\n * Tree layout generator. Supports both 'tidy' and 'cluster' layouts.\n */\n layout(method) {\n const m = method || 'tidy';\n if (hasOwnProperty(Layouts, m)) return Layouts[m]();else error('Unrecognized Tree layout method: ' + m);\n },\n\n params: ['size', 'nodeSize'],\n fields: Output$2\n});\n\n/**\n * Generate tuples representing links between tree nodes.\n * The resulting tuples will contain 'source' and 'target' fields,\n * which point to parent and child node tuples, respectively.\n * @constructor\n * @param {object} params - The parameters for this operator.\n */\n\nfunction TreeLinks(params) {\n Transform.call(this, [], params);\n}\nTreeLinks.Definition = {\n 'type': 'TreeLinks',\n 'metadata': {\n 'tree': true,\n 'generates': true,\n 'changes': true\n },\n 'params': []\n};\ninherits(TreeLinks, Transform, {\n transform(_, pulse) {\n const links = this.value,\n tree = pulse.source && pulse.source.root,\n out = pulse.fork(pulse.NO_SOURCE),\n lut = {};\n if (!tree) error('TreeLinks transform requires a tree data source.');\n\n if (pulse.changed(pulse.ADD_REM)) {\n // remove previous links\n out.rem = links; // build lookup table of valid tuples\n\n pulse.visit(pulse.SOURCE, t => lut[tupleid(t)] = 1); // generate links for all edges incident on valid tuples\n\n tree.each(node => {\n const t = node.data,\n p = node.parent && node.parent.data;\n\n if (p && lut[tupleid(t)] && lut[tupleid(p)]) {\n out.add.push(ingest({\n source: p,\n target: t\n }));\n }\n });\n this.value = out.add;\n } else if (pulse.changed(pulse.MOD)) {\n // build lookup table of modified tuples\n pulse.visit(pulse.MOD, t => lut[tupleid(t)] = 1); // gather links incident on modified tuples\n\n links.forEach(link => {\n if (lut[tupleid(link.source)] || lut[tupleid(link.target)]) {\n out.mod.push(link);\n }\n });\n }\n\n return out;\n }\n\n});\n\nconst Tiles = {\n binary: treemapBinary,\n dice: treemapDice,\n slice: treemapSlice,\n slicedice: treemapSliceDice,\n squarify: treemapSquarify,\n resquarify: treemapResquarify\n};\nconst Output$3 = ['x0', 'y0', 'x1', 'y1', 'depth', 'children'];\n/**\n * Treemap layout.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.field - The value field to size nodes.\n */\n\nfunction Treemap(params) {\n HierarchyLayout.call(this, params);\n}\nTreemap.Definition = {\n 'type': 'Treemap',\n 'metadata': {\n 'tree': true,\n 'modifies': true\n },\n 'params': [{\n 'name': 'field',\n 'type': 'field'\n }, {\n 'name': 'sort',\n 'type': 'compare'\n }, {\n 'name': 'method',\n 'type': 'enum',\n 'default': 'squarify',\n 'values': ['squarify', 'resquarify', 'binary', 'dice', 'slice', 'slicedice']\n }, {\n 'name': 'padding',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'paddingInner',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'paddingOuter',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'paddingTop',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'paddingRight',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'paddingBottom',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'paddingLeft',\n 'type': 'number',\n 'default': 0\n }, {\n 'name': 'ratio',\n 'type': 'number',\n 'default': 1.618033988749895\n }, {\n 'name': 'round',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'size',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': Output$3.length,\n 'default': Output$3\n }]\n};\ninherits(Treemap, HierarchyLayout, {\n /**\n * Treemap layout generator. Adds 'method' and 'ratio' parameters\n * to configure the underlying tile method.\n */\n layout() {\n const x = treemap();\n\n x.ratio = _ => {\n const t = x.tile();\n if (t.ratio) x.tile(t.ratio(_));\n };\n\n x.method = _ => {\n if (hasOwnProperty(Tiles, _)) x.tile(Tiles[_]);else error('Unrecognized Treemap layout method: ' + _);\n };\n\n return x;\n },\n\n params: ['method', 'ratio', 'size', 'round', 'padding', 'paddingInner', 'paddingOuter', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'],\n fields: Output$3\n});\n\nexport { Nest as nest, Pack as pack, Partition as partition, Stratify as stratify, Tree as tree, TreeLinks as treelinks, Treemap as treemap };\n","import roundNode from \"./treemap/round.js\";\nimport treemapDice from \"./treemap/dice.js\";\n\nexport default function() {\n var dx = 1,\n dy = 1,\n padding = 0,\n round = false;\n\n function partition(root) {\n var n = root.height + 1;\n root.x0 =\n root.y0 = padding;\n root.x1 = dx;\n root.y1 = dy / n;\n root.eachBefore(positionNode(dy, n));\n if (round) root.eachBefore(roundNode);\n return root;\n }\n\n function positionNode(dy, n) {\n return function(node) {\n if (node.children) {\n treemapDice(node, node.x0, dy * (node.depth + 1) / n, node.x1, dy * (node.depth + 2) / n);\n }\n var x0 = node.x0,\n y0 = node.y0,\n x1 = node.x1 - padding,\n y1 = node.y1 - padding;\n if (x1 < x0) x0 = x1 = (x0 + x1) / 2;\n if (y1 < y0) y0 = y1 = (y0 + y1) / 2;\n node.x0 = x0;\n node.y0 = y0;\n node.x1 = x1;\n node.y1 = y1;\n };\n }\n\n partition.round = function(x) {\n return arguments.length ? (round = !!x, partition) : round;\n };\n\n partition.size = function(x) {\n return arguments.length ? (dx = +x[0], dy = +x[1], partition) : [dx, dy];\n };\n\n partition.padding = function(x) {\n return arguments.length ? (padding = +x, partition) : padding;\n };\n\n return partition;\n}\n","export default function(parent, x0, y0, x1, y1) {\n var nodes = parent.children,\n i, n = nodes.length,\n sum, sums = new Array(n + 1);\n\n for (sums[0] = sum = i = 0; i < n; ++i) {\n sums[i + 1] = sum += nodes[i].value;\n }\n\n partition(0, n, parent.value, x0, y0, x1, y1);\n\n function partition(i, j, value, x0, y0, x1, y1) {\n if (i >= j - 1) {\n var node = nodes[i];\n node.x0 = x0, node.y0 = y0;\n node.x1 = x1, node.y1 = y1;\n return;\n }\n\n var valueOffset = sums[i],\n valueTarget = (value / 2) + valueOffset,\n k = i + 1,\n hi = j - 1;\n\n while (k < hi) {\n var mid = k + hi >>> 1;\n if (sums[mid] < valueTarget) k = mid + 1;\n else hi = mid;\n }\n\n if ((valueTarget - sums[k - 1]) < (sums[k] - valueTarget) && i + 1 < k) --k;\n\n var valueLeft = sums[k] - valueOffset,\n valueRight = value - valueLeft;\n\n if ((x1 - x0) > (y1 - y0)) {\n var xk = value ? (x0 * valueRight + x1 * valueLeft) / value : x1;\n partition(i, k, valueLeft, x0, y0, xk, y1);\n partition(k, j, valueRight, xk, y0, x1, y1);\n } else {\n var yk = value ? (y0 * valueRight + y1 * valueLeft) / value : y1;\n partition(i, k, valueLeft, x0, y0, x1, yk);\n partition(k, j, valueRight, x0, yk, x1, y1);\n }\n }\n}\n","import dice from \"./dice.js\";\nimport slice from \"./slice.js\";\n\nexport default function(parent, x0, y0, x1, y1) {\n (parent.depth & 1 ? slice : dice)(parent, x0, y0, x1, y1);\n}\n","import roundNode from \"./round.js\";\nimport squarify from \"./squarify.js\";\nimport {required} from \"../accessors.js\";\nimport constant, {constantZero} from \"../constant.js\";\n\nexport default function() {\n var tile = squarify,\n round = false,\n dx = 1,\n dy = 1,\n paddingStack = [0],\n paddingInner = constantZero,\n paddingTop = constantZero,\n paddingRight = constantZero,\n paddingBottom = constantZero,\n paddingLeft = constantZero;\n\n function treemap(root) {\n root.x0 =\n root.y0 = 0;\n root.x1 = dx;\n root.y1 = dy;\n root.eachBefore(positionNode);\n paddingStack = [0];\n if (round) root.eachBefore(roundNode);\n return root;\n }\n\n function positionNode(node) {\n var p = paddingStack[node.depth],\n x0 = node.x0 + p,\n y0 = node.y0 + p,\n x1 = node.x1 - p,\n y1 = node.y1 - p;\n if (x1 < x0) x0 = x1 = (x0 + x1) / 2;\n if (y1 < y0) y0 = y1 = (y0 + y1) / 2;\n node.x0 = x0;\n node.y0 = y0;\n node.x1 = x1;\n node.y1 = y1;\n if (node.children) {\n p = paddingStack[node.depth + 1] = paddingInner(node) / 2;\n x0 += paddingLeft(node) - p;\n y0 += paddingTop(node) - p;\n x1 -= paddingRight(node) - p;\n y1 -= paddingBottom(node) - p;\n if (x1 < x0) x0 = x1 = (x0 + x1) / 2;\n if (y1 < y0) y0 = y1 = (y0 + y1) / 2;\n tile(node, x0, y0, x1, y1);\n }\n }\n\n treemap.round = function(x) {\n return arguments.length ? (round = !!x, treemap) : round;\n };\n\n treemap.size = function(x) {\n return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];\n };\n\n treemap.tile = function(x) {\n return arguments.length ? (tile = required(x), treemap) : tile;\n };\n\n treemap.padding = function(x) {\n return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();\n };\n\n treemap.paddingInner = function(x) {\n return arguments.length ? (paddingInner = typeof x === \"function\" ? x : constant(+x), treemap) : paddingInner;\n };\n\n treemap.paddingOuter = function(x) {\n return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();\n };\n\n treemap.paddingTop = function(x) {\n return arguments.length ? (paddingTop = typeof x === \"function\" ? x : constant(+x), treemap) : paddingTop;\n };\n\n treemap.paddingRight = function(x) {\n return arguments.length ? (paddingRight = typeof x === \"function\" ? x : constant(+x), treemap) : paddingRight;\n };\n\n treemap.paddingBottom = function(x) {\n return arguments.length ? (paddingBottom = typeof x === \"function\" ? x : constant(+x), treemap) : paddingBottom;\n };\n\n treemap.paddingLeft = function(x) {\n return arguments.length ? (paddingLeft = typeof x === \"function\" ? x : constant(+x), treemap) : paddingLeft;\n };\n\n return treemap;\n}\n","import { canvas } from 'vega-canvas';\nimport { rederive, Transform } from 'vega-dataflow';\nimport { Marks, textMetrics } from 'vega-scenegraph';\nimport { inherits, isFunction, error, array } from 'vega-util';\n\nconst ALPHA_MASK = 0xff000000; // alpha value equivalent to opacity 0.0625\n\nconst INSIDE_OPACITY_IN_ALPHA = 0x10000000;\nconst INSIDE_OPACITY = 0.0625;\nfunction baseBitmaps($, data) {\n const bitmap = $.bitmap(); // when there is no base mark but data points are to be avoided\n\n (data || []).forEach(d => bitmap.set($(d.boundary[0]), $(d.boundary[3])));\n return [bitmap, undefined];\n}\nfunction markBitmaps($, avoidMarks, labelInside, isGroupArea) {\n // create canvas\n const width = $.width,\n height = $.height,\n border = labelInside || isGroupArea,\n context = canvas(width, height).getContext('2d'); // render all marks to be avoided into canvas\n\n avoidMarks.forEach(items => draw(context, items, border)); // get canvas buffer, create bitmaps\n\n const buffer = new Uint32Array(context.getImageData(0, 0, width, height).data.buffer),\n layer1 = $.bitmap(),\n layer2 = border && $.bitmap(); // populate bitmap layers\n\n let x, y, u, v, alpha;\n\n for (y = 0; y < height; ++y) {\n for (x = 0; x < width; ++x) {\n alpha = buffer[y * width + x] & ALPHA_MASK;\n\n if (alpha) {\n u = $(x);\n v = $(y);\n if (!isGroupArea) layer1.set(u, v); // update interior bitmap\n\n if (border && alpha ^ INSIDE_OPACITY_IN_ALPHA) layer2.set(u, v); // update border bitmap\n }\n }\n }\n\n return [layer1, layer2];\n}\n\nfunction draw(context, items, interior) {\n if (!items.length) return;\n const type = items[0].mark.marktype;\n\n if (type === 'group') {\n items.forEach(group => {\n group.items.forEach(mark => draw(context, mark.items, interior));\n });\n } else {\n Marks[type].draw(context, {\n items: interior ? items.map(prepare) : items\n });\n }\n}\n/**\n * Prepare item before drawing into canvas (setting stroke and opacity)\n * @param {object} source item to be prepared\n * @returns prepared item\n */\n\n\nfunction prepare(source) {\n const item = rederive(source, {});\n\n if (item.stroke) {\n item.strokeOpacity = 1;\n }\n\n if (item.fill) {\n item.fillOpacity = INSIDE_OPACITY;\n item.stroke = '#000';\n item.strokeOpacity = 1;\n item.strokeWidth = 2;\n }\n\n return item;\n}\n\nconst DIV = 5,\n // bit shift from x, y index to bit vector array index\nMOD = 31,\n // bit mask for index lookup within a bit vector\nSIZE = 32,\n // individual bit vector size\nRIGHT0 = new Uint32Array(SIZE + 1),\n // left-anchored bit vectors, full -> 0\nRIGHT1 = new Uint32Array(SIZE + 1); // right-anchored bit vectors, 0 -> full\n\nRIGHT1[0] = 0;\nRIGHT0[0] = ~RIGHT1[0];\n\nfor (let i = 1; i <= SIZE; ++i) {\n RIGHT1[i] = RIGHT1[i - 1] << 1 | 1;\n RIGHT0[i] = ~RIGHT1[i];\n}\n\nfunction Bitmap (w, h) {\n const array = new Uint32Array(~~((w * h + SIZE) / SIZE));\n\n function _set(index, mask) {\n array[index] |= mask;\n }\n\n function _clear(index, mask) {\n array[index] &= mask;\n }\n\n return {\n array: array,\n get: (x, y) => {\n const index = y * w + x;\n return array[index >>> DIV] & 1 << (index & MOD);\n },\n set: (x, y) => {\n const index = y * w + x;\n\n _set(index >>> DIV, 1 << (index & MOD));\n },\n clear: (x, y) => {\n const index = y * w + x;\n\n _clear(index >>> DIV, ~(1 << (index & MOD)));\n },\n getRange: (x, y, x2, y2) => {\n let r = y2,\n start,\n end,\n indexStart,\n indexEnd;\n\n for (; r >= y; --r) {\n start = r * w + x;\n end = r * w + x2;\n indexStart = start >>> DIV;\n indexEnd = end >>> DIV;\n\n if (indexStart === indexEnd) {\n if (array[indexStart] & RIGHT0[start & MOD] & RIGHT1[(end & MOD) + 1]) {\n return true;\n }\n } else {\n if (array[indexStart] & RIGHT0[start & MOD]) return true;\n if (array[indexEnd] & RIGHT1[(end & MOD) + 1]) return true;\n\n for (let i = indexStart + 1; i < indexEnd; ++i) {\n if (array[i]) return true;\n }\n }\n }\n\n return false;\n },\n setRange: (x, y, x2, y2) => {\n let start, end, indexStart, indexEnd, i;\n\n for (; y <= y2; ++y) {\n start = y * w + x;\n end = y * w + x2;\n indexStart = start >>> DIV;\n indexEnd = end >>> DIV;\n\n if (indexStart === indexEnd) {\n _set(indexStart, RIGHT0[start & MOD] & RIGHT1[(end & MOD) + 1]);\n } else {\n _set(indexStart, RIGHT0[start & MOD]);\n\n _set(indexEnd, RIGHT1[(end & MOD) + 1]);\n\n for (i = indexStart + 1; i < indexEnd; ++i) _set(i, 0xffffffff);\n }\n }\n },\n clearRange: (x, y, x2, y2) => {\n let start, end, indexStart, indexEnd, i;\n\n for (; y <= y2; ++y) {\n start = y * w + x;\n end = y * w + x2;\n indexStart = start >>> DIV;\n indexEnd = end >>> DIV;\n\n if (indexStart === indexEnd) {\n _clear(indexStart, RIGHT1[start & MOD] | RIGHT0[(end & MOD) + 1]);\n } else {\n _clear(indexStart, RIGHT1[start & MOD]);\n\n _clear(indexEnd, RIGHT0[(end & MOD) + 1]);\n\n for (i = indexStart + 1; i < indexEnd; ++i) _clear(i, 0);\n }\n }\n },\n outOfBounds: (x, y, x2, y2) => x < 0 || y < 0 || y2 >= h || x2 >= w\n };\n}\n\nfunction scaler (width, height, padding) {\n const ratio = Math.max(1, Math.sqrt(width * height / 1e6)),\n w = ~~((width + 2 * padding + ratio) / ratio),\n h = ~~((height + 2 * padding + ratio) / ratio),\n scale = _ => ~~((_ + padding) / ratio);\n\n scale.invert = _ => _ * ratio - padding;\n\n scale.bitmap = () => Bitmap(w, h);\n\n scale.ratio = ratio;\n scale.padding = padding;\n scale.width = width;\n scale.height = height;\n return scale;\n}\n\nfunction placeAreaLabelNaive ($, bitmaps, avoidBaseMark, markIndex) {\n const width = $.width,\n height = $.height; // try to place a label within an input area mark\n\n return function (d) {\n const items = d.datum.datum.items[markIndex].items,\n // area points\n n = items.length,\n // number of points\n textHeight = d.datum.fontSize,\n // label width\n textWidth = textMetrics.width(d.datum, d.datum.text); // label height\n\n let maxAreaWidth = 0,\n x1,\n x2,\n y1,\n y2,\n x,\n y,\n areaWidth; // for each area sample point\n\n for (let i = 0; i < n; ++i) {\n x1 = items[i].x;\n y1 = items[i].y;\n x2 = items[i].x2 === undefined ? x1 : items[i].x2;\n y2 = items[i].y2 === undefined ? y1 : items[i].y2;\n x = (x1 + x2) / 2;\n y = (y1 + y2) / 2;\n areaWidth = Math.abs(x2 - x1 + y2 - y1);\n\n if (areaWidth >= maxAreaWidth) {\n maxAreaWidth = areaWidth;\n d.x = x;\n d.y = y;\n }\n }\n\n x = textWidth / 2;\n y = textHeight / 2;\n x1 = d.x - x;\n x2 = d.x + x;\n y1 = d.y - y;\n y2 = d.y + y;\n d.align = 'center';\n\n if (x1 < 0 && x2 <= width) {\n d.align = 'left';\n } else if (0 <= x1 && width < x2) {\n d.align = 'right';\n }\n\n d.baseline = 'middle';\n\n if (y1 < 0 && y2 <= height) {\n d.baseline = 'top';\n } else if (0 <= y1 && height < y2) {\n d.baseline = 'bottom';\n }\n\n return true;\n };\n}\n\nfunction outOfBounds(x, y, textWidth, textHeight, width, height) {\n let r = textWidth / 2;\n return x - r < 0 || x + r > width || y - (r = textHeight / 2) < 0 || y + r > height;\n}\n\nfunction _outOfBounds() {\n return false;\n}\n\nfunction collision($, x, y, textHeight, textWidth, h, bm0, bm1) {\n const w = textWidth * h / (textHeight * 2),\n x1 = $(x - w),\n x2 = $(x + w),\n y1 = $(y - (h = h / 2)),\n y2 = $(y + h);\n return bm0.outOfBounds(x1, y1, x2, y2) || bm0.getRange(x1, y1, x2, y2) || bm1 && bm1.getRange(x1, y1, x2, y2);\n}\n\nfunction _collision($, x, y, textHeight, textWidth, h, bm0, bm1) {\n const w = textWidth * h / (textHeight * 2);\n let x1 = $(x - w),\n x2 = $(x + w),\n y1 = $(y - (h = h / 2)),\n y2 = $(y + h);\n x1 = x1 > 0 ? x1 : 0;\n y1 = y1 > 0 ? y1 : 0;\n x2 = x2 < $.width ? x2 : $.width - 1;\n y2 = y2 < $.height ? y2 : $.height - 1;\n return bm0.getRange(x1, y1, x2, y2) || bm1 && bm1.getRange(x1, y1, x2, y2);\n}\n\nfunction getTests(infPadding) {\n return infPadding ? [_collision, _outOfBounds] : [collision, outOfBounds];\n}\n\nfunction placeAreaLabelReducedSearch ($, bitmaps, avoidBaseMark, markIndex, infPadding) {\n const width = $.width,\n height = $.height,\n [collision, outOfBounds] = getTests(infPadding),\n bm0 = bitmaps[0],\n // where labels have been placed\n bm1 = bitmaps[1]; // area outlines\n\n function tryLabel(_x, _y, maxSize, textWidth, textHeight) {\n const x = $.invert(_x),\n y = $.invert(_y);\n let lo = maxSize,\n hi = height,\n mid;\n\n if (!outOfBounds(x, y, textWidth, textHeight, width, height) && !collision($, x, y, textHeight, textWidth, lo, bm0, bm1) && !collision($, x, y, textHeight, textWidth, textHeight, bm0, null)) {\n // if the label fits at the current sample point,\n // perform binary search to find the largest font size that fits\n while (hi - lo >= 1) {\n mid = (lo + hi) / 2;\n\n if (collision($, x, y, textHeight, textWidth, mid, bm0, bm1)) {\n hi = mid;\n } else {\n lo = mid;\n }\n } // place label if current lower bound exceeds prior max font size\n\n\n if (lo > maxSize) {\n return [x, y, lo, true];\n }\n }\n } // try to place a label within an input area mark\n\n\n return function (d) {\n const items = d.datum.datum.items[markIndex].items,\n // area points\n n = items.length,\n // number of points\n textHeight = d.datum.fontSize,\n // label width\n textWidth = textMetrics.width(d.datum, d.datum.text); // label height\n\n let maxSize = avoidBaseMark ? textHeight : 0,\n labelPlaced = false,\n labelPlaced2 = false,\n maxAreaWidth = 0,\n x1,\n x2,\n y1,\n y2,\n x,\n y,\n _x,\n _y,\n _x1,\n _xMid,\n _x2,\n _y1,\n _yMid,\n _y2,\n areaWidth,\n result,\n swapTmp; // for each area sample point\n\n\n for (let i = 0; i < n; ++i) {\n x1 = items[i].x;\n y1 = items[i].y;\n x2 = items[i].x2 === undefined ? x1 : items[i].x2;\n y2 = items[i].y2 === undefined ? y1 : items[i].y2;\n\n if (x1 > x2) {\n swapTmp = x1;\n x1 = x2;\n x2 = swapTmp;\n }\n\n if (y1 > y2) {\n swapTmp = y1;\n y1 = y2;\n y2 = swapTmp;\n }\n\n _x1 = $(x1);\n _x2 = $(x2);\n _xMid = ~~((_x1 + _x2) / 2);\n _y1 = $(y1);\n _y2 = $(y2);\n _yMid = ~~((_y1 + _y2) / 2); // search along the line from mid point between the 2 border to lower border\n\n for (_x = _xMid; _x >= _x1; --_x) {\n for (_y = _yMid; _y >= _y1; --_y) {\n result = tryLabel(_x, _y, maxSize, textWidth, textHeight);\n\n if (result) {\n [d.x, d.y, maxSize, labelPlaced] = result;\n }\n }\n } // search along the line from mid point between the 2 border to upper border\n\n\n for (_x = _xMid; _x <= _x2; ++_x) {\n for (_y = _yMid; _y <= _y2; ++_y) {\n result = tryLabel(_x, _y, maxSize, textWidth, textHeight);\n\n if (result) {\n [d.x, d.y, maxSize, labelPlaced] = result;\n }\n }\n } // place label at slice center if not placed through other means\n // and if we're not avoiding overlap with other areas\n\n\n if (!labelPlaced && !avoidBaseMark) {\n // one span is zero, hence we can add\n areaWidth = Math.abs(x2 - x1 + y2 - y1);\n x = (x1 + x2) / 2;\n y = (y1 + y2) / 2; // place label if it fits and improves the max area width\n\n if (areaWidth >= maxAreaWidth && !outOfBounds(x, y, textWidth, textHeight, width, height) && !collision($, x, y, textHeight, textWidth, textHeight, bm0, null)) {\n maxAreaWidth = areaWidth;\n d.x = x;\n d.y = y;\n labelPlaced2 = true;\n }\n }\n } // record current label placement information, update label bitmap\n\n\n if (labelPlaced || labelPlaced2) {\n x = textWidth / 2;\n y = textHeight / 2;\n bm0.setRange($(d.x - x), $(d.y - y), $(d.x + x), $(d.y + y));\n d.align = 'center';\n d.baseline = 'middle';\n return true;\n } else {\n return false;\n }\n };\n}\n\nconst X_DIR = [-1, -1, 1, 1];\nconst Y_DIR = [-1, 1, -1, 1];\nfunction placeAreaLabelFloodFill ($, bitmaps, avoidBaseMark, markIndex, infPadding) {\n const width = $.width,\n height = $.height,\n [collision, outOfBounds] = getTests(infPadding),\n bm0 = bitmaps[0],\n // where labels have been placed\n bm1 = bitmaps[1],\n // area outlines\n bm2 = $.bitmap(); // flood-fill visitations\n // try to place a label within an input area mark\n\n return function (d) {\n const items = d.datum.datum.items[markIndex].items,\n // area points\n n = items.length,\n // number of points\n textHeight = d.datum.fontSize,\n // label width\n textWidth = textMetrics.width(d.datum, d.datum.text),\n // label height\n stack = []; // flood fill stack\n\n let maxSize = avoidBaseMark ? textHeight : 0,\n labelPlaced = false,\n labelPlaced2 = false,\n maxAreaWidth = 0,\n x1,\n x2,\n y1,\n y2,\n x,\n y,\n _x,\n _y,\n lo,\n hi,\n mid,\n areaWidth; // for each area sample point\n\n\n for (let i = 0; i < n; ++i) {\n x1 = items[i].x;\n y1 = items[i].y;\n x2 = items[i].x2 === undefined ? x1 : items[i].x2;\n y2 = items[i].y2 === undefined ? y1 : items[i].y2; // add scaled center point to stack\n\n stack.push([$((x1 + x2) / 2), $((y1 + y2) / 2)]); // perform flood fill, visit points\n\n while (stack.length) {\n [_x, _y] = stack.pop(); // exit if point already marked\n\n if (bm0.get(_x, _y) || bm1.get(_x, _y) || bm2.get(_x, _y)) continue; // mark point in flood fill bitmap\n // add search points for all (in bound) directions\n\n bm2.set(_x, _y);\n\n for (let j = 0; j < 4; ++j) {\n x = _x + X_DIR[j];\n y = _y + Y_DIR[j];\n if (!bm2.outOfBounds(x, y, x, y)) stack.push([x, y]);\n } // unscale point back to x, y space\n\n\n x = $.invert(_x);\n y = $.invert(_y);\n lo = maxSize;\n hi = height; // TODO: make this bound smaller\n\n if (!outOfBounds(x, y, textWidth, textHeight, width, height) && !collision($, x, y, textHeight, textWidth, lo, bm0, bm1) && !collision($, x, y, textHeight, textWidth, textHeight, bm0, null)) {\n // if the label fits at the current sample point,\n // perform binary search to find the largest font size that fits\n while (hi - lo >= 1) {\n mid = (lo + hi) / 2;\n\n if (collision($, x, y, textHeight, textWidth, mid, bm0, bm1)) {\n hi = mid;\n } else {\n lo = mid;\n }\n } // place label if current lower bound exceeds prior max font size\n\n\n if (lo > maxSize) {\n d.x = x;\n d.y = y;\n maxSize = lo;\n labelPlaced = true;\n }\n }\n } // place label at slice center if not placed through other means\n // and if we're not avoiding overlap with other areas\n\n\n if (!labelPlaced && !avoidBaseMark) {\n // one span is zero, hence we can add\n areaWidth = Math.abs(x2 - x1 + y2 - y1);\n x = (x1 + x2) / 2;\n y = (y1 + y2) / 2; // place label if it fits and improves the max area width\n\n if (areaWidth >= maxAreaWidth && !outOfBounds(x, y, textWidth, textHeight, width, height) && !collision($, x, y, textHeight, textWidth, textHeight, bm0, null)) {\n maxAreaWidth = areaWidth;\n d.x = x;\n d.y = y;\n labelPlaced2 = true;\n }\n }\n } // record current label placement information, update label bitmap\n\n\n if (labelPlaced || labelPlaced2) {\n x = textWidth / 2;\n y = textHeight / 2;\n bm0.setRange($(d.x - x), $(d.y - y), $(d.x + x), $(d.y + y));\n d.align = 'center';\n d.baseline = 'middle';\n return true;\n } else {\n return false;\n }\n };\n}\n\nconst Aligns = ['right', 'center', 'left'],\n Baselines = ['bottom', 'middle', 'top'];\nfunction placeMarkLabel ($, bitmaps, anchors, offsets, infPadding) {\n const width = $.width,\n height = $.height,\n bm0 = bitmaps[0],\n bm1 = bitmaps[1],\n n = offsets.length;\n return function (d) {\n const boundary = d.boundary,\n textHeight = d.datum.fontSize; // can not be placed if the mark is not visible in the graph bound\n\n if (!infPadding && (boundary[2] < 0 || boundary[5] < 0 || boundary[0] > width || boundary[3] > height)) {\n return false;\n }\n\n let textWidth = 0,\n dx,\n dy,\n isInside,\n sizeFactor,\n insideFactor,\n x1,\n x2,\n y1,\n y2,\n xc,\n yc,\n _x1,\n _x2,\n _y1,\n _y2; // for each anchor and offset\n\n\n for (let i = 0; i < n; ++i) {\n dx = (anchors[i] & 0x3) - 1;\n dy = (anchors[i] >>> 0x2 & 0x3) - 1;\n isInside = dx === 0 && dy === 0 || offsets[i] < 0;\n sizeFactor = dx && dy ? Math.SQRT1_2 : 1;\n insideFactor = offsets[i] < 0 ? -1 : 1;\n x1 = boundary[1 + dx] + offsets[i] * dx * sizeFactor;\n yc = boundary[4 + dy] + insideFactor * textHeight * dy / 2 + offsets[i] * dy * sizeFactor;\n y1 = yc - textHeight / 2;\n y2 = yc + textHeight / 2;\n _x1 = $(x1);\n _y1 = $(y1);\n _y2 = $(y2);\n\n if (infPadding) {\n _x1 = _x1 < 0 ? 0 : _x1;\n _y1 = _y1 < 0 ? 0 : _y1;\n _y2 = _y2 >= $.height ? $.height - 1 : _y2;\n }\n\n if (!textWidth) {\n // to avoid finding width of text label,\n if (!test(_x1, _x1, _y1, _y2, bm0, bm1, x1, x1, y1, y2, boundary, isInside)) {\n // skip this anchor/offset option if we fail to place a label with 1px width\n continue;\n } else {\n // Otherwise, find the label width\n textWidth = textMetrics.width(d.datum, d.datum.text);\n }\n }\n\n xc = x1 + insideFactor * textWidth * dx / 2;\n x1 = xc - textWidth / 2;\n x2 = xc + textWidth / 2;\n _x1 = $(x1);\n _x2 = $(x2);\n\n if (infPadding) {\n _x1 = _x1 < 0 ? 0 : _x1;\n _x2 = _x2 >= $.width ? $.width - 1 : _x2;\n }\n\n if (test(_x1, _x2, _y1, _y2, bm0, bm1, x1, x2, y1, y2, boundary, isInside)) {\n // place label if the position is placeable\n d.x = !dx ? xc : dx * insideFactor < 0 ? x2 : x1;\n d.y = !dy ? yc : dy * insideFactor < 0 ? y2 : y1;\n d.align = Aligns[dx * insideFactor + 1];\n d.baseline = Baselines[dy * insideFactor + 1];\n bm0.setRange(_x1, _y1, _x2, _y2);\n return true;\n }\n }\n\n return false;\n };\n} // Test if a label with the given dimensions can be added without overlap\n\nfunction test(_x1, _x2, _y1, _y2, bm0, bm1, x1, x2, y1, y2, boundary, isInside) {\n return !(bm0.outOfBounds(_x1, _y1, _x2, _y2) || (isInside && bm1 ? bm1.getRange(_x1, _y1, _x2, _y2) || !isInMarkBound(x1, y1, x2, y2, boundary) : bm0.getRange(_x1, _y1, _x2, _y2)));\n}\n\nfunction isInMarkBound(x1, y1, x2, y2, boundary) {\n return boundary[0] <= x1 && x2 <= boundary[2] && boundary[3] <= y1 && y2 <= boundary[5];\n}\n\nconst TOP = 0x0,\n MIDDLE = 0x4,\n BOTTOM = 0x8,\n LEFT = 0x0,\n CENTER = 0x1,\n RIGHT = 0x2; // Mapping from text anchor to number representation\n\nconst anchorCode = {\n 'top-left': TOP + LEFT,\n 'top': TOP + CENTER,\n 'top-right': TOP + RIGHT,\n 'left': MIDDLE + LEFT,\n 'middle': MIDDLE + CENTER,\n 'right': MIDDLE + RIGHT,\n 'bottom-left': BOTTOM + LEFT,\n 'bottom': BOTTOM + CENTER,\n 'bottom-right': BOTTOM + RIGHT\n};\nconst placeAreaLabel = {\n 'naive': placeAreaLabelNaive,\n 'reduced-search': placeAreaLabelReducedSearch,\n 'floodfill': placeAreaLabelFloodFill\n};\nfunction labelLayout (texts, size, compare, offset, anchor, avoidMarks, avoidBaseMark, lineAnchor, markIndex, padding, method) {\n // early exit for empty data\n if (!texts.length) return texts;\n const positions = Math.max(offset.length, anchor.length),\n offsets = getOffsets(offset, positions),\n anchors = getAnchors(anchor, positions),\n marktype = markType(texts[0].datum),\n grouptype = marktype === 'group' && texts[0].datum.items[markIndex].marktype,\n isGroupArea = grouptype === 'area',\n boundary = markBoundary(marktype, grouptype, lineAnchor, markIndex),\n infPadding = padding === null || padding === Infinity,\n $ = scaler(size[0], size[1], infPadding ? 0 : padding),\n isNaiveGroupArea = isGroupArea && method === 'naive'; // prepare text mark data for placing\n\n const data = texts.map(d => ({\n datum: d,\n opacity: 0,\n x: undefined,\n y: undefined,\n align: undefined,\n baseline: undefined,\n boundary: boundary(d)\n }));\n let bitmaps;\n\n if (!isNaiveGroupArea) {\n // sort labels in priority order, if comparator is provided\n if (compare) {\n data.sort((a, b) => compare(a.datum, b.datum));\n } // flag indicating if label can be placed inside its base mark\n\n\n let labelInside = false;\n\n for (let i = 0; i < anchors.length && !labelInside; ++i) {\n // label inside if anchor is at center\n // label inside if offset to be inside the mark bound\n labelInside = anchors[i] === 0x5 || offsets[i] < 0;\n } // extract data information from base mark when base mark is to be avoided\n // base mark is implicitly avoided if it is a group area\n\n\n if (marktype && (avoidBaseMark || isGroupArea)) {\n avoidMarks = [texts.map(d => d.datum)].concat(avoidMarks);\n } // generate bitmaps for layout calculation\n\n\n bitmaps = avoidMarks.length ? markBitmaps($, avoidMarks, labelInside, isGroupArea) : baseBitmaps($, avoidBaseMark && data);\n } // generate label placement function\n\n\n const place = isGroupArea ? placeAreaLabel[method]($, bitmaps, avoidBaseMark, markIndex, infPadding) : placeMarkLabel($, bitmaps, anchors, offsets, infPadding); // place all labels\n\n data.forEach(d => d.opacity = +place(d));\n return data;\n}\n\nfunction getOffsets(_, count) {\n const offsets = new Float64Array(count),\n n = _.length;\n\n for (let i = 0; i < n; ++i) offsets[i] = _[i] || 0;\n\n for (let i = n; i < count; ++i) offsets[i] = offsets[n - 1];\n\n return offsets;\n}\n\nfunction getAnchors(_, count) {\n const anchors = new Int8Array(count),\n n = _.length;\n\n for (let i = 0; i < n; ++i) anchors[i] |= anchorCode[_[i]];\n\n for (let i = n; i < count; ++i) anchors[i] = anchors[n - 1];\n\n return anchors;\n}\n\nfunction markType(item) {\n return item && item.mark && item.mark.marktype;\n}\n/**\n * Factory function for function for getting base mark boundary, depending\n * on mark and group type. When mark type is undefined, line or area: boundary\n * is the coordinate of each data point. When base mark is grouped line,\n * boundary is either at the beginning or end of the line depending on the\n * value of lineAnchor. Otherwise, use bounds of base mark.\n */\n\n\nfunction markBoundary(marktype, grouptype, lineAnchor, markIndex) {\n const xy = d => [d.x, d.x, d.x, d.y, d.y, d.y];\n\n if (!marktype) {\n return xy; // no reactive geometry\n } else if (marktype === 'line' || marktype === 'area') {\n return d => xy(d.datum);\n } else if (grouptype === 'line') {\n return d => {\n const items = d.datum.items[markIndex].items;\n return xy(items.length ? items[lineAnchor === 'start' ? 0 : items.length - 1] : {\n x: NaN,\n y: NaN\n });\n };\n } else {\n return d => {\n const b = d.datum.bounds;\n return [b.x1, (b.x1 + b.x2) / 2, b.x2, b.y1, (b.y1 + b.y2) / 2, b.y2];\n };\n }\n}\n\nconst Output = ['x', 'y', 'opacity', 'align', 'baseline'];\nconst Anchors = ['top-left', 'left', 'bottom-left', 'top', 'bottom', 'top-right', 'right', 'bottom-right'];\n/**\n * Compute text label layout to annotate marks.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} params.size - The size of the layout, provided as a [width, height] array.\n * @param {function(*,*): number} [params.sort] - An optional\n * comparator function for sorting label data in priority order.\n * @param {Array} [params.anchor] - Label anchor points relative to the base mark bounding box.\n * The available options are 'top-left', 'left', 'bottom-left', 'top',\n * 'bottom', 'top-right', 'right', 'bottom-right', 'middle'.\n * @param {Array} [params.offset] - Label offsets (in pixels) from the base mark bounding box.\n * This parameter is parallel to the list of anchor points.\n * @param {number | null} [params.padding=0] - The amount (in pixels) that a label may exceed the layout size.\n * If this parameter is null, a label may exceed the layout size without any boundary.\n * @param {string} [params.lineAnchor='end'] - For group line mark labels only, indicates the anchor\n * position for labels. One of 'start' or 'end'.\n * @param {string} [params.markIndex=0] - For group mark labels only, an index indicating\n * which mark within the group should be labeled.\n * @param {Array} [params.avoidMarks] - A list of additional mark names for which the label\n * layout should avoid overlap.\n * @param {boolean} [params.avoidBaseMark=true] - Boolean flag indicating if labels should avoid\n * overlap with the underlying base mark being labeled.\n * @param {string} [params.method='naive'] - For area make labels only, a method for\n * place labels. One of 'naive', 'reduced-search', or 'floodfill'.\n * @param {Array} [params.as] - The output fields written by the transform.\n * The default is ['x', 'y', 'opacity', 'align', 'baseline'].\n */\n\nfunction Label(params) {\n Transform.call(this, null, params);\n}\nLabel.Definition = {\n type: 'Label',\n metadata: {\n modifies: true\n },\n params: [{\n name: 'size',\n type: 'number',\n array: true,\n length: 2,\n required: true\n }, {\n name: 'sort',\n type: 'compare'\n }, {\n name: 'anchor',\n type: 'string',\n array: true,\n default: Anchors\n }, {\n name: 'offset',\n type: 'number',\n array: true,\n default: [1]\n }, {\n name: 'padding',\n type: 'number',\n default: 0,\n null: true\n }, {\n name: 'lineAnchor',\n type: 'string',\n values: ['start', 'end'],\n default: 'end'\n }, {\n name: 'markIndex',\n type: 'number',\n default: 0\n }, {\n name: 'avoidBaseMark',\n type: 'boolean',\n default: true\n }, {\n name: 'avoidMarks',\n type: 'data',\n array: true\n }, {\n name: 'method',\n type: 'string',\n default: 'naive'\n }, {\n name: 'as',\n type: 'string',\n array: true,\n length: Output.length,\n default: Output\n }]\n};\ninherits(Label, Transform, {\n transform(_, pulse) {\n function modp(param) {\n const p = _[param];\n return isFunction(p) && pulse.modified(p.fields);\n }\n\n const mod = _.modified();\n\n if (!(mod || pulse.changed(pulse.ADD_REM) || modp('sort'))) return;\n\n if (!_.size || _.size.length !== 2) {\n error('Size parameter should be specified as a [width, height] array.');\n }\n\n const as = _.as || Output; // run label layout\n\n labelLayout(pulse.materialize(pulse.SOURCE).source || [], _.size, _.sort, array(_.offset == null ? 1 : _.offset), array(_.anchor || Anchors), _.avoidMarks || [], _.avoidBaseMark !== false, _.lineAnchor || 'end', _.markIndex || 0, _.padding === undefined ? 0 : _.padding, _.method || 'naive').forEach(l => {\n // write layout results to data stream\n const t = l.datum;\n t[as[0]] = l.x;\n t[as[1]] = l.y;\n t[as[2]] = l.opacity;\n t[as[3]] = l.align;\n t[as[4]] = l.baseline;\n });\n return pulse.reflow(mod).modifies(as);\n }\n\n});\n\nexport { Label as label };\n","import { regressionLoess, sampleCurve, regressionLinear, regressionLog, regressionExp, regressionPow, regressionQuad, regressionPoly } from 'vega-statistics';\nimport { Transform, ingest } from 'vega-dataflow';\nimport { inherits, accessorName, hasOwnProperty, error, extent } from 'vega-util';\n\nfunction partition (data, groupby) {\n var groups = [],\n get = function (f) {\n return f(t);\n },\n map,\n i,\n n,\n t,\n k,\n g; // partition data points into stack groups\n\n\n if (groupby == null) {\n groups.push(data);\n } else {\n for (map = {}, i = 0, n = data.length; i < n; ++i) {\n t = data[i];\n k = groupby.map(get);\n g = map[k];\n\n if (!g) {\n map[k] = g = [];\n g.dims = k;\n groups.push(g);\n }\n\n g.push(t);\n }\n }\n\n return groups;\n}\n\n/**\n * Compute locally-weighted regression fits for one or more data groups.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.x - An accessor for the predictor data field.\n * @param {function(object): *} params.y - An accessor for the predicted data field.\n * @param {Array} [params.groupby] - An array of accessors to groupby.\n * @param {number} [params.bandwidth=0.3] - The loess bandwidth.\n */\n\nfunction Loess(params) {\n Transform.call(this, null, params);\n}\nLoess.Definition = {\n 'type': 'Loess',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'x',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'y',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'bandwidth',\n 'type': 'number',\n 'default': 0.3\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true\n }]\n};\ninherits(Loess, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);\n\n if (!this.value || pulse.changed() || _.modified()) {\n const source = pulse.materialize(pulse.SOURCE).source,\n groups = partition(source, _.groupby),\n names = (_.groupby || []).map(accessorName),\n m = names.length,\n as = _.as || [accessorName(_.x), accessorName(_.y)],\n values = [];\n groups.forEach(g => {\n regressionLoess(g, _.x, _.y, _.bandwidth || 0.3).forEach(p => {\n const t = {};\n\n for (let i = 0; i < m; ++i) {\n t[names[i]] = g.dims[i];\n }\n\n t[as[0]] = p[0];\n t[as[1]] = p[1];\n values.push(ingest(t));\n });\n });\n if (this.value) out.rem = this.value;\n this.value = out.add = out.source = values;\n }\n\n return out;\n }\n\n});\n\nconst Methods = {\n linear: regressionLinear,\n log: regressionLog,\n exp: regressionExp,\n pow: regressionPow,\n quad: regressionQuad,\n poly: regressionPoly\n};\n\nconst degreesOfFreedom = (method, order) => method === 'poly' ? order : method === 'quad' ? 2 : 1;\n/**\n * Compute regression fits for one or more data groups.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {function(object): *} params.x - An accessor for the predictor data field.\n * @param {function(object): *} params.y - An accessor for the predicted data field.\n * @param {string} [params.method='linear'] - The regression method to apply.\n * @param {Array} [params.groupby] - An array of accessors to groupby.\n * @param {Array} [params.extent] - The domain extent over which to plot the regression line.\n * @param {number} [params.order=3] - The polynomial order. Only applies to the 'poly' method.\n */\n\n\nfunction Regression(params) {\n Transform.call(this, null, params);\n}\nRegression.Definition = {\n 'type': 'Regression',\n 'metadata': {\n 'generates': true\n },\n 'params': [{\n 'name': 'x',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'y',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'groupby',\n 'type': 'field',\n 'array': true\n }, {\n 'name': 'method',\n 'type': 'string',\n 'default': 'linear',\n 'values': Object.keys(Methods)\n }, {\n 'name': 'order',\n 'type': 'number',\n 'default': 3\n }, {\n 'name': 'extent',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'params',\n 'type': 'boolean',\n 'default': false\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true\n }]\n};\ninherits(Regression, Transform, {\n transform(_, pulse) {\n const out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);\n\n if (!this.value || pulse.changed() || _.modified()) {\n const source = pulse.materialize(pulse.SOURCE).source,\n groups = partition(source, _.groupby),\n names = (_.groupby || []).map(accessorName),\n method = _.method || 'linear',\n order = _.order || 3,\n dof = degreesOfFreedom(method, order),\n as = _.as || [accessorName(_.x), accessorName(_.y)],\n fit = Methods[method],\n values = [];\n let domain = _.extent;\n\n if (!hasOwnProperty(Methods, method)) {\n error('Invalid regression method: ' + method);\n }\n\n if (domain != null) {\n if (method === 'log' && domain[0] <= 0) {\n pulse.dataflow.warn('Ignoring extent with values <= 0 for log regression.');\n domain = null;\n }\n }\n\n groups.forEach(g => {\n const n = g.length;\n\n if (n <= dof) {\n pulse.dataflow.warn('Skipping regression with more parameters than data points.');\n return;\n }\n\n const model = fit(g, _.x, _.y, order);\n\n if (_.params) {\n // if parameter vectors requested return those\n values.push(ingest({\n keys: g.dims,\n coef: model.coef,\n rSquared: model.rSquared\n }));\n return;\n }\n\n const dom = domain || extent(g, _.x),\n add = p => {\n const t = {};\n\n for (let i = 0; i < names.length; ++i) {\n t[names[i]] = g.dims[i];\n }\n\n t[as[0]] = p[0];\n t[as[1]] = p[1];\n values.push(ingest(t));\n };\n\n if (method === 'linear') {\n // for linear regression we only need the end points\n dom.forEach(x => add([x, model.predict(x)]));\n } else {\n // otherwise return trend line sample points\n sampleCurve(model.predict, dom, 25, 200).forEach(add);\n }\n });\n if (this.value) out.rem = this.value;\n this.value = out.add = out.source = values;\n }\n\n return out;\n }\n\n});\n\nexport { Loess as loess, Regression as regression };\n","\nconst EPSILON = Math.pow(2, -52);\nconst EDGE_STACK = new Uint32Array(512);\n\nexport default class Delaunator {\n\n static from(points, getX = defaultGetX, getY = defaultGetY) {\n const n = points.length;\n const coords = new Float64Array(n * 2);\n\n for (let i = 0; i < n; i++) {\n const p = points[i];\n coords[2 * i] = getX(p);\n coords[2 * i + 1] = getY(p);\n }\n\n return new Delaunator(coords);\n }\n\n constructor(coords) {\n const n = coords.length >> 1;\n if (n > 0 && typeof coords[0] !== 'number') throw new Error('Expected coords to contain numbers.');\n\n this.coords = coords;\n\n // arrays that will store the triangulation graph\n const maxTriangles = Math.max(2 * n - 5, 0);\n this._triangles = new Uint32Array(maxTriangles * 3);\n this._halfedges = new Int32Array(maxTriangles * 3);\n\n // temporary arrays for tracking the edges of the advancing convex hull\n this._hashSize = Math.ceil(Math.sqrt(n));\n this._hullPrev = new Uint32Array(n); // edge to prev edge\n this._hullNext = new Uint32Array(n); // edge to next edge\n this._hullTri = new Uint32Array(n); // edge to adjacent triangle\n this._hullHash = new Int32Array(this._hashSize).fill(-1); // angular edge hash\n\n // temporary arrays for sorting points\n this._ids = new Uint32Array(n);\n this._dists = new Float64Array(n);\n\n this.update();\n }\n\n update() {\n const {coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash} = this;\n const n = coords.length >> 1;\n\n // populate an array of point indices; calculate input data bbox\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (let i = 0; i < n; i++) {\n const x = coords[2 * i];\n const y = coords[2 * i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n this._ids[i] = i;\n }\n const cx = (minX + maxX) / 2;\n const cy = (minY + maxY) / 2;\n\n let minDist = Infinity;\n let i0, i1, i2;\n\n // pick a seed point close to the center\n for (let i = 0; i < n; i++) {\n const d = dist(cx, cy, coords[2 * i], coords[2 * i + 1]);\n if (d < minDist) {\n i0 = i;\n minDist = d;\n }\n }\n const i0x = coords[2 * i0];\n const i0y = coords[2 * i0 + 1];\n\n minDist = Infinity;\n\n // find the point closest to the seed\n for (let i = 0; i < n; i++) {\n if (i === i0) continue;\n const d = dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);\n if (d < minDist && d > 0) {\n i1 = i;\n minDist = d;\n }\n }\n let i1x = coords[2 * i1];\n let i1y = coords[2 * i1 + 1];\n\n let minRadius = Infinity;\n\n // find the third point which forms the smallest circumcircle with the first two\n for (let i = 0; i < n; i++) {\n if (i === i0 || i === i1) continue;\n const r = circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);\n if (r < minRadius) {\n i2 = i;\n minRadius = r;\n }\n }\n let i2x = coords[2 * i2];\n let i2y = coords[2 * i2 + 1];\n\n if (minRadius === Infinity) {\n // order collinear points by dx (or dy if all x are identical)\n // and return the list as a hull\n for (let i = 0; i < n; i++) {\n this._dists[i] = (coords[2 * i] - coords[0]) || (coords[2 * i + 1] - coords[1]);\n }\n quicksort(this._ids, this._dists, 0, n - 1);\n const hull = new Uint32Array(n);\n let j = 0;\n for (let i = 0, d0 = -Infinity; i < n; i++) {\n const id = this._ids[i];\n if (this._dists[id] > d0) {\n hull[j++] = id;\n d0 = this._dists[id];\n }\n }\n this.hull = hull.subarray(0, j);\n this.triangles = new Uint32Array(0);\n this.halfedges = new Uint32Array(0);\n return;\n }\n\n // swap the order of the seed points for counter-clockwise orientation\n if (orient(i0x, i0y, i1x, i1y, i2x, i2y)) {\n const i = i1;\n const x = i1x;\n const y = i1y;\n i1 = i2;\n i1x = i2x;\n i1y = i2y;\n i2 = i;\n i2x = x;\n i2y = y;\n }\n\n const center = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);\n this._cx = center.x;\n this._cy = center.y;\n\n for (let i = 0; i < n; i++) {\n this._dists[i] = dist(coords[2 * i], coords[2 * i + 1], center.x, center.y);\n }\n\n // sort the points by distance from the seed triangle circumcenter\n quicksort(this._ids, this._dists, 0, n - 1);\n\n // set up the seed triangle as the starting hull\n this._hullStart = i0;\n let hullSize = 3;\n\n hullNext[i0] = hullPrev[i2] = i1;\n hullNext[i1] = hullPrev[i0] = i2;\n hullNext[i2] = hullPrev[i1] = i0;\n\n hullTri[i0] = 0;\n hullTri[i1] = 1;\n hullTri[i2] = 2;\n\n hullHash.fill(-1);\n hullHash[this._hashKey(i0x, i0y)] = i0;\n hullHash[this._hashKey(i1x, i1y)] = i1;\n hullHash[this._hashKey(i2x, i2y)] = i2;\n\n this.trianglesLen = 0;\n this._addTriangle(i0, i1, i2, -1, -1, -1);\n\n for (let k = 0, xp, yp; k < this._ids.length; k++) {\n const i = this._ids[k];\n const x = coords[2 * i];\n const y = coords[2 * i + 1];\n\n // skip near-duplicate points\n if (k > 0 && Math.abs(x - xp) <= EPSILON && Math.abs(y - yp) <= EPSILON) continue;\n xp = x;\n yp = y;\n\n // skip seed triangle points\n if (i === i0 || i === i1 || i === i2) continue;\n\n // find a visible edge on the convex hull using edge hash\n let start = 0;\n for (let j = 0, key = this._hashKey(x, y); j < this._hashSize; j++) {\n start = hullHash[(key + j) % this._hashSize];\n if (start !== -1 && start !== hullNext[start]) break;\n }\n\n start = hullPrev[start];\n let e = start, q;\n while (q = hullNext[e], !orient(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1])) {\n e = q;\n if (e === start) {\n e = -1;\n break;\n }\n }\n if (e === -1) continue; // likely a near-duplicate point; skip it\n\n // add the first triangle from the point\n let t = this._addTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);\n\n // recursively flip triangles from the point until they satisfy the Delaunay condition\n hullTri[i] = this._legalize(t + 2);\n hullTri[e] = t; // keep track of boundary triangles on the hull\n hullSize++;\n\n // walk forward through the hull, adding more triangles and flipping recursively\n let n = hullNext[e];\n while (q = hullNext[n], orient(x, y, coords[2 * n], coords[2 * n + 1], coords[2 * q], coords[2 * q + 1])) {\n t = this._addTriangle(n, i, q, hullTri[i], -1, hullTri[n]);\n hullTri[i] = this._legalize(t + 2);\n hullNext[n] = n; // mark as removed\n hullSize--;\n n = q;\n }\n\n // walk backward from the other side, adding more triangles and flipping\n if (e === start) {\n while (q = hullPrev[e], orient(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1])) {\n t = this._addTriangle(q, i, e, -1, hullTri[e], hullTri[q]);\n this._legalize(t + 2);\n hullTri[q] = t;\n hullNext[e] = e; // mark as removed\n hullSize--;\n e = q;\n }\n }\n\n // update the hull indices\n this._hullStart = hullPrev[i] = e;\n hullNext[e] = hullPrev[n] = i;\n hullNext[i] = n;\n\n // save the two new edges in the hash table\n hullHash[this._hashKey(x, y)] = i;\n hullHash[this._hashKey(coords[2 * e], coords[2 * e + 1])] = e;\n }\n\n this.hull = new Uint32Array(hullSize);\n for (let i = 0, e = this._hullStart; i < hullSize; i++) {\n this.hull[i] = e;\n e = hullNext[e];\n }\n\n // trim typed triangle mesh arrays\n this.triangles = this._triangles.subarray(0, this.trianglesLen);\n this.halfedges = this._halfedges.subarray(0, this.trianglesLen);\n }\n\n _hashKey(x, y) {\n return Math.floor(pseudoAngle(x - this._cx, y - this._cy) * this._hashSize) % this._hashSize;\n }\n\n _legalize(a) {\n const {_triangles: triangles, _halfedges: halfedges, coords} = this;\n\n let i = 0;\n let ar = 0;\n\n // recursion eliminated with a fixed-size stack\n while (true) {\n const b = halfedges[a];\n\n /* if the pair of triangles doesn't satisfy the Delaunay condition\n * (p1 is inside the circumcircle of [p0, pl, pr]), flip them,\n * then do the same check/flip recursively for the new pair of triangles\n *\n * pl pl\n * /||\\ / \\\n * al/ || \\bl al/ \\a\n * / || \\ / \\\n * / a||b \\ flip /___ar___\\\n * p0\\ || /p1 => p0\\---bl---/p1\n * \\ || / \\ /\n * ar\\ || /br b\\ /br\n * \\||/ \\ /\n * pr pr\n */\n const a0 = a - a % 3;\n ar = a0 + (a + 2) % 3;\n\n if (b === -1) { // convex hull edge\n if (i === 0) break;\n a = EDGE_STACK[--i];\n continue;\n }\n\n const b0 = b - b % 3;\n const al = a0 + (a + 1) % 3;\n const bl = b0 + (b + 2) % 3;\n\n const p0 = triangles[ar];\n const pr = triangles[a];\n const pl = triangles[al];\n const p1 = triangles[bl];\n\n const illegal = inCircle(\n coords[2 * p0], coords[2 * p0 + 1],\n coords[2 * pr], coords[2 * pr + 1],\n coords[2 * pl], coords[2 * pl + 1],\n coords[2 * p1], coords[2 * p1 + 1]);\n\n if (illegal) {\n triangles[a] = p1;\n triangles[b] = p0;\n\n const hbl = halfedges[bl];\n\n // edge swapped on the other side of the hull (rare); fix the halfedge reference\n if (hbl === -1) {\n let e = this._hullStart;\n do {\n if (this._hullTri[e] === bl) {\n this._hullTri[e] = a;\n break;\n }\n e = this._hullPrev[e];\n } while (e !== this._hullStart);\n }\n this._link(a, hbl);\n this._link(b, halfedges[ar]);\n this._link(ar, bl);\n\n const br = b0 + (b + 1) % 3;\n\n // don't worry about hitting the cap: it can only happen on extremely degenerate input\n if (i < EDGE_STACK.length) {\n EDGE_STACK[i++] = br;\n }\n } else {\n if (i === 0) break;\n a = EDGE_STACK[--i];\n }\n }\n\n return ar;\n }\n\n _link(a, b) {\n this._halfedges[a] = b;\n if (b !== -1) this._halfedges[b] = a;\n }\n\n // add a new triangle given vertex indices and adjacent half-edge ids\n _addTriangle(i0, i1, i2, a, b, c) {\n const t = this.trianglesLen;\n\n this._triangles[t] = i0;\n this._triangles[t + 1] = i1;\n this._triangles[t + 2] = i2;\n\n this._link(t, a);\n this._link(t + 1, b);\n this._link(t + 2, c);\n\n this.trianglesLen += 3;\n\n return t;\n }\n}\n\n// monotonically increases with real angle, but doesn't need expensive trigonometry\nfunction pseudoAngle(dx, dy) {\n const p = dx / (Math.abs(dx) + Math.abs(dy));\n return (dy > 0 ? 3 - p : 1 + p) / 4; // [0..1]\n}\n\nfunction dist(ax, ay, bx, by) {\n const dx = ax - bx;\n const dy = ay - by;\n return dx * dx + dy * dy;\n}\n\n// return 2d orientation sign if we're confident in it through J. Shewchuk's error bound check\nfunction orientIfSure(px, py, rx, ry, qx, qy) {\n const l = (ry - py) * (qx - px);\n const r = (rx - px) * (qy - py);\n return Math.abs(l - r) >= 3.3306690738754716e-16 * Math.abs(l + r) ? l - r : 0;\n}\n\n// a more robust orientation test that's stable in a given triangle (to fix robustness issues)\nfunction orient(rx, ry, qx, qy, px, py) {\n const sign = orientIfSure(px, py, rx, ry, qx, qy) ||\n orientIfSure(rx, ry, qx, qy, px, py) ||\n orientIfSure(qx, qy, px, py, rx, ry);\n return sign < 0;\n}\n\nfunction inCircle(ax, ay, bx, by, cx, cy, px, py) {\n const dx = ax - px;\n const dy = ay - py;\n const ex = bx - px;\n const ey = by - py;\n const fx = cx - px;\n const fy = cy - py;\n\n const ap = dx * dx + dy * dy;\n const bp = ex * ex + ey * ey;\n const cp = fx * fx + fy * fy;\n\n return dx * (ey * cp - bp * fy) -\n dy * (ex * cp - bp * fx) +\n ap * (ex * fy - ey * fx) < 0;\n}\n\nfunction circumradius(ax, ay, bx, by, cx, cy) {\n const dx = bx - ax;\n const dy = by - ay;\n const ex = cx - ax;\n const ey = cy - ay;\n\n const bl = dx * dx + dy * dy;\n const cl = ex * ex + ey * ey;\n const d = 0.5 / (dx * ey - dy * ex);\n\n const x = (ey * bl - dy * cl) * d;\n const y = (dx * cl - ex * bl) * d;\n\n return x * x + y * y;\n}\n\nfunction circumcenter(ax, ay, bx, by, cx, cy) {\n const dx = bx - ax;\n const dy = by - ay;\n const ex = cx - ax;\n const ey = cy - ay;\n\n const bl = dx * dx + dy * dy;\n const cl = ex * ex + ey * ey;\n const d = 0.5 / (dx * ey - dy * ex);\n\n const x = ax + (ey * bl - dy * cl) * d;\n const y = ay + (dx * cl - ex * bl) * d;\n\n return {x, y};\n}\n\nfunction quicksort(ids, dists, left, right) {\n if (right - left <= 20) {\n for (let i = left + 1; i <= right; i++) {\n const temp = ids[i];\n const tempDist = dists[temp];\n let j = i - 1;\n while (j >= left && dists[ids[j]] > tempDist) ids[j + 1] = ids[j--];\n ids[j + 1] = temp;\n }\n } else {\n const median = (left + right) >> 1;\n let i = left + 1;\n let j = right;\n swap(ids, median, i);\n if (dists[ids[left]] > dists[ids[right]]) swap(ids, left, right);\n if (dists[ids[i]] > dists[ids[right]]) swap(ids, i, right);\n if (dists[ids[left]] > dists[ids[i]]) swap(ids, left, i);\n\n const temp = ids[i];\n const tempDist = dists[temp];\n while (true) {\n do i++; while (dists[ids[i]] < tempDist);\n do j--; while (dists[ids[j]] > tempDist);\n if (j < i) break;\n swap(ids, i, j);\n }\n ids[left + 1] = ids[j];\n ids[j] = temp;\n\n if (right - i + 1 >= j - left) {\n quicksort(ids, dists, i, right);\n quicksort(ids, dists, left, j - 1);\n } else {\n quicksort(ids, dists, left, j - 1);\n quicksort(ids, dists, i, right);\n }\n }\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\nfunction defaultGetX(p) {\n return p[0];\n}\nfunction defaultGetY(p) {\n return p[1];\n}\n","const epsilon = 1e-6;\n\nexport default class Path {\n constructor() {\n this._x0 = this._y0 = // start of current subpath\n this._x1 = this._y1 = null; // end of current subpath\n this._ = \"\";\n }\n moveTo(x, y) {\n this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}`;\n }\n closePath() {\n if (this._x1 !== null) {\n this._x1 = this._x0, this._y1 = this._y0;\n this._ += \"Z\";\n }\n }\n lineTo(x, y) {\n this._ += `L${this._x1 = +x},${this._y1 = +y}`;\n }\n arc(x, y, r) {\n x = +x, y = +y, r = +r;\n const x0 = x + r;\n const y0 = y;\n if (r < 0) throw new Error(\"negative radius\");\n if (this._x1 === null) this._ += `M${x0},${y0}`;\n else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) this._ += \"L\" + x0 + \",\" + y0;\n if (!r) return;\n this._ += `A${r},${r},0,1,1,${x - r},${y}A${r},${r},0,1,1,${this._x1 = x0},${this._y1 = y0}`;\n }\n rect(x, y, w, h) {\n this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${+w}v${+h}h${-w}Z`;\n }\n value() {\n return this._ || null;\n }\n}\n","export default class Polygon {\n constructor() {\n this._ = [];\n }\n moveTo(x, y) {\n this._.push([x, y]);\n }\n closePath() {\n this._.push(this._[0].slice());\n }\n lineTo(x, y) {\n this._.push([x, y]);\n }\n value() {\n return this._.length ? this._ : null;\n }\n}\n","import Path from \"./path.js\";\nimport Polygon from \"./polygon.js\";\n\nexport default class Voronoi {\n constructor(delaunay, [xmin, ymin, xmax, ymax] = [0, 0, 960, 500]) {\n if (!((xmax = +xmax) >= (xmin = +xmin)) || !((ymax = +ymax) >= (ymin = +ymin))) throw new Error(\"invalid bounds\");\n this.delaunay = delaunay;\n this._circumcenters = new Float64Array(delaunay.points.length * 2);\n this.vectors = new Float64Array(delaunay.points.length * 2);\n this.xmax = xmax, this.xmin = xmin;\n this.ymax = ymax, this.ymin = ymin;\n this._init();\n }\n update() {\n this.delaunay.update();\n this._init();\n return this;\n }\n _init() {\n const {delaunay: {points, hull, triangles}, vectors} = this;\n\n // Compute circumcenters.\n const circumcenters = this.circumcenters = this._circumcenters.subarray(0, triangles.length / 3 * 2);\n for (let i = 0, j = 0, n = triangles.length, x, y; i < n; i += 3, j += 2) {\n const t1 = triangles[i] * 2;\n const t2 = triangles[i + 1] * 2;\n const t3 = triangles[i + 2] * 2;\n const x1 = points[t1];\n const y1 = points[t1 + 1];\n const x2 = points[t2];\n const y2 = points[t2 + 1];\n const x3 = points[t3];\n const y3 = points[t3 + 1];\n\n const dx = x2 - x1;\n const dy = y2 - y1;\n const ex = x3 - x1;\n const ey = y3 - y1;\n const bl = dx * dx + dy * dy;\n const cl = ex * ex + ey * ey;\n const ab = (dx * ey - dy * ex) * 2;\n\n if (!ab) {\n // degenerate case (collinear diagram)\n x = (x1 + x3) / 2 - 1e8 * ey;\n y = (y1 + y3) / 2 + 1e8 * ex;\n }\n else if (Math.abs(ab) < 1e-8) {\n // almost equal points (degenerate triangle)\n x = (x1 + x3) / 2;\n y = (y1 + y3) / 2;\n } else {\n const d = 1 / ab;\n x = x1 + (ey * bl - dy * cl) * d;\n y = y1 + (dx * cl - ex * bl) * d;\n }\n circumcenters[j] = x;\n circumcenters[j + 1] = y;\n }\n\n // Compute exterior cell rays.\n let h = hull[hull.length - 1];\n let p0, p1 = h * 4;\n let x0, x1 = points[2 * h];\n let y0, y1 = points[2 * h + 1];\n vectors.fill(0);\n for (let i = 0; i < hull.length; ++i) {\n h = hull[i];\n p0 = p1, x0 = x1, y0 = y1;\n p1 = h * 4, x1 = points[2 * h], y1 = points[2 * h + 1];\n vectors[p0 + 2] = vectors[p1] = y0 - y1;\n vectors[p0 + 3] = vectors[p1 + 1] = x1 - x0;\n }\n }\n render(context) {\n const buffer = context == null ? context = new Path : undefined;\n const {delaunay: {halfedges, inedges, hull}, circumcenters, vectors} = this;\n if (hull.length <= 1) return null;\n for (let i = 0, n = halfedges.length; i < n; ++i) {\n const j = halfedges[i];\n if (j < i) continue;\n const ti = Math.floor(i / 3) * 2;\n const tj = Math.floor(j / 3) * 2;\n const xi = circumcenters[ti];\n const yi = circumcenters[ti + 1];\n const xj = circumcenters[tj];\n const yj = circumcenters[tj + 1];\n this._renderSegment(xi, yi, xj, yj, context);\n }\n let h0, h1 = hull[hull.length - 1];\n for (let i = 0; i < hull.length; ++i) {\n h0 = h1, h1 = hull[i];\n const t = Math.floor(inedges[h1] / 3) * 2;\n const x = circumcenters[t];\n const y = circumcenters[t + 1];\n const v = h0 * 4;\n const p = this._project(x, y, vectors[v + 2], vectors[v + 3]);\n if (p) this._renderSegment(x, y, p[0], p[1], context);\n }\n return buffer && buffer.value();\n }\n renderBounds(context) {\n const buffer = context == null ? context = new Path : undefined;\n context.rect(this.xmin, this.ymin, this.xmax - this.xmin, this.ymax - this.ymin);\n return buffer && buffer.value();\n }\n renderCell(i, context) {\n const buffer = context == null ? context = new Path : undefined;\n const points = this._clip(i);\n if (points === null || !points.length) return;\n context.moveTo(points[0], points[1]);\n let n = points.length;\n while (points[0] === points[n-2] && points[1] === points[n-1] && n > 1) n -= 2;\n for (let i = 2; i < n; i += 2) {\n if (points[i] !== points[i-2] || points[i+1] !== points[i-1])\n context.lineTo(points[i], points[i + 1]);\n }\n context.closePath();\n return buffer && buffer.value();\n }\n *cellPolygons() {\n const {delaunay: {points}} = this;\n for (let i = 0, n = points.length / 2; i < n; ++i) {\n const cell = this.cellPolygon(i);\n if (cell) cell.index = i, yield cell;\n }\n }\n cellPolygon(i) {\n const polygon = new Polygon;\n this.renderCell(i, polygon);\n return polygon.value();\n }\n _renderSegment(x0, y0, x1, y1, context) {\n let S;\n const c0 = this._regioncode(x0, y0);\n const c1 = this._regioncode(x1, y1);\n if (c0 === 0 && c1 === 0) {\n context.moveTo(x0, y0);\n context.lineTo(x1, y1);\n } else if (S = this._clipSegment(x0, y0, x1, y1, c0, c1)) {\n context.moveTo(S[0], S[1]);\n context.lineTo(S[2], S[3]);\n }\n }\n contains(i, x, y) {\n if ((x = +x, x !== x) || (y = +y, y !== y)) return false;\n return this.delaunay._step(i, x, y) === i;\n }\n *neighbors(i) {\n const ci = this._clip(i);\n if (ci) for (const j of this.delaunay.neighbors(i)) {\n const cj = this._clip(j);\n // find the common edge\n if (cj) loop: for (let ai = 0, li = ci.length; ai < li; ai += 2) {\n for (let aj = 0, lj = cj.length; aj < lj; aj += 2) {\n if (ci[ai] == cj[aj]\n && ci[ai + 1] == cj[aj + 1]\n && ci[(ai + 2) % li] == cj[(aj + lj - 2) % lj]\n && ci[(ai + 3) % li] == cj[(aj + lj - 1) % lj]\n ) {\n yield j;\n break loop;\n }\n }\n }\n }\n }\n _cell(i) {\n const {circumcenters, delaunay: {inedges, halfedges, triangles}} = this;\n const e0 = inedges[i];\n if (e0 === -1) return null; // coincident point\n const points = [];\n let e = e0;\n do {\n const t = Math.floor(e / 3);\n points.push(circumcenters[t * 2], circumcenters[t * 2 + 1]);\n e = e % 3 === 2 ? e - 2 : e + 1;\n if (triangles[e] !== i) break; // bad triangulation\n e = halfedges[e];\n } while (e !== e0 && e !== -1);\n return points;\n }\n _clip(i) {\n // degenerate case (1 valid point: return the box)\n if (i === 0 && this.delaunay.hull.length === 1) {\n return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];\n }\n const points = this._cell(i);\n if (points === null) return null;\n const {vectors: V} = this;\n const v = i * 4;\n return V[v] || V[v + 1]\n ? this._clipInfinite(i, points, V[v], V[v + 1], V[v + 2], V[v + 3])\n : this._clipFinite(i, points);\n }\n _clipFinite(i, points) {\n const n = points.length;\n let P = null;\n let x0, y0, x1 = points[n - 2], y1 = points[n - 1];\n let c0, c1 = this._regioncode(x1, y1);\n let e0, e1;\n for (let j = 0; j < n; j += 2) {\n x0 = x1, y0 = y1, x1 = points[j], y1 = points[j + 1];\n c0 = c1, c1 = this._regioncode(x1, y1);\n if (c0 === 0 && c1 === 0) {\n e0 = e1, e1 = 0;\n if (P) P.push(x1, y1);\n else P = [x1, y1];\n } else {\n let S, sx0, sy0, sx1, sy1;\n if (c0 === 0) {\n if ((S = this._clipSegment(x0, y0, x1, y1, c0, c1)) === null) continue;\n [sx0, sy0, sx1, sy1] = S;\n } else {\n if ((S = this._clipSegment(x1, y1, x0, y0, c1, c0)) === null) continue;\n [sx1, sy1, sx0, sy0] = S;\n e0 = e1, e1 = this._edgecode(sx0, sy0);\n if (e0 && e1) this._edge(i, e0, e1, P, P.length);\n if (P) P.push(sx0, sy0);\n else P = [sx0, sy0];\n }\n e0 = e1, e1 = this._edgecode(sx1, sy1);\n if (e0 && e1) this._edge(i, e0, e1, P, P.length);\n if (P) P.push(sx1, sy1);\n else P = [sx1, sy1];\n }\n }\n if (P) {\n e0 = e1, e1 = this._edgecode(P[0], P[1]);\n if (e0 && e1) this._edge(i, e0, e1, P, P.length);\n } else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {\n return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];\n }\n return P;\n }\n _clipSegment(x0, y0, x1, y1, c0, c1) {\n while (true) {\n if (c0 === 0 && c1 === 0) return [x0, y0, x1, y1];\n if (c0 & c1) return null;\n let x, y, c = c0 || c1;\n if (c & 0b1000) x = x0 + (x1 - x0) * (this.ymax - y0) / (y1 - y0), y = this.ymax;\n else if (c & 0b0100) x = x0 + (x1 - x0) * (this.ymin - y0) / (y1 - y0), y = this.ymin;\n else if (c & 0b0010) y = y0 + (y1 - y0) * (this.xmax - x0) / (x1 - x0), x = this.xmax;\n else y = y0 + (y1 - y0) * (this.xmin - x0) / (x1 - x0), x = this.xmin;\n if (c0) x0 = x, y0 = y, c0 = this._regioncode(x0, y0);\n else x1 = x, y1 = y, c1 = this._regioncode(x1, y1);\n }\n }\n _clipInfinite(i, points, vx0, vy0, vxn, vyn) {\n let P = Array.from(points), p;\n if (p = this._project(P[0], P[1], vx0, vy0)) P.unshift(p[0], p[1]);\n if (p = this._project(P[P.length - 2], P[P.length - 1], vxn, vyn)) P.push(p[0], p[1]);\n if (P = this._clipFinite(i, P)) {\n for (let j = 0, n = P.length, c0, c1 = this._edgecode(P[n - 2], P[n - 1]); j < n; j += 2) {\n c0 = c1, c1 = this._edgecode(P[j], P[j + 1]);\n if (c0 && c1) j = this._edge(i, c0, c1, P, j), n = P.length;\n }\n } else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {\n P = [this.xmin, this.ymin, this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax];\n }\n return P;\n }\n _edge(i, e0, e1, P, j) {\n while (e0 !== e1) {\n let x, y;\n switch (e0) {\n case 0b0101: e0 = 0b0100; continue; // top-left\n case 0b0100: e0 = 0b0110, x = this.xmax, y = this.ymin; break; // top\n case 0b0110: e0 = 0b0010; continue; // top-right\n case 0b0010: e0 = 0b1010, x = this.xmax, y = this.ymax; break; // right\n case 0b1010: e0 = 0b1000; continue; // bottom-right\n case 0b1000: e0 = 0b1001, x = this.xmin, y = this.ymax; break; // bottom\n case 0b1001: e0 = 0b0001; continue; // bottom-left\n case 0b0001: e0 = 0b0101, x = this.xmin, y = this.ymin; break; // left\n }\n if ((P[j] !== x || P[j + 1] !== y) && this.contains(i, x, y)) {\n P.splice(j, 0, x, y), j += 2;\n }\n }\n if (P.length > 4) {\n for (let i = 0; i < P.length; i+= 2) {\n const j = (i + 2) % P.length, k = (i + 4) % P.length;\n if (P[i] === P[j] && P[j] === P[k]\n || P[i + 1] === P[j + 1] && P[j + 1] === P[k + 1])\n P.splice(j, 2), i -= 2;\n }\n }\n return j;\n }\n _project(x0, y0, vx, vy) {\n let t = Infinity, c, x, y;\n if (vy < 0) { // top\n if (y0 <= this.ymin) return null;\n if ((c = (this.ymin - y0) / vy) < t) y = this.ymin, x = x0 + (t = c) * vx;\n } else if (vy > 0) { // bottom\n if (y0 >= this.ymax) return null;\n if ((c = (this.ymax - y0) / vy) < t) y = this.ymax, x = x0 + (t = c) * vx;\n }\n if (vx > 0) { // right\n if (x0 >= this.xmax) return null;\n if ((c = (this.xmax - x0) / vx) < t) x = this.xmax, y = y0 + (t = c) * vy;\n } else if (vx < 0) { // left\n if (x0 <= this.xmin) return null;\n if ((c = (this.xmin - x0) / vx) < t) x = this.xmin, y = y0 + (t = c) * vy;\n }\n return [x, y];\n }\n _edgecode(x, y) {\n return (x === this.xmin ? 0b0001\n : x === this.xmax ? 0b0010 : 0b0000)\n | (y === this.ymin ? 0b0100\n : y === this.ymax ? 0b1000 : 0b0000);\n }\n _regioncode(x, y) {\n return (x < this.xmin ? 0b0001\n : x > this.xmax ? 0b0010 : 0b0000)\n | (y < this.ymin ? 0b0100\n : y > this.ymax ? 0b1000 : 0b0000);\n }\n}\n","import Delaunator from \"delaunator\";\nimport Path from \"./path.js\";\nimport Polygon from \"./polygon.js\";\nimport Voronoi from \"./voronoi.js\";\n\nconst tau = 2 * Math.PI, pow = Math.pow;\n\nfunction pointX(p) {\n return p[0];\n}\n\nfunction pointY(p) {\n return p[1];\n}\n\n// A triangulation is collinear if all its triangles have a non-null area\nfunction collinear(d) {\n const {triangles, coords} = d;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = 2 * triangles[i],\n b = 2 * triangles[i + 1],\n c = 2 * triangles[i + 2],\n cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1])\n - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]);\n if (cross > 1e-10) return false;\n }\n return true;\n}\n\nfunction jitter(x, y, r) {\n return [x + Math.sin(x + y) * r, y + Math.cos(x - y) * r];\n}\n\nexport default class Delaunay {\n static from(points, fx = pointX, fy = pointY, that) {\n return new Delaunay(\"length\" in points\n ? flatArray(points, fx, fy, that)\n : Float64Array.from(flatIterable(points, fx, fy, that)));\n }\n constructor(points) {\n this._delaunator = new Delaunator(points);\n this.inedges = new Int32Array(points.length / 2);\n this._hullIndex = new Int32Array(points.length / 2);\n this.points = this._delaunator.coords;\n this._init();\n }\n update() {\n this._delaunator.update();\n this._init();\n return this;\n }\n _init() {\n const d = this._delaunator, points = this.points;\n\n // check for collinear\n if (d.hull && d.hull.length > 2 && collinear(d)) {\n this.collinear = Int32Array.from({length: points.length/2}, (_,i) => i)\n .sort((i, j) => points[2 * i] - points[2 * j] || points[2 * i + 1] - points[2 * j + 1]); // for exact neighbors\n const e = this.collinear[0], f = this.collinear[this.collinear.length - 1],\n bounds = [ points[2 * e], points[2 * e + 1], points[2 * f], points[2 * f + 1] ],\n r = 1e-8 * Math.hypot(bounds[3] - bounds[1], bounds[2] - bounds[0]);\n for (let i = 0, n = points.length / 2; i < n; ++i) {\n const p = jitter(points[2 * i], points[2 * i + 1], r);\n points[2 * i] = p[0];\n points[2 * i + 1] = p[1];\n }\n this._delaunator = new Delaunator(points);\n } else {\n delete this.collinear;\n }\n\n const halfedges = this.halfedges = this._delaunator.halfedges;\n const hull = this.hull = this._delaunator.hull;\n const triangles = this.triangles = this._delaunator.triangles;\n const inedges = this.inedges.fill(-1);\n const hullIndex = this._hullIndex.fill(-1);\n\n // Compute an index from each point to an (arbitrary) incoming halfedge\n // Used to give the first neighbor of each point; for this reason,\n // on the hull we give priority to exterior halfedges\n for (let e = 0, n = halfedges.length; e < n; ++e) {\n const p = triangles[e % 3 === 2 ? e - 2 : e + 1];\n if (halfedges[e] === -1 || inedges[p] === -1) inedges[p] = e;\n }\n for (let i = 0, n = hull.length; i < n; ++i) {\n hullIndex[hull[i]] = i;\n }\n\n // degenerate case: 1 or 2 (distinct) points\n if (hull.length <= 2 && hull.length > 0) {\n this.triangles = new Int32Array(3).fill(-1);\n this.halfedges = new Int32Array(3).fill(-1);\n this.triangles[0] = hull[0];\n this.triangles[1] = hull[1];\n this.triangles[2] = hull[1];\n inedges[hull[0]] = 1;\n if (hull.length === 2) inedges[hull[1]] = 0;\n }\n }\n voronoi(bounds) {\n return new Voronoi(this, bounds);\n }\n *neighbors(i) {\n const {inedges, hull, _hullIndex, halfedges, triangles, collinear} = this;\n\n // degenerate case with several collinear points\n if (collinear) {\n const l = collinear.indexOf(i);\n if (l > 0) yield collinear[l - 1];\n if (l < collinear.length - 1) yield collinear[l + 1];\n return;\n }\n\n const e0 = inedges[i];\n if (e0 === -1) return; // coincident point\n let e = e0, p0 = -1;\n do {\n yield p0 = triangles[e];\n e = e % 3 === 2 ? e - 2 : e + 1;\n if (triangles[e] !== i) return; // bad triangulation\n e = halfedges[e];\n if (e === -1) {\n const p = hull[(_hullIndex[i] + 1) % hull.length];\n if (p !== p0) yield p;\n return;\n }\n } while (e !== e0);\n }\n find(x, y, i = 0) {\n if ((x = +x, x !== x) || (y = +y, y !== y)) return -1;\n const i0 = i;\n let c;\n while ((c = this._step(i, x, y)) >= 0 && c !== i && c !== i0) i = c;\n return c;\n }\n _step(i, x, y) {\n const {inedges, hull, _hullIndex, halfedges, triangles, points} = this;\n if (inedges[i] === -1 || !points.length) return (i + 1) % (points.length >> 1);\n let c = i;\n let dc = pow(x - points[i * 2], 2) + pow(y - points[i * 2 + 1], 2);\n const e0 = inedges[i];\n let e = e0;\n do {\n let t = triangles[e];\n const dt = pow(x - points[t * 2], 2) + pow(y - points[t * 2 + 1], 2);\n if (dt < dc) dc = dt, c = t;\n e = e % 3 === 2 ? e - 2 : e + 1;\n if (triangles[e] !== i) break; // bad triangulation\n e = halfedges[e];\n if (e === -1) {\n e = hull[(_hullIndex[i] + 1) % hull.length];\n if (e !== t) {\n if (pow(x - points[e * 2], 2) + pow(y - points[e * 2 + 1], 2) < dc) return e;\n }\n break;\n }\n } while (e !== e0);\n return c;\n }\n render(context) {\n const buffer = context == null ? context = new Path : undefined;\n const {points, halfedges, triangles} = this;\n for (let i = 0, n = halfedges.length; i < n; ++i) {\n const j = halfedges[i];\n if (j < i) continue;\n const ti = triangles[i] * 2;\n const tj = triangles[j] * 2;\n context.moveTo(points[ti], points[ti + 1]);\n context.lineTo(points[tj], points[tj + 1]);\n }\n this.renderHull(context);\n return buffer && buffer.value();\n }\n renderPoints(context, r = 2) {\n const buffer = context == null ? context = new Path : undefined;\n const {points} = this;\n for (let i = 0, n = points.length; i < n; i += 2) {\n const x = points[i], y = points[i + 1];\n context.moveTo(x + r, y);\n context.arc(x, y, r, 0, tau);\n }\n return buffer && buffer.value();\n }\n renderHull(context) {\n const buffer = context == null ? context = new Path : undefined;\n const {hull, points} = this;\n const h = hull[0] * 2, n = hull.length;\n context.moveTo(points[h], points[h + 1]);\n for (let i = 1; i < n; ++i) {\n const h = 2 * hull[i];\n context.lineTo(points[h], points[h + 1]);\n }\n context.closePath();\n return buffer && buffer.value();\n }\n hullPolygon() {\n const polygon = new Polygon;\n this.renderHull(polygon);\n return polygon.value();\n }\n renderTriangle(i, context) {\n const buffer = context == null ? context = new Path : undefined;\n const {points, triangles} = this;\n const t0 = triangles[i *= 3] * 2;\n const t1 = triangles[i + 1] * 2;\n const t2 = triangles[i + 2] * 2;\n context.moveTo(points[t0], points[t0 + 1]);\n context.lineTo(points[t1], points[t1 + 1]);\n context.lineTo(points[t2], points[t2 + 1]);\n context.closePath();\n return buffer && buffer.value();\n }\n *trianglePolygons() {\n const {triangles} = this;\n for (let i = 0, n = triangles.length / 3; i < n; ++i) {\n yield this.trianglePolygon(i);\n }\n }\n trianglePolygon(i) {\n const polygon = new Polygon;\n this.renderTriangle(i, polygon);\n return polygon.value();\n }\n}\n\nfunction flatArray(points, fx, fy, that) {\n const n = points.length;\n const array = new Float64Array(n * 2);\n for (let i = 0; i < n; ++i) {\n const p = points[i];\n array[i * 2] = fx.call(that, p, i, points);\n array[i * 2 + 1] = fy.call(that, p, i, points);\n }\n return array;\n}\n\nfunction* flatIterable(points, fx, fy, that) {\n let i = 0;\n for (const p of points) {\n yield fx.call(that, p, i, points);\n yield fy.call(that, p, i, points);\n ++i;\n }\n}\n","import { Transform } from 'vega-dataflow';\nimport { inherits } from 'vega-util';\nimport { Delaunay } from 'd3-delaunay';\n\nfunction Voronoi(params) {\n Transform.call(this, null, params);\n}\nVoronoi.Definition = {\n 'type': 'Voronoi',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'x',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'y',\n 'type': 'field',\n 'required': true\n }, {\n 'name': 'size',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'extent',\n 'type': 'array',\n 'array': true,\n 'length': 2,\n 'default': [[-1e5, -1e5], [1e5, 1e5]],\n 'content': {\n 'type': 'number',\n 'array': true,\n 'length': 2\n }\n }, {\n 'name': 'as',\n 'type': 'string',\n 'default': 'path'\n }]\n};\nconst defaultExtent = [-1e5, -1e5, 1e5, 1e5];\ninherits(Voronoi, Transform, {\n transform(_, pulse) {\n const as = _.as || 'path',\n data = pulse.source; // nothing to do if no data\n\n if (!data || !data.length) return pulse; // configure and construct voronoi diagram\n\n let s = _.size;\n s = s ? [0, 0, s[0], s[1]] : (s = _.extent) ? [s[0][0], s[0][1], s[1][0], s[1][1]] : defaultExtent;\n const voronoi = this.value = Delaunay.from(data, _.x, _.y).voronoi(s); // map polygons to paths\n\n for (let i = 0, n = data.length; i < n; ++i) {\n const polygon = voronoi.cellPolygon(i);\n data[i][as] = polygon ? toPathString(polygon) : null;\n }\n\n return pulse.reflow(_.modified()).modifies(as);\n }\n\n}); // suppress duplicated end point vertices\n\nfunction toPathString(p) {\n const x = p[0][0],\n y = p[0][1];\n let n = p.length - 1;\n\n for (; p[n][0] === x && p[n][1] === y; --n);\n\n return 'M' + p.slice(0, n + 1).join('L') + 'Z';\n}\n\nexport { Voronoi as voronoi };\n","import { canvas } from 'vega-canvas';\nimport { Transform } from 'vega-dataflow';\nimport { inherits, error, isFunction, constant, extent } from 'vega-util';\nimport { scale } from 'vega-scale';\nimport { random } from 'vega-statistics';\n\n/*\nCopyright (c) 2013, Jason Davies.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n * The name Jason Davies may not be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL JASON DAVIES BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n// Word cloud layout by Jason Davies, https://www.jasondavies.com/wordcloud/\n// Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf\n\nvar cloudRadians = Math.PI / 180,\n cw = 1 << 11 >> 5,\n ch = 1 << 11;\nfunction cloud () {\n var size = [256, 256],\n text,\n font,\n fontSize,\n fontStyle,\n fontWeight,\n rotate,\n padding,\n spiral = archimedeanSpiral,\n words = [],\n random = Math.random,\n cloud = {};\n\n cloud.layout = function () {\n var contextAndRatio = getContext(canvas()),\n board = zeroArray((size[0] >> 5) * size[1]),\n bounds = null,\n n = words.length,\n i = -1,\n tags = [],\n data = words.map(d => ({\n text: text(d),\n font: font(d),\n style: fontStyle(d),\n weight: fontWeight(d),\n rotate: rotate(d),\n size: ~~(fontSize(d) + 1e-14),\n padding: padding(d),\n xoff: 0,\n yoff: 0,\n x1: 0,\n y1: 0,\n x0: 0,\n y0: 0,\n hasText: false,\n sprite: null,\n datum: d\n })).sort((a, b) => b.size - a.size);\n\n while (++i < n) {\n var d = data[i];\n d.x = size[0] * (random() + .5) >> 1;\n d.y = size[1] * (random() + .5) >> 1;\n cloudSprite(contextAndRatio, d, data, i);\n\n if (d.hasText && place(board, d, bounds)) {\n tags.push(d);\n if (bounds) cloudBounds(bounds, d);else bounds = [{\n x: d.x + d.x0,\n y: d.y + d.y0\n }, {\n x: d.x + d.x1,\n y: d.y + d.y1\n }]; // Temporary hack\n\n d.x -= size[0] >> 1;\n d.y -= size[1] >> 1;\n }\n }\n\n return tags;\n };\n\n function getContext(canvas) {\n canvas.width = canvas.height = 1;\n var ratio = Math.sqrt(canvas.getContext('2d').getImageData(0, 0, 1, 1).data.length >> 2);\n canvas.width = (cw << 5) / ratio;\n canvas.height = ch / ratio;\n var context = canvas.getContext('2d');\n context.fillStyle = context.strokeStyle = 'red';\n context.textAlign = 'center';\n return {\n context: context,\n ratio: ratio\n };\n }\n\n function place(board, tag, bounds) {\n var startX = tag.x,\n startY = tag.y,\n maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]),\n s = spiral(size),\n dt = random() < .5 ? 1 : -1,\n t = -dt,\n dxdy,\n dx,\n dy;\n\n while (dxdy = s(t += dt)) {\n dx = ~~dxdy[0];\n dy = ~~dxdy[1];\n if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break;\n tag.x = startX + dx;\n tag.y = startY + dy;\n if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 || tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue; // TODO only check for collisions within current bounds.\n\n if (!bounds || !cloudCollide(tag, board, size[0])) {\n if (!bounds || collideRects(tag, bounds)) {\n var sprite = tag.sprite,\n w = tag.width >> 5,\n sw = size[0] >> 5,\n lx = tag.x - (w << 4),\n sx = lx & 0x7f,\n msx = 32 - sx,\n h = tag.y1 - tag.y0,\n x = (tag.y + tag.y0) * sw + (lx >> 5),\n last;\n\n for (var j = 0; j < h; j++) {\n last = 0;\n\n for (var i = 0; i <= w; i++) {\n board[x + i] |= last << msx | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);\n }\n\n x += sw;\n }\n\n tag.sprite = null;\n return true;\n }\n }\n }\n\n return false;\n }\n\n cloud.words = function (_) {\n if (arguments.length) {\n words = _;\n return cloud;\n } else {\n return words;\n }\n };\n\n cloud.size = function (_) {\n if (arguments.length) {\n size = [+_[0], +_[1]];\n return cloud;\n } else {\n return size;\n }\n };\n\n cloud.font = function (_) {\n if (arguments.length) {\n font = functor(_);\n return cloud;\n } else {\n return font;\n }\n };\n\n cloud.fontStyle = function (_) {\n if (arguments.length) {\n fontStyle = functor(_);\n return cloud;\n } else {\n return fontStyle;\n }\n };\n\n cloud.fontWeight = function (_) {\n if (arguments.length) {\n fontWeight = functor(_);\n return cloud;\n } else {\n return fontWeight;\n }\n };\n\n cloud.rotate = function (_) {\n if (arguments.length) {\n rotate = functor(_);\n return cloud;\n } else {\n return rotate;\n }\n };\n\n cloud.text = function (_) {\n if (arguments.length) {\n text = functor(_);\n return cloud;\n } else {\n return text;\n }\n };\n\n cloud.spiral = function (_) {\n if (arguments.length) {\n spiral = spirals[_] || _;\n return cloud;\n } else {\n return spiral;\n }\n };\n\n cloud.fontSize = function (_) {\n if (arguments.length) {\n fontSize = functor(_);\n return cloud;\n } else {\n return fontSize;\n }\n };\n\n cloud.padding = function (_) {\n if (arguments.length) {\n padding = functor(_);\n return cloud;\n } else {\n return padding;\n }\n };\n\n cloud.random = function (_) {\n if (arguments.length) {\n random = _;\n return cloud;\n } else {\n return random;\n }\n };\n\n return cloud;\n} // Fetches a monochrome sprite bitmap for the specified text.\n// Load in batches for speed.\n\nfunction cloudSprite(contextAndRatio, d, data, di) {\n if (d.sprite) return;\n var c = contextAndRatio.context,\n ratio = contextAndRatio.ratio;\n c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);\n var x = 0,\n y = 0,\n maxh = 0,\n n = data.length,\n w,\n w32,\n h,\n i,\n j;\n --di;\n\n while (++di < n) {\n d = data[di];\n c.save();\n c.font = d.style + ' ' + d.weight + ' ' + ~~((d.size + 1) / ratio) + 'px ' + d.font;\n w = c.measureText(d.text + 'm').width * ratio;\n h = d.size << 1;\n\n if (d.rotate) {\n var sr = Math.sin(d.rotate * cloudRadians),\n cr = Math.cos(d.rotate * cloudRadians),\n wcr = w * cr,\n wsr = w * sr,\n hcr = h * cr,\n hsr = h * sr;\n w = Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f >> 5 << 5;\n h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));\n } else {\n w = w + 0x1f >> 5 << 5;\n }\n\n if (h > maxh) maxh = h;\n\n if (x + w >= cw << 5) {\n x = 0;\n y += maxh;\n maxh = 0;\n }\n\n if (y + h >= ch) break;\n c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);\n if (d.rotate) c.rotate(d.rotate * cloudRadians);\n c.fillText(d.text, 0, 0);\n\n if (d.padding) {\n c.lineWidth = 2 * d.padding;\n c.strokeText(d.text, 0, 0);\n }\n\n c.restore();\n d.width = w;\n d.height = h;\n d.xoff = x;\n d.yoff = y;\n d.x1 = w >> 1;\n d.y1 = h >> 1;\n d.x0 = -d.x1;\n d.y0 = -d.y1;\n d.hasText = true;\n x += w;\n }\n\n var pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data,\n sprite = [];\n\n while (--di >= 0) {\n d = data[di];\n if (!d.hasText) continue;\n w = d.width;\n w32 = w >> 5;\n h = d.y1 - d.y0; // Zero the buffer\n\n for (i = 0; i < h * w32; i++) sprite[i] = 0;\n\n x = d.xoff;\n if (x == null) return;\n y = d.yoff;\n var seen = 0,\n seenRow = -1;\n\n for (j = 0; j < h; j++) {\n for (i = 0; i < w; i++) {\n var k = w32 * j + (i >> 5),\n m = pixels[(y + j) * (cw << 5) + (x + i) << 2] ? 1 << 31 - i % 32 : 0;\n sprite[k] |= m;\n seen |= m;\n }\n\n if (seen) seenRow = j;else {\n d.y0++;\n h--;\n j--;\n y++;\n }\n }\n\n d.y1 = d.y0 + seenRow;\n d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);\n }\n} // Use mask-based collision detection.\n\n\nfunction cloudCollide(tag, board, sw) {\n sw >>= 5;\n var sprite = tag.sprite,\n w = tag.width >> 5,\n lx = tag.x - (w << 4),\n sx = lx & 0x7f,\n msx = 32 - sx,\n h = tag.y1 - tag.y0,\n x = (tag.y + tag.y0) * sw + (lx >> 5),\n last;\n\n for (var j = 0; j < h; j++) {\n last = 0;\n\n for (var i = 0; i <= w; i++) {\n if ((last << msx | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true;\n }\n\n x += sw;\n }\n\n return false;\n}\n\nfunction cloudBounds(bounds, d) {\n var b0 = bounds[0],\n b1 = bounds[1];\n if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;\n if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;\n if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;\n if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;\n}\n\nfunction collideRects(a, b) {\n return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y;\n}\n\nfunction archimedeanSpiral(size) {\n var e = size[0] / size[1];\n return function (t) {\n return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)];\n };\n}\n\nfunction rectangularSpiral(size) {\n var dy = 4,\n dx = dy * size[0] / size[1],\n x = 0,\n y = 0;\n return function (t) {\n var sign = t < 0 ? -1 : 1; // See triangular numbers: T_n = n * (n + 1) / 2.\n\n switch (Math.sqrt(1 + 4 * sign * t) - sign & 3) {\n case 0:\n x += dx;\n break;\n\n case 1:\n y += dy;\n break;\n\n case 2:\n x -= dx;\n break;\n\n default:\n y -= dy;\n break;\n }\n\n return [x, y];\n };\n} // TODO reuse arrays?\n\n\nfunction zeroArray(n) {\n var a = [],\n i = -1;\n\n while (++i < n) a[i] = 0;\n\n return a;\n}\n\nfunction functor(d) {\n return typeof d === 'function' ? d : function () {\n return d;\n };\n}\n\nvar spirals = {\n archimedean: archimedeanSpiral,\n rectangular: rectangularSpiral\n};\n\nconst Output = ['x', 'y', 'font', 'fontSize', 'fontStyle', 'fontWeight', 'angle'];\nconst Params = ['text', 'font', 'rotate', 'fontSize', 'fontStyle', 'fontWeight'];\nfunction Wordcloud(params) {\n Transform.call(this, cloud(), params);\n}\nWordcloud.Definition = {\n 'type': 'Wordcloud',\n 'metadata': {\n 'modifies': true\n },\n 'params': [{\n 'name': 'size',\n 'type': 'number',\n 'array': true,\n 'length': 2\n }, {\n 'name': 'font',\n 'type': 'string',\n 'expr': true,\n 'default': 'sans-serif'\n }, {\n 'name': 'fontStyle',\n 'type': 'string',\n 'expr': true,\n 'default': 'normal'\n }, {\n 'name': 'fontWeight',\n 'type': 'string',\n 'expr': true,\n 'default': 'normal'\n }, {\n 'name': 'fontSize',\n 'type': 'number',\n 'expr': true,\n 'default': 14\n }, {\n 'name': 'fontSizeRange',\n 'type': 'number',\n 'array': 'nullable',\n 'default': [10, 50]\n }, {\n 'name': 'rotate',\n 'type': 'number',\n 'expr': true,\n 'default': 0\n }, {\n 'name': 'text',\n 'type': 'field'\n }, {\n 'name': 'spiral',\n 'type': 'string',\n 'values': ['archimedean', 'rectangular']\n }, {\n 'name': 'padding',\n 'type': 'number',\n 'expr': true\n }, {\n 'name': 'as',\n 'type': 'string',\n 'array': true,\n 'length': 7,\n 'default': Output\n }]\n};\ninherits(Wordcloud, Transform, {\n transform(_, pulse) {\n if (_.size && !(_.size[0] && _.size[1])) {\n error('Wordcloud size dimensions must be non-zero.');\n }\n\n function modp(param) {\n const p = _[param];\n return isFunction(p) && pulse.modified(p.fields);\n }\n\n const mod = _.modified();\n\n if (!(mod || pulse.changed(pulse.ADD_REM) || Params.some(modp))) return;\n const data = pulse.materialize(pulse.SOURCE).source,\n layout = this.value,\n as = _.as || Output;\n let fontSize = _.fontSize || 14,\n range;\n isFunction(fontSize) ? range = _.fontSizeRange : fontSize = constant(fontSize); // create font size scaling function as needed\n\n if (range) {\n const fsize = fontSize,\n sizeScale = scale('sqrt')().domain(extent(data, fsize)).range(range);\n\n fontSize = x => sizeScale(fsize(x));\n }\n\n data.forEach(t => {\n t[as[0]] = NaN;\n t[as[1]] = NaN;\n t[as[3]] = 0;\n }); // configure layout\n\n const words = layout.words(data).text(_.text).size(_.size || [500, 500]).padding(_.padding || 1).spiral(_.spiral || 'archimedean').rotate(_.rotate || 0).font(_.font || 'sans-serif').fontStyle(_.fontStyle || 'normal').fontWeight(_.fontWeight || 'normal').fontSize(fontSize).random(random).layout();\n const size = layout.size(),\n dx = size[0] >> 1,\n dy = size[1] >> 1,\n n = words.length;\n\n for (let i = 0, w, t; i < n; ++i) {\n w = words[i];\n t = w.datum;\n t[as[0]] = w.x + dx;\n t[as[1]] = w.y + dy;\n t[as[2]] = w.font;\n t[as[3]] = w.size;\n t[as[4]] = w.style;\n t[as[5]] = w.weight;\n t[as[6]] = w.rotate;\n }\n\n return pulse.reflow(mod).modifies(as);\n }\n\n});\n\nexport { Wordcloud as wordcloud };\n","export default function(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","import ascending from \"./ascending.js\";\n\nexport default function(f) {\n let delta = f;\n let compare = f;\n\n if (f.length === 1) {\n delta = (d, x) => f(d) - x;\n compare = ascendingComparator(f);\n }\n\n function left(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (compare(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n\n function right(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (compare(a[mid], x) > 0) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n }\n\n function center(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n const i = left(a, x, lo, hi - 1);\n return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;\n }\n\n return {left, center, right};\n}\n\nfunction ascendingComparator(f) {\n return (d, x) => ascending(f(d), x);\n}\n","import ascending from \"./ascending.js\";\nimport bisector from \"./bisector.js\";\nimport number from \"./number.js\";\n\nconst ascendingBisect = bisector(ascending);\nexport const bisectRight = ascendingBisect.right;\nexport const bisectLeft = ascendingBisect.left;\nexport const bisectCenter = bisector(number).center;\nexport default bisectRight;\n","import { permute, bisectLeft, bisectRight } from 'd3-array';\nimport { Transform } from 'vega-dataflow';\nimport { inherits } from 'vega-util';\n\nconst array8 = n => new Uint8Array(n);\nconst array16 = n => new Uint16Array(n);\nconst array32 = n => new Uint32Array(n);\n\n/**\n * Maintains CrossFilter state.\n */\n\nfunction Bitmaps() {\n let width = 8,\n data = [],\n seen = array32(0),\n curr = array(0, width),\n prev = array(0, width);\n return {\n data: () => data,\n seen: () => seen = lengthen(seen, data.length),\n\n add(array) {\n for (let i = 0, j = data.length, n = array.length, t; i < n; ++i) {\n t = array[i];\n t._index = j++;\n data.push(t);\n }\n },\n\n remove(num, map) {\n // map: index -> boolean (true => remove)\n const n = data.length,\n copy = Array(n - num),\n reindex = data; // reuse old data array for index map\n\n let t, i, j; // seek forward to first removal\n\n for (i = 0; !map[i] && i < n; ++i) {\n copy[i] = data[i];\n reindex[i] = i;\n } // condense arrays\n\n\n for (j = i; i < n; ++i) {\n t = data[i];\n\n if (!map[i]) {\n reindex[i] = j;\n curr[j] = curr[i];\n prev[j] = prev[i];\n copy[j] = t;\n t._index = j++;\n } else {\n reindex[i] = -1;\n }\n\n curr[i] = 0; // clear unused bits\n }\n\n data = copy;\n return reindex;\n },\n\n size: () => data.length,\n curr: () => curr,\n prev: () => prev,\n reset: k => prev[k] = curr[k],\n all: () => width < 0x101 ? 0xff : width < 0x10001 ? 0xffff : 0xffffffff,\n\n set(k, one) {\n curr[k] |= one;\n },\n\n clear(k, one) {\n curr[k] &= ~one;\n },\n\n resize(n, m) {\n const k = curr.length;\n\n if (n > k || m > width) {\n width = Math.max(m, width);\n curr = array(n, width, curr);\n prev = array(n, width);\n }\n }\n\n };\n}\n\nfunction lengthen(array, length, copy) {\n if (array.length >= length) return array;\n copy = copy || new array.constructor(length);\n copy.set(array);\n return copy;\n}\n\nfunction array(n, m, array) {\n const copy = (m < 0x101 ? array8 : m < 0x10001 ? array16 : array32)(n);\n if (array) copy.set(array);\n return copy;\n}\n\nfunction Dimension (index, i, query) {\n const bit = 1 << i;\n return {\n one: bit,\n zero: ~bit,\n range: query.slice(),\n bisect: index.bisect,\n index: index.index,\n size: index.size,\n\n onAdd(added, curr) {\n const dim = this,\n range = dim.bisect(dim.range, added.value),\n idx = added.index,\n lo = range[0],\n hi = range[1],\n n1 = idx.length;\n let i;\n\n for (i = 0; i < lo; ++i) curr[idx[i]] |= bit;\n\n for (i = hi; i < n1; ++i) curr[idx[i]] |= bit;\n\n return dim;\n }\n\n };\n}\n\n/**\n * Maintains a list of values, sorted by key.\n */\n\nfunction SortedIndex() {\n let index = array32(0),\n value = [],\n size = 0;\n\n function insert(key, data, base) {\n if (!data.length) return [];\n const n0 = size,\n n1 = data.length,\n addi = array32(n1);\n let addv = Array(n1),\n oldv,\n oldi,\n i;\n\n for (i = 0; i < n1; ++i) {\n addv[i] = key(data[i]);\n addi[i] = i;\n }\n\n addv = sort(addv, addi);\n\n if (n0) {\n oldv = value;\n oldi = index;\n value = Array(n0 + n1);\n index = array32(n0 + n1);\n merge(base, oldv, oldi, n0, addv, addi, n1, value, index);\n } else {\n if (base > 0) for (i = 0; i < n1; ++i) {\n addi[i] += base;\n }\n value = addv;\n index = addi;\n }\n\n size = n0 + n1;\n return {\n index: addi,\n value: addv\n };\n }\n\n function remove(num, map) {\n // map: index -> remove\n const n = size;\n let idx, i, j; // seek forward to first removal\n\n for (i = 0; !map[index[i]] && i < n; ++i); // condense index and value arrays\n\n\n for (j = i; i < n; ++i) {\n if (!map[idx = index[i]]) {\n index[j] = idx;\n value[j] = value[i];\n ++j;\n }\n }\n\n size = n - num;\n }\n\n function reindex(map) {\n for (let i = 0, n = size; i < n; ++i) {\n index[i] = map[index[i]];\n }\n }\n\n function bisect(range, array) {\n let n;\n\n if (array) {\n n = array.length;\n } else {\n array = value;\n n = size;\n }\n\n return [bisectLeft(array, range[0], 0, n), bisectRight(array, range[1], 0, n)];\n }\n\n return {\n insert: insert,\n remove: remove,\n bisect: bisect,\n reindex: reindex,\n index: () => index,\n size: () => size\n };\n}\n\nfunction sort(values, index) {\n values.sort.call(index, (a, b) => {\n const x = values[a],\n y = values[b];\n return x < y ? -1 : x > y ? 1 : 0;\n });\n return permute(values, index);\n}\n\nfunction merge(base, value0, index0, n0, value1, index1, n1, value, index) {\n let i0 = 0,\n i1 = 0,\n i;\n\n for (i = 0; i0 < n0 && i1 < n1; ++i) {\n if (value0[i0] < value1[i1]) {\n value[i] = value0[i0];\n index[i] = index0[i0++];\n } else {\n value[i] = value1[i1];\n index[i] = index1[i1++] + base;\n }\n }\n\n for (; i0 < n0; ++i0, ++i) {\n value[i] = value0[i0];\n index[i] = index0[i0];\n }\n\n for (; i1 < n1; ++i1, ++i) {\n value[i] = value1[i1];\n index[i] = index1[i1] + base;\n }\n}\n\n/**\n * An indexed multi-dimensional filter.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {Array} params.fields - An array of dimension accessors to filter.\n * @param {Array} params.query - An array of per-dimension range queries.\n */\n\nfunction CrossFilter(params) {\n Transform.call(this, Bitmaps(), params);\n this._indices = null;\n this._dims = null;\n}\nCrossFilter.Definition = {\n 'type': 'CrossFilter',\n 'metadata': {},\n 'params': [{\n 'name': 'fields',\n 'type': 'field',\n 'array': true,\n 'required': true\n }, {\n 'name': 'query',\n 'type': 'array',\n 'array': true,\n 'required': true,\n 'content': {\n 'type': 'number',\n 'array': true,\n 'length': 2\n }\n }]\n};\ninherits(CrossFilter, Transform, {\n transform(_, pulse) {\n if (!this._dims) {\n return this.init(_, pulse);\n } else {\n var init = _.modified('fields') || _.fields.some(f => pulse.modified(f.fields));\n\n return init ? this.reinit(_, pulse) : this.eval(_, pulse);\n }\n },\n\n init(_, pulse) {\n const fields = _.fields,\n query = _.query,\n indices = this._indices = {},\n dims = this._dims = [],\n m = query.length;\n let i = 0,\n key,\n index; // instantiate indices and dimensions\n\n for (; i < m; ++i) {\n key = fields[i].fname;\n index = indices[key] || (indices[key] = SortedIndex());\n dims.push(Dimension(index, i, query[i]));\n }\n\n return this.eval(_, pulse);\n },\n\n reinit(_, pulse) {\n const output = pulse.materialize().fork(),\n fields = _.fields,\n query = _.query,\n indices = this._indices,\n dims = this._dims,\n bits = this.value,\n curr = bits.curr(),\n prev = bits.prev(),\n all = bits.all(),\n out = output.rem = output.add,\n mod = output.mod,\n m = query.length,\n adds = {};\n let add, index, key, mods, remMap, modMap, i, n, f; // set prev to current state\n\n prev.set(curr); // if pulse has remove tuples, process them first\n\n if (pulse.rem.length) {\n remMap = this.remove(_, pulse, output);\n } // if pulse has added tuples, add them to state\n\n\n if (pulse.add.length) {\n bits.add(pulse.add);\n } // if pulse has modified tuples, create an index map\n\n\n if (pulse.mod.length) {\n modMap = {};\n\n for (mods = pulse.mod, i = 0, n = mods.length; i < n; ++i) {\n modMap[mods[i]._index] = 1;\n }\n } // re-initialize indices as needed, update curr bitmap\n\n\n for (i = 0; i < m; ++i) {\n f = fields[i];\n\n if (!dims[i] || _.modified('fields', i) || pulse.modified(f.fields)) {\n key = f.fname;\n\n if (!(add = adds[key])) {\n indices[key] = index = SortedIndex();\n adds[key] = add = index.insert(f, pulse.source, 0);\n }\n\n dims[i] = Dimension(index, i, query[i]).onAdd(add, curr);\n }\n } // visit each tuple\n // if filter state changed, push index to add/rem\n // else if in mod and passes a filter, push index to mod\n\n\n for (i = 0, n = bits.data().length; i < n; ++i) {\n if (remMap[i]) {\n // skip if removed tuple\n continue;\n } else if (prev[i] !== curr[i]) {\n // add if state changed\n out.push(i);\n } else if (modMap[i] && curr[i] !== all) {\n // otherwise, pass mods through\n mod.push(i);\n }\n }\n\n bits.mask = (1 << m) - 1;\n return output;\n },\n\n eval(_, pulse) {\n const output = pulse.materialize().fork(),\n m = this._dims.length;\n let mask = 0;\n\n if (pulse.rem.length) {\n this.remove(_, pulse, output);\n mask |= (1 << m) - 1;\n }\n\n if (_.modified('query') && !_.modified('fields')) {\n mask |= this.update(_, pulse, output);\n }\n\n if (pulse.add.length) {\n this.insert(_, pulse, output);\n mask |= (1 << m) - 1;\n }\n\n if (pulse.mod.length) {\n this.modify(pulse, output);\n mask |= (1 << m) - 1;\n }\n\n this.value.mask = mask;\n return output;\n },\n\n insert(_, pulse, output) {\n const tuples = pulse.add,\n bits = this.value,\n dims = this._dims,\n indices = this._indices,\n fields = _.fields,\n adds = {},\n out = output.add,\n n = bits.size() + tuples.length,\n m = dims.length;\n let k = bits.size(),\n j,\n key,\n add; // resize bitmaps and add tuples as needed\n\n bits.resize(n, m);\n bits.add(tuples);\n const curr = bits.curr(),\n prev = bits.prev(),\n all = bits.all(); // add to dimensional indices\n\n for (j = 0; j < m; ++j) {\n key = fields[j].fname;\n add = adds[key] || (adds[key] = indices[key].insert(fields[j], tuples, k));\n dims[j].onAdd(add, curr);\n } // set previous filters, output if passes at least one filter\n\n\n for (; k < n; ++k) {\n prev[k] = all;\n if (curr[k] !== all) out.push(k);\n }\n },\n\n modify(pulse, output) {\n const out = output.mod,\n bits = this.value,\n curr = bits.curr(),\n all = bits.all(),\n tuples = pulse.mod;\n let i, n, k;\n\n for (i = 0, n = tuples.length; i < n; ++i) {\n k = tuples[i]._index;\n if (curr[k] !== all) out.push(k);\n }\n },\n\n remove(_, pulse, output) {\n const indices = this._indices,\n bits = this.value,\n curr = bits.curr(),\n prev = bits.prev(),\n all = bits.all(),\n map = {},\n out = output.rem,\n tuples = pulse.rem;\n let i, n, k, f; // process tuples, output if passes at least one filter\n\n for (i = 0, n = tuples.length; i < n; ++i) {\n k = tuples[i]._index;\n map[k] = 1; // build index map\n\n prev[k] = f = curr[k];\n curr[k] = all;\n if (f !== all) out.push(k);\n } // remove from dimensional indices\n\n\n for (k in indices) {\n indices[k].remove(n, map);\n }\n\n this.reindex(pulse, n, map);\n return map;\n },\n\n // reindex filters and indices after propagation completes\n reindex(pulse, num, map) {\n const indices = this._indices,\n bits = this.value;\n pulse.runAfter(() => {\n const indexMap = bits.remove(num, map);\n\n for (const key in indices) indices[key].reindex(indexMap);\n });\n },\n\n update(_, pulse, output) {\n const dims = this._dims,\n query = _.query,\n stamp = pulse.stamp,\n m = dims.length;\n let mask = 0,\n i,\n q; // survey how many queries have changed\n\n output.filters = 0;\n\n for (q = 0; q < m; ++q) {\n if (_.modified('query', q)) {\n i = q;\n ++mask;\n }\n }\n\n if (mask === 1) {\n // only one query changed, use more efficient update\n mask = dims[i].one;\n this.incrementOne(dims[i], query[i], output.add, output.rem);\n } else {\n // multiple queries changed, perform full record keeping\n for (q = 0, mask = 0; q < m; ++q) {\n if (!_.modified('query', q)) continue;\n mask |= dims[q].one;\n this.incrementAll(dims[q], query[q], stamp, output.add);\n output.rem = output.add; // duplicate add/rem for downstream resolve\n }\n }\n\n return mask;\n },\n\n incrementAll(dim, query, stamp, out) {\n const bits = this.value,\n seen = bits.seen(),\n curr = bits.curr(),\n prev = bits.prev(),\n index = dim.index(),\n old = dim.bisect(dim.range),\n range = dim.bisect(query),\n lo1 = range[0],\n hi1 = range[1],\n lo0 = old[0],\n hi0 = old[1],\n one = dim.one;\n let i, j, k; // Fast incremental update based on previous lo index.\n\n if (lo1 < lo0) {\n for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {\n k = index[i];\n\n if (seen[k] !== stamp) {\n prev[k] = curr[k];\n seen[k] = stamp;\n out.push(k);\n }\n\n curr[k] ^= one;\n }\n } else if (lo1 > lo0) {\n for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {\n k = index[i];\n\n if (seen[k] !== stamp) {\n prev[k] = curr[k];\n seen[k] = stamp;\n out.push(k);\n }\n\n curr[k] ^= one;\n }\n } // Fast incremental update based on previous hi index.\n\n\n if (hi1 > hi0) {\n for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {\n k = index[i];\n\n if (seen[k] !== stamp) {\n prev[k] = curr[k];\n seen[k] = stamp;\n out.push(k);\n }\n\n curr[k] ^= one;\n }\n } else if (hi1 < hi0) {\n for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {\n k = index[i];\n\n if (seen[k] !== stamp) {\n prev[k] = curr[k];\n seen[k] = stamp;\n out.push(k);\n }\n\n curr[k] ^= one;\n }\n }\n\n dim.range = query.slice();\n },\n\n incrementOne(dim, query, add, rem) {\n const bits = this.value,\n curr = bits.curr(),\n index = dim.index(),\n old = dim.bisect(dim.range),\n range = dim.bisect(query),\n lo1 = range[0],\n hi1 = range[1],\n lo0 = old[0],\n hi0 = old[1],\n one = dim.one;\n let i, j, k; // Fast incremental update based on previous lo index.\n\n if (lo1 < lo0) {\n for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {\n k = index[i];\n curr[k] ^= one;\n add.push(k);\n }\n } else if (lo1 > lo0) {\n for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {\n k = index[i];\n curr[k] ^= one;\n rem.push(k);\n }\n } // Fast incremental update based on previous hi index.\n\n\n if (hi1 > hi0) {\n for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {\n k = index[i];\n curr[k] ^= one;\n add.push(k);\n }\n } else if (hi1 < hi0) {\n for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {\n k = index[i];\n curr[k] ^= one;\n rem.push(k);\n }\n }\n\n dim.range = query.slice();\n }\n\n});\n\n/**\n * Selectively filters tuples by resolving against a filter bitmap.\n * Useful for processing the output of a cross-filter transform.\n * @constructor\n * @param {object} params - The parameters for this operator.\n * @param {object} params.ignore - A bit mask indicating which filters to ignore.\n * @param {object} params.filter - The per-tuple filter bitmaps. Typically this\n * parameter value is a reference to a {@link CrossFilter} transform.\n */\n\nfunction ResolveFilter(params) {\n Transform.call(this, null, params);\n}\nResolveFilter.Definition = {\n 'type': 'ResolveFilter',\n 'metadata': {},\n 'params': [{\n 'name': 'ignore',\n 'type': 'number',\n 'required': true,\n 'description': 'A bit mask indicating which filters to ignore.'\n }, {\n 'name': 'filter',\n 'type': 'object',\n 'required': true,\n 'description': 'Per-tuple filter bitmaps from a CrossFilter transform.'\n }]\n};\ninherits(ResolveFilter, Transform, {\n transform(_, pulse) {\n const ignore = ~(_.ignore || 0),\n // bit mask where zeros -> dims to ignore\n bitmap = _.filter,\n mask = bitmap.mask; // exit early if no relevant filter changes\n\n if ((mask & ignore) === 0) return pulse.StopPropagation;\n\n const output = pulse.fork(pulse.ALL),\n data = bitmap.data(),\n curr = bitmap.curr(),\n prev = bitmap.prev(),\n pass = k => !(curr[k] & ignore) ? data[k] : null; // propagate all mod tuples that pass the filter\n\n\n output.filter(output.MOD, pass); // determine add & rem tuples via filter functions\n // for efficiency, we do *not* populate new arrays,\n // instead we add filter functions applied downstream\n\n if (!(mask & mask - 1)) {\n // only one filter changed\n output.filter(output.ADD, pass);\n output.filter(output.REM, k => (curr[k] & ignore) === mask ? data[k] : null);\n } else {\n // multiple filters changed\n output.filter(output.ADD, k => {\n const c = curr[k] & ignore,\n f = !c && c ^ prev[k] & ignore;\n return f ? data[k] : null;\n });\n output.filter(output.REM, k => {\n const c = curr[k] & ignore,\n f = c && !(c ^ (c ^ prev[k] & ignore));\n return f ? data[k] : null;\n });\n } // add filter to source data in case of reflow...\n\n\n return output.filter(output.SOURCE, t => pass(t._index));\n }\n\n});\n\nexport { CrossFilter as crossfilter, ResolveFilter as resolvefilter };\n","export default function(x) {\n return x === null ? NaN : +x;\n}\n\nexport function* numbers(values, valueof) {\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n yield value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n yield value;\n }\n }\n }\n}\n","export default function(source, keys) {\n return Array.from(keys, key => source[key]);\n}\n","var e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nexport default function(start, stop, count) {\n var reverse,\n i = -1,\n n,\n ticks,\n step;\n\n stop = +stop, start = +start, count = +count;\n if (start === stop && count > 0) return [start];\n if (reverse = stop < start) n = start, start = stop, stop = n;\n if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];\n\n if (step > 0) {\n let r0 = Math.round(start / step), r1 = Math.round(stop / step);\n if (r0 * step < start) ++r0;\n if (r1 * step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) * step;\n } else {\n step = -step;\n let r0 = Math.round(start * step), r1 = Math.round(stop * step);\n if (r0 / step < start) ++r0;\n if (r1 / step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) / step;\n }\n\n if (reverse) ticks.reverse();\n\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n var step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log(step) / Math.LN10),\n error = step / Math.pow(10, power);\n return power >= 0\n ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)\n : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);\n}\n\nexport function tickStep(start, stop, count) {\n var step0 = Math.abs(stop - start) / Math.max(0, count),\n step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),\n error = step0 / step1;\n if (error >= e10) step1 *= 10;\n else if (error >= e5) step1 *= 5;\n else if (error >= e2) step1 *= 2;\n return stop < start ? -step1 : step1;\n}\n","import { error, toSet, isFunction, isString, hasOwnProperty } from 'vega-util';\n\nconst RawCode = 'RawCode';\nconst Literal = 'Literal';\nconst Property = 'Property';\nconst Identifier = 'Identifier';\nconst ArrayExpression = 'ArrayExpression';\nconst BinaryExpression = 'BinaryExpression';\nconst CallExpression = 'CallExpression';\nconst ConditionalExpression = 'ConditionalExpression';\nconst LogicalExpression = 'LogicalExpression';\nconst MemberExpression = 'MemberExpression';\nconst ObjectExpression = 'ObjectExpression';\nconst UnaryExpression = 'UnaryExpression';\nfunction ASTNode(type) {\n this.type = type;\n}\n\nASTNode.prototype.visit = function (visitor) {\n let c, i, n;\n if (visitor(this)) return 1;\n\n for (c = children(this), i = 0, n = c.length; i < n; ++i) {\n if (c[i].visit(visitor)) return 1;\n }\n};\n\nfunction children(node) {\n switch (node.type) {\n case ArrayExpression:\n return node.elements;\n\n case BinaryExpression:\n case LogicalExpression:\n return [node.left, node.right];\n\n case CallExpression:\n return [node.callee].concat(node.arguments);\n\n case ConditionalExpression:\n return [node.test, node.consequent, node.alternate];\n\n case MemberExpression:\n return [node.object, node.property];\n\n case ObjectExpression:\n return node.properties;\n\n case Property:\n return [node.key, node.value];\n\n case UnaryExpression:\n return [node.argument];\n\n case Identifier:\n case Literal:\n case RawCode:\n default:\n return [];\n }\n}\n\n/*\n The following expression parser is based on Esprima (http://esprima.org/).\n Original header comment and license for Esprima is included here:\n\n Copyright (C) 2013 Ariya Hidayat \n Copyright (C) 2013 Thaddee Tyl \n Copyright (C) 2013 Mathias Bynens \n Copyright (C) 2012 Ariya Hidayat \n Copyright (C) 2012 Mathias Bynens \n Copyright (C) 2012 Joost-Wim Boekesteijn \n Copyright (C) 2012 Kris Kowal \n Copyright (C) 2012 Yusuke Suzuki \n Copyright (C) 2012 Arpad Borsos \n Copyright (C) 2011 Ariya Hidayat \n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\nvar TokenName, source, index, length, lookahead;\nvar TokenBooleanLiteral = 1,\n TokenEOF = 2,\n TokenIdentifier = 3,\n TokenKeyword = 4,\n TokenNullLiteral = 5,\n TokenNumericLiteral = 6,\n TokenPunctuator = 7,\n TokenStringLiteral = 8,\n TokenRegularExpression = 9;\nTokenName = {};\nTokenName[TokenBooleanLiteral] = 'Boolean';\nTokenName[TokenEOF] = '';\nTokenName[TokenIdentifier] = 'Identifier';\nTokenName[TokenKeyword] = 'Keyword';\nTokenName[TokenNullLiteral] = 'Null';\nTokenName[TokenNumericLiteral] = 'Numeric';\nTokenName[TokenPunctuator] = 'Punctuator';\nTokenName[TokenStringLiteral] = 'String';\nTokenName[TokenRegularExpression] = 'RegularExpression';\nvar SyntaxArrayExpression = 'ArrayExpression',\n SyntaxBinaryExpression = 'BinaryExpression',\n SyntaxCallExpression = 'CallExpression',\n SyntaxConditionalExpression = 'ConditionalExpression',\n SyntaxIdentifier = 'Identifier',\n SyntaxLiteral = 'Literal',\n SyntaxLogicalExpression = 'LogicalExpression',\n SyntaxMemberExpression = 'MemberExpression',\n SyntaxObjectExpression = 'ObjectExpression',\n SyntaxProperty = 'Property',\n SyntaxUnaryExpression = 'UnaryExpression'; // Error messages should be identical to V8.\n\nvar MessageUnexpectedToken = 'Unexpected token %0',\n MessageUnexpectedNumber = 'Unexpected number',\n MessageUnexpectedString = 'Unexpected string',\n MessageUnexpectedIdentifier = 'Unexpected identifier',\n MessageUnexpectedReserved = 'Unexpected reserved word',\n MessageUnexpectedEOS = 'Unexpected end of input',\n MessageInvalidRegExp = 'Invalid regular expression',\n MessageUnterminatedRegExp = 'Invalid regular expression: missing /',\n MessageStrictOctalLiteral = 'Octal literals are not allowed in strict mode.',\n MessageStrictDuplicateProperty = 'Duplicate data property in object literal not allowed in strict mode';\nvar ILLEGAL = 'ILLEGAL',\n DISABLED = 'Disabled.'; // See also tools/generate-unicode-regex.py.\n\nvar RegexNonAsciiIdentifierStart = new RegExp('[\\\\xAA\\\\xB5\\\\xBA\\\\xC0-\\\\xD6\\\\xD8-\\\\xF6\\\\xF8-\\\\u02C1\\\\u02C6-\\\\u02D1\\\\u02E0-\\\\u02E4\\\\u02EC\\\\u02EE\\\\u0370-\\\\u0374\\\\u0376\\\\u0377\\\\u037A-\\\\u037D\\\\u037F\\\\u0386\\\\u0388-\\\\u038A\\\\u038C\\\\u038E-\\\\u03A1\\\\u03A3-\\\\u03F5\\\\u03F7-\\\\u0481\\\\u048A-\\\\u052F\\\\u0531-\\\\u0556\\\\u0559\\\\u0561-\\\\u0587\\\\u05D0-\\\\u05EA\\\\u05F0-\\\\u05F2\\\\u0620-\\\\u064A\\\\u066E\\\\u066F\\\\u0671-\\\\u06D3\\\\u06D5\\\\u06E5\\\\u06E6\\\\u06EE\\\\u06EF\\\\u06FA-\\\\u06FC\\\\u06FF\\\\u0710\\\\u0712-\\\\u072F\\\\u074D-\\\\u07A5\\\\u07B1\\\\u07CA-\\\\u07EA\\\\u07F4\\\\u07F5\\\\u07FA\\\\u0800-\\\\u0815\\\\u081A\\\\u0824\\\\u0828\\\\u0840-\\\\u0858\\\\u08A0-\\\\u08B2\\\\u0904-\\\\u0939\\\\u093D\\\\u0950\\\\u0958-\\\\u0961\\\\u0971-\\\\u0980\\\\u0985-\\\\u098C\\\\u098F\\\\u0990\\\\u0993-\\\\u09A8\\\\u09AA-\\\\u09B0\\\\u09B2\\\\u09B6-\\\\u09B9\\\\u09BD\\\\u09CE\\\\u09DC\\\\u09DD\\\\u09DF-\\\\u09E1\\\\u09F0\\\\u09F1\\\\u0A05-\\\\u0A0A\\\\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\\\u0DBB\\\\u0DBD\\\\u0DC0-\\\\u0DC6\\\\u0E01-\\\\u0E30\\\\u0E32\\\\u0E33\\\\u0E40-\\\\u0E46\\\\u0E81\\\\u0E82\\\\u0E84\\\\u0E87\\\\u0E88\\\\u0E8A\\\\u0E8D\\\\u0E94-\\\\u0E97\\\\u0E99-\\\\u0E9F\\\\u0EA1-\\\\u0EA3\\\\u0EA5\\\\u0EA7\\\\u0EAA\\\\u0EAB\\\\u0EAD-\\\\u0EB0\\\\u0EB2\\\\u0EB3\\\\u0EBD\\\\u0EC0-\\\\u0EC4\\\\u0EC6\\\\u0EDC-\\\\u0EDF\\\\u0F00\\\\u0F40-\\\\u0F47\\\\u0F49-\\\\u0F6C\\\\u0F88-\\\\u0F8C\\\\u1000-\\\\u102A\\\\u103F\\\\u1050-\\\\u1055\\\\u105A-\\\\u105D\\\\u1061\\\\u1065\\\\u1066\\\\u106E-\\\\u1070\\\\u1075-\\\\u1081\\\\u108E\\\\u10A0-\\\\u10C5\\\\u10C7\\\\u10CD\\\\u10D0-\\\\u10FA\\\\u10FC-\\\\u1248\\\\u124A-\\\\u124D\\\\u1250-\\\\u1256\\\\u1258\\\\u125A-\\\\u125D\\\\u1260-\\\\u1288\\\\u128A-\\\\u128D\\\\u1290-\\\\u12B0\\\\u12B2-\\\\u12B5\\\\u12B8-\\\\u12BE\\\\u12C0\\\\u12C2-\\\\u12C5\\\\u12C8-\\\\u12D6\\\\u12D8-\\\\u1310\\\\u1312-\\\\u1315\\\\u1318-\\\\u135A\\\\u1380-\\\\u138F\\\\u13A0-\\\\u13F4\\\\u1401-\\\\u166C\\\\u166F-\\\\u167F\\\\u1681-\\\\u169A\\\\u16A0-\\\\u16EA\\\\u16EE-\\\\u16F8\\\\u1700-\\\\u170C\\\\u170E-\\\\u1711\\\\u1720-\\\\u1731\\\\u1740-\\\\u1751\\\\u1760-\\\\u176C\\\\u176E-\\\\u1770\\\\u1780-\\\\u17B3\\\\u17D7\\\\u17DC\\\\u1820-\\\\u1877\\\\u1880-\\\\u18A8\\\\u18AA\\\\u18B0-\\\\u18F5\\\\u1900-\\\\u191E\\\\u1950-\\\\u196D\\\\u1970-\\\\u1974\\\\u1980-\\\\u19AB\\\\u19C1-\\\\u19C7\\\\u1A00-\\\\u1A16\\\\u1A20-\\\\u1A54\\\\u1AA7\\\\u1B05-\\\\u1B33\\\\u1B45-\\\\u1B4B\\\\u1B83-\\\\u1BA0\\\\u1BAE\\\\u1BAF\\\\u1BBA-\\\\u1BE5\\\\u1C00-\\\\u1C23\\\\u1C4D-\\\\u1C4F\\\\u1C5A-\\\\u1C7D\\\\u1CE9-\\\\u1CEC\\\\u1CEE-\\\\u1CF1\\\\u1CF5\\\\u1CF6\\\\u1D00-\\\\u1DBF\\\\u1E00-\\\\u1F15\\\\u1F18-\\\\u1F1D\\\\u1F20-\\\\u1F45\\\\u1F48-\\\\u1F4D\\\\u1F50-\\\\u1F57\\\\u1F59\\\\u1F5B\\\\u1F5D\\\\u1F5F-\\\\u1F7D\\\\u1F80-\\\\u1FB4\\\\u1FB6-\\\\u1FBC\\\\u1FBE\\\\u1FC2-\\\\u1FC4\\\\u1FC6-\\\\u1FCC\\\\u1FD0-\\\\u1FD3\\\\u1FD6-\\\\u1FDB\\\\u1FE0-\\\\u1FEC\\\\u1FF2-\\\\u1FF4\\\\u1FF6-\\\\u1FFC\\\\u2071\\\\u207F\\\\u2090-\\\\u209C\\\\u2102\\\\u2107\\\\u210A-\\\\u2113\\\\u2115\\\\u2119-\\\\u211D\\\\u2124\\\\u2126\\\\u2128\\\\u212A-\\\\u212D\\\\u212F-\\\\u2139\\\\u213C-\\\\u213F\\\\u2145-\\\\u2149\\\\u214E\\\\u2160-\\\\u2188\\\\u2C00-\\\\u2C2E\\\\u2C30-\\\\u2C5E\\\\u2C60-\\\\u2CE4\\\\u2CEB-\\\\u2CEE\\\\u2CF2\\\\u2CF3\\\\u2D00-\\\\u2D25\\\\u2D27\\\\u2D2D\\\\u2D30-\\\\u2D67\\\\u2D6F\\\\u2D80-\\\\u2D96\\\\u2DA0-\\\\u2DA6\\\\u2DA8-\\\\u2DAE\\\\u2DB0-\\\\u2DB6\\\\u2DB8-\\\\u2DBE\\\\u2DC0-\\\\u2DC6\\\\u2DC8-\\\\u2DCE\\\\u2DD0-\\\\u2DD6\\\\u2DD8-\\\\u2DDE\\\\u2E2F\\\\u3005-\\\\u3007\\\\u3021-\\\\u3029\\\\u3031-\\\\u3035\\\\u3038-\\\\u303C\\\\u3041-\\\\u3096\\\\u309D-\\\\u309F\\\\u30A1-\\\\u30FA\\\\u30FC-\\\\u30FF\\\\u3105-\\\\u312D\\\\u3131-\\\\u318E\\\\u31A0-\\\\u31BA\\\\u31F0-\\\\u31FF\\\\u3400-\\\\u4DB5\\\\u4E00-\\\\u9FCC\\\\uA000-\\\\uA48C\\\\uA4D0-\\\\uA4FD\\\\uA500-\\\\uA60C\\\\uA610-\\\\uA61F\\\\uA62A\\\\uA62B\\\\uA640-\\\\uA66E\\\\uA67F-\\\\uA69D\\\\uA6A0-\\\\uA6EF\\\\uA717-\\\\uA71F\\\\uA722-\\\\uA788\\\\uA78B-\\\\uA78E\\\\uA790-\\\\uA7AD\\\\uA7B0\\\\uA7B1\\\\uA7F7-\\\\uA801\\\\uA803-\\\\uA805\\\\uA807-\\\\uA80A\\\\uA80C-\\\\uA822\\\\uA840-\\\\uA873\\\\uA882-\\\\uA8B3\\\\uA8F2-\\\\uA8F7\\\\uA8FB\\\\uA90A-\\\\uA925\\\\uA930-\\\\uA946\\\\uA960-\\\\uA97C\\\\uA984-\\\\uA9B2\\\\uA9CF\\\\uA9E0-\\\\uA9E4\\\\uA9E6-\\\\uA9EF\\\\uA9FA-\\\\uA9FE\\\\uAA00-\\\\uAA28\\\\uAA40-\\\\uAA42\\\\uAA44-\\\\uAA4B\\\\uAA60-\\\\uAA76\\\\uAA7A\\\\uAA7E-\\\\uAAAF\\\\uAAB1\\\\uAAB5\\\\uAAB6\\\\uAAB9-\\\\uAABD\\\\uAAC0\\\\uAAC2\\\\uAADB-\\\\uAADD\\\\uAAE0-\\\\uAAEA\\\\uAAF2-\\\\uAAF4\\\\uAB01-\\\\uAB06\\\\uAB09-\\\\uAB0E\\\\uAB11-\\\\uAB16\\\\uAB20-\\\\uAB26\\\\uAB28-\\\\uAB2E\\\\uAB30-\\\\uAB5A\\\\uAB5C-\\\\uAB5F\\\\uAB64\\\\uAB65\\\\uABC0-\\\\uABE2\\\\uAC00-\\\\uD7A3\\\\uD7B0-\\\\uD7C6\\\\uD7CB-\\\\uD7FB\\\\uF900-\\\\uFA6D\\\\uFA70-\\\\uFAD9\\\\uFB00-\\\\uFB06\\\\uFB13-\\\\uFB17\\\\uFB1D\\\\uFB1F-\\\\uFB28\\\\uFB2A-\\\\uFB36\\\\uFB38-\\\\uFB3C\\\\uFB3E\\\\uFB40\\\\uFB41\\\\uFB43\\\\uFB44\\\\uFB46-\\\\uFBB1\\\\uFBD3-\\\\uFD3D\\\\uFD50-\\\\uFD8F\\\\uFD92-\\\\uFDC7\\\\uFDF0-\\\\uFDFB\\\\uFE70-\\\\uFE74\\\\uFE76-\\\\uFEFC\\\\uFF21-\\\\uFF3A\\\\uFF41-\\\\uFF5A\\\\uFF66-\\\\uFFBE\\\\uFFC2-\\\\uFFC7\\\\uFFCA-\\\\uFFCF\\\\uFFD2-\\\\uFFD7\\\\uFFDA-\\\\uFFDC]'),\n // eslint-disable-next-line no-misleading-character-class\nRegexNonAsciiIdentifierPart = new RegExp('[\\\\xAA\\\\xB5\\\\xBA\\\\xC0-\\\\xD6\\\\xD8-\\\\xF6\\\\xF8-\\\\u02C1\\\\u02C6-\\\\u02D1\\\\u02E0-\\\\u02E4\\\\u02EC\\\\u02EE\\\\u0300-\\\\u0374\\\\u0376\\\\u0377\\\\u037A-\\\\u037D\\\\u037F\\\\u0386\\\\u0388-\\\\u038A\\\\u038C\\\\u038E-\\\\u03A1\\\\u03A3-\\\\u03F5\\\\u03F7-\\\\u0481\\\\u0483-\\\\u0487\\\\u048A-\\\\u052F\\\\u0531-\\\\u0556\\\\u0559\\\\u0561-\\\\u0587\\\\u0591-\\\\u05BD\\\\u05BF\\\\u05C1\\\\u05C2\\\\u05C4\\\\u05C5\\\\u05C7\\\\u05D0-\\\\u05EA\\\\u05F0-\\\\u05F2\\\\u0610-\\\\u061A\\\\u0620-\\\\u0669\\\\u066E-\\\\u06D3\\\\u06D5-\\\\u06DC\\\\u06DF-\\\\u06E8\\\\u06EA-\\\\u06FC\\\\u06FF\\\\u0710-\\\\u074A\\\\u074D-\\\\u07B1\\\\u07C0-\\\\u07F5\\\\u07FA\\\\u0800-\\\\u082D\\\\u0840-\\\\u085B\\\\u08A0-\\\\u08B2\\\\u08E4-\\\\u0963\\\\u0966-\\\\u096F\\\\u0971-\\\\u0983\\\\u0985-\\\\u098C\\\\u098F\\\\u0990\\\\u0993-\\\\u09A8\\\\u09AA-\\\\u09B0\\\\u09B2\\\\u09B6-\\\\u09B9\\\\u09BC-\\\\u09C4\\\\u09C7\\\\u09C8\\\\u09CB-\\\\u09CE\\\\u09D7\\\\u09DC\\\\u09DD\\\\u09DF-\\\\u09E3\\\\u09E6-\\\\u09F1\\\\u0A01-\\\\u0A03\\\\u0A05-\\\\u0A0A\\\\u0A0F\\\\u0A10\\\\u0A13-\\\\u0A28\\\\u0A2A-\\\\u0A30\\\\u0A32\\\\u0A33\\\\u0A35\\\\u0A36\\\\u0A38\\\\u0A39\\\\u0A3C\\\\u0A3E-\\\\u0A42\\\\u0A47\\\\u0A48\\\\u0A4B-\\\\u0A4D\\\\u0A51\\\\u0A59-\\\\u0A5C\\\\u0A5E\\\\u0A66-\\\\u0A75\\\\u0A81-\\\\u0A83\\\\u0A85-\\\\u0A8D\\\\u0A8F-\\\\u0A91\\\\u0A93-\\\\u0AA8\\\\u0AAA-\\\\u0AB0\\\\u0AB2\\\\u0AB3\\\\u0AB5-\\\\u0AB9\\\\u0ABC-\\\\u0AC5\\\\u0AC7-\\\\u0AC9\\\\u0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\u1260-\\\\u1288\\\\u128A-\\\\u128D\\\\u1290-\\\\u12B0\\\\u12B2-\\\\u12B5\\\\u12B8-\\\\u12BE\\\\u12C0\\\\u12C2-\\\\u12C5\\\\u12C8-\\\\u12D6\\\\u12D8-\\\\u1310\\\\u1312-\\\\u1315\\\\u1318-\\\\u135A\\\\u135D-\\\\u135F\\\\u1380-\\\\u138F\\\\u13A0-\\\\u13F4\\\\u1401-\\\\u166C\\\\u166F-\\\\u167F\\\\u1681-\\\\u169A\\\\u16A0-\\\\u16EA\\\\u16EE-\\\\u16F8\\\\u1700-\\\\u170C\\\\u170E-\\\\u1714\\\\u1720-\\\\u1734\\\\u1740-\\\\u1753\\\\u1760-\\\\u176C\\\\u176E-\\\\u1770\\\\u1772\\\\u1773\\\\u1780-\\\\u17D3\\\\u17D7\\\\u17DC\\\\u17DD\\\\u17E0-\\\\u17E9\\\\u180B-\\\\u180D\\\\u1810-\\\\u1819\\\\u1820-\\\\u1877\\\\u1880-\\\\u18AA\\\\u18B0-\\\\u18F5\\\\u1900-\\\\u191E\\\\u1920-\\\\u192B\\\\u1930-\\\\u193B\\\\u1946-\\\\u196D\\\\u1970-\\\\u1974\\\\u1980-\\\\u19AB\\\\u19B0-\\\\u19C9\\\\u19D0-\\\\u19D9\\\\u1A00-\\\\u1A1B\\\\u1A20-\\\\u1A5E\\\\u1A60-\\\\u1A7C\\\\u1A7F-\\\\u1A89\\\\u1A90-\\\\u1A99\\\\u1AA7\\\\u1AB0-\\\\u1ABD\\\\u1B00-\\\\u1B4B\\\\u1B50-\\\\u1B59\\\\u1B6B-\\\\u1B73\\\\u1B80-\\\\u1BF3\\\\u1C00-\\\\u1C37\\\\u1C40-\\\\u1C49\\\\u1C4D-\\\\u1C7D\\\\u1CD0-\\\\u1CD2\\\\u1CD4-\\\\u1CF6\\\\u1CF8\\\\u1CF9\\\\u1D00-\\\\u1DF5\\\\u1DFC-\\\\u1F15\\\\u1F18-\\\\u1F1D\\\\u1F20-\\\\u1F45\\\\u1F48-\\\\u1F4D\\\\u1F50-\\\\u1F57\\\\u1F59\\\\u1F5B\\\\u1F5D\\\\u1F5F-\\\\u1F7D\\\\u1F80-\\\\u1FB4\\\\u1FB6-\\\\u1FBC\\\\u1FBE\\\\u1FC2-\\\\u1FC4\\\\u1FC6-\\\\u1FCC\\\\u1FD0-\\\\u1FD3\\\\u1FD6-\\\\u1FDB\\\\u1FE0-\\\\u1FEC\\\\u1FF2-\\\\u1FF4\\\\u1FF6-\\\\u1FFC\\\\u200C\\\\u200D\\\\u203F\\\\u2040\\\\u2054\\\\u2071\\\\u207F\\\\u2090-\\\\u209C\\\\u20D0-\\\\u20DC\\\\u20E1\\\\u20E5-\\\\u20F0\\\\u2102\\\\u2107\\\\u210A-\\\\u2113\\\\u2115\\\\u2119-\\\\u211D\\\\u2124\\\\u2126\\\\u2128\\\\u212A-\\\\u212D\\\\u212F-\\\\u2139\\\\u213C-\\\\u213F\\\\u2145-\\\\u2149\\\\u214E\\\\u2160-\\\\u2188\\\\u2C00-\\\\u2C2E\\\\u2C30-\\\\u2C5E\\\\u2C60-\\\\u2CE4\\\\u2CEB-\\\\u2CF3\\\\u2D00-\\\\u2D25\\\\u2D27\\\\u2D2D\\\\u2D30-\\\\u2D67\\\\u2D6F\\\\u2D7F-\\\\u2D96\\\\u2DA0-\\\\u2DA6\\\\u2DA8-\\\\u2DAE\\\\u2DB0-\\\\u2DB6\\\\u2DB8-\\\\u2DBE\\\\u2DC0-\\\\u2DC6\\\\u2DC8-\\\\u2DCE\\\\u2DD0-\\\\u2DD6\\\\u2DD8-\\\\u2DDE\\\\u2DE0-\\\\u2DFF\\\\u2E2F\\\\u3005-\\\\u3007\\\\u3021-\\\\u302F\\\\u3031-\\\\u3035\\\\u3038-\\\\u303C\\\\u3041-\\\\u3096\\\\u3099\\\\u309A\\\\u309D-\\\\u309F\\\\u30A1-\\\\u30FA\\\\u30FC-\\\\u30FF\\\\u3105-\\\\u312D\\\\u3131-\\\\u318E\\\\u31A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\uFB44\\\\uFB46-\\\\uFBB1\\\\uFBD3-\\\\uFD3D\\\\uFD50-\\\\uFD8F\\\\uFD92-\\\\uFDC7\\\\uFDF0-\\\\uFDFB\\\\uFE00-\\\\uFE0F\\\\uFE20-\\\\uFE2D\\\\uFE33\\\\uFE34\\\\uFE4D-\\\\uFE4F\\\\uFE70-\\\\uFE74\\\\uFE76-\\\\uFEFC\\\\uFF10-\\\\uFF19\\\\uFF21-\\\\uFF3A\\\\uFF3F\\\\uFF41-\\\\uFF5A\\\\uFF66-\\\\uFFBE\\\\uFFC2-\\\\uFFC7\\\\uFFCA-\\\\uFFCF\\\\uFFD2-\\\\uFFD7\\\\uFFDA-\\\\uFFDC]'); // Ensure the condition is true, otherwise throw an error.\n// This is only to have a better contract semantic, i.e. another safety net\n// to catch a logic error. The condition shall be fulfilled in normal case.\n// Do NOT use this to enforce a certain condition on any user input.\n\nfunction assert(condition, message) {\n /* istanbul ignore next */\n if (!condition) {\n throw new Error('ASSERT: ' + message);\n }\n}\n\nfunction isDecimalDigit(ch) {\n return ch >= 0x30 && ch <= 0x39; // 0..9\n}\n\nfunction isHexDigit(ch) {\n return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;\n}\n\nfunction isOctalDigit(ch) {\n return '01234567'.indexOf(ch) >= 0;\n} // 7.2 White Space\n\n\nfunction isWhiteSpace(ch) {\n return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0;\n} // 7.3 Line Terminators\n\n\nfunction isLineTerminator(ch) {\n return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;\n} // 7.6 Identifier Names and Identifiers\n\n\nfunction isIdentifierStart(ch) {\n return ch === 0x24 || ch === 0x5F || ch >= 0x41 && ch <= 0x5A || ch >= 0x61 && ch <= 0x7A || ch === 0x5C || ch >= 0x80 && RegexNonAsciiIdentifierStart.test(String.fromCharCode(ch));\n}\n\nfunction isIdentifierPart(ch) {\n return ch === 0x24 || ch === 0x5F || ch >= 0x41 && ch <= 0x5A || ch >= 0x61 && ch <= 0x7A || ch >= 0x30 && ch <= 0x39 || ch === 0x5C || ch >= 0x80 && RegexNonAsciiIdentifierPart.test(String.fromCharCode(ch));\n} // 7.6.1.1 Keywords\n\n\nconst keywords = {\n 'if': 1,\n 'in': 1,\n 'do': 1,\n 'var': 1,\n 'for': 1,\n 'new': 1,\n 'try': 1,\n 'let': 1,\n 'this': 1,\n 'else': 1,\n 'case': 1,\n 'void': 1,\n 'with': 1,\n 'enum': 1,\n 'while': 1,\n 'break': 1,\n 'catch': 1,\n 'throw': 1,\n 'const': 1,\n 'yield': 1,\n 'class': 1,\n 'super': 1,\n 'return': 1,\n 'typeof': 1,\n 'delete': 1,\n 'switch': 1,\n 'export': 1,\n 'import': 1,\n 'public': 1,\n 'static': 1,\n 'default': 1,\n 'finally': 1,\n 'extends': 1,\n 'package': 1,\n 'private': 1,\n 'function': 1,\n 'continue': 1,\n 'debugger': 1,\n 'interface': 1,\n 'protected': 1,\n 'instanceof': 1,\n 'implements': 1\n};\n\nfunction skipComment() {\n while (index < length) {\n const ch = source.charCodeAt(index);\n\n if (isWhiteSpace(ch) || isLineTerminator(ch)) {\n ++index;\n } else {\n break;\n }\n }\n}\n\nfunction scanHexEscape(prefix) {\n var i,\n len,\n ch,\n code = 0;\n len = prefix === 'u' ? 4 : 2;\n\n for (i = 0; i < len; ++i) {\n if (index < length && isHexDigit(source[index])) {\n ch = source[index++];\n code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());\n } else {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n }\n\n return String.fromCharCode(code);\n}\n\nfunction scanUnicodeCodePointEscape() {\n var ch, code, cu1, cu2;\n ch = source[index];\n code = 0; // At least, one hex digit is required.\n\n if (ch === '}') {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n while (index < length) {\n ch = source[index++];\n\n if (!isHexDigit(ch)) {\n break;\n }\n\n code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());\n }\n\n if (code > 0x10FFFF || ch !== '}') {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n } // UTF-16 Encoding\n\n\n if (code <= 0xFFFF) {\n return String.fromCharCode(code);\n }\n\n cu1 = (code - 0x10000 >> 10) + 0xD800;\n cu2 = (code - 0x10000 & 1023) + 0xDC00;\n return String.fromCharCode(cu1, cu2);\n}\n\nfunction getEscapedIdentifier() {\n var ch, id;\n ch = source.charCodeAt(index++);\n id = String.fromCharCode(ch); // '\\u' (U+005C, U+0075) denotes an escaped character.\n\n if (ch === 0x5C) {\n if (source.charCodeAt(index) !== 0x75) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n ++index;\n ch = scanHexEscape('u');\n\n if (!ch || ch === '\\\\' || !isIdentifierStart(ch.charCodeAt(0))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n id = ch;\n }\n\n while (index < length) {\n ch = source.charCodeAt(index);\n\n if (!isIdentifierPart(ch)) {\n break;\n }\n\n ++index;\n id += String.fromCharCode(ch); // '\\u' (U+005C, U+0075) denotes an escaped character.\n\n if (ch === 0x5C) {\n id = id.substr(0, id.length - 1);\n\n if (source.charCodeAt(index) !== 0x75) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n ++index;\n ch = scanHexEscape('u');\n\n if (!ch || ch === '\\\\' || !isIdentifierPart(ch.charCodeAt(0))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n id += ch;\n }\n }\n\n return id;\n}\n\nfunction getIdentifier() {\n var start, ch;\n start = index++;\n\n while (index < length) {\n ch = source.charCodeAt(index);\n\n if (ch === 0x5C) {\n // Blackslash (U+005C) marks Unicode escape sequence.\n index = start;\n return getEscapedIdentifier();\n }\n\n if (isIdentifierPart(ch)) {\n ++index;\n } else {\n break;\n }\n }\n\n return source.slice(start, index);\n}\n\nfunction scanIdentifier() {\n var start, id, type;\n start = index; // Backslash (U+005C) starts an escaped character.\n\n id = source.charCodeAt(index) === 0x5C ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character.\n // Thus, it must be an identifier.\n\n if (id.length === 1) {\n type = TokenIdentifier;\n } else if (keywords.hasOwnProperty(id)) {\n // eslint-disable-line no-prototype-builtins\n type = TokenKeyword;\n } else if (id === 'null') {\n type = TokenNullLiteral;\n } else if (id === 'true' || id === 'false') {\n type = TokenBooleanLiteral;\n } else {\n type = TokenIdentifier;\n }\n\n return {\n type: type,\n value: id,\n start: start,\n end: index\n };\n} // 7.7 Punctuators\n\n\nfunction scanPunctuator() {\n var start = index,\n code = source.charCodeAt(index),\n code2,\n ch1 = source[index],\n ch2,\n ch3,\n ch4;\n\n switch (code) {\n // Check for most common single-character punctuators.\n case 0x2E: // . dot\n\n case 0x28: // ( open bracket\n\n case 0x29: // ) close bracket\n\n case 0x3B: // ; semicolon\n\n case 0x2C: // , comma\n\n case 0x7B: // { open curly brace\n\n case 0x7D: // } close curly brace\n\n case 0x5B: // [\n\n case 0x5D: // ]\n\n case 0x3A: // :\n\n case 0x3F: // ?\n\n case 0x7E:\n // ~\n ++index;\n return {\n type: TokenPunctuator,\n value: String.fromCharCode(code),\n start: start,\n end: index\n };\n\n default:\n code2 = source.charCodeAt(index + 1); // '=' (U+003D) marks an assignment or comparison operator.\n\n if (code2 === 0x3D) {\n switch (code) {\n case 0x2B: // +\n\n case 0x2D: // -\n\n case 0x2F: // /\n\n case 0x3C: // <\n\n case 0x3E: // >\n\n case 0x5E: // ^\n\n case 0x7C: // |\n\n case 0x25: // %\n\n case 0x26: // &\n\n case 0x2A:\n // *\n index += 2;\n return {\n type: TokenPunctuator,\n value: String.fromCharCode(code) + String.fromCharCode(code2),\n start: start,\n end: index\n };\n\n case 0x21: // !\n\n case 0x3D:\n // =\n index += 2; // !== and ===\n\n if (source.charCodeAt(index) === 0x3D) {\n ++index;\n }\n\n return {\n type: TokenPunctuator,\n value: source.slice(start, index),\n start: start,\n end: index\n };\n }\n }\n\n } // 4-character punctuator: >>>=\n\n\n ch4 = source.substr(index, 4);\n\n if (ch4 === '>>>=') {\n index += 4;\n return {\n type: TokenPunctuator,\n value: ch4,\n start: start,\n end: index\n };\n } // 3-character punctuators: === !== >>> <<= >>=\n\n\n ch3 = ch4.substr(0, 3);\n\n if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {\n index += 3;\n return {\n type: TokenPunctuator,\n value: ch3,\n start: start,\n end: index\n };\n } // Other 2-character punctuators: ++ -- << >> && ||\n\n\n ch2 = ch3.substr(0, 2);\n\n if (ch1 === ch2[1] && '+-<>&|'.indexOf(ch1) >= 0 || ch2 === '=>') {\n index += 2;\n return {\n type: TokenPunctuator,\n value: ch2,\n start: start,\n end: index\n };\n }\n\n if (ch2 === '//') {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n } // 1-character punctuators: < > = ! + - * % & | ^ /\n\n\n if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {\n ++index;\n return {\n type: TokenPunctuator,\n value: ch1,\n start: start,\n end: index\n };\n }\n\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n} // 7.8.3 Numeric Literals\n\n\nfunction scanHexLiteral(start) {\n let number = '';\n\n while (index < length) {\n if (!isHexDigit(source[index])) {\n break;\n }\n\n number += source[index++];\n }\n\n if (number.length === 0) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n if (isIdentifierStart(source.charCodeAt(index))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n return {\n type: TokenNumericLiteral,\n value: parseInt('0x' + number, 16),\n start: start,\n end: index\n };\n}\n\nfunction scanOctalLiteral(start) {\n let number = '0' + source[index++];\n\n while (index < length) {\n if (!isOctalDigit(source[index])) {\n break;\n }\n\n number += source[index++];\n }\n\n if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n return {\n type: TokenNumericLiteral,\n value: parseInt(number, 8),\n octal: true,\n start: start,\n end: index\n };\n}\n\nfunction scanNumericLiteral() {\n var number, start, ch;\n ch = source[index];\n assert(isDecimalDigit(ch.charCodeAt(0)) || ch === '.', 'Numeric literal must start with a decimal digit or a decimal point');\n start = index;\n number = '';\n\n if (ch !== '.') {\n number = source[index++];\n ch = source[index]; // Hex number starts with '0x'.\n // Octal number starts with '0'.\n\n if (number === '0') {\n if (ch === 'x' || ch === 'X') {\n ++index;\n return scanHexLiteral(start);\n }\n\n if (isOctalDigit(ch)) {\n return scanOctalLiteral(start);\n } // decimal number starts with '0' such as '09' is illegal.\n\n\n if (ch && isDecimalDigit(ch.charCodeAt(0))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n }\n\n while (isDecimalDigit(source.charCodeAt(index))) {\n number += source[index++];\n }\n\n ch = source[index];\n }\n\n if (ch === '.') {\n number += source[index++];\n\n while (isDecimalDigit(source.charCodeAt(index))) {\n number += source[index++];\n }\n\n ch = source[index];\n }\n\n if (ch === 'e' || ch === 'E') {\n number += source[index++];\n ch = source[index];\n\n if (ch === '+' || ch === '-') {\n number += source[index++];\n }\n\n if (isDecimalDigit(source.charCodeAt(index))) {\n while (isDecimalDigit(source.charCodeAt(index))) {\n number += source[index++];\n }\n } else {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n }\n\n if (isIdentifierStart(source.charCodeAt(index))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n return {\n type: TokenNumericLiteral,\n value: parseFloat(number),\n start: start,\n end: index\n };\n} // 7.8.4 String Literals\n\n\nfunction scanStringLiteral() {\n var str = '',\n quote,\n start,\n ch,\n code,\n octal = false;\n quote = source[index];\n assert(quote === '\\'' || quote === '\"', 'String literal must starts with a quote');\n start = index;\n ++index;\n\n while (index < length) {\n ch = source[index++];\n\n if (ch === quote) {\n quote = '';\n break;\n } else if (ch === '\\\\') {\n ch = source[index++];\n\n if (!ch || !isLineTerminator(ch.charCodeAt(0))) {\n switch (ch) {\n case 'u':\n case 'x':\n if (source[index] === '{') {\n ++index;\n str += scanUnicodeCodePointEscape();\n } else {\n str += scanHexEscape(ch);\n }\n\n break;\n\n case 'n':\n str += '\\n';\n break;\n\n case 'r':\n str += '\\r';\n break;\n\n case 't':\n str += '\\t';\n break;\n\n case 'b':\n str += '\\b';\n break;\n\n case 'f':\n str += '\\f';\n break;\n\n case 'v':\n str += '\\x0B';\n break;\n\n default:\n if (isOctalDigit(ch)) {\n code = '01234567'.indexOf(ch); // \\0 is not octal escape sequence\n\n if (code !== 0) {\n octal = true;\n }\n\n if (index < length && isOctalDigit(source[index])) {\n octal = true;\n code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts\n // with 0, 1, 2, 3\n\n if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) {\n code = code * 8 + '01234567'.indexOf(source[index++]);\n }\n }\n\n str += String.fromCharCode(code);\n } else {\n str += ch;\n }\n\n break;\n }\n } else {\n if (ch === '\\r' && source[index] === '\\n') {\n ++index;\n }\n }\n } else if (isLineTerminator(ch.charCodeAt(0))) {\n break;\n } else {\n str += ch;\n }\n }\n\n if (quote !== '') {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n return {\n type: TokenStringLiteral,\n value: str,\n octal: octal,\n start: start,\n end: index\n };\n}\n\nfunction testRegExp(pattern, flags) {\n let tmp = pattern;\n\n if (flags.indexOf('u') >= 0) {\n // Replace each astral symbol and every Unicode code point\n // escape sequence with a single ASCII symbol to avoid throwing on\n // regular expressions that are only valid in combination with the\n // `/u` flag.\n // Note: replacing with the ASCII symbol `x` might cause false\n // negatives in unlikely scenarios. For example, `[\\u{61}-b]` is a\n // perfectly valid pattern that is equivalent to `[a-b]`, but it\n // would be replaced by `[x-b]` which throws an error.\n tmp = tmp.replace(/\\\\u\\{([0-9a-fA-F]+)\\}/g, ($0, $1) => {\n if (parseInt($1, 16) <= 0x10FFFF) {\n return 'x';\n }\n\n throwError({}, MessageInvalidRegExp);\n }).replace(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g, 'x');\n } // First, detect invalid regular expressions.\n\n\n try {\n new RegExp(tmp);\n } catch (e) {\n throwError({}, MessageInvalidRegExp);\n } // Return a regular expression object for this pattern-flag pair, or\n // `null` in case the current environment doesn't support the flags it\n // uses.\n\n\n try {\n return new RegExp(pattern, flags);\n } catch (exception) {\n return null;\n }\n}\n\nfunction scanRegExpBody() {\n var ch, str, classMarker, terminated, body;\n ch = source[index];\n assert(ch === '/', 'Regular expression literal must start with a slash');\n str = source[index++];\n classMarker = false;\n terminated = false;\n\n while (index < length) {\n ch = source[index++];\n str += ch;\n\n if (ch === '\\\\') {\n ch = source[index++]; // ECMA-262 7.8.5\n\n if (isLineTerminator(ch.charCodeAt(0))) {\n throwError({}, MessageUnterminatedRegExp);\n }\n\n str += ch;\n } else if (isLineTerminator(ch.charCodeAt(0))) {\n throwError({}, MessageUnterminatedRegExp);\n } else if (classMarker) {\n if (ch === ']') {\n classMarker = false;\n }\n } else {\n if (ch === '/') {\n terminated = true;\n break;\n } else if (ch === '[') {\n classMarker = true;\n }\n }\n }\n\n if (!terminated) {\n throwError({}, MessageUnterminatedRegExp);\n } // Exclude leading and trailing slash.\n\n\n body = str.substr(1, str.length - 2);\n return {\n value: body,\n literal: str\n };\n}\n\nfunction scanRegExpFlags() {\n var ch, str, flags;\n str = '';\n flags = '';\n\n while (index < length) {\n ch = source[index];\n\n if (!isIdentifierPart(ch.charCodeAt(0))) {\n break;\n }\n\n ++index;\n\n if (ch === '\\\\' && index < length) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n } else {\n flags += ch;\n str += ch;\n }\n }\n\n if (flags.search(/[^gimuy]/g) >= 0) {\n throwError({}, MessageInvalidRegExp, flags);\n }\n\n return {\n value: flags,\n literal: str\n };\n}\n\nfunction scanRegExp() {\n var start, body, flags, value;\n lookahead = null;\n skipComment();\n start = index;\n body = scanRegExpBody();\n flags = scanRegExpFlags();\n value = testRegExp(body.value, flags.value);\n return {\n literal: body.literal + flags.literal,\n value: value,\n regex: {\n pattern: body.value,\n flags: flags.value\n },\n start: start,\n end: index\n };\n}\n\nfunction isIdentifierName(token) {\n return token.type === TokenIdentifier || token.type === TokenKeyword || token.type === TokenBooleanLiteral || token.type === TokenNullLiteral;\n}\n\nfunction advance() {\n skipComment();\n\n if (index >= length) {\n return {\n type: TokenEOF,\n start: index,\n end: index\n };\n }\n\n const ch = source.charCodeAt(index);\n\n if (isIdentifierStart(ch)) {\n return scanIdentifier();\n } // Very common: ( and ) and ;\n\n\n if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {\n return scanPunctuator();\n } // String literal starts with single quote (U+0027) or double quote (U+0022).\n\n\n if (ch === 0x27 || ch === 0x22) {\n return scanStringLiteral();\n } // Dot (.) U+002E can also start a floating-point number, hence the need\n // to check the next character.\n\n\n if (ch === 0x2E) {\n if (isDecimalDigit(source.charCodeAt(index + 1))) {\n return scanNumericLiteral();\n }\n\n return scanPunctuator();\n }\n\n if (isDecimalDigit(ch)) {\n return scanNumericLiteral();\n }\n\n return scanPunctuator();\n}\n\nfunction lex() {\n const token = lookahead;\n index = token.end;\n lookahead = advance();\n index = token.end;\n return token;\n}\n\nfunction peek() {\n const pos = index;\n lookahead = advance();\n index = pos;\n}\n\nfunction finishArrayExpression(elements) {\n const node = new ASTNode(SyntaxArrayExpression);\n node.elements = elements;\n return node;\n}\n\nfunction finishBinaryExpression(operator, left, right) {\n const node = new ASTNode(operator === '||' || operator === '&&' ? SyntaxLogicalExpression : SyntaxBinaryExpression);\n node.operator = operator;\n node.left = left;\n node.right = right;\n return node;\n}\n\nfunction finishCallExpression(callee, args) {\n const node = new ASTNode(SyntaxCallExpression);\n node.callee = callee;\n node.arguments = args;\n return node;\n}\n\nfunction finishConditionalExpression(test, consequent, alternate) {\n const node = new ASTNode(SyntaxConditionalExpression);\n node.test = test;\n node.consequent = consequent;\n node.alternate = alternate;\n return node;\n}\n\nfunction finishIdentifier(name) {\n const node = new ASTNode(SyntaxIdentifier);\n node.name = name;\n return node;\n}\n\nfunction finishLiteral(token) {\n const node = new ASTNode(SyntaxLiteral);\n node.value = token.value;\n node.raw = source.slice(token.start, token.end);\n\n if (token.regex) {\n if (node.raw === '//') {\n node.raw = '/(?:)/';\n }\n\n node.regex = token.regex;\n }\n\n return node;\n}\n\nfunction finishMemberExpression(accessor, object, property) {\n const node = new ASTNode(SyntaxMemberExpression);\n node.computed = accessor === '[';\n node.object = object;\n node.property = property;\n if (!node.computed) property.member = true;\n return node;\n}\n\nfunction finishObjectExpression(properties) {\n const node = new ASTNode(SyntaxObjectExpression);\n node.properties = properties;\n return node;\n}\n\nfunction finishProperty(kind, key, value) {\n const node = new ASTNode(SyntaxProperty);\n node.key = key;\n node.value = value;\n node.kind = kind;\n return node;\n}\n\nfunction finishUnaryExpression(operator, argument) {\n const node = new ASTNode(SyntaxUnaryExpression);\n node.operator = operator;\n node.argument = argument;\n node.prefix = true;\n return node;\n} // Throw an exception\n\n\nfunction throwError(token, messageFormat) {\n var error,\n args = Array.prototype.slice.call(arguments, 2),\n msg = messageFormat.replace(/%(\\d)/g, (whole, index) => {\n assert(index < args.length, 'Message reference must be in range');\n return args[index];\n });\n error = new Error(msg);\n error.index = index;\n error.description = msg;\n throw error;\n} // Throw an exception because of the token.\n\n\nfunction throwUnexpected(token) {\n if (token.type === TokenEOF) {\n throwError(token, MessageUnexpectedEOS);\n }\n\n if (token.type === TokenNumericLiteral) {\n throwError(token, MessageUnexpectedNumber);\n }\n\n if (token.type === TokenStringLiteral) {\n throwError(token, MessageUnexpectedString);\n }\n\n if (token.type === TokenIdentifier) {\n throwError(token, MessageUnexpectedIdentifier);\n }\n\n if (token.type === TokenKeyword) {\n throwError(token, MessageUnexpectedReserved);\n } // BooleanLiteral, NullLiteral, or Punctuator.\n\n\n throwError(token, MessageUnexpectedToken, token.value);\n} // Expect the next token to match the specified punctuator.\n// If not, an exception will be thrown.\n\n\nfunction expect(value) {\n const token = lex();\n\n if (token.type !== TokenPunctuator || token.value !== value) {\n throwUnexpected(token);\n }\n} // Return true if the next token matches the specified punctuator.\n\n\nfunction match(value) {\n return lookahead.type === TokenPunctuator && lookahead.value === value;\n} // Return true if the next token matches the specified keyword\n\n\nfunction matchKeyword(keyword) {\n return lookahead.type === TokenKeyword && lookahead.value === keyword;\n} // 11.1.4 Array Initialiser\n\n\nfunction parseArrayInitialiser() {\n const elements = [];\n index = lookahead.start;\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else {\n elements.push(parseConditionalExpression());\n\n if (!match(']')) {\n expect(',');\n }\n }\n }\n\n lex();\n return finishArrayExpression(elements);\n} // 11.1.5 Object Initialiser\n\n\nfunction parseObjectPropertyKey() {\n index = lookahead.start;\n const token = lex(); // Note: This function is called only from parseObjectProperty(), where\n // EOF and Punctuator tokens are already filtered out.\n\n if (token.type === TokenStringLiteral || token.type === TokenNumericLiteral) {\n if (token.octal) {\n throwError(token, MessageStrictOctalLiteral);\n }\n\n return finishLiteral(token);\n }\n\n return finishIdentifier(token.value);\n}\n\nfunction parseObjectProperty() {\n var token, key, id, value;\n index = lookahead.start;\n token = lookahead;\n\n if (token.type === TokenIdentifier) {\n id = parseObjectPropertyKey();\n expect(':');\n value = parseConditionalExpression();\n return finishProperty('init', id, value);\n }\n\n if (token.type === TokenEOF || token.type === TokenPunctuator) {\n throwUnexpected(token);\n } else {\n key = parseObjectPropertyKey();\n expect(':');\n value = parseConditionalExpression();\n return finishProperty('init', key, value);\n }\n}\n\nfunction parseObjectInitialiser() {\n var properties = [],\n property,\n name,\n key,\n map = {},\n toString = String;\n index = lookahead.start;\n expect('{');\n\n while (!match('}')) {\n property = parseObjectProperty();\n\n if (property.key.type === SyntaxIdentifier) {\n name = property.key.name;\n } else {\n name = toString(property.key.value);\n }\n\n key = '$' + name;\n\n if (Object.prototype.hasOwnProperty.call(map, key)) {\n throwError({}, MessageStrictDuplicateProperty);\n } else {\n map[key] = true;\n }\n\n properties.push(property);\n\n if (!match('}')) {\n expect(',');\n }\n }\n\n expect('}');\n return finishObjectExpression(properties);\n} // 11.1.6 The Grouping Operator\n\n\nfunction parseGroupExpression() {\n expect('(');\n const expr = parseExpression();\n expect(')');\n return expr;\n} // 11.1 Primary Expressions\n\n\nconst legalKeywords = {\n 'if': 1\n};\n\nfunction parsePrimaryExpression() {\n var type, token, expr;\n\n if (match('(')) {\n return parseGroupExpression();\n }\n\n if (match('[')) {\n return parseArrayInitialiser();\n }\n\n if (match('{')) {\n return parseObjectInitialiser();\n }\n\n type = lookahead.type;\n index = lookahead.start;\n\n if (type === TokenIdentifier || legalKeywords[lookahead.value]) {\n expr = finishIdentifier(lex().value);\n } else if (type === TokenStringLiteral || type === TokenNumericLiteral) {\n if (lookahead.octal) {\n throwError(lookahead, MessageStrictOctalLiteral);\n }\n\n expr = finishLiteral(lex());\n } else if (type === TokenKeyword) {\n throw new Error(DISABLED);\n } else if (type === TokenBooleanLiteral) {\n token = lex();\n token.value = token.value === 'true';\n expr = finishLiteral(token);\n } else if (type === TokenNullLiteral) {\n token = lex();\n token.value = null;\n expr = finishLiteral(token);\n } else if (match('/') || match('/=')) {\n expr = finishLiteral(scanRegExp());\n peek();\n } else {\n throwUnexpected(lex());\n }\n\n return expr;\n} // 11.2 Left-Hand-Side Expressions\n\n\nfunction parseArguments() {\n const args = [];\n expect('(');\n\n if (!match(')')) {\n while (index < length) {\n args.push(parseConditionalExpression());\n\n if (match(')')) {\n break;\n }\n\n expect(',');\n }\n }\n\n expect(')');\n return args;\n}\n\nfunction parseNonComputedProperty() {\n index = lookahead.start;\n const token = lex();\n\n if (!isIdentifierName(token)) {\n throwUnexpected(token);\n }\n\n return finishIdentifier(token.value);\n}\n\nfunction parseNonComputedMember() {\n expect('.');\n return parseNonComputedProperty();\n}\n\nfunction parseComputedMember() {\n expect('[');\n const expr = parseExpression();\n expect(']');\n return expr;\n}\n\nfunction parseLeftHandSideExpressionAllowCall() {\n var expr, args, property;\n expr = parsePrimaryExpression();\n\n for (;;) {\n if (match('.')) {\n property = parseNonComputedMember();\n expr = finishMemberExpression('.', expr, property);\n } else if (match('(')) {\n args = parseArguments();\n expr = finishCallExpression(expr, args);\n } else if (match('[')) {\n property = parseComputedMember();\n expr = finishMemberExpression('[', expr, property);\n } else {\n break;\n }\n }\n\n return expr;\n} // 11.3 Postfix Expressions\n\n\nfunction parsePostfixExpression() {\n const expr = parseLeftHandSideExpressionAllowCall();\n\n if (lookahead.type === TokenPunctuator) {\n if (match('++') || match('--')) {\n throw new Error(DISABLED);\n }\n }\n\n return expr;\n} // 11.4 Unary Operators\n\n\nfunction parseUnaryExpression() {\n var token, expr;\n\n if (lookahead.type !== TokenPunctuator && lookahead.type !== TokenKeyword) {\n expr = parsePostfixExpression();\n } else if (match('++') || match('--')) {\n throw new Error(DISABLED);\n } else if (match('+') || match('-') || match('~') || match('!')) {\n token = lex();\n expr = parseUnaryExpression();\n expr = finishUnaryExpression(token.value, expr);\n } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {\n throw new Error(DISABLED);\n } else {\n expr = parsePostfixExpression();\n }\n\n return expr;\n}\n\nfunction binaryPrecedence(token) {\n let prec = 0;\n\n if (token.type !== TokenPunctuator && token.type !== TokenKeyword) {\n return 0;\n }\n\n switch (token.value) {\n case '||':\n prec = 1;\n break;\n\n case '&&':\n prec = 2;\n break;\n\n case '|':\n prec = 3;\n break;\n\n case '^':\n prec = 4;\n break;\n\n case '&':\n prec = 5;\n break;\n\n case '==':\n case '!=':\n case '===':\n case '!==':\n prec = 6;\n break;\n\n case '<':\n case '>':\n case '<=':\n case '>=':\n case 'instanceof':\n case 'in':\n prec = 7;\n break;\n\n case '<<':\n case '>>':\n case '>>>':\n prec = 8;\n break;\n\n case '+':\n case '-':\n prec = 9;\n break;\n\n case '*':\n case '/':\n case '%':\n prec = 11;\n break;\n }\n\n return prec;\n} // 11.5 Multiplicative Operators\n// 11.6 Additive Operators\n// 11.7 Bitwise Shift Operators\n// 11.8 Relational Operators\n// 11.9 Equality Operators\n// 11.10 Binary Bitwise Operators\n// 11.11 Binary Logical Operators\n\n\nfunction parseBinaryExpression() {\n var marker, markers, expr, token, prec, stack, right, operator, left, i;\n marker = lookahead;\n left = parseUnaryExpression();\n token = lookahead;\n prec = binaryPrecedence(token);\n\n if (prec === 0) {\n return left;\n }\n\n token.prec = prec;\n lex();\n markers = [marker, lookahead];\n right = parseUnaryExpression();\n stack = [left, token, right];\n\n while ((prec = binaryPrecedence(lookahead)) > 0) {\n // Reduce: make a binary expression from the three topmost entries.\n while (stack.length > 2 && prec <= stack[stack.length - 2].prec) {\n right = stack.pop();\n operator = stack.pop().value;\n left = stack.pop();\n markers.pop();\n expr = finishBinaryExpression(operator, left, right);\n stack.push(expr);\n } // Shift.\n\n\n token = lex();\n token.prec = prec;\n stack.push(token);\n markers.push(lookahead);\n expr = parseUnaryExpression();\n stack.push(expr);\n } // Final reduce to clean-up the stack.\n\n\n i = stack.length - 1;\n expr = stack[i];\n markers.pop();\n\n while (i > 1) {\n markers.pop();\n expr = finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);\n i -= 2;\n }\n\n return expr;\n} // 11.12 Conditional Operator\n\n\nfunction parseConditionalExpression() {\n var expr, consequent, alternate;\n expr = parseBinaryExpression();\n\n if (match('?')) {\n lex();\n consequent = parseConditionalExpression();\n expect(':');\n alternate = parseConditionalExpression();\n expr = finishConditionalExpression(expr, consequent, alternate);\n }\n\n return expr;\n} // 11.14 Comma Operator\n\n\nfunction parseExpression() {\n const expr = parseConditionalExpression();\n\n if (match(',')) {\n throw new Error(DISABLED); // no sequence expressions\n }\n\n return expr;\n}\n\nfunction parser (code) {\n source = code;\n index = 0;\n length = source.length;\n lookahead = null;\n peek();\n const expr = parseExpression();\n\n if (lookahead.type !== TokenEOF) {\n throw new Error('Unexpect token after expression.');\n }\n\n return expr;\n}\n\nvar Constants = {\n NaN: 'NaN',\n E: 'Math.E',\n LN2: 'Math.LN2',\n LN10: 'Math.LN10',\n LOG2E: 'Math.LOG2E',\n LOG10E: 'Math.LOG10E',\n PI: 'Math.PI',\n SQRT1_2: 'Math.SQRT1_2',\n SQRT2: 'Math.SQRT2',\n MIN_VALUE: 'Number.MIN_VALUE',\n MAX_VALUE: 'Number.MAX_VALUE'\n};\n\nfunction Functions (codegen) {\n function fncall(name, args, cast, type) {\n let obj = codegen(args[0]);\n\n if (cast) {\n obj = cast + '(' + obj + ')';\n if (cast.lastIndexOf('new ', 0) === 0) obj = '(' + obj + ')';\n }\n\n return obj + '.' + name + (type < 0 ? '' : type === 0 ? '()' : '(' + args.slice(1).map(codegen).join(',') + ')');\n }\n\n function fn(name, cast, type) {\n return args => fncall(name, args, cast, type);\n }\n\n const DATE = 'new Date',\n STRING = 'String',\n REGEXP = 'RegExp';\n return {\n // MATH functions\n isNaN: 'Number.isNaN',\n isFinite: 'Number.isFinite',\n abs: 'Math.abs',\n acos: 'Math.acos',\n asin: 'Math.asin',\n atan: 'Math.atan',\n atan2: 'Math.atan2',\n ceil: 'Math.ceil',\n cos: 'Math.cos',\n exp: 'Math.exp',\n floor: 'Math.floor',\n log: 'Math.log',\n max: 'Math.max',\n min: 'Math.min',\n pow: 'Math.pow',\n random: 'Math.random',\n round: 'Math.round',\n sin: 'Math.sin',\n sqrt: 'Math.sqrt',\n tan: 'Math.tan',\n clamp: function (args) {\n if (args.length < 3) error('Missing arguments to clamp function.');\n if (args.length > 3) error('Too many arguments to clamp function.');\n const a = args.map(codegen);\n return 'Math.max(' + a[1] + ', Math.min(' + a[2] + ',' + a[0] + '))';\n },\n // DATE functions\n now: 'Date.now',\n utc: 'Date.UTC',\n datetime: DATE,\n date: fn('getDate', DATE, 0),\n day: fn('getDay', DATE, 0),\n year: fn('getFullYear', DATE, 0),\n month: fn('getMonth', DATE, 0),\n hours: fn('getHours', DATE, 0),\n minutes: fn('getMinutes', DATE, 0),\n seconds: fn('getSeconds', DATE, 0),\n milliseconds: fn('getMilliseconds', DATE, 0),\n time: fn('getTime', DATE, 0),\n timezoneoffset: fn('getTimezoneOffset', DATE, 0),\n utcdate: fn('getUTCDate', DATE, 0),\n utcday: fn('getUTCDay', DATE, 0),\n utcyear: fn('getUTCFullYear', DATE, 0),\n utcmonth: fn('getUTCMonth', DATE, 0),\n utchours: fn('getUTCHours', DATE, 0),\n utcminutes: fn('getUTCMinutes', DATE, 0),\n utcseconds: fn('getUTCSeconds', DATE, 0),\n utcmilliseconds: fn('getUTCMilliseconds', DATE, 0),\n // sequence functions\n length: fn('length', null, -1),\n // STRING functions\n parseFloat: 'parseFloat',\n parseInt: 'parseInt',\n upper: fn('toUpperCase', STRING, 0),\n lower: fn('toLowerCase', STRING, 0),\n substring: fn('substring', STRING),\n split: fn('split', STRING),\n trim: fn('trim', STRING, 0),\n // REGEXP functions\n regexp: REGEXP,\n test: fn('test', REGEXP),\n // Control Flow functions\n if: function (args) {\n if (args.length < 3) error('Missing arguments to if function.');\n if (args.length > 3) error('Too many arguments to if function.');\n const a = args.map(codegen);\n return '(' + a[0] + '?' + a[1] + ':' + a[2] + ')';\n }\n };\n}\n\nfunction stripQuotes(s) {\n const n = s && s.length - 1;\n return n && (s[0] === '\"' && s[n] === '\"' || s[0] === '\\'' && s[n] === '\\'') ? s.slice(1, -1) : s;\n}\n\nfunction codegen (opt) {\n opt = opt || {};\n const allowed = opt.allowed ? toSet(opt.allowed) : {},\n forbidden = opt.forbidden ? toSet(opt.forbidden) : {},\n constants = opt.constants || Constants,\n functions = (opt.functions || Functions)(visit),\n globalvar = opt.globalvar,\n fieldvar = opt.fieldvar,\n outputGlobal = isFunction(globalvar) ? globalvar : id => `${globalvar}[\"${id}\"]`;\n let globals = {},\n fields = {},\n memberDepth = 0;\n\n function visit(ast) {\n if (isString(ast)) return ast;\n const generator = Generators[ast.type];\n if (generator == null) error('Unsupported type: ' + ast.type);\n return generator(ast);\n }\n\n const Generators = {\n Literal: n => n.raw,\n Identifier: n => {\n const id = n.name;\n\n if (memberDepth > 0) {\n return id;\n } else if (hasOwnProperty(forbidden, id)) {\n return error('Illegal identifier: ' + id);\n } else if (hasOwnProperty(constants, id)) {\n return constants[id];\n } else if (hasOwnProperty(allowed, id)) {\n return id;\n } else {\n globals[id] = 1;\n return outputGlobal(id);\n }\n },\n MemberExpression: n => {\n const d = !n.computed,\n o = visit(n.object);\n if (d) memberDepth += 1;\n const p = visit(n.property);\n\n if (o === fieldvar) {\n // strip quotes to sanitize field name (#1653)\n fields[stripQuotes(p)] = 1;\n }\n\n if (d) memberDepth -= 1;\n return o + (d ? '.' + p : '[' + p + ']');\n },\n CallExpression: n => {\n if (n.callee.type !== 'Identifier') {\n error('Illegal callee type: ' + n.callee.type);\n }\n\n const callee = n.callee.name,\n args = n.arguments,\n fn = hasOwnProperty(functions, callee) && functions[callee];\n if (!fn) error('Unrecognized function: ' + callee);\n return isFunction(fn) ? fn(args) : fn + '(' + args.map(visit).join(',') + ')';\n },\n ArrayExpression: n => '[' + n.elements.map(visit).join(',') + ']',\n BinaryExpression: n => '(' + visit(n.left) + ' ' + n.operator + ' ' + visit(n.right) + ')',\n UnaryExpression: n => '(' + n.operator + visit(n.argument) + ')',\n ConditionalExpression: n => '(' + visit(n.test) + '?' + visit(n.consequent) + ':' + visit(n.alternate) + ')',\n LogicalExpression: n => '(' + visit(n.left) + n.operator + visit(n.right) + ')',\n ObjectExpression: n => '{' + n.properties.map(visit).join(',') + '}',\n Property: n => {\n memberDepth += 1;\n const k = visit(n.key);\n memberDepth -= 1;\n return k + ':' + visit(n.value);\n }\n };\n\n function codegen(ast) {\n const result = {\n code: visit(ast),\n globals: Object.keys(globals),\n fields: Object.keys(fields)\n };\n globals = {};\n fields = {};\n return result;\n }\n\n codegen.functions = functions;\n codegen.constants = constants;\n return codegen;\n}\n\nexport { ASTNode, ArrayExpression, BinaryExpression, CallExpression, ConditionalExpression, Identifier, Literal, LogicalExpression, MemberExpression, ObjectExpression, Property, RawCode, UnaryExpression, codegen as codegenExpression, Constants as constants, Functions as functions, parser as parseExpression };\n","// https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423\nexport class Adder {\n constructor() {\n this._partials = new Float64Array(32);\n this._n = 0;\n }\n add(x) {\n const p = this._partials;\n let i = 0;\n for (let j = 0; j < this._n && j < 32; j++) {\n const y = p[j],\n hi = x + y,\n lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);\n if (lo) p[i++] = lo;\n x = hi;\n }\n p[i] = x;\n this._n = i + 1;\n return this;\n }\n valueOf() {\n const p = this._partials;\n let n = this._n, x, y, lo, hi = 0;\n if (n > 0) {\n hi = p[--n];\n while (n > 0) {\n x = hi;\n y = p[--n];\n hi = x + y;\n lo = y - (hi - x);\n if (lo) break;\n }\n if (n > 0 && ((lo < 0 && p[n - 1] < 0) || (lo > 0 && p[n - 1] > 0))) {\n y = lo * 2;\n x = hi + y;\n if (y == x - hi) hi = x;\n }\n }\n return hi;\n }\n}\n\nexport function fsum(values, valueof) {\n const adder = new Adder();\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n adder.add(value);\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n adder.add(value);\n }\n }\n }\n return +adder;\n}\n\nexport function fcumsum(values, valueof) {\n const adder = new Adder();\n let index = -1;\n return Float64Array.from(values, valueof === undefined\n ? v => adder.add(+v || 0)\n : v => adder.add(+valueof(v, ++index, values) || 0)\n );\n}\n","export var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var quarterPi = pi / 4;\nexport var tau = pi * 2;\n\nexport var degrees = 180 / pi;\nexport var radians = pi / 180;\n\nexport var abs = Math.abs;\nexport var atan = Math.atan;\nexport var atan2 = Math.atan2;\nexport var cos = Math.cos;\nexport var ceil = Math.ceil;\nexport var exp = Math.exp;\nexport var floor = Math.floor;\nexport var hypot = Math.hypot;\nexport var log = Math.log;\nexport var pow = Math.pow;\nexport var sin = Math.sin;\nexport var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };\nexport var sqrt = Math.sqrt;\nexport var tan = Math.tan;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);\n}\n\nexport function haversin(x) {\n return (x = sin(x / 2)) * x;\n}\n","export default function noop() {}\n","function streamGeometry(geometry, stream) {\n if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {\n streamGeometryType[geometry.type](geometry, stream);\n }\n}\n\nvar streamObjectType = {\n Feature: function(object, stream) {\n streamGeometry(object.geometry, stream);\n },\n FeatureCollection: function(object, stream) {\n var features = object.features, i = -1, n = features.length;\n while (++i < n) streamGeometry(features[i].geometry, stream);\n }\n};\n\nvar streamGeometryType = {\n Sphere: function(object, stream) {\n stream.sphere();\n },\n Point: function(object, stream) {\n object = object.coordinates;\n stream.point(object[0], object[1], object[2]);\n },\n MultiPoint: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);\n },\n LineString: function(object, stream) {\n streamLine(object.coordinates, stream, 0);\n },\n MultiLineString: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamLine(coordinates[i], stream, 0);\n },\n Polygon: function(object, stream) {\n streamPolygon(object.coordinates, stream);\n },\n MultiPolygon: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamPolygon(coordinates[i], stream);\n },\n GeometryCollection: function(object, stream) {\n var geometries = object.geometries, i = -1, n = geometries.length;\n while (++i < n) streamGeometry(geometries[i], stream);\n }\n};\n\nfunction streamLine(coordinates, stream, closed) {\n var i = -1, n = coordinates.length - closed, coordinate;\n stream.lineStart();\n while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);\n stream.lineEnd();\n}\n\nfunction streamPolygon(coordinates, stream) {\n var i = -1, n = coordinates.length;\n stream.polygonStart();\n while (++i < n) streamLine(coordinates[i], stream, 1);\n stream.polygonEnd();\n}\n\nexport default function(object, stream) {\n if (object && streamObjectType.hasOwnProperty(object.type)) {\n streamObjectType[object.type](object, stream);\n } else {\n streamGeometry(object, stream);\n }\n}\n","import {Adder} from \"d3-array\";\nimport {atan2, cos, quarterPi, radians, sin, tau} from \"./math.js\";\nimport noop from \"./noop.js\";\nimport stream from \"./stream.js\";\n\nexport var areaRingSum = new Adder();\n\n// hello?\n\nvar areaSum = new Adder(),\n lambda00,\n phi00,\n lambda0,\n cosPhi0,\n sinPhi0;\n\nexport var areaStream = {\n point: noop,\n lineStart: noop,\n lineEnd: noop,\n polygonStart: function() {\n areaRingSum = new Adder();\n areaStream.lineStart = areaRingStart;\n areaStream.lineEnd = areaRingEnd;\n },\n polygonEnd: function() {\n var areaRing = +areaRingSum;\n areaSum.add(areaRing < 0 ? tau + areaRing : areaRing);\n this.lineStart = this.lineEnd = this.point = noop;\n },\n sphere: function() {\n areaSum.add(tau);\n }\n};\n\nfunction areaRingStart() {\n areaStream.point = areaPointFirst;\n}\n\nfunction areaRingEnd() {\n areaPoint(lambda00, phi00);\n}\n\nfunction areaPointFirst(lambda, phi) {\n areaStream.point = areaPoint;\n lambda00 = lambda, phi00 = phi;\n lambda *= radians, phi *= radians;\n lambda0 = lambda, cosPhi0 = cos(phi = phi / 2 + quarterPi), sinPhi0 = sin(phi);\n}\n\nfunction areaPoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n phi = phi / 2 + quarterPi; // half the angular distance from south pole\n\n // Spherical excess E for a spherical triangle with vertices: south pole,\n // previous point, current point. Uses a formula derived from Cagnoli’s\n // theorem. See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).\n var dLambda = lambda - lambda0,\n sdLambda = dLambda >= 0 ? 1 : -1,\n adLambda = sdLambda * dLambda,\n cosPhi = cos(phi),\n sinPhi = sin(phi),\n k = sinPhi0 * sinPhi,\n u = cosPhi0 * cosPhi + k * cos(adLambda),\n v = k * sdLambda * sin(adLambda);\n areaRingSum.add(atan2(v, u));\n\n // Advance the previous points.\n lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi;\n}\n\nexport default function(object) {\n areaSum = new Adder();\n stream(object, areaStream);\n return areaSum * 2;\n}\n","import {Adder} from \"d3-array\";\nimport {areaStream, areaRingSum} from \"./area.js\";\nimport {cartesian, cartesianCross, cartesianNormalizeInPlace, spherical} from \"./cartesian.js\";\nimport {abs, degrees, epsilon, radians} from \"./math.js\";\nimport stream from \"./stream.js\";\n\nvar lambda0, phi0, lambda1, phi1, // bounds\n lambda2, // previous lambda-coordinate\n lambda00, phi00, // first point\n p0, // previous 3D point\n deltaSum,\n ranges,\n range;\n\nvar boundsStream = {\n point: boundsPoint,\n lineStart: boundsLineStart,\n lineEnd: boundsLineEnd,\n polygonStart: function() {\n boundsStream.point = boundsRingPoint;\n boundsStream.lineStart = boundsRingStart;\n boundsStream.lineEnd = boundsRingEnd;\n deltaSum = new Adder();\n areaStream.polygonStart();\n },\n polygonEnd: function() {\n areaStream.polygonEnd();\n boundsStream.point = boundsPoint;\n boundsStream.lineStart = boundsLineStart;\n boundsStream.lineEnd = boundsLineEnd;\n if (areaRingSum < 0) lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);\n else if (deltaSum > epsilon) phi1 = 90;\n else if (deltaSum < -epsilon) phi0 = -90;\n range[0] = lambda0, range[1] = lambda1;\n },\n sphere: function() {\n lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);\n }\n};\n\nfunction boundsPoint(lambda, phi) {\n ranges.push(range = [lambda0 = lambda, lambda1 = lambda]);\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n}\n\nfunction linePoint(lambda, phi) {\n var p = cartesian([lambda * radians, phi * radians]);\n if (p0) {\n var normal = cartesianCross(p0, p),\n equatorial = [normal[1], -normal[0], 0],\n inflection = cartesianCross(equatorial, normal);\n cartesianNormalizeInPlace(inflection);\n inflection = spherical(inflection);\n var delta = lambda - lambda2,\n sign = delta > 0 ? 1 : -1,\n lambdai = inflection[0] * degrees * sign,\n phii,\n antimeridian = abs(delta) > 180;\n if (antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {\n phii = inflection[1] * degrees;\n if (phii > phi1) phi1 = phii;\n } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {\n phii = -inflection[1] * degrees;\n if (phii < phi0) phi0 = phii;\n } else {\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n }\n if (antimeridian) {\n if (lambda < lambda2) {\n if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;\n } else {\n if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;\n }\n } else {\n if (lambda1 >= lambda0) {\n if (lambda < lambda0) lambda0 = lambda;\n if (lambda > lambda1) lambda1 = lambda;\n } else {\n if (lambda > lambda2) {\n if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;\n } else {\n if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;\n }\n }\n }\n } else {\n ranges.push(range = [lambda0 = lambda, lambda1 = lambda]);\n }\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n p0 = p, lambda2 = lambda;\n}\n\nfunction boundsLineStart() {\n boundsStream.point = linePoint;\n}\n\nfunction boundsLineEnd() {\n range[0] = lambda0, range[1] = lambda1;\n boundsStream.point = boundsPoint;\n p0 = null;\n}\n\nfunction boundsRingPoint(lambda, phi) {\n if (p0) {\n var delta = lambda - lambda2;\n deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);\n } else {\n lambda00 = lambda, phi00 = phi;\n }\n areaStream.point(lambda, phi);\n linePoint(lambda, phi);\n}\n\nfunction boundsRingStart() {\n areaStream.lineStart();\n}\n\nfunction boundsRingEnd() {\n boundsRingPoint(lambda00, phi00);\n areaStream.lineEnd();\n if (abs(deltaSum) > epsilon) lambda0 = -(lambda1 = 180);\n range[0] = lambda0, range[1] = lambda1;\n p0 = null;\n}\n\n// Finds the left-right distance between two longitudes.\n// This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want\n// the distance between ±180° to be 360°.\nfunction angle(lambda0, lambda1) {\n return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;\n}\n\nfunction rangeCompare(a, b) {\n return a[0] - b[0];\n}\n\nfunction rangeContains(range, x) {\n return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;\n}\n\nexport default function(feature) {\n var i, n, a, b, merged, deltaMax, delta;\n\n phi1 = lambda1 = -(lambda0 = phi0 = Infinity);\n ranges = [];\n stream(feature, boundsStream);\n\n // First, sort ranges by their minimum longitudes.\n if (n = ranges.length) {\n ranges.sort(rangeCompare);\n\n // Then, merge any ranges that overlap.\n for (i = 1, a = ranges[0], merged = [a]; i < n; ++i) {\n b = ranges[i];\n if (rangeContains(a, b[0]) || rangeContains(a, b[1])) {\n if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];\n if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];\n } else {\n merged.push(a = b);\n }\n }\n\n // Finally, find the largest gap between the merged ranges.\n // The final bounding box will be the inverse of this gap.\n for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {\n b = merged[i];\n if ((delta = angle(a[1], b[0])) > deltaMax) deltaMax = delta, lambda0 = b[0], lambda1 = a[1];\n }\n }\n\n ranges = range = null;\n\n return lambda0 === Infinity || phi0 === Infinity\n ? [[NaN, NaN], [NaN, NaN]]\n : [[lambda0, phi0], [lambda1, phi1]];\n}\n","import {asin, atan2, cos, sin, sqrt} from \"./math.js\";\n\nexport function spherical(cartesian) {\n return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];\n}\n\nexport function cartesian(spherical) {\n var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi);\n return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];\n}\n\nexport function cartesianDot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\nexport function cartesianCross(a, b) {\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\n}\n\n// TODO return a\nexport function cartesianAddInPlace(a, b) {\n a[0] += b[0], a[1] += b[1], a[2] += b[2];\n}\n\nexport function cartesianScale(vector, k) {\n return [vector[0] * k, vector[1] * k, vector[2] * k];\n}\n\n// TODO return d\nexport function cartesianNormalizeInPlace(d) {\n var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);\n d[0] /= l, d[1] /= l, d[2] /= l;\n}\n","import {Adder} from \"d3-array\";\nimport {asin, atan2, cos, degrees, epsilon, epsilon2, hypot, radians, sin, sqrt} from \"./math.js\";\nimport noop from \"./noop.js\";\nimport stream from \"./stream.js\";\n\nvar W0, W1,\n X0, Y0, Z0,\n X1, Y1, Z1,\n X2, Y2, Z2,\n lambda00, phi00, // first point\n x0, y0, z0; // previous point\n\nvar centroidStream = {\n sphere: noop,\n point: centroidPoint,\n lineStart: centroidLineStart,\n lineEnd: centroidLineEnd,\n polygonStart: function() {\n centroidStream.lineStart = centroidRingStart;\n centroidStream.lineEnd = centroidRingEnd;\n },\n polygonEnd: function() {\n centroidStream.lineStart = centroidLineStart;\n centroidStream.lineEnd = centroidLineEnd;\n }\n};\n\n// Arithmetic mean of Cartesian vectors.\nfunction centroidPoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n var cosPhi = cos(phi);\n centroidPointCartesian(cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi));\n}\n\nfunction centroidPointCartesian(x, y, z) {\n ++W0;\n X0 += (x - X0) / W0;\n Y0 += (y - Y0) / W0;\n Z0 += (z - Z0) / W0;\n}\n\nfunction centroidLineStart() {\n centroidStream.point = centroidLinePointFirst;\n}\n\nfunction centroidLinePointFirst(lambda, phi) {\n lambda *= radians, phi *= radians;\n var cosPhi = cos(phi);\n x0 = cosPhi * cos(lambda);\n y0 = cosPhi * sin(lambda);\n z0 = sin(phi);\n centroidStream.point = centroidLinePoint;\n centroidPointCartesian(x0, y0, z0);\n}\n\nfunction centroidLinePoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n var cosPhi = cos(phi),\n x = cosPhi * cos(lambda),\n y = cosPhi * sin(lambda),\n z = sin(phi),\n w = atan2(sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);\n W1 += w;\n X1 += w * (x0 + (x0 = x));\n Y1 += w * (y0 + (y0 = y));\n Z1 += w * (z0 + (z0 = z));\n centroidPointCartesian(x0, y0, z0);\n}\n\nfunction centroidLineEnd() {\n centroidStream.point = centroidPoint;\n}\n\n// See J. E. Brock, The Inertia Tensor for a Spherical Triangle,\n// J. Applied Mechanics 42, 239 (1975).\nfunction centroidRingStart() {\n centroidStream.point = centroidRingPointFirst;\n}\n\nfunction centroidRingEnd() {\n centroidRingPoint(lambda00, phi00);\n centroidStream.point = centroidPoint;\n}\n\nfunction centroidRingPointFirst(lambda, phi) {\n lambda00 = lambda, phi00 = phi;\n lambda *= radians, phi *= radians;\n centroidStream.point = centroidRingPoint;\n var cosPhi = cos(phi);\n x0 = cosPhi * cos(lambda);\n y0 = cosPhi * sin(lambda);\n z0 = sin(phi);\n centroidPointCartesian(x0, y0, z0);\n}\n\nfunction centroidRingPoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n var cosPhi = cos(phi),\n x = cosPhi * cos(lambda),\n y = cosPhi * sin(lambda),\n z = sin(phi),\n cx = y0 * z - z0 * y,\n cy = z0 * x - x0 * z,\n cz = x0 * y - y0 * x,\n m = hypot(cx, cy, cz),\n w = asin(m), // line weight = angle\n v = m && -w / m; // area weight multiplier\n X2.add(v * cx);\n Y2.add(v * cy);\n Z2.add(v * cz);\n W1 += w;\n X1 += w * (x0 + (x0 = x));\n Y1 += w * (y0 + (y0 = y));\n Z1 += w * (z0 + (z0 = z));\n centroidPointCartesian(x0, y0, z0);\n}\n\nexport default function(object) {\n W0 = W1 =\n X0 = Y0 = Z0 =\n X1 = Y1 = Z1 = 0;\n X2 = new Adder();\n Y2 = new Adder();\n Z2 = new Adder();\n stream(object, centroidStream);\n\n var x = +X2,\n y = +Y2,\n z = +Z2,\n m = hypot(x, y, z);\n\n // If the area-weighted ccentroid is undefined, fall back to length-weighted ccentroid.\n if (m < epsilon2) {\n x = X1, y = Y1, z = Z1;\n // If the feature has zero length, fall back to arithmetic mean of point vectors.\n if (W1 < epsilon) x = X0, y = Y0, z = Z0;\n m = hypot(x, y, z);\n // If the feature still has an undefined ccentroid, then return.\n if (m < epsilon2) return [NaN, NaN];\n }\n\n return [atan2(y, x) * degrees, asin(z / m) * degrees];\n}\n","export default function(constructor, factory, prototype) {\n constructor.prototype = factory.prototype = prototype;\n prototype.constructor = constructor;\n}\n\nexport function extend(parent, definition) {\n var prototype = Object.create(parent.prototype);\n for (var key in definition) prototype[key] = definition[key];\n return prototype;\n}\n","import define, {extend} from \"./define.js\";\n\nexport function Color() {}\n\nexport var darker = 0.7;\nexport var brighter = 1 / darker;\n\nvar reI = \"\\\\s*([+-]?\\\\d+)\\\\s*\",\n reN = \"\\\\s*([+-]?\\\\d*\\\\.?\\\\d+(?:[eE][+-]?\\\\d+)?)\\\\s*\",\n reP = \"\\\\s*([+-]?\\\\d*\\\\.?\\\\d+(?:[eE][+-]?\\\\d+)?)%\\\\s*\",\n reHex = /^#([0-9a-f]{3,8})$/,\n reRgbInteger = new RegExp(\"^rgb\\\\(\" + [reI, reI, reI] + \"\\\\)$\"),\n reRgbPercent = new RegExp(\"^rgb\\\\(\" + [reP, reP, reP] + \"\\\\)$\"),\n reRgbaInteger = new RegExp(\"^rgba\\\\(\" + [reI, reI, reI, reN] + \"\\\\)$\"),\n reRgbaPercent = new RegExp(\"^rgba\\\\(\" + [reP, reP, reP, reN] + \"\\\\)$\"),\n reHslPercent = new RegExp(\"^hsl\\\\(\" + [reN, reP, reP] + \"\\\\)$\"),\n reHslaPercent = new RegExp(\"^hsla\\\\(\" + [reN, reP, reP, reN] + \"\\\\)$\");\n\nvar named = {\n aliceblue: 0xf0f8ff,\n antiquewhite: 0xfaebd7,\n aqua: 0x00ffff,\n aquamarine: 0x7fffd4,\n azure: 0xf0ffff,\n beige: 0xf5f5dc,\n bisque: 0xffe4c4,\n black: 0x000000,\n blanchedalmond: 0xffebcd,\n blue: 0x0000ff,\n blueviolet: 0x8a2be2,\n brown: 0xa52a2a,\n burlywood: 0xdeb887,\n cadetblue: 0x5f9ea0,\n chartreuse: 0x7fff00,\n chocolate: 0xd2691e,\n coral: 0xff7f50,\n cornflowerblue: 0x6495ed,\n cornsilk: 0xfff8dc,\n crimson: 0xdc143c,\n cyan: 0x00ffff,\n darkblue: 0x00008b,\n darkcyan: 0x008b8b,\n darkgoldenrod: 0xb8860b,\n darkgray: 0xa9a9a9,\n darkgreen: 0x006400,\n darkgrey: 0xa9a9a9,\n darkkhaki: 0xbdb76b,\n darkmagenta: 0x8b008b,\n darkolivegreen: 0x556b2f,\n darkorange: 0xff8c00,\n darkorchid: 0x9932cc,\n darkred: 0x8b0000,\n darksalmon: 0xe9967a,\n darkseagreen: 0x8fbc8f,\n darkslateblue: 0x483d8b,\n darkslategray: 0x2f4f4f,\n darkslategrey: 0x2f4f4f,\n darkturquoise: 0x00ced1,\n darkviolet: 0x9400d3,\n deeppink: 0xff1493,\n deepskyblue: 0x00bfff,\n dimgray: 0x696969,\n dimgrey: 0x696969,\n dodgerblue: 0x1e90ff,\n firebrick: 0xb22222,\n floralwhite: 0xfffaf0,\n forestgreen: 0x228b22,\n fuchsia: 0xff00ff,\n gainsboro: 0xdcdcdc,\n ghostwhite: 0xf8f8ff,\n gold: 0xffd700,\n goldenrod: 0xdaa520,\n gray: 0x808080,\n green: 0x008000,\n greenyellow: 0xadff2f,\n grey: 0x808080,\n honeydew: 0xf0fff0,\n hotpink: 0xff69b4,\n indianred: 0xcd5c5c,\n indigo: 0x4b0082,\n ivory: 0xfffff0,\n khaki: 0xf0e68c,\n lavender: 0xe6e6fa,\n lavenderblush: 0xfff0f5,\n lawngreen: 0x7cfc00,\n lemonchiffon: 0xfffacd,\n lightblue: 0xadd8e6,\n lightcoral: 0xf08080,\n lightcyan: 0xe0ffff,\n lightgoldenrodyellow: 0xfafad2,\n lightgray: 0xd3d3d3,\n lightgreen: 0x90ee90,\n lightgrey: 0xd3d3d3,\n lightpink: 0xffb6c1,\n lightsalmon: 0xffa07a,\n lightseagreen: 0x20b2aa,\n lightskyblue: 0x87cefa,\n lightslategray: 0x778899,\n lightslategrey: 0x778899,\n lightsteelblue: 0xb0c4de,\n lightyellow: 0xffffe0,\n lime: 0x00ff00,\n limegreen: 0x32cd32,\n linen: 0xfaf0e6,\n magenta: 0xff00ff,\n maroon: 0x800000,\n mediumaquamarine: 0x66cdaa,\n mediumblue: 0x0000cd,\n mediumorchid: 0xba55d3,\n mediumpurple: 0x9370db,\n mediumseagreen: 0x3cb371,\n mediumslateblue: 0x7b68ee,\n mediumspringgreen: 0x00fa9a,\n mediumturquoise: 0x48d1cc,\n mediumvioletred: 0xc71585,\n midnightblue: 0x191970,\n mintcream: 0xf5fffa,\n mistyrose: 0xffe4e1,\n moccasin: 0xffe4b5,\n navajowhite: 0xffdead,\n navy: 0x000080,\n oldlace: 0xfdf5e6,\n olive: 0x808000,\n olivedrab: 0x6b8e23,\n orange: 0xffa500,\n orangered: 0xff4500,\n orchid: 0xda70d6,\n palegoldenrod: 0xeee8aa,\n palegreen: 0x98fb98,\n paleturquoise: 0xafeeee,\n palevioletred: 0xdb7093,\n papayawhip: 0xffefd5,\n peachpuff: 0xffdab9,\n peru: 0xcd853f,\n pink: 0xffc0cb,\n plum: 0xdda0dd,\n powderblue: 0xb0e0e6,\n purple: 0x800080,\n rebeccapurple: 0x663399,\n red: 0xff0000,\n rosybrown: 0xbc8f8f,\n royalblue: 0x4169e1,\n saddlebrown: 0x8b4513,\n salmon: 0xfa8072,\n sandybrown: 0xf4a460,\n seagreen: 0x2e8b57,\n seashell: 0xfff5ee,\n sienna: 0xa0522d,\n silver: 0xc0c0c0,\n skyblue: 0x87ceeb,\n slateblue: 0x6a5acd,\n slategray: 0x708090,\n slategrey: 0x708090,\n snow: 0xfffafa,\n springgreen: 0x00ff7f,\n steelblue: 0x4682b4,\n tan: 0xd2b48c,\n teal: 0x008080,\n thistle: 0xd8bfd8,\n tomato: 0xff6347,\n turquoise: 0x40e0d0,\n violet: 0xee82ee,\n wheat: 0xf5deb3,\n white: 0xffffff,\n whitesmoke: 0xf5f5f5,\n yellow: 0xffff00,\n yellowgreen: 0x9acd32\n};\n\ndefine(Color, color, {\n copy: function(channels) {\n return Object.assign(new this.constructor, this, channels);\n },\n displayable: function() {\n return this.rgb().displayable();\n },\n hex: color_formatHex, // Deprecated! Use color.formatHex.\n formatHex: color_formatHex,\n formatHsl: color_formatHsl,\n formatRgb: color_formatRgb,\n toString: color_formatRgb\n});\n\nfunction color_formatHex() {\n return this.rgb().formatHex();\n}\n\nfunction color_formatHsl() {\n return hslConvert(this).formatHsl();\n}\n\nfunction color_formatRgb() {\n return this.rgb().formatRgb();\n}\n\nexport default function color(format) {\n var m, l;\n format = (format + \"\").trim().toLowerCase();\n return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000\n : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00\n : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000\n : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000\n : null) // invalid hex\n : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)\n : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)\n : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)\n : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)\n : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)\n : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)\n : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins\n : format === \"transparent\" ? new Rgb(NaN, NaN, NaN, 0)\n : null;\n}\n\nfunction rgbn(n) {\n return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);\n}\n\nfunction rgba(r, g, b, a) {\n if (a <= 0) r = g = b = NaN;\n return new Rgb(r, g, b, a);\n}\n\nexport function rgbConvert(o) {\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Rgb;\n o = o.rgb();\n return new Rgb(o.r, o.g, o.b, o.opacity);\n}\n\nexport function rgb(r, g, b, opacity) {\n return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);\n}\n\nexport function Rgb(r, g, b, opacity) {\n this.r = +r;\n this.g = +g;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Rgb, rgb, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n rgb: function() {\n return this;\n },\n displayable: function() {\n return (-0.5 <= this.r && this.r < 255.5)\n && (-0.5 <= this.g && this.g < 255.5)\n && (-0.5 <= this.b && this.b < 255.5)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n hex: rgb_formatHex, // Deprecated! Use color.formatHex.\n formatHex: rgb_formatHex,\n formatRgb: rgb_formatRgb,\n toString: rgb_formatRgb\n}));\n\nfunction rgb_formatHex() {\n return \"#\" + hex(this.r) + hex(this.g) + hex(this.b);\n}\n\nfunction rgb_formatRgb() {\n var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));\n return (a === 1 ? \"rgb(\" : \"rgba(\")\n + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + \", \"\n + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + \", \"\n + Math.max(0, Math.min(255, Math.round(this.b) || 0))\n + (a === 1 ? \")\" : \", \" + a + \")\");\n}\n\nfunction hex(value) {\n value = Math.max(0, Math.min(255, Math.round(value) || 0));\n return (value < 16 ? \"0\" : \"\") + value.toString(16);\n}\n\nfunction hsla(h, s, l, a) {\n if (a <= 0) h = s = l = NaN;\n else if (l <= 0 || l >= 1) h = s = NaN;\n else if (s <= 0) h = NaN;\n return new Hsl(h, s, l, a);\n}\n\nexport function hslConvert(o) {\n if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Hsl;\n if (o instanceof Hsl) return o;\n o = o.rgb();\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n min = Math.min(r, g, b),\n max = Math.max(r, g, b),\n h = NaN,\n s = max - min,\n l = (max + min) / 2;\n if (s) {\n if (r === max) h = (g - b) / s + (g < b) * 6;\n else if (g === max) h = (b - r) / s + 2;\n else h = (r - g) / s + 4;\n s /= l < 0.5 ? max + min : 2 - max - min;\n h *= 60;\n } else {\n s = l > 0 && l < 1 ? 0 : h;\n }\n return new Hsl(h, s, l, o.opacity);\n}\n\nexport function hsl(h, s, l, opacity) {\n return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);\n}\n\nfunction Hsl(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Hsl, hsl, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n rgb: function() {\n var h = this.h % 360 + (this.h < 0) * 360,\n s = isNaN(h) || isNaN(this.s) ? 0 : this.s,\n l = this.l,\n m2 = l + (l < 0.5 ? l : 1 - l) * s,\n m1 = 2 * l - m2;\n return new Rgb(\n hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),\n hsl2rgb(h, m1, m2),\n hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),\n this.opacity\n );\n },\n displayable: function() {\n return (0 <= this.s && this.s <= 1 || isNaN(this.s))\n && (0 <= this.l && this.l <= 1)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n formatHsl: function() {\n var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));\n return (a === 1 ? \"hsl(\" : \"hsla(\")\n + (this.h || 0) + \", \"\n + (this.s || 0) * 100 + \"%, \"\n + (this.l || 0) * 100 + \"%\"\n + (a === 1 ? \")\" : \", \" + a + \")\");\n }\n}));\n\n/* From FvD 13.37, CSS Color Module Level 3 */\nfunction hsl2rgb(h, m1, m2) {\n return (h < 60 ? m1 + (m2 - m1) * h / 60\n : h < 180 ? m2\n : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60\n : m1) * 255;\n}\n","export const radians = Math.PI / 180;\nexport const degrees = 180 / Math.PI;\n","import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb} from \"./color.js\";\nimport {degrees, radians} from \"./math.js\";\n\n// https://observablehq.com/@mbostock/lab-and-rgb\nconst K = 18,\n Xn = 0.96422,\n Yn = 1,\n Zn = 0.82521,\n t0 = 4 / 29,\n t1 = 6 / 29,\n t2 = 3 * t1 * t1,\n t3 = t1 * t1 * t1;\n\nfunction labConvert(o) {\n if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);\n if (o instanceof Hcl) return hcl2lab(o);\n if (!(o instanceof Rgb)) o = rgbConvert(o);\n var r = rgb2lrgb(o.r),\n g = rgb2lrgb(o.g),\n b = rgb2lrgb(o.b),\n y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;\n if (r === g && g === b) x = z = y; else {\n x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);\n z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);\n }\n return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);\n}\n\nexport function gray(l, opacity) {\n return new Lab(l, 0, 0, opacity == null ? 1 : opacity);\n}\n\nexport default function lab(l, a, b, opacity) {\n return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);\n}\n\nexport function Lab(l, a, b, opacity) {\n this.l = +l;\n this.a = +a;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Lab, lab, extend(Color, {\n brighter: function(k) {\n return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n darker: function(k) {\n return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n rgb: function() {\n var y = (this.l + 16) / 116,\n x = isNaN(this.a) ? y : y + this.a / 500,\n z = isNaN(this.b) ? y : y - this.b / 200;\n x = Xn * lab2xyz(x);\n y = Yn * lab2xyz(y);\n z = Zn * lab2xyz(z);\n return new Rgb(\n lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),\n lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),\n lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),\n this.opacity\n );\n }\n}));\n\nfunction xyz2lab(t) {\n return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\n\nfunction lab2xyz(t) {\n return t > t1 ? t * t * t : t2 * (t - t0);\n}\n\nfunction lrgb2rgb(x) {\n return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);\n}\n\nfunction rgb2lrgb(x) {\n return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\n\nfunction hclConvert(o) {\n if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);\n if (!(o instanceof Lab)) o = labConvert(o);\n if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);\n var h = Math.atan2(o.b, o.a) * degrees;\n return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);\n}\n\nexport function lch(l, c, h, opacity) {\n return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function hcl(h, c, l, opacity) {\n return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function Hcl(h, c, l, opacity) {\n this.h = +h;\n this.c = +c;\n this.l = +l;\n this.opacity = +opacity;\n}\n\nfunction hcl2lab(o) {\n if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);\n var h = o.h * radians;\n return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);\n}\n\ndefine(Hcl, hcl, extend(Color, {\n brighter: function(k) {\n return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);\n },\n darker: function(k) {\n return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);\n },\n rgb: function() {\n return hcl2lab(this).rgb();\n }\n}));\n","import { field, isDate, toNumber, isArray, inrange, extend, array, error, peek, hasOwnProperty } from 'vega-util';\nimport { Literal } from 'vega-expression';\n\nfunction ascending (a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n\nfunction bisector (f) {\n let delta = f;\n let compare = f;\n\n if (f.length === 1) {\n delta = (d, x) => f(d) - x;\n\n compare = ascendingComparator(f);\n }\n\n function left(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n\n while (lo < hi) {\n const mid = lo + hi >>> 1;\n if (compare(a[mid], x) < 0) lo = mid + 1;else hi = mid;\n }\n\n return lo;\n }\n\n function right(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n\n while (lo < hi) {\n const mid = lo + hi >>> 1;\n if (compare(a[mid], x) > 0) hi = mid;else lo = mid + 1;\n }\n\n return lo;\n }\n\n function center(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n const i = left(a, x, lo, hi - 1);\n return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;\n }\n\n return {\n left,\n center,\n right\n };\n}\n\nfunction ascendingComparator(f) {\n return (d, x) => ascending(f(d), x);\n}\n\nconst Intersect = 'intersect';\nconst Union = 'union';\nconst VlMulti = 'vlMulti';\nconst VlPoint = 'vlPoint';\nconst Or = 'or';\nconst And = 'and';\n\nconst SELECTION_ID = '_vgsid_',\n TYPE_ENUM = 'E',\n TYPE_RANGE_INC = 'R',\n TYPE_RANGE_EXC = 'R-E',\n TYPE_RANGE_LE = 'R-LE',\n TYPE_RANGE_RE = 'R-RE',\n UNIT_INDEX = 'index:unit'; // TODO: revisit date coercion?\n\nfunction testPoint(datum, entry) {\n var fields = entry.fields,\n values = entry.values,\n n = fields.length,\n i = 0,\n dval,\n f;\n\n for (; i < n; ++i) {\n f = fields[i];\n f.getter = field.getter || field(f.field);\n dval = f.getter(datum);\n if (isDate(dval)) dval = toNumber(dval);\n if (isDate(values[i])) values[i] = toNumber(values[i]);\n if (isDate(values[i][0])) values[i] = values[i].map(toNumber);\n\n if (f.type === TYPE_ENUM) {\n // Enumerated fields can either specify individual values (single/multi selections)\n // or an array of values (interval selections).\n if (isArray(values[i]) ? values[i].indexOf(dval) < 0 : dval !== values[i]) {\n return false;\n }\n } else {\n if (f.type === TYPE_RANGE_INC) {\n if (!inrange(dval, values[i])) return false;\n } else if (f.type === TYPE_RANGE_RE) {\n // Discrete selection of bins test within the range [bin_start, bin_end).\n if (!inrange(dval, values[i], true, false)) return false;\n } else if (f.type === TYPE_RANGE_EXC) {\n // 'R-E'/'R-LE' included for completeness.\n if (!inrange(dval, values[i], false, false)) return false;\n } else if (f.type === TYPE_RANGE_LE) {\n if (!inrange(dval, values[i], false, true)) return false;\n }\n }\n }\n\n return true;\n}\n/**\n * Tests if a tuple is contained within an interactive selection.\n * @param {string} name - The name of the data set representing the selection.\n * Tuples in the dataset are of the form\n * {unit: string, fields: array, values: array<*>}.\n * Fielddef is of the form\n * {field: string, channel: string, type: 'E' | 'R'} where\n * 'type' identifies whether tuples in the dataset enumerate\n * values for the field, or specify a continuous range.\n * @param {object} datum - The tuple to test for inclusion.\n * @param {string} op - The set operation for combining selections.\n * One of 'intersect' or 'union' (default).\n * @return {boolean} - True if the datum is in the selection, false otherwise.\n */\n\n\nfunction selectionTest(name, datum, op) {\n var data = this.context.data[name],\n entries = data ? data.values.value : [],\n unitIdx = data ? data[UNIT_INDEX] && data[UNIT_INDEX].value : undefined,\n intersect = op === Intersect,\n n = entries.length,\n i = 0,\n entry,\n miss,\n count,\n unit,\n b;\n\n for (; i < n; ++i) {\n entry = entries[i];\n\n if (unitIdx && intersect) {\n // multi selections union within the same unit and intersect across units.\n miss = miss || {};\n count = miss[unit = entry.unit] || 0; // if we've already matched this unit, skip.\n\n if (count === -1) continue;\n b = testPoint(datum, entry);\n miss[unit] = b ? -1 : ++count; // if we match and there are no other units return true\n // if we've missed against all tuples in this unit return false\n\n if (b && unitIdx.size === 1) return true;\n if (!b && count === unitIdx.get(unit).count) return false;\n } else {\n b = testPoint(datum, entry); // if we find a miss and we do require intersection return false\n // if we find a match and we don't require intersection return true\n\n if (intersect ^ b) return b;\n }\n } // if intersecting and we made it here, then we saw no misses\n // if not intersecting, then we saw no matches\n // if no active selections, return false\n\n\n return n && intersect;\n}\nconst selectionId = field(SELECTION_ID),\n bisect = bisector(selectionId),\n bisectLeft = bisect.left,\n bisectRight = bisect.right;\nfunction selectionIdTest(name, datum, op) {\n const data = this.context.data[name],\n entries = data ? data.values.value : [],\n unitIdx = data ? data[UNIT_INDEX] && data[UNIT_INDEX].value : undefined,\n intersect = op === Intersect,\n value = selectionId(datum),\n index = bisectLeft(entries, value);\n if (index === entries.length) return false;\n if (selectionId(entries[index]) !== value) return false;\n\n if (unitIdx && intersect) {\n if (unitIdx.size === 1) return true;\n if (bisectRight(entries, value) - index < unitIdx.size) return false;\n }\n\n return true;\n}\n\n/**\n * Maps an array of scene graph items to an array of selection tuples.\n * @param {string} name - The name of the dataset representing the selection.\n * @param {string} unit - The name of the unit view.\n *\n * @returns {array} An array of selection entries for the given unit.\n */\n\nfunction selectionTuples(array, base) {\n return array.map(x => extend({\n values: base.fields.map(f => (f.getter || (f.getter = field(f.field)))(x.datum))\n }, base));\n}\n\n/**\n * Resolves selection for use as a scale domain or reads via the API.\n * @param {string} name - The name of the dataset representing the selection\n * @param {string} [op='union'] - The set operation for combining selections.\n * One of 'intersect' or 'union' (default).\n * @param {boolean} isMulti - Identifies a \"multi\" selection to perform more\n * expensive resolution computation.\n * @param {boolean} vl5 - With Vega-Lite v5, \"multi\" selections are now called \"point\"\n * selections, and thus the resolved tuple should reflect this name.\n * This parameter allows us to reflect this change without triggering\n * a major version bump for Vega.\n * @returns {object} An object of selected fields and values.\n */\n\nfunction selectionResolve(name, op, isMulti, vl5) {\n var data = this.context.data[name],\n entries = data ? data.values.value : [],\n resolved = {},\n multiRes = {},\n types = {},\n entry,\n fields,\n values,\n unit,\n field,\n res,\n resUnit,\n type,\n union,\n n = entries.length,\n i = 0,\n j,\n m; // First union all entries within the same unit.\n\n for (; i < n; ++i) {\n entry = entries[i];\n unit = entry.unit;\n fields = entry.fields;\n values = entry.values;\n\n for (j = 0, m = fields.length; j < m; ++j) {\n field = fields[j];\n res = resolved[field.field] || (resolved[field.field] = {});\n resUnit = res[unit] || (res[unit] = []);\n types[field.field] = type = field.type.charAt(0);\n union = ops[type + '_union'];\n res[unit] = union(resUnit, array(values[j]));\n } // If the same multi-selection is repeated over views and projected over\n // an encoding, it may operate over different fields making it especially\n // tricky to reliably resolve it. At best, we can de-dupe identical entries\n // but doing so may be more computationally expensive than it is worth.\n // Instead, for now, we simply transform our store representation into\n // a more human-friendly one.\n\n\n if (isMulti) {\n resUnit = multiRes[unit] || (multiRes[unit] = []);\n resUnit.push(array(values).reduce((obj, curr, j) => (obj[fields[j].field] = curr, obj), {}));\n }\n } // Then resolve fields across units as per the op.\n\n\n op = op || Union;\n Object.keys(resolved).forEach(field => {\n resolved[field] = Object.keys(resolved[field]).map(unit => resolved[field][unit]).reduce((acc, curr) => acc === undefined ? curr : ops[types[field] + '_' + op](acc, curr));\n });\n entries = Object.keys(multiRes);\n\n if (isMulti && entries.length) {\n const key = vl5 ? VlPoint : VlMulti;\n resolved[key] = op === Union ? {\n [Or]: entries.reduce((acc, k) => (acc.push(...multiRes[k]), acc), [])\n } : {\n [And]: entries.map(k => ({\n [Or]: multiRes[k]\n }))\n };\n }\n\n return resolved;\n}\nvar ops = {\n E_union: function (base, value) {\n if (!base.length) return value;\n var i = 0,\n n = value.length;\n\n for (; i < n; ++i) if (base.indexOf(value[i]) < 0) base.push(value[i]);\n\n return base;\n },\n E_intersect: function (base, value) {\n return !base.length ? value : base.filter(v => value.indexOf(v) >= 0);\n },\n R_union: function (base, value) {\n var lo = toNumber(value[0]),\n hi = toNumber(value[1]);\n\n if (lo > hi) {\n lo = value[1];\n hi = value[0];\n }\n\n if (!base.length) return [lo, hi];\n if (base[0] > lo) base[0] = lo;\n if (base[1] < hi) base[1] = hi;\n return base;\n },\n R_intersect: function (base, value) {\n var lo = toNumber(value[0]),\n hi = toNumber(value[1]);\n\n if (lo > hi) {\n lo = value[1];\n hi = value[0];\n }\n\n if (!base.length) return [lo, hi];\n\n if (hi < base[0] || base[1] < lo) {\n return [];\n } else {\n if (base[0] < lo) base[0] = lo;\n if (base[1] > hi) base[1] = hi;\n }\n\n return base;\n }\n};\n\nconst DataPrefix = ':',\n IndexPrefix = '@';\nfunction selectionVisitor(name, args, scope, params) {\n if (args[0].type !== Literal) error('First argument to selection functions must be a string literal.');\n const data = args[0].value,\n op = args.length >= 2 && peek(args).value,\n field = 'unit',\n indexName = IndexPrefix + field,\n dataName = DataPrefix + data; // eslint-disable-next-line no-prototype-builtins\n\n if (op === Intersect && !hasOwnProperty(params, indexName)) {\n params[indexName] = scope.getData(data).indataRef(scope, field);\n } // eslint-disable-next-line no-prototype-builtins\n\n\n if (!hasOwnProperty(params, dataName)) {\n params[dataName] = scope.getData(data).tuplesRef();\n }\n}\n\nexport { selectionIdTest, selectionResolve, selectionTest, selectionTuples, selectionVisitor };\n","import { truthy, error, hasOwnProperty, isFunction, isString, stringValue, extend, isArray, isObject, field, peek, identity, array as array$1, isBoolean, isDate, isNumber, isRegExp, toBoolean, toDate, toNumber, toString, flush, lerp, pad, span, inrange, truncate, quarter, utcquarter, extent, clampRange, panLinear, panLog, panPow, panSymlog, zoomLinear, zoomLog, zoomPow, zoomSymlog } from 'vega-util';\nimport { Literal, codegenExpression, constants, functions, parseExpression, CallExpression } from 'vega-expression';\nimport { geoBounds as geoBounds$1, geoCentroid as geoCentroid$1, geoArea as geoArea$1 } from 'd3-geo';\nimport { rgb, lab, hcl, hsl } from 'd3-color';\nimport { isTuple } from 'vega-dataflow';\nimport { bandSpace, scale as scale$1, scaleFraction } from 'vega-scale';\nimport { Gradient, pathRender, pathParse, Bounds, intersect as intersect$1 } from 'vega-scenegraph';\nimport { selectionVisitor, selectionTest, selectionIdTest, selectionResolve, selectionTuples } from 'vega-selections';\nimport { random, cumulativeNormal, cumulativeLogNormal, cumulativeUniform, densityNormal, densityLogNormal, densityUniform, quantileNormal, quantileLogNormal, quantileUniform, sampleNormal, sampleLogNormal, sampleUniform } from 'vega-statistics';\nimport { utcOffset, utcSequence, timeOffset, timeSequence, timeUnitSpecifier, week, utcweek, dayofyear, utcdayofyear } from 'vega-time';\nimport { range as range$1 } from 'd3-array';\n\nfunction data(name) {\n const data = this.context.data[name];\n return data ? data.values.value : [];\n}\nfunction indata(name, field, value) {\n const index = this.context.data[name]['index:' + field],\n entry = index ? index.value.get(value) : undefined;\n return entry ? entry.count : entry;\n}\nfunction setdata(name, tuples) {\n const df = this.context.dataflow,\n data = this.context.data[name],\n input = data.input;\n df.pulse(input, df.changeset().remove(truthy).insert(tuples));\n return 1;\n}\n\nfunction encode (item, name, retval) {\n if (item) {\n const df = this.context.dataflow,\n target = item.mark.source;\n df.pulse(target, df.changeset().encode(item, name));\n }\n\n return retval !== undefined ? retval : item;\n}\n\nconst wrap = method => function (value, spec) {\n const locale = this.context.dataflow.locale();\n return locale[method](spec)(value);\n};\n\nconst format = wrap('format');\nconst timeFormat = wrap('timeFormat');\nconst utcFormat = wrap('utcFormat');\nconst timeParse = wrap('timeParse');\nconst utcParse = wrap('utcParse');\nconst dateObj = new Date(2000, 0, 1);\n\nfunction time(month, day, specifier) {\n if (!Number.isInteger(month) || !Number.isInteger(day)) return '';\n dateObj.setYear(2000);\n dateObj.setMonth(month);\n dateObj.setDate(day);\n return timeFormat.call(this, dateObj, specifier);\n}\n\nfunction monthFormat(month) {\n return time.call(this, month, 1, '%B');\n}\nfunction monthAbbrevFormat(month) {\n return time.call(this, month, 1, '%b');\n}\nfunction dayFormat(day) {\n return time.call(this, 0, 2 + day, '%A');\n}\nfunction dayAbbrevFormat(day) {\n return time.call(this, 0, 2 + day, '%a');\n}\n\nconst DataPrefix = ':';\nconst IndexPrefix = '@';\nconst ScalePrefix = '%';\nconst SignalPrefix = '$';\n\nfunction dataVisitor(name, args, scope, params) {\n if (args[0].type !== Literal) {\n error('First argument to data functions must be a string literal.');\n }\n\n const data = args[0].value,\n dataName = DataPrefix + data;\n\n if (!hasOwnProperty(dataName, params)) {\n try {\n params[dataName] = scope.getData(data).tuplesRef();\n } catch (err) {// if data set does not exist, there's nothing to track\n }\n }\n}\nfunction indataVisitor(name, args, scope, params) {\n if (args[0].type !== Literal) error('First argument to indata must be a string literal.');\n if (args[1].type !== Literal) error('Second argument to indata must be a string literal.');\n const data = args[0].value,\n field = args[1].value,\n indexName = IndexPrefix + field;\n\n if (!hasOwnProperty(indexName, params)) {\n params[indexName] = scope.getData(data).indataRef(scope, field);\n }\n}\nfunction scaleVisitor(name, args, scope, params) {\n if (args[0].type === Literal) {\n // add scale dependency\n addScaleDependency(scope, params, args[0].value);\n } else {\n // indirect scale lookup; add all scales as parameters\n for (name in scope.scales) {\n addScaleDependency(scope, params, name);\n }\n }\n}\n\nfunction addScaleDependency(scope, params, name) {\n const scaleName = ScalePrefix + name;\n\n if (!hasOwnProperty(params, scaleName)) {\n try {\n params[scaleName] = scope.scaleRef(name);\n } catch (err) {// TODO: error handling? warning?\n }\n }\n}\n\nfunction getScale(name, ctx) {\n let s;\n return isFunction(name) ? name : isString(name) ? (s = ctx.scales[name]) && s.value : undefined;\n}\nfunction internalScaleFunctions(codegen, fnctx, visitors) {\n // add helper method to the 'this' expression function context\n fnctx.__bandwidth = s => s && s.bandwidth ? s.bandwidth() : 0; // register AST visitors for internal scale functions\n\n\n visitors._bandwidth = scaleVisitor;\n visitors._range = scaleVisitor;\n visitors._scale = scaleVisitor; // resolve scale reference directly to the signal hash argument\n\n const ref = arg => '_[' + (arg.type === Literal ? stringValue(ScalePrefix + arg.value) : stringValue(ScalePrefix) + '+' + codegen(arg)) + ']'; // define and return internal scale function code generators\n // these internal functions are called by mark encoders\n\n\n return {\n _bandwidth: args => `this.__bandwidth(${ref(args[0])})`,\n _range: args => `${ref(args[0])}.range()`,\n _scale: args => `${ref(args[0])}(${codegen(args[1])})`\n };\n}\n\nfunction geoMethod(methodName, globalMethod) {\n return function (projection, geojson, group) {\n if (projection) {\n // projection defined, use it\n const p = getScale(projection, (group || this).context);\n return p && p.path[methodName](geojson);\n } else {\n // projection undefined, use global method\n return globalMethod(geojson);\n }\n };\n}\n\nconst geoArea = geoMethod('area', geoArea$1);\nconst geoBounds = geoMethod('bounds', geoBounds$1);\nconst geoCentroid = geoMethod('centroid', geoCentroid$1);\n\nfunction inScope (item) {\n const group = this.context.group;\n let value = false;\n if (group) while (item) {\n if (item === group) {\n value = true;\n break;\n }\n\n item = item.mark.group;\n }\n return value;\n}\n\nfunction log(df, method, args) {\n try {\n df[method].apply(df, ['EXPRESSION'].concat([].slice.call(args)));\n } catch (err) {\n df.warn(err);\n }\n\n return args[args.length - 1];\n}\n\nfunction warn() {\n return log(this.context.dataflow, 'warn', arguments);\n}\nfunction info() {\n return log(this.context.dataflow, 'info', arguments);\n}\nfunction debug() {\n return log(this.context.dataflow, 'debug', arguments);\n}\n\nfunction channel_luminance_value(channelValue) {\n const val = channelValue / 255;\n\n if (val <= 0.03928) {\n return val / 12.92;\n }\n\n return Math.pow((val + 0.055) / 1.055, 2.4);\n}\n\nfunction luminance(color) {\n const c = rgb(color),\n r = channel_luminance_value(c.r),\n g = channel_luminance_value(c.g),\n b = channel_luminance_value(c.b);\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n} // https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef\n\nfunction contrast(color1, color2) {\n const lum1 = luminance(color1),\n lum2 = luminance(color2),\n lumL = Math.max(lum1, lum2),\n lumD = Math.min(lum1, lum2);\n return (lumL + 0.05) / (lumD + 0.05);\n}\n\nfunction merge () {\n const args = [].slice.call(arguments);\n args.unshift({});\n return extend(...args);\n}\n\nfunction equal(a, b) {\n return a === b || a !== a && b !== b ? true : isArray(a) ? isArray(b) && a.length === b.length ? equalArray(a, b) : false : isObject(a) && isObject(b) ? equalObject(a, b) : false;\n}\n\nfunction equalArray(a, b) {\n for (let i = 0, n = a.length; i < n; ++i) {\n if (!equal(a[i], b[i])) return false;\n }\n\n return true;\n}\n\nfunction equalObject(a, b) {\n for (const key in a) {\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n}\n\nfunction removePredicate(props) {\n return _ => equalObject(props, _);\n}\n\nfunction modify (name, insert, remove, toggle, modify, values) {\n const df = this.context.dataflow,\n data = this.context.data[name],\n input = data.input,\n stamp = df.stamp();\n let changes = data.changes,\n predicate,\n key;\n\n if (df._trigger === false || !(input.value.length || insert || toggle)) {\n // nothing to do!\n return 0;\n }\n\n if (!changes || changes.stamp < stamp) {\n data.changes = changes = df.changeset();\n changes.stamp = stamp;\n df.runAfter(() => {\n data.modified = true;\n df.pulse(input, changes).run();\n }, true, 1);\n }\n\n if (remove) {\n predicate = remove === true ? truthy : isArray(remove) || isTuple(remove) ? remove : removePredicate(remove);\n changes.remove(predicate);\n }\n\n if (insert) {\n changes.insert(insert);\n }\n\n if (toggle) {\n predicate = removePredicate(toggle);\n\n if (input.value.some(predicate)) {\n changes.remove(predicate);\n } else {\n changes.insert(toggle);\n }\n }\n\n if (modify) {\n for (key in values) {\n changes.modify(modify, key, values[key]);\n }\n }\n\n return 1;\n}\n\nfunction pinchDistance(event) {\n const t = event.touches,\n dx = t[0].clientX - t[1].clientX,\n dy = t[0].clientY - t[1].clientY;\n return Math.sqrt(dx * dx + dy * dy);\n}\nfunction pinchAngle(event) {\n const t = event.touches;\n return Math.atan2(t[0].clientY - t[1].clientY, t[0].clientX - t[1].clientX);\n}\n\nconst accessors = {};\nfunction pluck (data, name) {\n const accessor = accessors[name] || (accessors[name] = field(name));\n return isArray(data) ? data.map(accessor) : accessor(data);\n}\n\nfunction array(seq) {\n return isArray(seq) || ArrayBuffer.isView(seq) ? seq : null;\n}\n\nfunction sequence(seq) {\n return array(seq) || (isString(seq) ? seq : null);\n}\n\nfunction join(seq, ...args) {\n return array(seq).join(...args);\n}\nfunction indexof(seq, ...args) {\n return sequence(seq).indexOf(...args);\n}\nfunction lastindexof(seq, ...args) {\n return sequence(seq).lastIndexOf(...args);\n}\nfunction slice(seq, ...args) {\n return sequence(seq).slice(...args);\n}\nfunction replace(str, pattern, repl) {\n if (isFunction(repl)) error('Function argument passed to replace.');\n return String(str).replace(pattern, repl);\n}\nfunction reverse(seq) {\n return array(seq).slice().reverse();\n}\n\nfunction bandspace(count, paddingInner, paddingOuter) {\n return bandSpace(count || 0, paddingInner || 0, paddingOuter || 0);\n}\nfunction bandwidth(name, group) {\n const s = getScale(name, (group || this).context);\n return s && s.bandwidth ? s.bandwidth() : 0;\n}\nfunction copy(name, group) {\n const s = getScale(name, (group || this).context);\n return s ? s.copy() : undefined;\n}\nfunction domain(name, group) {\n const s = getScale(name, (group || this).context);\n return s ? s.domain() : [];\n}\nfunction invert(name, range, group) {\n const s = getScale(name, (group || this).context);\n return !s ? undefined : isArray(range) ? (s.invertRange || s.invert)(range) : (s.invert || s.invertExtent)(range);\n}\nfunction range(name, group) {\n const s = getScale(name, (group || this).context);\n return s && s.range ? s.range() : [];\n}\nfunction scale(name, value, group) {\n const s = getScale(name, (group || this).context);\n return s ? s(value) : undefined;\n}\n\nfunction scaleGradient (scale, p0, p1, count, group) {\n scale = getScale(scale, (group || this).context);\n const gradient = Gradient(p0, p1);\n let stops = scale.domain(),\n min = stops[0],\n max = peek(stops),\n fraction = identity;\n\n if (!(max - min)) {\n // expand scale if domain has zero span, fix #1479\n scale = (scale.interpolator ? scale$1('sequential')().interpolator(scale.interpolator()) : scale$1('linear')().interpolate(scale.interpolate()).range(scale.range())).domain([min = 0, max = 1]);\n } else {\n fraction = scaleFraction(scale, min, max);\n }\n\n if (scale.ticks) {\n stops = scale.ticks(+count || 15);\n if (min !== stops[0]) stops.unshift(min);\n if (max !== peek(stops)) stops.push(max);\n }\n\n stops.forEach(_ => gradient.stop(fraction(_), scale(_)));\n return gradient;\n}\n\nfunction geoShape(projection, geojson, group) {\n const p = getScale(projection, (group || this).context);\n return function (context) {\n return p ? p.path.context(context)(geojson) : '';\n };\n}\nfunction pathShape(path) {\n let p = null;\n return function (context) {\n return context ? pathRender(context, p = p || pathParse(path)) : path;\n };\n}\n\nconst datum = d => d.data;\n\nfunction treeNodes(name, context) {\n const tree = data.call(context, name);\n return tree.root && tree.root.lookup || {};\n}\n\nfunction treePath(name, source, target) {\n const nodes = treeNodes(name, this),\n s = nodes[source],\n t = nodes[target];\n return s && t ? s.path(t).map(datum) : undefined;\n}\nfunction treeAncestors(name, node) {\n const n = treeNodes(name, this)[node];\n return n ? n.ancestors().map(datum) : undefined;\n}\n\nconst _window = () => typeof window !== 'undefined' && window || null;\n\nfunction screen() {\n const w = _window();\n\n return w ? w.screen : {};\n}\nfunction windowSize() {\n const w = _window();\n\n return w ? [w.innerWidth, w.innerHeight] : [undefined, undefined];\n}\nfunction containerSize() {\n const view = this.context.dataflow,\n el = view.container && view.container();\n return el ? [el.clientWidth, el.clientHeight] : [undefined, undefined];\n}\n\nfunction intersect (b, opt, group) {\n if (!b) return [];\n const [u, v] = b,\n box = new Bounds().set(u[0], u[1], v[0], v[1]),\n scene = group || this.context.dataflow.scenegraph().root;\n return intersect$1(scene, box, filter(opt));\n}\n\nfunction filter(opt) {\n let p = null;\n\n if (opt) {\n const types = array$1(opt.marktype),\n names = array$1(opt.markname);\n\n p = _ => (!types.length || types.some(t => _.marktype === t)) && (!names.length || names.some(s => _.name === s));\n }\n\n return p;\n}\n\nconst functionContext = {\n random() {\n return random();\n },\n\n // override default\n cumulativeNormal,\n cumulativeLogNormal,\n cumulativeUniform,\n densityNormal,\n densityLogNormal,\n densityUniform,\n quantileNormal,\n quantileLogNormal,\n quantileUniform,\n sampleNormal,\n sampleLogNormal,\n sampleUniform,\n isArray,\n isBoolean,\n isDate,\n\n isDefined(_) {\n return _ !== undefined;\n },\n\n isNumber,\n isObject,\n isRegExp,\n isString,\n isTuple,\n\n isValid(_) {\n return _ != null && _ === _;\n },\n\n toBoolean,\n toDate,\n toNumber,\n toString,\n indexof,\n join,\n lastindexof,\n replace,\n reverse,\n slice,\n flush,\n lerp,\n merge,\n pad,\n peek,\n pluck,\n span,\n inrange,\n truncate,\n rgb,\n lab,\n hcl,\n hsl,\n luminance,\n contrast,\n sequence: range$1,\n format,\n utcFormat,\n utcParse,\n utcOffset,\n utcSequence,\n timeFormat,\n timeParse,\n timeOffset,\n timeSequence,\n timeUnitSpecifier,\n monthFormat,\n monthAbbrevFormat,\n dayFormat,\n dayAbbrevFormat,\n quarter,\n utcquarter,\n week,\n utcweek,\n dayofyear,\n utcdayofyear,\n warn,\n info,\n debug,\n extent,\n inScope,\n intersect,\n clampRange,\n pinchDistance,\n pinchAngle,\n screen,\n containerSize,\n windowSize,\n bandspace,\n setdata,\n pathShape,\n panLinear,\n panLog,\n panPow,\n panSymlog,\n zoomLinear,\n zoomLog,\n zoomPow,\n zoomSymlog,\n encode,\n modify\n};\nconst eventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y'],\n // event functions\neventPrefix = 'event.vega.',\n // event function prefix\nthisPrefix = 'this.',\n // function context prefix\nastVisitors = {}; // AST visitors for dependency analysis\n// export code generator parameters\n\nconst codegenParams = {\n forbidden: ['_'],\n allowed: ['datum', 'event', 'item'],\n fieldvar: 'datum',\n globalvar: id => `_[${stringValue(SignalPrefix + id)}]`,\n functions: buildFunctions,\n constants: constants,\n visitors: astVisitors\n}; // export code generator\n\nconst codeGenerator = codegenExpression(codegenParams); // Build expression function registry\n\nfunction buildFunctions(codegen) {\n const fn = functions(codegen);\n eventFunctions.forEach(name => fn[name] = eventPrefix + name);\n\n for (const name in functionContext) {\n fn[name] = thisPrefix + name;\n }\n\n extend(fn, internalScaleFunctions(codegen, functionContext, astVisitors));\n return fn;\n} // Register an expression function\n\n\nfunction expressionFunction(name, fn, visitor) {\n if (arguments.length === 1) {\n return functionContext[name];\n } // register with the functionContext\n\n\n functionContext[name] = fn; // if there is an astVisitor register that, too\n\n if (visitor) astVisitors[name] = visitor; // if the code generator has already been initialized,\n // we need to also register the function with it\n\n if (codeGenerator) codeGenerator.functions[name] = thisPrefix + name;\n return this;\n} // register expression functions with ast visitors\n\nexpressionFunction('bandwidth', bandwidth, scaleVisitor);\nexpressionFunction('copy', copy, scaleVisitor);\nexpressionFunction('domain', domain, scaleVisitor);\nexpressionFunction('range', range, scaleVisitor);\nexpressionFunction('invert', invert, scaleVisitor);\nexpressionFunction('scale', scale, scaleVisitor);\nexpressionFunction('gradient', scaleGradient, scaleVisitor);\nexpressionFunction('geoArea', geoArea, scaleVisitor);\nexpressionFunction('geoBounds', geoBounds, scaleVisitor);\nexpressionFunction('geoCentroid', geoCentroid, scaleVisitor);\nexpressionFunction('geoShape', geoShape, scaleVisitor);\nexpressionFunction('indata', indata, indataVisitor);\nexpressionFunction('data', data, dataVisitor);\nexpressionFunction('treePath', treePath, dataVisitor);\nexpressionFunction('treeAncestors', treeAncestors, dataVisitor); // register Vega-Lite selection functions\n\nexpressionFunction('vlSelectionTest', selectionTest, selectionVisitor);\nexpressionFunction('vlSelectionIdTest', selectionIdTest, selectionVisitor);\nexpressionFunction('vlSelectionResolve', selectionResolve, selectionVisitor);\nexpressionFunction('vlSelectionTuples', selectionTuples);\n\nfunction parser (expr, scope) {\n const params = {}; // parse the expression to an abstract syntax tree (ast)\n\n let ast;\n\n try {\n expr = isString(expr) ? expr : stringValue(expr) + '';\n ast = parseExpression(expr);\n } catch (err) {\n error('Expression parse error: ' + expr);\n } // analyze ast function calls for dependencies\n\n\n ast.visit(node => {\n if (node.type !== CallExpression) return;\n const name = node.callee.name,\n visit = codegenParams.visitors[name];\n if (visit) visit(name, node.arguments, scope, params);\n }); // perform code generation\n\n const gen = codeGenerator(ast); // collect signal dependencies\n\n gen.globals.forEach(name => {\n const signalName = SignalPrefix + name;\n\n if (!hasOwnProperty(params, signalName) && scope.getSignal(name)) {\n params[signalName] = scope.signalRef(name);\n }\n }); // return generated expression code and dependencies\n\n return {\n $expr: extend({\n code: gen.code\n }, scope.options.ast ? {\n ast\n } : null),\n $fields: gen.fields,\n $params: params\n };\n}\n\nexport { DataPrefix, IndexPrefix, ScalePrefix, SignalPrefix, bandspace, bandwidth, codeGenerator, codegenParams, containerSize, contrast, copy, data, dataVisitor, dayAbbrevFormat, dayFormat, debug, domain, encode, expressionFunction, format, functionContext, geoArea, geoBounds, geoCentroid, geoShape, inScope, indata, indataVisitor, indexof, info, invert, join, lastindexof, luminance, merge, modify, monthAbbrevFormat, monthFormat, parser as parseExpression, pathShape, pinchAngle, pinchDistance, pluck, range, replace, reverse, scale, scaleGradient, scaleVisitor, screen, setdata, slice, timeFormat, timeParse, treeAncestors, treePath, utcFormat, utcParse, warn, windowSize };\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","import { toSet, stringValue, error, isArray, isObject, hasOwnProperty, accessor, key, field, array, compare, truthy } from 'vega-util';\nimport { tupleid } from 'vega-dataflow';\n\n/**\n * Parse a serialized dataflow specification.\n */\nfunction parse (spec) {\n const ctx = this,\n operators = spec.operators || []; // parse background\n\n if (spec.background) {\n ctx.background = spec.background;\n } // parse event configuration\n\n\n if (spec.eventConfig) {\n ctx.eventConfig = spec.eventConfig;\n } // parse locale configuration\n\n\n if (spec.locale) {\n ctx.locale = spec.locale;\n } // parse operators\n\n\n operators.forEach(entry => ctx.parseOperator(entry)); // parse operator parameters\n\n operators.forEach(entry => ctx.parseOperatorParameters(entry)); // parse streams\n\n (spec.streams || []).forEach(entry => ctx.parseStream(entry)); // parse updates\n\n (spec.updates || []).forEach(entry => ctx.parseUpdate(entry));\n return ctx.resolve();\n}\n\nconst Skip = toSet(['rule']),\n Swap = toSet(['group', 'image', 'rect']);\nfunction adjustSpatial(encode, marktype) {\n let code = '';\n if (Skip[marktype]) return code;\n\n if (encode.x2) {\n if (encode.x) {\n if (Swap[marktype]) {\n code += 'if(o.x>o.x2)$=o.x,o.x=o.x2,o.x2=$;';\n }\n\n code += 'o.width=o.x2-o.x;';\n } else {\n code += 'o.x=o.x2-(o.width||0);';\n }\n }\n\n if (encode.xc) {\n code += 'o.x=o.xc-(o.width||0)/2;';\n }\n\n if (encode.y2) {\n if (encode.y) {\n if (Swap[marktype]) {\n code += 'if(o.y>o.y2)$=o.y,o.y=o.y2,o.y2=$;';\n }\n\n code += 'o.height=o.y2-o.y;';\n } else {\n code += 'o.y=o.y2-(o.height||0);';\n }\n }\n\n if (encode.yc) {\n code += 'o.y=o.yc-(o.height||0)/2;';\n }\n\n return code;\n}\nfunction canonicalType(type) {\n return (type + '').toLowerCase();\n}\nfunction isOperator(type) {\n return canonicalType(type) === 'operator';\n}\nfunction isCollect(type) {\n return canonicalType(type) === 'collect';\n}\n\nfunction expression(ctx, args, code) {\n // wrap code in return statement if expression does not terminate\n if (code[code.length - 1] !== ';') {\n code = 'return(' + code + ');';\n }\n\n const fn = Function(...args.concat(code));\n return ctx && ctx.functions ? fn.bind(ctx.functions) : fn;\n} // generate code for comparing a single field\n\n\nfunction _compare(u, v, lt, gt) {\n return \"((u = \".concat(u, \") < (v = \").concat(v, \") || u == null) && v != null ? \").concat(lt, \"\\n : (u > v || v == null) && u != null ? \").concat(gt, \"\\n : ((v = v instanceof Date ? +v : v), (u = u instanceof Date ? +u : u)) !== u && v === v ? \").concat(lt, \"\\n : v !== v && u === u ? \").concat(gt, \" : \");\n}\n\nvar expressionCodegen = {\n /**\n * Parse an expression used to update an operator value.\n */\n operator: (ctx, expr) => expression(ctx, ['_'], expr.code),\n\n /**\n * Parse an expression provided as an operator parameter value.\n */\n parameter: (ctx, expr) => expression(ctx, ['datum', '_'], expr.code),\n\n /**\n * Parse an expression applied to an event stream.\n */\n event: (ctx, expr) => expression(ctx, ['event'], expr.code),\n\n /**\n * Parse an expression used to handle an event-driven operator update.\n */\n handler: (ctx, expr) => {\n const code = \"var datum=event.item&&event.item.datum;return \".concat(expr.code, \";\");\n return expression(ctx, ['_', 'event'], code);\n },\n\n /**\n * Parse an expression that performs visual encoding.\n */\n encode: (ctx, encode) => {\n const {\n marktype,\n channels\n } = encode;\n let code = 'var o=item,datum=o.datum,m=0,$;';\n\n for (const name in channels) {\n const o = 'o[' + stringValue(name) + ']';\n code += \"$=\".concat(channels[name].code, \";if(\").concat(o, \"!==$)\").concat(o, \"=$,m=1;\");\n }\n\n code += adjustSpatial(channels, marktype);\n code += 'return m;';\n return expression(ctx, ['item', '_'], code);\n },\n\n /**\n * Optimized code generators for access and comparison.\n */\n codegen: {\n get(path) {\n const ref = \"[\".concat(path.map(stringValue).join(']['), \"]\");\n const get = Function('_', \"return _\".concat(ref, \";\"));\n get.path = ref;\n return get;\n },\n\n comparator(fields, orders) {\n let t;\n\n const map = (f, i) => {\n const o = orders[i];\n let u, v;\n\n if (f.path) {\n u = \"a\".concat(f.path);\n v = \"b\".concat(f.path);\n } else {\n (t = t || {})['f' + i] = f;\n u = \"this.f\".concat(i, \"(a)\");\n v = \"this.f\".concat(i, \"(b)\");\n }\n\n return _compare(u, v, -o, o);\n };\n\n const fn = Function('a', 'b', 'var u, v; return ' + fields.map(map).join('') + '0;');\n return t ? fn.bind(t) : fn;\n }\n\n }\n};\n\n/**\n * Parse a dataflow operator.\n */\n\nfunction parseOperator(spec) {\n const ctx = this;\n\n if (isOperator(spec.type) || !spec.type) {\n ctx.operator(spec, spec.update ? ctx.operatorExpression(spec.update) : null);\n } else {\n ctx.transform(spec, spec.type);\n }\n}\n/**\n * Parse and assign operator parameters.\n */\n\nfunction parseOperatorParameters(spec) {\n const ctx = this;\n\n if (spec.params) {\n const op = ctx.get(spec.id);\n if (!op) error('Invalid operator id: ' + spec.id);\n ctx.dataflow.connect(op, op.parameters(ctx.parseParameters(spec.params), spec.react, spec.initonly));\n }\n}\n\n/**\n * Parse a set of operator parameters.\n */\n\nfunction parseParameters(spec, params) {\n params = params || {};\n const ctx = this;\n\n for (const key in spec) {\n const value = spec[key];\n params[key] = isArray(value) ? value.map(v => parseParameter(v, ctx, params)) : parseParameter(value, ctx, params);\n }\n\n return params;\n}\n/**\n * Parse a single parameter.\n */\n\nfunction parseParameter(spec, ctx, params) {\n if (!spec || !isObject(spec)) return spec;\n\n for (let i = 0, n = PARSERS.length, p; i < n; ++i) {\n p = PARSERS[i];\n\n if (hasOwnProperty(spec, p.key)) {\n return p.parse(spec, ctx, params);\n }\n }\n\n return spec;\n}\n/** Reference parsers. */\n\n\nvar PARSERS = [{\n key: '$ref',\n parse: getOperator\n}, {\n key: '$key',\n parse: getKey\n}, {\n key: '$expr',\n parse: getExpression\n}, {\n key: '$field',\n parse: getField\n}, {\n key: '$encode',\n parse: getEncode\n}, {\n key: '$compare',\n parse: getCompare\n}, {\n key: '$context',\n parse: getContext\n}, {\n key: '$subflow',\n parse: getSubflow\n}, {\n key: '$tupleid',\n parse: getTupleId\n}];\n/**\n * Resolve an operator reference.\n */\n\nfunction getOperator(_, ctx) {\n return ctx.get(_.$ref) || error('Operator not defined: ' + _.$ref);\n}\n/**\n * Resolve an expression reference.\n */\n\n\nfunction getExpression(_, ctx, params) {\n if (_.$params) {\n // parse expression parameters\n ctx.parseParameters(_.$params, params);\n }\n\n const k = 'e:' + _.$expr.code + '_' + _.$name;\n return ctx.fn[k] || (ctx.fn[k] = accessor(ctx.parameterExpression(_.$expr), _.$fields, _.$name));\n}\n/**\n * Resolve a key accessor reference.\n */\n\n\nfunction getKey(_, ctx) {\n const k = 'k:' + _.$key + '_' + !!_.$flat;\n return ctx.fn[k] || (ctx.fn[k] = key(_.$key, _.$flat, ctx.expr.codegen));\n}\n/**\n * Resolve a field accessor reference.\n */\n\n\nfunction getField(_, ctx) {\n if (!_.$field) return null;\n const k = 'f:' + _.$field + '_' + _.$name;\n return ctx.fn[k] || (ctx.fn[k] = field(_.$field, _.$name, ctx.expr.codegen));\n}\n/**\n * Resolve a comparator function reference.\n */\n\n\nfunction getCompare(_, ctx) {\n // As of Vega 5.5.3, $tupleid sort is no longer used.\n // Keep here for now for backwards compatibility.\n const k = 'c:' + _.$compare + '_' + _.$order,\n c = array(_.$compare).map(_ => _ && _.$tupleid ? tupleid : _);\n return ctx.fn[k] || (ctx.fn[k] = compare(c, _.$order, ctx.expr.codegen));\n}\n/**\n * Resolve an encode operator reference.\n */\n\n\nfunction getEncode(_, ctx) {\n const spec = _.$encode,\n encode = {};\n\n for (const name in spec) {\n const enc = spec[name];\n encode[name] = accessor(ctx.encodeExpression(enc.$expr), enc.$fields);\n encode[name].output = enc.$output;\n }\n\n return encode;\n}\n/**\n * Resolve a context reference.\n */\n\n\nfunction getContext(_, ctx) {\n return ctx;\n}\n/**\n * Resolve a recursive subflow specification.\n */\n\n\nfunction getSubflow(_, ctx) {\n const spec = _.$subflow;\n return function (dataflow, key, parent) {\n const subctx = ctx.fork().parse(spec),\n op = subctx.get(spec.operators[0].id),\n p = subctx.signals.parent;\n if (p) p.set(parent);\n\n op.detachSubflow = () => ctx.detach(subctx);\n\n return op;\n };\n}\n/**\n * Resolve a tuple id reference.\n */\n\n\nfunction getTupleId() {\n return tupleid;\n}\n\n/**\n * Parse an event stream specification.\n */\n\nfunction parseStream (spec) {\n var ctx = this,\n filter = spec.filter != null ? ctx.eventExpression(spec.filter) : undefined,\n stream = spec.stream != null ? ctx.get(spec.stream) : undefined,\n args;\n\n if (spec.source) {\n stream = ctx.events(spec.source, spec.type, filter);\n } else if (spec.merge) {\n args = spec.merge.map(_ => ctx.get(_));\n stream = args[0].merge.apply(args[0], args.slice(1));\n }\n\n if (spec.between) {\n args = spec.between.map(_ => ctx.get(_));\n stream = stream.between(args[0], args[1]);\n }\n\n if (spec.filter) {\n stream = stream.filter(filter);\n }\n\n if (spec.throttle != null) {\n stream = stream.throttle(+spec.throttle);\n }\n\n if (spec.debounce != null) {\n stream = stream.debounce(+spec.debounce);\n }\n\n if (stream == null) {\n error('Invalid stream definition: ' + JSON.stringify(spec));\n }\n\n if (spec.consume) stream.consume(true);\n ctx.stream(spec, stream);\n}\n\n/**\n * Parse an event-driven operator update.\n */\n\nfunction parseUpdate (spec) {\n var ctx = this,\n srcid = isObject(srcid = spec.source) ? srcid.$ref : srcid,\n source = ctx.get(srcid),\n target = null,\n update = spec.update,\n params = undefined;\n if (!source) error('Source not defined: ' + spec.source);\n target = spec.target && spec.target.$expr ? ctx.eventExpression(spec.target.$expr) : ctx.get(spec.target);\n\n if (update && update.$expr) {\n if (update.$params) {\n params = ctx.parseParameters(update.$params);\n }\n\n update = ctx.handlerExpression(update.$expr);\n }\n\n ctx.update(spec, source, target, update, params);\n}\n\nconst SKIP = {\n skip: true\n};\nfunction getState(options) {\n var ctx = this,\n state = {};\n\n if (options.signals) {\n var signals = state.signals = {};\n Object.keys(ctx.signals).forEach(key => {\n const op = ctx.signals[key];\n\n if (options.signals(key, op)) {\n signals[key] = op.value;\n }\n });\n }\n\n if (options.data) {\n var data = state.data = {};\n Object.keys(ctx.data).forEach(key => {\n const dataset = ctx.data[key];\n\n if (options.data(key, dataset)) {\n data[key] = dataset.input.value;\n }\n });\n }\n\n if (ctx.subcontext && options.recurse !== false) {\n state.subcontext = ctx.subcontext.map(ctx => ctx.getState(options));\n }\n\n return state;\n}\nfunction setState(state) {\n var ctx = this,\n df = ctx.dataflow,\n data = state.data,\n signals = state.signals;\n Object.keys(signals || {}).forEach(key => {\n df.update(ctx.signals[key], signals[key], SKIP);\n });\n Object.keys(data || {}).forEach(key => {\n df.pulse(ctx.data[key].input, df.changeset().remove(truthy).insert(data[key]));\n });\n (state.subcontext || []).forEach((substate, i) => {\n const subctx = ctx.subcontext[i];\n if (subctx) subctx.setState(substate);\n });\n}\n\n/**\n * Context objects store the current parse state.\n * Enables lookup of parsed operators, event streams, accessors, etc.\n * Provides a 'fork' method for creating child contexts for subflows.\n */\n\nfunction context (df, transforms, functions, expr) {\n return new Context(df, transforms, functions, expr);\n}\n\nfunction Context(df, transforms, functions, expr) {\n this.dataflow = df;\n this.transforms = transforms;\n this.events = df.events.bind(df);\n this.expr = expr || expressionCodegen, this.signals = {};\n this.scales = {};\n this.nodes = {};\n this.data = {};\n this.fn = {};\n\n if (functions) {\n this.functions = Object.create(functions);\n this.functions.context = this;\n }\n}\n\nfunction Subcontext(ctx) {\n this.dataflow = ctx.dataflow;\n this.transforms = ctx.transforms;\n this.events = ctx.events;\n this.expr = ctx.expr;\n this.signals = Object.create(ctx.signals);\n this.scales = Object.create(ctx.scales);\n this.nodes = Object.create(ctx.nodes);\n this.data = Object.create(ctx.data);\n this.fn = Object.create(ctx.fn);\n\n if (ctx.functions) {\n this.functions = Object.create(ctx.functions);\n this.functions.context = this;\n }\n}\n\nContext.prototype = Subcontext.prototype = {\n fork() {\n const ctx = new Subcontext(this);\n (this.subcontext || (this.subcontext = [])).push(ctx);\n return ctx;\n },\n\n detach(ctx) {\n this.subcontext = this.subcontext.filter(c => c !== ctx); // disconnect all nodes in the subcontext\n // wipe out targets first for better efficiency\n\n const keys = Object.keys(ctx.nodes);\n\n for (const key of keys) ctx.nodes[key]._targets = null;\n\n for (const key of keys) ctx.nodes[key].detach();\n\n ctx.nodes = null;\n },\n\n get(id) {\n return this.nodes[id];\n },\n\n set(id, node) {\n return this.nodes[id] = node;\n },\n\n add(spec, op) {\n const ctx = this,\n df = ctx.dataflow,\n data = spec.value;\n ctx.set(spec.id, op);\n\n if (isCollect(spec.type) && data) {\n if (data.$ingest) {\n df.ingest(op, data.$ingest, data.$format);\n } else if (data.$request) {\n df.preload(op, data.$request, data.$format);\n } else {\n df.pulse(op, df.changeset().insert(data));\n }\n }\n\n if (spec.root) {\n ctx.root = op;\n }\n\n if (spec.parent) {\n let p = ctx.get(spec.parent.$ref);\n\n if (p) {\n df.connect(p, [op]);\n op.targets().add(p);\n } else {\n (ctx.unresolved = ctx.unresolved || []).push(() => {\n p = ctx.get(spec.parent.$ref);\n df.connect(p, [op]);\n op.targets().add(p);\n });\n }\n }\n\n if (spec.signal) {\n ctx.signals[spec.signal] = op;\n }\n\n if (spec.scale) {\n ctx.scales[spec.scale] = op;\n }\n\n if (spec.data) {\n for (const name in spec.data) {\n const data = ctx.data[name] || (ctx.data[name] = {});\n spec.data[name].forEach(role => data[role] = op);\n }\n }\n },\n\n resolve() {\n (this.unresolved || []).forEach(fn => fn());\n delete this.unresolved;\n return this;\n },\n\n operator(spec, update) {\n this.add(spec, this.dataflow.add(spec.value, update));\n },\n\n transform(spec, type) {\n this.add(spec, this.dataflow.add(this.transforms[canonicalType(type)]));\n },\n\n stream(spec, stream) {\n this.set(spec.id, stream);\n },\n\n update(spec, stream, target, update, params) {\n this.dataflow.on(stream, target, update, params, spec.options);\n },\n\n // expression parsing\n operatorExpression(expr) {\n return this.expr.operator(this, expr);\n },\n\n parameterExpression(expr) {\n return this.expr.parameter(this, expr);\n },\n\n eventExpression(expr) {\n return this.expr.event(this, expr);\n },\n\n handlerExpression(expr) {\n return this.expr.handler(this, expr);\n },\n\n encodeExpression(encode) {\n return this.expr.encode(this, encode);\n },\n\n // parse methods\n parse,\n parseOperator,\n parseOperatorParameters,\n parseParameters,\n parseStream,\n parseUpdate,\n // state methods\n getState,\n setState\n};\n\nexport { context };\n","var frame = 0, // is an animation frame pending?\n timeout = 0, // is a timeout pending?\n interval = 0, // are any timers active?\n pokeDelay = 1000, // how frequently we check for clock skew\n taskHead,\n taskTail,\n clockLast = 0,\n clockNow = 0,\n clockSkew = 0,\n clock = typeof performance === \"object\" && performance.now ? performance : Date,\n setFrame = typeof window === \"object\" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };\n\nexport function now() {\n return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);\n}\n\nfunction clearNow() {\n clockNow = 0;\n}\n\nexport function Timer() {\n this._call =\n this._time =\n this._next = null;\n}\n\nTimer.prototype = timer.prototype = {\n constructor: Timer,\n restart: function(callback, delay, time) {\n if (typeof callback !== \"function\") throw new TypeError(\"callback is not a function\");\n time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);\n if (!this._next && taskTail !== this) {\n if (taskTail) taskTail._next = this;\n else taskHead = this;\n taskTail = this;\n }\n this._call = callback;\n this._time = time;\n sleep();\n },\n stop: function() {\n if (this._call) {\n this._call = null;\n this._time = Infinity;\n sleep();\n }\n }\n};\n\nexport function timer(callback, delay, time) {\n var t = new Timer;\n t.restart(callback, delay, time);\n return t;\n}\n\nexport function timerFlush() {\n now(); // Get the current time, if not already set.\n ++frame; // Pretend we’ve set an alarm, if we haven’t already.\n var t = taskHead, e;\n while (t) {\n if ((e = clockNow - t._time) >= 0) t._call.call(null, e);\n t = t._next;\n }\n --frame;\n}\n\nfunction wake() {\n clockNow = (clockLast = clock.now()) + clockSkew;\n frame = timeout = 0;\n try {\n timerFlush();\n } finally {\n frame = 0;\n nap();\n clockNow = 0;\n }\n}\n\nfunction poke() {\n var now = clock.now(), delay = now - clockLast;\n if (delay > pokeDelay) clockSkew -= delay, clockLast = now;\n}\n\nfunction nap() {\n var t0, t1 = taskHead, t2, time = Infinity;\n while (t1) {\n if (t1._call) {\n if (time > t1._time) time = t1._time;\n t0 = t1, t1 = t1._next;\n } else {\n t2 = t1._next, t1._next = null;\n t1 = t0 ? t0._next = t2 : taskHead = t2;\n }\n }\n taskTail = t0;\n sleep(time);\n}\n\nfunction sleep(time) {\n if (frame) return; // Soonest alarm already set, or will be.\n if (timeout) timeout = clearTimeout(timeout);\n var delay = time - clockNow; // Strictly less than if we recomputed clockNow.\n if (delay > 24) {\n if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew);\n if (interval) interval = clearInterval(interval);\n } else {\n if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);\n frame = 1, setFrame(wake);\n }\n}\n","import { isString, hasOwnProperty, error, truthy, constant, extend, isArray, toSet, array, isObject, debounce, isDate, inherits, stringValue } from 'vega-util';\nimport { changeset, isChangeSet, EventStream, transforms, Dataflow, asyncCallback } from 'vega-dataflow';\nimport { point, renderModule, CanvasHandler, RenderType, Scenegraph } from 'vega-scenegraph';\nimport { tickStep } from 'd3-array';\nimport { functionContext } from 'vega-functions';\nimport { context } from 'vega-runtime';\nimport { interval } from 'd3-timer';\nimport { locale } from 'vega-format';\n\n// initialize aria role and label attributes\nfunction initializeAria(view) {\n const el = view.container();\n\n if (el) {\n el.setAttribute('role', 'graphics-document');\n el.setAttribute('aria-roleDescription', 'visualization');\n ariaLabel(el, view.description());\n }\n} // update aria-label if we have a DOM container element\n\nfunction ariaLabel(el, desc) {\n if (el) desc == null ? el.removeAttribute('aria-label') : el.setAttribute('aria-label', desc);\n}\n\nfunction background (view) {\n // respond to background signal\n view.add(null, _ => {\n view._background = _.bg;\n view._resize = 1;\n return _.bg;\n }, {\n bg: view._signals.background\n });\n}\n\nconst Default = 'default';\nfunction cursor (view) {\n // get cursor signal, add to dataflow if needed\n const cursor = view._signals.cursor || (view._signals.cursor = view.add({\n user: Default,\n item: null\n })); // evaluate cursor on each mousemove event\n\n view.on(view.events('view', 'mousemove'), cursor, (_, event) => {\n const value = cursor.value,\n user = value ? isString(value) ? value : value.user : Default,\n item = event.item && event.item.cursor || null;\n return value && user === value.user && item == value.item ? value : {\n user: user,\n item: item\n };\n }); // when cursor signal updates, set visible cursor\n\n view.add(null, function (_) {\n let user = _.cursor,\n item = this.value;\n\n if (!isString(user)) {\n item = user.item;\n user = user.user;\n }\n\n setCursor(view, user && user !== Default ? user : item || user);\n return item;\n }, {\n cursor: cursor\n });\n}\nfunction setCursor(view, cursor) {\n const el = view.globalCursor() ? typeof document !== 'undefined' && document.body : view.container();\n\n if (el) {\n return cursor == null ? el.style.removeProperty('cursor') : el.style.cursor = cursor;\n }\n}\n\nfunction dataref(view, name) {\n var data = view._runtime.data;\n\n if (!hasOwnProperty(data, name)) {\n error('Unrecognized data set: ' + name);\n }\n\n return data[name];\n}\nfunction data(name, values) {\n return arguments.length < 2 ? dataref(this, name).values.value : change.call(this, name, changeset().remove(truthy).insert(values));\n}\nfunction change(name, changes) {\n if (!isChangeSet(changes)) {\n error('Second argument to changes must be a changeset.');\n }\n\n const dataset = dataref(this, name);\n dataset.modified = true;\n return this.pulse(dataset.input, changes);\n}\nfunction insert(name, _) {\n return change.call(this, name, changeset().insert(_));\n}\nfunction remove(name, _) {\n return change.call(this, name, changeset().remove(_));\n}\n\nfunction width(view) {\n var padding = view.padding();\n return Math.max(0, view._viewWidth + padding.left + padding.right);\n}\nfunction height(view) {\n var padding = view.padding();\n return Math.max(0, view._viewHeight + padding.top + padding.bottom);\n}\nfunction offset(view) {\n var padding = view.padding(),\n origin = view._origin;\n return [padding.left + origin[0], padding.top + origin[1]];\n}\nfunction resizeRenderer(view) {\n var origin = offset(view),\n w = width(view),\n h = height(view);\n\n view._renderer.background(view.background());\n\n view._renderer.resize(w, h, origin);\n\n view._handler.origin(origin);\n\n view._resizeListeners.forEach(handler => {\n try {\n handler(w, h);\n } catch (error) {\n view.error(error);\n }\n });\n}\n\n/**\n * Extend an event with additional view-specific methods.\n * Adds a new property ('vega') to an event that provides a number\n * of methods for querying information about the current interaction.\n * The vega object provides the following methods:\n * view - Returns the backing View instance.\n * item - Returns the currently active scenegraph item (if any).\n * group - Returns the currently active scenegraph group (if any).\n * This method accepts a single string-typed argument indicating the name\n * of the desired parent group. The scenegraph will be traversed from\n * the item up towards the root to search for a matching group. If no\n * argument is provided the enclosing group for the active item is\n * returned, unless the item it itself a group, in which case it is\n * returned directly.\n * xy - Returns a two-element array containing the x and y coordinates for\n * mouse or touch events. For touch events, this is based on the first\n * elements in the changedTouches array. This method accepts a single\n * argument: either an item instance or mark name that should serve as\n * the reference coordinate system. If no argument is provided the\n * top-level view coordinate system is assumed.\n * x - Returns the current x-coordinate, accepts the same arguments as xy.\n * y - Returns the current y-coordinate, accepts the same arguments as xy.\n * @param {Event} event - The input event to extend.\n * @param {Item} item - The currently active scenegraph item (if any).\n * @return {Event} - The extended input event.\n */\n\nfunction eventExtend (view, event, item) {\n var r = view._renderer,\n el = r && r.canvas(),\n p,\n e,\n translate;\n\n if (el) {\n translate = offset(view);\n e = event.changedTouches ? event.changedTouches[0] : event;\n p = point(e, el);\n p[0] -= translate[0];\n p[1] -= translate[1];\n }\n\n event.dataflow = view;\n event.item = item;\n event.vega = extension(view, item, p);\n return event;\n}\n\nfunction extension(view, item, point) {\n const itemGroup = item ? item.mark.marktype === 'group' ? item : item.mark.group : null;\n\n function group(name) {\n var g = itemGroup,\n i;\n if (name) for (i = item; i; i = i.mark.group) {\n if (i.mark.name === name) {\n g = i;\n break;\n }\n }\n return g && g.mark && g.mark.interactive ? g : {};\n }\n\n function xy(item) {\n if (!item) return point;\n if (isString(item)) item = group(item);\n const p = point.slice();\n\n while (item) {\n p[0] -= item.x || 0;\n p[1] -= item.y || 0;\n item = item.mark && item.mark.group;\n }\n\n return p;\n }\n\n return {\n view: constant(view),\n item: constant(item || {}),\n group: group,\n xy: xy,\n x: item => xy(item)[0],\n y: item => xy(item)[1]\n };\n}\n\nconst VIEW = 'view',\n TIMER = 'timer',\n WINDOW = 'window',\n NO_TRAP = {\n trap: false\n};\n/**\n * Initialize event handling configuration.\n * @param {object} config - The configuration settings.\n * @return {object}\n */\n\nfunction initializeEventConfig(config) {\n const events = extend({\n defaults: {}\n }, config);\n\n const unpack = (obj, keys) => {\n keys.forEach(k => {\n if (isArray(obj[k])) obj[k] = toSet(obj[k]);\n });\n };\n\n unpack(events.defaults, ['prevent', 'allow']);\n unpack(events, ['view', 'window', 'selector']);\n return events;\n}\nfunction trackEventListener(view, sources, type, handler) {\n view._eventListeners.push({\n type: type,\n sources: array(sources),\n handler: handler\n });\n}\n\nfunction prevent(view, type) {\n var def = view._eventConfig.defaults,\n prevent = def.prevent,\n allow = def.allow;\n return prevent === false || allow === true ? false : prevent === true || allow === false ? true : prevent ? prevent[type] : allow ? !allow[type] : view.preventDefault();\n}\n\nfunction permit(view, key, type) {\n const rule = view._eventConfig && view._eventConfig[key];\n\n if (rule === false || isObject(rule) && !rule[type]) {\n view.warn(`Blocked ${key} ${type} event listener.`);\n return false;\n }\n\n return true;\n}\n/**\n * Create a new event stream from an event source.\n * @param {object} source - The event source to monitor.\n * @param {string} type - The event type.\n * @param {function(object): boolean} [filter] - Event filter function.\n * @return {EventStream}\n */\n\n\nfunction events(source, type, filter) {\n var view = this,\n s = new EventStream(filter),\n send = function (e, item) {\n view.runAsync(null, () => {\n if (source === VIEW && prevent(view, type)) {\n e.preventDefault();\n }\n\n s.receive(eventExtend(view, e, item));\n });\n },\n sources;\n\n if (source === TIMER) {\n if (permit(view, 'timer', type)) {\n view.timer(send, type);\n }\n } else if (source === VIEW) {\n if (permit(view, 'view', type)) {\n // send traps errors, so use {trap: false} option\n view.addEventListener(type, send, NO_TRAP);\n }\n } else {\n if (source === WINDOW) {\n if (permit(view, 'window', type) && typeof window !== 'undefined') {\n sources = [window];\n }\n } else if (typeof document !== 'undefined') {\n if (permit(view, 'selector', type)) {\n sources = document.querySelectorAll(source);\n }\n }\n\n if (!sources) {\n view.warn('Can not resolve event source: ' + source);\n } else {\n for (var i = 0, n = sources.length; i < n; ++i) {\n sources[i].addEventListener(type, send);\n }\n\n trackEventListener(view, sources, type, send);\n }\n }\n\n return s;\n}\n\nfunction itemFilter(event) {\n return event.item;\n}\n\nfunction markTarget(event) {\n // grab upstream collector feeding the mark operator\n return event.item.mark.source;\n}\n\nfunction invoke(name) {\n return function (_, event) {\n return event.vega.view().changeset().encode(event.item, name);\n };\n}\n\nfunction hover (hoverSet, leaveSet) {\n hoverSet = [hoverSet || 'hover'];\n leaveSet = [leaveSet || 'update', hoverSet[0]]; // invoke hover set upon mouseover\n\n this.on(this.events('view', 'mouseover', itemFilter), markTarget, invoke(hoverSet)); // invoke leave set upon mouseout\n\n this.on(this.events('view', 'mouseout', itemFilter), markTarget, invoke(leaveSet));\n return this;\n}\n\n/**\n * Finalize a View instance that is being removed.\n * Cancel any running timers.\n * Remove all external event listeners.\n * Remove any currently displayed tooltip.\n */\nfunction finalize () {\n var tooltip = this._tooltip,\n timers = this._timers,\n listeners = this._eventListeners,\n n,\n m,\n e;\n n = timers.length;\n\n while (--n >= 0) {\n timers[n].stop();\n }\n\n n = listeners.length;\n\n while (--n >= 0) {\n e = listeners[n];\n m = e.sources.length;\n\n while (--m >= 0) {\n e.sources[m].removeEventListener(e.type, e.handler);\n }\n }\n\n if (tooltip) {\n tooltip.call(this, this._handler, null, null, null);\n }\n\n return this;\n}\n\nfunction element (tag, attr, text) {\n const el = document.createElement(tag);\n\n for (const key in attr) el.setAttribute(key, attr[key]);\n\n if (text != null) el.textContent = text;\n return el;\n}\n\nconst BindClass = 'vega-bind',\n NameClass = 'vega-bind-name',\n RadioClass = 'vega-bind-radio';\n/**\n * Bind a signal to an external HTML input element. The resulting two-way\n * binding will propagate input changes to signals, and propagate signal\n * changes to the input element state. If this view instance has no parent\n * element, we assume the view is headless and no bindings are created.\n * @param {Element|string} el - The parent DOM element to which the input\n * element should be appended as a child. If string-valued, this argument\n * will be treated as a CSS selector. If null or undefined, the parent\n * element of this view will be used as the element.\n * @param {object} param - The binding parameters which specify the signal\n * to bind to, the input element type, and type-specific configuration.\n * @return {View} - This view instance.\n */\n\nfunction bind (view, el, binding) {\n if (!el) return;\n const param = binding.param;\n let bind = binding.state;\n\n if (!bind) {\n bind = binding.state = {\n elements: null,\n active: false,\n set: null,\n update: value => {\n if (value != view.signal(param.signal)) {\n view.runAsync(null, () => {\n bind.source = true;\n view.signal(param.signal, value);\n });\n }\n }\n };\n\n if (param.debounce) {\n bind.update = debounce(param.debounce, bind.update);\n }\n }\n\n const create = param.input == null && param.element ? target : generate;\n create(bind, el, param, view);\n\n if (!bind.active) {\n view.on(view._signals[param.signal], null, () => {\n bind.source ? bind.source = false : bind.set(view.signal(param.signal));\n });\n bind.active = true;\n }\n\n return bind;\n}\n/**\n * Bind the signal to an external EventTarget.\n */\n\nfunction target(bind, node, param, view) {\n const type = param.event || 'input';\n\n const handler = () => bind.update(node.value); // initialize signal value to external input value\n\n\n view.signal(param.signal, node.value); // listen for changes on the element\n\n node.addEventListener(type, handler); // register with view, so we can remove it upon finalization\n\n trackEventListener(view, node, type, handler); // propagate change to element\n\n bind.set = value => {\n node.value = value;\n node.dispatchEvent(event(type));\n };\n}\n\nfunction event(type) {\n return typeof Event !== 'undefined' ? new Event(type) : {\n type\n };\n}\n/**\n * Generate an HTML input form element and bind it to a signal.\n */\n\n\nfunction generate(bind, el, param, view) {\n const value = view.signal(param.signal);\n const div = element('div', {\n 'class': BindClass\n });\n const wrapper = param.input === 'radio' ? div : div.appendChild(element('label'));\n wrapper.appendChild(element('span', {\n 'class': NameClass\n }, param.name || param.signal));\n el.appendChild(div);\n let input = form;\n\n switch (param.input) {\n case 'checkbox':\n input = checkbox;\n break;\n\n case 'select':\n input = select;\n break;\n\n case 'radio':\n input = radio;\n break;\n\n case 'range':\n input = range;\n break;\n }\n\n input(bind, wrapper, param, value);\n}\n/**\n * Generates an arbitrary input form element.\n * The input type is controlled via user-provided parameters.\n */\n\n\nfunction form(bind, el, param, value) {\n const node = element('input');\n\n for (const key in param) {\n if (key !== 'signal' && key !== 'element') {\n node.setAttribute(key === 'input' ? 'type' : key, param[key]);\n }\n }\n\n node.setAttribute('name', param.signal);\n node.value = value;\n el.appendChild(node);\n node.addEventListener('input', () => bind.update(node.value));\n bind.elements = [node];\n\n bind.set = value => node.value = value;\n}\n/**\n * Generates a checkbox input element.\n */\n\n\nfunction checkbox(bind, el, param, value) {\n const attr = {\n type: 'checkbox',\n name: param.signal\n };\n if (value) attr.checked = true;\n const node = element('input', attr);\n el.appendChild(node);\n node.addEventListener('change', () => bind.update(node.checked));\n bind.elements = [node];\n\n bind.set = value => node.checked = !!value || null;\n}\n/**\n * Generates a selection list input element.\n */\n\n\nfunction select(bind, el, param, value) {\n const node = element('select', {\n name: param.signal\n }),\n labels = param.labels || [];\n param.options.forEach((option, i) => {\n const attr = {\n value: option\n };\n if (valuesEqual(option, value)) attr.selected = true;\n node.appendChild(element('option', attr, (labels[i] || option) + ''));\n });\n el.appendChild(node);\n node.addEventListener('change', () => {\n bind.update(param.options[node.selectedIndex]);\n });\n bind.elements = [node];\n\n bind.set = value => {\n for (let i = 0, n = param.options.length; i < n; ++i) {\n if (valuesEqual(param.options[i], value)) {\n node.selectedIndex = i;\n return;\n }\n }\n };\n}\n/**\n * Generates a radio button group.\n */\n\n\nfunction radio(bind, el, param, value) {\n const group = element('span', {\n 'class': RadioClass\n }),\n labels = param.labels || [];\n el.appendChild(group);\n bind.elements = param.options.map((option, i) => {\n const attr = {\n type: 'radio',\n name: param.signal,\n value: option\n };\n if (valuesEqual(option, value)) attr.checked = true;\n const input = element('input', attr);\n input.addEventListener('change', () => bind.update(option));\n const label = element('label', {}, (labels[i] || option) + '');\n label.prepend(input);\n group.appendChild(label);\n return input;\n });\n\n bind.set = value => {\n const nodes = bind.elements,\n n = nodes.length;\n\n for (let i = 0; i < n; ++i) {\n if (valuesEqual(nodes[i].value, value)) nodes[i].checked = true;\n }\n };\n}\n/**\n * Generates a slider input element.\n */\n\n\nfunction range(bind, el, param, value) {\n value = value !== undefined ? value : (+param.max + +param.min) / 2;\n const max = param.max != null ? param.max : Math.max(100, +value) || 100,\n min = param.min || Math.min(0, max, +value) || 0,\n step = param.step || tickStep(min, max, 100);\n const node = element('input', {\n type: 'range',\n name: param.signal,\n min: min,\n max: max,\n step: step\n });\n node.value = value;\n const span = element('span', {}, +value);\n el.appendChild(node);\n el.appendChild(span);\n\n const update = () => {\n span.textContent = node.value;\n bind.update(+node.value);\n }; // subscribe to both input and change\n\n\n node.addEventListener('input', update);\n node.addEventListener('change', update);\n bind.elements = [node];\n\n bind.set = value => {\n node.value = value;\n span.textContent = value;\n };\n}\n\nfunction valuesEqual(a, b) {\n return a === b || a + '' === b + '';\n}\n\nfunction initializeRenderer (view, r, el, constructor, scaleFactor, opt) {\n r = r || new constructor(view.loader());\n return r.initialize(el, width(view), height(view), offset(view), scaleFactor, opt).background(view.background());\n}\n\nfunction trap (view, fn) {\n return !fn ? null : function () {\n try {\n fn.apply(this, arguments);\n } catch (error) {\n view.error(error);\n }\n };\n}\n\nfunction initializeHandler (view, prevHandler, el, constructor) {\n // instantiate scenegraph handler\n const handler = new constructor(view.loader(), trap(view, view.tooltip())).scene(view.scenegraph().root).initialize(el, offset(view), view); // transfer event handlers\n\n if (prevHandler) {\n prevHandler.handlers().forEach(h => {\n handler.on(h.type, h.handler);\n });\n }\n\n return handler;\n}\n\nfunction initialize (el, elBind) {\n const view = this,\n type = view._renderType,\n config = view._eventConfig.bind,\n module = renderModule(type); // containing dom element\n\n el = view._el = el ? lookup(view, el, true) : null; // initialize aria attributes\n\n initializeAria(view); // select appropriate renderer & handler\n\n if (!module) view.error('Unrecognized renderer type: ' + type);\n const Handler = module.handler || CanvasHandler,\n Renderer = el ? module.renderer : module.headless; // initialize renderer and input handler\n\n view._renderer = !Renderer ? null : initializeRenderer(view, view._renderer, el, Renderer);\n view._handler = initializeHandler(view, view._handler, el, Handler);\n view._redraw = true; // initialize signal bindings\n\n if (el && config !== 'none') {\n elBind = elBind ? view._elBind = lookup(view, elBind, true) : el.appendChild(element('form', {\n 'class': 'vega-bindings'\n }));\n\n view._bind.forEach(_ => {\n if (_.param.element && config !== 'container') {\n _.element = lookup(view, _.param.element, !!_.param.input);\n }\n });\n\n view._bind.forEach(_ => {\n bind(view, _.element || elBind, _);\n });\n }\n\n return view;\n}\n\nfunction lookup(view, el, clear) {\n if (typeof el === 'string') {\n if (typeof document !== 'undefined') {\n el = document.querySelector(el);\n\n if (!el) {\n view.error('Signal bind element not found: ' + el);\n return null;\n }\n } else {\n view.error('DOM document instance not found.');\n return null;\n }\n }\n\n if (el && clear) {\n try {\n el.innerHTML = '';\n } catch (e) {\n el = null;\n view.error(e);\n }\n }\n\n return el;\n}\n\nconst number = _ => +_ || 0;\n\nconst paddingObject = _ => ({\n top: _,\n bottom: _,\n left: _,\n right: _\n});\n\nfunction padding (_) {\n return isObject(_) ? {\n top: number(_.top),\n bottom: number(_.bottom),\n left: number(_.left),\n right: number(_.right)\n } : paddingObject(number(_));\n}\n\n/**\n * Render the current scene in a headless fashion.\n * This method is asynchronous, returning a Promise instance.\n * @return {Promise} - A Promise that resolves to a renderer.\n */\n\nasync function renderHeadless (view, type, scaleFactor, opt) {\n const module = renderModule(type),\n ctr = module && module.headless;\n if (!ctr) error('Unrecognized renderer type: ' + type);\n await view.runAsync();\n return initializeRenderer(view, null, null, ctr, scaleFactor, opt).renderAsync(view._scenegraph.root);\n}\n\n/**\n * Produce an image URL for the visualization. Depending on the type\n * parameter, the generated URL contains data for either a PNG or SVG image.\n * The URL can be used (for example) to download images of the visualization.\n * This method is asynchronous, returning a Promise instance.\n * @param {string} type - The image type. One of 'svg', 'png' or 'canvas'.\n * The 'canvas' and 'png' types are synonyms for a PNG image.\n * @return {Promise} - A promise that resolves to an image URL.\n */\n\nasync function renderToImageURL (type, scaleFactor) {\n if (type !== RenderType.Canvas && type !== RenderType.SVG && type !== RenderType.PNG) {\n error('Unrecognized image type: ' + type);\n }\n\n const r = await renderHeadless(this, type, scaleFactor);\n return type === RenderType.SVG ? toBlobURL(r.svg(), 'image/svg+xml') : r.canvas().toDataURL('image/png');\n}\n\nfunction toBlobURL(data, mime) {\n const blob = new Blob([data], {\n type: mime\n });\n return window.URL.createObjectURL(blob);\n}\n\n/**\n * Produce a Canvas instance containing a rendered visualization.\n * This method is asynchronous, returning a Promise instance.\n * @return {Promise} - A promise that resolves to a Canvas instance.\n */\n\nasync function renderToCanvas (scaleFactor, opt) {\n const r = await renderHeadless(this, RenderType.Canvas, scaleFactor, opt);\n return r.canvas();\n}\n\n/**\n * Produce a rendered SVG string of the visualization.\n * This method is asynchronous, returning a Promise instance.\n * @return {Promise} - A promise that resolves to an SVG string.\n */\n\nasync function renderToSVG (scaleFactor) {\n const r = await renderHeadless(this, RenderType.SVG, scaleFactor);\n return r.svg();\n}\n\nfunction runtime (view, spec, expr) {\n return context(view, transforms, functionContext, expr).parse(spec);\n}\n\nfunction scale(name) {\n var scales = this._runtime.scales;\n\n if (!hasOwnProperty(scales, name)) {\n error('Unrecognized scale or projection: ' + name);\n }\n\n return scales[name].value;\n}\n\nvar Width = 'width',\n Height = 'height',\n Padding = 'padding',\n Skip = {\n skip: true\n};\nfunction viewWidth(view, width) {\n var a = view.autosize(),\n p = view.padding();\n return width - (a && a.contains === Padding ? p.left + p.right : 0);\n}\nfunction viewHeight(view, height) {\n var a = view.autosize(),\n p = view.padding();\n return height - (a && a.contains === Padding ? p.top + p.bottom : 0);\n}\nfunction initializeResize(view) {\n var s = view._signals,\n w = s[Width],\n h = s[Height],\n p = s[Padding];\n\n function resetSize() {\n view._autosize = view._resize = 1;\n } // respond to width signal\n\n\n view._resizeWidth = view.add(null, _ => {\n view._width = _.size;\n view._viewWidth = viewWidth(view, _.size);\n resetSize();\n }, {\n size: w\n }); // respond to height signal\n\n view._resizeHeight = view.add(null, _ => {\n view._height = _.size;\n view._viewHeight = viewHeight(view, _.size);\n resetSize();\n }, {\n size: h\n }); // respond to padding signal\n\n const resizePadding = view.add(null, resetSize, {\n pad: p\n }); // set rank to run immediately after source signal\n\n view._resizeWidth.rank = w.rank + 1;\n view._resizeHeight.rank = h.rank + 1;\n resizePadding.rank = p.rank + 1;\n}\nfunction resizeView(viewWidth, viewHeight, width, height, origin, auto) {\n this.runAfter(view => {\n let rerun = 0; // reset autosize flag\n\n view._autosize = 0; // width value changed: update signal, skip resize op\n\n if (view.width() !== width) {\n rerun = 1;\n view.signal(Width, width, Skip); // set width, skip update calc\n\n view._resizeWidth.skip(true); // skip width resize handler\n\n } // height value changed: update signal, skip resize op\n\n\n if (view.height() !== height) {\n rerun = 1;\n view.signal(Height, height, Skip); // set height, skip update calc\n\n view._resizeHeight.skip(true); // skip height resize handler\n\n } // view width changed: update view property, set resize flag\n\n\n if (view._viewWidth !== viewWidth) {\n view._resize = 1;\n view._viewWidth = viewWidth;\n } // view height changed: update view property, set resize flag\n\n\n if (view._viewHeight !== viewHeight) {\n view._resize = 1;\n view._viewHeight = viewHeight;\n } // origin changed: update view property, set resize flag\n\n\n if (view._origin[0] !== origin[0] || view._origin[1] !== origin[1]) {\n view._resize = 1;\n view._origin = origin;\n } // run dataflow on width/height signal change\n\n\n if (rerun) view.run('enter');\n if (auto) view.runAfter(v => v.resize());\n }, false, 1);\n}\n\n/**\n * Get the current view state, consisting of signal values and/or data sets.\n * @param {object} [options] - Options flags indicating which state to export.\n * If unspecified, all signals and data sets will be exported.\n * @param {function(string, Operator):boolean} [options.signals] - Optional\n * predicate function for testing if a signal should be included in the\n * exported state. If unspecified, all signals will be included, except for\n * those named 'parent' or those which refer to a Transform value.\n * @param {function(string, object):boolean} [options.data] - Optional\n * predicate function for testing if a data set's input should be included\n * in the exported state. If unspecified, all data sets that have been\n * explicitly modified will be included.\n * @param {boolean} [options.recurse=true] - Flag indicating if the exported\n * state should recursively include state from group mark sub-contexts.\n * @return {object} - An object containing the exported state values.\n */\n\nfunction getState(options) {\n return this._runtime.getState(options || {\n data: dataTest,\n signals: signalTest,\n recurse: true\n });\n}\n\nfunction dataTest(name, data) {\n return data.modified && isArray(data.input.value) && name.indexOf('_:vega:_');\n}\n\nfunction signalTest(name, op) {\n return !(name === 'parent' || op instanceof transforms.proxy);\n}\n/**\n * Sets the current view state and updates the view by invoking run.\n * @param {object} state - A state object containing signal and/or\n * data set values, following the format used by the getState method.\n * @return {View} - This view instance.\n */\n\n\nfunction setState(state) {\n this.runAsync(null, v => {\n v._trigger = false;\n\n v._runtime.setState(state);\n }, v => {\n v._trigger = true;\n });\n return this;\n}\n\nfunction timer (callback, delay) {\n function tick(elapsed) {\n callback({\n timestamp: Date.now(),\n elapsed: elapsed\n });\n }\n\n this._timers.push(interval(tick, delay));\n}\n\nfunction defaultTooltip (handler, event, item, value) {\n const el = handler.element();\n if (el) el.setAttribute('title', formatTooltip(value));\n}\n\nfunction formatTooltip(value) {\n return value == null ? '' : isArray(value) ? formatArray(value) : isObject(value) && !isDate(value) ? formatObject(value) : value + '';\n}\n\nfunction formatObject(obj) {\n return Object.keys(obj).map(key => {\n const v = obj[key];\n return key + ': ' + (isArray(v) ? formatArray(v) : formatValue(v));\n }).join('\\n');\n}\n\nfunction formatArray(value) {\n return '[' + value.map(formatValue).join(', ') + ']';\n}\n\nfunction formatValue(value) {\n return isArray(value) ? '[\\u2026]' : isObject(value) && !isDate(value) ? '{\\u2026}' : value;\n}\n\n/**\n * Create a new View instance from a Vega dataflow runtime specification.\n * The generated View will not immediately be ready for display. Callers\n * should also invoke the initialize method (e.g., to set the parent\n * DOM element in browser-based deployment) and then invoke the run\n * method to evaluate the dataflow graph. Rendering will automatically\n * be performed upon dataflow runs.\n * @constructor\n * @param {object} spec - The Vega dataflow runtime specification.\n */\n\nfunction View(spec, options) {\n const view = this;\n options = options || {};\n Dataflow.call(view);\n if (options.loader) view.loader(options.loader);\n if (options.logger) view.logger(options.logger);\n if (options.logLevel != null) view.logLevel(options.logLevel);\n\n if (options.locale || spec.locale) {\n const loc = extend({}, spec.locale, options.locale);\n view.locale(locale(loc.number, loc.time));\n }\n\n view._el = null;\n view._elBind = null;\n view._renderType = options.renderer || RenderType.Canvas;\n view._scenegraph = new Scenegraph();\n const root = view._scenegraph.root; // initialize renderer, handler and event management\n\n view._renderer = null;\n view._tooltip = options.tooltip || defaultTooltip, view._redraw = true;\n view._handler = new CanvasHandler().scene(root);\n view._globalCursor = false;\n view._preventDefault = false;\n view._timers = [];\n view._eventListeners = [];\n view._resizeListeners = []; // initialize event configuration\n\n view._eventConfig = initializeEventConfig(spec.eventConfig);\n view.globalCursor(view._eventConfig.globalCursor); // initialize dataflow graph\n\n const ctx = runtime(view, spec, options.expr);\n view._runtime = ctx;\n view._signals = ctx.signals;\n view._bind = (spec.bindings || []).map(_ => ({\n state: null,\n param: extend({}, _)\n })); // initialize scenegraph\n\n if (ctx.root) ctx.root.set(root);\n root.source = ctx.data.root.input;\n view.pulse(ctx.data.root.input, view.changeset().insert(root.items)); // initialize view size\n\n view._width = view.width();\n view._height = view.height();\n view._viewWidth = viewWidth(view, view._width);\n view._viewHeight = viewHeight(view, view._height);\n view._origin = [0, 0];\n view._resize = 0;\n view._autosize = 1;\n initializeResize(view); // initialize background color\n\n background(view); // initialize cursor\n\n cursor(view); // initialize view description\n\n view.description(spec.description); // initialize hover proessing, if requested\n\n if (options.hover) view.hover(); // initialize DOM container(s) and renderer\n\n if (options.container) view.initialize(options.container, options.bind);\n}\n\nfunction lookupSignal(view, name) {\n return hasOwnProperty(view._signals, name) ? view._signals[name] : error('Unrecognized signal name: ' + stringValue(name));\n}\n\nfunction findOperatorHandler(op, handler) {\n const h = (op._targets || []).filter(op => op._update && op._update.handler === handler);\n return h.length ? h[0] : null;\n}\n\nfunction addOperatorListener(view, name, op, handler) {\n let h = findOperatorHandler(op, handler);\n\n if (!h) {\n h = trap(view, () => handler(name, op.value));\n h.handler = handler;\n view.on(op, null, h);\n }\n\n return view;\n}\n\nfunction removeOperatorListener(view, op, handler) {\n const h = findOperatorHandler(op, handler);\n if (h) op._targets.remove(h);\n return view;\n}\n\ninherits(View, Dataflow, {\n // -- DATAFLOW / RENDERING ----\n async evaluate(encode, prerun, postrun) {\n // evaluate dataflow and prerun\n await Dataflow.prototype.evaluate.call(this, encode, prerun); // render as needed\n\n if (this._redraw || this._resize) {\n try {\n if (this._renderer) {\n if (this._resize) {\n this._resize = 0;\n resizeRenderer(this);\n }\n\n await this._renderer.renderAsync(this._scenegraph.root);\n }\n\n this._redraw = false;\n } catch (e) {\n this.error(e);\n }\n } // evaluate postrun\n\n\n if (postrun) asyncCallback(this, postrun);\n return this;\n },\n\n dirty(item) {\n this._redraw = true;\n this._renderer && this._renderer.dirty(item);\n },\n\n // -- GET / SET ----\n description(text) {\n if (arguments.length) {\n const desc = text != null ? text + '' : null;\n if (desc !== this._desc) ariaLabel(this._el, this._desc = desc);\n return this;\n }\n\n return this._desc;\n },\n\n container() {\n return this._el;\n },\n\n scenegraph() {\n return this._scenegraph;\n },\n\n origin() {\n return this._origin.slice();\n },\n\n signal(name, value, options) {\n const op = lookupSignal(this, name);\n return arguments.length === 1 ? op.value : this.update(op, value, options);\n },\n\n width(_) {\n return arguments.length ? this.signal('width', _) : this.signal('width');\n },\n\n height(_) {\n return arguments.length ? this.signal('height', _) : this.signal('height');\n },\n\n padding(_) {\n return arguments.length ? this.signal('padding', padding(_)) : padding(this.signal('padding'));\n },\n\n autosize(_) {\n return arguments.length ? this.signal('autosize', _) : this.signal('autosize');\n },\n\n background(_) {\n return arguments.length ? this.signal('background', _) : this.signal('background');\n },\n\n renderer(type) {\n if (!arguments.length) return this._renderType;\n if (!renderModule(type)) error('Unrecognized renderer type: ' + type);\n\n if (type !== this._renderType) {\n this._renderType = type;\n\n this._resetRenderer();\n }\n\n return this;\n },\n\n tooltip(handler) {\n if (!arguments.length) return this._tooltip;\n\n if (handler !== this._tooltip) {\n this._tooltip = handler;\n\n this._resetRenderer();\n }\n\n return this;\n },\n\n loader(loader) {\n if (!arguments.length) return this._loader;\n\n if (loader !== this._loader) {\n Dataflow.prototype.loader.call(this, loader);\n\n this._resetRenderer();\n }\n\n return this;\n },\n\n resize() {\n // set flag to perform autosize\n this._autosize = 1; // touch autosize signal to ensure top-level ViewLayout runs\n\n return this.touch(lookupSignal(this, 'autosize'));\n },\n\n _resetRenderer() {\n if (this._renderer) {\n this._renderer = null;\n this.initialize(this._el, this._elBind);\n }\n },\n\n // -- SIZING ----\n _resizeView: resizeView,\n\n // -- EVENT HANDLING ----\n addEventListener(type, handler, options) {\n let callback = handler;\n\n if (!(options && options.trap === false)) {\n // wrap callback in error handler\n callback = trap(this, handler);\n callback.raw = handler;\n }\n\n this._handler.on(type, callback);\n\n return this;\n },\n\n removeEventListener(type, handler) {\n var handlers = this._handler.handlers(type),\n i = handlers.length,\n h,\n t; // search registered handlers, remove if match found\n\n\n while (--i >= 0) {\n t = handlers[i].type;\n h = handlers[i].handler;\n\n if (type === t && (handler === h || handler === h.raw)) {\n this._handler.off(t, h);\n\n break;\n }\n }\n\n return this;\n },\n\n addResizeListener(handler) {\n const l = this._resizeListeners;\n\n if (l.indexOf(handler) < 0) {\n // add handler if it isn't already registered\n // note: error trapping handled elsewhere, so\n // no need to wrap handlers here\n l.push(handler);\n }\n\n return this;\n },\n\n removeResizeListener(handler) {\n var l = this._resizeListeners,\n i = l.indexOf(handler);\n\n if (i >= 0) {\n l.splice(i, 1);\n }\n\n return this;\n },\n\n addSignalListener(name, handler) {\n return addOperatorListener(this, name, lookupSignal(this, name), handler);\n },\n\n removeSignalListener(name, handler) {\n return removeOperatorListener(this, lookupSignal(this, name), handler);\n },\n\n addDataListener(name, handler) {\n return addOperatorListener(this, name, dataref(this, name).values, handler);\n },\n\n removeDataListener(name, handler) {\n return removeOperatorListener(this, dataref(this, name).values, handler);\n },\n\n globalCursor(_) {\n if (arguments.length) {\n if (this._globalCursor !== !!_) {\n const prev = setCursor(this, null); // clear previous cursor\n\n this._globalCursor = !!_;\n if (prev) setCursor(this, prev); // swap cursor\n }\n\n return this;\n } else {\n return this._globalCursor;\n }\n },\n\n preventDefault(_) {\n if (arguments.length) {\n this._preventDefault = _;\n return this;\n } else {\n return this._preventDefault;\n }\n },\n\n timer,\n events,\n finalize,\n hover,\n // -- DATA ----\n data,\n change,\n insert,\n remove,\n // -- SCALES --\n scale,\n // -- INITIALIZATION ----\n initialize,\n // -- HEADLESS RENDERING ----\n toImageURL: renderToImageURL,\n toCanvas: renderToCanvas,\n toSVG: renderToSVG,\n // -- SAVE / RESTORE STATE ----\n getState,\n setState\n});\n\nexport { View };\n","import {Timer, now} from \"./timer.js\";\n\nexport default function(callback, delay, time) {\n var t = new Timer, total = delay;\n if (delay == null) return t.restart(callback, delay, time), t;\n t._restart = t.restart;\n t.restart = function(callback, delay, time) {\n delay = +delay, time = time == null ? now() : +time;\n t._restart(function tick(elapsed) {\n elapsed += total;\n t._restart(tick, total += delay, time);\n callback(elapsed);\n }, delay, time);\n }\n t.restart(callback, delay, time);\n return t;\n}\n","const VIEW = 'view',\n LBRACK = '[',\n RBRACK = ']',\n LBRACE = '{',\n RBRACE = '}',\n COLON = ':',\n COMMA = ',',\n NAME = '@',\n GT = '>',\n ILLEGAL = /[[\\]{}]/,\n DEFAULT_MARKS = {\n '*': 1,\n arc: 1,\n area: 1,\n group: 1,\n image: 1,\n line: 1,\n path: 1,\n rect: 1,\n rule: 1,\n shape: 1,\n symbol: 1,\n text: 1,\n trail: 1\n};\nlet DEFAULT_SOURCE, MARKS;\n/**\n * Parse an event selector string.\n * Returns an array of event stream definitions.\n */\n\nfunction eventSelector (selector, source, marks) {\n DEFAULT_SOURCE = source || VIEW;\n MARKS = marks || DEFAULT_MARKS;\n return parseMerge(selector.trim()).map(parseSelector);\n}\n\nfunction isMarkType(type) {\n return MARKS[type];\n}\n\nfunction find(s, i, endChar, pushChar, popChar) {\n const n = s.length;\n let count = 0,\n c;\n\n for (; i < n; ++i) {\n c = s[i];\n if (!count && c === endChar) return i;else if (popChar && popChar.indexOf(c) >= 0) --count;else if (pushChar && pushChar.indexOf(c) >= 0) ++count;\n }\n\n return i;\n}\n\nfunction parseMerge(s) {\n const output = [],\n n = s.length;\n let start = 0,\n i = 0;\n\n while (i < n) {\n i = find(s, i, COMMA, LBRACK + LBRACE, RBRACK + RBRACE);\n output.push(s.substring(start, i).trim());\n start = ++i;\n }\n\n if (output.length === 0) {\n throw 'Empty event selector: ' + s;\n }\n\n return output;\n}\n\nfunction parseSelector(s) {\n return s[0] === '[' ? parseBetween(s) : parseStream(s);\n}\n\nfunction parseBetween(s) {\n const n = s.length;\n let i = 1,\n b;\n i = find(s, i, RBRACK, LBRACK, RBRACK);\n\n if (i === n) {\n throw 'Empty between selector: ' + s;\n }\n\n b = parseMerge(s.substring(1, i));\n\n if (b.length !== 2) {\n throw 'Between selector must have two elements: ' + s;\n }\n\n s = s.slice(i + 1).trim();\n\n if (s[0] !== GT) {\n throw 'Expected \\'>\\' after between selector: ' + s;\n }\n\n b = b.map(parseSelector);\n const stream = parseSelector(s.slice(1).trim());\n\n if (stream.between) {\n return {\n between: b,\n stream: stream\n };\n } else {\n stream.between = b;\n }\n\n return stream;\n}\n\nfunction parseStream(s) {\n const stream = {\n source: DEFAULT_SOURCE\n },\n source = [];\n let throttle = [0, 0],\n markname = 0,\n start = 0,\n n = s.length,\n i = 0,\n j,\n filter; // extract throttle from end\n\n if (s[n - 1] === RBRACE) {\n i = s.lastIndexOf(LBRACE);\n\n if (i >= 0) {\n try {\n throttle = parseThrottle(s.substring(i + 1, n - 1));\n } catch (e) {\n throw 'Invalid throttle specification: ' + s;\n }\n\n s = s.slice(0, i).trim();\n n = s.length;\n } else throw 'Unmatched right brace: ' + s;\n\n i = 0;\n }\n\n if (!n) throw s; // set name flag based on first char\n\n if (s[0] === NAME) markname = ++i; // extract first part of multi-part stream selector\n\n j = find(s, i, COLON);\n\n if (j < n) {\n source.push(s.substring(start, j).trim());\n start = i = ++j;\n } // extract remaining part of stream selector\n\n\n i = find(s, i, LBRACK);\n\n if (i === n) {\n source.push(s.substring(start, n).trim());\n } else {\n source.push(s.substring(start, i).trim());\n filter = [];\n start = ++i;\n if (start === n) throw 'Unmatched left bracket: ' + s;\n } // extract filters\n\n\n while (i < n) {\n i = find(s, i, RBRACK);\n if (i === n) throw 'Unmatched left bracket: ' + s;\n filter.push(s.substring(start, i).trim());\n if (i < n - 1 && s[++i] !== LBRACK) throw 'Expected left bracket: ' + s;\n start = ++i;\n } // marshall event stream specification\n\n\n if (!(n = source.length) || ILLEGAL.test(source[n - 1])) {\n throw 'Invalid event selector: ' + s;\n }\n\n if (n > 1) {\n stream.type = source[1];\n\n if (markname) {\n stream.markname = source[0].slice(1);\n } else if (isMarkType(source[0])) {\n stream.marktype = source[0];\n } else {\n stream.source = source[0];\n }\n } else {\n stream.type = source[0];\n }\n\n if (stream.type.slice(-1) === '!') {\n stream.consume = true;\n stream.type = stream.type.slice(0, -1);\n }\n\n if (filter != null) stream.filter = filter;\n if (throttle[0]) stream.throttle = throttle[0];\n if (throttle[1]) stream.debounce = throttle[1];\n return stream;\n}\n\nfunction parseThrottle(s) {\n const a = s.split(COMMA);\n if (!s.length || a.length > 2) throw s;\n return a.map(_ => {\n const x = +_;\n if (x !== x) throw s;\n return x;\n });\n}\n\nexport { eventSelector as parseSelector };\n","import { isObject, isArray, extend, hasOwnProperty, array, stringValue, peek, isString, error, splitAccessPath, mergeConfig } from 'vega-util';\nimport { parseExpression } from 'vega-functions';\nimport { parseSelector } from 'vega-event-selector';\nimport { isValidScaleType, isDiscrete, isQuantile, isDiscretizing, isContinuous } from 'vega-scale';\nimport { definition as definition$1 } from 'vega-dataflow';\n\nfunction parseAutosize (spec) {\n return isObject(spec) ? spec : {\n type: spec || 'pad'\n };\n}\n\nconst number = _ => +_ || 0;\n\nconst paddingObject = _ => ({\n top: _,\n bottom: _,\n left: _,\n right: _\n});\n\nfunction parsePadding (spec) {\n return !isObject(spec) ? paddingObject(number(spec)) : spec.signal ? spec : {\n top: number(spec.top),\n bottom: number(spec.bottom),\n left: number(spec.left),\n right: number(spec.right)\n };\n}\n\nconst encoder = _ => isObject(_) && !isArray(_) ? extend({}, _) : {\n value: _\n};\nfunction addEncode(object, name, value, set) {\n if (value != null) {\n const isEncoder = isObject(value) && !isArray(value) || isArray(value) && value.length && isObject(value[0]); // Always assign signal to update, even if the signal is from the enter block\n\n if (isEncoder) {\n object.update[name] = value;\n } else {\n object[set || 'enter'][name] = {\n value: value\n };\n }\n\n return 1;\n } else {\n return 0;\n }\n}\nfunction addEncoders(object, enter, update) {\n for (const name in enter) {\n addEncode(object, name, enter[name]);\n }\n\n for (const name in update) {\n addEncode(object, name, update[name], 'update');\n }\n}\nfunction extendEncode(encode, extra, skip) {\n for (const name in extra) {\n if (skip && hasOwnProperty(skip, name)) continue;\n encode[name] = extend(encode[name] || {}, extra[name]);\n }\n\n return encode;\n}\nfunction has(key, encode) {\n return encode && (encode.enter && encode.enter[key] || encode.update && encode.update[key]);\n}\n\nconst MarkRole = 'mark';\nconst FrameRole = 'frame';\nconst ScopeRole = 'scope';\nconst AxisRole = 'axis';\nconst AxisDomainRole = 'axis-domain';\nconst AxisGridRole = 'axis-grid';\nconst AxisLabelRole = 'axis-label';\nconst AxisTickRole = 'axis-tick';\nconst AxisTitleRole = 'axis-title';\nconst LegendRole = 'legend';\nconst LegendBandRole = 'legend-band';\nconst LegendEntryRole = 'legend-entry';\nconst LegendGradientRole = 'legend-gradient';\nconst LegendLabelRole = 'legend-label';\nconst LegendSymbolRole = 'legend-symbol';\nconst LegendTitleRole = 'legend-title';\nconst TitleRole = 'title';\nconst TitleTextRole = 'title-text';\nconst TitleSubtitleRole = 'title-subtitle';\n\nfunction applyDefaults (encode, type, role, style, config) {\n const defaults = {},\n enter = {};\n let update, key, skip, props; // if text mark, apply global lineBreak settings (#2370)\n\n key = 'lineBreak';\n\n if (type === 'text' && config[key] != null && !has(key, encode)) {\n applyDefault(defaults, key, config[key]);\n } // ignore legend and axis roles\n\n\n if (role == 'legend' || String(role).startsWith('axis')) {\n role = null;\n } // resolve mark config\n\n\n props = role === FrameRole ? config.group : role === MarkRole ? extend({}, config.mark, config[type]) : null;\n\n for (key in props) {\n // do not apply defaults if relevant fields are defined\n skip = has(key, encode) || (key === 'fill' || key === 'stroke') && (has('fill', encode) || has('stroke', encode));\n if (!skip) applyDefault(defaults, key, props[key]);\n } // resolve styles, apply with increasing precedence\n\n\n array(style).forEach(name => {\n const props = config.style && config.style[name];\n\n for (const key in props) {\n if (!has(key, encode)) {\n applyDefault(defaults, key, props[key]);\n }\n }\n });\n encode = extend({}, encode); // defensive copy\n\n for (key in defaults) {\n props = defaults[key];\n\n if (props.signal) {\n (update = update || {})[key] = props;\n } else {\n enter[key] = props;\n }\n }\n\n encode.enter = extend(enter, encode.enter);\n if (update) encode.update = extend(update, encode.update);\n return encode;\n}\n\nfunction applyDefault(defaults, key, value) {\n defaults[key] = value && value.signal ? {\n signal: value.signal\n } : {\n value: value\n };\n}\n\nconst scaleRef = scale => isString(scale) ? stringValue(scale) : scale.signal ? `(${scale.signal})` : field(scale);\n\nfunction entry$1(enc) {\n if (enc.gradient != null) {\n return gradient(enc);\n }\n\n let value = enc.signal ? `(${enc.signal})` : enc.color ? color(enc.color) : enc.field != null ? field(enc.field) : enc.value !== undefined ? stringValue(enc.value) : undefined;\n\n if (enc.scale != null) {\n value = scale(enc, value);\n }\n\n if (value === undefined) {\n value = null;\n }\n\n if (enc.exponent != null) {\n value = `pow(${value},${property(enc.exponent)})`;\n }\n\n if (enc.mult != null) {\n value += `*${property(enc.mult)}`;\n }\n\n if (enc.offset != null) {\n value += `+${property(enc.offset)}`;\n }\n\n if (enc.round) {\n value = `round(${value})`;\n }\n\n return value;\n}\n\nconst _color = (type, x, y, z) => `(${type}(${[x, y, z].map(entry$1).join(',')})+'')`;\n\nfunction color(enc) {\n return enc.c ? _color('hcl', enc.h, enc.c, enc.l) : enc.h || enc.s ? _color('hsl', enc.h, enc.s, enc.l) : enc.l || enc.a ? _color('lab', enc.l, enc.a, enc.b) : enc.r || enc.g || enc.b ? _color('rgb', enc.r, enc.g, enc.b) : null;\n}\n\nfunction gradient(enc) {\n // map undefined to null; expression lang does not allow undefined\n const args = [enc.start, enc.stop, enc.count].map(_ => _ == null ? null : stringValue(_)); // trim null inputs from the end\n\n while (args.length && peek(args) == null) args.pop();\n\n args.unshift(scaleRef(enc.gradient));\n return `gradient(${args.join(',')})`;\n}\n\nfunction property(property) {\n return isObject(property) ? '(' + entry$1(property) + ')' : property;\n}\n\nfunction field(ref) {\n return resolveField(isObject(ref) ? ref : {\n datum: ref\n });\n}\n\nfunction resolveField(ref) {\n let object, level, field;\n\n if (ref.signal) {\n object = 'datum';\n field = ref.signal;\n } else if (ref.group || ref.parent) {\n level = Math.max(1, ref.level || 1);\n object = 'item';\n\n while (level-- > 0) {\n object += '.mark.group';\n }\n\n if (ref.parent) {\n field = ref.parent;\n object += '.datum';\n } else {\n field = ref.group;\n }\n } else if (ref.datum) {\n object = 'datum';\n field = ref.datum;\n } else {\n error('Invalid field reference: ' + stringValue(ref));\n }\n\n if (!ref.signal) {\n field = isString(field) ? splitAccessPath(field).map(stringValue).join('][') : resolveField(field);\n }\n\n return object + '[' + field + ']';\n}\n\nfunction scale(enc, value) {\n const scale = scaleRef(enc.scale);\n\n if (enc.range != null) {\n // pull value from scale range\n value = `lerp(_range(${scale}), ${+enc.range})`;\n } else {\n // run value through scale and/or pull scale bandwidth\n if (value !== undefined) value = `_scale(${scale}, ${value})`;\n\n if (enc.band) {\n value = (value ? value + '+' : '') + `_bandwidth(${scale})` + (+enc.band === 1 ? '' : '*' + property(enc.band));\n\n if (enc.extra) {\n // include logic to handle extraneous elements\n value = `(datum.extra ? _scale(${scale}, datum.extra.value) : ${value})`;\n }\n }\n\n if (value == null) value = '0';\n }\n\n return value;\n}\n\nfunction rule (enc) {\n let code = '';\n enc.forEach(rule => {\n const value = entry$1(rule);\n code += rule.test ? `(${rule.test})?${value}:` : value;\n }); // if no else clause, terminate with null (#1366)\n\n if (peek(code) === ':') {\n code += 'null';\n }\n\n return code;\n}\n\nfunction parseEncode (encode, type, role, style, scope, params) {\n const enc = {};\n params = params || {};\n params.encoders = {\n $encode: enc\n };\n encode = applyDefaults(encode, type, role, style, scope.config);\n\n for (const key in encode) {\n enc[key] = parseBlock(encode[key], type, params, scope);\n }\n\n return params;\n}\n\nfunction parseBlock(block, marktype, params, scope) {\n const channels = {},\n fields = {};\n\n for (const name in block) {\n if (block[name] != null) {\n // skip any null entries\n channels[name] = parse$1(expr(block[name]), scope, params, fields);\n }\n }\n\n return {\n $expr: {\n marktype,\n channels\n },\n $fields: Object.keys(fields),\n $output: Object.keys(block)\n };\n}\n\nfunction expr(enc) {\n return isArray(enc) ? rule(enc) : entry$1(enc);\n}\n\nfunction parse$1(code, scope, params, fields) {\n const expr = parseExpression(code, scope);\n expr.$fields.forEach(name => fields[name] = 1);\n extend(params, expr.$params);\n return expr.$expr;\n}\n\nconst OUTER = 'outer',\n OUTER_INVALID = ['value', 'update', 'init', 'react', 'bind'];\n\nfunction outerError(prefix, name) {\n error(prefix + ' for \"outer\" push: ' + stringValue(name));\n}\n\nfunction parseSignal (signal, scope) {\n const name = signal.name;\n\n if (signal.push === OUTER) {\n // signal must already be defined, raise error if not\n if (!scope.signals[name]) outerError('No prior signal definition', name); // signal push must not use properties reserved for standard definition\n\n OUTER_INVALID.forEach(prop => {\n if (signal[prop] !== undefined) outerError('Invalid property ', prop);\n });\n } else {\n // define a new signal in the current scope\n const op = scope.addSignal(name, signal.value);\n if (signal.react === false) op.react = false;\n if (signal.bind) scope.addBinding(name, signal.bind);\n }\n}\n\nfunction Entry(type, value, params, parent) {\n this.id = -1;\n this.type = type;\n this.value = value;\n this.params = params;\n if (parent) this.parent = parent;\n}\nfunction entry(type, value, params, parent) {\n return new Entry(type, value, params, parent);\n}\nfunction operator(value, params) {\n return entry('operator', value, params);\n} // -----\n\nfunction ref(op) {\n const ref = {\n $ref: op.id\n }; // if operator not yet registered, cache ref to resolve later\n\n if (op.id < 0) (op.refs = op.refs || []).push(ref);\n return ref;\n}\nfunction fieldRef$1(field, name) {\n return name ? {\n $field: field,\n $name: name\n } : {\n $field: field\n };\n}\nconst keyFieldRef = fieldRef$1('key');\nfunction compareRef(fields, orders) {\n return {\n $compare: fields,\n $order: orders\n };\n}\nfunction keyRef(fields, flat) {\n const ref = {\n $key: fields\n };\n if (flat) ref.$flat = true;\n return ref;\n} // -----\n\nconst Ascending = 'ascending';\nconst Descending = 'descending';\nfunction sortKey(sort) {\n return !isObject(sort) ? '' : (sort.order === Descending ? '-' : '+') + aggrField(sort.op, sort.field);\n}\nfunction aggrField(op, field) {\n return (op && op.signal ? '$' + op.signal : op || '') + (op && field ? '_' : '') + (field && field.signal ? '$' + field.signal : field || '');\n} // -----\n\nconst Scope$1 = 'scope';\nconst View = 'view';\nfunction isSignal(_) {\n return _ && _.signal;\n}\nfunction isExpr$1(_) {\n return _ && _.expr;\n}\nfunction hasSignal(_) {\n if (isSignal(_)) return true;\n if (isObject(_)) for (const key in _) {\n if (hasSignal(_[key])) return true;\n }\n return false;\n}\nfunction value(specValue, defaultValue) {\n return specValue != null ? specValue : defaultValue;\n}\nfunction deref(v) {\n return v && v.signal || v;\n}\n\nconst Timer = 'timer';\nfunction parseStream(stream, scope) {\n const method = stream.merge ? mergeStream : stream.stream ? nestedStream : stream.type ? eventStream : error('Invalid stream specification: ' + stringValue(stream));\n return method(stream, scope);\n}\n\nfunction eventSource(source) {\n return source === Scope$1 ? View : source || View;\n}\n\nfunction mergeStream(stream, scope) {\n const list = stream.merge.map(s => parseStream(s, scope)),\n entry = streamParameters({\n merge: list\n }, stream, scope);\n return scope.addStream(entry).id;\n}\n\nfunction nestedStream(stream, scope) {\n const id = parseStream(stream.stream, scope),\n entry = streamParameters({\n stream: id\n }, stream, scope);\n return scope.addStream(entry).id;\n}\n\nfunction eventStream(stream, scope) {\n let id;\n\n if (stream.type === Timer) {\n id = scope.event(Timer, stream.throttle);\n stream = {\n between: stream.between,\n filter: stream.filter\n };\n } else {\n id = scope.event(eventSource(stream.source), stream.type);\n }\n\n const entry = streamParameters({\n stream: id\n }, stream, scope);\n return Object.keys(entry).length === 1 ? id : scope.addStream(entry).id;\n}\n\nfunction streamParameters(entry, stream, scope) {\n let param = stream.between;\n\n if (param) {\n if (param.length !== 2) {\n error('Stream \"between\" parameter must have 2 entries: ' + stringValue(stream));\n }\n\n entry.between = [parseStream(param[0], scope), parseStream(param[1], scope)];\n }\n\n param = stream.filter ? [].concat(stream.filter) : [];\n\n if (stream.marktype || stream.markname || stream.markrole) {\n // add filter for mark type, name and/or role\n param.push(filterMark(stream.marktype, stream.markname, stream.markrole));\n }\n\n if (stream.source === Scope$1) {\n // add filter to limit events from sub-scope only\n param.push('inScope(event.item)');\n }\n\n if (param.length) {\n entry.filter = parseExpression('(' + param.join(')&&(') + ')', scope).$expr;\n }\n\n if ((param = stream.throttle) != null) {\n entry.throttle = +param;\n }\n\n if ((param = stream.debounce) != null) {\n entry.debounce = +param;\n }\n\n if (stream.consume) {\n entry.consume = true;\n }\n\n return entry;\n}\n\nfunction filterMark(type, name, role) {\n const item = 'event.item';\n return item + (type && type !== '*' ? '&&' + item + '.mark.marktype===\\'' + type + '\\'' : '') + (role ? '&&' + item + '.mark.role===\\'' + role + '\\'' : '') + (name ? '&&' + item + '.mark.name===\\'' + name + '\\'' : '');\n}\n\nconst OP_VALUE_EXPR = {\n code: '_.$value',\n ast: {\n type: 'Identifier',\n value: 'value'\n }\n};\nfunction parseUpdate (spec, scope, target) {\n const encode = spec.encode,\n entry = {\n target: target\n };\n let events = spec.events,\n update = spec.update,\n sources = [];\n\n if (!events) {\n error('Signal update missing events specification.');\n } // interpret as an event selector string\n\n\n if (isString(events)) {\n events = parseSelector(events, scope.isSubscope() ? Scope$1 : View);\n } // separate event streams from signal updates\n\n\n events = array(events).filter(s => s.signal || s.scale ? (sources.push(s), 0) : 1); // merge internal operator listeners\n\n if (sources.length > 1) {\n sources = [mergeSources(sources)];\n } // merge event streams, include as source\n\n\n if (events.length) {\n sources.push(events.length > 1 ? {\n merge: events\n } : events[0]);\n }\n\n if (encode != null) {\n if (update) error('Signal encode and update are mutually exclusive.');\n update = 'encode(item(),' + stringValue(encode) + ')';\n } // resolve update value\n\n\n entry.update = isString(update) ? parseExpression(update, scope) : update.expr != null ? parseExpression(update.expr, scope) : update.value != null ? update.value : update.signal != null ? {\n $expr: OP_VALUE_EXPR,\n $params: {\n $value: scope.signalRef(update.signal)\n }\n } : error('Invalid signal update specification.');\n\n if (spec.force) {\n entry.options = {\n force: true\n };\n }\n\n sources.forEach(source => scope.addUpdate(extend(streamSource(source, scope), entry)));\n}\n\nfunction streamSource(stream, scope) {\n return {\n source: stream.signal ? scope.signalRef(stream.signal) : stream.scale ? scope.scaleRef(stream.scale) : parseStream(stream, scope)\n };\n}\n\nfunction mergeSources(sources) {\n return {\n signal: '[' + sources.map(s => s.scale ? 'scale(\"' + s.scale + '\")' : s.signal) + ']'\n };\n}\n\nfunction parseSignalUpdates (signal, scope) {\n const op = scope.getSignal(signal.name);\n let expr = signal.update;\n\n if (signal.init) {\n if (expr) {\n error('Signals can not include both init and update expressions.');\n } else {\n expr = signal.init;\n op.initonly = true;\n }\n }\n\n if (expr) {\n expr = parseExpression(expr, scope);\n op.update = expr.$expr;\n op.params = expr.$params;\n }\n\n if (signal.on) {\n signal.on.forEach(_ => parseUpdate(_, scope, op.id));\n }\n}\n\nconst transform = name => (params, value, parent) => entry(name, value, params || undefined, parent);\n\nconst Aggregate = transform('aggregate');\nconst AxisTicks = transform('axisticks');\nconst Bound = transform('bound');\nconst Collect = transform('collect');\nconst Compare = transform('compare');\nconst DataJoin = transform('datajoin');\nconst Encode = transform('encode');\nconst Expression = transform('expression');\nconst Facet = transform('facet');\nconst Field = transform('field');\nconst Key = transform('key');\nconst LegendEntries = transform('legendentries');\nconst Load = transform('load');\nconst Mark = transform('mark');\nconst MultiExtent = transform('multiextent');\nconst MultiValues = transform('multivalues');\nconst Overlap = transform('overlap');\nconst Params = transform('params');\nconst PreFacet = transform('prefacet');\nconst Projection = transform('projection');\nconst Proxy = transform('proxy');\nconst Relay = transform('relay');\nconst Render = transform('render');\nconst Scale = transform('scale');\nconst Sieve = transform('sieve');\nconst SortItems = transform('sortitems');\nconst ViewLayout = transform('viewlayout');\nconst Values = transform('values');\n\nlet FIELD_REF_ID = 0;\nconst MULTIDOMAIN_SORT_OPS = {\n min: 'min',\n max: 'max',\n count: 'sum'\n};\nfunction initScale(spec, scope) {\n const type = spec.type || 'linear';\n\n if (!isValidScaleType(type)) {\n error('Unrecognized scale type: ' + stringValue(type));\n }\n\n scope.addScale(spec.name, {\n type,\n domain: undefined\n });\n}\nfunction parseScale(spec, scope) {\n const params = scope.getScale(spec.name).params;\n let key;\n params.domain = parseScaleDomain(spec.domain, spec, scope);\n\n if (spec.range != null) {\n params.range = parseScaleRange(spec, scope, params);\n }\n\n if (spec.interpolate != null) {\n parseScaleInterpolate(spec.interpolate, params);\n }\n\n if (spec.nice != null) {\n params.nice = parseScaleNice(spec.nice);\n }\n\n if (spec.bins != null) {\n params.bins = parseScaleBins(spec.bins, scope);\n }\n\n for (key in spec) {\n if (hasOwnProperty(params, key) || key === 'name') continue;\n params[key] = parseLiteral(spec[key], scope);\n }\n}\n\nfunction parseLiteral(v, scope) {\n return !isObject(v) ? v : v.signal ? scope.signalRef(v.signal) : error('Unsupported object: ' + stringValue(v));\n}\n\nfunction parseArray(v, scope) {\n return v.signal ? scope.signalRef(v.signal) : v.map(v => parseLiteral(v, scope));\n}\n\nfunction dataLookupError(name) {\n error('Can not find data set: ' + stringValue(name));\n} // -- SCALE DOMAIN ----\n\n\nfunction parseScaleDomain(domain, spec, scope) {\n if (!domain) {\n if (spec.domainMin != null || spec.domainMax != null) {\n error('No scale domain defined for domainMin/domainMax to override.');\n }\n\n return; // default domain\n }\n\n return domain.signal ? scope.signalRef(domain.signal) : (isArray(domain) ? explicitDomain : domain.fields ? multipleDomain : singularDomain)(domain, spec, scope);\n}\n\nfunction explicitDomain(domain, spec, scope) {\n return domain.map(v => parseLiteral(v, scope));\n}\n\nfunction singularDomain(domain, spec, scope) {\n const data = scope.getData(domain.data);\n if (!data) dataLookupError(domain.data);\n return isDiscrete(spec.type) ? data.valuesRef(scope, domain.field, parseSort(domain.sort, false)) : isQuantile(spec.type) ? data.domainRef(scope, domain.field) : data.extentRef(scope, domain.field);\n}\n\nfunction multipleDomain(domain, spec, scope) {\n const data = domain.data,\n fields = domain.fields.reduce((dom, d) => {\n d = isString(d) ? {\n data: data,\n field: d\n } : isArray(d) || d.signal ? fieldRef(d, scope) : d;\n dom.push(d);\n return dom;\n }, []);\n return (isDiscrete(spec.type) ? ordinalMultipleDomain : isQuantile(spec.type) ? quantileMultipleDomain : numericMultipleDomain)(domain, scope, fields);\n}\n\nfunction fieldRef(data, scope) {\n const name = '_:vega:_' + FIELD_REF_ID++,\n coll = Collect({});\n\n if (isArray(data)) {\n coll.value = {\n $ingest: data\n };\n } else if (data.signal) {\n const code = 'setdata(' + stringValue(name) + ',' + data.signal + ')';\n coll.params.input = scope.signalRef(code);\n }\n\n scope.addDataPipeline(name, [coll, Sieve({})]);\n return {\n data: name,\n field: 'data'\n };\n}\n\nfunction ordinalMultipleDomain(domain, scope, fields) {\n const sort = parseSort(domain.sort, true);\n let a, v; // get value counts for each domain field\n\n const counts = fields.map(f => {\n const data = scope.getData(f.data);\n if (!data) dataLookupError(f.data);\n return data.countsRef(scope, f.field, sort);\n }); // aggregate the results from each domain field\n\n const p = {\n groupby: keyFieldRef,\n pulse: counts\n };\n\n if (sort) {\n a = sort.op || 'count';\n v = sort.field ? aggrField(a, sort.field) : 'count';\n p.ops = [MULTIDOMAIN_SORT_OPS[a]];\n p.fields = [scope.fieldRef(v)];\n p.as = [v];\n }\n\n a = scope.add(Aggregate(p)); // collect aggregate output\n\n const c = scope.add(Collect({\n pulse: ref(a)\n })); // extract values for combined domain\n\n v = scope.add(Values({\n field: keyFieldRef,\n sort: scope.sortRef(sort),\n pulse: ref(c)\n }));\n return ref(v);\n}\n\nfunction parseSort(sort, multidomain) {\n if (sort) {\n if (!sort.field && !sort.op) {\n if (isObject(sort)) sort.field = 'key';else sort = {\n field: 'key'\n };\n } else if (!sort.field && sort.op !== 'count') {\n error('No field provided for sort aggregate op: ' + sort.op);\n } else if (multidomain && sort.field) {\n if (sort.op && !MULTIDOMAIN_SORT_OPS[sort.op]) {\n error('Multiple domain scales can not be sorted using ' + sort.op);\n }\n }\n }\n\n return sort;\n}\n\nfunction quantileMultipleDomain(domain, scope, fields) {\n // get value arrays for each domain field\n const values = fields.map(f => {\n const data = scope.getData(f.data);\n if (!data) dataLookupError(f.data);\n return data.domainRef(scope, f.field);\n }); // combine value arrays\n\n return ref(scope.add(MultiValues({\n values: values\n })));\n}\n\nfunction numericMultipleDomain(domain, scope, fields) {\n // get extents for each domain field\n const extents = fields.map(f => {\n const data = scope.getData(f.data);\n if (!data) dataLookupError(f.data);\n return data.extentRef(scope, f.field);\n }); // combine extents\n\n return ref(scope.add(MultiExtent({\n extents: extents\n })));\n} // -- SCALE BINS -----\n\n\nfunction parseScaleBins(v, scope) {\n return v.signal || isArray(v) ? parseArray(v, scope) : scope.objectProperty(v);\n} // -- SCALE NICE -----\n\n\nfunction parseScaleNice(nice) {\n return isObject(nice) ? {\n interval: parseLiteral(nice.interval),\n step: parseLiteral(nice.step)\n } : parseLiteral(nice);\n} // -- SCALE INTERPOLATION -----\n\n\nfunction parseScaleInterpolate(interpolate, params) {\n params.interpolate = parseLiteral(interpolate.type || interpolate);\n\n if (interpolate.gamma != null) {\n params.interpolateGamma = parseLiteral(interpolate.gamma);\n }\n} // -- SCALE RANGE -----\n\n\nfunction parseScaleRange(spec, scope, params) {\n const config = scope.config.range;\n let range = spec.range;\n\n if (range.signal) {\n return scope.signalRef(range.signal);\n } else if (isString(range)) {\n if (config && hasOwnProperty(config, range)) {\n spec = extend({}, spec, {\n range: config[range]\n });\n return parseScaleRange(spec, scope, params);\n } else if (range === 'width') {\n range = [0, {\n signal: 'width'\n }];\n } else if (range === 'height') {\n range = isDiscrete(spec.type) ? [0, {\n signal: 'height'\n }] : [{\n signal: 'height'\n }, 0];\n } else {\n error('Unrecognized scale range value: ' + stringValue(range));\n }\n } else if (range.scheme) {\n params.scheme = isArray(range.scheme) ? parseArray(range.scheme, scope) : parseLiteral(range.scheme, scope);\n if (range.extent) params.schemeExtent = parseArray(range.extent, scope);\n if (range.count) params.schemeCount = parseLiteral(range.count, scope);\n return;\n } else if (range.step) {\n params.rangeStep = parseLiteral(range.step, scope);\n return;\n } else if (isDiscrete(spec.type) && !isArray(range)) {\n return parseScaleDomain(range, spec, scope);\n } else if (!isArray(range)) {\n error('Unsupported range type: ' + stringValue(range));\n }\n\n return range.map(v => (isArray(v) ? parseArray : parseLiteral)(v, scope));\n}\n\nfunction parseProjection (proj, scope) {\n const config = scope.config.projection || {},\n params = {};\n\n for (const name in proj) {\n if (name === 'name') continue;\n params[name] = parseParameter$1(proj[name], name, scope);\n } // apply projection defaults from config\n\n\n for (const name in config) {\n if (params[name] == null) {\n params[name] = parseParameter$1(config[name], name, scope);\n }\n }\n\n scope.addProjection(proj.name, params);\n}\n\nfunction parseParameter$1(_, name, scope) {\n return isArray(_) ? _.map(_ => parseParameter$1(_, name, scope)) : !isObject(_) ? _ : _.signal ? scope.signalRef(_.signal) : name === 'fit' ? _ : error('Unsupported parameter object: ' + stringValue(_));\n}\n\nconst Top = 'top';\nconst Left = 'left';\nconst Right = 'right';\nconst Bottom = 'bottom';\nconst Center = 'center';\nconst Vertical = 'vertical';\nconst Start = 'start';\nconst Middle = 'middle';\nconst End = 'end';\nconst Index = 'index';\nconst Label = 'label';\nconst Offset = 'offset';\nconst Perc = 'perc';\nconst Perc2 = 'perc2';\nconst Value = 'value';\nconst GuideLabelStyle = 'guide-label';\nconst GuideTitleStyle = 'guide-title';\nconst GroupTitleStyle = 'group-title';\nconst GroupSubtitleStyle = 'group-subtitle';\nconst Symbols = 'symbol';\nconst Gradient = 'gradient';\nconst Discrete = 'discrete';\nconst Size = 'size';\nconst Shape = 'shape';\nconst Fill = 'fill';\nconst Stroke = 'stroke';\nconst StrokeWidth = 'strokeWidth';\nconst StrokeDash = 'strokeDash';\nconst Opacity = 'opacity'; // Encoding channels supported by legends\n// In priority order of 'canonical' scale\n\nconst LegendScales = [Size, Shape, Fill, Stroke, StrokeWidth, StrokeDash, Opacity];\nconst Skip = {\n name: 1,\n style: 1,\n interactive: 1\n};\nconst zero = {\n value: 0\n};\nconst one = {\n value: 1\n};\n\nconst GroupMark = 'group';\nconst RectMark = 'rect';\nconst RuleMark = 'rule';\nconst SymbolMark = 'symbol';\nconst TextMark = 'text';\n\nfunction guideGroup (mark) {\n mark.type = GroupMark;\n mark.interactive = mark.interactive || false;\n return mark;\n}\n\nfunction lookup(spec, config) {\n const _ = (name, dflt) => value(spec[name], value(config[name], dflt));\n\n _.isVertical = s => Vertical === value(spec.direction, config.direction || (s ? config.symbolDirection : config.gradientDirection));\n\n _.gradientLength = () => value(spec.gradientLength, config.gradientLength || config.gradientWidth);\n\n _.gradientThickness = () => value(spec.gradientThickness, config.gradientThickness || config.gradientHeight);\n\n _.entryColumns = () => value(spec.columns, value(config.columns, +_.isVertical(true)));\n\n return _;\n}\nfunction getEncoding(name, encode) {\n const v = encode && (encode.update && encode.update[name] || encode.enter && encode.enter[name]);\n return v && v.signal ? v : v ? v.value : null;\n}\nfunction getStyle(name, scope, style) {\n const s = scope.config.style[style];\n return s && s[name];\n}\nfunction anchorExpr(s, e, m) {\n return `item.anchor === '${Start}' ? ${s} : item.anchor === '${End}' ? ${e} : ${m}`;\n}\nconst alignExpr$1 = anchorExpr(stringValue(Left), stringValue(Right), stringValue(Center));\nfunction tickBand(_) {\n const v = _('tickBand');\n\n let offset = _('tickOffset'),\n band,\n extra;\n\n if (!v) {\n // if no tick band entry, fall back on other properties\n band = _('bandPosition');\n extra = _('tickExtra');\n } else if (v.signal) {\n // if signal, augment code to interpret values\n band = {\n signal: `(${v.signal}) === 'extent' ? 1 : 0.5`\n };\n extra = {\n signal: `(${v.signal}) === 'extent'`\n };\n\n if (!isObject(offset)) {\n offset = {\n signal: `(${v.signal}) === 'extent' ? 0 : ${offset}`\n };\n }\n } else if (v === 'extent') {\n // if constant, simply set values\n band = 1;\n extra = true;\n offset = 0;\n } else {\n band = 0.5;\n extra = false;\n }\n\n return {\n extra,\n band,\n offset\n };\n}\nfunction extendOffset(value, offset) {\n return !offset ? value : !value ? offset : !isObject(value) ? {\n value,\n offset\n } : Object.assign({}, value, {\n offset: extendOffset(value.offset, offset)\n });\n}\n\nfunction guideMark (mark, extras) {\n if (extras) {\n mark.name = extras.name;\n mark.style = extras.style || mark.style;\n mark.interactive = !!extras.interactive;\n mark.encode = extendEncode(mark.encode, extras, Skip);\n } else {\n mark.interactive = false;\n }\n\n return mark;\n}\n\nfunction legendGradient (spec, scale, config, userEncode) {\n const _ = lookup(spec, config),\n vertical = _.isVertical(),\n thickness = _.gradientThickness(),\n length = _.gradientLength();\n\n let enter, start, stop, width, height;\n\n if (vertical) {\n start = [0, 1];\n stop = [0, 0];\n width = thickness;\n height = length;\n } else {\n start = [0, 0];\n stop = [1, 0];\n width = length;\n height = thickness;\n }\n\n const encode = {\n enter: enter = {\n opacity: zero,\n x: zero,\n y: zero,\n width: encoder(width),\n height: encoder(height)\n },\n update: extend({}, enter, {\n opacity: one,\n fill: {\n gradient: scale,\n start: start,\n stop: stop\n }\n }),\n exit: {\n opacity: zero\n }\n };\n addEncoders(encode, {\n stroke: _('gradientStrokeColor'),\n strokeWidth: _('gradientStrokeWidth')\n }, {\n // update\n opacity: _('gradientOpacity')\n });\n return guideMark({\n type: RectMark,\n role: LegendGradientRole,\n encode\n }, userEncode);\n}\n\nfunction legendGradientDiscrete (spec, scale, config, userEncode, dataRef) {\n const _ = lookup(spec, config),\n vertical = _.isVertical(),\n thickness = _.gradientThickness(),\n length = _.gradientLength();\n\n let u,\n v,\n uu,\n vv,\n adjust = '';\n vertical ? (u = 'y', uu = 'y2', v = 'x', vv = 'width', adjust = '1-') : (u = 'x', uu = 'x2', v = 'y', vv = 'height');\n const enter = {\n opacity: zero,\n fill: {\n scale: scale,\n field: Value\n }\n };\n enter[u] = {\n signal: adjust + 'datum.' + Perc,\n mult: length\n };\n enter[v] = zero;\n enter[uu] = {\n signal: adjust + 'datum.' + Perc2,\n mult: length\n };\n enter[vv] = encoder(thickness);\n const encode = {\n enter: enter,\n update: extend({}, enter, {\n opacity: one\n }),\n exit: {\n opacity: zero\n }\n };\n addEncoders(encode, {\n stroke: _('gradientStrokeColor'),\n strokeWidth: _('gradientStrokeWidth')\n }, {\n // update\n opacity: _('gradientOpacity')\n });\n return guideMark({\n type: RectMark,\n role: LegendBandRole,\n key: Value,\n from: dataRef,\n encode\n }, userEncode);\n}\n\nconst alignExpr = `datum.${Perc}<=0?\"${Left}\":datum.${Perc}>=1?\"${Right}\":\"${Center}\"`,\n baselineExpr = `datum.${Perc}<=0?\"${Bottom}\":datum.${Perc}>=1?\"${Top}\":\"${Middle}\"`;\nfunction legendGradientLabels (spec, config, userEncode, dataRef) {\n const _ = lookup(spec, config),\n vertical = _.isVertical(),\n thickness = encoder(_.gradientThickness()),\n length = _.gradientLength();\n\n let overlap = _('labelOverlap'),\n enter,\n update,\n u,\n v,\n adjust = '';\n\n const encode = {\n enter: enter = {\n opacity: zero\n },\n update: update = {\n opacity: one,\n text: {\n field: Label\n }\n },\n exit: {\n opacity: zero\n }\n };\n addEncoders(encode, {\n fill: _('labelColor'),\n fillOpacity: _('labelOpacity'),\n font: _('labelFont'),\n fontSize: _('labelFontSize'),\n fontStyle: _('labelFontStyle'),\n fontWeight: _('labelFontWeight'),\n limit: value(spec.labelLimit, config.gradientLabelLimit)\n });\n\n if (vertical) {\n enter.align = {\n value: 'left'\n };\n enter.baseline = update.baseline = {\n signal: baselineExpr\n };\n u = 'y';\n v = 'x';\n adjust = '1-';\n } else {\n enter.align = update.align = {\n signal: alignExpr\n };\n enter.baseline = {\n value: 'top'\n };\n u = 'x';\n v = 'y';\n }\n\n enter[u] = update[u] = {\n signal: adjust + 'datum.' + Perc,\n mult: length\n };\n enter[v] = update[v] = thickness;\n thickness.offset = value(spec.labelOffset, config.gradientLabelOffset) || 0;\n overlap = overlap ? {\n separation: _('labelSeparation'),\n method: overlap,\n order: 'datum.' + Index\n } : undefined; // type, role, style, key, dataRef, encode, extras\n\n return guideMark({\n type: TextMark,\n role: LegendLabelRole,\n style: GuideLabelStyle,\n key: Value,\n from: dataRef,\n encode,\n overlap\n }, userEncode);\n}\n\nfunction legendSymbolGroups (spec, config, userEncode, dataRef, columns) {\n const _ = lookup(spec, config),\n entries = userEncode.entries,\n interactive = !!(entries && entries.interactive),\n name = entries ? entries.name : undefined,\n height = _('clipHeight'),\n symbolOffset = _('symbolOffset'),\n valueRef = {\n data: 'value'\n },\n xSignal = `(${columns}) ? datum.${Offset} : datum.${Size}`,\n yEncode = height ? encoder(height) : {\n field: Size\n },\n index = `datum.${Index}`,\n ncols = `max(1, ${columns})`;\n\n let encode, enter, update, nrows, sort;\n yEncode.mult = 0.5; // -- LEGEND SYMBOLS --\n\n encode = {\n enter: enter = {\n opacity: zero,\n x: {\n signal: xSignal,\n mult: 0.5,\n offset: symbolOffset\n },\n y: yEncode\n },\n update: update = {\n opacity: one,\n x: enter.x,\n y: enter.y\n },\n exit: {\n opacity: zero\n }\n };\n let baseFill = null,\n baseStroke = null;\n\n if (!spec.fill) {\n baseFill = config.symbolBaseFillColor;\n baseStroke = config.symbolBaseStrokeColor;\n }\n\n addEncoders(encode, {\n fill: _('symbolFillColor', baseFill),\n shape: _('symbolType'),\n size: _('symbolSize'),\n stroke: _('symbolStrokeColor', baseStroke),\n strokeDash: _('symbolDash'),\n strokeDashOffset: _('symbolDashOffset'),\n strokeWidth: _('symbolStrokeWidth')\n }, {\n // update\n opacity: _('symbolOpacity')\n });\n LegendScales.forEach(scale => {\n if (spec[scale]) {\n update[scale] = enter[scale] = {\n scale: spec[scale],\n field: Value\n };\n }\n });\n const symbols = guideMark({\n type: SymbolMark,\n role: LegendSymbolRole,\n key: Value,\n from: valueRef,\n clip: height ? true : undefined,\n encode\n }, userEncode.symbols); // -- LEGEND LABELS --\n\n const labelOffset = encoder(symbolOffset);\n labelOffset.offset = _('labelOffset');\n encode = {\n enter: enter = {\n opacity: zero,\n x: {\n signal: xSignal,\n offset: labelOffset\n },\n y: yEncode\n },\n update: update = {\n opacity: one,\n text: {\n field: Label\n },\n x: enter.x,\n y: enter.y\n },\n exit: {\n opacity: zero\n }\n };\n addEncoders(encode, {\n align: _('labelAlign'),\n baseline: _('labelBaseline'),\n fill: _('labelColor'),\n fillOpacity: _('labelOpacity'),\n font: _('labelFont'),\n fontSize: _('labelFontSize'),\n fontStyle: _('labelFontStyle'),\n fontWeight: _('labelFontWeight'),\n limit: _('labelLimit')\n });\n const labels = guideMark({\n type: TextMark,\n role: LegendLabelRole,\n style: GuideLabelStyle,\n key: Value,\n from: valueRef,\n encode\n }, userEncode.labels); // -- LEGEND ENTRY GROUPS --\n\n encode = {\n enter: {\n noBound: {\n value: !height\n },\n // ignore width/height in bounds calc\n width: zero,\n height: height ? encoder(height) : zero,\n opacity: zero\n },\n exit: {\n opacity: zero\n },\n update: update = {\n opacity: one,\n row: {\n signal: null\n },\n column: {\n signal: null\n }\n }\n }; // annotate and sort groups to ensure correct ordering\n\n if (_.isVertical(true)) {\n nrows = `ceil(item.mark.items.length / ${ncols})`;\n update.row.signal = `${index}%${nrows}`;\n update.column.signal = `floor(${index} / ${nrows})`;\n sort = {\n field: ['row', index]\n };\n } else {\n update.row.signal = `floor(${index} / ${ncols})`;\n update.column.signal = `${index} % ${ncols}`;\n sort = {\n field: index\n };\n } // handle zero column case (implies infinite columns)\n\n\n update.column.signal = `(${columns})?${update.column.signal}:${index}`; // facet legend entries into sub-groups\n\n dataRef = {\n facet: {\n data: dataRef,\n name: 'value',\n groupby: Index\n }\n };\n return guideGroup({\n role: ScopeRole,\n from: dataRef,\n encode: extendEncode(encode, entries, Skip),\n marks: [symbols, labels],\n name,\n interactive,\n sort\n });\n}\nfunction legendSymbolLayout(spec, config) {\n const _ = lookup(spec, config); // layout parameters for legend entries\n\n\n return {\n align: _('gridAlign'),\n columns: _.entryColumns(),\n center: {\n row: true,\n column: false\n },\n padding: {\n row: _('rowPadding'),\n column: _('columnPadding')\n }\n };\n}\n\nconst isL = 'item.orient === \"left\"',\n isR = 'item.orient === \"right\"',\n isLR = `(${isL} || ${isR})`,\n isVG = `datum.vgrad && ${isLR}`,\n baseline = anchorExpr('\"top\"', '\"bottom\"', '\"middle\"'),\n alignFlip = anchorExpr('\"right\"', '\"left\"', '\"center\"'),\n exprAlign = `datum.vgrad && ${isR} ? (${alignFlip}) : (${isLR} && !(datum.vgrad && ${isL})) ? \"left\" : ${alignExpr$1}`,\n exprAnchor = `item._anchor || (${isLR} ? \"middle\" : \"start\")`,\n exprAngle = `${isVG} ? (${isL} ? -90 : 90) : 0`,\n exprBaseline = `${isLR} ? (datum.vgrad ? (${isR} ? \"bottom\" : \"top\") : ${baseline}) : \"top\"`;\nfunction legendTitle (spec, config, userEncode, dataRef) {\n const _ = lookup(spec, config);\n\n const encode = {\n enter: {\n opacity: zero\n },\n update: {\n opacity: one,\n x: {\n field: {\n group: 'padding'\n }\n },\n y: {\n field: {\n group: 'padding'\n }\n }\n },\n exit: {\n opacity: zero\n }\n };\n addEncoders(encode, {\n orient: _('titleOrient'),\n _anchor: _('titleAnchor'),\n anchor: {\n signal: exprAnchor\n },\n angle: {\n signal: exprAngle\n },\n align: {\n signal: exprAlign\n },\n baseline: {\n signal: exprBaseline\n },\n text: spec.title,\n fill: _('titleColor'),\n fillOpacity: _('titleOpacity'),\n font: _('titleFont'),\n fontSize: _('titleFontSize'),\n fontStyle: _('titleFontStyle'),\n fontWeight: _('titleFontWeight'),\n limit: _('titleLimit'),\n lineHeight: _('titleLineHeight')\n }, {\n // require update\n align: _('titleAlign'),\n baseline: _('titleBaseline')\n });\n return guideMark({\n type: TextMark,\n role: LegendTitleRole,\n style: GuideTitleStyle,\n from: dataRef,\n encode\n }, userEncode);\n}\n\nfunction clip (clip, scope) {\n let expr;\n\n if (isObject(clip)) {\n if (clip.signal) {\n expr = clip.signal;\n } else if (clip.path) {\n expr = 'pathShape(' + param(clip.path) + ')';\n } else if (clip.sphere) {\n expr = 'geoShape(' + param(clip.sphere) + ', {type: \"Sphere\"})';\n }\n }\n\n return expr ? scope.signalRef(expr) : !!clip;\n}\n\nfunction param(value) {\n return isObject(value) && value.signal ? value.signal : stringValue(value);\n}\n\nfunction getRole (spec) {\n const role = spec.role || '';\n return !role.indexOf('axis') || !role.indexOf('legend') || !role.indexOf('title') ? role : spec.type === GroupMark ? ScopeRole : role || MarkRole;\n}\n\nfunction definition (spec) {\n return {\n marktype: spec.type,\n name: spec.name || undefined,\n role: spec.role || getRole(spec),\n zindex: +spec.zindex || undefined,\n aria: spec.aria,\n description: spec.description\n };\n}\n\nfunction interactive (spec, scope) {\n return spec && spec.signal ? scope.signalRef(spec.signal) : spec === false ? false : true;\n}\n\n/**\n * Parse a data transform specification.\n */\n\nfunction parseTransform (spec, scope) {\n const def = definition$1(spec.type);\n if (!def) error('Unrecognized transform type: ' + stringValue(spec.type));\n const t = entry(def.type.toLowerCase(), null, parseParameters(def, spec, scope));\n if (spec.signal) scope.addSignal(spec.signal, scope.proxy(t));\n t.metadata = def.metadata || {};\n return t;\n}\n/**\n * Parse all parameters of a data transform.\n */\n\nfunction parseParameters(def, spec, scope) {\n const params = {},\n n = def.params.length;\n\n for (let i = 0; i < n; ++i) {\n const pdef = def.params[i];\n params[pdef.name] = parseParameter(pdef, spec, scope);\n }\n\n return params;\n}\n/**\n * Parse a data transform parameter.\n */\n\n\nfunction parseParameter(def, spec, scope) {\n const type = def.type,\n value = spec[def.name];\n\n if (type === 'index') {\n return parseIndexParameter(def, spec, scope);\n } else if (value === undefined) {\n if (def.required) {\n error('Missing required ' + stringValue(spec.type) + ' parameter: ' + stringValue(def.name));\n }\n\n return;\n } else if (type === 'param') {\n return parseSubParameters(def, spec, scope);\n } else if (type === 'projection') {\n return scope.projectionRef(spec[def.name]);\n }\n\n return def.array && !isSignal(value) ? value.map(v => parameterValue(def, v, scope)) : parameterValue(def, value, scope);\n}\n/**\n * Parse a single parameter value.\n */\n\n\nfunction parameterValue(def, value, scope) {\n const type = def.type;\n\n if (isSignal(value)) {\n return isExpr(type) ? error('Expression references can not be signals.') : isField(type) ? scope.fieldRef(value) : isCompare(type) ? scope.compareRef(value) : scope.signalRef(value.signal);\n } else {\n const expr = def.expr || isField(type);\n return expr && outerExpr(value) ? scope.exprRef(value.expr, value.as) : expr && outerField(value) ? fieldRef$1(value.field, value.as) : isExpr(type) ? parseExpression(value, scope) : isData(type) ? ref(scope.getData(value).values) : isField(type) ? fieldRef$1(value) : isCompare(type) ? scope.compareRef(value) : value;\n }\n}\n/**\n * Parse parameter for accessing an index of another data set.\n */\n\n\nfunction parseIndexParameter(def, spec, scope) {\n if (!isString(spec.from)) {\n error('Lookup \"from\" parameter must be a string literal.');\n }\n\n return scope.getData(spec.from).lookupRef(scope, spec.key);\n}\n/**\n * Parse a parameter that contains one or more sub-parameter objects.\n */\n\n\nfunction parseSubParameters(def, spec, scope) {\n const value = spec[def.name];\n\n if (def.array) {\n if (!isArray(value)) {\n // signals not allowed!\n error('Expected an array of sub-parameters. Instead: ' + stringValue(value));\n }\n\n return value.map(v => parseSubParameter(def, v, scope));\n } else {\n return parseSubParameter(def, value, scope);\n }\n}\n/**\n * Parse a sub-parameter object.\n */\n\n\nfunction parseSubParameter(def, value, scope) {\n const n = def.params.length;\n let pdef; // loop over defs to find matching key\n\n for (let i = 0; i < n; ++i) {\n pdef = def.params[i];\n\n for (const k in pdef.key) {\n if (pdef.key[k] !== value[k]) {\n pdef = null;\n break;\n }\n }\n\n if (pdef) break;\n } // raise error if matching key not found\n\n\n if (!pdef) error('Unsupported parameter: ' + stringValue(value)); // parse params, create Params transform, return ref\n\n const params = extend(parseParameters(pdef, value, scope), pdef.key);\n return ref(scope.add(Params(params)));\n} // -- Utilities -----\n\n\nconst outerExpr = _ => _ && _.expr;\nconst outerField = _ => _ && _.field;\nconst isData = _ => _ === 'data';\nconst isExpr = _ => _ === 'expr';\nconst isField = _ => _ === 'field';\nconst isCompare = _ => _ === 'compare';\n\nfunction parseData$1 (from, group, scope) {\n let facet, key, op, dataRef, parent; // if no source data, generate singleton datum\n\n if (!from) {\n dataRef = ref(scope.add(Collect(null, [{}])));\n } // if faceted, process facet specification\n else if (facet = from.facet) {\n if (!group) error('Only group marks can be faceted.'); // use pre-faceted source data, if available\n\n if (facet.field != null) {\n dataRef = parent = getDataRef(facet, scope);\n } else {\n // generate facet aggregates if no direct data specification\n if (!from.data) {\n op = parseTransform(extend({\n type: 'aggregate',\n groupby: array(facet.groupby)\n }, facet.aggregate), scope);\n op.params.key = scope.keyRef(facet.groupby);\n op.params.pulse = getDataRef(facet, scope);\n dataRef = parent = ref(scope.add(op));\n } else {\n parent = ref(scope.getData(from.data).aggregate);\n }\n\n key = scope.keyRef(facet.groupby, true);\n }\n } // if not yet defined, get source data reference\n\n\n if (!dataRef) {\n dataRef = getDataRef(from, scope);\n }\n\n return {\n key: key,\n pulse: dataRef,\n parent: parent\n };\n}\nfunction getDataRef(from, scope) {\n return from.$ref ? from : from.data && from.data.$ref ? from.data : ref(scope.getData(from.data).output);\n}\n\nfunction DataScope(scope, input, output, values, aggr) {\n this.scope = scope; // parent scope object\n\n this.input = input; // first operator in pipeline (tuple input)\n\n this.output = output; // last operator in pipeline (tuple output)\n\n this.values = values; // operator for accessing tuples (but not tuple flow)\n // last aggregate in transform pipeline\n\n this.aggregate = aggr; // lookup table of field indices\n\n this.index = {};\n}\n\nDataScope.fromEntries = function (scope, entries) {\n const n = entries.length,\n values = entries[n - 1],\n output = entries[n - 2];\n let input = entries[0],\n aggr = null,\n i = 1;\n\n if (input && input.type === 'load') {\n input = entries[1];\n } // add operator entries to this scope, wire up pulse chain\n\n\n scope.add(entries[0]);\n\n for (; i < n; ++i) {\n entries[i].params.pulse = ref(entries[i - 1]);\n scope.add(entries[i]);\n if (entries[i].type === 'aggregate') aggr = entries[i];\n }\n\n return new DataScope(scope, input, output, values, aggr);\n};\n\nfunction fieldKey(field) {\n return isString(field) ? field : null;\n}\n\nfunction addSortField(scope, p, sort) {\n const as = aggrField(sort.op, sort.field);\n let s;\n\n if (p.ops) {\n for (let i = 0, n = p.as.length; i < n; ++i) {\n if (p.as[i] === as) return;\n }\n } else {\n p.ops = ['count'];\n p.fields = [null];\n p.as = ['count'];\n }\n\n if (sort.op) {\n p.ops.push((s = sort.op.signal) ? scope.signalRef(s) : sort.op);\n p.fields.push(scope.fieldRef(sort.field));\n p.as.push(as);\n }\n}\n\nfunction cache(scope, ds, name, optype, field, counts, index) {\n const cache = ds[name] || (ds[name] = {}),\n sort = sortKey(counts);\n let k = fieldKey(field),\n v,\n op;\n\n if (k != null) {\n scope = ds.scope;\n k = k + (sort ? '|' + sort : '');\n v = cache[k];\n }\n\n if (!v) {\n const params = counts ? {\n field: keyFieldRef,\n pulse: ds.countsRef(scope, field, counts)\n } : {\n field: scope.fieldRef(field),\n pulse: ref(ds.output)\n };\n if (sort) params.sort = scope.sortRef(counts);\n op = scope.add(entry(optype, undefined, params));\n if (index) ds.index[field] = op;\n v = ref(op);\n if (k != null) cache[k] = v;\n }\n\n return v;\n}\n\nDataScope.prototype = {\n countsRef(scope, field, sort) {\n const ds = this,\n cache = ds.counts || (ds.counts = {}),\n k = fieldKey(field);\n let v, a, p;\n\n if (k != null) {\n scope = ds.scope;\n v = cache[k];\n }\n\n if (!v) {\n p = {\n groupby: scope.fieldRef(field, 'key'),\n pulse: ref(ds.output)\n };\n if (sort && sort.field) addSortField(scope, p, sort);\n a = scope.add(Aggregate(p));\n v = scope.add(Collect({\n pulse: ref(a)\n }));\n v = {\n agg: a,\n ref: ref(v)\n };\n if (k != null) cache[k] = v;\n } else if (sort && sort.field) {\n addSortField(scope, v.agg.params, sort);\n }\n\n return v.ref;\n },\n\n tuplesRef() {\n return ref(this.values);\n },\n\n extentRef(scope, field) {\n return cache(scope, this, 'extent', 'extent', field, false);\n },\n\n domainRef(scope, field) {\n return cache(scope, this, 'domain', 'values', field, false);\n },\n\n valuesRef(scope, field, sort) {\n return cache(scope, this, 'vals', 'values', field, sort || true);\n },\n\n lookupRef(scope, field) {\n return cache(scope, this, 'lookup', 'tupleindex', field, false);\n },\n\n indataRef(scope, field) {\n return cache(scope, this, 'indata', 'tupleindex', field, true, true);\n }\n\n};\n\nfunction parseFacet (spec, scope, group) {\n const facet = spec.from.facet,\n name = facet.name,\n data = getDataRef(facet, scope);\n let op;\n\n if (!facet.name) {\n error('Facet must have a name: ' + stringValue(facet));\n }\n\n if (!facet.data) {\n error('Facet must reference a data set: ' + stringValue(facet));\n }\n\n if (facet.field) {\n op = scope.add(PreFacet({\n field: scope.fieldRef(facet.field),\n pulse: data\n }));\n } else if (facet.groupby) {\n op = scope.add(Facet({\n key: scope.keyRef(facet.groupby),\n group: ref(scope.proxy(group.parent)),\n pulse: data\n }));\n } else {\n error('Facet must specify groupby or field: ' + stringValue(facet));\n } // initialize facet subscope\n\n\n const subscope = scope.fork(),\n source = subscope.add(Collect()),\n values = subscope.add(Sieve({\n pulse: ref(source)\n }));\n subscope.addData(name, new DataScope(subscope, source, source, values));\n subscope.addSignal('parent', null); // parse faceted subflow\n\n op.params.subflow = {\n $subflow: subscope.parse(spec).toRuntime()\n };\n}\n\nfunction parseSubflow (spec, scope, input) {\n const op = scope.add(PreFacet({\n pulse: input.pulse\n })),\n subscope = scope.fork();\n subscope.add(Sieve());\n subscope.addSignal('parent', null); // parse group mark subflow\n\n op.params.subflow = {\n $subflow: subscope.parse(spec).toRuntime()\n };\n}\n\nfunction parseTrigger (spec, scope, name) {\n const remove = spec.remove,\n insert = spec.insert,\n toggle = spec.toggle,\n modify = spec.modify,\n values = spec.values,\n op = scope.add(operator());\n const update = 'if(' + spec.trigger + ',modify(\"' + name + '\",' + [insert, remove, toggle, modify, values].map(_ => _ == null ? 'null' : _).join(',') + '),0)';\n const expr = parseExpression(update, scope);\n op.update = expr.$expr;\n op.params = expr.$params;\n}\n\nfunction parseMark (spec, scope) {\n const role = getRole(spec),\n group = spec.type === GroupMark,\n facet = spec.from && spec.from.facet,\n overlap = spec.overlap;\n let layout = spec.layout || role === ScopeRole || role === FrameRole,\n ops,\n op,\n store,\n enc,\n name,\n layoutRef,\n boundRef;\n const nested = role === MarkRole || layout || facet; // resolve input data\n\n const input = parseData$1(spec.from, group, scope); // data join to map tuples to visual items\n\n op = scope.add(DataJoin({\n key: input.key || (spec.key ? fieldRef$1(spec.key) : undefined),\n pulse: input.pulse,\n clean: !group\n }));\n const joinRef = ref(op); // collect visual items\n\n op = store = scope.add(Collect({\n pulse: joinRef\n })); // connect visual items to scenegraph\n\n op = scope.add(Mark({\n markdef: definition(spec),\n interactive: interactive(spec.interactive, scope),\n clip: clip(spec.clip, scope),\n context: {\n $context: true\n },\n groups: scope.lookup(),\n parent: scope.signals.parent ? scope.signalRef('parent') : null,\n index: scope.markpath(),\n pulse: ref(op)\n }));\n const markRef = ref(op); // add visual encoders\n\n op = enc = scope.add(Encode(parseEncode(spec.encode, spec.type, role, spec.style, scope, {\n mod: false,\n pulse: markRef\n }))); // monitor parent marks to propagate changes\n\n op.params.parent = scope.encode(); // add post-encoding transforms, if defined\n\n if (spec.transform) {\n spec.transform.forEach(_ => {\n const tx = parseTransform(_, scope),\n md = tx.metadata;\n\n if (md.generates || md.changes) {\n error('Mark transforms should not generate new data.');\n }\n\n if (!md.nomod) enc.params.mod = true; // update encode mod handling\n\n tx.params.pulse = ref(op);\n scope.add(op = tx);\n });\n } // if item sort specified, perform post-encoding\n\n\n if (spec.sort) {\n op = scope.add(SortItems({\n sort: scope.compareRef(spec.sort),\n pulse: ref(op)\n }));\n }\n\n const encodeRef = ref(op); // add view layout operator if needed\n\n if (facet || layout) {\n layout = scope.add(ViewLayout({\n layout: scope.objectProperty(spec.layout),\n legends: scope.legends,\n mark: markRef,\n pulse: encodeRef\n }));\n layoutRef = ref(layout);\n } // compute bounding boxes\n\n\n const bound = scope.add(Bound({\n mark: markRef,\n pulse: layoutRef || encodeRef\n }));\n boundRef = ref(bound); // if group mark, recurse to parse nested content\n\n if (group) {\n // juggle layout & bounds to ensure they run *after* any faceting transforms\n if (nested) {\n ops = scope.operators;\n ops.pop();\n if (layout) ops.pop();\n }\n\n scope.pushState(encodeRef, layoutRef || boundRef, joinRef);\n facet ? parseFacet(spec, scope, input) // explicit facet\n : nested ? parseSubflow(spec, scope, input) // standard mark group\n : scope.parse(spec); // guide group, we can avoid nested scopes\n\n scope.popState();\n\n if (nested) {\n if (layout) ops.push(layout);\n ops.push(bound);\n }\n } // if requested, add overlap removal transform\n\n\n if (overlap) {\n boundRef = parseOverlap(overlap, boundRef, scope);\n } // render / sieve items\n\n\n const render = scope.add(Render({\n pulse: boundRef\n })),\n sieve = scope.add(Sieve({\n pulse: ref(render)\n }, undefined, scope.parent())); // if mark is named, make accessible as reactive geometry\n // add trigger updates if defined\n\n if (spec.name != null) {\n name = spec.name;\n scope.addData(name, new DataScope(scope, store, render, sieve));\n if (spec.on) spec.on.forEach(on => {\n if (on.insert || on.remove || on.toggle) {\n error('Marks only support modify triggers.');\n }\n\n parseTrigger(on, scope, name);\n });\n }\n}\n\nfunction parseOverlap(overlap, source, scope) {\n const method = overlap.method,\n bound = overlap.bound,\n sep = overlap.separation;\n const params = {\n separation: isSignal(sep) ? scope.signalRef(sep.signal) : sep,\n method: isSignal(method) ? scope.signalRef(method.signal) : method,\n pulse: source\n };\n\n if (overlap.order) {\n params.sort = scope.compareRef({\n field: overlap.order\n });\n }\n\n if (bound) {\n const tol = bound.tolerance;\n params.boundTolerance = isSignal(tol) ? scope.signalRef(tol.signal) : +tol;\n params.boundScale = scope.scaleRef(bound.scale);\n params.boundOrient = bound.orient;\n }\n\n return ref(scope.add(Overlap(params)));\n}\n\nfunction parseLegend (spec, scope) {\n const config = scope.config.legend,\n encode = spec.encode || {},\n _ = lookup(spec, config),\n legendEncode = encode.legend || {},\n name = legendEncode.name || undefined,\n interactive = legendEncode.interactive,\n style = legendEncode.style,\n scales = {};\n\n let scale = 0,\n entryLayout,\n params,\n children; // resolve scales and 'canonical' scale name\n\n LegendScales.forEach(s => spec[s] ? (scales[s] = spec[s], scale = scale || spec[s]) : 0);\n if (!scale) error('Missing valid scale for legend.'); // resolve legend type (symbol, gradient, or discrete gradient)\n\n const type = legendType(spec, scope.scaleType(scale)); // single-element data source for legend group\n\n const datum = {\n title: spec.title != null,\n scales: scales,\n type: type,\n vgrad: type !== 'symbol' && _.isVertical()\n };\n const dataRef = ref(scope.add(Collect(null, [datum]))); // encoding properties for legend entry sub-group\n\n const entryEncode = {\n enter: {\n x: {\n value: 0\n },\n y: {\n value: 0\n }\n }\n }; // data source for legend values\n\n const entryRef = ref(scope.add(LegendEntries(params = {\n type: type,\n scale: scope.scaleRef(scale),\n count: scope.objectProperty(_('tickCount')),\n limit: scope.property(_('symbolLimit')),\n values: scope.objectProperty(spec.values),\n minstep: scope.property(spec.tickMinStep),\n formatType: scope.property(spec.formatType),\n formatSpecifier: scope.property(spec.format)\n }))); // continuous gradient legend\n\n if (type === Gradient) {\n children = [legendGradient(spec, scale, config, encode.gradient), legendGradientLabels(spec, config, encode.labels, entryRef)]; // adjust default tick count based on the gradient length\n\n params.count = params.count || scope.signalRef(`max(2,2*floor((${deref(_.gradientLength())})/100))`);\n } // discrete gradient legend\n else if (type === Discrete) {\n children = [legendGradientDiscrete(spec, scale, config, encode.gradient, entryRef), legendGradientLabels(spec, config, encode.labels, entryRef)];\n } // symbol legend\n else {\n // determine legend symbol group layout\n entryLayout = legendSymbolLayout(spec, config);\n children = [legendSymbolGroups(spec, config, encode, entryRef, deref(entryLayout.columns))]; // pass symbol size information to legend entry generator\n\n params.size = sizeExpression(spec, scope, children[0].marks);\n } // generate legend marks\n\n\n children = [guideGroup({\n role: LegendEntryRole,\n from: dataRef,\n encode: entryEncode,\n marks: children,\n layout: entryLayout,\n interactive\n })]; // include legend title if defined\n\n if (datum.title) {\n children.push(legendTitle(spec, config, encode.title, dataRef));\n } // parse legend specification\n\n\n return parseMark(guideGroup({\n role: LegendRole,\n from: dataRef,\n encode: extendEncode(buildLegendEncode(_, spec, config), legendEncode, Skip),\n marks: children,\n aria: _('aria'),\n description: _('description'),\n zindex: _('zindex'),\n name,\n interactive,\n style\n }), scope);\n}\n\nfunction legendType(spec, scaleType) {\n let type = spec.type || Symbols;\n\n if (!spec.type && scaleCount(spec) === 1 && (spec.fill || spec.stroke)) {\n type = isContinuous(scaleType) ? Gradient : isDiscretizing(scaleType) ? Discrete : Symbols;\n }\n\n return type !== Gradient ? type : isDiscretizing(scaleType) ? Discrete : Gradient;\n}\n\nfunction scaleCount(spec) {\n return LegendScales.reduce((count, type) => count + (spec[type] ? 1 : 0), 0);\n}\n\nfunction buildLegendEncode(_, spec, config) {\n const encode = {\n enter: {},\n update: {}\n };\n addEncoders(encode, {\n orient: _('orient'),\n offset: _('offset'),\n padding: _('padding'),\n titlePadding: _('titlePadding'),\n cornerRadius: _('cornerRadius'),\n fill: _('fillColor'),\n stroke: _('strokeColor'),\n strokeWidth: config.strokeWidth,\n strokeDash: config.strokeDash,\n x: _('legendX'),\n y: _('legendY'),\n // accessibility support\n format: spec.format,\n formatType: spec.formatType\n });\n return encode;\n}\n\nfunction sizeExpression(spec, scope, marks) {\n const size = deref(getChannel('size', spec, marks)),\n strokeWidth = deref(getChannel('strokeWidth', spec, marks)),\n fontSize = deref(getFontSize(marks[1].encode, scope, GuideLabelStyle));\n return parseExpression(`max(ceil(sqrt(${size})+${strokeWidth}),${fontSize})`, scope);\n}\n\nfunction getChannel(name, spec, marks) {\n return spec[name] ? `scale(\"${spec[name]}\",datum)` : getEncoding(name, marks[0].encode);\n}\n\nfunction getFontSize(encode, scope, style) {\n return getEncoding('fontSize', encode) || getStyle('fontSize', scope, style);\n}\n\nconst angleExpr = `item.orient===\"${Left}\"?-90:item.orient===\"${Right}\"?90:0`;\nfunction parseTitle (spec, scope) {\n spec = isString(spec) ? {\n text: spec\n } : spec;\n\n const _ = lookup(spec, scope.config.title),\n encode = spec.encode || {},\n userEncode = encode.group || {},\n name = userEncode.name || undefined,\n interactive = userEncode.interactive,\n style = userEncode.style,\n children = []; // single-element data source for group title\n\n\n const datum = {},\n dataRef = ref(scope.add(Collect(null, [datum]))); // include title text\n\n children.push(buildTitle(spec, _, titleEncode(spec), dataRef)); // include subtitle text\n\n if (spec.subtitle) {\n children.push(buildSubTitle(spec, _, encode.subtitle, dataRef));\n } // parse title specification\n\n\n return parseMark(guideGroup({\n role: TitleRole,\n from: dataRef,\n encode: groupEncode(_, userEncode),\n marks: children,\n aria: _('aria'),\n description: _('description'),\n zindex: _('zindex'),\n name,\n interactive,\n style\n }), scope);\n} // provide backwards-compatibility for title custom encode;\n// the top-level encode block has been *deprecated*.\n\nfunction titleEncode(spec) {\n const encode = spec.encode;\n return encode && encode.title || extend({\n name: spec.name,\n interactive: spec.interactive,\n style: spec.style\n }, encode);\n}\n\nfunction groupEncode(_, userEncode) {\n const encode = {\n enter: {},\n update: {}\n };\n addEncoders(encode, {\n orient: _('orient'),\n anchor: _('anchor'),\n align: {\n signal: alignExpr$1\n },\n angle: {\n signal: angleExpr\n },\n limit: _('limit'),\n frame: _('frame'),\n offset: _('offset') || 0,\n padding: _('subtitlePadding')\n });\n return extendEncode(encode, userEncode, Skip);\n}\n\nfunction buildTitle(spec, _, userEncode, dataRef) {\n const zero = {\n value: 0\n },\n text = spec.text,\n encode = {\n enter: {\n opacity: zero\n },\n update: {\n opacity: {\n value: 1\n }\n },\n exit: {\n opacity: zero\n }\n };\n addEncoders(encode, {\n text: text,\n align: {\n signal: 'item.mark.group.align'\n },\n angle: {\n signal: 'item.mark.group.angle'\n },\n limit: {\n signal: 'item.mark.group.limit'\n },\n baseline: 'top',\n dx: _('dx'),\n dy: _('dy'),\n fill: _('color'),\n font: _('font'),\n fontSize: _('fontSize'),\n fontStyle: _('fontStyle'),\n fontWeight: _('fontWeight'),\n lineHeight: _('lineHeight')\n }, {\n // update\n align: _('align'),\n angle: _('angle'),\n baseline: _('baseline')\n });\n return guideMark({\n type: TextMark,\n role: TitleTextRole,\n style: GroupTitleStyle,\n from: dataRef,\n encode\n }, userEncode);\n}\n\nfunction buildSubTitle(spec, _, userEncode, dataRef) {\n const zero = {\n value: 0\n },\n text = spec.subtitle,\n encode = {\n enter: {\n opacity: zero\n },\n update: {\n opacity: {\n value: 1\n }\n },\n exit: {\n opacity: zero\n }\n };\n addEncoders(encode, {\n text: text,\n align: {\n signal: 'item.mark.group.align'\n },\n angle: {\n signal: 'item.mark.group.angle'\n },\n limit: {\n signal: 'item.mark.group.limit'\n },\n baseline: 'top',\n dx: _('dx'),\n dy: _('dy'),\n fill: _('subtitleColor'),\n font: _('subtitleFont'),\n fontSize: _('subtitleFontSize'),\n fontStyle: _('subtitleFontStyle'),\n fontWeight: _('subtitleFontWeight'),\n lineHeight: _('subtitleLineHeight')\n }, {\n // update\n align: _('align'),\n angle: _('angle'),\n baseline: _('baseline')\n });\n return guideMark({\n type: TextMark,\n role: TitleSubtitleRole,\n style: GroupSubtitleStyle,\n from: dataRef,\n encode\n }, userEncode);\n}\n\nfunction parseData(data, scope) {\n const transforms = [];\n\n if (data.transform) {\n data.transform.forEach(tx => {\n transforms.push(parseTransform(tx, scope));\n });\n }\n\n if (data.on) {\n data.on.forEach(on => {\n parseTrigger(on, scope, data.name);\n });\n }\n\n scope.addDataPipeline(data.name, analyze(data, scope, transforms));\n}\n/**\n * Analyze a data pipeline, add needed operators.\n */\n\nfunction analyze(data, scope, ops) {\n const output = [];\n let source = null,\n modify = false,\n generate = false,\n upstream,\n i,\n n,\n t,\n m;\n\n if (data.values) {\n // hard-wired input data set\n if (isSignal(data.values) || hasSignal(data.format)) {\n // if either values is signal or format has signal, use dynamic loader\n output.push(load(scope, data));\n output.push(source = collect());\n } else {\n // otherwise, ingest upon dataflow init\n output.push(source = collect({\n $ingest: data.values,\n $format: data.format\n }));\n }\n } else if (data.url) {\n // load data from external source\n if (hasSignal(data.url) || hasSignal(data.format)) {\n // if either url or format has signal, use dynamic loader\n output.push(load(scope, data));\n output.push(source = collect());\n } else {\n // otherwise, request load upon dataflow init\n output.push(source = collect({\n $request: data.url,\n $format: data.format\n }));\n }\n } else if (data.source) {\n // derives from one or more other data sets\n source = upstream = array(data.source).map(d => ref(scope.getData(d).output));\n output.push(null); // populate later\n } // scan data transforms, add collectors as needed\n\n\n for (i = 0, n = ops.length; i < n; ++i) {\n t = ops[i];\n m = t.metadata;\n\n if (!source && !m.source) {\n output.push(source = collect());\n }\n\n output.push(t);\n if (m.generates) generate = true;\n if (m.modifies && !generate) modify = true;\n if (m.source) source = t;else if (m.changes) source = null;\n }\n\n if (upstream) {\n n = upstream.length - 1;\n output[0] = Relay({\n derive: modify,\n pulse: n ? upstream : upstream[0]\n });\n\n if (modify || n) {\n // collect derived and multi-pulse tuples\n output.splice(1, 0, collect());\n }\n }\n\n if (!source) output.push(collect());\n output.push(Sieve({}));\n return output;\n}\n\nfunction collect(values) {\n const s = Collect({}, values);\n s.metadata = {\n source: true\n };\n return s;\n}\n\nfunction load(scope, data) {\n return Load({\n url: data.url ? scope.property(data.url) : undefined,\n async: data.async ? scope.property(data.async) : undefined,\n values: data.values ? scope.property(data.values) : undefined,\n format: scope.objectProperty(data.format)\n });\n}\n\nconst isX = orient => orient === Bottom || orient === Top; // get sign coefficient based on axis orient\n\n\nconst getSign = (orient, a, b) => isSignal(orient) ? ifLeftTopExpr(orient.signal, a, b) : orient === Left || orient === Top ? a : b; // condition on axis x-direction\n\nconst ifX = (orient, a, b) => isSignal(orient) ? ifXEnc(orient.signal, a, b) : isX(orient) ? a : b; // condition on axis y-direction\n\nconst ifY = (orient, a, b) => isSignal(orient) ? ifYEnc(orient.signal, a, b) : isX(orient) ? b : a;\nconst ifTop = (orient, a, b) => isSignal(orient) ? ifTopExpr(orient.signal, a, b) : orient === Top ? {\n value: a\n} : {\n value: b\n};\nconst ifRight = (orient, a, b) => isSignal(orient) ? ifRightExpr(orient.signal, a, b) : orient === Right ? {\n value: a\n} : {\n value: b\n};\n\nconst ifXEnc = ($orient, a, b) => ifEnc(`${$orient} === '${Top}' || ${$orient} === '${Bottom}'`, a, b);\n\nconst ifYEnc = ($orient, a, b) => ifEnc(`${$orient} !== '${Top}' && ${$orient} !== '${Bottom}'`, a, b);\n\nconst ifLeftTopExpr = ($orient, a, b) => ifExpr(`${$orient} === '${Left}' || ${$orient} === '${Top}'`, a, b);\n\nconst ifTopExpr = ($orient, a, b) => ifExpr(`${$orient} === '${Top}'`, a, b);\n\nconst ifRightExpr = ($orient, a, b) => ifExpr(`${$orient} === '${Right}'`, a, b);\n\nconst ifEnc = (test, a, b) => {\n // ensure inputs are encoder objects (or null)\n a = a != null ? encoder(a) : a;\n b = b != null ? encoder(b) : b;\n\n if (isSimple(a) && isSimple(b)) {\n // if possible generate simple signal expression\n a = a ? a.signal || stringValue(a.value) : null;\n b = b ? b.signal || stringValue(b.value) : null;\n return {\n signal: `${test} ? (${a}) : (${b})`\n };\n } else {\n // otherwise generate rule set\n return [extend({\n test\n }, a)].concat(b || []);\n }\n};\n\nconst isSimple = enc => enc == null || Object.keys(enc).length === 1;\n\nconst ifExpr = (test, a, b) => ({\n signal: `${test} ? (${toExpr(a)}) : (${toExpr(b)})`\n});\n\nconst ifOrient = ($orient, t, b, l, r) => ({\n signal: (l != null ? `${$orient} === '${Left}' ? (${toExpr(l)}) : ` : '') + (b != null ? `${$orient} === '${Bottom}' ? (${toExpr(b)}) : ` : '') + (r != null ? `${$orient} === '${Right}' ? (${toExpr(r)}) : ` : '') + (t != null ? `${$orient} === '${Top}' ? (${toExpr(t)}) : ` : '') + '(null)'\n});\n\nconst toExpr = v => isSignal(v) ? v.signal : v == null ? null : stringValue(v);\n\nconst mult = (sign, value) => value === 0 ? 0 : isSignal(sign) ? {\n signal: `(${sign.signal}) * ${value}`\n} : {\n value: sign * value\n};\nconst patch = (value, base) => {\n const s = value.signal;\n return s && s.endsWith('(null)') ? {\n signal: s.slice(0, -6) + base.signal\n } : value;\n};\n\nfunction fallback(prop, config, axisConfig, style) {\n let styleProp;\n\n if (config && hasOwnProperty(config, prop)) {\n return config[prop];\n } else if (hasOwnProperty(axisConfig, prop)) {\n return axisConfig[prop];\n } else if (prop.startsWith('title')) {\n switch (prop) {\n case 'titleColor':\n styleProp = 'fill';\n break;\n\n case 'titleFont':\n case 'titleFontSize':\n case 'titleFontWeight':\n styleProp = prop[5].toLowerCase() + prop.slice(6);\n }\n\n return style[GuideTitleStyle][styleProp];\n } else if (prop.startsWith('label')) {\n switch (prop) {\n case 'labelColor':\n styleProp = 'fill';\n break;\n\n case 'labelFont':\n case 'labelFontSize':\n styleProp = prop[5].toLowerCase() + prop.slice(6);\n }\n\n return style[GuideLabelStyle][styleProp];\n }\n\n return null;\n}\n\nfunction keys(objects) {\n const map = {};\n\n for (const obj of objects) {\n if (!obj) continue;\n\n for (const key in obj) map[key] = 1;\n }\n\n return Object.keys(map);\n}\n\nfunction axisConfig (spec, scope) {\n var config = scope.config,\n style = config.style,\n axis = config.axis,\n band = scope.scaleType(spec.scale) === 'band' && config.axisBand,\n orient = spec.orient,\n xy,\n or,\n key;\n\n if (isSignal(orient)) {\n const xyKeys = keys([config.axisX, config.axisY]),\n orientKeys = keys([config.axisTop, config.axisBottom, config.axisLeft, config.axisRight]);\n xy = {};\n\n for (key of xyKeys) {\n xy[key] = ifX(orient, fallback(key, config.axisX, axis, style), fallback(key, config.axisY, axis, style));\n }\n\n or = {};\n\n for (key of orientKeys) {\n or[key] = ifOrient(orient.signal, fallback(key, config.axisTop, axis, style), fallback(key, config.axisBottom, axis, style), fallback(key, config.axisLeft, axis, style), fallback(key, config.axisRight, axis, style));\n }\n } else {\n xy = orient === Top || orient === Bottom ? config.axisX : config.axisY;\n or = config['axis' + orient[0].toUpperCase() + orient.slice(1)];\n }\n\n const result = xy || or || band ? extend({}, axis, xy, or, band) : axis;\n return result;\n}\n\nfunction axisDomain (spec, config, userEncode, dataRef) {\n const _ = lookup(spec, config),\n orient = spec.orient;\n\n let enter, update;\n const encode = {\n enter: enter = {\n opacity: zero\n },\n update: update = {\n opacity: one\n },\n exit: {\n opacity: zero\n }\n };\n addEncoders(encode, {\n stroke: _('domainColor'),\n strokeCap: _('domainCap'),\n strokeDash: _('domainDash'),\n strokeDashOffset: _('domainDashOffset'),\n strokeWidth: _('domainWidth'),\n strokeOpacity: _('domainOpacity')\n });\n const pos0 = position(spec, 0);\n const pos1 = position(spec, 1);\n enter.x = update.x = ifX(orient, pos0, zero);\n enter.x2 = update.x2 = ifX(orient, pos1);\n enter.y = update.y = ifY(orient, pos0, zero);\n enter.y2 = update.y2 = ifY(orient, pos1);\n return guideMark({\n type: RuleMark,\n role: AxisDomainRole,\n from: dataRef,\n encode\n }, userEncode);\n}\n\nfunction position(spec, pos) {\n return {\n scale: spec.scale,\n range: pos\n };\n}\n\nfunction axisGrid (spec, config, userEncode, dataRef, band) {\n const _ = lookup(spec, config),\n orient = spec.orient,\n vscale = spec.gridScale,\n sign = getSign(orient, 1, -1),\n offset = offsetValue(spec.offset, sign);\n\n let enter, exit, update;\n const encode = {\n enter: enter = {\n opacity: zero\n },\n update: update = {\n opacity: one\n },\n exit: exit = {\n opacity: zero\n }\n };\n addEncoders(encode, {\n stroke: _('gridColor'),\n strokeCap: _('gridCap'),\n strokeDash: _('gridDash'),\n strokeDashOffset: _('gridDashOffset'),\n strokeOpacity: _('gridOpacity'),\n strokeWidth: _('gridWidth')\n });\n const tickPos = {\n scale: spec.scale,\n field: Value,\n band: band.band,\n extra: band.extra,\n offset: band.offset,\n round: _('tickRound')\n };\n const sz = ifX(orient, {\n signal: 'height'\n }, {\n signal: 'width'\n });\n const gridStart = vscale ? {\n scale: vscale,\n range: 0,\n mult: sign,\n offset: offset\n } : {\n value: 0,\n offset: offset\n };\n const gridEnd = vscale ? {\n scale: vscale,\n range: 1,\n mult: sign,\n offset: offset\n } : extend(sz, {\n mult: sign,\n offset: offset\n });\n enter.x = update.x = ifX(orient, tickPos, gridStart);\n enter.y = update.y = ifY(orient, tickPos, gridStart);\n enter.x2 = update.x2 = ifY(orient, gridEnd);\n enter.y2 = update.y2 = ifX(orient, gridEnd);\n exit.x = ifX(orient, tickPos);\n exit.y = ifY(orient, tickPos);\n return guideMark({\n type: RuleMark,\n role: AxisGridRole,\n key: Value,\n from: dataRef,\n encode\n }, userEncode);\n}\n\nfunction offsetValue(offset, sign) {\n if (sign === 1) ; else if (!isObject(offset)) {\n offset = isSignal(sign) ? {\n signal: `(${sign.signal}) * (${offset || 0})`\n } : sign * (offset || 0);\n } else {\n let entry = offset = extend({}, offset);\n\n while (entry.mult != null) {\n if (!isObject(entry.mult)) {\n entry.mult = isSignal(sign) // no offset if sign === 1\n ? {\n signal: `(${entry.mult}) * (${sign.signal})`\n } : entry.mult * sign;\n return offset;\n } else {\n entry = entry.mult = extend({}, entry.mult);\n }\n }\n\n entry.mult = sign;\n }\n\n return offset;\n}\n\nfunction axisTicks (spec, config, userEncode, dataRef, size, band) {\n const _ = lookup(spec, config),\n orient = spec.orient,\n sign = getSign(orient, -1, 1);\n\n let enter, exit, update;\n const encode = {\n enter: enter = {\n opacity: zero\n },\n update: update = {\n opacity: one\n },\n exit: exit = {\n opacity: zero\n }\n };\n addEncoders(encode, {\n stroke: _('tickColor'),\n strokeCap: _('tickCap'),\n strokeDash: _('tickDash'),\n strokeDashOffset: _('tickDashOffset'),\n strokeOpacity: _('tickOpacity'),\n strokeWidth: _('tickWidth')\n });\n const tickSize = encoder(size);\n tickSize.mult = sign;\n const tickPos = {\n scale: spec.scale,\n field: Value,\n band: band.band,\n extra: band.extra,\n offset: band.offset,\n round: _('tickRound')\n };\n update.y = enter.y = ifX(orient, zero, tickPos);\n update.y2 = enter.y2 = ifX(orient, tickSize);\n exit.x = ifX(orient, tickPos);\n update.x = enter.x = ifY(orient, zero, tickPos);\n update.x2 = enter.x2 = ifY(orient, tickSize);\n exit.y = ifY(orient, tickPos);\n return guideMark({\n type: RuleMark,\n role: AxisTickRole,\n key: Value,\n from: dataRef,\n encode\n }, userEncode);\n}\n\nfunction flushExpr(scale, threshold, a, b, c) {\n return {\n signal: 'flush(range(\"' + scale + '\"), ' + 'scale(\"' + scale + '\", datum.value), ' + threshold + ',' + a + ',' + b + ',' + c + ')'\n };\n}\n\nfunction axisLabels (spec, config, userEncode, dataRef, size, band) {\n const _ = lookup(spec, config),\n orient = spec.orient,\n scale = spec.scale,\n sign = getSign(orient, -1, 1),\n flush = deref(_('labelFlush')),\n flushOffset = deref(_('labelFlushOffset')),\n labelAlign = _('labelAlign'),\n labelBaseline = _('labelBaseline');\n\n let flushOn = flush === 0 || !!flush,\n update;\n const tickSize = encoder(size);\n tickSize.mult = sign;\n tickSize.offset = encoder(_('labelPadding') || 0);\n tickSize.offset.mult = sign;\n const tickPos = {\n scale: scale,\n field: Value,\n band: 0.5,\n offset: extendOffset(band.offset, _('labelOffset'))\n };\n const align = ifX(orient, flushOn ? flushExpr(scale, flush, '\"left\"', '\"right\"', '\"center\"') : {\n value: 'center'\n }, ifRight(orient, 'left', 'right'));\n const baseline = ifX(orient, ifTop(orient, 'bottom', 'top'), flushOn ? flushExpr(scale, flush, '\"top\"', '\"bottom\"', '\"middle\"') : {\n value: 'middle'\n });\n const offsetExpr = flushExpr(scale, flush, `-(${flushOffset})`, flushOffset, 0);\n flushOn = flushOn && flushOffset;\n const enter = {\n opacity: zero,\n x: ifX(orient, tickPos, tickSize),\n y: ifY(orient, tickPos, tickSize)\n };\n const encode = {\n enter: enter,\n update: update = {\n opacity: one,\n text: {\n field: Label\n },\n x: enter.x,\n y: enter.y,\n align,\n baseline\n },\n exit: {\n opacity: zero,\n x: enter.x,\n y: enter.y\n }\n };\n addEncoders(encode, {\n dx: !labelAlign && flushOn ? ifX(orient, offsetExpr) : null,\n dy: !labelBaseline && flushOn ? ifY(orient, offsetExpr) : null\n });\n addEncoders(encode, {\n angle: _('labelAngle'),\n fill: _('labelColor'),\n fillOpacity: _('labelOpacity'),\n font: _('labelFont'),\n fontSize: _('labelFontSize'),\n fontWeight: _('labelFontWeight'),\n fontStyle: _('labelFontStyle'),\n limit: _('labelLimit'),\n lineHeight: _('labelLineHeight')\n }, {\n align: labelAlign,\n baseline: labelBaseline\n });\n\n const bound = _('labelBound');\n\n let overlap = _('labelOverlap'); // if overlap method or bound defined, request label overlap removal\n\n\n overlap = overlap || bound ? {\n separation: _('labelSeparation'),\n method: overlap,\n order: 'datum.index',\n bound: bound ? {\n scale,\n orient,\n tolerance: bound\n } : null\n } : undefined;\n\n if (update.align !== align) {\n update.align = patch(update.align, align);\n }\n\n if (update.baseline !== baseline) {\n update.baseline = patch(update.baseline, baseline);\n }\n\n return guideMark({\n type: TextMark,\n role: AxisLabelRole,\n style: GuideLabelStyle,\n key: Value,\n from: dataRef,\n encode,\n overlap\n }, userEncode);\n}\n\nfunction axisTitle (spec, config, userEncode, dataRef) {\n const _ = lookup(spec, config),\n orient = spec.orient,\n sign = getSign(orient, -1, 1);\n\n let enter, update;\n const encode = {\n enter: enter = {\n opacity: zero,\n anchor: encoder(_('titleAnchor', null)),\n align: {\n signal: alignExpr$1\n }\n },\n update: update = extend({}, enter, {\n opacity: one,\n text: encoder(spec.title)\n }),\n exit: {\n opacity: zero\n }\n };\n const titlePos = {\n signal: `lerp(range(\"${spec.scale}\"), ${anchorExpr(0, 1, 0.5)})`\n };\n update.x = ifX(orient, titlePos);\n update.y = ifY(orient, titlePos);\n enter.angle = ifX(orient, zero, mult(sign, 90));\n enter.baseline = ifX(orient, ifTop(orient, Bottom, Top), {\n value: Bottom\n });\n update.angle = enter.angle;\n update.baseline = enter.baseline;\n addEncoders(encode, {\n fill: _('titleColor'),\n fillOpacity: _('titleOpacity'),\n font: _('titleFont'),\n fontSize: _('titleFontSize'),\n fontStyle: _('titleFontStyle'),\n fontWeight: _('titleFontWeight'),\n limit: _('titleLimit'),\n lineHeight: _('titleLineHeight')\n }, {\n // require update\n align: _('titleAlign'),\n angle: _('titleAngle'),\n baseline: _('titleBaseline')\n });\n autoLayout(_, orient, encode, userEncode);\n encode.update.align = patch(encode.update.align, enter.align);\n encode.update.angle = patch(encode.update.angle, enter.angle);\n encode.update.baseline = patch(encode.update.baseline, enter.baseline);\n return guideMark({\n type: TextMark,\n role: AxisTitleRole,\n style: GuideTitleStyle,\n from: dataRef,\n encode\n }, userEncode);\n}\n\nfunction autoLayout(_, orient, encode, userEncode) {\n const auto = (value, dim) => value != null ? (encode.update[dim] = patch(encoder(value), encode.update[dim]), false) : !has(dim, userEncode) ? true : false;\n\n const autoY = auto(_('titleX'), 'x'),\n autoX = auto(_('titleY'), 'y');\n encode.enter.auto = autoX === autoY ? encoder(autoX) : ifX(orient, encoder(autoX), encoder(autoY));\n}\n\nfunction parseAxis (spec, scope) {\n const config = axisConfig(spec, scope),\n encode = spec.encode || {},\n axisEncode = encode.axis || {},\n name = axisEncode.name || undefined,\n interactive = axisEncode.interactive,\n style = axisEncode.style,\n _ = lookup(spec, config),\n band = tickBand(_); // single-element data source for axis group\n\n\n const datum = {\n scale: spec.scale,\n ticks: !!_('ticks'),\n labels: !!_('labels'),\n grid: !!_('grid'),\n domain: !!_('domain'),\n title: spec.title != null\n };\n const dataRef = ref(scope.add(Collect({}, [datum]))); // data source for axis ticks\n\n const ticksRef = ref(scope.add(AxisTicks({\n scale: scope.scaleRef(spec.scale),\n extra: scope.property(band.extra),\n count: scope.objectProperty(spec.tickCount),\n values: scope.objectProperty(spec.values),\n minstep: scope.property(spec.tickMinStep),\n formatType: scope.property(spec.formatType),\n formatSpecifier: scope.property(spec.format)\n }))); // generate axis marks\n\n const children = [];\n let size; // include axis gridlines if requested\n\n if (datum.grid) {\n children.push(axisGrid(spec, config, encode.grid, ticksRef, band));\n } // include axis ticks if requested\n\n\n if (datum.ticks) {\n size = _('tickSize');\n children.push(axisTicks(spec, config, encode.ticks, ticksRef, size, band));\n } // include axis labels if requested\n\n\n if (datum.labels) {\n size = datum.ticks ? size : 0;\n children.push(axisLabels(spec, config, encode.labels, ticksRef, size, band));\n } // include axis domain path if requested\n\n\n if (datum.domain) {\n children.push(axisDomain(spec, config, encode.domain, dataRef));\n } // include axis title if defined\n\n\n if (datum.title) {\n children.push(axisTitle(spec, config, encode.title, dataRef));\n } // parse axis specification\n\n\n return parseMark(guideGroup({\n role: AxisRole,\n from: dataRef,\n encode: extendEncode(buildAxisEncode(_, spec), axisEncode, Skip),\n marks: children,\n aria: _('aria'),\n description: _('description'),\n zindex: _('zindex'),\n name,\n interactive,\n style\n }), scope);\n}\n\nfunction buildAxisEncode(_, spec) {\n const encode = {\n enter: {},\n update: {}\n };\n addEncoders(encode, {\n orient: _('orient'),\n offset: _('offset') || 0,\n position: value(spec.position, 0),\n titlePadding: _('titlePadding'),\n minExtent: _('minExtent'),\n maxExtent: _('maxExtent'),\n range: {\n signal: `abs(span(range(\"${spec.scale}\")))`\n },\n translate: _('translate'),\n // accessibility support\n format: spec.format,\n formatType: spec.formatType\n });\n return encode;\n}\n\nfunction parseScope (spec, scope, preprocessed) {\n const signals = array(spec.signals),\n scales = array(spec.scales); // parse signal definitions, if not already preprocessed\n\n if (!preprocessed) signals.forEach(_ => parseSignal(_, scope)); // parse cartographic projection definitions\n\n array(spec.projections).forEach(_ => parseProjection(_, scope)); // initialize scale references\n\n scales.forEach(_ => initScale(_, scope)); // parse data sources\n\n array(spec.data).forEach(_ => parseData(_, scope)); // parse scale definitions\n\n scales.forEach(_ => parseScale(_, scope)); // parse signal updates\n\n (preprocessed || signals).forEach(_ => parseSignalUpdates(_, scope)); // parse axis definitions\n\n array(spec.axes).forEach(_ => parseAxis(_, scope)); // parse mark definitions\n\n array(spec.marks).forEach(_ => parseMark(_, scope)); // parse legend definitions\n\n array(spec.legends).forEach(_ => parseLegend(_, scope)); // parse title, if defined\n\n if (spec.title) parseTitle(spec.title, scope); // parse collected lambda (anonymous) expressions\n\n scope.parseLambdas();\n return scope;\n}\n\nconst rootEncode = spec => extendEncode({\n enter: {\n x: {\n value: 0\n },\n y: {\n value: 0\n }\n },\n update: {\n width: {\n signal: 'width'\n },\n height: {\n signal: 'height'\n }\n }\n}, spec);\n\nfunction parseView(spec, scope) {\n const config = scope.config; // add scenegraph root\n\n const root = ref(scope.root = scope.add(operator())); // parse top-level signal definitions\n\n const signals = collectSignals(spec, config);\n signals.forEach(_ => parseSignal(_, scope)); // assign description, event, legend, and locale configuration\n\n scope.description = spec.description || config.description;\n scope.eventConfig = config.events;\n scope.legends = scope.objectProperty(config.legend && config.legend.layout);\n scope.locale = config.locale; // store root group item\n\n const input = scope.add(Collect()); // encode root group item\n\n const encode = scope.add(Encode(parseEncode(rootEncode(spec.encode), GroupMark, FrameRole, spec.style, scope, {\n pulse: ref(input)\n }))); // perform view layout\n\n const parent = scope.add(ViewLayout({\n layout: scope.objectProperty(spec.layout),\n legends: scope.legends,\n autosize: scope.signalRef('autosize'),\n mark: root,\n pulse: ref(encode)\n }));\n scope.operators.pop(); // parse remainder of specification\n\n scope.pushState(ref(encode), ref(parent), null);\n parseScope(spec, scope, signals);\n scope.operators.push(parent); // bound / render / sieve root item\n\n let op = scope.add(Bound({\n mark: root,\n pulse: ref(parent)\n }));\n op = scope.add(Render({\n pulse: ref(op)\n }));\n op = scope.add(Sieve({\n pulse: ref(op)\n })); // track metadata for root item\n\n scope.addData('root', new DataScope(scope, input, input, op));\n return scope;\n}\n\nfunction signalObject(name, value) {\n return value && value.signal ? {\n name,\n update: value.signal\n } : {\n name,\n value\n };\n}\n/**\n * Collect top-level signals, merging values as needed. Signals\n * defined in the config signals arrays are added only if that\n * signal is not explicitly defined in the specification.\n * Built-in signals (autosize, background, padding, width, height)\n * receive special treatment. They are initialized using the\n * top-level spec property, or, if undefined in the spec, using\n * the corresponding top-level config property. If this property\n * is a signal reference object, the signal expression maps to the\n * signal 'update' property. If the spec's top-level signal array\n * contains an entry that matches a built-in signal, that entry\n * will be merged with the built-in specification, potentially\n * overwriting existing 'value' or 'update' properties.\n */\n\n\nfunction collectSignals(spec, config) {\n const _ = name => value(spec[name], config[name]),\n signals = [signalObject('background', _('background')), signalObject('autosize', parseAutosize(_('autosize'))), signalObject('padding', parsePadding(_('padding'))), signalObject('width', _('width') || 0), signalObject('height', _('height') || 0)],\n pre = signals.reduce((p, s) => (p[s.name] = s, p), {}),\n map = {}; // add spec signal array\n\n\n array(spec.signals).forEach(s => {\n if (hasOwnProperty(pre, s.name)) {\n // merge if built-in signal\n s = extend(pre[s.name], s);\n } else {\n // otherwise add to signal list\n signals.push(s);\n }\n\n map[s.name] = s;\n }); // add config signal array\n\n array(config.signals).forEach(s => {\n if (!hasOwnProperty(map, s.name) && !hasOwnProperty(pre, s.name)) {\n // add to signal list if not already defined\n signals.push(s);\n }\n });\n return signals;\n}\n\nfunction Scope(config, options) {\n this.config = config || {};\n this.options = options || {};\n this.bindings = [];\n this.field = {};\n this.signals = {};\n this.lambdas = {};\n this.scales = {};\n this.events = {};\n this.data = {};\n this.streams = [];\n this.updates = [];\n this.operators = [];\n this.eventConfig = null;\n this.locale = null;\n this._id = 0;\n this._subid = 0;\n this._nextsub = [0];\n this._parent = [];\n this._encode = [];\n this._lookup = [];\n this._markpath = [];\n}\n\nfunction Subscope(scope) {\n this.config = scope.config;\n this.options = scope.options;\n this.legends = scope.legends;\n this.field = Object.create(scope.field);\n this.signals = Object.create(scope.signals);\n this.lambdas = Object.create(scope.lambdas);\n this.scales = Object.create(scope.scales);\n this.events = Object.create(scope.events);\n this.data = Object.create(scope.data);\n this.streams = [];\n this.updates = [];\n this.operators = [];\n this._id = 0;\n this._subid = ++scope._nextsub[0];\n this._nextsub = scope._nextsub;\n this._parent = scope._parent.slice();\n this._encode = scope._encode.slice();\n this._lookup = scope._lookup.slice();\n this._markpath = scope._markpath;\n}\n\nScope.prototype = Subscope.prototype = {\n parse(spec) {\n return parseScope(spec, this);\n },\n\n fork() {\n return new Subscope(this);\n },\n\n isSubscope() {\n return this._subid > 0;\n },\n\n toRuntime() {\n this.finish();\n return {\n description: this.description,\n operators: this.operators,\n streams: this.streams,\n updates: this.updates,\n bindings: this.bindings,\n eventConfig: this.eventConfig,\n locale: this.locale\n };\n },\n\n id() {\n return (this._subid ? this._subid + ':' : 0) + this._id++;\n },\n\n add(op) {\n this.operators.push(op);\n op.id = this.id(); // if pre-registration references exist, resolve them now\n\n if (op.refs) {\n op.refs.forEach(ref => {\n ref.$ref = op.id;\n });\n op.refs = null;\n }\n\n return op;\n },\n\n proxy(op) {\n const vref = op instanceof Entry ? ref(op) : op;\n return this.add(Proxy({\n value: vref\n }));\n },\n\n addStream(stream) {\n this.streams.push(stream);\n stream.id = this.id();\n return stream;\n },\n\n addUpdate(update) {\n this.updates.push(update);\n return update;\n },\n\n // Apply metadata\n finish() {\n let name, ds; // annotate root\n\n if (this.root) this.root.root = true; // annotate signals\n\n for (name in this.signals) {\n this.signals[name].signal = name;\n } // annotate scales\n\n\n for (name in this.scales) {\n this.scales[name].scale = name;\n } // annotate data sets\n\n\n function annotate(op, name, type) {\n let data, list;\n\n if (op) {\n data = op.data || (op.data = {});\n list = data[name] || (data[name] = []);\n list.push(type);\n }\n }\n\n for (name in this.data) {\n ds = this.data[name];\n annotate(ds.input, name, 'input');\n annotate(ds.output, name, 'output');\n annotate(ds.values, name, 'values');\n\n for (const field in ds.index) {\n annotate(ds.index[field], name, 'index:' + field);\n }\n }\n\n return this;\n },\n\n // ----\n pushState(encode, parent, lookup) {\n this._encode.push(ref(this.add(Sieve({\n pulse: encode\n }))));\n\n this._parent.push(parent);\n\n this._lookup.push(lookup ? ref(this.proxy(lookup)) : null);\n\n this._markpath.push(-1);\n },\n\n popState() {\n this._encode.pop();\n\n this._parent.pop();\n\n this._lookup.pop();\n\n this._markpath.pop();\n },\n\n parent() {\n return peek(this._parent);\n },\n\n encode() {\n return peek(this._encode);\n },\n\n lookup() {\n return peek(this._lookup);\n },\n\n markpath() {\n const p = this._markpath;\n return ++p[p.length - 1];\n },\n\n // ----\n fieldRef(field, name) {\n if (isString(field)) return fieldRef$1(field, name);\n\n if (!field.signal) {\n error('Unsupported field reference: ' + stringValue(field));\n }\n\n const s = field.signal;\n let f = this.field[s];\n\n if (!f) {\n const params = {\n name: this.signalRef(s)\n };\n if (name) params.as = name;\n this.field[s] = f = ref(this.add(Field(params)));\n }\n\n return f;\n },\n\n compareRef(cmp) {\n let signal = false;\n\n const check = _ => isSignal(_) ? (signal = true, this.signalRef(_.signal)) : isExpr$1(_) ? (signal = true, this.exprRef(_.expr)) : _;\n\n const fields = array(cmp.field).map(check),\n orders = array(cmp.order).map(check);\n return signal ? ref(this.add(Compare({\n fields: fields,\n orders: orders\n }))) : compareRef(fields, orders);\n },\n\n keyRef(fields, flat) {\n let signal = false;\n\n const check = _ => isSignal(_) ? (signal = true, ref(sig[_.signal])) : _;\n\n const sig = this.signals;\n fields = array(fields).map(check);\n return signal ? ref(this.add(Key({\n fields: fields,\n flat: flat\n }))) : keyRef(fields, flat);\n },\n\n sortRef(sort) {\n if (!sort) return sort; // including id ensures stable sorting\n\n const a = aggrField(sort.op, sort.field),\n o = sort.order || Ascending;\n return o.signal ? ref(this.add(Compare({\n fields: a,\n orders: this.signalRef(o.signal)\n }))) : compareRef(a, o);\n },\n\n // ----\n event(source, type) {\n const key = source + ':' + type;\n\n if (!this.events[key]) {\n const id = this.id();\n this.streams.push({\n id: id,\n source: source,\n type: type\n });\n this.events[key] = id;\n }\n\n return this.events[key];\n },\n\n // ----\n hasOwnSignal(name) {\n return hasOwnProperty(this.signals, name);\n },\n\n addSignal(name, value) {\n if (this.hasOwnSignal(name)) {\n error('Duplicate signal name: ' + stringValue(name));\n }\n\n const op = value instanceof Entry ? value : this.add(operator(value));\n return this.signals[name] = op;\n },\n\n getSignal(name) {\n if (!this.signals[name]) {\n error('Unrecognized signal name: ' + stringValue(name));\n }\n\n return this.signals[name];\n },\n\n signalRef(s) {\n if (this.signals[s]) {\n return ref(this.signals[s]);\n } else if (!hasOwnProperty(this.lambdas, s)) {\n this.lambdas[s] = this.add(operator(null));\n }\n\n return ref(this.lambdas[s]);\n },\n\n parseLambdas() {\n const code = Object.keys(this.lambdas);\n\n for (let i = 0, n = code.length; i < n; ++i) {\n const s = code[i],\n e = parseExpression(s, this),\n op = this.lambdas[s];\n op.params = e.$params;\n op.update = e.$expr;\n }\n },\n\n property(spec) {\n return spec && spec.signal ? this.signalRef(spec.signal) : spec;\n },\n\n objectProperty(spec) {\n return !spec || !isObject(spec) ? spec : this.signalRef(spec.signal || propertyLambda(spec));\n },\n\n exprRef(code, name) {\n const params = {\n expr: parseExpression(code, this)\n };\n if (name) params.expr.$name = name;\n return ref(this.add(Expression(params)));\n },\n\n addBinding(name, bind) {\n if (!this.bindings) {\n error('Nested signals do not support binding: ' + stringValue(name));\n }\n\n this.bindings.push(extend({\n signal: name\n }, bind));\n },\n\n // ----\n addScaleProj(name, transform) {\n if (hasOwnProperty(this.scales, name)) {\n error('Duplicate scale or projection name: ' + stringValue(name));\n }\n\n this.scales[name] = this.add(transform);\n },\n\n addScale(name, params) {\n this.addScaleProj(name, Scale(params));\n },\n\n addProjection(name, params) {\n this.addScaleProj(name, Projection(params));\n },\n\n getScale(name) {\n if (!this.scales[name]) {\n error('Unrecognized scale name: ' + stringValue(name));\n }\n\n return this.scales[name];\n },\n\n scaleRef(name) {\n return ref(this.getScale(name));\n },\n\n scaleType(name) {\n return this.getScale(name).params.type;\n },\n\n projectionRef(name) {\n return this.scaleRef(name);\n },\n\n projectionType(name) {\n return this.scaleType(name);\n },\n\n // ----\n addData(name, dataScope) {\n if (hasOwnProperty(this.data, name)) {\n error('Duplicate data set name: ' + stringValue(name));\n }\n\n return this.data[name] = dataScope;\n },\n\n getData(name) {\n if (!this.data[name]) {\n error('Undefined data set name: ' + stringValue(name));\n }\n\n return this.data[name];\n },\n\n addDataPipeline(name, entries) {\n if (hasOwnProperty(this.data, name)) {\n error('Duplicate data set name: ' + stringValue(name));\n }\n\n return this.addData(name, DataScope.fromEntries(this, entries));\n }\n\n};\n\nfunction propertyLambda(spec) {\n return (isArray(spec) ? arrayLambda : objectLambda)(spec);\n}\n\nfunction arrayLambda(array) {\n const n = array.length;\n let code = '[';\n\n for (let i = 0; i < n; ++i) {\n const value = array[i];\n code += (i > 0 ? ',' : '') + (isObject(value) ? value.signal || propertyLambda(value) : stringValue(value));\n }\n\n return code + ']';\n}\n\nfunction objectLambda(obj) {\n let code = '{',\n i = 0,\n key,\n value;\n\n for (key in obj) {\n value = obj[key];\n code += (++i > 1 ? ',' : '') + stringValue(key) + ':' + (isObject(value) ? value.signal || propertyLambda(value) : stringValue(value));\n }\n\n return code + '}';\n}\n\n/**\n * Standard configuration defaults for Vega specification parsing.\n * Users can provide their own (sub-)set of these default values\n * by passing in a config object to the top-level parse method.\n */\nfunction defaults () {\n const defaultFont = 'sans-serif',\n defaultSymbolSize = 30,\n defaultStrokeWidth = 2,\n defaultColor = '#4c78a8',\n black = '#000',\n gray = '#888',\n lightGray = '#ddd';\n return {\n // default visualization description\n description: 'Vega visualization',\n // default padding around visualization\n padding: 0,\n // default for automatic sizing; options: 'none', 'pad', 'fit'\n // or provide an object (e.g., {'type': 'pad', 'resize': true})\n autosize: 'pad',\n // default view background color\n // covers the entire view component\n background: null,\n // default event handling configuration\n // preventDefault for view-sourced event types except 'wheel'\n events: {\n defaults: {\n allow: ['wheel']\n }\n },\n // defaults for top-level group marks\n // accepts mark properties (fill, stroke, etc)\n // covers the data rectangle within group width/height\n group: null,\n // defaults for basic mark types\n // each subset accepts mark properties (fill, stroke, etc)\n mark: null,\n arc: {\n fill: defaultColor\n },\n area: {\n fill: defaultColor\n },\n image: null,\n line: {\n stroke: defaultColor,\n strokeWidth: defaultStrokeWidth\n },\n path: {\n stroke: defaultColor\n },\n rect: {\n fill: defaultColor\n },\n rule: {\n stroke: black\n },\n shape: {\n stroke: defaultColor\n },\n symbol: {\n fill: defaultColor,\n size: 64\n },\n text: {\n fill: black,\n font: defaultFont,\n fontSize: 11\n },\n trail: {\n fill: defaultColor,\n size: defaultStrokeWidth\n },\n // style definitions\n style: {\n // axis & legend labels\n 'guide-label': {\n fill: black,\n font: defaultFont,\n fontSize: 10\n },\n // axis & legend titles\n 'guide-title': {\n fill: black,\n font: defaultFont,\n fontSize: 11,\n fontWeight: 'bold'\n },\n // headers, including chart title\n 'group-title': {\n fill: black,\n font: defaultFont,\n fontSize: 13,\n fontWeight: 'bold'\n },\n // chart subtitle\n 'group-subtitle': {\n fill: black,\n font: defaultFont,\n fontSize: 12\n },\n // defaults for styled point marks in Vega-Lite\n point: {\n size: defaultSymbolSize,\n strokeWidth: defaultStrokeWidth,\n shape: 'circle'\n },\n circle: {\n size: defaultSymbolSize,\n strokeWidth: defaultStrokeWidth\n },\n square: {\n size: defaultSymbolSize,\n strokeWidth: defaultStrokeWidth,\n shape: 'square'\n },\n // defaults for styled group marks in Vega-Lite\n cell: {\n fill: 'transparent',\n stroke: lightGray\n }\n },\n // defaults for title\n title: {\n orient: 'top',\n anchor: 'middle',\n offset: 4,\n subtitlePadding: 3\n },\n // defaults for axes\n axis: {\n minExtent: 0,\n maxExtent: 200,\n bandPosition: 0.5,\n domain: true,\n domainWidth: 1,\n domainColor: gray,\n grid: false,\n gridWidth: 1,\n gridColor: lightGray,\n labels: true,\n labelAngle: 0,\n labelLimit: 180,\n labelOffset: 0,\n labelPadding: 2,\n ticks: true,\n tickColor: gray,\n tickOffset: 0,\n tickRound: true,\n tickSize: 5,\n tickWidth: 1,\n titlePadding: 4\n },\n // correction for centering bias\n axisBand: {\n tickOffset: -0.5\n },\n // defaults for cartographic projection\n projection: {\n type: 'mercator'\n },\n // defaults for legends\n legend: {\n orient: 'right',\n padding: 0,\n gridAlign: 'each',\n columnPadding: 10,\n rowPadding: 2,\n symbolDirection: 'vertical',\n gradientDirection: 'vertical',\n gradientLength: 200,\n gradientThickness: 16,\n gradientStrokeColor: lightGray,\n gradientStrokeWidth: 0,\n gradientLabelOffset: 2,\n labelAlign: 'left',\n labelBaseline: 'middle',\n labelLimit: 160,\n labelOffset: 4,\n labelOverlap: true,\n symbolLimit: 30,\n symbolType: 'circle',\n symbolSize: 100,\n symbolOffset: 0,\n symbolStrokeWidth: 1.5,\n symbolBaseFillColor: 'transparent',\n symbolBaseStrokeColor: gray,\n titleLimit: 180,\n titleOrient: 'top',\n titlePadding: 5,\n layout: {\n offset: 18,\n direction: 'horizontal',\n left: {\n direction: 'vertical'\n },\n right: {\n direction: 'vertical'\n }\n }\n },\n // defaults for scale ranges\n range: {\n category: {\n scheme: 'tableau10'\n },\n ordinal: {\n scheme: 'blues'\n },\n heatmap: {\n scheme: 'yellowgreenblue'\n },\n ramp: {\n scheme: 'blues'\n },\n diverging: {\n scheme: 'blueorange',\n extent: [1, 0]\n },\n symbol: ['circle', 'square', 'triangle-up', 'cross', 'diamond', 'triangle-right', 'triangle-down', 'triangle-left']\n }\n };\n}\n\nfunction parse (spec, config, options) {\n if (!isObject(spec)) {\n error('Input Vega specification must be an object.');\n }\n\n config = mergeConfig(defaults(), config, spec.config);\n return parseView(spec, new Scope(config, options)).toRuntime();\n}\n\nexport { AxisDomainRole, AxisGridRole, AxisLabelRole, AxisRole, AxisTickRole, AxisTitleRole, DataScope, FrameRole, LegendEntryRole, LegendLabelRole, LegendRole, LegendSymbolRole, LegendTitleRole, MarkRole, Scope, ScopeRole, defaults as config, parse, parseSignal as signal, parseSignalUpdates as signalUpdates, parseStream as stream };\n","import { extend } from 'vega-util';\nexport * from 'vega-util';\nimport { transforms } from 'vega-dataflow';\nexport { Dataflow, EventStream, MultiPulse, Operator, Parameters, Pulse, Transform, changeset, definition, ingest, isTuple, transform, transforms, tupleid } from 'vega-dataflow';\nimport * as tx from 'vega-transforms';\nimport * as vtx from 'vega-view-transforms';\nimport * as encode from 'vega-encode';\nimport * as geo from 'vega-geo';\nimport * as force from 'vega-force';\nimport * as tree from 'vega-hierarchy';\nimport * as label from 'vega-label';\nimport * as reg from 'vega-regression';\nimport * as voronoi from 'vega-voronoi';\nimport * as wordcloud from 'vega-wordcloud';\nimport * as xf from 'vega-crossfilter';\nexport * from 'vega-statistics';\nexport * from 'vega-time';\nexport * from 'vega-loader';\nexport * from 'vega-scenegraph';\nexport { interpolate, interpolateColors, interpolateRange, quantizeInterpolator, scale, scheme } from 'vega-scale';\nexport { projection } from 'vega-projection';\nexport { View } from 'vega-view';\nexport { defaultLocale, numberFormatDefaultLocale as formatLocale, locale, resetDefaultLocale, timeFormatDefaultLocale as timeFormatLocale } from 'vega-format';\nexport { expressionFunction } from 'vega-functions';\nexport { parse } from 'vega-parser';\nexport { context as runtimeContext } from 'vega-runtime';\nexport { codegenExpression, parseExpression } from 'vega-expression';\nexport { parseSelector } from 'vega-event-selector';\n\nvar name = \"vega\";\nvar version$1 = \"5.21.0\";\nvar description = \"The Vega visualization grammar.\";\nvar keywords = [\n\t\"vega\",\n\t\"visualization\",\n\t\"interaction\",\n\t\"dataflow\",\n\t\"library\",\n\t\"data\",\n\t\"d3\"\n];\nvar license = \"BSD-3-Clause\";\nvar author = \"UW Interactive Data Lab (http://idl.cs.washington.edu)\";\nvar main = \"build/vega-node.js\";\nvar module = \"build/vega.module.js\";\nvar unpkg = \"build/vega.min.js\";\nvar jsdelivr = \"build/vega.min.js\";\nvar types = \"index.d.ts\";\nvar repository = \"vega/vega\";\nvar scripts = {\n\tbundle: \"rollup -c --config-bundle\",\n\tprebuild: \"rimraf build && rimraf build-es5\",\n\tbuild: \"rollup -c --config-core --config-bundle --config-ie\",\n\tpostbuild: \"node schema-copy\",\n\tpretest: \"yarn build --config-test\",\n\ttest: \"TZ=America/Los_Angeles tape 'test/**/*-test.js'\",\n\tprepublishOnly: \"yarn test && yarn build\",\n\tpostpublish: \"./schema-deploy.sh\"\n};\nvar dependencies = {\n\t\"vega-crossfilter\": \"~4.0.5\",\n\t\"vega-dataflow\": \"~5.7.4\",\n\t\"vega-encode\": \"~4.8.3\",\n\t\"vega-event-selector\": \"~3.0.0\",\n\t\"vega-expression\": \"~5.0.0\",\n\t\"vega-force\": \"~4.0.7\",\n\t\"vega-format\": \"~1.0.4\",\n\t\"vega-functions\": \"~5.12.1\",\n\t\"vega-geo\": \"~4.3.8\",\n\t\"vega-hierarchy\": \"~4.0.9\",\n\t\"vega-label\": \"~1.1.0\",\n\t\"vega-loader\": \"~4.4.1\",\n\t\"vega-parser\": \"~6.1.4\",\n\t\"vega-projection\": \"~1.4.5\",\n\t\"vega-regression\": \"~1.0.9\",\n\t\"vega-runtime\": \"~6.1.3\",\n\t\"vega-scale\": \"~7.1.1\",\n\t\"vega-scenegraph\": \"~4.9.4\",\n\t\"vega-statistics\": \"~1.7.10\",\n\t\"vega-time\": \"~2.0.4\",\n\t\"vega-transforms\": \"~4.9.4\",\n\t\"vega-typings\": \"~0.22.0\",\n\t\"vega-util\": \"~1.17.0\",\n\t\"vega-view\": \"~5.10.1\",\n\t\"vega-view-transforms\": \"~4.5.8\",\n\t\"vega-voronoi\": \"~4.1.5\",\n\t\"vega-wordcloud\": \"~4.1.3\"\n};\nvar devDependencies = {\n\t\"vega-schema\": \"*\"\n};\nvar gitHead = \"774165e29850b66ec8b79ba52a7955f1ab936ea6\";\nvar pkg = {\n\tname: name,\n\tversion: version$1,\n\tdescription: description,\n\tkeywords: keywords,\n\tlicense: license,\n\tauthor: author,\n\tmain: main,\n\tmodule: module,\n\tunpkg: unpkg,\n\tjsdelivr: jsdelivr,\n\ttypes: types,\n\trepository: repository,\n\tscripts: scripts,\n\tdependencies: dependencies,\n\tdevDependencies: devDependencies,\n\tgitHead: gitHead\n};\n\n// -- Transforms -----\nextend(transforms, tx, vtx, encode, geo, force, label, tree, reg, voronoi, wordcloud, xf); // -- Exports -----\n\nconst version = pkg.version;\n\nexport { version };\n","function adjustSpatial (item, encode, swap) {\n let t;\n\n if (encode.x2) {\n if (encode.x) {\n if (swap && item.x > item.x2) {\n t = item.x;\n item.x = item.x2;\n item.x2 = t;\n }\n\n item.width = item.x2 - item.x;\n } else {\n item.x = item.x2 - (item.width || 0);\n }\n }\n\n if (encode.xc) {\n item.x = item.xc - (item.width || 0) / 2;\n }\n\n if (encode.y2) {\n if (encode.y) {\n if (swap && item.y > item.y2) {\n t = item.y;\n item.y = item.y2;\n item.y2 = t;\n }\n\n item.height = item.y2 - item.y;\n } else {\n item.y = item.y2 - (item.height || 0);\n }\n }\n\n if (encode.yc) {\n item.y = item.yc - (item.height || 0) / 2;\n }\n}\n\nvar Constants = {\n NaN: NaN,\n E: Math.E,\n LN2: Math.LN2,\n LN10: Math.LN10,\n LOG2E: Math.LOG2E,\n LOG10E: Math.LOG10E,\n PI: Math.PI,\n SQRT1_2: Math.SQRT1_2,\n SQRT2: Math.SQRT2,\n MIN_VALUE: Number.MIN_VALUE,\n MAX_VALUE: Number.MAX_VALUE\n};\n\nvar Ops = {\n '*': (a, b) => a * b,\n '+': (a, b) => a + b,\n '-': (a, b) => a - b,\n '/': (a, b) => a / b,\n '%': (a, b) => a % b,\n '>': (a, b) => a > b,\n '<': (a, b) => a < b,\n '<=': (a, b) => a <= b,\n '>=': (a, b) => a >= b,\n '==': (a, b) => a == b,\n '!=': (a, b) => a != b,\n '===': (a, b) => a === b,\n '!==': (a, b) => a !== b,\n '&': (a, b) => a & b,\n '|': (a, b) => a | b,\n '^': (a, b) => a ^ b,\n '<<': (a, b) => a << b,\n '>>': (a, b) => a >> b,\n '>>>': (a, b) => a >>> b\n};\n\nvar Unary = {\n '+': a => +a,\n '-': a => -a,\n '~': a => ~a,\n '!': a => !a\n};\n\nconst slice = Array.prototype.slice;\n\nconst apply = (m, args, cast) => {\n const obj = cast ? cast(args[0]) : args[0];\n return obj[m].apply(obj, slice.call(args, 1));\n};\n\nconst datetime = (y, m, d, H, M, S, ms) => new Date(y, m || 0, d != null ? d : 1, H || 0, M || 0, S || 0, ms || 0);\n\nvar Functions = {\n // math functions\n isNaN: Number.isNaN,\n isFinite: Number.isFinite,\n abs: Math.abs,\n acos: Math.acos,\n asin: Math.asin,\n atan: Math.atan,\n atan2: Math.atan2,\n ceil: Math.ceil,\n cos: Math.cos,\n exp: Math.exp,\n floor: Math.floor,\n log: Math.log,\n max: Math.max,\n min: Math.min,\n pow: Math.pow,\n random: Math.random,\n round: Math.round,\n sin: Math.sin,\n sqrt: Math.sqrt,\n tan: Math.tan,\n clamp: (a, b, c) => Math.max(b, Math.min(c, a)),\n // date functions\n now: Date.now,\n utc: Date.UTC,\n datetime: datetime,\n date: d => new Date(d).getDate(),\n day: d => new Date(d).getDay(),\n year: d => new Date(d).getFullYear(),\n month: d => new Date(d).getMonth(),\n hours: d => new Date(d).getHours(),\n minutes: d => new Date(d).getMinutes(),\n seconds: d => new Date(d).getSeconds(),\n milliseconds: d => new Date(d).getMilliseconds(),\n time: d => new Date(d).getTime(),\n timezoneoffset: d => new Date(d).getTimezoneOffset(),\n utcdate: d => new Date(d).getUTCDate(),\n utcday: d => new Date(d).getUTCDay(),\n utcyear: d => new Date(d).getUTCFullYear(),\n utcmonth: d => new Date(d).getUTCMonth(),\n utchours: d => new Date(d).getUTCHours(),\n utcminutes: d => new Date(d).getUTCMinutes(),\n utcseconds: d => new Date(d).getUTCSeconds(),\n utcmilliseconds: d => new Date(d).getUTCMilliseconds(),\n // sequence functions\n length: x => x.length,\n join: function () {\n return apply('join', arguments);\n },\n indexof: function () {\n return apply('indexOf', arguments);\n },\n lastindexof: function () {\n return apply('lastIndexOf', arguments);\n },\n slice: function () {\n return apply('slice', arguments);\n },\n reverse: x => x.slice().reverse(),\n // string functions\n parseFloat: parseFloat,\n parseInt: parseInt,\n upper: x => String(x).toUpperCase(),\n lower: x => String(x).toLowerCase(),\n substring: function () {\n return apply('substring', arguments, String);\n },\n split: function () {\n return apply('split', arguments, String);\n },\n replace: function () {\n return apply('replace', arguments, String);\n },\n trim: x => String(x).trim(),\n // regexp functions\n regexp: RegExp,\n test: (r, t) => RegExp(r).test(t)\n};\n\nconst EventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y'];\nconst Visitors = {\n Literal: ($, n) => n.value,\n Identifier: ($, n) => {\n const id = n.name;\n return $.memberDepth > 0 ? id : id === 'datum' ? $.datum : id === 'event' ? $.event : id === 'item' ? $.item : Constants[id] || $.params['$' + id];\n },\n MemberExpression: ($, n) => {\n const d = !n.computed,\n o = $(n.object);\n if (d) $.memberDepth += 1;\n const p = $(n.property);\n if (d) $.memberDepth -= 1;\n return o[p];\n },\n CallExpression: ($, n) => {\n const args = n.arguments;\n let name = n.callee.name; // handle special internal functions used by encoders\n // re-route to corresponding standard function\n\n if (name.startsWith('_')) {\n name = name.slice(1);\n } // special case \"if\" due to conditional evaluation of branches\n\n\n return name === 'if' ? $(args[0]) ? $(args[1]) : $(args[2]) : ($.fn[name] || Functions[name]).apply($.fn, args.map($));\n },\n ArrayExpression: ($, n) => n.elements.map($),\n BinaryExpression: ($, n) => Ops[n.operator]($(n.left), $(n.right)),\n UnaryExpression: ($, n) => Unary[n.operator]($(n.argument)),\n ConditionalExpression: ($, n) => $(n.test) ? $(n.consequent) : $(n.alternate),\n LogicalExpression: ($, n) => n.operator === '&&' ? $(n.left) && $(n.right) : $(n.left) || $(n.right),\n ObjectExpression: ($, n) => n.properties.reduce((o, p) => {\n $.memberDepth += 1;\n const k = $(p.key);\n $.memberDepth -= 1;\n o[k] = $(p.value);\n return o;\n }, {})\n};\nfunction interpret (ast, fn, params, datum, event, item) {\n const $ = n => Visitors[n.type]($, n);\n\n $.memberDepth = 0;\n $.fn = Object.create(fn);\n $.params = params;\n $.datum = datum;\n $.event = event;\n $.item = item; // route event functions to annotated vega event context\n\n EventFunctions.forEach(f => $.fn[f] = (...args) => event.vega[f](...args));\n return $(ast);\n}\n\nvar expression = {\n /**\n * Parse an expression used to update an operator value.\n */\n operator(ctx, expr) {\n const ast = expr.ast,\n fn = ctx.functions;\n return _ => interpret(ast, fn, _);\n },\n\n /**\n * Parse an expression provided as an operator parameter value.\n */\n parameter(ctx, expr) {\n const ast = expr.ast,\n fn = ctx.functions;\n return (datum, _) => interpret(ast, fn, _, datum);\n },\n\n /**\n * Parse an expression applied to an event stream.\n */\n event(ctx, expr) {\n const ast = expr.ast,\n fn = ctx.functions;\n return event => interpret(ast, fn, undefined, undefined, event);\n },\n\n /**\n * Parse an expression used to handle an event-driven operator update.\n */\n handler(ctx, expr) {\n const ast = expr.ast,\n fn = ctx.functions;\n return (_, event) => {\n const datum = event.item && event.item.datum;\n return interpret(ast, fn, _, datum, event);\n };\n },\n\n /**\n * Parse an expression that performs visual encoding.\n */\n encode(ctx, encode) {\n const {\n marktype,\n channels\n } = encode,\n fn = ctx.functions,\n swap = marktype === 'group' || marktype === 'image' || marktype === 'rect';\n return (item, _) => {\n const datum = item.datum;\n let m = 0,\n v;\n\n for (const name in channels) {\n v = interpret(channels[name].ast, fn, _, datum, undefined, item);\n\n if (item[name] !== v) {\n item[name] = v;\n m = 1;\n }\n }\n\n if (marktype !== 'rule') {\n adjustSpatial(item, channels, swap);\n }\n\n return m;\n };\n }\n\n};\n\nexport { expression as expressionInterpreter };\n","function accessor (fn, fields, name) {\n fn.fields = fields || [];\n fn.fname = name;\n return fn;\n}\nfunction accessorName(fn) {\n return fn == null ? null : fn.fname;\n}\nfunction accessorFields(fn) {\n return fn == null ? null : fn.fields;\n}\n\nfunction getter (path) {\n return path.length === 1 ? get1(path[0]) : getN(path);\n}\n\nconst get1 = field => function (obj) {\n return obj[field];\n};\n\nconst getN = path => {\n const len = path.length;\n return function (obj) {\n for (let i = 0; i < len; ++i) {\n obj = obj[path[i]];\n }\n\n return obj;\n };\n};\n\nfunction error (message) {\n throw Error(message);\n}\n\nfunction splitAccessPath (p) {\n const path = [],\n n = p.length;\n let q = null,\n b = 0,\n s = '',\n i,\n j,\n c;\n p = p + '';\n\n function push() {\n path.push(s + p.substring(i, j));\n s = '';\n i = j + 1;\n }\n\n for (i = j = 0; j < n; ++j) {\n c = p[j];\n\n if (c === '\\\\') {\n s += p.substring(i, j);\n s += p.substring(++j, ++j);\n i = j;\n } else if (c === q) {\n push();\n q = null;\n b = -1;\n } else if (q) {\n continue;\n } else if (i === b && c === '\"') {\n i = j + 1;\n q = c;\n } else if (i === b && c === \"'\") {\n i = j + 1;\n q = c;\n } else if (c === '.' && !b) {\n if (j > i) {\n push();\n } else {\n i = j + 1;\n }\n } else if (c === '[') {\n if (j > i) push();\n b = i = j + 1;\n } else if (c === ']') {\n if (!b) error('Access path missing open bracket: ' + p);\n if (b > 0) push();\n b = 0;\n i = j + 1;\n }\n }\n\n if (b) error('Access path missing closing bracket: ' + p);\n if (q) error('Access path missing closing quote: ' + p);\n\n if (j > i) {\n j++;\n push();\n }\n\n return path;\n}\n\nfunction field (field, name, opt) {\n const path = splitAccessPath(field);\n field = path.length === 1 ? path[0] : field;\n return accessor((opt && opt.get || getter)(path), [field], name || field);\n}\n\nconst id = field('id');\nconst identity = accessor(_ => _, [], 'identity');\nconst zero = accessor(() => 0, [], 'zero');\nconst one = accessor(() => 1, [], 'one');\nconst truthy = accessor(() => true, [], 'true');\nconst falsy = accessor(() => false, [], 'false');\n\nfunction log$1(method, level, input) {\n const args = [level].concat([].slice.call(input));\n console[method].apply(console, args); // eslint-disable-line no-console\n}\n\nconst None = 0;\nconst Error$1 = 1;\nconst Warn = 2;\nconst Info = 3;\nconst Debug = 4;\nfunction logger (_, method) {\n let level = _ || None;\n return {\n level(_) {\n if (arguments.length) {\n level = +_;\n return this;\n } else {\n return level;\n }\n },\n\n error() {\n if (level >= Error$1) log$1(method || 'error', 'ERROR', arguments);\n return this;\n },\n\n warn() {\n if (level >= Warn) log$1(method || 'warn', 'WARN', arguments);\n return this;\n },\n\n info() {\n if (level >= Info) log$1(method || 'log', 'INFO', arguments);\n return this;\n },\n\n debug() {\n if (level >= Debug) log$1(method || 'log', 'DEBUG', arguments);\n return this;\n }\n\n };\n}\n\nvar isArray = Array.isArray;\n\nfunction isObject (_) {\n return _ === Object(_);\n}\n\nconst isLegalKey = key => key !== '__proto__';\n\nfunction mergeConfig(...configs) {\n return configs.reduce((out, source) => {\n for (const key in source) {\n if (key === 'signals') {\n // for signals, we merge the signals arrays\n // source signals take precedence over\n // existing signals with the same name\n out.signals = mergeNamed(out.signals, source.signals);\n } else {\n // otherwise, merge objects subject to recursion constraints\n // for legend block, recurse for the layout entry only\n // for style block, recurse for all properties\n // otherwise, no recursion: objects overwrite, no merging\n const r = key === 'legend' ? {\n layout: 1\n } : key === 'style' ? true : null;\n writeConfig(out, key, source[key], r);\n }\n }\n\n return out;\n }, {});\n}\nfunction writeConfig(output, key, value, recurse) {\n if (!isLegalKey(key)) return;\n let k, o;\n\n if (isObject(value) && !isArray(value)) {\n o = isObject(output[key]) ? output[key] : output[key] = {};\n\n for (k in value) {\n if (recurse && (recurse === true || recurse[k])) {\n writeConfig(o, k, value[k]);\n } else if (isLegalKey(k)) {\n o[k] = value[k];\n }\n }\n } else {\n output[key] = value;\n }\n}\n\nfunction mergeNamed(a, b) {\n if (a == null) return b;\n const map = {},\n out = [];\n\n function add(_) {\n if (!map[_.name]) {\n map[_.name] = 1;\n out.push(_);\n }\n }\n\n b.forEach(add);\n a.forEach(add);\n return out;\n}\n\nfunction peek (array) {\n return array[array.length - 1];\n}\n\nfunction toNumber (_) {\n return _ == null || _ === '' ? null : +_;\n}\n\nconst exp = sign => x => sign * Math.exp(x);\n\nconst log = sign => x => Math.log(sign * x);\n\nconst symlog = c => x => Math.sign(x) * Math.log1p(Math.abs(x / c));\n\nconst symexp = c => x => Math.sign(x) * Math.expm1(Math.abs(x)) * c;\n\nconst pow = exponent => x => x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);\n\nfunction pan(domain, delta, lift, ground) {\n const d0 = lift(domain[0]),\n d1 = lift(peek(domain)),\n dd = (d1 - d0) * delta;\n return [ground(d0 - dd), ground(d1 - dd)];\n}\n\nfunction panLinear(domain, delta) {\n return pan(domain, delta, toNumber, identity);\n}\nfunction panLog(domain, delta) {\n var sign = Math.sign(domain[0]);\n return pan(domain, delta, log(sign), exp(sign));\n}\nfunction panPow(domain, delta, exponent) {\n return pan(domain, delta, pow(exponent), pow(1 / exponent));\n}\nfunction panSymlog(domain, delta, constant) {\n return pan(domain, delta, symlog(constant), symexp(constant));\n}\n\nfunction zoom(domain, anchor, scale, lift, ground) {\n const d0 = lift(domain[0]),\n d1 = lift(peek(domain)),\n da = anchor != null ? lift(anchor) : (d0 + d1) / 2;\n return [ground(da + (d0 - da) * scale), ground(da + (d1 - da) * scale)];\n}\n\nfunction zoomLinear(domain, anchor, scale) {\n return zoom(domain, anchor, scale, toNumber, identity);\n}\nfunction zoomLog(domain, anchor, scale) {\n const sign = Math.sign(domain[0]);\n return zoom(domain, anchor, scale, log(sign), exp(sign));\n}\nfunction zoomPow(domain, anchor, scale, exponent) {\n return zoom(domain, anchor, scale, pow(exponent), pow(1 / exponent));\n}\nfunction zoomSymlog(domain, anchor, scale, constant) {\n return zoom(domain, anchor, scale, symlog(constant), symexp(constant));\n}\n\nfunction quarter(date) {\n return 1 + ~~(new Date(date).getMonth() / 3);\n}\nfunction utcquarter(date) {\n return 1 + ~~(new Date(date).getUTCMonth() / 3);\n}\n\nfunction array (_) {\n return _ != null ? isArray(_) ? _ : [_] : [];\n}\n\n/**\n * Span-preserving range clamp. If the span of the input range is less\n * than (max - min) and an endpoint exceeds either the min or max value,\n * the range is translated such that the span is preserved and one\n * endpoint touches the boundary of the min/max range.\n * If the span exceeds (max - min), the range [min, max] is returned.\n */\nfunction clampRange (range, min, max) {\n let lo = range[0],\n hi = range[1],\n span;\n\n if (hi < lo) {\n span = hi;\n hi = lo;\n lo = span;\n }\n\n span = hi - lo;\n return span >= max - min ? [min, max] : [lo = Math.min(Math.max(lo, min), max - span), lo + span];\n}\n\nfunction isFunction (_) {\n return typeof _ === 'function';\n}\n\nconst DESCENDING = 'descending';\nfunction compare (fields, orders, opt) {\n opt = opt || {};\n orders = array(orders) || [];\n const ord = [],\n get = [],\n fmap = {},\n gen = opt.comparator || comparator;\n array(fields).forEach((f, i) => {\n if (f == null) return;\n ord.push(orders[i] === DESCENDING ? -1 : 1);\n get.push(f = isFunction(f) ? f : field(f, null, opt));\n (accessorFields(f) || []).forEach(_ => fmap[_] = 1);\n });\n return get.length === 0 ? null : accessor(gen(get, ord), Object.keys(fmap));\n}\nconst ascending = (u, v) => (u < v || u == null) && v != null ? -1 : (u > v || v == null) && u != null ? 1 : (v = v instanceof Date ? +v : v, u = u instanceof Date ? +u : u) !== u && v === v ? -1 : v !== v && u === u ? 1 : 0;\n\nconst comparator = (fields, orders) => fields.length === 1 ? compare1(fields[0], orders[0]) : compareN(fields, orders, fields.length);\n\nconst compare1 = (field, order) => function (a, b) {\n return ascending(field(a), field(b)) * order;\n};\n\nconst compareN = (fields, orders, n) => {\n orders.push(0); // pad zero for convenient lookup\n\n return function (a, b) {\n let f,\n c = 0,\n i = -1;\n\n while (c === 0 && ++i < n) {\n f = fields[i];\n c = ascending(f(a), f(b));\n }\n\n return c * orders[i];\n };\n};\n\nfunction constant (_) {\n return isFunction(_) ? _ : () => _;\n}\n\nfunction debounce (delay, handler) {\n let tid;\n return e => {\n if (tid) clearTimeout(tid);\n tid = setTimeout(() => (handler(e), tid = null), delay);\n };\n}\n\nfunction extend (_) {\n for (let x, k, i = 1, len = arguments.length; i < len; ++i) {\n x = arguments[i];\n\n for (k in x) {\n _[k] = x[k];\n }\n }\n\n return _;\n}\n\n/**\n * Return an array with minimum and maximum values, in the\n * form [min, max]. Ignores null, undefined, and NaN values.\n */\nfunction extent (array, f) {\n let i = 0,\n n,\n v,\n min,\n max;\n\n if (array && (n = array.length)) {\n if (f == null) {\n // find first valid value\n for (v = array[i]; i < n && (v == null || v !== v); v = array[++i]);\n\n min = max = v; // visit all other values\n\n for (; i < n; ++i) {\n v = array[i]; // skip null/undefined; NaN will fail all comparisons\n\n if (v != null) {\n if (v < min) min = v;\n if (v > max) max = v;\n }\n }\n } else {\n // find first valid value\n for (v = f(array[i]); i < n && (v == null || v !== v); v = f(array[++i]));\n\n min = max = v; // visit all other values\n\n for (; i < n; ++i) {\n v = f(array[i]); // skip null/undefined; NaN will fail all comparisons\n\n if (v != null) {\n if (v < min) min = v;\n if (v > max) max = v;\n }\n }\n }\n }\n\n return [min, max];\n}\n\nfunction extentIndex (array, f) {\n const n = array.length;\n let i = -1,\n a,\n b,\n c,\n u,\n v;\n\n if (f == null) {\n while (++i < n) {\n b = array[i];\n\n if (b != null && b >= b) {\n a = c = b;\n break;\n }\n }\n\n if (i === n) return [-1, -1];\n u = v = i;\n\n while (++i < n) {\n b = array[i];\n\n if (b != null) {\n if (a > b) {\n a = b;\n u = i;\n }\n\n if (c < b) {\n c = b;\n v = i;\n }\n }\n }\n } else {\n while (++i < n) {\n b = f(array[i], i, array);\n\n if (b != null && b >= b) {\n a = c = b;\n break;\n }\n }\n\n if (i === n) return [-1, -1];\n u = v = i;\n\n while (++i < n) {\n b = f(array[i], i, array);\n\n if (b != null) {\n if (a > b) {\n a = b;\n u = i;\n }\n\n if (c < b) {\n c = b;\n v = i;\n }\n }\n }\n }\n\n return [u, v];\n}\n\nconst hop = Object.prototype.hasOwnProperty;\nfunction has (object, property) {\n return hop.call(object, property);\n}\n\nconst NULL = {};\nfunction fastmap (input) {\n let obj = {},\n test;\n\n function has$1(key) {\n return has(obj, key) && obj[key] !== NULL;\n }\n\n const map = {\n size: 0,\n empty: 0,\n object: obj,\n has: has$1,\n\n get(key) {\n return has$1(key) ? obj[key] : undefined;\n },\n\n set(key, value) {\n if (!has$1(key)) {\n ++map.size;\n if (obj[key] === NULL) --map.empty;\n }\n\n obj[key] = value;\n return this;\n },\n\n delete(key) {\n if (has$1(key)) {\n --map.size;\n ++map.empty;\n obj[key] = NULL;\n }\n\n return this;\n },\n\n clear() {\n map.size = map.empty = 0;\n map.object = obj = {};\n },\n\n test(_) {\n if (arguments.length) {\n test = _;\n return map;\n } else {\n return test;\n }\n },\n\n clean() {\n const next = {};\n let size = 0;\n\n for (const key in obj) {\n const value = obj[key];\n\n if (value !== NULL && (!test || !test(value))) {\n next[key] = value;\n ++size;\n }\n }\n\n map.size = size;\n map.empty = 0;\n map.object = obj = next;\n }\n\n };\n if (input) Object.keys(input).forEach(key => {\n map.set(key, input[key]);\n });\n return map;\n}\n\nfunction flush (range, value, threshold, left, right, center) {\n if (!threshold && threshold !== 0) return center;\n const t = +threshold;\n let a = range[0],\n b = peek(range),\n l; // swap endpoints if range is reversed\n\n if (b < a) {\n l = a;\n a = b;\n b = l;\n } // compare value to endpoints\n\n\n l = Math.abs(value - a);\n const r = Math.abs(b - value); // adjust if value is within threshold distance of endpoint\n\n return l < r && l <= t ? left : r <= t ? right : center;\n}\n\nfunction inherits (child, parent, members) {\n const proto = child.prototype = Object.create(parent.prototype);\n Object.defineProperty(proto, 'constructor', {\n value: child,\n writable: true,\n enumerable: true,\n configurable: true\n });\n return extend(proto, members);\n}\n\n/**\n * Predicate that returns true if the value lies within the span\n * of the given range. The left and right flags control the use\n * of inclusive (true) or exclusive (false) comparisons.\n */\nfunction inrange (value, range, left, right) {\n let r0 = range[0],\n r1 = range[range.length - 1],\n t;\n\n if (r0 > r1) {\n t = r0;\n r0 = r1;\n r1 = t;\n }\n\n left = left === undefined || left;\n right = right === undefined || right;\n return (left ? r0 <= value : r0 < value) && (right ? value <= r1 : value < r1);\n}\n\nfunction isBoolean (_) {\n return typeof _ === 'boolean';\n}\n\nfunction isDate (_) {\n return Object.prototype.toString.call(_) === '[object Date]';\n}\n\nfunction isIterable (_) {\n return _ && isFunction(_[Symbol.iterator]);\n}\n\nfunction isNumber (_) {\n return typeof _ === 'number';\n}\n\nfunction isRegExp (_) {\n return Object.prototype.toString.call(_) === '[object RegExp]';\n}\n\nfunction isString (_) {\n return typeof _ === 'string';\n}\n\nfunction key (fields, flat, opt) {\n if (fields) {\n fields = flat ? array(fields).map(f => f.replace(/\\\\(.)/g, '$1')) : array(fields);\n }\n\n const len = fields && fields.length,\n gen = opt && opt.get || getter,\n map = f => gen(flat ? [f] : splitAccessPath(f));\n\n let fn;\n\n if (!len) {\n fn = function () {\n return '';\n };\n } else if (len === 1) {\n const get = map(fields[0]);\n\n fn = function (_) {\n return '' + get(_);\n };\n } else {\n const get = fields.map(map);\n\n fn = function (_) {\n let s = '' + get[0](_),\n i = 0;\n\n while (++i < len) s += '|' + get[i](_);\n\n return s;\n };\n }\n\n return accessor(fn, fields, 'key');\n}\n\nfunction lerp (array, frac) {\n const lo = array[0],\n hi = peek(array),\n f = +frac;\n return !f ? lo : f === 1 ? hi : lo + f * (hi - lo);\n}\n\nconst DEFAULT_MAX_SIZE = 10000; // adapted from https://github.com/dominictarr/hashlru/ (MIT License)\n\nfunction lruCache (maxsize) {\n maxsize = +maxsize || DEFAULT_MAX_SIZE;\n let curr, prev, size;\n\n const clear = () => {\n curr = {};\n prev = {};\n size = 0;\n };\n\n const update = (key, value) => {\n if (++size > maxsize) {\n prev = curr;\n curr = {};\n size = 1;\n }\n\n return curr[key] = value;\n };\n\n clear();\n return {\n clear,\n has: key => has(curr, key) || has(prev, key),\n get: key => has(curr, key) ? curr[key] : has(prev, key) ? update(key, prev[key]) : undefined,\n set: (key, value) => has(curr, key) ? curr[key] = value : update(key, value)\n };\n}\n\nfunction merge (compare, array0, array1, output) {\n const n0 = array0.length,\n n1 = array1.length;\n if (!n1) return array0;\n if (!n0) return array1;\n const merged = output || new array0.constructor(n0 + n1);\n let i0 = 0,\n i1 = 0,\n i = 0;\n\n for (; i0 < n0 && i1 < n1; ++i) {\n merged[i] = compare(array0[i0], array1[i1]) > 0 ? array1[i1++] : array0[i0++];\n }\n\n for (; i0 < n0; ++i0, ++i) {\n merged[i] = array0[i0];\n }\n\n for (; i1 < n1; ++i1, ++i) {\n merged[i] = array1[i1];\n }\n\n return merged;\n}\n\nfunction repeat (str, reps) {\n let s = '';\n\n while (--reps >= 0) s += str;\n\n return s;\n}\n\nfunction pad (str, length, padchar, align) {\n const c = padchar || ' ',\n s = str + '',\n n = length - s.length;\n return n <= 0 ? s : align === 'left' ? repeat(c, n) + s : align === 'center' ? repeat(c, ~~(n / 2)) + s + repeat(c, Math.ceil(n / 2)) : s + repeat(c, n);\n}\n\n/**\n * Return the numerical span of an array: the difference between\n * the last and first values.\n */\n\nfunction span (array) {\n return array && peek(array) - array[0] || 0;\n}\n\nfunction $(x) {\n return isArray(x) ? '[' + x.map($) + ']' : isObject(x) || isString(x) ? // Output valid JSON and JS source strings.\n // See http://timelessrepo.com/json-isnt-a-javascript-subset\n JSON.stringify(x).replace('\\u2028', '\\\\u2028').replace('\\u2029', '\\\\u2029') : x;\n}\n\nfunction toBoolean (_) {\n return _ == null || _ === '' ? null : !_ || _ === 'false' || _ === '0' ? false : !!_;\n}\n\nconst defaultParser = _ => isNumber(_) ? _ : isDate(_) ? _ : Date.parse(_);\n\nfunction toDate (_, parser) {\n parser = parser || defaultParser;\n return _ == null || _ === '' ? null : parser(_);\n}\n\nfunction toString (_) {\n return _ == null || _ === '' ? null : _ + '';\n}\n\nfunction toSet (_) {\n const s = {},\n n = _.length;\n\n for (let i = 0; i < n; ++i) s[_[i]] = true;\n\n return s;\n}\n\nfunction truncate (str, length, align, ellipsis) {\n const e = ellipsis != null ? ellipsis : '\\u2026',\n s = str + '',\n n = s.length,\n l = Math.max(0, length - e.length);\n return n <= length ? s : align === 'left' ? e + s.slice(n - l) : align === 'center' ? s.slice(0, Math.ceil(l / 2)) + e + s.slice(n - ~~(l / 2)) : s.slice(0, l) + e;\n}\n\nfunction visitArray (array, filter, visitor) {\n if (array) {\n if (filter) {\n const n = array.length;\n\n for (let i = 0; i < n; ++i) {\n const t = filter(array[i]);\n if (t) visitor(t, i, array);\n }\n } else {\n array.forEach(visitor);\n }\n }\n}\n\nexport { Debug, Error$1 as Error, Info, None, Warn, accessor, accessorFields, accessorName, array, ascending, clampRange, compare, constant, debounce, error, extend, extent, extentIndex, falsy, fastmap, field, flush, has as hasOwnProperty, id, identity, inherits, inrange, isArray, isBoolean, isDate, isFunction, isIterable, isNumber, isObject, isRegExp, isString, key, lerp, logger, lruCache, merge, mergeConfig, one, pad, panLinear, panLog, panPow, panSymlog, peek, quarter, repeat, span, splitAccessPath, $ as stringValue, toBoolean, toDate, toNumber, toSet, toString, truncate, truthy, utcquarter, visitArray, writeConfig, zero, zoomLinear, zoomLog, zoomPow, zoomSymlog };\n","export function isLogicalOr(op) {\n return !!op.or;\n}\nexport function isLogicalAnd(op) {\n return !!op.and;\n}\nexport function isLogicalNot(op) {\n return !!op.not;\n}\nexport function forEachLeaf(op, fn) {\n if (isLogicalNot(op)) {\n forEachLeaf(op.not, fn);\n }\n else if (isLogicalAnd(op)) {\n for (const subop of op.and) {\n forEachLeaf(subop, fn);\n }\n }\n else if (isLogicalOr(op)) {\n for (const subop of op.or) {\n forEachLeaf(subop, fn);\n }\n }\n else {\n fn(op);\n }\n}\nexport function normalizeLogicalComposition(op, normalizer) {\n if (isLogicalNot(op)) {\n return { not: normalizeLogicalComposition(op.not, normalizer) };\n }\n else if (isLogicalAnd(op)) {\n return { and: op.and.map(o => normalizeLogicalComposition(o, normalizer)) };\n }\n else if (isLogicalOr(op)) {\n return { or: op.or.map(o => normalizeLogicalComposition(o, normalizer)) };\n }\n else {\n return normalizer(op);\n }\n}\n//# sourceMappingURL=logical.js.map","/*\n * Constants and utilities for encoding channels (Visual variables)\n * such as 'x', 'y', 'color'.\n */\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { keys } from './util';\n// Facet\nexport const ROW = 'row';\nexport const COLUMN = 'column';\nexport const FACET = 'facet';\n// Position\nexport const X = 'x';\nexport const Y = 'y';\nexport const X2 = 'x2';\nexport const Y2 = 'y2';\n// Arc-Position\nexport const RADIUS = 'radius';\nexport const RADIUS2 = 'radius2';\nexport const THETA = 'theta';\nexport const THETA2 = 'theta2';\n// Geo Position\nexport const LATITUDE = 'latitude';\nexport const LONGITUDE = 'longitude';\nexport const LATITUDE2 = 'latitude2';\nexport const LONGITUDE2 = 'longitude2';\n// Mark property with scale\nexport const COLOR = 'color';\nexport const FILL = 'fill';\nexport const STROKE = 'stroke';\nexport const SHAPE = 'shape';\nexport const SIZE = 'size';\nexport const ANGLE = 'angle';\nexport const OPACITY = 'opacity';\nexport const FILLOPACITY = 'fillOpacity';\nexport const STROKEOPACITY = 'strokeOpacity';\nexport const STROKEWIDTH = 'strokeWidth';\nexport const STROKEDASH = 'strokeDash';\n// Non-scale channel\nexport const TEXT = 'text';\nexport const ORDER = 'order';\nexport const DETAIL = 'detail';\nexport const KEY = 'key';\nexport const TOOLTIP = 'tooltip';\nexport const HREF = 'href';\nexport const URL = 'url';\nexport const DESCRIPTION = 'description';\nconst POSITION_CHANNEL_INDEX = {\n x: 1,\n y: 1,\n x2: 1,\n y2: 1\n};\nconst POLAR_POSITION_CHANNEL_INDEX = {\n theta: 1,\n theta2: 1,\n radius: 1,\n radius2: 1\n};\nexport function isPolarPositionChannel(c) {\n return c in POLAR_POSITION_CHANNEL_INDEX;\n}\nconst GEO_POSIITON_CHANNEL_INDEX = {\n longitude: 1,\n longitude2: 1,\n latitude: 1,\n latitude2: 1\n};\nexport function getPositionChannelFromLatLong(channel) {\n switch (channel) {\n case LATITUDE:\n return 'y';\n case LATITUDE2:\n return 'y2';\n case LONGITUDE:\n return 'x';\n case LONGITUDE2:\n return 'x2';\n }\n}\nexport function isGeoPositionChannel(c) {\n return c in GEO_POSIITON_CHANNEL_INDEX;\n}\nexport const GEOPOSITION_CHANNELS = keys(GEO_POSIITON_CHANNEL_INDEX);\nconst UNIT_CHANNEL_INDEX = Object.assign(Object.assign(Object.assign(Object.assign({}, POSITION_CHANNEL_INDEX), POLAR_POSITION_CHANNEL_INDEX), GEO_POSIITON_CHANNEL_INDEX), { \n // color\n color: 1, fill: 1, stroke: 1, \n // other non-position with scale\n opacity: 1, fillOpacity: 1, strokeOpacity: 1, strokeWidth: 1, strokeDash: 1, size: 1, angle: 1, shape: 1, \n // channels without scales\n order: 1, text: 1, detail: 1, key: 1, tooltip: 1, href: 1, url: 1, description: 1 });\nexport function isColorChannel(channel) {\n return channel === COLOR || channel === FILL || channel === STROKE;\n}\nconst FACET_CHANNEL_INDEX = {\n row: 1,\n column: 1,\n facet: 1\n};\nexport const FACET_CHANNELS = keys(FACET_CHANNEL_INDEX);\nconst CHANNEL_INDEX = Object.assign(Object.assign({}, UNIT_CHANNEL_INDEX), FACET_CHANNEL_INDEX);\nexport const CHANNELS = keys(CHANNEL_INDEX);\nconst { order: _o, detail: _d, tooltip: _tt1 } = CHANNEL_INDEX, SINGLE_DEF_CHANNEL_INDEX = __rest(CHANNEL_INDEX, [\"order\", \"detail\", \"tooltip\"]);\nconst { row: _r, column: _c, facet: _f } = SINGLE_DEF_CHANNEL_INDEX, SINGLE_DEF_UNIT_CHANNEL_INDEX = __rest(SINGLE_DEF_CHANNEL_INDEX, [\"row\", \"column\", \"facet\"]);\n/**\n * Channels that cannot have an array of channelDef.\n * model.fieldDef, getFieldDef only work for these channels.\n *\n * (The only two channels that can have an array of channelDefs are \"detail\" and \"order\".\n * Since there can be multiple fieldDefs for detail and order, getFieldDef/model.fieldDef\n * are not applicable for them. Similarly, selection projection won't work with \"detail\" and \"order\".)\n */\nexport const SINGLE_DEF_CHANNELS = keys(SINGLE_DEF_CHANNEL_INDEX);\nexport const SINGLE_DEF_UNIT_CHANNELS = keys(SINGLE_DEF_UNIT_CHANNEL_INDEX);\nexport function isSingleDefUnitChannel(str) {\n return !!SINGLE_DEF_UNIT_CHANNEL_INDEX[str];\n}\nexport function isChannel(str) {\n return !!CHANNEL_INDEX[str];\n}\nexport const SECONDARY_RANGE_CHANNEL = [X2, Y2, LATITUDE2, LONGITUDE2, THETA2, RADIUS2];\nexport function isSecondaryRangeChannel(c) {\n const main = getMainRangeChannel(c);\n return main !== c;\n}\n/**\n * Get the main channel for a range channel. E.g. `x` for `x2`.\n */\nexport function getMainRangeChannel(channel) {\n switch (channel) {\n case X2:\n return X;\n case Y2:\n return Y;\n case LATITUDE2:\n return LATITUDE;\n case LONGITUDE2:\n return LONGITUDE;\n case THETA2:\n return THETA;\n case RADIUS2:\n return RADIUS;\n }\n return channel;\n}\nexport function getVgPositionChannel(channel) {\n if (isPolarPositionChannel(channel)) {\n switch (channel) {\n case THETA:\n return 'startAngle';\n case THETA2:\n return 'endAngle';\n case RADIUS:\n return 'outerRadius';\n case RADIUS2:\n return 'innerRadius';\n }\n }\n return channel;\n}\n/**\n * Get the main channel for a range channel. E.g. `x` for `x2`.\n */\nexport function getSecondaryRangeChannel(channel) {\n switch (channel) {\n case X:\n return X2;\n case Y:\n return Y2;\n case LATITUDE:\n return LATITUDE2;\n case LONGITUDE:\n return LONGITUDE2;\n case THETA:\n return THETA2;\n case RADIUS:\n return RADIUS2;\n }\n return undefined;\n}\nexport function getSizeChannel(channel) {\n switch (channel) {\n case X:\n case X2:\n return 'width';\n case Y:\n case Y2:\n return 'height';\n }\n return undefined;\n}\n/**\n * Get the main channel for a range channel. E.g. `x` for `x2`.\n */\nexport function getOffsetChannel(channel) {\n switch (channel) {\n case X:\n return 'xOffset';\n case Y:\n return 'yOffset';\n case X2:\n return 'x2Offset';\n case Y2:\n return 'y2Offset';\n case THETA:\n return 'thetaOffset';\n case RADIUS:\n return 'radiusOffset';\n case THETA2:\n return 'theta2Offset';\n case RADIUS2:\n return 'radius2Offset';\n }\n return undefined;\n}\n// CHANNELS without COLUMN, ROW\nexport const UNIT_CHANNELS = keys(UNIT_CHANNEL_INDEX);\n// NONPOSITION_CHANNELS = UNIT_CHANNELS without X, Y, X2, Y2;\nconst { x: _x, y: _y, \n// x2 and y2 share the same scale as x and y\nx2: _x2, y2: _y2, latitude: _latitude, longitude: _longitude, latitude2: _latitude2, longitude2: _longitude2, theta: _theta, theta2: _theta2, radius: _radius, radius2: _radius2 } = UNIT_CHANNEL_INDEX, \n// The rest of unit channels then have scale\nNONPOSITION_CHANNEL_INDEX = __rest(UNIT_CHANNEL_INDEX, [\"x\", \"y\", \"x2\", \"y2\", \"latitude\", \"longitude\", \"latitude2\", \"longitude2\", \"theta\", \"theta2\", \"radius\", \"radius2\"]);\nexport const NONPOSITION_CHANNELS = keys(NONPOSITION_CHANNEL_INDEX);\nexport const POSITION_SCALE_CHANNEL_INDEX = {\n x: 1,\n y: 1\n};\nexport const POSITION_SCALE_CHANNELS = keys(POSITION_SCALE_CHANNEL_INDEX);\nexport function isXorY(channel) {\n return channel in POSITION_SCALE_CHANNEL_INDEX;\n}\nexport const POLAR_POSITION_SCALE_CHANNEL_INDEX = {\n theta: 1,\n radius: 1\n};\nexport const POLAR_POSITION_SCALE_CHANNELS = keys(POLAR_POSITION_SCALE_CHANNEL_INDEX);\nexport function getPositionScaleChannel(sizeType) {\n return sizeType === 'width' ? X : Y;\n}\n// NON_POSITION_SCALE_CHANNEL = SCALE_CHANNELS without X, Y\nconst { \n// x2 and y2 share the same scale as x and y\n// text and tooltip have format instead of scale,\n// href has neither format, nor scale\ntext: _t, tooltip: _tt, href: _hr, url: _u, description: _al, \n// detail and order have no scale\ndetail: _dd, key: _k, order: _oo } = NONPOSITION_CHANNEL_INDEX, NONPOSITION_SCALE_CHANNEL_INDEX = __rest(NONPOSITION_CHANNEL_INDEX, [\"text\", \"tooltip\", \"href\", \"url\", \"description\", \"detail\", \"key\", \"order\"]);\nexport const NONPOSITION_SCALE_CHANNELS = keys(NONPOSITION_SCALE_CHANNEL_INDEX);\nexport function isNonPositionScaleChannel(channel) {\n return !!NONPOSITION_CHANNEL_INDEX[channel];\n}\n/**\n * @returns whether Vega supports legends for a particular channel\n */\nexport function supportLegend(channel) {\n switch (channel) {\n case COLOR:\n case FILL:\n case STROKE:\n case SIZE:\n case SHAPE:\n case OPACITY:\n case STROKEWIDTH:\n case STROKEDASH:\n return true;\n case FILLOPACITY:\n case STROKEOPACITY:\n case ANGLE:\n return false;\n }\n}\n// Declare SCALE_CHANNEL_INDEX\nconst SCALE_CHANNEL_INDEX = Object.assign(Object.assign(Object.assign({}, POSITION_SCALE_CHANNEL_INDEX), POLAR_POSITION_SCALE_CHANNEL_INDEX), NONPOSITION_SCALE_CHANNEL_INDEX);\n/** List of channels with scales */\nexport const SCALE_CHANNELS = keys(SCALE_CHANNEL_INDEX);\nexport function isScaleChannel(channel) {\n return !!SCALE_CHANNEL_INDEX[channel];\n}\n/**\n * Return whether a channel supports a particular mark type.\n * @param channel channel name\n * @param mark the mark type\n * @return whether the mark supports the channel\n */\nexport function supportMark(channel, mark) {\n return getSupportedMark(channel)[mark];\n}\nconst ALL_MARKS = {\n // all marks\n arc: 'always',\n area: 'always',\n bar: 'always',\n circle: 'always',\n geoshape: 'always',\n image: 'always',\n line: 'always',\n rule: 'always',\n point: 'always',\n rect: 'always',\n square: 'always',\n trail: 'always',\n text: 'always',\n tick: 'always'\n};\nconst { geoshape: _g } = ALL_MARKS, ALL_MARKS_EXCEPT_GEOSHAPE = __rest(ALL_MARKS, [\"geoshape\"]);\n/**\n * Return a dictionary showing whether a channel supports mark type.\n * @param channel\n * @return A dictionary mapping mark types to 'always', 'binned', or undefined\n */\nfunction getSupportedMark(channel) {\n switch (channel) {\n case COLOR:\n case FILL:\n case STROKE:\n // falls through\n case DESCRIPTION:\n case DETAIL:\n case KEY:\n case TOOLTIP:\n case HREF:\n case ORDER: // TODO: revise (order might not support rect, which is not stackable?)\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n case STROKEWIDTH:\n // falls through\n case FACET:\n case ROW: // falls through\n case COLUMN:\n return ALL_MARKS;\n case X:\n case Y:\n case LATITUDE:\n case LONGITUDE:\n // all marks except geoshape. geoshape does not use X, Y -- it uses a projection\n return ALL_MARKS_EXCEPT_GEOSHAPE;\n case X2:\n case Y2:\n case LATITUDE2:\n case LONGITUDE2:\n return {\n area: 'always',\n bar: 'always',\n image: 'always',\n rect: 'always',\n rule: 'always',\n circle: 'binned',\n point: 'binned',\n square: 'binned',\n tick: 'binned',\n line: 'binned',\n trail: 'binned'\n };\n case SIZE:\n return {\n point: 'always',\n tick: 'always',\n rule: 'always',\n circle: 'always',\n square: 'always',\n bar: 'always',\n text: 'always',\n line: 'always',\n trail: 'always'\n };\n case STROKEDASH:\n return {\n line: 'always',\n point: 'always',\n tick: 'always',\n rule: 'always',\n circle: 'always',\n square: 'always',\n bar: 'always',\n geoshape: 'always'\n };\n case SHAPE:\n return { point: 'always', geoshape: 'always' };\n case TEXT:\n return { text: 'always' };\n case ANGLE:\n return { point: 'always', square: 'always', text: 'always' };\n case URL:\n return { image: 'always' };\n case THETA:\n return { text: 'always', arc: 'always' };\n case RADIUS:\n return { text: 'always', arc: 'always' };\n case THETA2:\n case RADIUS2:\n return { arc: 'always' };\n }\n}\nexport function rangeType(channel) {\n switch (channel) {\n case X:\n case Y:\n case THETA:\n case RADIUS:\n case SIZE:\n case ANGLE:\n case STROKEWIDTH:\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n // X2 and Y2 use X and Y scales, so they similarly have continuous range. [falls through]\n case X2:\n case Y2:\n case THETA2:\n case RADIUS2:\n return undefined;\n case FACET:\n case ROW:\n case COLUMN:\n case SHAPE:\n case STROKEDASH:\n // TEXT, TOOLTIP, URL, and HREF have no scale but have discrete output [falls through]\n case TEXT:\n case TOOLTIP:\n case HREF:\n case URL:\n case DESCRIPTION:\n return 'discrete';\n // Color can be either continuous or discrete, depending on scale type.\n case COLOR:\n case FILL:\n case STROKE:\n return 'flexible';\n // No scale, no range type.\n case LATITUDE:\n case LONGITUDE:\n case LATITUDE2:\n case LONGITUDE2:\n case DETAIL:\n case KEY:\n case ORDER:\n return undefined;\n }\n}\n//# sourceMappingURL=channel.js.map","import { isString, toSet } from 'vega-util';\nimport { contains, keys } from './util';\nconst AGGREGATE_OP_INDEX = {\n argmax: 1,\n argmin: 1,\n average: 1,\n count: 1,\n distinct: 1,\n product: 1,\n max: 1,\n mean: 1,\n median: 1,\n min: 1,\n missing: 1,\n q1: 1,\n q3: 1,\n ci0: 1,\n ci1: 1,\n stderr: 1,\n stdev: 1,\n stdevp: 1,\n sum: 1,\n valid: 1,\n values: 1,\n variance: 1,\n variancep: 1\n};\nexport const MULTIDOMAIN_SORT_OP_INDEX = {\n count: 1,\n min: 1,\n max: 1\n};\nexport function isArgminDef(a) {\n return !!a && !!a['argmin'];\n}\nexport function isArgmaxDef(a) {\n return !!a && !!a['argmax'];\n}\nexport const AGGREGATE_OPS = keys(AGGREGATE_OP_INDEX);\nexport function isAggregateOp(a) {\n return isString(a) && !!AGGREGATE_OP_INDEX[a];\n}\nexport const COUNTING_OPS = ['count', 'valid', 'missing', 'distinct'];\nexport function isCountingAggregateOp(aggregate) {\n return isString(aggregate) && contains(COUNTING_OPS, aggregate);\n}\nexport function isMinMaxOp(aggregate) {\n return isString(aggregate) && contains(['min', 'max'], aggregate);\n}\n/** Additive-based aggregation operations. These can be applied to stack. */\nexport const SUM_OPS = ['count', 'sum', 'distinct', 'valid', 'missing'];\n/**\n * Aggregation operators that always produce values within the range [domainMin, domainMax].\n */\nexport const SHARED_DOMAIN_OPS = ['mean', 'average', 'median', 'q1', 'q3', 'min', 'max'];\nexport const SHARED_DOMAIN_OP_INDEX = toSet(SHARED_DOMAIN_OPS);\n//# sourceMappingURL=aggregate.js.map","import { isBoolean, isObject } from 'vega-util';\nimport { COLOR, COLUMN, FILL, FILLOPACITY, OPACITY, ROW, SHAPE, SIZE, STROKE, STROKEDASH, STROKEOPACITY, STROKEWIDTH } from './channel';\nimport { normalizeBin } from './channeldef';\nimport { entries, keys, varName } from './util';\n/**\n * Create a key for the bin configuration. Not for prebinned bin.\n */\nexport function binToString(bin) {\n if (isBoolean(bin)) {\n bin = normalizeBin(bin, undefined);\n }\n return ('bin' +\n keys(bin)\n .map(p => (isParameterExtent(bin[p]) ? varName(`_${p}_${entries(bin[p])}`) : varName(`_${p}_${bin[p]}`)))\n .join(''));\n}\n/**\n * Vega-Lite should bin the data.\n */\nexport function isBinning(bin) {\n return bin === true || (isBinParams(bin) && !bin.binned);\n}\n/**\n * The data is already binned and so Vega-Lite should not bin it again.\n */\nexport function isBinned(bin) {\n return bin === 'binned' || (isBinParams(bin) && bin.binned === true);\n}\nexport function isBinParams(bin) {\n return isObject(bin);\n}\nexport function isParameterExtent(extent) {\n return extent === null || extent === void 0 ? void 0 : extent['param'];\n}\nexport function autoMaxBins(channel) {\n switch (channel) {\n case ROW:\n case COLUMN:\n case SIZE:\n case COLOR:\n case FILL:\n case STROKE:\n case STROKEWIDTH:\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n // Facets and Size shouldn't have too many bins\n // We choose 6 like shape to simplify the rule [falls through]\n case SHAPE:\n return 6; // Vega's \"shape\" has 6 distinct values\n case STROKEDASH:\n return 4; // We only provide 5 different stroke dash values (but 4 is more effective)\n default:\n return 10;\n }\n}\n//# sourceMappingURL=bin.js.map","import { signalRefOrValue } from './compile/common';\nimport { keys } from './util';\nexport function isExprRef(o) {\n return o && !!o['expr'];\n}\nexport function replaceExprRef(index) {\n const props = keys(index || {});\n const newIndex = {};\n for (const prop of props) {\n newIndex[prop] = signalRefOrValue(index[prop]);\n }\n return newIndex;\n}\n//# sourceMappingURL=expr.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isArray, isString } from 'vega-util';\nimport { pick } from './util';\nexport function extractTitleConfig(titleConfig) {\n const { \n // These are non-mark title config that need to be hardcoded\n anchor, frame, offset, orient, angle, limit, \n // color needs to be redirect to fill\n color, \n // subtitle properties\n subtitleColor, subtitleFont, subtitleFontSize, subtitleFontStyle, subtitleFontWeight, subtitleLineHeight, subtitlePadding } = titleConfig, \n // The rest are mark config.\n rest = __rest(titleConfig, [\"anchor\", \"frame\", \"offset\", \"orient\", \"angle\", \"limit\", \"color\", \"subtitleColor\", \"subtitleFont\", \"subtitleFontSize\", \"subtitleFontStyle\", \"subtitleFontWeight\", \"subtitleLineHeight\", \"subtitlePadding\"]);\n const titleMarkConfig = Object.assign(Object.assign({}, rest), (color ? { fill: color } : {}));\n // These are non-mark title config that need to be hardcoded\n const nonMarkTitleProperties = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (anchor ? { anchor } : {})), (frame ? { frame } : {})), (offset ? { offset } : {})), (orient ? { orient } : {})), (angle !== undefined ? { angle } : {})), (limit !== undefined ? { limit } : {}));\n // subtitle part can stay in config.title since header titles do not use subtitle\n const subtitle = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (subtitleColor ? { subtitleColor } : {})), (subtitleFont ? { subtitleFont } : {})), (subtitleFontSize ? { subtitleFontSize } : {})), (subtitleFontStyle ? { subtitleFontStyle } : {})), (subtitleFontWeight ? { subtitleFontWeight } : {})), (subtitleLineHeight ? { subtitleLineHeight } : {})), (subtitlePadding ? { subtitlePadding } : {}));\n const subtitleMarkConfig = pick(titleConfig, ['align', 'baseline', 'dx', 'dy', 'limit']);\n return { titleMarkConfig, subtitleMarkConfig, nonMarkTitleProperties: nonMarkTitleProperties, subtitle };\n}\nexport function isText(v) {\n return isString(v) || (isArray(v) && isString(v[0]));\n}\n//# sourceMappingURL=title.js.map","import { isArray } from 'vega-util';\nimport { keys } from './util';\nexport function isSignalRef(o) {\n return o && !!o['signal'];\n}\nexport function isVgRangeStep(range) {\n return !!range['step'];\n}\nexport function isDataRefUnionedDomain(domain) {\n if (!isArray(domain)) {\n return 'fields' in domain && !('data' in domain);\n }\n return false;\n}\nexport function isFieldRefUnionDomain(domain) {\n if (!isArray(domain)) {\n return 'fields' in domain && 'data' in domain;\n }\n return false;\n}\nexport function isDataRefDomain(domain) {\n if (!isArray(domain)) {\n return 'field' in domain && 'data' in domain;\n }\n return false;\n}\nconst VG_MARK_CONFIG_INDEX = {\n aria: 1,\n description: 1,\n ariaRole: 1,\n ariaRoleDescription: 1,\n blend: 1,\n opacity: 1,\n fill: 1,\n fillOpacity: 1,\n stroke: 1,\n strokeCap: 1,\n strokeWidth: 1,\n strokeOpacity: 1,\n strokeDash: 1,\n strokeDashOffset: 1,\n strokeJoin: 1,\n strokeOffset: 1,\n strokeMiterLimit: 1,\n startAngle: 1,\n endAngle: 1,\n padAngle: 1,\n innerRadius: 1,\n outerRadius: 1,\n size: 1,\n shape: 1,\n interpolate: 1,\n tension: 1,\n orient: 1,\n align: 1,\n baseline: 1,\n text: 1,\n dir: 1,\n dx: 1,\n dy: 1,\n ellipsis: 1,\n limit: 1,\n radius: 1,\n theta: 1,\n angle: 1,\n font: 1,\n fontSize: 1,\n fontWeight: 1,\n fontStyle: 1,\n lineBreak: 1,\n lineHeight: 1,\n cursor: 1,\n href: 1,\n tooltip: 1,\n cornerRadius: 1,\n cornerRadiusTopLeft: 1,\n cornerRadiusTopRight: 1,\n cornerRadiusBottomLeft: 1,\n cornerRadiusBottomRight: 1,\n aspect: 1,\n width: 1,\n height: 1,\n url: 1,\n smooth: 1\n // commented below are vg channel that do not have mark config.\n // x: 1,\n // y: 1,\n // x2: 1,\n // y2: 1,\n // xc'|'yc'\n // clip: 1,\n // path: 1,\n // url: 1,\n};\nexport const VG_MARK_CONFIGS = keys(VG_MARK_CONFIG_INDEX);\nexport const VG_MARK_INDEX = {\n arc: 1,\n area: 1,\n group: 1,\n image: 1,\n line: 1,\n path: 1,\n rect: 1,\n rule: 1,\n shape: 1,\n symbol: 1,\n text: 1,\n trail: 1\n};\n// Vega's cornerRadius channels.\nexport const VG_CORNERRADIUS_CHANNELS = [\n 'cornerRadius',\n 'cornerRadiusTopLeft',\n 'cornerRadiusTopRight',\n 'cornerRadiusBottomLeft',\n 'cornerRadiusBottomRight'\n];\n//# sourceMappingURL=vega.schema.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { array, isArray, stringValue } from 'vega-util';\nimport { vgField } from '../channeldef';\nimport { isExprRef } from '../expr';\nimport { isText } from '../title';\nimport { deepEqual, getFirstDefined } from '../util';\nimport { isSignalRef } from '../vega.schema';\nexport const BIN_RANGE_DELIMITER = ' \\u2013 ';\nexport function signalOrValueRefWithCondition(val) {\n const condition = isArray(val.condition)\n ? val.condition.map(conditionalSignalRefOrValue)\n : conditionalSignalRefOrValue(val.condition);\n return Object.assign(Object.assign({}, signalRefOrValue(val)), { condition });\n}\nexport function signalRefOrValue(value) {\n if (isExprRef(value)) {\n const { expr } = value, rest = __rest(value, [\"expr\"]);\n return Object.assign({ signal: expr }, rest);\n }\n return value;\n}\nexport function conditionalSignalRefOrValue(value) {\n if (isExprRef(value)) {\n const { expr } = value, rest = __rest(value, [\"expr\"]);\n return Object.assign({ signal: expr }, rest);\n }\n return value;\n}\nexport function signalOrValueRef(value) {\n if (isExprRef(value)) {\n const { expr } = value, rest = __rest(value, [\"expr\"]);\n return Object.assign({ signal: expr }, rest);\n }\n if (isSignalRef(value)) {\n return value;\n }\n return value !== undefined ? { value } : undefined;\n}\nexport function exprFromValueOrSignalRef(ref) {\n if (isSignalRef(ref)) {\n return ref.signal;\n }\n return stringValue(ref.value);\n}\nexport function signalOrStringValue(v) {\n if (isSignalRef(v)) {\n return v.signal;\n }\n return v == null ? null : stringValue(v);\n}\nexport function applyMarkConfig(e, model, propsList) {\n for (const property of propsList) {\n const value = getMarkConfig(property, model.markDef, model.config);\n if (value !== undefined) {\n e[property] = signalOrValueRef(value);\n }\n }\n return e;\n}\nexport function getStyles(mark) {\n var _a;\n return [].concat(mark.type, (_a = mark.style) !== null && _a !== void 0 ? _a : []);\n}\nexport function getMarkPropOrConfig(channel, mark, config, opt = {}) {\n const { vgChannel, ignoreVgConfig } = opt;\n if (vgChannel && mark[vgChannel] !== undefined) {\n return mark[vgChannel];\n }\n else if (mark[channel] !== undefined) {\n return mark[channel];\n }\n else if (ignoreVgConfig && (!vgChannel || vgChannel === channel)) {\n return undefined;\n }\n return getMarkConfig(channel, mark, config, opt);\n}\n/**\n * Return property value from style or mark specific config property if exists.\n * Otherwise, return general mark specific config.\n */\nexport function getMarkConfig(channel, mark, config, { vgChannel } = {}) {\n return getFirstDefined(\n // style config has highest precedence\n vgChannel ? getMarkStyleConfig(channel, mark, config.style) : undefined, getMarkStyleConfig(channel, mark, config.style), \n // then mark-specific config\n vgChannel ? config[mark.type][vgChannel] : undefined, config[mark.type][channel], // Need to cast because MarkDef doesn't perfectly match with AnyMarkConfig, but if the type isn't available, we'll get nothing here, which is fine\n // If there is vgChannel, skip vl channel.\n // For example, vl size for text is vg fontSize, but config.mark.size is only for point size.\n vgChannel ? config.mark[vgChannel] : config.mark[channel] // Need to cast for the same reason as above\n );\n}\nexport function getMarkStyleConfig(prop, mark, styleConfigIndex) {\n return getStyleConfig(prop, getStyles(mark), styleConfigIndex);\n}\nexport function getStyleConfig(p, styles, styleConfigIndex) {\n styles = array(styles);\n let value;\n for (const style of styles) {\n const styleConfig = styleConfigIndex[style];\n if (styleConfig && styleConfig[p] !== undefined) {\n value = styleConfig[p];\n }\n }\n return value;\n}\n/**\n * Return Vega sort parameters (tuple of field and order).\n */\nexport function sortParams(orderDef, fieldRefOption) {\n return array(orderDef).reduce((s, orderChannelDef) => {\n var _a;\n s.field.push(vgField(orderChannelDef, fieldRefOption));\n s.order.push((_a = orderChannelDef.sort) !== null && _a !== void 0 ? _a : 'ascending');\n return s;\n }, { field: [], order: [] });\n}\nexport function mergeTitleFieldDefs(f1, f2) {\n const merged = [...f1];\n f2.forEach(fdToMerge => {\n for (const fieldDef1 of merged) {\n // If already exists, no need to append to merged array\n if (deepEqual(fieldDef1, fdToMerge)) {\n return;\n }\n }\n merged.push(fdToMerge);\n });\n return merged;\n}\nexport function mergeTitle(title1, title2) {\n if (deepEqual(title1, title2) || !title2) {\n // if titles are the same or title2 is falsy\n return title1;\n }\n else if (!title1) {\n // if title1 is falsy\n return title2;\n }\n else {\n return [...array(title1), ...array(title2)].join(', ');\n }\n}\nexport function mergeTitleComponent(v1, v2) {\n const v1Val = v1.value;\n const v2Val = v2.value;\n if (v1Val == null || v2Val === null) {\n return {\n explicit: v1.explicit,\n value: null\n };\n }\n else if ((isText(v1Val) || isSignalRef(v1Val)) && (isText(v2Val) || isSignalRef(v2Val))) {\n return {\n explicit: v1.explicit,\n value: mergeTitle(v1Val, v2Val)\n };\n }\n else if (isText(v1Val) || isSignalRef(v1Val)) {\n return {\n explicit: v1.explicit,\n value: v1Val\n };\n }\n else if (isText(v2Val) || isSignalRef(v2Val)) {\n return {\n explicit: v1.explicit,\n value: v2Val\n };\n }\n else if (!isText(v1Val) && !isSignalRef(v1Val) && !isText(v2Val) && !isSignalRef(v2Val)) {\n return {\n explicit: v1.explicit,\n value: mergeTitleFieldDefs(v1Val, v2Val)\n };\n }\n /* istanbul ignore next: Condition should not happen -- only for warning in development. */\n throw new Error('It should never reach here');\n}\n//# sourceMappingURL=common.js.map","import { getSizeChannel } from '../channel';\nimport { stringify } from '../util';\nexport function invalidSpec(spec) {\n return `Invalid specification ${stringify(spec)}. Make sure the specification includes at least one of the following properties: \"mark\", \"layer\", \"facet\", \"hconcat\", \"vconcat\", \"concat\", or \"repeat\".`;\n}\n// FIT\nexport const FIT_NON_SINGLE = 'Autosize \"fit\" only works for single views and layered views.';\nexport function containerSizeNonSingle(name) {\n const uName = name == 'width' ? 'Width' : 'Height';\n return `${uName} \"container\" only works for single views and layered views.`;\n}\nexport function containerSizeNotCompatibleWithAutosize(name) {\n const uName = name == 'width' ? 'Width' : 'Height';\n const fitDirection = name == 'width' ? 'x' : 'y';\n return `${uName} \"container\" only works well with autosize \"fit\" or \"fit-${fitDirection}\".`;\n}\nexport function droppingFit(channel) {\n return channel\n ? `Dropping \"fit-${channel}\" because spec has discrete ${getSizeChannel(channel)}.`\n : `Dropping \"fit\" because spec has discrete size.`;\n}\n// VIEW SIZE\nexport function unknownField(channel) {\n return `Unknown field for ${channel}. Cannot calculate view size.`;\n}\n// SELECTION\nexport function cannotProjectOnChannelWithoutField(channel) {\n return `Cannot project a selection on encoding channel \"${channel}\", which has no field.`;\n}\nexport function cannotProjectAggregate(channel, aggregate) {\n return `Cannot project a selection on encoding channel \"${channel}\" as it uses an aggregate function (\"${aggregate}\").`;\n}\nexport function nearestNotSupportForContinuous(mark) {\n return `The \"nearest\" transform is not supported for ${mark} marks.`;\n}\nexport function selectionNotSupported(mark) {\n return `Selection not supported for ${mark} yet.`;\n}\nexport function selectionNotFound(name) {\n return `Cannot find a selection named \"${name}\".`;\n}\nexport const SCALE_BINDINGS_CONTINUOUS = 'Scale bindings are currently only supported for scales with unbinned, continuous domains.';\nexport const LEGEND_BINDINGS_MUST_HAVE_PROJECTION = 'Legend bindings are only supported for selections over an individual field or encoding channel.';\nexport function cannotLookupVariableParameter(name) {\n return `Lookups can only be performed on selection parameters. \"${name}\" is a variable parameter.`;\n}\nexport function noSameUnitLookup(name) {\n return (`Cannot define and lookup the \"${name}\" selection in the same view. ` +\n `Try moving the lookup into a second, layered view?`);\n}\nexport const NEEDS_SAME_SELECTION = 'The same selection must be used to override scale domains in a layered view.';\nexport const INTERVAL_INITIALIZED_WITH_X_Y = 'Interval selections should be initialized using \"x\" and/or \"y\" keys.';\n// REPEAT\nexport function noSuchRepeatedValue(field) {\n return `Unknown repeated value \"${field}\".`;\n}\nexport function columnsNotSupportByRowCol(type) {\n return `The \"columns\" property cannot be used when \"${type}\" has nested row/column.`;\n}\n// CONCAT / REPEAT\nexport const CONCAT_CANNOT_SHARE_AXIS = 'Axes cannot be shared in concatenated or repeated views yet (https://github.com/vega/vega-lite/issues/2415).';\n// DATA\nexport function unrecognizedParse(p) {\n return `Unrecognized parse \"${p}\".`;\n}\nexport function differentParse(field, local, ancestor) {\n return `An ancestor parsed field \"${field}\" as ${ancestor} but a child wants to parse the field as ${local}.`;\n}\nexport const ADD_SAME_CHILD_TWICE = 'Attempt to add the same child twice.';\n// TRANSFORMS\nexport function invalidTransformIgnored(transform) {\n return `Ignoring an invalid transform: ${stringify(transform)}.`;\n}\nexport const NO_FIELDS_NEEDS_AS = 'If \"from.fields\" is not specified, \"as\" has to be a string that specifies the key to be used for the data from the secondary source.';\n// ENCODING & FACET\nexport function customFormatTypeNotAllowed(channel) {\n return `Config.customFormatTypes is not true, thus custom format type and format for channel ${channel} are dropped.`;\n}\nexport function projectionOverridden(opt) {\n const { parentProjection, projection } = opt;\n return `Layer's shared projection ${stringify(parentProjection)} is overridden by a child projection ${stringify(projection)}.`;\n}\nexport const REPLACE_ANGLE_WITH_THETA = 'Arc marks uses theta channel rather than angle, replacing angle with theta.';\nexport function primitiveChannelDef(channel, type, value) {\n return `Channel ${channel} is a ${type}. Converted to {value: ${stringify(value)}}.`;\n}\nexport function invalidFieldType(type) {\n return `Invalid field type \"${type}\".`;\n}\nexport function invalidFieldTypeForCountAggregate(type, aggregate) {\n return `Invalid field type \"${type}\" for aggregate: \"${aggregate}\", using \"quantitative\" instead.`;\n}\nexport function invalidAggregate(aggregate) {\n return `Invalid aggregation operator \"${aggregate}\".`;\n}\nexport function missingFieldType(channel, newType) {\n return `Missing type for channel \"${channel}\", using \"${newType}\" instead.`;\n}\nexport function droppingColor(type, opt) {\n const { fill, stroke } = opt;\n return `Dropping color ${type} as the plot also has ${fill && stroke ? 'fill and stroke' : fill ? 'fill' : 'stroke'}.`;\n}\nexport function relativeBandSizeNotSupported(sizeChannel) {\n return `Position range does not support relative band size for ${sizeChannel}.`;\n}\nexport function emptyFieldDef(fieldDef, channel) {\n return `Dropping ${stringify(fieldDef)} from channel \"${channel}\" since it does not contain any data field, datum, value, or signal.`;\n}\nexport const LINE_WITH_VARYING_SIZE = 'Line marks cannot encode size with a non-groupby field. You may want to use trail marks instead.';\nexport function incompatibleChannel(channel, markOrFacet, when) {\n return `${channel} dropped as it is incompatible with \"${markOrFacet}\"${when ? ` when ${when}` : ''}.`;\n}\nexport function invalidEncodingChannel(channel) {\n return `${channel}-encoding is dropped as ${channel} is not a valid encoding channel.`;\n}\nexport function channelShouldBeDiscrete(channel) {\n return `${channel} encoding should be discrete (ordinal / nominal / binned).`;\n}\nexport function channelShouldBeDiscreteOrDiscretizing(channel) {\n return `${channel} encoding should be discrete (ordinal / nominal / binned) or use a discretizing scale (e.g. threshold).`;\n}\nexport function facetChannelDropped(channels) {\n return `Facet encoding dropped as ${channels.join(' and ')} ${channels.length > 1 ? 'are' : 'is'} also specified.`;\n}\nexport function discreteChannelCannotEncode(channel, type) {\n return `Using discrete channel \"${channel}\" to encode \"${type}\" field can be misleading as it does not encode ${type === 'ordinal' ? 'order' : 'magnitude'}.`;\n}\n// MARK\nexport function rangeMarkAlignmentCannotBeExpression(align) {\n return `The ${align} for range marks cannot be an expression`;\n}\nexport function lineWithRange(hasX2, hasY2) {\n const channels = hasX2 && hasY2 ? 'x2 and y2' : hasX2 ? 'x2' : 'y2';\n return `Line mark is for continuous lines and thus cannot be used with ${channels}. We will use the rule mark (line segments) instead.`;\n}\nexport function orientOverridden(original, actual) {\n return `Specified orient \"${original}\" overridden with \"${actual}\".`;\n}\n// SCALE\nexport const CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN = 'Custom domain scale cannot be unioned with default field-based domain.';\nexport function cannotUseScalePropertyWithNonColor(prop) {\n return `Cannot use the scale property \"${prop}\" with non-color channel.`;\n}\nexport function cannotUseRelativeBandSizeWithNonBandScale(scaleType) {\n return `Cannot use the relative band size with ${scaleType} scale.`;\n}\nexport function unaggregateDomainHasNoEffectForRawField(fieldDef) {\n return `Using unaggregated domain with raw field has no effect (${stringify(fieldDef)}).`;\n}\nexport function unaggregateDomainWithNonSharedDomainOp(aggregate) {\n return `Unaggregated domain not applicable for \"${aggregate}\" since it produces values outside the origin domain of the source data.`;\n}\nexport function unaggregatedDomainWithLogScale(fieldDef) {\n return `Unaggregated domain is currently unsupported for log scale (${stringify(fieldDef)}).`;\n}\nexport function cannotApplySizeToNonOrientedMark(mark) {\n return `Cannot apply size to non-oriented mark \"${mark}\".`;\n}\nexport function scaleTypeNotWorkWithChannel(channel, scaleType, defaultScaleType) {\n return `Channel \"${channel}\" does not work with \"${scaleType}\" scale. We are using \"${defaultScaleType}\" scale instead.`;\n}\nexport function scaleTypeNotWorkWithFieldDef(scaleType, defaultScaleType) {\n return `FieldDef does not work with \"${scaleType}\" scale. We are using \"${defaultScaleType}\" scale instead.`;\n}\nexport function scalePropertyNotWorkWithScaleType(scaleType, propName, channel) {\n return `${channel}-scale's \"${propName}\" is dropped as it does not work with ${scaleType} scale.`;\n}\nexport function scaleTypeNotWorkWithMark(mark, scaleType) {\n return `Scale type \"${scaleType}\" does not work with mark \"${mark}\".`;\n}\nexport function stepDropped(channel) {\n return `The step for \"${channel}\" is dropped because the ${channel === 'width' ? 'x' : 'y'} is continuous.`;\n}\nexport function mergeConflictingProperty(property, propertyOf, v1, v2) {\n return `Conflicting ${propertyOf.toString()} property \"${property.toString()}\" (${stringify(v1)} and ${stringify(v2)}). Using ${stringify(v1)}.`;\n}\nexport function mergeConflictingDomainProperty(property, propertyOf, v1, v2) {\n return `Conflicting ${propertyOf.toString()} property \"${property.toString()}\" (${stringify(v1)} and ${stringify(v2)}). Using the union of the two domains.`;\n}\nexport function independentScaleMeansIndependentGuide(channel) {\n return `Setting the scale to be independent for \"${channel}\" means we also have to set the guide (axis or legend) to be independent.`;\n}\nexport function domainSortDropped(sort) {\n return `Dropping sort property ${stringify(sort)} as unioned domains only support boolean or op \"count\", \"min\", and \"max\".`;\n}\nexport const MORE_THAN_ONE_SORT = 'Domains that should be unioned has conflicting sort properties. Sort will be set to true.';\nexport const FACETED_INDEPENDENT_DIFFERENT_SOURCES = 'Detected faceted independent scales that union domain of multiple fields from different data sources. We will use the first field. The result view size may be incorrect.';\nexport const FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES = 'Detected faceted independent scales that union domain of the same fields from different source. We will assume that this is the same field from a different fork of the same data source. However, if this is not the case, the result view size may be incorrect.';\nexport const FACETED_INDEPENDENT_SAME_SOURCE = 'Detected faceted independent scales that union domain of multiple fields from the same data source. We will use the first field. The result view size may be incorrect.';\n// AXIS\nexport const INVALID_CHANNEL_FOR_AXIS = 'Invalid channel for axis.';\n// STACK\nexport function cannotStackRangedMark(channel) {\n return `Cannot stack \"${channel}\" if there is already \"${channel}2\".`;\n}\nexport function cannotStackNonLinearScale(scaleType) {\n return `Cannot stack non-linear scale (${scaleType}).`;\n}\nexport function stackNonSummativeAggregate(aggregate) {\n return `Stacking is applied even though the aggregate function is non-summative (\"${aggregate}\").`;\n}\n// TIMEUNIT\nexport function invalidTimeUnit(unitName, value) {\n return `Invalid ${unitName}: ${stringify(value)}.`;\n}\nexport function droppedDay(d) {\n return `Dropping day from datetime ${stringify(d)} as day cannot be combined with other units.`;\n}\nexport function errorBarCenterAndExtentAreNotNeeded(center, extent) {\n return `${extent ? 'extent ' : ''}${extent && center ? 'and ' : ''}${center ? 'center ' : ''}${extent && center ? 'are ' : 'is '}not needed when data are aggregated.`;\n}\nexport function errorBarCenterIsUsedWithWrongExtent(center, extent, mark) {\n return `${center} is not usually used with ${extent} for ${mark}.`;\n}\nexport function errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark) {\n return `Continuous axis should not have customized aggregation function ${aggregate}; ${compositeMark} already agregates the axis.`;\n}\nexport function errorBand1DNotSupport(property) {\n return `1D error band does not support ${property}.`;\n}\n// CHANNEL\nexport function channelRequiredForBinned(channel) {\n return `Channel ${channel} is required for \"binned\" bin.`;\n}\nexport function channelShouldNotBeUsedForBinned(channel) {\n return `Channel ${channel} should not be used with \"binned\" bin.`;\n}\nexport function domainRequiredForThresholdScale(channel) {\n return `Domain for ${channel} is required for threshold scale.`;\n}\n//# sourceMappingURL=message.js.map","/**\n * Vega-Lite's singleton logger utility.\n */\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _LocalLogger_level;\nimport { Debug, Error as ErrorLevel, Info, logger, Warn } from 'vega-util';\nimport * as message_1 from './message';\nexport { message_1 as message };\n/**\n * Main (default) Vega Logger instance for Vega-Lite.\n */\nconst main = logger(Warn);\nlet current = main;\n/**\n * Logger tool for checking if the code throws correct warning.\n */\nexport class LocalLogger {\n constructor() {\n this.warns = [];\n this.infos = [];\n this.debugs = [];\n _LocalLogger_level.set(this, Warn);\n }\n level(_) {\n if (_) {\n __classPrivateFieldSet(this, _LocalLogger_level, _, \"f\");\n return this;\n }\n return __classPrivateFieldGet(this, _LocalLogger_level, \"f\");\n }\n warn(...args) {\n if (__classPrivateFieldGet(this, _LocalLogger_level, \"f\") >= Warn)\n this.warns.push(...args);\n return this;\n }\n info(...args) {\n if (__classPrivateFieldGet(this, _LocalLogger_level, \"f\") >= Info)\n this.infos.push(...args);\n return this;\n }\n debug(...args) {\n if (__classPrivateFieldGet(this, _LocalLogger_level, \"f\") >= Debug)\n this.debugs.push(...args);\n return this;\n }\n error(...args) {\n if (__classPrivateFieldGet(this, _LocalLogger_level, \"f\") >= ErrorLevel)\n throw Error(...args);\n return this;\n }\n}\n_LocalLogger_level = new WeakMap();\nexport function wrap(f) {\n return () => {\n current = new LocalLogger();\n f(current);\n reset();\n };\n}\n/**\n * Set the singleton logger to be a custom logger.\n */\nexport function set(newLogger) {\n current = newLogger;\n return current;\n}\n/**\n * Reset the main logger to use the default Vega Logger.\n */\nexport function reset() {\n current = main;\n return current;\n}\nexport function error(...args) {\n current.error(...args);\n}\nexport function warn(...args) {\n current.warn(...args);\n}\nexport function info(...args) {\n current.info(...args);\n}\nexport function debug(...args) {\n current.debug(...args);\n}\n//# sourceMappingURL=index.js.map","// DateTime definition object\nimport { isNumber, isObject } from 'vega-util';\nimport * as log from './log';\nimport { TIMEUNIT_PARTS } from './timeunit';\nimport { duplicate, isNumeric, keys } from './util';\nexport function isDateTime(o) {\n if (o && isObject(o)) {\n for (const part of TIMEUNIT_PARTS) {\n if (part in o) {\n return true;\n }\n }\n }\n return false;\n}\nexport const MONTHS = [\n 'january',\n 'february',\n 'march',\n 'april',\n 'may',\n 'june',\n 'july',\n 'august',\n 'september',\n 'october',\n 'november',\n 'december'\n];\nexport const SHORT_MONTHS = MONTHS.map(m => m.substr(0, 3));\nexport const DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];\nexport const SHORT_DAYS = DAYS.map(d => d.substr(0, 3));\nfunction normalizeQuarter(q) {\n if (isNumeric(q)) {\n q = +q;\n }\n if (isNumber(q)) {\n if (q > 4) {\n log.warn(log.message.invalidTimeUnit('quarter', q));\n }\n // We accept 1-based quarter, so need to readjust to 0-based quarter\n return q - 1;\n }\n else {\n // Invalid quarter\n throw new Error(log.message.invalidTimeUnit('quarter', q));\n }\n}\nfunction normalizeMonth(m) {\n if (isNumeric(m)) {\n m = +m;\n }\n if (isNumber(m)) {\n // We accept 1-based month, so need to readjust to 0-based month\n return m - 1;\n }\n else {\n const lowerM = m.toLowerCase();\n const monthIndex = MONTHS.indexOf(lowerM);\n if (monthIndex !== -1) {\n return monthIndex; // 0 for january, ...\n }\n const shortM = lowerM.substr(0, 3);\n const shortMonthIndex = SHORT_MONTHS.indexOf(shortM);\n if (shortMonthIndex !== -1) {\n return shortMonthIndex;\n }\n // Invalid month\n throw new Error(log.message.invalidTimeUnit('month', m));\n }\n}\nfunction normalizeDay(d) {\n if (isNumeric(d)) {\n d = +d;\n }\n if (isNumber(d)) {\n // mod so that this can be both 0-based where 0 = sunday\n // and 1-based where 7=sunday\n return d % 7;\n }\n else {\n const lowerD = d.toLowerCase();\n const dayIndex = DAYS.indexOf(lowerD);\n if (dayIndex !== -1) {\n return dayIndex; // 0 for january, ...\n }\n const shortD = lowerD.substr(0, 3);\n const shortDayIndex = SHORT_DAYS.indexOf(shortD);\n if (shortDayIndex !== -1) {\n return shortDayIndex;\n }\n // Invalid day\n throw new Error(log.message.invalidTimeUnit('day', d));\n }\n}\n/**\n * @param d the date.\n * @param normalize whether to normalize quarter, month, day. This should probably be true if d is a DateTime.\n * @returns array of date time parts [year, month, day, hours, minutes, seconds, milliseconds]\n */\nfunction dateTimeParts(d, normalize) {\n const parts = [];\n if (normalize && d.day !== undefined) {\n if (keys(d).length > 1) {\n log.warn(log.message.droppedDay(d));\n d = duplicate(d);\n delete d.day;\n }\n }\n if (d.year !== undefined) {\n parts.push(d.year);\n }\n else {\n // Just like Vega's timeunit transform, set default year to 2012, so domain conversion will be compatible with Vega\n // Note: 2012 is a leap year (and so the date February 29 is respected) that begins on a Sunday (and so days of the week will order properly at the beginning of the year).\n parts.push(2012);\n }\n if (d.month !== undefined) {\n const month = normalize ? normalizeMonth(d.month) : d.month;\n parts.push(month);\n }\n else if (d.quarter !== undefined) {\n const quarter = normalize ? normalizeQuarter(d.quarter) : d.quarter;\n parts.push(isNumber(quarter) ? quarter * 3 : `${quarter}*3`);\n }\n else {\n parts.push(0); // months start at zero in JS\n }\n if (d.date !== undefined) {\n parts.push(d.date);\n }\n else if (d.day !== undefined) {\n // HACK: Day only works as a standalone unit\n // This is only correct because we always set year to 2006 for day\n const day = normalize ? normalizeDay(d.day) : d.day;\n parts.push(isNumber(day) ? day + 1 : `${day}+1`);\n }\n else {\n parts.push(1); // Date starts at 1 in JS\n }\n // Note: can't use TimeUnit enum here as importing it will create\n // circular dependency problem!\n for (const timeUnit of ['hours', 'minutes', 'seconds', 'milliseconds']) {\n const unit = d[timeUnit];\n parts.push(typeof unit === 'undefined' ? 0 : unit);\n }\n return parts;\n}\n/**\n * Return Vega expression for a date time.\n *\n * @param d the date time.\n * @returns the Vega expression.\n */\nexport function dateTimeToExpr(d) {\n const parts = dateTimeParts(d, true);\n const string = parts.join(', ');\n if (d.utc) {\n return `utc(${string})`;\n }\n else {\n return `datetime(${string})`;\n }\n}\n/**\n * Return Vega expression for a date time expression.\n *\n * @param d the internal date time object with expression.\n * @returns the Vega expression.\n */\nexport function dateTimeExprToExpr(d) {\n const parts = dateTimeParts(d, false);\n const string = parts.join(', ');\n if (d.utc) {\n return `utc(${string})`;\n }\n else {\n return `datetime(${string})`;\n }\n}\n/**\n * @param d the date time.\n * @returns the timestamp.\n */\nexport function dateTimeToTimestamp(d) {\n const parts = dateTimeParts(d, true);\n if (d.utc) {\n return +new Date(Date.UTC(...parts));\n }\n else {\n return +new Date(...parts);\n }\n}\n//# sourceMappingURL=datetime.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isObject, isString } from 'vega-util';\nimport { dateTimeExprToExpr } from './datetime';\nimport { accessPathWithDatum, keys, stringify, varName } from './util';\n/** Time Unit that only corresponds to only one part of Date objects. */\nexport const LOCAL_SINGLE_TIMEUNIT_INDEX = {\n year: 1,\n quarter: 1,\n month: 1,\n week: 1,\n day: 1,\n dayofyear: 1,\n date: 1,\n hours: 1,\n minutes: 1,\n seconds: 1,\n milliseconds: 1\n};\nexport const TIMEUNIT_PARTS = keys(LOCAL_SINGLE_TIMEUNIT_INDEX);\nexport function isLocalSingleTimeUnit(timeUnit) {\n return !!LOCAL_SINGLE_TIMEUNIT_INDEX[timeUnit];\n}\nexport const UTC_SINGLE_TIMEUNIT_INDEX = {\n utcyear: 1,\n utcquarter: 1,\n utcmonth: 1,\n utcweek: 1,\n utcday: 1,\n utcdayofyear: 1,\n utcdate: 1,\n utchours: 1,\n utcminutes: 1,\n utcseconds: 1,\n utcmilliseconds: 1\n};\nexport const LOCAL_MULTI_TIMEUNIT_INDEX = {\n yearquarter: 1,\n yearquartermonth: 1,\n yearmonth: 1,\n yearmonthdate: 1,\n yearmonthdatehours: 1,\n yearmonthdatehoursminutes: 1,\n yearmonthdatehoursminutesseconds: 1,\n yearweek: 1,\n yearweekday: 1,\n yearweekdayhours: 1,\n yearweekdayhoursminutes: 1,\n yearweekdayhoursminutesseconds: 1,\n yeardayofyear: 1,\n quartermonth: 1,\n monthdate: 1,\n monthdatehours: 1,\n monthdatehoursminutes: 1,\n monthdatehoursminutesseconds: 1,\n weekday: 1,\n weeksdayhours: 1,\n weekdayhoursminutes: 1,\n weekdayhoursminutesseconds: 1,\n dayhours: 1,\n dayhoursminutes: 1,\n dayhoursminutesseconds: 1,\n hoursminutes: 1,\n hoursminutesseconds: 1,\n minutesseconds: 1,\n secondsmilliseconds: 1\n};\nexport const UTC_MULTI_TIMEUNIT_INDEX = {\n utcyearquarter: 1,\n utcyearquartermonth: 1,\n utcyearmonth: 1,\n utcyearmonthdate: 1,\n utcyearmonthdatehours: 1,\n utcyearmonthdatehoursminutes: 1,\n utcyearmonthdatehoursminutesseconds: 1,\n utcyearweek: 1,\n utcyearweekday: 1,\n utcyearweekdayhours: 1,\n utcyearweekdayhoursminutes: 1,\n utcyearweekdayhoursminutesseconds: 1,\n utcyeardayofyear: 1,\n utcquartermonth: 1,\n utcmonthdate: 1,\n utcmonthdatehours: 1,\n utcmonthdatehoursminutes: 1,\n utcmonthdatehoursminutesseconds: 1,\n utcweekday: 1,\n utcweeksdayhours: 1,\n utcweekdayhoursminutes: 1,\n utcweekdayhoursminutesseconds: 1,\n utcdayhours: 1,\n utcdayhoursminutes: 1,\n utcdayhoursminutesseconds: 1,\n utchoursminutes: 1,\n utchoursminutesseconds: 1,\n utcminutesseconds: 1,\n utcsecondsmilliseconds: 1\n};\nexport function isUTCTimeUnit(t) {\n return t.startsWith('utc');\n}\nexport function getLocalTimeUnit(t) {\n return t.substr(3);\n}\n// In order of increasing specificity\nexport const VEGALITE_TIMEFORMAT = {\n 'year-month': '%b %Y ',\n 'year-month-date': '%b %d, %Y '\n};\nexport function getTimeUnitParts(timeUnit) {\n return TIMEUNIT_PARTS.filter(part => containsTimeUnit(timeUnit, part));\n}\n/** Returns true if fullTimeUnit contains the timeUnit, false otherwise. */\nexport function containsTimeUnit(fullTimeUnit, timeUnit) {\n const index = fullTimeUnit.indexOf(timeUnit);\n if (index < 0) {\n return false;\n }\n // exclude milliseconds\n if (index > 0 && timeUnit === 'seconds' && fullTimeUnit.charAt(index - 1) === 'i') {\n return false;\n }\n // exclude dayofyear\n if (fullTimeUnit.length > index + 3 && timeUnit === 'day' && fullTimeUnit.charAt(index + 3) === 'o') {\n return false;\n }\n if (index > 0 && timeUnit === 'year' && fullTimeUnit.charAt(index - 1) === 'f') {\n return false;\n }\n return true;\n}\n/**\n * Returns Vega expression for a given timeUnit and fieldRef\n */\nexport function fieldExpr(fullTimeUnit, field, { end } = { end: false }) {\n const fieldRef = accessPathWithDatum(field);\n const utc = isUTCTimeUnit(fullTimeUnit) ? 'utc' : '';\n function func(timeUnit) {\n if (timeUnit === 'quarter') {\n // quarter starting at 0 (0,3,6,9).\n return `(${utc}quarter(${fieldRef})-1)`;\n }\n else {\n return `${utc}${timeUnit}(${fieldRef})`;\n }\n }\n let lastTimeUnit;\n const dateExpr = {};\n for (const part of TIMEUNIT_PARTS) {\n if (containsTimeUnit(fullTimeUnit, part)) {\n dateExpr[part] = func(part);\n lastTimeUnit = part;\n }\n }\n if (end) {\n dateExpr[lastTimeUnit] += '+1';\n }\n return dateTimeExprToExpr(dateExpr);\n}\nexport function timeUnitSpecifierExpression(timeUnit) {\n if (!timeUnit) {\n return undefined;\n }\n const timeUnitParts = getTimeUnitParts(timeUnit);\n return `timeUnitSpecifier(${stringify(timeUnitParts)}, ${stringify(VEGALITE_TIMEFORMAT)})`;\n}\n/**\n * Returns the signal expression used for axis labels for a time unit.\n */\nexport function formatExpression(timeUnit, field, isUTCScale) {\n if (!timeUnit) {\n return undefined;\n }\n const expr = timeUnitSpecifierExpression(timeUnit);\n // We only use utcFormat for utc scale\n // For utc time units, the data is already converted as a part of timeUnit transform.\n // Thus, utc time units should use timeFormat to avoid shifting the time twice.\n const utc = isUTCScale || isUTCTimeUnit(timeUnit);\n return `${utc ? 'utc' : 'time'}Format(${field}, ${expr})`;\n}\nexport function normalizeTimeUnit(timeUnit) {\n if (!timeUnit) {\n return undefined;\n }\n let params;\n if (isString(timeUnit)) {\n params = {\n unit: timeUnit\n };\n }\n else if (isObject(timeUnit)) {\n params = Object.assign(Object.assign({}, timeUnit), (timeUnit.unit ? { unit: timeUnit.unit } : {}));\n }\n if (isUTCTimeUnit(params.unit)) {\n params.utc = true;\n params.unit = getLocalTimeUnit(params.unit);\n }\n return params;\n}\nexport function timeUnitToString(tu) {\n const _a = normalizeTimeUnit(tu), { utc } = _a, rest = __rest(_a, [\"utc\"]);\n if (rest.unit) {\n return ((utc ? 'utc' : '') +\n keys(rest)\n .map(p => varName(`${p === 'unit' ? '' : `_${p}_`}${rest[p]}`))\n .join(''));\n }\n else {\n // when maxbins is specified instead of units\n return ((utc ? 'utc' : '') +\n 'timeunit' +\n keys(rest)\n .map(p => varName(`_${p}_${rest[p]}`))\n .join(''));\n }\n}\n//# sourceMappingURL=timeunit.js.map","import { isArray } from 'vega-util';\nimport { valueExpr, vgField } from './channeldef';\nimport { fieldExpr as timeUnitFieldExpr, normalizeTimeUnit } from './timeunit';\nimport { stringify } from './util';\nimport { isSignalRef } from './vega.schema';\nexport function isSelectionPredicate(predicate) {\n return predicate === null || predicate === void 0 ? void 0 : predicate['param'];\n}\nexport function isFieldEqualPredicate(predicate) {\n return predicate && !!predicate.field && predicate.equal !== undefined;\n}\nexport function isFieldLTPredicate(predicate) {\n return predicate && !!predicate.field && predicate.lt !== undefined;\n}\nexport function isFieldLTEPredicate(predicate) {\n return predicate && !!predicate.field && predicate.lte !== undefined;\n}\nexport function isFieldGTPredicate(predicate) {\n return predicate && !!predicate.field && predicate.gt !== undefined;\n}\nexport function isFieldGTEPredicate(predicate) {\n return predicate && !!predicate.field && predicate.gte !== undefined;\n}\nexport function isFieldRangePredicate(predicate) {\n if (predicate === null || predicate === void 0 ? void 0 : predicate.field) {\n if (isArray(predicate.range) && predicate.range.length === 2) {\n return true;\n }\n else if (isSignalRef(predicate.range)) {\n return true;\n }\n }\n return false;\n}\nexport function isFieldOneOfPredicate(predicate) {\n return (predicate && !!predicate.field && (isArray(predicate.oneOf) || isArray(predicate.in)) // backward compatibility\n );\n}\nexport function isFieldValidPredicate(predicate) {\n return predicate && !!predicate.field && predicate.valid !== undefined;\n}\nexport function isFieldPredicate(predicate) {\n return (isFieldOneOfPredicate(predicate) ||\n isFieldEqualPredicate(predicate) ||\n isFieldRangePredicate(predicate) ||\n isFieldLTPredicate(predicate) ||\n isFieldGTPredicate(predicate) ||\n isFieldLTEPredicate(predicate) ||\n isFieldGTEPredicate(predicate));\n}\nfunction predicateValueExpr(v, timeUnit) {\n return valueExpr(v, { timeUnit, wrapTime: true });\n}\nfunction predicateValuesExpr(vals, timeUnit) {\n return vals.map(v => predicateValueExpr(v, timeUnit));\n}\n// This method is used by Voyager. Do not change its behavior without changing Voyager.\nexport function fieldFilterExpression(predicate, useInRange = true) {\n var _a;\n const { field } = predicate;\n const timeUnit = (_a = normalizeTimeUnit(predicate.timeUnit)) === null || _a === void 0 ? void 0 : _a.unit;\n const fieldExpr = timeUnit\n ? // For timeUnit, cast into integer with time() so we can use ===, inrange, indexOf to compare values directly.\n // TODO: We calculate timeUnit on the fly here. Consider if we would like to consolidate this with timeUnit pipeline\n // TODO: support utc\n `time(${timeUnitFieldExpr(timeUnit, field)})`\n : vgField(predicate, { expr: 'datum' });\n if (isFieldEqualPredicate(predicate)) {\n return `${fieldExpr}===${predicateValueExpr(predicate.equal, timeUnit)}`;\n }\n else if (isFieldLTPredicate(predicate)) {\n const upper = predicate.lt;\n return `${fieldExpr}<${predicateValueExpr(upper, timeUnit)}`;\n }\n else if (isFieldGTPredicate(predicate)) {\n const lower = predicate.gt;\n return `${fieldExpr}>${predicateValueExpr(lower, timeUnit)}`;\n }\n else if (isFieldLTEPredicate(predicate)) {\n const upper = predicate.lte;\n return `${fieldExpr}<=${predicateValueExpr(upper, timeUnit)}`;\n }\n else if (isFieldGTEPredicate(predicate)) {\n const lower = predicate.gte;\n return `${fieldExpr}>=${predicateValueExpr(lower, timeUnit)}`;\n }\n else if (isFieldOneOfPredicate(predicate)) {\n return `indexof([${predicateValuesExpr(predicate.oneOf, timeUnit).join(',')}], ${fieldExpr}) !== -1`;\n }\n else if (isFieldValidPredicate(predicate)) {\n return fieldValidPredicate(fieldExpr, predicate.valid);\n }\n else if (isFieldRangePredicate(predicate)) {\n const { range } = predicate;\n const lower = isSignalRef(range) ? { signal: `${range.signal}[0]` } : range[0];\n const upper = isSignalRef(range) ? { signal: `${range.signal}[1]` } : range[1];\n if (lower !== null && upper !== null && useInRange) {\n return ('inrange(' +\n fieldExpr +\n ', [' +\n predicateValueExpr(lower, timeUnit) +\n ', ' +\n predicateValueExpr(upper, timeUnit) +\n '])');\n }\n const exprs = [];\n if (lower !== null) {\n exprs.push(`${fieldExpr} >= ${predicateValueExpr(lower, timeUnit)}`);\n }\n if (upper !== null) {\n exprs.push(`${fieldExpr} <= ${predicateValueExpr(upper, timeUnit)}`);\n }\n return exprs.length > 0 ? exprs.join(' && ') : 'true';\n }\n /* istanbul ignore next: it should never reach here */\n throw new Error(`Invalid field predicate: ${stringify(predicate)}`);\n}\nexport function fieldValidPredicate(fieldExpr, valid = true) {\n if (valid) {\n return `isValid(${fieldExpr}) && isFinite(+${fieldExpr})`;\n }\n else {\n return `!isValid(${fieldExpr}) || !isFinite(+${fieldExpr})`;\n }\n}\nexport function normalizePredicate(f) {\n var _a;\n if (isFieldPredicate(f) && f.timeUnit) {\n return Object.assign(Object.assign({}, f), { timeUnit: (_a = normalizeTimeUnit(f.timeUnit)) === null || _a === void 0 ? void 0 : _a.unit });\n }\n return f;\n}\n//# sourceMappingURL=predicate.js.map","import { keys } from './util';\n/**\n * Data type based on level of measurement\n */\nexport const Type = {\n quantitative: 'quantitative',\n ordinal: 'ordinal',\n temporal: 'temporal',\n nominal: 'nominal',\n geojson: 'geojson'\n};\nexport function isType(t) {\n return t in Type;\n}\nexport const QUANTITATIVE = Type.quantitative;\nexport const ORDINAL = Type.ordinal;\nexport const TEMPORAL = Type.temporal;\nexport const NOMINAL = Type.nominal;\nexport const GEOJSON = Type.geojson;\nexport const TYPES = keys(Type);\n/**\n * Get full, lowercase type name for a given type.\n * @param type\n * @return Full type name.\n */\nexport function getFullName(type) {\n if (type) {\n type = type.toLowerCase();\n switch (type) {\n case 'q':\n case QUANTITATIVE:\n return 'quantitative';\n case 't':\n case TEMPORAL:\n return 'temporal';\n case 'o':\n case ORDINAL:\n return 'ordinal';\n case 'n':\n case NOMINAL:\n return 'nominal';\n case GEOJSON:\n return 'geojson';\n }\n }\n // If we get invalid input, return undefined type.\n return undefined;\n}\n//# sourceMappingURL=type.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isObject } from 'vega';\nimport { isString, toSet } from 'vega-util';\nimport * as CHANNEL from './channel';\nimport { isColorChannel } from './channel';\nimport * as log from './log';\nimport { NOMINAL, ORDINAL, QUANTITATIVE, TEMPORAL } from './type';\nimport { contains, keys } from './util';\nexport const ScaleType = {\n // Continuous - Quantitative\n LINEAR: 'linear',\n LOG: 'log',\n POW: 'pow',\n SQRT: 'sqrt',\n SYMLOG: 'symlog',\n IDENTITY: 'identity',\n SEQUENTIAL: 'sequential',\n // Continuous - Time\n TIME: 'time',\n UTC: 'utc',\n // Discretizing scales\n QUANTILE: 'quantile',\n QUANTIZE: 'quantize',\n THRESHOLD: 'threshold',\n BIN_ORDINAL: 'bin-ordinal',\n // Discrete scales\n ORDINAL: 'ordinal',\n POINT: 'point',\n BAND: 'band'\n};\n/**\n * Index for scale categories -- only scale of the same categories can be merged together.\n * Current implementation is trying to be conservative and avoid merging scale type that might not work together\n */\nexport const SCALE_CATEGORY_INDEX = {\n linear: 'numeric',\n log: 'numeric',\n pow: 'numeric',\n sqrt: 'numeric',\n symlog: 'numeric',\n identity: 'numeric',\n sequential: 'numeric',\n time: 'time',\n utc: 'time',\n ordinal: 'ordinal',\n 'bin-ordinal': 'bin-ordinal',\n point: 'ordinal-position',\n band: 'ordinal-position',\n quantile: 'discretizing',\n quantize: 'discretizing',\n threshold: 'discretizing'\n};\nexport const SCALE_TYPES = keys(SCALE_CATEGORY_INDEX);\n/**\n * Whether the two given scale types can be merged together.\n */\nexport function scaleCompatible(scaleType1, scaleType2) {\n const scaleCategory1 = SCALE_CATEGORY_INDEX[scaleType1];\n const scaleCategory2 = SCALE_CATEGORY_INDEX[scaleType2];\n return (scaleCategory1 === scaleCategory2 ||\n (scaleCategory1 === 'ordinal-position' && scaleCategory2 === 'time') ||\n (scaleCategory2 === 'ordinal-position' && scaleCategory1 === 'time'));\n}\n/**\n * Index for scale precedence -- high score = higher priority for merging.\n */\nconst SCALE_PRECEDENCE_INDEX = {\n // numeric\n linear: 0,\n log: 1,\n pow: 1,\n sqrt: 1,\n symlog: 1,\n identity: 1,\n sequential: 1,\n // time\n time: 0,\n utc: 0,\n // ordinal-position -- these have higher precedence than continuous scales as they support more types of data\n point: 10,\n band: 11,\n // non grouped types\n ordinal: 0,\n 'bin-ordinal': 0,\n quantile: 0,\n quantize: 0,\n threshold: 0\n};\n/**\n * Return scale categories -- only scale of the same categories can be merged together.\n */\nexport function scaleTypePrecedence(scaleType) {\n return SCALE_PRECEDENCE_INDEX[scaleType];\n}\nexport const CONTINUOUS_TO_CONTINUOUS_SCALES = ['linear', 'log', 'pow', 'sqrt', 'symlog', 'time', 'utc'];\nconst CONTINUOUS_TO_CONTINUOUS_INDEX = toSet(CONTINUOUS_TO_CONTINUOUS_SCALES);\nexport const QUANTITATIVE_SCALES = ['linear', 'log', 'pow', 'sqrt', 'symlog'];\nconst QUANTITATIVE_SCALES_INDEX = toSet(QUANTITATIVE_SCALES);\nexport function isQuantitative(type) {\n return type in QUANTITATIVE_SCALES_INDEX;\n}\nexport const CONTINUOUS_TO_DISCRETE_SCALES = ['quantile', 'quantize', 'threshold'];\nconst CONTINUOUS_TO_DISCRETE_INDEX = toSet(CONTINUOUS_TO_DISCRETE_SCALES);\nexport const CONTINUOUS_DOMAIN_SCALES = CONTINUOUS_TO_CONTINUOUS_SCALES.concat([\n 'quantile',\n 'quantize',\n 'threshold',\n 'sequential',\n 'identity'\n]);\nconst CONTINUOUS_DOMAIN_INDEX = toSet(CONTINUOUS_DOMAIN_SCALES);\nexport const DISCRETE_DOMAIN_SCALES = ['ordinal', 'bin-ordinal', 'point', 'band'];\nconst DISCRETE_DOMAIN_INDEX = toSet(DISCRETE_DOMAIN_SCALES);\nexport const TIME_SCALE_TYPES = ['time', 'utc'];\nexport function hasDiscreteDomain(type) {\n return type in DISCRETE_DOMAIN_INDEX;\n}\nexport function hasContinuousDomain(type) {\n return type in CONTINUOUS_DOMAIN_INDEX;\n}\nexport function isContinuousToContinuous(type) {\n return type in CONTINUOUS_TO_CONTINUOUS_INDEX;\n}\nexport function isContinuousToDiscrete(type) {\n return type in CONTINUOUS_TO_DISCRETE_INDEX;\n}\nexport const defaultScaleConfig = {\n pointPadding: 0.5,\n barBandPaddingInner: 0.1,\n rectBandPaddingInner: 0,\n minBandSize: 2,\n minFontSize: 8,\n maxFontSize: 40,\n minOpacity: 0.3,\n maxOpacity: 0.8,\n // FIXME: revise if these *can* become ratios of width/height step\n minSize: 9,\n minStrokeWidth: 1,\n maxStrokeWidth: 4,\n quantileCount: 4,\n quantizeCount: 4\n};\nexport function isExtendedScheme(scheme) {\n return !isString(scheme) && !!scheme['name'];\n}\nexport function isParameterDomain(domain) {\n return domain === null || domain === void 0 ? void 0 : domain['param'];\n}\nexport function isDomainUnionWith(domain) {\n return domain && domain['unionWith'];\n}\nexport function isFieldRange(range) {\n return isObject(range) && 'field' in range;\n}\nconst SCALE_PROPERTY_INDEX = {\n type: 1,\n domain: 1,\n domainMax: 1,\n domainMin: 1,\n domainMid: 1,\n align: 1,\n range: 1,\n rangeMax: 1,\n rangeMin: 1,\n scheme: 1,\n bins: 1,\n // Other properties\n reverse: 1,\n round: 1,\n // quantitative / time\n clamp: 1,\n nice: 1,\n // quantitative\n base: 1,\n exponent: 1,\n constant: 1,\n interpolate: 1,\n zero: 1,\n // band/point\n padding: 1,\n paddingInner: 1,\n paddingOuter: 1\n};\nexport const SCALE_PROPERTIES = keys(SCALE_PROPERTY_INDEX);\nconst { type, domain, range, rangeMax, rangeMin, scheme } = SCALE_PROPERTY_INDEX, NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX = __rest(SCALE_PROPERTY_INDEX, [\"type\", \"domain\", \"range\", \"rangeMax\", \"rangeMin\", \"scheme\"]);\nexport const NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES = keys(NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX);\nexport function scaleTypeSupportProperty(scaleType, propName) {\n switch (propName) {\n case 'type':\n case 'domain':\n case 'reverse':\n case 'range':\n return true;\n case 'scheme':\n case 'interpolate':\n return !['point', 'band', 'identity'].includes(scaleType);\n case 'bins':\n return !['point', 'band', 'identity', 'ordinal'].includes(scaleType);\n case 'round':\n return isContinuousToContinuous(scaleType) || scaleType === 'band' || scaleType === 'point';\n case 'padding':\n case 'rangeMin':\n case 'rangeMax':\n return isContinuousToContinuous(scaleType) || ['point', 'band'].includes(scaleType);\n case 'paddingOuter':\n case 'align':\n return ['point', 'band'].includes(scaleType);\n case 'paddingInner':\n return scaleType === 'band';\n case 'domainMax':\n case 'domainMid':\n case 'domainMin':\n case 'clamp':\n return isContinuousToContinuous(scaleType);\n case 'nice':\n return isContinuousToContinuous(scaleType) || scaleType === 'quantize' || scaleType === 'threshold';\n case 'exponent':\n return scaleType === 'pow';\n case 'base':\n return scaleType === 'log';\n case 'constant':\n return scaleType === 'symlog';\n case 'zero':\n return (hasContinuousDomain(scaleType) &&\n !contains([\n 'log',\n 'time',\n 'utc',\n 'threshold',\n 'quantile' // quantile depends on distribution so zero does not matter\n ], scaleType));\n }\n}\n/**\n * Returns undefined if the input channel supports the input scale property name\n */\nexport function channelScalePropertyIncompatability(channel, propName) {\n switch (propName) {\n case 'interpolate':\n case 'scheme':\n case 'domainMid':\n if (!isColorChannel(channel)) {\n return log.message.cannotUseScalePropertyWithNonColor(channel);\n }\n return undefined;\n case 'align':\n case 'type':\n case 'bins':\n case 'domain':\n case 'domainMax':\n case 'domainMin':\n case 'range':\n case 'base':\n case 'exponent':\n case 'constant':\n case 'nice':\n case 'padding':\n case 'paddingInner':\n case 'paddingOuter':\n case 'rangeMax':\n case 'rangeMin':\n case 'reverse':\n case 'round':\n case 'clamp':\n case 'zero':\n return undefined; // GOOD!\n }\n}\nexport function scaleTypeSupportDataType(specifiedType, fieldDefType) {\n if (contains([ORDINAL, NOMINAL], fieldDefType)) {\n return specifiedType === undefined || hasDiscreteDomain(specifiedType);\n }\n else if (fieldDefType === TEMPORAL) {\n return contains([ScaleType.TIME, ScaleType.UTC, undefined], specifiedType);\n }\n else if (fieldDefType === QUANTITATIVE) {\n return contains([\n ScaleType.LOG,\n ScaleType.POW,\n ScaleType.SQRT,\n ScaleType.SYMLOG,\n ScaleType.QUANTILE,\n ScaleType.QUANTIZE,\n ScaleType.THRESHOLD,\n ScaleType.LINEAR,\n undefined\n ], specifiedType);\n }\n return true;\n}\nexport function channelSupportScaleType(channel, scaleType) {\n if (!CHANNEL.isScaleChannel(channel)) {\n return false;\n }\n switch (channel) {\n case CHANNEL.X:\n case CHANNEL.Y:\n case CHANNEL.THETA:\n case CHANNEL.RADIUS:\n return isContinuousToContinuous(scaleType) || contains(['band', 'point'], scaleType);\n case CHANNEL.SIZE: // TODO: size and opacity can support ordinal with more modification\n case CHANNEL.STROKEWIDTH:\n case CHANNEL.OPACITY:\n case CHANNEL.FILLOPACITY:\n case CHANNEL.STROKEOPACITY:\n case CHANNEL.ANGLE:\n // Although it generally doesn't make sense to use band with size and opacity,\n // it can also work since we use band: 0.5 to get midpoint.\n return (isContinuousToContinuous(scaleType) ||\n isContinuousToDiscrete(scaleType) ||\n contains(['band', 'point', 'ordinal'], scaleType));\n case CHANNEL.COLOR:\n case CHANNEL.FILL:\n case CHANNEL.STROKE:\n return scaleType !== 'band'; // band does not make sense with color\n case CHANNEL.STROKEDASH:\n case CHANNEL.SHAPE:\n return scaleType === 'ordinal' || isContinuousToDiscrete(scaleType);\n }\n}\n//# sourceMappingURL=scale.js.map","import { toSet } from 'vega-util';\nimport { keys } from './util';\n/**\n * All types of primitive marks.\n */\nexport const Mark = {\n arc: 'arc',\n area: 'area',\n bar: 'bar',\n image: 'image',\n line: 'line',\n point: 'point',\n rect: 'rect',\n rule: 'rule',\n text: 'text',\n tick: 'tick',\n trail: 'trail',\n circle: 'circle',\n square: 'square',\n geoshape: 'geoshape'\n};\nexport const ARC = Mark.arc;\nexport const AREA = Mark.area;\nexport const BAR = Mark.bar;\nexport const IMAGE = Mark.image;\nexport const LINE = Mark.line;\nexport const POINT = Mark.point;\nexport const RECT = Mark.rect;\nexport const RULE = Mark.rule;\nexport const TEXT = Mark.text;\nexport const TICK = Mark.tick;\nexport const TRAIL = Mark.trail;\nexport const CIRCLE = Mark.circle;\nexport const SQUARE = Mark.square;\nexport const GEOSHAPE = Mark.geoshape;\nexport function isMark(m) {\n return m in Mark;\n}\nexport function isPathMark(m) {\n return ['line', 'area', 'trail'].includes(m);\n}\nexport function isRectBasedMark(m) {\n return ['rect', 'bar', 'image', 'arc' /* arc is rect/interval in polar coordinate */].includes(m);\n}\nexport const PRIMITIVE_MARKS = keys(Mark);\nexport function isMarkDef(mark) {\n return mark['type'];\n}\nconst PRIMITIVE_MARK_INDEX = toSet(PRIMITIVE_MARKS);\nexport function isPrimitiveMark(mark) {\n const markType = isMarkDef(mark) ? mark.type : mark;\n return markType in PRIMITIVE_MARK_INDEX;\n}\nexport const STROKE_CONFIG = [\n 'stroke',\n 'strokeWidth',\n 'strokeDash',\n 'strokeDashOffset',\n 'strokeOpacity',\n 'strokeJoin',\n 'strokeMiterLimit'\n];\nexport const FILL_CONFIG = ['fill', 'fillOpacity'];\nexport const FILL_STROKE_CONFIG = [...STROKE_CONFIG, ...FILL_CONFIG];\nconst VL_ONLY_MARK_CONFIG_INDEX = {\n color: 1,\n filled: 1,\n invalid: 1,\n order: 1,\n radius2: 1,\n theta2: 1,\n timeUnitBandSize: 1,\n timeUnitBandPosition: 1\n};\nexport const VL_ONLY_MARK_CONFIG_PROPERTIES = keys(VL_ONLY_MARK_CONFIG_INDEX);\nexport const VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = {\n area: ['line', 'point'],\n bar: ['binSpacing', 'continuousBandSize', 'discreteBandSize'],\n rect: ['binSpacing', 'continuousBandSize', 'discreteBandSize'],\n line: ['point'],\n tick: ['bandSize', 'thickness']\n};\nexport const defaultMarkConfig = {\n color: '#4c78a8',\n invalid: 'filter',\n timeUnitBandSize: 1\n};\nconst MARK_CONFIG_INDEX = {\n mark: 1,\n arc: 1,\n area: 1,\n bar: 1,\n circle: 1,\n image: 1,\n line: 1,\n point: 1,\n rect: 1,\n rule: 1,\n square: 1,\n text: 1,\n tick: 1,\n trail: 1,\n geoshape: 1\n};\nexport const MARK_CONFIGS = keys(MARK_CONFIG_INDEX);\nexport function isRelativeBandSize(o) {\n return o && o['band'] != undefined;\n}\nexport const BAR_CORNER_RADIUS_INDEX = {\n horizontal: ['cornerRadiusTopRight', 'cornerRadiusBottomRight'],\n vertical: ['cornerRadiusTopLeft', 'cornerRadiusTopRight']\n};\nconst DEFAULT_RECT_BAND_SIZE = 5;\nexport const defaultBarConfig = {\n binSpacing: 1,\n continuousBandSize: DEFAULT_RECT_BAND_SIZE,\n timeUnitBandPosition: 0.5\n};\nexport const defaultRectConfig = {\n binSpacing: 0,\n continuousBandSize: DEFAULT_RECT_BAND_SIZE,\n timeUnitBandPosition: 0.5\n};\nexport const defaultTickConfig = {\n thickness: 1\n};\nexport function getMarkType(m) {\n return isMarkDef(m) ? m.type : m;\n}\n//# sourceMappingURL=mark.js.map","import { isFunction, isString } from 'vega-util';\nimport { isCountingAggregateOp } from '../../../aggregate';\nimport { isBinned, isBinning } from '../../../bin';\nimport { getMainRangeChannel, X, X2, Y2 } from '../../../channel';\nimport { binRequiresRange, getBandPosition, isDatumDef, isFieldDef, isFieldOrDatumDef, isTypedFieldDef, isValueDef, vgField } from '../../../channeldef';\nimport { dateTimeToExpr, isDateTime } from '../../../datetime';\nimport { isExprRef } from '../../../expr';\nimport * as log from '../../../log';\nimport { isPathMark } from '../../../mark';\nimport { fieldValidPredicate } from '../../../predicate';\nimport { hasDiscreteDomain, isContinuousToContinuous } from '../../../scale';\nimport { TEMPORAL } from '../../../type';\nimport { contains, stringify } from '../../../util';\nimport { isSignalRef } from '../../../vega.schema';\nimport { getMarkPropOrConfig, signalOrValueRef } from '../../common';\nexport function midPointRefWithPositionInvalidTest(params) {\n const { channel, channelDef, markDef, scale, config } = params;\n const ref = midPoint(params);\n // Wrap to check if the positional value is invalid, if so, plot the point on the min value\n if (\n // Only this for field def without counting aggregate (as count wouldn't be null)\n isFieldDef(channelDef) &&\n !isCountingAggregateOp(channelDef.aggregate) &&\n // and only for continuous scale without zero (otherwise, null / invalid will be interpreted as zero, which doesn't cause layout problem)\n scale &&\n isContinuousToContinuous(scale.get('type')) &&\n scale.get('zero') === false) {\n return wrapPositionInvalidTest({\n fieldDef: channelDef,\n channel,\n markDef,\n ref,\n config\n });\n }\n return ref;\n}\nexport function wrapPositionInvalidTest({ fieldDef, channel, markDef, ref, config }) {\n if (isPathMark(markDef.type)) {\n // path mark already use defined to skip points, no need to do it here.\n return ref;\n }\n const invalid = getMarkPropOrConfig('invalid', markDef, config);\n if (invalid === null) {\n // if there is no invalid filter, don't do the invalid test\n return ref;\n }\n return [fieldInvalidTestValueRef(fieldDef, channel), ref];\n}\nexport function fieldInvalidTestValueRef(fieldDef, channel) {\n const test = fieldInvalidPredicate(fieldDef, true);\n const mainChannel = getMainRangeChannel(channel); // we can cast here as the output can't be other things.\n const zeroValueRef = mainChannel === 'y'\n ? { field: { group: 'height' } }\n : // x / angle / radius can all use 0\n { value: 0 };\n return Object.assign({ test }, zeroValueRef);\n}\nexport function fieldInvalidPredicate(field, invalid = true) {\n return fieldValidPredicate(isString(field) ? field : vgField(field, { expr: 'datum' }), !invalid);\n}\nexport function datumDefToExpr(datumDef) {\n const { datum } = datumDef;\n if (isDateTime(datum)) {\n return dateTimeToExpr(datum);\n }\n return `${stringify(datum)}`;\n}\nexport function valueRefForFieldOrDatumDef(fieldDef, scaleName, opt, encode) {\n const ref = {};\n if (scaleName) {\n ref.scale = scaleName;\n }\n if (isDatumDef(fieldDef)) {\n const { datum } = fieldDef;\n if (isDateTime(datum)) {\n ref.signal = dateTimeToExpr(datum);\n }\n else if (isSignalRef(datum)) {\n ref.signal = datum.signal;\n }\n else if (isExprRef(datum)) {\n ref.signal = datum.expr;\n }\n else {\n ref.value = datum;\n }\n }\n else {\n ref.field = vgField(fieldDef, opt);\n }\n if (encode) {\n const { offset, band } = encode;\n if (offset) {\n ref.offset = offset;\n }\n if (band) {\n ref.band = band;\n }\n }\n return ref;\n}\n/**\n * Signal that returns the middle of a bin from start and end field. Should only be used with x and y.\n */\nexport function interpolatedSignalRef({ scaleName, fieldOrDatumDef, fieldOrDatumDef2, offset, startSuffix, bandPosition = 0.5 }) {\n const expr = 0 < bandPosition && bandPosition < 1 ? 'datum' : undefined;\n const start = vgField(fieldOrDatumDef, { expr, suffix: startSuffix });\n const end = fieldOrDatumDef2 !== undefined\n ? vgField(fieldOrDatumDef2, { expr })\n : vgField(fieldOrDatumDef, { suffix: 'end', expr });\n const ref = {};\n if (bandPosition === 0 || bandPosition === 1) {\n ref.scale = scaleName;\n const val = bandPosition === 0 ? start : end;\n ref.field = val;\n }\n else {\n const datum = isSignalRef(bandPosition)\n ? `${bandPosition.signal} * ${start} + (1-${bandPosition.signal}) * ${end}`\n : `${bandPosition} * ${start} + ${1 - bandPosition} * ${end}`;\n ref.signal = `scale(\"${scaleName}\", ${datum})`;\n }\n if (offset) {\n ref.offset = offset;\n }\n return ref;\n}\n/**\n * @returns {VgValueRef} Value Ref for xc / yc or mid point for other channels.\n */\nexport function midPoint({ channel, channelDef, channel2Def, markDef, config, scaleName, scale, stack, offset, defaultRef, bandPosition }) {\n var _a;\n // TODO: datum support\n if (channelDef) {\n /* istanbul ignore else */\n if (isFieldOrDatumDef(channelDef)) {\n if (isTypedFieldDef(channelDef)) {\n bandPosition !== null && bandPosition !== void 0 ? bandPosition : (bandPosition = getBandPosition({\n fieldDef: channelDef,\n fieldDef2: channel2Def,\n markDef,\n config\n }));\n const { bin, timeUnit, type } = channelDef;\n if (isBinning(bin) || (bandPosition && timeUnit && type === TEMPORAL)) {\n // Use middle only for x an y to place marks in the center between start and end of the bin range.\n // We do not use the mid point for other channels (e.g. size) so that properties of legends and marks match.\n if (stack === null || stack === void 0 ? void 0 : stack.impute) {\n // For stack, we computed bin_mid so we can impute.\n return valueRefForFieldOrDatumDef(channelDef, scaleName, { binSuffix: 'mid' }, { offset });\n }\n if (bandPosition) {\n // if band = 0, no need to call interpolation\n // For non-stack, we can just calculate bin mid on the fly using signal.\n return interpolatedSignalRef({ scaleName, fieldOrDatumDef: channelDef, bandPosition, offset });\n }\n return valueRefForFieldOrDatumDef(channelDef, scaleName, binRequiresRange(channelDef, channel) ? { binSuffix: 'range' } : {}, {\n offset\n });\n }\n else if (isBinned(bin)) {\n if (isFieldDef(channel2Def)) {\n return interpolatedSignalRef({\n scaleName,\n fieldOrDatumDef: channelDef,\n fieldOrDatumDef2: channel2Def,\n bandPosition,\n offset\n });\n }\n else {\n const channel2 = channel === X ? X2 : Y2;\n log.warn(log.message.channelRequiredForBinned(channel2));\n }\n }\n }\n const scaleType = scale === null || scale === void 0 ? void 0 : scale.get('type');\n return valueRefForFieldOrDatumDef(channelDef, scaleName, hasDiscreteDomain(scaleType) ? { binSuffix: 'range' } : {}, // no need for bin suffix if there is no scale\n {\n offset,\n // For band, to get mid point, need to offset by half of the band\n band: scaleType === 'band' ? (_a = bandPosition !== null && bandPosition !== void 0 ? bandPosition : channelDef.bandPosition) !== null && _a !== void 0 ? _a : 0.5 : undefined\n });\n }\n else if (isValueDef(channelDef)) {\n const value = channelDef.value;\n const offsetMixins = offset ? { offset } : {};\n return Object.assign(Object.assign({}, widthHeightValueOrSignalRef(channel, value)), offsetMixins);\n }\n // If channelDef is neither field def or value def, it's a condition-only def.\n // In such case, we will use default ref.\n }\n if (isFunction(defaultRef)) {\n defaultRef = defaultRef();\n }\n if (defaultRef) {\n // for non-position, ref could be undefined.\n return Object.assign(Object.assign({}, defaultRef), (offset ? { offset } : {}));\n }\n return defaultRef;\n}\n/**\n * Convert special \"width\" and \"height\" values in Vega-Lite into Vega value ref.\n */\nexport function widthHeightValueOrSignalRef(channel, value) {\n if (contains(['x', 'x2'], channel) && value === 'width') {\n return { field: { group: 'width' } };\n }\n else if (contains(['y', 'y2'], channel) && value === 'height') {\n return { field: { group: 'height' } };\n }\n return signalOrValueRef(value);\n}\n//# sourceMappingURL=valueref.js.map","import { isString } from 'vega-util';\nimport { isBinning } from '../bin';\nimport { channelDefType, isFieldDef, isFieldOrDatumDefForTimeFormat, isScaleFieldDef, vgField } from '../channeldef';\nimport { fieldValidPredicate } from '../predicate';\nimport { ScaleType } from '../scale';\nimport { formatExpression, normalizeTimeUnit, timeUnitSpecifierExpression } from '../timeunit';\nimport { QUANTITATIVE } from '../type';\nimport { stringify } from '../util';\nimport { isSignalRef } from '../vega.schema';\nimport { datumDefToExpr } from './mark/encode/valueref';\nexport function isCustomFormatType(formatType) {\n return formatType && formatType !== 'number' && formatType !== 'time';\n}\nfunction customFormatExpr(formatType, field, format) {\n return `${formatType}(${field}${format ? `, ${stringify(format)}` : ''})`;\n}\nexport const BIN_RANGE_DELIMITER = ' \\u2013 ';\nexport function formatSignalRef({ fieldOrDatumDef, format, formatType, expr, normalizeStack, config }) {\n var _a, _b;\n if (isCustomFormatType(formatType)) {\n return formatCustomType({\n fieldOrDatumDef,\n format,\n formatType,\n expr,\n config\n });\n }\n const field = fieldToFormat(fieldOrDatumDef, expr, normalizeStack);\n if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef)) {\n const signal = timeFormatExpression(field, isFieldDef(fieldOrDatumDef) ? (_a = normalizeTimeUnit(fieldOrDatumDef.timeUnit)) === null || _a === void 0 ? void 0 : _a.unit : undefined, format, config.timeFormat, isScaleFieldDef(fieldOrDatumDef) && ((_b = fieldOrDatumDef.scale) === null || _b === void 0 ? void 0 : _b.type) === ScaleType.UTC);\n return signal ? { signal } : undefined;\n }\n format = numberFormat(channelDefType(fieldOrDatumDef), format, config);\n if (isFieldDef(fieldOrDatumDef) && isBinning(fieldOrDatumDef.bin)) {\n const endField = vgField(fieldOrDatumDef, { expr, binSuffix: 'end' });\n return {\n signal: binFormatExpression(field, endField, format, formatType, config)\n };\n }\n else if (format || channelDefType(fieldOrDatumDef) === 'quantitative') {\n return {\n signal: `${formatExpr(field, format)}`\n };\n }\n else {\n return { signal: `isValid(${field}) ? ${field} : \"\"+${field}` };\n }\n}\nfunction fieldToFormat(fieldOrDatumDef, expr, normalizeStack) {\n if (isFieldDef(fieldOrDatumDef)) {\n if (normalizeStack) {\n return `${vgField(fieldOrDatumDef, { expr, suffix: 'end' })}-${vgField(fieldOrDatumDef, {\n expr,\n suffix: 'start'\n })}`;\n }\n else {\n return vgField(fieldOrDatumDef, { expr });\n }\n }\n else {\n return datumDefToExpr(fieldOrDatumDef);\n }\n}\nexport function formatCustomType({ fieldOrDatumDef, format, formatType, expr, normalizeStack, config, field }) {\n field !== null && field !== void 0 ? field : (field = fieldToFormat(fieldOrDatumDef, expr, normalizeStack));\n if (isFieldDef(fieldOrDatumDef) && isBinning(fieldOrDatumDef.bin)) {\n const endField = vgField(fieldOrDatumDef, { expr, binSuffix: 'end' });\n return {\n signal: binFormatExpression(field, endField, format, formatType, config)\n };\n }\n return { signal: customFormatExpr(formatType, field, format) };\n}\nexport function guideFormat(fieldOrDatumDef, type, format, formatType, config, omitTimeFormatConfig // axis doesn't use config.timeFormat\n) {\n var _a;\n if (isCustomFormatType(formatType)) {\n return undefined; // handled in encode block\n }\n if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef)) {\n const timeUnit = isFieldDef(fieldOrDatumDef) ? (_a = normalizeTimeUnit(fieldOrDatumDef.timeUnit)) === null || _a === void 0 ? void 0 : _a.unit : undefined;\n return timeFormat(format, timeUnit, config, omitTimeFormatConfig);\n }\n return numberFormat(type, format, config);\n}\nexport function guideFormatType(formatType, fieldOrDatumDef, scaleType) {\n if (formatType && (isSignalRef(formatType) || formatType === 'number' || formatType === 'time')) {\n return formatType;\n }\n if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef) && scaleType !== 'time' && scaleType !== 'utc') {\n return 'time';\n }\n return undefined;\n}\n/**\n * Returns number format for a fieldDef.\n */\nexport function numberFormat(type, specifiedFormat, config) {\n // Specified format in axis/legend has higher precedence than fieldDef.format\n if (isString(specifiedFormat)) {\n return specifiedFormat;\n }\n if (type === QUANTITATIVE) {\n // we only apply the default if the field is quantitative\n return config.numberFormat;\n }\n return undefined;\n}\n/**\n * Returns time format for a fieldDef for use in guides.\n */\nexport function timeFormat(specifiedFormat, timeUnit, config, omitTimeFormatConfig) {\n if (specifiedFormat) {\n return specifiedFormat;\n }\n if (timeUnit) {\n return {\n signal: timeUnitSpecifierExpression(timeUnit)\n };\n }\n return omitTimeFormatConfig ? undefined : config.timeFormat;\n}\nfunction formatExpr(field, format) {\n return `format(${field}, \"${format || ''}\")`;\n}\nfunction binNumberFormatExpr(field, format, formatType, config) {\n var _a;\n if (isCustomFormatType(formatType)) {\n return customFormatExpr(formatType, field, format);\n }\n return formatExpr(field, (_a = (isString(format) ? format : undefined)) !== null && _a !== void 0 ? _a : config.numberFormat);\n}\nexport function binFormatExpression(startField, endField, format, formatType, config) {\n const start = binNumberFormatExpr(startField, format, formatType, config);\n const end = binNumberFormatExpr(endField, format, formatType, config);\n return `${fieldValidPredicate(startField, false)} ? \"null\" : ${start} + \"${BIN_RANGE_DELIMITER}\" + ${end}`;\n}\n/**\n * Returns the time expression used for axis/legend labels or text mark for a temporal field\n */\nexport function timeFormatExpression(field, timeUnit, format, rawTimeFormat, // should be provided only for actual text and headers, not axis/legend labels\nisUTCScale) {\n if (!timeUnit || format) {\n // If there is no time unit, or if user explicitly specifies format for axis/legend/text.\n format = isString(format) ? format : rawTimeFormat; // only use provided timeFormat if there is no timeUnit.\n return `${isUTCScale ? 'utc' : 'time'}Format(${field}, '${format}')`;\n }\n else {\n return formatExpression(timeUnit, field, isUTCScale);\n }\n}\n//# sourceMappingURL=format.js.map","import { isArray } from 'vega-util';\nexport const DEFAULT_SORT_OP = 'min';\nconst SORT_BY_CHANNEL_INDEX = {\n x: 1,\n y: 1,\n color: 1,\n fill: 1,\n stroke: 1,\n strokeWidth: 1,\n size: 1,\n shape: 1,\n fillOpacity: 1,\n strokeOpacity: 1,\n opacity: 1,\n text: 1\n};\nexport function isSortByChannel(c) {\n return c in SORT_BY_CHANNEL_INDEX;\n}\nexport function isSortByEncoding(sort) {\n return !!sort && !!sort['encoding'];\n}\nexport function isSortField(sort) {\n return !!sort && (sort['op'] === 'count' || !!sort['field']);\n}\nexport function isSortArray(sort) {\n return !!sort && isArray(sort);\n}\n//# sourceMappingURL=sort.js.map","export function isFacetMapping(f) {\n return 'row' in f || 'column' in f;\n}\nexport function isFacetFieldDef(channelDef) {\n return !!channelDef && 'header' in channelDef;\n}\nexport function isFacetSpec(spec) {\n return 'facet' in spec;\n}\n//# sourceMappingURL=facet.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isArray, isBoolean, isNumber, isString } from 'vega-util';\nimport { isAggregateOp, isArgmaxDef, isArgminDef, isCountingAggregateOp } from './aggregate';\nimport { autoMaxBins, binToString, isBinned, isBinning } from './bin';\nimport { ANGLE, COLOR, COLUMN, DESCRIPTION, DETAIL, FACET, FILL, FILLOPACITY, getSizeChannel, HREF, isScaleChannel, isSecondaryRangeChannel, isXorY, KEY, LATITUDE, LATITUDE2, LONGITUDE, LONGITUDE2, OPACITY, ORDER, RADIUS, RADIUS2, ROW, SHAPE, SIZE, STROKE, STROKEDASH, STROKEOPACITY, STROKEWIDTH, TEXT, THETA, THETA2, TOOLTIP, URL, X, X2, Y, Y2 } from './channel';\nimport { getMarkConfig, getMarkPropOrConfig } from './compile/common';\nimport { isCustomFormatType } from './compile/format';\nimport { dateTimeToExpr, isDateTime } from './datetime';\nimport { isExprRef } from './expr';\nimport * as log from './log';\nimport { isRectBasedMark } from './mark';\nimport { hasDiscreteDomain, isContinuousToDiscrete, SCALE_CATEGORY_INDEX } from './scale';\nimport { isSortByChannel } from './sort';\nimport { isFacetFieldDef } from './spec/facet';\nimport { getTimeUnitParts, isLocalSingleTimeUnit, normalizeTimeUnit, timeUnitToString } from './timeunit';\nimport { getFullName, QUANTITATIVE } from './type';\nimport { flatAccessWithDatum, getFirstDefined, internalField, omit, removePathFromField, replacePathInField, stringify, titleCase } from './util';\nimport { isSignalRef } from './vega.schema';\nexport function isConditionalParameter(c) {\n return c['param'];\n}\nexport function isRepeatRef(field) {\n return field && !isString(field) && 'repeat' in field;\n}\nexport function toFieldDefBase(fieldDef) {\n const { field, timeUnit, bin, aggregate } = fieldDef;\n return Object.assign(Object.assign(Object.assign(Object.assign({}, (timeUnit ? { timeUnit } : {})), (bin ? { bin } : {})), (aggregate ? { aggregate } : {})), { field });\n}\nexport function isSortableFieldDef(fieldDef) {\n return 'sort' in fieldDef;\n}\nexport function getBandPosition({ fieldDef, fieldDef2, markDef: mark, config }) {\n if (isFieldOrDatumDef(fieldDef) && fieldDef.bandPosition !== undefined) {\n return fieldDef.bandPosition;\n }\n if (isFieldDef(fieldDef)) {\n const { timeUnit, bin } = fieldDef;\n if (timeUnit && !fieldDef2) {\n return isRectBasedMark(mark.type) ? 0 : getMarkConfig('timeUnitBandPosition', mark, config);\n }\n else if (isBinning(bin)) {\n return 0.5;\n }\n }\n return undefined;\n}\nexport function getBandSize({ channel, fieldDef, fieldDef2, markDef: mark, config, scaleType, useVlSizeChannel }) {\n var _a, _b, _c;\n const sizeChannel = getSizeChannel(channel);\n const size = getMarkPropOrConfig(useVlSizeChannel ? 'size' : sizeChannel, mark, config, {\n vgChannel: sizeChannel\n });\n if (size !== undefined) {\n return size;\n }\n if (isFieldDef(fieldDef)) {\n const { timeUnit, bin } = fieldDef;\n if (timeUnit && !fieldDef2) {\n return { band: getMarkConfig('timeUnitBandSize', mark, config) };\n }\n else if (isBinning(bin) && !hasDiscreteDomain(scaleType)) {\n return { band: 1 };\n }\n }\n if (isRectBasedMark(mark.type)) {\n if (scaleType) {\n if (hasDiscreteDomain(scaleType)) {\n return ((_a = config[mark.type]) === null || _a === void 0 ? void 0 : _a.discreteBandSize) || { band: 1 };\n }\n else {\n return (_b = config[mark.type]) === null || _b === void 0 ? void 0 : _b.continuousBandSize;\n }\n }\n return (_c = config[mark.type]) === null || _c === void 0 ? void 0 : _c.discreteBandSize;\n }\n return undefined;\n}\nexport function hasBandEnd(fieldDef, fieldDef2, markDef, config) {\n if (isBinning(fieldDef.bin) || (fieldDef.timeUnit && isTypedFieldDef(fieldDef) && fieldDef.type === 'temporal')) {\n // Need to check bandPosition because non-rect marks (e.g., point) with timeUnit\n // doesn't have to use bandEnd if there is no bandPosition.\n return getBandPosition({ fieldDef, fieldDef2, markDef, config }) !== undefined;\n }\n return false;\n}\nexport function isConditionalDef(channelDef) {\n return channelDef && 'condition' in channelDef;\n}\n/**\n * Return if a channelDef is a ConditionalValueDef with ConditionFieldDef\n */\nexport function hasConditionalFieldDef(channelDef) {\n const condition = channelDef && channelDef['condition'];\n return !!condition && !isArray(condition) && isFieldDef(condition);\n}\nexport function hasConditionalFieldOrDatumDef(channelDef) {\n const condition = channelDef && channelDef['condition'];\n return !!condition && !isArray(condition) && isFieldOrDatumDef(condition);\n}\nexport function hasConditionalValueDef(channelDef) {\n const condition = channelDef && channelDef['condition'];\n return !!condition && (isArray(condition) || isValueDef(condition));\n}\nexport function isFieldDef(channelDef) {\n // TODO: we can't use field in channelDef here as it's somehow failing runtime test\n return channelDef && (!!channelDef['field'] || channelDef['aggregate'] === 'count');\n}\nexport function channelDefType(channelDef) {\n return channelDef && channelDef['type'];\n}\nexport function isDatumDef(channelDef) {\n return channelDef && 'datum' in channelDef;\n}\nexport function isContinuousFieldOrDatumDef(cd) {\n // TODO: make datum support DateTime object\n return (isTypedFieldDef(cd) && !isDiscrete(cd)) || isNumericDataDef(cd);\n}\nexport function isQuantitativeFieldOrDatumDef(cd) {\n // TODO: make datum support DateTime object\n return channelDefType(cd) === 'quantitative' || isNumericDataDef(cd);\n}\nexport function isNumericDataDef(cd) {\n return isDatumDef(cd) && isNumber(cd.datum);\n}\nexport function isFieldOrDatumDef(channelDef) {\n return isFieldDef(channelDef) || isDatumDef(channelDef);\n}\nexport function isTypedFieldDef(channelDef) {\n return channelDef && ('field' in channelDef || channelDef['aggregate'] === 'count') && 'type' in channelDef;\n}\nexport function isValueDef(channelDef) {\n return channelDef && 'value' in channelDef && 'value' in channelDef;\n}\nexport function isScaleFieldDef(channelDef) {\n return channelDef && ('scale' in channelDef || 'sort' in channelDef);\n}\nexport function isPositionFieldOrDatumDef(channelDef) {\n return channelDef && ('axis' in channelDef || 'stack' in channelDef || 'impute' in channelDef);\n}\nexport function isMarkPropFieldOrDatumDef(channelDef) {\n return channelDef && 'legend' in channelDef;\n}\nexport function isStringFieldOrDatumDef(channelDef) {\n return channelDef && ('format' in channelDef || 'formatType' in channelDef);\n}\nexport function toStringFieldDef(fieldDef) {\n // omit properties that don't exist in string field defs\n return omit(fieldDef, ['legend', 'axis', 'header', 'scale']);\n}\nfunction isOpFieldDef(fieldDef) {\n return 'op' in fieldDef;\n}\n/**\n * Get a Vega field reference from a Vega-Lite field def.\n */\nexport function vgField(fieldDef, opt = {}) {\n var _a, _b, _c;\n let field = fieldDef.field;\n const prefix = opt.prefix;\n let suffix = opt.suffix;\n let argAccessor = ''; // for accessing argmin/argmax field at the end without getting escaped\n if (isCount(fieldDef)) {\n field = internalField('count');\n }\n else {\n let fn;\n if (!opt.nofn) {\n if (isOpFieldDef(fieldDef)) {\n fn = fieldDef.op;\n }\n else {\n const { bin, aggregate, timeUnit } = fieldDef;\n if (isBinning(bin)) {\n fn = binToString(bin);\n suffix = ((_a = opt.binSuffix) !== null && _a !== void 0 ? _a : '') + ((_b = opt.suffix) !== null && _b !== void 0 ? _b : '');\n }\n else if (aggregate) {\n if (isArgmaxDef(aggregate)) {\n argAccessor = `[\"${field}\"]`;\n field = `argmax_${aggregate.argmax}`;\n }\n else if (isArgminDef(aggregate)) {\n argAccessor = `[\"${field}\"]`;\n field = `argmin_${aggregate.argmin}`;\n }\n else {\n fn = String(aggregate);\n }\n }\n else if (timeUnit) {\n fn = timeUnitToString(timeUnit);\n suffix = ((!['range', 'mid'].includes(opt.binSuffix) && opt.binSuffix) || '') + ((_c = opt.suffix) !== null && _c !== void 0 ? _c : '');\n }\n }\n }\n if (fn) {\n field = field ? `${fn}_${field}` : fn;\n }\n }\n if (suffix) {\n field = `${field}_${suffix}`;\n }\n if (prefix) {\n field = `${prefix}_${field}`;\n }\n if (opt.forAs) {\n return removePathFromField(field);\n }\n else if (opt.expr) {\n // Expression to access flattened field. No need to escape dots.\n return flatAccessWithDatum(field, opt.expr) + argAccessor;\n }\n else {\n // We flattened all fields so paths should have become dot.\n return replacePathInField(field) + argAccessor;\n }\n}\nexport function isDiscrete(def) {\n switch (def.type) {\n case 'nominal':\n case 'ordinal':\n case 'geojson':\n return true;\n case 'quantitative':\n return isFieldDef(def) && !!def.bin;\n case 'temporal':\n return false;\n }\n throw new Error(log.message.invalidFieldType(def.type));\n}\nexport function isDiscretizing(def) {\n var _a;\n return isScaleFieldDef(def) && isContinuousToDiscrete((_a = def.scale) === null || _a === void 0 ? void 0 : _a.type);\n}\nexport function isCount(fieldDef) {\n return fieldDef.aggregate === 'count';\n}\nexport function verbalTitleFormatter(fieldDef, config) {\n var _a;\n const { field, bin, timeUnit, aggregate } = fieldDef;\n if (aggregate === 'count') {\n return config.countTitle;\n }\n else if (isBinning(bin)) {\n return `${field} (binned)`;\n }\n else if (timeUnit) {\n const unit = (_a = normalizeTimeUnit(timeUnit)) === null || _a === void 0 ? void 0 : _a.unit;\n if (unit) {\n return `${field} (${getTimeUnitParts(unit).join('-')})`;\n }\n }\n else if (aggregate) {\n if (isArgmaxDef(aggregate)) {\n return `${field} for max ${aggregate.argmax}`;\n }\n else if (isArgminDef(aggregate)) {\n return `${field} for min ${aggregate.argmin}`;\n }\n else {\n return `${titleCase(aggregate)} of ${field}`;\n }\n }\n return field;\n}\nexport function functionalTitleFormatter(fieldDef) {\n const { aggregate, bin, timeUnit, field } = fieldDef;\n if (isArgmaxDef(aggregate)) {\n return `${field} for argmax(${aggregate.argmax})`;\n }\n else if (isArgminDef(aggregate)) {\n return `${field} for argmin(${aggregate.argmin})`;\n }\n const timeUnitParams = normalizeTimeUnit(timeUnit);\n const fn = aggregate || (timeUnitParams === null || timeUnitParams === void 0 ? void 0 : timeUnitParams.unit) || ((timeUnitParams === null || timeUnitParams === void 0 ? void 0 : timeUnitParams.maxbins) && 'timeunit') || (isBinning(bin) && 'bin');\n if (fn) {\n return `${fn.toUpperCase()}(${field})`;\n }\n else {\n return field;\n }\n}\nexport const defaultTitleFormatter = (fieldDef, config) => {\n switch (config.fieldTitle) {\n case 'plain':\n return fieldDef.field;\n case 'functional':\n return functionalTitleFormatter(fieldDef);\n default:\n return verbalTitleFormatter(fieldDef, config);\n }\n};\nlet titleFormatter = defaultTitleFormatter;\nexport function setTitleFormatter(formatter) {\n titleFormatter = formatter;\n}\nexport function resetTitleFormatter() {\n setTitleFormatter(defaultTitleFormatter);\n}\nexport function title(fieldOrDatumDef, config, { allowDisabling, includeDefault = true }) {\n var _a, _b;\n const guideTitle = (_a = getGuide(fieldOrDatumDef)) === null || _a === void 0 ? void 0 : _a.title;\n if (!isFieldDef(fieldOrDatumDef)) {\n return guideTitle;\n }\n const fieldDef = fieldOrDatumDef;\n const def = includeDefault ? defaultTitle(fieldDef, config) : undefined;\n if (allowDisabling) {\n return getFirstDefined(guideTitle, fieldDef.title, def);\n }\n else {\n return (_b = guideTitle !== null && guideTitle !== void 0 ? guideTitle : fieldDef.title) !== null && _b !== void 0 ? _b : def;\n }\n}\nexport function getGuide(fieldDef) {\n if (isPositionFieldOrDatumDef(fieldDef) && fieldDef.axis) {\n return fieldDef.axis;\n }\n else if (isMarkPropFieldOrDatumDef(fieldDef) && fieldDef.legend) {\n return fieldDef.legend;\n }\n else if (isFacetFieldDef(fieldDef) && fieldDef.header) {\n return fieldDef.header;\n }\n return undefined;\n}\nexport function defaultTitle(fieldDef, config) {\n return titleFormatter(fieldDef, config);\n}\nexport function getFormatMixins(fieldDef) {\n var _a;\n if (isStringFieldOrDatumDef(fieldDef)) {\n const { format, formatType } = fieldDef;\n return { format, formatType };\n }\n else {\n const guide = (_a = getGuide(fieldDef)) !== null && _a !== void 0 ? _a : {};\n const { format, formatType } = guide;\n return { format, formatType };\n }\n}\nexport function defaultType(fieldDef, channel) {\n var _a;\n switch (channel) {\n case 'latitude':\n case 'longitude':\n return 'quantitative';\n case 'row':\n case 'column':\n case 'facet':\n case 'shape':\n case 'strokeDash':\n return 'nominal';\n case 'order':\n return 'ordinal';\n }\n if (isSortableFieldDef(fieldDef) && isArray(fieldDef.sort)) {\n return 'ordinal';\n }\n const { aggregate, bin, timeUnit } = fieldDef;\n if (timeUnit) {\n return 'temporal';\n }\n if (bin || (aggregate && !isArgmaxDef(aggregate) && !isArgminDef(aggregate))) {\n return 'quantitative';\n }\n if (isScaleFieldDef(fieldDef) && ((_a = fieldDef.scale) === null || _a === void 0 ? void 0 : _a.type)) {\n switch (SCALE_CATEGORY_INDEX[fieldDef.scale.type]) {\n case 'numeric':\n case 'discretizing':\n return 'quantitative';\n case 'time':\n return 'temporal';\n }\n }\n return 'nominal';\n}\n/**\n * Returns the fieldDef -- either from the outer channelDef or from the condition of channelDef.\n * @param channelDef\n */\nexport function getFieldDef(channelDef) {\n if (isFieldDef(channelDef)) {\n return channelDef;\n }\n else if (hasConditionalFieldDef(channelDef)) {\n return channelDef.condition;\n }\n return undefined;\n}\nexport function getFieldOrDatumDef(channelDef) {\n if (isFieldOrDatumDef(channelDef)) {\n return channelDef;\n }\n else if (hasConditionalFieldOrDatumDef(channelDef)) {\n return channelDef.condition;\n }\n return undefined;\n}\n/**\n * Convert type to full, lowercase type, or augment the fieldDef with a default type if missing.\n */\nexport function initChannelDef(channelDef, channel, config, opt = {}) {\n if (isString(channelDef) || isNumber(channelDef) || isBoolean(channelDef)) {\n const primitiveType = isString(channelDef) ? 'string' : isNumber(channelDef) ? 'number' : 'boolean';\n log.warn(log.message.primitiveChannelDef(channel, primitiveType, channelDef));\n return { value: channelDef };\n }\n // If a fieldDef contains a field, we need type.\n if (isFieldOrDatumDef(channelDef)) {\n return initFieldOrDatumDef(channelDef, channel, config, opt);\n }\n else if (hasConditionalFieldOrDatumDef(channelDef)) {\n return Object.assign(Object.assign({}, channelDef), { \n // Need to cast as normalizeFieldDef normally return FieldDef, but here we know that it is definitely Condition\n condition: initFieldOrDatumDef(channelDef.condition, channel, config, opt) });\n }\n return channelDef;\n}\nexport function initFieldOrDatumDef(fd, channel, config, opt) {\n if (isStringFieldOrDatumDef(fd)) {\n const { format, formatType } = fd, rest = __rest(fd, [\"format\", \"formatType\"]);\n if (isCustomFormatType(formatType) && !config.customFormatTypes) {\n log.warn(log.message.customFormatTypeNotAllowed(channel));\n return initFieldOrDatumDef(rest, channel, config, opt);\n }\n }\n else {\n const guideType = isPositionFieldOrDatumDef(fd)\n ? 'axis'\n : isMarkPropFieldOrDatumDef(fd)\n ? 'legend'\n : isFacetFieldDef(fd)\n ? 'header'\n : null;\n if (guideType && fd[guideType]) {\n const _a = fd[guideType], { format, formatType } = _a, newGuide = __rest(_a, [\"format\", \"formatType\"]);\n if (isCustomFormatType(formatType) && !config.customFormatTypes) {\n log.warn(log.message.customFormatTypeNotAllowed(channel));\n return initFieldOrDatumDef(Object.assign(Object.assign({}, fd), { [guideType]: newGuide }), channel, config, opt);\n }\n }\n }\n if (isFieldDef(fd)) {\n return initFieldDef(fd, channel, opt);\n }\n return initDatumDef(fd);\n}\nfunction initDatumDef(datumDef) {\n let type = datumDef['type'];\n if (type) {\n return datumDef;\n }\n const { datum } = datumDef;\n type = isNumber(datum) ? 'quantitative' : isString(datum) ? 'nominal' : isDateTime(datum) ? 'temporal' : undefined;\n return Object.assign(Object.assign({}, datumDef), { type });\n}\nexport function initFieldDef(fd, channel, { compositeMark = false } = {}) {\n const { aggregate, timeUnit, bin, field } = fd;\n const fieldDef = Object.assign({}, fd);\n // Drop invalid aggregate\n if (!compositeMark && aggregate && !isAggregateOp(aggregate) && !isArgmaxDef(aggregate) && !isArgminDef(aggregate)) {\n log.warn(log.message.invalidAggregate(aggregate));\n delete fieldDef.aggregate;\n }\n // Normalize Time Unit\n if (timeUnit) {\n fieldDef.timeUnit = normalizeTimeUnit(timeUnit);\n }\n if (field) {\n fieldDef.field = `${field}`;\n }\n // Normalize bin\n if (isBinning(bin)) {\n fieldDef.bin = normalizeBin(bin, channel);\n }\n if (isBinned(bin) && !isXorY(channel)) {\n log.warn(log.message.channelShouldNotBeUsedForBinned(channel));\n }\n // Normalize Type\n if (isTypedFieldDef(fieldDef)) {\n const { type } = fieldDef;\n const fullType = getFullName(type);\n if (type !== fullType) {\n // convert short type to full type\n fieldDef.type = fullType;\n }\n if (type !== 'quantitative') {\n if (isCountingAggregateOp(aggregate)) {\n log.warn(log.message.invalidFieldTypeForCountAggregate(type, aggregate));\n fieldDef.type = 'quantitative';\n }\n }\n }\n else if (!isSecondaryRangeChannel(channel)) {\n // If type is empty / invalid, then augment with default type\n const newType = defaultType(fieldDef, channel);\n fieldDef['type'] = newType;\n }\n if (isTypedFieldDef(fieldDef)) {\n const { compatible, warning } = channelCompatibility(fieldDef, channel) || {};\n if (compatible === false) {\n log.warn(warning);\n }\n }\n if (isSortableFieldDef(fieldDef) && isString(fieldDef.sort)) {\n const { sort } = fieldDef;\n if (isSortByChannel(sort)) {\n return Object.assign(Object.assign({}, fieldDef), { sort: { encoding: sort } });\n }\n const sub = sort.substr(1);\n if (sort.charAt(0) === '-' && isSortByChannel(sub)) {\n return Object.assign(Object.assign({}, fieldDef), { sort: { encoding: sub, order: 'descending' } });\n }\n }\n if (isFacetFieldDef(fieldDef)) {\n const { header } = fieldDef;\n if (header) {\n const { orient } = header, rest = __rest(header, [\"orient\"]);\n if (orient) {\n return Object.assign(Object.assign({}, fieldDef), { header: Object.assign(Object.assign({}, rest), { labelOrient: header.labelOrient || orient, titleOrient: header.titleOrient || orient }) });\n }\n }\n }\n return fieldDef;\n}\nexport function normalizeBin(bin, channel) {\n if (isBoolean(bin)) {\n return { maxbins: autoMaxBins(channel) };\n }\n else if (bin === 'binned') {\n return {\n binned: true\n };\n }\n else if (!bin.maxbins && !bin.step) {\n return Object.assign(Object.assign({}, bin), { maxbins: autoMaxBins(channel) });\n }\n else {\n return bin;\n }\n}\nconst COMPATIBLE = { compatible: true };\nexport function channelCompatibility(fieldDef, channel) {\n const type = fieldDef.type;\n if (type === 'geojson' && channel !== 'shape') {\n return {\n compatible: false,\n warning: `Channel ${channel} should not be used with a geojson data.`\n };\n }\n switch (channel) {\n case ROW:\n case COLUMN:\n case FACET:\n if (!isDiscrete(fieldDef)) {\n return {\n compatible: false,\n warning: log.message.channelShouldBeDiscrete(channel)\n };\n }\n return COMPATIBLE;\n case X:\n case Y:\n case COLOR:\n case FILL:\n case STROKE:\n case TEXT:\n case DETAIL:\n case KEY:\n case TOOLTIP:\n case HREF:\n case URL:\n case ANGLE:\n case THETA:\n case RADIUS:\n case DESCRIPTION:\n return COMPATIBLE;\n case LONGITUDE:\n case LONGITUDE2:\n case LATITUDE:\n case LATITUDE2:\n if (type !== QUANTITATIVE) {\n return {\n compatible: false,\n warning: `Channel ${channel} should be used with a quantitative field only, not ${fieldDef.type} field.`\n };\n }\n return COMPATIBLE;\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n case STROKEWIDTH:\n case SIZE:\n case THETA2:\n case RADIUS2:\n case X2:\n case Y2:\n if (type === 'nominal' && !fieldDef['sort']) {\n return {\n compatible: false,\n warning: `Channel ${channel} should not be used with an unsorted discrete field.`\n };\n }\n return COMPATIBLE;\n case SHAPE:\n case STROKEDASH:\n if (!isDiscrete(fieldDef) && !isDiscretizing(fieldDef)) {\n return {\n compatible: false,\n warning: log.message.channelShouldBeDiscreteOrDiscretizing(channel)\n };\n }\n return COMPATIBLE;\n case ORDER:\n if (fieldDef.type === 'nominal' && !('sort' in fieldDef)) {\n return {\n compatible: false,\n warning: `Channel order is inappropriate for nominal field, which has no inherent order.`\n };\n }\n return COMPATIBLE;\n }\n}\n/**\n * Check if the field def uses a time format or does not use any format but is temporal\n * (this does not cover field defs that are temporal but use a number format).\n */\nexport function isFieldOrDatumDefForTimeFormat(fieldOrDatumDef) {\n const { formatType } = getFormatMixins(fieldOrDatumDef);\n return formatType === 'time' || (!formatType && isTimeFieldDef(fieldOrDatumDef));\n}\n/**\n * Check if field def has type `temporal`. If you want to also cover field defs that use a time format, use `isTimeFormatFieldDef`.\n */\nexport function isTimeFieldDef(def) {\n return def && (def['type'] === 'temporal' || (isFieldDef(def) && !!def.timeUnit));\n}\n/**\n * Getting a value associated with a fielddef.\n * Convert the value to Vega expression if applicable (for datetime object, or string if the field def is temporal or has timeUnit)\n */\nexport function valueExpr(v, { timeUnit, type, wrapTime, undefinedIfExprNotRequired }) {\n var _a;\n const unit = timeUnit && ((_a = normalizeTimeUnit(timeUnit)) === null || _a === void 0 ? void 0 : _a.unit);\n let isTime = unit || type === 'temporal';\n let expr;\n if (isExprRef(v)) {\n expr = v.expr;\n }\n else if (isSignalRef(v)) {\n expr = v.signal;\n }\n else if (isDateTime(v)) {\n isTime = true;\n expr = dateTimeToExpr(v);\n }\n else if (isString(v) || isNumber(v)) {\n if (isTime) {\n expr = `datetime(${stringify(v)})`;\n if (isLocalSingleTimeUnit(unit)) {\n // for single timeUnit, we will use dateTimeToExpr to convert number/string to match the timeUnit\n if ((isNumber(v) && v < 10000) || (isString(v) && isNaN(Date.parse(v)))) {\n expr = dateTimeToExpr({ [unit]: v });\n }\n }\n }\n }\n if (expr) {\n return wrapTime && isTime ? `time(${expr})` : expr;\n }\n // number or boolean or normal string\n return undefinedIfExprNotRequired ? undefined : stringify(v);\n}\n/**\n * Standardize value array -- convert each value to Vega expression if applicable\n */\nexport function valueArray(fieldOrDatumDef, values) {\n const { type } = fieldOrDatumDef;\n return values.map(v => {\n const expr = valueExpr(v, {\n timeUnit: isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.timeUnit : undefined,\n type,\n undefinedIfExprNotRequired: true\n });\n // return signal for the expression if we need an expression\n if (expr !== undefined) {\n return { signal: expr };\n }\n // otherwise just return the original value\n return v;\n });\n}\n/**\n * Checks whether a fieldDef for a particular channel requires a computed bin range.\n */\nexport function binRequiresRange(fieldDef, channel) {\n if (!isBinning(fieldDef.bin)) {\n console.warn('Only call this method for binned field defs.');\n return false;\n }\n // We need the range only when the user explicitly forces a binned field to be use discrete scale. In this case, bin range is used in axis and legend labels.\n // We could check whether the axis or legend exists (not disabled) but that seems overkill.\n return isScaleChannel(channel) && ['ordinal', 'nominal'].includes(fieldDef.type);\n}\n//# sourceMappingURL=channeldef.js.map","import { keys } from './util';\nexport const CONDITIONAL_AXIS_PROP_INDEX = {\n labelAlign: {\n part: 'labels',\n vgProp: 'align'\n },\n labelBaseline: {\n part: 'labels',\n vgProp: 'baseline'\n },\n labelColor: {\n part: 'labels',\n vgProp: 'fill'\n },\n labelFont: {\n part: 'labels',\n vgProp: 'font'\n },\n labelFontSize: {\n part: 'labels',\n vgProp: 'fontSize'\n },\n labelFontStyle: {\n part: 'labels',\n vgProp: 'fontStyle'\n },\n labelFontWeight: {\n part: 'labels',\n vgProp: 'fontWeight'\n },\n labelOpacity: {\n part: 'labels',\n vgProp: 'opacity'\n },\n labelOffset: null,\n labelPadding: null,\n gridColor: {\n part: 'grid',\n vgProp: 'stroke'\n },\n gridDash: {\n part: 'grid',\n vgProp: 'strokeDash'\n },\n gridDashOffset: {\n part: 'grid',\n vgProp: 'strokeDashOffset'\n },\n gridOpacity: {\n part: 'grid',\n vgProp: 'opacity'\n },\n gridWidth: {\n part: 'grid',\n vgProp: 'strokeWidth'\n },\n tickColor: {\n part: 'ticks',\n vgProp: 'stroke'\n },\n tickDash: {\n part: 'ticks',\n vgProp: 'strokeDash'\n },\n tickDashOffset: {\n part: 'ticks',\n vgProp: 'strokeDashOffset'\n },\n tickOpacity: {\n part: 'ticks',\n vgProp: 'opacity'\n },\n tickSize: null,\n tickWidth: {\n part: 'ticks',\n vgProp: 'strokeWidth'\n }\n};\nexport function isConditionalAxisValue(v) {\n return v && v['condition'];\n}\nexport const AXIS_PARTS = ['domain', 'grid', 'labels', 'ticks', 'title'];\n/**\n * A dictionary listing whether a certain axis property is applicable for only main axes or only grid axes.\n */\nexport const AXIS_PROPERTY_TYPE = {\n grid: 'grid',\n gridCap: 'grid',\n gridColor: 'grid',\n gridDash: 'grid',\n gridDashOffset: 'grid',\n gridOpacity: 'grid',\n gridScale: 'grid',\n gridWidth: 'grid',\n orient: 'main',\n bandPosition: 'both',\n aria: 'main',\n description: 'main',\n domain: 'main',\n domainCap: 'main',\n domainColor: 'main',\n domainDash: 'main',\n domainDashOffset: 'main',\n domainOpacity: 'main',\n domainWidth: 'main',\n format: 'main',\n formatType: 'main',\n labelAlign: 'main',\n labelAngle: 'main',\n labelBaseline: 'main',\n labelBound: 'main',\n labelColor: 'main',\n labelFlush: 'main',\n labelFlushOffset: 'main',\n labelFont: 'main',\n labelFontSize: 'main',\n labelFontStyle: 'main',\n labelFontWeight: 'main',\n labelLimit: 'main',\n labelLineHeight: 'main',\n labelOffset: 'main',\n labelOpacity: 'main',\n labelOverlap: 'main',\n labelPadding: 'main',\n labels: 'main',\n labelSeparation: 'main',\n maxExtent: 'main',\n minExtent: 'main',\n offset: 'both',\n position: 'main',\n tickCap: 'main',\n tickColor: 'main',\n tickDash: 'main',\n tickDashOffset: 'main',\n tickMinStep: 'both',\n tickOffset: 'both',\n tickOpacity: 'main',\n tickRound: 'both',\n ticks: 'main',\n tickSize: 'main',\n tickWidth: 'both',\n title: 'main',\n titleAlign: 'main',\n titleAnchor: 'main',\n titleAngle: 'main',\n titleBaseline: 'main',\n titleColor: 'main',\n titleFont: 'main',\n titleFontSize: 'main',\n titleFontStyle: 'main',\n titleFontWeight: 'main',\n titleLimit: 'main',\n titleLineHeight: 'main',\n titleOpacity: 'main',\n titlePadding: 'main',\n titleX: 'main',\n titleY: 'main',\n encode: 'both',\n scale: 'both',\n tickBand: 'both',\n tickCount: 'both',\n tickExtra: 'both',\n translate: 'both',\n values: 'both',\n zindex: 'both' // this is actually set afterward, so it doesn't matter\n};\nexport const COMMON_AXIS_PROPERTIES_INDEX = {\n orient: 1,\n aria: 1,\n bandPosition: 1,\n description: 1,\n domain: 1,\n domainCap: 1,\n domainColor: 1,\n domainDash: 1,\n domainDashOffset: 1,\n domainOpacity: 1,\n domainWidth: 1,\n format: 1,\n formatType: 1,\n grid: 1,\n gridCap: 1,\n gridColor: 1,\n gridDash: 1,\n gridDashOffset: 1,\n gridOpacity: 1,\n gridWidth: 1,\n labelAlign: 1,\n labelAngle: 1,\n labelBaseline: 1,\n labelBound: 1,\n labelColor: 1,\n labelFlush: 1,\n labelFlushOffset: 1,\n labelFont: 1,\n labelFontSize: 1,\n labelFontStyle: 1,\n labelFontWeight: 1,\n labelLimit: 1,\n labelLineHeight: 1,\n labelOffset: 1,\n labelOpacity: 1,\n labelOverlap: 1,\n labelPadding: 1,\n labels: 1,\n labelSeparation: 1,\n maxExtent: 1,\n minExtent: 1,\n offset: 1,\n position: 1,\n tickBand: 1,\n tickCap: 1,\n tickColor: 1,\n tickCount: 1,\n tickDash: 1,\n tickDashOffset: 1,\n tickExtra: 1,\n tickMinStep: 1,\n tickOffset: 1,\n tickOpacity: 1,\n tickRound: 1,\n ticks: 1,\n tickSize: 1,\n tickWidth: 1,\n title: 1,\n titleAlign: 1,\n titleAnchor: 1,\n titleAngle: 1,\n titleBaseline: 1,\n titleColor: 1,\n titleFont: 1,\n titleFontSize: 1,\n titleFontStyle: 1,\n titleFontWeight: 1,\n titleLimit: 1,\n titleLineHeight: 1,\n titleOpacity: 1,\n titlePadding: 1,\n titleX: 1,\n titleY: 1,\n translate: 1,\n values: 1,\n zindex: 1\n};\nconst AXIS_PROPERTIES_INDEX = Object.assign(Object.assign({}, COMMON_AXIS_PROPERTIES_INDEX), { style: 1, labelExpr: 1, encoding: 1 });\nexport function isAxisProperty(prop) {\n return !!AXIS_PROPERTIES_INDEX[prop];\n}\n// Export for dependent projects\nexport const AXIS_PROPERTIES = keys(AXIS_PROPERTIES_INDEX);\nconst AXIS_CONFIGS_INDEX = {\n axis: 1,\n axisBand: 1,\n axisBottom: 1,\n axisDiscrete: 1,\n axisLeft: 1,\n axisPoint: 1,\n axisQuantitative: 1,\n axisRight: 1,\n axisTemporal: 1,\n axisTop: 1,\n axisX: 1,\n axisXBand: 1,\n axisXDiscrete: 1,\n axisXPoint: 1,\n axisXQuantitative: 1,\n axisXTemporal: 1,\n axisY: 1,\n axisYBand: 1,\n axisYDiscrete: 1,\n axisYPoint: 1,\n axisYQuantitative: 1,\n axisYTemporal: 1\n};\nexport const AXIS_CONFIGS = keys(AXIS_CONFIGS_INDEX);\n//# sourceMappingURL=axis.js.map","export function isUnitSpec(spec) {\n return 'mark' in spec;\n}\n//# sourceMappingURL=unit.js.map","import { getMarkType } from '../mark';\nimport { isUnitSpec } from '../spec/unit';\nexport class CompositeMarkNormalizer {\n constructor(name, run) {\n this.name = name;\n this.run = run;\n }\n hasMatchingType(spec) {\n if (isUnitSpec(spec)) {\n return getMarkType(spec.mark) === this.name;\n }\n return false;\n }\n}\n//# sourceMappingURL=base.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { array, isArray } from 'vega-util';\nimport { isArgmaxDef, isArgminDef } from './aggregate';\nimport { isBinned, isBinning } from './bin';\nimport { ANGLE, CHANNELS, COLOR, DESCRIPTION, DETAIL, FILL, FILLOPACITY, HREF, isChannel, isNonPositionScaleChannel, isSecondaryRangeChannel, isXorY, KEY, LATITUDE, LATITUDE2, LONGITUDE, LONGITUDE2, OPACITY, ORDER, RADIUS, RADIUS2, SHAPE, SIZE, STROKE, STROKEDASH, STROKEOPACITY, STROKEWIDTH, supportMark, TEXT, THETA, THETA2, TOOLTIP, URL, X, X2, Y, Y2 } from './channel';\nimport { binRequiresRange, getFieldDef, getGuide, hasConditionalFieldDef, initChannelDef, initFieldDef, isConditionalDef, isDatumDef, isFieldDef, isTypedFieldDef, isValueDef, title, vgField } from './channeldef';\nimport * as log from './log';\nimport { QUANTITATIVE, TEMPORAL } from './type';\nimport { keys, some } from './util';\nimport { isSignalRef } from './vega.schema';\nexport function channelHasField(encoding, channel) {\n const channelDef = encoding && encoding[channel];\n if (channelDef) {\n if (isArray(channelDef)) {\n return some(channelDef, fieldDef => !!fieldDef.field);\n }\n else {\n return isFieldDef(channelDef) || hasConditionalFieldDef(channelDef);\n }\n }\n return false;\n}\nexport function isAggregate(encoding) {\n return some(CHANNELS, channel => {\n if (channelHasField(encoding, channel)) {\n const channelDef = encoding[channel];\n if (isArray(channelDef)) {\n return some(channelDef, fieldDef => !!fieldDef.aggregate);\n }\n else {\n const fieldDef = getFieldDef(channelDef);\n return fieldDef && !!fieldDef.aggregate;\n }\n }\n return false;\n });\n}\nexport function extractTransformsFromEncoding(oldEncoding, config) {\n const groupby = [];\n const bins = [];\n const timeUnits = [];\n const aggregate = [];\n const encoding = {};\n forEach(oldEncoding, (channelDef, channel) => {\n // Extract potential embedded transformations along with remaining properties\n if (isFieldDef(channelDef)) {\n const { field, aggregate: aggOp, bin, timeUnit } = channelDef, remaining = __rest(channelDef, [\"field\", \"aggregate\", \"bin\", \"timeUnit\"]);\n if (aggOp || timeUnit || bin) {\n const guide = getGuide(channelDef);\n const isTitleDefined = guide === null || guide === void 0 ? void 0 : guide.title;\n let newField = vgField(channelDef, { forAs: true });\n const newFieldDef = Object.assign(Object.assign(Object.assign({}, (isTitleDefined ? [] : { title: title(channelDef, config, { allowDisabling: true }) })), remaining), { \n // Always overwrite field\n field: newField });\n if (aggOp) {\n let op;\n if (isArgmaxDef(aggOp)) {\n op = 'argmax';\n newField = vgField({ op: 'argmax', field: aggOp.argmax }, { forAs: true });\n newFieldDef.field = `${newField}.${field}`;\n }\n else if (isArgminDef(aggOp)) {\n op = 'argmin';\n newField = vgField({ op: 'argmin', field: aggOp.argmin }, { forAs: true });\n newFieldDef.field = `${newField}.${field}`;\n }\n else if (aggOp !== 'boxplot' && aggOp !== 'errorbar' && aggOp !== 'errorband') {\n op = aggOp;\n }\n if (op) {\n const aggregateEntry = {\n op,\n as: newField\n };\n if (field) {\n aggregateEntry.field = field;\n }\n aggregate.push(aggregateEntry);\n }\n }\n else {\n groupby.push(newField);\n if (isTypedFieldDef(channelDef) && isBinning(bin)) {\n bins.push({ bin, field, as: newField });\n // Add additional groupbys for range and end of bins\n groupby.push(vgField(channelDef, { binSuffix: 'end' }));\n if (binRequiresRange(channelDef, channel)) {\n groupby.push(vgField(channelDef, { binSuffix: 'range' }));\n }\n // Create accompanying 'x2' or 'y2' field if channel is 'x' or 'y' respectively\n if (isXorY(channel)) {\n const secondaryChannel = {\n field: `${newField}_end`\n };\n encoding[`${channel}2`] = secondaryChannel;\n }\n newFieldDef.bin = 'binned';\n if (!isSecondaryRangeChannel(channel)) {\n newFieldDef['type'] = QUANTITATIVE;\n }\n }\n else if (timeUnit) {\n timeUnits.push({\n timeUnit,\n field,\n as: newField\n });\n // define the format type for later compilation\n const formatType = isTypedFieldDef(channelDef) && channelDef.type !== TEMPORAL && 'time';\n if (formatType) {\n if (channel === TEXT || channel === TOOLTIP) {\n newFieldDef['formatType'] = formatType;\n }\n else if (isNonPositionScaleChannel(channel)) {\n newFieldDef['legend'] = Object.assign({ formatType }, newFieldDef['legend']);\n }\n else if (isXorY(channel)) {\n newFieldDef['axis'] = Object.assign({ formatType }, newFieldDef['axis']);\n }\n }\n }\n }\n // now the field should refer to post-transformed field instead\n encoding[channel] = newFieldDef;\n }\n else {\n groupby.push(field);\n encoding[channel] = oldEncoding[channel];\n }\n }\n else {\n // For value def / signal ref / datum def, just copy\n encoding[channel] = oldEncoding[channel];\n }\n });\n return {\n bins,\n timeUnits,\n aggregate,\n groupby,\n encoding\n };\n}\nexport function markChannelCompatible(encoding, channel, mark) {\n const markSupported = supportMark(channel, mark);\n if (!markSupported) {\n return false;\n }\n else if (markSupported === 'binned') {\n const primaryFieldDef = encoding[channel === X2 ? X : Y];\n // circle, point, square and tick only support x2/y2 when their corresponding x/y fieldDef\n // has \"binned\" data and thus need x2/y2 to specify the bin-end field.\n if (isFieldDef(primaryFieldDef) && isFieldDef(encoding[channel]) && isBinned(primaryFieldDef.bin)) {\n return true;\n }\n else {\n return false;\n }\n }\n return true;\n}\nexport function initEncoding(encoding, mark, filled, config) {\n return keys(encoding).reduce((normalizedEncoding, channel) => {\n if (!isChannel(channel)) {\n // Drop invalid channel\n log.warn(log.message.invalidEncodingChannel(channel));\n return normalizedEncoding;\n }\n const channelDef = encoding[channel];\n if (channel === 'angle' && mark === 'arc' && !encoding.theta) {\n log.warn(log.message.REPLACE_ANGLE_WITH_THETA);\n channel = THETA;\n }\n if (!markChannelCompatible(encoding, channel, mark)) {\n // Drop unsupported channel\n log.warn(log.message.incompatibleChannel(channel, mark));\n return normalizedEncoding;\n }\n // Drop line's size if the field is aggregated.\n if (channel === SIZE && mark === 'line') {\n const fieldDef = getFieldDef(encoding[channel]);\n if (fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.aggregate) {\n log.warn(log.message.LINE_WITH_VARYING_SIZE);\n return normalizedEncoding;\n }\n }\n // Drop color if either fill or stroke is specified\n if (channel === COLOR && (filled ? 'fill' in encoding : 'stroke' in encoding)) {\n log.warn(log.message.droppingColor('encoding', { fill: 'fill' in encoding, stroke: 'stroke' in encoding }));\n return normalizedEncoding;\n }\n if (channel === DETAIL ||\n (channel === ORDER && !isArray(channelDef) && !isValueDef(channelDef)) ||\n (channel === TOOLTIP && isArray(channelDef))) {\n if (channelDef) {\n // Array of fieldDefs for detail channel (or production rule)\n normalizedEncoding[channel] = array(channelDef).reduce((defs, fieldDef) => {\n if (!isFieldDef(fieldDef)) {\n log.warn(log.message.emptyFieldDef(fieldDef, channel));\n }\n else {\n defs.push(initFieldDef(fieldDef, channel));\n }\n return defs;\n }, []);\n }\n }\n else {\n if (channel === TOOLTIP && channelDef === null) {\n // Preserve null so we can use it to disable tooltip\n normalizedEncoding[channel] = null;\n }\n else if (!isFieldDef(channelDef) &&\n !isDatumDef(channelDef) &&\n !isValueDef(channelDef) &&\n !isConditionalDef(channelDef) &&\n !isSignalRef(channelDef)) {\n log.warn(log.message.emptyFieldDef(channelDef, channel));\n return normalizedEncoding;\n }\n normalizedEncoding[channel] = initChannelDef(channelDef, channel, config);\n }\n return normalizedEncoding;\n }, {});\n}\n/**\n * For composite marks, we have to call initChannelDef during init so we can infer types earlier.\n */\nexport function normalizeEncoding(encoding, config) {\n const normalizedEncoding = {};\n for (const channel of keys(encoding)) {\n const newChannelDef = initChannelDef(encoding[channel], channel, config, { compositeMark: true });\n normalizedEncoding[channel] = newChannelDef;\n }\n return normalizedEncoding;\n}\nexport function fieldDefs(encoding) {\n const arr = [];\n for (const channel of keys(encoding)) {\n if (channelHasField(encoding, channel)) {\n const channelDef = encoding[channel];\n const channelDefArray = array(channelDef);\n for (const def of channelDefArray) {\n if (isFieldDef(def)) {\n arr.push(def);\n }\n else if (hasConditionalFieldDef(def)) {\n arr.push(def.condition);\n }\n }\n }\n }\n return arr;\n}\nexport function forEach(mapping, f, thisArg) {\n if (!mapping) {\n return;\n }\n for (const channel of keys(mapping)) {\n const el = mapping[channel];\n if (isArray(el)) {\n for (const channelDef of el) {\n f.call(thisArg, channelDef, channel);\n }\n }\n else {\n f.call(thisArg, el, channel);\n }\n }\n}\nexport function reduce(mapping, f, init, thisArg) {\n if (!mapping) {\n return init;\n }\n return keys(mapping).reduce((r, channel) => {\n const map = mapping[channel];\n if (isArray(map)) {\n return map.reduce((r1, channelDef) => {\n return f.call(thisArg, r1, channelDef, channel);\n }, r);\n }\n else {\n return f.call(thisArg, r, map, channel);\n }\n }, init);\n}\n/**\n * Returns list of path grouping fields for the given encoding\n */\nexport function pathGroupingFields(mark, encoding) {\n return keys(encoding).reduce((details, channel) => {\n switch (channel) {\n // x, y, x2, y2, lat, long, lat1, long2, order, tooltip, href, aria label, cursor should not cause lines to group\n case X:\n case Y:\n case HREF:\n case DESCRIPTION:\n case URL:\n case X2:\n case Y2:\n case THETA:\n case THETA2:\n case RADIUS:\n case RADIUS2:\n // falls through\n case LATITUDE:\n case LONGITUDE:\n case LATITUDE2:\n case LONGITUDE2:\n // TODO: case 'cursor':\n // text, shape, shouldn't be a part of line/trail/area [falls through]\n case TEXT:\n case SHAPE:\n case ANGLE:\n // falls through\n // tooltip fields should not be added to group by [falls through]\n case TOOLTIP:\n return details;\n case ORDER:\n // order should not group line / trail\n if (mark === 'line' || mark === 'trail') {\n return details;\n }\n // but order should group area for stacking (falls through)\n case DETAIL:\n case KEY: {\n const channelDef = encoding[channel];\n if (isArray(channelDef) || isFieldDef(channelDef)) {\n for (const fieldDef of array(channelDef)) {\n if (!fieldDef.aggregate) {\n details.push(vgField(fieldDef, {}));\n }\n }\n }\n return details;\n }\n case SIZE:\n if (mark === 'trail') {\n // For trail, size should not group trail lines.\n return details;\n }\n // For line, size should group lines.\n // falls through\n case COLOR:\n case FILL:\n case STROKE:\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n case STROKEDASH:\n case STROKEWIDTH: {\n // TODO strokeDashOffset:\n // falls through\n const fieldDef = getFieldDef(encoding[channel]);\n if (fieldDef && !fieldDef.aggregate) {\n details.push(vgField(fieldDef, {}));\n }\n return details;\n }\n }\n }, []);\n}\n//# sourceMappingURL=encoding.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isArray, isBoolean, isString } from 'vega-util';\nimport { isContinuousFieldOrDatumDef, isFieldDef, isFieldOrDatumDefForTimeFormat } from '../channeldef';\nimport { fieldDefs } from '../encoding';\nimport * as log from '../log';\nimport { isMarkDef } from '../mark';\nimport { getFirstDefined, hash, unique } from '../util';\nimport { isSignalRef } from '../vega.schema';\nimport { toStringFieldDef } from './../channeldef';\nexport function filterTooltipWithAggregatedField(oldEncoding) {\n const { tooltip } = oldEncoding, filteredEncoding = __rest(oldEncoding, [\"tooltip\"]);\n if (!tooltip) {\n return { filteredEncoding };\n }\n let customTooltipWithAggregatedField;\n let customTooltipWithoutAggregatedField;\n if (isArray(tooltip)) {\n for (const t of tooltip) {\n if (t.aggregate) {\n if (!customTooltipWithAggregatedField) {\n customTooltipWithAggregatedField = [];\n }\n customTooltipWithAggregatedField.push(t);\n }\n else {\n if (!customTooltipWithoutAggregatedField) {\n customTooltipWithoutAggregatedField = [];\n }\n customTooltipWithoutAggregatedField.push(t);\n }\n }\n if (customTooltipWithAggregatedField) {\n filteredEncoding.tooltip = customTooltipWithAggregatedField;\n }\n }\n else {\n if (tooltip['aggregate']) {\n filteredEncoding.tooltip = tooltip;\n }\n else {\n customTooltipWithoutAggregatedField = tooltip;\n }\n }\n if (isArray(customTooltipWithoutAggregatedField) && customTooltipWithoutAggregatedField.length === 1) {\n customTooltipWithoutAggregatedField = customTooltipWithoutAggregatedField[0];\n }\n return { customTooltipWithoutAggregatedField, filteredEncoding };\n}\nexport function getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, withFieldName = true) {\n if ('tooltip' in encodingWithoutContinuousAxis) {\n return { tooltip: encodingWithoutContinuousAxis.tooltip };\n }\n const fiveSummaryTooltip = tooltipSummary.map(({ fieldPrefix, titlePrefix }) => {\n const mainTitle = withFieldName ? ` of ${getTitle(continuousAxisChannelDef)}` : '';\n return {\n field: fieldPrefix + continuousAxisChannelDef.field,\n type: continuousAxisChannelDef.type,\n title: isSignalRef(titlePrefix) ? { signal: `${titlePrefix}\"${escape(mainTitle)}\"` } : titlePrefix + mainTitle\n };\n });\n const tooltipFieldDefs = fieldDefs(encodingWithoutContinuousAxis).map(toStringFieldDef);\n return {\n tooltip: [\n ...fiveSummaryTooltip,\n // need to cast because TextFieldDef supports fewer types of bin\n ...unique(tooltipFieldDefs, hash)\n ]\n };\n}\nexport function getTitle(continuousAxisChannelDef) {\n const { title, field } = continuousAxisChannelDef;\n return getFirstDefined(title, field);\n}\nexport function makeCompositeAggregatePartFactory(compositeMarkDef, continuousAxis, continuousAxisChannelDef, sharedEncoding, compositeMarkConfig) {\n const { scale, axis } = continuousAxisChannelDef;\n return ({ partName, mark, positionPrefix, endPositionPrefix = undefined, extraEncoding = {} }) => {\n const title = getTitle(continuousAxisChannelDef);\n return partLayerMixins(compositeMarkDef, partName, compositeMarkConfig, {\n mark,\n encoding: Object.assign(Object.assign(Object.assign({ [continuousAxis]: Object.assign(Object.assign(Object.assign({ field: `${positionPrefix}_${continuousAxisChannelDef.field}`, type: continuousAxisChannelDef.type }, (title !== undefined ? { title } : {})), (scale !== undefined ? { scale } : {})), (axis !== undefined ? { axis } : {})) }, (isString(endPositionPrefix)\n ? {\n [`${continuousAxis}2`]: {\n field: `${endPositionPrefix}_${continuousAxisChannelDef.field}`\n }\n }\n : {})), sharedEncoding), extraEncoding)\n });\n };\n}\nexport function partLayerMixins(markDef, part, compositeMarkConfig, partBaseSpec) {\n const { clip, color, opacity } = markDef;\n const mark = markDef.type;\n if (markDef[part] || (markDef[part] === undefined && compositeMarkConfig[part])) {\n return [\n Object.assign(Object.assign({}, partBaseSpec), { mark: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, compositeMarkConfig[part]), (clip ? { clip } : {})), (color ? { color } : {})), (opacity ? { opacity } : {})), (isMarkDef(partBaseSpec.mark) ? partBaseSpec.mark : { type: partBaseSpec.mark })), { style: `${mark}-${part}` }), (isBoolean(markDef[part]) ? {} : markDef[part])) })\n ];\n }\n return [];\n}\nexport function compositeMarkContinuousAxis(spec, orient, compositeMark) {\n const { encoding } = spec;\n const continuousAxis = orient === 'vertical' ? 'y' : 'x';\n const continuousAxisChannelDef = encoding[continuousAxis]; // Safe to cast because if x is not continuous fielddef, the orient would not be horizontal.\n const continuousAxisChannelDef2 = encoding[`${continuousAxis}2`];\n const continuousAxisChannelDefError = encoding[`${continuousAxis}Error`];\n const continuousAxisChannelDefError2 = encoding[`${continuousAxis}Error2`];\n return {\n continuousAxisChannelDef: filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark),\n continuousAxisChannelDef2: filterAggregateFromChannelDef(continuousAxisChannelDef2, compositeMark),\n continuousAxisChannelDefError: filterAggregateFromChannelDef(continuousAxisChannelDefError, compositeMark),\n continuousAxisChannelDefError2: filterAggregateFromChannelDef(continuousAxisChannelDefError2, compositeMark),\n continuousAxis\n };\n}\nfunction filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark) {\n if (continuousAxisChannelDef === null || continuousAxisChannelDef === void 0 ? void 0 : continuousAxisChannelDef.aggregate) {\n const { aggregate } = continuousAxisChannelDef, continuousAxisWithoutAggregate = __rest(continuousAxisChannelDef, [\"aggregate\"]);\n if (aggregate !== compositeMark) {\n log.warn(log.message.errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark));\n }\n return continuousAxisWithoutAggregate;\n }\n else {\n return continuousAxisChannelDef;\n }\n}\nexport function compositeMarkOrient(spec, compositeMark) {\n const { mark, encoding } = spec;\n const { x, y } = encoding;\n if (isMarkDef(mark) && mark.orient) {\n return mark.orient;\n }\n if (isContinuousFieldOrDatumDef(x)) {\n // x is continuous\n if (isContinuousFieldOrDatumDef(y)) {\n // both x and y are continuous\n const xAggregate = isFieldDef(x) && x.aggregate;\n const yAggregate = isFieldDef(y) && y.aggregate;\n if (!xAggregate && yAggregate === compositeMark) {\n return 'vertical';\n }\n else if (!yAggregate && xAggregate === compositeMark) {\n return 'horizontal';\n }\n else if (xAggregate === compositeMark && yAggregate === compositeMark) {\n throw new Error('Both x and y cannot have aggregate');\n }\n else {\n if (isFieldOrDatumDefForTimeFormat(y) && !isFieldOrDatumDefForTimeFormat(x)) {\n // y is temporal but x is not\n return 'horizontal';\n }\n // default orientation for two continuous\n return 'vertical';\n }\n }\n return 'horizontal';\n }\n else if (isContinuousFieldOrDatumDef(y)) {\n // y is continuous but x is not\n return 'vertical';\n }\n else {\n // Neither x nor y is continuous.\n throw new Error(`Need a valid continuous axis for ${compositeMark}s`);\n }\n}\n//# sourceMappingURL=common.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isNumber, isObject } from 'vega-util';\nimport { getMarkPropOrConfig } from '../compile/common';\nimport { extractTransformsFromEncoding, normalizeEncoding } from '../encoding';\nimport * as log from '../log';\nimport { isMarkDef } from '../mark';\nimport { isEmpty, omit } from '../util';\nimport { CompositeMarkNormalizer } from './base';\nimport { compositeMarkContinuousAxis, compositeMarkOrient, filterTooltipWithAggregatedField, getCompositeMarkTooltip, getTitle, makeCompositeAggregatePartFactory, partLayerMixins } from './common';\nexport const BOXPLOT = 'boxplot';\nexport const BOXPLOT_PARTS = ['box', 'median', 'outliers', 'rule', 'ticks'];\nexport const boxPlotNormalizer = new CompositeMarkNormalizer(BOXPLOT, normalizeBoxPlot);\nexport function getBoxPlotType(extent) {\n if (isNumber(extent)) {\n return 'tukey';\n }\n // Ham: If we ever want to, we could add another extent syntax `{kIQR: number}` for the original [Q1-k*IQR, Q3+k*IQR] whisker and call this boxPlotType = `kIQR`. However, I'm not exposing this for now.\n return extent;\n}\nexport function normalizeBoxPlot(spec, { config }) {\n var _a, _b;\n // Need to initEncoding first so we can infer type\n spec = Object.assign(Object.assign({}, spec), { encoding: normalizeEncoding(spec.encoding, config) });\n const { mark, encoding: _encoding, params, projection: _p } = spec, outerSpec = __rest(spec, [\"mark\", \"encoding\", \"params\", \"projection\"]);\n const markDef = isMarkDef(mark) ? mark : { type: mark };\n // TODO(https://github.com/vega/vega-lite/issues/3702): add selection support\n if (params) {\n log.warn(log.message.selectionNotSupported('boxplot'));\n }\n const extent = (_a = markDef.extent) !== null && _a !== void 0 ? _a : config.boxplot.extent;\n const sizeValue = getMarkPropOrConfig('size', markDef, // TODO: https://github.com/vega/vega-lite/issues/6245\n config);\n const boxPlotType = getBoxPlotType(extent);\n const { bins, timeUnits, transform, continuousAxisChannelDef, continuousAxis, groupby, aggregate, encodingWithoutContinuousAxis, ticksOrient, boxOrient, customTooltipWithoutAggregatedField } = boxParams(spec, extent, config);\n const { color, size } = encodingWithoutContinuousAxis, encodingWithoutSizeColorAndContinuousAxis = __rest(encodingWithoutContinuousAxis, [\"color\", \"size\"]);\n const makeBoxPlotPart = (sharedEncoding) => {\n return makeCompositeAggregatePartFactory(markDef, continuousAxis, continuousAxisChannelDef, sharedEncoding, config.boxplot);\n };\n const makeBoxPlotExtent = makeBoxPlotPart(encodingWithoutSizeColorAndContinuousAxis);\n const makeBoxPlotBox = makeBoxPlotPart(encodingWithoutContinuousAxis);\n const makeBoxPlotMidTick = makeBoxPlotPart(Object.assign(Object.assign({}, encodingWithoutSizeColorAndContinuousAxis), (size ? { size } : {})));\n const fiveSummaryTooltipEncoding = getCompositeMarkTooltip([\n { fieldPrefix: boxPlotType === 'min-max' ? 'upper_whisker_' : 'max_', titlePrefix: 'Max' },\n { fieldPrefix: 'upper_box_', titlePrefix: 'Q3' },\n { fieldPrefix: 'mid_box_', titlePrefix: 'Median' },\n { fieldPrefix: 'lower_box_', titlePrefix: 'Q1' },\n { fieldPrefix: boxPlotType === 'min-max' ? 'lower_whisker_' : 'min_', titlePrefix: 'Min' }\n ], continuousAxisChannelDef, encodingWithoutContinuousAxis);\n // ## Whisker Layers\n const endTick = { type: 'tick', color: 'black', opacity: 1, orient: ticksOrient, invalid: null, aria: false };\n const whiskerTooltipEncoding = boxPlotType === 'min-max'\n ? fiveSummaryTooltipEncoding // for min-max, show five-summary tooltip for whisker\n : // for tukey / k-IQR, just show upper/lower-whisker\n getCompositeMarkTooltip([\n { fieldPrefix: 'upper_whisker_', titlePrefix: 'Upper Whisker' },\n { fieldPrefix: 'lower_whisker_', titlePrefix: 'Lower Whisker' }\n ], continuousAxisChannelDef, encodingWithoutContinuousAxis);\n const whiskerLayers = [\n ...makeBoxPlotExtent({\n partName: 'rule',\n mark: { type: 'rule', invalid: null, aria: false },\n positionPrefix: 'lower_whisker',\n endPositionPrefix: 'lower_box',\n extraEncoding: whiskerTooltipEncoding\n }),\n ...makeBoxPlotExtent({\n partName: 'rule',\n mark: { type: 'rule', invalid: null, aria: false },\n positionPrefix: 'upper_box',\n endPositionPrefix: 'upper_whisker',\n extraEncoding: whiskerTooltipEncoding\n }),\n ...makeBoxPlotExtent({\n partName: 'ticks',\n mark: endTick,\n positionPrefix: 'lower_whisker',\n extraEncoding: whiskerTooltipEncoding\n }),\n ...makeBoxPlotExtent({\n partName: 'ticks',\n mark: endTick,\n positionPrefix: 'upper_whisker',\n extraEncoding: whiskerTooltipEncoding\n })\n ];\n // ## Box Layers\n // TODO: support hiding certain mark parts\n const boxLayers = [\n ...(boxPlotType !== 'tukey' ? whiskerLayers : []),\n ...makeBoxPlotBox({\n partName: 'box',\n mark: Object.assign(Object.assign({ type: 'bar' }, (sizeValue ? { size: sizeValue } : {})), { orient: boxOrient, invalid: null, ariaRoleDescription: 'box' }),\n positionPrefix: 'lower_box',\n endPositionPrefix: 'upper_box',\n extraEncoding: fiveSummaryTooltipEncoding\n }),\n ...makeBoxPlotMidTick({\n partName: 'median',\n mark: Object.assign(Object.assign(Object.assign({ type: 'tick', invalid: null }, (isObject(config.boxplot.median) && config.boxplot.median.color ? { color: config.boxplot.median.color } : {})), (sizeValue ? { size: sizeValue } : {})), { orient: ticksOrient, aria: false }),\n positionPrefix: 'mid_box',\n extraEncoding: fiveSummaryTooltipEncoding\n })\n ];\n if (boxPlotType === 'min-max') {\n return Object.assign(Object.assign({}, outerSpec), { transform: ((_b = outerSpec.transform) !== null && _b !== void 0 ? _b : []).concat(transform), layer: boxLayers });\n }\n // Tukey Box Plot\n const lowerBoxExpr = `datum[\"lower_box_${continuousAxisChannelDef.field}\"]`;\n const upperBoxExpr = `datum[\"upper_box_${continuousAxisChannelDef.field}\"]`;\n const iqrExpr = `(${upperBoxExpr} - ${lowerBoxExpr})`;\n const lowerWhiskerExpr = `${lowerBoxExpr} - ${extent} * ${iqrExpr}`;\n const upperWhiskerExpr = `${upperBoxExpr} + ${extent} * ${iqrExpr}`;\n const fieldExpr = `datum[\"${continuousAxisChannelDef.field}\"]`;\n const joinaggregateTransform = {\n joinaggregate: boxParamsQuartiles(continuousAxisChannelDef.field),\n groupby\n };\n const filteredWhiskerSpec = {\n transform: [\n {\n filter: `(${lowerWhiskerExpr} <= ${fieldExpr}) && (${fieldExpr} <= ${upperWhiskerExpr})`\n },\n {\n aggregate: [\n {\n op: 'min',\n field: continuousAxisChannelDef.field,\n as: `lower_whisker_${continuousAxisChannelDef.field}`\n },\n {\n op: 'max',\n field: continuousAxisChannelDef.field,\n as: `upper_whisker_${continuousAxisChannelDef.field}`\n },\n // preserve lower_box / upper_box\n {\n op: 'min',\n field: `lower_box_${continuousAxisChannelDef.field}`,\n as: `lower_box_${continuousAxisChannelDef.field}`\n },\n {\n op: 'max',\n field: `upper_box_${continuousAxisChannelDef.field}`,\n as: `upper_box_${continuousAxisChannelDef.field}`\n },\n ...aggregate\n ],\n groupby\n }\n ],\n layer: whiskerLayers\n };\n const { tooltip } = encodingWithoutSizeColorAndContinuousAxis, encodingWithoutSizeColorContinuousAxisAndTooltip = __rest(encodingWithoutSizeColorAndContinuousAxis, [\"tooltip\"]);\n const { scale, axis } = continuousAxisChannelDef;\n const title = getTitle(continuousAxisChannelDef);\n const axisWithoutTitle = omit(axis, ['title']);\n const outlierLayersMixins = partLayerMixins(markDef, 'outliers', config.boxplot, {\n transform: [{ filter: `(${fieldExpr} < ${lowerWhiskerExpr}) || (${fieldExpr} > ${upperWhiskerExpr})` }],\n mark: 'point',\n encoding: Object.assign(Object.assign(Object.assign({ [continuousAxis]: Object.assign(Object.assign(Object.assign({ field: continuousAxisChannelDef.field, type: continuousAxisChannelDef.type }, (title !== undefined ? { title } : {})), (scale !== undefined ? { scale } : {})), (isEmpty(axisWithoutTitle) ? {} : { axis: axisWithoutTitle })) }, encodingWithoutSizeColorContinuousAxisAndTooltip), (color ? { color } : {})), (customTooltipWithoutAggregatedField ? { tooltip: customTooltipWithoutAggregatedField } : {}))\n })[0];\n let filteredLayersMixins;\n const filteredLayersMixinsTransforms = [...bins, ...timeUnits, joinaggregateTransform];\n if (outlierLayersMixins) {\n filteredLayersMixins = {\n transform: filteredLayersMixinsTransforms,\n layer: [outlierLayersMixins, filteredWhiskerSpec]\n };\n }\n else {\n filteredLayersMixins = filteredWhiskerSpec;\n filteredLayersMixins.transform.unshift(...filteredLayersMixinsTransforms);\n }\n return Object.assign(Object.assign({}, outerSpec), { layer: [\n filteredLayersMixins,\n {\n // boxplot\n transform,\n layer: boxLayers\n }\n ] });\n}\nfunction boxParamsQuartiles(continousAxisField) {\n return [\n {\n op: 'q1',\n field: continousAxisField,\n as: `lower_box_${continousAxisField}`\n },\n {\n op: 'q3',\n field: continousAxisField,\n as: `upper_box_${continousAxisField}`\n }\n ];\n}\nfunction boxParams(spec, extent, config) {\n const orient = compositeMarkOrient(spec, BOXPLOT);\n const { continuousAxisChannelDef, continuousAxis } = compositeMarkContinuousAxis(spec, orient, BOXPLOT);\n const continuousFieldName = continuousAxisChannelDef.field;\n const boxPlotType = getBoxPlotType(extent);\n const boxplotSpecificAggregate = [\n ...boxParamsQuartiles(continuousFieldName),\n {\n op: 'median',\n field: continuousFieldName,\n as: `mid_box_${continuousFieldName}`\n },\n {\n op: 'min',\n field: continuousFieldName,\n as: (boxPlotType === 'min-max' ? 'lower_whisker_' : 'min_') + continuousFieldName\n },\n {\n op: 'max',\n field: continuousFieldName,\n as: (boxPlotType === 'min-max' ? 'upper_whisker_' : 'max_') + continuousFieldName\n }\n ];\n const postAggregateCalculates = boxPlotType === 'min-max' || boxPlotType === 'tukey'\n ? []\n : [\n // This is for the original k-IQR, which we do not expose\n {\n calculate: `datum[\"upper_box_${continuousFieldName}\"] - datum[\"lower_box_${continuousFieldName}\"]`,\n as: `iqr_${continuousFieldName}`\n },\n {\n calculate: `min(datum[\"upper_box_${continuousFieldName}\"] + datum[\"iqr_${continuousFieldName}\"] * ${extent}, datum[\"max_${continuousFieldName}\"])`,\n as: `upper_whisker_${continuousFieldName}`\n },\n {\n calculate: `max(datum[\"lower_box_${continuousFieldName}\"] - datum[\"iqr_${continuousFieldName}\"] * ${extent}, datum[\"min_${continuousFieldName}\"])`,\n as: `lower_whisker_${continuousFieldName}`\n }\n ];\n const _a = spec.encoding, _b = continuousAxis, oldContinuousAxisChannelDef = _a[_b], oldEncodingWithoutContinuousAxis = __rest(_a, [typeof _b === \"symbol\" ? _b : _b + \"\"]);\n const { customTooltipWithoutAggregatedField, filteredEncoding } = filterTooltipWithAggregatedField(oldEncodingWithoutContinuousAxis);\n const { bins, timeUnits, aggregate, groupby, encoding: encodingWithoutContinuousAxis } = extractTransformsFromEncoding(filteredEncoding, config);\n const ticksOrient = orient === 'vertical' ? 'horizontal' : 'vertical';\n const boxOrient = orient;\n const transform = [\n ...bins,\n ...timeUnits,\n {\n aggregate: [...aggregate, ...boxplotSpecificAggregate],\n groupby\n },\n ...postAggregateCalculates\n ];\n return {\n bins,\n timeUnits,\n transform,\n groupby,\n aggregate,\n continuousAxisChannelDef,\n continuousAxis,\n encodingWithoutContinuousAxis,\n ticksOrient,\n boxOrient,\n customTooltipWithoutAggregatedField\n };\n}\n//# sourceMappingURL=boxplot.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isContinuousFieldOrDatumDef, isFieldOrDatumDef, title } from '../channeldef';\nimport { extractTransformsFromEncoding, normalizeEncoding } from '../encoding';\nimport * as log from '../log';\nimport { isMarkDef } from '../mark';\nimport { replaceAll, titleCase } from '../util';\nimport { CompositeMarkNormalizer } from './base';\nimport { compositeMarkContinuousAxis, compositeMarkOrient, getCompositeMarkTooltip, makeCompositeAggregatePartFactory } from './common';\nexport const ERRORBAR = 'errorbar';\nexport const ERRORBAR_PARTS = ['ticks', 'rule'];\nexport const errorBarNormalizer = new CompositeMarkNormalizer(ERRORBAR, normalizeErrorBar);\nexport function normalizeErrorBar(spec, { config }) {\n // Need to initEncoding first so we can infer type\n spec = Object.assign(Object.assign({}, spec), { encoding: normalizeEncoding(spec.encoding, config) });\n const { transform, continuousAxisChannelDef, continuousAxis, encodingWithoutContinuousAxis, ticksOrient, markDef, outerSpec, tooltipEncoding } = errorBarParams(spec, ERRORBAR, config);\n delete encodingWithoutContinuousAxis['size'];\n const makeErrorBarPart = makeCompositeAggregatePartFactory(markDef, continuousAxis, continuousAxisChannelDef, encodingWithoutContinuousAxis, config.errorbar);\n const thickness = markDef.thickness;\n const size = markDef.size;\n const tick = Object.assign(Object.assign({ type: 'tick', orient: ticksOrient, aria: false }, (thickness !== undefined ? { thickness } : {})), (size !== undefined ? { size } : {}));\n const layer = [\n ...makeErrorBarPart({\n partName: 'ticks',\n mark: tick,\n positionPrefix: 'lower',\n extraEncoding: tooltipEncoding\n }),\n ...makeErrorBarPart({\n partName: 'ticks',\n mark: tick,\n positionPrefix: 'upper',\n extraEncoding: tooltipEncoding\n }),\n ...makeErrorBarPart({\n partName: 'rule',\n mark: Object.assign({ type: 'rule', ariaRoleDescription: 'errorbar' }, (thickness !== undefined ? { size: thickness } : {})),\n positionPrefix: 'lower',\n endPositionPrefix: 'upper',\n extraEncoding: tooltipEncoding\n })\n ];\n return Object.assign(Object.assign(Object.assign({}, outerSpec), { transform }), (layer.length > 1 ? { layer } : Object.assign({}, layer[0])));\n}\nfunction errorBarOrientAndInputType(spec, compositeMark) {\n const { encoding } = spec;\n if (errorBarIsInputTypeRaw(encoding)) {\n return {\n orient: compositeMarkOrient(spec, compositeMark),\n inputType: 'raw'\n };\n }\n const isTypeAggregatedUpperLower = errorBarIsInputTypeAggregatedUpperLower(encoding);\n const isTypeAggregatedError = errorBarIsInputTypeAggregatedError(encoding);\n const x = encoding.x;\n const y = encoding.y;\n if (isTypeAggregatedUpperLower) {\n // type is aggregated-upper-lower\n if (isTypeAggregatedError) {\n throw new Error(`${compositeMark} cannot be both type aggregated-upper-lower and aggregated-error`);\n }\n const x2 = encoding.x2;\n const y2 = encoding.y2;\n if (isFieldOrDatumDef(x2) && isFieldOrDatumDef(y2)) {\n // having both x, x2 and y, y2\n throw new Error(`${compositeMark} cannot have both x2 and y2`);\n }\n else if (isFieldOrDatumDef(x2)) {\n if (isContinuousFieldOrDatumDef(x)) {\n // having x, x2 quantitative and field y, y2 are not specified\n return { orient: 'horizontal', inputType: 'aggregated-upper-lower' };\n }\n else {\n // having x, x2 that are not both quantitative\n throw new Error(`Both x and x2 have to be quantitative in ${compositeMark}`);\n }\n }\n else if (isFieldOrDatumDef(y2)) {\n // y2 is a FieldDef\n if (isContinuousFieldOrDatumDef(y)) {\n // having y, y2 quantitative and field x, x2 are not specified\n return { orient: 'vertical', inputType: 'aggregated-upper-lower' };\n }\n else {\n // having y, y2 that are not both quantitative\n throw new Error(`Both y and y2 have to be quantitative in ${compositeMark}`);\n }\n }\n throw new Error('No ranged axis');\n }\n else {\n // type is aggregated-error\n const xError = encoding.xError;\n const xError2 = encoding.xError2;\n const yError = encoding.yError;\n const yError2 = encoding.yError2;\n if (isFieldOrDatumDef(xError2) && !isFieldOrDatumDef(xError)) {\n // having xError2 without xError\n throw new Error(`${compositeMark} cannot have xError2 without xError`);\n }\n if (isFieldOrDatumDef(yError2) && !isFieldOrDatumDef(yError)) {\n // having yError2 without yError\n throw new Error(`${compositeMark} cannot have yError2 without yError`);\n }\n if (isFieldOrDatumDef(xError) && isFieldOrDatumDef(yError)) {\n // having both xError and yError\n throw new Error(`${compositeMark} cannot have both xError and yError with both are quantiative`);\n }\n else if (isFieldOrDatumDef(xError)) {\n if (isContinuousFieldOrDatumDef(x)) {\n // having x and xError that are all quantitative\n return { orient: 'horizontal', inputType: 'aggregated-error' };\n }\n else {\n // having x, xError, and xError2 that are not all quantitative\n throw new Error('All x, xError, and xError2 (if exist) have to be quantitative');\n }\n }\n else if (isFieldOrDatumDef(yError)) {\n if (isContinuousFieldOrDatumDef(y)) {\n // having y and yError that are all quantitative\n return { orient: 'vertical', inputType: 'aggregated-error' };\n }\n else {\n // having y, yError, and yError2 that are not all quantitative\n throw new Error('All y, yError, and yError2 (if exist) have to be quantitative');\n }\n }\n throw new Error('No ranged axis');\n }\n}\nfunction errorBarIsInputTypeRaw(encoding) {\n return ((isFieldOrDatumDef(encoding.x) || isFieldOrDatumDef(encoding.y)) &&\n !isFieldOrDatumDef(encoding.x2) &&\n !isFieldOrDatumDef(encoding.y2) &&\n !isFieldOrDatumDef(encoding.xError) &&\n !isFieldOrDatumDef(encoding.xError2) &&\n !isFieldOrDatumDef(encoding.yError) &&\n !isFieldOrDatumDef(encoding.yError2));\n}\nfunction errorBarIsInputTypeAggregatedUpperLower(encoding) {\n return isFieldOrDatumDef(encoding.x2) || isFieldOrDatumDef(encoding.y2);\n}\nfunction errorBarIsInputTypeAggregatedError(encoding) {\n return (isFieldOrDatumDef(encoding.xError) ||\n isFieldOrDatumDef(encoding.xError2) ||\n isFieldOrDatumDef(encoding.yError) ||\n isFieldOrDatumDef(encoding.yError2));\n}\nexport function errorBarParams(spec, compositeMark, config) {\n var _a;\n // TODO: use selection\n const { mark, encoding, params, projection: _p } = spec, outerSpec = __rest(spec, [\"mark\", \"encoding\", \"params\", \"projection\"]);\n const markDef = isMarkDef(mark) ? mark : { type: mark };\n // TODO(https://github.com/vega/vega-lite/issues/3702): add selection support\n if (params) {\n log.warn(log.message.selectionNotSupported(compositeMark));\n }\n const { orient, inputType } = errorBarOrientAndInputType(spec, compositeMark);\n const { continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, continuousAxis } = compositeMarkContinuousAxis(spec, orient, compositeMark);\n const { errorBarSpecificAggregate, postAggregateCalculates, tooltipSummary, tooltipTitleWithFieldName } = errorBarAggregationAndCalculation(markDef, continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, inputType, compositeMark, config);\n const _b = encoding, _c = continuousAxis, oldContinuousAxisChannelDef = _b[_c], _d = continuousAxis === 'x' ? 'x2' : 'y2', oldContinuousAxisChannelDef2 = _b[_d], _e = continuousAxis === 'x' ? 'xError' : 'yError', oldContinuousAxisChannelDefError = _b[_e], _f = continuousAxis === 'x' ? 'xError2' : 'yError2', oldContinuousAxisChannelDefError2 = _b[_f], oldEncodingWithoutContinuousAxis = __rest(_b, [typeof _c === \"symbol\" ? _c : _c + \"\", typeof _d === \"symbol\" ? _d : _d + \"\", typeof _e === \"symbol\" ? _e : _e + \"\", typeof _f === \"symbol\" ? _f : _f + \"\"]);\n const { bins, timeUnits, aggregate: oldAggregate, groupby: oldGroupBy, encoding: encodingWithoutContinuousAxis } = extractTransformsFromEncoding(oldEncodingWithoutContinuousAxis, config);\n const aggregate = [...oldAggregate, ...errorBarSpecificAggregate];\n const groupby = inputType !== 'raw' ? [] : oldGroupBy;\n const tooltipEncoding = getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, tooltipTitleWithFieldName);\n return {\n transform: [\n ...((_a = outerSpec.transform) !== null && _a !== void 0 ? _a : []),\n ...bins,\n ...timeUnits,\n ...(aggregate.length === 0 ? [] : [{ aggregate, groupby }]),\n ...postAggregateCalculates\n ],\n groupby,\n continuousAxisChannelDef,\n continuousAxis,\n encodingWithoutContinuousAxis,\n ticksOrient: orient === 'vertical' ? 'horizontal' : 'vertical',\n markDef,\n outerSpec,\n tooltipEncoding\n };\n}\nfunction errorBarAggregationAndCalculation(markDef, continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, inputType, compositeMark, config) {\n let errorBarSpecificAggregate = [];\n let postAggregateCalculates = [];\n const continuousFieldName = continuousAxisChannelDef.field;\n let tooltipSummary;\n let tooltipTitleWithFieldName = false;\n if (inputType === 'raw') {\n const center = markDef.center\n ? markDef.center\n : markDef.extent\n ? markDef.extent === 'iqr'\n ? 'median'\n : 'mean'\n : config.errorbar.center;\n const extent = markDef.extent ? markDef.extent : center === 'mean' ? 'stderr' : 'iqr';\n if ((center === 'median') !== (extent === 'iqr')) {\n log.warn(log.message.errorBarCenterIsUsedWithWrongExtent(center, extent, compositeMark));\n }\n if (extent === 'stderr' || extent === 'stdev') {\n errorBarSpecificAggregate = [\n { op: extent, field: continuousFieldName, as: `extent_${continuousFieldName}` },\n { op: center, field: continuousFieldName, as: `center_${continuousFieldName}` }\n ];\n postAggregateCalculates = [\n {\n calculate: `datum[\"center_${continuousFieldName}\"] + datum[\"extent_${continuousFieldName}\"]`,\n as: `upper_${continuousFieldName}`\n },\n {\n calculate: `datum[\"center_${continuousFieldName}\"] - datum[\"extent_${continuousFieldName}\"]`,\n as: `lower_${continuousFieldName}`\n }\n ];\n tooltipSummary = [\n { fieldPrefix: 'center_', titlePrefix: titleCase(center) },\n { fieldPrefix: 'upper_', titlePrefix: getTitlePrefix(center, extent, '+') },\n { fieldPrefix: 'lower_', titlePrefix: getTitlePrefix(center, extent, '-') }\n ];\n tooltipTitleWithFieldName = true;\n }\n else {\n let centerOp;\n let lowerExtentOp;\n let upperExtentOp;\n if (extent === 'ci') {\n centerOp = 'mean';\n lowerExtentOp = 'ci0';\n upperExtentOp = 'ci1';\n }\n else {\n centerOp = 'median';\n lowerExtentOp = 'q1';\n upperExtentOp = 'q3';\n }\n errorBarSpecificAggregate = [\n { op: lowerExtentOp, field: continuousFieldName, as: `lower_${continuousFieldName}` },\n { op: upperExtentOp, field: continuousFieldName, as: `upper_${continuousFieldName}` },\n { op: centerOp, field: continuousFieldName, as: `center_${continuousFieldName}` }\n ];\n tooltipSummary = [\n {\n fieldPrefix: 'upper_',\n titlePrefix: title({ field: continuousFieldName, aggregate: upperExtentOp, type: 'quantitative' }, config, {\n allowDisabling: false\n })\n },\n {\n fieldPrefix: 'lower_',\n titlePrefix: title({ field: continuousFieldName, aggregate: lowerExtentOp, type: 'quantitative' }, config, {\n allowDisabling: false\n })\n },\n {\n fieldPrefix: 'center_',\n titlePrefix: title({ field: continuousFieldName, aggregate: centerOp, type: 'quantitative' }, config, {\n allowDisabling: false\n })\n }\n ];\n }\n }\n else {\n if (markDef.center || markDef.extent) {\n log.warn(log.message.errorBarCenterAndExtentAreNotNeeded(markDef.center, markDef.extent));\n }\n if (inputType === 'aggregated-upper-lower') {\n tooltipSummary = [];\n postAggregateCalculates = [\n { calculate: `datum[\"${continuousAxisChannelDef2.field}\"]`, as: `upper_${continuousFieldName}` },\n { calculate: `datum[\"${continuousFieldName}\"]`, as: `lower_${continuousFieldName}` }\n ];\n }\n else if (inputType === 'aggregated-error') {\n tooltipSummary = [{ fieldPrefix: '', titlePrefix: continuousFieldName }];\n postAggregateCalculates = [\n {\n calculate: `datum[\"${continuousFieldName}\"] + datum[\"${continuousAxisChannelDefError.field}\"]`,\n as: `upper_${continuousFieldName}`\n }\n ];\n if (continuousAxisChannelDefError2) {\n postAggregateCalculates.push({\n calculate: `datum[\"${continuousFieldName}\"] + datum[\"${continuousAxisChannelDefError2.field}\"]`,\n as: `lower_${continuousFieldName}`\n });\n }\n else {\n postAggregateCalculates.push({\n calculate: `datum[\"${continuousFieldName}\"] - datum[\"${continuousAxisChannelDefError.field}\"]`,\n as: `lower_${continuousFieldName}`\n });\n }\n }\n for (const postAggregateCalculate of postAggregateCalculates) {\n tooltipSummary.push({\n fieldPrefix: postAggregateCalculate.as.substring(0, 6),\n titlePrefix: replaceAll(replaceAll(postAggregateCalculate.calculate, 'datum[\"', ''), '\"]', '')\n });\n }\n }\n return { postAggregateCalculates, errorBarSpecificAggregate, tooltipSummary, tooltipTitleWithFieldName };\n}\nfunction getTitlePrefix(center, extent, operation) {\n return `${titleCase(center)} ${operation} ${extent}`;\n}\n//# sourceMappingURL=errorbar.js.map","import { normalizeEncoding } from '../encoding';\nimport * as log from '../log';\nimport { CompositeMarkNormalizer } from './base';\nimport { makeCompositeAggregatePartFactory } from './common';\nimport { errorBarParams } from './errorbar';\nexport const ERRORBAND = 'errorband';\nexport const ERRORBAND_PARTS = ['band', 'borders'];\nexport const errorBandNormalizer = new CompositeMarkNormalizer(ERRORBAND, normalizeErrorBand);\nexport function normalizeErrorBand(spec, { config }) {\n // Need to initEncoding first so we can infer type\n spec = Object.assign(Object.assign({}, spec), { encoding: normalizeEncoding(spec.encoding, config) });\n const { transform, continuousAxisChannelDef, continuousAxis, encodingWithoutContinuousAxis, markDef, outerSpec, tooltipEncoding } = errorBarParams(spec, ERRORBAND, config);\n const errorBandDef = markDef;\n const makeErrorBandPart = makeCompositeAggregatePartFactory(errorBandDef, continuousAxis, continuousAxisChannelDef, encodingWithoutContinuousAxis, config.errorband);\n const is2D = spec.encoding.x !== undefined && spec.encoding.y !== undefined;\n let bandMark = { type: is2D ? 'area' : 'rect' };\n let bordersMark = { type: is2D ? 'line' : 'rule' };\n const interpolate = Object.assign(Object.assign({}, (errorBandDef.interpolate ? { interpolate: errorBandDef.interpolate } : {})), (errorBandDef.tension && errorBandDef.interpolate ? { tension: errorBandDef.tension } : {}));\n if (is2D) {\n bandMark = Object.assign(Object.assign(Object.assign({}, bandMark), interpolate), { ariaRoleDescription: 'errorband' });\n bordersMark = Object.assign(Object.assign(Object.assign({}, bordersMark), interpolate), { aria: false });\n }\n else if (errorBandDef.interpolate) {\n log.warn(log.message.errorBand1DNotSupport('interpolate'));\n }\n else if (errorBandDef.tension) {\n log.warn(log.message.errorBand1DNotSupport('tension'));\n }\n return Object.assign(Object.assign({}, outerSpec), { transform, layer: [\n ...makeErrorBandPart({\n partName: 'band',\n mark: bandMark,\n positionPrefix: 'lower',\n endPositionPrefix: 'upper',\n extraEncoding: tooltipEncoding\n }),\n ...makeErrorBandPart({\n partName: 'borders',\n mark: bordersMark,\n positionPrefix: 'lower',\n extraEncoding: tooltipEncoding\n }),\n ...makeErrorBandPart({\n partName: 'borders',\n mark: bordersMark,\n positionPrefix: 'upper',\n extraEncoding: tooltipEncoding\n })\n ] });\n}\n//# sourceMappingURL=errorband.js.map","import { keys } from '../util';\nimport { CompositeMarkNormalizer } from './base';\nimport { BOXPLOT, BOXPLOT_PARTS, normalizeBoxPlot } from './boxplot';\nimport { ERRORBAND, ERRORBAND_PARTS, normalizeErrorBand } from './errorband';\nimport { ERRORBAR, ERRORBAR_PARTS, normalizeErrorBar } from './errorbar';\n/**\n * Registry index for all composite mark's normalizer\n */\nconst compositeMarkRegistry = {};\nexport function add(mark, run, parts) {\n const normalizer = new CompositeMarkNormalizer(mark, run);\n compositeMarkRegistry[mark] = { normalizer, parts };\n}\nexport function remove(mark) {\n delete compositeMarkRegistry[mark];\n}\nexport function getAllCompositeMarks() {\n return keys(compositeMarkRegistry);\n}\nadd(BOXPLOT, normalizeBoxPlot, BOXPLOT_PARTS);\nadd(ERRORBAR, normalizeErrorBar, ERRORBAR_PARTS);\nadd(ERRORBAND, normalizeErrorBand, ERRORBAND_PARTS);\n//# sourceMappingURL=index.js.map","export const VL_ONLY_LEGEND_CONFIG = [\n 'gradientHorizontalMaxLength',\n 'gradientHorizontalMinLength',\n 'gradientVerticalMaxLength',\n 'gradientVerticalMinLength',\n 'unselectedOpacity'\n];\n//# sourceMappingURL=guide.js.map","import { keys } from './util';\nexport const HEADER_TITLE_PROPERTIES_MAP = {\n titleAlign: 'align',\n titleAnchor: 'anchor',\n titleAngle: 'angle',\n titleBaseline: 'baseline',\n titleColor: 'color',\n titleFont: 'font',\n titleFontSize: 'fontSize',\n titleFontStyle: 'fontStyle',\n titleFontWeight: 'fontWeight',\n titleLimit: 'limit',\n titleLineHeight: 'lineHeight',\n titleOrient: 'orient',\n titlePadding: 'offset'\n};\nexport const HEADER_LABEL_PROPERTIES_MAP = {\n labelAlign: 'align',\n labelAnchor: 'anchor',\n labelAngle: 'angle',\n labelBaseline: 'baseline',\n labelColor: 'color',\n labelFont: 'font',\n labelFontSize: 'fontSize',\n labelFontStyle: 'fontStyle',\n labelFontWeight: 'fontWeight',\n labelLimit: 'limit',\n labelLineHeight: 'lineHeight',\n labelOrient: 'orient',\n labelPadding: 'offset'\n};\nexport const HEADER_TITLE_PROPERTIES = keys(HEADER_TITLE_PROPERTIES_MAP);\nexport const HEADER_LABEL_PROPERTIES = keys(HEADER_LABEL_PROPERTIES_MAP);\nconst HEADER_CONFIGS_INDEX = {\n header: 1,\n headerRow: 1,\n headerColumn: 1,\n headerFacet: 1\n};\nexport const HEADER_CONFIGS = keys(HEADER_CONFIGS_INDEX);\n//# sourceMappingURL=header.js.map","import { keys } from './util';\nexport const LEGEND_SCALE_CHANNELS = [\n 'size',\n 'shape',\n 'fill',\n 'stroke',\n 'strokeDash',\n 'strokeWidth',\n 'opacity'\n];\nexport const defaultLegendConfig = {\n gradientHorizontalMaxLength: 200,\n gradientHorizontalMinLength: 100,\n gradientVerticalMaxLength: 200,\n gradientVerticalMinLength: 64,\n unselectedOpacity: 0.35\n};\nexport const COMMON_LEGEND_PROPERTY_INDEX = {\n aria: 1,\n clipHeight: 1,\n columnPadding: 1,\n columns: 1,\n cornerRadius: 1,\n description: 1,\n direction: 1,\n fillColor: 1,\n format: 1,\n formatType: 1,\n gradientLength: 1,\n gradientOpacity: 1,\n gradientStrokeColor: 1,\n gradientStrokeWidth: 1,\n gradientThickness: 1,\n gridAlign: 1,\n labelAlign: 1,\n labelBaseline: 1,\n labelColor: 1,\n labelFont: 1,\n labelFontSize: 1,\n labelFontStyle: 1,\n labelFontWeight: 1,\n labelLimit: 1,\n labelOffset: 1,\n labelOpacity: 1,\n labelOverlap: 1,\n labelPadding: 1,\n labelSeparation: 1,\n legendX: 1,\n legendY: 1,\n offset: 1,\n orient: 1,\n padding: 1,\n rowPadding: 1,\n strokeColor: 1,\n symbolDash: 1,\n symbolDashOffset: 1,\n symbolFillColor: 1,\n symbolLimit: 1,\n symbolOffset: 1,\n symbolOpacity: 1,\n symbolSize: 1,\n symbolStrokeColor: 1,\n symbolStrokeWidth: 1,\n symbolType: 1,\n tickCount: 1,\n tickMinStep: 1,\n title: 1,\n titleAlign: 1,\n titleAnchor: 1,\n titleBaseline: 1,\n titleColor: 1,\n titleFont: 1,\n titleFontSize: 1,\n titleFontStyle: 1,\n titleFontWeight: 1,\n titleLimit: 1,\n titleLineHeight: 1,\n titleOpacity: 1,\n titleOrient: 1,\n titlePadding: 1,\n type: 1,\n values: 1,\n zindex: 1\n};\nexport const LEGEND_PROPERTIES = keys(COMMON_LEGEND_PROPERTY_INDEX);\n//# sourceMappingURL=legend.js.map","import { isObject } from 'vega-util';\nexport const SELECTION_ID = '_vgsid_';\nexport const defaultConfig = {\n point: {\n on: 'click',\n fields: [SELECTION_ID],\n toggle: 'event.shiftKey',\n resolve: 'global',\n clear: 'dblclick'\n },\n interval: {\n on: '[mousedown, window:mouseup] > window:mousemove!',\n encodings: ['x', 'y'],\n translate: '[mousedown, window:mouseup] > window:mousemove!',\n zoom: 'wheel!',\n mark: { fill: '#333', fillOpacity: 0.125, stroke: 'white' },\n resolve: 'global',\n clear: 'dblclick'\n }\n};\nexport function isLegendBinding(bind) {\n return !!bind && (bind === 'legend' || !!bind.legend);\n}\nexport function isLegendStreamBinding(bind) {\n return isLegendBinding(bind) && isObject(bind);\n}\nexport function isSelectionParameter(param) {\n return !!param['select'];\n}\n//# sourceMappingURL=selection.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isSelectionParameter } from './selection';\nexport function assembleParameterSignals(params) {\n const signals = [];\n for (const param of params || []) {\n // Selection parameters are handled separately via assembleSelectionTopLevelSignals\n // and assembleSignals methods registered on the Model.\n if (isSelectionParameter(param))\n continue;\n const { expr, bind } = param, rest = __rest(param, [\"expr\", \"bind\"]);\n if (bind && expr) {\n // Vega's InitSignal -- apply expr to \"init\"\n const signal = Object.assign(Object.assign({}, rest), { bind, init: expr });\n signals.push(signal);\n }\n else {\n const signal = Object.assign(Object.assign(Object.assign({}, rest), (expr ? { update: expr } : {})), (bind ? { bind } : {}));\n signals.push(signal);\n }\n }\n return signals;\n}\n//# sourceMappingURL=parameter.js.map","export function isAnyConcatSpec(spec) {\n return isVConcatSpec(spec) || isHConcatSpec(spec) || isConcatSpec(spec);\n}\nexport function isConcatSpec(spec) {\n return 'concat' in spec;\n}\nexport function isVConcatSpec(spec) {\n return 'vconcat' in spec;\n}\nexport function isHConcatSpec(spec) {\n return 'hconcat' in spec;\n}\n//# sourceMappingURL=concat.js.map","import { isNumber, isObject } from 'vega-util';\nimport { keys } from '../util';\nimport { isConcatSpec, isVConcatSpec } from './concat';\nimport { isFacetMapping, isFacetSpec } from './facet';\nexport function isStep(size) {\n return isObject(size) && size['step'] !== undefined;\n}\nexport function isFrameMixins(o) {\n return o['view'] || o['width'] || o['height'];\n}\nexport const DEFAULT_SPACING = 20;\nconst COMPOSITION_LAYOUT_INDEX = {\n align: 1,\n bounds: 1,\n center: 1,\n columns: 1,\n spacing: 1\n};\nconst COMPOSITION_LAYOUT_PROPERTIES = keys(COMPOSITION_LAYOUT_INDEX);\nexport function extractCompositionLayout(spec, specType, config) {\n var _a, _b;\n const compositionConfig = config[specType];\n const layout = {};\n // Apply config first\n const { spacing: spacingConfig, columns } = compositionConfig;\n if (spacingConfig !== undefined) {\n layout.spacing = spacingConfig;\n }\n if (columns !== undefined) {\n if ((isFacetSpec(spec) && !isFacetMapping(spec.facet)) || isConcatSpec(spec)) {\n layout.columns = columns;\n }\n }\n if (isVConcatSpec(spec)) {\n layout.columns = 1;\n }\n // Then copy properties from the spec\n for (const prop of COMPOSITION_LAYOUT_PROPERTIES) {\n if (spec[prop] !== undefined) {\n if (prop === 'spacing') {\n const spacing = spec[prop];\n layout[prop] = isNumber(spacing)\n ? spacing\n : {\n row: (_a = spacing.row) !== null && _a !== void 0 ? _a : spacingConfig,\n column: (_b = spacing.column) !== null && _b !== void 0 ? _b : spacingConfig\n };\n }\n else {\n layout[prop] = spec[prop];\n }\n }\n }\n return layout;\n}\n//# sourceMappingURL=base.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { writeConfig } from 'vega';\nimport { isObject, mergeConfig } from 'vega-util';\nimport { AXIS_CONFIGS, isConditionalAxisValue } from './axis';\nimport { signalOrValueRefWithCondition, signalRefOrValue } from './compile/common';\nimport { getAllCompositeMarks } from './compositemark';\nimport { replaceExprRef } from './expr';\nimport { VL_ONLY_LEGEND_CONFIG } from './guide';\nimport { HEADER_CONFIGS } from './header';\nimport { defaultLegendConfig } from './legend';\nimport * as mark from './mark';\nimport { MARK_CONFIGS, PRIMITIVE_MARKS, VL_ONLY_MARK_CONFIG_PROPERTIES, VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX } from './mark';\nimport { assembleParameterSignals } from './parameter';\nimport { defaultScaleConfig } from './scale';\nimport { defaultConfig as defaultSelectionConfig } from './selection';\nimport { DEFAULT_SPACING, isStep } from './spec/base';\nimport { extractTitleConfig } from './title';\nimport { duplicate, getFirstDefined, isEmpty, keys, omit } from './util';\nexport function getViewConfigContinuousSize(viewConfig, channel) {\n var _a;\n return (_a = viewConfig[channel]) !== null && _a !== void 0 ? _a : viewConfig[channel === 'width' ? 'continuousWidth' : 'continuousHeight']; // get width/height for backwards compatibility\n}\nexport function getViewConfigDiscreteStep(viewConfig, channel) {\n const size = getViewConfigDiscreteSize(viewConfig, channel);\n return isStep(size) ? size.step : DEFAULT_STEP;\n}\nexport function getViewConfigDiscreteSize(viewConfig, channel) {\n var _a;\n const size = (_a = viewConfig[channel]) !== null && _a !== void 0 ? _a : viewConfig[channel === 'width' ? 'discreteWidth' : 'discreteHeight']; // get width/height for backwards compatibility\n return getFirstDefined(size, { step: viewConfig.step });\n}\nexport const DEFAULT_STEP = 20;\nexport const defaultViewConfig = {\n continuousWidth: 200,\n continuousHeight: 200,\n step: DEFAULT_STEP\n};\nexport function isVgScheme(rangeScheme) {\n return rangeScheme && !!rangeScheme['scheme'];\n}\nexport const defaultConfig = {\n background: 'white',\n padding: 5,\n timeFormat: '%b %d, %Y',\n countTitle: 'Count of Records',\n view: defaultViewConfig,\n mark: mark.defaultMarkConfig,\n arc: {},\n area: {},\n bar: mark.defaultBarConfig,\n circle: {},\n geoshape: {},\n image: {},\n line: {},\n point: {},\n rect: mark.defaultRectConfig,\n rule: { color: 'black' },\n square: {},\n text: { color: 'black' },\n tick: mark.defaultTickConfig,\n trail: {},\n boxplot: {\n size: 14,\n extent: 1.5,\n box: {},\n median: { color: 'white' },\n outliers: {},\n rule: {},\n ticks: null\n },\n errorbar: {\n center: 'mean',\n rule: true,\n ticks: false\n },\n errorband: {\n band: {\n opacity: 0.3\n },\n borders: false\n },\n scale: defaultScaleConfig,\n projection: {},\n legend: defaultLegendConfig,\n header: { titlePadding: 10, labelPadding: 10 },\n headerColumn: {},\n headerRow: {},\n headerFacet: {},\n selection: defaultSelectionConfig,\n style: {},\n title: {},\n facet: { spacing: DEFAULT_SPACING },\n concat: { spacing: DEFAULT_SPACING }\n};\n// Tableau10 color palette, copied from `vegaScale.scheme('tableau10')`\nconst tab10 = [\n '#4c78a8',\n '#f58518',\n '#e45756',\n '#72b7b2',\n '#54a24b',\n '#eeca3b',\n '#b279a2',\n '#ff9da6',\n '#9d755d',\n '#bab0ac'\n];\nexport const DEFAULT_FONT_SIZE = {\n text: 11,\n guideLabel: 10,\n guideTitle: 11,\n groupTitle: 13,\n groupSubtitle: 12\n};\nexport const DEFAULT_COLOR = {\n blue: tab10[0],\n orange: tab10[1],\n red: tab10[2],\n teal: tab10[3],\n green: tab10[4],\n yellow: tab10[5],\n purple: tab10[6],\n pink: tab10[7],\n brown: tab10[8],\n gray0: '#000',\n gray1: '#111',\n gray2: '#222',\n gray3: '#333',\n gray4: '#444',\n gray5: '#555',\n gray6: '#666',\n gray7: '#777',\n gray8: '#888',\n gray9: '#999',\n gray10: '#aaa',\n gray11: '#bbb',\n gray12: '#ccc',\n gray13: '#ddd',\n gray14: '#eee',\n gray15: '#fff'\n};\nexport function colorSignalConfig(color = {}) {\n return {\n signals: [\n {\n name: 'color',\n value: isObject(color) ? Object.assign(Object.assign({}, DEFAULT_COLOR), color) : DEFAULT_COLOR\n }\n ],\n mark: { color: { signal: 'color.blue' } },\n rule: { color: { signal: 'color.gray0' } },\n text: {\n color: { signal: 'color.gray0' }\n },\n style: {\n 'guide-label': {\n fill: { signal: 'color.gray0' }\n },\n 'guide-title': {\n fill: { signal: 'color.gray0' }\n },\n 'group-title': {\n fill: { signal: 'color.gray0' }\n },\n 'group-subtitle': {\n fill: { signal: 'color.gray0' }\n },\n cell: {\n stroke: { signal: 'color.gray8' }\n }\n },\n axis: {\n domainColor: { signal: 'color.gray13' },\n gridColor: { signal: 'color.gray8' },\n tickColor: { signal: 'color.gray13' }\n },\n range: {\n category: [\n { signal: 'color.blue' },\n { signal: 'color.orange' },\n { signal: 'color.red' },\n { signal: 'color.teal' },\n { signal: 'color.green' },\n { signal: 'color.yellow' },\n { signal: 'color.purple' },\n { signal: 'color.pink' },\n { signal: 'color.brown' },\n { signal: 'color.grey8' }\n ]\n }\n };\n}\nexport function fontSizeSignalConfig(fontSize) {\n return {\n signals: [\n {\n name: 'fontSize',\n value: isObject(fontSize) ? Object.assign(Object.assign({}, DEFAULT_FONT_SIZE), fontSize) : DEFAULT_FONT_SIZE\n }\n ],\n text: {\n fontSize: { signal: 'fontSize.text' }\n },\n style: {\n 'guide-label': {\n fontSize: { signal: 'fontSize.guideLabel' }\n },\n 'guide-title': {\n fontSize: { signal: 'fontSize.guideTitle' }\n },\n 'group-title': {\n fontSize: { signal: 'fontSize.groupTitle' }\n },\n 'group-subtitle': {\n fontSize: { signal: 'fontSize.groupSubtitle' }\n }\n }\n };\n}\nexport function fontConfig(font) {\n return {\n text: { font },\n style: {\n 'guide-label': { font },\n 'guide-title': { font },\n 'group-title': { font },\n 'group-subtitle': { font }\n }\n };\n}\nfunction getAxisConfigInternal(axisConfig) {\n const props = keys(axisConfig || {});\n const axisConfigInternal = {};\n for (const prop of props) {\n const val = axisConfig[prop];\n axisConfigInternal[prop] = isConditionalAxisValue(val)\n ? signalOrValueRefWithCondition(val)\n : signalRefOrValue(val);\n }\n return axisConfigInternal;\n}\nfunction getStyleConfigInternal(styleConfig) {\n const props = keys(styleConfig);\n const styleConfigInternal = {};\n for (const prop of props) {\n // We need to cast to cheat a bit here since styleConfig can be either mark config or axis config\n styleConfigInternal[prop] = getAxisConfigInternal(styleConfig[prop]);\n }\n return styleConfigInternal;\n}\nconst configPropsWithExpr = [\n ...MARK_CONFIGS,\n ...AXIS_CONFIGS,\n ...HEADER_CONFIGS,\n 'background',\n 'padding',\n 'legend',\n 'lineBreak',\n 'scale',\n 'style',\n 'title',\n 'view'\n];\n/**\n * Merge specified config with default config and config for the `color` flag,\n * then replace all expressions with signals\n */\nexport function initConfig(specifiedConfig = {}) {\n const { color, font, fontSize, selection } = specifiedConfig, restConfig = __rest(specifiedConfig, [\"color\", \"font\", \"fontSize\", \"selection\"]);\n const mergedConfig = mergeConfig({}, duplicate(defaultConfig), font ? fontConfig(font) : {}, color ? colorSignalConfig(color) : {}, fontSize ? fontSizeSignalConfig(fontSize) : {}, restConfig || {});\n // mergeConfig doesn't recurse and overrides object values.\n if (selection) {\n writeConfig(mergedConfig, 'selection', selection, true);\n }\n const outputConfig = omit(mergedConfig, configPropsWithExpr);\n for (const prop of ['background', 'lineBreak', 'padding']) {\n if (mergedConfig[prop]) {\n outputConfig[prop] = signalRefOrValue(mergedConfig[prop]);\n }\n }\n for (const markConfigType of mark.MARK_CONFIGS) {\n if (mergedConfig[markConfigType]) {\n // FIXME: outputConfig[markConfigType] expects that types are replaced recursively but replaceExprRef only replaces one level deep\n outputConfig[markConfigType] = replaceExprRef(mergedConfig[markConfigType]);\n }\n }\n for (const axisConfigType of AXIS_CONFIGS) {\n if (mergedConfig[axisConfigType]) {\n outputConfig[axisConfigType] = getAxisConfigInternal(mergedConfig[axisConfigType]);\n }\n }\n for (const headerConfigType of HEADER_CONFIGS) {\n if (mergedConfig[headerConfigType]) {\n outputConfig[headerConfigType] = replaceExprRef(mergedConfig[headerConfigType]);\n }\n }\n if (mergedConfig.legend) {\n outputConfig.legend = replaceExprRef(mergedConfig.legend);\n }\n if (mergedConfig.scale) {\n outputConfig.scale = replaceExprRef(mergedConfig.scale);\n }\n if (mergedConfig.style) {\n outputConfig.style = getStyleConfigInternal(mergedConfig.style);\n }\n if (mergedConfig.title) {\n outputConfig.title = replaceExprRef(mergedConfig.title);\n }\n if (mergedConfig.view) {\n outputConfig.view = replaceExprRef(mergedConfig.view);\n }\n return outputConfig;\n}\nconst MARK_STYLES = ['view', ...PRIMITIVE_MARKS];\nconst VL_ONLY_CONFIG_PROPERTIES = [\n 'color',\n 'fontSize',\n 'background',\n 'padding',\n 'facet',\n 'concat',\n 'numberFormat',\n 'timeFormat',\n 'countTitle',\n 'header',\n 'axisQuantitative',\n 'axisTemporal',\n 'axisDiscrete',\n 'axisPoint',\n 'axisXBand',\n 'axisXPoint',\n 'axisXDiscrete',\n 'axisXQuantitative',\n 'axisXTemporal',\n 'axisYBand',\n 'axisYPoint',\n 'axisYDiscrete',\n 'axisYQuantitative',\n 'axisYTemporal',\n 'scale',\n 'selection',\n 'overlay' // FIXME: Redesign and unhide this\n];\nconst VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = Object.assign({ view: ['continuousWidth', 'continuousHeight', 'discreteWidth', 'discreteHeight', 'step'] }, VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX);\nexport function stripAndRedirectConfig(config) {\n config = duplicate(config);\n for (const prop of VL_ONLY_CONFIG_PROPERTIES) {\n delete config[prop];\n }\n if (config.axis) {\n // delete condition axis config\n for (const prop in config.axis) {\n if (isConditionalAxisValue(config.axis[prop])) {\n delete config.axis[prop];\n }\n }\n }\n if (config.legend) {\n for (const prop of VL_ONLY_LEGEND_CONFIG) {\n delete config.legend[prop];\n }\n }\n // Remove Vega-Lite only generic mark config\n if (config.mark) {\n for (const prop of VL_ONLY_MARK_CONFIG_PROPERTIES) {\n delete config.mark[prop];\n }\n if (config.mark.tooltip && isObject(config.mark.tooltip)) {\n delete config.mark.tooltip;\n }\n }\n if (config.params) {\n config.signals = (config.signals || []).concat(assembleParameterSignals(config.params));\n delete config.params;\n }\n for (const markType of MARK_STYLES) {\n // Remove Vega-Lite-only mark config\n for (const prop of VL_ONLY_MARK_CONFIG_PROPERTIES) {\n delete config[markType][prop];\n }\n // Remove Vega-Lite only mark-specific config\n const vlOnlyMarkSpecificConfigs = VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX[markType];\n if (vlOnlyMarkSpecificConfigs) {\n for (const prop of vlOnlyMarkSpecificConfigs) {\n delete config[markType][prop];\n }\n }\n // Redirect mark config to config.style so that mark config only affect its own mark type\n // without affecting other marks that share the same underlying Vega marks.\n // For example, config.rect should not affect bar marks.\n redirectConfigToStyleConfig(config, markType);\n }\n for (const m of getAllCompositeMarks()) {\n // Clean up the composite mark config as we don't need them in the output specs anymore\n delete config[m];\n }\n redirectTitleConfig(config);\n // Remove empty config objects.\n for (const prop in config) {\n if (isObject(config[prop]) && isEmpty(config[prop])) {\n delete config[prop];\n }\n }\n return isEmpty(config) ? undefined : config;\n}\n/**\n *\n * Redirect config.title -- so that title config do not affect header labels,\n * which also uses `title` directive to implement.\n *\n * For subtitle configs in config.title, keep them in config.title as header titles never have subtitles.\n */\nfunction redirectTitleConfig(config) {\n const { titleMarkConfig, subtitleMarkConfig, subtitle } = extractTitleConfig(config.title);\n // set config.style if title/subtitleMarkConfig is not an empty object\n if (!isEmpty(titleMarkConfig)) {\n config.style['group-title'] = Object.assign(Object.assign({}, config.style['group-title']), titleMarkConfig // config.title has higher precedence than config.style.group-title in Vega\n );\n }\n if (!isEmpty(subtitleMarkConfig)) {\n config.style['group-subtitle'] = Object.assign(Object.assign({}, config.style['group-subtitle']), subtitleMarkConfig);\n }\n // subtitle part can stay in config.title since header titles do not use subtitle\n if (!isEmpty(subtitle)) {\n config.title = subtitle;\n }\n else {\n delete config.title;\n }\n}\nfunction redirectConfigToStyleConfig(config, prop, // string = composite mark\ntoProp, compositeMarkPart) {\n const propConfig = compositeMarkPart ? config[prop][compositeMarkPart] : config[prop];\n if (prop === 'view') {\n toProp = 'cell'; // View's default style is \"cell\"\n }\n const style = Object.assign(Object.assign({}, propConfig), config.style[toProp !== null && toProp !== void 0 ? toProp : prop]);\n // set config.style if it is not an empty object\n if (!isEmpty(style)) {\n config.style[toProp !== null && toProp !== void 0 ? toProp : prop] = style;\n }\n if (!compositeMarkPart) {\n // For composite mark, so don't delete the whole config yet as we have to do multiple redirections.\n delete config[prop];\n }\n}\n//# sourceMappingURL=config.js.map","export function isLayerSpec(spec) {\n return 'layer' in spec;\n}\n//# sourceMappingURL=layer.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport * as log from '../log';\nimport { isConcatSpec, isHConcatSpec, isVConcatSpec } from './concat';\nimport { isFacetSpec } from './facet';\nimport { isLayerSpec } from './layer';\nimport { isRepeatSpec } from './repeat';\nimport { isUnitSpec } from './unit';\nexport class SpecMapper {\n map(spec, params) {\n if (isFacetSpec(spec)) {\n return this.mapFacet(spec, params);\n }\n else if (isRepeatSpec(spec)) {\n return this.mapRepeat(spec, params);\n }\n else if (isHConcatSpec(spec)) {\n return this.mapHConcat(spec, params);\n }\n else if (isVConcatSpec(spec)) {\n return this.mapVConcat(spec, params);\n }\n else if (isConcatSpec(spec)) {\n return this.mapConcat(spec, params);\n }\n else {\n return this.mapLayerOrUnit(spec, params);\n }\n }\n mapLayerOrUnit(spec, params) {\n if (isLayerSpec(spec)) {\n return this.mapLayer(spec, params);\n }\n else if (isUnitSpec(spec)) {\n return this.mapUnit(spec, params);\n }\n throw new Error(log.message.invalidSpec(spec));\n }\n mapLayer(spec, params) {\n return Object.assign(Object.assign({}, spec), { layer: spec.layer.map(subspec => this.mapLayerOrUnit(subspec, params)) });\n }\n mapHConcat(spec, params) {\n return Object.assign(Object.assign({}, spec), { hconcat: spec.hconcat.map(subspec => this.map(subspec, params)) });\n }\n mapVConcat(spec, params) {\n return Object.assign(Object.assign({}, spec), { vconcat: spec.vconcat.map(subspec => this.map(subspec, params)) });\n }\n mapConcat(spec, params) {\n const { concat } = spec, rest = __rest(spec, [\"concat\"]);\n return Object.assign(Object.assign({}, rest), { concat: concat.map(subspec => this.map(subspec, params)) });\n }\n mapFacet(spec, params) {\n return Object.assign(Object.assign({}, spec), { \n // TODO: remove \"any\" once we support all facet listed in https://github.com/vega/vega-lite/issues/2760\n spec: this.map(spec.spec, params) });\n }\n mapRepeat(spec, params) {\n return Object.assign(Object.assign({}, spec), { \n // as any is required here since TS cannot infer that the output type satisfies the input type\n spec: this.map(spec.spec, params) });\n }\n}\n//# sourceMappingURL=map.js.map","import { isArray } from 'vega-util';\nexport function isRepeatSpec(spec) {\n return 'repeat' in spec;\n}\nexport function isLayerRepeatSpec(spec) {\n return !isArray(spec.repeat) && spec.repeat['layer'];\n}\n//# sourceMappingURL=repeat.js.map","import { array, isBoolean } from 'vega-util';\nimport { SUM_OPS } from './aggregate';\nimport { getSecondaryRangeChannel, NONPOSITION_CHANNELS } from './channel';\nimport { channelDefType, getFieldDef, isFieldDef, isFieldOrDatumDef, vgField } from './channeldef';\nimport { channelHasField, isAggregate } from './encoding';\nimport * as log from './log';\nimport { ARC, AREA, BAR, CIRCLE, isMarkDef, isPathMark, LINE, POINT, RULE, SQUARE, TEXT, TICK } from './mark';\nimport { ScaleType } from './scale';\nimport { contains } from './util';\nconst STACK_OFFSET_INDEX = {\n zero: 1,\n center: 1,\n normalize: 1\n};\nexport function isStackOffset(s) {\n return s in STACK_OFFSET_INDEX;\n}\nexport const STACKABLE_MARKS = new Set([ARC, BAR, AREA, RULE, POINT, CIRCLE, SQUARE, LINE, TEXT, TICK]);\nexport const STACK_BY_DEFAULT_MARKS = new Set([BAR, AREA, ARC]);\nfunction isUnbinnedQuantitative(channelDef) {\n return isFieldDef(channelDef) && channelDefType(channelDef) === 'quantitative' && !channelDef.bin;\n}\nfunction potentialStackedChannel(encoding, x) {\n var _a, _b;\n const y = x === 'x' ? 'y' : 'radius';\n const xDef = encoding[x];\n const yDef = encoding[y];\n if (isFieldDef(xDef) && isFieldDef(yDef)) {\n if (isUnbinnedQuantitative(xDef) && isUnbinnedQuantitative(yDef)) {\n if (xDef.stack) {\n return x;\n }\n else if (yDef.stack) {\n return y;\n }\n const xAggregate = isFieldDef(xDef) && !!xDef.aggregate;\n const yAggregate = isFieldDef(yDef) && !!yDef.aggregate;\n // if there is no explicit stacking, only apply stack if there is only one aggregate for x or y\n if (xAggregate !== yAggregate) {\n return xAggregate ? x : y;\n }\n else {\n const xScale = (_a = xDef.scale) === null || _a === void 0 ? void 0 : _a.type;\n const yScale = (_b = yDef.scale) === null || _b === void 0 ? void 0 : _b.type;\n if (xScale && xScale !== 'linear') {\n return y;\n }\n else if (yScale && yScale !== 'linear') {\n return x;\n }\n }\n }\n else if (isUnbinnedQuantitative(xDef)) {\n return x;\n }\n else if (isUnbinnedQuantitative(yDef)) {\n return y;\n }\n }\n else if (isUnbinnedQuantitative(xDef)) {\n return x;\n }\n else if (isUnbinnedQuantitative(yDef)) {\n return y;\n }\n return undefined;\n}\nfunction getDimensionChannel(channel) {\n switch (channel) {\n case 'x':\n return 'y';\n case 'y':\n return 'x';\n case 'theta':\n return 'radius';\n case 'radius':\n return 'theta';\n }\n}\n// Note: CompassQL uses this method and only pass in required properties of each argument object.\n// If required properties change, make sure to update CompassQL.\nexport function stack(m, encoding, opt = {}) {\n var _a, _b;\n const mark = isMarkDef(m) ? m.type : m;\n // Should have stackable mark\n if (!STACKABLE_MARKS.has(mark)) {\n return null;\n }\n // Run potential stacked twice, one for Cartesian and another for Polar,\n // so text marks can be stacked in any of the coordinates.\n // Note: The logic here is not perfectly correct. If we want to support stacked dot plots where each dot is a pie chart with label, we have to change the stack logic here to separate Cartesian stacking for polar stacking.\n // However, since we probably never want to do that, let's just note the limitation here.\n const fieldChannel = potentialStackedChannel(encoding, 'x') || potentialStackedChannel(encoding, 'theta');\n if (!fieldChannel) {\n return null;\n }\n const stackedFieldDef = encoding[fieldChannel];\n const stackedField = isFieldDef(stackedFieldDef) ? vgField(stackedFieldDef, {}) : undefined;\n let dimensionChannel = getDimensionChannel(fieldChannel);\n let dimensionDef = encoding[dimensionChannel];\n let dimensionField = isFieldDef(dimensionDef) ? vgField(dimensionDef, {}) : undefined;\n // avoid grouping by the stacked field\n if (dimensionField === stackedField) {\n dimensionField = undefined;\n dimensionDef = undefined;\n dimensionChannel = undefined;\n }\n // Should have grouping level of detail that is different from the dimension field\n const stackBy = NONPOSITION_CHANNELS.reduce((sc, channel) => {\n // Ignore tooltip in stackBy (https://github.com/vega/vega-lite/issues/4001)\n if (channel !== 'tooltip' && channelHasField(encoding, channel)) {\n const channelDef = encoding[channel];\n for (const cDef of array(channelDef)) {\n const fieldDef = getFieldDef(cDef);\n if (fieldDef.aggregate) {\n continue;\n }\n // Check whether the channel's field is identical to x/y's field or if the channel is a repeat\n const f = vgField(fieldDef, {});\n if (\n // if fielddef is a repeat, just include it in the stack by\n !f ||\n // otherwise, the field must be different from x and y fields.\n f !== dimensionField) {\n sc.push({ channel, fieldDef });\n }\n }\n }\n return sc;\n }, []);\n // Automatically determine offset\n let offset;\n if (stackedFieldDef.stack !== undefined) {\n if (isBoolean(stackedFieldDef.stack)) {\n offset = stackedFieldDef.stack ? 'zero' : null;\n }\n else {\n offset = stackedFieldDef.stack;\n }\n }\n else if (STACK_BY_DEFAULT_MARKS.has(mark)) {\n offset = 'zero';\n }\n if (!offset || !isStackOffset(offset)) {\n return null;\n }\n if (isAggregate(encoding) && stackBy.length === 0) {\n return null;\n }\n // warn when stacking non-linear\n if (((_a = stackedFieldDef === null || stackedFieldDef === void 0 ? void 0 : stackedFieldDef.scale) === null || _a === void 0 ? void 0 : _a.type) && ((_b = stackedFieldDef === null || stackedFieldDef === void 0 ? void 0 : stackedFieldDef.scale) === null || _b === void 0 ? void 0 : _b.type) !== ScaleType.LINEAR) {\n if (opt.disallowNonLinearStack) {\n return null;\n }\n else {\n log.warn(log.message.cannotStackNonLinearScale(stackedFieldDef.scale.type));\n }\n }\n // Check if it is a ranged mark\n if (isFieldOrDatumDef(encoding[getSecondaryRangeChannel(fieldChannel)])) {\n if (stackedFieldDef.stack !== undefined) {\n log.warn(log.message.cannotStackRangedMark(fieldChannel));\n }\n return null;\n }\n // Warn if stacking non-summative aggregate\n if (isFieldDef(stackedFieldDef) && stackedFieldDef.aggregate && !contains(SUM_OPS, stackedFieldDef.aggregate)) {\n log.warn(log.message.stackNonSummativeAggregate(stackedFieldDef.aggregate));\n }\n return {\n groupbyChannel: dimensionDef ? dimensionChannel : undefined,\n groupbyField: dimensionField,\n fieldChannel,\n impute: stackedFieldDef.impute === null ? false : isPathMark(mark),\n stackBy,\n offset\n };\n}\n//# sourceMappingURL=stack.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isObject } from 'vega-util';\nimport { normalizeEncoding } from '../encoding';\nimport { isMarkDef } from '../mark';\nimport { isUnitSpec } from '../spec/unit';\nimport { stack } from '../stack';\nimport { keys, omit, pick } from '../util';\nfunction dropLineAndPoint(markDef) {\n const { point: _point, line: _line } = markDef, mark = __rest(markDef, [\"point\", \"line\"]);\n return keys(mark).length > 1 ? mark : mark.type;\n}\nfunction dropLineAndPointFromConfig(config) {\n for (const mark of ['line', 'area', 'rule', 'trail']) {\n if (config[mark]) {\n config = Object.assign(Object.assign({}, config), { \n // TODO: remove as any\n [mark]: omit(config[mark], ['point', 'line']) });\n }\n }\n return config;\n}\nfunction getPointOverlay(markDef, markConfig = {}, encoding) {\n if (markDef.point === 'transparent') {\n return { opacity: 0 };\n }\n else if (markDef.point) {\n // truthy : true or object\n return isObject(markDef.point) ? markDef.point : {};\n }\n else if (markDef.point !== undefined) {\n // false or null\n return null;\n }\n else {\n // undefined (not disabled)\n if (markConfig.point || encoding.shape) {\n // enable point overlay if config[mark].point is truthy or if encoding.shape is provided\n return isObject(markConfig.point) ? markConfig.point : {};\n }\n // markDef.point is defined as falsy\n return undefined;\n }\n}\nfunction getLineOverlay(markDef, markConfig = {}) {\n if (markDef.line) {\n // true or object\n return markDef.line === true ? {} : markDef.line;\n }\n else if (markDef.line !== undefined) {\n // false or null\n return null;\n }\n else {\n // undefined (not disabled)\n if (markConfig.line) {\n // enable line overlay if config[mark].line is truthy\n return markConfig.line === true ? {} : markConfig.line;\n }\n // markDef.point is defined as falsy\n return undefined;\n }\n}\nexport class PathOverlayNormalizer {\n constructor() {\n this.name = 'path-overlay';\n }\n hasMatchingType(spec, config) {\n if (isUnitSpec(spec)) {\n const { mark, encoding } = spec;\n const markDef = isMarkDef(mark) ? mark : { type: mark };\n switch (markDef.type) {\n case 'line':\n case 'rule':\n case 'trail':\n return !!getPointOverlay(markDef, config[markDef.type], encoding);\n case 'area':\n return (\n // false / null are also included as we want to remove the properties\n !!getPointOverlay(markDef, config[markDef.type], encoding) ||\n !!getLineOverlay(markDef, config[markDef.type]));\n }\n }\n return false;\n }\n run(spec, normParams, normalize) {\n const { config } = normParams;\n const { params, projection, mark, encoding: e } = spec, outerSpec = __rest(spec, [\"params\", \"projection\", \"mark\", \"encoding\"]);\n // Need to call normalizeEncoding because we need the inferred types to correctly determine stack\n const encoding = normalizeEncoding(e, config);\n const markDef = isMarkDef(mark) ? mark : { type: mark };\n const pointOverlay = getPointOverlay(markDef, config[markDef.type], encoding);\n const lineOverlay = markDef.type === 'area' && getLineOverlay(markDef, config[markDef.type]);\n const layer = [\n Object.assign(Object.assign({}, (params ? { params } : {})), { mark: dropLineAndPoint(Object.assign(Object.assign({}, (markDef.type === 'area' && markDef.opacity === undefined && markDef.fillOpacity === undefined\n ? { opacity: 0.7 }\n : {})), markDef)), \n // drop shape from encoding as this might be used to trigger point overlay\n encoding: omit(encoding, ['shape']) })\n ];\n // FIXME: determine rules for applying selections.\n // Need to copy stack config to overlayed layer\n const stackProps = stack(markDef, encoding);\n let overlayEncoding = encoding;\n if (stackProps) {\n const { fieldChannel: stackFieldChannel, offset } = stackProps;\n overlayEncoding = Object.assign(Object.assign({}, encoding), { [stackFieldChannel]: Object.assign(Object.assign({}, encoding[stackFieldChannel]), (offset ? { stack: offset } : {})) });\n }\n if (lineOverlay) {\n layer.push(Object.assign(Object.assign({}, (projection ? { projection } : {})), { mark: Object.assign(Object.assign({ type: 'line' }, pick(markDef, ['clip', 'interpolate', 'tension', 'tooltip'])), lineOverlay), encoding: overlayEncoding }));\n }\n if (pointOverlay) {\n layer.push(Object.assign(Object.assign({}, (projection ? { projection } : {})), { mark: Object.assign(Object.assign({ type: 'point', opacity: 1, filled: true }, pick(markDef, ['clip', 'tooltip'])), pointOverlay), encoding: overlayEncoding }));\n }\n return normalize(Object.assign(Object.assign({}, outerSpec), { layer }), Object.assign(Object.assign({}, normParams), { config: dropLineAndPointFromConfig(config) }));\n }\n}\n//# sourceMappingURL=pathoverlay.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { hasOwnProperty, isArray } from 'vega-util';\nimport { hasConditionalFieldOrDatumDef, isConditionalDef, isFieldDef, isFieldOrDatumDef, isRepeatRef, isSortableFieldDef } from '../channeldef';\nimport * as log from '../log';\nimport { isSortField } from '../sort';\nimport { isFacetMapping } from '../spec/facet';\nexport function replaceRepeaterInFacet(facet, repeater) {\n if (!repeater) {\n return facet;\n }\n if (isFacetMapping(facet)) {\n return replaceRepeaterInMapping(facet, repeater);\n }\n return replaceRepeaterInFieldDef(facet, repeater);\n}\nexport function replaceRepeaterInEncoding(encoding, repeater) {\n if (!repeater) {\n return encoding;\n }\n return replaceRepeaterInMapping(encoding, repeater);\n}\n/**\n * Replaces repeated value and returns if the repeated value is valid.\n */\nfunction replaceRepeatInProp(prop, o, repeater) {\n const val = o[prop];\n if (isRepeatRef(val)) {\n if (val.repeat in repeater) {\n return Object.assign(Object.assign({}, o), { [prop]: repeater[val.repeat] });\n }\n else {\n log.warn(log.message.noSuchRepeatedValue(val.repeat));\n return undefined;\n }\n }\n return o;\n}\n/**\n * Replace repeater values in a field def with the concrete field name.\n */\nfunction replaceRepeaterInFieldDef(fieldDef, repeater) {\n fieldDef = replaceRepeatInProp('field', fieldDef, repeater);\n if (fieldDef === undefined) {\n // the field def should be ignored\n return undefined;\n }\n else if (fieldDef === null) {\n return null;\n }\n if (isSortableFieldDef(fieldDef) && isSortField(fieldDef.sort)) {\n const sort = replaceRepeatInProp('field', fieldDef.sort, repeater);\n fieldDef = Object.assign(Object.assign({}, fieldDef), (sort ? { sort } : {}));\n }\n return fieldDef;\n}\nfunction replaceRepeaterInFieldOrDatumDef(def, repeater) {\n if (isFieldDef(def)) {\n return replaceRepeaterInFieldDef(def, repeater);\n }\n else {\n const datumDef = replaceRepeatInProp('datum', def, repeater);\n if (datumDef !== def && !datumDef.type) {\n datumDef.type = 'nominal';\n }\n return datumDef;\n }\n}\nfunction replaceRepeaterInChannelDef(channelDef, repeater) {\n if (isFieldOrDatumDef(channelDef)) {\n const fd = replaceRepeaterInFieldOrDatumDef(channelDef, repeater);\n if (fd) {\n return fd;\n }\n else if (isConditionalDef(channelDef)) {\n return { condition: channelDef.condition };\n }\n }\n else {\n if (hasConditionalFieldOrDatumDef(channelDef)) {\n const fd = replaceRepeaterInFieldOrDatumDef(channelDef.condition, repeater);\n if (fd) {\n return Object.assign(Object.assign({}, channelDef), { condition: fd });\n }\n else {\n const { condition } = channelDef, channelDefWithoutCondition = __rest(channelDef, [\"condition\"]);\n return channelDefWithoutCondition;\n }\n }\n return channelDef;\n }\n return undefined;\n}\nfunction replaceRepeaterInMapping(mapping, repeater) {\n const out = {};\n for (const channel in mapping) {\n if (hasOwnProperty(mapping, channel)) {\n const channelDef = mapping[channel];\n if (isArray(channelDef)) {\n // array cannot have condition\n out[channel] = channelDef // somehow we need to cast it here\n .map(cd => replaceRepeaterInChannelDef(cd, repeater))\n .filter(cd => cd);\n }\n else {\n const cd = replaceRepeaterInChannelDef(channelDef, repeater);\n if (cd !== undefined) {\n out[channel] = cd;\n }\n }\n }\n }\n return out;\n}\n//# sourceMappingURL=repeater.js.map","import { isObject } from 'vega-util';\nimport { isBinned } from '../bin';\nimport { getMainRangeChannel, SECONDARY_RANGE_CHANNEL } from '../channel';\nimport { isDatumDef, isFieldDef } from '../channeldef';\nimport * as log from '../log';\nimport { isMarkDef } from '../mark';\nimport { isUnitSpec } from '../spec/unit';\nexport class RuleForRangedLineNormalizer {\n constructor() {\n this.name = 'RuleForRangedLine';\n }\n hasMatchingType(spec) {\n if (isUnitSpec(spec)) {\n const { encoding, mark } = spec;\n if (mark === 'line' || (isMarkDef(mark) && mark.type === 'line')) {\n for (const channel of SECONDARY_RANGE_CHANNEL) {\n const mainChannel = getMainRangeChannel(channel);\n const mainChannelDef = encoding[mainChannel];\n if (encoding[channel]) {\n if ((isFieldDef(mainChannelDef) && !isBinned(mainChannelDef.bin)) || isDatumDef(mainChannelDef)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n run(spec, params, normalize) {\n const { encoding, mark } = spec;\n log.warn(log.message.lineWithRange(!!encoding.x2, !!encoding.y2));\n return normalize(Object.assign(Object.assign({}, spec), { mark: isObject(mark) ? Object.assign(Object.assign({}, mark), { type: 'rule' }) : 'rule' }), params);\n }\n}\n//# sourceMappingURL=ruleforrangedline.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isArray } from 'vega-util';\nimport { COLUMN, FACET, ROW } from '../channel';\nimport { hasConditionalFieldOrDatumDef, isFieldOrDatumDef, isValueDef } from '../channeldef';\nimport { boxPlotNormalizer } from '../compositemark/boxplot';\nimport { errorBandNormalizer } from '../compositemark/errorband';\nimport { errorBarNormalizer } from '../compositemark/errorbar';\nimport { channelHasField } from '../encoding';\nimport * as log from '../log';\nimport { isFacetMapping } from '../spec/facet';\nimport { SpecMapper } from '../spec/map';\nimport { isLayerRepeatSpec } from '../spec/repeat';\nimport { isUnitSpec } from '../spec/unit';\nimport { isEmpty, keys, omit, varName } from '../util';\nimport { isSignalRef } from '../vega.schema';\nimport { PathOverlayNormalizer } from './pathoverlay';\nimport { replaceRepeaterInEncoding, replaceRepeaterInFacet } from './repeater';\nimport { RuleForRangedLineNormalizer } from './ruleforrangedline';\nexport class CoreNormalizer extends SpecMapper {\n constructor() {\n super(...arguments);\n this.nonFacetUnitNormalizers = [\n boxPlotNormalizer,\n errorBarNormalizer,\n errorBandNormalizer,\n new PathOverlayNormalizer(),\n new RuleForRangedLineNormalizer()\n ];\n }\n map(spec, params) {\n // Special handling for a faceted unit spec as it can return a facet spec, not just a layer or unit spec like a normal unit spec.\n if (isUnitSpec(spec)) {\n const hasRow = channelHasField(spec.encoding, ROW);\n const hasColumn = channelHasField(spec.encoding, COLUMN);\n const hasFacet = channelHasField(spec.encoding, FACET);\n if (hasRow || hasColumn || hasFacet) {\n return this.mapFacetedUnit(spec, params);\n }\n }\n return super.map(spec, params);\n }\n // This is for normalizing non-facet unit\n mapUnit(spec, params) {\n const { parentEncoding, parentProjection } = params;\n const encoding = replaceRepeaterInEncoding(spec.encoding, params.repeater);\n const specWithReplacedEncoding = Object.assign(Object.assign({}, spec), (encoding ? { encoding } : {}));\n if (parentEncoding || parentProjection) {\n return this.mapUnitWithParentEncodingOrProjection(specWithReplacedEncoding, params);\n }\n const normalizeLayerOrUnit = this.mapLayerOrUnit.bind(this);\n for (const unitNormalizer of this.nonFacetUnitNormalizers) {\n if (unitNormalizer.hasMatchingType(specWithReplacedEncoding, params.config)) {\n return unitNormalizer.run(specWithReplacedEncoding, params, normalizeLayerOrUnit);\n }\n }\n return specWithReplacedEncoding;\n }\n mapRepeat(spec, params) {\n if (isLayerRepeatSpec(spec)) {\n return this.mapLayerRepeat(spec, params);\n }\n else {\n return this.mapNonLayerRepeat(spec, params);\n }\n }\n mapLayerRepeat(spec, params) {\n const { repeat, spec: childSpec } = spec, rest = __rest(spec, [\"repeat\", \"spec\"]);\n const { row, column, layer } = repeat;\n const { repeater = {}, repeaterPrefix = '' } = params;\n if (row || column) {\n return this.mapRepeat(Object.assign(Object.assign({}, spec), { repeat: Object.assign(Object.assign({}, (row ? { row } : {})), (column ? { column } : {})), spec: {\n repeat: { layer },\n spec: childSpec\n } }), params);\n }\n else {\n return Object.assign(Object.assign({}, rest), { layer: layer.map(layerValue => {\n const childRepeater = Object.assign(Object.assign({}, repeater), { layer: layerValue });\n const childName = `${(childSpec.name || '') + repeaterPrefix}child__layer_${varName(layerValue)}`;\n const child = this.mapLayerOrUnit(childSpec, Object.assign(Object.assign({}, params), { repeater: childRepeater, repeaterPrefix: childName }));\n child.name = childName;\n return child;\n }) });\n }\n }\n mapNonLayerRepeat(spec, params) {\n var _a;\n const { repeat, spec: childSpec, data } = spec, remainingProperties = __rest(spec, [\"repeat\", \"spec\", \"data\"]);\n if (!isArray(repeat) && spec.columns) {\n // is repeat with row/column\n spec = omit(spec, ['columns']);\n log.warn(log.message.columnsNotSupportByRowCol('repeat'));\n }\n const concat = [];\n const { repeater = {}, repeaterPrefix = '' } = params;\n const row = (!isArray(repeat) && repeat.row) || [repeater ? repeater.row : null];\n const column = (!isArray(repeat) && repeat.column) || [repeater ? repeater.column : null];\n const repeatValues = (isArray(repeat) && repeat) || [repeater ? repeater.repeat : null];\n // cross product\n for (const repeatValue of repeatValues) {\n for (const rowValue of row) {\n for (const columnValue of column) {\n const childRepeater = {\n repeat: repeatValue,\n row: rowValue,\n column: columnValue,\n layer: repeater.layer\n };\n const childName = (childSpec.name || '') +\n repeaterPrefix +\n 'child__' +\n (isArray(repeat)\n ? `${varName(repeatValue)}`\n : (repeat.row ? `row_${varName(rowValue)}` : '') +\n (repeat.column ? `column_${varName(columnValue)}` : ''));\n const child = this.map(childSpec, Object.assign(Object.assign({}, params), { repeater: childRepeater, repeaterPrefix: childName }));\n child.name = childName;\n // we move data up\n concat.push(omit(child, ['data']));\n }\n }\n }\n const columns = isArray(repeat) ? spec.columns : repeat.column ? repeat.column.length : 1;\n return Object.assign(Object.assign({ data: (_a = childSpec.data) !== null && _a !== void 0 ? _a : data, align: 'all' }, remainingProperties), { columns,\n concat });\n }\n mapFacet(spec, params) {\n const { facet } = spec;\n if (isFacetMapping(facet) && spec.columns) {\n // is facet with row/column\n spec = omit(spec, ['columns']);\n log.warn(log.message.columnsNotSupportByRowCol('facet'));\n }\n return super.mapFacet(spec, params);\n }\n mapUnitWithParentEncodingOrProjection(spec, params) {\n const { encoding, projection } = spec;\n const { parentEncoding, parentProjection, config } = params;\n const mergedProjection = mergeProjection({ parentProjection, projection });\n const mergedEncoding = mergeEncoding({\n parentEncoding,\n encoding: replaceRepeaterInEncoding(encoding, params.repeater)\n });\n return this.mapUnit(Object.assign(Object.assign(Object.assign({}, spec), (mergedProjection ? { projection: mergedProjection } : {})), (mergedEncoding ? { encoding: mergedEncoding } : {})), { config });\n }\n mapFacetedUnit(spec, normParams) {\n // New encoding in the inside spec should not contain row / column\n // as row/column should be moved to facet\n const _a = spec.encoding, { row, column, facet } = _a, encoding = __rest(_a, [\"row\", \"column\", \"facet\"]);\n // Mark and encoding should be moved into the inner spec\n const { mark, width, projection, height, view, params, encoding: _ } = spec, outerSpec = __rest(spec, [\"mark\", \"width\", \"projection\", \"height\", \"view\", \"params\", \"encoding\"]);\n const { facetMapping, layout } = this.getFacetMappingAndLayout({ row, column, facet }, normParams);\n const newEncoding = replaceRepeaterInEncoding(encoding, normParams.repeater);\n return this.mapFacet(Object.assign(Object.assign(Object.assign({}, outerSpec), layout), { \n // row / column has higher precedence than facet\n facet: facetMapping, spec: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (width ? { width } : {})), (height ? { height } : {})), (view ? { view } : {})), (projection ? { projection } : {})), { mark, encoding: newEncoding }), (params ? { params } : {})) }), normParams);\n }\n getFacetMappingAndLayout(facets, params) {\n var _a;\n const { row, column, facet } = facets;\n if (row || column) {\n if (facet) {\n log.warn(log.message.facetChannelDropped([...(row ? [ROW] : []), ...(column ? [COLUMN] : [])]));\n }\n const facetMapping = {};\n const layout = {};\n for (const channel of [ROW, COLUMN]) {\n const def = facets[channel];\n if (def) {\n const { align, center, spacing, columns } = def, defWithoutLayout = __rest(def, [\"align\", \"center\", \"spacing\", \"columns\"]);\n facetMapping[channel] = defWithoutLayout;\n for (const prop of ['align', 'center', 'spacing']) {\n if (def[prop] !== undefined) {\n (_a = layout[prop]) !== null && _a !== void 0 ? _a : (layout[prop] = {});\n layout[prop][channel] = def[prop];\n }\n }\n }\n }\n return { facetMapping, layout };\n }\n else {\n const { align, center, spacing, columns } = facet, facetMapping = __rest(facet, [\"align\", \"center\", \"spacing\", \"columns\"]);\n return {\n facetMapping: replaceRepeaterInFacet(facetMapping, params.repeater),\n layout: Object.assign(Object.assign(Object.assign(Object.assign({}, (align ? { align } : {})), (center ? { center } : {})), (spacing ? { spacing } : {})), (columns ? { columns } : {}))\n };\n }\n }\n mapLayer(spec, _a) {\n // Special handling for extended layer spec\n var { parentEncoding, parentProjection } = _a, otherParams = __rest(_a, [\"parentEncoding\", \"parentProjection\"]);\n const { encoding, projection } = spec, rest = __rest(spec, [\"encoding\", \"projection\"]);\n const params = Object.assign(Object.assign({}, otherParams), { parentEncoding: mergeEncoding({ parentEncoding, encoding, layer: true }), parentProjection: mergeProjection({ parentProjection, projection }) });\n return super.mapLayer(rest, params);\n }\n}\nfunction mergeEncoding({ parentEncoding, encoding = {}, layer }) {\n let merged = {};\n if (parentEncoding) {\n const channels = new Set([...keys(parentEncoding), ...keys(encoding)]);\n for (const channel of channels) {\n const channelDef = encoding[channel];\n const parentChannelDef = parentEncoding[channel];\n if (isFieldOrDatumDef(channelDef)) {\n // Field/Datum Def can inherit properties from its parent\n // Note that parentChannelDef doesn't have to be a field/datum def if the channelDef is already one.\n const mergedChannelDef = Object.assign(Object.assign({}, parentChannelDef), channelDef);\n merged[channel] = mergedChannelDef;\n }\n else if (hasConditionalFieldOrDatumDef(channelDef)) {\n merged[channel] = Object.assign(Object.assign({}, channelDef), { condition: Object.assign(Object.assign({}, parentChannelDef), channelDef.condition) });\n }\n else if (channelDef || channelDef === null) {\n merged[channel] = channelDef;\n }\n else if (layer ||\n isValueDef(parentChannelDef) ||\n isSignalRef(parentChannelDef) ||\n isFieldOrDatumDef(parentChannelDef) ||\n isArray(parentChannelDef)) {\n merged[channel] = parentChannelDef;\n }\n }\n }\n else {\n merged = encoding;\n }\n return !merged || isEmpty(merged) ? undefined : merged;\n}\nfunction mergeProjection(opt) {\n const { parentProjection, projection } = opt;\n if (parentProjection && projection) {\n log.warn(log.message.projectionOverridden({ parentProjection, projection }));\n }\n return projection !== null && projection !== void 0 ? projection : parentProjection;\n}\n//# sourceMappingURL=core.js.map","import { normalizeLogicalComposition } from './logical';\nimport { normalizePredicate } from './predicate';\nexport function isFilter(t) {\n return 'filter' in t;\n}\nexport function isImputeSequence(t) {\n return (t === null || t === void 0 ? void 0 : t['stop']) !== undefined;\n}\nexport function isLookup(t) {\n return 'lookup' in t;\n}\nexport function isLookupData(from) {\n return 'data' in from;\n}\nexport function isLookupSelection(from) {\n return 'param' in from;\n}\nexport function isPivot(t) {\n return 'pivot' in t;\n}\nexport function isDensity(t) {\n return 'density' in t;\n}\nexport function isQuantile(t) {\n return 'quantile' in t;\n}\nexport function isRegression(t) {\n return 'regression' in t;\n}\nexport function isLoess(t) {\n return 'loess' in t;\n}\nexport function isSample(t) {\n return 'sample' in t;\n}\nexport function isWindow(t) {\n return 'window' in t;\n}\nexport function isJoinAggregate(t) {\n return 'joinaggregate' in t;\n}\nexport function isFlatten(t) {\n return 'flatten' in t;\n}\nexport function isCalculate(t) {\n return 'calculate' in t;\n}\nexport function isBin(t) {\n return 'bin' in t;\n}\nexport function isImpute(t) {\n return 'impute' in t;\n}\nexport function isTimeUnit(t) {\n return 'timeUnit' in t;\n}\nexport function isAggregate(t) {\n return 'aggregate' in t;\n}\nexport function isStack(t) {\n return 'stack' in t;\n}\nexport function isFold(t) {\n return 'fold' in t;\n}\nexport function normalizeTransform(transform) {\n return transform.map(t => {\n if (isFilter(t)) {\n return {\n filter: normalizeLogicalComposition(t.filter, normalizePredicate)\n };\n }\n return t;\n });\n}\n//# sourceMappingURL=transform.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isArray } from 'vega';\nimport { isBinParams } from '../bin';\nimport { isConditionalDef, isFieldDef, isScaleFieldDef } from '../channeldef';\nimport { normalizeLogicalComposition } from '../logical';\nimport { SpecMapper } from '../spec/map';\nimport { isBin, isFilter, isLookup } from '../transform';\nimport { duplicate, entries, vals } from '../util';\nexport class SelectionCompatibilityNormalizer extends SpecMapper {\n map(spec, normParams) {\n var _a, _b;\n (_a = normParams.emptySelections) !== null && _a !== void 0 ? _a : (normParams.emptySelections = {});\n (_b = normParams.selectionPredicates) !== null && _b !== void 0 ? _b : (normParams.selectionPredicates = {});\n spec = normalizeTransforms(spec, normParams);\n return super.map(spec, normParams);\n }\n mapLayerOrUnit(spec, normParams) {\n spec = normalizeTransforms(spec, normParams);\n if (spec.encoding) {\n const encoding = {};\n for (const [channel, enc] of entries(spec.encoding)) {\n encoding[channel] = normalizeChannelDef(enc, normParams);\n }\n spec = Object.assign(Object.assign({}, spec), { encoding });\n }\n return super.mapLayerOrUnit(spec, normParams);\n }\n mapUnit(spec, normParams) {\n const _a = spec, { selection } = _a, rest = __rest(_a, [\"selection\"]);\n if (selection) {\n return Object.assign(Object.assign({}, rest), { params: entries(selection).map(([name, selDef]) => {\n var _a;\n const _b = selDef, { init: value, bind, empty } = _b, select = __rest(_b, [\"init\", \"bind\", \"empty\"]);\n if (select.type === 'single') {\n select.type = 'point';\n select.toggle = false;\n }\n else if (select.type === 'multi') {\n select.type = 'point';\n }\n // Propagate emptiness forwards and backwards\n normParams.emptySelections[name] = empty !== 'none';\n for (const pred of vals((_a = normParams.selectionPredicates[name]) !== null && _a !== void 0 ? _a : {})) {\n pred.empty = empty !== 'none';\n }\n return { name, value, select, bind };\n }) });\n }\n return spec;\n }\n}\nfunction normalizeTransforms(spec, normParams) {\n const { transform: tx } = spec, rest = __rest(spec, [\"transform\"]);\n if (tx) {\n const transform = tx.map((t) => {\n if (isFilter(t)) {\n return { filter: normalizePredicate(t, normParams) };\n }\n else if (isBin(t) && isBinParams(t.bin)) {\n return Object.assign(Object.assign({}, t), { bin: normalizeBinExtent(t.bin) });\n }\n else if (isLookup(t)) {\n const _a = t.from, { selection: param } = _a, from = __rest(_a, [\"selection\"]);\n return param\n ? Object.assign(Object.assign({}, t), { from: Object.assign({ param }, from) }) : t;\n }\n return t;\n });\n return Object.assign(Object.assign({}, rest), { transform });\n }\n return spec;\n}\nfunction normalizeChannelDef(obj, normParams) {\n var _a, _b;\n const enc = duplicate(obj);\n if (isFieldDef(enc) && isBinParams(enc.bin)) {\n enc.bin = normalizeBinExtent(enc.bin);\n }\n if (isScaleFieldDef(enc) && ((_b = (_a = enc.scale) === null || _a === void 0 ? void 0 : _a.domain) === null || _b === void 0 ? void 0 : _b.selection)) {\n const _c = enc.scale.domain, { selection: param } = _c, domain = __rest(_c, [\"selection\"]);\n enc.scale.domain = Object.assign(Object.assign({}, domain), (param ? { param } : {}));\n }\n if (isConditionalDef(enc)) {\n if (isArray(enc.condition)) {\n enc.condition = enc.condition.map((c) => {\n const { selection, param, test } = c, cond = __rest(c, [\"selection\", \"param\", \"test\"]);\n return param ? c : Object.assign(Object.assign({}, cond), { test: normalizePredicate(c, normParams) });\n });\n }\n else {\n const _d = normalizeChannelDef(enc.condition, normParams), { selection, param, test } = _d, cond = __rest(_d, [\"selection\", \"param\", \"test\"]);\n enc.condition = param\n ? enc.condition\n : Object.assign(Object.assign({}, cond), { test: normalizePredicate(enc.condition, normParams) });\n }\n }\n return enc;\n}\nfunction normalizeBinExtent(bin) {\n const ext = bin.extent;\n if (ext === null || ext === void 0 ? void 0 : ext.selection) {\n const { selection: param } = ext, rest = __rest(ext, [\"selection\"]);\n return Object.assign(Object.assign({}, bin), { extent: Object.assign(Object.assign({}, rest), { param }) });\n }\n return bin;\n}\nfunction normalizePredicate(op, normParams) {\n // Normalize old compositions of selection names (e.g., selection: {and: [\"one\", \"two\"]})\n const normalizeSelectionComposition = (o) => {\n return normalizeLogicalComposition(o, param => {\n var _a, _b;\n var _c;\n const empty = (_a = normParams.emptySelections[param]) !== null && _a !== void 0 ? _a : true;\n const pred = { param, empty };\n (_b = (_c = normParams.selectionPredicates)[param]) !== null && _b !== void 0 ? _b : (_c[param] = []);\n normParams.selectionPredicates[param].push(pred);\n return pred;\n });\n };\n return op.selection\n ? normalizeSelectionComposition(op.selection)\n : normalizeLogicalComposition(op.test || op.filter, o => o.selection ? normalizeSelectionComposition(o.selection) : o);\n}\n//# sourceMappingURL=selectioncompat.js.map","import { isArray, isString } from 'vega';\nimport { isSelectionParameter } from '../selection';\nimport { isUnitSpec } from '../spec';\nimport { SpecMapper } from '../spec/map';\nexport class TopLevelSelectionsNormalizer extends SpecMapper {\n map(spec, normParams) {\n var _a;\n const selections = (_a = normParams.selections) !== null && _a !== void 0 ? _a : [];\n if (spec.params && !isUnitSpec(spec)) {\n const params = [];\n for (const param of spec.params) {\n if (isSelectionParameter(param)) {\n selections.push(param);\n }\n else {\n params.push(param);\n }\n }\n spec.params = params;\n }\n normParams.selections = selections;\n return super.map(spec, addSpecNameToParams(spec, normParams));\n }\n mapUnit(spec, normParams) {\n var _a;\n const selections = normParams.selections;\n if (!selections || !selections.length)\n return spec;\n const path = ((_a = normParams.path) !== null && _a !== void 0 ? _a : []).concat(spec.name);\n const params = [];\n for (const selection of selections) {\n // By default, apply selections to all unit views.\n if (!selection.views || !selection.views.length) {\n params.push(selection);\n }\n else {\n for (const view of selection.views) {\n // view is either a specific unit name, or a partial path through the spec tree.\n if ((isString(view) && (view === spec.name || path.indexOf(view) >= 0)) ||\n (isArray(view) &&\n view.map(v => path.indexOf(v)).every((v, i, arr) => v !== -1 && (i === 0 || v > arr[i - 1])))) {\n params.push(selection);\n }\n }\n }\n }\n if (params.length)\n spec.params = params;\n return spec;\n }\n}\nfor (const method of ['mapFacet', 'mapRepeat', 'mapHConcat', 'mapVConcat', 'mapLayer']) {\n const proto = TopLevelSelectionsNormalizer.prototype[method];\n TopLevelSelectionsNormalizer.prototype[method] = function (spec, params) {\n return proto.call(this, spec, addSpecNameToParams(spec, params));\n };\n}\nfunction addSpecNameToParams(spec, params) {\n var _a;\n return spec.name\n ? Object.assign(Object.assign({}, params), { path: ((_a = params.path) !== null && _a !== void 0 ? _a : []).concat(spec.name) }) : params;\n}\n//# sourceMappingURL=toplevelselection.js.map","import { isString } from 'vega-util';\nimport { initConfig } from '../config';\nimport * as log from '../log';\nimport { isLayerSpec, isUnitSpec } from '../spec';\nimport { deepEqual } from '../util';\nimport { CoreNormalizer } from './core';\nimport { SelectionCompatibilityNormalizer } from './selectioncompat';\nimport { TopLevelSelectionsNormalizer } from './toplevelselection';\nexport function normalize(spec, config) {\n if (config === undefined) {\n config = initConfig(spec.config);\n }\n const normalizedSpec = normalizeGenericSpec(spec, config);\n const { width, height } = spec;\n const autosize = normalizeAutoSize(normalizedSpec, { width, height, autosize: spec.autosize }, config);\n return Object.assign(Object.assign({}, normalizedSpec), (autosize ? { autosize } : {}));\n}\nconst coreNormalizer = new CoreNormalizer();\nconst selectionCompatNormalizer = new SelectionCompatibilityNormalizer();\nconst topLevelSelectionNormalizer = new TopLevelSelectionsNormalizer();\n/**\n * Decompose extended unit specs into composition of pure unit specs.\n * And push top-level selection definitions down to unit specs.\n */\nfunction normalizeGenericSpec(spec, config = {}) {\n const normParams = { config };\n return topLevelSelectionNormalizer.map(coreNormalizer.map(selectionCompatNormalizer.map(spec, normParams), normParams), normParams);\n}\nfunction _normalizeAutoSize(autosize) {\n return isString(autosize) ? { type: autosize } : autosize !== null && autosize !== void 0 ? autosize : {};\n}\n/**\n * Normalize autosize and deal with width or height == \"container\".\n */\nexport function normalizeAutoSize(spec, sizeInfo, config) {\n let { width, height } = sizeInfo;\n const isFitCompatible = isUnitSpec(spec) || isLayerSpec(spec);\n const autosizeDefault = {};\n if (!isFitCompatible) {\n // If spec is not compatible with autosize == \"fit\", discard width/height == container\n if (width == 'container') {\n log.warn(log.message.containerSizeNonSingle('width'));\n width = undefined;\n }\n if (height == 'container') {\n log.warn(log.message.containerSizeNonSingle('height'));\n height = undefined;\n }\n }\n else {\n // Default autosize parameters to fit when width/height is \"container\"\n if (width == 'container' && height == 'container') {\n autosizeDefault.type = 'fit';\n autosizeDefault.contains = 'padding';\n }\n else if (width == 'container') {\n autosizeDefault.type = 'fit-x';\n autosizeDefault.contains = 'padding';\n }\n else if (height == 'container') {\n autosizeDefault.type = 'fit-y';\n autosizeDefault.contains = 'padding';\n }\n }\n const autosize = Object.assign(Object.assign(Object.assign({ type: 'pad' }, autosizeDefault), (config ? _normalizeAutoSize(config.autosize) : {})), _normalizeAutoSize(spec.autosize));\n if (autosize.type === 'fit' && !isFitCompatible) {\n log.warn(log.message.FIT_NON_SINGLE);\n autosize.type = 'pad';\n }\n if (width == 'container' && !(autosize.type == 'fit' || autosize.type == 'fit-x')) {\n log.warn(log.message.containerSizeNotCompatibleWithAutosize('width'));\n }\n if (height == 'container' && !(autosize.type == 'fit' || autosize.type == 'fit-y')) {\n log.warn(log.message.containerSizeNotCompatibleWithAutosize('height'));\n }\n // Delete autosize property if it's Vega's default\n if (deepEqual(autosize, { type: 'pad' })) {\n return undefined;\n }\n return autosize;\n}\n//# sourceMappingURL=index.js.map","import { getPositionScaleChannel } from '../channel';\nimport { signalRefOrValue } from '../compile/common';\nexport function isFitType(autoSizeType) {\n return autoSizeType === 'fit' || autoSizeType === 'fit-x' || autoSizeType === 'fit-y';\n}\nexport function getFitType(sizeType) {\n return sizeType ? `fit-${getPositionScaleChannel(sizeType)}` : 'fit';\n}\nconst TOP_LEVEL_PROPERTIES = [\n 'background',\n 'padding'\n // We do not include \"autosize\" here as it is supported by only unit and layer specs and thus need to be normalized\n];\nexport function extractTopLevelProperties(t, includeParams) {\n const o = {};\n for (const p of TOP_LEVEL_PROPERTIES) {\n if (t && t[p] !== undefined) {\n o[p] = signalRefOrValue(t[p]);\n }\n }\n if (includeParams) {\n o.params = t.params;\n }\n return o;\n}\n//# sourceMappingURL=toplevel.js.map","import * as log from '../log';\nimport { deepEqual, duplicate, getFirstDefined, keys } from '../util';\n/**\n * Generic class for storing properties that are explicitly specified\n * and implicitly determined by the compiler.\n * This is important for scale/axis/legend merging as\n * we want to prioritize properties that users explicitly specified.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport class Split {\n constructor(explicit = {}, implicit = {}) {\n this.explicit = explicit;\n this.implicit = implicit;\n }\n clone() {\n return new Split(duplicate(this.explicit), duplicate(this.implicit));\n }\n combine() {\n return Object.assign(Object.assign({}, this.explicit), this.implicit);\n }\n get(key) {\n // Explicit has higher precedence\n return getFirstDefined(this.explicit[key], this.implicit[key]);\n }\n getWithExplicit(key) {\n // Explicit has higher precedence\n if (this.explicit[key] !== undefined) {\n return { explicit: true, value: this.explicit[key] };\n }\n else if (this.implicit[key] !== undefined) {\n return { explicit: false, value: this.implicit[key] };\n }\n return { explicit: false, value: undefined };\n }\n setWithExplicit(key, { value, explicit }) {\n if (value !== undefined) {\n this.set(key, value, explicit);\n }\n }\n set(key, value, explicit) {\n delete this[explicit ? 'implicit' : 'explicit'][key];\n this[explicit ? 'explicit' : 'implicit'][key] = value;\n return this;\n }\n copyKeyFromSplit(key, { explicit, implicit }) {\n // Explicit has higher precedence\n if (explicit[key] !== undefined) {\n this.set(key, explicit[key], true);\n }\n else if (implicit[key] !== undefined) {\n this.set(key, implicit[key], false);\n }\n }\n copyKeyFromObject(key, s) {\n // Explicit has higher precedence\n if (s[key] !== undefined) {\n this.set(key, s[key], true);\n }\n }\n /**\n * Merge split object into this split object. Properties from the other split\n * overwrite properties from this split.\n */\n copyAll(other) {\n for (const key of keys(other.combine())) {\n const val = other.getWithExplicit(key);\n this.setWithExplicit(key, val);\n }\n }\n}\nexport function makeExplicit(value) {\n return {\n explicit: true,\n value\n };\n}\nexport function makeImplicit(value) {\n return {\n explicit: false,\n value\n };\n}\nexport function tieBreakByComparing(compare) {\n return (v1, v2, property, propertyOf) => {\n const diff = compare(v1.value, v2.value);\n if (diff > 0) {\n return v1;\n }\n else if (diff < 0) {\n return v2;\n }\n return defaultTieBreaker(v1, v2, property, propertyOf);\n };\n}\nexport function defaultTieBreaker(v1, v2, property, propertyOf) {\n if (v1.explicit && v2.explicit) {\n log.warn(log.message.mergeConflictingProperty(property, propertyOf, v1.value, v2.value));\n }\n // If equal score, prefer v1.\n return v1;\n}\nexport function mergeValuesWithExplicit(v1, v2, property, propertyOf, tieBreaker = defaultTieBreaker) {\n if (v1 === undefined || v1.value === undefined) {\n // For first run\n return v2;\n }\n if (v1.explicit && !v2.explicit) {\n return v1;\n }\n else if (v2.explicit && !v1.explicit) {\n return v2;\n }\n else if (deepEqual(v1.value, v2.value)) {\n return v1;\n }\n else {\n return tieBreaker(v1, v2, property, propertyOf);\n }\n}\n//# sourceMappingURL=split.js.map","import { Split } from '../split';\n/**\n * Class to track interesting properties (see https://15721.courses.cs.cmu.edu/spring2016/papers/graefe-ieee1995.pdf)\n * about how fields have been parsed or whether they have been derived in a transform. We use this to not parse the\n * same field again (or differently).\n */\nexport class AncestorParse extends Split {\n constructor(explicit = {}, implicit = {}, parseNothing = false) {\n super(explicit, implicit);\n this.explicit = explicit;\n this.implicit = implicit;\n this.parseNothing = parseNothing;\n }\n clone() {\n const clone = super.clone();\n clone.parseNothing = this.parseNothing;\n return clone;\n }\n}\n//# sourceMappingURL=index.js.map","export function isUrlData(data) {\n return 'url' in data;\n}\nexport function isInlineData(data) {\n return 'values' in data;\n}\nexport function isNamedData(data) {\n return 'name' in data && !isUrlData(data) && !isInlineData(data) && !isGenerator(data);\n}\nexport function isGenerator(data) {\n return data && (isSequenceGenerator(data) || isSphereGenerator(data) || isGraticuleGenerator(data));\n}\nexport function isSequenceGenerator(data) {\n return 'sequence' in data;\n}\nexport function isSphereGenerator(data) {\n return 'sphere' in data;\n}\nexport function isGraticuleGenerator(data) {\n return 'graticule' in data;\n}\nexport var DataSourceType;\n(function (DataSourceType) {\n DataSourceType[DataSourceType[\"Raw\"] = 0] = \"Raw\";\n DataSourceType[DataSourceType[\"Main\"] = 1] = \"Main\";\n DataSourceType[DataSourceType[\"Row\"] = 2] = \"Row\";\n DataSourceType[DataSourceType[\"Column\"] = 3] = \"Column\";\n DataSourceType[DataSourceType[\"Lookup\"] = 4] = \"Lookup\";\n})(DataSourceType || (DataSourceType = {}));\n//# sourceMappingURL=data.js.map","const VIEW = 'view',\n LBRACK = '[',\n RBRACK = ']',\n LBRACE = '{',\n RBRACE = '}',\n COLON = ':',\n COMMA = ',',\n NAME = '@',\n GT = '>',\n ILLEGAL = /[[\\]{}]/,\n DEFAULT_MARKS = {\n '*': 1,\n arc: 1,\n area: 1,\n group: 1,\n image: 1,\n line: 1,\n path: 1,\n rect: 1,\n rule: 1,\n shape: 1,\n symbol: 1,\n text: 1,\n trail: 1\n};\nlet DEFAULT_SOURCE, MARKS;\n/**\n * Parse an event selector string.\n * Returns an array of event stream definitions.\n */\n\nfunction eventSelector (selector, source, marks) {\n DEFAULT_SOURCE = source || VIEW;\n MARKS = marks || DEFAULT_MARKS;\n return parseMerge(selector.trim()).map(parseSelector);\n}\n\nfunction isMarkType(type) {\n return MARKS[type];\n}\n\nfunction find(s, i, endChar, pushChar, popChar) {\n const n = s.length;\n let count = 0,\n c;\n\n for (; i < n; ++i) {\n c = s[i];\n if (!count && c === endChar) return i;else if (popChar && popChar.indexOf(c) >= 0) --count;else if (pushChar && pushChar.indexOf(c) >= 0) ++count;\n }\n\n return i;\n}\n\nfunction parseMerge(s) {\n const output = [],\n n = s.length;\n let start = 0,\n i = 0;\n\n while (i < n) {\n i = find(s, i, COMMA, LBRACK + LBRACE, RBRACK + RBRACE);\n output.push(s.substring(start, i).trim());\n start = ++i;\n }\n\n if (output.length === 0) {\n throw 'Empty event selector: ' + s;\n }\n\n return output;\n}\n\nfunction parseSelector(s) {\n return s[0] === '[' ? parseBetween(s) : parseStream(s);\n}\n\nfunction parseBetween(s) {\n const n = s.length;\n let i = 1,\n b;\n i = find(s, i, RBRACK, LBRACK, RBRACK);\n\n if (i === n) {\n throw 'Empty between selector: ' + s;\n }\n\n b = parseMerge(s.substring(1, i));\n\n if (b.length !== 2) {\n throw 'Between selector must have two elements: ' + s;\n }\n\n s = s.slice(i + 1).trim();\n\n if (s[0] !== GT) {\n throw 'Expected \\'>\\' after between selector: ' + s;\n }\n\n b = b.map(parseSelector);\n const stream = parseSelector(s.slice(1).trim());\n\n if (stream.between) {\n return {\n between: b,\n stream: stream\n };\n } else {\n stream.between = b;\n }\n\n return stream;\n}\n\nfunction parseStream(s) {\n const stream = {\n source: DEFAULT_SOURCE\n },\n source = [];\n let throttle = [0, 0],\n markname = 0,\n start = 0,\n n = s.length,\n i = 0,\n j,\n filter; // extract throttle from end\n\n if (s[n - 1] === RBRACE) {\n i = s.lastIndexOf(LBRACE);\n\n if (i >= 0) {\n try {\n throttle = parseThrottle(s.substring(i + 1, n - 1));\n } catch (e) {\n throw 'Invalid throttle specification: ' + s;\n }\n\n s = s.slice(0, i).trim();\n n = s.length;\n } else throw 'Unmatched right brace: ' + s;\n\n i = 0;\n }\n\n if (!n) throw s; // set name flag based on first char\n\n if (s[0] === NAME) markname = ++i; // extract first part of multi-part stream selector\n\n j = find(s, i, COLON);\n\n if (j < n) {\n source.push(s.substring(start, j).trim());\n start = i = ++j;\n } // extract remaining part of stream selector\n\n\n i = find(s, i, LBRACK);\n\n if (i === n) {\n source.push(s.substring(start, n).trim());\n } else {\n source.push(s.substring(start, i).trim());\n filter = [];\n start = ++i;\n if (start === n) throw 'Unmatched left bracket: ' + s;\n } // extract filters\n\n\n while (i < n) {\n i = find(s, i, RBRACK);\n if (i === n) throw 'Unmatched left bracket: ' + s;\n filter.push(s.substring(start, i).trim());\n if (i < n - 1 && s[++i] !== LBRACK) throw 'Expected left bracket: ' + s;\n start = ++i;\n } // marshall event stream specification\n\n\n if (!(n = source.length) || ILLEGAL.test(source[n - 1])) {\n throw 'Invalid event selector: ' + s;\n }\n\n if (n > 1) {\n stream.type = source[1];\n\n if (markname) {\n stream.markname = source[0].slice(1);\n } else if (isMarkType(source[0])) {\n stream.marktype = source[0];\n } else {\n stream.source = source[0];\n }\n } else {\n stream.type = source[0];\n }\n\n if (stream.type.slice(-1) === '!') {\n stream.consume = true;\n stream.type = stream.type.slice(0, -1);\n }\n\n if (filter != null) stream.filter = filter;\n if (throttle[0]) stream.throttle = throttle[0];\n if (throttle[1]) stream.debounce = throttle[1];\n return stream;\n}\n\nfunction parseThrottle(s) {\n const a = s.split(COMMA);\n if (!s.length || a.length > 2) throw s;\n return a.map(_ => {\n const x = +_;\n if (x !== x) throw s;\n return x;\n });\n}\n\nexport { eventSelector as selector };\n","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { selector as parseSelector } from 'vega-event-selector';\nimport { identity, isArray, stringValue } from 'vega-util';\nimport { MODIFY, STORE, unitName, VL_SELECTION_RESOLVE, TUPLE, selectionCompilers } from '.';\nimport { dateTimeToExpr, isDateTime, dateTimeToTimestamp } from '../../datetime';\nimport { hasContinuousDomain } from '../../scale';\nimport { keys, stringify, vals } from '../../util';\nimport { isUnitModel } from '../model';\nimport { parseSelectionExtent } from './parse';\nexport function assembleInit(init, isExpr = true, wrap = identity) {\n if (isArray(init)) {\n const assembled = init.map(v => assembleInit(v, isExpr, wrap));\n return isExpr ? `[${assembled.join(', ')}]` : assembled;\n }\n else if (isDateTime(init)) {\n if (isExpr) {\n return wrap(dateTimeToExpr(init));\n }\n else {\n return wrap(dateTimeToTimestamp(init));\n }\n }\n return isExpr ? wrap(stringify(init)) : init;\n}\nexport function assembleUnitSelectionSignals(model, signals) {\n var _a;\n for (const selCmpt of vals((_a = model.component.selection) !== null && _a !== void 0 ? _a : {})) {\n const name = selCmpt.name;\n let modifyExpr = `${name}${TUPLE}, ${selCmpt.resolve === 'global' ? 'true' : `{unit: ${unitName(model)}}`}`;\n for (const c of selectionCompilers) {\n if (!c.defined(selCmpt))\n continue;\n if (c.signals)\n signals = c.signals(model, selCmpt, signals);\n if (c.modifyExpr)\n modifyExpr = c.modifyExpr(model, selCmpt, modifyExpr);\n }\n signals.push({\n name: name + MODIFY,\n on: [\n {\n events: { signal: selCmpt.name + TUPLE },\n update: `modify(${stringValue(selCmpt.name + STORE)}, ${modifyExpr})`\n }\n ]\n });\n }\n return cleanupEmptyOnArray(signals);\n}\nexport function assembleFacetSignals(model, signals) {\n if (model.component.selection && keys(model.component.selection).length) {\n const name = stringValue(model.getName('cell'));\n signals.unshift({\n name: 'facet',\n value: {},\n on: [\n {\n events: parseSelector('mousemove', 'scope'),\n update: `isTuple(facet) ? facet : group(${name}).datum`\n }\n ]\n });\n }\n return cleanupEmptyOnArray(signals);\n}\nexport function assembleTopLevelSignals(model, signals) {\n var _a;\n let hasSelections = false;\n for (const selCmpt of vals((_a = model.component.selection) !== null && _a !== void 0 ? _a : {})) {\n const name = selCmpt.name;\n const store = stringValue(name + STORE);\n const hasSg = signals.filter(s => s.name === name);\n if (hasSg.length === 0) {\n const resolve = selCmpt.resolve === 'global' ? 'union' : selCmpt.resolve;\n const isPoint = selCmpt.type === 'point' ? ', true, true)' : ')';\n signals.push({\n name: selCmpt.name,\n update: `${VL_SELECTION_RESOLVE}(${store}, ${stringValue(resolve)}${isPoint}`\n });\n }\n hasSelections = true;\n for (const c of selectionCompilers) {\n if (c.defined(selCmpt) && c.topLevelSignals) {\n signals = c.topLevelSignals(model, selCmpt, signals);\n }\n }\n }\n if (hasSelections) {\n const hasUnit = signals.filter(s => s.name === 'unit');\n if (hasUnit.length === 0) {\n signals.unshift({\n name: 'unit',\n value: {},\n on: [{ events: 'mousemove', update: 'isTuple(group()) ? group() : unit' }]\n });\n }\n }\n return cleanupEmptyOnArray(signals);\n}\nexport function assembleUnitSelectionData(model, data) {\n var _a;\n const dataCopy = [...data];\n for (const selCmpt of vals((_a = model.component.selection) !== null && _a !== void 0 ? _a : {})) {\n const init = { name: selCmpt.name + STORE };\n if (selCmpt.init) {\n const fields = selCmpt.project.items.map(proj => {\n const { signals } = proj, rest = __rest(proj, [\"signals\"]);\n return rest;\n });\n init.values = selCmpt.init.map(i => ({\n unit: unitName(model, { escape: false }),\n fields,\n values: assembleInit(i, false)\n }));\n }\n const contains = dataCopy.filter(d => d.name === selCmpt.name + STORE);\n if (!contains.length) {\n dataCopy.push(init);\n }\n }\n return dataCopy;\n}\nexport function assembleUnitSelectionMarks(model, marks) {\n var _a;\n for (const selCmpt of vals((_a = model.component.selection) !== null && _a !== void 0 ? _a : {})) {\n for (const c of selectionCompilers) {\n if (c.defined(selCmpt) && c.marks) {\n marks = c.marks(model, selCmpt, marks);\n }\n }\n }\n return marks;\n}\nexport function assembleLayerSelectionMarks(model, marks) {\n for (const child of model.children) {\n if (isUnitModel(child)) {\n marks = assembleUnitSelectionMarks(child, marks);\n }\n }\n return marks;\n}\nexport function assembleSelectionScaleDomain(model, extent, scaleCmpt, domain) {\n const parsedExtent = parseSelectionExtent(model, extent.param, extent);\n return {\n signal: hasContinuousDomain(scaleCmpt.get('type')) && isArray(domain) && domain[0] > domain[1]\n ? `isValid(${parsedExtent}) && reverse(${parsedExtent})`\n : parsedExtent\n };\n}\nfunction cleanupEmptyOnArray(signals) {\n return signals.map(s => {\n if (s.on && !s.on.length)\n delete s.on;\n return s;\n });\n}\n//# sourceMappingURL=assemble.js.map","import * as log from '../../log';\nimport { uniqueId } from '../../util';\n/**\n * A node in the dataflow tree.\n */\nexport class DataFlowNode {\n constructor(parent, debugName) {\n this.debugName = debugName;\n this._children = [];\n this._parent = null;\n if (parent) {\n this.parent = parent;\n }\n }\n /**\n * Clone this node with a deep copy but don't clone links to children or parents.\n */\n clone() {\n throw new Error('Cannot clone node');\n }\n get parent() {\n return this._parent;\n }\n /**\n * Set the parent of the node and also add this node to the parent's children.\n */\n set parent(parent) {\n this._parent = parent;\n if (parent) {\n parent.addChild(this);\n }\n }\n get children() {\n return this._children;\n }\n numChildren() {\n return this._children.length;\n }\n addChild(child, loc) {\n // do not add the same child twice\n if (this._children.includes(child)) {\n log.warn(log.message.ADD_SAME_CHILD_TWICE);\n return;\n }\n if (loc !== undefined) {\n this._children.splice(loc, 0, child);\n }\n else {\n this._children.push(child);\n }\n }\n removeChild(oldChild) {\n const loc = this._children.indexOf(oldChild);\n this._children.splice(loc, 1);\n return loc;\n }\n /**\n * Remove node from the dataflow.\n */\n remove() {\n let loc = this._parent.removeChild(this);\n for (const child of this._children) {\n // do not use the set method because we want to insert at a particular location\n child._parent = this._parent;\n this._parent.addChild(child, loc++);\n }\n }\n /**\n * Insert another node as a parent of this node.\n */\n insertAsParentOf(other) {\n const parent = other.parent;\n parent.removeChild(this);\n this.parent = parent;\n other.parent = this;\n }\n swapWithParent() {\n const parent = this._parent;\n const newParent = parent.parent;\n // reconnect the children\n for (const child of this._children) {\n child.parent = parent;\n }\n // remove old links\n this._children = []; // equivalent to removing every child link one by one\n parent.removeChild(this);\n parent.parent.removeChild(parent);\n // swap two nodes\n this.parent = newParent;\n parent.parent = this;\n }\n}\nexport class OutputNode extends DataFlowNode {\n /**\n * @param source The name of the source. Will change in assemble.\n * @param type The type of the output node.\n * @param refCounts A global ref counter map.\n */\n constructor(parent, source, type, refCounts) {\n super(parent, source);\n this.type = type;\n this.refCounts = refCounts;\n this._source = this._name = source;\n if (this.refCounts && !(this._name in this.refCounts)) {\n this.refCounts[this._name] = 0;\n }\n }\n clone() {\n const cloneObj = new this.constructor();\n cloneObj.debugName = `clone_${this.debugName}`;\n cloneObj._source = this._source;\n cloneObj._name = `clone_${this._name}`;\n cloneObj.type = this.type;\n cloneObj.refCounts = this.refCounts;\n cloneObj.refCounts[cloneObj._name] = 0;\n return cloneObj;\n }\n dependentFields() {\n return new Set();\n }\n producedFields() {\n return new Set();\n }\n hash() {\n if (this._hash === undefined) {\n this._hash = `Output ${uniqueId()}`;\n }\n return this._hash;\n }\n /**\n * Request the datasource name and increase the ref counter.\n *\n * During the parsing phase, this will return the simple name such as 'main' or 'raw'.\n * It is crucial to request the name from an output node to mark it as a required node.\n * If nobody ever requests the name, this datasource will not be instantiated in the assemble phase.\n *\n * In the assemble phase, this will return the correct name.\n */\n getSource() {\n this.refCounts[this._name]++;\n return this._source;\n }\n isRequired() {\n return !!this.refCounts[this._name];\n }\n setSource(source) {\n this._source = source;\n }\n}\n//# sourceMappingURL=dataflow.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { vgField } from '../../channeldef';\nimport { getTimeUnitParts, normalizeTimeUnit } from '../../timeunit';\nimport { duplicate, entries, hash, isEmpty, replacePathInField, vals } from '../../util';\nimport { DataFlowNode } from './dataflow';\nexport class TimeUnitNode extends DataFlowNode {\n constructor(parent, formula) {\n super(parent);\n this.formula = formula;\n }\n clone() {\n return new TimeUnitNode(null, duplicate(this.formula));\n }\n static makeFromEncoding(parent, model) {\n const formula = model.reduceFieldDef((timeUnitComponent, fieldDef) => {\n const { field, timeUnit } = fieldDef;\n if (timeUnit) {\n const as = vgField(fieldDef, { forAs: true });\n timeUnitComponent[hash({\n as,\n field,\n timeUnit\n })] = {\n as,\n field,\n timeUnit\n };\n }\n return timeUnitComponent;\n }, {});\n if (isEmpty(formula)) {\n return null;\n }\n return new TimeUnitNode(parent, formula);\n }\n static makeFromTransform(parent, t) {\n const _a = Object.assign({}, t), { timeUnit } = _a, other = __rest(_a, [\"timeUnit\"]);\n const normalizedTimeUnit = normalizeTimeUnit(timeUnit);\n const component = Object.assign(Object.assign({}, other), { timeUnit: normalizedTimeUnit });\n return new TimeUnitNode(parent, {\n [hash(component)]: component\n });\n }\n /**\n * Merge together TimeUnitNodes assigning the children of `other` to `this`\n * and removing `other`.\n */\n merge(other) {\n this.formula = Object.assign({}, this.formula);\n // if the same hash happen twice, merge\n for (const key in other.formula) {\n if (!this.formula[key]) {\n // copy if it's not a duplicate\n this.formula[key] = other.formula[key];\n }\n }\n for (const child of other.children) {\n other.removeChild(child);\n child.parent = this;\n }\n other.remove();\n }\n /**\n * Remove time units coming from the other node.\n */\n removeFormulas(fields) {\n const newFormula = {};\n for (const [key, timeUnit] of entries(this.formula)) {\n if (!fields.has(timeUnit.as)) {\n newFormula[key] = timeUnit;\n }\n }\n this.formula = newFormula;\n }\n producedFields() {\n return new Set(vals(this.formula).map(f => f.as));\n }\n dependentFields() {\n return new Set(vals(this.formula).map(f => f.field));\n }\n hash() {\n return `TimeUnit ${hash(this.formula)}`;\n }\n assemble() {\n const transforms = [];\n for (const f of vals(this.formula)) {\n const { field, as, timeUnit } = f;\n const _a = normalizeTimeUnit(timeUnit), { unit, utc } = _a, params = __rest(_a, [\"unit\", \"utc\"]);\n transforms.push(Object.assign(Object.assign(Object.assign(Object.assign({ field: replacePathInField(field), type: 'timeunit' }, (unit ? { units: getTimeUnitParts(unit) } : {})), (utc ? { timezone: 'utc' } : {})), params), { as: [as, `${as}_end`] }));\n }\n return transforms;\n }\n}\n//# sourceMappingURL=timeunit.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { array, isObject } from 'vega-util';\nimport { isSingleDefUnitChannel } from '../../channel';\nimport * as log from '../../log';\nimport { hasContinuousDomain } from '../../scale';\nimport { hash, keys, replacePathInField, varName, isEmpty } from '../../util';\nimport { TimeUnitNode } from '../data/timeunit';\nexport const TUPLE_FIELDS = '_tuple_fields';\nexport class SelectionProjectionComponent {\n constructor(...items) {\n this.items = items;\n this.hasChannel = {};\n this.hasField = {};\n }\n}\nconst project = {\n defined: () => {\n return true; // This transform handles its own defaults, so always run parse.\n },\n parse: (model, selCmpt, selDef) => {\n var _a;\n const name = selCmpt.name;\n const proj = ((_a = selCmpt.project) !== null && _a !== void 0 ? _a : (selCmpt.project = new SelectionProjectionComponent()));\n const parsed = {};\n const timeUnits = {};\n const signals = new Set();\n const signalName = (p, range) => {\n const suffix = range === 'visual' ? p.channel : p.field;\n let sg = varName(`${name}_${suffix}`);\n for (let counter = 1; signals.has(sg); counter++) {\n sg = varName(`${name}_${suffix}_${counter}`);\n }\n signals.add(sg);\n return { [range]: sg };\n };\n const type = selCmpt.type;\n const cfg = model.config.selection[type];\n const init = selDef.value !== undefined\n ? array(selDef.value)\n : null;\n // If no explicit projection (either fields or encodings) is specified, set some defaults.\n // If an initial value is set, try to infer projections.\n let { fields, encodings } = (isObject(selDef.select) ? selDef.select : {});\n if (!fields && !encodings && init) {\n for (const initVal of init) {\n // initVal may be a scalar value to smoothen varParam -> pointSelection gradient.\n if (!isObject(initVal)) {\n continue;\n }\n for (const key of keys(initVal)) {\n if (isSingleDefUnitChannel(key)) {\n (encodings || (encodings = [])).push(key);\n }\n else {\n if (type === 'interval') {\n log.warn(log.message.INTERVAL_INITIALIZED_WITH_X_Y);\n encodings = cfg.encodings;\n }\n else {\n (fields || (fields = [])).push(key);\n }\n }\n }\n }\n }\n // If no initial value is specified, use the default configuration.\n // We break this out as a separate if block (instead of an else condition)\n // to account for unprojected point selections that have scalar initial values\n if (!fields && !encodings) {\n encodings = cfg.encodings;\n if ('fields' in cfg) {\n fields = cfg.fields;\n }\n }\n for (const channel of encodings !== null && encodings !== void 0 ? encodings : []) {\n const fieldDef = model.fieldDef(channel);\n if (fieldDef) {\n let field = fieldDef.field;\n if (fieldDef.aggregate) {\n log.warn(log.message.cannotProjectAggregate(channel, fieldDef.aggregate));\n continue;\n }\n else if (!field) {\n log.warn(log.message.cannotProjectOnChannelWithoutField(channel));\n continue;\n }\n if (fieldDef.timeUnit) {\n field = model.vgField(channel);\n // Construct TimeUnitComponents which will be combined into a\n // TimeUnitNode. This node may need to be inserted into the\n // dataflow if the selection is used across views that do not\n // have these time units defined.\n const component = {\n timeUnit: fieldDef.timeUnit,\n as: field,\n field: fieldDef.field\n };\n timeUnits[hash(component)] = component;\n }\n // Prevent duplicate projections on the same field.\n // TODO: what if the same field is bound to multiple channels (e.g., SPLOM diag).\n if (!parsed[field]) {\n // Determine whether the tuple will store enumerated or ranged values.\n // Interval selections store ranges for continuous scales, and enumerations otherwise.\n // Single/multi selections store ranges for binned fields, and enumerations otherwise.\n let tplType = 'E';\n if (type === 'interval') {\n const scaleType = model.getScaleComponent(channel).get('type');\n if (hasContinuousDomain(scaleType)) {\n tplType = 'R';\n }\n }\n else if (fieldDef.bin) {\n tplType = 'R-RE';\n }\n const p = { field, channel, type: tplType };\n p.signals = Object.assign(Object.assign({}, signalName(p, 'data')), signalName(p, 'visual'));\n proj.items.push((parsed[field] = p));\n proj.hasField[field] = proj.hasChannel[channel] = parsed[field];\n }\n }\n else {\n log.warn(log.message.cannotProjectOnChannelWithoutField(channel));\n }\n }\n for (const field of fields !== null && fields !== void 0 ? fields : []) {\n if (proj.hasField[field])\n continue;\n const p = { type: 'E', field };\n p.signals = Object.assign({}, signalName(p, 'data'));\n proj.items.push(p);\n proj.hasField[field] = p;\n }\n if (init) {\n selCmpt.init = init.map((v) => {\n // Selections can be initialized either with a full object that maps projections to values\n // or scalar values to smoothen the abstraction gradient from variable params to point selections.\n return proj.items.map(p => (isObject(v) ? (v[p.channel] !== undefined ? v[p.channel] : v[p.field]) : v));\n });\n }\n if (!isEmpty(timeUnits)) {\n proj.timeUnit = new TimeUnitNode(null, timeUnits);\n }\n },\n signals: (model, selCmpt, allSignals) => {\n const name = selCmpt.name + TUPLE_FIELDS;\n const hasSignal = allSignals.filter(s => s.name === name);\n return hasSignal.length > 0\n ? allSignals\n : allSignals.concat({\n name,\n value: selCmpt.project.items.map(proj => {\n const { signals, hasLegend } = proj, rest = __rest(proj, [\"signals\", \"hasLegend\"]);\n rest.field = replacePathInField(rest.field);\n return rest;\n })\n });\n }\n};\nexport default project;\n//# sourceMappingURL=project.js.map","import { stringValue } from 'vega-util';\nimport { VL_SELECTION_RESOLVE } from '.';\nimport { isScaleChannel } from '../../channel';\nimport * as log from '../../log';\nimport { hasContinuousDomain } from '../../scale';\nimport { isLayerModel } from '../model';\nimport { replacePathInField } from '../../util';\nconst scaleBindings = {\n defined: selCmpt => {\n return selCmpt.type === 'interval' && selCmpt.resolve === 'global' && selCmpt.bind && selCmpt.bind === 'scales';\n },\n parse: (model, selCmpt) => {\n const bound = (selCmpt.scales = []);\n for (const proj of selCmpt.project.items) {\n const channel = proj.channel;\n if (!isScaleChannel(channel)) {\n continue;\n }\n const scale = model.getScaleComponent(channel);\n const scaleType = scale ? scale.get('type') : undefined;\n if (!scale || !hasContinuousDomain(scaleType)) {\n log.warn(log.message.SCALE_BINDINGS_CONTINUOUS);\n continue;\n }\n scale.set('selectionExtent', { param: selCmpt.name, field: proj.field }, true);\n bound.push(proj);\n }\n },\n topLevelSignals: (model, selCmpt, signals) => {\n const bound = selCmpt.scales.filter(proj => signals.filter(s => s.name === proj.signals.data).length === 0);\n // Top-level signals are only needed for multiview displays and if this\n // view's top-level signals haven't already been generated.\n if (!model.parent || isTopLevelLayer(model) || bound.length === 0) {\n return signals;\n }\n // vlSelectionResolve does not account for the behavior of bound scales in\n // multiview displays. Each unit view adds a tuple to the store, but the\n // state of the selection is the unit selection most recently updated. This\n // state is captured by the top-level signals that we insert and \"push\n // outer\" to from within the units. We need to reassemble this state into\n // the top-level named signal, except no single selCmpt has a global view.\n const namedSg = signals.filter(s => s.name === selCmpt.name)[0];\n let update = namedSg.update;\n if (update.indexOf(VL_SELECTION_RESOLVE) >= 0) {\n namedSg.update = `{${bound\n .map(proj => `${stringValue(replacePathInField(proj.field))}: ${proj.signals.data}`)\n .join(', ')}}`;\n }\n else {\n for (const proj of bound) {\n const mapping = `${stringValue(replacePathInField(proj.field))}: ${proj.signals.data}`;\n if (!update.includes(mapping)) {\n update = `${update.substring(0, update.length - 1)}, ${mapping}}`;\n }\n }\n namedSg.update = update;\n }\n return signals.concat(bound.map(proj => ({ name: proj.signals.data })));\n },\n signals: (model, selCmpt, signals) => {\n // Nested signals need only push to top-level signals with multiview displays.\n if (model.parent && !isTopLevelLayer(model)) {\n for (const proj of selCmpt.scales) {\n const signal = signals.filter(s => s.name === proj.signals.data)[0];\n signal.push = 'outer';\n delete signal.value;\n delete signal.update;\n }\n }\n return signals;\n }\n};\nexport default scaleBindings;\nexport function domain(model, channel) {\n const scale = stringValue(model.scaleName(channel));\n return `domain(${scale})`;\n}\nfunction isTopLevelLayer(model) {\n var _a;\n return model.parent && isLayerModel(model.parent) && ((_a = !model.parent.parent) !== null && _a !== void 0 ? _a : isTopLevelLayer(model.parent.parent));\n}\n//# sourceMappingURL=scales.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { array, stringValue } from 'vega-util';\nimport { STORE, TUPLE, unitName } from '.';\nimport { X, Y } from '../../channel';\nimport { warn } from '../../log';\nimport { hasContinuousDomain } from '../../scale';\nimport { keys } from '../../util';\nimport { assembleInit } from './assemble';\nimport { TUPLE_FIELDS } from './project';\nimport scales from './scales';\nexport const BRUSH = '_brush';\nexport const SCALE_TRIGGER = '_scale_trigger';\nconst interval = {\n defined: selCmpt => selCmpt.type === 'interval',\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const fieldsSg = name + TUPLE_FIELDS;\n const hasScales = scales.defined(selCmpt);\n const init = selCmpt.init ? selCmpt.init[0] : null;\n const dataSignals = [];\n const scaleTriggers = [];\n if (selCmpt.translate && !hasScales) {\n const filterExpr = `!event.item || event.item.mark.name !== ${stringValue(name + BRUSH)}`;\n events(selCmpt, (on, evt) => {\n var _a;\n var _b;\n const filters = array(((_a = (_b = evt.between[0]).filter) !== null && _a !== void 0 ? _a : (_b.filter = [])));\n if (!filters.includes(filterExpr)) {\n filters.push(filterExpr);\n }\n return on;\n });\n }\n selCmpt.project.items.forEach((proj, i) => {\n const channel = proj.channel;\n if (channel !== X && channel !== Y) {\n warn('Interval selections only support x and y encoding channels.');\n return;\n }\n const val = init ? init[i] : null;\n const cs = channelSignals(model, selCmpt, proj, val);\n const dname = proj.signals.data;\n const vname = proj.signals.visual;\n const scaleName = stringValue(model.scaleName(channel));\n const scaleType = model.getScaleComponent(channel).get('type');\n const toNum = hasContinuousDomain(scaleType) ? '+' : '';\n signals.push(...cs);\n dataSignals.push(dname);\n scaleTriggers.push({\n scaleName: model.scaleName(channel),\n expr: `(!isArray(${dname}) || ` +\n `(${toNum}invert(${scaleName}, ${vname})[0] === ${toNum}${dname}[0] && ` +\n `${toNum}invert(${scaleName}, ${vname})[1] === ${toNum}${dname}[1]))`\n });\n });\n // Proxy scale reactions to ensure that an infinite loop doesn't occur\n // when an interval selection filter touches the scale.\n if (!hasScales && scaleTriggers.length) {\n signals.push({\n name: name + SCALE_TRIGGER,\n value: {},\n on: [\n {\n events: scaleTriggers.map(t => ({ scale: t.scaleName })),\n update: `${scaleTriggers.map(t => t.expr).join(' && ')} ? ${name + SCALE_TRIGGER} : {}`\n }\n ]\n });\n }\n // Only add an interval to the store if it has valid data extents. Data extents\n // are set to null if pixel extents are equal to account for intervals over\n // ordinal/nominal domains which, when inverted, will still produce a valid datum.\n const update = `unit: ${unitName(model)}, fields: ${fieldsSg}, values`;\n return signals.concat(Object.assign(Object.assign({ name: name + TUPLE }, (init ? { init: `{${update}: ${assembleInit(init)}}` } : {})), (dataSignals.length\n ? {\n on: [\n {\n events: [{ signal: dataSignals.join(' || ') }],\n update: `${dataSignals.join(' && ')} ? {${update}: [${dataSignals}]} : null`\n }\n ]\n }\n : {})));\n },\n marks: (model, selCmpt, marks) => {\n const name = selCmpt.name;\n const { x, y } = selCmpt.project.hasChannel;\n const xvname = x && x.signals.visual;\n const yvname = y && y.signals.visual;\n const store = `data(${stringValue(selCmpt.name + STORE)})`;\n // Do not add a brush if we're binding to scales\n // or we don't have a valid interval projection\n if (scales.defined(selCmpt) || (!x && !y)) {\n return marks;\n }\n const update = {\n x: x !== undefined ? { signal: `${xvname}[0]` } : { value: 0 },\n y: y !== undefined ? { signal: `${yvname}[0]` } : { value: 0 },\n x2: x !== undefined ? { signal: `${xvname}[1]` } : { field: { group: 'width' } },\n y2: y !== undefined ? { signal: `${yvname}[1]` } : { field: { group: 'height' } }\n };\n // If the selection is resolved to global, only a single interval is in\n // the store. Wrap brush mark's encodings with a production rule to test\n // this based on the `unit` property. Hide the brush mark if it corresponds\n // to a unit different from the one in the store.\n if (selCmpt.resolve === 'global') {\n for (const key of keys(update)) {\n update[key] = [\n Object.assign({ test: `${store}.length && ${store}[0].unit === ${unitName(model)}` }, update[key]),\n { value: 0 }\n ];\n }\n }\n // Two brush marks ensure that fill colors and other aesthetic choices do\n // not interefere with the core marks, but that the brushed region can still\n // be interacted with (e.g., dragging it around).\n const _a = selCmpt.mark, { fill, fillOpacity, cursor } = _a, stroke = __rest(_a, [\"fill\", \"fillOpacity\", \"cursor\"]);\n const vgStroke = keys(stroke).reduce((def, k) => {\n def[k] = [\n {\n test: [x !== undefined && `${xvname}[0] !== ${xvname}[1]`, y !== undefined && `${yvname}[0] !== ${yvname}[1]`]\n .filter(t => t)\n .join(' && '),\n value: stroke[k]\n },\n { value: null }\n ];\n return def;\n }, {});\n return [\n {\n name: `${name + BRUSH}_bg`,\n type: 'rect',\n clip: true,\n encode: {\n enter: {\n fill: { value: fill },\n fillOpacity: { value: fillOpacity }\n },\n update: update\n }\n },\n ...marks,\n {\n name: name + BRUSH,\n type: 'rect',\n clip: true,\n encode: {\n enter: Object.assign(Object.assign({}, (cursor ? { cursor: { value: cursor } } : {})), { fill: { value: 'transparent' } }),\n update: Object.assign(Object.assign({}, update), vgStroke)\n }\n }\n ];\n }\n};\nexport default interval;\n/**\n * Returns the visual and data signals for an interval selection.\n */\nfunction channelSignals(model, selCmpt, proj, init) {\n const channel = proj.channel;\n const vname = proj.signals.visual;\n const dname = proj.signals.data;\n const hasScales = scales.defined(selCmpt);\n const scaleName = stringValue(model.scaleName(channel));\n const scale = model.getScaleComponent(channel);\n const scaleType = scale ? scale.get('type') : undefined;\n const scaled = (str) => `scale(${scaleName}, ${str})`;\n const size = model.getSizeSignalRef(channel === X ? 'width' : 'height').signal;\n const coord = `${channel}(unit)`;\n const on = events(selCmpt, (def, evt) => {\n return [\n ...def,\n { events: evt.between[0], update: `[${coord}, ${coord}]` },\n { events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]` } // Brush End\n ];\n });\n // React to pan/zooms of continuous scales. Non-continuous scales\n // (band, point) cannot be pan/zoomed and any other changes\n // to their domains (e.g., filtering) should clear the brushes.\n on.push({\n events: { signal: selCmpt.name + SCALE_TRIGGER },\n update: hasContinuousDomain(scaleType) ? `[${scaled(`${dname}[0]`)}, ${scaled(`${dname}[1]`)}]` : `[0, 0]`\n });\n return hasScales\n ? [{ name: dname, on: [] }]\n : [\n Object.assign(Object.assign({ name: vname }, (init ? { init: assembleInit(init, true, scaled) } : { value: [] })), { on: on }),\n Object.assign(Object.assign({ name: dname }, (init ? { init: assembleInit(init) } : {})), { on: [\n {\n events: { signal: vname },\n update: `${vname}[0] === ${vname}[1] ? null : invert(${scaleName}, ${vname})`\n }\n ] })\n ];\n}\nfunction events(selCmpt, cb) {\n return selCmpt.events.reduce((on, evt) => {\n if (!evt.between) {\n warn(`${evt} is not an ordered event stream for interval selections.`);\n return on;\n }\n return cb(on, evt);\n }, []);\n}\n//# sourceMappingURL=interval.js.map","import { stringValue } from 'vega-util';\nimport { TUPLE, unitName } from '.';\nimport { vals } from '../../util';\nimport { BRUSH } from './interval';\nimport { TUPLE_FIELDS } from './project';\nconst point = {\n defined: selCmpt => selCmpt.type === 'point',\n signals: (model, selCmpt, signals) => {\n var _a;\n const name = selCmpt.name;\n const fieldsSg = name + TUPLE_FIELDS;\n const project = selCmpt.project;\n const datum = '(item().isVoronoi ? datum.datum : datum)';\n const values = project.items\n .map(p => {\n const fieldDef = model.fieldDef(p.channel);\n // Binned fields should capture extents, for a range test against the raw field.\n return (fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.bin)\n ? `[${datum}[${stringValue(model.vgField(p.channel, {}))}], ` +\n `${datum}[${stringValue(model.vgField(p.channel, { binSuffix: 'end' }))}]]`\n : `${datum}[${stringValue(p.field)}]`;\n })\n .join(', ');\n // Only add a discrete selection to the store if a datum is present _and_\n // the interaction isn't occurring on a group mark. This guards against\n // polluting interactive state with invalid values in faceted displays\n // as the group marks are also data-driven. We force the update to account\n // for constant null states but varying toggles (e.g., shift-click in\n // whitespace followed by a click in whitespace; the store should only\n // be cleared on the second click).\n const update = `unit: ${unitName(model)}, fields: ${fieldsSg}, values`;\n const events = selCmpt.events;\n const brushes = vals((_a = model.component.selection) !== null && _a !== void 0 ? _a : {})\n .reduce((acc, cmpt) => {\n return cmpt.type === 'interval' ? acc.concat(cmpt.name + BRUSH) : acc;\n }, [])\n .map(b => `indexof(item().mark.name, '${b}') < 0`)\n .join(' && ');\n const test = `datum && item().mark.marktype !== 'group'` + (brushes ? ` && ${brushes}` : '');\n return signals.concat([\n {\n name: name + TUPLE,\n on: events\n ? [\n {\n events,\n update: `${test} ? {${update}: [${values}]} : null`,\n force: true\n }\n ]\n : []\n }\n ]);\n }\n};\nexport default point;\n//# sourceMappingURL=point.js.map","import { array } from 'vega-util';\nimport { isConditionalDef, isConditionalParameter } from '../../../channeldef';\nimport { expression } from '../../predicate';\nimport { parseSelectionPredicate } from '../../selection/parse';\n/**\n * Return a mixin that includes a Vega production rule for a Vega-Lite conditional channel definition\n * or a simple mixin if channel def has no condition.\n */\nexport function wrapCondition(model, channelDef, vgChannel, refFn) {\n const condition = isConditionalDef(channelDef) && channelDef.condition;\n const valueRef = refFn(channelDef);\n if (condition) {\n const conditions = array(condition);\n const vgConditions = conditions.map(c => {\n const conditionValueRef = refFn(c);\n if (isConditionalParameter(c)) {\n const { param, empty } = c;\n const test = parseSelectionPredicate(model, { param, empty });\n return Object.assign({ test }, conditionValueRef);\n }\n else {\n const test = expression(model, c.test); // FIXME: remove casting once TS is no longer dumb about it\n return Object.assign({ test }, conditionValueRef);\n }\n });\n return {\n [vgChannel]: [...vgConditions, ...(valueRef !== undefined ? [valueRef] : [])]\n };\n }\n else {\n return valueRef !== undefined ? { [vgChannel]: valueRef } : {};\n }\n}\n//# sourceMappingURL=conditional.js.map","import { getFormatMixins, isFieldOrDatumDef, isValueDef } from '../../../channeldef';\nimport { signalOrValueRef } from '../../common';\nimport { formatSignalRef } from '../../format';\nimport { wrapCondition } from './conditional';\nexport function text(model, channel = 'text') {\n const channelDef = model.encoding[channel];\n return wrapCondition(model, channelDef, channel, cDef => textRef(cDef, model.config));\n}\nexport function textRef(channelDef, config, expr = 'datum') {\n // text\n if (channelDef) {\n if (isValueDef(channelDef)) {\n return signalOrValueRef(channelDef.value);\n }\n if (isFieldOrDatumDef(channelDef)) {\n const { format, formatType } = getFormatMixins(channelDef);\n return formatSignalRef({ fieldOrDatumDef: channelDef, format, formatType, expr, config });\n }\n }\n return undefined;\n}\n//# sourceMappingURL=text.js.map","import { array, isArray, isObject, isString } from 'vega-util';\nimport { isBinned } from '../../../bin';\nimport { getMainRangeChannel, isXorY } from '../../../channel';\nimport { defaultTitle, getFieldDef, getFormatMixins, hasConditionalFieldDef, isFieldDef, isTypedFieldDef, vgField } from '../../../channeldef';\nimport { forEach } from '../../../encoding';\nimport { entries } from '../../../util';\nimport { isSignalRef } from '../../../vega.schema';\nimport { getMarkPropOrConfig } from '../../common';\nimport { binFormatExpression, formatSignalRef } from '../../format';\nimport { wrapCondition } from './conditional';\nimport { textRef } from './text';\nexport function tooltip(model, opt = {}) {\n const { encoding, markDef, config, stack } = model;\n const channelDef = encoding.tooltip;\n if (isArray(channelDef)) {\n return { tooltip: tooltipRefForEncoding({ tooltip: channelDef }, stack, config, opt) };\n }\n else {\n const datum = opt.reactiveGeom ? 'datum.datum' : 'datum';\n return wrapCondition(model, channelDef, 'tooltip', cDef => {\n // use valueRef based on channelDef first\n const tooltipRefFromChannelDef = textRef(cDef, config, datum);\n if (tooltipRefFromChannelDef) {\n return tooltipRefFromChannelDef;\n }\n if (cDef === null) {\n // Allow using encoding.tooltip = null to disable tooltip\n return undefined;\n }\n let markTooltip = getMarkPropOrConfig('tooltip', markDef, config);\n if (markTooltip === true) {\n markTooltip = { content: 'encoding' };\n }\n if (isString(markTooltip)) {\n return { value: markTooltip };\n }\n else if (isObject(markTooltip)) {\n // `tooltip` is `{fields: 'encodings' | 'fields'}`\n if (isSignalRef(markTooltip)) {\n return markTooltip;\n }\n else if (markTooltip.content === 'encoding') {\n return tooltipRefForEncoding(encoding, stack, config, opt);\n }\n else {\n return { signal: datum };\n }\n }\n return undefined;\n });\n }\n}\nexport function tooltipData(encoding, stack, config, { reactiveGeom } = {}) {\n const toSkip = {};\n const expr = reactiveGeom ? 'datum.datum' : 'datum';\n const tuples = [];\n function add(fDef, channel) {\n const mainChannel = getMainRangeChannel(channel);\n const fieldDef = isTypedFieldDef(fDef)\n ? fDef\n : Object.assign(Object.assign({}, fDef), { type: encoding[mainChannel].type // for secondary field def, copy type from main channel\n });\n const title = fieldDef.title || defaultTitle(fieldDef, config);\n const key = array(title).join(', ');\n let value;\n if (isXorY(channel)) {\n const channel2 = channel === 'x' ? 'x2' : 'y2';\n const fieldDef2 = getFieldDef(encoding[channel2]);\n if (isBinned(fieldDef.bin) && fieldDef2) {\n const startField = vgField(fieldDef, { expr });\n const endField = vgField(fieldDef2, { expr });\n const { format, formatType } = getFormatMixins(fieldDef);\n value = binFormatExpression(startField, endField, format, formatType, config);\n toSkip[channel2] = true;\n }\n else if (stack && stack.fieldChannel === channel && stack.offset === 'normalize') {\n const { format, formatType } = getFormatMixins(fieldDef);\n value = formatSignalRef({\n fieldOrDatumDef: fieldDef,\n format,\n formatType,\n expr,\n config,\n normalizeStack: true\n }).signal;\n }\n }\n value !== null && value !== void 0 ? value : (value = textRef(fieldDef, config, expr).signal);\n tuples.push({ channel, key, value });\n }\n forEach(encoding, (channelDef, channel) => {\n if (isFieldDef(channelDef)) {\n add(channelDef, channel);\n }\n else if (hasConditionalFieldDef(channelDef)) {\n add(channelDef.condition, channel);\n }\n });\n const out = {};\n for (const { channel, key, value } of tuples) {\n if (!toSkip[channel] && !out[key]) {\n out[key] = value;\n }\n }\n return out;\n}\nexport function tooltipRefForEncoding(encoding, stack, config, { reactiveGeom } = {}) {\n const data = tooltipData(encoding, stack, config, { reactiveGeom });\n const keyValues = entries(data).map(([key, value]) => `\"${key}\": ${value}`);\n return keyValues.length > 0 ? { signal: `{${keyValues.join(', ')}}` } : undefined;\n}\n//# sourceMappingURL=tooltip.js.map","import { entries, isEmpty } from '../../../util';\nimport { getMarkPropOrConfig, signalOrValueRef } from '../../common';\nimport { VG_MARK_INDEX } from './../../../vega.schema';\nimport { wrapCondition } from './conditional';\nimport { textRef } from './text';\nimport { tooltipData } from './tooltip';\nexport function aria(model) {\n const { markDef, config } = model;\n const enableAria = getMarkPropOrConfig('aria', markDef, config);\n // We can ignore other aria properties if ariaHidden is true.\n if (enableAria === false) {\n // getMarkGroups sets aria to false already so we don't have to set it in the encode block\n return {};\n }\n return Object.assign(Object.assign(Object.assign({}, (enableAria ? { aria: enableAria } : {})), ariaRoleDescription(model)), description(model));\n}\nfunction ariaRoleDescription(model) {\n const { mark, markDef, config } = model;\n if (config.aria === false) {\n return {};\n }\n const ariaRoleDesc = getMarkPropOrConfig('ariaRoleDescription', markDef, config);\n if (ariaRoleDesc != null) {\n return { ariaRoleDescription: { value: ariaRoleDesc } };\n }\n return mark in VG_MARK_INDEX ? {} : { ariaRoleDescription: { value: mark } };\n}\nexport function description(model) {\n const { encoding, markDef, config, stack } = model;\n const channelDef = encoding.description;\n if (channelDef) {\n return wrapCondition(model, channelDef, 'description', cDef => textRef(cDef, model.config));\n }\n // Use default from mark def or config if defined.\n // Functions in encode usually just return undefined but since we are defining a default below, we need to check the default here.\n const descriptionValue = getMarkPropOrConfig('description', markDef, config);\n if (descriptionValue != null) {\n return {\n description: signalOrValueRef(descriptionValue)\n };\n }\n if (config.aria === false) {\n return {};\n }\n const data = tooltipData(encoding, stack, config);\n if (isEmpty(data)) {\n return undefined;\n }\n return {\n description: {\n signal: entries(data)\n .map(([key, value], index) => `\"${index > 0 ? '; ' : ''}${key}: \" + (${value})`)\n .join(' + ')\n }\n };\n}\n//# sourceMappingURL=aria.js.map","import { getMarkPropOrConfig, signalOrValueRef } from '../../common';\nimport { wrapCondition } from './conditional';\nimport * as ref from './valueref';\n/**\n * Return encode for non-positional channels with scales. (Text doesn't have scale.)\n */\nexport function nonPosition(channel, model, opt = {}) {\n const { markDef, encoding, config } = model;\n const { vgChannel } = opt;\n let { defaultRef, defaultValue } = opt;\n if (defaultRef === undefined) {\n // prettier-ignore\n defaultValue !== null && defaultValue !== void 0 ? defaultValue : (defaultValue = getMarkPropOrConfig(channel, markDef, config, { vgChannel, ignoreVgConfig: true }));\n if (defaultValue !== undefined) {\n defaultRef = signalOrValueRef(defaultValue);\n }\n }\n const channelDef = encoding[channel];\n return wrapCondition(model, channelDef, vgChannel !== null && vgChannel !== void 0 ? vgChannel : channel, cDef => {\n return ref.midPoint({\n channel,\n channelDef: cDef,\n markDef,\n config,\n scaleName: model.scaleName(channel),\n scale: model.getScaleComponent(channel),\n stack: null,\n defaultRef\n });\n });\n}\n//# sourceMappingURL=nonposition.js.map","import * as log from '../../../log';\nimport { contains } from '../../../util';\nimport { getMarkPropOrConfig, signalOrValueRef } from '../../common';\nimport { nonPosition } from './nonposition';\nexport function color(model, opt = { filled: undefined }) {\n var _a, _b, _c, _d;\n const { markDef, encoding, config } = model;\n const { type: markType } = markDef;\n // Allow filled to be overridden (for trail's \"filled\")\n const filled = (_a = opt.filled) !== null && _a !== void 0 ? _a : getMarkPropOrConfig('filled', markDef, config);\n const transparentIfNeeded = contains(['bar', 'point', 'circle', 'square', 'geoshape'], markType)\n ? 'transparent'\n : undefined;\n const defaultFill = (_c = (_b = getMarkPropOrConfig(filled === true ? 'color' : undefined, markDef, config, { vgChannel: 'fill' })) !== null && _b !== void 0 ? _b : \n // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified\n config.mark[filled === true && 'color']) !== null && _c !== void 0 ? _c : \n // If there is no fill, always fill symbols, bar, geoshape\n // with transparent fills https://github.com/vega/vega-lite/issues/1316\n transparentIfNeeded;\n const defaultStroke = (_d = getMarkPropOrConfig(filled === false ? 'color' : undefined, markDef, config, { vgChannel: 'stroke' })) !== null && _d !== void 0 ? _d : \n // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified\n config.mark[filled === false && 'color'];\n const colorVgChannel = filled ? 'fill' : 'stroke';\n const fillStrokeMarkDefAndConfig = Object.assign(Object.assign({}, (defaultFill ? { fill: signalOrValueRef(defaultFill) } : {})), (defaultStroke ? { stroke: signalOrValueRef(defaultStroke) } : {}));\n if (markDef.color && (filled ? markDef.fill : markDef.stroke)) {\n log.warn(log.message.droppingColor('property', { fill: 'fill' in markDef, stroke: 'stroke' in markDef }));\n }\n return Object.assign(Object.assign(Object.assign(Object.assign({}, fillStrokeMarkDefAndConfig), nonPosition('color', model, {\n vgChannel: colorVgChannel,\n defaultValue: filled ? defaultFill : defaultStroke\n })), nonPosition('fill', model, {\n // if there is encoding.fill, include default fill just in case we have conditional-only fill encoding\n defaultValue: encoding.fill ? defaultFill : undefined\n })), nonPosition('stroke', model, {\n // if there is encoding.stroke, include default fill just in case we have conditional-only stroke encoding\n defaultValue: encoding.stroke ? defaultStroke : undefined\n }));\n}\n//# sourceMappingURL=color.js.map","import { getOffsetChannel } from '../../../channel';\nexport function getOffset(channel, markDef) {\n const offsetChannel = getOffsetChannel(channel);\n // TODO: in the future read from encoding channel too\n const markDefOffsetValue = markDef[offsetChannel];\n if (markDefOffsetValue) {\n return markDefOffsetValue;\n }\n return undefined;\n}\n//# sourceMappingURL=offset.js.map","import { getMainRangeChannel, getSecondaryRangeChannel, getSizeChannel, getVgPositionChannel, isXorY } from '../../../channel';\nimport { isFieldDef, isFieldOrDatumDef } from '../../../channeldef';\nimport { ScaleType } from '../../../scale';\nimport { contains } from '../../../util';\nimport { getMarkPropOrConfig } from '../../common';\nimport { getOffset } from './offset';\nimport * as ref from './valueref';\n/**\n * Return encode for point (non-band) position channels.\n */\nexport function pointPosition(channel, model, { defaultPos, vgChannel }) {\n const { encoding, markDef, config, stack } = model;\n const channelDef = encoding[channel];\n const channel2Def = encoding[getSecondaryRangeChannel(channel)];\n const scaleName = model.scaleName(channel);\n const scale = model.getScaleComponent(channel);\n const offset = getOffset(channel, markDef);\n // Get default position or position from mark def\n const defaultRef = pointPositionDefaultRef({\n model,\n defaultPos,\n channel,\n scaleName,\n scale\n });\n const valueRef = !channelDef && isXorY(channel) && (encoding.latitude || encoding.longitude)\n ? // use geopoint output if there are lat/long and there is no point position overriding lat/long.\n { field: model.getName(channel) }\n : positionRef({\n channel,\n channelDef,\n channel2Def,\n markDef,\n config,\n scaleName,\n scale,\n stack,\n offset,\n defaultRef\n });\n return valueRef ? { [vgChannel || channel]: valueRef } : undefined;\n}\n// TODO: we need to find a way to refactor these so that scaleName is a part of scale\n// but that's complicated. For now, this is a huge step moving forward.\n/**\n * @return Vega ValueRef for normal x- or y-position without projection\n */\nexport function positionRef(params) {\n const { channel, channelDef, scaleName, stack, offset, markDef } = params;\n // This isn't a part of midPoint because we use midPoint for non-position too\n if (isFieldOrDatumDef(channelDef) && stack && channel === stack.fieldChannel) {\n if (isFieldDef(channelDef)) {\n let bandPosition = channelDef.bandPosition;\n if (bandPosition === undefined && markDef.type === 'text' && (channel === 'radius' || channel === 'theta')) {\n // theta and radius of text mark should use bandPosition = 0.5 by default\n // so that labels for arc marks are centered automatically\n bandPosition = 0.5;\n }\n if (bandPosition !== undefined) {\n return ref.interpolatedSignalRef({\n scaleName,\n fieldOrDatumDef: channelDef,\n startSuffix: 'start',\n bandPosition,\n offset\n });\n }\n }\n // x or y use stack_end so that stacked line's point mark use stack_end too.\n return ref.valueRefForFieldOrDatumDef(channelDef, scaleName, { suffix: 'end' }, { offset });\n }\n return ref.midPointRefWithPositionInvalidTest(params);\n}\nexport function pointPositionDefaultRef({ model, defaultPos, channel, scaleName, scale }) {\n const { markDef, config } = model;\n return () => {\n const mainChannel = getMainRangeChannel(channel);\n const vgChannel = getVgPositionChannel(channel);\n const definedValueOrConfig = getMarkPropOrConfig(channel, markDef, config, { vgChannel });\n if (definedValueOrConfig !== undefined) {\n return ref.widthHeightValueOrSignalRef(channel, definedValueOrConfig);\n }\n switch (defaultPos) {\n case 'zeroOrMin':\n case 'zeroOrMax':\n if (scaleName) {\n const scaleType = scale.get('type');\n if (contains([ScaleType.LOG, ScaleType.TIME, ScaleType.UTC], scaleType)) {\n // Log scales cannot have zero.\n // Zero in time scale is arbitrary, and does not affect ratio.\n // (Time is an interval level of measurement, not ratio).\n // See https://en.wikipedia.org/wiki/Level_of_measurement for more info.\n }\n else {\n if (scale.domainDefinitelyIncludesZero()) {\n return {\n scale: scaleName,\n value: 0\n };\n }\n }\n }\n if (defaultPos === 'zeroOrMin') {\n return mainChannel === 'y' ? { field: { group: 'height' } } : { value: 0 };\n }\n else {\n // zeroOrMax\n switch (mainChannel) {\n case 'radius':\n // max of radius is min(width, height) / 2\n return {\n signal: `min(${model.width.signal},${model.height.signal})/2`\n };\n case 'theta':\n return { signal: '2*PI' };\n case 'x':\n return { field: { group: 'width' } };\n case 'y':\n return { value: 0 };\n }\n }\n break;\n case 'mid': {\n const sizeRef = model[getSizeChannel(channel)];\n return Object.assign(Object.assign({}, sizeRef), { mult: 0.5 });\n }\n }\n // defaultPos === null\n return undefined;\n };\n}\n//# sourceMappingURL=position-point.js.map","import { getVgPositionChannel } from '../../../channel';\nimport * as log from '../../../log';\nimport { isSignalRef } from '../../../vega.schema';\nimport { getMarkPropOrConfig } from '../../common';\nconst ALIGNED_X_CHANNEL = {\n left: 'x',\n center: 'xc',\n right: 'x2'\n};\nconst BASELINED_Y_CHANNEL = {\n top: 'y',\n middle: 'yc',\n bottom: 'y2'\n};\nexport function vgAlignedPositionChannel(channel, markDef, config, defaultAlign = 'middle') {\n if (channel === 'radius' || channel === 'theta') {\n return getVgPositionChannel(channel);\n }\n const alignChannel = channel === 'x' ? 'align' : 'baseline';\n const align = getMarkPropOrConfig(alignChannel, markDef, config);\n let alignExcludingSignal;\n if (isSignalRef(align)) {\n log.warn(log.message.rangeMarkAlignmentCannotBeExpression(alignChannel));\n alignExcludingSignal = undefined;\n }\n else {\n alignExcludingSignal = align;\n }\n if (channel === 'x') {\n return ALIGNED_X_CHANNEL[alignExcludingSignal || (defaultAlign === 'top' ? 'left' : 'center')];\n }\n else {\n return BASELINED_Y_CHANNEL[alignExcludingSignal || defaultAlign];\n }\n}\n//# sourceMappingURL=position-align.js.map","import { getMainRangeChannel, getSecondaryRangeChannel, getSizeChannel, getVgPositionChannel } from '../../../channel';\nimport { isFieldOrDatumDef } from '../../../channeldef';\nimport * as log from '../../../log';\nimport { isRelativeBandSize } from '../../../mark';\nimport { getMarkStyleConfig } from '../../common';\nimport { getOffset } from './offset';\nimport { vgAlignedPositionChannel } from './position-align';\nimport { pointPosition, pointPositionDefaultRef } from './position-point';\nimport * as ref from './valueref';\n/**\n * Utility for area/rule position, which can be either point or range.\n * (One of the axes should be point and the other should be range.)\n */\nexport function pointOrRangePosition(channel, model, { defaultPos, defaultPos2, range }) {\n if (range) {\n return rangePosition(channel, model, { defaultPos, defaultPos2 });\n }\n return pointPosition(channel, model, { defaultPos });\n}\nexport function rangePosition(channel, model, { defaultPos, defaultPos2 }) {\n const { markDef, config } = model;\n const channel2 = getSecondaryRangeChannel(channel);\n const sizeChannel = getSizeChannel(channel);\n const pos2Mixins = pointPosition2OrSize(model, defaultPos2, channel2);\n const vgChannel = pos2Mixins[sizeChannel]\n ? // If there is width/height, we need to position the marks based on the alignment.\n vgAlignedPositionChannel(channel, markDef, config)\n : // Otherwise, make sure to apply to the right Vg Channel (for arc mark)\n getVgPositionChannel(channel);\n return Object.assign(Object.assign({}, pointPosition(channel, model, { defaultPos, vgChannel })), pos2Mixins);\n}\n/**\n * Return encode for x2, y2.\n * If channel is not specified, return one channel based on orientation.\n */\nfunction pointPosition2OrSize(model, defaultPos, channel) {\n const { encoding, mark, markDef, stack, config } = model;\n const baseChannel = getMainRangeChannel(channel);\n const sizeChannel = getSizeChannel(channel);\n const vgChannel = getVgPositionChannel(channel);\n const channelDef = encoding[baseChannel];\n const scaleName = model.scaleName(baseChannel);\n const scale = model.getScaleComponent(baseChannel);\n const offset = channel in encoding || channel in markDef\n ? getOffset(channel, model.markDef)\n : getOffset(baseChannel, model.markDef);\n if (!channelDef && (channel === 'x2' || channel === 'y2') && (encoding.latitude || encoding.longitude)) {\n const vgSizeChannel = getSizeChannel(channel);\n const size = model.markDef[vgSizeChannel];\n if (size != null) {\n return {\n [vgSizeChannel]: { value: size }\n };\n }\n else {\n return {\n [vgChannel]: { field: model.getName(channel) }\n };\n }\n }\n const valueRef = position2Ref({\n channel,\n channelDef,\n channel2Def: encoding[channel],\n markDef,\n config,\n scaleName,\n scale,\n stack,\n offset,\n defaultRef: undefined\n });\n if (valueRef !== undefined) {\n return { [vgChannel]: valueRef };\n }\n // TODO: check width/height encoding here once we add them\n // no x2/y2 encoding, then try to read x2/y2 or width/height based on precedence:\n // markDef > config.style > mark-specific config (config[mark]) > general mark config (config.mark)\n return (position2orSize(channel, markDef) ||\n position2orSize(channel, {\n [channel]: getMarkStyleConfig(channel, markDef, config.style),\n [sizeChannel]: getMarkStyleConfig(sizeChannel, markDef, config.style)\n }) ||\n position2orSize(channel, config[mark]) ||\n position2orSize(channel, config.mark) || {\n [vgChannel]: pointPositionDefaultRef({\n model,\n defaultPos,\n channel,\n scaleName,\n scale\n })()\n });\n}\nexport function position2Ref({ channel, channelDef, channel2Def, markDef, config, scaleName, scale, stack, offset, defaultRef }) {\n if (isFieldOrDatumDef(channelDef) &&\n stack &&\n // If fieldChannel is X and channel is X2 (or Y and Y2)\n channel.charAt(0) === stack.fieldChannel.charAt(0)) {\n return ref.valueRefForFieldOrDatumDef(channelDef, scaleName, { suffix: 'start' }, { offset });\n }\n return ref.midPointRefWithPositionInvalidTest({\n channel,\n channelDef: channel2Def,\n scaleName,\n scale,\n stack,\n markDef,\n config,\n offset,\n defaultRef\n });\n}\nfunction position2orSize(channel, markDef) {\n const sizeChannel = getSizeChannel(channel);\n const vgChannel = getVgPositionChannel(channel);\n if (markDef[vgChannel] !== undefined) {\n return { [vgChannel]: ref.widthHeightValueOrSignalRef(channel, markDef[vgChannel]) };\n }\n else if (markDef[channel] !== undefined) {\n return { [vgChannel]: ref.widthHeightValueOrSignalRef(channel, markDef[channel]) };\n }\n else if (markDef[sizeChannel]) {\n const dimensionSize = markDef[sizeChannel];\n if (isRelativeBandSize(dimensionSize)) {\n log.warn(log.message.relativeBandSizeNotSupported(sizeChannel));\n }\n else {\n return { [sizeChannel]: ref.widthHeightValueOrSignalRef(channel, dimensionSize) };\n }\n }\n return undefined;\n}\n//# sourceMappingURL=position-range.js.map","import { isArray, isNumber } from 'vega-util';\nimport { isBinned, isBinning, isBinParams } from '../../../bin';\nimport { getSecondaryRangeChannel, getSizeChannel, getVgPositionChannel, isPolarPositionChannel, isXorY } from '../../../channel';\nimport { getBandSize, isFieldDef, isFieldOrDatumDef, vgField } from '../../../channeldef';\nimport { getViewConfigDiscreteStep } from '../../../config';\nimport * as log from '../../../log';\nimport { isRelativeBandSize } from '../../../mark';\nimport { hasDiscreteDomain } from '../../../scale';\nimport { isSignalRef, isVgRangeStep } from '../../../vega.schema';\nimport { getMarkPropOrConfig, signalOrStringValue, signalOrValueRef } from '../../common';\nimport { nonPosition } from './nonposition';\nimport { getOffset } from './offset';\nimport { vgAlignedPositionChannel } from './position-align';\nimport { pointPositionDefaultRef } from './position-point';\nimport { rangePosition } from './position-range';\nimport * as ref from './valueref';\nexport function rectPosition(model, channel, mark) {\n var _a, _b, _c, _d;\n const { config, encoding, markDef } = model;\n const channel2 = getSecondaryRangeChannel(channel);\n const sizeChannel = getSizeChannel(channel);\n const channelDef = encoding[channel];\n const channelDef2 = encoding[channel2];\n const scale = model.getScaleComponent(channel);\n const scaleType = scale ? scale.get('type') : undefined;\n const scaleName = model.scaleName(channel);\n const orient = markDef.orient;\n const hasSizeDef = (_b = (_a = encoding[sizeChannel]) !== null && _a !== void 0 ? _a : encoding.size) !== null && _b !== void 0 ? _b : getMarkPropOrConfig('size', markDef, config, { vgChannel: sizeChannel });\n const isBarBand = mark === 'bar' && (channel === 'x' ? orient === 'vertical' : orient === 'horizontal');\n // x, x2, and width -- we must specify two of these in all conditions\n if (isFieldDef(channelDef) &&\n (isBinning(channelDef.bin) || isBinned(channelDef.bin) || (channelDef.timeUnit && !channelDef2)) &&\n !(hasSizeDef && !isRelativeBandSize(hasSizeDef)) &&\n !hasDiscreteDomain(scaleType)) {\n const bandSize = getBandSize({ channel, fieldDef: channelDef, markDef, config, scaleType });\n const axis = (_c = model.component.axes[channel]) === null || _c === void 0 ? void 0 : _c[0];\n const axisTranslate = (_d = axis === null || axis === void 0 ? void 0 : axis.get('translate')) !== null && _d !== void 0 ? _d : 0.5; // vega default is 0.5\n return rectBinPosition({\n fieldDef: channelDef,\n fieldDef2: channelDef2,\n channel,\n markDef,\n scaleName,\n bandSize,\n axisTranslate,\n spacing: isXorY(channel) ? getMarkPropOrConfig('binSpacing', markDef, config) : undefined,\n reverse: scale.get('reverse'),\n config\n });\n }\n else if (((isFieldOrDatumDef(channelDef) && hasDiscreteDomain(scaleType)) || isBarBand) && !channelDef2) {\n return positionAndSize(channelDef, channel, model);\n }\n else {\n return rangePosition(channel, model, { defaultPos: 'zeroOrMax', defaultPos2: 'zeroOrMin' });\n }\n}\nfunction defaultSizeRef(sizeChannel, scaleName, scale, config, bandSize) {\n if (isRelativeBandSize(bandSize)) {\n if (scale) {\n const scaleType = scale.get('type');\n if (scaleType === 'band') {\n return { scale: scaleName, band: bandSize.band };\n }\n else if (bandSize.band !== 1) {\n log.warn(log.message.cannotUseRelativeBandSizeWithNonBandScale(scaleType));\n bandSize = undefined;\n }\n }\n else {\n return {\n mult: bandSize.band,\n field: { group: sizeChannel }\n };\n }\n }\n else if (isSignalRef(bandSize)) {\n return bandSize;\n }\n else if (bandSize) {\n return { value: bandSize };\n }\n // no valid band size\n if (scale) {\n const scaleRange = scale.get('range');\n if (isVgRangeStep(scaleRange) && isNumber(scaleRange.step)) {\n return { value: scaleRange.step - 2 };\n }\n }\n const defaultStep = getViewConfigDiscreteStep(config.view, sizeChannel);\n return { value: defaultStep - 2 };\n}\n/**\n * Output position encoding and its size encoding for continuous, point, and band scales.\n */\nfunction positionAndSize(fieldDef, channel, model) {\n const { markDef, encoding, config, stack } = model;\n const orient = markDef.orient;\n const scaleName = model.scaleName(channel);\n const scale = model.getScaleComponent(channel);\n const vgSizeChannel = getSizeChannel(channel);\n const channel2 = getSecondaryRangeChannel(channel);\n // use \"size\" channel for bars, if there is orient and the channel matches the right orientation\n const useVlSizeChannel = (orient === 'horizontal' && channel === 'y') || (orient === 'vertical' && channel === 'x');\n // Use size encoding / mark property / config if it exists\n let sizeMixins;\n if (encoding.size || markDef.size) {\n if (useVlSizeChannel) {\n sizeMixins = nonPosition('size', model, {\n vgChannel: vgSizeChannel,\n defaultRef: signalOrValueRef(markDef.size)\n });\n }\n else {\n log.warn(log.message.cannotApplySizeToNonOrientedMark(markDef.type));\n }\n }\n // Otherwise, apply default value\n const bandSize = getBandSize({ channel, fieldDef, markDef, config, scaleType: scale === null || scale === void 0 ? void 0 : scale.get('type'), useVlSizeChannel });\n sizeMixins = sizeMixins || { [vgSizeChannel]: defaultSizeRef(vgSizeChannel, scaleName, scale, config, bandSize) };\n /*\n Band scales with size value and all point scales, use xc/yc + band=0.5\n \n Otherwise (band scales that has size based on a band ref), use x/y with position band = (1 - size_band) / 2.\n In this case, size_band is the band specified in the x/y-encoding.\n By default band is 1, so `(1 - band) / 2` = 0.\n If band is 0.6, the the x/y position in such case should be `(1 - band) / 2` = 0.2\n */\n const defaultBandAlign = (scale === null || scale === void 0 ? void 0 : scale.get('type')) !== 'band' || !('band' in sizeMixins[vgSizeChannel]) ? 'middle' : 'top';\n const vgChannel = vgAlignedPositionChannel(channel, markDef, config, defaultBandAlign);\n const center = vgChannel === 'xc' || vgChannel === 'yc';\n const offset = getOffset(channel, markDef);\n const posRef = ref.midPointRefWithPositionInvalidTest({\n channel,\n channelDef: fieldDef,\n markDef,\n config,\n scaleName,\n scale,\n stack,\n offset,\n defaultRef: pointPositionDefaultRef({ model, defaultPos: 'mid', channel, scaleName, scale }),\n bandPosition: center\n ? 0.5\n : isSignalRef(bandSize)\n ? { signal: `(1-${bandSize})/2` }\n : isRelativeBandSize(bandSize)\n ? (1 - bandSize.band) / 2\n : 0\n });\n if (vgSizeChannel) {\n return Object.assign({ [vgChannel]: posRef }, sizeMixins);\n }\n else {\n // otherwise, we must simulate size by setting position2 = position + size\n // (for theta/radius since Vega doesn't have thetaWidth/radiusWidth)\n const vgChannel2 = getVgPositionChannel(channel2);\n const sizeRef = sizeMixins[vgSizeChannel];\n const sizeOffset = offset ? Object.assign(Object.assign({}, sizeRef), { offset }) : sizeRef;\n return {\n [vgChannel]: posRef,\n // posRef might be an array that wraps position invalid test\n [vgChannel2]: isArray(posRef)\n ? [posRef[0], Object.assign(Object.assign({}, posRef[1]), { offset: sizeOffset })]\n : Object.assign(Object.assign({}, posRef), { offset: sizeOffset })\n };\n }\n}\nfunction getBinSpacing(channel, spacing, reverse, translate, offset) {\n if (isPolarPositionChannel(channel)) {\n return 0;\n }\n const spacingOffset = channel === 'x' || channel === 'y2' ? -spacing / 2 : spacing / 2;\n if (isSignalRef(reverse) || isSignalRef(offset) || isSignalRef(translate)) {\n const reverseExpr = signalOrStringValue(reverse);\n const offsetExpr = signalOrStringValue(offset);\n const translateExpr = signalOrStringValue(translate);\n const t = translateExpr ? `${translateExpr} + ` : '';\n const r = reverseExpr ? `(${reverseExpr} ? -1 : 1) * ` : '';\n const o = offsetExpr ? `(${offsetExpr} + ${spacingOffset})` : spacingOffset;\n return {\n signal: t + r + o\n };\n }\n else {\n offset = offset || 0;\n return translate + (reverse ? -offset - spacingOffset : +offset + spacingOffset);\n }\n}\nexport function rectBinPosition({ fieldDef, fieldDef2, channel, bandSize, scaleName, markDef, spacing = 0, axisTranslate, reverse, config }) {\n const channel2 = getSecondaryRangeChannel(channel);\n const vgChannel = getVgPositionChannel(channel);\n const vgChannel2 = getVgPositionChannel(channel2);\n const offset = getOffset(channel, markDef);\n const bandPosition = isSignalRef(bandSize)\n ? { signal: `(1-${bandSize.signal})/2` }\n : isRelativeBandSize(bandSize)\n ? (1 - bandSize.band) / 2\n : 0.5;\n if (isBinning(fieldDef.bin) || fieldDef.timeUnit) {\n return {\n [vgChannel2]: rectBinRef({\n channel,\n fieldDef,\n scaleName,\n markDef,\n bandPosition,\n offset: getBinSpacing(channel2, spacing, reverse, axisTranslate, offset),\n config\n }),\n [vgChannel]: rectBinRef({\n channel,\n fieldDef,\n scaleName,\n markDef,\n bandPosition: isSignalRef(bandPosition) ? { signal: `1-${bandPosition.signal}` } : 1 - bandPosition,\n offset: getBinSpacing(channel, spacing, reverse, axisTranslate, offset),\n config\n })\n };\n }\n else if (isBinned(fieldDef.bin)) {\n const startRef = ref.valueRefForFieldOrDatumDef(fieldDef, scaleName, {}, { offset: getBinSpacing(channel2, spacing, reverse, axisTranslate, offset) });\n if (isFieldDef(fieldDef2)) {\n return {\n [vgChannel2]: startRef,\n [vgChannel]: ref.valueRefForFieldOrDatumDef(fieldDef2, scaleName, {}, { offset: getBinSpacing(channel, spacing, reverse, axisTranslate, offset) })\n };\n }\n else if (isBinParams(fieldDef.bin) && fieldDef.bin.step) {\n return {\n [vgChannel2]: startRef,\n [vgChannel]: {\n signal: `scale(\"${scaleName}\", ${vgField(fieldDef, { expr: 'datum' })} + ${fieldDef.bin.step})`,\n offset: getBinSpacing(channel, spacing, reverse, axisTranslate, offset)\n }\n };\n }\n }\n log.warn(log.message.channelRequiredForBinned(channel2));\n return undefined;\n}\n/**\n * Value Ref for binned fields\n */\nexport function rectBinRef({ channel, fieldDef, scaleName, markDef, bandPosition, offset, config }) {\n const r = ref.interpolatedSignalRef({\n scaleName,\n fieldOrDatumDef: fieldDef,\n bandPosition,\n offset\n });\n return ref.wrapPositionInvalidTest({\n fieldDef,\n channel,\n markDef,\n ref: r,\n config\n });\n}\n//# sourceMappingURL=position-rect.js.map","import { array } from 'vega-util';\nimport { SCALE_CHANNELS } from '../../../channel';\nimport { isPathMark } from '../../../mark';\nimport { hasContinuousDomain } from '../../../scale';\nimport { keys } from '../../../util';\nimport { VG_MARK_CONFIGS } from '../../../vega.schema';\nimport { getMarkPropOrConfig, signalOrValueRef } from '../../common';\nimport { aria } from './aria';\nimport { color } from './color';\nimport { nonPosition } from './nonposition';\nimport { text } from './text';\nimport { tooltip } from './tooltip';\nimport { fieldInvalidPredicate } from './valueref';\nimport { zindex } from './zindex';\nexport { color } from './color';\nexport { wrapCondition } from './conditional';\nexport { nonPosition } from './nonposition';\nexport { pointPosition } from './position-point';\nexport { pointOrRangePosition, rangePosition } from './position-range';\nexport { rectPosition } from './position-rect';\nexport { text } from './text';\nexport { tooltip } from './tooltip';\nconst ALWAYS_IGNORE = new Set(['aria', 'width', 'height']);\nexport function baseEncodeEntry(model, ignore) {\n const { fill = undefined, stroke = undefined } = ignore.color === 'include' ? color(model) : {};\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, markDefProperties(model.markDef, ignore)), wrapAllFieldsInvalid(model, 'fill', fill)), wrapAllFieldsInvalid(model, 'stroke', stroke)), nonPosition('opacity', model)), nonPosition('fillOpacity', model)), nonPosition('strokeOpacity', model)), nonPosition('strokeWidth', model)), nonPosition('strokeDash', model)), zindex(model)), tooltip(model)), text(model, 'href')), aria(model));\n}\n// TODO: mark VgValueRef[] as readonly after https://github.com/vega/vega/pull/1987\nfunction wrapAllFieldsInvalid(model, channel, valueRef) {\n const { config, mark, markDef } = model;\n const invalid = getMarkPropOrConfig('invalid', markDef, config);\n if (invalid === 'hide' && valueRef && !isPathMark(mark)) {\n // For non-path marks, we have to exclude invalid values (null and NaN) for scales with continuous domains.\n // For path marks, we will use \"defined\" property and skip these values instead.\n const test = allFieldsInvalidPredicate(model, { invalid: true, channels: SCALE_CHANNELS });\n if (test) {\n return {\n [channel]: [\n // prepend the invalid case\n // TODO: support custom value\n { test, value: null },\n ...array(valueRef)\n ]\n };\n }\n }\n return valueRef ? { [channel]: valueRef } : {};\n}\nfunction markDefProperties(mark, ignore) {\n return VG_MARK_CONFIGS.reduce((m, prop) => {\n if (!ALWAYS_IGNORE.has(prop) && mark[prop] !== undefined && ignore[prop] !== 'ignore') {\n m[prop] = signalOrValueRef(mark[prop]);\n }\n return m;\n }, {});\n}\nfunction allFieldsInvalidPredicate(model, { invalid = false, channels }) {\n const filterIndex = channels.reduce((aggregator, channel) => {\n const scaleComponent = model.getScaleComponent(channel);\n if (scaleComponent) {\n const scaleType = scaleComponent.get('type');\n const field = model.vgField(channel, { expr: 'datum' });\n // While discrete domain scales can handle invalid values, continuous scales can't.\n if (field && hasContinuousDomain(scaleType)) {\n aggregator[field] = true;\n }\n }\n return aggregator;\n }, {});\n const fields = keys(filterIndex);\n if (fields.length > 0) {\n const op = invalid ? '||' : '&&';\n return fields.map(field => fieldInvalidPredicate(field, invalid)).join(` ${op} `);\n }\n return undefined;\n}\n//# sourceMappingURL=base.js.map","import { isValueDef } from '../../../channeldef';\nimport { isPathMark } from '../../../mark';\nimport { signalOrValueRef } from '../../common';\nimport { wrapCondition } from './conditional';\nexport function zindex(model) {\n const { encoding, mark } = model;\n const order = encoding.order;\n if (!isPathMark(mark) && isValueDef(order)) {\n return wrapCondition(model, order, 'zindex', cd => signalOrValueRef(cd.value));\n }\n return {};\n}\n//# sourceMappingURL=zindex.js.map","import { POSITION_SCALE_CHANNELS } from '../../../channel';\nimport { hasContinuousDomain } from '../../../scale';\nimport { keys } from '../../../util';\nimport { getMarkPropOrConfig, signalOrValueRef } from '../../common';\nimport { fieldInvalidPredicate } from './valueref';\nexport function defined(model) {\n const { config, markDef } = model;\n const invalid = getMarkPropOrConfig('invalid', markDef, config);\n if (invalid) {\n const signal = allFieldsInvalidPredicate(model, { channels: POSITION_SCALE_CHANNELS });\n if (signal) {\n return { defined: { signal } };\n }\n }\n return {};\n}\nfunction allFieldsInvalidPredicate(model, { invalid = false, channels }) {\n const filterIndex = channels.reduce((aggregator, channel) => {\n const scaleComponent = model.getScaleComponent(channel);\n if (scaleComponent) {\n const scaleType = scaleComponent.get('type');\n const field = model.vgField(channel, { expr: 'datum' });\n // While discrete domain scales can handle invalid values, continuous scales can't.\n if (field && hasContinuousDomain(scaleType)) {\n aggregator[field] = true;\n }\n }\n return aggregator;\n }, {});\n const fields = keys(filterIndex);\n if (fields.length > 0) {\n const op = invalid ? '||' : '&&';\n return fields.map(field => fieldInvalidPredicate(field, invalid)).join(` ${op} `);\n }\n return undefined;\n}\nexport function valueIfDefined(prop, value) {\n if (value !== undefined) {\n return { [prop]: signalOrValueRef(value) };\n }\n return undefined;\n}\n//# sourceMappingURL=defined.js.map","import * as log from '../../log';\nimport { isPathMark } from '../../mark';\nimport { tooltip } from '../mark/encode';\nconst VORONOI = 'voronoi';\nconst nearest = {\n defined: selCmpt => {\n return selCmpt.type === 'point' && selCmpt.nearest;\n },\n parse: (model, selCmpt) => {\n // Scope selection events to the voronoi mark to prevent capturing\n // events that occur on the group mark (https://github.com/vega/vega/issues/2112).\n if (selCmpt.events) {\n for (const s of selCmpt.events) {\n s.markname = model.getName(VORONOI);\n }\n }\n },\n marks: (model, selCmpt, marks) => {\n const { x, y } = selCmpt.project.hasChannel;\n const markType = model.mark;\n if (isPathMark(markType)) {\n log.warn(log.message.nearestNotSupportForContinuous(markType));\n return marks;\n }\n const cellDef = {\n name: model.getName(VORONOI),\n type: 'path',\n interactive: true,\n from: { data: model.getName('marks') },\n encode: {\n update: Object.assign({ fill: { value: 'transparent' }, strokeWidth: { value: 0.35 }, stroke: { value: 'transparent' }, isVoronoi: { value: true } }, tooltip(model, { reactiveGeom: true }))\n },\n transform: [\n {\n type: 'voronoi',\n x: { expr: x || !y ? 'datum.datum.x || 0' : '0' },\n y: { expr: y || !x ? 'datum.datum.y || 0' : '0' },\n size: [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')]\n }\n ]\n };\n let index = 0;\n let exists = false;\n marks.forEach((mark, i) => {\n var _a;\n const name = (_a = mark.name) !== null && _a !== void 0 ? _a : '';\n if (name === model.component.mark[0].name) {\n index = i;\n }\n else if (name.indexOf(VORONOI) >= 0) {\n exists = true;\n }\n });\n if (!exists) {\n marks.splice(index + 1, 0, cellDef);\n }\n return marks;\n }\n};\nexport default nearest;\n//# sourceMappingURL=nearest.js.map","import { stringValue } from 'vega-util';\nimport { disableDirectManipulation, TUPLE } from '.';\nimport { varName } from '../../util';\nimport { assembleInit } from './assemble';\nimport nearest from './nearest';\nimport { TUPLE_FIELDS } from './project';\nimport { isLegendBinding } from '../../selection';\nconst inputBindings = {\n defined: selCmpt => {\n return (selCmpt.type === 'point' &&\n selCmpt.resolve === 'global' &&\n selCmpt.bind &&\n selCmpt.bind !== 'scales' &&\n !isLegendBinding(selCmpt.bind));\n },\n parse: (model, selCmpt, selDef) => disableDirectManipulation(selCmpt, selDef),\n topLevelSignals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const proj = selCmpt.project;\n const bind = selCmpt.bind;\n const init = selCmpt.init && selCmpt.init[0]; // Can only exist on single selections (one initial value).\n const datum = nearest.defined(selCmpt) ? '(item().isVoronoi ? datum.datum : datum)' : 'datum';\n proj.items.forEach((p, i) => {\n var _a, _b;\n const sgname = varName(`${name}_${p.field}`);\n const hasSignal = signals.filter(s => s.name === sgname);\n if (!hasSignal.length) {\n signals.unshift(Object.assign(Object.assign({ name: sgname }, (init ? { init: assembleInit(init[i]) } : { value: null })), { on: selCmpt.events\n ? [\n {\n events: selCmpt.events,\n update: `datum && item().mark.marktype !== 'group' ? ${datum}[${stringValue(p.field)}] : null`\n }\n ]\n : [], bind: (_b = (_a = bind[p.field]) !== null && _a !== void 0 ? _a : bind[p.channel]) !== null && _b !== void 0 ? _b : bind }));\n }\n });\n return signals;\n },\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const proj = selCmpt.project;\n const signal = signals.filter(s => s.name === name + TUPLE)[0];\n const fields = name + TUPLE_FIELDS;\n const values = proj.items.map(p => varName(`${name}_${p.field}`));\n const valid = values.map(v => `${v} !== null`).join(' && ');\n if (values.length) {\n signal.update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;\n }\n delete signal.value;\n delete signal.on;\n return signals;\n }\n};\nexport default inputBindings;\n//# sourceMappingURL=inputs.js.map","import { TUPLE, unitName } from '.';\nexport const TOGGLE = '_toggle';\nconst toggle = {\n defined: selCmpt => {\n return selCmpt.type === 'point' && !!selCmpt.toggle;\n },\n signals: (model, selCmpt, signals) => {\n return signals.concat({\n name: selCmpt.name + TOGGLE,\n value: false,\n on: [{ events: selCmpt.events, update: selCmpt.toggle }]\n });\n },\n modifyExpr: (model, selCmpt) => {\n const tpl = selCmpt.name + TUPLE;\n const signal = selCmpt.name + TOGGLE;\n return (`${signal} ? null : ${tpl}, ` +\n (selCmpt.resolve === 'global' ? `${signal} ? null : true, ` : `${signal} ? null : {unit: ${unitName(model)}}, `) +\n `${signal} ? ${tpl} : null`);\n }\n};\nexport default toggle;\n//# sourceMappingURL=toggle.js.map","import { selector as parseSelector } from 'vega-event-selector';\nimport { isString } from 'vega-util';\nimport { TUPLE } from '.';\nimport { varName } from '../../util';\nimport inputBindings from './inputs';\nimport toggle, { TOGGLE } from './toggle';\nconst clear = {\n defined: selCmpt => {\n return selCmpt.clear !== undefined && selCmpt.clear !== false;\n },\n parse: (model, selCmpt) => {\n if (selCmpt.clear) {\n selCmpt.clear = isString(selCmpt.clear) ? parseSelector(selCmpt.clear, 'view') : selCmpt.clear;\n }\n },\n topLevelSignals: (model, selCmpt, signals) => {\n if (inputBindings.defined(selCmpt)) {\n for (const proj of selCmpt.project.items) {\n const idx = signals.findIndex(n => n.name === varName(`${selCmpt.name}_${proj.field}`));\n if (idx !== -1) {\n signals[idx].on.push({ events: selCmpt.clear, update: 'null' });\n }\n }\n }\n return signals;\n },\n signals: (model, selCmpt, signals) => {\n function addClear(idx, update) {\n if (idx !== -1 && signals[idx].on) {\n signals[idx].on.push({ events: selCmpt.clear, update });\n }\n }\n // Be as minimalist as possible when adding clear triggers to minimize dataflow execution.\n if (selCmpt.type === 'interval') {\n for (const proj of selCmpt.project.items) {\n const vIdx = signals.findIndex(n => n.name === proj.signals.visual);\n addClear(vIdx, '[0, 0]');\n if (vIdx === -1) {\n const dIdx = signals.findIndex(n => n.name === proj.signals.data);\n addClear(dIdx, 'null');\n }\n }\n }\n else {\n let tIdx = signals.findIndex(n => n.name === selCmpt.name + TUPLE);\n addClear(tIdx, 'null');\n if (toggle.defined(selCmpt)) {\n tIdx = signals.findIndex(n => n.name === selCmpt.name + TOGGLE);\n addClear(tIdx, 'false');\n }\n }\n return signals;\n }\n};\nexport default clear;\n//# sourceMappingURL=clear.js.map","import { isObject } from 'vega';\nimport { selector as parseSelector } from 'vega-event-selector';\nimport { array, isString } from 'vega-util';\nimport { disableDirectManipulation, TUPLE } from '.';\nimport * as log from '../../log';\nimport { isLegendBinding, isLegendStreamBinding, SELECTION_ID } from '../../selection';\nimport { duplicate, vals, varName } from '../../util';\nimport { TUPLE_FIELDS } from './project';\nimport { TOGGLE } from './toggle';\nconst legendBindings = {\n defined: selCmpt => {\n const spec = selCmpt.resolve === 'global' && selCmpt.bind && isLegendBinding(selCmpt.bind);\n const projLen = selCmpt.project.items.length === 1 && selCmpt.project.items[0].field !== SELECTION_ID;\n if (spec && !projLen) {\n log.warn(log.message.LEGEND_BINDINGS_MUST_HAVE_PROJECTION);\n }\n return spec && projLen;\n },\n parse: (model, selCmpt, selDef) => {\n var _a;\n // Allow legend items to be toggleable by default even though direct manipulation is disabled.\n const selDef_ = duplicate(selDef);\n selDef_.select = isString(selDef_.select)\n ? { type: selDef_.select, toggle: selCmpt.toggle }\n : Object.assign(Object.assign({}, selDef_.select), { toggle: selCmpt.toggle });\n disableDirectManipulation(selCmpt, selDef_);\n if (isObject(selDef.select) && (selDef.select.on || selDef.select.clear)) {\n const legendFilter = 'event.item && indexof(event.item.mark.role, \"legend\") < 0';\n for (const evt of selCmpt.events) {\n evt.filter = array((_a = evt.filter) !== null && _a !== void 0 ? _a : []);\n if (!evt.filter.includes(legendFilter)) {\n evt.filter.push(legendFilter);\n }\n }\n }\n const evt = isLegendStreamBinding(selCmpt.bind) ? selCmpt.bind.legend : 'click';\n const stream = isString(evt) ? parseSelector(evt, 'view') : array(evt);\n selCmpt.bind = { legend: { merge: stream } };\n },\n topLevelSignals: (model, selCmpt, signals) => {\n const selName = selCmpt.name;\n const stream = isLegendStreamBinding(selCmpt.bind) && selCmpt.bind.legend;\n const markName = (name) => (s) => {\n const ds = duplicate(s);\n ds.markname = name;\n return ds;\n };\n for (const proj of selCmpt.project.items) {\n if (!proj.hasLegend)\n continue;\n const prefix = `${varName(proj.field)}_legend`;\n const sgName = `${selName}_${prefix}`;\n const hasSignal = signals.filter(s => s.name === sgName);\n if (hasSignal.length === 0) {\n const events = stream.merge\n .map(markName(`${prefix}_symbols`))\n .concat(stream.merge.map(markName(`${prefix}_labels`)))\n .concat(stream.merge.map(markName(`${prefix}_entries`)));\n signals.unshift(Object.assign(Object.assign({ name: sgName }, (!selCmpt.init ? { value: null } : {})), { on: [\n // Legend entries do not store values, so we need to walk the scenegraph to the symbol datum.\n { events, update: 'datum.value || item().items[0].items[0].datum.value', force: true },\n { events: stream.merge, update: `!event.item || !datum ? null : ${sgName}`, force: true }\n ] }));\n }\n }\n return signals;\n },\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const proj = selCmpt.project;\n const tuple = signals.find(s => s.name === name + TUPLE);\n const fields = name + TUPLE_FIELDS;\n const values = proj.items.filter(p => p.hasLegend).map(p => varName(`${name}_${varName(p.field)}_legend`));\n const valid = values.map(v => `${v} !== null`).join(' && ');\n const update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;\n if (selCmpt.events && values.length > 0) {\n tuple.on.push({\n events: values.map(signal => ({ signal })),\n update\n });\n }\n else if (values.length > 0) {\n tuple.update = update;\n delete tuple.value;\n delete tuple.on;\n }\n const toggle = signals.find(s => s.name === name + TOGGLE);\n const events = isLegendStreamBinding(selCmpt.bind) && selCmpt.bind.legend;\n if (toggle) {\n if (!selCmpt.events)\n toggle.on[0].events = events;\n else\n toggle.on.push(Object.assign(Object.assign({}, toggle.on[0]), { events }));\n }\n return signals;\n }\n};\nexport default legendBindings;\nexport function parseInteractiveLegend(model, channel, legendCmpt) {\n var _a, _b, _c, _d;\n const field = (_a = model.fieldDef(channel)) === null || _a === void 0 ? void 0 : _a.field;\n for (const selCmpt of vals((_b = model.component.selection) !== null && _b !== void 0 ? _b : {})) {\n const proj = (_c = selCmpt.project.hasField[field]) !== null && _c !== void 0 ? _c : selCmpt.project.hasChannel[channel];\n if (proj && legendBindings.defined(selCmpt)) {\n const legendSelections = (_d = legendCmpt.get('selections')) !== null && _d !== void 0 ? _d : [];\n legendSelections.push(selCmpt.name);\n legendCmpt.set('selections', legendSelections, false);\n proj.hasLegend = true;\n }\n }\n}\n//# sourceMappingURL=legends.js.map","import { selector as parseSelector } from 'vega-event-selector';\nimport { X, Y } from '../../channel';\nimport { BRUSH as INTERVAL_BRUSH } from './interval';\nimport scalesCompiler, { domain } from './scales';\nconst ANCHOR = '_translate_anchor';\nconst DELTA = '_translate_delta';\nconst translate = {\n defined: selCmpt => {\n return selCmpt.type === 'interval' && selCmpt.translate;\n },\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const hasScales = scalesCompiler.defined(selCmpt);\n const anchor = name + ANCHOR;\n const { x, y } = selCmpt.project.hasChannel;\n let events = parseSelector(selCmpt.translate, 'scope');\n if (!hasScales) {\n events = events.map(e => ((e.between[0].markname = name + INTERVAL_BRUSH), e));\n }\n signals.push({\n name: anchor,\n value: {},\n on: [\n {\n events: events.map(e => e.between[0]),\n update: '{x: x(unit), y: y(unit)' +\n (x !== undefined ? `, extent_x: ${hasScales ? domain(model, X) : `slice(${x.signals.visual})`}` : '') +\n (y !== undefined ? `, extent_y: ${hasScales ? domain(model, Y) : `slice(${y.signals.visual})`}` : '') +\n '}'\n }\n ]\n }, {\n name: name + DELTA,\n value: {},\n on: [\n {\n events: events,\n update: `{x: ${anchor}.x - x(unit), y: ${anchor}.y - y(unit)}`\n }\n ]\n });\n if (x !== undefined) {\n onDelta(model, selCmpt, x, 'width', signals);\n }\n if (y !== undefined) {\n onDelta(model, selCmpt, y, 'height', signals);\n }\n return signals;\n }\n};\nexport default translate;\nfunction onDelta(model, selCmpt, proj, size, signals) {\n var _a, _b;\n const name = selCmpt.name;\n const anchor = name + ANCHOR;\n const delta = name + DELTA;\n const channel = proj.channel;\n const hasScales = scalesCompiler.defined(selCmpt);\n const signal = signals.filter(s => s.name === proj.signals[hasScales ? 'data' : 'visual'])[0];\n const sizeSg = model.getSizeSignalRef(size).signal;\n const scaleCmpt = model.getScaleComponent(channel);\n const scaleType = scaleCmpt.get('type');\n const reversed = scaleCmpt.get('reverse'); // scale parsing sets this flag for fieldDef.sort\n const sign = !hasScales ? '' : channel === X ? (reversed ? '' : '-') : reversed ? '-' : '';\n const extent = `${anchor}.extent_${channel}`;\n const offset = `${sign}${delta}.${channel} / ${hasScales ? `${sizeSg}` : `span(${extent})`}`;\n const panFn = !hasScales\n ? 'panLinear'\n : scaleType === 'log'\n ? 'panLog'\n : scaleType === 'symlog'\n ? 'panSymlog'\n : scaleType === 'pow'\n ? 'panPow'\n : 'panLinear';\n const arg = !hasScales\n ? ''\n : scaleType === 'pow'\n ? `, ${(_a = scaleCmpt.get('exponent')) !== null && _a !== void 0 ? _a : 1}`\n : scaleType === 'symlog'\n ? `, ${(_b = scaleCmpt.get('constant')) !== null && _b !== void 0 ? _b : 1}`\n : '';\n const update = `${panFn}(${extent}, ${offset}${arg})`;\n signal.on.push({\n events: { signal: delta },\n update: hasScales ? update : `clampRange(${update}, 0, ${sizeSg})`\n });\n}\n//# sourceMappingURL=translate.js.map","import { selector as parseSelector } from 'vega-event-selector';\nimport { stringValue } from 'vega-util';\nimport { X, Y } from '../../channel';\nimport { BRUSH as INTERVAL_BRUSH } from './interval';\nimport { default as scalesCompiler, domain } from './scales';\nconst ANCHOR = '_zoom_anchor';\nconst DELTA = '_zoom_delta';\nconst zoom = {\n defined: selCmpt => {\n return selCmpt.type === 'interval' && selCmpt.zoom;\n },\n signals: (model, selCmpt, signals) => {\n const name = selCmpt.name;\n const hasScales = scalesCompiler.defined(selCmpt);\n const delta = name + DELTA;\n const { x, y } = selCmpt.project.hasChannel;\n const sx = stringValue(model.scaleName(X));\n const sy = stringValue(model.scaleName(Y));\n let events = parseSelector(selCmpt.zoom, 'scope');\n if (!hasScales) {\n events = events.map(e => ((e.markname = name + INTERVAL_BRUSH), e));\n }\n signals.push({\n name: name + ANCHOR,\n on: [\n {\n events: events,\n update: !hasScales\n ? `{x: x(unit), y: y(unit)}`\n : '{' +\n [sx ? `x: invert(${sx}, x(unit))` : '', sy ? `y: invert(${sy}, y(unit))` : '']\n .filter(expr => !!expr)\n .join(', ') +\n '}'\n }\n ]\n }, {\n name: delta,\n on: [\n {\n events: events,\n force: true,\n update: 'pow(1.001, event.deltaY * pow(16, event.deltaMode))'\n }\n ]\n });\n if (x !== undefined) {\n onDelta(model, selCmpt, x, 'width', signals);\n }\n if (y !== undefined) {\n onDelta(model, selCmpt, y, 'height', signals);\n }\n return signals;\n }\n};\nexport default zoom;\nfunction onDelta(model, selCmpt, proj, size, signals) {\n var _a, _b;\n const name = selCmpt.name;\n const channel = proj.channel;\n const hasScales = scalesCompiler.defined(selCmpt);\n const signal = signals.filter(s => s.name === proj.signals[hasScales ? 'data' : 'visual'])[0];\n const sizeSg = model.getSizeSignalRef(size).signal;\n const scaleCmpt = model.getScaleComponent(channel);\n const scaleType = scaleCmpt.get('type');\n const base = hasScales ? domain(model, channel) : signal.name;\n const delta = name + DELTA;\n const anchor = `${name}${ANCHOR}.${channel}`;\n const zoomFn = !hasScales\n ? 'zoomLinear'\n : scaleType === 'log'\n ? 'zoomLog'\n : scaleType === 'symlog'\n ? 'zoomSymlog'\n : scaleType === 'pow'\n ? 'zoomPow'\n : 'zoomLinear';\n const arg = !hasScales\n ? ''\n : scaleType === 'pow'\n ? `, ${(_a = scaleCmpt.get('exponent')) !== null && _a !== void 0 ? _a : 1}`\n : scaleType === 'symlog'\n ? `, ${(_b = scaleCmpt.get('constant')) !== null && _b !== void 0 ? _b : 1}`\n : '';\n const update = `${zoomFn}(${base}, ${anchor}, ${delta}${arg})`;\n signal.on.push({\n events: { signal: delta },\n update: hasScales ? update : `clampRange(${update}, 0, ${sizeSg})`\n });\n}\n//# sourceMappingURL=zoom.js.map","import { isString } from 'vega';\nimport { stringValue } from 'vega-util';\nimport { FACET_CHANNELS } from '../../channel';\nimport { SELECTION_ID } from '../../selection';\nimport { vals } from '../../util';\nimport { isFacetModel } from '../model';\nimport interval from './interval';\nimport point from './point';\nimport clear from './clear';\nimport inputs from './inputs';\nimport nearest from './nearest';\nimport project from './project';\nimport scales from './scales';\nimport legends from './legends';\nimport toggle from './toggle';\nimport translate from './translate';\nimport zoom from './zoom';\nexport const STORE = '_store';\nexport const TUPLE = '_tuple';\nexport const MODIFY = '_modify';\nexport const SELECTION_DOMAIN = '_selection_domain_';\nexport const VL_SELECTION_RESOLVE = 'vlSelectionResolve';\n// Order matters for parsing and assembly.\nexport const selectionCompilers = [\n point,\n interval,\n project,\n toggle,\n // Bindings may disable direct manipulation.\n inputs,\n scales,\n legends,\n clear,\n translate,\n zoom,\n nearest\n];\nfunction getFacetModel(model) {\n let parent = model.parent;\n while (parent) {\n if (isFacetModel(parent))\n break;\n parent = parent.parent;\n }\n return parent;\n}\nexport function unitName(model, { escape } = { escape: true }) {\n let name = escape ? stringValue(model.name) : model.name;\n const facetModel = getFacetModel(model);\n if (facetModel) {\n const { facet } = facetModel;\n for (const channel of FACET_CHANNELS) {\n if (facet[channel]) {\n name += ` + '__facet_${channel}_' + (facet[${stringValue(facetModel.vgField(channel))}])`;\n }\n }\n }\n return name;\n}\nexport function requiresSelectionId(model) {\n var _a;\n return vals((_a = model.component.selection) !== null && _a !== void 0 ? _a : {}).reduce((identifier, selCmpt) => {\n return identifier || selCmpt.project.items.some(proj => proj.field === SELECTION_ID);\n }, false);\n}\n// Binding a point selection to query widgets or legends disables default direct manipulation interaction.\n// A user can choose to re-enable it by explicitly specifying triggering input events.\nexport function disableDirectManipulation(selCmpt, selDef) {\n if (isString(selDef.select) || !selDef.select.on)\n delete selCmpt.events;\n if (isString(selDef.select) || !selDef.select.clear)\n delete selCmpt.clear;\n if (isString(selDef.select) || !selDef.select.toggle)\n delete selCmpt.toggle;\n}\n//# sourceMappingURL=index.js.map","import { error, toSet, isFunction, isString, hasOwnProperty } from 'vega-util';\n\nconst RawCode = 'RawCode';\nconst Literal = 'Literal';\nconst Property = 'Property';\nconst Identifier = 'Identifier';\nconst ArrayExpression = 'ArrayExpression';\nconst BinaryExpression = 'BinaryExpression';\nconst CallExpression = 'CallExpression';\nconst ConditionalExpression = 'ConditionalExpression';\nconst LogicalExpression = 'LogicalExpression';\nconst MemberExpression = 'MemberExpression';\nconst ObjectExpression = 'ObjectExpression';\nconst UnaryExpression = 'UnaryExpression';\nfunction ASTNode(type) {\n this.type = type;\n}\n\nASTNode.prototype.visit = function (visitor) {\n let c, i, n;\n if (visitor(this)) return 1;\n\n for (c = children(this), i = 0, n = c.length; i < n; ++i) {\n if (c[i].visit(visitor)) return 1;\n }\n};\n\nfunction children(node) {\n switch (node.type) {\n case ArrayExpression:\n return node.elements;\n\n case BinaryExpression:\n case LogicalExpression:\n return [node.left, node.right];\n\n case CallExpression:\n return [node.callee].concat(node.arguments);\n\n case ConditionalExpression:\n return [node.test, node.consequent, node.alternate];\n\n case MemberExpression:\n return [node.object, node.property];\n\n case ObjectExpression:\n return node.properties;\n\n case Property:\n return [node.key, node.value];\n\n case UnaryExpression:\n return [node.argument];\n\n case Identifier:\n case Literal:\n case RawCode:\n default:\n return [];\n }\n}\n\n/*\n The following expression parser is based on Esprima (http://esprima.org/).\n Original header comment and license for Esprima is included here:\n\n Copyright (C) 2013 Ariya Hidayat \n Copyright (C) 2013 Thaddee Tyl \n Copyright (C) 2013 Mathias Bynens \n Copyright (C) 2012 Ariya Hidayat \n Copyright (C) 2012 Mathias Bynens \n Copyright (C) 2012 Joost-Wim Boekesteijn \n Copyright (C) 2012 Kris Kowal \n Copyright (C) 2012 Yusuke Suzuki \n Copyright (C) 2012 Arpad Borsos \n Copyright (C) 2011 Ariya Hidayat \n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\nvar TokenName, source, index, length, lookahead;\nvar TokenBooleanLiteral = 1,\n TokenEOF = 2,\n TokenIdentifier = 3,\n TokenKeyword = 4,\n TokenNullLiteral = 5,\n TokenNumericLiteral = 6,\n TokenPunctuator = 7,\n TokenStringLiteral = 8,\n TokenRegularExpression = 9;\nTokenName = {};\nTokenName[TokenBooleanLiteral] = 'Boolean';\nTokenName[TokenEOF] = '';\nTokenName[TokenIdentifier] = 'Identifier';\nTokenName[TokenKeyword] = 'Keyword';\nTokenName[TokenNullLiteral] = 'Null';\nTokenName[TokenNumericLiteral] = 'Numeric';\nTokenName[TokenPunctuator] = 'Punctuator';\nTokenName[TokenStringLiteral] = 'String';\nTokenName[TokenRegularExpression] = 'RegularExpression';\nvar SyntaxArrayExpression = 'ArrayExpression',\n SyntaxBinaryExpression = 'BinaryExpression',\n SyntaxCallExpression = 'CallExpression',\n SyntaxConditionalExpression = 'ConditionalExpression',\n SyntaxIdentifier = 'Identifier',\n SyntaxLiteral = 'Literal',\n SyntaxLogicalExpression = 'LogicalExpression',\n SyntaxMemberExpression = 'MemberExpression',\n SyntaxObjectExpression = 'ObjectExpression',\n SyntaxProperty = 'Property',\n SyntaxUnaryExpression = 'UnaryExpression'; // Error messages should be identical to V8.\n\nvar MessageUnexpectedToken = 'Unexpected token %0',\n MessageUnexpectedNumber = 'Unexpected number',\n MessageUnexpectedString = 'Unexpected string',\n MessageUnexpectedIdentifier = 'Unexpected identifier',\n MessageUnexpectedReserved = 'Unexpected reserved word',\n MessageUnexpectedEOS = 'Unexpected end of input',\n MessageInvalidRegExp = 'Invalid regular expression',\n MessageUnterminatedRegExp = 'Invalid regular expression: missing /',\n MessageStrictOctalLiteral = 'Octal literals are not allowed in strict mode.',\n MessageStrictDuplicateProperty = 'Duplicate data property in object literal not allowed in strict mode';\nvar ILLEGAL = 'ILLEGAL',\n DISABLED = 'Disabled.'; // See also tools/generate-unicode-regex.py.\n\nvar RegexNonAsciiIdentifierStart = new RegExp('[\\\\xAA\\\\xB5\\\\xBA\\\\xC0-\\\\xD6\\\\xD8-\\\\xF6\\\\xF8-\\\\u02C1\\\\u02C6-\\\\u02D1\\\\u02E0-\\\\u02E4\\\\u02EC\\\\u02EE\\\\u0370-\\\\u0374\\\\u0376\\\\u0377\\\\u037A-\\\\u037D\\\\u037F\\\\u0386\\\\u0388-\\\\u038A\\\\u038C\\\\u038E-\\\\u03A1\\\\u03A3-\\\\u03F5\\\\u03F7-\\\\u0481\\\\u048A-\\\\u052F\\\\u0531-\\\\u0556\\\\u0559\\\\u0561-\\\\u0587\\\\u05D0-\\\\u05EA\\\\u05F0-\\\\u05F2\\\\u0620-\\\\u064A\\\\u066E\\\\u066F\\\\u0671-\\\\u06D3\\\\u06D5\\\\u06E5\\\\u06E6\\\\u06EE\\\\u06EF\\\\u06FA-\\\\u06FC\\\\u06FF\\\\u0710\\\\u0712-\\\\u072F\\\\u074D-\\\\u07A5\\\\u07B1\\\\u07CA-\\\\u07EA\\\\u07F4\\\\u07F5\\\\u07FA\\\\u0800-\\\\u0815\\\\u081A\\\\u0824\\\\u0828\\\\u0840-\\\\u0858\\\\u08A0-\\\\u08B2\\\\u0904-\\\\u0939\\\\u093D\\\\u0950\\\\u0958-\\\\u0961\\\\u0971-\\\\u0980\\\\u0985-\\\\u098C\\\\u098F\\\\u0990\\\\u0993-\\\\u09A8\\\\u09AA-\\\\u09B0\\\\u09B2\\\\u09B6-\\\\u09B9\\\\u09BD\\\\u09CE\\\\u09DC\\\\u09DD\\\\u09DF-\\\\u09E1\\\\u09F0\\\\u09F1\\\\u0A05-\\\\u0A0A\\\\u0A0F\\\\u0A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u0DBD\\\\u0DC0-\\\\u0DC6\\\\u0E01-\\\\u0E30\\\\u0E32\\\\u0E33\\\\u0E40-\\\\u0E46\\\\u0E81\\\\u0E82\\\\u0E84\\\\u0E87\\\\u0E88\\\\u0E8A\\\\u0E8D\\\\u0E94-\\\\u0E97\\\\u0E99-\\\\u0E9F\\\\u0EA1-\\\\u0EA3\\\\u0EA5\\\\u0EA7\\\\u0EAA\\\\u0EAB\\\\u0EAD-\\\\u0EB0\\\\u0EB2\\\\u0EB3\\\\u0EBD\\\\u0EC0-\\\\u0EC4\\\\u0EC6\\\\u0EDC-\\\\u0EDF\\\\u0F00\\\\u0F40-\\\\u0F47\\\\u0F49-\\\\u0F6C\\\\u0F88-\\\\u0F8C\\\\u1000-\\\\u102A\\\\u103F\\\\u1050-\\\\u1055\\\\u105A-\\\\u105D\\\\u1061\\\\u1065\\\\u1066\\\\u106E-\\\\u1070\\\\u1075-\\\\u1081\\\\u108E\\\\u10A0-\\\\u10C5\\\\u10C7\\\\u10CD\\\\u10D0-\\\\u10FA\\\\u10FC-\\\\u1248\\\\u124A-\\\\u124D\\\\u1250-\\\\u1256\\\\u1258\\\\u125A-\\\\u125D\\\\u1260-\\\\u1288\\\\u128A-\\\\u128D\\\\u1290-\\\\u12B0\\\\u12B2-\\\\u12B5\\\\u12B8-\\\\u12BE\\\\u12C0\\\\u12C2-\\\\u12C5\\\\u12C8-\\\\u12D6\\\\u12D8-\\\\u1310\\\\u1312-\\\\u1315\\\\u1318-\\\\u135A\\\\u1380-\\\\u138F\\\\u13A0-\\\\u13F4\\\\u1401-\\\\u166C\\\\u166F-\\\\u167F\\\\u1681-\\\\u169A\\\\u16A0-\\\\u16EA\\\\u16EE-\\\\u16F8\\\\u1700-\\\\u170C\\\\u170E-\\\\u1711\\\\u1720-\\\\u1731\\\\u1740-\\\\u1751\\\\u1760-\\\\u176C\\\\u176E-\\\\u1770\\\\u1780-\\\\u17B3\\\\u17D7\\\\u17DC\\\\u1820-\\\\u1877\\\\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\\u2D80-\\\\u2D96\\\\u2DA0-\\\\u2DA6\\\\u2DA8-\\\\u2DAE\\\\u2DB0-\\\\u2DB6\\\\u2DB8-\\\\u2DBE\\\\u2DC0-\\\\u2DC6\\\\u2DC8-\\\\u2DCE\\\\u2DD0-\\\\u2DD6\\\\u2DD8-\\\\u2DDE\\\\u2E2F\\\\u3005-\\\\u3007\\\\u3021-\\\\u3029\\\\u3031-\\\\u3035\\\\u3038-\\\\u303C\\\\u3041-\\\\u3096\\\\u309D-\\\\u309F\\\\u30A1-\\\\u30FA\\\\u30FC-\\\\u30FF\\\\u3105-\\\\u312D\\\\u3131-\\\\u318E\\\\u31A0-\\\\u31BA\\\\u31F0-\\\\u31FF\\\\u3400-\\\\u4DB5\\\\u4E00-\\\\u9FCC\\\\uA000-\\\\uA48C\\\\uA4D0-\\\\uA4FD\\\\uA500-\\\\uA60C\\\\uA610-\\\\uA61F\\\\uA62A\\\\uA62B\\\\uA640-\\\\uA66E\\\\uA67F-\\\\uA69D\\\\uA6A0-\\\\uA6EF\\\\uA717-\\\\uA71F\\\\uA722-\\\\uA788\\\\uA78B-\\\\uA78E\\\\uA790-\\\\uA7AD\\\\uA7B0\\\\uA7B1\\\\uA7F7-\\\\uA801\\\\uA803-\\\\uA805\\\\uA807-\\\\uA80A\\\\uA80C-\\\\uA822\\\\uA840-\\\\uA873\\\\uA882-\\\\uA8B3\\\\uA8F2-\\\\uA8F7\\\\uA8FB\\\\uA90A-\\\\uA925\\\\uA930-\\\\uA946\\\\uA960-\\\\uA97C\\\\uA984-\\\\uA9B2\\\\uA9CF\\\\uA9E0-\\\\uA9E4\\\\uA9E6-\\\\uA9EF\\\\uA9FA-\\\\uA9FE\\\\uAA00-\\\\uAA28\\\\uAA40-\\\\uAA42\\\\uAA44-\\\\uAA4B\\\\uAA60-\\\\uAA76\\\\uAA7A\\\\uAA7E-\\\\uAAAF\\\\uAAB1\\\\uAAB5\\\\uAAB6\\\\uAAB9-\\\\uAABD\\\\uAAC0\\\\uAAC2\\\\uAADB-\\\\uAADD\\\\uAAE0-\\\\uAAEA\\\\uAAF2-\\\\uAAF4\\\\uAB01-\\\\uAB06\\\\uAB09-\\\\uAB0E\\\\uAB11-\\\\uAB16\\\\uAB20-\\\\uAB26\\\\uAB28-\\\\uAB2E\\\\uAB30-\\\\uAB5A\\\\uAB5C-\\\\uAB5F\\\\uAB64\\\\uAB65\\\\uABC0-\\\\uABE2\\\\uAC00-\\\\uD7A3\\\\uD7B0-\\\\uD7C6\\\\uD7CB-\\\\uD7FB\\\\uF900-\\\\uFA6D\\\\uFA70-\\\\uFAD9\\\\uFB00-\\\\uFB06\\\\uFB13-\\\\uFB17\\\\uFB1D\\\\uFB1F-\\\\uFB28\\\\uFB2A-\\\\uFB36\\\\uFB38-\\\\uFB3C\\\\uFB3E\\\\uFB40\\\\uFB41\\\\uFB43\\\\uFB44\\\\uFB46-\\\\uFBB1\\\\uFBD3-\\\\uFD3D\\\\uFD50-\\\\uFD8F\\\\uFD92-\\\\uFDC7\\\\uFDF0-\\\\uFDFB\\\\uFE70-\\\\uFE74\\\\uFE76-\\\\uFEFC\\\\uFF21-\\\\uFF3A\\\\uFF41-\\\\uFF5A\\\\uFF66-\\\\uFFBE\\\\uFFC2-\\\\uFFC7\\\\uFFCA-\\\\uFFCF\\\\uFFD2-\\\\uFFD7\\\\uFFDA-\\\\uFFDC]'),\n // eslint-disable-next-line no-misleading-character-class\nRegexNonAsciiIdentifierPart = new RegExp('[\\\\xAA\\\\xB5\\\\xBA\\\\xC0-\\\\xD6\\\\xD8-\\\\xF6\\\\xF8-\\\\u02C1\\\\u02C6-\\\\u02D1\\\\u02E0-\\\\u02E4\\\\u02EC\\\\u02EE\\\\u0300-\\\\u0374\\\\u0376\\\\u0377\\\\u037A-\\\\u037D\\\\u037F\\\\u0386\\\\u0388-\\\\u038A\\\\u038C\\\\u038E-\\\\u03A1\\\\u03A3-\\\\u03F5\\\\u03F7-\\\\u0481\\\\u0483-\\\\u0487\\\\u048A-\\\\u052F\\\\u0531-\\\\u0556\\\\u0559\\\\u0561-\\\\u0587\\\\u0591-\\\\u05BD\\\\u05BF\\\\u05C1\\\\u05C2\\\\u05C4\\\\u05C5\\\\u05C7\\\\u05D0-\\\\u05EA\\\\u05F0-\\\\u05F2\\\\u0610-\\\\u061A\\\\u0620-\\\\u0669\\\\u066E-\\\\u06D3\\\\u06D5-\\\\u06DC\\\\u06DF-\\\\u06E8\\\\u06EA-\\\\u06FC\\\\u06FF\\\\u0710-\\\\u074A\\\\u074D-\\\\u07B1\\\\u07C0-\\\\u07F5\\\\u07FA\\\\u0800-\\\\u082D\\\\u0840-\\\\u085B\\\\u08A0-\\\\u08B2\\\\u08E4-\\\\u0963\\\\u0966-\\\\u096F\\\\u0971-\\\\u0983\\\\u0985-\\\\u098C\\\\u098F\\\\u0990\\\\u0993-\\\\u09A8\\\\u09AA-\\\\u09B0\\\\u09B2\\\\u09B6-\\\\u09B9\\\\u09BC-\\\\u09C4\\\\u09C7\\\\u09C8\\\\u09CB-\\\\u09CE\\\\u09D7\\\\u09DC\\\\u09DD\\\\u09DF-\\\\u09E3\\\\u09E6-\\\\u09F1\\\\u0A01-\\\\u0A03\\\\u0A05-\\\\u0A0A\\\\u0A0F\\\\u0A10\\\\u0A13-\\\\u0A28\\\\u0A2A-\\\\u0A30\\\\u0A32\\\\u0A33\\\\u0A35\\\\u0A36\\\\u0A38\\\\u0A39\\\\u0A3C\\\\u0A3E-\\\\u0A42\\\\u0A47\\\\u0A48\\\\u0A4B-\\\\u0A4D\\\\u0A51\\\\u0A59-\\\\u0A5C\\\\u0A5E\\\\u0A66-\\\\u0A75\\\\u0A81-\\\\u0A83\\\\u0A85-\\\\u0A8D\\\\u0A8F-\\\\u0A91\\\\u0A93-\\\\u0AA8\\\\u0AAA-\\\\u0AB0\\\\u0AB2\\\\u0AB3\\\\u0AB5-\\\\u0AB9\\\\u0ABC-\\\\u0AC5\\\\u0AC7-\\\\u0AC9\\\\u0ACB-\\\\u0AC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\\\\u128A-\\\\u128D\\\\u1290-\\\\u12B0\\\\u12B2-\\\\u12B5\\\\u12B8-\\\\u12BE\\\\u12C0\\\\u12C2-\\\\u12C5\\\\u12C8-\\\\u12D6\\\\u12D8-\\\\u1310\\\\u1312-\\\\u1315\\\\u1318-\\\\u135A\\\\u135D-\\\\u135F\\\\u1380-\\\\u138F\\\\u13A0-\\\\u13F4\\\\u1401-\\\\u166C\\\\u166F-\\\\u167F\\\\u1681-\\\\u169A\\\\u16A0-\\\\u16EA\\\\u16EE-\\\\u16F8\\\\u1700-\\\\u170C\\\\u170E-\\\\u1714\\\\u1720-\\\\u1734\\\\u1740-\\\\u1753\\\\u1760-\\\\u176C\\\\u176E-\\\\u1770\\\\u1772\\\\u1773\\\\u1780-\\\\u17D3\\\\u17D7\\\\u17DC\\\\u17DD\\\\u17E0-\\\\u17E9\\\\u180B-\\\\u180D\\\\u1810-\\\\u1819\\\\u1820-\\\\u1877\\\\u1880-\\\\u18AA\\\\u18B0-\\\\u18F5\\\\u1900-\\\\u191E\\\\u1920-\\\\u192B\\\\u1930-\\\\u193B\\\\u1946-\\\\u196D\\\\u1970-\\\\u1974\\\\u1980-\\\\u19AB\\\\u19B0-\\\\u19C9\\\\u19D0-\\\\u19D9\\\\u1A00-\\\\u1A1B\\\\u1A20-\\\\u1A5E\\\\u1A60-\\\\u1A7C\\\\u1A7F-\\\\u1A89\\\\u1A90-\\\\u1A99\\\\u1AA7\\\\u1AB0-\\\\u1ABD\\\\u1B00-\\\\u1B4B\\\\u1B50-\\\\u1B59\\\\u1B6B-\\\\u1B73\\\\u1B80-\\\\u1BF3\\\\u1C00-\\\\u1C37\\\\u1C40-\\\\u1C49\\\\u1C4D-\\\\u1C7D\\\\u1CD0-\\\\u1CD2\\\\u1CD4-\\\\u1CF6\\\\u1CF8\\\\u1CF9\\\\u1D00-\\\\u1DF5\\\\u1DFC-\\\\u1F15\\\\u1F18-\\\\u1F1D\\\\u1F20-\\\\u1F45\\\\u1F48-\\\\u1F4D\\\\u1F50-\\\\u1F57\\\\u1F59\\\\u1F5B\\\\u1F5D\\\\u1F5F-\\\\u1F7D\\\\u1F80-\\\\u1FB4\\\\u1FB6-\\\\u1FBC\\\\u1FBE\\\\u1FC2-\\\\u1FC4\\\\u1FC6-\\\\u1FCC\\\\u1FD0-\\\\u1FD3\\\\u1FD6-\\\\u1FDB\\\\u1FE0-\\\\u1FEC\\\\u1FF2-\\\\u1FF4\\\\u1FF6-\\\\u1FFC\\\\u200C\\\\u200D\\\\u203F\\\\u2040\\\\u2054\\\\u2071\\\\u207F\\\\u2090-\\\\u209C\\\\u20D0-\\\\u20DC\\\\u20E1\\\\u20E5-\\\\u20F0\\\\u2102\\\\u2107\\\\u210A-\\\\u2113\\\\u2115\\\\u2119-\\\\u211D\\\\u2124\\\\u2126\\\\u2128\\\\u212A-\\\\u212D\\\\u212F-\\\\u2139\\\\u213C-\\\\u213F\\\\u2145-\\\\u2149\\\\u214E\\\\u2160-\\\\u2188\\\\u2C00-\\\\u2C2E\\\\u2C30-\\\\u2C5E\\\\u2C60-\\\\u2CE4\\\\u2CEB-\\\\u2CF3\\\\u2D00-\\\\u2D25\\\\u2D27\\\\u2D2D\\\\u2D30-\\\\u2D67\\\\u2D6F\\\\u2D7F-\\\\u2D96\\\\u2DA0-\\\\u2DA6\\\\u2DA8-\\\\u2DAE\\\\u2DB0-\\\\u2DB6\\\\u2DB8-\\\\u2DBE\\\\u2DC0-\\\\u2DC6\\\\u2DC8-\\\\u2DCE\\\\u2DD0-\\\\u2DD6\\\\u2DD8-\\\\u2DDE\\\\u2DE0-\\\\u2DFF\\\\u2E2F\\\\u3005-\\\\u3007\\\\u3021-\\\\u302F\\\\u3031-\\\\u3035\\\\u3038-\\\\u303C\\\\u3041-\\\\u3096\\\\u3099\\\\u309A\\\\u309D-\\\\u309F\\\\u30A1-\\\\u30FA\\\\u30FC-\\\\u30FF\\\\u3105-\\\\u312D\\\\u3131-\\\\u318E\\\\u31A0-\\\\u31BA\\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46-\\\\uFBB1\\\\uFBD3-\\\\uFD3D\\\\uFD50-\\\\uFD8F\\\\uFD92-\\\\uFDC7\\\\uFDF0-\\\\uFDFB\\\\uFE00-\\\\uFE0F\\\\uFE20-\\\\uFE2D\\\\uFE33\\\\uFE34\\\\uFE4D-\\\\uFE4F\\\\uFE70-\\\\uFE74\\\\uFE76-\\\\uFEFC\\\\uFF10-\\\\uFF19\\\\uFF21-\\\\uFF3A\\\\uFF3F\\\\uFF41-\\\\uFF5A\\\\uFF66-\\\\uFFBE\\\\uFFC2-\\\\uFFC7\\\\uFFCA-\\\\uFFCF\\\\uFFD2-\\\\uFFD7\\\\uFFDA-\\\\uFFDC]'); // Ensure the condition is true, otherwise throw an error.\n// This is only to have a better contract semantic, i.e. another safety net\n// to catch a logic error. The condition shall be fulfilled in normal case.\n// Do NOT use this to enforce a certain condition on any user input.\n\nfunction assert(condition, message) {\n /* istanbul ignore next */\n if (!condition) {\n throw new Error('ASSERT: ' + message);\n }\n}\n\nfunction isDecimalDigit(ch) {\n return ch >= 0x30 && ch <= 0x39; // 0..9\n}\n\nfunction isHexDigit(ch) {\n return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;\n}\n\nfunction isOctalDigit(ch) {\n return '01234567'.indexOf(ch) >= 0;\n} // 7.2 White Space\n\n\nfunction isWhiteSpace(ch) {\n return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0;\n} // 7.3 Line Terminators\n\n\nfunction isLineTerminator(ch) {\n return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;\n} // 7.6 Identifier Names and Identifiers\n\n\nfunction isIdentifierStart(ch) {\n return ch === 0x24 || ch === 0x5F || // $ (dollar) and _ (underscore)\n ch >= 0x41 && ch <= 0x5A || // A..Z\n ch >= 0x61 && ch <= 0x7A || // a..z\n ch === 0x5C || // \\ (backslash)\n ch >= 0x80 && RegexNonAsciiIdentifierStart.test(String.fromCharCode(ch));\n}\n\nfunction isIdentifierPart(ch) {\n return ch === 0x24 || ch === 0x5F || // $ (dollar) and _ (underscore)\n ch >= 0x41 && ch <= 0x5A || // A..Z\n ch >= 0x61 && ch <= 0x7A || // a..z\n ch >= 0x30 && ch <= 0x39 || // 0..9\n ch === 0x5C || // \\ (backslash)\n ch >= 0x80 && RegexNonAsciiIdentifierPart.test(String.fromCharCode(ch));\n} // 7.6.1.1 Keywords\n\n\nconst keywords = {\n 'if': 1,\n 'in': 1,\n 'do': 1,\n 'var': 1,\n 'for': 1,\n 'new': 1,\n 'try': 1,\n 'let': 1,\n 'this': 1,\n 'else': 1,\n 'case': 1,\n 'void': 1,\n 'with': 1,\n 'enum': 1,\n 'while': 1,\n 'break': 1,\n 'catch': 1,\n 'throw': 1,\n 'const': 1,\n 'yield': 1,\n 'class': 1,\n 'super': 1,\n 'return': 1,\n 'typeof': 1,\n 'delete': 1,\n 'switch': 1,\n 'export': 1,\n 'import': 1,\n 'public': 1,\n 'static': 1,\n 'default': 1,\n 'finally': 1,\n 'extends': 1,\n 'package': 1,\n 'private': 1,\n 'function': 1,\n 'continue': 1,\n 'debugger': 1,\n 'interface': 1,\n 'protected': 1,\n 'instanceof': 1,\n 'implements': 1\n};\n\nfunction skipComment() {\n while (index < length) {\n const ch = source.charCodeAt(index);\n\n if (isWhiteSpace(ch) || isLineTerminator(ch)) {\n ++index;\n } else {\n break;\n }\n }\n}\n\nfunction scanHexEscape(prefix) {\n var i,\n len,\n ch,\n code = 0;\n len = prefix === 'u' ? 4 : 2;\n\n for (i = 0; i < len; ++i) {\n if (index < length && isHexDigit(source[index])) {\n ch = source[index++];\n code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());\n } else {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n }\n\n return String.fromCharCode(code);\n}\n\nfunction scanUnicodeCodePointEscape() {\n var ch, code, cu1, cu2;\n ch = source[index];\n code = 0; // At least, one hex digit is required.\n\n if (ch === '}') {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n while (index < length) {\n ch = source[index++];\n\n if (!isHexDigit(ch)) {\n break;\n }\n\n code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());\n }\n\n if (code > 0x10FFFF || ch !== '}') {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n } // UTF-16 Encoding\n\n\n if (code <= 0xFFFF) {\n return String.fromCharCode(code);\n }\n\n cu1 = (code - 0x10000 >> 10) + 0xD800;\n cu2 = (code - 0x10000 & 1023) + 0xDC00;\n return String.fromCharCode(cu1, cu2);\n}\n\nfunction getEscapedIdentifier() {\n var ch, id;\n ch = source.charCodeAt(index++);\n id = String.fromCharCode(ch); // '\\u' (U+005C, U+0075) denotes an escaped character.\n\n if (ch === 0x5C) {\n if (source.charCodeAt(index) !== 0x75) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n ++index;\n ch = scanHexEscape('u');\n\n if (!ch || ch === '\\\\' || !isIdentifierStart(ch.charCodeAt(0))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n id = ch;\n }\n\n while (index < length) {\n ch = source.charCodeAt(index);\n\n if (!isIdentifierPart(ch)) {\n break;\n }\n\n ++index;\n id += String.fromCharCode(ch); // '\\u' (U+005C, U+0075) denotes an escaped character.\n\n if (ch === 0x5C) {\n id = id.substr(0, id.length - 1);\n\n if (source.charCodeAt(index) !== 0x75) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n ++index;\n ch = scanHexEscape('u');\n\n if (!ch || ch === '\\\\' || !isIdentifierPart(ch.charCodeAt(0))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n id += ch;\n }\n }\n\n return id;\n}\n\nfunction getIdentifier() {\n var start, ch;\n start = index++;\n\n while (index < length) {\n ch = source.charCodeAt(index);\n\n if (ch === 0x5C) {\n // Blackslash (U+005C) marks Unicode escape sequence.\n index = start;\n return getEscapedIdentifier();\n }\n\n if (isIdentifierPart(ch)) {\n ++index;\n } else {\n break;\n }\n }\n\n return source.slice(start, index);\n}\n\nfunction scanIdentifier() {\n var start, id, type;\n start = index; // Backslash (U+005C) starts an escaped character.\n\n id = source.charCodeAt(index) === 0x5C ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character.\n // Thus, it must be an identifier.\n\n if (id.length === 1) {\n type = TokenIdentifier;\n } else if (keywords.hasOwnProperty(id)) {\n // eslint-disable-line no-prototype-builtins\n type = TokenKeyword;\n } else if (id === 'null') {\n type = TokenNullLiteral;\n } else if (id === 'true' || id === 'false') {\n type = TokenBooleanLiteral;\n } else {\n type = TokenIdentifier;\n }\n\n return {\n type: type,\n value: id,\n start: start,\n end: index\n };\n} // 7.7 Punctuators\n\n\nfunction scanPunctuator() {\n var start = index,\n code = source.charCodeAt(index),\n code2,\n ch1 = source[index],\n ch2,\n ch3,\n ch4;\n\n switch (code) {\n // Check for most common single-character punctuators.\n case 0x2E: // . dot\n\n case 0x28: // ( open bracket\n\n case 0x29: // ) close bracket\n\n case 0x3B: // ; semicolon\n\n case 0x2C: // , comma\n\n case 0x7B: // { open curly brace\n\n case 0x7D: // } close curly brace\n\n case 0x5B: // [\n\n case 0x5D: // ]\n\n case 0x3A: // :\n\n case 0x3F: // ?\n\n case 0x7E:\n // ~\n ++index;\n return {\n type: TokenPunctuator,\n value: String.fromCharCode(code),\n start: start,\n end: index\n };\n\n default:\n code2 = source.charCodeAt(index + 1); // '=' (U+003D) marks an assignment or comparison operator.\n\n if (code2 === 0x3D) {\n switch (code) {\n case 0x2B: // +\n\n case 0x2D: // -\n\n case 0x2F: // /\n\n case 0x3C: // <\n\n case 0x3E: // >\n\n case 0x5E: // ^\n\n case 0x7C: // |\n\n case 0x25: // %\n\n case 0x26: // &\n\n case 0x2A:\n // *\n index += 2;\n return {\n type: TokenPunctuator,\n value: String.fromCharCode(code) + String.fromCharCode(code2),\n start: start,\n end: index\n };\n\n case 0x21: // !\n\n case 0x3D:\n // =\n index += 2; // !== and ===\n\n if (source.charCodeAt(index) === 0x3D) {\n ++index;\n }\n\n return {\n type: TokenPunctuator,\n value: source.slice(start, index),\n start: start,\n end: index\n };\n }\n }\n\n } // 4-character punctuator: >>>=\n\n\n ch4 = source.substr(index, 4);\n\n if (ch4 === '>>>=') {\n index += 4;\n return {\n type: TokenPunctuator,\n value: ch4,\n start: start,\n end: index\n };\n } // 3-character punctuators: === !== >>> <<= >>=\n\n\n ch3 = ch4.substr(0, 3);\n\n if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {\n index += 3;\n return {\n type: TokenPunctuator,\n value: ch3,\n start: start,\n end: index\n };\n } // Other 2-character punctuators: ++ -- << >> && ||\n\n\n ch2 = ch3.substr(0, 2);\n\n if (ch1 === ch2[1] && '+-<>&|'.indexOf(ch1) >= 0 || ch2 === '=>') {\n index += 2;\n return {\n type: TokenPunctuator,\n value: ch2,\n start: start,\n end: index\n };\n }\n\n if (ch2 === '//') {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n } // 1-character punctuators: < > = ! + - * % & | ^ /\n\n\n if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {\n ++index;\n return {\n type: TokenPunctuator,\n value: ch1,\n start: start,\n end: index\n };\n }\n\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n} // 7.8.3 Numeric Literals\n\n\nfunction scanHexLiteral(start) {\n let number = '';\n\n while (index < length) {\n if (!isHexDigit(source[index])) {\n break;\n }\n\n number += source[index++];\n }\n\n if (number.length === 0) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n if (isIdentifierStart(source.charCodeAt(index))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n return {\n type: TokenNumericLiteral,\n value: parseInt('0x' + number, 16),\n start: start,\n end: index\n };\n}\n\nfunction scanOctalLiteral(start) {\n let number = '0' + source[index++];\n\n while (index < length) {\n if (!isOctalDigit(source[index])) {\n break;\n }\n\n number += source[index++];\n }\n\n if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n return {\n type: TokenNumericLiteral,\n value: parseInt(number, 8),\n octal: true,\n start: start,\n end: index\n };\n}\n\nfunction scanNumericLiteral() {\n var number, start, ch;\n ch = source[index];\n assert(isDecimalDigit(ch.charCodeAt(0)) || ch === '.', 'Numeric literal must start with a decimal digit or a decimal point');\n start = index;\n number = '';\n\n if (ch !== '.') {\n number = source[index++];\n ch = source[index]; // Hex number starts with '0x'.\n // Octal number starts with '0'.\n\n if (number === '0') {\n if (ch === 'x' || ch === 'X') {\n ++index;\n return scanHexLiteral(start);\n }\n\n if (isOctalDigit(ch)) {\n return scanOctalLiteral(start);\n } // decimal number starts with '0' such as '09' is illegal.\n\n\n if (ch && isDecimalDigit(ch.charCodeAt(0))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n }\n\n while (isDecimalDigit(source.charCodeAt(index))) {\n number += source[index++];\n }\n\n ch = source[index];\n }\n\n if (ch === '.') {\n number += source[index++];\n\n while (isDecimalDigit(source.charCodeAt(index))) {\n number += source[index++];\n }\n\n ch = source[index];\n }\n\n if (ch === 'e' || ch === 'E') {\n number += source[index++];\n ch = source[index];\n\n if (ch === '+' || ch === '-') {\n number += source[index++];\n }\n\n if (isDecimalDigit(source.charCodeAt(index))) {\n while (isDecimalDigit(source.charCodeAt(index))) {\n number += source[index++];\n }\n } else {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n }\n\n if (isIdentifierStart(source.charCodeAt(index))) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n return {\n type: TokenNumericLiteral,\n value: parseFloat(number),\n start: start,\n end: index\n };\n} // 7.8.4 String Literals\n\n\nfunction scanStringLiteral() {\n var str = '',\n quote,\n start,\n ch,\n code,\n octal = false;\n quote = source[index];\n assert(quote === '\\'' || quote === '\"', 'String literal must starts with a quote');\n start = index;\n ++index;\n\n while (index < length) {\n ch = source[index++];\n\n if (ch === quote) {\n quote = '';\n break;\n } else if (ch === '\\\\') {\n ch = source[index++];\n\n if (!ch || !isLineTerminator(ch.charCodeAt(0))) {\n switch (ch) {\n case 'u':\n case 'x':\n if (source[index] === '{') {\n ++index;\n str += scanUnicodeCodePointEscape();\n } else {\n str += scanHexEscape(ch);\n }\n\n break;\n\n case 'n':\n str += '\\n';\n break;\n\n case 'r':\n str += '\\r';\n break;\n\n case 't':\n str += '\\t';\n break;\n\n case 'b':\n str += '\\b';\n break;\n\n case 'f':\n str += '\\f';\n break;\n\n case 'v':\n str += '\\x0B';\n break;\n\n default:\n if (isOctalDigit(ch)) {\n code = '01234567'.indexOf(ch); // \\0 is not octal escape sequence\n\n if (code !== 0) {\n octal = true;\n }\n\n if (index < length && isOctalDigit(source[index])) {\n octal = true;\n code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts\n // with 0, 1, 2, 3\n\n if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) {\n code = code * 8 + '01234567'.indexOf(source[index++]);\n }\n }\n\n str += String.fromCharCode(code);\n } else {\n str += ch;\n }\n\n break;\n }\n } else {\n if (ch === '\\r' && source[index] === '\\n') {\n ++index;\n }\n }\n } else if (isLineTerminator(ch.charCodeAt(0))) {\n break;\n } else {\n str += ch;\n }\n }\n\n if (quote !== '') {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n }\n\n return {\n type: TokenStringLiteral,\n value: str,\n octal: octal,\n start: start,\n end: index\n };\n}\n\nfunction testRegExp(pattern, flags) {\n let tmp = pattern;\n\n if (flags.indexOf('u') >= 0) {\n // Replace each astral symbol and every Unicode code point\n // escape sequence with a single ASCII symbol to avoid throwing on\n // regular expressions that are only valid in combination with the\n // `/u` flag.\n // Note: replacing with the ASCII symbol `x` might cause false\n // negatives in unlikely scenarios. For example, `[\\u{61}-b]` is a\n // perfectly valid pattern that is equivalent to `[a-b]`, but it\n // would be replaced by `[x-b]` which throws an error.\n tmp = tmp.replace(/\\\\u\\{([0-9a-fA-F]+)\\}/g, ($0, $1) => {\n if (parseInt($1, 16) <= 0x10FFFF) {\n return 'x';\n }\n\n throwError({}, MessageInvalidRegExp);\n }).replace(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g, 'x');\n } // First, detect invalid regular expressions.\n\n\n try {\n new RegExp(tmp);\n } catch (e) {\n throwError({}, MessageInvalidRegExp);\n } // Return a regular expression object for this pattern-flag pair, or\n // `null` in case the current environment doesn't support the flags it\n // uses.\n\n\n try {\n return new RegExp(pattern, flags);\n } catch (exception) {\n return null;\n }\n}\n\nfunction scanRegExpBody() {\n var ch, str, classMarker, terminated, body;\n ch = source[index];\n assert(ch === '/', 'Regular expression literal must start with a slash');\n str = source[index++];\n classMarker = false;\n terminated = false;\n\n while (index < length) {\n ch = source[index++];\n str += ch;\n\n if (ch === '\\\\') {\n ch = source[index++]; // ECMA-262 7.8.5\n\n if (isLineTerminator(ch.charCodeAt(0))) {\n throwError({}, MessageUnterminatedRegExp);\n }\n\n str += ch;\n } else if (isLineTerminator(ch.charCodeAt(0))) {\n throwError({}, MessageUnterminatedRegExp);\n } else if (classMarker) {\n if (ch === ']') {\n classMarker = false;\n }\n } else {\n if (ch === '/') {\n terminated = true;\n break;\n } else if (ch === '[') {\n classMarker = true;\n }\n }\n }\n\n if (!terminated) {\n throwError({}, MessageUnterminatedRegExp);\n } // Exclude leading and trailing slash.\n\n\n body = str.substr(1, str.length - 2);\n return {\n value: body,\n literal: str\n };\n}\n\nfunction scanRegExpFlags() {\n var ch, str, flags;\n str = '';\n flags = '';\n\n while (index < length) {\n ch = source[index];\n\n if (!isIdentifierPart(ch.charCodeAt(0))) {\n break;\n }\n\n ++index;\n\n if (ch === '\\\\' && index < length) {\n throwError({}, MessageUnexpectedToken, ILLEGAL);\n } else {\n flags += ch;\n str += ch;\n }\n }\n\n if (flags.search(/[^gimuy]/g) >= 0) {\n throwError({}, MessageInvalidRegExp, flags);\n }\n\n return {\n value: flags,\n literal: str\n };\n}\n\nfunction scanRegExp() {\n var start, body, flags, value;\n lookahead = null;\n skipComment();\n start = index;\n body = scanRegExpBody();\n flags = scanRegExpFlags();\n value = testRegExp(body.value, flags.value);\n return {\n literal: body.literal + flags.literal,\n value: value,\n regex: {\n pattern: body.value,\n flags: flags.value\n },\n start: start,\n end: index\n };\n}\n\nfunction isIdentifierName(token) {\n return token.type === TokenIdentifier || token.type === TokenKeyword || token.type === TokenBooleanLiteral || token.type === TokenNullLiteral;\n}\n\nfunction advance() {\n skipComment();\n\n if (index >= length) {\n return {\n type: TokenEOF,\n start: index,\n end: index\n };\n }\n\n const ch = source.charCodeAt(index);\n\n if (isIdentifierStart(ch)) {\n return scanIdentifier();\n } // Very common: ( and ) and ;\n\n\n if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {\n return scanPunctuator();\n } // String literal starts with single quote (U+0027) or double quote (U+0022).\n\n\n if (ch === 0x27 || ch === 0x22) {\n return scanStringLiteral();\n } // Dot (.) U+002E can also start a floating-point number, hence the need\n // to check the next character.\n\n\n if (ch === 0x2E) {\n if (isDecimalDigit(source.charCodeAt(index + 1))) {\n return scanNumericLiteral();\n }\n\n return scanPunctuator();\n }\n\n if (isDecimalDigit(ch)) {\n return scanNumericLiteral();\n }\n\n return scanPunctuator();\n}\n\nfunction lex() {\n const token = lookahead;\n index = token.end;\n lookahead = advance();\n index = token.end;\n return token;\n}\n\nfunction peek() {\n const pos = index;\n lookahead = advance();\n index = pos;\n}\n\nfunction finishArrayExpression(elements) {\n const node = new ASTNode(SyntaxArrayExpression);\n node.elements = elements;\n return node;\n}\n\nfunction finishBinaryExpression(operator, left, right) {\n const node = new ASTNode(operator === '||' || operator === '&&' ? SyntaxLogicalExpression : SyntaxBinaryExpression);\n node.operator = operator;\n node.left = left;\n node.right = right;\n return node;\n}\n\nfunction finishCallExpression(callee, args) {\n const node = new ASTNode(SyntaxCallExpression);\n node.callee = callee;\n node.arguments = args;\n return node;\n}\n\nfunction finishConditionalExpression(test, consequent, alternate) {\n const node = new ASTNode(SyntaxConditionalExpression);\n node.test = test;\n node.consequent = consequent;\n node.alternate = alternate;\n return node;\n}\n\nfunction finishIdentifier(name) {\n const node = new ASTNode(SyntaxIdentifier);\n node.name = name;\n return node;\n}\n\nfunction finishLiteral(token) {\n const node = new ASTNode(SyntaxLiteral);\n node.value = token.value;\n node.raw = source.slice(token.start, token.end);\n\n if (token.regex) {\n if (node.raw === '//') {\n node.raw = '/(?:)/';\n }\n\n node.regex = token.regex;\n }\n\n return node;\n}\n\nfunction finishMemberExpression(accessor, object, property) {\n const node = new ASTNode(SyntaxMemberExpression);\n node.computed = accessor === '[';\n node.object = object;\n node.property = property;\n if (!node.computed) property.member = true;\n return node;\n}\n\nfunction finishObjectExpression(properties) {\n const node = new ASTNode(SyntaxObjectExpression);\n node.properties = properties;\n return node;\n}\n\nfunction finishProperty(kind, key, value) {\n const node = new ASTNode(SyntaxProperty);\n node.key = key;\n node.value = value;\n node.kind = kind;\n return node;\n}\n\nfunction finishUnaryExpression(operator, argument) {\n const node = new ASTNode(SyntaxUnaryExpression);\n node.operator = operator;\n node.argument = argument;\n node.prefix = true;\n return node;\n} // Throw an exception\n\n\nfunction throwError(token, messageFormat) {\n var error,\n args = Array.prototype.slice.call(arguments, 2),\n msg = messageFormat.replace(/%(\\d)/g, (whole, index) => {\n assert(index < args.length, 'Message reference must be in range');\n return args[index];\n });\n error = new Error(msg);\n error.index = index;\n error.description = msg;\n throw error;\n} // Throw an exception because of the token.\n\n\nfunction throwUnexpected(token) {\n if (token.type === TokenEOF) {\n throwError(token, MessageUnexpectedEOS);\n }\n\n if (token.type === TokenNumericLiteral) {\n throwError(token, MessageUnexpectedNumber);\n }\n\n if (token.type === TokenStringLiteral) {\n throwError(token, MessageUnexpectedString);\n }\n\n if (token.type === TokenIdentifier) {\n throwError(token, MessageUnexpectedIdentifier);\n }\n\n if (token.type === TokenKeyword) {\n throwError(token, MessageUnexpectedReserved);\n } // BooleanLiteral, NullLiteral, or Punctuator.\n\n\n throwError(token, MessageUnexpectedToken, token.value);\n} // Expect the next token to match the specified punctuator.\n// If not, an exception will be thrown.\n\n\nfunction expect(value) {\n const token = lex();\n\n if (token.type !== TokenPunctuator || token.value !== value) {\n throwUnexpected(token);\n }\n} // Return true if the next token matches the specified punctuator.\n\n\nfunction match(value) {\n return lookahead.type === TokenPunctuator && lookahead.value === value;\n} // Return true if the next token matches the specified keyword\n\n\nfunction matchKeyword(keyword) {\n return lookahead.type === TokenKeyword && lookahead.value === keyword;\n} // 11.1.4 Array Initialiser\n\n\nfunction parseArrayInitialiser() {\n const elements = [];\n index = lookahead.start;\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else {\n elements.push(parseConditionalExpression());\n\n if (!match(']')) {\n expect(',');\n }\n }\n }\n\n lex();\n return finishArrayExpression(elements);\n} // 11.1.5 Object Initialiser\n\n\nfunction parseObjectPropertyKey() {\n index = lookahead.start;\n const token = lex(); // Note: This function is called only from parseObjectProperty(), where\n // EOF and Punctuator tokens are already filtered out.\n\n if (token.type === TokenStringLiteral || token.type === TokenNumericLiteral) {\n if (token.octal) {\n throwError(token, MessageStrictOctalLiteral);\n }\n\n return finishLiteral(token);\n }\n\n return finishIdentifier(token.value);\n}\n\nfunction parseObjectProperty() {\n var token, key, id, value;\n index = lookahead.start;\n token = lookahead;\n\n if (token.type === TokenIdentifier) {\n id = parseObjectPropertyKey();\n expect(':');\n value = parseConditionalExpression();\n return finishProperty('init', id, value);\n }\n\n if (token.type === TokenEOF || token.type === TokenPunctuator) {\n throwUnexpected(token);\n } else {\n key = parseObjectPropertyKey();\n expect(':');\n value = parseConditionalExpression();\n return finishProperty('init', key, value);\n }\n}\n\nfunction parseObjectInitialiser() {\n var properties = [],\n property,\n name,\n key,\n map = {},\n toString = String;\n index = lookahead.start;\n expect('{');\n\n while (!match('}')) {\n property = parseObjectProperty();\n\n if (property.key.type === SyntaxIdentifier) {\n name = property.key.name;\n } else {\n name = toString(property.key.value);\n }\n\n key = '$' + name;\n\n if (Object.prototype.hasOwnProperty.call(map, key)) {\n throwError({}, MessageStrictDuplicateProperty);\n } else {\n map[key] = true;\n }\n\n properties.push(property);\n\n if (!match('}')) {\n expect(',');\n }\n }\n\n expect('}');\n return finishObjectExpression(properties);\n} // 11.1.6 The Grouping Operator\n\n\nfunction parseGroupExpression() {\n expect('(');\n const expr = parseExpression();\n expect(')');\n return expr;\n} // 11.1 Primary Expressions\n\n\nconst legalKeywords = {\n 'if': 1\n};\n\nfunction parsePrimaryExpression() {\n var type, token, expr;\n\n if (match('(')) {\n return parseGroupExpression();\n }\n\n if (match('[')) {\n return parseArrayInitialiser();\n }\n\n if (match('{')) {\n return parseObjectInitialiser();\n }\n\n type = lookahead.type;\n index = lookahead.start;\n\n if (type === TokenIdentifier || legalKeywords[lookahead.value]) {\n expr = finishIdentifier(lex().value);\n } else if (type === TokenStringLiteral || type === TokenNumericLiteral) {\n if (lookahead.octal) {\n throwError(lookahead, MessageStrictOctalLiteral);\n }\n\n expr = finishLiteral(lex());\n } else if (type === TokenKeyword) {\n throw new Error(DISABLED);\n } else if (type === TokenBooleanLiteral) {\n token = lex();\n token.value = token.value === 'true';\n expr = finishLiteral(token);\n } else if (type === TokenNullLiteral) {\n token = lex();\n token.value = null;\n expr = finishLiteral(token);\n } else if (match('/') || match('/=')) {\n expr = finishLiteral(scanRegExp());\n peek();\n } else {\n throwUnexpected(lex());\n }\n\n return expr;\n} // 11.2 Left-Hand-Side Expressions\n\n\nfunction parseArguments() {\n const args = [];\n expect('(');\n\n if (!match(')')) {\n while (index < length) {\n args.push(parseConditionalExpression());\n\n if (match(')')) {\n break;\n }\n\n expect(',');\n }\n }\n\n expect(')');\n return args;\n}\n\nfunction parseNonComputedProperty() {\n index = lookahead.start;\n const token = lex();\n\n if (!isIdentifierName(token)) {\n throwUnexpected(token);\n }\n\n return finishIdentifier(token.value);\n}\n\nfunction parseNonComputedMember() {\n expect('.');\n return parseNonComputedProperty();\n}\n\nfunction parseComputedMember() {\n expect('[');\n const expr = parseExpression();\n expect(']');\n return expr;\n}\n\nfunction parseLeftHandSideExpressionAllowCall() {\n var expr, args, property;\n expr = parsePrimaryExpression();\n\n for (;;) {\n if (match('.')) {\n property = parseNonComputedMember();\n expr = finishMemberExpression('.', expr, property);\n } else if (match('(')) {\n args = parseArguments();\n expr = finishCallExpression(expr, args);\n } else if (match('[')) {\n property = parseComputedMember();\n expr = finishMemberExpression('[', expr, property);\n } else {\n break;\n }\n }\n\n return expr;\n} // 11.3 Postfix Expressions\n\n\nfunction parsePostfixExpression() {\n const expr = parseLeftHandSideExpressionAllowCall();\n\n if (lookahead.type === TokenPunctuator) {\n if (match('++') || match('--')) {\n throw new Error(DISABLED);\n }\n }\n\n return expr;\n} // 11.4 Unary Operators\n\n\nfunction parseUnaryExpression() {\n var token, expr;\n\n if (lookahead.type !== TokenPunctuator && lookahead.type !== TokenKeyword) {\n expr = parsePostfixExpression();\n } else if (match('++') || match('--')) {\n throw new Error(DISABLED);\n } else if (match('+') || match('-') || match('~') || match('!')) {\n token = lex();\n expr = parseUnaryExpression();\n expr = finishUnaryExpression(token.value, expr);\n } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {\n throw new Error(DISABLED);\n } else {\n expr = parsePostfixExpression();\n }\n\n return expr;\n}\n\nfunction binaryPrecedence(token) {\n let prec = 0;\n\n if (token.type !== TokenPunctuator && token.type !== TokenKeyword) {\n return 0;\n }\n\n switch (token.value) {\n case '||':\n prec = 1;\n break;\n\n case '&&':\n prec = 2;\n break;\n\n case '|':\n prec = 3;\n break;\n\n case '^':\n prec = 4;\n break;\n\n case '&':\n prec = 5;\n break;\n\n case '==':\n case '!=':\n case '===':\n case '!==':\n prec = 6;\n break;\n\n case '<':\n case '>':\n case '<=':\n case '>=':\n case 'instanceof':\n case 'in':\n prec = 7;\n break;\n\n case '<<':\n case '>>':\n case '>>>':\n prec = 8;\n break;\n\n case '+':\n case '-':\n prec = 9;\n break;\n\n case '*':\n case '/':\n case '%':\n prec = 11;\n break;\n }\n\n return prec;\n} // 11.5 Multiplicative Operators\n// 11.6 Additive Operators\n// 11.7 Bitwise Shift Operators\n// 11.8 Relational Operators\n// 11.9 Equality Operators\n// 11.10 Binary Bitwise Operators\n// 11.11 Binary Logical Operators\n\n\nfunction parseBinaryExpression() {\n var marker, markers, expr, token, prec, stack, right, operator, left, i;\n marker = lookahead;\n left = parseUnaryExpression();\n token = lookahead;\n prec = binaryPrecedence(token);\n\n if (prec === 0) {\n return left;\n }\n\n token.prec = prec;\n lex();\n markers = [marker, lookahead];\n right = parseUnaryExpression();\n stack = [left, token, right];\n\n while ((prec = binaryPrecedence(lookahead)) > 0) {\n // Reduce: make a binary expression from the three topmost entries.\n while (stack.length > 2 && prec <= stack[stack.length - 2].prec) {\n right = stack.pop();\n operator = stack.pop().value;\n left = stack.pop();\n markers.pop();\n expr = finishBinaryExpression(operator, left, right);\n stack.push(expr);\n } // Shift.\n\n\n token = lex();\n token.prec = prec;\n stack.push(token);\n markers.push(lookahead);\n expr = parseUnaryExpression();\n stack.push(expr);\n } // Final reduce to clean-up the stack.\n\n\n i = stack.length - 1;\n expr = stack[i];\n markers.pop();\n\n while (i > 1) {\n markers.pop();\n expr = finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);\n i -= 2;\n }\n\n return expr;\n} // 11.12 Conditional Operator\n\n\nfunction parseConditionalExpression() {\n var expr, consequent, alternate;\n expr = parseBinaryExpression();\n\n if (match('?')) {\n lex();\n consequent = parseConditionalExpression();\n expect(':');\n alternate = parseConditionalExpression();\n expr = finishConditionalExpression(expr, consequent, alternate);\n }\n\n return expr;\n} // 11.14 Comma Operator\n\n\nfunction parseExpression() {\n const expr = parseConditionalExpression();\n\n if (match(',')) {\n throw new Error(DISABLED); // no sequence expressions\n }\n\n return expr;\n}\n\nfunction parser (code) {\n source = code;\n index = 0;\n length = source.length;\n lookahead = null;\n peek();\n const expr = parseExpression();\n\n if (lookahead.type !== TokenEOF) {\n throw new Error('Unexpect token after expression.');\n }\n\n return expr;\n}\n\nvar Constants = {\n NaN: 'NaN',\n E: 'Math.E',\n LN2: 'Math.LN2',\n LN10: 'Math.LN10',\n LOG2E: 'Math.LOG2E',\n LOG10E: 'Math.LOG10E',\n PI: 'Math.PI',\n SQRT1_2: 'Math.SQRT1_2',\n SQRT2: 'Math.SQRT2',\n MIN_VALUE: 'Number.MIN_VALUE',\n MAX_VALUE: 'Number.MAX_VALUE'\n};\n\nfunction Functions (codegen) {\n function fncall(name, args, cast, type) {\n let obj = codegen(args[0]);\n\n if (cast) {\n obj = cast + '(' + obj + ')';\n if (cast.lastIndexOf('new ', 0) === 0) obj = '(' + obj + ')';\n }\n\n return obj + '.' + name + (type < 0 ? '' : type === 0 ? '()' : '(' + args.slice(1).map(codegen).join(',') + ')');\n }\n\n function fn(name, cast, type) {\n return args => fncall(name, args, cast, type);\n }\n\n const DATE = 'new Date',\n STRING = 'String',\n REGEXP = 'RegExp';\n return {\n // MATH functions\n isNaN: 'Number.isNaN',\n isFinite: 'Number.isFinite',\n abs: 'Math.abs',\n acos: 'Math.acos',\n asin: 'Math.asin',\n atan: 'Math.atan',\n atan2: 'Math.atan2',\n ceil: 'Math.ceil',\n cos: 'Math.cos',\n exp: 'Math.exp',\n floor: 'Math.floor',\n log: 'Math.log',\n max: 'Math.max',\n min: 'Math.min',\n pow: 'Math.pow',\n random: 'Math.random',\n round: 'Math.round',\n sin: 'Math.sin',\n sqrt: 'Math.sqrt',\n tan: 'Math.tan',\n clamp: function (args) {\n if (args.length < 3) error('Missing arguments to clamp function.');\n if (args.length > 3) error('Too many arguments to clamp function.');\n const a = args.map(codegen);\n return 'Math.max(' + a[1] + ', Math.min(' + a[2] + ',' + a[0] + '))';\n },\n // DATE functions\n now: 'Date.now',\n utc: 'Date.UTC',\n datetime: DATE,\n date: fn('getDate', DATE, 0),\n day: fn('getDay', DATE, 0),\n year: fn('getFullYear', DATE, 0),\n month: fn('getMonth', DATE, 0),\n hours: fn('getHours', DATE, 0),\n minutes: fn('getMinutes', DATE, 0),\n seconds: fn('getSeconds', DATE, 0),\n milliseconds: fn('getMilliseconds', DATE, 0),\n time: fn('getTime', DATE, 0),\n timezoneoffset: fn('getTimezoneOffset', DATE, 0),\n utcdate: fn('getUTCDate', DATE, 0),\n utcday: fn('getUTCDay', DATE, 0),\n utcyear: fn('getUTCFullYear', DATE, 0),\n utcmonth: fn('getUTCMonth', DATE, 0),\n utchours: fn('getUTCHours', DATE, 0),\n utcminutes: fn('getUTCMinutes', DATE, 0),\n utcseconds: fn('getUTCSeconds', DATE, 0),\n utcmilliseconds: fn('getUTCMilliseconds', DATE, 0),\n // sequence functions\n length: fn('length', null, -1),\n // STRING functions\n parseFloat: 'parseFloat',\n parseInt: 'parseInt',\n upper: fn('toUpperCase', STRING, 0),\n lower: fn('toLowerCase', STRING, 0),\n substring: fn('substring', STRING),\n split: fn('split', STRING),\n trim: fn('trim', STRING, 0),\n // REGEXP functions\n regexp: REGEXP,\n test: fn('test', REGEXP),\n // Control Flow functions\n if: function (args) {\n if (args.length < 3) error('Missing arguments to if function.');\n if (args.length > 3) error('Too many arguments to if function.');\n const a = args.map(codegen);\n return '(' + a[0] + '?' + a[1] + ':' + a[2] + ')';\n }\n };\n}\n\nfunction stripQuotes(s) {\n const n = s && s.length - 1;\n return n && (s[0] === '\"' && s[n] === '\"' || s[0] === '\\'' && s[n] === '\\'') ? s.slice(1, -1) : s;\n}\n\nfunction codegen (opt) {\n opt = opt || {};\n const allowed = opt.allowed ? toSet(opt.allowed) : {},\n forbidden = opt.forbidden ? toSet(opt.forbidden) : {},\n constants = opt.constants || Constants,\n functions = (opt.functions || Functions)(visit),\n globalvar = opt.globalvar,\n fieldvar = opt.fieldvar,\n outputGlobal = isFunction(globalvar) ? globalvar : id => \"\".concat(globalvar, \"[\\\"\").concat(id, \"\\\"]\");\n let globals = {},\n fields = {},\n memberDepth = 0;\n\n function visit(ast) {\n if (isString(ast)) return ast;\n const generator = Generators[ast.type];\n if (generator == null) error('Unsupported type: ' + ast.type);\n return generator(ast);\n }\n\n const Generators = {\n Literal: n => n.raw,\n Identifier: n => {\n const id = n.name;\n\n if (memberDepth > 0) {\n return id;\n } else if (hasOwnProperty(forbidden, id)) {\n return error('Illegal identifier: ' + id);\n } else if (hasOwnProperty(constants, id)) {\n return constants[id];\n } else if (hasOwnProperty(allowed, id)) {\n return id;\n } else {\n globals[id] = 1;\n return outputGlobal(id);\n }\n },\n MemberExpression: n => {\n const d = !n.computed,\n o = visit(n.object);\n if (d) memberDepth += 1;\n const p = visit(n.property);\n\n if (o === fieldvar) {\n // strip quotes to sanitize field name (#1653)\n fields[stripQuotes(p)] = 1;\n }\n\n if (d) memberDepth -= 1;\n return o + (d ? '.' + p : '[' + p + ']');\n },\n CallExpression: n => {\n if (n.callee.type !== 'Identifier') {\n error('Illegal callee type: ' + n.callee.type);\n }\n\n const callee = n.callee.name,\n args = n.arguments,\n fn = hasOwnProperty(functions, callee) && functions[callee];\n if (!fn) error('Unrecognized function: ' + callee);\n return isFunction(fn) ? fn(args) : fn + '(' + args.map(visit).join(',') + ')';\n },\n ArrayExpression: n => '[' + n.elements.map(visit).join(',') + ']',\n BinaryExpression: n => '(' + visit(n.left) + ' ' + n.operator + ' ' + visit(n.right) + ')',\n UnaryExpression: n => '(' + n.operator + visit(n.argument) + ')',\n ConditionalExpression: n => '(' + visit(n.test) + '?' + visit(n.consequent) + ':' + visit(n.alternate) + ')',\n LogicalExpression: n => '(' + visit(n.left) + n.operator + visit(n.right) + ')',\n ObjectExpression: n => '{' + n.properties.map(visit).join(',') + '}',\n Property: n => {\n memberDepth += 1;\n const k = visit(n.key);\n memberDepth -= 1;\n return k + ':' + visit(n.value);\n }\n };\n\n function codegen(ast) {\n const result = {\n code: visit(ast),\n globals: Object.keys(globals),\n fields: Object.keys(fields)\n };\n globals = {};\n fields = {};\n return result;\n }\n\n codegen.functions = functions;\n codegen.constants = constants;\n return codegen;\n}\n\nexport { ASTNode, ArrayExpression, BinaryExpression, CallExpression, ConditionalExpression, Identifier, Literal, LogicalExpression, MemberExpression, ObjectExpression, Property, RawCode, UnaryExpression, codegen, Constants as constants, Functions as functions, parser as parse };\n","import { parse } from 'vega-expression';\nfunction getName(node) {\n const name = [];\n if (node.type === 'Identifier') {\n return [node.name];\n }\n if (node.type === 'Literal') {\n return [node.value];\n }\n if (node.type === 'MemberExpression') {\n name.push(...getName(node.object));\n name.push(...getName(node.property));\n }\n return name;\n}\nfunction startsWithDatum(node) {\n if (node.object.type === 'MemberExpression') {\n return startsWithDatum(node.object);\n }\n return node.object.name === 'datum';\n}\nexport function getDependentFields(expression) {\n const ast = parse(expression);\n const dependents = new Set();\n ast.visit((node) => {\n if (node.type === 'MemberExpression' && startsWithDatum(node)) {\n dependents.add(getName(node).slice(1).join('.'));\n }\n });\n return dependents;\n}\n//# sourceMappingURL=expressions.js.map","import { duplicate } from '../../util';\nimport { expression } from '../predicate';\nimport { DataFlowNode } from './dataflow';\nimport { getDependentFields } from './expressions';\nexport class FilterNode extends DataFlowNode {\n constructor(parent, model, filter) {\n super(parent);\n this.model = model;\n this.filter = filter;\n // TODO: refactor this to not take a node and\n // then add a static function makeFromOperand and make the constructor take only an expression\n this.expr = expression(this.model, this.filter, this);\n this._dependentFields = getDependentFields(this.expr);\n }\n clone() {\n return new FilterNode(null, this.model, duplicate(this.filter));\n }\n dependentFields() {\n return this._dependentFields;\n }\n producedFields() {\n return new Set(); // filter does not produce any new fields\n }\n assemble() {\n return {\n type: 'filter',\n expr: this.expr\n };\n }\n hash() {\n return `Filter ${this.expr}`;\n }\n}\n//# sourceMappingURL=filter.js.map","import { selector as parseSelector } from 'vega-event-selector';\nimport { array, isObject, isString, stringValue } from 'vega-util';\nimport { selectionCompilers, STORE } from '.';\nimport { warn } from '../../log';\nimport { duplicate, entries, replacePathInField, varName } from '../../util';\nimport { OutputNode } from '../data/dataflow';\nimport { FilterNode } from '../data/filter';\nimport { DataSourceType } from '../../data';\nexport function parseUnitSelection(model, selDefs) {\n var _a;\n const selCmpts = {};\n const selectionConfig = model.config.selection;\n if (!selDefs || !selDefs.length)\n return selCmpts;\n for (const def of selDefs) {\n const name = varName(def.name);\n const selDef = def.select;\n const type = isString(selDef) ? selDef : selDef.type;\n const defaults = isObject(selDef) ? duplicate(selDef) : { type };\n // Set default values from config if a property hasn't been specified,\n // or if it is true. E.g., \"translate\": true should use the default\n // event handlers for translate. However, true may be a valid value for\n // a property (e.g., \"nearest\": true).\n const cfg = selectionConfig[type];\n for (const key in cfg) {\n // Project transform applies its defaults.\n if (key === 'fields' || key === 'encodings') {\n continue;\n }\n if (key === 'mark') {\n defaults[key] = Object.assign(Object.assign({}, cfg[key]), defaults[key]);\n }\n if (defaults[key] === undefined || defaults[key] === true) {\n defaults[key] = (_a = cfg[key]) !== null && _a !== void 0 ? _a : defaults[key];\n }\n }\n const selCmpt = (selCmpts[name] = Object.assign(Object.assign({}, defaults), { name,\n type, init: def.value, bind: def.bind, events: isString(defaults.on) ? parseSelector(defaults.on, 'scope') : array(duplicate(defaults.on)) }));\n for (const c of selectionCompilers) {\n if (c.defined(selCmpt) && c.parse) {\n c.parse(model, selCmpt, def);\n }\n }\n }\n return selCmpts;\n}\nexport function parseSelectionPredicate(model, pred, dfnode, datum = 'datum') {\n const name = isString(pred) ? pred : pred.param;\n const vname = varName(name);\n const store = stringValue(vname + STORE);\n let selCmpt;\n try {\n selCmpt = model.getSelectionComponent(vname, name);\n }\n catch (e) {\n // If a selection isn't found, treat as a variable parameter and coerce to boolean.\n return `!!${vname}`;\n }\n if (selCmpt.project.timeUnit) {\n const child = dfnode !== null && dfnode !== void 0 ? dfnode : model.component.data.raw;\n const tunode = selCmpt.project.timeUnit.clone();\n if (child.parent) {\n tunode.insertAsParentOf(child);\n }\n else {\n child.parent = tunode;\n }\n }\n const test = `vlSelectionTest(${store}, ${datum}${selCmpt.resolve === 'global' ? ')' : `, ${stringValue(selCmpt.resolve)})`}`;\n const length = `length(data(${store}))`;\n return pred.empty === false ? `${length} && ${test}` : `!${length} || ${test}`;\n}\nexport function parseSelectionExtent(model, name, extent) {\n const vname = varName(name);\n const encoding = extent['encoding'];\n let field = extent['field'];\n let selCmpt;\n try {\n selCmpt = model.getSelectionComponent(vname, name);\n }\n catch (e) {\n // If a selection isn't found, treat it as a variable parameter.\n return vname;\n }\n if (!encoding && !field) {\n field = selCmpt.project.items[0].field;\n if (selCmpt.project.items.length > 1) {\n warn('A \"field\" or \"encoding\" must be specified when using a selection as a scale domain. ' +\n `Using \"field\": ${stringValue(field)}.`);\n }\n }\n else if (encoding && !field) {\n const encodings = selCmpt.project.items.filter(p => p.channel === encoding);\n if (!encodings.length || encodings.length > 1) {\n field = selCmpt.project.items[0].field;\n warn((!encodings.length ? 'No ' : 'Multiple ') +\n `matching ${stringValue(encoding)} encoding found for selection ${stringValue(extent.param)}. ` +\n `Using \"field\": ${stringValue(field)}.`);\n }\n else {\n field = encodings[0].field;\n }\n }\n return `${selCmpt.name}[${stringValue(replacePathInField(field))}]`;\n}\nexport function materializeSelections(model, main) {\n var _a;\n for (const [selection, selCmpt] of entries((_a = model.component.selection) !== null && _a !== void 0 ? _a : {})) {\n const lookupName = model.getName(`lookup_${selection}`);\n model.component.data.outputNodes[lookupName] = selCmpt.materialized = new OutputNode(new FilterNode(main, model, { param: selection }), lookupName, DataSourceType.Lookup, model.component.data.outputNodeRefCounts);\n }\n}\n//# sourceMappingURL=parse.js.map","import { isString } from 'vega-util';\nimport { fieldFilterExpression, isSelectionPredicate } from '../predicate';\nimport { logicalExpr } from '../util';\nimport { parseSelectionPredicate } from './selection/parse';\n/**\n * Converts a predicate into an expression.\n */\n// model is only used for selection filters.\nexport function expression(model, filterOp, node) {\n return logicalExpr(filterOp, (predicate) => {\n if (isString(predicate)) {\n return predicate;\n }\n else if (isSelectionPredicate(predicate)) {\n return parseSelectionPredicate(model, predicate, node);\n }\n else {\n // Filter Object\n return fieldFilterExpression(predicate);\n }\n });\n}\n//# sourceMappingURL=predicate.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { array, isArray } from 'vega-util';\nimport { AXIS_PARTS, AXIS_PROPERTY_TYPE, CONDITIONAL_AXIS_PROP_INDEX, isConditionalAxisValue } from '../../axis';\nimport { POSITION_SCALE_CHANNELS } from '../../channel';\nimport { defaultTitle } from '../../channeldef';\nimport { isText } from '../../title';\nimport { contains, getFirstDefined, isEmpty, replaceAll } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { exprFromValueOrSignalRef } from '../common';\nimport { expression } from '../predicate';\nfunction assembleTitle(title, config) {\n if (!title) {\n return undefined;\n }\n if (isArray(title) && !isText(title)) {\n return title.map(fieldDef => defaultTitle(fieldDef, config)).join(', ');\n }\n return title;\n}\nfunction setAxisEncode(axis, part, vgProp, vgRef) {\n var _a, _b, _c;\n var _d, _e;\n (_a = axis.encode) !== null && _a !== void 0 ? _a : (axis.encode = {});\n (_b = (_d = axis.encode)[part]) !== null && _b !== void 0 ? _b : (_d[part] = {});\n (_c = (_e = axis.encode[part]).update) !== null && _c !== void 0 ? _c : (_e.update = {});\n // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291\n axis.encode[part].update[vgProp] = vgRef;\n}\nexport function assembleAxis(axisCmpt, kind, config, opt = { header: false }) {\n var _a, _b;\n const _c = axisCmpt.combine(), { disable, orient, scale, labelExpr, title, zindex } = _c, axis = __rest(_c, [\"disable\", \"orient\", \"scale\", \"labelExpr\", \"title\", \"zindex\"]);\n if (disable) {\n return undefined;\n }\n for (const prop in axis) {\n const propType = AXIS_PROPERTY_TYPE[prop];\n const propValue = axis[prop];\n if (propType && propType !== kind && propType !== 'both') {\n // Remove properties that are not valid for this kind of axis\n delete axis[prop];\n }\n else if (isConditionalAxisValue(propValue)) {\n // deal with conditional axis value\n const { condition } = propValue, valueOrSignalRef = __rest(propValue, [\"condition\"]);\n const conditions = array(condition);\n const propIndex = CONDITIONAL_AXIS_PROP_INDEX[prop];\n if (propIndex) {\n const { vgProp, part } = propIndex;\n // If there is a corresponding Vega property for the channel,\n // use Vega's custom axis encoding and delete the original axis property to avoid conflicts\n const vgRef = [\n ...conditions.map(c => {\n const { test } = c, valueOrSignalCRef = __rest(c, [\"test\"]);\n return Object.assign({ test: expression(null, test) }, valueOrSignalCRef);\n }),\n valueOrSignalRef\n ];\n setAxisEncode(axis, part, vgProp, vgRef);\n delete axis[prop];\n }\n else if (propIndex === null) {\n // If propIndex is null, this means we support conditional axis property by converting the condition to signal instead.\n const signalRef = {\n signal: conditions\n .map(c => {\n const { test } = c, valueOrSignalCRef = __rest(c, [\"test\"]);\n return `${expression(null, test)} ? ${exprFromValueOrSignalRef(valueOrSignalCRef)} : `;\n })\n .join('') + exprFromValueOrSignalRef(valueOrSignalRef)\n };\n axis[prop] = signalRef;\n }\n }\n else if (isSignalRef(propValue)) {\n const propIndex = CONDITIONAL_AXIS_PROP_INDEX[prop];\n if (propIndex) {\n const { vgProp, part } = propIndex;\n setAxisEncode(axis, part, vgProp, propValue);\n delete axis[prop];\n } // else do nothing since the property already supports signal\n }\n // Do not pass labelAlign/Baseline = null to Vega since it won't pass the schema\n // Note that we need to use null so the default labelAlign is preserved.\n if (contains(['labelAlign', 'labelBaseline'], prop) && axis[prop] === null) {\n delete axis[prop];\n }\n }\n if (kind === 'grid') {\n if (!axis.grid) {\n return undefined;\n }\n // Remove unnecessary encode block\n if (axis.encode) {\n // Only need to keep encode block for grid\n const { grid } = axis.encode;\n axis.encode = Object.assign({}, (grid ? { grid } : {}));\n if (isEmpty(axis.encode)) {\n delete axis.encode;\n }\n }\n return Object.assign(Object.assign({ scale,\n orient }, axis), { domain: false, labels: false, aria: false, \n // Always set min/maxExtent to 0 to ensure that `config.axis*.minExtent` and `config.axis*.maxExtent`\n // would not affect gridAxis\n maxExtent: 0, minExtent: 0, ticks: false, zindex: getFirstDefined(zindex, 0) // put grid behind marks by default\n });\n }\n else {\n // kind === 'main'\n if (!opt.header && axisCmpt.mainExtracted) {\n // if mainExtracted has been extracted to a separate facet\n return undefined;\n }\n if (labelExpr !== undefined) {\n let expr = labelExpr;\n if (((_b = (_a = axis.encode) === null || _a === void 0 ? void 0 : _a.labels) === null || _b === void 0 ? void 0 : _b.update) && isSignalRef(axis.encode.labels.update.text)) {\n expr = replaceAll(labelExpr, 'datum.label', axis.encode.labels.update.text.signal);\n }\n setAxisEncode(axis, 'labels', 'text', { signal: expr });\n }\n if (axis.labelAlign === null) {\n delete axis.labelAlign;\n }\n // Remove unnecessary encode block\n if (axis.encode) {\n for (const part of AXIS_PARTS) {\n if (!axisCmpt.hasAxisPart(part)) {\n delete axis.encode[part];\n }\n }\n if (isEmpty(axis.encode)) {\n delete axis.encode;\n }\n }\n const titleString = assembleTitle(title, config);\n return Object.assign(Object.assign(Object.assign(Object.assign({ scale,\n orient, grid: false }, (titleString ? { title: titleString } : {})), axis), (config.aria === false ? { aria: false } : {})), { zindex: getFirstDefined(zindex, 0) // put axis line above marks by default\n });\n }\n}\n/**\n * Add axis signals so grid line works correctly\n * (Fix https://github.com/vega/vega-lite/issues/4226)\n */\nexport function assembleAxisSignals(model) {\n const { axes } = model.component;\n const signals = [];\n for (const channel of POSITION_SCALE_CHANNELS) {\n if (axes[channel]) {\n for (const axis of axes[channel]) {\n if (!axis.get('disable') && !axis.get('gridScale')) {\n // If there is x-axis but no y-scale for gridScale, need to set height/width so x-axis can draw the grid with the right height. Same for y-axis and width.\n const sizeType = channel === 'x' ? 'height' : 'width';\n const update = model.getSizeSignalRef(sizeType).signal;\n if (sizeType !== update) {\n signals.push({\n name: sizeType,\n update: update\n });\n }\n }\n }\n }\n }\n return signals;\n}\nexport function assembleAxes(axisComponents, config) {\n const { x = [], y = [] } = axisComponents;\n return [\n ...x.map(a => assembleAxis(a, 'grid', config)),\n ...y.map(a => assembleAxis(a, 'grid', config)),\n ...x.map(a => assembleAxis(a, 'main', config)),\n ...y.map(a => assembleAxis(a, 'main', config))\n ].filter(a => a); // filter undefined\n}\n//# sourceMappingURL=assemble.js.map","import { array } from 'vega-util';\nimport { isQuantitative } from '../../scale';\nimport { keys, titleCase } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { getStyleConfig, signalOrStringValue } from '../common';\nfunction getAxisConfigFromConfigTypes(configTypes, config, channel, orient) {\n // TODO: add special casing to add conditional value based on orient signal\n return Object.assign.apply(null, [\n {},\n ...configTypes.map(configType => {\n if (configType === 'axisOrient') {\n const orient1 = channel === 'x' ? 'bottom' : 'left';\n const orientConfig1 = config[channel === 'x' ? 'axisBottom' : 'axisLeft'] || {};\n const orientConfig2 = config[channel === 'x' ? 'axisTop' : 'axisRight'] || {};\n const props = new Set([...keys(orientConfig1), ...keys(orientConfig2)]);\n const conditionalOrientAxisConfig = {};\n for (const prop of props.values()) {\n conditionalOrientAxisConfig[prop] = {\n // orient is surely signal in this case\n signal: `${orient['signal']} === \"${orient1}\" ? ${signalOrStringValue(orientConfig1[prop])} : ${signalOrStringValue(orientConfig2[prop])}`\n };\n }\n return conditionalOrientAxisConfig;\n }\n return config[configType];\n })\n ]);\n}\nexport function getAxisConfigs(channel, scaleType, orient, config) {\n const typeBasedConfigTypes = scaleType === 'band'\n ? ['axisDiscrete', 'axisBand']\n : scaleType === 'point'\n ? ['axisDiscrete', 'axisPoint']\n : isQuantitative(scaleType)\n ? ['axisQuantitative']\n : scaleType === 'time' || scaleType === 'utc'\n ? ['axisTemporal']\n : [];\n const axisChannel = channel === 'x' ? 'axisX' : 'axisY';\n const axisOrient = isSignalRef(orient) ? 'axisOrient' : `axis${titleCase(orient)}`; // axisTop, axisBottom, ...\n const vlOnlyConfigTypes = [\n // technically Vega does have axisBand, but if we make another separation here,\n // it will further introduce complexity in the code\n ...typeBasedConfigTypes,\n ...typeBasedConfigTypes.map(c => axisChannel + c.substr(4))\n ];\n const vgConfigTypes = ['axis', axisOrient, axisChannel];\n return {\n vlOnlyAxisConfig: getAxisConfigFromConfigTypes(vlOnlyConfigTypes, config, channel, orient),\n vgAxisConfig: getAxisConfigFromConfigTypes(vgConfigTypes, config, channel, orient),\n axisConfigStyle: getAxisConfigStyle([...vgConfigTypes, ...vlOnlyConfigTypes], config)\n };\n}\nexport function getAxisConfigStyle(axisConfigTypes, config) {\n var _a;\n const toMerge = [{}];\n for (const configType of axisConfigTypes) {\n // TODO: add special casing to add conditional value based on orient signal\n let style = (_a = config[configType]) === null || _a === void 0 ? void 0 : _a.style;\n if (style) {\n style = array(style);\n for (const s of style) {\n toMerge.push(config.style[s]);\n }\n }\n }\n return Object.assign.apply(null, toMerge);\n}\nexport function getAxisConfig(property, styleConfigIndex, style, axisConfigs = {}) {\n var _a;\n const styleConfig = getStyleConfig(property, style, styleConfigIndex);\n if (styleConfig !== undefined) {\n return {\n configFrom: 'style',\n configValue: styleConfig\n };\n }\n for (const configFrom of ['vlOnlyAxisConfig', 'vgAxisConfig', 'axisConfigStyle']) {\n if (((_a = axisConfigs[configFrom]) === null || _a === void 0 ? void 0 : _a[property]) !== undefined) {\n return { configFrom, configValue: axisConfigs[configFrom][property] };\n }\n }\n return {};\n}\n//# sourceMappingURL=config.js.map","import { isArray, isObject } from 'vega-util';\nimport { isBinned, isBinning } from '../../bin';\nimport { X } from '../../channel';\nimport { isDiscrete, isFieldDef, toFieldDefBase, valueArray } from '../../channeldef';\nimport { hasDiscreteDomain } from '../../scale';\nimport { normalizeTimeUnit } from '../../timeunit';\nimport { NOMINAL, ORDINAL } from '../../type';\nimport { contains, normalizeAngle } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { mergeTitle, mergeTitleFieldDefs } from '../common';\nimport { guideFormat, guideFormatType } from '../format';\nimport { getAxisConfig } from './config';\nexport const axisRules = {\n scale: ({ model, channel }) => model.scaleName(channel),\n format: ({ fieldOrDatumDef, config, axis }) => {\n const { format, formatType } = axis;\n return guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, format, formatType, config, true);\n },\n formatType: ({ axis, fieldOrDatumDef, scaleType }) => {\n const { formatType } = axis;\n return guideFormatType(formatType, fieldOrDatumDef, scaleType);\n },\n grid: ({ fieldOrDatumDef, axis, scaleType }) => { var _a; return (_a = axis.grid) !== null && _a !== void 0 ? _a : defaultGrid(scaleType, fieldOrDatumDef); },\n gridScale: ({ model, channel }) => gridScale(model, channel),\n labelAlign: ({ axis, labelAngle, orient, channel }) => axis.labelAlign || defaultLabelAlign(labelAngle, orient, channel),\n labelAngle: ({ labelAngle }) => labelAngle,\n labelBaseline: ({ axis, labelAngle, orient, channel }) => axis.labelBaseline || defaultLabelBaseline(labelAngle, orient, channel),\n labelFlush: ({ axis, fieldOrDatumDef, channel }) => { var _a; return (_a = axis.labelFlush) !== null && _a !== void 0 ? _a : defaultLabelFlush(fieldOrDatumDef.type, channel); },\n labelOverlap: ({ axis, fieldOrDatumDef, scaleType }) => {\n var _a;\n return (_a = axis.labelOverlap) !== null && _a !== void 0 ? _a : defaultLabelOverlap(fieldOrDatumDef.type, scaleType, isFieldDef(fieldOrDatumDef) && !!fieldOrDatumDef.timeUnit, isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined);\n },\n // we already calculate orient in parse\n orient: ({ orient }) => orient,\n tickCount: ({ channel, model, axis, fieldOrDatumDef, scaleType }) => {\n var _a;\n const sizeType = channel === 'x' ? 'width' : channel === 'y' ? 'height' : undefined;\n const size = sizeType ? model.getSizeSignalRef(sizeType) : undefined;\n return (_a = axis.tickCount) !== null && _a !== void 0 ? _a : defaultTickCount({ fieldOrDatumDef, scaleType, size, values: axis.values });\n },\n title: ({ axis, model, channel }) => {\n if (axis.title !== undefined) {\n return axis.title;\n }\n const fieldDefTitle = getFieldDefTitle(model, channel);\n if (fieldDefTitle !== undefined) {\n return fieldDefTitle;\n }\n const fieldDef = model.typedFieldDef(channel);\n const channel2 = channel === 'x' ? 'x2' : 'y2';\n const fieldDef2 = model.fieldDef(channel2);\n // If title not specified, store base parts of fieldDef (and fieldDef2 if exists)\n return mergeTitleFieldDefs(fieldDef ? [toFieldDefBase(fieldDef)] : [], isFieldDef(fieldDef2) ? [toFieldDefBase(fieldDef2)] : []);\n },\n values: ({ axis, fieldOrDatumDef }) => values(axis, fieldOrDatumDef),\n zindex: ({ axis, fieldOrDatumDef, mark }) => { var _a; return (_a = axis.zindex) !== null && _a !== void 0 ? _a : defaultZindex(mark, fieldOrDatumDef); }\n};\n// TODO: we need to refactor this method after we take care of config refactoring\n/**\n * Default rules for whether to show a grid should be shown for a channel.\n * If `grid` is unspecified, the default value is `true` for ordinal scales that are not binned\n */\nexport function defaultGrid(scaleType, fieldDef) {\n return !hasDiscreteDomain(scaleType) && isFieldDef(fieldDef) && !isBinning(fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.bin) && !isBinned(fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.bin);\n}\nexport function gridScale(model, channel) {\n const gridChannel = channel === 'x' ? 'y' : 'x';\n if (model.getScaleComponent(gridChannel)) {\n return model.scaleName(gridChannel);\n }\n return undefined;\n}\nexport function getLabelAngle(fieldOrDatumDef, axis, channel, styleConfig, axisConfigs) {\n const labelAngle = axis === null || axis === void 0 ? void 0 : axis.labelAngle;\n // try axis value\n if (labelAngle !== undefined) {\n return isSignalRef(labelAngle) ? labelAngle : normalizeAngle(labelAngle);\n }\n else {\n // try axis config value\n const { configValue: angle } = getAxisConfig('labelAngle', styleConfig, axis === null || axis === void 0 ? void 0 : axis.style, axisConfigs);\n if (angle !== undefined) {\n return normalizeAngle(angle);\n }\n else {\n // get default value\n if (channel === X &&\n contains([NOMINAL, ORDINAL], fieldOrDatumDef.type) &&\n !(isFieldDef(fieldOrDatumDef) && fieldOrDatumDef.timeUnit)) {\n return 270;\n }\n // no default\n return undefined;\n }\n }\n}\nexport function normalizeAngleExpr(angle) {\n return `(((${angle.signal} % 360) + 360) % 360)`;\n}\nexport function defaultLabelBaseline(angle, orient, channel, alwaysIncludeMiddle) {\n if (angle !== undefined) {\n if (channel === 'x') {\n if (isSignalRef(angle)) {\n const a = normalizeAngleExpr(angle);\n const orientIsTop = isSignalRef(orient) ? `(${orient.signal} === \"top\")` : orient === 'top';\n return {\n signal: `(45 < ${a} && ${a} < 135) || (225 < ${a} && ${a} < 315) ? \"middle\" :` +\n `(${a} <= 45 || 315 <= ${a}) === ${orientIsTop} ? \"bottom\" : \"top\"`\n };\n }\n if ((45 < angle && angle < 135) || (225 < angle && angle < 315)) {\n return 'middle';\n }\n if (isSignalRef(orient)) {\n const op = angle <= 45 || 315 <= angle ? '===' : '!==';\n return { signal: `${orient.signal} ${op} \"top\" ? \"bottom\" : \"top\"` };\n }\n return (angle <= 45 || 315 <= angle) === (orient === 'top') ? 'bottom' : 'top';\n }\n else {\n if (isSignalRef(angle)) {\n const a = normalizeAngleExpr(angle);\n const orientIsLeft = isSignalRef(orient) ? `(${orient.signal} === \"left\")` : orient === 'left';\n const middle = alwaysIncludeMiddle ? '\"middle\"' : 'null';\n return {\n signal: `${a} <= 45 || 315 <= ${a} || (135 <= ${a} && ${a} <= 225) ? ${middle} : (45 <= ${a} && ${a} <= 135) === ${orientIsLeft} ? \"top\" : \"bottom\"`\n };\n }\n if (angle <= 45 || 315 <= angle || (135 <= angle && angle <= 225)) {\n return alwaysIncludeMiddle ? 'middle' : null;\n }\n if (isSignalRef(orient)) {\n const op = 45 <= angle && angle <= 135 ? '===' : '!==';\n return { signal: `${orient.signal} ${op} \"left\" ? \"top\" : \"bottom\"` };\n }\n return (45 <= angle && angle <= 135) === (orient === 'left') ? 'top' : 'bottom';\n }\n }\n return undefined;\n}\nexport function defaultLabelAlign(angle, orient, channel) {\n if (angle === undefined) {\n return undefined;\n }\n const isX = channel === 'x';\n const startAngle = isX ? 0 : 90;\n const mainOrient = isX ? 'bottom' : 'left';\n if (isSignalRef(angle)) {\n const a = normalizeAngleExpr(angle);\n const orientIsMain = isSignalRef(orient) ? `(${orient.signal} === \"${mainOrient}\")` : orient === mainOrient;\n return {\n signal: `(${startAngle ? `(${a} + 90)` : a} % 180 === 0) ? ${isX ? null : '\"center\"'} :` +\n `(${startAngle} < ${a} && ${a} < ${180 + startAngle}) === ${orientIsMain} ? \"left\" : \"right\"`\n };\n }\n if ((angle + startAngle) % 180 === 0) {\n // For bottom, use default label align so label flush still works\n return isX ? null : 'center';\n }\n if (isSignalRef(orient)) {\n const op = startAngle < angle && angle < 180 + startAngle ? '===' : '!==';\n const orientIsMain = `${orient.signal} ${op} \"${mainOrient}\"`;\n return {\n signal: `${orientIsMain} ? \"left\" : \"right\"`\n };\n }\n if ((startAngle < angle && angle < 180 + startAngle) === (orient === mainOrient)) {\n return 'left';\n }\n return 'right';\n}\nexport function defaultLabelFlush(type, channel) {\n if (channel === 'x' && contains(['quantitative', 'temporal'], type)) {\n return true;\n }\n return undefined;\n}\nexport function defaultLabelOverlap(type, scaleType, hasTimeUnit, sort) {\n // do not prevent overlap for nominal data because there is no way to infer what the missing labels are\n if ((hasTimeUnit && !isObject(sort)) || (type !== 'nominal' && type !== 'ordinal')) {\n if (scaleType === 'log' || scaleType === 'symlog') {\n return 'greedy';\n }\n return true;\n }\n return undefined;\n}\nexport function defaultOrient(channel) {\n return channel === 'x' ? 'bottom' : 'left';\n}\nexport function defaultTickCount({ fieldOrDatumDef, scaleType, size, values: vals }) {\n var _a;\n if (!vals && !hasDiscreteDomain(scaleType) && scaleType !== 'log') {\n if (isFieldDef(fieldOrDatumDef)) {\n if (isBinning(fieldOrDatumDef.bin)) {\n // for binned data, we don't want more ticks than maxbins\n return { signal: `ceil(${size.signal}/10)` };\n }\n if (fieldOrDatumDef.timeUnit &&\n contains(['month', 'hours', 'day', 'quarter'], (_a = normalizeTimeUnit(fieldOrDatumDef.timeUnit)) === null || _a === void 0 ? void 0 : _a.unit)) {\n return undefined;\n }\n }\n return { signal: `ceil(${size.signal}/40)` };\n }\n return undefined;\n}\nexport function getFieldDefTitle(model, channel) {\n const channel2 = channel === 'x' ? 'x2' : 'y2';\n const fieldDef = model.fieldDef(channel);\n const fieldDef2 = model.fieldDef(channel2);\n const title1 = fieldDef ? fieldDef.title : undefined;\n const title2 = fieldDef2 ? fieldDef2.title : undefined;\n if (title1 && title2) {\n return mergeTitle(title1, title2);\n }\n else if (title1) {\n return title1;\n }\n else if (title2) {\n return title2;\n }\n else if (title1 !== undefined) {\n // falsy value to disable config\n return title1;\n }\n else if (title2 !== undefined) {\n // falsy value to disable config\n return title2;\n }\n return undefined;\n}\nexport function values(axis, fieldOrDatumDef) {\n const vals = axis.values;\n if (isArray(vals)) {\n return valueArray(fieldOrDatumDef, vals);\n }\n else if (isSignalRef(vals)) {\n return vals;\n }\n return undefined;\n}\nexport function defaultZindex(mark, fieldDef) {\n if (mark === 'rect' && isDiscrete(fieldDef)) {\n return 1;\n }\n return 0;\n}\n//# sourceMappingURL=properties.js.map","import { isScaleFieldDef, vgField } from '../../channeldef';\nimport { fieldFilterExpression } from '../../predicate';\nimport { isSortArray } from '../../sort';\nimport { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\nimport { getDependentFields } from './expressions';\nexport class CalculateNode extends DataFlowNode {\n constructor(parent, transform) {\n super(parent);\n this.transform = transform;\n this._dependentFields = getDependentFields(this.transform.calculate);\n }\n clone() {\n return new CalculateNode(null, duplicate(this.transform));\n }\n static parseAllForSortIndex(parent, model) {\n // get all the encoding with sort fields from model\n model.forEachFieldDef((fieldDef, channel) => {\n if (!isScaleFieldDef(fieldDef)) {\n return;\n }\n if (isSortArray(fieldDef.sort)) {\n const { field, timeUnit } = fieldDef;\n const sort = fieldDef.sort;\n // generate `datum[\"a\"] === val0 ? 0 : datum[\"a\"] === val1 ? 1 : ... : n` via FieldEqualPredicate\n const calculate = sort\n .map((sortValue, i) => {\n return `${fieldFilterExpression({ field, timeUnit, equal: sortValue })} ? ${i} : `;\n })\n .join('') + sort.length;\n parent = new CalculateNode(parent, {\n calculate,\n as: sortArrayIndexField(fieldDef, channel, { forAs: true })\n });\n }\n });\n return parent;\n }\n producedFields() {\n return new Set([this.transform.as]);\n }\n dependentFields() {\n return this._dependentFields;\n }\n assemble() {\n return {\n type: 'formula',\n expr: this.transform.calculate,\n as: this.transform.as\n };\n }\n hash() {\n return `Calculate ${hash(this.transform)}`;\n }\n}\nexport function sortArrayIndexField(fieldDef, channel, opt) {\n return vgField(fieldDef, Object.assign({ prefix: channel, suffix: 'sort_index' }, (opt !== null && opt !== void 0 ? opt : {})));\n}\n//# sourceMappingURL=calculate.js.map","import { contains, getFirstDefined } from '../../util';\n/**\n * Get header channel, which can be different from facet channel when orient is specified or when the facet channel is facet.\n */\nexport function getHeaderChannel(channel, orient) {\n if (contains(['top', 'bottom'], orient)) {\n return 'column';\n }\n else if (contains(['left', 'right'], orient)) {\n return 'row';\n }\n return channel === 'row' ? 'row' : 'column';\n}\nexport function getHeaderProperty(prop, header, config, channel) {\n const headerSpecificConfig = channel === 'row' ? config.headerRow : channel === 'column' ? config.headerColumn : config.headerFacet;\n return getFirstDefined((header || {})[prop], headerSpecificConfig[prop], config.header[prop]);\n}\nexport function getHeaderProperties(properties, header, config, channel) {\n const props = {};\n for (const prop of properties) {\n const value = getHeaderProperty(prop, header || {}, config, channel);\n if (value !== undefined) {\n props[prop] = value;\n }\n }\n return props;\n}\n//# sourceMappingURL=common.js.map","export const HEADER_CHANNELS = ['row', 'column'];\nexport const HEADER_TYPES = ['header', 'footer'];\n//# sourceMappingURL=component.js.map","/**\n * Utility for generating row / column headers\n */\nimport { isArray } from 'vega-util';\nimport { FACET_CHANNELS } from '../../channel';\nimport { vgField } from '../../channeldef';\nimport { HEADER_LABEL_PROPERTIES, HEADER_LABEL_PROPERTIES_MAP, HEADER_TITLE_PROPERTIES, HEADER_TITLE_PROPERTIES_MAP } from '../../header';\nimport { isSortField } from '../../sort';\nimport { isFacetMapping } from '../../spec/facet';\nimport { contains, isEmpty, normalizeAngle, replaceAll } from '../../util';\nimport { defaultLabelAlign, defaultLabelBaseline } from '../axis/properties';\nimport { sortArrayIndexField } from '../data/calculate';\nimport { formatSignalRef } from '../format';\nimport { isFacetModel } from '../model';\nimport { getHeaderChannel, getHeaderProperties, getHeaderProperty } from './common';\nimport { HEADER_TYPES } from './component';\n// TODO: rename to assembleHeaderTitleGroup\nexport function assembleTitleGroup(model, channel) {\n const title = model.component.layoutHeaders[channel].title;\n const config = model.config ? model.config : undefined;\n const facetFieldDef = model.component.layoutHeaders[channel].facetFieldDef\n ? model.component.layoutHeaders[channel].facetFieldDef\n : undefined;\n const { titleAnchor, titleAngle: ta, titleOrient } = getHeaderProperties(['titleAnchor', 'titleAngle', 'titleOrient'], facetFieldDef.header, config, channel);\n const headerChannel = getHeaderChannel(channel, titleOrient);\n const titleAngle = normalizeAngle(ta);\n return {\n name: `${channel}-title`,\n type: 'group',\n role: `${headerChannel}-title`,\n title: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ text: title }, (channel === 'row' ? { orient: 'left' } : {})), { style: 'guide-title' }), defaultHeaderGuideBaseline(titleAngle, headerChannel)), defaultHeaderGuideAlign(headerChannel, titleAngle, titleAnchor)), assembleHeaderProperties(config, facetFieldDef, channel, HEADER_TITLE_PROPERTIES, HEADER_TITLE_PROPERTIES_MAP))\n };\n}\nexport function defaultHeaderGuideAlign(headerChannel, angle, anchor = 'middle') {\n switch (anchor) {\n case 'start':\n return { align: 'left' };\n case 'end':\n return { align: 'right' };\n }\n const align = defaultLabelAlign(angle, headerChannel === 'row' ? 'left' : 'top', headerChannel === 'row' ? 'y' : 'x');\n return align ? { align } : {};\n}\nexport function defaultHeaderGuideBaseline(angle, channel) {\n const baseline = defaultLabelBaseline(angle, channel === 'row' ? 'left' : 'top', channel === 'row' ? 'y' : 'x', true);\n return baseline ? { baseline } : {};\n}\nexport function assembleHeaderGroups(model, channel) {\n const layoutHeader = model.component.layoutHeaders[channel];\n const groups = [];\n for (const headerType of HEADER_TYPES) {\n if (layoutHeader[headerType]) {\n for (const headerComponent of layoutHeader[headerType]) {\n const group = assembleHeaderGroup(model, channel, headerType, layoutHeader, headerComponent);\n if (group != null) {\n groups.push(group);\n }\n }\n }\n }\n return groups;\n}\nfunction getSort(facetFieldDef, channel) {\n var _a;\n const { sort } = facetFieldDef;\n if (isSortField(sort)) {\n return {\n field: vgField(sort, { expr: 'datum' }),\n order: (_a = sort.order) !== null && _a !== void 0 ? _a : 'ascending'\n };\n }\n else if (isArray(sort)) {\n return {\n field: sortArrayIndexField(facetFieldDef, channel, { expr: 'datum' }),\n order: 'ascending'\n };\n }\n else {\n return {\n field: vgField(facetFieldDef, { expr: 'datum' }),\n order: sort !== null && sort !== void 0 ? sort : 'ascending'\n };\n }\n}\nexport function assembleLabelTitle(facetFieldDef, channel, config) {\n const { format, formatType, labelAngle, labelAnchor, labelOrient, labelExpr } = getHeaderProperties(['format', 'formatType', 'labelAngle', 'labelAnchor', 'labelOrient', 'labelExpr'], facetFieldDef.header, config, channel);\n const titleTextExpr = formatSignalRef({\n fieldOrDatumDef: facetFieldDef,\n format,\n formatType,\n expr: 'parent',\n config\n }).signal;\n const headerChannel = getHeaderChannel(channel, labelOrient);\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ text: {\n signal: labelExpr\n ? replaceAll(replaceAll(labelExpr, 'datum.label', titleTextExpr), 'datum.value', vgField(facetFieldDef, { expr: 'parent' }))\n : titleTextExpr\n } }, (channel === 'row' ? { orient: 'left' } : {})), { style: 'guide-label', frame: 'group' }), defaultHeaderGuideBaseline(labelAngle, headerChannel)), defaultHeaderGuideAlign(headerChannel, labelAngle, labelAnchor)), assembleHeaderProperties(config, facetFieldDef, channel, HEADER_LABEL_PROPERTIES, HEADER_LABEL_PROPERTIES_MAP));\n}\nexport function assembleHeaderGroup(model, channel, headerType, layoutHeader, headerComponent) {\n if (headerComponent) {\n let title = null;\n const { facetFieldDef } = layoutHeader;\n const config = model.config ? model.config : undefined;\n if (facetFieldDef && headerComponent.labels) {\n const { labelOrient } = getHeaderProperties(['labelOrient'], facetFieldDef.header, config, channel);\n // Include label title in the header if orient aligns with the channel\n if ((channel === 'row' && !contains(['top', 'bottom'], labelOrient)) ||\n (channel === 'column' && !contains(['left', 'right'], labelOrient))) {\n title = assembleLabelTitle(facetFieldDef, channel, config);\n }\n }\n const isFacetWithoutRowCol = isFacetModel(model) && !isFacetMapping(model.facet);\n const axes = headerComponent.axes;\n const hasAxes = (axes === null || axes === void 0 ? void 0 : axes.length) > 0;\n if (title || hasAxes) {\n const sizeChannel = channel === 'row' ? 'height' : 'width';\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name: model.getName(`${channel}_${headerType}`), type: 'group', role: `${channel}-${headerType}` }, (layoutHeader.facetFieldDef\n ? {\n from: { data: model.getName(`${channel}_domain`) },\n sort: getSort(facetFieldDef, channel)\n }\n : {})), (hasAxes && isFacetWithoutRowCol\n ? {\n from: { data: model.getName(`facet_domain_${channel}`) }\n }\n : {})), (title ? { title } : {})), (headerComponent.sizeSignal\n ? {\n encode: {\n update: {\n [sizeChannel]: headerComponent.sizeSignal\n }\n }\n }\n : {})), (hasAxes ? { axes } : {}));\n }\n }\n return null;\n}\nconst LAYOUT_TITLE_BAND = {\n column: {\n start: 0,\n end: 1\n },\n row: {\n start: 1,\n end: 0\n }\n};\nexport function getLayoutTitleBand(titleAnchor, headerChannel) {\n return LAYOUT_TITLE_BAND[headerChannel][titleAnchor];\n}\nexport function assembleLayoutTitleBand(headerComponentIndex, config) {\n const titleBand = {};\n for (const channel of FACET_CHANNELS) {\n const headerComponent = headerComponentIndex[channel];\n if (headerComponent === null || headerComponent === void 0 ? void 0 : headerComponent.facetFieldDef) {\n const { titleAnchor, titleOrient } = getHeaderProperties(['titleAnchor', 'titleOrient'], headerComponent.facetFieldDef.header, config, channel);\n const headerChannel = getHeaderChannel(channel, titleOrient);\n const band = getLayoutTitleBand(titleAnchor, headerChannel);\n if (band !== undefined) {\n titleBand[headerChannel] = band;\n }\n }\n }\n return isEmpty(titleBand) ? undefined : titleBand;\n}\nexport function assembleHeaderProperties(config, facetFieldDef, channel, properties, propertiesMap) {\n const props = {};\n for (const prop of properties) {\n if (!propertiesMap[prop]) {\n continue;\n }\n const value = getHeaderProperty(prop, facetFieldDef === null || facetFieldDef === void 0 ? void 0 : facetFieldDef.header, config, channel);\n if (value !== undefined) {\n props[propertiesMap[prop]] = value;\n }\n }\n return props;\n}\n//# sourceMappingURL=assemble.js.map","import { getViewConfigContinuousSize } from '../../config';\nimport { hasDiscreteDomain } from '../../scale';\nimport { getFirstDefined } from '../../util';\nimport { isVgRangeStep } from '../../vega.schema';\nimport { signalOrStringValue } from '../common';\nimport { isFacetModel } from '../model';\nexport function assembleLayoutSignals(model) {\n return [\n ...sizeSignals(model, 'width'),\n ...sizeSignals(model, 'height'),\n ...sizeSignals(model, 'childWidth'),\n ...sizeSignals(model, 'childHeight')\n ];\n}\nexport function sizeSignals(model, sizeType) {\n const channel = sizeType === 'width' ? 'x' : 'y';\n const size = model.component.layoutSize.get(sizeType);\n if (!size || size === 'merged') {\n return [];\n }\n // Read size signal name from name map, just in case it is the top-level size signal that got renamed.\n const name = model.getSizeSignalRef(sizeType).signal;\n if (size === 'step') {\n const scaleComponent = model.getScaleComponent(channel);\n if (scaleComponent) {\n const type = scaleComponent.get('type');\n const range = scaleComponent.get('range');\n if (hasDiscreteDomain(type) && isVgRangeStep(range)) {\n const scaleName = model.scaleName(channel);\n if (isFacetModel(model.parent)) {\n // If parent is facet and this is an independent scale, return only signal signal\n // as the width/height will be calculated using the cardinality from\n // facet's aggregate rather than reading from scale domain\n const parentResolve = model.parent.component.resolve;\n if (parentResolve.scale[channel] === 'independent') {\n return [stepSignal(scaleName, range)];\n }\n }\n return [\n stepSignal(scaleName, range),\n {\n name,\n update: sizeExpr(scaleName, scaleComponent, `domain('${scaleName}').length`)\n }\n ];\n }\n }\n /* istanbul ignore next: Condition should not happen -- only for warning in development. */\n throw new Error('layout size is step although width/height is not step.');\n }\n else if (size == 'container') {\n const isWidth = name.endsWith('width');\n const expr = isWidth ? 'containerSize()[0]' : 'containerSize()[1]';\n const defaultValue = getViewConfigContinuousSize(model.config.view, isWidth ? 'width' : 'height');\n const safeExpr = `isFinite(${expr}) ? ${expr} : ${defaultValue}`;\n return [{ name, init: safeExpr, on: [{ update: safeExpr, events: 'window:resize' }] }];\n }\n else {\n return [\n {\n name,\n value: size\n }\n ];\n }\n}\nfunction stepSignal(scaleName, range) {\n return {\n name: `${scaleName}_step`,\n value: range.step\n };\n}\nexport function sizeExpr(scaleName, scaleComponent, cardinality) {\n const type = scaleComponent.get('type');\n const padding = scaleComponent.get('padding');\n const paddingOuter = getFirstDefined(scaleComponent.get('paddingOuter'), padding);\n let paddingInner = scaleComponent.get('paddingInner');\n paddingInner =\n type === 'band'\n ? // only band has real paddingInner\n paddingInner !== undefined\n ? paddingInner\n : padding\n : // For point, as calculated in https://github.com/vega/vega-scale/blob/master/src/band.js#L128,\n // it's equivalent to have paddingInner = 1 since there is only n-1 steps between n points.\n 1;\n return `bandspace(${cardinality}, ${signalOrStringValue(paddingInner)}, ${signalOrStringValue(paddingOuter)}) * ${scaleName}_step`;\n}\n//# sourceMappingURL=assemble.js.map","export function getSizeTypeFromLayoutSizeType(layoutSizeType) {\n return layoutSizeType === 'childWidth' ? 'width' : layoutSizeType === 'childHeight' ? 'height' : layoutSizeType;\n}\n//# sourceMappingURL=component.js.map","import { keys } from '../util';\nimport { signalOrValueRef } from './common';\nimport { wrapCondition } from './mark/encode';\nexport function guideEncodeEntry(encoding, model) {\n return keys(encoding).reduce((encode, channel) => {\n const valueDef = encoding[channel];\n return Object.assign(Object.assign({}, encode), wrapCondition(model, valueDef, channel, def => signalOrValueRef(def.value)));\n }, {});\n}\n//# sourceMappingURL=guide.js.map","import { isXorY } from '../channel';\nimport * as log from '../log';\nimport { isConcatModel, isFacetModel, isLayerModel } from './model';\nexport function defaultScaleResolve(channel, model) {\n if (isFacetModel(model)) {\n return channel === 'theta' ? 'independent' : 'shared';\n }\n else if (isLayerModel(model)) {\n return 'shared';\n }\n else if (isConcatModel(model)) {\n return isXorY(channel) || channel === 'theta' || channel === 'radius' ? 'independent' : 'shared';\n }\n /* istanbul ignore next: should never reach here. */\n throw new Error('invalid model type for resolve');\n}\nexport function parseGuideResolve(resolve, channel) {\n const channelScaleResolve = resolve.scale[channel];\n const guide = isXorY(channel) ? 'axis' : 'legend';\n if (channelScaleResolve === 'independent') {\n if (resolve[guide][channel] === 'shared') {\n log.warn(log.message.independentScaleMeansIndependentGuide(channel));\n }\n return 'independent';\n }\n return resolve[guide][channel] || 'shared';\n}\n//# sourceMappingURL=resolve.js.map","import { COMMON_LEGEND_PROPERTY_INDEX } from '../../legend';\nimport { keys } from '../../util';\nimport { Split } from '../split';\nconst LEGEND_COMPONENT_PROPERTY_INDEX = Object.assign(Object.assign({}, COMMON_LEGEND_PROPERTY_INDEX), { disable: 1, labelExpr: 1, selections: 1, \n // channel scales\n opacity: 1, shape: 1, stroke: 1, fill: 1, size: 1, strokeWidth: 1, strokeDash: 1, \n // encode\n encode: 1 });\nexport const LEGEND_COMPONENT_PROPERTIES = keys(LEGEND_COMPONENT_PROPERTY_INDEX);\nexport class LegendComponent extends Split {\n}\n//# sourceMappingURL=component.js.map","import { array, isArray, stringValue } from 'vega-util';\nimport { COLOR, OPACITY } from '../../channel';\nimport { hasConditionalValueDef, isFieldDef, isValueDef } from '../../channeldef';\nimport { FILL_STROKE_CONFIG } from '../../mark';\nimport { getFirstDefined, isEmpty, varName } from '../../util';\nimport { applyMarkConfig, signalOrValueRef } from '../common';\nimport { formatCustomType, isCustomFormatType } from '../format';\nimport * as mixins from '../mark/encode';\nimport { STORE } from '../selection';\nexport const legendEncodeRules = {\n symbols,\n gradient,\n labels,\n entries\n};\nexport function symbols(symbolsSpec, { fieldOrDatumDef, model, channel, legendCmpt, legendType }) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (legendType !== 'symbol') {\n return undefined;\n }\n const { markDef, encoding, config, mark } = model;\n const filled = markDef.filled && mark !== 'trail';\n let out = Object.assign(Object.assign({}, applyMarkConfig({}, model, FILL_STROKE_CONFIG)), mixins.color(model, { filled })); // FIXME: remove this when VgEncodeEntry is compatible with SymbolEncodeEntry\n const symbolOpacity = (_a = legendCmpt.get('symbolOpacity')) !== null && _a !== void 0 ? _a : config.legend.symbolOpacity;\n const symbolFillColor = (_b = legendCmpt.get('symbolFillColor')) !== null && _b !== void 0 ? _b : config.legend.symbolFillColor;\n const symbolStrokeColor = (_c = legendCmpt.get('symbolStrokeColor')) !== null && _c !== void 0 ? _c : config.legend.symbolStrokeColor;\n const opacity = symbolOpacity === undefined ? (_d = getMaxValue(encoding.opacity)) !== null && _d !== void 0 ? _d : markDef.opacity : undefined;\n if (out.fill) {\n // for fill legend, we don't want any fill in symbol\n if (channel === 'fill' || (filled && channel === COLOR)) {\n delete out.fill;\n }\n else {\n if (out.fill['field']) {\n // For others, set fill to some opaque value (or nothing if a color is already set)\n if (symbolFillColor) {\n delete out.fill;\n }\n else {\n out.fill = signalOrValueRef((_e = config.legend.symbolBaseFillColor) !== null && _e !== void 0 ? _e : 'black');\n out.fillOpacity = signalOrValueRef(opacity !== null && opacity !== void 0 ? opacity : 1);\n }\n }\n else if (isArray(out.fill)) {\n const fill = (_h = (_g = getFirstConditionValue((_f = encoding.fill) !== null && _f !== void 0 ? _f : encoding.color)) !== null && _g !== void 0 ? _g : markDef.fill) !== null && _h !== void 0 ? _h : (filled && markDef.color);\n if (fill) {\n out.fill = signalOrValueRef(fill);\n }\n }\n }\n }\n if (out.stroke) {\n if (channel === 'stroke' || (!filled && channel === COLOR)) {\n delete out.stroke;\n }\n else {\n if (out.stroke['field'] || symbolStrokeColor) {\n // For others, remove stroke field\n delete out.stroke;\n }\n else if (isArray(out.stroke)) {\n const stroke = getFirstDefined(getFirstConditionValue(encoding.stroke || encoding.color), markDef.stroke, filled ? markDef.color : undefined);\n if (stroke) {\n out.stroke = { value: stroke };\n }\n }\n }\n }\n if (channel !== OPACITY) {\n const condition = isFieldDef(fieldOrDatumDef) && selectedCondition(model, legendCmpt, fieldOrDatumDef);\n if (condition) {\n out.opacity = [\n Object.assign({ test: condition }, signalOrValueRef(opacity !== null && opacity !== void 0 ? opacity : 1)),\n signalOrValueRef(config.legend.unselectedOpacity)\n ];\n }\n else if (opacity) {\n out.opacity = signalOrValueRef(opacity);\n }\n }\n out = Object.assign(Object.assign({}, out), symbolsSpec);\n return isEmpty(out) ? undefined : out;\n}\nexport function gradient(gradientSpec, { model, legendType, legendCmpt }) {\n var _a;\n if (legendType !== 'gradient') {\n return undefined;\n }\n const { config, markDef, encoding } = model;\n let out = {};\n const gradientOpacity = (_a = legendCmpt.get('gradientOpacity')) !== null && _a !== void 0 ? _a : config.legend.gradientOpacity;\n const opacity = gradientOpacity === undefined ? getMaxValue(encoding.opacity) || markDef.opacity : undefined;\n if (opacity) {\n // only apply opacity if it is neither zero or undefined\n out.opacity = signalOrValueRef(opacity);\n }\n out = Object.assign(Object.assign({}, out), gradientSpec);\n return isEmpty(out) ? undefined : out;\n}\nexport function labels(specifiedlabelsSpec, { fieldOrDatumDef, model, channel, legendCmpt }) {\n const legend = model.legend(channel) || {};\n const config = model.config;\n const condition = isFieldDef(fieldOrDatumDef) ? selectedCondition(model, legendCmpt, fieldOrDatumDef) : undefined;\n const opacity = condition ? [{ test: condition, value: 1 }, { value: config.legend.unselectedOpacity }] : undefined;\n const { format, formatType } = legend;\n const text = isCustomFormatType(formatType)\n ? formatCustomType({\n fieldOrDatumDef,\n field: 'datum.value',\n format,\n formatType,\n config\n })\n : undefined;\n const labelsSpec = Object.assign(Object.assign(Object.assign({}, (opacity ? { opacity } : {})), (text ? { text } : {})), specifiedlabelsSpec);\n return isEmpty(labelsSpec) ? undefined : labelsSpec;\n}\nexport function entries(entriesSpec, { legendCmpt }) {\n const selections = legendCmpt.get('selections');\n return (selections === null || selections === void 0 ? void 0 : selections.length) ? Object.assign(Object.assign({}, entriesSpec), { fill: { value: 'transparent' } }) : entriesSpec;\n}\nfunction getMaxValue(channelDef) {\n return getConditionValue(channelDef, (v, conditionalDef) => Math.max(v, conditionalDef.value));\n}\nexport function getFirstConditionValue(channelDef) {\n return getConditionValue(channelDef, (v, conditionalDef) => {\n return getFirstDefined(v, conditionalDef.value);\n });\n}\nfunction getConditionValue(channelDef, reducer) {\n if (hasConditionalValueDef(channelDef)) {\n return array(channelDef.condition).reduce(reducer, channelDef.value);\n }\n else if (isValueDef(channelDef)) {\n return channelDef.value;\n }\n return undefined;\n}\nfunction selectedCondition(model, legendCmpt, fieldDef) {\n const selections = legendCmpt.get('selections');\n if (!(selections === null || selections === void 0 ? void 0 : selections.length))\n return undefined;\n const field = stringValue(fieldDef.field);\n return selections\n .map(name => {\n const store = stringValue(varName(name) + STORE);\n return `(!length(data(${store})) || (${name}[${field}] && indexof(${name}[${field}], datum.value) >= 0))`;\n })\n .join(' || ');\n}\n//# sourceMappingURL=encode.js.map","import { isArray } from 'vega-util';\nimport { isColorChannel } from '../../channel';\nimport { title as fieldDefTitle, valueArray } from '../../channeldef';\nimport { isContinuousToContinuous } from '../../scale';\nimport { contains, getFirstDefined } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { guideFormat, guideFormatType } from '../format';\nimport { getFirstConditionValue } from './encode';\nexport const legendRules = {\n direction: ({ direction }) => direction,\n format: ({ fieldOrDatumDef, legend, config }) => {\n const { format, formatType } = legend;\n return guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, format, formatType, config, false);\n },\n formatType: ({ legend, fieldOrDatumDef, scaleType }) => {\n const { formatType } = legend;\n return guideFormatType(formatType, fieldOrDatumDef, scaleType);\n },\n gradientLength: params => {\n var _a, _b;\n const { legend, legendConfig } = params;\n return (_b = (_a = legend.gradientLength) !== null && _a !== void 0 ? _a : legendConfig.gradientLength) !== null && _b !== void 0 ? _b : defaultGradientLength(params);\n },\n labelOverlap: ({ legend, legendConfig, scaleType }) => { var _a, _b; return (_b = (_a = legend.labelOverlap) !== null && _a !== void 0 ? _a : legendConfig.labelOverlap) !== null && _b !== void 0 ? _b : defaultLabelOverlap(scaleType); },\n symbolType: ({ legend, markDef, channel, encoding }) => { var _a; return (_a = legend.symbolType) !== null && _a !== void 0 ? _a : defaultSymbolType(markDef.type, channel, encoding.shape, markDef.shape); },\n title: ({ fieldOrDatumDef, config }) => fieldDefTitle(fieldOrDatumDef, config, { allowDisabling: true }),\n type: ({ legendType, scaleType, channel }) => {\n if (isColorChannel(channel) && isContinuousToContinuous(scaleType)) {\n if (legendType === 'gradient') {\n return undefined;\n }\n }\n else if (legendType === 'symbol') {\n return undefined;\n }\n return legendType;\n },\n values: ({ fieldOrDatumDef, legend }) => values(legend, fieldOrDatumDef)\n};\nexport function values(legend, fieldOrDatumDef) {\n const vals = legend.values;\n if (isArray(vals)) {\n return valueArray(fieldOrDatumDef, vals);\n }\n else if (isSignalRef(vals)) {\n return vals;\n }\n return undefined;\n}\nexport function defaultSymbolType(mark, channel, shapeChannelDef, markShape) {\n var _a;\n if (channel !== 'shape') {\n // use the value from the shape encoding or the mark config if they exist\n const shape = (_a = getFirstConditionValue(shapeChannelDef)) !== null && _a !== void 0 ? _a : markShape;\n if (shape) {\n return shape;\n }\n }\n switch (mark) {\n case 'bar':\n case 'rect':\n case 'image':\n case 'square':\n return 'square';\n case 'line':\n case 'trail':\n case 'rule':\n return 'stroke';\n case 'arc':\n case 'point':\n case 'circle':\n case 'tick':\n case 'geoshape':\n case 'area':\n case 'text':\n return 'circle';\n }\n}\nexport function clipHeight(legendType) {\n if (legendType === 'gradient') {\n return 20;\n }\n return undefined;\n}\nexport function getLegendType(params) {\n const { legend } = params;\n return getFirstDefined(legend.type, defaultType(params));\n}\nexport function defaultType({ channel, timeUnit, scaleType }) {\n // Following the logic in https://github.com/vega/vega-parser/blob/master/src/parsers/legend.js\n if (isColorChannel(channel)) {\n if (contains(['quarter', 'month', 'day'], timeUnit)) {\n return 'symbol';\n }\n if (isContinuousToContinuous(scaleType)) {\n return 'gradient';\n }\n }\n return 'symbol';\n}\nexport function getDirection({ legendConfig, legendType, orient, legend }) {\n var _a, _b;\n return ((_b = (_a = legend.direction) !== null && _a !== void 0 ? _a : legendConfig[legendType ? 'gradientDirection' : 'symbolDirection']) !== null && _b !== void 0 ? _b : defaultDirection(orient, legendType));\n}\nexport function defaultDirection(orient, legendType) {\n switch (orient) {\n case 'top':\n case 'bottom':\n return 'horizontal';\n case 'left':\n case 'right':\n case 'none':\n case undefined: // undefined = \"right\" in Vega\n return undefined; // vertical is Vega's default\n default:\n // top-left / ...\n // For inner legend, uses compact layout like Tableau\n return legendType === 'gradient' ? 'horizontal' : undefined;\n }\n}\nexport function defaultGradientLength({ legendConfig, model, direction, orient, scaleType }) {\n const { gradientHorizontalMaxLength, gradientHorizontalMinLength, gradientVerticalMaxLength, gradientVerticalMinLength } = legendConfig;\n if (isContinuousToContinuous(scaleType)) {\n if (direction === 'horizontal') {\n if (orient === 'top' || orient === 'bottom') {\n return gradientLengthSignal(model, 'width', gradientHorizontalMinLength, gradientHorizontalMaxLength);\n }\n else {\n return gradientHorizontalMinLength;\n }\n }\n else {\n // vertical / undefined (Vega uses vertical by default)\n return gradientLengthSignal(model, 'height', gradientVerticalMinLength, gradientVerticalMaxLength);\n }\n }\n return undefined;\n}\nfunction gradientLengthSignal(model, sizeType, min, max) {\n const sizeSignal = model.getSizeSignalRef(sizeType).signal;\n return { signal: `clamp(${sizeSignal}, ${min}, ${max})` };\n}\nexport function defaultLabelOverlap(scaleType) {\n if (contains(['quantile', 'threshold', 'log', 'symlog'], scaleType)) {\n return 'greedy';\n }\n return undefined;\n}\n//# sourceMappingURL=properties.js.map","import { COLOR, SHAPE } from '../../channel';\nimport { getFieldOrDatumDef, isFieldDef } from '../../channeldef';\nimport { LEGEND_SCALE_CHANNELS } from '../../legend';\nimport { normalizeTimeUnit } from '../../timeunit';\nimport { GEOJSON } from '../../type';\nimport { deleteNestedProperty, isEmpty, keys, varName } from '../../util';\nimport { mergeTitleComponent } from '../common';\nimport { guideEncodeEntry } from '../guide';\nimport { isUnitModel } from '../model';\nimport { parseGuideResolve } from '../resolve';\nimport { parseInteractiveLegend } from '../selection/legends';\nimport { defaultTieBreaker, makeImplicit, mergeValuesWithExplicit } from '../split';\nimport { LegendComponent, LEGEND_COMPONENT_PROPERTIES } from './component';\nimport { legendEncodeRules } from './encode';\nimport { getDirection, getLegendType, legendRules } from './properties';\nexport function parseLegend(model) {\n const legendComponent = isUnitModel(model) ? parseUnitLegend(model) : parseNonUnitLegend(model);\n model.component.legends = legendComponent;\n return legendComponent;\n}\nfunction parseUnitLegend(model) {\n const { encoding } = model;\n const legendComponent = {};\n for (const channel of [COLOR, ...LEGEND_SCALE_CHANNELS]) {\n const def = getFieldOrDatumDef(encoding[channel]);\n if (!def || !model.getScaleComponent(channel)) {\n continue;\n }\n if (channel === SHAPE && isFieldDef(def) && def.type === GEOJSON) {\n continue;\n }\n legendComponent[channel] = parseLegendForChannel(model, channel);\n }\n return legendComponent;\n}\nfunction getLegendDefWithScale(model, channel) {\n const scale = model.scaleName(channel);\n if (model.mark === 'trail') {\n if (channel === 'color') {\n // trail is a filled mark, but its default symbolType (\"stroke\") should use \"stroke\"\n return { stroke: scale };\n }\n else if (channel === 'size') {\n return { strokeWidth: scale };\n }\n }\n if (channel === 'color') {\n return model.markDef.filled ? { fill: scale } : { stroke: scale };\n }\n return { [channel]: scale };\n}\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isExplicit(value, property, legend, fieldDef) {\n switch (property) {\n case 'disable':\n return legend !== undefined; // if axis is specified or null/false, then its enable/disable state is explicit\n case 'values':\n // specified legend.values is already respected, but may get transformed.\n return !!(legend === null || legend === void 0 ? void 0 : legend.values);\n case 'title':\n // title can be explicit if fieldDef.title is set\n if (property === 'title' && value === (fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.title)) {\n return true;\n }\n }\n // Otherwise, things are explicit if the returned value matches the specified property\n return value === (legend || {})[property];\n}\nexport function parseLegendForChannel(model, channel) {\n var _a, _b, _c;\n let legend = model.legend(channel);\n const { markDef, encoding, config } = model;\n const legendConfig = config.legend;\n const legendCmpt = new LegendComponent({}, getLegendDefWithScale(model, channel));\n parseInteractiveLegend(model, channel, legendCmpt);\n const disable = legend !== undefined ? !legend : legendConfig.disable;\n legendCmpt.set('disable', disable, legend !== undefined);\n if (disable) {\n return legendCmpt;\n }\n legend = legend || {};\n const scaleType = model.getScaleComponent(channel).get('type');\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);\n const timeUnit = isFieldDef(fieldOrDatumDef) ? (_a = normalizeTimeUnit(fieldOrDatumDef.timeUnit)) === null || _a === void 0 ? void 0 : _a.unit : undefined;\n const orient = legend.orient || config.legend.orient || 'right';\n const legendType = getLegendType({ legend, channel, timeUnit, scaleType });\n const direction = getDirection({ legend, legendType, orient, legendConfig });\n const ruleParams = {\n legend,\n channel,\n model,\n markDef,\n encoding,\n fieldOrDatumDef,\n legendConfig,\n config,\n scaleType,\n orient,\n legendType,\n direction\n };\n for (const property of LEGEND_COMPONENT_PROPERTIES) {\n if ((legendType === 'gradient' && property.startsWith('symbol')) ||\n (legendType === 'symbol' && property.startsWith('gradient'))) {\n continue;\n }\n const value = property in legendRules ? legendRules[property](ruleParams) : legend[property];\n if (value !== undefined) {\n const explicit = isExplicit(value, property, legend, model.fieldDef(channel));\n if (explicit || config.legend[property] === undefined) {\n legendCmpt.set(property, value, explicit);\n }\n }\n }\n const legendEncoding = (_b = legend === null || legend === void 0 ? void 0 : legend.encoding) !== null && _b !== void 0 ? _b : {};\n const selections = legendCmpt.get('selections');\n const legendEncode = {};\n const legendEncodeParams = { fieldOrDatumDef, model, channel, legendCmpt, legendType };\n for (const part of ['labels', 'legend', 'title', 'symbols', 'gradient', 'entries']) {\n const legendEncodingPart = guideEncodeEntry((_c = legendEncoding[part]) !== null && _c !== void 0 ? _c : {}, model);\n const value = part in legendEncodeRules\n ? legendEncodeRules[part](legendEncodingPart, legendEncodeParams) // apply rule\n : legendEncodingPart; // no rule -- just default values\n if (value !== undefined && !isEmpty(value)) {\n legendEncode[part] = Object.assign(Object.assign(Object.assign({}, ((selections === null || selections === void 0 ? void 0 : selections.length) && isFieldDef(fieldOrDatumDef)\n ? { name: `${varName(fieldOrDatumDef.field)}_legend_${part}` }\n : {})), ((selections === null || selections === void 0 ? void 0 : selections.length) ? { interactive: !!selections } : {})), { update: value });\n }\n }\n if (!isEmpty(legendEncode)) {\n legendCmpt.set('encode', legendEncode, !!(legend === null || legend === void 0 ? void 0 : legend.encoding));\n }\n return legendCmpt;\n}\nfunction parseNonUnitLegend(model) {\n const { legends, resolve } = model.component;\n for (const child of model.children) {\n parseLegend(child);\n for (const channel of keys(child.component.legends)) {\n resolve.legend[channel] = parseGuideResolve(model.component.resolve, channel);\n if (resolve.legend[channel] === 'shared') {\n // If the resolve says shared (and has not been overridden)\n // We will try to merge and see if there is a conflict\n legends[channel] = mergeLegendComponent(legends[channel], child.component.legends[channel]);\n if (!legends[channel]) {\n // If merge returns nothing, there is a conflict so we cannot make the legend shared.\n // Thus, mark legend as independent and remove the legend component.\n resolve.legend[channel] = 'independent';\n delete legends[channel];\n }\n }\n }\n }\n for (const channel of keys(legends)) {\n for (const child of model.children) {\n if (!child.component.legends[channel]) {\n // skip if the child does not have a particular legend\n continue;\n }\n if (resolve.legend[channel] === 'shared') {\n // After merging shared legend, make sure to remove legend from child\n delete child.component.legends[channel];\n }\n }\n }\n return legends;\n}\nexport function mergeLegendComponent(mergedLegend, childLegend) {\n var _a, _b, _c, _d;\n if (!mergedLegend) {\n return childLegend.clone();\n }\n const mergedOrient = mergedLegend.getWithExplicit('orient');\n const childOrient = childLegend.getWithExplicit('orient');\n if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {\n // TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.)\n // Cannot merge due to inconsistent orient\n return undefined;\n }\n let typeMerged = false;\n // Otherwise, let's merge\n for (const prop of LEGEND_COMPONENT_PROPERTIES) {\n const mergedValueWithExplicit = mergeValuesWithExplicit(mergedLegend.getWithExplicit(prop), childLegend.getWithExplicit(prop), prop, 'legend', \n // Tie breaker function\n (v1, v2) => {\n switch (prop) {\n case 'symbolType':\n return mergeSymbolType(v1, v2);\n case 'title':\n return mergeTitleComponent(v1, v2);\n case 'type':\n // There are only two types. If we have different types, then prefer symbol over gradient.\n typeMerged = true;\n return makeImplicit('symbol');\n }\n return defaultTieBreaker(v1, v2, prop, 'legend');\n });\n mergedLegend.setWithExplicit(prop, mergedValueWithExplicit);\n }\n if (typeMerged) {\n if ((_b = (_a = mergedLegend.implicit) === null || _a === void 0 ? void 0 : _a.encode) === null || _b === void 0 ? void 0 : _b.gradient) {\n deleteNestedProperty(mergedLegend.implicit, ['encode', 'gradient']);\n }\n if ((_d = (_c = mergedLegend.explicit) === null || _c === void 0 ? void 0 : _c.encode) === null || _d === void 0 ? void 0 : _d.gradient) {\n deleteNestedProperty(mergedLegend.explicit, ['encode', 'gradient']);\n }\n }\n return mergedLegend;\n}\nfunction mergeSymbolType(st1, st2) {\n if (st2.value === 'circle') {\n // prefer \"circle\" over \"stroke\"\n return st2;\n }\n return st1;\n}\n//# sourceMappingURL=parse.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { LEGEND_SCALE_CHANNELS } from '../../legend';\nimport { keys, replaceAll, stringify, vals } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { mergeLegendComponent } from './parse';\nfunction setLegendEncode(legend, part, vgProp, vgRef) {\n var _a, _b, _c;\n var _d, _e;\n (_a = legend.encode) !== null && _a !== void 0 ? _a : (legend.encode = {});\n (_b = (_d = legend.encode)[part]) !== null && _b !== void 0 ? _b : (_d[part] = {});\n (_c = (_e = legend.encode[part]).update) !== null && _c !== void 0 ? _c : (_e.update = {});\n // TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291\n legend.encode[part].update[vgProp] = vgRef;\n}\nexport function assembleLegends(model) {\n const legendComponentIndex = model.component.legends;\n const legendByDomain = {};\n for (const channel of keys(legendComponentIndex)) {\n const scaleComponent = model.getScaleComponent(channel);\n const domainHash = stringify(scaleComponent.get('domains'));\n if (legendByDomain[domainHash]) {\n for (const mergedLegendComponent of legendByDomain[domainHash]) {\n const merged = mergeLegendComponent(mergedLegendComponent, legendComponentIndex[channel]);\n if (!merged) {\n // If cannot merge, need to add this legend separately\n legendByDomain[domainHash].push(legendComponentIndex[channel]);\n }\n }\n }\n else {\n legendByDomain[domainHash] = [legendComponentIndex[channel].clone()];\n }\n }\n const legends = vals(legendByDomain)\n .flat()\n .map(l => assembleLegend(l, model.config))\n .filter(l => l !== undefined);\n return legends;\n}\nexport function assembleLegend(legendCmpt, config) {\n var _a, _b, _c;\n const _d = legendCmpt.combine(), { disable, labelExpr, selections } = _d, legend = __rest(_d, [\"disable\", \"labelExpr\", \"selections\"]);\n if (disable) {\n return undefined;\n }\n if (config.aria === false && legend.aria == undefined) {\n legend.aria = false;\n }\n if ((_a = legend.encode) === null || _a === void 0 ? void 0 : _a.symbols) {\n const out = legend.encode.symbols.update;\n if (out.fill && out.fill['value'] !== 'transparent' && !out.stroke && !legend.stroke) {\n // For non color channel's legend, we need to override symbol stroke config from Vega config if stroke channel is not used.\n out.stroke = { value: 'transparent' };\n }\n // Remove properties that the legend is encoding.\n for (const property of LEGEND_SCALE_CHANNELS) {\n if (legend[property]) {\n delete out[property];\n }\n }\n }\n if (!legend.title) {\n // title schema doesn't include null, ''\n delete legend.title;\n }\n if (labelExpr !== undefined) {\n let expr = labelExpr;\n if (((_c = (_b = legend.encode) === null || _b === void 0 ? void 0 : _b.labels) === null || _c === void 0 ? void 0 : _c.update) && isSignalRef(legend.encode.labels.update.text)) {\n expr = replaceAll(labelExpr, 'datum.label', legend.encode.labels.update.text.signal);\n }\n setLegendEncode(legend, 'labels', 'text', { signal: expr });\n }\n return legend;\n}\n//# sourceMappingURL=assemble.js.map","import { contains } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { isConcatModel, isLayerModel } from '../model';\nexport function assembleProjections(model) {\n if (isLayerModel(model) || isConcatModel(model)) {\n return assembleProjectionsForModelAndChildren(model);\n }\n else {\n return assembleProjectionForModel(model);\n }\n}\nexport function assembleProjectionsForModelAndChildren(model) {\n return model.children.reduce((projections, child) => {\n return projections.concat(child.assembleProjections());\n }, assembleProjectionForModel(model));\n}\nexport function assembleProjectionForModel(model) {\n const component = model.component.projection;\n if (!component || component.merged) {\n return [];\n }\n const projection = component.combine();\n const { name } = projection; // we need to extract name so that it is always present in the output and pass TS type validation\n if (!component.data) {\n // generate custom projection, no automatic fitting\n return [\n Object.assign(Object.assign({ name }, { translate: { signal: '[width / 2, height / 2]' } }), projection)\n ];\n }\n else {\n // generate projection that uses extent fitting\n const size = {\n signal: `[${component.size.map(ref => ref.signal).join(', ')}]`\n };\n const fits = component.data.reduce((sources, data) => {\n const source = isSignalRef(data) ? data.signal : `data('${model.lookupDataSource(data)}')`;\n if (!contains(sources, source)) {\n // build a unique list of sources\n sources.push(source);\n }\n return sources;\n }, []);\n if (fits.length <= 0) {\n throw new Error(\"Projection's fit didn't find any data sources\");\n }\n return [\n Object.assign({ name,\n size, fit: {\n signal: fits.length > 1 ? `[${fits.join(', ')}]` : fits[0]\n } }, projection)\n ];\n }\n}\n//# sourceMappingURL=assemble.js.map","export const PROJECTION_PROPERTIES = [\n 'type',\n 'clipAngle',\n 'clipExtent',\n 'center',\n 'rotate',\n 'precision',\n 'reflectX',\n 'reflectY',\n 'coefficient',\n 'distance',\n 'fraction',\n 'lobes',\n 'parallel',\n 'radius',\n 'ratio',\n 'spacing',\n 'tilt'\n];\n//# sourceMappingURL=projection.js.map","import { Split } from '../split';\nexport class ProjectionComponent extends Split {\n constructor(name, specifiedProjection, size, data) {\n super(Object.assign({}, specifiedProjection), // all explicit properties of projection\n { name } // name as initial implicit property\n );\n this.specifiedProjection = specifiedProjection;\n this.size = size;\n this.data = data;\n this.merged = false;\n }\n /**\n * Whether the projection parameters should fit provided data.\n */\n get isFit() {\n return !!this.data;\n }\n}\n//# sourceMappingURL=component.js.map","import { hasOwnProperty } from 'vega-util';\nimport { LATITUDE, LATITUDE2, LONGITUDE, LONGITUDE2, SHAPE } from '../../channel';\nimport { getFieldOrDatumDef } from '../../channeldef';\nimport { DataSourceType } from '../../data';\nimport { replaceExprRef } from '../../expr';\nimport { PROJECTION_PROPERTIES } from '../../projection';\nimport { GEOJSON } from '../../type';\nimport { deepEqual, duplicate, every } from '../../util';\nimport { isUnitModel } from '../model';\nimport { ProjectionComponent } from './component';\nexport function parseProjection(model) {\n model.component.projection = isUnitModel(model) ? parseUnitProjection(model) : parseNonUnitProjections(model);\n}\nfunction parseUnitProjection(model) {\n var _a;\n if (model.hasProjection) {\n const proj = replaceExprRef(model.specifiedProjection);\n const fit = !(proj && (proj.scale != null || proj.translate != null));\n const size = fit ? [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')] : undefined;\n const data = fit ? gatherFitData(model) : undefined;\n const projComp = new ProjectionComponent(model.projectionName(true), Object.assign(Object.assign({}, ((_a = replaceExprRef(model.config.projection)) !== null && _a !== void 0 ? _a : {})), (proj !== null && proj !== void 0 ? proj : {})), size, data);\n if (!projComp.get('type')) {\n projComp.set('type', 'equalEarth', false);\n }\n return projComp;\n }\n return undefined;\n}\nfunction gatherFitData(model) {\n const data = [];\n const { encoding } = model;\n for (const posssiblePair of [\n [LONGITUDE, LATITUDE],\n [LONGITUDE2, LATITUDE2]\n ]) {\n if (getFieldOrDatumDef(encoding[posssiblePair[0]]) || getFieldOrDatumDef(encoding[posssiblePair[1]])) {\n data.push({\n signal: model.getName(`geojson_${data.length}`)\n });\n }\n }\n if (model.channelHasField(SHAPE) && model.typedFieldDef(SHAPE).type === GEOJSON) {\n data.push({\n signal: model.getName(`geojson_${data.length}`)\n });\n }\n if (data.length === 0) {\n // main source is geojson, so we can just use that\n data.push(model.requestDataName(DataSourceType.Main));\n }\n return data;\n}\nfunction mergeIfNoConflict(first, second) {\n const allPropertiesShared = every(PROJECTION_PROPERTIES, prop => {\n // neither has the property\n if (!hasOwnProperty(first.explicit, prop) && !hasOwnProperty(second.explicit, prop)) {\n return true;\n }\n // both have property and an equal value for property\n if (hasOwnProperty(first.explicit, prop) &&\n hasOwnProperty(second.explicit, prop) &&\n // some properties might be signals or objects and require hashing for comparison\n deepEqual(first.get(prop), second.get(prop))) {\n return true;\n }\n return false;\n });\n const size = deepEqual(first.size, second.size);\n if (size) {\n if (allPropertiesShared) {\n return first;\n }\n else if (deepEqual(first.explicit, {})) {\n return second;\n }\n else if (deepEqual(second.explicit, {})) {\n return first;\n }\n }\n // if all properties don't match, let each unit spec have its own projection\n return null;\n}\nfunction parseNonUnitProjections(model) {\n if (model.children.length === 0) {\n return undefined;\n }\n let nonUnitProjection;\n // parse all children first\n for (const child of model.children) {\n parseProjection(child);\n }\n // analyze parsed projections, attempt to merge\n const mergable = every(model.children, child => {\n const projection = child.component.projection;\n if (!projection) {\n // child layer does not use a projection\n return true;\n }\n else if (!nonUnitProjection) {\n // cached 'projection' is null, cache this one\n nonUnitProjection = projection;\n return true;\n }\n else {\n const merge = mergeIfNoConflict(nonUnitProjection, projection);\n if (merge) {\n nonUnitProjection = merge;\n }\n return !!merge;\n }\n });\n // if cached one and all other children share the same projection,\n if (nonUnitProjection && mergable) {\n // so we can elevate it to the layer level\n const name = model.projectionName(true);\n const modelProjection = new ProjectionComponent(name, nonUnitProjection.specifiedProjection, nonUnitProjection.size, duplicate(nonUnitProjection.data));\n // rename and assign all others as merged\n for (const child of model.children) {\n const projection = child.component.projection;\n if (projection) {\n if (projection.isFit) {\n modelProjection.data.push(...child.component.projection.data);\n }\n child.renameProjection(projection.get('name'), name);\n projection.merged = true;\n }\n }\n return modelProjection;\n }\n return undefined;\n}\n//# sourceMappingURL=parse.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isString } from 'vega-util';\nimport { binToString, isBinning, isParameterExtent } from '../../bin';\nimport { binRequiresRange, isTypedFieldDef, normalizeBin, vgField } from '../../channeldef';\nimport { duplicate, hash, isEmpty, keys, replacePathInField, unique, vals } from '../../util';\nimport { binFormatExpression } from '../format';\nimport { isUnitModel } from '../model';\nimport { parseSelectionExtent } from '../selection/parse';\nimport { DataFlowNode } from './dataflow';\nfunction rangeFormula(model, fieldDef, channel, config) {\n var _a, _b;\n if (binRequiresRange(fieldDef, channel)) {\n // read format from axis or legend, if there is no format then use config.numberFormat\n const guide = isUnitModel(model)\n ? (_b = (_a = model.axis(channel)) !== null && _a !== void 0 ? _a : model.legend(channel)) !== null && _b !== void 0 ? _b : {}\n : {};\n const startField = vgField(fieldDef, { expr: 'datum' });\n const endField = vgField(fieldDef, { expr: 'datum', binSuffix: 'end' });\n return {\n formulaAs: vgField(fieldDef, { binSuffix: 'range', forAs: true }),\n formula: binFormatExpression(startField, endField, guide.format, guide.formatType, config)\n };\n }\n return {};\n}\nfunction binKey(bin, field) {\n return `${binToString(bin)}_${field}`;\n}\nfunction getSignalsFromModel(model, key) {\n return {\n signal: model.getName(`${key}_bins`),\n extentSignal: model.getName(`${key}_extent`)\n };\n}\nexport function getBinSignalName(model, field, bin) {\n var _a;\n const normalizedBin = (_a = normalizeBin(bin, undefined)) !== null && _a !== void 0 ? _a : {};\n const key = binKey(normalizedBin, field);\n return model.getName(`${key}_bins`);\n}\nfunction isBinTransform(t) {\n return 'as' in t;\n}\nfunction createBinComponent(t, bin, model) {\n let as;\n let span;\n if (isBinTransform(t)) {\n as = isString(t.as) ? [t.as, `${t.as}_end`] : [t.as[0], t.as[1]];\n }\n else {\n as = [vgField(t, { forAs: true }), vgField(t, { binSuffix: 'end', forAs: true })];\n }\n const normalizedBin = Object.assign({}, normalizeBin(bin, undefined));\n const key = binKey(normalizedBin, t.field);\n const { signal, extentSignal } = getSignalsFromModel(model, key);\n if (isParameterExtent(normalizedBin.extent)) {\n const ext = normalizedBin.extent;\n span = parseSelectionExtent(model, ext.param, ext);\n delete normalizedBin.extent; // Vega-Lite selection extent map to Vega's span property.\n }\n const binComponent = Object.assign(Object.assign(Object.assign({ bin: normalizedBin, field: t.field, as: [as] }, (signal ? { signal } : {})), (extentSignal ? { extentSignal } : {})), (span ? { span } : {}));\n return { key, binComponent };\n}\nexport class BinNode extends DataFlowNode {\n constructor(parent, bins) {\n super(parent);\n this.bins = bins;\n }\n clone() {\n return new BinNode(null, duplicate(this.bins));\n }\n static makeFromEncoding(parent, model) {\n const bins = model.reduceFieldDef((binComponentIndex, fieldDef, channel) => {\n if (isTypedFieldDef(fieldDef) && isBinning(fieldDef.bin)) {\n const { key, binComponent } = createBinComponent(fieldDef, fieldDef.bin, model);\n binComponentIndex[key] = Object.assign(Object.assign(Object.assign({}, binComponent), binComponentIndex[key]), rangeFormula(model, fieldDef, channel, model.config));\n }\n return binComponentIndex;\n }, {});\n if (isEmpty(bins)) {\n return null;\n }\n return new BinNode(parent, bins);\n }\n /**\n * Creates a bin node from BinTransform.\n * The optional parameter should provide\n */\n static makeFromTransform(parent, t, model) {\n const { key, binComponent } = createBinComponent(t, t.bin, model);\n return new BinNode(parent, {\n [key]: binComponent\n });\n }\n /**\n * Merge bin nodes. This method either integrates the bin config from the other node\n * or if this node already has a bin config, renames the corresponding signal in the model.\n */\n merge(other, renameSignal) {\n for (const key of keys(other.bins)) {\n if (key in this.bins) {\n renameSignal(other.bins[key].signal, this.bins[key].signal);\n // Ensure that we don't have duplicate names for signal pairs\n this.bins[key].as = unique([...this.bins[key].as, ...other.bins[key].as], hash);\n }\n else {\n this.bins[key] = other.bins[key];\n }\n }\n for (const child of other.children) {\n other.removeChild(child);\n child.parent = this;\n }\n other.remove();\n }\n producedFields() {\n return new Set(vals(this.bins)\n .map(c => c.as)\n .flat(2));\n }\n dependentFields() {\n return new Set(vals(this.bins).map(c => c.field));\n }\n hash() {\n return `Bin ${hash(this.bins)}`;\n }\n assemble() {\n return vals(this.bins).flatMap(bin => {\n const transform = [];\n const [binAs, ...remainingAs] = bin.as;\n const _a = bin.bin, { extent } = _a, params = __rest(_a, [\"extent\"]);\n const binTrans = Object.assign(Object.assign(Object.assign({ type: 'bin', field: replacePathInField(bin.field), as: binAs, signal: bin.signal }, (!isParameterExtent(extent) ? { extent } : { extent: null })), (bin.span ? { span: { signal: `span(${bin.span})` } } : {})), params);\n if (!extent && bin.extentSignal) {\n transform.push({\n type: 'extent',\n field: replacePathInField(bin.field),\n signal: bin.extentSignal\n });\n binTrans.extent = { signal: bin.extentSignal };\n }\n transform.push(binTrans);\n for (const as of remainingAs) {\n for (let i = 0; i < 2; i++) {\n transform.push({\n type: 'formula',\n expr: vgField({ field: binAs[i] }, { expr: 'datum' }),\n as: as[i]\n });\n }\n }\n if (bin.formula) {\n transform.push({\n type: 'formula',\n expr: bin.formula,\n as: bin.formulaAs\n });\n }\n return transform;\n });\n }\n}\n//# sourceMappingURL=bin.js.map","import { isArgmaxDef, isArgminDef } from '../../aggregate';\nimport { getPositionChannelFromLatLong, getSecondaryRangeChannel, isGeoPositionChannel, isScaleChannel } from '../../channel';\nimport { binRequiresRange, hasBandEnd, isScaleFieldDef, isTypedFieldDef, vgField } from '../../channeldef';\nimport * as log from '../../log';\nimport { isFieldRange } from '../../scale';\nimport { duplicate, hash, keys, replacePathInField, setEqual } from '../../util';\nimport { isUnitModel } from '../model';\nimport { DataFlowNode } from './dataflow';\nfunction addDimension(dims, channel, fieldDef, model) {\n var _a;\n const channelDef2 = isUnitModel(model) ? model.encoding[getSecondaryRangeChannel(channel)] : undefined;\n if (isTypedFieldDef(fieldDef) &&\n isUnitModel(model) &&\n hasBandEnd(fieldDef, channelDef2, model.markDef, model.config)) {\n dims.add(vgField(fieldDef, {}));\n dims.add(vgField(fieldDef, { suffix: 'end' }));\n if (fieldDef.bin && binRequiresRange(fieldDef, channel)) {\n dims.add(vgField(fieldDef, { binSuffix: 'range' }));\n }\n }\n else if (isGeoPositionChannel(channel)) {\n const posChannel = getPositionChannelFromLatLong(channel);\n dims.add(model.getName(posChannel));\n }\n else {\n dims.add(vgField(fieldDef));\n }\n if (isScaleFieldDef(fieldDef) && isFieldRange((_a = fieldDef.scale) === null || _a === void 0 ? void 0 : _a.range)) {\n dims.add(fieldDef.scale.range.field);\n }\n return dims;\n}\nfunction mergeMeasures(parentMeasures, childMeasures) {\n var _a;\n for (const field of keys(childMeasures)) {\n // when we merge a measure, we either have to add an aggregation operator or even a new field\n const ops = childMeasures[field];\n for (const op of keys(ops)) {\n if (field in parentMeasures) {\n // add operator to existing measure field\n parentMeasures[field][op] = new Set([...((_a = parentMeasures[field][op]) !== null && _a !== void 0 ? _a : []), ...ops[op]]);\n }\n else {\n parentMeasures[field] = { [op]: ops[op] };\n }\n }\n }\n}\nexport class AggregateNode extends DataFlowNode {\n /**\n * @param dimensions string set for dimensions\n * @param measures dictionary mapping field name => dict of aggregation functions and names to use\n */\n constructor(parent, dimensions, measures) {\n super(parent);\n this.dimensions = dimensions;\n this.measures = measures;\n }\n clone() {\n return new AggregateNode(null, new Set(this.dimensions), duplicate(this.measures));\n }\n get groupBy() {\n return this.dimensions;\n }\n static makeFromEncoding(parent, model) {\n let isAggregate = false;\n model.forEachFieldDef(fd => {\n if (fd.aggregate) {\n isAggregate = true;\n }\n });\n const meas = {};\n const dims = new Set();\n if (!isAggregate) {\n // no need to create this node if the model has no aggregation\n return null;\n }\n model.forEachFieldDef((fieldDef, channel) => {\n var _a, _b, _c, _d;\n const { aggregate, field } = fieldDef;\n if (aggregate) {\n if (aggregate === 'count') {\n (_a = meas['*']) !== null && _a !== void 0 ? _a : (meas['*'] = {});\n meas['*']['count'] = new Set([vgField(fieldDef, { forAs: true })]);\n }\n else {\n if (isArgminDef(aggregate) || isArgmaxDef(aggregate)) {\n const op = isArgminDef(aggregate) ? 'argmin' : 'argmax';\n const argField = aggregate[op];\n (_b = meas[argField]) !== null && _b !== void 0 ? _b : (meas[argField] = {});\n meas[argField][op] = new Set([vgField({ op, field: argField }, { forAs: true })]);\n }\n else {\n (_c = meas[field]) !== null && _c !== void 0 ? _c : (meas[field] = {});\n meas[field][aggregate] = new Set([vgField(fieldDef, { forAs: true })]);\n }\n // For scale channel with domain === 'unaggregated', add min/max so we can use their union as unaggregated domain\n if (isScaleChannel(channel) && model.scaleDomain(channel) === 'unaggregated') {\n (_d = meas[field]) !== null && _d !== void 0 ? _d : (meas[field] = {});\n meas[field]['min'] = new Set([vgField({ field, aggregate: 'min' }, { forAs: true })]);\n meas[field]['max'] = new Set([vgField({ field, aggregate: 'max' }, { forAs: true })]);\n }\n }\n }\n else {\n addDimension(dims, channel, fieldDef, model);\n }\n });\n if (dims.size + keys(meas).length === 0) {\n return null;\n }\n return new AggregateNode(parent, dims, meas);\n }\n static makeFromTransform(parent, t) {\n var _a, _b, _c;\n const dims = new Set();\n const meas = {};\n for (const s of t.aggregate) {\n const { op, field, as } = s;\n if (op) {\n if (op === 'count') {\n (_a = meas['*']) !== null && _a !== void 0 ? _a : (meas['*'] = {});\n meas['*']['count'] = new Set([as ? as : vgField(s, { forAs: true })]);\n }\n else {\n (_b = meas[field]) !== null && _b !== void 0 ? _b : (meas[field] = {});\n meas[field][op] = new Set([as ? as : vgField(s, { forAs: true })]);\n }\n }\n }\n for (const s of (_c = t.groupby) !== null && _c !== void 0 ? _c : []) {\n dims.add(s);\n }\n if (dims.size + keys(meas).length === 0) {\n return null;\n }\n return new AggregateNode(parent, dims, meas);\n }\n merge(other) {\n if (setEqual(this.dimensions, other.dimensions)) {\n mergeMeasures(this.measures, other.measures);\n return true;\n }\n else {\n log.debug('different dimensions, cannot merge');\n return false;\n }\n }\n addDimensions(fields) {\n fields.forEach(this.dimensions.add, this.dimensions);\n }\n dependentFields() {\n return new Set([...this.dimensions, ...keys(this.measures)]);\n }\n producedFields() {\n const out = new Set();\n for (const field of keys(this.measures)) {\n for (const op of keys(this.measures[field])) {\n const m = this.measures[field][op];\n if (m.size === 0) {\n out.add(`${op}_${field}`);\n }\n else {\n m.forEach(out.add, out);\n }\n }\n }\n return out;\n }\n hash() {\n return `Aggregate ${hash({ dimensions: this.dimensions, measures: this.measures })}`;\n }\n assemble() {\n const ops = [];\n const fields = [];\n const as = [];\n for (const field of keys(this.measures)) {\n for (const op of keys(this.measures[field])) {\n for (const alias of this.measures[field][op]) {\n as.push(alias);\n ops.push(op);\n fields.push(field === '*' ? null : replacePathInField(field));\n }\n }\n }\n const result = {\n type: 'aggregate',\n groupby: [...this.dimensions].map(replacePathInField),\n ops,\n fields,\n as\n };\n return result;\n }\n}\n//# sourceMappingURL=aggregate.js.map","import { isArray } from 'vega-util';\nimport { isBinning } from '../../bin';\nimport { COLUMN, FACET_CHANNELS, POSITION_SCALE_CHANNELS, ROW } from '../../channel';\nimport { vgField } from '../../channeldef';\nimport * as log from '../../log';\nimport { hasDiscreteDomain } from '../../scale';\nimport { DEFAULT_SORT_OP, isSortField } from '../../sort';\nimport { hash } from '../../util';\nimport { isVgRangeStep } from '../../vega.schema';\nimport { HEADER_CHANNELS, HEADER_TYPES } from '../header/component';\nimport { assembleDomain, getFieldFromDomain } from '../scale/domain';\nimport { sortArrayIndexField } from './calculate';\nimport { DataFlowNode } from './dataflow';\n/**\n * A node that helps us track what fields we are faceting by.\n */\nexport class FacetNode extends DataFlowNode {\n /**\n * @param model The facet model.\n * @param name The name that this facet source will have.\n * @param data The source data for this facet data.\n */\n constructor(parent, model, name, data) {\n super(parent);\n this.model = model;\n this.name = name;\n this.data = data;\n for (const channel of FACET_CHANNELS) {\n const fieldDef = model.facet[channel];\n if (fieldDef) {\n const { bin, sort } = fieldDef;\n this[channel] = Object.assign({ name: model.getName(`${channel}_domain`), fields: [vgField(fieldDef), ...(isBinning(bin) ? [vgField(fieldDef, { binSuffix: 'end' })] : [])] }, (isSortField(sort)\n ? { sortField: sort }\n : isArray(sort)\n ? { sortIndexField: sortArrayIndexField(fieldDef, channel) }\n : {}));\n }\n }\n this.childModel = model.child;\n }\n hash() {\n let out = `Facet`;\n for (const channel of FACET_CHANNELS) {\n if (this[channel]) {\n out += ` ${channel.charAt(0)}:${hash(this[channel])}`;\n }\n }\n return out;\n }\n get fields() {\n var _a;\n const f = [];\n for (const channel of FACET_CHANNELS) {\n if ((_a = this[channel]) === null || _a === void 0 ? void 0 : _a.fields) {\n f.push(...this[channel].fields);\n }\n }\n return f;\n }\n dependentFields() {\n const depFields = new Set(this.fields);\n for (const channel of FACET_CHANNELS) {\n if (this[channel]) {\n if (this[channel].sortField) {\n depFields.add(this[channel].sortField.field);\n }\n if (this[channel].sortIndexField) {\n depFields.add(this[channel].sortIndexField);\n }\n }\n }\n return depFields;\n }\n producedFields() {\n return new Set(); // facet does not produce any new fields\n }\n /**\n * The name to reference this source is its name.\n */\n getSource() {\n return this.name;\n }\n getChildIndependentFieldsWithStep() {\n const childIndependentFieldsWithStep = {};\n for (const channel of POSITION_SCALE_CHANNELS) {\n const childScaleComponent = this.childModel.component.scales[channel];\n if (childScaleComponent && !childScaleComponent.merged) {\n // independent scale\n const type = childScaleComponent.get('type');\n const range = childScaleComponent.get('range');\n if (hasDiscreteDomain(type) && isVgRangeStep(range)) {\n const domain = assembleDomain(this.childModel, channel);\n const field = getFieldFromDomain(domain);\n if (field) {\n childIndependentFieldsWithStep[channel] = field;\n }\n else {\n log.warn(log.message.unknownField(channel));\n }\n }\n }\n }\n return childIndependentFieldsWithStep;\n }\n assembleRowColumnHeaderData(channel, crossedDataName, childIndependentFieldsWithStep) {\n const childChannel = { row: 'y', column: 'x', facet: undefined }[channel];\n const fields = [];\n const ops = [];\n const as = [];\n if (childChannel && childIndependentFieldsWithStep && childIndependentFieldsWithStep[childChannel]) {\n if (crossedDataName) {\n // If there is a crossed data, calculate max\n fields.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);\n ops.push('max');\n }\n else {\n // If there is no crossed data, just calculate distinct\n fields.push(childIndependentFieldsWithStep[childChannel]);\n ops.push('distinct');\n }\n // Although it is technically a max, just name it distinct so it's easier to refer to it\n as.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);\n }\n const { sortField, sortIndexField } = this[channel];\n if (sortField) {\n const { op = DEFAULT_SORT_OP, field } = sortField;\n fields.push(field);\n ops.push(op);\n as.push(vgField(sortField, { forAs: true }));\n }\n else if (sortIndexField) {\n fields.push(sortIndexField);\n ops.push('max');\n as.push(sortIndexField);\n }\n return {\n name: this[channel].name,\n // Use data from the crossed one if it exist\n source: crossedDataName !== null && crossedDataName !== void 0 ? crossedDataName : this.data,\n transform: [\n Object.assign({ type: 'aggregate', groupby: this[channel].fields }, (fields.length\n ? {\n fields,\n ops,\n as\n }\n : {}))\n ]\n };\n }\n assembleFacetHeaderData(childIndependentFieldsWithStep) {\n var _a, _b;\n const { columns } = this.model.layout;\n const { layoutHeaders } = this.model.component;\n const data = [];\n const hasSharedAxis = {};\n for (const headerChannel of HEADER_CHANNELS) {\n for (const headerType of HEADER_TYPES) {\n const headers = (_a = (layoutHeaders[headerChannel] && layoutHeaders[headerChannel][headerType])) !== null && _a !== void 0 ? _a : [];\n for (const header of headers) {\n if (((_b = header.axes) === null || _b === void 0 ? void 0 : _b.length) > 0) {\n hasSharedAxis[headerChannel] = true;\n break;\n }\n }\n }\n if (hasSharedAxis[headerChannel]) {\n const cardinality = `length(data(\"${this.facet.name}\"))`;\n const stop = headerChannel === 'row'\n ? columns\n ? { signal: `ceil(${cardinality} / ${columns})` }\n : 1\n : columns\n ? { signal: `min(${cardinality}, ${columns})` }\n : { signal: cardinality };\n data.push({\n name: `${this.facet.name}_${headerChannel}`,\n transform: [\n {\n type: 'sequence',\n start: 0,\n stop\n }\n ]\n });\n }\n }\n const { row, column } = hasSharedAxis;\n if (row || column) {\n data.unshift(this.assembleRowColumnHeaderData('facet', null, childIndependentFieldsWithStep));\n }\n return data;\n }\n assemble() {\n var _a, _b;\n const data = [];\n let crossedDataName = null;\n const childIndependentFieldsWithStep = this.getChildIndependentFieldsWithStep();\n const { column, row, facet } = this;\n if (column && row && (childIndependentFieldsWithStep.x || childIndependentFieldsWithStep.y)) {\n // Need to create a cross dataset to correctly calculate cardinality\n crossedDataName = `cross_${this.column.name}_${this.row.name}`;\n const fields = [].concat((_a = childIndependentFieldsWithStep.x) !== null && _a !== void 0 ? _a : [], (_b = childIndependentFieldsWithStep.y) !== null && _b !== void 0 ? _b : []);\n const ops = fields.map(() => 'distinct');\n data.push({\n name: crossedDataName,\n source: this.data,\n transform: [\n {\n type: 'aggregate',\n groupby: this.fields,\n fields,\n ops\n }\n ]\n });\n }\n for (const channel of [COLUMN, ROW]) {\n if (this[channel]) {\n data.push(this.assembleRowColumnHeaderData(channel, crossedDataName, childIndependentFieldsWithStep));\n }\n }\n if (facet) {\n const facetData = this.assembleFacetHeaderData(childIndependentFieldsWithStep);\n if (facetData) {\n data.push(...facetData);\n }\n }\n return data;\n }\n}\n//# sourceMappingURL=facet.js.map","import { isNumber, isString } from 'vega-util';\nimport { isMinMaxOp } from '../../aggregate';\nimport { getMainRangeChannel } from '../../channel';\nimport { isFieldDef, isFieldOrDatumDefForTimeFormat, isScaleFieldDef, isTypedFieldDef } from '../../channeldef';\nimport { isGenerator } from '../../data';\nimport { isDateTime } from '../../datetime';\nimport * as log from '../../log';\nimport { forEachLeaf } from '../../logical';\nimport { isPathMark } from '../../mark';\nimport { isFieldEqualPredicate, isFieldGTEPredicate, isFieldGTPredicate, isFieldLTEPredicate, isFieldLTPredicate, isFieldOneOfPredicate, isFieldPredicate, isFieldRangePredicate } from '../../predicate';\nimport { isSortField } from '../../sort';\nimport { accessPathDepth, accessPathWithDatum, duplicate, hash, keys, removePathFromField } from '../../util';\nimport { signalRefOrValue } from '../common';\nimport { isFacetModel, isUnitModel } from '../model';\nimport { Split } from '../split';\nimport { DataFlowNode } from './dataflow';\n/**\n * Remove quotes from a string.\n */\nfunction unquote(pattern) {\n if ((pattern[0] === \"'\" && pattern[pattern.length - 1] === \"'\") ||\n (pattern[0] === '\"' && pattern[pattern.length - 1] === '\"')) {\n return pattern.slice(1, -1);\n }\n return pattern;\n}\n/**\n * @param field The field.\n * @param parse What to parse the field as.\n */\nfunction parseExpression(field, parse) {\n const f = accessPathWithDatum(field);\n if (parse === 'number') {\n return `toNumber(${f})`;\n }\n else if (parse === 'boolean') {\n return `toBoolean(${f})`;\n }\n else if (parse === 'string') {\n return `toString(${f})`;\n }\n else if (parse === 'date') {\n return `toDate(${f})`;\n }\n else if (parse === 'flatten') {\n return f;\n }\n else if (parse.startsWith('date:')) {\n const specifier = unquote(parse.slice(5, parse.length));\n return `timeParse(${f},'${specifier}')`;\n }\n else if (parse.startsWith('utc:')) {\n const specifier = unquote(parse.slice(4, parse.length));\n return `utcParse(${f},'${specifier}')`;\n }\n else {\n log.warn(log.message.unrecognizedParse(parse));\n return null;\n }\n}\nexport function getImplicitFromFilterTransform(transform) {\n const implicit = {};\n forEachLeaf(transform.filter, filter => {\n var _a;\n if (isFieldPredicate(filter)) {\n // Automatically add a parse node for filters with filter objects\n let val = null;\n // For EqualFilter, just use the equal property.\n // For RangeFilter and OneOfFilter, all array members should have\n // the same type, so we only use the first one.\n if (isFieldEqualPredicate(filter)) {\n val = signalRefOrValue(filter.equal);\n }\n else if (isFieldLTEPredicate(filter)) {\n val = signalRefOrValue(filter.lte);\n }\n else if (isFieldLTPredicate(filter)) {\n val = signalRefOrValue(filter.lt);\n }\n else if (isFieldGTPredicate(filter)) {\n val = signalRefOrValue(filter.gt);\n }\n else if (isFieldGTEPredicate(filter)) {\n val = signalRefOrValue(filter.gte);\n }\n else if (isFieldRangePredicate(filter)) {\n val = filter.range[0];\n }\n else if (isFieldOneOfPredicate(filter)) {\n val = ((_a = filter.oneOf) !== null && _a !== void 0 ? _a : filter['in'])[0];\n } // else -- for filter expression, we can't infer anything\n if (val) {\n if (isDateTime(val)) {\n implicit[filter.field] = 'date';\n }\n else if (isNumber(val)) {\n implicit[filter.field] = 'number';\n }\n else if (isString(val)) {\n implicit[filter.field] = 'string';\n }\n }\n if (filter.timeUnit) {\n implicit[filter.field] = 'date';\n }\n }\n });\n return implicit;\n}\n/**\n * Creates a parse node for implicit parsing from a model and updates ancestorParse.\n */\nexport function getImplicitFromEncoding(model) {\n const implicit = {};\n function add(fieldDef) {\n if (isFieldOrDatumDefForTimeFormat(fieldDef)) {\n implicit[fieldDef.field] = 'date';\n }\n else if (fieldDef.type === 'quantitative' &&\n isMinMaxOp(fieldDef.aggregate) // we need to parse numbers to support correct min and max\n ) {\n implicit[fieldDef.field] = 'number';\n }\n else if (accessPathDepth(fieldDef.field) > 1) {\n // For non-date/non-number (strings and booleans), derive a flattened field for a referenced nested field.\n // (Parsing numbers / dates already flattens numeric and temporal fields.)\n if (!(fieldDef.field in implicit)) {\n implicit[fieldDef.field] = 'flatten';\n }\n }\n else if (isScaleFieldDef(fieldDef) && isSortField(fieldDef.sort) && accessPathDepth(fieldDef.sort.field) > 1) {\n // Flatten fields that we sort by but that are not otherwise flattened.\n if (!(fieldDef.sort.field in implicit)) {\n implicit[fieldDef.sort.field] = 'flatten';\n }\n }\n }\n if (isUnitModel(model) || isFacetModel(model)) {\n // Parse encoded fields\n model.forEachFieldDef((fieldDef, channel) => {\n if (isTypedFieldDef(fieldDef)) {\n add(fieldDef);\n }\n else {\n const mainChannel = getMainRangeChannel(channel);\n const mainFieldDef = model.fieldDef(mainChannel);\n add(Object.assign(Object.assign({}, fieldDef), { type: mainFieldDef.type }));\n }\n });\n }\n // Parse quantitative dimension fields of path marks as numbers so that we sort them correctly.\n if (isUnitModel(model)) {\n const { mark, markDef, encoding } = model;\n if (isPathMark(mark) &&\n // No need to sort by dimension if we have a connected scatterplot (order channel is present)\n !model.encoding.order) {\n const dimensionChannel = markDef.orient === 'horizontal' ? 'y' : 'x';\n const dimensionChannelDef = encoding[dimensionChannel];\n if (isFieldDef(dimensionChannelDef) &&\n dimensionChannelDef.type === 'quantitative' &&\n !(dimensionChannelDef.field in implicit)) {\n implicit[dimensionChannelDef.field] = 'number';\n }\n }\n }\n return implicit;\n}\n/**\n * Creates a parse node for implicit parsing from a model and updates ancestorParse.\n */\nexport function getImplicitFromSelection(model) {\n const implicit = {};\n if (isUnitModel(model) && model.component.selection) {\n for (const name of keys(model.component.selection)) {\n const selCmpt = model.component.selection[name];\n for (const proj of selCmpt.project.items) {\n if (!proj.channel && accessPathDepth(proj.field) > 1) {\n implicit[proj.field] = 'flatten';\n }\n }\n }\n }\n return implicit;\n}\nexport class ParseNode extends DataFlowNode {\n constructor(parent, parse) {\n super(parent);\n this._parse = parse;\n }\n clone() {\n return new ParseNode(null, duplicate(this._parse));\n }\n hash() {\n return `Parse ${hash(this._parse)}`;\n }\n /**\n * Creates a parse node from a data.format.parse and updates ancestorParse.\n */\n static makeExplicit(parent, model, ancestorParse) {\n var _a;\n // Custom parse\n let explicit = {};\n const data = model.data;\n if (!isGenerator(data) && ((_a = data === null || data === void 0 ? void 0 : data.format) === null || _a === void 0 ? void 0 : _a.parse)) {\n explicit = data.format.parse;\n }\n return this.makeWithAncestors(parent, explicit, {}, ancestorParse);\n }\n /**\n * Creates a parse node from \"explicit\" parse and \"implicit\" parse and updates ancestorParse.\n */\n static makeWithAncestors(parent, explicit, implicit, ancestorParse) {\n // We should not parse what has already been parsed in a parent (explicitly or implicitly) or what has been derived (maked as \"derived\"). We also don't need to flatten a field that has already been parsed.\n for (const field of keys(implicit)) {\n const parsedAs = ancestorParse.getWithExplicit(field);\n if (parsedAs.value !== undefined) {\n // We always ignore derived fields even if they are implicitly defined because we expect users to create the right types.\n if (parsedAs.explicit ||\n parsedAs.value === implicit[field] ||\n parsedAs.value === 'derived' ||\n implicit[field] === 'flatten') {\n delete implicit[field];\n }\n else {\n log.warn(log.message.differentParse(field, implicit[field], parsedAs.value));\n }\n }\n }\n for (const field of keys(explicit)) {\n const parsedAs = ancestorParse.get(field);\n if (parsedAs !== undefined) {\n // Don't parse a field again if it has been parsed with the same type already.\n if (parsedAs === explicit[field]) {\n delete explicit[field];\n }\n else {\n log.warn(log.message.differentParse(field, explicit[field], parsedAs));\n }\n }\n }\n const parse = new Split(explicit, implicit);\n // add the format parse from this model so that children don't parse the same field again\n ancestorParse.copyAll(parse);\n // copy only non-null parses\n const p = {};\n for (const key of keys(parse.combine())) {\n const val = parse.get(key);\n if (val !== null) {\n p[key] = val;\n }\n }\n if (keys(p).length === 0 || ancestorParse.parseNothing) {\n return null;\n }\n return new ParseNode(parent, p);\n }\n get parse() {\n return this._parse;\n }\n merge(other) {\n this._parse = Object.assign(Object.assign({}, this._parse), other.parse);\n other.remove();\n }\n /**\n * Assemble an object for Vega's format.parse property.\n */\n assembleFormatParse() {\n const formatParse = {};\n for (const field of keys(this._parse)) {\n const p = this._parse[field];\n if (accessPathDepth(field) === 1) {\n formatParse[field] = p;\n }\n }\n return formatParse;\n }\n // format parse depends and produces all fields in its parse\n producedFields() {\n return new Set(keys(this._parse));\n }\n dependentFields() {\n return new Set(keys(this._parse));\n }\n assembleTransforms(onlyNested = false) {\n return keys(this._parse)\n .filter(field => (onlyNested ? accessPathDepth(field) > 1 : true))\n .map(field => {\n const expr = parseExpression(field, this._parse[field]);\n if (!expr) {\n return null;\n }\n const formula = {\n type: 'formula',\n expr,\n as: removePathFromField(field) // Vega output is always flattened\n };\n return formula;\n })\n .filter(t => t !== null);\n }\n}\n//# sourceMappingURL=formatparse.js.map","import { SELECTION_ID } from '../../selection';\nimport { DataFlowNode } from './dataflow';\nexport class IdentifierNode extends DataFlowNode {\n clone() {\n return new IdentifierNode(null);\n }\n constructor(parent) {\n super(parent);\n }\n dependentFields() {\n return new Set();\n }\n producedFields() {\n return new Set([SELECTION_ID]);\n }\n hash() {\n return 'Identifier';\n }\n assemble() {\n return { type: 'identifier', as: SELECTION_ID };\n }\n}\n//# sourceMappingURL=identifier.js.map","import { hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\nexport class GraticuleNode extends DataFlowNode {\n constructor(parent, params) {\n super(parent);\n this.params = params;\n }\n clone() {\n return new GraticuleNode(null, this.params);\n }\n dependentFields() {\n return new Set();\n }\n producedFields() {\n return undefined; // there should never be a node before graticule\n }\n hash() {\n return `Graticule ${hash(this.params)}`;\n }\n assemble() {\n return Object.assign({ type: 'graticule' }, (this.params === true ? {} : this.params));\n }\n}\n//# sourceMappingURL=graticule.js.map","import { hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\nexport class SequenceNode extends DataFlowNode {\n constructor(parent, params) {\n super(parent);\n this.params = params;\n }\n clone() {\n return new SequenceNode(null, this.params);\n }\n dependentFields() {\n return new Set();\n }\n producedFields() {\n var _a;\n return new Set([(_a = this.params.as) !== null && _a !== void 0 ? _a : 'data']);\n }\n hash() {\n return `Hash ${hash(this.params)}`;\n }\n assemble() {\n return Object.assign({ type: 'sequence' }, this.params);\n }\n}\n//# sourceMappingURL=sequence.js.map","import { isGenerator, isInlineData, isNamedData, isSphereGenerator, isUrlData } from '../../data';\nimport { contains, isEmpty, omit } from '../../util';\nimport { DataFlowNode } from './dataflow';\nexport class SourceNode extends DataFlowNode {\n constructor(data) {\n super(null); // source cannot have parent\n data !== null && data !== void 0 ? data : (data = { name: 'source' });\n let format;\n if (!isGenerator(data)) {\n format = data.format ? Object.assign({}, omit(data.format, ['parse'])) : {};\n }\n if (isInlineData(data)) {\n this._data = { values: data.values };\n }\n else if (isUrlData(data)) {\n this._data = { url: data.url };\n if (!format.type) {\n // Extract extension from URL using snippet from\n // http://stackoverflow.com/questions/680929/how-to-extract-extension-from-filename-string-in-javascript\n let defaultExtension = /(?:\\.([^.]+))?$/.exec(data.url)[1];\n if (!contains(['json', 'csv', 'tsv', 'dsv', 'topojson'], defaultExtension)) {\n defaultExtension = 'json';\n }\n // defaultExtension has type string but we ensure that it is DataFormatType above\n format.type = defaultExtension;\n }\n }\n else if (isSphereGenerator(data)) {\n // hardwire GeoJSON sphere data into output specification\n this._data = { values: [{ type: 'Sphere' }] };\n }\n else if (isNamedData(data) || isGenerator(data)) {\n this._data = {};\n }\n // set flag to check if generator\n this._generator = isGenerator(data);\n // any dataset can be named\n if (data.name) {\n this._name = data.name;\n }\n if (format && !isEmpty(format)) {\n this._data.format = format;\n }\n }\n dependentFields() {\n return new Set();\n }\n producedFields() {\n return undefined; // we don't know what this source produces\n }\n get data() {\n return this._data;\n }\n hasName() {\n return !!this._name;\n }\n get isGenerator() {\n return this._generator;\n }\n get dataName() {\n return this._name;\n }\n set dataName(name) {\n this._name = name;\n }\n set parent(parent) {\n throw new Error('Source nodes have to be roots.');\n }\n remove() {\n throw new Error('Source nodes are roots and cannot be removed.');\n }\n hash() {\n throw new Error('Cannot hash sources');\n }\n assemble() {\n return Object.assign(Object.assign({ name: this._name }, this._data), { transform: [] });\n }\n}\n//# sourceMappingURL=source.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _Optimizer_modified;\nimport { GraticuleNode } from './graticule';\nimport { SequenceNode } from './sequence';\nimport { SourceNode } from './source';\n/**\n * Whether this dataflow node is the source of the dataflow that produces data i.e. a source or a generator.\n */\nexport function isDataSourceNode(node) {\n return node instanceof SourceNode || node instanceof GraticuleNode || node instanceof SequenceNode;\n}\n/**\n * Abstract base class for Dataflow optimizers.\n * Contains only mutation handling logic. Subclasses need to implement iteration logic.\n */\nexport class Optimizer {\n constructor() {\n _Optimizer_modified.set(this, void 0);\n __classPrivateFieldSet(this, _Optimizer_modified, false, \"f\");\n }\n // Once true, #modified is never set to false\n setModified() {\n __classPrivateFieldSet(this, _Optimizer_modified, true, \"f\");\n }\n get modifiedFlag() {\n return __classPrivateFieldGet(this, _Optimizer_modified, \"f\");\n }\n}\n_Optimizer_modified = new WeakMap();\n/**\n * Starts from a node and runs the optimization function (the \"run\" method) upwards to the root,\n * depending on the continue and modified flag values returned by the optimization function.\n */\nexport class BottomUpOptimizer extends Optimizer {\n /**\n * Compute a map of node depths that we can use to determine a topological sort order.\n */\n getNodeDepths(node, depth, depths) {\n depths.set(node, depth);\n for (const child of node.children) {\n this.getNodeDepths(child, depth + 1, depths);\n }\n return depths;\n }\n /**\n * Run the optimizer on all nodes starting from the leaves.\n */\n optimize(node) {\n const depths = this.getNodeDepths(node, 0, new Map());\n const topologicalSort = [...depths.entries()].sort((a, b) => b[1] - a[1]);\n for (const tuple of topologicalSort) {\n this.run(tuple[0]);\n }\n return this.modifiedFlag;\n }\n}\n/**\n * The optimizer function (the \"run\" method), is invoked on the given node and then continues recursively.\n */\nexport class TopDownOptimizer extends Optimizer {\n /**\n * Run the optimizer depth first on all nodes starting from the roots.\n */\n optimize(node) {\n this.run(node);\n for (const child of node.children) {\n this.optimize(child);\n }\n return this.modifiedFlag;\n }\n}\n//# sourceMappingURL=optimizer.js.map","import { fieldIntersection, hash, hasIntersection, isEmpty, keys, some } from '../../util';\nimport { requiresSelectionId } from '../selection';\nimport { AggregateNode } from './aggregate';\nimport { BinNode } from './bin';\nimport { OutputNode } from './dataflow';\nimport { FacetNode } from './facet';\nimport { FilterNode } from './filter';\nimport { ParseNode } from './formatparse';\nimport { IdentifierNode } from './identifier';\nimport { BottomUpOptimizer, isDataSourceNode, Optimizer, TopDownOptimizer } from './optimizer';\nimport { SourceNode } from './source';\nimport { TimeUnitNode } from './timeunit';\n/**\n * Merge identical nodes at forks by comparing hashes.\n *\n * Does not need to iterate from leaves so we implement this with recursion as it's a bit simpler.\n */\nexport class MergeIdenticalNodes extends TopDownOptimizer {\n mergeNodes(parent, nodes) {\n const mergedNode = nodes.shift();\n for (const node of nodes) {\n parent.removeChild(node);\n node.parent = mergedNode;\n node.remove();\n }\n }\n run(node) {\n const hashes = node.children.map(x => x.hash());\n const buckets = {};\n for (let i = 0; i < hashes.length; i++) {\n if (buckets[hashes[i]] === undefined) {\n buckets[hashes[i]] = [node.children[i]];\n }\n else {\n buckets[hashes[i]].push(node.children[i]);\n }\n }\n for (const k of keys(buckets)) {\n if (buckets[k].length > 1) {\n this.setModified();\n this.mergeNodes(node, buckets[k]);\n }\n }\n }\n}\n/**\n * Optimizer that removes identifier nodes that are not needed for selections.\n */\nexport class RemoveUnnecessaryIdentifierNodes extends TopDownOptimizer {\n constructor(model) {\n super();\n this.requiresSelectionId = model && requiresSelectionId(model);\n }\n run(node) {\n if (node instanceof IdentifierNode) {\n // Only preserve IdentifierNodes if we have default discrete selections\n // in our model tree, and if the nodes come after tuple producing nodes.\n if (!(this.requiresSelectionId &&\n (isDataSourceNode(node.parent) || node.parent instanceof AggregateNode || node.parent instanceof ParseNode))) {\n this.setModified();\n node.remove();\n }\n }\n }\n}\n/**\n * Removes duplicate time unit nodes (as determined by the name of the output field) that may be generated due to\n * selections projected over time units. Only keeps the first time unit in any branch.\n *\n * This optimizer is a custom top down optimizer that keep track of produced fields in a branch.\n */\nexport class RemoveDuplicateTimeUnits extends Optimizer {\n optimize(node) {\n this.run(node, new Set());\n return this.modifiedFlag;\n }\n run(node, timeUnitFields) {\n let producedFields = new Set();\n if (node instanceof TimeUnitNode) {\n producedFields = node.producedFields();\n if (hasIntersection(producedFields, timeUnitFields)) {\n this.setModified();\n node.removeFormulas(timeUnitFields);\n if (node.producedFields.length === 0) {\n node.remove();\n }\n }\n }\n for (const child of node.children) {\n this.run(child, new Set([...timeUnitFields, ...producedFields]));\n }\n }\n}\n/**\n * Remove output nodes that are not required.\n */\nexport class RemoveUnnecessaryOutputNodes extends TopDownOptimizer {\n constructor() {\n super();\n }\n run(node) {\n if (node instanceof OutputNode && !node.isRequired()) {\n this.setModified();\n node.remove();\n }\n }\n}\n/**\n * Move parse nodes up to forks and merges them if possible.\n */\nexport class MoveParseUp extends BottomUpOptimizer {\n run(node) {\n if (isDataSourceNode(node)) {\n return;\n }\n if (node.numChildren() > 1) {\n // Don't move parse further up but continue with parent.\n return;\n }\n for (const child of node.children) {\n if (child instanceof ParseNode) {\n if (node instanceof ParseNode) {\n this.setModified();\n node.merge(child);\n }\n else {\n // Don't swap with nodes that produce something that the parse node depends on (e.g. lookup).\n if (fieldIntersection(node.producedFields(), child.dependentFields())) {\n continue;\n }\n this.setModified();\n child.swapWithParent();\n }\n }\n }\n return;\n }\n}\n/**\n * Inserts an intermediate ParseNode containing all non-conflicting parse fields and removes the empty ParseNodes.\n *\n * We assume that dependent paths that do not have a parse node can be just merged.\n */\nexport class MergeParse extends BottomUpOptimizer {\n run(node) {\n const originalChildren = [...node.children];\n const parseChildren = node.children.filter((child) => child instanceof ParseNode);\n if (node.numChildren() > 1 && parseChildren.length >= 1) {\n const commonParse = {};\n const conflictingParse = new Set();\n for (const parseNode of parseChildren) {\n const parse = parseNode.parse;\n for (const k of keys(parse)) {\n if (!(k in commonParse)) {\n commonParse[k] = parse[k];\n }\n else if (commonParse[k] !== parse[k]) {\n conflictingParse.add(k);\n }\n }\n }\n for (const field of conflictingParse) {\n delete commonParse[field];\n }\n if (!isEmpty(commonParse)) {\n this.setModified();\n const mergedParseNode = new ParseNode(node, commonParse);\n for (const childNode of originalChildren) {\n if (childNode instanceof ParseNode) {\n for (const key of keys(commonParse)) {\n delete childNode.parse[key];\n }\n }\n node.removeChild(childNode);\n childNode.parent = mergedParseNode;\n // remove empty parse nodes\n if (childNode instanceof ParseNode && keys(childNode.parse).length === 0) {\n childNode.remove();\n }\n }\n }\n }\n }\n}\n/**\n * Repeatedly remove leaf nodes that are not output or facet nodes.\n * The reason is that we don't need subtrees that don't have any output nodes.\n * Facet nodes are needed for the row or column domains.\n */\nexport class RemoveUnusedSubtrees extends BottomUpOptimizer {\n run(node) {\n if (node instanceof OutputNode || node.numChildren() > 0 || node instanceof FacetNode) {\n // no need to continue with parent because it is output node or will have children (there was a fork)\n }\n else if (node instanceof SourceNode) {\n // ignore empty unused sources as they will be removed in optimizationDataflowHelper\n }\n else {\n this.setModified();\n node.remove();\n }\n }\n}\n/**\n * Merge adjacent time unit nodes.\n */\nexport class MergeTimeUnits extends BottomUpOptimizer {\n run(node) {\n const timeUnitChildren = node.children.filter((x) => x instanceof TimeUnitNode);\n const combination = timeUnitChildren.pop();\n for (const timeUnit of timeUnitChildren) {\n this.setModified();\n combination.merge(timeUnit);\n }\n }\n}\nexport class MergeAggregates extends BottomUpOptimizer {\n run(node) {\n const aggChildren = node.children.filter((child) => child instanceof AggregateNode);\n // Object which we'll use to map the fields which an aggregate is grouped by to\n // the set of aggregates with that grouping. This is useful as only aggregates\n // with the same group by can be merged\n const groupedAggregates = {};\n // Build groupedAggregates\n for (const agg of aggChildren) {\n const groupBys = hash(agg.groupBy);\n if (!(groupBys in groupedAggregates)) {\n groupedAggregates[groupBys] = [];\n }\n groupedAggregates[groupBys].push(agg);\n }\n // Merge aggregateNodes with same key in groupedAggregates\n for (const group of keys(groupedAggregates)) {\n const mergeableAggs = groupedAggregates[group];\n if (mergeableAggs.length > 1) {\n const mergedAggs = mergeableAggs.pop();\n for (const agg of mergeableAggs) {\n if (mergedAggs.merge(agg)) {\n node.removeChild(agg);\n agg.parent = mergedAggs;\n agg.remove();\n this.setModified();\n }\n }\n }\n }\n }\n}\n/**\n * Merge bin nodes and move them up through forks. Stop at filters, parse, identifier as we want them to stay before the bin node.\n */\nexport class MergeBins extends BottomUpOptimizer {\n constructor(model) {\n super();\n this.model = model;\n }\n run(node) {\n const moveBinsUp = !(isDataSourceNode(node) ||\n node instanceof FilterNode ||\n node instanceof ParseNode ||\n node instanceof IdentifierNode);\n const promotableBins = [];\n const remainingBins = [];\n for (const child of node.children) {\n if (child instanceof BinNode) {\n if (moveBinsUp && !fieldIntersection(node.producedFields(), child.dependentFields())) {\n promotableBins.push(child);\n }\n else {\n remainingBins.push(child);\n }\n }\n }\n if (promotableBins.length > 0) {\n const promotedBin = promotableBins.pop();\n for (const bin of promotableBins) {\n promotedBin.merge(bin, this.model.renameSignal.bind(this.model));\n }\n this.setModified();\n if (node instanceof BinNode) {\n node.merge(promotedBin, this.model.renameSignal.bind(this.model));\n }\n else {\n promotedBin.swapWithParent();\n }\n }\n if (remainingBins.length > 1) {\n const remainingBin = remainingBins.pop();\n for (const bin of remainingBins) {\n remainingBin.merge(bin, this.model.renameSignal.bind(this.model));\n }\n this.setModified();\n }\n }\n}\n/**\n * This optimizer takes output nodes that are at a fork and moves them before the fork.\n *\n * The algorithm iterates over the children and tries to find the last output node in a chain of output nodes.\n * It then moves all output nodes before that main output node. All other children (and the children of the output nodes)\n * are inserted after the main output node.\n */\nexport class MergeOutputs extends BottomUpOptimizer {\n run(node) {\n const children = [...node.children];\n const hasOutputChild = some(children, child => child instanceof OutputNode);\n if (!hasOutputChild || node.numChildren() <= 1) {\n return;\n }\n const otherChildren = [];\n // The output node we will connect all other nodes to.\n // Output nodes will be added before the new node, other nodes after.\n let mainOutput;\n for (const child of children) {\n if (child instanceof OutputNode) {\n let lastOutput = child;\n while (lastOutput.numChildren() === 1) {\n const [theChild] = lastOutput.children;\n if (theChild instanceof OutputNode) {\n lastOutput = theChild;\n }\n else {\n break;\n }\n }\n otherChildren.push(...lastOutput.children);\n if (mainOutput) {\n // Move the output nodes before the mainOutput. We do this by setting\n // the parent of the first not to the parent of the main output and\n // the main output's parent to the last output.\n // note: the child is the first output\n node.removeChild(child);\n child.parent = mainOutput.parent;\n mainOutput.parent.removeChild(mainOutput);\n mainOutput.parent = lastOutput;\n this.setModified();\n }\n else {\n mainOutput = lastOutput;\n }\n }\n else {\n otherChildren.push(child);\n }\n }\n if (otherChildren.length) {\n this.setModified();\n for (const child of otherChildren) {\n child.parent.removeChild(child);\n child.parent = mainOutput;\n }\n }\n }\n}\n//# sourceMappingURL=optimizers.js.map","import { vgField } from '../../channeldef';\nimport { duplicate, hash } from '../../util';\nimport { unique } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for the join aggregate transform nodes.\n */\nexport class JoinAggregateTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n super(parent);\n this.transform = transform;\n }\n clone() {\n return new JoinAggregateTransformNode(null, duplicate(this.transform));\n }\n addDimensions(fields) {\n this.transform.groupby = unique(this.transform.groupby.concat(fields), d => d);\n }\n dependentFields() {\n const out = new Set();\n if (this.transform.groupby) {\n this.transform.groupby.forEach(out.add, out);\n }\n this.transform.joinaggregate\n .map(w => w.field)\n .filter(f => f !== undefined)\n .forEach(out.add, out);\n return out;\n }\n producedFields() {\n return new Set(this.transform.joinaggregate.map(this.getDefaultName));\n }\n getDefaultName(joinAggregateFieldDef) {\n var _a;\n return (_a = joinAggregateFieldDef.as) !== null && _a !== void 0 ? _a : vgField(joinAggregateFieldDef);\n }\n hash() {\n return `JoinAggregateTransform ${hash(this.transform)}`;\n }\n assemble() {\n const fields = [];\n const ops = [];\n const as = [];\n for (const joinaggregate of this.transform.joinaggregate) {\n ops.push(joinaggregate.op);\n as.push(this.getDefaultName(joinaggregate));\n fields.push(joinaggregate.field === undefined ? null : joinaggregate.field);\n }\n const groupby = this.transform.groupby;\n return Object.assign({ type: 'joinaggregate', as,\n ops,\n fields }, (groupby !== undefined ? { groupby } : {}));\n }\n}\n//# sourceMappingURL=joinaggregate.js.map","import { isArray, isString } from 'vega-util';\nimport { getFieldDef, isFieldDef, vgField } from '../../channeldef';\nimport { duplicate, getFirstDefined, hash } from '../../util';\nimport { sortParams } from '../common';\nimport { DataFlowNode } from './dataflow';\nfunction getStackByFields(model) {\n return model.stack.stackBy.reduce((fields, by) => {\n const fieldDef = by.fieldDef;\n const _field = vgField(fieldDef);\n if (_field) {\n fields.push(_field);\n }\n return fields;\n }, []);\n}\nfunction isValidAsArray(as) {\n return isArray(as) && as.every(s => isString(s)) && as.length > 1;\n}\nexport class StackNode extends DataFlowNode {\n constructor(parent, stack) {\n super(parent);\n this._stack = stack;\n }\n clone() {\n return new StackNode(null, duplicate(this._stack));\n }\n static makeFromTransform(parent, stackTransform) {\n const { stack, groupby, as, offset = 'zero' } = stackTransform;\n const sortFields = [];\n const sortOrder = [];\n if (stackTransform.sort !== undefined) {\n for (const sortField of stackTransform.sort) {\n sortFields.push(sortField.field);\n sortOrder.push(getFirstDefined(sortField.order, 'ascending'));\n }\n }\n const sort = {\n field: sortFields,\n order: sortOrder\n };\n let normalizedAs;\n if (isValidAsArray(as)) {\n normalizedAs = as;\n }\n else if (isString(as)) {\n normalizedAs = [as, `${as}_end`];\n }\n else {\n normalizedAs = [`${stackTransform.stack}_start`, `${stackTransform.stack}_end`];\n }\n return new StackNode(parent, {\n stackField: stack,\n groupby,\n offset,\n sort,\n facetby: [],\n as: normalizedAs\n });\n }\n static makeFromEncoding(parent, model) {\n const stackProperties = model.stack;\n const { encoding } = model;\n if (!stackProperties) {\n return null;\n }\n const { groupbyChannel, fieldChannel, offset, impute } = stackProperties;\n let dimensionFieldDef;\n if (groupbyChannel) {\n const cDef = encoding[groupbyChannel];\n dimensionFieldDef = getFieldDef(cDef); // Fair to cast as groupByChannel is always either x or y\n }\n const stackby = getStackByFields(model);\n const orderDef = model.encoding.order;\n let sort;\n if (isArray(orderDef) || isFieldDef(orderDef)) {\n sort = sortParams(orderDef);\n }\n else {\n // default = descending by stackFields\n // FIXME is the default here correct for binned fields?\n sort = stackby.reduce((s, field) => {\n s.field.push(field);\n s.order.push(fieldChannel === 'y' ? 'descending' : 'ascending');\n return s;\n }, { field: [], order: [] });\n }\n return new StackNode(parent, {\n dimensionFieldDef,\n stackField: model.vgField(fieldChannel),\n facetby: [],\n stackby,\n sort,\n offset,\n impute,\n as: [\n model.vgField(fieldChannel, { suffix: 'start', forAs: true }),\n model.vgField(fieldChannel, { suffix: 'end', forAs: true })\n ]\n });\n }\n get stack() {\n return this._stack;\n }\n addDimensions(fields) {\n this._stack.facetby.push(...fields);\n }\n dependentFields() {\n const out = new Set();\n out.add(this._stack.stackField);\n this.getGroupbyFields().forEach(out.add, out);\n this._stack.facetby.forEach(out.add, out);\n this._stack.sort.field.forEach(out.add, out);\n return out;\n }\n producedFields() {\n return new Set(this._stack.as);\n }\n hash() {\n return `Stack ${hash(this._stack)}`;\n }\n getGroupbyFields() {\n const { dimensionFieldDef, impute, groupby } = this._stack;\n if (dimensionFieldDef) {\n if (dimensionFieldDef.bin) {\n if (impute) {\n // For binned group by field with impute, we calculate bin_mid\n // as we cannot impute two fields simultaneously\n return [vgField(dimensionFieldDef, { binSuffix: 'mid' })];\n }\n return [\n // For binned group by field without impute, we need both bin (start) and bin_end\n vgField(dimensionFieldDef, {}),\n vgField(dimensionFieldDef, { binSuffix: 'end' })\n ];\n }\n return [vgField(dimensionFieldDef)];\n }\n return groupby !== null && groupby !== void 0 ? groupby : [];\n }\n assemble() {\n const transform = [];\n const { facetby, dimensionFieldDef, stackField: field, stackby, sort, offset, impute, as } = this._stack;\n // Impute\n if (impute && dimensionFieldDef) {\n const { bandPosition = 0.5, bin } = dimensionFieldDef;\n if (bin) {\n // As we can only impute one field at a time, we need to calculate\n // mid point for a binned field\n transform.push({\n type: 'formula',\n expr: `${bandPosition}*` +\n vgField(dimensionFieldDef, { expr: 'datum' }) +\n `+${1 - bandPosition}*` +\n vgField(dimensionFieldDef, { expr: 'datum', binSuffix: 'end' }),\n as: vgField(dimensionFieldDef, { binSuffix: 'mid', forAs: true })\n });\n }\n transform.push({\n type: 'impute',\n field,\n groupby: [...stackby, ...facetby],\n key: vgField(dimensionFieldDef, { binSuffix: 'mid' }),\n method: 'value',\n value: 0\n });\n }\n // Stack\n transform.push({\n type: 'stack',\n groupby: [...this.getGroupbyFields(), ...facetby],\n field,\n sort,\n as,\n offset\n });\n return transform;\n }\n}\n//# sourceMappingURL=stack.js.map","import { isAggregateOp } from '../../aggregate';\nimport { vgField } from '../../channeldef';\nimport { duplicate, hash } from '../../util';\nimport { unique } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for the window transform nodes\n */\nexport class WindowTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n super(parent);\n this.transform = transform;\n }\n clone() {\n return new WindowTransformNode(null, duplicate(this.transform));\n }\n addDimensions(fields) {\n this.transform.groupby = unique(this.transform.groupby.concat(fields), d => d);\n }\n dependentFields() {\n var _a, _b;\n const out = new Set();\n ((_a = this.transform.groupby) !== null && _a !== void 0 ? _a : []).forEach(out.add, out);\n ((_b = this.transform.sort) !== null && _b !== void 0 ? _b : []).forEach(m => out.add(m.field));\n this.transform.window\n .map(w => w.field)\n .filter(f => f !== undefined)\n .forEach(out.add, out);\n return out;\n }\n producedFields() {\n return new Set(this.transform.window.map(this.getDefaultName));\n }\n getDefaultName(windowFieldDef) {\n var _a;\n return (_a = windowFieldDef.as) !== null && _a !== void 0 ? _a : vgField(windowFieldDef);\n }\n hash() {\n return `WindowTransform ${hash(this.transform)}`;\n }\n assemble() {\n var _a;\n const fields = [];\n const ops = [];\n const as = [];\n const params = [];\n for (const window of this.transform.window) {\n ops.push(window.op);\n as.push(this.getDefaultName(window));\n params.push(window.param === undefined ? null : window.param);\n fields.push(window.field === undefined ? null : window.field);\n }\n const frame = this.transform.frame;\n const groupby = this.transform.groupby;\n if (frame && frame[0] === null && frame[1] === null && ops.every(o => isAggregateOp(o))) {\n // when the window does not rely on any particular window ops or frame, switch to a simpler and more efficient joinaggregate\n return Object.assign({ type: 'joinaggregate', as, ops: ops, fields }, (groupby !== undefined ? { groupby } : {}));\n }\n const sortFields = [];\n const sortOrder = [];\n if (this.transform.sort !== undefined) {\n for (const sortField of this.transform.sort) {\n sortFields.push(sortField.field);\n sortOrder.push((_a = sortField.order) !== null && _a !== void 0 ? _a : 'ascending');\n }\n }\n const sort = {\n field: sortFields,\n order: sortOrder\n };\n const ignorePeers = this.transform.ignorePeers;\n return Object.assign(Object.assign(Object.assign({ type: 'window', params,\n as,\n ops,\n fields,\n sort }, (ignorePeers !== undefined ? { ignorePeers } : {})), (groupby !== undefined ? { groupby } : {})), (frame !== undefined ? { frame } : {}));\n }\n}\n//# sourceMappingURL=window.js.map","import { DataSourceType } from '../../data';\nimport { AggregateNode } from './aggregate';\nimport { OutputNode } from './dataflow';\nimport { FacetNode } from './facet';\nimport { JoinAggregateTransformNode } from './joinaggregate';\nimport { FACET_SCALE_PREFIX } from './optimize';\nimport { StackNode } from './stack';\nimport { WindowTransformNode } from './window';\n/**\n * Clones the subtree and ignores output nodes except for the leaves, which are renamed.\n */\nfunction cloneSubtree(facet) {\n function clone(node) {\n if (!(node instanceof FacetNode)) {\n const copy = node.clone();\n if (copy instanceof OutputNode) {\n const newName = FACET_SCALE_PREFIX + copy.getSource();\n copy.setSource(newName);\n facet.model.component.data.outputNodes[newName] = copy;\n }\n else if (copy instanceof AggregateNode ||\n copy instanceof StackNode ||\n copy instanceof WindowTransformNode ||\n copy instanceof JoinAggregateTransformNode) {\n copy.addDimensions(facet.fields);\n }\n for (const n of node.children.flatMap(clone)) {\n n.parent = copy;\n }\n return [copy];\n }\n return node.children.flatMap(clone);\n }\n return clone;\n}\n/**\n * Move facet nodes down to the next fork or output node. Also pull the main output with the facet node.\n * After moving down the facet node, make a copy of the subtree and make it a child of the main output.\n */\nexport function moveFacetDown(node) {\n if (node instanceof FacetNode) {\n if (node.numChildren() === 1 && !(node.children[0] instanceof OutputNode)) {\n // move down until we hit a fork or output node\n const child = node.children[0];\n if (child instanceof AggregateNode ||\n child instanceof StackNode ||\n child instanceof WindowTransformNode ||\n child instanceof JoinAggregateTransformNode) {\n child.addDimensions(node.fields);\n }\n child.swapWithParent();\n moveFacetDown(node);\n }\n else {\n // move main to facet\n const facetMain = node.model.component.data.main;\n moveMainDownToFacet(facetMain);\n // replicate the subtree and place it before the facet's main node\n const cloner = cloneSubtree(node);\n const copy = node.children.map(cloner).flat();\n for (const c of copy) {\n c.parent = facetMain;\n }\n }\n }\n else {\n node.children.map(moveFacetDown);\n }\n}\nfunction moveMainDownToFacet(node) {\n if (node instanceof OutputNode && node.type === DataSourceType.Main) {\n if (node.numChildren() === 1) {\n const child = node.children[0];\n if (!(child instanceof FacetNode)) {\n child.swapWithParent();\n moveMainDownToFacet(node);\n }\n }\n }\n}\n//# sourceMappingURL=subtree.js.map","import * as log from '../../log';\nimport * as optimizers from './optimizers';\nimport { moveFacetDown } from './subtree';\nexport const FACET_SCALE_PREFIX = 'scale_';\nexport const MAX_OPTIMIZATION_RUNS = 5;\n/**\n * Iterates over a dataflow graph and checks whether all links are consistent.\n */\nexport function checkLinks(nodes) {\n for (const node of nodes) {\n for (const child of node.children) {\n if (child.parent !== node) {\n // log.error('Dataflow graph is inconsistent.', node, child);\n return false;\n }\n }\n if (!checkLinks(node.children)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Run the specified optimizer on the provided nodes.\n *\n * @param optimizer The optimizer instance to run.\n * @param nodes A set of nodes to optimize.\n */\nfunction runOptimizer(optimizer, nodes) {\n let modified = false;\n for (const node of nodes) {\n modified = optimizer.optimize(node) || modified;\n }\n return modified;\n}\nfunction optimizationDataflowHelper(dataComponent, model, firstPass) {\n let roots = dataComponent.sources;\n let modified = false;\n modified = runOptimizer(new optimizers.RemoveUnnecessaryOutputNodes(), roots) || modified;\n modified = runOptimizer(new optimizers.RemoveUnnecessaryIdentifierNodes(model), roots) || modified;\n // remove source nodes that don't have any children because they also don't have output nodes\n roots = roots.filter(r => r.numChildren() > 0);\n modified = runOptimizer(new optimizers.RemoveUnusedSubtrees(), roots) || modified;\n roots = roots.filter(r => r.numChildren() > 0);\n if (!firstPass) {\n // Only run these optimizations after the optimizer has moved down the facet node.\n // With this change, we can be more aggressive in the optimizations.\n modified = runOptimizer(new optimizers.MoveParseUp(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeBins(model), roots) || modified;\n modified = runOptimizer(new optimizers.RemoveDuplicateTimeUnits(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeParse(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeAggregates(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeTimeUnits(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeIdenticalNodes(), roots) || modified;\n modified = runOptimizer(new optimizers.MergeOutputs(), roots) || modified;\n }\n dataComponent.sources = roots;\n return modified;\n}\n/**\n * Optimizes the dataflow of the passed in data component.\n */\nexport function optimizeDataflow(data, model) {\n // check before optimizations\n checkLinks(data.sources);\n let firstPassCounter = 0;\n let secondPassCounter = 0;\n for (let i = 0; i < MAX_OPTIMIZATION_RUNS; i++) {\n if (!optimizationDataflowHelper(data, model, true)) {\n break;\n }\n firstPassCounter++;\n }\n // move facets down and make a copy of the subtree so that we can have scales at the top level\n data.sources.map(moveFacetDown);\n for (let i = 0; i < MAX_OPTIMIZATION_RUNS; i++) {\n if (!optimizationDataflowHelper(data, model, false)) {\n break;\n }\n secondPassCounter++;\n }\n // check after optimizations\n checkLinks(data.sources);\n if (Math.max(firstPassCounter, secondPassCounter) === MAX_OPTIMIZATION_RUNS) {\n log.warn(`Maximum optimization runs(${MAX_OPTIMIZATION_RUNS}) reached.`);\n }\n}\n//# sourceMappingURL=optimize.js.map","/**\n * A class that behaves like a SignalRef but lazily generates the signal.\n * The provided generator function should use `Model.getSignalName` to use the correct signal name.\n */\nexport class SignalRefWrapper {\n constructor(exprGenerator) {\n Object.defineProperty(this, 'signal', {\n enumerable: true,\n get: exprGenerator\n });\n }\n static fromName(rename, signalName) {\n return new SignalRefWrapper(() => rename(signalName));\n }\n}\n//# sourceMappingURL=signal.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isObject, isString } from 'vega-util';\nimport { isAggregateOp, isArgmaxDef, isArgminDef, MULTIDOMAIN_SORT_OP_INDEX as UNIONDOMAIN_SORT_OP_INDEX, SHARED_DOMAIN_OP_INDEX } from '../../aggregate';\nimport { isBinning, isBinParams, isParameterExtent } from '../../bin';\nimport { getSecondaryRangeChannel, isScaleChannel } from '../../channel';\nimport { binRequiresRange, getFieldOrDatumDef, hasBandEnd, isDatumDef, isFieldDef, valueExpr, vgField } from '../../channeldef';\nimport { DataSourceType } from '../../data';\nimport * as log from '../../log';\nimport { hasDiscreteDomain, isDomainUnionWith, isParameterDomain } from '../../scale';\nimport { DEFAULT_SORT_OP, isSortArray, isSortByEncoding, isSortField } from '../../sort';\nimport { normalizeTimeUnit } from '../../timeunit';\nimport * as util from '../../util';\nimport { isDataRefDomain, isDataRefUnionedDomain, isFieldRefUnionDomain, isSignalRef } from '../../vega.schema';\nimport { getBinSignalName } from '../data/bin';\nimport { sortArrayIndexField } from '../data/calculate';\nimport { FACET_SCALE_PREFIX } from '../data/optimize';\nimport { isFacetModel, isUnitModel } from '../model';\nimport { SignalRefWrapper } from '../signal';\nimport { makeExplicit, makeImplicit, mergeValuesWithExplicit } from '../split';\nexport function parseScaleDomain(model) {\n if (isUnitModel(model)) {\n parseUnitScaleDomain(model);\n }\n else {\n parseNonUnitScaleDomain(model);\n }\n}\nfunction parseUnitScaleDomain(model) {\n const localScaleComponents = model.component.scales;\n for (const channel of util.keys(localScaleComponents)) {\n const domains = parseDomainForChannel(model, channel);\n const localScaleCmpt = localScaleComponents[channel];\n localScaleCmpt.setWithExplicit('domains', domains);\n parseSelectionDomain(model, channel);\n if (model.component.data.isFaceted) {\n // get resolve from closest facet parent as this decides whether we need to refer to cloned subtree or not\n let facetParent = model;\n while (!isFacetModel(facetParent) && facetParent.parent) {\n facetParent = facetParent.parent;\n }\n const resolve = facetParent.component.resolve.scale[channel];\n if (resolve === 'shared') {\n for (const domain of domains.value) {\n // Replace the scale domain with data output from a cloned subtree after the facet.\n if (isDataRefDomain(domain)) {\n // use data from cloned subtree (which is the same as data but with a prefix added once)\n domain.data = FACET_SCALE_PREFIX + domain.data.replace(FACET_SCALE_PREFIX, '');\n }\n }\n }\n }\n }\n}\nfunction parseNonUnitScaleDomain(model) {\n for (const child of model.children) {\n parseScaleDomain(child);\n }\n const localScaleComponents = model.component.scales;\n for (const channel of util.keys(localScaleComponents)) {\n let domains;\n let selectionExtent = null;\n for (const child of model.children) {\n const childComponent = child.component.scales[channel];\n if (childComponent) {\n if (domains === undefined) {\n domains = childComponent.getWithExplicit('domains');\n }\n else {\n domains = mergeValuesWithExplicit(domains, childComponent.getWithExplicit('domains'), 'domains', 'scale', domainsTieBreaker);\n }\n const se = childComponent.get('selectionExtent');\n if (selectionExtent && se && selectionExtent.param !== se.param) {\n log.warn(log.message.NEEDS_SAME_SELECTION);\n }\n selectionExtent = se;\n }\n }\n localScaleComponents[channel].setWithExplicit('domains', domains);\n if (selectionExtent) {\n localScaleComponents[channel].set('selectionExtent', selectionExtent, true);\n }\n }\n}\n/**\n * Remove unaggregated domain if it is not applicable\n * Add unaggregated domain if domain is not specified and config.scale.useUnaggregatedDomain is true.\n */\nfunction normalizeUnaggregatedDomain(domain, fieldDef, scaleType, scaleConfig) {\n if (domain === 'unaggregated') {\n const { valid, reason } = canUseUnaggregatedDomain(fieldDef, scaleType);\n if (!valid) {\n log.warn(reason);\n return undefined;\n }\n }\n else if (domain === undefined && scaleConfig.useUnaggregatedDomain) {\n // Apply config if domain is not specified.\n const { valid } = canUseUnaggregatedDomain(fieldDef, scaleType);\n if (valid) {\n return 'unaggregated';\n }\n }\n return domain;\n}\nexport function parseDomainForChannel(model, channel) {\n const scaleType = model.getScaleComponent(channel).get('type');\n const { encoding } = model;\n const domain = normalizeUnaggregatedDomain(model.scaleDomain(channel), model.typedFieldDef(channel), scaleType, model.config.scale);\n if (domain !== model.scaleDomain(channel)) {\n model.specifiedScales[channel] = Object.assign(Object.assign({}, model.specifiedScales[channel]), { domain });\n }\n // If channel is either X or Y then union them with X2 & Y2 if they exist\n if (channel === 'x' && getFieldOrDatumDef(encoding.x2)) {\n if (getFieldOrDatumDef(encoding.x)) {\n return mergeValuesWithExplicit(parseSingleChannelDomain(scaleType, domain, model, 'x'), parseSingleChannelDomain(scaleType, domain, model, 'x2'), 'domain', 'scale', domainsTieBreaker);\n }\n else {\n return parseSingleChannelDomain(scaleType, domain, model, 'x2');\n }\n }\n else if (channel === 'y' && getFieldOrDatumDef(encoding.y2)) {\n if (getFieldOrDatumDef(encoding.y)) {\n return mergeValuesWithExplicit(parseSingleChannelDomain(scaleType, domain, model, 'y'), parseSingleChannelDomain(scaleType, domain, model, 'y2'), 'domain', 'scale', domainsTieBreaker);\n }\n else {\n return parseSingleChannelDomain(scaleType, domain, model, 'y2');\n }\n }\n return parseSingleChannelDomain(scaleType, domain, model, channel);\n}\nfunction mapDomainToDataSignal(domain, type, timeUnit) {\n return domain.map(v => {\n const data = valueExpr(v, { timeUnit, type });\n return { signal: `{data: ${data}}` };\n });\n}\nfunction convertDomainIfItIsDateTime(domain, type, timeUnit) {\n var _a;\n // explicit value\n const normalizedTimeUnit = (_a = normalizeTimeUnit(timeUnit)) === null || _a === void 0 ? void 0 : _a.unit;\n if (type === 'temporal' || normalizedTimeUnit) {\n return mapDomainToDataSignal(domain, type, normalizedTimeUnit);\n }\n return [domain]; // Date time won't make sense\n}\nfunction parseSingleChannelDomain(scaleType, domain, model, channel) {\n const { encoding } = model;\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);\n const { type } = fieldOrDatumDef;\n const timeUnit = fieldOrDatumDef['timeUnit'];\n if (isDomainUnionWith(domain)) {\n const defaultDomain = parseSingleChannelDomain(scaleType, undefined, model, channel);\n const unionWith = convertDomainIfItIsDateTime(domain.unionWith, type, timeUnit);\n return makeExplicit([...defaultDomain.value, ...unionWith]);\n }\n else if (isSignalRef(domain)) {\n return makeExplicit([domain]);\n }\n else if (domain && domain !== 'unaggregated' && !isParameterDomain(domain)) {\n return makeExplicit(convertDomainIfItIsDateTime(domain, type, timeUnit));\n }\n const stack = model.stack;\n if (stack && channel === stack.fieldChannel) {\n if (stack.offset === 'normalize') {\n return makeImplicit([[0, 1]]);\n }\n const data = model.requestDataName(DataSourceType.Main);\n return makeImplicit([\n {\n data,\n field: model.vgField(channel, { suffix: 'start' })\n },\n {\n data,\n field: model.vgField(channel, { suffix: 'end' })\n }\n ]);\n }\n const sort = isScaleChannel(channel) && isFieldDef(fieldOrDatumDef) ? domainSort(model, channel, scaleType) : undefined;\n if (isDatumDef(fieldOrDatumDef)) {\n const d = convertDomainIfItIsDateTime([fieldOrDatumDef.datum], type, timeUnit);\n return makeImplicit(d);\n }\n const fieldDef = fieldOrDatumDef; // now we can be sure it's a fieldDef\n if (domain === 'unaggregated') {\n const data = model.requestDataName(DataSourceType.Main);\n const { field } = fieldOrDatumDef;\n return makeImplicit([\n {\n data,\n field: vgField({ field, aggregate: 'min' })\n },\n {\n data,\n field: vgField({ field, aggregate: 'max' })\n }\n ]);\n }\n else if (isBinning(fieldDef.bin)) {\n if (hasDiscreteDomain(scaleType)) {\n if (scaleType === 'bin-ordinal') {\n // we can omit the domain as it is inferred from the `bins` property\n return makeImplicit([]);\n }\n // ordinal bin scale takes domain from bin_range, ordered by bin start\n // This is useful for both axis-based scale (x/y) and legend-based scale (other channels).\n return makeImplicit([\n {\n // If sort by aggregation of a specified sort field, we need to use RAW table,\n // so we can aggregate values for the scale independently from the main aggregation.\n data: util.isBoolean(sort)\n ? model.requestDataName(DataSourceType.Main)\n : model.requestDataName(DataSourceType.Raw),\n // Use range if we added it and the scale does not support computing a range as a signal.\n field: model.vgField(channel, binRequiresRange(fieldDef, channel) ? { binSuffix: 'range' } : {}),\n // we have to use a sort object if sort = true to make the sort correct by bin start\n sort: sort === true || !isObject(sort)\n ? {\n field: model.vgField(channel, {}),\n op: 'min' // min or max doesn't matter since we sort by the start of the bin range\n }\n : sort\n }\n ]);\n }\n else {\n // continuous scales\n const { bin } = fieldDef;\n if (isBinning(bin)) {\n const binSignal = getBinSignalName(model, fieldDef.field, bin);\n return makeImplicit([\n new SignalRefWrapper(() => {\n const signal = model.getSignalName(binSignal);\n return `[${signal}.start, ${signal}.stop]`;\n })\n ]);\n }\n else {\n return makeImplicit([\n {\n data: model.requestDataName(DataSourceType.Main),\n field: model.vgField(channel, {})\n }\n ]);\n }\n }\n }\n else if (fieldDef.timeUnit &&\n util.contains(['time', 'utc'], scaleType) &&\n hasBandEnd(fieldDef, isUnitModel(model) ? model.encoding[getSecondaryRangeChannel(channel)] : undefined, model.markDef, model.config)) {\n const data = model.requestDataName(DataSourceType.Main);\n return makeImplicit([\n {\n data,\n field: model.vgField(channel)\n },\n {\n data,\n field: model.vgField(channel, { suffix: 'end' })\n }\n ]);\n }\n else if (sort) {\n return makeImplicit([\n {\n // If sort by aggregation of a specified sort field, we need to use RAW table,\n // so we can aggregate values for the scale independently from the main aggregation.\n data: util.isBoolean(sort)\n ? model.requestDataName(DataSourceType.Main)\n : model.requestDataName(DataSourceType.Raw),\n field: model.vgField(channel),\n sort: sort\n }\n ]);\n }\n else {\n return makeImplicit([\n {\n data: model.requestDataName(DataSourceType.Main),\n field: model.vgField(channel)\n }\n ]);\n }\n}\nfunction normalizeSortField(sort, isStackedMeasure) {\n const { op, field, order } = sort;\n return Object.assign(Object.assign({ \n // Apply default op\n op: op !== null && op !== void 0 ? op : (isStackedMeasure ? 'sum' : DEFAULT_SORT_OP) }, (field ? { field: util.replacePathInField(field) } : {})), (order ? { order } : {}));\n}\nfunction parseSelectionDomain(model, channel) {\n var _a;\n const scale = model.component.scales[channel];\n const spec = model.specifiedScales[channel].domain;\n const bin = (_a = model.fieldDef(channel)) === null || _a === void 0 ? void 0 : _a.bin;\n const domain = isParameterDomain(spec) && spec;\n const extent = isBinParams(bin) && isParameterExtent(bin.extent) && bin.extent;\n if (domain || extent) {\n // As scale parsing occurs before selection parsing, we cannot set\n // domainRaw directly. So instead, we store the selectionExtent on\n // the scale component, and then add domainRaw during scale assembly.\n scale.set('selectionExtent', domain !== null && domain !== void 0 ? domain : extent, true);\n }\n}\nexport function domainSort(model, channel, scaleType) {\n if (!hasDiscreteDomain(scaleType)) {\n return undefined;\n }\n // save to cast as the only exception is the geojson type for shape, which would not generate a scale\n const fieldDef = model.fieldDef(channel);\n const sort = fieldDef.sort;\n // if the sort is specified with array, use the derived sort index field\n if (isSortArray(sort)) {\n return {\n op: 'min',\n field: sortArrayIndexField(fieldDef, channel),\n order: 'ascending'\n };\n }\n const { stack } = model;\n const stackDimensions = stack\n ? [...(stack.groupbyField ? [stack.groupbyField] : []), ...stack.stackBy.map(s => s.fieldDef.field)]\n : undefined;\n // Sorted based on an aggregate calculation over a specified sort field (only for ordinal scale)\n if (isSortField(sort)) {\n const isStackedMeasure = stack && !util.contains(stackDimensions, sort.field);\n return normalizeSortField(sort, isStackedMeasure);\n }\n else if (isSortByEncoding(sort)) {\n const { encoding, order } = sort;\n const fieldDefToSortBy = model.fieldDef(encoding);\n const { aggregate, field } = fieldDefToSortBy;\n const isStackedMeasure = stack && !util.contains(stackDimensions, field);\n if (isArgminDef(aggregate) || isArgmaxDef(aggregate)) {\n return normalizeSortField({\n field: vgField(fieldDefToSortBy),\n order\n }, isStackedMeasure);\n }\n else if (isAggregateOp(aggregate) || !aggregate) {\n return normalizeSortField({\n op: aggregate,\n field,\n order\n }, isStackedMeasure);\n }\n }\n else if (sort === 'descending') {\n return {\n op: 'min',\n field: model.vgField(channel),\n order: 'descending'\n };\n }\n else if (util.contains(['ascending', undefined /* default =ascending*/], sort)) {\n return true;\n }\n // sort == null\n return undefined;\n}\n/**\n * Determine if a scale can use unaggregated domain.\n * @return {Boolean} Returns true if all of the following conditions apply:\n * 1. `scale.domain` is `unaggregated`\n * 2. Aggregation function is not `count` or `sum`\n * 3. The scale is quantitative or time scale.\n */\nexport function canUseUnaggregatedDomain(fieldDef, scaleType) {\n const { aggregate, type } = fieldDef;\n if (!aggregate) {\n return {\n valid: false,\n reason: log.message.unaggregateDomainHasNoEffectForRawField(fieldDef)\n };\n }\n if (isString(aggregate) && !SHARED_DOMAIN_OP_INDEX[aggregate]) {\n return {\n valid: false,\n reason: log.message.unaggregateDomainWithNonSharedDomainOp(aggregate)\n };\n }\n if (type === 'quantitative') {\n if (scaleType === 'log') {\n return {\n valid: false,\n reason: log.message.unaggregatedDomainWithLogScale(fieldDef)\n };\n }\n }\n return { valid: true };\n}\n/**\n * Tie breaker for mergeValuesWithExplicit for domains. We concat the specified values.\n */\nfunction domainsTieBreaker(v1, v2, property, propertyOf) {\n if (v1.explicit && v2.explicit) {\n log.warn(log.message.mergeConflictingDomainProperty(property, propertyOf, v1.value, v2.value));\n }\n // If equal score, concat the domains so that we union them later.\n return { explicit: v1.explicit, value: [...v1.value, ...v2.value] };\n}\n/**\n * Converts an array of domains to a single Vega scale domain.\n */\nexport function mergeDomains(domains) {\n const uniqueDomains = util.unique(domains.map(domain => {\n // ignore sort property when computing the unique domains\n if (isDataRefDomain(domain)) {\n const { sort: _s } = domain, domainWithoutSort = __rest(domain, [\"sort\"]);\n return domainWithoutSort;\n }\n return domain;\n }), util.hash);\n const sorts = util.unique(domains\n .map(d => {\n if (isDataRefDomain(d)) {\n const s = d.sort;\n if (s !== undefined && !util.isBoolean(s)) {\n if ('op' in s && s.op === 'count') {\n // let's make sure that if op is count, we don't use a field\n delete s.field;\n }\n if (s.order === 'ascending') {\n // drop order: ascending as it is the default\n delete s.order;\n }\n }\n return s;\n }\n return undefined;\n })\n .filter(s => s !== undefined), util.hash);\n if (uniqueDomains.length === 0) {\n return undefined;\n }\n else if (uniqueDomains.length === 1) {\n const domain = domains[0];\n if (isDataRefDomain(domain) && sorts.length > 0) {\n let sort = sorts[0];\n if (sorts.length > 1) {\n log.warn(log.message.MORE_THAN_ONE_SORT);\n sort = true;\n }\n else {\n // Simplify domain sort by removing field and op when the field is the same as the domain field.\n if (isObject(sort) && 'field' in sort) {\n const sortField = sort.field;\n if (domain.field === sortField) {\n sort = sort.order ? { order: sort.order } : true;\n }\n }\n }\n return Object.assign(Object.assign({}, domain), { sort });\n }\n return domain;\n }\n // only keep sort properties that work with unioned domains\n const unionDomainSorts = util.unique(sorts.map(s => {\n if (util.isBoolean(s) || !('op' in s) || (isString(s.op) && s.op in UNIONDOMAIN_SORT_OP_INDEX)) {\n return s;\n }\n log.warn(log.message.domainSortDropped(s));\n return true;\n }), util.hash);\n let sort;\n if (unionDomainSorts.length === 1) {\n sort = unionDomainSorts[0];\n }\n else if (unionDomainSorts.length > 1) {\n log.warn(log.message.MORE_THAN_ONE_SORT);\n sort = true;\n }\n const allData = util.unique(domains.map(d => {\n if (isDataRefDomain(d)) {\n return d.data;\n }\n return null;\n }), x => x);\n if (allData.length === 1 && allData[0] !== null) {\n // create a union domain of different fields with a single data source\n const domain = Object.assign({ data: allData[0], fields: uniqueDomains.map(d => d.field) }, (sort ? { sort } : {}));\n return domain;\n }\n return Object.assign({ fields: uniqueDomains }, (sort ? { sort } : {}));\n}\n/**\n * Return a field if a scale uses a single field.\n * Return `undefined` otherwise.\n */\nexport function getFieldFromDomain(domain) {\n if (isDataRefDomain(domain) && isString(domain.field)) {\n return domain.field;\n }\n else if (isDataRefUnionedDomain(domain)) {\n let field;\n for (const nonUnionDomain of domain.fields) {\n if (isDataRefDomain(nonUnionDomain) && isString(nonUnionDomain.field)) {\n if (!field) {\n field = nonUnionDomain.field;\n }\n else if (field !== nonUnionDomain.field) {\n log.warn(log.message.FACETED_INDEPENDENT_DIFFERENT_SOURCES);\n return field;\n }\n }\n }\n log.warn(log.message.FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES);\n return field;\n }\n else if (isFieldRefUnionDomain(domain)) {\n log.warn(log.message.FACETED_INDEPENDENT_SAME_SOURCE);\n const field = domain.fields[0];\n return isString(field) ? field : undefined;\n }\n return undefined;\n}\nexport function assembleDomain(model, channel) {\n const scaleComponent = model.component.scales[channel];\n const domains = scaleComponent.get('domains').map((domain) => {\n // Correct references to data as the original domain's data was determined\n // in parseScale, which happens before parseData. Thus the original data\n // reference can be incorrect.\n if (isDataRefDomain(domain)) {\n domain.data = model.lookupDataSource(domain.data);\n }\n return domain;\n });\n // domains is an array that has to be merged into a single vega domain\n return mergeDomains(domains);\n}\n//# sourceMappingURL=domain.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isObject } from 'vega-util';\nimport { isXorY } from '../../channel';\nimport { keys } from '../../util';\nimport { isDataRefDomain, isVgRangeStep } from '../../vega.schema';\nimport { isConcatModel, isLayerModel } from '../model';\nimport { assembleSelectionScaleDomain } from '../selection/assemble';\nimport { assembleDomain } from './domain';\nexport function assembleScales(model) {\n if (isLayerModel(model) || isConcatModel(model)) {\n // For concat and layer, include scales of children too\n return model.children.reduce((scales, child) => {\n return scales.concat(assembleScales(child));\n }, assembleScalesForModel(model));\n }\n else {\n // For facet, child scales would not be included in the parent's scope.\n // For unit, there is no child.\n return assembleScalesForModel(model);\n }\n}\nexport function assembleScalesForModel(model) {\n return keys(model.component.scales).reduce((scales, channel) => {\n const scaleComponent = model.component.scales[channel];\n if (scaleComponent.merged) {\n // Skipped merged scales\n return scales;\n }\n const scale = scaleComponent.combine();\n const { name, type, selectionExtent, domains: _d, range: _r, reverse } = scale, otherScaleProps = __rest(scale, [\"name\", \"type\", \"selectionExtent\", \"domains\", \"range\", \"reverse\"]);\n const range = assembleScaleRange(scale.range, name, channel, model);\n const domain = assembleDomain(model, channel);\n const domainRaw = selectionExtent\n ? assembleSelectionScaleDomain(model, selectionExtent, scaleComponent, domain)\n : null;\n scales.push(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name,\n type }, (domain ? { domain } : {})), (domainRaw ? { domainRaw } : {})), { range }), (reverse !== undefined ? { reverse: reverse } : {})), otherScaleProps));\n return scales;\n }, []);\n}\nexport function assembleScaleRange(scaleRange, scaleName, channel, model) {\n // add signals to x/y range\n if (isXorY(channel)) {\n if (isVgRangeStep(scaleRange)) {\n // For width/height step, use a signal created in layout assemble instead of a constant step.\n return {\n step: { signal: `${scaleName}_step` }\n };\n }\n }\n else if (isObject(scaleRange) && isDataRefDomain(scaleRange)) {\n return Object.assign(Object.assign({}, scaleRange), { data: model.lookupDataSource(scaleRange.data) });\n }\n return scaleRange;\n}\n//# sourceMappingURL=assemble.js.map","import { isArray } from 'vega-util';\nimport { some } from '../../util';\nimport { Split } from '../split';\nexport class ScaleComponent extends Split {\n constructor(name, typeWithExplicit) {\n super({}, // no initial explicit property\n { name } // name as initial implicit property\n );\n this.merged = false;\n this.setWithExplicit('type', typeWithExplicit);\n }\n /**\n * Whether the scale definitely includes zero in the domain\n */\n domainDefinitelyIncludesZero() {\n if (this.get('zero') !== false) {\n return true;\n }\n return some(this.get('domains'), d => isArray(d) && d.length === 2 && d[0] <= 0 && d[1] >= 0);\n }\n}\n//# sourceMappingURL=component.js.map","import { isArray, isNumber, isObject } from 'vega-util';\nimport { isBinning } from '../../bin';\nimport { ANGLE, COLOR, FILL, FILLOPACITY, isXorY, OPACITY, RADIUS, SCALE_CHANNELS, SHAPE, SIZE, STROKE, STROKEDASH, STROKEOPACITY, STROKEWIDTH, THETA, X, Y } from '../../channel';\nimport { getFieldOrDatumDef } from '../../channeldef';\nimport { getViewConfigDiscreteSize, getViewConfigDiscreteStep } from '../../config';\nimport { DataSourceType } from '../../data';\nimport * as log from '../../log';\nimport { channelScalePropertyIncompatability, hasContinuousDomain, hasDiscreteDomain, isContinuousToDiscrete, isExtendedScheme, scaleTypeSupportProperty } from '../../scale';\nimport { isStep } from '../../spec/base';\nimport * as util from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { signalOrStringValue } from '../common';\nimport { getBinSignalName } from '../data/bin';\nimport { SignalRefWrapper } from '../signal';\nimport { makeExplicit, makeImplicit } from '../split';\nexport const RANGE_PROPERTIES = ['range', 'scheme'];\nfunction getSizeChannel(channel) {\n return channel === 'x' ? 'width' : channel === 'y' ? 'height' : undefined;\n}\nexport function parseUnitScaleRange(model) {\n const localScaleComponents = model.component.scales;\n // use SCALE_CHANNELS instead of scales[channel] to ensure that x, y come first!\n for (const channel of SCALE_CHANNELS) {\n const localScaleCmpt = localScaleComponents[channel];\n if (!localScaleCmpt) {\n continue;\n }\n const rangeWithExplicit = parseRangeForChannel(channel, model);\n localScaleCmpt.setWithExplicit('range', rangeWithExplicit);\n }\n}\nfunction getBinStepSignal(model, channel) {\n const fieldDef = model.fieldDef(channel);\n if (fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.bin) {\n const { bin, field } = fieldDef;\n const sizeType = getSizeChannel(channel);\n const sizeSignal = model.getName(sizeType);\n if (isObject(bin) && bin.binned && bin.step !== undefined) {\n return new SignalRefWrapper(() => {\n const scaleName = model.scaleName(channel);\n const binCount = `(domain(\"${scaleName}\")[1] - domain(\"${scaleName}\")[0]) / ${bin.step}`;\n return `${model.getSignalName(sizeSignal)} / (${binCount})`;\n });\n }\n else if (isBinning(bin)) {\n const binSignal = getBinSignalName(model, field, bin);\n // TODO: extract this to be range step signal\n return new SignalRefWrapper(() => {\n const updatedName = model.getSignalName(binSignal);\n const binCount = `(${updatedName}.stop - ${updatedName}.start) / ${updatedName}.step`;\n return `${model.getSignalName(sizeSignal)} / (${binCount})`;\n });\n }\n }\n return undefined;\n}\n/**\n * Return mixins that includes one of the Vega range types (explicit range, range.step, range.scheme).\n */\nexport function parseRangeForChannel(channel, model) {\n const specifiedScale = model.specifiedScales[channel];\n const { size } = model;\n const mergedScaleCmpt = model.getScaleComponent(channel);\n const scaleType = mergedScaleCmpt.get('type');\n // Check if any of the range properties is specified.\n // If so, check if it is compatible and make sure that we only output one of the properties\n for (const property of RANGE_PROPERTIES) {\n if (specifiedScale[property] !== undefined) {\n const supportedByScaleType = scaleTypeSupportProperty(scaleType, property);\n const channelIncompatability = channelScalePropertyIncompatability(channel, property);\n if (!supportedByScaleType) {\n log.warn(log.message.scalePropertyNotWorkWithScaleType(scaleType, property, channel));\n }\n else if (channelIncompatability) {\n // channel\n log.warn(channelIncompatability);\n }\n else {\n switch (property) {\n case 'range': {\n const range = specifiedScale.range;\n if (isArray(range)) {\n if (isXorY(channel)) {\n return makeExplicit(range.map(v => {\n if (v === 'width' || v === 'height') {\n // get signal for width/height\n // Just like default range logic below, we use SignalRefWrapper to account for potential merges and renames.\n const sizeSignal = model.getName(v);\n const getSignalName = model.getSignalName.bind(model);\n return SignalRefWrapper.fromName(getSignalName, sizeSignal);\n }\n return v;\n }));\n }\n }\n else if (isObject(range)) {\n return makeExplicit({\n data: model.requestDataName(DataSourceType.Main),\n field: range.field,\n sort: { op: 'min', field: model.vgField(channel) }\n });\n }\n return makeExplicit(range);\n }\n case 'scheme':\n return makeExplicit(parseScheme(specifiedScale[property]));\n }\n }\n }\n }\n if (channel === X || channel === Y) {\n const sizeChannel = channel === X ? 'width' : 'height';\n const sizeValue = size[sizeChannel];\n if (isStep(sizeValue)) {\n if (hasDiscreteDomain(scaleType)) {\n return makeExplicit({ step: sizeValue.step });\n }\n else {\n log.warn(log.message.stepDropped(sizeChannel));\n }\n }\n }\n const { rangeMin, rangeMax } = specifiedScale;\n const d = defaultRange(channel, model);\n if ((rangeMin !== undefined || rangeMax !== undefined) &&\n // it's ok to check just rangeMin's compatibility since rangeMin/rangeMax are the same\n scaleTypeSupportProperty(scaleType, 'rangeMin') &&\n isArray(d) &&\n d.length === 2) {\n return makeExplicit([rangeMin !== null && rangeMin !== void 0 ? rangeMin : d[0], rangeMax !== null && rangeMax !== void 0 ? rangeMax : d[1]]);\n }\n return makeImplicit(d);\n}\nfunction parseScheme(scheme) {\n if (isExtendedScheme(scheme)) {\n return Object.assign({ scheme: scheme.name }, util.omit(scheme, ['name']));\n }\n return { scheme: scheme };\n}\nfunction defaultRange(channel, model) {\n const { size, config, mark, encoding } = model;\n const getSignalName = model.getSignalName.bind(model);\n const { type } = getFieldOrDatumDef(encoding[channel]);\n const mergedScaleCmpt = model.getScaleComponent(channel);\n const scaleType = mergedScaleCmpt.get('type');\n const { domain, domainMid } = model.specifiedScales[channel];\n switch (channel) {\n case X:\n case Y: {\n // If there is no explicit width/height for discrete x/y scales\n if (util.contains(['point', 'band'], scaleType)) {\n if (channel === X && !size.width) {\n const w = getViewConfigDiscreteSize(config.view, 'width');\n if (isStep(w)) {\n return w;\n }\n }\n else if (channel === Y && !size.height) {\n const h = getViewConfigDiscreteSize(config.view, 'height');\n if (isStep(h)) {\n return h;\n }\n }\n }\n // If step is null, use zero to width or height.\n // Note that we use SignalRefWrapper to account for potential merges and renames.\n const sizeType = getSizeChannel(channel);\n const sizeSignal = model.getName(sizeType);\n if (channel === Y && hasContinuousDomain(scaleType)) {\n // For y continuous scale, we have to start from the height as the bottom part has the max value.\n return [SignalRefWrapper.fromName(getSignalName, sizeSignal), 0];\n }\n else {\n return [0, SignalRefWrapper.fromName(getSignalName, sizeSignal)];\n }\n }\n case SIZE: {\n // TODO: support custom rangeMin, rangeMax\n const zero = model.component.scales[channel].get('zero');\n const rangeMin = sizeRangeMin(mark, zero, config);\n const rangeMax = sizeRangeMax(mark, size, model, config);\n if (isContinuousToDiscrete(scaleType)) {\n return interpolateRange(rangeMin, rangeMax, defaultContinuousToDiscreteCount(scaleType, config, domain, channel));\n }\n else {\n return [rangeMin, rangeMax];\n }\n }\n case THETA:\n return [0, Math.PI * 2];\n case ANGLE:\n // TODO: add config.scale.min/maxAngleDegree (for point and text) and config.scale.min/maxAngleRadian (for arc) once we add arc marks.\n // (It's weird to add just config.scale.min/maxAngleDegree for now)\n return [0, 360];\n case RADIUS: {\n // max radius = half od min(width,height)\n return [\n 0,\n new SignalRefWrapper(() => {\n const w = model.getSignalName('width');\n const h = model.getSignalName('height');\n return `min(${w},${h})/2`;\n })\n ];\n }\n case STROKEWIDTH:\n // TODO: support custom rangeMin, rangeMax\n return [config.scale.minStrokeWidth, config.scale.maxStrokeWidth];\n case STROKEDASH:\n return [\n // TODO: add this to Vega's config.range?\n [1, 0],\n [4, 2],\n [2, 1],\n [1, 1],\n [1, 2, 4, 2]\n ];\n case SHAPE:\n return 'symbol';\n case COLOR:\n case FILL:\n case STROKE:\n if (scaleType === 'ordinal') {\n // Only nominal data uses ordinal scale by default\n return type === 'nominal' ? 'category' : 'ordinal';\n }\n else {\n if (domainMid !== undefined) {\n return 'diverging';\n }\n else {\n return mark === 'rect' || mark === 'geoshape' ? 'heatmap' : 'ramp';\n }\n }\n case OPACITY:\n case FILLOPACITY:\n case STROKEOPACITY:\n // TODO: support custom rangeMin, rangeMax\n return [config.scale.minOpacity, config.scale.maxOpacity];\n }\n /* istanbul ignore next: should never reach here */\n throw new Error(`Scale range undefined for channel ${channel}`);\n}\nexport function defaultContinuousToDiscreteCount(scaleType, config, domain, channel) {\n switch (scaleType) {\n case 'quantile':\n return config.scale.quantileCount;\n case 'quantize':\n return config.scale.quantizeCount;\n case 'threshold':\n if (domain !== undefined && isArray(domain)) {\n return domain.length + 1;\n }\n else {\n log.warn(log.message.domainRequiredForThresholdScale(channel));\n // default threshold boundaries for threshold scale since domain has cardinality of 2\n return 3;\n }\n }\n}\n/**\n * Returns the linear interpolation of the range according to the cardinality\n *\n * @param rangeMin start of the range\n * @param rangeMax end of the range\n * @param cardinality number of values in the output range\n */\nexport function interpolateRange(rangeMin, rangeMax, cardinality) {\n // always return a signal since it's better to compute the sequence in Vega later\n const f = () => {\n const rMax = signalOrStringValue(rangeMax);\n const rMin = signalOrStringValue(rangeMin);\n const step = `(${rMax} - ${rMin}) / (${cardinality} - 1)`;\n return `sequence(${rMin}, ${rMax} + ${step}, ${step})`;\n };\n if (isSignalRef(rangeMax)) {\n return new SignalRefWrapper(f);\n }\n else {\n return { signal: f() };\n }\n}\nfunction sizeRangeMin(mark, zero, config) {\n if (zero) {\n if (isSignalRef(zero)) {\n return { signal: `${zero.signal} ? 0 : ${sizeRangeMin(mark, false, config)}` };\n }\n else {\n return 0;\n }\n }\n switch (mark) {\n case 'bar':\n case 'tick':\n return config.scale.minBandSize;\n case 'line':\n case 'trail':\n case 'rule':\n return config.scale.minStrokeWidth;\n case 'text':\n return config.scale.minFontSize;\n case 'point':\n case 'square':\n case 'circle':\n return config.scale.minSize;\n }\n /* istanbul ignore next: should never reach here */\n // sizeRangeMin not implemented for the mark\n throw new Error(log.message.incompatibleChannel('size', mark));\n}\nexport const MAX_SIZE_RANGE_STEP_RATIO = 0.95;\nfunction sizeRangeMax(mark, size, model, config) {\n const xyStepSignals = {\n x: getBinStepSignal(model, 'x'),\n y: getBinStepSignal(model, 'y')\n };\n switch (mark) {\n case 'bar':\n case 'tick': {\n if (config.scale.maxBandSize !== undefined) {\n return config.scale.maxBandSize;\n }\n const min = minXYStep(size, xyStepSignals, config.view);\n if (isNumber(min)) {\n return min - 1;\n }\n else {\n return new SignalRefWrapper(() => `${min.signal} - 1`);\n }\n }\n case 'line':\n case 'trail':\n case 'rule':\n return config.scale.maxStrokeWidth;\n case 'text':\n return config.scale.maxFontSize;\n case 'point':\n case 'square':\n case 'circle': {\n if (config.scale.maxSize) {\n return config.scale.maxSize;\n }\n const pointStep = minXYStep(size, xyStepSignals, config.view);\n if (isNumber(pointStep)) {\n return Math.pow(MAX_SIZE_RANGE_STEP_RATIO * pointStep, 2);\n }\n else {\n return new SignalRefWrapper(() => `pow(${MAX_SIZE_RANGE_STEP_RATIO} * ${pointStep.signal}, 2)`);\n }\n }\n }\n /* istanbul ignore next: should never reach here */\n // sizeRangeMax not implemented for the mark\n throw new Error(log.message.incompatibleChannel('size', mark));\n}\n/**\n * @returns {number} Range step of x or y or minimum between the two if both are ordinal scale.\n */\nfunction minXYStep(size, xyStepSignals, viewConfig) {\n const widthStep = isStep(size.width) ? size.width.step : getViewConfigDiscreteStep(viewConfig, 'width');\n const heightStep = isStep(size.height) ? size.height.step : getViewConfigDiscreteStep(viewConfig, 'height');\n if (xyStepSignals.x || xyStepSignals.y) {\n return new SignalRefWrapper(() => {\n const exprs = [\n xyStepSignals.x ? xyStepSignals.x.signal : widthStep,\n xyStepSignals.y ? xyStepSignals.y.signal : heightStep\n ];\n return `min(${exprs.join(', ')})`;\n });\n }\n return Math.min(widthStep, heightStep);\n}\n//# sourceMappingURL=range.js.map","import { isArray } from 'vega-util';\nimport { isBinned, isBinning, isBinParams } from '../../bin';\nimport { COLOR, FILL, POLAR_POSITION_SCALE_CHANNELS, POSITION_SCALE_CHANNELS, POSITION_SCALE_CHANNEL_INDEX, STROKE } from '../../channel';\nimport { getFieldDef, getFieldOrDatumDef, isFieldDef, valueExpr } from '../../channeldef';\nimport { isDateTime } from '../../datetime';\nimport * as log from '../../log';\nimport { channelScalePropertyIncompatability, hasContinuousDomain, isContinuousToContinuous, isContinuousToDiscrete, ScaleType, scaleTypeSupportProperty } from '../../scale';\nimport * as util from '../../util';\nimport { contains, getFirstDefined, keys } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { getBinSignalName } from '../data/bin';\nimport { isUnitModel } from '../model';\nimport { SignalRefWrapper } from '../signal';\nimport { mergeValuesWithExplicit, tieBreakByComparing } from '../split';\nimport { parseUnitScaleRange } from './range';\nexport function parseScaleProperty(model, property) {\n if (isUnitModel(model)) {\n parseUnitScaleProperty(model, property);\n }\n else {\n parseNonUnitScaleProperty(model, property);\n }\n}\nfunction parseUnitScaleProperty(model, property) {\n const localScaleComponents = model.component.scales;\n const { config, encoding, markDef, specifiedScales } = model;\n for (const channel of keys(localScaleComponents)) {\n const specifiedScale = specifiedScales[channel];\n const localScaleCmpt = localScaleComponents[channel];\n const mergedScaleCmpt = model.getScaleComponent(channel);\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);\n const specifiedValue = specifiedScale[property];\n const scaleType = mergedScaleCmpt.get('type');\n const scalePadding = mergedScaleCmpt.get('padding');\n const scalePaddingInner = mergedScaleCmpt.get('paddingInner');\n const supportedByScaleType = scaleTypeSupportProperty(scaleType, property);\n const channelIncompatability = channelScalePropertyIncompatability(channel, property);\n if (specifiedValue !== undefined) {\n // If there is a specified value, check if it is compatible with scale type and channel\n if (!supportedByScaleType) {\n log.warn(log.message.scalePropertyNotWorkWithScaleType(scaleType, property, channel));\n }\n else if (channelIncompatability) {\n // channel\n log.warn(channelIncompatability);\n }\n }\n if (supportedByScaleType && channelIncompatability === undefined) {\n if (specifiedValue !== undefined) {\n const timeUnit = fieldOrDatumDef['timeUnit'];\n const type = fieldOrDatumDef.type;\n switch (property) {\n // domainMax/Min to signal if the value is a datetime object\n case 'domainMax':\n case 'domainMin':\n if (isDateTime(specifiedScale[property]) || type === 'temporal' || timeUnit) {\n localScaleCmpt.set(property, { signal: valueExpr(specifiedScale[property], { type, timeUnit }) }, true);\n }\n else {\n localScaleCmpt.set(property, specifiedScale[property], true);\n }\n break;\n default:\n localScaleCmpt.copyKeyFromObject(property, specifiedScale);\n }\n }\n else {\n const value = property in scaleRules\n ? scaleRules[property]({\n model,\n channel,\n fieldOrDatumDef,\n scaleType,\n scalePadding,\n scalePaddingInner,\n domain: specifiedScale.domain,\n markDef,\n config\n })\n : config.scale[property];\n if (value !== undefined) {\n localScaleCmpt.set(property, value, false);\n }\n }\n }\n }\n}\nexport const scaleRules = {\n bins: ({ model, fieldOrDatumDef }) => (isFieldDef(fieldOrDatumDef) ? bins(model, fieldOrDatumDef) : undefined),\n interpolate: ({ channel, fieldOrDatumDef }) => interpolate(channel, fieldOrDatumDef.type),\n nice: ({ scaleType, channel, domain, fieldOrDatumDef }) => nice(scaleType, channel, domain, fieldOrDatumDef),\n padding: ({ channel, scaleType, fieldOrDatumDef, markDef, config }) => padding(channel, scaleType, config.scale, fieldOrDatumDef, markDef, config.bar),\n paddingInner: ({ scalePadding, channel, markDef, config }) => paddingInner(scalePadding, channel, markDef.type, config.scale),\n paddingOuter: ({ scalePadding, channel, scaleType, markDef, scalePaddingInner, config }) => paddingOuter(scalePadding, channel, scaleType, markDef.type, scalePaddingInner, config.scale),\n reverse: ({ fieldOrDatumDef, scaleType, channel, config }) => {\n const sort = isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : undefined;\n return reverse(scaleType, sort, channel, config.scale);\n },\n zero: ({ channel, fieldOrDatumDef, domain, markDef, scaleType }) => zero(channel, fieldOrDatumDef, domain, markDef, scaleType)\n};\n// This method is here rather than in range.ts to avoid circular dependency.\nexport function parseScaleRange(model) {\n if (isUnitModel(model)) {\n parseUnitScaleRange(model);\n }\n else {\n parseNonUnitScaleProperty(model, 'range');\n }\n}\nexport function parseNonUnitScaleProperty(model, property) {\n const localScaleComponents = model.component.scales;\n for (const child of model.children) {\n if (property === 'range') {\n parseScaleRange(child);\n }\n else {\n parseScaleProperty(child, property);\n }\n }\n for (const channel of keys(localScaleComponents)) {\n let valueWithExplicit;\n for (const child of model.children) {\n const childComponent = child.component.scales[channel];\n if (childComponent) {\n const childValueWithExplicit = childComponent.getWithExplicit(property);\n valueWithExplicit = mergeValuesWithExplicit(valueWithExplicit, childValueWithExplicit, property, 'scale', tieBreakByComparing((v1, v2) => {\n switch (property) {\n case 'range':\n // For step, prefer larger step\n if (v1.step && v2.step) {\n return v1.step - v2.step;\n }\n return 0;\n // TODO: precedence rule for other properties\n }\n return 0;\n }));\n }\n }\n localScaleComponents[channel].setWithExplicit(property, valueWithExplicit);\n }\n}\nexport function bins(model, fieldDef) {\n const bin = fieldDef.bin;\n if (isBinning(bin)) {\n const binSignal = getBinSignalName(model, fieldDef.field, bin);\n return new SignalRefWrapper(() => {\n return model.getSignalName(binSignal);\n });\n }\n else if (isBinned(bin) && isBinParams(bin) && bin.step !== undefined) {\n // start and stop will be determined from the scale domain\n return {\n step: bin.step\n };\n }\n return undefined;\n}\nexport function interpolate(channel, type) {\n if (contains([COLOR, FILL, STROKE], channel) && type !== 'nominal') {\n return 'hcl';\n }\n return undefined;\n}\nexport function nice(scaleType, channel, specifiedDomain, fieldOrDatumDef) {\n var _a;\n if (((_a = getFieldDef(fieldOrDatumDef)) === null || _a === void 0 ? void 0 : _a.bin) ||\n isArray(specifiedDomain) ||\n util.contains([ScaleType.TIME, ScaleType.UTC], scaleType)) {\n return undefined;\n }\n return channel in POSITION_SCALE_CHANNEL_INDEX ? true : undefined;\n}\nexport function padding(channel, scaleType, scaleConfig, fieldOrDatumDef, markDef, barConfig) {\n if (channel in POSITION_SCALE_CHANNEL_INDEX) {\n if (isContinuousToContinuous(scaleType)) {\n if (scaleConfig.continuousPadding !== undefined) {\n return scaleConfig.continuousPadding;\n }\n const { type, orient } = markDef;\n if (type === 'bar' && !(isFieldDef(fieldOrDatumDef) && (fieldOrDatumDef.bin || fieldOrDatumDef.timeUnit))) {\n if ((orient === 'vertical' && channel === 'x') || (orient === 'horizontal' && channel === 'y')) {\n return barConfig.continuousBandSize;\n }\n }\n }\n if (scaleType === ScaleType.POINT) {\n return scaleConfig.pointPadding;\n }\n }\n return undefined;\n}\nexport function paddingInner(paddingValue, channel, mark, scaleConfig) {\n if (paddingValue !== undefined) {\n // If user has already manually specified \"padding\", no need to add default paddingInner.\n return undefined;\n }\n if (channel in POSITION_SCALE_CHANNEL_INDEX) {\n // Padding is only set for X and Y by default.\n // Basically it doesn't make sense to add padding for color and size.\n // paddingOuter would only be called if it's a band scale, just return the default for bandScale.\n const { bandPaddingInner, barBandPaddingInner, rectBandPaddingInner } = scaleConfig;\n return getFirstDefined(bandPaddingInner, mark === 'bar' ? barBandPaddingInner : rectBandPaddingInner);\n }\n return undefined;\n}\nexport function paddingOuter(paddingValue, channel, scaleType, mark, paddingInnerValue, scaleConfig) {\n if (paddingValue !== undefined) {\n // If user has already manually specified \"padding\", no need to add default paddingOuter.\n return undefined;\n }\n if (channel in POSITION_SCALE_CHANNEL_INDEX) {\n // Padding is only set for X and Y by default.\n // Basically it doesn't make sense to add padding for color and size.\n if (scaleType === ScaleType.BAND) {\n const { bandPaddingOuter } = scaleConfig;\n return getFirstDefined(bandPaddingOuter, \n /* By default, paddingOuter is paddingInner / 2. The reason is that\n size (width/height) = step * (cardinality - paddingInner + 2 * paddingOuter).\n and we want the width/height to be integer by default.\n Note that step (by default) and cardinality are integers.) */\n isSignalRef(paddingInnerValue) ? { signal: `${paddingInnerValue.signal}/2` } : paddingInnerValue / 2);\n }\n }\n return undefined;\n}\nexport function reverse(scaleType, sort, channel, scaleConfig) {\n if (channel === 'x' && scaleConfig.xReverse !== undefined) {\n if (hasContinuousDomain(scaleType) && sort === 'descending') {\n if (isSignalRef(scaleConfig.xReverse)) {\n return { signal: `!${scaleConfig.xReverse.signal}` };\n }\n else {\n return !scaleConfig.xReverse;\n }\n }\n return scaleConfig.xReverse;\n }\n if (hasContinuousDomain(scaleType) && sort === 'descending') {\n // For continuous domain scales, Vega does not support domain sort.\n // Thus, we reverse range instead if sort is descending\n return true;\n }\n return undefined;\n}\nexport function zero(channel, fieldDef, specifiedDomain, markDef, scaleType) {\n // If users explicitly provide a domain, we should not augment zero as that will be unexpected.\n const hasCustomDomain = !!specifiedDomain && specifiedDomain !== 'unaggregated';\n if (hasCustomDomain) {\n if (hasContinuousDomain(scaleType)) {\n if (isArray(specifiedDomain)) {\n const first = specifiedDomain[0];\n const last = specifiedDomain[specifiedDomain.length - 1];\n if (first <= 0 && last >= 0) {\n // if the domain includes zero, make zero remains true\n return true;\n }\n }\n return false;\n }\n }\n // If there is no custom domain, return true only for the following cases:\n // 1) using quantitative field with size\n // While this can be either ratio or interval fields, our assumption is that\n // ratio are more common. However, if the scaleType is discretizing scale, we want to return\n // false so that range doesn't start at zero\n if (channel === 'size' && fieldDef.type === 'quantitative' && !isContinuousToDiscrete(scaleType)) {\n return true;\n }\n // 2) non-binned, quantitative x-scale or y-scale\n // (For binning, we should not include zero by default because binning are calculated without zero.)\n if (!(isFieldDef(fieldDef) && fieldDef.bin) &&\n util.contains([...POSITION_SCALE_CHANNELS, ...POLAR_POSITION_SCALE_CHANNELS], channel)) {\n const { orient, type } = markDef;\n if (contains(['bar', 'area', 'line', 'trail'], type)) {\n if ((orient === 'horizontal' && channel === 'y') || (orient === 'vertical' && channel === 'x')) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n//# sourceMappingURL=properties.js.map","import { isBinning } from '../../bin';\nimport { getSizeChannel, isColorChannel, isScaleChannel, rangeType } from '../../channel';\nimport { isFieldDef, isPositionFieldOrDatumDef } from '../../channeldef';\nimport * as log from '../../log';\nimport { isRelativeBandSize } from '../../mark';\nimport { channelSupportScaleType, scaleTypeSupportDataType } from '../../scale';\nimport { normalizeTimeUnit } from '../../timeunit';\nimport * as util from '../../util';\nimport { POLAR_POSITION_SCALE_CHANNEL_INDEX, POSITION_SCALE_CHANNEL_INDEX } from './../../channel';\n/**\n * Determine if there is a specified scale type and if it is appropriate,\n * or determine default type if type is unspecified or inappropriate.\n */\n// NOTE: CompassQL uses this method.\nexport function scaleType(specifiedScale, channel, fieldDef, mark) {\n const defaultScaleType = defaultType(channel, fieldDef, mark);\n const { type } = specifiedScale;\n if (!isScaleChannel(channel)) {\n // There is no scale for these channels\n return null;\n }\n if (type !== undefined) {\n // Check if explicitly specified scale type is supported by the channel\n if (!channelSupportScaleType(channel, type)) {\n log.warn(log.message.scaleTypeNotWorkWithChannel(channel, type, defaultScaleType));\n return defaultScaleType;\n }\n // Check if explicitly specified scale type is supported by the data type\n if (isFieldDef(fieldDef) && !scaleTypeSupportDataType(type, fieldDef.type)) {\n log.warn(log.message.scaleTypeNotWorkWithFieldDef(type, defaultScaleType));\n return defaultScaleType;\n }\n return type;\n }\n return defaultScaleType;\n}\n/**\n * Determine appropriate default scale type.\n */\n// NOTE: Voyager uses this method.\nfunction defaultType(channel, fieldDef, mark) {\n var _a;\n switch (fieldDef.type) {\n case 'nominal':\n case 'ordinal': {\n if (isColorChannel(channel) || rangeType(channel) === 'discrete') {\n if (channel === 'shape' && fieldDef.type === 'ordinal') {\n log.warn(log.message.discreteChannelCannotEncode(channel, 'ordinal'));\n }\n return 'ordinal';\n }\n if (channel in POSITION_SCALE_CHANNEL_INDEX) {\n if (util.contains(['rect', 'bar', 'image', 'rule'], mark.type)) {\n // The rect/bar mark should fit into a band.\n // For rule, using band scale to make rule align with axis ticks better https://github.com/vega/vega-lite/issues/3429\n return 'band';\n }\n }\n else if (mark.type === 'arc' && channel in POLAR_POSITION_SCALE_CHANNEL_INDEX) {\n return 'band';\n }\n const dimensionSize = mark[getSizeChannel(channel)];\n if (isRelativeBandSize(dimensionSize)) {\n return 'band';\n }\n if (isPositionFieldOrDatumDef(fieldDef) && ((_a = fieldDef.axis) === null || _a === void 0 ? void 0 : _a.tickBand)) {\n return 'band';\n }\n // Otherwise, use ordinal point scale so we can easily get center positions of the marks.\n return 'point';\n }\n case 'temporal':\n if (isColorChannel(channel)) {\n return 'time';\n }\n else if (rangeType(channel) === 'discrete') {\n log.warn(log.message.discreteChannelCannotEncode(channel, 'temporal'));\n // TODO: consider using quantize (equivalent to binning) once we have it\n return 'ordinal';\n }\n else if (isFieldDef(fieldDef) && fieldDef.timeUnit && normalizeTimeUnit(fieldDef.timeUnit).utc) {\n return 'utc';\n }\n return 'time';\n case 'quantitative':\n if (isColorChannel(channel)) {\n if (isFieldDef(fieldDef) && isBinning(fieldDef.bin)) {\n return 'bin-ordinal';\n }\n return 'linear';\n }\n else if (rangeType(channel) === 'discrete') {\n log.warn(log.message.discreteChannelCannotEncode(channel, 'quantitative'));\n // TODO: consider using quantize (equivalent to binning) once we have it\n return 'ordinal';\n }\n return 'linear';\n case 'geojson':\n return undefined;\n }\n /* istanbul ignore next: should never reach this */\n throw new Error(log.message.invalidFieldType(fieldDef.type));\n}\n//# sourceMappingURL=type.js.map","import { SCALE_CHANNELS, SHAPE } from '../../channel';\nimport { getFieldOrDatumDef } from '../../channeldef';\nimport { GEOSHAPE } from '../../mark';\nimport { NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES, scaleCompatible, scaleTypePrecedence } from '../../scale';\nimport { GEOJSON } from '../../type';\nimport { keys } from '../../util';\nimport { isUnitModel } from '../model';\nimport { defaultScaleResolve } from '../resolve';\nimport { mergeValuesWithExplicit, tieBreakByComparing } from '../split';\nimport { ScaleComponent } from './component';\nimport { parseScaleDomain } from './domain';\nimport { parseScaleProperty, parseScaleRange } from './properties';\nimport { scaleType } from './type';\nexport function parseScales(model, { ignoreRange } = {}) {\n parseScaleCore(model);\n parseScaleDomain(model);\n for (const prop of NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES) {\n parseScaleProperty(model, prop);\n }\n if (!ignoreRange) {\n // range depends on zero\n parseScaleRange(model);\n }\n}\nexport function parseScaleCore(model) {\n if (isUnitModel(model)) {\n model.component.scales = parseUnitScaleCore(model);\n }\n else {\n model.component.scales = parseNonUnitScaleCore(model);\n }\n}\n/**\n * Parse scales for all channels of a model.\n */\nfunction parseUnitScaleCore(model) {\n const { encoding, mark, markDef } = model;\n return SCALE_CHANNELS.reduce((scaleComponents, channel) => {\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]); // must be typed def to have scale\n // Don't generate scale for shape of geoshape\n if (fieldOrDatumDef && mark === GEOSHAPE && channel === SHAPE && fieldOrDatumDef.type === GEOJSON) {\n return scaleComponents;\n }\n let specifiedScale = fieldOrDatumDef && fieldOrDatumDef['scale'];\n if (fieldOrDatumDef && specifiedScale !== null && specifiedScale !== false) {\n specifiedScale !== null && specifiedScale !== void 0 ? specifiedScale : (specifiedScale = {});\n const sType = scaleType(specifiedScale, channel, fieldOrDatumDef, markDef);\n scaleComponents[channel] = new ScaleComponent(model.scaleName(`${channel}`, true), {\n value: sType,\n explicit: specifiedScale.type === sType\n });\n }\n return scaleComponents;\n }, {});\n}\nconst scaleTypeTieBreaker = tieBreakByComparing((st1, st2) => scaleTypePrecedence(st1) - scaleTypePrecedence(st2));\nfunction parseNonUnitScaleCore(model) {\n var _a;\n var _b;\n const scaleComponents = (model.component.scales = {});\n const scaleTypeWithExplicitIndex = {};\n const resolve = model.component.resolve;\n // Parse each child scale and determine if a particular channel can be merged.\n for (const child of model.children) {\n parseScaleCore(child);\n // Instead of always merging right away -- check if it is compatible to merge first!\n for (const channel of keys(child.component.scales)) {\n // if resolve is undefined, set default first\n (_a = (_b = resolve.scale)[channel]) !== null && _a !== void 0 ? _a : (_b[channel] = defaultScaleResolve(channel, model));\n if (resolve.scale[channel] === 'shared') {\n const explicitScaleType = scaleTypeWithExplicitIndex[channel];\n const childScaleType = child.component.scales[channel].getWithExplicit('type');\n if (explicitScaleType) {\n if (scaleCompatible(explicitScaleType.value, childScaleType.value)) {\n // merge scale component if type are compatible\n scaleTypeWithExplicitIndex[channel] = mergeValuesWithExplicit(explicitScaleType, childScaleType, 'type', 'scale', scaleTypeTieBreaker);\n }\n else {\n // Otherwise, update conflicting channel to be independent\n resolve.scale[channel] = 'independent';\n // Remove from the index so they don't get merged\n delete scaleTypeWithExplicitIndex[channel];\n }\n }\n else {\n scaleTypeWithExplicitIndex[channel] = childScaleType;\n }\n }\n }\n }\n // Merge each channel listed in the index\n for (const channel of keys(scaleTypeWithExplicitIndex)) {\n // Create new merged scale component\n const name = model.scaleName(channel, true);\n const typeWithExplicit = scaleTypeWithExplicitIndex[channel];\n scaleComponents[channel] = new ScaleComponent(name, typeWithExplicit);\n // rename each child and mark them as merged\n for (const child of model.children) {\n const childScale = child.component.scales[channel];\n if (childScale) {\n child.renameScale(childScale.get('name'), name);\n childScale.merged = true;\n }\n }\n }\n return scaleComponents;\n}\n//# sourceMappingURL=parse.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { FACET_CHANNELS, getPositionScaleChannel, isChannel, isScaleChannel } from '../channel';\nimport { getFieldDef, vgField } from '../channeldef';\nimport { DataSourceType } from '../data';\nimport { forEach, reduce } from '../encoding';\nimport { replaceExprRef } from '../expr';\nimport * as log from '../log';\nimport { hasDiscreteDomain } from '../scale';\nimport { isFacetSpec } from '../spec';\nimport { extractCompositionLayout } from '../spec/base';\nimport { extractTitleConfig, isText } from '../title';\nimport { normalizeTransform } from '../transform';\nimport { contains, duplicate, isEmpty, keys, varName } from '../util';\nimport { isVgRangeStep } from '../vega.schema';\nimport { assembleAxes } from './axis/assemble';\nimport { signalOrValueRef } from './common';\nimport { assembleHeaderGroups, assembleLayoutTitleBand, assembleTitleGroup } from './header/assemble';\nimport { HEADER_CHANNELS } from './header/component';\nimport { sizeExpr } from './layoutsize/assemble';\nimport { getSizeTypeFromLayoutSizeType } from './layoutsize/component';\nimport { assembleLegends } from './legend/assemble';\nimport { parseLegend } from './legend/parse';\nimport { assembleProjections } from './projection/assemble';\nimport { parseProjection } from './projection/parse';\nimport { assembleScales } from './scale/assemble';\nimport { assembleDomain, getFieldFromDomain } from './scale/domain';\nimport { parseScales } from './scale/parse';\nimport { Split } from './split';\nexport class NameMap {\n constructor() {\n this.nameMap = {};\n }\n rename(oldName, newName) {\n this.nameMap[oldName] = newName;\n }\n has(name) {\n return this.nameMap[name] !== undefined;\n }\n get(name) {\n // If the name appears in the _nameMap, we need to read its new name.\n // We have to loop over the dict just in case the new name also gets renamed.\n while (this.nameMap[name] && name !== this.nameMap[name]) {\n name = this.nameMap[name];\n }\n return name;\n }\n}\n/*\n We use type guards instead of `instanceof` as `instanceof` makes\n different parts of the compiler depend on the actual implementation of\n the model classes, which in turn depend on different parts of the compiler.\n Thus, `instanceof` leads to circular dependency problems.\n\n On the other hand, type guards only make different parts of the compiler\n depend on the type of the model classes, but not the actual implementation.\n*/\nexport function isUnitModel(model) {\n return (model === null || model === void 0 ? void 0 : model.type) === 'unit';\n}\nexport function isFacetModel(model) {\n return (model === null || model === void 0 ? void 0 : model.type) === 'facet';\n}\nexport function isConcatModel(model) {\n return (model === null || model === void 0 ? void 0 : model.type) === 'concat';\n}\nexport function isLayerModel(model) {\n return (model === null || model === void 0 ? void 0 : model.type) === 'layer';\n}\nexport class Model {\n constructor(spec, type, parent, parentGivenName, config, resolve, view) {\n var _a, _b;\n this.type = type;\n this.parent = parent;\n this.config = config;\n /**\n * Corrects the data references in marks after assemble.\n */\n this.correctDataNames = (mark) => {\n // TODO: make this correct\n var _a, _b, _c;\n // for normal data references\n if ((_a = mark.from) === null || _a === void 0 ? void 0 : _a.data) {\n mark.from.data = this.lookupDataSource(mark.from.data);\n }\n // for access to facet data\n if ((_c = (_b = mark.from) === null || _b === void 0 ? void 0 : _b.facet) === null || _c === void 0 ? void 0 : _c.data) {\n mark.from.facet.data = this.lookupDataSource(mark.from.facet.data);\n }\n return mark;\n };\n this.parent = parent;\n this.config = config;\n this.view = replaceExprRef(view);\n // If name is not provided, always use parent's givenName to avoid name conflicts.\n this.name = (_a = spec.name) !== null && _a !== void 0 ? _a : parentGivenName;\n this.title = isText(spec.title) ? { text: spec.title } : spec.title ? replaceExprRef(spec.title) : undefined;\n // Shared name maps\n this.scaleNameMap = parent ? parent.scaleNameMap : new NameMap();\n this.projectionNameMap = parent ? parent.projectionNameMap : new NameMap();\n this.signalNameMap = parent ? parent.signalNameMap : new NameMap();\n this.data = spec.data;\n this.description = spec.description;\n this.transforms = normalizeTransform((_b = spec.transform) !== null && _b !== void 0 ? _b : []);\n this.layout = type === 'layer' || type === 'unit' ? {} : extractCompositionLayout(spec, type, config);\n this.component = {\n data: {\n sources: parent ? parent.component.data.sources : [],\n outputNodes: parent ? parent.component.data.outputNodes : {},\n outputNodeRefCounts: parent ? parent.component.data.outputNodeRefCounts : {},\n // data is faceted if the spec is a facet spec or the parent has faceted data and data is undefined\n isFaceted: isFacetSpec(spec) || (parent && parent.component.data.isFaceted && spec.data === undefined)\n },\n layoutSize: new Split(),\n layoutHeaders: { row: {}, column: {}, facet: {} },\n mark: null,\n resolve: Object.assign({ scale: {}, axis: {}, legend: {} }, (resolve ? duplicate(resolve) : {})),\n selection: null,\n scales: null,\n projection: null,\n axes: {},\n legends: {}\n };\n }\n get width() {\n return this.getSizeSignalRef('width');\n }\n get height() {\n return this.getSizeSignalRef('height');\n }\n parse() {\n this.parseScale();\n this.parseLayoutSize(); // depends on scale\n this.renameTopLevelLayoutSizeSignal();\n this.parseSelections();\n this.parseProjection();\n this.parseData(); // (pathorder) depends on markDef; selection filters depend on parsed selections; depends on projection because some transforms require the finalized projection name.\n this.parseAxesAndHeaders(); // depends on scale and layout size\n this.parseLegends(); // depends on scale, markDef\n this.parseMarkGroup(); // depends on data name, scale, layout size, axisGroup, and children's scale, axis, legend and mark.\n }\n parseScale() {\n parseScales(this);\n }\n parseProjection() {\n parseProjection(this);\n }\n /**\n * Rename top-level spec's size to be just width / height, ignoring model name.\n * This essentially merges the top-level spec's width/height signals with the width/height signals\n * to help us reduce redundant signals declaration.\n */\n renameTopLevelLayoutSizeSignal() {\n if (this.getName('width') !== 'width') {\n this.renameSignal(this.getName('width'), 'width');\n }\n if (this.getName('height') !== 'height') {\n this.renameSignal(this.getName('height'), 'height');\n }\n }\n parseLegends() {\n parseLegend(this);\n }\n assembleEncodeFromView(view) {\n // Exclude \"style\"\n const { style: _ } = view, baseView = __rest(view, [\"style\"]);\n const e = {};\n for (const property of keys(baseView)) {\n const value = baseView[property];\n if (value !== undefined) {\n e[property] = signalOrValueRef(value);\n }\n }\n return e;\n }\n assembleGroupEncodeEntry(isTopLevel) {\n let encodeEntry = {};\n if (this.view) {\n encodeEntry = this.assembleEncodeFromView(this.view);\n }\n if (!isTopLevel) {\n // Descriptions are already added to the top-level description so we only need to add them to the inner views.\n if (this.description) {\n encodeEntry['description'] = signalOrValueRef(this.description);\n }\n // For top-level spec, we can set the global width and height signal to adjust the group size.\n // For other child specs, we have to manually set width and height in the encode entry.\n if (this.type === 'unit' || this.type === 'layer') {\n return Object.assign({ width: this.getSizeSignalRef('width'), height: this.getSizeSignalRef('height') }, (encodeEntry !== null && encodeEntry !== void 0 ? encodeEntry : {}));\n }\n }\n return isEmpty(encodeEntry) ? undefined : encodeEntry;\n }\n assembleLayout() {\n if (!this.layout) {\n return undefined;\n }\n const _a = this.layout, { spacing } = _a, layout = __rest(_a, [\"spacing\"]);\n const { component, config } = this;\n const titleBand = assembleLayoutTitleBand(component.layoutHeaders, config);\n return Object.assign(Object.assign(Object.assign({ padding: spacing }, this.assembleDefaultLayout()), layout), (titleBand ? { titleBand } : {}));\n }\n assembleDefaultLayout() {\n return {};\n }\n assembleHeaderMarks() {\n const { layoutHeaders } = this.component;\n let headerMarks = [];\n for (const channel of FACET_CHANNELS) {\n if (layoutHeaders[channel].title) {\n headerMarks.push(assembleTitleGroup(this, channel));\n }\n }\n for (const channel of HEADER_CHANNELS) {\n headerMarks = headerMarks.concat(assembleHeaderGroups(this, channel));\n }\n return headerMarks;\n }\n assembleAxes() {\n return assembleAxes(this.component.axes, this.config);\n }\n assembleLegends() {\n return assembleLegends(this);\n }\n assembleProjections() {\n return assembleProjections(this);\n }\n assembleTitle() {\n var _a, _b, _c;\n const _d = (_a = this.title) !== null && _a !== void 0 ? _a : {}, { encoding } = _d, titleNoEncoding = __rest(_d, [\"encoding\"]);\n const title = Object.assign(Object.assign(Object.assign({}, extractTitleConfig(this.config.title).nonMarkTitleProperties), titleNoEncoding), (encoding ? { encode: { update: encoding } } : {}));\n if (title.text) {\n if (contains(['unit', 'layer'], this.type)) {\n // Unit/Layer\n if (contains(['middle', undefined], title.anchor)) {\n (_b = title.frame) !== null && _b !== void 0 ? _b : (title.frame = 'group');\n }\n }\n else {\n // composition with Vega layout\n // Set title = \"start\" by default for composition as \"middle\" does not look nice\n // https://github.com/vega/vega/issues/960#issuecomment-471360328\n (_c = title.anchor) !== null && _c !== void 0 ? _c : (title.anchor = 'start');\n }\n return isEmpty(title) ? undefined : title;\n }\n return undefined;\n }\n /**\n * Assemble the mark group for this model. We accept optional `signals` so that we can include concat top-level signals with the top-level model's local signals.\n */\n assembleGroup(signals = []) {\n const group = {};\n signals = signals.concat(this.assembleSignals());\n if (signals.length > 0) {\n group.signals = signals;\n }\n const layout = this.assembleLayout();\n if (layout) {\n group.layout = layout;\n }\n group.marks = [].concat(this.assembleHeaderMarks(), this.assembleMarks());\n // Only include scales if this spec is top-level or if parent is facet.\n // (Otherwise, it will be merged with upper-level's scope.)\n const scales = !this.parent || isFacetModel(this.parent) ? assembleScales(this) : [];\n if (scales.length > 0) {\n group.scales = scales;\n }\n const axes = this.assembleAxes();\n if (axes.length > 0) {\n group.axes = axes;\n }\n const legends = this.assembleLegends();\n if (legends.length > 0) {\n group.legends = legends;\n }\n return group;\n }\n getName(text) {\n return varName((this.name ? `${this.name}_` : '') + text);\n }\n getDataName(type) {\n return this.getName(DataSourceType[type].toLowerCase());\n }\n /**\n * Request a data source name for the given data source type and mark that data source as required.\n * This method should be called in parse, so that all used data source can be correctly instantiated in assembleData().\n * You can lookup the correct dataset name in assemble with `lookupDataSource`.\n */\n requestDataName(name) {\n const fullName = this.getDataName(name);\n // Increase ref count. This is critical because otherwise we won't create a data source.\n // We also increase the ref counts on OutputNode.getSource() calls.\n const refCounts = this.component.data.outputNodeRefCounts;\n refCounts[fullName] = (refCounts[fullName] || 0) + 1;\n return fullName;\n }\n getSizeSignalRef(layoutSizeType) {\n if (isFacetModel(this.parent)) {\n const sizeType = getSizeTypeFromLayoutSizeType(layoutSizeType);\n const channel = getPositionScaleChannel(sizeType);\n const scaleComponent = this.component.scales[channel];\n if (scaleComponent && !scaleComponent.merged) {\n // independent scale\n const type = scaleComponent.get('type');\n const range = scaleComponent.get('range');\n if (hasDiscreteDomain(type) && isVgRangeStep(range)) {\n const scaleName = scaleComponent.get('name');\n const domain = assembleDomain(this, channel);\n const field = getFieldFromDomain(domain);\n if (field) {\n const fieldRef = vgField({ aggregate: 'distinct', field }, { expr: 'datum' });\n return {\n signal: sizeExpr(scaleName, scaleComponent, fieldRef)\n };\n }\n else {\n log.warn(log.message.unknownField(channel));\n return null;\n }\n }\n }\n }\n return {\n signal: this.signalNameMap.get(this.getName(layoutSizeType))\n };\n }\n /**\n * Lookup the name of the datasource for an output node. You probably want to call this in assemble.\n */\n lookupDataSource(name) {\n const node = this.component.data.outputNodes[name];\n if (!node) {\n // Name not found in map so let's just return what we got.\n // This can happen if we already have the correct name.\n return name;\n }\n return node.getSource();\n }\n getSignalName(oldSignalName) {\n return this.signalNameMap.get(oldSignalName);\n }\n renameSignal(oldName, newName) {\n this.signalNameMap.rename(oldName, newName);\n }\n renameScale(oldName, newName) {\n this.scaleNameMap.rename(oldName, newName);\n }\n renameProjection(oldName, newName) {\n this.projectionNameMap.rename(oldName, newName);\n }\n /**\n * @return scale name for a given channel after the scale has been parsed and named.\n */\n scaleName(originalScaleName, parse) {\n if (parse) {\n // During the parse phase always return a value\n // No need to refer to rename map because a scale can't be renamed\n // before it has the original name.\n return this.getName(originalScaleName);\n }\n // If there is a scale for the channel, it should either\n // be in the scale component or exist in the name map\n if (\n // If there is a scale for the channel, there should be a local scale component for it\n (isChannel(originalScaleName) && isScaleChannel(originalScaleName) && this.component.scales[originalScaleName]) ||\n // in the scale name map (the scale get merged by its parent)\n this.scaleNameMap.has(this.getName(originalScaleName))) {\n return this.scaleNameMap.get(this.getName(originalScaleName));\n }\n return undefined;\n }\n /**\n * @return projection name after the projection has been parsed and named.\n */\n projectionName(parse) {\n if (parse) {\n // During the parse phase always return a value\n // No need to refer to rename map because a projection can't be renamed\n // before it has the original name.\n return this.getName('projection');\n }\n if ((this.component.projection && !this.component.projection.merged) ||\n this.projectionNameMap.has(this.getName('projection'))) {\n return this.projectionNameMap.get(this.getName('projection'));\n }\n return undefined;\n }\n /**\n * Traverse a model's hierarchy to get the scale component for a particular channel.\n */\n getScaleComponent(channel) {\n /* istanbul ignore next: This is warning for debugging test */\n if (!this.component.scales) {\n throw new Error('getScaleComponent cannot be called before parseScale(). Make sure you have called parseScale or use parseUnitModelWithScale().');\n }\n const localScaleComponent = this.component.scales[channel];\n if (localScaleComponent && !localScaleComponent.merged) {\n return localScaleComponent;\n }\n return this.parent ? this.parent.getScaleComponent(channel) : undefined;\n }\n /**\n * Traverse a model's hierarchy to get a particular selection component.\n */\n getSelectionComponent(variableName, origName) {\n let sel = this.component.selection[variableName];\n if (!sel && this.parent) {\n sel = this.parent.getSelectionComponent(variableName, origName);\n }\n if (!sel) {\n throw new Error(log.message.selectionNotFound(origName));\n }\n return sel;\n }\n /**\n * Returns true if the model has a signalRef for an axis orient.\n */\n hasAxisOrientSignalRef() {\n var _a, _b;\n return (((_a = this.component.axes.x) === null || _a === void 0 ? void 0 : _a.some(a => a.hasOrientSignalRef())) ||\n ((_b = this.component.axes.y) === null || _b === void 0 ? void 0 : _b.some(a => a.hasOrientSignalRef())));\n }\n}\n/** Abstract class for UnitModel and FacetModel. Both of which can contain fieldDefs as a part of its own specification. */\nexport class ModelWithField extends Model {\n /** Get \"field\" reference for Vega */\n vgField(channel, opt = {}) {\n const fieldDef = this.fieldDef(channel);\n if (!fieldDef) {\n return undefined;\n }\n return vgField(fieldDef, opt);\n }\n reduceFieldDef(f, init) {\n return reduce(this.getMapping(), (acc, cd, c) => {\n const fieldDef = getFieldDef(cd);\n if (fieldDef) {\n return f(acc, fieldDef, c);\n }\n return acc;\n }, init);\n }\n forEachFieldDef(f, t) {\n forEach(this.getMapping(), (cd, c) => {\n const fieldDef = getFieldDef(cd);\n if (fieldDef) {\n f(fieldDef, c);\n }\n }, t);\n }\n}\n//# sourceMappingURL=model.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for density transform nodes\n */\nexport class DensityTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n var _a, _b, _c;\n super(parent);\n this.transform = transform;\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = (_a = this.transform.as) !== null && _a !== void 0 ? _a : [undefined, undefined];\n this.transform.as = [(_b = specifiedAs[0]) !== null && _b !== void 0 ? _b : 'value', (_c = specifiedAs[1]) !== null && _c !== void 0 ? _c : 'density'];\n }\n clone() {\n return new DensityTransformNode(null, duplicate(this.transform));\n }\n dependentFields() {\n var _a;\n return new Set([this.transform.density, ...((_a = this.transform.groupby) !== null && _a !== void 0 ? _a : [])]);\n }\n producedFields() {\n return new Set(this.transform.as);\n }\n hash() {\n return `DensityTransform ${hash(this.transform)}`;\n }\n assemble() {\n const _a = this.transform, { density } = _a, rest = __rest(_a, [\"density\"]);\n const result = Object.assign({ type: 'kde', field: density }, rest);\n return result;\n }\n}\n//# sourceMappingURL=density.js.map","import { isScaleChannel } from '../../channel';\nimport { vgField as fieldRef } from '../../channeldef';\nimport { isPathMark } from '../../mark';\nimport { hasContinuousDomain } from '../../scale';\nimport { hash, keys } from '../../util';\nimport { getMarkPropOrConfig } from '../common';\nimport { DataFlowNode } from './dataflow';\nexport class FilterInvalidNode extends DataFlowNode {\n constructor(parent, filter) {\n super(parent);\n this.filter = filter;\n }\n clone() {\n return new FilterInvalidNode(null, Object.assign({}, this.filter));\n }\n static make(parent, model) {\n const { config, mark, markDef } = model;\n const invalid = getMarkPropOrConfig('invalid', markDef, config);\n if (invalid !== 'filter') {\n return null;\n }\n const filter = model.reduceFieldDef((aggregator, fieldDef, channel) => {\n const scaleComponent = isScaleChannel(channel) && model.getScaleComponent(channel);\n if (scaleComponent) {\n const scaleType = scaleComponent.get('type');\n // While discrete domain scales can handle invalid values, continuous scales can't.\n // Thus, for non-path marks, we have to filter null for scales with continuous domains.\n // (For path marks, we will use \"defined\" property and skip these values instead.)\n if (hasContinuousDomain(scaleType) && fieldDef.aggregate !== 'count' && !isPathMark(mark)) {\n aggregator[fieldDef.field] = fieldDef; // we know that the fieldDef is a typed field def\n }\n }\n return aggregator;\n }, {});\n if (!keys(filter).length) {\n return null;\n }\n return new FilterInvalidNode(parent, filter);\n }\n dependentFields() {\n return new Set(keys(this.filter));\n }\n producedFields() {\n return new Set(); // filter does not produce any new fields\n }\n hash() {\n return `FilterInvalid ${hash(this.filter)}`;\n }\n /**\n * Create the VgTransforms for each of the filtered fields.\n */\n assemble() {\n const filters = keys(this.filter).reduce((vegaFilters, field) => {\n const fieldDef = this.filter[field];\n const ref = fieldRef(fieldDef, { expr: 'datum' });\n if (fieldDef !== null) {\n if (fieldDef.type === 'temporal') {\n vegaFilters.push(`(isDate(${ref}) || (isValid(${ref}) && isFinite(+${ref})))`);\n }\n else if (fieldDef.type === 'quantitative') {\n vegaFilters.push(`isValid(${ref})`);\n vegaFilters.push(`isFinite(+${ref})`);\n }\n else {\n // should never get here\n }\n }\n return vegaFilters;\n }, []);\n return filters.length > 0\n ? {\n type: 'filter',\n expr: filters.join(' && ')\n }\n : null;\n }\n}\n//# sourceMappingURL=filterinvalid.js.map","import { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for flatten transform nodes\n */\nexport class FlattenTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n super(parent);\n this.transform = transform;\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const { flatten, as = [] } = this.transform;\n this.transform.as = flatten.map((f, i) => { var _a; return (_a = as[i]) !== null && _a !== void 0 ? _a : f; });\n }\n clone() {\n return new FlattenTransformNode(this.parent, duplicate(this.transform));\n }\n dependentFields() {\n return new Set(this.transform.flatten);\n }\n producedFields() {\n return new Set(this.transform.as);\n }\n hash() {\n return `FlattenTransform ${hash(this.transform)}`;\n }\n assemble() {\n const { flatten: fields, as } = this.transform;\n const result = {\n type: 'flatten',\n fields,\n as\n };\n return result;\n }\n}\n//# sourceMappingURL=flatten.js.map","import { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for flatten transform nodes\n */\nexport class FoldTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n var _a, _b, _c;\n super(parent);\n this.transform = transform;\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = (_a = this.transform.as) !== null && _a !== void 0 ? _a : [undefined, undefined];\n this.transform.as = [(_b = specifiedAs[0]) !== null && _b !== void 0 ? _b : 'key', (_c = specifiedAs[1]) !== null && _c !== void 0 ? _c : 'value'];\n }\n clone() {\n return new FoldTransformNode(null, duplicate(this.transform));\n }\n dependentFields() {\n return new Set(this.transform.fold);\n }\n producedFields() {\n return new Set(this.transform.as);\n }\n hash() {\n return `FoldTransform ${hash(this.transform)}`;\n }\n assemble() {\n const { fold, as } = this.transform;\n const result = {\n type: 'fold',\n fields: fold,\n as\n };\n return result;\n }\n}\n//# sourceMappingURL=fold.js.map","import { isString } from 'vega-util';\nimport { LATITUDE, LATITUDE2, LONGITUDE, LONGITUDE2, SHAPE } from '../../channel';\nimport { getFieldOrDatumDef, isDatumDef, isFieldDef, isValueDef } from '../../channeldef';\nimport { GEOJSON } from '../../type';\nimport { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\nexport class GeoJSONNode extends DataFlowNode {\n constructor(parent, fields, geojson, signal) {\n super(parent);\n this.fields = fields;\n this.geojson = geojson;\n this.signal = signal;\n }\n clone() {\n return new GeoJSONNode(null, duplicate(this.fields), this.geojson, this.signal);\n }\n static parseAll(parent, model) {\n if (model.component.projection && !model.component.projection.isFit) {\n return parent;\n }\n let geoJsonCounter = 0;\n for (const coordinates of [\n [LONGITUDE, LATITUDE],\n [LONGITUDE2, LATITUDE2]\n ]) {\n const pair = coordinates.map(channel => {\n const def = getFieldOrDatumDef(model.encoding[channel]);\n return isFieldDef(def)\n ? def.field\n : isDatumDef(def)\n ? { expr: `${def.datum}` }\n : isValueDef(def)\n ? { expr: `${def['value']}` }\n : undefined;\n });\n if (pair[0] || pair[1]) {\n parent = new GeoJSONNode(parent, pair, null, model.getName(`geojson_${geoJsonCounter++}`));\n }\n }\n if (model.channelHasField(SHAPE)) {\n const fieldDef = model.typedFieldDef(SHAPE);\n if (fieldDef.type === GEOJSON) {\n parent = new GeoJSONNode(parent, null, fieldDef.field, model.getName(`geojson_${geoJsonCounter++}`));\n }\n }\n return parent;\n }\n dependentFields() {\n var _a;\n const fields = ((_a = this.fields) !== null && _a !== void 0 ? _a : []).filter(isString);\n return new Set([...(this.geojson ? [this.geojson] : []), ...fields]);\n }\n producedFields() {\n return new Set();\n }\n hash() {\n return `GeoJSON ${this.geojson} ${this.signal} ${hash(this.fields)}`;\n }\n assemble() {\n return [\n ...(this.geojson\n ? [\n {\n type: 'filter',\n expr: `isValid(datum[\"${this.geojson}\"])`\n }\n ]\n : []),\n Object.assign(Object.assign(Object.assign({ type: 'geojson' }, (this.fields ? { fields: this.fields } : {})), (this.geojson ? { geojson: this.geojson } : {})), { signal: this.signal })\n ];\n }\n}\n//# sourceMappingURL=geojson.js.map","import { isString } from 'vega-util';\nimport { LATITUDE, LATITUDE2, LONGITUDE, LONGITUDE2 } from '../../channel';\nimport { getFieldOrDatumDef, isDatumDef, isFieldDef, isValueDef } from '../../channeldef';\nimport { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\nexport class GeoPointNode extends DataFlowNode {\n constructor(parent, projection, fields, as) {\n super(parent);\n this.projection = projection;\n this.fields = fields;\n this.as = as;\n }\n clone() {\n return new GeoPointNode(null, this.projection, duplicate(this.fields), duplicate(this.as));\n }\n static parseAll(parent, model) {\n if (!model.projectionName()) {\n return parent;\n }\n for (const coordinates of [\n [LONGITUDE, LATITUDE],\n [LONGITUDE2, LATITUDE2]\n ]) {\n const pair = coordinates.map(channel => {\n const def = getFieldOrDatumDef(model.encoding[channel]);\n return isFieldDef(def)\n ? def.field\n : isDatumDef(def)\n ? { expr: `${def.datum}` }\n : isValueDef(def)\n ? { expr: `${def['value']}` }\n : undefined;\n });\n const suffix = coordinates[0] === LONGITUDE2 ? '2' : '';\n if (pair[0] || pair[1]) {\n parent = new GeoPointNode(parent, model.projectionName(), pair, [\n model.getName(`x${suffix}`),\n model.getName(`y${suffix}`)\n ]);\n }\n }\n return parent;\n }\n dependentFields() {\n return new Set(this.fields.filter(isString));\n }\n producedFields() {\n return new Set(this.as);\n }\n hash() {\n return `Geopoint ${this.projection} ${hash(this.fields)} ${hash(this.as)}`;\n }\n assemble() {\n return {\n type: 'geopoint',\n projection: this.projection,\n fields: this.fields,\n as: this.as\n };\n }\n}\n//# sourceMappingURL=geopoint.js.map","import { isFieldDef } from '../../channeldef';\nimport { pathGroupingFields } from '../../encoding';\nimport { isImputeSequence } from '../../transform';\nimport { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\nexport class ImputeNode extends DataFlowNode {\n constructor(parent, transform) {\n super(parent);\n this.transform = transform;\n }\n clone() {\n return new ImputeNode(null, duplicate(this.transform));\n }\n dependentFields() {\n var _a;\n return new Set([this.transform.impute, this.transform.key, ...((_a = this.transform.groupby) !== null && _a !== void 0 ? _a : [])]);\n }\n producedFields() {\n return new Set([this.transform.impute]);\n }\n processSequence(keyvals) {\n const { start = 0, stop, step } = keyvals;\n const result = [start, stop, ...(step ? [step] : [])].join(',');\n return { signal: `sequence(${result})` };\n }\n static makeFromTransform(parent, imputeTransform) {\n return new ImputeNode(parent, imputeTransform);\n }\n static makeFromEncoding(parent, model) {\n const encoding = model.encoding;\n const xDef = encoding.x;\n const yDef = encoding.y;\n if (isFieldDef(xDef) && isFieldDef(yDef)) {\n const imputedChannel = xDef.impute ? xDef : yDef.impute ? yDef : undefined;\n if (imputedChannel === undefined) {\n return undefined;\n }\n const keyChannel = xDef.impute ? yDef : yDef.impute ? xDef : undefined;\n const { method, value, frame, keyvals } = imputedChannel.impute;\n const groupbyFields = pathGroupingFields(model.mark, encoding);\n return new ImputeNode(parent, Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ impute: imputedChannel.field, key: keyChannel.field }, (method ? { method } : {})), (value !== undefined ? { value } : {})), (frame ? { frame } : {})), (keyvals !== undefined ? { keyvals } : {})), (groupbyFields.length ? { groupby: groupbyFields } : {})));\n }\n return null;\n }\n hash() {\n return `Impute ${hash(this.transform)}`;\n }\n assemble() {\n const { impute, key, keyvals, method, groupby, value, frame = [null, null] } = this.transform;\n const imputeTransform = Object.assign(Object.assign(Object.assign(Object.assign({ type: 'impute', field: impute, key }, (keyvals ? { keyvals: isImputeSequence(keyvals) ? this.processSequence(keyvals) : keyvals } : {})), { method: 'value' }), (groupby ? { groupby } : {})), { value: !method || method === 'value' ? value : null });\n if (method && method !== 'value') {\n const deriveNewField = Object.assign({ type: 'window', as: [`imputed_${impute}_value`], ops: [method], fields: [impute], frame, ignorePeers: false }, (groupby ? { groupby } : {}));\n const replaceOriginal = {\n type: 'formula',\n expr: `datum.${impute} === null ? datum.imputed_${impute}_value : datum.${impute}`,\n as: impute\n };\n return [imputeTransform, deriveNewField, replaceOriginal];\n }\n else {\n return [imputeTransform];\n }\n }\n}\n//# sourceMappingURL=impute.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for loess transform nodes\n */\nexport class LoessTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n var _a, _b, _c;\n super(parent);\n this.transform = transform;\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = (_a = this.transform.as) !== null && _a !== void 0 ? _a : [undefined, undefined];\n this.transform.as = [(_b = specifiedAs[0]) !== null && _b !== void 0 ? _b : transform.on, (_c = specifiedAs[1]) !== null && _c !== void 0 ? _c : transform.loess];\n }\n clone() {\n return new LoessTransformNode(null, duplicate(this.transform));\n }\n dependentFields() {\n var _a;\n return new Set([this.transform.loess, this.transform.on, ...((_a = this.transform.groupby) !== null && _a !== void 0 ? _a : [])]);\n }\n producedFields() {\n return new Set(this.transform.as);\n }\n hash() {\n return `LoessTransform ${hash(this.transform)}`;\n }\n assemble() {\n const _a = this.transform, { loess, on } = _a, rest = __rest(_a, [\"loess\", \"on\"]);\n const result = Object.assign({ type: 'loess', x: on, y: loess }, rest);\n return result;\n }\n}\n//# sourceMappingURL=loess.js.map","import { array, isString } from 'vega-util';\nimport * as log from '../../log';\nimport { isLookupData, isLookupSelection } from '../../transform';\nimport { duplicate, hash, varName } from '../../util';\nimport { DataFlowNode, OutputNode } from './dataflow';\nimport { findSource } from './parse';\nimport { SourceNode } from './source';\nimport { DataSourceType } from '../../data';\nexport class LookupNode extends DataFlowNode {\n constructor(parent, transform, secondary) {\n super(parent);\n this.transform = transform;\n this.secondary = secondary;\n }\n clone() {\n return new LookupNode(null, duplicate(this.transform), this.secondary);\n }\n static make(parent, model, transform, counter) {\n const sources = model.component.data.sources;\n const { from } = transform;\n let fromOutputNode = null;\n if (isLookupData(from)) {\n let fromSource = findSource(from.data, sources);\n if (!fromSource) {\n fromSource = new SourceNode(from.data);\n sources.push(fromSource);\n }\n const fromOutputName = model.getName(`lookup_${counter}`);\n fromOutputNode = new OutputNode(fromSource, fromOutputName, DataSourceType.Lookup, model.component.data.outputNodeRefCounts);\n model.component.data.outputNodes[fromOutputName] = fromOutputNode;\n }\n else if (isLookupSelection(from)) {\n const selName = from.param;\n transform = Object.assign({ as: selName }, transform);\n let selCmpt;\n try {\n selCmpt = model.getSelectionComponent(varName(selName), selName);\n }\n catch (e) {\n throw new Error(log.message.cannotLookupVariableParameter(selName));\n }\n fromOutputNode = selCmpt.materialized;\n if (!fromOutputNode) {\n throw new Error(log.message.noSameUnitLookup(selName));\n }\n }\n return new LookupNode(parent, transform, fromOutputNode.getSource());\n }\n dependentFields() {\n return new Set([this.transform.lookup]);\n }\n producedFields() {\n return new Set(this.transform.as ? array(this.transform.as) : this.transform.from.fields);\n }\n hash() {\n return `Lookup ${hash({ transform: this.transform, secondary: this.secondary })}`;\n }\n assemble() {\n let foreign;\n if (this.transform.from.fields) {\n // lookup a few fields and add create a flat output\n foreign = Object.assign({ values: this.transform.from.fields }, (this.transform.as ? { as: array(this.transform.as) } : {}));\n }\n else {\n // lookup full record and nest it\n let asName = this.transform.as;\n if (!isString(asName)) {\n log.warn(log.message.NO_FIELDS_NEEDS_AS);\n asName = '_lookup';\n }\n foreign = {\n as: [asName]\n };\n }\n return Object.assign(Object.assign({ type: 'lookup', from: this.secondary, key: this.transform.from.key, fields: [this.transform.lookup] }, foreign), (this.transform.default ? { default: this.transform.default } : {}));\n }\n}\n//# sourceMappingURL=lookup.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for quantile transform nodes\n */\nexport class QuantileTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n var _a, _b, _c;\n super(parent);\n this.transform = transform;\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = (_a = this.transform.as) !== null && _a !== void 0 ? _a : [undefined, undefined];\n this.transform.as = [(_b = specifiedAs[0]) !== null && _b !== void 0 ? _b : 'prob', (_c = specifiedAs[1]) !== null && _c !== void 0 ? _c : 'value'];\n }\n clone() {\n return new QuantileTransformNode(null, duplicate(this.transform));\n }\n dependentFields() {\n var _a;\n return new Set([this.transform.quantile, ...((_a = this.transform.groupby) !== null && _a !== void 0 ? _a : [])]);\n }\n producedFields() {\n return new Set(this.transform.as);\n }\n hash() {\n return `QuantileTransform ${hash(this.transform)}`;\n }\n assemble() {\n const _a = this.transform, { quantile } = _a, rest = __rest(_a, [\"quantile\"]);\n const result = Object.assign({ type: 'quantile', field: quantile }, rest);\n return result;\n }\n}\n//# sourceMappingURL=quantile.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for regression transform nodes\n */\nexport class RegressionTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n var _a, _b, _c;\n super(parent);\n this.transform = transform;\n this.transform = duplicate(transform); // duplicate to prevent side effects\n const specifiedAs = (_a = this.transform.as) !== null && _a !== void 0 ? _a : [undefined, undefined];\n this.transform.as = [(_b = specifiedAs[0]) !== null && _b !== void 0 ? _b : transform.on, (_c = specifiedAs[1]) !== null && _c !== void 0 ? _c : transform.regression];\n }\n clone() {\n return new RegressionTransformNode(null, duplicate(this.transform));\n }\n dependentFields() {\n var _a;\n return new Set([this.transform.regression, this.transform.on, ...((_a = this.transform.groupby) !== null && _a !== void 0 ? _a : [])]);\n }\n producedFields() {\n return new Set(this.transform.as);\n }\n hash() {\n return `RegressionTransform ${hash(this.transform)}`;\n }\n assemble() {\n const _a = this.transform, { regression, on } = _a, rest = __rest(_a, [\"regression\", \"on\"]);\n const result = Object.assign({ type: 'regression', x: on, y: regression }, rest);\n return result;\n }\n}\n//# sourceMappingURL=regression.js.map","import { duplicate, hash, unique } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for pivot transform nodes.\n */\nexport class PivotTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n super(parent);\n this.transform = transform;\n }\n clone() {\n return new PivotTransformNode(null, duplicate(this.transform));\n }\n addDimensions(fields) {\n var _a;\n this.transform.groupby = unique(((_a = this.transform.groupby) !== null && _a !== void 0 ? _a : []).concat(fields), d => d);\n }\n producedFields() {\n return undefined; // return undefined so that potentially everything can depend on the pivot\n }\n dependentFields() {\n var _a;\n return new Set([this.transform.pivot, this.transform.value, ...((_a = this.transform.groupby) !== null && _a !== void 0 ? _a : [])]);\n }\n hash() {\n return `PivotTransform ${hash(this.transform)}`;\n }\n assemble() {\n const { pivot, value, groupby, limit, op } = this.transform;\n return Object.assign(Object.assign(Object.assign({ type: 'pivot', field: pivot, value }, (limit !== undefined ? { limit } : {})), (op !== undefined ? { op } : {})), (groupby !== undefined ? { groupby } : {}));\n }\n}\n//# sourceMappingURL=pivot.js.map","import { duplicate, hash } from '../../util';\nimport { DataFlowNode } from './dataflow';\n/**\n * A class for the sample transform nodes\n */\nexport class SampleTransformNode extends DataFlowNode {\n constructor(parent, transform) {\n super(parent);\n this.transform = transform;\n }\n clone() {\n return new SampleTransformNode(null, duplicate(this.transform));\n }\n dependentFields() {\n return new Set();\n }\n producedFields() {\n return new Set();\n }\n hash() {\n return `SampleTransform ${hash(this.transform)}`;\n }\n assemble() {\n return {\n type: 'sample',\n size: this.transform.sample\n };\n }\n}\n//# sourceMappingURL=sample.js.map","import { isUrlData } from '../../data';\nimport { AggregateNode } from './aggregate';\nimport { BinNode } from './bin';\nimport { CalculateNode } from './calculate';\nimport { OutputNode } from './dataflow';\nimport { DensityTransformNode } from './density';\nimport { FacetNode } from './facet';\nimport { FilterNode } from './filter';\nimport { FilterInvalidNode } from './filterinvalid';\nimport { FlattenTransformNode } from './flatten';\nimport { FoldTransformNode } from './fold';\nimport { ParseNode } from './formatparse';\nimport { GeoJSONNode } from './geojson';\nimport { GeoPointNode } from './geopoint';\nimport { GraticuleNode } from './graticule';\nimport { IdentifierNode } from './identifier';\nimport { ImputeNode } from './impute';\nimport { JoinAggregateTransformNode } from './joinaggregate';\nimport { LoessTransformNode } from './loess';\nimport { LookupNode } from './lookup';\nimport { QuantileTransformNode } from './quantile';\nimport { RegressionTransformNode } from './regression';\nimport { PivotTransformNode } from './pivot';\nimport { SampleTransformNode } from './sample';\nimport { SequenceNode } from './sequence';\nimport { SourceNode } from './source';\nimport { StackNode } from './stack';\nimport { TimeUnitNode } from './timeunit';\nimport { WindowTransformNode } from './window';\nfunction makeWalkTree(data) {\n // to name datasources\n let datasetIndex = 0;\n /**\n * Recursively walk down the tree.\n */\n function walkTree(node, dataSource) {\n var _a;\n if (node instanceof SourceNode) {\n // If the source is a named data source or a data source with values, we need\n // to put it in a different data source. Otherwise, Vega may override the data.\n if (!node.isGenerator && !isUrlData(node.data)) {\n data.push(dataSource);\n const newData = {\n name: null,\n source: dataSource.name,\n transform: []\n };\n dataSource = newData;\n }\n }\n if (node instanceof ParseNode) {\n if (node.parent instanceof SourceNode && !dataSource.source) {\n // If node's parent is a root source and the data source does not refer to another data source, use normal format parse\n dataSource.format = Object.assign(Object.assign({}, ((_a = dataSource.format) !== null && _a !== void 0 ? _a : {})), { parse: node.assembleFormatParse() });\n // add calculates for all nested fields\n dataSource.transform.push(...node.assembleTransforms(true));\n }\n else {\n // Otherwise use Vega expression to parse\n dataSource.transform.push(...node.assembleTransforms());\n }\n }\n if (node instanceof FacetNode) {\n if (!dataSource.name) {\n dataSource.name = `data_${datasetIndex++}`;\n }\n if (!dataSource.source || dataSource.transform.length > 0) {\n data.push(dataSource);\n node.data = dataSource.name;\n }\n else {\n node.data = dataSource.source;\n }\n data.push(...node.assemble());\n // break here because the rest of the tree has to be taken care of by the facet.\n return;\n }\n if (node instanceof GraticuleNode ||\n node instanceof SequenceNode ||\n node instanceof FilterInvalidNode ||\n node instanceof FilterNode ||\n node instanceof CalculateNode ||\n node instanceof GeoPointNode ||\n node instanceof AggregateNode ||\n node instanceof LookupNode ||\n node instanceof WindowTransformNode ||\n node instanceof JoinAggregateTransformNode ||\n node instanceof FoldTransformNode ||\n node instanceof FlattenTransformNode ||\n node instanceof DensityTransformNode ||\n node instanceof LoessTransformNode ||\n node instanceof QuantileTransformNode ||\n node instanceof RegressionTransformNode ||\n node instanceof IdentifierNode ||\n node instanceof SampleTransformNode ||\n node instanceof PivotTransformNode) {\n dataSource.transform.push(node.assemble());\n }\n if (node instanceof BinNode ||\n node instanceof TimeUnitNode ||\n node instanceof ImputeNode ||\n node instanceof StackNode ||\n node instanceof GeoJSONNode) {\n dataSource.transform.push(...node.assemble());\n }\n if (node instanceof OutputNode) {\n if (dataSource.source && dataSource.transform.length === 0) {\n node.setSource(dataSource.source);\n }\n else if (node.parent instanceof OutputNode) {\n // Note that an output node may be required but we still do not assemble a\n // separate data source for it.\n node.setSource(dataSource.name);\n }\n else {\n if (!dataSource.name) {\n dataSource.name = `data_${datasetIndex++}`;\n }\n // Here we set the name of the datasource we generated. From now on\n // other assemblers can use it.\n node.setSource(dataSource.name);\n // if this node has more than one child, we will add a datasource automatically\n if (node.numChildren() === 1) {\n data.push(dataSource);\n const newData = {\n name: null,\n source: dataSource.name,\n transform: []\n };\n dataSource = newData;\n }\n }\n }\n switch (node.numChildren()) {\n case 0:\n // done\n if (node instanceof OutputNode && (!dataSource.source || dataSource.transform.length > 0)) {\n // do not push empty datasources that are simply references\n data.push(dataSource);\n }\n break;\n case 1:\n walkTree(node.children[0], dataSource);\n break;\n default: {\n if (!dataSource.name) {\n dataSource.name = `data_${datasetIndex++}`;\n }\n let source = dataSource.name;\n if (!dataSource.source || dataSource.transform.length > 0) {\n data.push(dataSource);\n }\n else {\n source = dataSource.source;\n }\n for (const child of node.children) {\n const newData = {\n name: null,\n source: source,\n transform: []\n };\n walkTree(child, newData);\n }\n break;\n }\n }\n }\n return walkTree;\n}\n/**\n * Assemble data sources that are derived from faceted data.\n */\nexport function assembleFacetData(root) {\n const data = [];\n const walkTree = makeWalkTree(data);\n for (const child of root.children) {\n walkTree(child, {\n source: root.name,\n name: null,\n transform: []\n });\n }\n return data;\n}\n/**\n * Create Vega data array from a given compiled model and append all of them to the given array\n *\n * @param model\n * @param data array\n * @return modified data array\n */\nexport function assembleRootData(dataComponent, datasets) {\n var _a, _b;\n const data = [];\n // dataComponent.sources.forEach(debug);\n // draw(dataComponent.sources);\n const walkTree = makeWalkTree(data);\n let sourceIndex = 0;\n for (const root of dataComponent.sources) {\n // assign a name if the source does not have a name yet\n if (!root.hasName()) {\n root.dataName = `source_${sourceIndex++}`;\n }\n const newData = root.assemble();\n walkTree(root, newData);\n }\n // remove empty transform arrays for cleaner output\n for (const d of data) {\n if (d.transform.length === 0) {\n delete d.transform;\n }\n }\n // move sources without transforms (the ones that are potentially used in lookups) to the beginning\n let whereTo = 0;\n for (const [i, d] of data.entries()) {\n if (((_a = d.transform) !== null && _a !== void 0 ? _a : []).length === 0 && !d.source) {\n data.splice(whereTo++, 0, data.splice(i, 1)[0]);\n }\n }\n // now fix the from references in lookup transforms\n for (const d of data) {\n for (const t of (_b = d.transform) !== null && _b !== void 0 ? _b : []) {\n if (t.type === 'lookup') {\n t.from = dataComponent.outputNodes[t.from].getSource();\n }\n }\n }\n // inline values for datasets that are in the datastore\n for (const d of data) {\n if (d.name in datasets) {\n d.values = datasets[d.name];\n }\n }\n return data;\n}\n//# sourceMappingURL=assemble.js.map","import { isArray } from 'vega-util';\nimport { FACET_CHANNELS } from '../../channel';\nimport { title as fieldDefTitle } from '../../channeldef';\nimport { contains, getFirstDefined } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { assembleAxis } from '../axis/assemble';\nimport { parseGuideResolve } from '../resolve';\nimport { getHeaderProperty } from './common';\nexport function getHeaderType(orient) {\n if (orient === 'top' || orient === 'left' || isSignalRef(orient)) {\n // we always use header for orient signal since we can't dynamically make header becomes footer\n return 'header';\n }\n return 'footer';\n}\nexport function parseFacetHeaders(model) {\n for (const channel of FACET_CHANNELS) {\n parseFacetHeader(model, channel);\n }\n mergeChildAxis(model, 'x');\n mergeChildAxis(model, 'y');\n}\nfunction parseFacetHeader(model, channel) {\n var _a;\n const { facet, config, child, component } = model;\n if (model.channelHasField(channel)) {\n const fieldDef = facet[channel];\n const titleConfig = getHeaderProperty('title', null, config, channel);\n let title = fieldDefTitle(fieldDef, config, {\n allowDisabling: true,\n includeDefault: titleConfig === undefined || !!titleConfig\n });\n if (child.component.layoutHeaders[channel].title) {\n // TODO: better handle multiline titles\n title = isArray(title) ? title.join(', ') : title;\n // merge title with child to produce \"Title / Subtitle / Sub-subtitle\"\n title += ` / ${child.component.layoutHeaders[channel].title}`;\n child.component.layoutHeaders[channel].title = null;\n }\n const labelOrient = getHeaderProperty('labelOrient', fieldDef.header, config, channel);\n const labels = fieldDef.header !== null ? getFirstDefined((_a = fieldDef.header) === null || _a === void 0 ? void 0 : _a.labels, config.header.labels, true) : false;\n const headerType = contains(['bottom', 'right'], labelOrient) ? 'footer' : 'header';\n component.layoutHeaders[channel] = {\n title: fieldDef.header !== null ? title : null,\n facetFieldDef: fieldDef,\n [headerType]: channel === 'facet' ? [] : [makeHeaderComponent(model, channel, labels)]\n };\n }\n}\nfunction makeHeaderComponent(model, channel, labels) {\n const sizeType = channel === 'row' ? 'height' : 'width';\n return {\n labels,\n sizeSignal: model.child.component.layoutSize.get(sizeType) ? model.child.getSizeSignalRef(sizeType) : undefined,\n axes: []\n };\n}\nfunction mergeChildAxis(model, channel) {\n var _a;\n const { child } = model;\n if (child.component.axes[channel]) {\n const { layoutHeaders, resolve } = model.component;\n resolve.axis[channel] = parseGuideResolve(resolve, channel);\n if (resolve.axis[channel] === 'shared') {\n // For shared axis, move the axes to facet's header or footer\n const headerChannel = channel === 'x' ? 'column' : 'row';\n const layoutHeader = layoutHeaders[headerChannel];\n for (const axisComponent of child.component.axes[channel]) {\n const headerType = getHeaderType(axisComponent.get('orient'));\n (_a = layoutHeader[headerType]) !== null && _a !== void 0 ? _a : (layoutHeader[headerType] = [makeHeaderComponent(model, headerChannel, false)]);\n // FIXME: assemble shouldn't be called here, but we do it this way so we only extract the main part of the axes\n const mainAxis = assembleAxis(axisComponent, 'main', model.config, { header: true });\n if (mainAxis) {\n // LayoutHeader no longer keep track of property precedence, thus let's combine.\n layoutHeader[headerType][0].axes.push(mainAxis);\n }\n axisComponent.mainExtracted = true;\n }\n }\n else {\n // Otherwise do nothing for independent axes\n }\n }\n}\n//# sourceMappingURL=parse.js.map","import { getPositionScaleChannel, getSizeChannel, POSITION_SCALE_CHANNELS } from '../../channel';\nimport { getViewConfigContinuousSize, getViewConfigDiscreteSize } from '../../config';\nimport { hasDiscreteDomain } from '../../scale';\nimport { isStep } from '../../spec/base';\nimport { isVgRangeStep } from '../../vega.schema';\nimport { defaultScaleResolve } from '../resolve';\nimport { mergeValuesWithExplicit } from '../split';\nimport { getSizeTypeFromLayoutSizeType } from './component';\nexport function parseLayerLayoutSize(model) {\n parseChildrenLayoutSize(model);\n parseNonUnitLayoutSizeForChannel(model, 'width');\n parseNonUnitLayoutSizeForChannel(model, 'height');\n}\nexport function parseConcatLayoutSize(model) {\n parseChildrenLayoutSize(model);\n // for columns === 1 (vconcat), we can completely merge width. Otherwise, we can treat merged width as childWidth.\n const widthType = model.layout.columns === 1 ? 'width' : 'childWidth';\n // for columns === undefined (hconcat), we can completely merge height. Otherwise, we can treat merged height as childHeight.\n const heightType = model.layout.columns === undefined ? 'height' : 'childHeight';\n parseNonUnitLayoutSizeForChannel(model, widthType);\n parseNonUnitLayoutSizeForChannel(model, heightType);\n}\nexport function parseChildrenLayoutSize(model) {\n for (const child of model.children) {\n child.parseLayoutSize();\n }\n}\n/**\n * Merge child layout size (width or height).\n */\nfunction parseNonUnitLayoutSizeForChannel(model, layoutSizeType) {\n var _a;\n /*\n * For concat, the parent width or height might not be the same as the children's shared height.\n * For example, hconcat's subviews may share width, but the shared width is not the hconcat view's width.\n *\n * layoutSizeType represents the output of the view (could be childWidth/childHeight/width/height)\n * while the sizeType represents the properties of the child.\n */\n const sizeType = getSizeTypeFromLayoutSizeType(layoutSizeType);\n const channel = getPositionScaleChannel(sizeType);\n const resolve = model.component.resolve;\n const layoutSizeCmpt = model.component.layoutSize;\n let mergedSize;\n // Try to merge layout size\n for (const child of model.children) {\n const childSize = child.component.layoutSize.getWithExplicit(sizeType);\n const scaleResolve = (_a = resolve.scale[channel]) !== null && _a !== void 0 ? _a : defaultScaleResolve(channel, model);\n if (scaleResolve === 'independent' && childSize.value === 'step') {\n // Do not merge independent scales with range-step as their size depends\n // on the scale domains, which can be different between scales.\n mergedSize = undefined;\n break;\n }\n if (mergedSize) {\n if (scaleResolve === 'independent' && mergedSize.value !== childSize.value) {\n // For independent scale, only merge if all the sizes are the same.\n // If the values are different, abandon the merge!\n mergedSize = undefined;\n break;\n }\n mergedSize = mergeValuesWithExplicit(mergedSize, childSize, sizeType, '');\n }\n else {\n mergedSize = childSize;\n }\n }\n if (mergedSize) {\n // If merged, rename size and set size of all children.\n for (const child of model.children) {\n model.renameSignal(child.getName(sizeType), model.getName(layoutSizeType));\n child.component.layoutSize.set(sizeType, 'merged', false);\n }\n layoutSizeCmpt.setWithExplicit(layoutSizeType, mergedSize);\n }\n else {\n layoutSizeCmpt.setWithExplicit(layoutSizeType, {\n explicit: false,\n value: undefined\n });\n }\n}\nexport function parseUnitLayoutSize(model) {\n const { size, component } = model;\n for (const channel of POSITION_SCALE_CHANNELS) {\n const sizeType = getSizeChannel(channel);\n if (size[sizeType]) {\n const specifiedSize = size[sizeType];\n component.layoutSize.set(sizeType, isStep(specifiedSize) ? 'step' : specifiedSize, true);\n }\n else {\n const defaultSize = defaultUnitSize(model, sizeType);\n component.layoutSize.set(sizeType, defaultSize, false);\n }\n }\n}\nfunction defaultUnitSize(model, sizeType) {\n const channel = sizeType === 'width' ? 'x' : 'y';\n const config = model.config;\n const scaleComponent = model.getScaleComponent(channel);\n if (scaleComponent) {\n const scaleType = scaleComponent.get('type');\n const range = scaleComponent.get('range');\n if (hasDiscreteDomain(scaleType)) {\n const size = getViewConfigDiscreteSize(config.view, sizeType);\n if (isVgRangeStep(range) || isStep(size)) {\n // For discrete domain with range.step, use dynamic width/height\n return 'step';\n }\n else {\n return size;\n }\n }\n else {\n return getViewConfigContinuousSize(config.view, sizeType);\n }\n }\n else if (model.hasProjection || model.mark === 'arc') {\n // arc should use continuous size by default otherwise the pie is extremely small\n return getViewConfigContinuousSize(config.view, sizeType);\n }\n else {\n const size = getViewConfigDiscreteSize(config.view, sizeType);\n return isStep(size) ? size.step : size;\n }\n}\n//# sourceMappingURL=parse.js.map","import { isArray } from 'vega-util';\nimport { isBinning } from '../bin';\nimport { COLUMN, FACET_CHANNELS, POSITION_SCALE_CHANNELS, ROW } from '../channel';\nimport { initFieldDef, vgField } from '../channeldef';\nimport { replaceExprRef } from '../expr';\nimport * as log from '../log';\nimport { hasDiscreteDomain } from '../scale';\nimport { DEFAULT_SORT_OP, isSortField } from '../sort';\nimport { isFacetMapping } from '../spec/facet';\nimport { keys } from '../util';\nimport { isVgRangeStep } from '../vega.schema';\nimport { buildModel } from './buildmodel';\nimport { assembleFacetData } from './data/assemble';\nimport { sortArrayIndexField } from './data/calculate';\nimport { parseData } from './data/parse';\nimport { assembleLabelTitle } from './header/assemble';\nimport { getHeaderChannel, getHeaderProperty } from './header/common';\nimport { HEADER_CHANNELS, HEADER_TYPES } from './header/component';\nimport { parseFacetHeaders } from './header/parse';\nimport { parseChildrenLayoutSize } from './layoutsize/parse';\nimport { ModelWithField } from './model';\nimport { assembleDomain, getFieldFromDomain } from './scale/domain';\nimport { assembleFacetSignals } from './selection/assemble';\nexport function facetSortFieldName(fieldDef, sort, opt) {\n return vgField(sort, Object.assign({ suffix: `by_${vgField(fieldDef)}` }, (opt !== null && opt !== void 0 ? opt : {})));\n}\nexport class FacetModel extends ModelWithField {\n constructor(spec, parent, parentGivenName, config) {\n super(spec, 'facet', parent, parentGivenName, config, spec.resolve);\n this.child = buildModel(spec.spec, this, this.getName('child'), undefined, config);\n this.children = [this.child];\n this.facet = this.initFacet(spec.facet);\n }\n initFacet(facet) {\n // clone to prevent side effect to the original spec\n if (!isFacetMapping(facet)) {\n return { facet: this.initFacetFieldDef(facet, 'facet') };\n }\n const channels = keys(facet);\n const normalizedFacet = {};\n for (const channel of channels) {\n if (![ROW, COLUMN].includes(channel)) {\n // Drop unsupported channel\n log.warn(log.message.incompatibleChannel(channel, 'facet'));\n break;\n }\n const fieldDef = facet[channel];\n if (fieldDef.field === undefined) {\n log.warn(log.message.emptyFieldDef(fieldDef, channel));\n break;\n }\n normalizedFacet[channel] = this.initFacetFieldDef(fieldDef, channel);\n }\n return normalizedFacet;\n }\n initFacetFieldDef(fieldDef, channel) {\n // Cast because we call initFieldDef, which assumes general FieldDef.\n // However, FacetFieldDef is a bit more constrained than the general FieldDef\n const facetFieldDef = initFieldDef(fieldDef, channel);\n if (facetFieldDef.header) {\n facetFieldDef.header = replaceExprRef(facetFieldDef.header);\n }\n else if (facetFieldDef.header === null) {\n facetFieldDef.header = null;\n }\n return facetFieldDef;\n }\n channelHasField(channel) {\n return !!this.facet[channel];\n }\n fieldDef(channel) {\n return this.facet[channel];\n }\n parseData() {\n this.component.data = parseData(this);\n this.child.parseData();\n }\n parseLayoutSize() {\n parseChildrenLayoutSize(this);\n }\n parseSelections() {\n // As a facet has a single child, the selection components are the same.\n // The child maintains its selections to assemble signals, which remain\n // within its unit.\n this.child.parseSelections();\n this.component.selection = this.child.component.selection;\n }\n parseMarkGroup() {\n this.child.parseMarkGroup();\n }\n parseAxesAndHeaders() {\n this.child.parseAxesAndHeaders();\n parseFacetHeaders(this);\n }\n assembleSelectionTopLevelSignals(signals) {\n return this.child.assembleSelectionTopLevelSignals(signals);\n }\n assembleSignals() {\n this.child.assembleSignals();\n return [];\n }\n assembleSelectionData(data) {\n return this.child.assembleSelectionData(data);\n }\n getHeaderLayoutMixins() {\n var _a, _b, _c;\n const layoutMixins = {};\n for (const channel of FACET_CHANNELS) {\n for (const headerType of HEADER_TYPES) {\n const layoutHeaderComponent = this.component.layoutHeaders[channel];\n const headerComponent = layoutHeaderComponent[headerType];\n const { facetFieldDef } = layoutHeaderComponent;\n if (facetFieldDef) {\n const titleOrient = getHeaderProperty('titleOrient', facetFieldDef.header, this.config, channel);\n if (['right', 'bottom'].includes(titleOrient)) {\n const headerChannel = getHeaderChannel(channel, titleOrient);\n (_a = layoutMixins.titleAnchor) !== null && _a !== void 0 ? _a : (layoutMixins.titleAnchor = {});\n layoutMixins.titleAnchor[headerChannel] = 'end';\n }\n }\n if (headerComponent === null || headerComponent === void 0 ? void 0 : headerComponent[0]) {\n // set header/footerBand\n const sizeType = channel === 'row' ? 'height' : 'width';\n const bandType = headerType === 'header' ? 'headerBand' : 'footerBand';\n if (channel !== 'facet' && !this.child.component.layoutSize.get(sizeType)) {\n // If facet child does not have size signal, then apply headerBand\n (_b = layoutMixins[bandType]) !== null && _b !== void 0 ? _b : (layoutMixins[bandType] = {});\n layoutMixins[bandType][channel] = 0.5;\n }\n if (layoutHeaderComponent.title) {\n (_c = layoutMixins.offset) !== null && _c !== void 0 ? _c : (layoutMixins.offset = {});\n layoutMixins.offset[channel === 'row' ? 'rowTitle' : 'columnTitle'] = 10;\n }\n }\n }\n }\n return layoutMixins;\n }\n assembleDefaultLayout() {\n const { column, row } = this.facet;\n const columns = column ? this.columnDistinctSignal() : row ? 1 : undefined;\n let align = 'all';\n // Do not align the cells if the scale corresponding to the direction is indepent.\n // We always align when we facet into both row and column.\n if (!row && this.component.resolve.scale.x === 'independent') {\n align = 'none';\n }\n else if (!column && this.component.resolve.scale.y === 'independent') {\n align = 'none';\n }\n return Object.assign(Object.assign(Object.assign({}, this.getHeaderLayoutMixins()), (columns ? { columns } : {})), { bounds: 'full', align });\n }\n assembleLayoutSignals() {\n // FIXME(https://github.com/vega/vega-lite/issues/1193): this can be incorrect if we have independent scales.\n return this.child.assembleLayoutSignals();\n }\n columnDistinctSignal() {\n if (this.parent && this.parent instanceof FacetModel) {\n // For nested facet, we will add columns to group mark instead\n // See discussion in https://github.com/vega/vega/issues/952\n // and https://github.com/vega/vega-view/releases/tag/v1.2.6\n return undefined;\n }\n else {\n // In facetNode.assemble(), the name is always this.getName('column') + '_layout'.\n const facetLayoutDataName = this.getName('column_domain');\n return { signal: `length(data('${facetLayoutDataName}'))` };\n }\n }\n assembleGroupStyle() {\n return undefined;\n }\n assembleGroup(signals) {\n if (this.parent && this.parent instanceof FacetModel) {\n // Provide number of columns for layout.\n // See discussion in https://github.com/vega/vega/issues/952\n // and https://github.com/vega/vega-view/releases/tag/v1.2.6\n return Object.assign(Object.assign({}, (this.channelHasField('column')\n ? {\n encode: {\n update: {\n // TODO(https://github.com/vega/vega-lite/issues/2759):\n // Correct the signal for facet of concat of facet_column\n columns: { field: vgField(this.facet.column, { prefix: 'distinct' }) }\n }\n }\n }\n : {})), super.assembleGroup(signals));\n }\n return super.assembleGroup(signals);\n }\n /**\n * Aggregate cardinality for calculating size\n */\n getCardinalityAggregateForChild() {\n const fields = [];\n const ops = [];\n const as = [];\n if (this.child instanceof FacetModel) {\n if (this.child.channelHasField('column')) {\n const field = vgField(this.child.facet.column);\n fields.push(field);\n ops.push('distinct');\n as.push(`distinct_${field}`);\n }\n }\n else {\n for (const channel of POSITION_SCALE_CHANNELS) {\n const childScaleComponent = this.child.component.scales[channel];\n if (childScaleComponent && !childScaleComponent.merged) {\n const type = childScaleComponent.get('type');\n const range = childScaleComponent.get('range');\n if (hasDiscreteDomain(type) && isVgRangeStep(range)) {\n const domain = assembleDomain(this.child, channel);\n const field = getFieldFromDomain(domain);\n if (field) {\n fields.push(field);\n ops.push('distinct');\n as.push(`distinct_${field}`);\n }\n else {\n log.warn(log.message.unknownField(channel));\n }\n }\n }\n }\n }\n return { fields, ops, as };\n }\n assembleFacet() {\n const { name, data } = this.component.data.facetRoot;\n const { row, column } = this.facet;\n const { fields, ops, as } = this.getCardinalityAggregateForChild();\n const groupby = [];\n for (const channel of FACET_CHANNELS) {\n const fieldDef = this.facet[channel];\n if (fieldDef) {\n groupby.push(vgField(fieldDef));\n const { bin, sort } = fieldDef;\n if (isBinning(bin)) {\n groupby.push(vgField(fieldDef, { binSuffix: 'end' }));\n }\n if (isSortField(sort)) {\n const { field, op = DEFAULT_SORT_OP } = sort;\n const outputName = facetSortFieldName(fieldDef, sort);\n if (row && column) {\n // For crossed facet, use pre-calculate field as it requires a different groupby\n // For each calculated field, apply max and assign them to the same name as\n // all values of the same group should be the same anyway.\n fields.push(outputName);\n ops.push('max');\n as.push(outputName);\n }\n else {\n fields.push(field);\n ops.push(op);\n as.push(outputName);\n }\n }\n else if (isArray(sort)) {\n const outputName = sortArrayIndexField(fieldDef, channel);\n fields.push(outputName);\n ops.push('max');\n as.push(outputName);\n }\n }\n }\n const cross = !!row && !!column;\n return Object.assign({ name,\n data,\n groupby }, (cross || fields.length > 0\n ? {\n aggregate: Object.assign(Object.assign({}, (cross ? { cross } : {})), (fields.length ? { fields, ops, as } : {}))\n }\n : {}));\n }\n facetSortFields(channel) {\n const { facet } = this;\n const fieldDef = facet[channel];\n if (fieldDef) {\n if (isSortField(fieldDef.sort)) {\n return [facetSortFieldName(fieldDef, fieldDef.sort, { expr: 'datum' })];\n }\n else if (isArray(fieldDef.sort)) {\n return [sortArrayIndexField(fieldDef, channel, { expr: 'datum' })];\n }\n return [vgField(fieldDef, { expr: 'datum' })];\n }\n return [];\n }\n facetSortOrder(channel) {\n const { facet } = this;\n const fieldDef = facet[channel];\n if (fieldDef) {\n const { sort } = fieldDef;\n const order = (isSortField(sort) ? sort.order : !isArray(sort) && sort) || 'ascending';\n return [order];\n }\n return [];\n }\n assembleLabelTitle() {\n var _a;\n const { facet, config } = this;\n if (facet.facet) {\n // Facet always uses title to display labels\n return assembleLabelTitle(facet.facet, 'facet', config);\n }\n const ORTHOGONAL_ORIENT = {\n row: ['top', 'bottom'],\n column: ['left', 'right']\n };\n for (const channel of HEADER_CHANNELS) {\n if (facet[channel]) {\n const labelOrient = getHeaderProperty('labelOrient', (_a = facet[channel]) === null || _a === void 0 ? void 0 : _a.header, config, channel);\n if (ORTHOGONAL_ORIENT[channel].includes(labelOrient)) {\n // Row/Column with orthogonal labelOrient must use title to display labels\n return assembleLabelTitle(facet[channel], channel, config);\n }\n }\n }\n return undefined;\n }\n assembleMarks() {\n const { child } = this;\n // If we facet by two dimensions, we need to add a cross operator to the aggregation\n // so that we create all groups\n const facetRoot = this.component.data.facetRoot;\n const data = assembleFacetData(facetRoot);\n const encodeEntry = child.assembleGroupEncodeEntry(false);\n const title = this.assembleLabelTitle() || child.assembleTitle();\n const style = child.assembleGroupStyle();\n const markGroup = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name: this.getName('cell'), type: 'group' }, (title ? { title } : {})), (style ? { style } : {})), { from: {\n facet: this.assembleFacet()\n }, \n // TODO: move this to after data\n sort: {\n field: FACET_CHANNELS.map(c => this.facetSortFields(c)).flat(),\n order: FACET_CHANNELS.map(c => this.facetSortOrder(c)).flat()\n } }), (data.length > 0 ? { data: data } : {})), (encodeEntry ? { encode: { update: encodeEntry } } : {})), child.assembleGroup(assembleFacetSignals(this, [])));\n return [markGroup];\n }\n getMapping() {\n return this.facet;\n }\n}\n//# sourceMappingURL=facet.js.map","import { AncestorParse } from '.';\nimport { isGenerator, isGraticuleGenerator, isInlineData, isNamedData, isSequenceGenerator, isUrlData, DataSourceType } from '../../data';\nimport * as log from '../../log';\nimport { isAggregate, isBin, isCalculate, isDensity, isFilter, isFlatten, isFold, isImpute, isJoinAggregate, isLoess, isLookup, isPivot, isQuantile, isRegression, isSample, isStack, isTimeUnit, isWindow } from '../../transform';\nimport { deepEqual, mergeDeep } from '../../util';\nimport { isFacetModel, isLayerModel, isUnitModel } from '../model';\nimport { requiresSelectionId } from '../selection';\nimport { materializeSelections } from '../selection/parse';\nimport { AggregateNode } from './aggregate';\nimport { BinNode } from './bin';\nimport { CalculateNode } from './calculate';\nimport { OutputNode } from './dataflow';\nimport { DensityTransformNode } from './density';\nimport { FacetNode } from './facet';\nimport { FilterNode } from './filter';\nimport { FilterInvalidNode } from './filterinvalid';\nimport { FlattenTransformNode } from './flatten';\nimport { FoldTransformNode } from './fold';\nimport { getImplicitFromEncoding, getImplicitFromFilterTransform, getImplicitFromSelection, ParseNode } from './formatparse';\nimport { GeoJSONNode } from './geojson';\nimport { GeoPointNode } from './geopoint';\nimport { GraticuleNode } from './graticule';\nimport { IdentifierNode } from './identifier';\nimport { ImputeNode } from './impute';\nimport { JoinAggregateTransformNode } from './joinaggregate';\nimport { makeJoinAggregateFromFacet } from './joinaggregatefacet';\nimport { LoessTransformNode } from './loess';\nimport { LookupNode } from './lookup';\nimport { PivotTransformNode } from './pivot';\nimport { QuantileTransformNode } from './quantile';\nimport { RegressionTransformNode } from './regression';\nimport { SampleTransformNode } from './sample';\nimport { SequenceNode } from './sequence';\nimport { SourceNode } from './source';\nimport { StackNode } from './stack';\nimport { TimeUnitNode } from './timeunit';\nimport { WindowTransformNode } from './window';\nexport function findSource(data, sources) {\n var _a, _b, _c, _d;\n for (const other of sources) {\n const otherData = other.data;\n // if both datasets have a name defined, we cannot merge\n if (data.name && other.hasName() && data.name !== other.dataName) {\n continue;\n }\n const formatMesh = (_a = data['format']) === null || _a === void 0 ? void 0 : _a.mesh;\n const otherFeature = (_b = otherData.format) === null || _b === void 0 ? void 0 : _b.feature;\n // feature and mesh are mutually exclusive\n if (formatMesh && otherFeature) {\n continue;\n }\n // we have to extract the same feature or mesh\n const formatFeature = (_c = data['format']) === null || _c === void 0 ? void 0 : _c.feature;\n if ((formatFeature || otherFeature) && formatFeature !== otherFeature) {\n continue;\n }\n const otherMesh = (_d = otherData.format) === null || _d === void 0 ? void 0 : _d.mesh;\n if ((formatMesh || otherMesh) && formatMesh !== otherMesh) {\n continue;\n }\n if (isInlineData(data) && isInlineData(otherData)) {\n if (deepEqual(data.values, otherData.values)) {\n return other;\n }\n }\n else if (isUrlData(data) && isUrlData(otherData)) {\n if (data.url === otherData.url) {\n return other;\n }\n }\n else if (isNamedData(data)) {\n if (data.name === other.dataName) {\n return other;\n }\n }\n }\n return null;\n}\nfunction parseRoot(model, sources) {\n if (model.data || !model.parent) {\n // if the model defines a data source or is the root, create a source node\n if (model.data === null) {\n // data: null means we should ignore the parent's data so we just create a new data source\n const source = new SourceNode({ values: [] });\n sources.push(source);\n return source;\n }\n const existingSource = findSource(model.data, sources);\n if (existingSource) {\n if (!isGenerator(model.data)) {\n existingSource.data.format = mergeDeep({}, model.data.format, existingSource.data.format);\n }\n // if the new source has a name but the existing one does not, we can set it\n if (!existingSource.hasName() && model.data.name) {\n existingSource.dataName = model.data.name;\n }\n return existingSource;\n }\n else {\n const source = new SourceNode(model.data);\n sources.push(source);\n return source;\n }\n }\n else {\n // If we don't have a source defined (overriding parent's data), use the parent's facet root or main.\n return model.parent.component.data.facetRoot\n ? model.parent.component.data.facetRoot\n : model.parent.component.data.main;\n }\n}\n/**\n * Parses a transform array into a chain of connected dataflow nodes.\n */\nexport function parseTransformArray(head, model, ancestorParse) {\n var _a, _b;\n let lookupCounter = 0;\n for (const t of model.transforms) {\n let derivedType = undefined;\n let transformNode;\n if (isCalculate(t)) {\n transformNode = head = new CalculateNode(head, t);\n derivedType = 'derived';\n }\n else if (isFilter(t)) {\n const implicit = getImplicitFromFilterTransform(t);\n transformNode = head = (_a = ParseNode.makeWithAncestors(head, {}, implicit, ancestorParse)) !== null && _a !== void 0 ? _a : head;\n head = new FilterNode(head, model, t.filter);\n }\n else if (isBin(t)) {\n transformNode = head = BinNode.makeFromTransform(head, t, model);\n derivedType = 'number';\n }\n else if (isTimeUnit(t)) {\n derivedType = 'date';\n const parsedAs = ancestorParse.getWithExplicit(t.field);\n // Create parse node because the input to time unit is always date.\n if (parsedAs.value === undefined) {\n head = new ParseNode(head, { [t.field]: derivedType });\n ancestorParse.set(t.field, derivedType, false);\n }\n transformNode = head = TimeUnitNode.makeFromTransform(head, t);\n }\n else if (isAggregate(t)) {\n transformNode = head = AggregateNode.makeFromTransform(head, t);\n derivedType = 'number';\n if (requiresSelectionId(model)) {\n head = new IdentifierNode(head);\n }\n }\n else if (isLookup(t)) {\n transformNode = head = LookupNode.make(head, model, t, lookupCounter++);\n derivedType = 'derived';\n }\n else if (isWindow(t)) {\n transformNode = head = new WindowTransformNode(head, t);\n derivedType = 'number';\n }\n else if (isJoinAggregate(t)) {\n transformNode = head = new JoinAggregateTransformNode(head, t);\n derivedType = 'number';\n }\n else if (isStack(t)) {\n transformNode = head = StackNode.makeFromTransform(head, t);\n derivedType = 'derived';\n }\n else if (isFold(t)) {\n transformNode = head = new FoldTransformNode(head, t);\n derivedType = 'derived';\n }\n else if (isFlatten(t)) {\n transformNode = head = new FlattenTransformNode(head, t);\n derivedType = 'derived';\n }\n else if (isPivot(t)) {\n transformNode = head = new PivotTransformNode(head, t);\n derivedType = 'derived';\n }\n else if (isSample(t)) {\n head = new SampleTransformNode(head, t);\n }\n else if (isImpute(t)) {\n transformNode = head = ImputeNode.makeFromTransform(head, t);\n derivedType = 'derived';\n }\n else if (isDensity(t)) {\n transformNode = head = new DensityTransformNode(head, t);\n derivedType = 'derived';\n }\n else if (isQuantile(t)) {\n transformNode = head = new QuantileTransformNode(head, t);\n derivedType = 'derived';\n }\n else if (isRegression(t)) {\n transformNode = head = new RegressionTransformNode(head, t);\n derivedType = 'derived';\n }\n else if (isLoess(t)) {\n transformNode = head = new LoessTransformNode(head, t);\n derivedType = 'derived';\n }\n else {\n log.warn(log.message.invalidTransformIgnored(t));\n continue;\n }\n if (transformNode && derivedType !== undefined) {\n for (const field of (_b = transformNode.producedFields()) !== null && _b !== void 0 ? _b : []) {\n ancestorParse.set(field, derivedType, false);\n }\n }\n }\n return head;\n}\n/*\nDescription of the dataflow (http://asciiflow.com/):\n +--------+\n | Source |\n +---+----+\n |\n v\n FormatParse\n (explicit)\n |\n v\n Transforms\n(Filter, Calculate, Binning, TimeUnit, Aggregate, Window, ...)\n |\n v\n FormatParse\n (implicit)\n |\n v\n Binning (in `encoding`)\n |\n v\n Timeunit (in `encoding`)\n |\n v\nFormula From Sort Array\n |\n v\n +--+--+\n | Raw |\n +-----+\n |\n v\n Aggregate (in `encoding`)\n |\n v\n Stack (in `encoding`)\n |\n v\n Invalid Filter\n |\n v\n +----------+\n | Main |\n +----------+\n |\n v\n +-------+\n | Facet |----> \"column\", \"column-layout\", and \"row\"\n +-------+\n |\n v\n ...Child data...\n*/\nexport function parseData(model) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\n let head = parseRoot(model, model.component.data.sources);\n const { outputNodes, outputNodeRefCounts } = model.component.data;\n const data = model.data;\n const newData = data && (isGenerator(data) || isUrlData(data) || isInlineData(data));\n const ancestorParse = !newData && model.parent ? model.parent.component.data.ancestorParse.clone() : new AncestorParse();\n if (isGenerator(data)) {\n // insert generator transform\n if (isSequenceGenerator(data)) {\n head = new SequenceNode(head, data.sequence);\n }\n else if (isGraticuleGenerator(data)) {\n head = new GraticuleNode(head, data.graticule);\n }\n // no parsing necessary for generator\n ancestorParse.parseNothing = true;\n }\n else if (((_a = data === null || data === void 0 ? void 0 : data.format) === null || _a === void 0 ? void 0 : _a.parse) === null) {\n // format.parse: null means disable parsing\n ancestorParse.parseNothing = true;\n }\n head = (_b = ParseNode.makeExplicit(head, model, ancestorParse)) !== null && _b !== void 0 ? _b : head;\n // Default discrete selections require an identifer transform to\n // uniquely identify data points. Add this transform at the head of\n // the pipeline such that the identifier field is available for all\n // subsequent datasets. During optimization, we will remove this\n // transform if it proves to be unnecessary. Additional identifier\n // transforms will be necessary when new tuples are constructed\n // (e.g., post-aggregation).\n head = new IdentifierNode(head);\n // HACK: This is equivalent for merging bin extent for union scale.\n // FIXME(https://github.com/vega/vega-lite/issues/2270): Correctly merge extent / bin node for shared bin scale\n const parentIsLayer = model.parent && isLayerModel(model.parent);\n if (isUnitModel(model) || isFacetModel(model)) {\n if (parentIsLayer) {\n head = (_c = BinNode.makeFromEncoding(head, model)) !== null && _c !== void 0 ? _c : head;\n }\n }\n if (model.transforms.length > 0) {\n head = parseTransformArray(head, model, ancestorParse);\n }\n // create parse nodes for fields that need to be parsed (or flattened) implicitly\n const implicitSelection = getImplicitFromSelection(model);\n const implicitEncoding = getImplicitFromEncoding(model);\n head = (_d = ParseNode.makeWithAncestors(head, {}, Object.assign(Object.assign({}, implicitSelection), implicitEncoding), ancestorParse)) !== null && _d !== void 0 ? _d : head;\n if (isUnitModel(model)) {\n head = GeoJSONNode.parseAll(head, model);\n head = GeoPointNode.parseAll(head, model);\n }\n if (isUnitModel(model) || isFacetModel(model)) {\n if (!parentIsLayer) {\n head = (_e = BinNode.makeFromEncoding(head, model)) !== null && _e !== void 0 ? _e : head;\n }\n head = (_f = TimeUnitNode.makeFromEncoding(head, model)) !== null && _f !== void 0 ? _f : head;\n head = CalculateNode.parseAllForSortIndex(head, model);\n }\n // add an output node pre aggregation\n const rawName = model.getDataName(DataSourceType.Raw);\n const raw = new OutputNode(head, rawName, DataSourceType.Raw, outputNodeRefCounts);\n outputNodes[rawName] = raw;\n head = raw;\n if (isUnitModel(model)) {\n const agg = AggregateNode.makeFromEncoding(head, model);\n if (agg) {\n head = agg;\n if (requiresSelectionId(model)) {\n head = new IdentifierNode(head);\n }\n }\n head = (_g = ImputeNode.makeFromEncoding(head, model)) !== null && _g !== void 0 ? _g : head;\n head = (_h = StackNode.makeFromEncoding(head, model)) !== null && _h !== void 0 ? _h : head;\n }\n if (isUnitModel(model)) {\n head = (_j = FilterInvalidNode.make(head, model)) !== null && _j !== void 0 ? _j : head;\n }\n // output node for marks\n const mainName = model.getDataName(DataSourceType.Main);\n const main = new OutputNode(head, mainName, DataSourceType.Main, outputNodeRefCounts);\n outputNodes[mainName] = main;\n head = main;\n if (isUnitModel(model)) {\n materializeSelections(model, main);\n }\n // add facet marker\n let facetRoot = null;\n if (isFacetModel(model)) {\n const facetName = model.getName('facet');\n // Derive new aggregate for facet's sort field\n // augment data source with new fields for crossed facet\n head = (_k = makeJoinAggregateFromFacet(head, model.facet)) !== null && _k !== void 0 ? _k : head;\n facetRoot = new FacetNode(head, model, facetName, main.getSource());\n outputNodes[facetName] = facetRoot;\n }\n return Object.assign(Object.assign({}, model.component.data), { outputNodes,\n outputNodeRefCounts,\n raw,\n main,\n facetRoot,\n ancestorParse });\n}\n//# sourceMappingURL=parse.js.map","import { vgField } from '../../channeldef';\nimport { DEFAULT_SORT_OP, isSortField } from '../../sort';\nimport { facetSortFieldName } from '../facet';\nimport { JoinAggregateTransformNode } from './joinaggregate';\nexport function makeJoinAggregateFromFacet(parent, facet) {\n const { row, column } = facet;\n if (row && column) {\n let newParent = null;\n // only need to make one for crossed facet\n for (const fieldDef of [row, column]) {\n if (isSortField(fieldDef.sort)) {\n const { field, op = DEFAULT_SORT_OP } = fieldDef.sort;\n parent = newParent = new JoinAggregateTransformNode(parent, {\n joinaggregate: [\n {\n op,\n field,\n as: facetSortFieldName(fieldDef, fieldDef.sort, { forAs: true })\n }\n ],\n groupby: [vgField(fieldDef)]\n });\n }\n }\n return newParent;\n }\n return null;\n}\n//# sourceMappingURL=joinaggregatefacet.js.map","import * as log from '../log';\nimport { isHConcatSpec, isVConcatSpec } from '../spec';\nimport { keys } from '../util';\nimport { buildModel } from './buildmodel';\nimport { parseData } from './data/parse';\nimport { assembleLayoutSignals } from './layoutsize/assemble';\nimport { parseConcatLayoutSize } from './layoutsize/parse';\nimport { Model } from './model';\nexport class ConcatModel extends Model {\n constructor(spec, parent, parentGivenName, config) {\n var _a, _b, _c, _d;\n super(spec, 'concat', parent, parentGivenName, config, spec.resolve);\n if (((_b = (_a = spec.resolve) === null || _a === void 0 ? void 0 : _a.axis) === null || _b === void 0 ? void 0 : _b.x) === 'shared' || ((_d = (_c = spec.resolve) === null || _c === void 0 ? void 0 : _c.axis) === null || _d === void 0 ? void 0 : _d.y) === 'shared') {\n log.warn(log.message.CONCAT_CANNOT_SHARE_AXIS);\n }\n this.children = this.getChildren(spec).map((child, i) => {\n return buildModel(child, this, this.getName(`concat_${i}`), undefined, config);\n });\n }\n parseData() {\n this.component.data = parseData(this);\n for (const child of this.children) {\n child.parseData();\n }\n }\n parseSelections() {\n // Merge selections up the hierarchy so that they may be referenced\n // across unit specs. Persist their definitions within each child\n // to assemble signals which remain within output Vega unit groups.\n this.component.selection = {};\n for (const child of this.children) {\n child.parseSelections();\n for (const key of keys(child.component.selection)) {\n this.component.selection[key] = child.component.selection[key];\n }\n }\n }\n parseMarkGroup() {\n for (const child of this.children) {\n child.parseMarkGroup();\n }\n }\n parseAxesAndHeaders() {\n for (const child of this.children) {\n child.parseAxesAndHeaders();\n }\n // TODO(#2415): support shared axes\n }\n getChildren(spec) {\n if (isVConcatSpec(spec)) {\n return spec.vconcat;\n }\n else if (isHConcatSpec(spec)) {\n return spec.hconcat;\n }\n return spec.concat;\n }\n parseLayoutSize() {\n parseConcatLayoutSize(this);\n }\n parseAxisGroup() {\n return null;\n }\n assembleSelectionTopLevelSignals(signals) {\n return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);\n }\n assembleSignals() {\n this.children.forEach(child => child.assembleSignals());\n return [];\n }\n assembleLayoutSignals() {\n const layoutSignals = assembleLayoutSignals(this);\n for (const child of this.children) {\n layoutSignals.push(...child.assembleLayoutSignals());\n }\n return layoutSignals;\n }\n assembleSelectionData(data) {\n return this.children.reduce((db, child) => child.assembleSelectionData(db), data);\n }\n assembleMarks() {\n // only children have marks\n return this.children.map(child => {\n const title = child.assembleTitle();\n const style = child.assembleGroupStyle();\n const encodeEntry = child.assembleGroupEncodeEntry(false);\n return Object.assign(Object.assign(Object.assign(Object.assign({ type: 'group', name: child.getName('group') }, (title ? { title } : {})), (style ? { style } : {})), (encodeEntry ? { encode: { update: encodeEntry } } : {})), child.assembleGroup());\n });\n }\n assembleGroupStyle() {\n return undefined;\n }\n assembleDefaultLayout() {\n const columns = this.layout.columns;\n return Object.assign(Object.assign({}, (columns != null ? { columns: columns } : {})), { bounds: 'full', \n // Use align each so it can work with multiple plots with different size\n align: 'each' });\n }\n}\n//# sourceMappingURL=concat.js.map","import { COMMON_AXIS_PROPERTIES_INDEX } from '../../axis';\nimport { duplicate, keys } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { Split } from '../split';\nfunction isFalseOrNull(v) {\n return v === false || v === null;\n}\nconst AXIS_COMPONENT_PROPERTIES_INDEX = Object.assign(Object.assign({ disable: 1, gridScale: 1, scale: 1 }, COMMON_AXIS_PROPERTIES_INDEX), { labelExpr: 1, encode: 1 });\nexport const AXIS_COMPONENT_PROPERTIES = keys(AXIS_COMPONENT_PROPERTIES_INDEX);\nexport class AxisComponent extends Split {\n constructor(explicit = {}, implicit = {}, mainExtracted = false) {\n super();\n this.explicit = explicit;\n this.implicit = implicit;\n this.mainExtracted = mainExtracted;\n }\n clone() {\n return new AxisComponent(duplicate(this.explicit), duplicate(this.implicit), this.mainExtracted);\n }\n hasAxisPart(part) {\n // FIXME(https://github.com/vega/vega-lite/issues/2552) this method can be wrong if users use a Vega theme.\n if (part === 'axis') {\n // always has the axis container part\n return true;\n }\n if (part === 'grid' || part === 'title') {\n return !!this.get(part);\n }\n // Other parts are enabled by default, so they should not be false or null.\n return !isFalseOrNull(this.get(part));\n }\n hasOrientSignalRef() {\n return isSignalRef(this.explicit.orient);\n }\n}\n//# sourceMappingURL=component.js.map","import { AXIS_PARTS, isAxisProperty, isConditionalAxisValue } from '../../axis';\nimport { POSITION_SCALE_CHANNELS } from '../../channel';\nimport { getFieldOrDatumDef } from '../../channeldef';\nimport { getFirstDefined, isEmpty, keys, normalizeAngle } from '../../util';\nimport { isSignalRef } from '../../vega.schema';\nimport { mergeTitleComponent } from '../common';\nimport { guideEncodeEntry } from '../guide';\nimport { parseGuideResolve } from '../resolve';\nimport { defaultTieBreaker, mergeValuesWithExplicit } from '../split';\nimport { AxisComponent, AXIS_COMPONENT_PROPERTIES } from './component';\nimport { getAxisConfig, getAxisConfigs } from './config';\nimport * as encode from './encode';\nimport { axisRules, defaultOrient, getFieldDefTitle, getLabelAngle } from './properties';\nexport function parseUnitAxes(model) {\n return POSITION_SCALE_CHANNELS.reduce((axis, channel) => {\n if (model.component.scales[channel]) {\n axis[channel] = [parseAxis(channel, model)];\n }\n return axis;\n }, {});\n}\nconst OPPOSITE_ORIENT = {\n bottom: 'top',\n top: 'bottom',\n left: 'right',\n right: 'left'\n};\nexport function parseLayerAxes(model) {\n var _a;\n const { axes, resolve } = model.component;\n const axisCount = { top: 0, bottom: 0, right: 0, left: 0 };\n for (const child of model.children) {\n child.parseAxesAndHeaders();\n for (const channel of keys(child.component.axes)) {\n resolve.axis[channel] = parseGuideResolve(model.component.resolve, channel);\n if (resolve.axis[channel] === 'shared') {\n // If the resolve says shared (and has not been overridden)\n // We will try to merge and see if there is a conflict\n axes[channel] = mergeAxisComponents(axes[channel], child.component.axes[channel]);\n if (!axes[channel]) {\n // If merge returns nothing, there is a conflict so we cannot make the axis shared.\n // Thus, mark axis as independent and remove the axis component.\n resolve.axis[channel] = 'independent';\n delete axes[channel];\n }\n }\n }\n }\n // Move axes to layer's axis component and merge shared axes\n for (const channel of POSITION_SCALE_CHANNELS) {\n for (const child of model.children) {\n if (!child.component.axes[channel]) {\n // skip if the child does not have a particular axis\n continue;\n }\n if (resolve.axis[channel] === 'independent') {\n // If axes are independent, concat the axisComponent array.\n axes[channel] = ((_a = axes[channel]) !== null && _a !== void 0 ? _a : []).concat(child.component.axes[channel]);\n // Automatically adjust orient\n for (const axisComponent of child.component.axes[channel]) {\n const { value: orient, explicit } = axisComponent.getWithExplicit('orient');\n if (isSignalRef(orient)) {\n continue;\n }\n if (axisCount[orient] > 0 && !explicit) {\n // Change axis orient if the number do not match\n const oppositeOrient = OPPOSITE_ORIENT[orient];\n if (axisCount[orient] > axisCount[oppositeOrient]) {\n axisComponent.set('orient', oppositeOrient, false);\n }\n }\n axisCount[orient]++;\n // TODO(https://github.com/vega/vega-lite/issues/2634): automatically add extra offset?\n }\n }\n // After merging, make sure to remove axes from child\n delete child.component.axes[channel];\n }\n // Suppress grid lines for dual axis charts (https://github.com/vega/vega-lite/issues/4676)\n if (resolve.axis[channel] === 'independent' && axes[channel] && axes[channel].length > 1) {\n for (const axisCmpt of axes[channel]) {\n if (!!axisCmpt.get('grid') && !axisCmpt.explicit.grid) {\n axisCmpt.implicit.grid = false;\n }\n }\n }\n }\n}\nfunction mergeAxisComponents(mergedAxisCmpts, childAxisCmpts) {\n if (mergedAxisCmpts) {\n // FIXME: this is a bit wrong once we support multiple axes\n if (mergedAxisCmpts.length !== childAxisCmpts.length) {\n return undefined; // Cannot merge axis component with different number of axes.\n }\n const length = mergedAxisCmpts.length;\n for (let i = 0; i < length; i++) {\n const merged = mergedAxisCmpts[i];\n const child = childAxisCmpts[i];\n if (!!merged !== !!child) {\n return undefined;\n }\n else if (merged && child) {\n const mergedOrient = merged.getWithExplicit('orient');\n const childOrient = child.getWithExplicit('orient');\n if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {\n // TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.)\n // Cannot merge due to inconsistent orient\n return undefined;\n }\n else {\n mergedAxisCmpts[i] = mergeAxisComponent(merged, child);\n }\n }\n }\n }\n else {\n // For first one, return a copy of the child\n return childAxisCmpts.map(axisComponent => axisComponent.clone());\n }\n return mergedAxisCmpts;\n}\nfunction mergeAxisComponent(merged, child) {\n for (const prop of AXIS_COMPONENT_PROPERTIES) {\n const mergedValueWithExplicit = mergeValuesWithExplicit(merged.getWithExplicit(prop), child.getWithExplicit(prop), prop, 'axis', \n // Tie breaker function\n (v1, v2) => {\n switch (prop) {\n case 'title':\n return mergeTitleComponent(v1, v2);\n case 'gridScale':\n return {\n explicit: v1.explicit,\n value: getFirstDefined(v1.value, v2.value)\n };\n }\n return defaultTieBreaker(v1, v2, prop, 'axis');\n });\n merged.setWithExplicit(prop, mergedValueWithExplicit);\n }\n return merged;\n}\nfunction isExplicit(value, property, axis, model, channel) {\n if (property === 'disable') {\n return axis !== undefined; // if axis is specified or null/false, then its enable/disable state is explicit\n }\n axis = axis || {};\n switch (property) {\n case 'titleAngle':\n case 'labelAngle':\n return value === (isSignalRef(axis.labelAngle) ? axis.labelAngle : normalizeAngle(axis.labelAngle));\n case 'values':\n return !!axis.values;\n // specified axis.values is already respected, but may get transformed.\n case 'encode':\n // both VL axis.encoding and axis.labelAngle affect VG axis.encode\n return !!axis.encoding || !!axis.labelAngle;\n case 'title':\n // title can be explicit if fieldDef.title is set\n if (value === getFieldDefTitle(model, channel)) {\n return true;\n }\n }\n // Otherwise, things are explicit if the returned value matches the specified property\n return value === axis[property];\n}\n/**\n * Properties to always include values from config\n */\nconst propsToAlwaysIncludeConfig = new Set([\n 'grid',\n 'translate',\n // the rest are not axis configs in Vega, but are in VL, so we need to set too.\n 'format',\n 'formatType',\n 'orient',\n 'labelExpr',\n 'tickCount',\n 'position',\n 'tickMinStep'\n]);\nfunction parseAxis(channel, model) {\n var _a, _b, _c;\n let axis = model.axis(channel);\n const axisComponent = new AxisComponent();\n const fieldOrDatumDef = getFieldOrDatumDef(model.encoding[channel]);\n const { mark, config } = model;\n const orient = (axis === null || axis === void 0 ? void 0 : axis.orient) ||\n ((_a = config[channel === 'x' ? 'axisX' : 'axisY']) === null || _a === void 0 ? void 0 : _a.orient) ||\n ((_b = config.axis) === null || _b === void 0 ? void 0 : _b.orient) ||\n defaultOrient(channel);\n const scaleType = model.getScaleComponent(channel).get('type');\n const axisConfigs = getAxisConfigs(channel, scaleType, orient, model.config);\n const disable = axis !== undefined ? !axis : getAxisConfig('disable', config.style, axis === null || axis === void 0 ? void 0 : axis.style, axisConfigs).configValue;\n axisComponent.set('disable', disable, axis !== undefined);\n if (disable) {\n return axisComponent;\n }\n axis = axis || {};\n const labelAngle = getLabelAngle(fieldOrDatumDef, axis, channel, config.style, axisConfigs);\n const ruleParams = {\n fieldOrDatumDef,\n axis,\n channel,\n model,\n scaleType,\n orient,\n labelAngle,\n mark,\n config\n };\n // 1.2. Add properties\n for (const property of AXIS_COMPONENT_PROPERTIES) {\n const value = property in axisRules ? axisRules[property](ruleParams) : isAxisProperty(property) ? axis[property] : undefined;\n const hasValue = value !== undefined;\n const explicit = isExplicit(value, property, axis, model, channel);\n if (hasValue && explicit) {\n axisComponent.set(property, value, explicit);\n }\n else {\n const { configValue = undefined, configFrom = undefined } = isAxisProperty(property) && property !== 'values'\n ? getAxisConfig(property, config.style, axis.style, axisConfigs)\n : {};\n const hasConfigValue = configValue !== undefined;\n if (hasValue && !hasConfigValue) {\n // only set property if it is explicitly set or has no config value (otherwise we will accidentally override config)\n axisComponent.set(property, value, explicit);\n }\n else if (\n // Cases need implicit values\n // 1. Axis config that aren't available in Vega\n !(configFrom === 'vgAxisConfig') ||\n // 2. Certain properties are always included (see `propsToAlwaysIncludeConfig`'s declaration for more details)\n (propsToAlwaysIncludeConfig.has(property) && hasConfigValue) ||\n // 3. Conditional axis values and signals\n isConditionalAxisValue(configValue) ||\n isSignalRef(configValue)) {\n // If a config is specified and is conditional, copy conditional value from axis config\n axisComponent.set(property, configValue, false);\n }\n }\n }\n // 2) Add guide encode definition groups\n const axisEncoding = (_c = axis.encoding) !== null && _c !== void 0 ? _c : {};\n const axisEncode = AXIS_PARTS.reduce((e, part) => {\n var _a;\n if (!axisComponent.hasAxisPart(part)) {\n // No need to create encode for a disabled part.\n return e;\n }\n const axisEncodingPart = guideEncodeEntry((_a = axisEncoding[part]) !== null && _a !== void 0 ? _a : {}, model);\n const value = part === 'labels' ? encode.labels(model, channel, axisEncodingPart) : axisEncodingPart;\n if (value !== undefined && !isEmpty(value)) {\n e[part] = { update: value };\n }\n return e;\n }, {});\n // FIXME: By having encode as one property, we won't have fine grained encode merging.\n if (!isEmpty(axisEncode)) {\n axisComponent.set('encode', axisEncode, !!axis.encoding || axis.labelAngle !== undefined);\n }\n return axisComponent;\n}\n//# sourceMappingURL=parse.js.map","import { getSecondaryRangeChannel } from '../../channel';\nimport { getFieldOrDatumDef } from '../../channeldef';\nimport { formatCustomType, isCustomFormatType } from '../format';\nexport function labels(model, channel, specifiedLabelsSpec) {\n var _a;\n const { encoding, config } = model;\n const fieldOrDatumDef = (_a = getFieldOrDatumDef(encoding[channel])) !== null && _a !== void 0 ? _a : getFieldOrDatumDef(encoding[getSecondaryRangeChannel(channel)]);\n const axis = model.axis(channel) || {};\n const { format, formatType } = axis;\n if (isCustomFormatType(formatType)) {\n return Object.assign({ text: formatCustomType({\n fieldOrDatumDef,\n field: 'datum.value',\n format,\n formatType,\n config\n }) }, specifiedLabelsSpec);\n }\n return specifiedLabelsSpec;\n}\n//# sourceMappingURL=encode.js.map","import { getSizeChannel, POSITION_SCALE_CHANNELS } from '../../channel';\nimport { isContinuousFieldOrDatumDef } from '../../channeldef';\nimport * as log from '../../log';\nimport { isStep } from '../../spec/base';\nexport function initLayoutSize({ encoding, size }) {\n for (const channel of POSITION_SCALE_CHANNELS) {\n const sizeType = getSizeChannel(channel);\n if (isStep(size[sizeType])) {\n if (isContinuousFieldOrDatumDef(encoding[channel])) {\n delete size[sizeType];\n log.warn(log.message.stepDropped(sizeType));\n }\n }\n }\n return size;\n}\n//# sourceMappingURL=init.js.map","import { isBinned, isBinning } from '../../bin';\nimport { isContinuousFieldOrDatumDef, isFieldDef, isNumericDataDef } from '../../channeldef';\nimport { isAggregate } from '../../encoding';\nimport { replaceExprRef } from '../../expr';\nimport * as log from '../../log';\nimport { AREA, BAR, BAR_CORNER_RADIUS_INDEX as BAR_CORNER_RADIUS_END_INDEX, CIRCLE, IMAGE, LINE, POINT, RECT, RULE, SQUARE, TEXT, TICK } from '../../mark';\nimport { QUANTITATIVE, TEMPORAL } from '../../type';\nimport { contains, getFirstDefined } from '../../util';\nimport { getMarkConfig, getMarkPropOrConfig } from '../common';\nexport function initMarkdef(originalMarkDef, encoding, config) {\n // FIXME: markDef expects that exprRefs are replaced recursively but replaceExprRef only replaces the top level\n const markDef = replaceExprRef(originalMarkDef);\n // set orient, which can be overridden by rules as sometimes the specified orient is invalid.\n const specifiedOrient = getMarkPropOrConfig('orient', markDef, config);\n markDef.orient = orient(markDef.type, encoding, specifiedOrient);\n if (specifiedOrient !== undefined && specifiedOrient !== markDef.orient) {\n log.warn(log.message.orientOverridden(markDef.orient, specifiedOrient));\n }\n if (markDef.type === 'bar' && markDef.orient) {\n const cornerRadiusEnd = getMarkPropOrConfig('cornerRadiusEnd', markDef, config);\n if (cornerRadiusEnd !== undefined) {\n const newProps = (markDef.orient === 'horizontal' && encoding.x2) || (markDef.orient === 'vertical' && encoding.y2)\n ? ['cornerRadius']\n : BAR_CORNER_RADIUS_END_INDEX[markDef.orient];\n for (const newProp of newProps) {\n markDef[newProp] = cornerRadiusEnd;\n }\n if (markDef.cornerRadiusEnd !== undefined) {\n delete markDef.cornerRadiusEnd; // no need to keep the original cap cornerRadius\n }\n }\n }\n // set opacity and filled if not specified in mark config\n const specifiedOpacity = getMarkPropOrConfig('opacity', markDef, config);\n if (specifiedOpacity === undefined) {\n markDef.opacity = opacity(markDef.type, encoding);\n }\n // set cursor, which should be pointer if href channel is present unless otherwise specified\n const specifiedCursor = getMarkPropOrConfig('cursor', markDef, config);\n if (specifiedCursor === undefined) {\n markDef.cursor = cursor(markDef, encoding, config);\n }\n return markDef;\n}\nfunction cursor(markDef, encoding, config) {\n if (encoding.href || markDef.href || getMarkPropOrConfig('href', markDef, config)) {\n return 'pointer';\n }\n return markDef.cursor;\n}\nfunction opacity(mark, encoding) {\n if (contains([POINT, TICK, CIRCLE, SQUARE], mark)) {\n // point-based marks\n if (!isAggregate(encoding)) {\n return 0.7;\n }\n }\n return undefined;\n}\nexport function defaultFilled(markDef, config, { graticule }) {\n if (graticule) {\n return false;\n }\n const filledConfig = getMarkConfig('filled', markDef, config);\n const mark = markDef.type;\n return getFirstDefined(filledConfig, mark !== POINT && mark !== LINE && mark !== RULE);\n}\nfunction orient(mark, encoding, specifiedOrient) {\n switch (mark) {\n case POINT:\n case CIRCLE:\n case SQUARE:\n case TEXT:\n case RECT:\n case IMAGE:\n // orient is meaningless for these marks.\n return undefined;\n }\n const { x, y, x2, y2 } = encoding;\n switch (mark) {\n case BAR:\n if (isFieldDef(x) && (isBinned(x.bin) || (isFieldDef(y) && y.aggregate && !x.aggregate))) {\n return 'vertical';\n }\n if (isFieldDef(y) && (isBinned(y.bin) || (isFieldDef(x) && x.aggregate && !y.aggregate))) {\n return 'horizontal';\n }\n if (y2 || x2) {\n // Ranged bar does not always have clear orientation, so we allow overriding\n if (specifiedOrient) {\n return specifiedOrient;\n }\n // If y is range and x is non-range, non-bin Q, y is likely a prebinned field\n if (!x2) {\n if ((isFieldDef(x) && x.type === QUANTITATIVE && !isBinning(x.bin)) || isNumericDataDef(x)) {\n return 'horizontal';\n }\n }\n // If x is range and y is non-range, non-bin Q, x is likely a prebinned field\n if (!y2) {\n if ((isFieldDef(y) && y.type === QUANTITATIVE && !isBinning(y.bin)) || isNumericDataDef(y)) {\n return 'vertical';\n }\n }\n }\n // falls through\n case RULE:\n // return undefined for line segment rule and bar with both axis ranged\n // we have to ignore the case that the data are already binned\n if (x2 && !(isFieldDef(x) && isBinned(x.bin)) && y2 && !(isFieldDef(y) && isBinned(y.bin))) {\n return undefined;\n }\n // falls through\n case AREA:\n // If there are range for both x and y, y (vertical) has higher precedence.\n if (y2) {\n if (isFieldDef(y) && isBinned(y.bin)) {\n return 'horizontal';\n }\n else {\n return 'vertical';\n }\n }\n else if (x2) {\n if (isFieldDef(x) && isBinned(x.bin)) {\n return 'vertical';\n }\n else {\n return 'horizontal';\n }\n }\n else if (mark === RULE) {\n if (x && !y) {\n return 'vertical';\n }\n else if (y && !x) {\n return 'horizontal';\n }\n }\n // falls through\n case LINE:\n case TICK: {\n // Tick is opposite to bar, line, area and never have ranged mark.\n const xIsContinuous = isContinuousFieldOrDatumDef(x);\n const yIsContinuous = isContinuousFieldOrDatumDef(y);\n if (specifiedOrient) {\n return specifiedOrient;\n }\n else if (xIsContinuous && !yIsContinuous) {\n return mark !== 'tick' ? 'horizontal' : 'vertical';\n }\n else if (!xIsContinuous && yIsContinuous) {\n return mark !== 'tick' ? 'vertical' : 'horizontal';\n }\n else if (xIsContinuous && yIsContinuous) {\n const xDef = x; // we can cast here since they are surely fieldDef\n const yDef = y;\n const xIsTemporal = xDef.type === TEMPORAL;\n const yIsTemporal = yDef.type === TEMPORAL;\n // temporal without timeUnit is considered continuous, but better serves as dimension\n if (xIsTemporal && !yIsTemporal) {\n return mark !== 'tick' ? 'vertical' : 'horizontal';\n }\n else if (!xIsTemporal && yIsTemporal) {\n return mark !== 'tick' ? 'horizontal' : 'vertical';\n }\n if (!xDef.aggregate && yDef.aggregate) {\n return mark !== 'tick' ? 'vertical' : 'horizontal';\n }\n else if (xDef.aggregate && !yDef.aggregate) {\n return mark !== 'tick' ? 'horizontal' : 'vertical';\n }\n return 'vertical';\n }\n else {\n return undefined;\n }\n }\n }\n return 'vertical';\n}\n//# sourceMappingURL=init.js.map","import * as encode from './encode';\nfunction encodeEntry(model, fixedShape) {\n const { config } = model;\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'include',\n orient: 'ignore',\n theta: 'ignore'\n })), encode.pointPosition('x', model, { defaultPos: 'mid' })), encode.pointPosition('y', model, { defaultPos: 'mid' })), encode.nonPosition('size', model)), encode.nonPosition('angle', model)), shapeMixins(model, config, fixedShape));\n}\nexport function shapeMixins(model, config, fixedShape) {\n if (fixedShape) {\n return { shape: { value: fixedShape } };\n }\n return encode.nonPosition('shape', model);\n}\nexport const point = {\n vgMark: 'symbol',\n encodeEntry: (model) => {\n return encodeEntry(model);\n }\n};\nexport const circle = {\n vgMark: 'symbol',\n encodeEntry: (model) => {\n return encodeEntry(model, 'circle');\n }\n};\nexport const square = {\n vgMark: 'symbol',\n encodeEntry: (model) => {\n return encodeEntry(model, 'square');\n }\n};\n//# sourceMappingURL=point.js.map","import { isNumber } from 'vega-util';\nimport { getViewConfigDiscreteStep } from '../../config';\nimport { isVgRangeStep } from '../../vega.schema';\nimport { getMarkPropOrConfig, signalOrValueRef } from '../common';\nimport * as encode from './encode';\nexport const tick = {\n vgMark: 'rect',\n encodeEntry: (model) => {\n const { config, markDef } = model;\n const orient = markDef.orient;\n const vgSizeChannel = orient === 'horizontal' ? 'width' : 'height';\n const vgThicknessChannel = orient === 'horizontal' ? 'height' : 'width';\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n })), encode.pointPosition('x', model, { defaultPos: 'mid', vgChannel: 'xc' })), encode.pointPosition('y', model, { defaultPos: 'mid', vgChannel: 'yc' })), encode.nonPosition('size', model, {\n defaultValue: defaultSize(model),\n vgChannel: vgSizeChannel\n })), { [vgThicknessChannel]: signalOrValueRef(getMarkPropOrConfig('thickness', markDef, config)) });\n }\n};\nfunction defaultSize(model) {\n var _a;\n const { config, markDef } = model;\n const { orient } = markDef;\n const vgSizeChannel = orient === 'horizontal' ? 'width' : 'height';\n const scale = model.getScaleComponent(orient === 'horizontal' ? 'x' : 'y');\n const markPropOrConfig = (_a = getMarkPropOrConfig('size', markDef, config, { vgChannel: vgSizeChannel })) !== null && _a !== void 0 ? _a : config.tick.bandSize;\n if (markPropOrConfig !== undefined) {\n return markPropOrConfig;\n }\n else {\n const scaleRange = scale ? scale.get('range') : undefined;\n if (scaleRange && isVgRangeStep(scaleRange) && isNumber(scaleRange.step)) {\n return (scaleRange.step * 3) / 4;\n }\n const defaultViewStep = getViewConfigDiscreteStep(config.view, vgSizeChannel);\n return (defaultViewStep * 3) / 4;\n }\n}\n//# sourceMappingURL=tick.js.map","import { isArray } from 'vega-util';\nimport { isFieldDef, isValueDef, vgField } from '../../channeldef';\nimport { DataSourceType } from '../../data';\nimport { isAggregate, pathGroupingFields } from '../../encoding';\nimport { AREA, BAR, isPathMark, LINE, TRAIL } from '../../mark';\nimport { isSortByEncoding, isSortField } from '../../sort';\nimport { contains, getFirstDefined, isNullOrFalse, keys, omit, pick } from '../../util';\nimport { VG_CORNERRADIUS_CHANNELS } from '../../vega.schema';\nimport { getMarkConfig, getMarkPropOrConfig, getStyles, signalOrValueRef, sortParams } from '../common';\nimport { arc } from './arc';\nimport { area } from './area';\nimport { bar } from './bar';\nimport { geoshape } from './geoshape';\nimport { image } from './image';\nimport { line, trail } from './line';\nimport { circle, point, square } from './point';\nimport { rect } from './rect';\nimport { rule } from './rule';\nimport { text } from './text';\nimport { tick } from './tick';\nconst markCompiler = {\n arc,\n area,\n bar,\n circle,\n geoshape,\n image,\n line,\n point,\n rect,\n rule,\n square,\n text,\n tick,\n trail\n};\nexport function parseMarkGroups(model) {\n if (contains([LINE, AREA, TRAIL], model.mark)) {\n const details = pathGroupingFields(model.mark, model.encoding);\n if (details.length > 0) {\n return getPathGroups(model, details);\n }\n // otherwise use standard mark groups\n }\n else if (model.mark === BAR) {\n const hasCornerRadius = VG_CORNERRADIUS_CHANNELS.some(prop => getMarkPropOrConfig(prop, model.markDef, model.config));\n if (model.stack && !model.fieldDef('size') && hasCornerRadius) {\n return getGroupsForStackedBarWithCornerRadius(model);\n }\n }\n return getMarkGroup(model);\n}\nconst FACETED_PATH_PREFIX = 'faceted_path_';\nfunction getPathGroups(model, details) {\n // TODO: for non-stacked plot, map order to zindex. (Maybe rename order for layer to zindex?)\n return [\n {\n name: model.getName('pathgroup'),\n type: 'group',\n from: {\n facet: {\n name: FACETED_PATH_PREFIX + model.requestDataName(DataSourceType.Main),\n data: model.requestDataName(DataSourceType.Main),\n groupby: details\n }\n },\n encode: {\n update: {\n width: { field: { group: 'width' } },\n height: { field: { group: 'height' } }\n }\n },\n // With subfacet for line/area group, need to use faceted data from above.\n marks: getMarkGroup(model, { fromPrefix: FACETED_PATH_PREFIX })\n }\n ];\n}\nconst STACK_GROUP_PREFIX = 'stack_group_';\n/**\n * We need to put stacked bars into groups in order to enable cornerRadius for stacks.\n * If stack is used and the model doesn't have size encoding, we put the mark into groups,\n * and apply cornerRadius properties at the group.\n */\nfunction getGroupsForStackedBarWithCornerRadius(model) {\n // Generate the mark\n const [mark] = getMarkGroup(model, { fromPrefix: STACK_GROUP_PREFIX });\n // Get the scale for the stacked field\n const fieldScale = model.scaleName(model.stack.fieldChannel);\n const stackField = (opt = {}) => model.vgField(model.stack.fieldChannel, opt);\n // Find the min/max of the pixel value on the stacked direction\n const stackFieldGroup = (func, expr) => {\n const vgFieldMinMax = [\n stackField({ prefix: 'min', suffix: 'start', expr }),\n stackField({ prefix: 'max', suffix: 'start', expr }),\n stackField({ prefix: 'min', suffix: 'end', expr }),\n stackField({ prefix: 'max', suffix: 'end', expr })\n ];\n return `${func}(${vgFieldMinMax.map(field => `scale('${fieldScale}',${field})`).join(',')})`;\n };\n let groupUpdate;\n let innerGroupUpdate;\n // Build the encoding for group and an inner group\n if (model.stack.fieldChannel === 'x') {\n // Move cornerRadius, y/yc/y2/height properties to group\n // Group x/x2 should be the min/max of the marks within\n groupUpdate = Object.assign(Object.assign({}, pick(mark.encode.update, ['y', 'yc', 'y2', 'height', ...VG_CORNERRADIUS_CHANNELS])), { x: { signal: stackFieldGroup('min', 'datum') }, x2: { signal: stackFieldGroup('max', 'datum') }, clip: { value: true } });\n // Inner group should revert the x translation, and pass height through\n innerGroupUpdate = {\n x: { field: { group: 'x' }, mult: -1 },\n height: { field: { group: 'height' } }\n };\n // The marks should use the same height as group, without y/yc/y2 properties (because it's already done by group)\n // This is why size encoding is not supported yet\n mark.encode.update = Object.assign(Object.assign({}, omit(mark.encode.update, ['y', 'yc', 'y2'])), { height: { field: { group: 'height' } } });\n }\n else {\n groupUpdate = Object.assign(Object.assign({}, pick(mark.encode.update, ['x', 'xc', 'x2', 'width'])), { y: { signal: stackFieldGroup('min', 'datum') }, y2: { signal: stackFieldGroup('max', 'datum') }, clip: { value: true } });\n innerGroupUpdate = {\n y: { field: { group: 'y' }, mult: -1 },\n width: { field: { group: 'width' } }\n };\n mark.encode.update = Object.assign(Object.assign({}, omit(mark.encode.update, ['x', 'xc', 'x2'])), { width: { field: { group: 'width' } } });\n }\n // Deal with cornerRadius properties\n for (const key of VG_CORNERRADIUS_CHANNELS) {\n const configValue = getMarkConfig(key, model.markDef, model.config);\n // Move from mark to group\n if (mark.encode.update[key]) {\n groupUpdate[key] = mark.encode.update[key];\n delete mark.encode.update[key];\n }\n else if (configValue) {\n groupUpdate[key] = signalOrValueRef(configValue);\n }\n // Overwrite any cornerRadius on mark set by config --- they are already moved to the group\n if (configValue) {\n mark.encode.update[key] = { value: 0 };\n }\n }\n const groupby = [];\n if (model.stack.groupbyChannel) {\n // For bin and time unit, we have to add bin/timeunit -end channels.\n const groupByField = model.fieldDef(model.stack.groupbyChannel);\n const field = vgField(groupByField);\n if (field) {\n groupby.push(field);\n }\n if ((groupByField === null || groupByField === void 0 ? void 0 : groupByField.bin) || (groupByField === null || groupByField === void 0 ? void 0 : groupByField.timeUnit)) {\n groupby.push(vgField(groupByField, { binSuffix: 'end' }));\n }\n }\n const strokeProperties = [\n 'stroke',\n 'strokeWidth',\n 'strokeJoin',\n 'strokeCap',\n 'strokeDash',\n 'strokeDashOffset',\n 'strokeMiterLimit',\n 'strokeOpacity'\n ];\n // Generate stroke properties for the group\n groupUpdate = strokeProperties.reduce((encode, prop) => {\n if (mark.encode.update[prop]) {\n return Object.assign(Object.assign({}, encode), { [prop]: mark.encode.update[prop] });\n }\n else {\n const configValue = getMarkConfig(prop, model.markDef, model.config);\n if (configValue !== undefined) {\n return Object.assign(Object.assign({}, encode), { [prop]: signalOrValueRef(configValue) });\n }\n else {\n return encode;\n }\n }\n }, groupUpdate);\n // Apply strokeForeground and strokeOffset if stroke is used\n if (groupUpdate.stroke) {\n groupUpdate.strokeForeground = { value: true };\n groupUpdate.strokeOffset = { value: 0 };\n }\n return [\n {\n type: 'group',\n from: {\n facet: {\n data: model.requestDataName(DataSourceType.Main),\n name: STACK_GROUP_PREFIX + model.requestDataName(DataSourceType.Main),\n groupby,\n aggregate: {\n fields: [\n stackField({ suffix: 'start' }),\n stackField({ suffix: 'start' }),\n stackField({ suffix: 'end' }),\n stackField({ suffix: 'end' })\n ],\n ops: ['min', 'max', 'min', 'max']\n }\n }\n },\n encode: {\n update: groupUpdate\n },\n marks: [\n {\n type: 'group',\n encode: { update: innerGroupUpdate },\n marks: [mark]\n }\n ]\n }\n ];\n}\nexport function getSort(model) {\n var _a;\n const { encoding, stack, mark, markDef, config } = model;\n const order = encoding.order;\n if ((!isArray(order) && isValueDef(order) && isNullOrFalse(order.value)) ||\n (!order && isNullOrFalse(getMarkPropOrConfig('order', markDef, config)))) {\n return undefined;\n }\n else if ((isArray(order) || isFieldDef(order)) && !stack) {\n // Sort by the order field if it is specified and the field is not stacked. (For stacked field, order specify stack order.)\n return sortParams(order, { expr: 'datum' });\n }\n else if (isPathMark(mark)) {\n // For both line and area, we sort values based on dimension by default\n const dimensionChannel = markDef.orient === 'horizontal' ? 'y' : 'x';\n const dimensionChannelDef = encoding[dimensionChannel];\n if (isFieldDef(dimensionChannelDef)) {\n const s = dimensionChannelDef.sort;\n if (isArray(s)) {\n return {\n field: vgField(dimensionChannelDef, { prefix: dimensionChannel, suffix: 'sort_index', expr: 'datum' })\n };\n }\n else if (isSortField(s)) {\n return {\n field: vgField({\n // FIXME: this op might not already exist?\n // FIXME: what if dimensionChannel (x or y) contains custom domain?\n aggregate: isAggregate(model.encoding) ? s.op : undefined,\n field: s.field\n }, { expr: 'datum' })\n };\n }\n else if (isSortByEncoding(s)) {\n const fieldDefToSort = model.fieldDef(s.encoding);\n return {\n field: vgField(fieldDefToSort, { expr: 'datum' }),\n order: s.order\n };\n }\n else if (s === null) {\n return undefined;\n }\n else {\n return {\n field: vgField(dimensionChannelDef, {\n // For stack with imputation, we only have bin_mid\n binSuffix: ((_a = model.stack) === null || _a === void 0 ? void 0 : _a.impute) ? 'mid' : undefined,\n expr: 'datum'\n })\n };\n }\n }\n return undefined;\n }\n return undefined;\n}\nfunction getMarkGroup(model, opt = { fromPrefix: '' }) {\n const { mark, markDef, encoding, config } = model;\n const clip = getFirstDefined(markDef.clip, scaleClip(model), projectionClip(model));\n const style = getStyles(markDef);\n const key = encoding.key;\n const sort = getSort(model);\n const interactive = interactiveFlag(model);\n const aria = getMarkPropOrConfig('aria', markDef, config);\n const postEncodingTransform = markCompiler[mark].postEncodingTransform\n ? markCompiler[mark].postEncodingTransform(model)\n : null;\n return [\n Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name: model.getName('marks'), type: markCompiler[mark].vgMark }, (clip ? { clip: true } : {})), (style ? { style } : {})), (key ? { key: key.field } : {})), (sort ? { sort } : {})), (interactive ? interactive : {})), (aria === false ? { aria } : {})), { from: { data: opt.fromPrefix + model.requestDataName(DataSourceType.Main) }, encode: {\n update: markCompiler[mark].encodeEntry(model)\n } }), (postEncodingTransform\n ? {\n transform: postEncodingTransform\n }\n : {}))\n ];\n}\n/**\n * If scales are bound to interval selections, we want to automatically clip\n * marks to account for panning/zooming interactions. We identify bound scales\n * by the selectionExtent property, which gets added during scale parsing.\n */\nfunction scaleClip(model) {\n const xScale = model.getScaleComponent('x');\n const yScale = model.getScaleComponent('y');\n return (xScale && xScale.get('selectionExtent')) || (yScale && yScale.get('selectionExtent')) ? true : undefined;\n}\n/**\n * If we use a custom projection with auto-fitting to the geodata extent,\n * we need to clip to ensure the chart size doesn't explode.\n */\nfunction projectionClip(model) {\n const projection = model.component.projection;\n return projection && !projection.isFit ? true : undefined;\n}\n/**\n * Only output interactive flags if we have selections defined somewhere in our model hierarchy.\n */\nfunction interactiveFlag(model) {\n if (!model.component.selection)\n return null;\n const unitCount = keys(model.component.selection).length;\n let parentCount = unitCount;\n let parent = model.parent;\n while (parent && parentCount === 0) {\n parentCount = keys(parent.component.selection).length;\n parent = parent.parent;\n }\n return parentCount\n ? {\n interactive: unitCount > 0 || !!model.encoding.tooltip\n }\n : null;\n}\n//# sourceMappingURL=mark.js.map","import * as encode from './encode';\nexport const arc = {\n vgMark: 'arc',\n encodeEntry: (model) => {\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'ignore',\n orient: 'ignore',\n theta: 'ignore'\n })), encode.pointPosition('x', model, { defaultPos: 'mid' })), encode.pointPosition('y', model, { defaultPos: 'mid' })), encode.rectPosition(model, 'radius', 'arc')), encode.rectPosition(model, 'theta', 'arc'));\n }\n};\n//# sourceMappingURL=arc.js.map","import * as encode from './encode';\nexport const area = {\n vgMark: 'area',\n encodeEntry: (model) => {\n return Object.assign(Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'include',\n size: 'ignore',\n theta: 'ignore'\n })), encode.pointOrRangePosition('x', model, {\n defaultPos: 'zeroOrMin',\n defaultPos2: 'zeroOrMin',\n range: model.markDef.orient === 'horizontal'\n })), encode.pointOrRangePosition('y', model, {\n defaultPos: 'zeroOrMin',\n defaultPos2: 'zeroOrMin',\n range: model.markDef.orient === 'vertical'\n })), encode.defined(model));\n }\n};\n//# sourceMappingURL=area.js.map","import * as encode from './encode';\nexport const bar = {\n vgMark: 'rect',\n encodeEntry: (model) => {\n return Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n })), encode.rectPosition(model, 'x', 'bar')), encode.rectPosition(model, 'y', 'bar'));\n }\n};\n//# sourceMappingURL=bar.js.map","import { isFieldDef, vgField } from '../../channeldef';\nimport { GEOJSON } from '../../type';\nimport * as encode from './encode';\nexport const geoshape = {\n vgMark: 'shape',\n encodeEntry: (model) => {\n return Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'ignore',\n orient: 'ignore',\n theta: 'ignore'\n }));\n },\n postEncodingTransform: (model) => {\n const { encoding } = model;\n const shapeDef = encoding.shape;\n const transform = Object.assign({ type: 'geoshape', projection: model.projectionName() }, (shapeDef && isFieldDef(shapeDef) && shapeDef.type === GEOJSON\n ? { field: vgField(shapeDef, { expr: 'datum' }) }\n : {}));\n return [transform];\n }\n};\n//# sourceMappingURL=geoshape.js.map","import * as encode from './encode';\nexport const image = {\n vgMark: 'image',\n encodeEntry: (model) => {\n return Object.assign(Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'ignore',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n })), encode.rectPosition(model, 'x', 'image')), encode.rectPosition(model, 'y', 'image')), encode.text(model, 'url'));\n }\n};\n//# sourceMappingURL=image.js.map","import * as encode from './encode';\nexport const line = {\n vgMark: 'line',\n encodeEntry: (model) => {\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'ignore',\n orient: 'ignore',\n theta: 'ignore'\n })), encode.pointPosition('x', model, { defaultPos: 'mid' })), encode.pointPosition('y', model, { defaultPos: 'mid' })), encode.nonPosition('size', model, {\n vgChannel: 'strokeWidth' // VL's line size is strokeWidth\n })), encode.defined(model));\n }\n};\nexport const trail = {\n vgMark: 'trail',\n encodeEntry: (model) => {\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n size: 'include',\n orient: 'ignore',\n theta: 'ignore'\n })), encode.pointPosition('x', model, { defaultPos: 'mid' })), encode.pointPosition('y', model, { defaultPos: 'mid' })), encode.nonPosition('size', model)), encode.defined(model));\n }\n};\n//# sourceMappingURL=line.js.map","import * as encode from './encode';\nexport const rect = {\n vgMark: 'rect',\n encodeEntry: (model) => {\n return Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n })), encode.rectPosition(model, 'x', 'rect')), encode.rectPosition(model, 'y', 'rect'));\n }\n};\n//# sourceMappingURL=rect.js.map","import * as encode from './encode';\nexport const rule = {\n vgMark: 'rule',\n encodeEntry: (model) => {\n const { markDef } = model;\n const orient = markDef.orient;\n if (!model.encoding.x && !model.encoding.y && !model.encoding.latitude && !model.encoding.longitude) {\n // Show nothing if we have none of x, y, lat, and long.\n return {};\n }\n return Object.assign(Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'ignore',\n baseline: 'ignore',\n color: 'include',\n orient: 'ignore',\n size: 'ignore',\n theta: 'ignore'\n })), encode.pointOrRangePosition('x', model, {\n defaultPos: orient === 'horizontal' ? 'zeroOrMax' : 'mid',\n defaultPos2: 'zeroOrMin',\n range: orient !== 'vertical' // include x2 for horizontal or line segment rule\n })), encode.pointOrRangePosition('y', model, {\n defaultPos: orient === 'vertical' ? 'zeroOrMax' : 'mid',\n defaultPos2: 'zeroOrMin',\n range: orient !== 'horizontal' // include y2 for vertical or line segment rule\n })), encode.nonPosition('size', model, {\n vgChannel: 'strokeWidth' // VL's rule size is strokeWidth\n }));\n }\n};\n//# sourceMappingURL=rule.js.map","import { getMarkPropOrConfig } from '../common';\nimport * as encode from './encode';\nexport const text = {\n vgMark: 'text',\n encodeEntry: (model) => {\n const { config, encoding } = model;\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, encode.baseEncodeEntry(model, {\n align: 'include',\n baseline: 'include',\n color: 'include',\n size: 'ignore',\n orient: 'ignore',\n theta: 'include'\n })), encode.pointPosition('x', model, { defaultPos: 'mid' })), encode.pointPosition('y', model, { defaultPos: 'mid' })), encode.text(model)), encode.nonPosition('size', model, {\n vgChannel: 'fontSize' // VL's text size is fontSize\n })), encode.nonPosition('angle', model)), encode.valueIfDefined('align', align(model.markDef, encoding, config))), encode.valueIfDefined('baseline', baseline(model.markDef, encoding, config))), encode.pointPosition('radius', model, { defaultPos: null })), encode.pointPosition('theta', model, { defaultPos: null }));\n }\n};\nfunction align(markDef, encoding, config) {\n const a = getMarkPropOrConfig('align', markDef, config);\n if (a === undefined) {\n return 'center';\n }\n // If there is a config, Vega-parser will process this already.\n return undefined;\n}\nfunction baseline(markDef, encoding, config) {\n const b = getMarkPropOrConfig('baseline', markDef, config);\n if (b === undefined) {\n return 'middle';\n }\n // If there is a config, Vega-parser will process this already.\n return undefined;\n}\n//# sourceMappingURL=text.js.map","import { isArray } from 'vega-util';\nimport { isConditionalAxisValue } from '../axis';\nimport { GEOPOSITION_CHANNELS, NONPOSITION_SCALE_CHANNELS, POSITION_SCALE_CHANNELS, SCALE_CHANNELS, supportLegend, X, Y } from '../channel';\nimport { getFieldDef, getFieldOrDatumDef, isFieldOrDatumDef, isTypedFieldDef } from '../channeldef';\nimport { isGraticuleGenerator } from '../data';\nimport * as vlEncoding from '../encoding';\nimport { initEncoding } from '../encoding';\nimport { replaceExprRef } from '../expr';\nimport { GEOSHAPE, isMarkDef } from '../mark';\nimport { isSelectionParameter } from '../selection';\nimport { isFrameMixins } from '../spec/base';\nimport { stack } from '../stack';\nimport { keys } from '../util';\nimport { assembleAxisSignals } from './axis/assemble';\nimport { parseUnitAxes } from './axis/parse';\nimport { signalOrValueRefWithCondition, signalRefOrValue } from './common';\nimport { parseData } from './data/parse';\nimport { assembleLayoutSignals } from './layoutsize/assemble';\nimport { initLayoutSize } from './layoutsize/init';\nimport { parseUnitLayoutSize } from './layoutsize/parse';\nimport { defaultFilled, initMarkdef } from './mark/init';\nimport { parseMarkGroups } from './mark/mark';\nimport { isLayerModel, ModelWithField } from './model';\nimport { assembleTopLevelSignals, assembleUnitSelectionData, assembleUnitSelectionMarks, assembleUnitSelectionSignals } from './selection/assemble';\nimport { parseUnitSelection } from './selection/parse';\n/**\n * Internal model of Vega-Lite specification for the compiler.\n */\nexport class UnitModel extends ModelWithField {\n constructor(spec, parent, parentGivenName, parentGivenSize = {}, config) {\n var _a;\n super(spec, 'unit', parent, parentGivenName, config, undefined, isFrameMixins(spec) ? spec.view : undefined);\n this.specifiedScales = {};\n this.specifiedAxes = {};\n this.specifiedLegends = {};\n this.specifiedProjection = {};\n this.selection = [];\n this.children = [];\n const markDef = isMarkDef(spec.mark) ? Object.assign({}, spec.mark) : { type: spec.mark };\n const mark = markDef.type;\n // Need to init filled before other mark properties because encoding depends on filled but other mark properties depend on types inside encoding\n if (markDef.filled === undefined) {\n markDef.filled = defaultFilled(markDef, config, {\n graticule: spec.data && isGraticuleGenerator(spec.data)\n });\n }\n const encoding = (this.encoding = initEncoding(spec.encoding || {}, mark, markDef.filled, config));\n this.markDef = initMarkdef(markDef, encoding, config);\n this.size = initLayoutSize({\n encoding: encoding,\n size: isFrameMixins(spec)\n ? Object.assign(Object.assign(Object.assign({}, parentGivenSize), (spec.width ? { width: spec.width } : {})), (spec.height ? { height: spec.height } : {})) : parentGivenSize\n });\n // calculate stack properties\n this.stack = stack(mark, encoding);\n this.specifiedScales = this.initScales(mark, encoding);\n this.specifiedAxes = this.initAxes(encoding);\n this.specifiedLegends = this.initLegends(encoding);\n this.specifiedProjection = spec.projection;\n // Selections will be initialized upon parse.\n this.selection = ((_a = spec.params) !== null && _a !== void 0 ? _a : []).filter(p => isSelectionParameter(p));\n }\n get hasProjection() {\n const { encoding } = this;\n const isGeoShapeMark = this.mark === GEOSHAPE;\n const hasGeoPosition = encoding && GEOPOSITION_CHANNELS.some(channel => isFieldOrDatumDef(encoding[channel]));\n return isGeoShapeMark || hasGeoPosition;\n }\n /**\n * Return specified Vega-Lite scale domain for a particular channel\n * @param channel\n */\n scaleDomain(channel) {\n const scale = this.specifiedScales[channel];\n return scale ? scale.domain : undefined;\n }\n axis(channel) {\n return this.specifiedAxes[channel];\n }\n legend(channel) {\n return this.specifiedLegends[channel];\n }\n initScales(mark, encoding) {\n return SCALE_CHANNELS.reduce((scales, channel) => {\n var _a;\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);\n if (fieldOrDatumDef) {\n scales[channel] = this.initScale((_a = fieldOrDatumDef.scale) !== null && _a !== void 0 ? _a : {});\n }\n return scales;\n }, {});\n }\n initScale(scale) {\n const { domain, range } = scale;\n // TODO: we could simplify this function if we had a recursive replace function\n const scaleInternal = replaceExprRef(scale);\n if (isArray(domain)) {\n scaleInternal.domain = domain.map(signalRefOrValue);\n }\n if (isArray(range)) {\n scaleInternal.range = range.map(signalRefOrValue);\n }\n return scaleInternal;\n }\n initAxes(encoding) {\n return POSITION_SCALE_CHANNELS.reduce((_axis, channel) => {\n // Position Axis\n // TODO: handle ConditionFieldDef\n const channelDef = encoding[channel];\n if (isFieldOrDatumDef(channelDef) ||\n (channel === X && isFieldOrDatumDef(encoding.x2)) ||\n (channel === Y && isFieldOrDatumDef(encoding.y2))) {\n const axisSpec = isFieldOrDatumDef(channelDef) ? channelDef.axis : undefined;\n _axis[channel] = axisSpec\n ? this.initAxis(Object.assign({}, axisSpec)) // convert truthy value to object\n : axisSpec;\n }\n return _axis;\n }, {});\n }\n initAxis(axis) {\n const props = keys(axis);\n const axisInternal = {};\n for (const prop of props) {\n const val = axis[prop];\n axisInternal[prop] = isConditionalAxisValue(val)\n ? signalOrValueRefWithCondition(val)\n : signalRefOrValue(val);\n }\n return axisInternal;\n }\n initLegends(encoding) {\n return NONPOSITION_SCALE_CHANNELS.reduce((_legend, channel) => {\n const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);\n if (fieldOrDatumDef && supportLegend(channel)) {\n const legend = fieldOrDatumDef.legend;\n _legend[channel] = legend\n ? replaceExprRef(legend) // convert truthy value to object\n : legend;\n }\n return _legend;\n }, {});\n }\n parseData() {\n this.component.data = parseData(this);\n }\n parseLayoutSize() {\n parseUnitLayoutSize(this);\n }\n parseSelections() {\n this.component.selection = parseUnitSelection(this, this.selection);\n }\n parseMarkGroup() {\n this.component.mark = parseMarkGroups(this);\n }\n parseAxesAndHeaders() {\n this.component.axes = parseUnitAxes(this);\n }\n assembleSelectionTopLevelSignals(signals) {\n return assembleTopLevelSignals(this, signals);\n }\n assembleSignals() {\n return [...assembleAxisSignals(this), ...assembleUnitSelectionSignals(this, [])];\n }\n assembleSelectionData(data) {\n return assembleUnitSelectionData(this, data);\n }\n assembleLayout() {\n return null;\n }\n assembleLayoutSignals() {\n return assembleLayoutSignals(this);\n }\n assembleMarks() {\n var _a;\n let marks = (_a = this.component.mark) !== null && _a !== void 0 ? _a : [];\n // If this unit is part of a layer, selections should augment\n // all in concert rather than each unit individually. This\n // ensures correct interleaving of clipping and brushed marks.\n if (!this.parent || !isLayerModel(this.parent)) {\n marks = assembleUnitSelectionMarks(this, marks);\n }\n return marks.map(this.correctDataNames);\n }\n assembleGroupStyle() {\n const { style } = this.view || {};\n if (style !== undefined) {\n return style;\n }\n if (this.encoding.x || this.encoding.y) {\n return 'cell';\n }\n else {\n return undefined;\n }\n }\n getMapping() {\n return this.encoding;\n }\n get mark() {\n return this.markDef.type;\n }\n channelHasField(channel) {\n return vlEncoding.channelHasField(this.encoding, channel);\n }\n fieldDef(channel) {\n const channelDef = this.encoding[channel];\n return getFieldDef(channelDef);\n }\n typedFieldDef(channel) {\n const fieldDef = this.fieldDef(channel);\n if (isTypedFieldDef(fieldDef)) {\n return fieldDef;\n }\n return null;\n }\n}\n//# sourceMappingURL=unit.js.map","import { array } from 'vega-util';\nimport * as log from '../log';\nimport { isLayerSpec, isUnitSpec } from '../spec';\nimport { keys } from '../util';\nimport { assembleAxisSignals } from './axis/assemble';\nimport { parseLayerAxes } from './axis/parse';\nimport { parseData } from './data/parse';\nimport { assembleLayoutSignals } from './layoutsize/assemble';\nimport { parseLayerLayoutSize } from './layoutsize/parse';\nimport { assembleLegends } from './legend/assemble';\nimport { Model } from './model';\nimport { assembleLayerSelectionMarks } from './selection/assemble';\nimport { UnitModel } from './unit';\nexport class LayerModel extends Model {\n constructor(spec, parent, parentGivenName, parentGivenSize, config) {\n super(spec, 'layer', parent, parentGivenName, config, spec.resolve, spec.view);\n const layoutSize = Object.assign(Object.assign(Object.assign({}, parentGivenSize), (spec.width ? { width: spec.width } : {})), (spec.height ? { height: spec.height } : {}));\n this.children = spec.layer.map((layer, i) => {\n if (isLayerSpec(layer)) {\n return new LayerModel(layer, this, this.getName(`layer_${i}`), layoutSize, config);\n }\n else if (isUnitSpec(layer)) {\n return new UnitModel(layer, this, this.getName(`layer_${i}`), layoutSize, config);\n }\n throw new Error(log.message.invalidSpec(layer));\n });\n }\n parseData() {\n this.component.data = parseData(this);\n for (const child of this.children) {\n child.parseData();\n }\n }\n parseLayoutSize() {\n parseLayerLayoutSize(this);\n }\n parseSelections() {\n // Merge selections up the hierarchy so that they may be referenced\n // across unit specs. Persist their definitions within each child\n // to assemble signals which remain within output Vega unit groups.\n this.component.selection = {};\n for (const child of this.children) {\n child.parseSelections();\n for (const key of keys(child.component.selection)) {\n this.component.selection[key] = child.component.selection[key];\n }\n }\n }\n parseMarkGroup() {\n for (const child of this.children) {\n child.parseMarkGroup();\n }\n }\n parseAxesAndHeaders() {\n parseLayerAxes(this);\n }\n assembleSelectionTopLevelSignals(signals) {\n return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);\n }\n // TODO: Support same named selections across children.\n assembleSignals() {\n return this.children.reduce((signals, child) => {\n return signals.concat(child.assembleSignals());\n }, assembleAxisSignals(this));\n }\n assembleLayoutSignals() {\n return this.children.reduce((signals, child) => {\n return signals.concat(child.assembleLayoutSignals());\n }, assembleLayoutSignals(this));\n }\n assembleSelectionData(data) {\n return this.children.reduce((db, child) => child.assembleSelectionData(db), data);\n }\n assembleGroupStyle() {\n const uniqueStyles = new Set();\n for (const child of this.children) {\n for (const style of array(child.assembleGroupStyle())) {\n uniqueStyles.add(style);\n }\n }\n const styles = Array.from(uniqueStyles);\n return styles.length > 1 ? styles : styles.length === 1 ? styles[0] : undefined;\n }\n assembleTitle() {\n let title = super.assembleTitle();\n if (title) {\n return title;\n }\n // If title does not provide layer, look into children\n for (const child of this.children) {\n title = child.assembleTitle();\n if (title) {\n return title;\n }\n }\n return undefined;\n }\n assembleLayout() {\n return null;\n }\n assembleMarks() {\n return assembleLayerSelectionMarks(this, this.children.flatMap(child => {\n return child.assembleMarks();\n }));\n }\n assembleLegends() {\n return this.children.reduce((legends, child) => {\n return legends.concat(child.assembleLegends());\n }, assembleLegends(this));\n }\n}\n//# sourceMappingURL=layer.js.map","import * as log from '../log';\nimport { isAnyConcatSpec, isFacetSpec, isLayerSpec, isUnitSpec } from '../spec';\nimport { ConcatModel } from './concat';\nimport { FacetModel } from './facet';\nimport { LayerModel } from './layer';\nimport { UnitModel } from './unit';\nexport function buildModel(spec, parent, parentGivenName, unitSize, config) {\n if (isFacetSpec(spec)) {\n return new FacetModel(spec, parent, parentGivenName, config);\n }\n else if (isLayerSpec(spec)) {\n return new LayerModel(spec, parent, parentGivenName, unitSize, config);\n }\n else if (isUnitSpec(spec)) {\n return new UnitModel(spec, parent, parentGivenName, unitSize, config);\n }\n else if (isAnyConcatSpec(spec)) {\n return new ConcatModel(spec, parent, parentGivenName, config);\n }\n throw new Error(log.message.invalidSpec(spec));\n}\n//# sourceMappingURL=buildmodel.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isString, mergeConfig } from 'vega-util';\nimport { getPositionScaleChannel } from '../channel';\nimport * as vlFieldDef from '../channeldef';\nimport { initConfig, stripAndRedirectConfig } from '../config';\nimport * as log from '../log';\nimport { normalize } from '../normalize';\nimport { assembleParameterSignals } from '../parameter';\nimport { extractTopLevelProperties, getFitType, isFitType } from '../spec/toplevel';\nimport { keys } from '../util';\nimport { buildModel } from './buildmodel';\nimport { assembleRootData } from './data/assemble';\nimport { optimizeDataflow } from './data/optimize';\n/**\n * Vega-Lite's main function, for compiling Vega-Lite spec into Vega spec.\n *\n * At a high-level, we make the following transformations in different phases:\n *\n * Input spec\n * |\n * | (Normalization)\n * v\n * Normalized Spec (Row/Column channels in single-view specs becomes faceted specs, composite marks becomes layered specs.)\n * |\n * | (Build Model)\n * v\n * A model tree of the spec\n * |\n * | (Parse)\n * v\n * A model tree with parsed components (intermediate structure of visualization primitives in a format that can be easily merged)\n * |\n * | (Optimize)\n * v\n * A model tree with parsed components with the data component optimized\n * |\n * | (Assemble)\n * v\n * Vega spec\n *\n * @param inputSpec The Vega-Lite specification.\n * @param opt Optional arguments passed to the Vega-Lite compiler.\n * @returns An object containing the compiled Vega spec and normalized Vega-Lite spec.\n */\nexport function compile(inputSpec, opt = {}) {\n // 0. Augment opt with default opts\n if (opt.logger) {\n // set the singleton logger to the provided logger\n log.set(opt.logger);\n }\n if (opt.fieldTitle) {\n // set the singleton field title formatter\n vlFieldDef.setTitleFormatter(opt.fieldTitle);\n }\n try {\n // 1. Initialize config by deep merging default config with the config provided via option and the input spec.\n const config = initConfig(mergeConfig(opt.config, inputSpec.config));\n // 2. Normalize: Convert input spec -> normalized spec\n // - Decompose all extended unit specs into composition of unit spec. For example, a box plot get expanded into multiple layers of bars, ticks, and rules. The shorthand row/column channel is also expanded to a facet spec.\n // - Normalize autosize and width or height spec\n const spec = normalize(inputSpec, config);\n // 3. Build Model: normalized spec -> Model (a tree structure)\n // This phases instantiates the models with default config by doing a top-down traversal. This allows us to pass properties that child models derive from their parents via their constructors.\n // See the abstract `Model` class and its children (UnitModel, LayerModel, FacetModel, ConcatModel) for different types of models.\n const model = buildModel(spec, null, '', undefined, config);\n // 4 Parse: Model --> Model with components\n // Note that components = intermediate representations that are equivalent to Vega specs.\n // We need these intermediate representation because we need to merge many visualization \"components\" like projections, scales, axes, and legends.\n // We will later convert these components into actual Vega specs in the assemble phase.\n // In this phase, we do a bottom-up traversal over the whole tree to\n // parse for each type of components once (e.g., data, layout, mark, scale).\n // By doing bottom-up traversal, we start parsing components of unit specs and\n // then merge child components of parent composite specs.\n //\n // Please see inside model.parse() for order of different components parsed.\n model.parse();\n // drawDataflow(model.component.data.sources);\n // 5. Optimize the dataflow. This will modify the data component of the model.\n optimizeDataflow(model.component.data, model);\n // drawDataflow(model.component.data.sources);\n // 6. Assemble: convert model components --> Vega Spec.\n const vgSpec = assembleTopLevelModel(model, getTopLevelProperties(inputSpec, spec.autosize, config, model), inputSpec.datasets, inputSpec.usermeta);\n return {\n spec: vgSpec,\n normalized: spec\n };\n }\n finally {\n // Reset the singleton logger if a logger is provided\n if (opt.logger) {\n log.reset();\n }\n // Reset the singleton field title formatter if provided\n if (opt.fieldTitle) {\n vlFieldDef.resetTitleFormatter();\n }\n }\n}\nfunction getTopLevelProperties(inputSpec, autosize, config, model) {\n const width = model.component.layoutSize.get('width');\n const height = model.component.layoutSize.get('height');\n if (autosize === undefined) {\n autosize = { type: 'pad' };\n if (model.hasAxisOrientSignalRef()) {\n autosize.resize = true;\n }\n }\n else if (isString(autosize)) {\n autosize = { type: autosize };\n }\n if (width && height && isFitType(autosize.type)) {\n if (width === 'step' && height === 'step') {\n log.warn(log.message.droppingFit());\n autosize.type = 'pad';\n }\n else if (width === 'step' || height === 'step') {\n // effectively XOR, because else if\n // get step dimension\n const sizeType = width === 'step' ? 'width' : 'height';\n // log that we're dropping fit for respective channel\n log.warn(log.message.droppingFit(getPositionScaleChannel(sizeType)));\n // setting type to inverse fit (so if we dropped fit-x, type is now fit-y)\n const inverseSizeType = sizeType === 'width' ? 'height' : 'width';\n autosize.type = getFitType(inverseSizeType);\n }\n }\n return Object.assign(Object.assign(Object.assign({}, (keys(autosize).length === 1 && autosize.type\n ? autosize.type === 'pad'\n ? {}\n : { autosize: autosize.type }\n : { autosize })), extractTopLevelProperties(config, false)), extractTopLevelProperties(inputSpec, true));\n}\n/*\n * Assemble the top-level model to a Vega spec.\n *\n * Note: this couldn't be `model.assemble()` since the top-level model\n * needs some special treatment to generate top-level properties.\n */\nfunction assembleTopLevelModel(model, topLevelProperties, datasets = {}, usermeta) {\n // Config with Vega-Lite only config removed.\n const vgConfig = model.config ? stripAndRedirectConfig(model.config) : undefined;\n const data = [].concat(model.assembleSelectionData([]), \n // only assemble data in the root\n assembleRootData(model.component.data, datasets));\n const projections = model.assembleProjections();\n const title = model.assembleTitle();\n const style = model.assembleGroupStyle();\n const encodeEntry = model.assembleGroupEncodeEntry(true);\n let layoutSignals = model.assembleLayoutSignals();\n // move width and height signals with values to top level\n layoutSignals = layoutSignals.filter(signal => {\n if ((signal.name === 'width' || signal.name === 'height') && signal.value !== undefined) {\n topLevelProperties[signal.name] = +signal.value;\n return false;\n }\n return true;\n });\n const { params } = topLevelProperties, otherTopLevelProps = __rest(topLevelProperties, [\"params\"]);\n return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ $schema: 'https://vega.github.io/schema/vega/v5.json' }, (model.description ? { description: model.description } : {})), otherTopLevelProps), (title ? { title } : {})), (style ? { style } : {})), (encodeEntry ? { encode: { update: encodeEntry } } : {})), { data }), (projections.length > 0 ? { projections: projections } : {})), model.assembleGroup([\n ...layoutSignals,\n ...model.assembleSelectionTopLevelSignals([]),\n ...assembleParameterSignals(params)\n ])), (vgConfig ? { config: vgConfig } : {})), (usermeta ? { usermeta } : {}));\n}\n//# sourceMappingURL=compile.js.map","/**\n * Parse a vega schema url into library and version.\n */\nexport default function(url: string) {\n const regex = /schema\\/([\\w-]+)\\/([\\w\\.\\-]+)\\.json$/g;\n const [library, version] = regex.exec(url)!.slice(1, 3);\n return {library: library as 'vega' | 'vega-lite', version};\n}\n","var name = \"vega-themes\";\nvar version = \"2.10.0\";\nvar description = \"Themes for stylized Vega and Vega-Lite visualizations.\";\nvar keywords = [\n\t\"vega\",\n\t\"vega-lite\",\n\t\"themes\",\n\t\"style\"\n];\nvar license = \"BSD-3-Clause\";\nvar author = {\n\tname: \"UW Interactive Data Lab\",\n\turl: \"https://idl.cs.washington.edu\"\n};\nvar contributors = [\n\t{\n\t\tname: \"Emily Gu\",\n\t\turl: \"https://github.com/emilygu\"\n\t},\n\t{\n\t\tname: \"Arvind Satyanarayan\",\n\t\turl: \"http://arvindsatya.com\"\n\t},\n\t{\n\t\tname: \"Jeffrey Heer\",\n\t\turl: \"https://idl.cs.washington.edu\"\n\t},\n\t{\n\t\tname: \"Dominik Moritz\",\n\t\turl: \"https://www.domoritz.de\"\n\t}\n];\nvar main = \"build/vega-themes.js\";\nvar module = \"build/vega-themes.module.js\";\nvar unpkg = \"build/vega-themes.min.js\";\nvar jsdelivr = \"build/vega-themes.min.js\";\nvar types = \"build/vega-themes.module.d.ts\";\nvar repository = {\n\ttype: \"git\",\n\turl: \"https://github.com/vega/vega-themes.git\"\n};\nvar files = [\n\t\"src\",\n\t\"build\"\n];\nvar scripts = {\n\tprebuild: \"yarn clean\",\n\tbuild: \"rollup -c\",\n\tclean: \"rimraf build && rimraf examples/build\",\n\t\"copy:data\": \"rsync -r node_modules/vega-datasets/data/* examples/data\",\n\t\"copy:build\": \"rsync -r build/* examples/build\",\n\t\"deploy:gh\": \"yarn build && mkdir -p examples/build && rsync -r build/* examples/build && gh-pages -d examples\",\n\tprepublishOnly: \"yarn clean && yarn build\",\n\tpreversion: \"yarn lint\",\n\tserve: \"browser-sync start -s -f build examples --serveStatic examples\",\n\tstart: \"yarn build && concurrently --kill-others -n Server,Rollup 'yarn serve' 'rollup -c -w'\",\n\tprepare: \"beemo create-config\",\n\teslintbase: \"beemo eslint .\",\n\tformat: \"yarn eslintbase --fix\",\n\tlint: \"yarn eslintbase\"\n};\nvar devDependencies = {\n\t\"@rollup/plugin-json\": \"^4.1.0\",\n\t\"@rollup/plugin-node-resolve\": \"^11.2.0\",\n\t\"@wessberg/rollup-plugin-ts\": \"^1.3.8\",\n\t\"browser-sync\": \"^2.26.14\",\n\tconcurrently: \"^6.0.0\",\n\t\"gh-pages\": \"^3.1.0\",\n\trollup: \"^2.39.1\",\n\t\"rollup-plugin-bundle-size\": \"^1.0.3\",\n\t\"rollup-plugin-terser\": \"^7.0.2\",\n\ttypescript: \"^4.2.2\",\n\tvega: \"^5.19.1\",\n\t\"vega-lite\": \"^5.0.0\",\n\t\"vega-lite-dev-config\": \"^0.16.1\"\n};\nvar peerDependencies = {\n\tvega: \"*\",\n\t\"vega-lite\": \"*\"\n};\nvar pkg = {\n\tname: name,\n\tversion: version,\n\tdescription: description,\n\tkeywords: keywords,\n\tlicense: license,\n\tauthor: author,\n\tcontributors: contributors,\n\tmain: main,\n\tmodule: module,\n\tunpkg: unpkg,\n\tjsdelivr: jsdelivr,\n\ttypes: types,\n\trepository: repository,\n\tfiles: files,\n\tscripts: scripts,\n\tdevDependencies: devDependencies,\n\tpeerDependencies: peerDependencies\n};\n\nconst lightColor = '#fff';\nconst medColor = '#888';\nconst darkTheme = {\n background: '#333',\n title: {\n color: lightColor,\n subtitleColor: lightColor\n },\n style: {\n 'guide-label': {\n fill: lightColor,\n },\n 'guide-title': {\n fill: lightColor,\n },\n },\n axis: {\n domainColor: lightColor,\n gridColor: medColor,\n tickColor: lightColor,\n },\n};\n\nconst markColor = '#4572a7';\nconst excelTheme = {\n background: '#fff',\n arc: { fill: markColor },\n area: { fill: markColor },\n line: { stroke: markColor, strokeWidth: 2 },\n path: { stroke: markColor },\n rect: { fill: markColor },\n shape: { stroke: markColor },\n symbol: { fill: markColor, strokeWidth: 1.5, size: 50 },\n axis: {\n bandPosition: 0.5,\n grid: true,\n gridColor: '#000000',\n gridOpacity: 1,\n gridWidth: 0.5,\n labelPadding: 10,\n tickSize: 5,\n tickWidth: 0.5,\n },\n axisBand: {\n grid: false,\n tickExtra: true,\n },\n legend: {\n labelBaseline: 'middle',\n labelFontSize: 11,\n symbolSize: 50,\n symbolType: 'square',\n },\n range: {\n category: [\n '#4572a7',\n '#aa4643',\n '#8aa453',\n '#71598e',\n '#4598ae',\n '#d98445',\n '#94aace',\n '#d09393',\n '#b9cc98',\n '#a99cbc',\n ],\n },\n};\n\nconst markColor$1 = '#30a2da';\nconst axisColor = '#cbcbcb';\nconst guideLabelColor = '#999';\nconst guideTitleColor = '#333';\nconst backgroundColor = '#f0f0f0';\nconst blackTitle = '#333';\nconst fiveThirtyEightTheme = {\n arc: { fill: markColor$1 },\n area: { fill: markColor$1 },\n axis: {\n domainColor: axisColor,\n grid: true,\n gridColor: axisColor,\n gridWidth: 1,\n labelColor: guideLabelColor,\n labelFontSize: 10,\n titleColor: guideTitleColor,\n tickColor: axisColor,\n tickSize: 10,\n titleFontSize: 14,\n titlePadding: 10,\n labelPadding: 4,\n },\n axisBand: {\n grid: false,\n },\n background: backgroundColor,\n group: {\n fill: backgroundColor,\n },\n legend: {\n labelColor: blackTitle,\n labelFontSize: 11,\n padding: 1,\n symbolSize: 30,\n symbolType: 'square',\n titleColor: blackTitle,\n titleFontSize: 14,\n titlePadding: 10,\n },\n line: {\n stroke: markColor$1,\n strokeWidth: 2,\n },\n path: { stroke: markColor$1, strokeWidth: 0.5 },\n rect: { fill: markColor$1 },\n range: {\n category: [\n '#30a2da',\n '#fc4f30',\n '#e5ae38',\n '#6d904f',\n '#8b8b8b',\n '#b96db8',\n '#ff9e27',\n '#56cc60',\n '#52d2ca',\n '#52689e',\n '#545454',\n '#9fe4f8',\n ],\n diverging: ['#cc0020', '#e77866', '#f6e7e1', '#d6e8ed', '#91bfd9', '#1d78b5'],\n heatmap: ['#d6e8ed', '#cee0e5', '#91bfd9', '#549cc6', '#1d78b5'],\n },\n point: {\n filled: true,\n shape: 'circle',\n },\n shape: { stroke: markColor$1 },\n bar: {\n binSpacing: 2,\n fill: markColor$1,\n stroke: null,\n },\n title: {\n anchor: 'start',\n fontSize: 24,\n fontWeight: 600,\n offset: 20,\n },\n};\n\nconst markColor$2 = '#000';\nconst ggplot2Theme = {\n group: {\n fill: '#e5e5e5',\n },\n arc: { fill: markColor$2 },\n area: { fill: markColor$2 },\n line: { stroke: markColor$2 },\n path: { stroke: markColor$2 },\n rect: { fill: markColor$2 },\n shape: { stroke: markColor$2 },\n symbol: { fill: markColor$2, size: 40 },\n axis: {\n domain: false,\n grid: true,\n gridColor: '#FFFFFF',\n gridOpacity: 1,\n labelColor: '#7F7F7F',\n labelPadding: 4,\n tickColor: '#7F7F7F',\n tickSize: 5.67,\n titleFontSize: 16,\n titleFontWeight: 'normal',\n },\n legend: {\n labelBaseline: 'middle',\n labelFontSize: 11,\n symbolSize: 40,\n },\n range: {\n category: [\n '#000000',\n '#7F7F7F',\n '#1A1A1A',\n '#999999',\n '#333333',\n '#B0B0B0',\n '#4D4D4D',\n '#C9C9C9',\n '#666666',\n '#DCDCDC',\n ],\n },\n};\n\nconst headlineFontSize = 22;\nconst headlineFontWeight = 'normal';\nconst labelFont = 'Benton Gothic, sans-serif';\nconst labelFontSize = 11.5;\nconst labelFontWeight = 'normal';\nconst markColor$3 = '#82c6df';\n// const markHighlight = '#006d8f';\n// const markDemocrat = '#5789b8';\n// const markRepublican = '#d94f54';\nconst titleFont = 'Benton Gothic Bold, sans-serif';\nconst titleFontWeight = 'normal';\nconst titleFontSize = 13;\nconst colorSchemes = {\n 'category-6': ['#ec8431', '#829eb1', '#c89d29', '#3580b1', '#adc839', '#ab7fb4'],\n 'fire-7': ['#fbf2c7', '#f9e39c', '#f8d36e', '#f4bb6a', '#e68a4f', '#d15a40', '#ab4232'],\n 'fireandice-6': ['#e68a4f', '#f4bb6a', '#f9e39c', '#dadfe2', '#a6b7c6', '#849eae'],\n 'ice-7': ['#edefee', '#dadfe2', '#c4ccd2', '#a6b7c6', '#849eae', '#607785', '#47525d'],\n};\nconst latimesTheme = {\n background: '#ffffff',\n title: {\n anchor: 'start',\n color: '#000000',\n font: titleFont,\n fontSize: headlineFontSize,\n fontWeight: headlineFontWeight,\n },\n arc: { fill: markColor$3 },\n area: { fill: markColor$3 },\n line: { stroke: markColor$3, strokeWidth: 2 },\n path: { stroke: markColor$3 },\n rect: { fill: markColor$3 },\n shape: { stroke: markColor$3 },\n symbol: { fill: markColor$3, size: 30 },\n axis: {\n labelFont,\n labelFontSize,\n labelFontWeight,\n titleFont,\n titleFontSize,\n titleFontWeight,\n },\n axisX: {\n labelAngle: 0,\n labelPadding: 4,\n tickSize: 3,\n },\n axisY: {\n labelBaseline: 'middle',\n maxExtent: 45,\n minExtent: 45,\n tickSize: 2,\n titleAlign: 'left',\n titleAngle: 0,\n titleX: -45,\n titleY: -11,\n },\n legend: {\n labelFont,\n labelFontSize,\n symbolType: 'square',\n titleFont,\n titleFontSize,\n titleFontWeight,\n },\n range: {\n category: colorSchemes['category-6'],\n diverging: colorSchemes['fireandice-6'],\n heatmap: colorSchemes['fire-7'],\n ordinal: colorSchemes['fire-7'],\n ramp: colorSchemes['fire-7'],\n },\n};\n\nconst markColor$4 = '#ab5787';\nconst axisColor$1 = '#979797';\nconst quartzTheme = {\n background: '#f9f9f9',\n arc: { fill: markColor$4 },\n area: { fill: markColor$4 },\n line: { stroke: markColor$4 },\n path: { stroke: markColor$4 },\n rect: { fill: markColor$4 },\n shape: { stroke: markColor$4 },\n symbol: { fill: markColor$4, size: 30 },\n axis: {\n domainColor: axisColor$1,\n domainWidth: 0.5,\n gridWidth: 0.2,\n labelColor: axisColor$1,\n tickColor: axisColor$1,\n tickWidth: 0.2,\n titleColor: axisColor$1,\n },\n axisBand: {\n grid: false,\n },\n axisX: {\n grid: true,\n tickSize: 10,\n },\n axisY: {\n domain: false,\n grid: true,\n tickSize: 0,\n },\n legend: {\n labelFontSize: 11,\n padding: 1,\n symbolSize: 30,\n symbolType: 'square',\n },\n range: {\n category: [\n '#ab5787',\n '#51b2e5',\n '#703c5c',\n '#168dd9',\n '#d190b6',\n '#00609f',\n '#d365ba',\n '#154866',\n '#666666',\n '#c4c4c4',\n ],\n },\n};\n\nconst markColor$5 = '#3e5c69';\nconst voxTheme = {\n background: '#fff',\n arc: { fill: markColor$5 },\n area: { fill: markColor$5 },\n line: { stroke: markColor$5 },\n path: { stroke: markColor$5 },\n rect: { fill: markColor$5 },\n shape: { stroke: markColor$5 },\n symbol: { fill: markColor$5 },\n axis: {\n domainWidth: 0.5,\n grid: true,\n labelPadding: 2,\n tickSize: 5,\n tickWidth: 0.5,\n titleFontWeight: 'normal',\n },\n axisBand: {\n grid: false,\n },\n axisX: {\n gridWidth: 0.2,\n },\n axisY: {\n gridDash: [3],\n gridWidth: 0.4,\n },\n legend: {\n labelFontSize: 11,\n padding: 1,\n symbolType: 'square',\n },\n range: {\n category: ['#3e5c69', '#6793a6', '#182429', '#0570b0', '#3690c0', '#74a9cf', '#a6bddb', '#e2ddf2'],\n },\n};\n\nconst markColor$6 = '#1696d2';\nconst axisColor$2 = '#000000';\nconst backgroundColor$1 = '#FFFFFF';\nconst font = 'Lato';\nconst labelFont$1 = 'Lato';\nconst sourceFont = 'Lato';\nconst gridColor = '#DEDDDD';\nconst titleFontSize$1 = 18;\nconst colorSchemes$1 = {\n 'main-colors': ['#1696d2', '#d2d2d2', '#000000', '#fdbf11', '#ec008b', '#55b748', '#5c5859', '#db2b27'],\n 'shades-blue': ['#CFE8F3', '#A2D4EC', '#73BFE2', '#46ABDB', '#1696D2', '#12719E', '#0A4C6A', '#062635'],\n 'shades-gray': ['#F5F5F5', '#ECECEC', '#E3E3E3', '#DCDBDB', '#D2D2D2', '#9D9D9D', '#696969', '#353535'],\n 'shades-yellow': ['#FFF2CF', '#FCE39E', '#FDD870', '#FCCB41', '#FDBF11', '#E88E2D', '#CA5800', '#843215'],\n 'shades-magenta': ['#F5CBDF', '#EB99C2', '#E46AA7', '#E54096', '#EC008B', '#AF1F6B', '#761548', '#351123'],\n 'shades-green': ['#DCEDD9', '#BCDEB4', '#98CF90', '#78C26D', '#55B748', '#408941', '#2C5C2D', '#1A2E19'],\n 'shades-black': ['#D5D5D4', '#ADABAC', '#848081', '#5C5859', '#332D2F', '#262223', '#1A1717', '#0E0C0D'],\n 'shades-red': ['#F8D5D4', '#F1AAA9', '#E9807D', '#E25552', '#DB2B27', '#A4201D', '#6E1614', '#370B0A'],\n 'one-group': ['#1696d2', '#000000'],\n 'two-groups-cat-1': ['#1696d2', '#000000'],\n 'two-groups-cat-2': ['#1696d2', '#fdbf11'],\n 'two-groups-cat-3': ['#1696d2', '#db2b27'],\n 'two-groups-seq': ['#a2d4ec', '#1696d2'],\n 'three-groups-cat': ['#1696d2', '#fdbf11', '#000000'],\n 'three-groups-seq': ['#a2d4ec', '#1696d2', '#0a4c6a'],\n 'four-groups-cat-1': ['#000000', '#d2d2d2', '#fdbf11', '#1696d2'],\n 'four-groups-cat-2': ['#1696d2', '#ec0008b', '#fdbf11', '#5c5859'],\n 'four-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a'],\n 'five-groups-cat-1': ['#1696d2', '#fdbf11', '#d2d2d2', '#ec008b', '#000000'],\n 'five-groups-cat-2': ['#1696d2', '#0a4c6a', '#d2d2d2', '#fdbf11', '#332d2f'],\n 'five-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a', '#000000'],\n 'six-groups-cat-1': ['#1696d2', '#ec008b', '#fdbf11', '#000000', '#d2d2d2', '#55b748'],\n 'six-groups-cat-2': ['#1696d2', '#d2d2d2', '#ec008b', '#fdbf11', '#332d2f', '#0a4c6a'],\n 'six-groups-seq': ['#cfe8f3', '#a2d4ec', '#73bfe2', '#46abdb', '#1696d2', '#12719e'],\n 'diverging-colors': ['#ca5800', '#fdbf11', '#fdd870', '#fff2cf', '#cfe8f3', '#73bfe2', '#1696d2', '#0a4c6a'],\n};\nconst urbanInstituteTheme = {\n background: backgroundColor$1,\n title: {\n anchor: 'start',\n fontSize: titleFontSize$1,\n font: font,\n },\n axisX: {\n domain: true,\n domainColor: axisColor$2,\n domainWidth: 1,\n grid: false,\n labelFontSize: 12,\n labelFont: labelFont$1,\n labelAngle: 0,\n tickColor: axisColor$2,\n tickSize: 5,\n titleFontSize: 12,\n titlePadding: 10,\n titleFont: font,\n },\n axisY: {\n domain: false,\n domainWidth: 1,\n grid: true,\n gridColor: gridColor,\n gridWidth: 1,\n labelFontSize: 12,\n labelFont: labelFont$1,\n labelPadding: 8,\n ticks: false,\n titleFontSize: 12,\n titlePadding: 10,\n titleFont: font,\n titleAngle: 0,\n titleY: -10,\n titleX: 18,\n },\n legend: {\n labelFontSize: 12,\n labelFont: labelFont$1,\n symbolSize: 100,\n titleFontSize: 12,\n titlePadding: 10,\n titleFont: font,\n orient: 'right',\n offset: 10,\n },\n view: {\n stroke: 'transparent',\n },\n range: {\n category: colorSchemes$1['six-groups-cat-1'],\n diverging: colorSchemes$1['diverging-colors'],\n heatmap: colorSchemes$1['diverging-colors'],\n ordinal: colorSchemes$1['six-groups-seq'],\n ramp: colorSchemes$1['shades-blue'],\n },\n area: {\n fill: markColor$6,\n },\n rect: {\n fill: markColor$6,\n },\n line: {\n color: markColor$6,\n stroke: markColor$6,\n strokeWidth: 5,\n },\n trail: {\n color: markColor$6,\n stroke: markColor$6,\n strokeWidth: 0,\n size: 1,\n },\n path: {\n stroke: markColor$6,\n strokeWidth: 0.5,\n },\n point: {\n filled: true,\n },\n text: {\n font: sourceFont,\n color: markColor$6,\n fontSize: 11,\n align: 'center',\n fontWeight: 400,\n size: 11,\n },\n style: {\n bar: {\n fill: markColor$6,\n stroke: null,\n },\n },\n arc: { fill: markColor$6 },\n shape: { stroke: markColor$6 },\n symbol: { fill: markColor$6, size: 30 },\n};\n\n/**\n * Copyright 2020 Google LLC.\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nconst markColor$7 = '#3366CC';\nconst gridColor$1 = '#ccc';\nconst defaultFont = 'Arial, sans-serif';\nconst googlechartsTheme = {\n arc: { fill: markColor$7 },\n area: { fill: markColor$7 },\n path: { stroke: markColor$7 },\n rect: { fill: markColor$7 },\n shape: { stroke: markColor$7 },\n symbol: { stroke: markColor$7 },\n circle: { fill: markColor$7 },\n background: '#fff',\n padding: {\n top: 10,\n right: 10,\n bottom: 10,\n left: 10,\n },\n style: {\n 'guide-label': {\n font: defaultFont,\n fontSize: 12,\n },\n 'guide-title': {\n font: defaultFont,\n fontSize: 12,\n },\n 'group-title': {\n font: defaultFont,\n fontSize: 12,\n },\n },\n title: {\n font: defaultFont,\n fontSize: 14,\n fontWeight: 'bold',\n dy: -3,\n anchor: 'start',\n },\n axis: {\n gridColor: gridColor$1,\n tickColor: gridColor$1,\n domain: false,\n grid: true,\n },\n range: {\n category: [\n '#4285F4',\n '#DB4437',\n '#F4B400',\n '#0F9D58',\n '#AB47BC',\n '#00ACC1',\n '#FF7043',\n '#9E9D24',\n '#5C6BC0',\n '#F06292',\n '#00796B',\n '#C2185B',\n ],\n heatmap: ['#c6dafc', '#5e97f6', '#2a56c6'],\n },\n};\n\nconst version$1 = pkg.version;\n\nexport { darkTheme as dark, excelTheme as excel, fiveThirtyEightTheme as fivethirtyeight, ggplot2Theme as ggplot2, googlechartsTheme as googlecharts, latimesTheme as latimes, quartzTheme as quartz, urbanInstituteTheme as urbaninstitute, version$1 as version, voxTheme as vox };\n","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\n\nexport default function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n\n _next(undefined);\n });\n };\n}","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\"use strict\";\n\nvar Op = Object.prototype;\nvar hasOwn = Op.hasOwnProperty;\nvar undefined; // More compressible than void 0.\nvar $Symbol = typeof Symbol === \"function\" ? Symbol : {};\nvar iteratorSymbol = $Symbol.iterator || \"@@iterator\";\nvar asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\nvar toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\nfunction wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n}\n\n// Try/catch helper to minimize deoptimizations. Returns a completion\n// record like context.tryEntries[i].completion. This interface could\n// have been (and was previously) designed to take a closure to be\n// invoked without arguments, but in all the cases we care about we\n// already have an existing method we want to call, so there's no need\n// to create a new function object. We can even get away with assuming\n// the method takes exactly one argument, since that happens to be true\n// in every case, so we don't have to touch the arguments object. The\n// only additional allocation required is the completion record, which\n// has a stable shape and so hopefully should be cheap to allocate.\nfunction tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n}\n\nvar GenStateSuspendedStart = \"suspendedStart\";\nvar GenStateSuspendedYield = \"suspendedYield\";\nvar GenStateExecuting = \"executing\";\nvar GenStateCompleted = \"completed\";\n\n// Returning this object from the innerFn has the same effect as\n// breaking out of the dispatch switch statement.\nvar ContinueSentinel = {};\n\n// Dummy constructor functions that we use as the .constructor and\n// .constructor.prototype properties for functions that return Generator\n// objects. For full spec compliance, you may wish to configure your\n// minifier not to mangle the names of these two functions.\nfunction Generator() {}\nfunction GeneratorFunction() {}\nfunction GeneratorFunctionPrototype() {}\n\n// This is a polyfill for %IteratorPrototype% for environments that\n// don't natively support it.\nvar IteratorPrototype = {};\nIteratorPrototype[iteratorSymbol] = function () {\n return this;\n};\n\nvar getProto = Object.getPrototypeOf;\nvar NativeIteratorPrototype = getProto && getProto(getProto(values([])));\nif (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n}\n\nvar Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\nGeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\nGeneratorFunctionPrototype.constructor = GeneratorFunction;\nGeneratorFunctionPrototype[toStringTagSymbol] =\n GeneratorFunction.displayName = \"GeneratorFunction\";\n\n// Helper for defining the .next, .throw, and .return methods of the\n// Iterator interface in terms of a single ._invoke method.\nfunction defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n prototype[method] = function(arg) {\n return this._invoke(method, arg);\n };\n });\n}\n\nfunction isGeneratorFunction (genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n};\n\nfunction mark (genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n if (!(toStringTagSymbol in genFun)) {\n genFun[toStringTagSymbol] = \"GeneratorFunction\";\n }\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n};\n\n// Within the body of any async function, `await x` is transformed to\n// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n// `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n// meant to be awaited.\nfunction awrap (arg) {\n return { __await: arg };\n};\n\nfunction AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n}\n\ndefineIteratorMethods(AsyncIterator.prototype);\nAsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n};\n\n// Note that simple async functions are implemented on top of\n// AsyncIterator objects; they just return a Promise for the value of\n// the final result produced by the iterator.\n function async (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n};\n\nfunction makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n}\n\n// Call delegate.iterator[context.method](context.arg) and handle the\n// result, either by returning a { value, done } result from the\n// delegate iterator, or by modifying context.method and context.arg,\n// setting context.delegate to null, and returning the ContinueSentinel.\nfunction maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n}\n\n// Define Generator.prototype.{next,throw,return} in terms of the\n// unified ._invoke helper method.\ndefineIteratorMethods(Gp);\n\nGp[toStringTagSymbol] = \"Generator\";\n\n// A Generator should always return itself as the iterator object when the\n// @@iterator function is called on it. Some browsers' implementations of the\n// iterator prototype chain incorrectly implement this, causing the Generator\n// object to not be returned from this call. This ensures that doesn't happen.\n// See https://github.com/facebook/regenerator/issues/274 for more details.\nGp[iteratorSymbol] = function() {\n return this;\n};\n\nGp.toString = function() {\n return \"[object Generator]\";\n};\n\nfunction pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n}\n\nfunction resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n}\n\nfunction Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n}\n\nfunction keys (object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n};\n\nfunction values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n}\n\nfunction doneResult() {\n return { value: undefined, done: true };\n}\n\nContext.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n};\n\n// Export a default namespace that plays well with Rollup\nexport default {\n wrap,\n isGeneratorFunction,\n AsyncIterator,\n mark,\n awrap,\n async,\n keys,\n values\n};\n","import {MessageData} from './types';\n\n/**\n * Open editor url in a new window, and pass a message.\n */\nexport default function (window: Window, url: string, data: MessageData) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const editor = window.open(url)!;\n const wait = 10000;\n const step = 250;\n const {origin} = new URL(url);\n // eslint-disable-next-line no-bitwise\n let count = ~~(wait / step);\n\n function listen(evt: MessageEvent) {\n if (evt.source === editor) {\n count = 0;\n window.removeEventListener('message', listen, false);\n }\n }\n window.addEventListener('message', listen, false);\n\n // send message\n // periodically resend until ack received or timeout\n function send() {\n if (count <= 0) {\n return;\n }\n editor.postMessage(data, origin);\n setTimeout(send, step);\n count -= 1;\n }\n setTimeout(send, step);\n}\n","import {applyPatch, Operation} from 'fast-json-patch';\nimport stringify from 'json-stringify-pretty-compact';\nimport {satisfies} from 'semver';\nimport * as vegaImport from 'vega';\nimport {\n AutoSize,\n Config as VgConfig,\n EncodeEntryName,\n isBoolean,\n isString,\n Loader,\n LoaderOptions,\n mergeConfig,\n Renderers,\n Spec as VgSpec,\n TooltipHandler,\n View,\n} from 'vega';\nimport {expressionInterpreter} from 'vega-interpreter';\nimport * as vegaLiteImport from 'vega-lite';\nimport {Config as VlConfig, TopLevelSpec as VlSpec} from 'vega-lite';\nimport schemaParser from 'vega-schema-url-parser';\nimport * as themes from 'vega-themes';\nimport {Handler, Options as TooltipOptions} from 'vega-tooltip';\nimport post from './post';\nimport embedStyle from './style';\nimport {Config, Mode} from './types';\nimport {mergeDeep} from './util';\nimport pkg from '../package.json';\n\nexport const version = pkg.version;\n\nexport * from './types';\n\nexport const vega = vegaImport;\nexport let vegaLite = vegaLiteImport;\n\n// For backwards compatibility with Vega-Lite before v4.\nconst w = (typeof window !== 'undefined' ? window : undefined) as any;\nif (vegaLite === undefined && w?.['vl']?.compile) {\n vegaLite = w['vl'];\n}\n\nexport interface Actions {\n export?: boolean | {svg?: boolean; png?: boolean};\n source?: boolean;\n compiled?: boolean;\n editor?: boolean;\n}\n\nexport const DEFAULT_ACTIONS = {export: {svg: true, png: true}, source: true, compiled: true, editor: true};\n\nexport interface Hover {\n hoverSet?: EncodeEntryName;\n updateSet?: EncodeEntryName;\n}\n\nexport type PatchFunc = (spec: VgSpec) => VgSpec;\n\nconst I18N = {\n CLICK_TO_VIEW_ACTIONS: 'Click to view actions',\n COMPILED_ACTION: 'View Compiled Vega',\n EDITOR_ACTION: 'Open in Vega Editor',\n PNG_ACTION: 'Save as PNG',\n SOURCE_ACTION: 'View Source',\n SVG_ACTION: 'Save as SVG',\n};\n\nexport interface EmbedOptions {\n bind?: HTMLElement | string;\n actions?: boolean | Actions;\n mode?: Mode;\n theme?: 'excel' | 'ggplot2' | 'quartz' | 'vox' | 'dark';\n defaultStyle?: boolean | string;\n logLevel?: number;\n loader?: Loader | LoaderOptions;\n renderer?: R;\n tooltip?: TooltipHandler | TooltipOptions | boolean;\n patch?: S | PatchFunc | Operation[];\n width?: number;\n height?: number;\n padding?: number | {left?: number; right?: number; top?: number; bottom?: number};\n scaleFactor?: number;\n config?: S | Config;\n sourceHeader?: string;\n sourceFooter?: string;\n editorUrl?: string;\n hover?: boolean | Hover;\n i18n?: Partial;\n downloadFileName?: string;\n formatLocale?: Record;\n timeFormatLocale?: Record;\n ast?: boolean;\n expr?: typeof expressionInterpreter;\n viewClass?: typeof View;\n}\n\nconst NAMES: {[key in Mode]: string} = {\n vega: 'Vega',\n 'vega-lite': 'Vega-Lite',\n};\n\nconst VERSION = {\n vega: vega.version,\n 'vega-lite': vegaLite ? vegaLite.version : 'not available',\n};\n\nconst PREPROCESSOR: {[mode in Mode]: (spec: any, config?: Config) => VgSpec} = {\n vega: (vgSpec: VgSpec) => vgSpec,\n 'vega-lite': (vlSpec, config) => vegaLite.compile(vlSpec as VlSpec, {config: config as VlConfig}).spec,\n};\n\nconst SVG_CIRCLES = `\n\n \n \n \n`;\n\nconst CHART_WRAPPER_CLASS = 'chart-wrapper';\n\nexport type VisualizationSpec = VlSpec | VgSpec;\n\nexport interface Result {\n /** The Vega view. */\n view: View;\n\n /** The input specification. */\n spec: VisualizationSpec;\n\n /** The compiled and patched Vega specification. */\n vgSpec: VgSpec;\n\n /** Removes references to unwanted behaviors and memory leaks. Calls Vega's `view.finalize`. */\n finalize: () => void;\n}\n\nfunction isTooltipHandler(h?: boolean | TooltipOptions | TooltipHandler): h is TooltipHandler {\n return typeof h === 'function';\n}\n\nfunction viewSource(source: string, sourceHeader: string, sourceFooter: string, mode: Mode) {\n const header = `${sourceHeader}
`;\n  const footer = `
${sourceFooter}`;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const win = window.open('')!;\n win.document.write(header + source + footer);\n win.document.title = `${NAMES[mode]} JSON Source`;\n}\n\n/**\n * Try to guess the type of spec.\n *\n * @param spec Vega or Vega-Lite spec.\n */\nexport function guessMode(spec: VisualizationSpec, providedMode?: Mode): Mode {\n // Decide mode\n if (spec.$schema) {\n const parsed = schemaParser(spec.$schema);\n if (providedMode && providedMode !== parsed.library) {\n console.warn(\n `The given visualization spec is written in ${NAMES[parsed.library]}, but mode argument sets ${\n NAMES[providedMode] ?? providedMode\n }.`\n );\n }\n\n const mode = parsed.library as Mode;\n\n if (!satisfies(VERSION[mode], `^${parsed.version.slice(1)}`)) {\n console.warn(\n `The input spec uses ${NAMES[mode]} ${parsed.version}, but the current version of ${NAMES[mode]} is v${VERSION[mode]}.`\n );\n }\n\n return mode;\n }\n\n // try to guess from the provided spec\n if (\n 'mark' in spec ||\n 'encoding' in spec ||\n 'layer' in spec ||\n 'hconcat' in spec ||\n 'vconcat' in spec ||\n 'facet' in spec ||\n 'repeat' in spec\n ) {\n return 'vega-lite';\n }\n\n if ('marks' in spec || 'signals' in spec || 'scales' in spec || 'axes' in spec) {\n return 'vega';\n }\n\n return providedMode ?? 'vega';\n}\n\nfunction isLoader(o?: LoaderOptions | Loader): o is Loader {\n return !!(o && 'load' in o);\n}\n\nfunction createLoader(opts?: Loader | LoaderOptions) {\n return isLoader(opts) ? opts : vega.loader(opts);\n}\n\nfunction embedOptionsFromUsermeta(parsedSpec: VisualizationSpec) {\n return (parsedSpec.usermeta && (parsedSpec.usermeta as any)['embedOptions']) ?? {};\n}\n\n/**\n * Embed a Vega visualization component in a web page. This function returns a promise.\n *\n * @param el DOM element in which to place component (DOM node or CSS selector).\n * @param spec String : A URL string from which to load the Vega specification.\n * Object : The Vega/Vega-Lite specification as a parsed JSON object.\n * @param opts A JavaScript object containing options for embedding.\n */\nexport default async function embed(\n el: HTMLElement | string,\n spec: VisualizationSpec | string,\n opts: EmbedOptions = {}\n): Promise {\n let parsedSpec: VisualizationSpec;\n let loader: Loader | undefined;\n\n if (isString(spec)) {\n loader = createLoader(opts.loader);\n parsedSpec = JSON.parse(await loader.load(spec));\n } else {\n parsedSpec = spec;\n }\n\n const usermetaLoader = embedOptionsFromUsermeta(parsedSpec).loader;\n\n // either create the loader for the first time or create a new loader if the spec has new loader options\n if (!loader || usermetaLoader) {\n loader = createLoader(opts.loader ?? usermetaLoader);\n }\n\n const usermetaOpts = await loadOpts(embedOptionsFromUsermeta(parsedSpec), loader);\n const parsedOpts = await loadOpts(opts, loader);\n\n const mergedOpts = {\n ...mergeDeep(parsedOpts, usermetaOpts),\n config: mergeConfig(parsedOpts.config ?? {}, usermetaOpts.config ?? {}),\n };\n\n return await _embed(el, parsedSpec, mergedOpts, loader);\n}\n\nasync function loadOpts(opt: EmbedOptions, loader: Loader): Promise> {\n const config: Config = isString(opt.config) ? JSON.parse(await loader.load(opt.config)) : opt.config ?? {};\n const patch: PatchFunc | Operation[] = isString(opt.patch) ? JSON.parse(await loader.load(opt.patch)) : opt.patch;\n return {\n ...(opt as any),\n ...(patch ? {patch} : {}),\n ...(config ? {config} : {}),\n };\n}\n\nfunction getRoot(el: Element) {\n const possibleRoot = el.getRootNode ? el.getRootNode() : document;\n if (possibleRoot instanceof ShadowRoot) {\n return {root: possibleRoot, rootContainer: possibleRoot};\n } else {\n return {root: document, rootContainer: document.head ?? document.body};\n }\n}\n\nasync function _embed(\n el: HTMLElement | string,\n spec: VisualizationSpec,\n opts: EmbedOptions = {},\n loader: Loader\n): Promise {\n const config = opts.theme ? mergeConfig(themes[opts.theme], opts.config ?? {}) : opts.config;\n\n const actions = isBoolean(opts.actions) ? opts.actions : mergeDeep({}, DEFAULT_ACTIONS, opts.actions ?? {});\n const i18n = {...I18N, ...opts.i18n};\n\n const renderer = opts.renderer ?? 'canvas';\n const logLevel = opts.logLevel ?? vega.Warn;\n const downloadFileName = opts.downloadFileName ?? 'visualization';\n\n const element = typeof el === 'string' ? document.querySelector(el) : el;\n if (!element) {\n throw new Error(`${el} does not exist`);\n }\n\n if (opts.defaultStyle !== false) {\n // Add a default stylesheet to the head of the document.\n const ID = 'vega-embed-style';\n const {root, rootContainer} = getRoot(element);\n if (!root.getElementById(ID)) {\n const style = document.createElement('style');\n style.id = ID;\n style.innerText =\n opts.defaultStyle === undefined || opts.defaultStyle === true\n ? (embedStyle ?? '').toString()\n : opts.defaultStyle;\n rootContainer.appendChild(style);\n }\n }\n\n const mode = guessMode(spec, opts.mode);\n\n let vgSpec: VgSpec = PREPROCESSOR[mode](spec, config);\n\n if (mode === 'vega-lite') {\n if (vgSpec.$schema) {\n const parsed = schemaParser(vgSpec.$schema);\n\n if (!satisfies(VERSION.vega, `^${parsed.version.slice(1)}`)) {\n console.warn(`The compiled spec uses Vega ${parsed.version}, but current version is v${VERSION.vega}.`);\n }\n }\n }\n\n element.classList.add('vega-embed');\n if (actions) {\n element.classList.add('has-actions');\n }\n element.innerHTML = ''; // clear container\n\n let container = element;\n if (actions) {\n const chartWrapper = document.createElement('div');\n chartWrapper.classList.add(CHART_WRAPPER_CLASS);\n element.appendChild(chartWrapper);\n container = chartWrapper;\n }\n\n const patch = opts.patch;\n if (patch) {\n if (patch instanceof Function) {\n vgSpec = patch(vgSpec);\n } else {\n vgSpec = applyPatch(vgSpec, patch, true, false).newDocument;\n }\n }\n\n // Set locale. Note that this is a global setting.\n if (opts.formatLocale) {\n vega.formatLocale(opts.formatLocale);\n }\n\n if (opts.timeFormatLocale) {\n vega.timeFormatLocale(opts.timeFormatLocale);\n }\n\n const {ast} = opts;\n\n // Do not apply the config to Vega when we have already applied it to Vega-Lite.\n // This call may throw an Error if parsing fails.\n const runtime = vega.parse(vgSpec, mode === 'vega-lite' ? {} : (config as VgConfig), {ast});\n\n const view = new (opts.viewClass || vega.View)(runtime, {\n loader,\n logLevel,\n renderer,\n ...(ast ? {expr: (vega as any).expressionInterpreter ?? opts.expr ?? expressionInterpreter} : {}),\n });\n\n view.addSignalListener('autosize', (_, autosize: Exclude) => {\n const {type} = autosize;\n if (type == 'fit-x') {\n container.classList.add('fit-x');\n container.classList.remove('fit-y');\n } else if (type == 'fit-y') {\n container.classList.remove('fit-x');\n container.classList.add('fit-y');\n } else if (type == 'fit') {\n container.classList.add('fit-x', 'fit-y');\n } else {\n container.classList.remove('fit-x', 'fit-y');\n }\n });\n\n if (opts.tooltip !== false) {\n let handler: TooltipHandler;\n if (isTooltipHandler(opts.tooltip)) {\n handler = opts.tooltip;\n } else {\n // user provided boolean true or tooltip options\n handler = new Handler(opts.tooltip === true ? {} : opts.tooltip).call;\n }\n\n view.tooltip(handler);\n }\n\n let {hover} = opts;\n\n if (hover === undefined) {\n hover = mode === 'vega';\n }\n\n if (hover) {\n const {hoverSet, updateSet} = (typeof hover === 'boolean' ? {} : hover) as Hover;\n\n view.hover(hoverSet, updateSet);\n }\n\n if (opts) {\n if (opts.width != null) {\n view.width(opts.width);\n }\n if (opts.height != null) {\n view.height(opts.height);\n }\n if (opts.padding != null) {\n view.padding(opts.padding);\n }\n }\n\n await view.initialize(container, opts.bind).runAsync();\n\n let documentClickHandler: ((this: Document, ev: MouseEvent) => void) | undefined;\n\n if (actions !== false) {\n let wrapper = element;\n\n if (opts.defaultStyle !== false) {\n const details = document.createElement('details');\n details.title = i18n.CLICK_TO_VIEW_ACTIONS;\n element.append(details);\n\n wrapper = details;\n const summary = document.createElement('summary');\n summary.innerHTML = SVG_CIRCLES;\n\n details.append(summary);\n\n documentClickHandler = (ev: MouseEvent) => {\n if (!details.contains(ev.target as any)) {\n details.removeAttribute('open');\n }\n };\n document.addEventListener('click', documentClickHandler);\n }\n\n const ctrl = document.createElement('div');\n wrapper.append(ctrl);\n ctrl.classList.add('vega-actions');\n\n // add 'Export' action\n if (actions === true || actions.export !== false) {\n for (const ext of ['svg', 'png'] as const) {\n if (actions === true || actions.export === true || (actions.export as {svg?: boolean; png?: boolean})[ext]) {\n const i18nExportAction = (i18n as {[key: string]: string})[`${ext.toUpperCase()}_ACTION`];\n const exportLink = document.createElement('a');\n\n exportLink.text = i18nExportAction;\n exportLink.href = '#';\n exportLink.target = '_blank';\n exportLink.download = `${downloadFileName}.${ext}`;\n // add link on mousedown so that it's correct when the click happens\n exportLink.addEventListener('mousedown', async function (this, e) {\n e.preventDefault();\n const url = await view.toImageURL(ext, opts.scaleFactor);\n this.href = url;\n });\n\n ctrl.append(exportLink);\n }\n }\n }\n\n // add 'View Source' action\n if (actions === true || actions.source !== false) {\n const viewSourceLink = document.createElement('a');\n\n viewSourceLink.text = i18n.SOURCE_ACTION;\n viewSourceLink.href = '#';\n viewSourceLink.addEventListener('click', function (this, e) {\n viewSource(stringify(spec), opts.sourceHeader ?? '', opts.sourceFooter ?? '', mode);\n e.preventDefault();\n });\n\n ctrl.append(viewSourceLink);\n }\n\n // add 'View Compiled' action\n if (mode === 'vega-lite' && (actions === true || actions.compiled !== false)) {\n const compileLink = document.createElement('a');\n\n compileLink.text = i18n.COMPILED_ACTION;\n compileLink.href = '#';\n compileLink.addEventListener('click', function (this, e) {\n viewSource(stringify(vgSpec), opts.sourceHeader ?? '', opts.sourceFooter ?? '', 'vega');\n e.preventDefault();\n });\n\n ctrl.append(compileLink);\n }\n\n // add 'Open in Vega Editor' action\n if (actions === true || actions.editor !== false) {\n const editorUrl = opts.editorUrl ?? 'https://vega.github.io/editor/';\n const editorLink = document.createElement('a');\n\n editorLink.text = i18n.EDITOR_ACTION;\n editorLink.href = '#';\n editorLink.addEventListener('click', function (this, e) {\n post(window, editorUrl, {\n config: config as Config,\n mode,\n renderer,\n spec: stringify(spec),\n });\n e.preventDefault();\n });\n\n ctrl.append(editorLink);\n }\n }\n\n function finalize() {\n if (documentClickHandler) {\n document.removeEventListener('click', documentClickHandler);\n }\n view.finalize();\n }\n\n return {view, spec, vgSpec, finalize};\n}\n","import updateSingleDatasetInView from './updateSingleDatasetInView';\nexport default function updateMultipleDatasetsInView(view, data) {\n Object.keys(data).forEach(name => {\n updateSingleDatasetInView(view, name, data[name]);\n });\n}","import { vega } from 'vega-embed';\nimport isFunction from './isFunction';\nexport default function updateSingleDatasetInView(view, name, value) {\n if (value) {\n if (isFunction(value)) {\n value(view.data(name));\n } else {\n view.change(name, vega.changeset().remove(() => true).insert(value));\n }\n }\n}","export default function isFunction(functionToCheck) {\n const getType = {};\n return !!functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';\n}","export default function getUniqueFieldNames(objects) {\n const fields = new Set();\n objects.forEach(o => {\n Object.keys(o).forEach(field => {\n fields.add(field);\n });\n });\n return fields;\n}","// eslint-disable-next-line import/prefer-default-export\nexport const NOOP = () => {};","export default function addSignalListenersToView(view, signalListeners) {\n const signalNames = Object.keys(signalListeners);\n signalNames.forEach(signalName => {\n try {\n view.addSignalListener(signalName, signalListeners[signalName]);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn('Cannot add invalid signal listener.', error);\n }\n });\n return signalNames.length > 0;\n}","export default function removeSignalListenersFromView(view, signalListeners) {\n const signalNames = Object.keys(signalListeners);\n signalNames.forEach(signalName => {\n try {\n view.removeSignalListener(signalName, signalListeners[signalName]);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn('Cannot remove invalid signal listener.', error);\n }\n });\n return signalNames.length > 0;\n}","export default function combineSpecWithDimension(props) {\n const {\n spec,\n width,\n height\n } = props;\n\n if (typeof width !== 'undefined' && typeof height !== 'undefined') {\n return { ...spec,\n width,\n height\n };\n }\n\n if (typeof width !== 'undefined') {\n return { ...spec,\n width\n };\n }\n\n if (typeof height !== 'undefined') {\n return { ...spec,\n height\n };\n }\n\n return spec;\n}","import _pt from \"prop-types\";\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nimport React from 'react';\nimport vegaEmbed from 'vega-embed';\nimport shallowEqual from './utils/shallowEqual';\nimport getUniqueFieldNames from './utils/getUniqueFieldNames';\nimport { NOOP } from './constants';\nimport addSignalListenersToView from './utils/addSignalListenersToView';\nimport computeSpecChanges from './utils/computeSpecChanges';\nimport removeSignalListenersFromView from './utils/removeSignalListenersFromView';\nimport combineSpecWithDimension from './utils/combineSpecWithDimension';\nexport default class VegaEmbed extends React.PureComponent {\n constructor(...args) {\n super(...args);\n\n _defineProperty(this, \"containerRef\", /*#__PURE__*/React.createRef());\n\n _defineProperty(this, \"resultPromise\", void 0);\n\n _defineProperty(this, \"handleError\", error => {\n const {\n onError = NOOP\n } = this.props;\n onError(error); // eslint-disable-next-line no-console\n\n console.warn(error);\n return undefined;\n });\n\n _defineProperty(this, \"modifyView\", action => {\n if (this.resultPromise) {\n this.resultPromise.then(result => {\n if (result) {\n action(result.view);\n }\n\n return true;\n }).catch(this.handleError);\n }\n });\n }\n\n componentDidMount() {\n this.createView();\n }\n\n componentDidUpdate(prevProps) {\n const fieldSet = getUniqueFieldNames([this.props, prevProps]);\n fieldSet.delete('className');\n fieldSet.delete('signalListeners');\n fieldSet.delete('spec');\n fieldSet.delete('style');\n fieldSet.delete('width');\n fieldSet.delete('height'); // Only create a new view if necessary\n\n if (Array.from(fieldSet).some(f => this.props[f] !== prevProps[f])) {\n this.clearView();\n this.createView();\n } else {\n const specChanges = computeSpecChanges(combineSpecWithDimension(this.props), combineSpecWithDimension(prevProps));\n const {\n signalListeners: newSignalListeners\n } = this.props;\n const {\n signalListeners: oldSignalListeners\n } = prevProps;\n\n if (specChanges) {\n if (specChanges.isExpensive) {\n this.clearView();\n this.createView();\n } else {\n const areSignalListenersChanged = !shallowEqual(newSignalListeners, oldSignalListeners);\n this.modifyView(view => {\n if (specChanges.width !== false) {\n view.width(specChanges.width);\n }\n\n if (specChanges.height !== false) {\n view.height(specChanges.height);\n }\n\n if (areSignalListenersChanged) {\n if (oldSignalListeners) {\n removeSignalListenersFromView(view, oldSignalListeners);\n }\n\n if (newSignalListeners) {\n addSignalListenersToView(view, newSignalListeners);\n }\n }\n\n view.run();\n });\n }\n } else if (!shallowEqual(newSignalListeners, oldSignalListeners)) {\n this.modifyView(view => {\n if (oldSignalListeners) {\n removeSignalListenersFromView(view, oldSignalListeners);\n }\n\n if (newSignalListeners) {\n addSignalListenersToView(view, newSignalListeners);\n }\n\n view.run();\n });\n }\n }\n }\n\n componentWillUnmount() {\n this.clearView();\n }\n\n createView() {\n const {\n spec,\n onNewView,\n signalListeners = {},\n width,\n height,\n ...options\n } = this.props;\n\n if (this.containerRef.current) {\n const finalSpec = combineSpecWithDimension(this.props);\n this.resultPromise = vegaEmbed(this.containerRef.current, finalSpec, options).then(result => {\n if (result) {\n const {\n view\n } = result;\n\n if (addSignalListenersToView(view, signalListeners)) {\n view.run();\n }\n }\n\n return result;\n }).catch(this.handleError);\n\n if (onNewView) {\n this.modifyView(onNewView);\n }\n }\n }\n\n clearView() {\n if (this.resultPromise) {\n this.resultPromise.then(result => {\n if (result) {\n result.finalize();\n }\n }).catch(this.handleError);\n }\n\n this.resultPromise = undefined;\n return this;\n }\n\n render() {\n const {\n className,\n style\n } = this.props; // Create the container Vega draws inside\n\n return /*#__PURE__*/React.createElement(\"div\", {\n ref: this.containerRef,\n className: className,\n style: style\n });\n }\n\n}\n\n_defineProperty(VegaEmbed, \"propTypes\", {\n className: _pt.string,\n onError: _pt.func\n});","import equal from 'fast-deep-equal';\nimport getUniqueFieldNames from './getUniqueFieldNames';\nexport default function computeSpecChanges(newSpec, oldSpec) {\n if (newSpec === oldSpec) return false;\n const changes = {\n width: false,\n height: false,\n isExpensive: false\n };\n const fieldNames = getUniqueFieldNames([newSpec, oldSpec]);\n\n if (fieldNames.has('width') && (!('width' in newSpec) || !('width' in oldSpec) || newSpec.width !== oldSpec.width)) {\n if ('width' in newSpec && typeof newSpec.width === 'number') {\n changes.width = newSpec.width;\n } else {\n changes.isExpensive = true;\n }\n }\n\n if (fieldNames.has('height') && (!('height' in newSpec) || !('height' in oldSpec) || newSpec.height !== oldSpec.height)) {\n if ('height' in newSpec && typeof newSpec.height === 'number') {\n changes.height = newSpec.height;\n } else {\n changes.isExpensive = true;\n }\n } // Delete cheap fields\n\n\n fieldNames.delete('width');\n fieldNames.delete('height');\n\n if ([...fieldNames].some(field => !(field in newSpec) || !(field in oldSpec) || !equal(newSpec[field], oldSpec[field]))) {\n changes.isExpensive = true;\n }\n\n return changes.width !== false || changes.height !== false || changes.isExpensive ? changes : false;\n}","import _pt from \"prop-types\";\n\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nimport React from 'react';\nimport shallowEqual from './utils/shallowEqual';\nimport updateMultipleDatasetsInView from './utils/updateMultipleDatasetsInView';\nimport VegaEmbed from './VegaEmbed';\nimport { NOOP } from './constants';\nconst EMPTY = {};\nexport default class Vega extends React.PureComponent {\n constructor(...args) {\n super(...args);\n\n _defineProperty(this, \"vegaEmbed\", /*#__PURE__*/React.createRef());\n\n _defineProperty(this, \"handleNewView\", view => {\n this.update();\n const {\n onNewView = NOOP\n } = this.props;\n onNewView(view);\n });\n }\n\n componentDidMount() {\n this.update();\n }\n\n componentDidUpdate(prevProps) {\n if (!shallowEqual(this.props.data, prevProps.data)) {\n this.update();\n }\n }\n\n update() {\n const {\n data\n } = this.props;\n\n if (this.vegaEmbed.current && data && Object.keys(data).length > 0) {\n this.vegaEmbed.current.modifyView(view => {\n updateMultipleDatasetsInView(view, data);\n view.resize().run();\n });\n }\n }\n\n render() {\n const {\n data,\n ...restProps\n } = this.props;\n return /*#__PURE__*/React.createElement(VegaEmbed, _extends({\n ref: this.vegaEmbed\n }, restProps, {\n onNewView: this.handleNewView\n }));\n }\n\n}\n\n_defineProperty(Vega, \"defaultProps\", {\n data: EMPTY\n});","export var DEFAULT_CONFIG = {\n // minimum relative difference between two compared values,\n // used by all comparison functions\n epsilon: 1e-12,\n // type of default matrix output. Choose 'matrix' (default) or 'array'\n matrix: 'Matrix',\n // type of default number output. Choose 'number' (default) 'BigNumber', or 'Fraction\n number: 'number',\n // number of significant digits in BigNumbers\n precision: 64,\n // predictable output type of functions. When true, output type depends only\n // on the input types. When false (default), output type can vary depending\n // on input values. For example `math.sqrt(-4)` returns `complex('2i')` when\n // predictable is false, and returns `NaN` when true.\n predictable: false,\n // random seed for seeded pseudo random number generation\n // null = randomly seed\n randomSeed: null\n};","// type checks for all known types\n//\n// note that:\n//\n// - check by duck-typing on a property like `isUnit`, instead of checking instanceof.\n// instanceof cannot be used because that would not allow to pass data from\n// one instance of math.js to another since each has it's own instance of Unit.\n// - check the `isUnit` property via the constructor, so there will be no\n// matches for \"fake\" instances like plain objects with a property `isUnit`.\n// That is important for security reasons.\n// - It must not be possible to override the type checks used internally,\n// for security reasons, so these functions are not exposed in the expression\n// parser.\nexport function isNumber(x) {\n return typeof x === 'number';\n}\nexport function isBigNumber(x) {\n return x && x.constructor.prototype.isBigNumber === true || false;\n}\nexport function isComplex(x) {\n return x && typeof x === 'object' && Object.getPrototypeOf(x).isComplex === true || false;\n}\nexport function isFraction(x) {\n return x && typeof x === 'object' && Object.getPrototypeOf(x).isFraction === true || false;\n}\nexport function isUnit(x) {\n return x && x.constructor.prototype.isUnit === true || false;\n}\nexport function isString(x) {\n return typeof x === 'string';\n}\nexport var isArray = Array.isArray;\nexport function isMatrix(x) {\n return x && x.constructor.prototype.isMatrix === true || false;\n}\n/**\n * Test whether a value is a collection: an Array or Matrix\n * @param {*} x\n * @returns {boolean} isCollection\n */\n\nexport function isCollection(x) {\n return Array.isArray(x) || isMatrix(x);\n}\nexport function isDenseMatrix(x) {\n return x && x.isDenseMatrix && x.constructor.prototype.isMatrix === true || false;\n}\nexport function isSparseMatrix(x) {\n return x && x.isSparseMatrix && x.constructor.prototype.isMatrix === true || false;\n}\nexport function isRange(x) {\n return x && x.constructor.prototype.isRange === true || false;\n}\nexport function isIndex(x) {\n return x && x.constructor.prototype.isIndex === true || false;\n}\nexport function isBoolean(x) {\n return typeof x === 'boolean';\n}\nexport function isResultSet(x) {\n return x && x.constructor.prototype.isResultSet === true || false;\n}\nexport function isHelp(x) {\n return x && x.constructor.prototype.isHelp === true || false;\n}\nexport function isFunction(x) {\n return typeof x === 'function';\n}\nexport function isDate(x) {\n return x instanceof Date;\n}\nexport function isRegExp(x) {\n return x instanceof RegExp;\n}\nexport function isObject(x) {\n return !!(x && typeof x === 'object' && x.constructor === Object && !isComplex(x) && !isFraction(x));\n}\nexport function isNull(x) {\n return x === null;\n}\nexport function isUndefined(x) {\n return x === undefined;\n}\nexport function isAccessorNode(x) {\n return x && x.isAccessorNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isArrayNode(x) {\n return x && x.isArrayNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isAssignmentNode(x) {\n return x && x.isAssignmentNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isBlockNode(x) {\n return x && x.isBlockNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isConditionalNode(x) {\n return x && x.isConditionalNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isConstantNode(x) {\n return x && x.isConstantNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isFunctionAssignmentNode(x) {\n return x && x.isFunctionAssignmentNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isFunctionNode(x) {\n return x && x.isFunctionNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isIndexNode(x) {\n return x && x.isIndexNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isNode(x) {\n return x && x.isNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isObjectNode(x) {\n return x && x.isObjectNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isOperatorNode(x) {\n return x && x.isOperatorNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isParenthesisNode(x) {\n return x && x.isParenthesisNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isRangeNode(x) {\n return x && x.isRangeNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isSymbolNode(x) {\n return x && x.isSymbolNode === true && x.constructor.prototype.isNode === true || false;\n}\nexport function isChain(x) {\n return x && x.constructor.prototype.isChain === true || false;\n}\nexport function typeOf(x) {\n var t = typeof x;\n\n if (t === 'object') {\n // JavaScript types\n if (x === null) return 'null';\n if (Array.isArray(x)) return 'Array';\n if (x instanceof Date) return 'Date';\n if (x instanceof RegExp) return 'RegExp'; // math.js types\n\n if (isBigNumber(x)) return 'BigNumber';\n if (isComplex(x)) return 'Complex';\n if (isFraction(x)) return 'Fraction';\n if (isMatrix(x)) return 'Matrix';\n if (isUnit(x)) return 'Unit';\n if (isIndex(x)) return 'Index';\n if (isRange(x)) return 'Range';\n if (isResultSet(x)) return 'ResultSet';\n if (isNode(x)) return x.type;\n if (isChain(x)) return 'Chain';\n if (isHelp(x)) return 'Help';\n return 'Object';\n }\n\n if (t === 'function') return 'Function';\n return t; // can be 'string', 'number', 'boolean', ...\n}","import { isBigNumber } from './is.js';\n/**\n * Clone an object\n *\n * clone(x)\n *\n * Can clone any primitive type, array, and object.\n * If x has a function clone, this function will be invoked to clone the object.\n *\n * @param {*} x\n * @return {*} clone\n */\n\nexport function clone(x) {\n var type = typeof x; // immutable primitive types\n\n if (type === 'number' || type === 'string' || type === 'boolean' || x === null || x === undefined) {\n return x;\n } // use clone function of the object when available\n\n\n if (typeof x.clone === 'function') {\n return x.clone();\n } // array\n\n\n if (Array.isArray(x)) {\n return x.map(function (value) {\n return clone(value);\n });\n }\n\n if (x instanceof Date) return new Date(x.valueOf());\n if (isBigNumber(x)) return x; // bignumbers are immutable\n\n if (x instanceof RegExp) throw new TypeError('Cannot clone ' + x); // TODO: clone a RegExp\n // object\n\n return mapObject(x, clone);\n}\n/**\n * Apply map to all properties of an object\n * @param {Object} object\n * @param {function} callback\n * @return {Object} Returns a copy of the object with mapped properties\n */\n\nexport function mapObject(object, callback) {\n var clone = {};\n\n for (var key in object) {\n if (hasOwnProperty(object, key)) {\n clone[key] = callback(object[key]);\n }\n }\n\n return clone;\n}\n/**\n * Extend object a with the properties of object b\n * @param {Object} a\n * @param {Object} b\n * @return {Object} a\n */\n\nexport function extend(a, b) {\n for (var prop in b) {\n if (hasOwnProperty(b, prop)) {\n a[prop] = b[prop];\n }\n }\n\n return a;\n}\n/**\n * Deep extend an object a with the properties of object b\n * @param {Object} a\n * @param {Object} b\n * @returns {Object}\n */\n\nexport function deepExtend(a, b) {\n // TODO: add support for Arrays to deepExtend\n if (Array.isArray(b)) {\n throw new TypeError('Arrays are not supported by deepExtend');\n }\n\n for (var prop in b) {\n // We check against prop not being in Object.prototype or Function.prototype\n // to prevent polluting for example Object.__proto__.\n if (hasOwnProperty(b, prop) && !(prop in Object.prototype) && !(prop in Function.prototype)) {\n if (b[prop] && b[prop].constructor === Object) {\n if (a[prop] === undefined) {\n a[prop] = {};\n }\n\n if (a[prop] && a[prop].constructor === Object) {\n deepExtend(a[prop], b[prop]);\n } else {\n a[prop] = b[prop];\n }\n } else if (Array.isArray(b[prop])) {\n throw new TypeError('Arrays are not supported by deepExtend');\n } else {\n a[prop] = b[prop];\n }\n }\n }\n\n return a;\n}\n/**\n * Deep test equality of all fields in two pairs of arrays or objects.\n * Compares values and functions strictly (ie. 2 is not the same as '2').\n * @param {Array | Object} a\n * @param {Array | Object} b\n * @returns {boolean}\n */\n\nexport function deepStrictEqual(a, b) {\n var prop, i, len;\n\n if (Array.isArray(a)) {\n if (!Array.isArray(b)) {\n return false;\n }\n\n if (a.length !== b.length) {\n return false;\n }\n\n for (i = 0, len = a.length; i < len; i++) {\n if (!deepStrictEqual(a[i], b[i])) {\n return false;\n }\n }\n\n return true;\n } else if (typeof a === 'function') {\n return a === b;\n } else if (a instanceof Object) {\n if (Array.isArray(b) || !(b instanceof Object)) {\n return false;\n }\n\n for (prop in a) {\n // noinspection JSUnfilteredForInLoop\n if (!(prop in b) || !deepStrictEqual(a[prop], b[prop])) {\n return false;\n }\n }\n\n for (prop in b) {\n // noinspection JSUnfilteredForInLoop\n if (!(prop in a) || !deepStrictEqual(a[prop], b[prop])) {\n return false;\n }\n }\n\n return true;\n } else {\n return a === b;\n }\n}\n/**\n * Recursively flatten a nested object.\n * @param {Object} nestedObject\n * @return {Object} Returns the flattened object\n */\n\nexport function deepFlatten(nestedObject) {\n var flattenedObject = {};\n\n _deepFlatten(nestedObject, flattenedObject);\n\n return flattenedObject;\n} // helper function used by deepFlatten\n\nfunction _deepFlatten(nestedObject, flattenedObject) {\n for (var prop in nestedObject) {\n if (hasOwnProperty(nestedObject, prop)) {\n var value = nestedObject[prop];\n\n if (typeof value === 'object' && value !== null) {\n _deepFlatten(value, flattenedObject);\n } else {\n flattenedObject[prop] = value;\n }\n }\n }\n}\n/**\n * Test whether the current JavaScript engine supports Object.defineProperty\n * @returns {boolean} returns true if supported\n */\n\n\nexport function canDefineProperty() {\n // test needed for broken IE8 implementation\n try {\n if (Object.defineProperty) {\n Object.defineProperty({}, 'x', {\n get: function get() {}\n });\n return true;\n }\n } catch (e) {}\n\n return false;\n}\n/**\n * Attach a lazy loading property to a constant.\n * The given function `fn` is called once when the property is first requested.\n *\n * @param {Object} object Object where to add the property\n * @param {string} prop Property name\n * @param {Function} valueResolver Function returning the property value. Called\n * without arguments.\n */\n\nexport function lazy(object, prop, valueResolver) {\n var _uninitialized = true;\n\n var _value;\n\n Object.defineProperty(object, prop, {\n get: function get() {\n if (_uninitialized) {\n _value = valueResolver();\n _uninitialized = false;\n }\n\n return _value;\n },\n set: function set(value) {\n _value = value;\n _uninitialized = false;\n },\n configurable: true,\n enumerable: true\n });\n}\n/**\n * Traverse a path into an object.\n * When a namespace is missing, it will be created\n * @param {Object} object\n * @param {string | string[]} path A dot separated string like 'name.space'\n * @return {Object} Returns the object at the end of the path\n */\n\nexport function traverse(object, path) {\n if (path && typeof path === 'string') {\n return traverse(object, path.split('.'));\n }\n\n var obj = object;\n\n if (path) {\n for (var i = 0; i < path.length; i++) {\n var key = path[i];\n\n if (!(key in obj)) {\n obj[key] = {};\n }\n\n obj = obj[key];\n }\n }\n\n return obj;\n}\n/**\n * A safe hasOwnProperty\n * @param {Object} object\n * @param {string} property\n */\n\nexport function hasOwnProperty(object, property) {\n return object && Object.hasOwnProperty.call(object, property);\n}\n/**\n * Test whether an object is a factory. a factory has fields:\n *\n * - factory: function (type: Object, config: Object, load: function, typed: function [, math: Object]) (required)\n * - name: string (optional)\n * - path: string A dot separated path (optional)\n * - math: boolean If true (false by default), the math namespace is passed\n * as fifth argument of the factory function\n *\n * @param {*} object\n * @returns {boolean}\n */\n\nexport function isLegacyFactory(object) {\n return object && typeof object.factory === 'function';\n}\n/**\n * Get a nested property from an object\n * @param {Object} object\n * @param {string | string[]} path\n * @returns {Object}\n */\n\nexport function get(object, path) {\n if (typeof path === 'string') {\n if (isPath(path)) {\n return get(object, path.split('.'));\n } else {\n return object[path];\n }\n }\n\n var child = object;\n\n for (var i = 0; i < path.length; i++) {\n var key = path[i];\n child = child ? child[key] : undefined;\n }\n\n return child;\n}\n/**\n * Set a nested property in an object\n * Mutates the object itself\n * If the path doesn't exist, it will be created\n * @param {Object} object\n * @param {string | string[]} path\n * @param {*} value\n * @returns {Object}\n */\n\nexport function set(object, path, value) {\n if (typeof path === 'string') {\n if (isPath(path)) {\n return set(object, path.split('.'), value);\n } else {\n object[path] = value;\n return object;\n }\n }\n\n var child = object;\n\n for (var i = 0; i < path.length - 1; i++) {\n var key = path[i];\n\n if (child[key] === undefined) {\n child[key] = {};\n }\n\n child = child[key];\n }\n\n if (path.length > 0) {\n var lastKey = path[path.length - 1];\n child[lastKey] = value;\n }\n\n return object;\n}\n/**\n * Create an object composed of the picked object properties\n * @param {Object} object\n * @param {string[]} properties\n * @param {function} [transform] Optional value to transform a value when picking it\n * @return {Object}\n */\n\nexport function pick(object, properties, transform) {\n var copy = {};\n\n for (var i = 0; i < properties.length; i++) {\n var key = properties[i];\n var value = get(object, key);\n\n if (value !== undefined) {\n set(copy, key, transform ? transform(value, key) : value);\n }\n }\n\n return copy;\n}\n/**\n * Shallow version of pick, creating an object composed of the picked object properties\n * but not for nested properties\n * @param {Object} object\n * @param {string[]} properties\n * @return {Object}\n */\n\nexport function pickShallow(object, properties) {\n var copy = {};\n\n for (var i = 0; i < properties.length; i++) {\n var key = properties[i];\n var value = object[key];\n\n if (value !== undefined) {\n copy[key] = value;\n }\n }\n\n return copy;\n}\nexport function values(object) {\n return Object.keys(object).map(key => object[key]);\n} // helper function to test whether a string contains a path like 'user.name'\n\nfunction isPath(str) {\n return str.indexOf('.') !== -1;\n}","import { clone, mapObject, deepExtend } from '../../utils/object.js';\nimport { DEFAULT_CONFIG } from '../config.js';\nexport var MATRIX_OPTIONS = ['Matrix', 'Array']; // valid values for option matrix\n\nexport var NUMBER_OPTIONS = ['number', 'BigNumber', 'Fraction']; // valid values for option number\n\nexport function configFactory(config, emit) {\n /**\n * Set configuration options for math.js, and get current options.\n * Will emit a 'config' event, with arguments (curr, prev, changes).\n *\n * This function is only available on a mathjs instance created using `create`.\n *\n * Syntax:\n *\n * math.config(config: Object): Object\n *\n * Examples:\n *\n *\n * import { create, all } from 'mathjs'\n *\n * // create a mathjs instance\n * const math = create(all)\n *\n * math.config().number // outputs 'number'\n * math.evaluate('0.4') // outputs number 0.4\n * math.config({number: 'Fraction'})\n * math.evaluate('0.4') // outputs Fraction 2/5\n *\n * @param {Object} [options] Available options:\n * {number} epsilon\n * Minimum relative difference between two\n * compared values, used by all comparison functions.\n * {string} matrix\n * A string 'Matrix' (default) or 'Array'.\n * {string} number\n * A string 'number' (default), 'BigNumber', or 'Fraction'\n * {number} precision\n * The number of significant digits for BigNumbers.\n * Not applicable for Numbers.\n * {string} parenthesis\n * How to display parentheses in LaTeX and string\n * output.\n * {string} randomSeed\n * Random seed for seeded pseudo random number generator.\n * Set to null to randomly seed.\n * @return {Object} Returns the current configuration\n */\n function _config(options) {\n if (options) {\n var prev = mapObject(config, clone); // validate some of the options\n\n validateOption(options, 'matrix', MATRIX_OPTIONS);\n validateOption(options, 'number', NUMBER_OPTIONS); // merge options\n\n deepExtend(config, options);\n var curr = mapObject(config, clone);\n var changes = mapObject(options, clone); // emit 'config' event\n\n emit('config', curr, prev, changes);\n return curr;\n } else {\n return mapObject(config, clone);\n }\n } // attach the valid options to the function so they can be extended\n\n\n _config.MATRIX_OPTIONS = MATRIX_OPTIONS;\n _config.NUMBER_OPTIONS = NUMBER_OPTIONS; // attach the config properties as readonly properties to the config function\n\n Object.keys(DEFAULT_CONFIG).forEach(key => {\n Object.defineProperty(_config, key, {\n get: () => config[key],\n enumerable: true,\n configurable: true\n });\n });\n return _config;\n}\n/**\n * Test whether an Array contains a specific item.\n * @param {Array.} array\n * @param {string} item\n * @return {boolean}\n */\n\nfunction contains(array, item) {\n return array.indexOf(item) !== -1;\n}\n/**\n * Validate an option\n * @param {Object} options Object with options\n * @param {string} name Name of the option to validate\n * @param {Array.} values Array with valid values for this option\n */\n\n\nfunction validateOption(options, name, values) {\n if (options[name] !== undefined && !contains(values, options[name])) {\n // unknown value\n console.warn('Warning: Unknown value \"' + options[name] + '\" for configuration option \"' + name + '\". ' + 'Available options: ' + values.map(value => JSON.stringify(value)).join(', ') + '.');\n }\n}","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nimport { DEFAULT_CONFIG } from '../core/config.js';\nimport { MATRIX_OPTIONS, NUMBER_OPTIONS } from '../core/function/config.js'; // create a read-only version of config\n\nexport var config = /* #__PURE__ */function config(options) {\n if (options) {\n throw new Error('The global config is readonly. \\n' + 'Please create a mathjs instance if you want to change the default configuration. \\n' + 'Example:\\n' + '\\n' + ' import { create, all } from \\'mathjs\\';\\n' + ' const mathjs = create(all);\\n' + ' mathjs.config({ number: \\'BigNumber\\' });\\n');\n }\n\n return Object.freeze(DEFAULT_CONFIG);\n};\n\n_extends(config, DEFAULT_CONFIG, {\n MATRIX_OPTIONS,\n NUMBER_OPTIONS\n});","import { isNumber } from './is.js';\n/**\n * @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue\n */\n\n/**\n * Check if a number is integer\n * @param {number | boolean} value\n * @return {boolean} isInteger\n */\n\nexport function isInteger(value) {\n if (typeof value === 'boolean') {\n return true;\n }\n\n return isFinite(value) ? value === Math.round(value) : false;\n}\n/**\n * Calculate the sign of a number\n * @param {number} x\n * @returns {number}\n */\n\nexport var sign = /* #__PURE__ */Math.sign || function (x) {\n if (x > 0) {\n return 1;\n } else if (x < 0) {\n return -1;\n } else {\n return 0;\n }\n};\n/**\n * Calculate the base-2 logarithm of a number\n * @param {number} x\n * @returns {number}\n */\n\nexport var log2 = /* #__PURE__ */Math.log2 || function log2(x) {\n return Math.log(x) / Math.LN2;\n};\n/**\n * Calculate the base-10 logarithm of a number\n * @param {number} x\n * @returns {number}\n */\n\nexport var log10 = /* #__PURE__ */Math.log10 || function log10(x) {\n return Math.log(x) / Math.LN10;\n};\n/**\n * Calculate the natural logarithm of a number + 1\n * @param {number} x\n * @returns {number}\n */\n\nexport var log1p = /* #__PURE__ */Math.log1p || function (x) {\n return Math.log(x + 1);\n};\n/**\n * Calculate cubic root for a number\n *\n * Code from es6-shim.js:\n * https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577\n *\n * @param {number} x\n * @returns {number} Returns the cubic root of x\n */\n\nexport var cbrt = /* #__PURE__ */Math.cbrt || function cbrt(x) {\n if (x === 0) {\n return x;\n }\n\n var negate = x < 0;\n var result;\n\n if (negate) {\n x = -x;\n }\n\n if (isFinite(x)) {\n result = Math.exp(Math.log(x) / 3); // from https://en.wikipedia.org/wiki/Cube_root#Numerical_methods\n\n result = (x / (result * result) + 2 * result) / 3;\n } else {\n result = x;\n }\n\n return negate ? -result : result;\n};\n/**\n * Calculates exponentiation minus 1\n * @param {number} x\n * @return {number} res\n */\n\nexport var expm1 = /* #__PURE__ */Math.expm1 || function expm1(x) {\n return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6;\n};\n/**\n * Formats a number in a given base\n * @param {number} n\n * @param {number} base\n * @param {number} size\n * @returns {string}\n */\n\nfunction formatNumberToBase(n, base, size) {\n var prefixes = {\n 2: '0b',\n 8: '0o',\n 16: '0x'\n };\n var prefix = prefixes[base];\n var suffix = '';\n\n if (size) {\n if (size < 1) {\n throw new Error('size must be in greater than 0');\n }\n\n if (!isInteger(size)) {\n throw new Error('size must be an integer');\n }\n\n if (n > 2 ** (size - 1) - 1 || n < -(2 ** (size - 1))) {\n throw new Error(\"Value must be in range [-2^\".concat(size - 1, \", 2^\").concat(size - 1, \"-1]\"));\n }\n\n if (!isInteger(n)) {\n throw new Error('Value must be an integer');\n }\n\n if (n < 0) {\n n = n + 2 ** size;\n }\n\n suffix = \"i\".concat(size);\n }\n\n var sign = '';\n\n if (n < 0) {\n n = -n;\n sign = '-';\n }\n\n return \"\".concat(sign).concat(prefix).concat(n.toString(base)).concat(suffix);\n}\n/**\n * Convert a number to a formatted string representation.\n *\n * Syntax:\n *\n * format(value)\n * format(value, options)\n * format(value, precision)\n * format(value, fn)\n *\n * Where:\n *\n * {number} value The value to be formatted\n * {Object} options An object with formatting options. Available options:\n * {string} notation\n * Number notation. Choose from:\n * 'fixed' Always use regular number notation.\n * For example '123.40' and '14000000'\n * 'exponential' Always use exponential notation.\n * For example '1.234e+2' and '1.4e+7'\n * 'engineering' Always use engineering notation.\n * For example '123.4e+0' and '14.0e+6'\n * 'auto' (default) Regular number notation for numbers\n * having an absolute value between\n * `lowerExp` and `upperExp` bounds, and\n * uses exponential notation elsewhere.\n * Lower bound is included, upper bound\n * is excluded.\n * For example '123.4' and '1.4e7'.\n * 'bin', 'oct, or\n * 'hex' Format the number using binary, octal,\n * or hexadecimal notation.\n * For example '0b1101' and '0x10fe'.\n * {number} wordSize The word size in bits to use for formatting\n * in binary, octal, or hexadecimal notation.\n * To be used only with 'bin', 'oct', or 'hex'\n * values for 'notation' option. When this option\n * is defined the value is formatted as a signed\n * twos complement integer of the given word size\n * and the size suffix is appended to the output.\n * For example\n * format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'.\n * Default value is undefined.\n * {number} precision A number between 0 and 16 to round\n * the digits of the number.\n * In case of notations 'exponential',\n * 'engineering', and 'auto',\n * `precision` defines the total\n * number of significant digits returned.\n * In case of notation 'fixed',\n * `precision` defines the number of\n * significant digits after the decimal\n * point.\n * `precision` is undefined by default,\n * not rounding any digits.\n * {number} lowerExp Exponent determining the lower boundary\n * for formatting a value with an exponent\n * when `notation='auto`.\n * Default value is `-3`.\n * {number} upperExp Exponent determining the upper boundary\n * for formatting a value with an exponent\n * when `notation='auto`.\n * Default value is `5`.\n * {Function} fn A custom formatting function. Can be used to override the\n * built-in notations. Function `fn` is called with `value` as\n * parameter and must return a string. Is useful for example to\n * format all values inside a matrix in a particular way.\n *\n * Examples:\n *\n * format(6.4) // '6.4'\n * format(1240000) // '1.24e6'\n * format(1/3) // '0.3333333333333333'\n * format(1/3, 3) // '0.333'\n * format(21385, 2) // '21000'\n * format(12.071, {notation: 'fixed'}) // '12'\n * format(2.3, {notation: 'fixed', precision: 2}) // '2.30'\n * format(52.8, {notation: 'exponential'}) // '5.28e+1'\n * format(12345678, {notation: 'engineering'}) // '12.345678e+6'\n *\n * @param {number} value\n * @param {Object | Function | number} [options]\n * @return {string} str The formatted value\n */\n\n\nexport function format(value, options) {\n if (typeof options === 'function') {\n // handle format(value, fn)\n return options(value);\n } // handle special cases\n\n\n if (value === Infinity) {\n return 'Infinity';\n } else if (value === -Infinity) {\n return '-Infinity';\n } else if (isNaN(value)) {\n return 'NaN';\n } // default values for options\n\n\n var notation = 'auto';\n var precision;\n var wordSize;\n\n if (options) {\n // determine notation from options\n if (options.notation) {\n notation = options.notation;\n } // determine precision from options\n\n\n if (isNumber(options)) {\n precision = options;\n } else if (isNumber(options.precision)) {\n precision = options.precision;\n }\n\n if (options.wordSize) {\n wordSize = options.wordSize;\n\n if (typeof wordSize !== 'number') {\n throw new Error('Option \"wordSize\" must be a number');\n }\n }\n } // handle the various notations\n\n\n switch (notation) {\n case 'fixed':\n return toFixed(value, precision);\n\n case 'exponential':\n return toExponential(value, precision);\n\n case 'engineering':\n return toEngineering(value, precision);\n\n case 'bin':\n return formatNumberToBase(value, 2, wordSize);\n\n case 'oct':\n return formatNumberToBase(value, 8, wordSize);\n\n case 'hex':\n return formatNumberToBase(value, 16, wordSize);\n\n case 'auto':\n // remove trailing zeros after the decimal point\n return toPrecision(value, precision, options && options).replace(/((\\.\\d*?)(0+))($|e)/, function () {\n var digits = arguments[2];\n var e = arguments[4];\n return digits !== '.' ? digits + e : e;\n });\n\n default:\n throw new Error('Unknown notation \"' + notation + '\". ' + 'Choose \"auto\", \"exponential\", \"fixed\", \"bin\", \"oct\", or \"hex.');\n }\n}\n/**\n * Split a number into sign, coefficients, and exponent\n * @param {number | string} value\n * @return {SplitValue}\n * Returns an object containing sign, coefficients, and exponent\n */\n\nexport function splitNumber(value) {\n // parse the input value\n var match = String(value).toLowerCase().match(/^0*?(-?)(\\d+\\.?\\d*)(e([+-]?\\d+))?$/);\n\n if (!match) {\n throw new SyntaxError('Invalid number ' + value);\n }\n\n var sign = match[1];\n var digits = match[2];\n var exponent = parseFloat(match[4] || '0');\n var dot = digits.indexOf('.');\n exponent += dot !== -1 ? dot - 1 : digits.length - 1;\n var coefficients = digits.replace('.', '') // remove the dot (must be removed before removing leading zeros)\n .replace(/^0*/, function (zeros) {\n // remove leading zeros, add their count to the exponent\n exponent -= zeros.length;\n return '';\n }).replace(/0*$/, '') // remove trailing zeros\n .split('').map(function (d) {\n return parseInt(d);\n });\n\n if (coefficients.length === 0) {\n coefficients.push(0);\n exponent++;\n }\n\n return {\n sign: sign,\n coefficients: coefficients,\n exponent: exponent\n };\n}\n/**\n * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'\n * @param {number | string} value\n * @param {number} [precision] Optional number of significant figures to return.\n */\n\nexport function toEngineering(value, precision) {\n if (isNaN(value) || !isFinite(value)) {\n return String(value);\n }\n\n var split = splitNumber(value);\n var rounded = roundDigits(split, precision);\n var e = rounded.exponent;\n var c = rounded.coefficients; // find nearest lower multiple of 3 for exponent\n\n var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;\n\n if (isNumber(precision)) {\n // add zeroes to give correct sig figs\n while (precision > c.length || e - newExp + 1 > c.length) {\n c.push(0);\n }\n } else {\n // concatenate coefficients with necessary zeros\n // add zeros if necessary (for example: 1e+8 -> 100e+6)\n var missingZeros = Math.abs(e - newExp) - (c.length - 1);\n\n for (var i = 0; i < missingZeros; i++) {\n c.push(0);\n }\n } // find difference in exponents\n\n\n var expDiff = Math.abs(e - newExp);\n var decimalIdx = 1; // push decimal index over by expDiff times\n\n while (expDiff > 0) {\n decimalIdx++;\n expDiff--;\n } // if all coefficient values are zero after the decimal point and precision is unset, don't add a decimal value.\n // otherwise concat with the rest of the coefficients\n\n\n var decimals = c.slice(decimalIdx).join('');\n var decimalVal = isNumber(precision) && decimals.length || decimals.match(/[1-9]/) ? '.' + decimals : '';\n var str = c.slice(0, decimalIdx).join('') + decimalVal + 'e' + (e >= 0 ? '+' : '') + newExp.toString();\n return rounded.sign + str;\n}\n/**\n * Format a number with fixed notation.\n * @param {number | string} value\n * @param {number} [precision=undefined] Optional number of decimals after the\n * decimal point. null by default.\n */\n\nexport function toFixed(value, precision) {\n if (isNaN(value) || !isFinite(value)) {\n return String(value);\n }\n\n var splitValue = splitNumber(value);\n var rounded = typeof precision === 'number' ? roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue;\n var c = rounded.coefficients;\n var p = rounded.exponent + 1; // exponent may have changed\n // append zeros if needed\n\n var pp = p + (precision || 0);\n\n if (c.length < pp) {\n c = c.concat(zeros(pp - c.length));\n } // prepend zeros if needed\n\n\n if (p < 0) {\n c = zeros(-p + 1).concat(c);\n p = 1;\n } // insert a dot if needed\n\n\n if (p < c.length) {\n c.splice(p, 0, p === 0 ? '0.' : '.');\n }\n\n return rounded.sign + c.join('');\n}\n/**\n * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'\n * @param {number | string} value\n * @param {number} [precision] Number of digits in formatted output.\n * If not provided, the maximum available digits\n * is used.\n */\n\nexport function toExponential(value, precision) {\n if (isNaN(value) || !isFinite(value)) {\n return String(value);\n } // round if needed, else create a clone\n\n\n var split = splitNumber(value);\n var rounded = precision ? roundDigits(split, precision) : split;\n var c = rounded.coefficients;\n var e = rounded.exponent; // append zeros if needed\n\n if (c.length < precision) {\n c = c.concat(zeros(precision - c.length));\n } // format as `C.CCCe+EEE` or `C.CCCe-EEE`\n\n\n var first = c.shift();\n return rounded.sign + first + (c.length > 0 ? '.' + c.join('') : '') + 'e' + (e >= 0 ? '+' : '') + e;\n}\n/**\n * Format a number with a certain precision\n * @param {number | string} value\n * @param {number} [precision=undefined] Optional number of digits.\n * @param {{lowerExp: number | undefined, upperExp: number | undefined}} [options]\n * By default:\n * lowerExp = -3 (incl)\n * upper = +5 (excl)\n * @return {string}\n */\n\nexport function toPrecision(value, precision, options) {\n if (isNaN(value) || !isFinite(value)) {\n return String(value);\n } // determine lower and upper bound for exponential notation.\n\n\n var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3;\n var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5;\n var split = splitNumber(value);\n var rounded = precision ? roundDigits(split, precision) : split;\n\n if (rounded.exponent < lowerExp || rounded.exponent >= upperExp) {\n // exponential notation\n return toExponential(value, precision);\n } else {\n var c = rounded.coefficients;\n var e = rounded.exponent; // append trailing zeros\n\n if (c.length < precision) {\n c = c.concat(zeros(precision - c.length));\n } // append trailing zeros\n // TODO: simplify the next statement\n\n\n c = c.concat(zeros(e - c.length + 1 + (c.length < precision ? precision - c.length : 0))); // prepend zeros\n\n c = zeros(-e).concat(c);\n var dot = e > 0 ? e : 0;\n\n if (dot < c.length - 1) {\n c.splice(dot + 1, 0, '.');\n }\n\n return rounded.sign + c.join('');\n }\n}\n/**\n * Round the number of digits of a number *\n * @param {SplitValue} split A value split with .splitNumber(value)\n * @param {number} precision A positive integer\n * @return {SplitValue}\n * Returns an object containing sign, coefficients, and exponent\n * with rounded digits\n */\n\nexport function roundDigits(split, precision) {\n // create a clone\n var rounded = {\n sign: split.sign,\n coefficients: split.coefficients,\n exponent: split.exponent\n };\n var c = rounded.coefficients; // prepend zeros if needed\n\n while (precision <= 0) {\n c.unshift(0);\n rounded.exponent++;\n precision++;\n }\n\n if (c.length > precision) {\n var removed = c.splice(precision, c.length - precision);\n\n if (removed[0] >= 5) {\n var i = precision - 1;\n c[i]++;\n\n while (c[i] === 10) {\n c.pop();\n\n if (i === 0) {\n c.unshift(0);\n rounded.exponent++;\n i++;\n }\n\n i--;\n c[i]++;\n }\n }\n }\n\n return rounded;\n}\n/**\n * Create an array filled with zeros.\n * @param {number} length\n * @return {Array}\n */\n\nfunction zeros(length) {\n var arr = [];\n\n for (var i = 0; i < length; i++) {\n arr.push(0);\n }\n\n return arr;\n}\n/**\n * Count the number of significant digits of a number.\n *\n * For example:\n * 2.34 returns 3\n * 0.0034 returns 2\n * 120.5e+30 returns 4\n *\n * @param {number} value\n * @return {number} digits Number of significant digits\n */\n\n\nexport function digits(value) {\n return value.toExponential().replace(/e.*$/, '') // remove exponential notation\n .replace(/^0\\.?0*|\\./, '') // remove decimal point and leading zeros\n .length;\n}\n/**\n * Minimum number added to one that makes the result different than one\n */\n\nexport var DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16;\n/**\n * Compares two floating point numbers.\n * @param {number} x First value to compare\n * @param {number} y Second value to compare\n * @param {number} [epsilon] The maximum relative difference between x and y\n * If epsilon is undefined or null, the function will\n * test whether x and y are exactly equal.\n * @return {boolean} whether the two numbers are nearly equal\n*/\n\nexport function nearlyEqual(x, y, epsilon) {\n // if epsilon is null or undefined, test whether x and y are exactly equal\n if (epsilon === null || epsilon === undefined) {\n return x === y;\n }\n\n if (x === y) {\n return true;\n } // NaN\n\n\n if (isNaN(x) || isNaN(y)) {\n return false;\n } // at this point x and y should be finite\n\n\n if (isFinite(x) && isFinite(y)) {\n // check numbers are very close, needed when comparing numbers near zero\n var diff = Math.abs(x - y);\n\n if (diff < DBL_EPSILON) {\n return true;\n } else {\n // use relative error\n return diff <= Math.max(Math.abs(x), Math.abs(y)) * epsilon;\n }\n } // Infinite and Number or negative Infinite and positive Infinite cases\n\n\n return false;\n}\n/**\n * Calculate the hyperbolic arccos of a number\n * @param {number} x\n * @return {number}\n */\n\nexport var acosh = Math.acosh || function (x) {\n return Math.log(Math.sqrt(x * x - 1) + x);\n};\nexport var asinh = Math.asinh || function (x) {\n return Math.log(Math.sqrt(x * x + 1) + x);\n};\n/**\n * Calculate the hyperbolic arctangent of a number\n * @param {number} x\n * @return {number}\n */\n\nexport var atanh = Math.atanh || function (x) {\n return Math.log((1 + x) / (1 - x)) / 2;\n};\n/**\n * Calculate the hyperbolic cosine of a number\n * @param {number} x\n * @returns {number}\n */\n\nexport var cosh = Math.cosh || function (x) {\n return (Math.exp(x) + Math.exp(-x)) / 2;\n};\n/**\n * Calculate the hyperbolic sine of a number\n * @param {number} x\n * @returns {number}\n */\n\nexport var sinh = Math.sinh || function (x) {\n return (Math.exp(x) - Math.exp(-x)) / 2;\n};\n/**\n * Calculate the hyperbolic tangent of a number\n * @param {number} x\n * @returns {number}\n */\n\nexport var tanh = Math.tanh || function (x) {\n var e = Math.exp(2 * x);\n return (e - 1) / (e + 1);\n};","import { isInteger } from '../number.js';\n/**\n * Formats a BigNumber in a given base\n * @param {BigNumber} n\n * @param {number} base\n * @param {number} size\n * @returns {string}\n */\n\nfunction formatBigNumberToBase(n, base, size) {\n var BigNumberCtor = n.constructor;\n var big2 = new BigNumberCtor(2);\n var suffix = '';\n\n if (size) {\n if (size < 1) {\n throw new Error('size must be in greater than 0');\n }\n\n if (!isInteger(size)) {\n throw new Error('size must be an integer');\n }\n\n if (n.greaterThan(big2.pow(size - 1).sub(1)) || n.lessThan(big2.pow(size - 1).mul(-1))) {\n throw new Error(\"Value must be in range [-2^\".concat(size - 1, \", 2^\").concat(size - 1, \"-1]\"));\n }\n\n if (!n.isInteger()) {\n throw new Error('Value must be an integer');\n }\n\n if (n.lessThan(0)) {\n n = n.add(big2.pow(size));\n }\n\n suffix = \"i\".concat(size);\n }\n\n switch (base) {\n case 2:\n return \"\".concat(n.toBinary()).concat(suffix);\n\n case 8:\n return \"\".concat(n.toOctal()).concat(suffix);\n\n case 16:\n return \"\".concat(n.toHexadecimal()).concat(suffix);\n\n default:\n throw new Error(\"Base \".concat(base, \" not supported \"));\n }\n}\n/**\n * Convert a BigNumber to a formatted string representation.\n *\n * Syntax:\n *\n * format(value)\n * format(value, options)\n * format(value, precision)\n * format(value, fn)\n *\n * Where:\n *\n * {number} value The value to be formatted\n * {Object} options An object with formatting options. Available options:\n * {string} notation\n * Number notation. Choose from:\n * 'fixed' Always use regular number notation.\n * For example '123.40' and '14000000'\n * 'exponential' Always use exponential notation.\n * For example '1.234e+2' and '1.4e+7'\n * 'auto' (default) Regular number notation for numbers\n * having an absolute value between\n * `lower` and `upper` bounds, and uses\n * exponential notation elsewhere.\n * Lower bound is included, upper bound\n * is excluded.\n * For example '123.4' and '1.4e7'.\n * 'bin', 'oct, or\n * 'hex' Format the number using binary, octal,\n * or hexadecimal notation.\n * For example '0b1101' and '0x10fe'.\n * {number} wordSize The word size in bits to use for formatting\n * in binary, octal, or hexadecimal notation.\n * To be used only with 'bin', 'oct', or 'hex'\n * values for 'notation' option. When this option\n * is defined the value is formatted as a signed\n * twos complement integer of the given word size\n * and the size suffix is appended to the output.\n * For example\n * format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'.\n * Default value is undefined.\n * {number} precision A number between 0 and 16 to round\n * the digits of the number.\n * In case of notations 'exponential',\n * 'engineering', and 'auto',\n * `precision` defines the total\n * number of significant digits returned.\n * In case of notation 'fixed',\n * `precision` defines the number of\n * significant digits after the decimal\n * point.\n * `precision` is undefined by default.\n * {number} lowerExp Exponent determining the lower boundary\n * for formatting a value with an exponent\n * when `notation='auto`.\n * Default value is `-3`.\n * {number} upperExp Exponent determining the upper boundary\n * for formatting a value with an exponent\n * when `notation='auto`.\n * Default value is `5`.\n * {Function} fn A custom formatting function. Can be used to override the\n * built-in notations. Function `fn` is called with `value` as\n * parameter and must return a string. Is useful for example to\n * format all values inside a matrix in a particular way.\n *\n * Examples:\n *\n * format(6.4) // '6.4'\n * format(1240000) // '1.24e6'\n * format(1/3) // '0.3333333333333333'\n * format(1/3, 3) // '0.333'\n * format(21385, 2) // '21000'\n * format(12e8, {notation: 'fixed'}) // returns '1200000000'\n * format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000'\n * format(52.8, {notation: 'exponential'}) // returns '5.28e+1'\n * format(12400, {notation: 'engineering'}) // returns '12.400e+3'\n *\n * @param {BigNumber} value\n * @param {Object | Function | number} [options]\n * @return {string} str The formatted value\n */\n\n\nexport function format(value, options) {\n if (typeof options === 'function') {\n // handle format(value, fn)\n return options(value);\n } // handle special cases\n\n\n if (!value.isFinite()) {\n return value.isNaN() ? 'NaN' : value.gt(0) ? 'Infinity' : '-Infinity';\n } // default values for options\n\n\n var notation = 'auto';\n var precision;\n var wordSize;\n\n if (options !== undefined) {\n // determine notation from options\n if (options.notation) {\n notation = options.notation;\n } // determine precision from options\n\n\n if (typeof options === 'number') {\n precision = options;\n } else if (options.precision) {\n precision = options.precision;\n }\n\n if (options.wordSize) {\n wordSize = options.wordSize;\n\n if (typeof wordSize !== 'number') {\n throw new Error('Option \"wordSize\" must be a number');\n }\n }\n } // handle the various notations\n\n\n switch (notation) {\n case 'fixed':\n return toFixed(value, precision);\n\n case 'exponential':\n return toExponential(value, precision);\n\n case 'engineering':\n return toEngineering(value, precision);\n\n case 'bin':\n return formatBigNumberToBase(value, 2, wordSize);\n\n case 'oct':\n return formatBigNumberToBase(value, 8, wordSize);\n\n case 'hex':\n return formatBigNumberToBase(value, 16, wordSize);\n\n case 'auto':\n {\n // determine lower and upper bound for exponential notation.\n // TODO: implement support for upper and lower to be BigNumbers themselves\n var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3;\n var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5; // handle special case zero\n\n if (value.isZero()) return '0'; // determine whether or not to output exponential notation\n\n var str;\n var rounded = value.toSignificantDigits(precision);\n var exp = rounded.e;\n\n if (exp >= lowerExp && exp < upperExp) {\n // normal number notation\n str = rounded.toFixed();\n } else {\n // exponential notation\n str = toExponential(value, precision);\n } // remove trailing zeros after the decimal point\n\n\n return str.replace(/((\\.\\d*?)(0+))($|e)/, function () {\n var digits = arguments[2];\n var e = arguments[4];\n return digits !== '.' ? digits + e : e;\n });\n }\n\n default:\n throw new Error('Unknown notation \"' + notation + '\". ' + 'Choose \"auto\", \"exponential\", \"fixed\", \"bin\", \"oct\", or \"hex.');\n }\n}\n/**\n * Format a BigNumber in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'\n * @param {BigNumber | string} value\n * @param {number} [precision] Optional number of significant figures to return.\n */\n\nexport function toEngineering(value, precision) {\n // find nearest lower multiple of 3 for exponent\n var e = value.e;\n var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3; // find difference in exponents, and calculate the value without exponent\n\n var valueWithoutExp = value.mul(Math.pow(10, -newExp));\n var valueStr = valueWithoutExp.toPrecision(precision);\n\n if (valueStr.indexOf('e') !== -1) {\n valueStr = valueWithoutExp.toString();\n }\n\n return valueStr + 'e' + (e >= 0 ? '+' : '') + newExp.toString();\n}\n/**\n * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'\n * @param {BigNumber} value\n * @param {number} [precision] Number of digits in formatted output.\n * If not provided, the maximum available digits\n * is used.\n * @returns {string} str\n */\n\nexport function toExponential(value, precision) {\n if (precision !== undefined) {\n return value.toExponential(precision - 1); // Note the offset of one\n } else {\n return value.toExponential();\n }\n}\n/**\n * Format a number with fixed notation.\n * @param {BigNumber} value\n * @param {number} [precision=undefined] Optional number of decimals after the\n * decimal point. Undefined by default.\n */\n\nexport function toFixed(value, precision) {\n return value.toFixed(precision);\n}","import { isBigNumber, isString, typeOf } from './is.js';\nimport { format as formatNumber } from './number.js';\nimport { format as formatBigNumber } from './bignumber/formatter.js';\n/**\n * Check if a text ends with a certain string.\n * @param {string} text\n * @param {string} search\n */\n\nexport function endsWith(text, search) {\n var start = text.length - search.length;\n var end = text.length;\n return text.substring(start, end) === search;\n}\n/**\n * Format a value of any type into a string.\n *\n * Usage:\n * math.format(value)\n * math.format(value, precision)\n *\n * When value is a function:\n *\n * - When the function has a property `syntax`, it returns this\n * syntax description.\n * - In other cases, a string `'function'` is returned.\n *\n * When `value` is an Object:\n *\n * - When the object contains a property `format` being a function, this\n * function is invoked as `value.format(options)` and the result is returned.\n * - When the object has its own `toString` method, this method is invoked\n * and the result is returned.\n * - In other cases the function will loop over all object properties and\n * return JSON object notation like '{\"a\": 2, \"b\": 3}'.\n *\n * Example usage:\n * math.format(2/7) // '0.2857142857142857'\n * math.format(math.pi, 3) // '3.14'\n * math.format(new Complex(2, 3)) // '2 + 3i'\n * math.format('hello') // '\"hello\"'\n *\n * @param {*} value Value to be stringified\n * @param {Object | number | Function} [options] Formatting options. See\n * lib/utils/number:format for a\n * description of the available\n * options.\n * @return {string} str\n */\n\nexport function format(value, options) {\n if (typeof value === 'number') {\n return formatNumber(value, options);\n }\n\n if (isBigNumber(value)) {\n return formatBigNumber(value, options);\n } // note: we use unsafe duck-typing here to check for Fractions, this is\n // ok here since we're only invoking toString or concatenating its values\n\n\n if (looksLikeFraction(value)) {\n if (!options || options.fraction !== 'decimal') {\n // output as ratio, like '1/3'\n return value.s * value.n + '/' + value.d;\n } else {\n // output as decimal, like '0.(3)'\n return value.toString();\n }\n }\n\n if (Array.isArray(value)) {\n return formatArray(value, options);\n }\n\n if (isString(value)) {\n return '\"' + value + '\"';\n }\n\n if (typeof value === 'function') {\n return value.syntax ? String(value.syntax) : 'function';\n }\n\n if (value && typeof value === 'object') {\n if (typeof value.format === 'function') {\n return value.format(options);\n } else if (value && value.toString(options) !== {}.toString()) {\n // this object has a non-native toString method, use that one\n return value.toString(options);\n } else {\n var entries = Object.keys(value).map(key => {\n return '\"' + key + '\": ' + format(value[key], options);\n });\n return '{' + entries.join(', ') + '}';\n }\n }\n\n return String(value);\n}\n/**\n * Stringify a value into a string enclosed in double quotes.\n * Unescaped double quotes and backslashes inside the value are escaped.\n * @param {*} value\n * @return {string}\n */\n\nexport function stringify(value) {\n var text = String(value);\n var escaped = '';\n var i = 0;\n\n while (i < text.length) {\n var c = text.charAt(i);\n\n if (c === '\\\\') {\n escaped += c;\n i++;\n c = text.charAt(i);\n\n if (c === '' || '\"\\\\/bfnrtu'.indexOf(c) === -1) {\n escaped += '\\\\'; // no valid escape character -> escape it\n }\n\n escaped += c;\n } else if (c === '\"') {\n escaped += '\\\\\"';\n } else {\n escaped += c;\n }\n\n i++;\n }\n\n return '\"' + escaped + '\"';\n}\n/**\n * Escape special HTML characters\n * @param {*} value\n * @return {string}\n */\n\nexport function escape(value) {\n var text = String(value);\n text = text.replace(/&/g, '&').replace(/\"/g, '"').replace(/'/g, ''').replace(//g, '>');\n return text;\n}\n/**\n * Recursively format an n-dimensional matrix\n * Example output: \"[[1, 2], [3, 4]]\"\n * @param {Array} array\n * @param {Object | number | Function} [options] Formatting options. See\n * lib/utils/number:format for a\n * description of the available\n * options.\n * @returns {string} str\n */\n\nfunction formatArray(array, options) {\n if (Array.isArray(array)) {\n var str = '[';\n var len = array.length;\n\n for (var i = 0; i < len; i++) {\n if (i !== 0) {\n str += ', ';\n }\n\n str += formatArray(array[i], options);\n }\n\n str += ']';\n return str;\n } else {\n return format(array, options);\n }\n}\n/**\n * Check whether a value looks like a Fraction (unsafe duck-type check)\n * @param {*} value\n * @return {boolean}\n */\n\n\nfunction looksLikeFraction(value) {\n return value && typeof value === 'object' && typeof value.s === 'number' && typeof value.n === 'number' && typeof value.d === 'number' || false;\n}\n/**\n * Compare two strings\n * @param {string} x\n * @param {string} y\n * @returns {number}\n */\n\n\nexport function compareText(x, y) {\n // we don't want to convert numbers to string, only accept string input\n if (!isString(x)) {\n throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + typeOf(x) + ', index: 0)');\n }\n\n if (!isString(y)) {\n throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + typeOf(y) + ', index: 1)');\n }\n\n return x === y ? 0 : x > y ? 1 : -1;\n}","/**\n * Create a range error with the message:\n * 'Dimension mismatch ( != )'\n * @param {number | number[]} actual The actual size\n * @param {number | number[]} expected The expected size\n * @param {string} [relation='!='] Optional relation between actual\n * and expected size: '!=', '<', etc.\n * @extends RangeError\n */\nexport function DimensionError(actual, expected, relation) {\n if (!(this instanceof DimensionError)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n }\n\n this.actual = actual;\n this.expected = expected;\n this.relation = relation;\n this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? '[' + actual.join(', ') + ']' : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? '[' + expected.join(', ') + ']' : expected) + ')';\n this.stack = new Error().stack;\n}\nDimensionError.prototype = new RangeError();\nDimensionError.prototype.constructor = RangeError;\nDimensionError.prototype.name = 'DimensionError';\nDimensionError.prototype.isDimensionError = true;","/**\n * Create a range error with the message:\n * 'Index out of range (index < min)'\n * 'Index out of range (index < max)'\n *\n * @param {number} index The actual index\n * @param {number} [min=0] Minimum index (included)\n * @param {number} [max] Maximum index (excluded)\n * @extends RangeError\n */\nexport function IndexError(index, min, max) {\n if (!(this instanceof IndexError)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n }\n\n this.index = index;\n\n if (arguments.length < 3) {\n this.min = 0;\n this.max = min;\n } else {\n this.min = min;\n this.max = max;\n }\n\n if (this.min !== undefined && this.index < this.min) {\n this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')';\n } else if (this.max !== undefined && this.index >= this.max) {\n this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')';\n } else {\n this.message = 'Index out of range (' + this.index + ')';\n }\n\n this.stack = new Error().stack;\n}\nIndexError.prototype = new RangeError();\nIndexError.prototype.constructor = RangeError;\nIndexError.prototype.name = 'IndexError';\nIndexError.prototype.isIndexError = true;","import { isInteger } from './number.js';\nimport { isNumber } from './is.js';\nimport { format } from './string.js';\nimport { DimensionError } from '../error/DimensionError.js';\nimport { IndexError } from '../error/IndexError.js';\n/**\n * Calculate the size of a multi dimensional array.\n * This function checks the size of the first entry, it does not validate\n * whether all dimensions match. (use function `validate` for that)\n * @param {Array} x\n * @Return {Number[]} size\n */\n\nexport function arraySize(x) {\n var s = [];\n\n while (Array.isArray(x)) {\n s.push(x.length);\n x = x[0];\n }\n\n return s;\n}\n/**\n * Recursively validate whether each element in a multi dimensional array\n * has a size corresponding to the provided size array.\n * @param {Array} array Array to be validated\n * @param {number[]} size Array with the size of each dimension\n * @param {number} dim Current dimension\n * @throws DimensionError\n * @private\n */\n\nfunction _validate(array, size, dim) {\n var i;\n var len = array.length;\n\n if (len !== size[dim]) {\n throw new DimensionError(len, size[dim]);\n }\n\n if (dim < size.length - 1) {\n // recursively validate each child array\n var dimNext = dim + 1;\n\n for (i = 0; i < len; i++) {\n var child = array[i];\n\n if (!Array.isArray(child)) {\n throw new DimensionError(size.length - 1, size.length, '<');\n }\n\n _validate(array[i], size, dimNext);\n }\n } else {\n // last dimension. none of the childs may be an array\n for (i = 0; i < len; i++) {\n if (Array.isArray(array[i])) {\n throw new DimensionError(size.length + 1, size.length, '>');\n }\n }\n }\n}\n/**\n * Validate whether each element in a multi dimensional array has\n * a size corresponding to the provided size array.\n * @param {Array} array Array to be validated\n * @param {number[]} size Array with the size of each dimension\n * @throws DimensionError\n */\n\n\nexport function validate(array, size) {\n var isScalar = size.length === 0;\n\n if (isScalar) {\n // scalar\n if (Array.isArray(array)) {\n throw new DimensionError(array.length, 0);\n }\n } else {\n // array\n _validate(array, size, 0);\n }\n}\n/**\n * Test whether index is an integer number with index >= 0 and index < length\n * when length is provided\n * @param {number} index Zero-based index\n * @param {number} [length] Length of the array\n */\n\nexport function validateIndex(index, length) {\n if (!isNumber(index) || !isInteger(index)) {\n throw new TypeError('Index must be an integer (value: ' + index + ')');\n }\n\n if (index < 0 || typeof length === 'number' && index >= length) {\n throw new IndexError(index, length);\n }\n}\n/**\n * Resize a multi dimensional array. The resized array is returned.\n * @param {Array} array Array to be resized\n * @param {Array.} size Array with the size of each dimension\n * @param {*} [defaultValue=0] Value to be filled in in new entries,\n * zero by default. Specify for example `null`,\n * to clearly see entries that are not explicitly\n * set.\n * @return {Array} array The resized array\n */\n\nexport function resize(array, size, defaultValue) {\n // TODO: add support for scalars, having size=[] ?\n // check the type of the arguments\n if (!Array.isArray(array) || !Array.isArray(size)) {\n throw new TypeError('Array expected');\n }\n\n if (size.length === 0) {\n throw new Error('Resizing to scalar is not supported');\n } // check whether size contains positive integers\n\n\n size.forEach(function (value) {\n if (!isNumber(value) || !isInteger(value) || value < 0) {\n throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + format(size) + ')');\n }\n }); // recursively resize the array\n\n var _defaultValue = defaultValue !== undefined ? defaultValue : 0;\n\n _resize(array, size, 0, _defaultValue);\n\n return array;\n}\n/**\n * Recursively resize a multi dimensional array\n * @param {Array} array Array to be resized\n * @param {number[]} size Array with the size of each dimension\n * @param {number} dim Current dimension\n * @param {*} [defaultValue] Value to be filled in in new entries,\n * undefined by default.\n * @private\n */\n\nfunction _resize(array, size, dim, defaultValue) {\n var i;\n var elem;\n var oldLen = array.length;\n var newLen = size[dim];\n var minLen = Math.min(oldLen, newLen); // apply new length\n\n array.length = newLen;\n\n if (dim < size.length - 1) {\n // non-last dimension\n var dimNext = dim + 1; // resize existing child arrays\n\n for (i = 0; i < minLen; i++) {\n // resize child array\n elem = array[i];\n\n if (!Array.isArray(elem)) {\n elem = [elem]; // add a dimension\n\n array[i] = elem;\n }\n\n _resize(elem, size, dimNext, defaultValue);\n } // create new child arrays\n\n\n for (i = minLen; i < newLen; i++) {\n // get child array\n elem = [];\n array[i] = elem; // resize new child array\n\n _resize(elem, size, dimNext, defaultValue);\n }\n } else {\n // last dimension\n // remove dimensions of existing values\n for (i = 0; i < minLen; i++) {\n while (Array.isArray(array[i])) {\n array[i] = array[i][0];\n }\n } // fill new elements with the default value\n\n\n for (i = minLen; i < newLen; i++) {\n array[i] = defaultValue;\n }\n }\n}\n/**\n * Re-shape a multi dimensional array to fit the specified dimensions\n * @param {Array} array Array to be reshaped\n * @param {Array.} sizes List of sizes for each dimension\n * @returns {Array} Array whose data has been formatted to fit the\n * specified dimensions\n *\n * @throws {DimensionError} If the product of the new dimension sizes does\n * not equal that of the old ones\n */\n\n\nexport function reshape(array, sizes) {\n var flatArray = flatten(array);\n var currentLength = flatArray.length;\n\n if (!Array.isArray(array) || !Array.isArray(sizes)) {\n throw new TypeError('Array expected');\n }\n\n if (sizes.length === 0) {\n throw new DimensionError(0, currentLength, '!=');\n }\n\n sizes = processSizesWildcard(sizes, currentLength);\n var newLength = product(sizes);\n\n if (currentLength !== newLength) {\n throw new DimensionError(newLength, currentLength, '!=');\n }\n\n try {\n return _reshape(flatArray, sizes);\n } catch (e) {\n if (e instanceof DimensionError) {\n throw new DimensionError(newLength, currentLength, '!=');\n }\n\n throw e;\n }\n}\n/**\n * Replaces the wildcard -1 in the sizes array.\n * @param {Array.} sizes List of sizes for each dimension. At most on wildcard.\n * @param {number} currentLength Number of elements in the array.\n * @throws {Error} If more than one wildcard or unable to replace it.\n * @returns {Array.} The sizes array with wildcard replaced.\n */\n\nexport function processSizesWildcard(sizes, currentLength) {\n var newLength = product(sizes);\n var processedSizes = sizes.slice();\n var WILDCARD = -1;\n var wildCardIndex = sizes.indexOf(WILDCARD);\n var isMoreThanOneWildcard = sizes.indexOf(WILDCARD, wildCardIndex + 1) >= 0;\n\n if (isMoreThanOneWildcard) {\n throw new Error('More than one wildcard in sizes');\n }\n\n var hasWildcard = wildCardIndex >= 0;\n var canReplaceWildcard = currentLength % newLength === 0;\n\n if (hasWildcard) {\n if (canReplaceWildcard) {\n processedSizes[wildCardIndex] = -currentLength / newLength;\n } else {\n throw new Error('Could not replace wildcard, since ' + currentLength + ' is no multiple of ' + -newLength);\n }\n }\n\n return processedSizes;\n}\n/**\n * Computes the product of all array elements.\n * @param {Array} array Array of factors\n * @returns {number} Product of all elements\n */\n\nfunction product(array) {\n return array.reduce((prev, curr) => prev * curr, 1);\n}\n/**\n * Iteratively re-shape a multi dimensional array to fit the specified dimensions\n * @param {Array} array Array to be reshaped\n * @param {Array.} sizes List of sizes for each dimension\n * @returns {Array} Array whose data has been formatted to fit the\n * specified dimensions\n */\n\n\nfunction _reshape(array, sizes) {\n // testing if there are enough elements for the requested shape\n var tmpArray = array;\n var tmpArray2; // for each dimensions starting by the last one and ignoring the first one\n\n for (var sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) {\n var size = sizes[sizeIndex];\n tmpArray2 = []; // aggregate the elements of the current tmpArray in elements of the requested size\n\n var length = tmpArray.length / size;\n\n for (var i = 0; i < length; i++) {\n tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size));\n } // set it as the new tmpArray for the next loop turn or for return\n\n\n tmpArray = tmpArray2;\n }\n\n return tmpArray;\n}\n/**\n * Squeeze a multi dimensional array\n * @param {Array} array\n * @param {Array} [size]\n * @returns {Array} returns the array itself\n */\n\n\nexport function squeeze(array, size) {\n var s = size || arraySize(array); // squeeze outer dimensions\n\n while (Array.isArray(array) && array.length === 1) {\n array = array[0];\n s.shift();\n } // find the first dimension to be squeezed\n\n\n var dims = s.length;\n\n while (s[dims - 1] === 1) {\n dims--;\n } // squeeze inner dimensions\n\n\n if (dims < s.length) {\n array = _squeeze(array, dims, 0);\n s.length = dims;\n }\n\n return array;\n}\n/**\n * Recursively squeeze a multi dimensional array\n * @param {Array} array\n * @param {number} dims Required number of dimensions\n * @param {number} dim Current dimension\n * @returns {Array | *} Returns the squeezed array\n * @private\n */\n\nfunction _squeeze(array, dims, dim) {\n var i, ii;\n\n if (dim < dims) {\n var next = dim + 1;\n\n for (i = 0, ii = array.length; i < ii; i++) {\n array[i] = _squeeze(array[i], dims, next);\n }\n } else {\n while (Array.isArray(array)) {\n array = array[0];\n }\n }\n\n return array;\n}\n/**\n * Unsqueeze a multi dimensional array: add dimensions when missing\n *\n * Paramter `size` will be mutated to match the new, unqueezed matrix size.\n *\n * @param {Array} array\n * @param {number} dims Desired number of dimensions of the array\n * @param {number} [outer] Number of outer dimensions to be added\n * @param {Array} [size] Current size of array.\n * @returns {Array} returns the array itself\n * @private\n */\n\n\nexport function unsqueeze(array, dims, outer, size) {\n var s = size || arraySize(array); // unsqueeze outer dimensions\n\n if (outer) {\n for (var i = 0; i < outer; i++) {\n array = [array];\n s.unshift(1);\n }\n } // unsqueeze inner dimensions\n\n\n array = _unsqueeze(array, dims, 0);\n\n while (s.length < dims) {\n s.push(1);\n }\n\n return array;\n}\n/**\n * Recursively unsqueeze a multi dimensional array\n * @param {Array} array\n * @param {number} dims Required number of dimensions\n * @param {number} dim Current dimension\n * @returns {Array | *} Returns the squeezed array\n * @private\n */\n\nfunction _unsqueeze(array, dims, dim) {\n var i, ii;\n\n if (Array.isArray(array)) {\n var next = dim + 1;\n\n for (i = 0, ii = array.length; i < ii; i++) {\n array[i] = _unsqueeze(array[i], dims, next);\n }\n } else {\n for (var d = dim; d < dims; d++) {\n array = [array];\n }\n }\n\n return array;\n}\n/**\n * Flatten a multi dimensional array, put all elements in a one dimensional\n * array\n * @param {Array} array A multi dimensional array\n * @return {Array} The flattened array (1 dimensional)\n */\n\n\nexport function flatten(array) {\n if (!Array.isArray(array)) {\n // if not an array, return as is\n return array;\n }\n\n var flat = [];\n array.forEach(function callback(value) {\n if (Array.isArray(value)) {\n value.forEach(callback); // traverse through sub-arrays recursively\n } else {\n flat.push(value);\n }\n });\n return flat;\n}\n/**\n * A safe map\n * @param {Array} array\n * @param {function} callback\n */\n\nexport function map(array, callback) {\n return Array.prototype.map.call(array, callback);\n}\n/**\n * A safe forEach\n * @param {Array} array\n * @param {function} callback\n */\n\nexport function forEach(array, callback) {\n Array.prototype.forEach.call(array, callback);\n}\n/**\n * A safe filter\n * @param {Array} array\n * @param {function} callback\n */\n\nexport function filter(array, callback) {\n if (arraySize(array).length !== 1) {\n throw new Error('Only one dimensional matrices supported');\n }\n\n return Array.prototype.filter.call(array, callback);\n}\n/**\n * Filter values in a callback given a regular expression\n * @param {Array} array\n * @param {RegExp} regexp\n * @return {Array} Returns the filtered array\n * @private\n */\n\nexport function filterRegExp(array, regexp) {\n if (arraySize(array).length !== 1) {\n throw new Error('Only one dimensional matrices supported');\n }\n\n return Array.prototype.filter.call(array, entry => regexp.test(entry));\n}\n/**\n * A safe join\n * @param {Array} array\n * @param {string} separator\n */\n\nexport function join(array, separator) {\n return Array.prototype.join.call(array, separator);\n}\n/**\n * Assign a numeric identifier to every element of a sorted array\n * @param {Array} a An array\n * @return {Array} An array of objects containing the original value and its identifier\n */\n\nexport function identify(a) {\n if (!Array.isArray(a)) {\n throw new TypeError('Array input expected');\n }\n\n if (a.length === 0) {\n return a;\n }\n\n var b = [];\n var count = 0;\n b[0] = {\n value: a[0],\n identifier: 0\n };\n\n for (var i = 1; i < a.length; i++) {\n if (a[i] === a[i - 1]) {\n count++;\n } else {\n count = 0;\n }\n\n b.push({\n value: a[i],\n identifier: count\n });\n }\n\n return b;\n}\n/**\n * Remove the numeric identifier from the elements\n * @param {array} a An array\n * @return {array} An array of values without identifiers\n */\n\nexport function generalize(a) {\n if (!Array.isArray(a)) {\n throw new TypeError('Array input expected');\n }\n\n if (a.length === 0) {\n return a;\n }\n\n var b = [];\n\n for (var i = 0; i < a.length; i++) {\n b.push(a[i].value);\n }\n\n return b;\n}\n/**\n * Check the datatype of a given object\n * This is a low level implementation that should only be used by\n * parent Matrix classes such as SparseMatrix or DenseMatrix\n * This method does not validate Array Matrix shape\n * @param {Array} array\n * @param {function} typeOf Callback function to use to determine the type of a value\n * @return string\n */\n\nexport function getArrayDataType(array, typeOf) {\n var type; // to hold type info\n\n var length = 0; // to hold length value to ensure it has consistent sizes\n\n for (var i = 0; i < array.length; i++) {\n var item = array[i];\n var isArray = Array.isArray(item); // Saving the target matrix row size\n\n if (i === 0 && isArray) {\n length = item.length;\n } // If the current item is an array but the length does not equal the targetVectorSize\n\n\n if (isArray && item.length !== length) {\n return undefined;\n }\n\n var itemType = isArray ? getArrayDataType(item, typeOf) // recurse into a nested array\n : typeOf(item);\n\n if (type === undefined) {\n type = itemType; // first item\n } else if (type !== itemType) {\n return 'mixed';\n } else {// we're good, everything has the same type so far\n }\n }\n\n return type;\n}\n/**\n * Return the last item from an array\n * @param array\n * @returns {*}\n */\n\nexport function last(array) {\n return array[array.length - 1];\n}\n/**\n * Get all but the last element of array.\n */\n\nexport function initial(array) {\n return array.slice(0, array.length - 1);\n}\n/**\n * Test whether an array or string contains an item\n * @param {Array | string} array\n * @param {*} item\n * @return {boolean}\n */\n\nexport function contains(array, item) {\n return array.indexOf(item) !== -1;\n}","import { contains } from './array.js';\nimport { pickShallow } from './object.js';\n/**\n * Create a factory function, which can be used to inject dependencies.\n *\n * The created functions are memoized, a consecutive call of the factory\n * with the exact same inputs will return the same function instance.\n * The memoized cache is exposed on `factory.cache` and can be cleared\n * if needed.\n *\n * Example:\n *\n * const name = 'log'\n * const dependencies = ['config', 'typed', 'divideScalar', 'Complex']\n *\n * export const createLog = factory(name, dependencies, ({ typed, config, divideScalar, Complex }) => {\n * // ... create the function log here and return it\n * }\n *\n * @param {string} name Name of the function to be created\n * @param {string[]} dependencies The names of all required dependencies\n * @param {function} create Callback function called with an object with all dependencies\n * @param {Object} [meta] Optional object with meta information that will be attached\n * to the created factory function as property `meta`.\n * @returns {function}\n */\n\nexport function factory(name, dependencies, create, meta) {\n function assertAndCreate(scope) {\n // we only pass the requested dependencies to the factory function\n // to prevent functions to rely on dependencies that are not explicitly\n // requested.\n var deps = pickShallow(scope, dependencies.map(stripOptionalNotation));\n assertDependencies(name, dependencies, scope);\n return create(deps);\n }\n\n assertAndCreate.isFactory = true;\n assertAndCreate.fn = name;\n assertAndCreate.dependencies = dependencies.slice().sort();\n\n if (meta) {\n assertAndCreate.meta = meta;\n }\n\n return assertAndCreate;\n}\n/**\n * Sort all factories such that when loading in order, the dependencies are resolved.\n *\n * @param {Array} factories\n * @returns {Array} Returns a new array with the sorted factories.\n */\n\nexport function sortFactories(factories) {\n var factoriesByName = {};\n factories.forEach(factory => {\n factoriesByName[factory.fn] = factory;\n });\n\n function containsDependency(factory, dependency) {\n // TODO: detect circular references\n if (isFactory(factory)) {\n if (contains(factory.dependencies, dependency.fn || dependency.name)) {\n return true;\n }\n\n if (factory.dependencies.some(d => containsDependency(factoriesByName[d], dependency))) {\n return true;\n }\n }\n\n return false;\n }\n\n var sorted = [];\n\n function addFactory(factory) {\n var index = 0;\n\n while (index < sorted.length && !containsDependency(sorted[index], factory)) {\n index++;\n }\n\n sorted.splice(index, 0, factory);\n } // sort regular factory functions\n\n\n factories.filter(isFactory).forEach(addFactory); // sort legacy factory functions AFTER the regular factory functions\n\n factories.filter(factory => !isFactory(factory)).forEach(addFactory);\n return sorted;\n} // TODO: comment or cleanup if unused in the end\n\nexport function create(factories) {\n var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n sortFactories(factories).forEach(factory => factory(scope));\n return scope;\n}\n/**\n * Test whether an object is a factory. This is the case when it has\n * properties name, dependencies, and a function create.\n * @param {*} obj\n * @returns {boolean}\n */\n\nexport function isFactory(obj) {\n return typeof obj === 'function' && typeof obj.fn === 'string' && Array.isArray(obj.dependencies);\n}\n/**\n * Assert that all dependencies of a list with dependencies are available in the provided scope.\n *\n * Will throw an exception when there are dependencies missing.\n *\n * @param {string} name Name for the function to be created. Used to generate a useful error message\n * @param {string[]} dependencies\n * @param {Object} scope\n */\n\nexport function assertDependencies(name, dependencies, scope) {\n var allDefined = dependencies.filter(dependency => !isOptionalDependency(dependency)) // filter optionals\n .every(dependency => scope[dependency] !== undefined);\n\n if (!allDefined) {\n var missingDependencies = dependencies.filter(dependency => scope[dependency] === undefined); // TODO: create a custom error class for this, a MathjsError or something like that\n\n throw new Error(\"Cannot create function \\\"\".concat(name, \"\\\", \") + \"some dependencies are missing: \".concat(missingDependencies.map(d => \"\\\"\".concat(d, \"\\\"\")).join(', '), \".\"));\n }\n}\nexport function isOptionalDependency(dependency) {\n return dependency && dependency[0] === '?';\n}\nexport function stripOptionalNotation(dependency) {\n return dependency && dependency[0] === '?' ? dependency.slice(1) : dependency;\n}","import { factory } from '../../utils/factory.js';\nvar name = 'ResultSet';\nvar dependencies = [];\nexport var createResultSet = /* #__PURE__ */factory(name, dependencies, () => {\n /**\n * A ResultSet contains a list or results\n * @class ResultSet\n * @param {Array} entries\n * @constructor ResultSet\n */\n function ResultSet(entries) {\n if (!(this instanceof ResultSet)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n }\n\n this.entries = entries || [];\n }\n /**\n * Attach type information\n */\n\n\n ResultSet.prototype.type = 'ResultSet';\n ResultSet.prototype.isResultSet = true;\n /**\n * Returns the array with results hold by this ResultSet\n * @memberof ResultSet\n * @returns {Array} entries\n */\n\n ResultSet.prototype.valueOf = function () {\n return this.entries;\n };\n /**\n * Returns the stringified results of the ResultSet\n * @memberof ResultSet\n * @returns {string} string\n */\n\n\n ResultSet.prototype.toString = function () {\n return '[' + this.entries.join(', ') + ']';\n };\n /**\n * Get a JSON representation of the ResultSet\n * @memberof ResultSet\n * @returns {Object} Returns a JSON object structured as:\n * `{\"mathjs\": \"ResultSet\", \"entries\": [...]}`\n */\n\n\n ResultSet.prototype.toJSON = function () {\n return {\n mathjs: 'ResultSet',\n entries: this.entries\n };\n };\n /**\n * Instantiate a ResultSet from a JSON object\n * @memberof ResultSet\n * @param {Object} json A JSON object structured as:\n * `{\"mathjs\": \"ResultSet\", \"entries\": [...]}`\n * @return {ResultSet}\n */\n\n\n ResultSet.fromJSON = function (json) {\n return new ResultSet(json.entries);\n };\n\n return ResultSet;\n}, {\n isClass: true\n});","import Complex from 'complex.js';\nimport { format } from '../../utils/number.js';\nimport { isNumber, isUnit } from '../../utils/is.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'Complex';\nvar dependencies = [];\nexport var createComplexClass = /* #__PURE__ */factory(name, dependencies, () => {\n /**\n * Attach type information\n */\n Complex.prototype.type = 'Complex';\n Complex.prototype.isComplex = true;\n /**\n * Get a JSON representation of the complex number\n * @returns {Object} Returns a JSON object structured as:\n * `{\"mathjs\": \"Complex\", \"re\": 2, \"im\": 3}`\n */\n\n Complex.prototype.toJSON = function () {\n return {\n mathjs: 'Complex',\n re: this.re,\n im: this.im\n };\n };\n /*\n * Return the value of the complex number in polar notation\n * The angle phi will be set in the interval of [-pi, pi].\n * @return {{r: number, phi: number}} Returns and object with properties r and phi.\n */\n\n\n Complex.prototype.toPolar = function () {\n return {\n r: this.abs(),\n phi: this.arg()\n };\n };\n /**\n * Get a string representation of the complex number,\n * with optional formatting options.\n * @param {Object | number | Function} [options] Formatting options. See\n * lib/utils/number:format for a\n * description of the available\n * options.\n * @return {string} str\n */\n\n\n Complex.prototype.format = function (options) {\n var str = '';\n var im = this.im;\n var re = this.re;\n var strRe = format(this.re, options);\n var strIm = format(this.im, options); // round either re or im when smaller than the configured precision\n\n var precision = isNumber(options) ? options : options ? options.precision : null;\n\n if (precision !== null) {\n var epsilon = Math.pow(10, -precision);\n\n if (Math.abs(re / im) < epsilon) {\n re = 0;\n }\n\n if (Math.abs(im / re) < epsilon) {\n im = 0;\n }\n }\n\n if (im === 0) {\n // real value\n str = strRe;\n } else if (re === 0) {\n // purely complex value\n if (im === 1) {\n str = 'i';\n } else if (im === -1) {\n str = '-i';\n } else {\n str = strIm + 'i';\n }\n } else {\n // complex value\n if (im < 0) {\n if (im === -1) {\n str = strRe + ' - i';\n } else {\n str = strRe + ' - ' + strIm.substring(1) + 'i';\n }\n } else {\n if (im === 1) {\n str = strRe + ' + i';\n } else {\n str = strRe + ' + ' + strIm + 'i';\n }\n }\n }\n\n return str;\n };\n /**\n * Create a complex number from polar coordinates\n *\n * Usage:\n *\n * Complex.fromPolar(r: number, phi: number) : Complex\n * Complex.fromPolar({r: number, phi: number}) : Complex\n *\n * @param {*} args...\n * @return {Complex}\n */\n\n\n Complex.fromPolar = function (args) {\n switch (arguments.length) {\n case 1:\n {\n var arg = arguments[0];\n\n if (typeof arg === 'object') {\n return Complex(arg);\n } else {\n throw new TypeError('Input has to be an object with r and phi keys.');\n }\n }\n\n case 2:\n {\n var r = arguments[0];\n var phi = arguments[1];\n\n if (isNumber(r)) {\n if (isUnit(phi) && phi.hasBase('ANGLE')) {\n // convert unit to a number in radians\n phi = phi.toNumber('rad');\n }\n\n if (isNumber(phi)) {\n return new Complex({\n r: r,\n phi: phi\n });\n }\n\n throw new TypeError('Phi is not a number nor an angle unit.');\n } else {\n throw new TypeError('Radius r is not a number.');\n }\n }\n\n default:\n throw new SyntaxError('Wrong number of arguments in function fromPolar');\n }\n };\n\n Complex.prototype.valueOf = Complex.prototype.toString;\n /**\n * Create a Complex number from a JSON object\n * @param {Object} json A JSON Object structured as\n * {\"mathjs\": \"Complex\", \"re\": 2, \"im\": 3}\n * All properties are optional, default values\n * for `re` and `im` are 0.\n * @return {Complex} Returns a new Complex number\n */\n\n Complex.fromJSON = function (json) {\n return new Complex(json);\n };\n /**\n * Compare two complex numbers, `a` and `b`:\n *\n * - Returns 1 when the real part of `a` is larger than the real part of `b`\n * - Returns -1 when the real part of `a` is smaller than the real part of `b`\n * - Returns 1 when the real parts are equal\n * and the imaginary part of `a` is larger than the imaginary part of `b`\n * - Returns -1 when the real parts are equal\n * and the imaginary part of `a` is smaller than the imaginary part of `b`\n * - Returns 0 when both real and imaginary parts are equal.\n *\n * @params {Complex} a\n * @params {Complex} b\n * @returns {number} Returns the comparison result: -1, 0, or 1\n */\n\n\n Complex.compare = function (a, b) {\n if (a.re > b.re) {\n return 1;\n }\n\n if (a.re < b.re) {\n return -1;\n }\n\n if (a.im > b.im) {\n return 1;\n }\n\n if (a.im < b.im) {\n return -1;\n }\n\n return 0;\n };\n\n return Complex;\n}, {\n isClass: true\n});","// (c) 2018, Mariusz Nowak\n// SPDX-License-Identifier: ISC\n// Derived from https://github.com/medikoo/lru-queue\nexport function lruQueue(limit) {\n var size = 0;\n var base = 1;\n var queue = Object.create(null);\n var map = Object.create(null);\n var index = 0;\n\n var del = function del(id) {\n var oldIndex = map[id];\n if (!oldIndex) return;\n delete queue[oldIndex];\n delete map[id];\n --size;\n if (base !== oldIndex) return;\n\n if (!size) {\n index = 0;\n base = 1;\n return;\n }\n\n while (!hasOwnProperty.call(queue, ++base)) {\n continue;\n }\n };\n\n limit = Math.abs(limit);\n return {\n hit: function hit(id) {\n var oldIndex = map[id];\n var nuIndex = ++index;\n queue[nuIndex] = id;\n map[id] = nuIndex;\n\n if (!oldIndex) {\n ++size;\n if (size <= limit) return undefined;\n id = queue[base];\n del(id);\n return id;\n }\n\n delete queue[oldIndex];\n if (base !== oldIndex) return undefined;\n\n while (!hasOwnProperty.call(queue, ++base)) {\n continue;\n }\n\n return undefined;\n },\n delete: del,\n clear: function clear() {\n size = index = 0;\n base = 1;\n queue = Object.create(null);\n map = Object.create(null);\n }\n };\n}\n;","// function utils\nimport { lruQueue } from './lruQueue.js';\n/**\n * Memoize a given function by caching the computed result.\n * The cache of a memoized function can be cleared by deleting the `cache`\n * property of the function.\n *\n * @param {function} fn The function to be memoized.\n * Must be a pure function.\n * @param {Object} [options]\n * @param {function(args: Array): string} [options.hasher]\n * A custom hash builder. Is JSON.stringify by default.\n * @param {number | undefined} [options.limit]\n * Maximum number of values that may be cached. Undefined indicates\n * unlimited (default)\n * @return {function} Returns the memoized function\n */\n\nexport function memoize(fn) {\n var {\n hasher,\n limit\n } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n limit = limit == null ? Number.POSITIVE_INFINITY : limit;\n hasher = hasher == null ? JSON.stringify : hasher;\n return function memoize() {\n if (typeof memoize.cache !== 'object') {\n memoize.cache = {\n values: new Map(),\n lru: lruQueue(limit || Number.POSITIVE_INFINITY)\n };\n }\n\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args[i] = arguments[i];\n }\n\n var hash = hasher(args);\n\n if (memoize.cache.values.has(hash)) {\n memoize.cache.lru.hit(hash);\n return memoize.cache.values.get(hash);\n }\n\n var newVal = fn.apply(fn, args);\n memoize.cache.values.set(hash, newVal);\n memoize.cache.values.delete(memoize.cache.lru.hit(hash));\n return newVal;\n };\n}\n/**\n * Memoize a given function by caching all results and the arguments,\n * and comparing against the arguments of previous results before\n * executing again.\n * This is less performant than `memoize` which calculates a hash,\n * which is very fast to compare. Use `memoizeCompare` only when it is\n * not possible to create a unique serializable hash from the function\n * arguments.\n * The isEqual function must compare two sets of arguments\n * and return true when equal (can be a deep equality check for example).\n * @param {function} fn\n * @param {function(a: *, b: *) : boolean} isEqual\n * @returns {function}\n */\n\nexport function memoizeCompare(fn, isEqual) {\n var memoize = function memoize() {\n var args = [];\n\n for (var i = 0; i < arguments.length; i++) {\n args[i] = arguments[i];\n }\n\n for (var c = 0; c < memoize.cache.length; c++) {\n var cached = memoize.cache[c];\n\n if (isEqual(args, cached.args)) {\n // TODO: move this cache entry to the top so recently used entries move up?\n return cached.res;\n }\n }\n\n var res = fn.apply(fn, args);\n memoize.cache.unshift({\n args,\n res\n });\n return res;\n };\n\n memoize.cache = [];\n return memoize;\n}\n/**\n * Find the maximum number of arguments expected by a typed function.\n * @param {function} fn A typed function\n * @return {number} Returns the maximum number of expected arguments.\n * Returns -1 when no signatures where found on the function.\n */\n\nexport function maxArgumentCount(fn) {\n return Object.keys(fn.signatures || {}).reduce(function (args, signature) {\n var count = (signature.match(/,/g) || []).length + 1;\n return Math.max(args, count);\n }, -1);\n}","import { memoize } from '../function.js';\n/**\n * Calculate BigNumber e\n * @param {function} BigNumber BigNumber constructor\n * @returns {BigNumber} Returns e\n */\n\nexport var createBigNumberE = memoize(function (BigNumber) {\n return new BigNumber(1).exp();\n}, {\n hasher\n});\n/**\n * Calculate BigNumber golden ratio, phi = (1+sqrt(5))/2\n * @param {function} BigNumber BigNumber constructor\n * @returns {BigNumber} Returns phi\n */\n\nexport var createBigNumberPhi = memoize(function (BigNumber) {\n return new BigNumber(1).plus(new BigNumber(5).sqrt()).div(2);\n}, {\n hasher\n});\n/**\n * Calculate BigNumber pi.\n * @param {function} BigNumber BigNumber constructor\n * @returns {BigNumber} Returns pi\n */\n\nexport var createBigNumberPi = memoize(function (BigNumber) {\n return BigNumber.acos(-1);\n}, {\n hasher\n});\n/**\n * Calculate BigNumber tau, tau = 2 * pi\n * @param {function} BigNumber BigNumber constructor\n * @returns {BigNumber} Returns tau\n */\n\nexport var createBigNumberTau = memoize(function (BigNumber) {\n return createBigNumberPi(BigNumber).times(2);\n}, {\n hasher\n});\n/**\n * Create a hash for a BigNumber constructor function. The created has is\n * the configured precision\n * @param {Array} args Supposed to contain a single entry with\n * a BigNumber constructor\n * @return {number} precision\n * @private\n */\n\nfunction hasher(args) {\n return args[0].precision;\n}","export var pi = Math.PI;\nexport var tau = 2 * Math.PI;\nexport var e = Math.E;\nexport var phi = 1.6180339887498948; // eslint-disable-line no-loss-of-precision","import Decimal from 'decimal.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'BigNumber';\nvar dependencies = ['?on', 'config'];\nexport var createBigNumberClass = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n on,\n config\n } = _ref;\n var EUCLID = 9; // Use euclidian division for mod calculation\n\n var BigNumber = Decimal.clone({\n precision: config.precision,\n modulo: EUCLID\n });\n /**\n * Attach type information\n */\n\n BigNumber.prototype.type = 'BigNumber';\n BigNumber.prototype.isBigNumber = true;\n /**\n * Get a JSON representation of a BigNumber containing\n * type information\n * @returns {Object} Returns a JSON object structured as:\n * `{\"mathjs\": \"BigNumber\", \"value\": \"0.2\"}`\n */\n\n BigNumber.prototype.toJSON = function () {\n return {\n mathjs: 'BigNumber',\n value: this.toString()\n };\n };\n /**\n * Instantiate a BigNumber from a JSON object\n * @param {Object} json a JSON object structured as:\n * `{\"mathjs\": \"BigNumber\", \"value\": \"0.2\"}`\n * @return {BigNumber}\n */\n\n\n BigNumber.fromJSON = function (json) {\n return new BigNumber(json.value);\n };\n\n if (on) {\n // listen for changed in the configuration, automatically apply changed precision\n on('config', function (curr, prev) {\n if (curr.precision !== prev.precision) {\n BigNumber.config({\n precision: curr.precision\n });\n }\n });\n }\n\n return BigNumber;\n}, {\n isClass: true\n});","import { factory } from '../../utils/factory.js';\nvar name = 'Matrix';\nvar dependencies = [];\nexport var createMatrixClass = /* #__PURE__ */factory(name, dependencies, () => {\n /**\n * @constructor Matrix\n *\n * A Matrix is a wrapper around an Array. A matrix can hold a multi dimensional\n * array. A matrix can be constructed as:\n *\n * let matrix = math.matrix(data)\n *\n * Matrix contains the functions to resize, get and set values, get the size,\n * clone the matrix and to convert the matrix to a vector, array, or scalar.\n * Furthermore, one can iterate over the matrix using map and forEach.\n * The internal Array of the Matrix can be accessed using the function valueOf.\n *\n * Example usage:\n *\n * let matrix = math.matrix([[1, 2], [3, 4]])\n * matix.size() // [2, 2]\n * matrix.resize([3, 2], 5)\n * matrix.valueOf() // [[1, 2], [3, 4], [5, 5]]\n * matrix.subset([1,2]) // 3 (indexes are zero-based)\n *\n */\n function Matrix() {\n if (!(this instanceof Matrix)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n }\n }\n /**\n * Attach type information\n */\n\n\n Matrix.prototype.type = 'Matrix';\n Matrix.prototype.isMatrix = true;\n /**\n * Get the storage format used by the matrix.\n *\n * Usage:\n * const format = matrix.storage() // retrieve storage format\n *\n * @return {string} The storage format.\n */\n\n Matrix.prototype.storage = function () {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke storage on a Matrix interface');\n };\n /**\n * Get the datatype of the data stored in the matrix.\n *\n * Usage:\n * const format = matrix.datatype() // retrieve matrix datatype\n *\n * @return {string} The datatype.\n */\n\n\n Matrix.prototype.datatype = function () {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke datatype on a Matrix interface');\n };\n /**\n * Create a new Matrix With the type of the current matrix instance\n * @param {Array | Object} data\n * @param {string} [datatype]\n */\n\n\n Matrix.prototype.create = function (data, datatype) {\n throw new Error('Cannot invoke create on a Matrix interface');\n };\n /**\n * Get a subset of the matrix, or replace a subset of the matrix.\n *\n * Usage:\n * const subset = matrix.subset(index) // retrieve subset\n * const value = matrix.subset(index, replacement) // replace subset\n *\n * @param {Index} index\n * @param {Array | Matrix | *} [replacement]\n * @param {*} [defaultValue=0] Default value, filled in on new entries when\n * the matrix is resized. If not provided,\n * new matrix elements will be filled with zeros.\n */\n\n\n Matrix.prototype.subset = function (index, replacement, defaultValue) {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke subset on a Matrix interface');\n };\n /**\n * Get a single element from the matrix.\n * @param {number[]} index Zero-based index\n * @return {*} value\n */\n\n\n Matrix.prototype.get = function (index) {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke get on a Matrix interface');\n };\n /**\n * Replace a single element in the matrix.\n * @param {number[]} index Zero-based index\n * @param {*} value\n * @param {*} [defaultValue] Default value, filled in on new entries when\n * the matrix is resized. If not provided,\n * new matrix elements will be left undefined.\n * @return {Matrix} self\n */\n\n\n Matrix.prototype.set = function (index, value, defaultValue) {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke set on a Matrix interface');\n };\n /**\n * Resize the matrix to the given size. Returns a copy of the matrix when\n * `copy=true`, otherwise return the matrix itself (resize in place).\n *\n * @param {number[]} size The new size the matrix should have.\n * @param {*} [defaultValue=0] Default value, filled in on new entries.\n * If not provided, the matrix elements will\n * be filled with zeros.\n * @param {boolean} [copy] Return a resized copy of the matrix\n *\n * @return {Matrix} The resized matrix\n */\n\n\n Matrix.prototype.resize = function (size, defaultValue) {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke resize on a Matrix interface');\n };\n /**\n * Reshape the matrix to the given size. Returns a copy of the matrix when\n * `copy=true`, otherwise return the matrix itself (reshape in place).\n *\n * @param {number[]} size The new size the matrix should have.\n * @param {boolean} [copy] Return a reshaped copy of the matrix\n *\n * @return {Matrix} The reshaped matrix\n */\n\n\n Matrix.prototype.reshape = function (size, defaultValue) {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke reshape on a Matrix interface');\n };\n /**\n * Create a clone of the matrix\n * @return {Matrix} clone\n */\n\n\n Matrix.prototype.clone = function () {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke clone on a Matrix interface');\n };\n /**\n * Retrieve the size of the matrix.\n * @returns {number[]} size\n */\n\n\n Matrix.prototype.size = function () {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke size on a Matrix interface');\n };\n /**\n * Create a new matrix with the results of the callback function executed on\n * each entry of the matrix.\n * @param {Function} callback The callback function is invoked with three\n * parameters: the value of the element, the index\n * of the element, and the Matrix being traversed.\n * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.\n *\n * @return {Matrix} matrix\n */\n\n\n Matrix.prototype.map = function (callback, skipZeros) {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke map on a Matrix interface');\n };\n /**\n * Execute a callback function on each entry of the matrix.\n * @param {Function} callback The callback function is invoked with three\n * parameters: the value of the element, the index\n * of the element, and the Matrix being traversed.\n */\n\n\n Matrix.prototype.forEach = function (callback) {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke forEach on a Matrix interface');\n };\n /**\n * Create an Array with a copy of the data of the Matrix\n * @returns {Array} array\n */\n\n\n Matrix.prototype.toArray = function () {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke toArray on a Matrix interface');\n };\n /**\n * Get the primitive value of the Matrix: a multidimensional array\n * @returns {Array} array\n */\n\n\n Matrix.prototype.valueOf = function () {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke valueOf on a Matrix interface');\n };\n /**\n * Get a string representation of the matrix, with optional formatting options.\n * @param {Object | number | Function} [options] Formatting options. See\n * lib/utils/number:format for a\n * description of the available\n * options.\n * @returns {string} str\n */\n\n\n Matrix.prototype.format = function (options) {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke format on a Matrix interface');\n };\n /**\n * Get a string representation of the matrix\n * @returns {string} str\n */\n\n\n Matrix.prototype.toString = function () {\n // must be implemented by each of the Matrix implementations\n throw new Error('Cannot invoke toString on a Matrix interface');\n };\n\n return Matrix;\n}, {\n isClass: true\n});","import { factory } from '../../utils/factory.js'; // Source: https://en.wikipedia.org/wiki/Physical_constant\n// Universal constants\n\nexport var createSpeedOfLight = /* #__PURE__ */unitFactory('speedOfLight', '299792458', 'm s^-1');\nexport var createGravitationConstant = /* #__PURE__ */unitFactory('gravitationConstant', '6.67430e-11', 'm^3 kg^-1 s^-2');\nexport var createPlanckConstant = /* #__PURE__ */unitFactory('planckConstant', '6.62607015e-34', 'J s');\nexport var createReducedPlanckConstant = /* #__PURE__ */unitFactory('reducedPlanckConstant', '1.0545718176461565e-34', 'J s'); // Electromagnetic constants\n\nexport var createMagneticConstant = /* #__PURE__ */unitFactory('magneticConstant', '1.25663706212e-6', 'N A^-2');\nexport var createElectricConstant = /* #__PURE__ */unitFactory('electricConstant', '8.8541878128e-12', 'F m^-1');\nexport var createVacuumImpedance = /* #__PURE__ */unitFactory('vacuumImpedance', '376.730313667', 'ohm');\nexport var createCoulomb = /* #__PURE__ */unitFactory('coulomb', '8.987551792261171e9', 'N m^2 C^-2');\nexport var createElementaryCharge = /* #__PURE__ */unitFactory('elementaryCharge', '1.602176634e-19', 'C');\nexport var createBohrMagneton = /* #__PURE__ */unitFactory('bohrMagneton', '9.2740100783e-24', 'J T^-1');\nexport var createConductanceQuantum = /* #__PURE__ */unitFactory('conductanceQuantum', '7.748091729863649e-5', 'S');\nexport var createInverseConductanceQuantum = /* #__PURE__ */unitFactory('inverseConductanceQuantum', '12906.403729652257', 'ohm');\nexport var createMagneticFluxQuantum = /* #__PURE__ */unitFactory('magneticFluxQuantum', '2.0678338484619295e-15', 'Wb');\nexport var createNuclearMagneton = /* #__PURE__ */unitFactory('nuclearMagneton', '5.0507837461e-27', 'J T^-1');\nexport var createKlitzing = /* #__PURE__ */unitFactory('klitzing', '25812.807459304513', 'ohm');\nexport var createJosephson = /* #__PURE__ */unitFactory('josephson', '4.835978484169836e14 Hz V', 'Hz V^-1'); // TODO: support for Hz needed\n// Atomic and nuclear constants\n\nexport var createBohrRadius = /* #__PURE__ */unitFactory('bohrRadius', '5.29177210903e-11', 'm');\nexport var createClassicalElectronRadius = /* #__PURE__ */unitFactory('classicalElectronRadius', '2.8179403262e-15', 'm');\nexport var createElectronMass = /* #__PURE__ */unitFactory('electronMass', '9.1093837015e-31', 'kg');\nexport var createFermiCoupling = /* #__PURE__ */unitFactory('fermiCoupling', '1.1663787e-5', 'GeV^-2');\nexport var createFineStructure = numberFactory('fineStructure', 7.2973525693e-3);\nexport var createHartreeEnergy = /* #__PURE__ */unitFactory('hartreeEnergy', '4.3597447222071e-18', 'J');\nexport var createProtonMass = /* #__PURE__ */unitFactory('protonMass', '1.67262192369e-27', 'kg');\nexport var createDeuteronMass = /* #__PURE__ */unitFactory('deuteronMass', '3.3435830926e-27', 'kg');\nexport var createNeutronMass = /* #__PURE__ */unitFactory('neutronMass', '1.6749271613e-27', 'kg');\nexport var createQuantumOfCirculation = /* #__PURE__ */unitFactory('quantumOfCirculation', '3.6369475516e-4', 'm^2 s^-1');\nexport var createRydberg = /* #__PURE__ */unitFactory('rydberg', '10973731.568160', 'm^-1');\nexport var createThomsonCrossSection = /* #__PURE__ */unitFactory('thomsonCrossSection', '6.6524587321e-29', 'm^2');\nexport var createWeakMixingAngle = numberFactory('weakMixingAngle', 0.22290);\nexport var createEfimovFactor = numberFactory('efimovFactor', 22.7); // Physico-chemical constants\n\nexport var createAtomicMass = /* #__PURE__ */unitFactory('atomicMass', '1.66053906660e-27', 'kg');\nexport var createAvogadro = /* #__PURE__ */unitFactory('avogadro', '6.02214076e23', 'mol^-1');\nexport var createBoltzmann = /* #__PURE__ */unitFactory('boltzmann', '1.380649e-23', 'J K^-1');\nexport var createFaraday = /* #__PURE__ */unitFactory('faraday', '96485.33212331001', 'C mol^-1');\nexport var createFirstRadiation = /* #__PURE__ */unitFactory('firstRadiation', '3.7417718521927573e-16', 'W m^2'); // export const createSpectralRadiance = /* #__PURE__ */ unitFactory('spectralRadiance', '1.1910429723971881e-16', 'W m^2 sr^-1') // TODO spectralRadiance\n\nexport var createLoschmidt = /* #__PURE__ */unitFactory('loschmidt', '2.686780111798444e25', 'm^-3');\nexport var createGasConstant = /* #__PURE__ */unitFactory('gasConstant', '8.31446261815324', 'J K^-1 mol^-1');\nexport var createMolarPlanckConstant = /* #__PURE__ */unitFactory('molarPlanckConstant', '3.990312712893431e-10', 'J s mol^-1');\nexport var createMolarVolume = /* #__PURE__ */unitFactory('molarVolume', '0.022413969545014137', 'm^3 mol^-1');\nexport var createSackurTetrode = numberFactory('sackurTetrode', -1.16487052358);\nexport var createSecondRadiation = /* #__PURE__ */unitFactory('secondRadiation', '0.014387768775039337', 'm K');\nexport var createStefanBoltzmann = /* #__PURE__ */unitFactory('stefanBoltzmann', '5.67037441918443e-8', 'W m^-2 K^-4');\nexport var createWienDisplacement = /* #__PURE__ */unitFactory('wienDisplacement', '2.897771955e-3', 'm K'); // Adopted values\n\nexport var createMolarMass = /* #__PURE__ */unitFactory('molarMass', '0.99999999965e-3', 'kg mol^-1');\nexport var createMolarMassC12 = /* #__PURE__ */unitFactory('molarMassC12', '11.9999999958e-3', 'kg mol^-1');\nexport var createGravity = /* #__PURE__ */unitFactory('gravity', '9.80665', 'm s^-2'); // atm is defined in Unit.js\n// Natural units\n\nexport var createPlanckLength = /* #__PURE__ */unitFactory('planckLength', '1.616255e-35', 'm');\nexport var createPlanckMass = /* #__PURE__ */unitFactory('planckMass', '2.176435e-8', 'kg');\nexport var createPlanckTime = /* #__PURE__ */unitFactory('planckTime', '5.391245e-44', 's');\nexport var createPlanckCharge = /* #__PURE__ */unitFactory('planckCharge', '1.87554603778e-18', 'C');\nexport var createPlanckTemperature = /* #__PURE__ */unitFactory('planckTemperature', '1.416785e+32', 'K'); // helper function to create a factory function which creates a physical constant,\n// a Unit with either a number value or a BigNumber value depending on the configuration\n\nfunction unitFactory(name, valueStr, unitStr) {\n var dependencies = ['config', 'Unit', 'BigNumber'];\n return factory(name, dependencies, (_ref) => {\n var {\n config,\n Unit,\n BigNumber\n } = _ref;\n // Note that we can parse into number or BigNumber.\n // We do not parse into Fractions as that doesn't make sense: we would lose precision of the values\n // Therefore we dont use Unit.parse()\n var value = config.number === 'BigNumber' ? new BigNumber(valueStr) : parseFloat(valueStr);\n var unit = new Unit(value, unitStr);\n unit.fixPrefix = true;\n return unit;\n });\n} // helper function to create a factory function which creates a numeric constant,\n// either a number or BigNumber depending on the configuration\n\n\nfunction numberFactory(name, value) {\n var dependencies = ['config', 'BigNumber'];\n return factory(name, dependencies, (_ref2) => {\n var {\n config,\n BigNumber\n } = _ref2;\n return config.number === 'BigNumber' ? new BigNumber(value) : value;\n });\n}","import Fraction from 'fraction.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'Fraction';\nvar dependencies = [];\nexport var createFractionClass = /* #__PURE__ */factory(name, dependencies, () => {\n /**\n * Attach type information\n */\n Fraction.prototype.type = 'Fraction';\n Fraction.prototype.isFraction = true;\n /**\n * Get a JSON representation of a Fraction containing type information\n * @returns {Object} Returns a JSON object structured as:\n * `{\"mathjs\": \"Fraction\", \"n\": 3, \"d\": 8}`\n */\n\n Fraction.prototype.toJSON = function () {\n return {\n mathjs: 'Fraction',\n n: this.s * this.n,\n d: this.d\n };\n };\n /**\n * Instantiate a Fraction from a JSON object\n * @param {Object} json a JSON object structured as:\n * `{\"mathjs\": \"Fraction\", \"n\": 3, \"d\": 8}`\n * @return {BigNumber}\n */\n\n\n Fraction.fromJSON = function (json) {\n return new Fraction(json);\n };\n\n return Fraction;\n}, {\n isClass: true\n});","import { isArray, isBigNumber, isCollection, isIndex, isMatrix, isNumber, isString, typeOf } from '../../utils/is.js';\nimport { arraySize, getArrayDataType, processSizesWildcard, reshape, resize, unsqueeze, validate, validateIndex } from '../../utils/array.js';\nimport { format } from '../../utils/string.js';\nimport { isInteger } from '../../utils/number.js';\nimport { clone, deepStrictEqual } from '../../utils/object.js';\nimport { DimensionError } from '../../error/DimensionError.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'DenseMatrix';\nvar dependencies = ['Matrix'];\nexport var createDenseMatrixClass = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n Matrix\n } = _ref;\n\n /**\n * Dense Matrix implementation. A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type.\n * @class DenseMatrix\n */\n function DenseMatrix(data, datatype) {\n if (!(this instanceof DenseMatrix)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n }\n\n if (datatype && !isString(datatype)) {\n throw new Error('Invalid datatype: ' + datatype);\n }\n\n if (isMatrix(data)) {\n // check data is a DenseMatrix\n if (data.type === 'DenseMatrix') {\n // clone data & size\n this._data = clone(data._data);\n this._size = clone(data._size);\n this._datatype = datatype || data._datatype;\n } else {\n // build data from existing matrix\n this._data = data.toArray();\n this._size = data.size();\n this._datatype = datatype || data._datatype;\n }\n } else if (data && isArray(data.data) && isArray(data.size)) {\n // initialize fields from JSON representation\n this._data = data.data;\n this._size = data.size; // verify the dimensions of the array\n\n validate(this._data, this._size);\n this._datatype = datatype || data.datatype;\n } else if (isArray(data)) {\n // replace nested Matrices with Arrays\n this._data = preprocess(data); // get the dimensions of the array\n\n this._size = arraySize(this._data); // verify the dimensions of the array, TODO: compute size while processing array\n\n validate(this._data, this._size); // data type unknown\n\n this._datatype = datatype;\n } else if (data) {\n // unsupported type\n throw new TypeError('Unsupported type of data (' + typeOf(data) + ')');\n } else {\n // nothing provided\n this._data = [];\n this._size = [0];\n this._datatype = datatype;\n }\n }\n\n DenseMatrix.prototype = new Matrix();\n /**\n * Create a new DenseMatrix\n */\n\n DenseMatrix.prototype.createDenseMatrix = function (data, datatype) {\n return new DenseMatrix(data, datatype);\n };\n /**\n * Attach type information\n */\n\n\n DenseMatrix.prototype.type = 'DenseMatrix';\n DenseMatrix.prototype.isDenseMatrix = true;\n /**\n * Get the matrix type\n *\n * Usage:\n * const matrixType = matrix.getDataType() // retrieves the matrix type\n *\n * @memberOf DenseMatrix\n * @return {string} type information; if multiple types are found from the Matrix, it will return \"mixed\"\n */\n\n DenseMatrix.prototype.getDataType = function () {\n return getArrayDataType(this._data, typeOf);\n };\n /**\n * Get the storage format used by the matrix.\n *\n * Usage:\n * const format = matrix.storage() // retrieve storage format\n *\n * @memberof DenseMatrix\n * @return {string} The storage format.\n */\n\n\n DenseMatrix.prototype.storage = function () {\n return 'dense';\n };\n /**\n * Get the datatype of the data stored in the matrix.\n *\n * Usage:\n * const format = matrix.datatype() // retrieve matrix datatype\n *\n * @memberof DenseMatrix\n * @return {string} The datatype.\n */\n\n\n DenseMatrix.prototype.datatype = function () {\n return this._datatype;\n };\n /**\n * Create a new DenseMatrix\n * @memberof DenseMatrix\n * @param {Array} data\n * @param {string} [datatype]\n */\n\n\n DenseMatrix.prototype.create = function (data, datatype) {\n return new DenseMatrix(data, datatype);\n };\n /**\n * Get a subset of the matrix, or replace a subset of the matrix.\n *\n * Usage:\n * const subset = matrix.subset(index) // retrieve subset\n * const value = matrix.subset(index, replacement) // replace subset\n *\n * @memberof DenseMatrix\n * @param {Index} index\n * @param {Array | Matrix | *} [replacement]\n * @param {*} [defaultValue=0] Default value, filled in on new entries when\n * the matrix is resized. If not provided,\n * new matrix elements will be filled with zeros.\n */\n\n\n DenseMatrix.prototype.subset = function (index, replacement, defaultValue) {\n switch (arguments.length) {\n case 1:\n return _get(this, index);\n // intentional fall through\n\n case 2:\n case 3:\n return _set(this, index, replacement, defaultValue);\n\n default:\n throw new SyntaxError('Wrong number of arguments');\n }\n };\n /**\n * Get a single element from the matrix.\n * @memberof DenseMatrix\n * @param {number[]} index Zero-based index\n * @return {*} value\n */\n\n\n DenseMatrix.prototype.get = function (index) {\n if (!isArray(index)) {\n throw new TypeError('Array expected');\n }\n\n if (index.length !== this._size.length) {\n throw new DimensionError(index.length, this._size.length);\n } // check index\n\n\n for (var x = 0; x < index.length; x++) {\n validateIndex(index[x], this._size[x]);\n }\n\n var data = this._data;\n\n for (var i = 0, ii = index.length; i < ii; i++) {\n var indexI = index[i];\n validateIndex(indexI, data.length);\n data = data[indexI];\n }\n\n return data;\n };\n /**\n * Replace a single element in the matrix.\n * @memberof DenseMatrix\n * @param {number[]} index Zero-based index\n * @param {*} value\n * @param {*} [defaultValue] Default value, filled in on new entries when\n * the matrix is resized. If not provided,\n * new matrix elements will be left undefined.\n * @return {DenseMatrix} self\n */\n\n\n DenseMatrix.prototype.set = function (index, value, defaultValue) {\n if (!isArray(index)) {\n throw new TypeError('Array expected');\n }\n\n if (index.length < this._size.length) {\n throw new DimensionError(index.length, this._size.length, '<');\n }\n\n var i, ii, indexI; // enlarge matrix when needed\n\n var size = index.map(function (i) {\n return i + 1;\n });\n\n _fit(this, size, defaultValue); // traverse over the dimensions\n\n\n var data = this._data;\n\n for (i = 0, ii = index.length - 1; i < ii; i++) {\n indexI = index[i];\n validateIndex(indexI, data.length);\n data = data[indexI];\n } // set new value\n\n\n indexI = index[index.length - 1];\n validateIndex(indexI, data.length);\n data[indexI] = value;\n return this;\n };\n /**\n * Get a submatrix of this matrix\n * @memberof DenseMatrix\n * @param {DenseMatrix} matrix\n * @param {Index} index Zero-based index\n * @private\n */\n\n\n function _get(matrix, index) {\n if (!isIndex(index)) {\n throw new TypeError('Invalid index');\n }\n\n var isScalar = index.isScalar();\n\n if (isScalar) {\n // return a scalar\n return matrix.get(index.min());\n } else {\n // validate dimensions\n var size = index.size();\n\n if (size.length !== matrix._size.length) {\n throw new DimensionError(size.length, matrix._size.length);\n } // validate if any of the ranges in the index is out of range\n\n\n var min = index.min();\n var max = index.max();\n\n for (var i = 0, ii = matrix._size.length; i < ii; i++) {\n validateIndex(min[i], matrix._size[i]);\n validateIndex(max[i], matrix._size[i]);\n } // retrieve submatrix\n // TODO: more efficient when creating an empty matrix and setting _data and _size manually\n\n\n return new DenseMatrix(_getSubmatrix(matrix._data, index, size.length, 0), matrix._datatype);\n }\n }\n /**\n * Recursively get a submatrix of a multi dimensional matrix.\n * Index is not checked for correct number or length of dimensions.\n * @memberof DenseMatrix\n * @param {Array} data\n * @param {Index} index\n * @param {number} dims Total number of dimensions\n * @param {number} dim Current dimension\n * @return {Array} submatrix\n * @private\n */\n\n\n function _getSubmatrix(data, index, dims, dim) {\n var last = dim === dims - 1;\n var range = index.dimension(dim);\n\n if (last) {\n return range.map(function (i) {\n validateIndex(i, data.length);\n return data[i];\n }).valueOf();\n } else {\n return range.map(function (i) {\n validateIndex(i, data.length);\n var child = data[i];\n return _getSubmatrix(child, index, dims, dim + 1);\n }).valueOf();\n }\n }\n /**\n * Replace a submatrix in this matrix\n * Indexes are zero-based.\n * @memberof DenseMatrix\n * @param {DenseMatrix} matrix\n * @param {Index} index\n * @param {DenseMatrix | Array | *} submatrix\n * @param {*} defaultValue Default value, filled in on new entries when\n * the matrix is resized.\n * @return {DenseMatrix} matrix\n * @private\n */\n\n\n function _set(matrix, index, submatrix, defaultValue) {\n if (!index || index.isIndex !== true) {\n throw new TypeError('Invalid index');\n } // get index size and check whether the index contains a single value\n\n\n var iSize = index.size();\n var isScalar = index.isScalar(); // calculate the size of the submatrix, and convert it into an Array if needed\n\n var sSize;\n\n if (isMatrix(submatrix)) {\n sSize = submatrix.size();\n submatrix = submatrix.valueOf();\n } else {\n sSize = arraySize(submatrix);\n }\n\n if (isScalar) {\n // set a scalar\n // check whether submatrix is a scalar\n if (sSize.length !== 0) {\n throw new TypeError('Scalar expected');\n }\n\n matrix.set(index.min(), submatrix, defaultValue);\n } else {\n // set a submatrix\n // validate dimensions\n if (iSize.length < matrix._size.length) {\n throw new DimensionError(iSize.length, matrix._size.length, '<');\n }\n\n if (sSize.length < iSize.length) {\n // calculate number of missing outer dimensions\n var i = 0;\n var outer = 0;\n\n while (iSize[i] === 1 && sSize[i] === 1) {\n i++;\n }\n\n while (iSize[i] === 1) {\n outer++;\n i++;\n } // unsqueeze both outer and inner dimensions\n\n\n submatrix = unsqueeze(submatrix, iSize.length, outer, sSize);\n } // check whether the size of the submatrix matches the index size\n\n\n if (!deepStrictEqual(iSize, sSize)) {\n throw new DimensionError(iSize, sSize, '>');\n } // enlarge matrix when needed\n\n\n var size = index.max().map(function (i) {\n return i + 1;\n });\n\n _fit(matrix, size, defaultValue); // insert the sub matrix\n\n\n var dims = iSize.length;\n var dim = 0;\n\n _setSubmatrix(matrix._data, index, submatrix, dims, dim);\n }\n\n return matrix;\n }\n /**\n * Replace a submatrix of a multi dimensional matrix.\n * @memberof DenseMatrix\n * @param {Array} data\n * @param {Index} index\n * @param {Array} submatrix\n * @param {number} dims Total number of dimensions\n * @param {number} dim\n * @private\n */\n\n\n function _setSubmatrix(data, index, submatrix, dims, dim) {\n var last = dim === dims - 1;\n var range = index.dimension(dim);\n\n if (last) {\n range.forEach(function (dataIndex, subIndex) {\n validateIndex(dataIndex);\n data[dataIndex] = submatrix[subIndex[0]];\n });\n } else {\n range.forEach(function (dataIndex, subIndex) {\n validateIndex(dataIndex);\n\n _setSubmatrix(data[dataIndex], index, submatrix[subIndex[0]], dims, dim + 1);\n });\n }\n }\n /**\n * Resize the matrix to the given size. Returns a copy of the matrix when\n * `copy=true`, otherwise return the matrix itself (resize in place).\n *\n * @memberof DenseMatrix\n * @param {number[] || Matrix} size The new size the matrix should have.\n * @param {*} [defaultValue=0] Default value, filled in on new entries.\n * If not provided, the matrix elements will\n * be filled with zeros.\n * @param {boolean} [copy] Return a resized copy of the matrix\n *\n * @return {Matrix} The resized matrix\n */\n\n\n DenseMatrix.prototype.resize = function (size, defaultValue, copy) {\n // validate arguments\n if (!isCollection(size)) {\n throw new TypeError('Array or Matrix expected');\n } // SparseMatrix input is always 2d, flatten this into 1d if it's indeed a vector\n\n\n var sizeArray = size.valueOf().map(value => {\n return Array.isArray(value) && value.length === 1 ? value[0] : value;\n }); // matrix to resize\n\n var m = copy ? this.clone() : this; // resize matrix\n\n return _resize(m, sizeArray, defaultValue);\n };\n\n function _resize(matrix, size, defaultValue) {\n // check size\n if (size.length === 0) {\n // first value in matrix\n var v = matrix._data; // go deep\n\n while (isArray(v)) {\n v = v[0];\n }\n\n return v;\n } // resize matrix\n\n\n matrix._size = size.slice(0); // copy the array\n\n matrix._data = resize(matrix._data, matrix._size, defaultValue); // return matrix\n\n return matrix;\n }\n /**\n * Reshape the matrix to the given size. Returns a copy of the matrix when\n * `copy=true`, otherwise return the matrix itself (reshape in place).\n *\n * NOTE: This might be better suited to copy by default, instead of modifying\n * in place. For now, it operates in place to remain consistent with\n * resize().\n *\n * @memberof DenseMatrix\n * @param {number[]} size The new size the matrix should have.\n * @param {boolean} [copy] Return a reshaped copy of the matrix\n *\n * @return {Matrix} The reshaped matrix\n */\n\n\n DenseMatrix.prototype.reshape = function (size, copy) {\n var m = copy ? this.clone() : this;\n m._data = reshape(m._data, size);\n\n var currentLength = m._size.reduce((length, size) => length * size);\n\n m._size = processSizesWildcard(size, currentLength);\n return m;\n };\n /**\n * Enlarge the matrix when it is smaller than given size.\n * If the matrix is larger or equal sized, nothing is done.\n * @memberof DenseMatrix\n * @param {DenseMatrix} matrix The matrix to be resized\n * @param {number[]} size\n * @param {*} defaultValue Default value, filled in on new entries.\n * @private\n */\n\n\n function _fit(matrix, size, defaultValue) {\n var // copy the array\n newSize = matrix._size.slice(0);\n\n var changed = false; // add dimensions when needed\n\n while (newSize.length < size.length) {\n newSize.push(0);\n changed = true;\n } // enlarge size when needed\n\n\n for (var i = 0, ii = size.length; i < ii; i++) {\n if (size[i] > newSize[i]) {\n newSize[i] = size[i];\n changed = true;\n }\n }\n\n if (changed) {\n // resize only when size is changed\n _resize(matrix, newSize, defaultValue);\n }\n }\n /**\n * Create a clone of the matrix\n * @memberof DenseMatrix\n * @return {DenseMatrix} clone\n */\n\n\n DenseMatrix.prototype.clone = function () {\n var m = new DenseMatrix({\n data: clone(this._data),\n size: clone(this._size),\n datatype: this._datatype\n });\n return m;\n };\n /**\n * Retrieve the size of the matrix.\n * @memberof DenseMatrix\n * @returns {number[]} size\n */\n\n\n DenseMatrix.prototype.size = function () {\n return this._size.slice(0); // return a clone of _size\n };\n /**\n * Create a new matrix with the results of the callback function executed on\n * each entry of the matrix.\n * @memberof DenseMatrix\n * @param {Function} callback The callback function is invoked with three\n * parameters: the value of the element, the index\n * of the element, and the Matrix being traversed.\n *\n * @return {DenseMatrix} matrix\n */\n\n\n DenseMatrix.prototype.map = function (callback) {\n // matrix instance\n var me = this;\n\n var recurse = function recurse(value, index) {\n if (isArray(value)) {\n return value.map(function (child, i) {\n return recurse(child, index.concat(i));\n });\n } else {\n return callback(value, index, me);\n }\n }; // determine the new datatype when the original matrix has datatype defined\n // TODO: should be done in matrix constructor instead\n\n\n var data = recurse(this._data, []);\n var datatype = this._datatype !== undefined ? getArrayDataType(data, typeOf) : undefined;\n return new DenseMatrix(data, datatype);\n };\n /**\n * Execute a callback function on each entry of the matrix.\n * @memberof DenseMatrix\n * @param {Function} callback The callback function is invoked with three\n * parameters: the value of the element, the index\n * of the element, and the Matrix being traversed.\n */\n\n\n DenseMatrix.prototype.forEach = function (callback) {\n // matrix instance\n var me = this;\n\n var recurse = function recurse(value, index) {\n if (isArray(value)) {\n value.forEach(function (child, i) {\n recurse(child, index.concat(i));\n });\n } else {\n callback(value, index, me);\n }\n };\n\n recurse(this._data, []);\n };\n /**\n * Create an Array with a copy of the data of the DenseMatrix\n * @memberof DenseMatrix\n * @returns {Array} array\n */\n\n\n DenseMatrix.prototype.toArray = function () {\n return clone(this._data);\n };\n /**\n * Get the primitive value of the DenseMatrix: a multidimensional array\n * @memberof DenseMatrix\n * @returns {Array} array\n */\n\n\n DenseMatrix.prototype.valueOf = function () {\n return this._data;\n };\n /**\n * Get a string representation of the matrix, with optional formatting options.\n * @memberof DenseMatrix\n * @param {Object | number | Function} [options] Formatting options. See\n * lib/utils/number:format for a\n * description of the available\n * options.\n * @returns {string} str\n */\n\n\n DenseMatrix.prototype.format = function (options) {\n return format(this._data, options);\n };\n /**\n * Get a string representation of the matrix\n * @memberof DenseMatrix\n * @returns {string} str\n */\n\n\n DenseMatrix.prototype.toString = function () {\n return format(this._data);\n };\n /**\n * Get a JSON representation of the matrix\n * @memberof DenseMatrix\n * @returns {Object}\n */\n\n\n DenseMatrix.prototype.toJSON = function () {\n return {\n mathjs: 'DenseMatrix',\n data: this._data,\n size: this._size,\n datatype: this._datatype\n };\n };\n /**\n * Get the kth Matrix diagonal.\n *\n * @memberof DenseMatrix\n * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved.\n *\n * @returns {Matrix} The matrix with the diagonal values.\n */\n\n\n DenseMatrix.prototype.diagonal = function (k) {\n // validate k if any\n if (k) {\n // convert BigNumber to a number\n if (isBigNumber(k)) {\n k = k.toNumber();\n } // is must be an integer\n\n\n if (!isNumber(k) || !isInteger(k)) {\n throw new TypeError('The parameter k must be an integer number');\n }\n } else {\n // default value\n k = 0;\n }\n\n var kSuper = k > 0 ? k : 0;\n var kSub = k < 0 ? -k : 0; // rows & columns\n\n var rows = this._size[0];\n var columns = this._size[1]; // number diagonal values\n\n var n = Math.min(rows - kSub, columns - kSuper); // x is a matrix get diagonal from matrix\n\n var data = []; // loop rows\n\n for (var i = 0; i < n; i++) {\n data[i] = this._data[i + kSub][i + kSuper];\n } // create DenseMatrix\n\n\n return new DenseMatrix({\n data: data,\n size: [n],\n datatype: this._datatype\n });\n };\n /**\n * Create a diagonal matrix.\n *\n * @memberof DenseMatrix\n * @param {Array} size The matrix size.\n * @param {number | Matrix | Array } value The values for the diagonal.\n * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in.\n * @param {number} [defaultValue] The default value for non-diagonal\n * @param {string} [datatype] The datatype for the diagonal\n *\n * @returns {DenseMatrix}\n */\n\n\n DenseMatrix.diagonal = function (size, value, k, defaultValue) {\n if (!isArray(size)) {\n throw new TypeError('Array expected, size parameter');\n }\n\n if (size.length !== 2) {\n throw new Error('Only two dimensions matrix are supported');\n } // map size & validate\n\n\n size = size.map(function (s) {\n // check it is a big number\n if (isBigNumber(s)) {\n // convert it\n s = s.toNumber();\n } // validate arguments\n\n\n if (!isNumber(s) || !isInteger(s) || s < 1) {\n throw new Error('Size values must be positive integers');\n }\n\n return s;\n }); // validate k if any\n\n if (k) {\n // convert BigNumber to a number\n if (isBigNumber(k)) {\n k = k.toNumber();\n } // is must be an integer\n\n\n if (!isNumber(k) || !isInteger(k)) {\n throw new TypeError('The parameter k must be an integer number');\n }\n } else {\n // default value\n k = 0;\n }\n\n var kSuper = k > 0 ? k : 0;\n var kSub = k < 0 ? -k : 0; // rows and columns\n\n var rows = size[0];\n var columns = size[1]; // number of non-zero items\n\n var n = Math.min(rows - kSub, columns - kSuper); // value extraction function\n\n var _value; // check value\n\n\n if (isArray(value)) {\n // validate array\n if (value.length !== n) {\n // number of values in array must be n\n throw new Error('Invalid value array length');\n } // define function\n\n\n _value = function _value(i) {\n // return value @ i\n return value[i];\n };\n } else if (isMatrix(value)) {\n // matrix size\n var ms = value.size(); // validate matrix\n\n if (ms.length !== 1 || ms[0] !== n) {\n // number of values in array must be n\n throw new Error('Invalid matrix length');\n } // define function\n\n\n _value = function _value(i) {\n // return value @ i\n return value.get([i]);\n };\n } else {\n // define function\n _value = function _value() {\n // return value\n return value;\n };\n } // discover default value if needed\n\n\n if (!defaultValue) {\n // check first value in array\n defaultValue = isBigNumber(_value(0)) ? _value(0).mul(0) // trick to create a BigNumber with value zero\n : 0;\n } // empty array\n\n\n var data = []; // check we need to resize array\n\n if (size.length > 0) {\n // resize array\n data = resize(data, size, defaultValue); // fill diagonal\n\n for (var d = 0; d < n; d++) {\n data[d + kSub][d + kSuper] = _value(d);\n }\n } // create DenseMatrix\n\n\n return new DenseMatrix({\n data: data,\n size: [rows, columns]\n });\n };\n /**\n * Generate a matrix from a JSON object\n * @memberof DenseMatrix\n * @param {Object} json An object structured like\n * `{\"mathjs\": \"DenseMatrix\", data: [], size: []}`,\n * where mathjs is optional\n * @returns {DenseMatrix}\n */\n\n\n DenseMatrix.fromJSON = function (json) {\n return new DenseMatrix(json);\n };\n /**\n * Swap rows i and j in Matrix.\n *\n * @memberof DenseMatrix\n * @param {number} i Matrix row index 1\n * @param {number} j Matrix row index 2\n *\n * @return {Matrix} The matrix reference\n */\n\n\n DenseMatrix.prototype.swapRows = function (i, j) {\n // check index\n if (!isNumber(i) || !isInteger(i) || !isNumber(j) || !isInteger(j)) {\n throw new Error('Row index must be positive integers');\n } // check dimensions\n\n\n if (this._size.length !== 2) {\n throw new Error('Only two dimensional matrix is supported');\n } // validate index\n\n\n validateIndex(i, this._size[0]);\n validateIndex(j, this._size[0]); // swap rows\n\n DenseMatrix._swapRows(i, j, this._data); // return current instance\n\n\n return this;\n };\n /**\n * Swap rows i and j in Dense Matrix data structure.\n *\n * @param {number} i Matrix row index 1\n * @param {number} j Matrix row index 2\n * @param {Array} data Matrix data\n */\n\n\n DenseMatrix._swapRows = function (i, j, data) {\n // swap values i <-> j\n var vi = data[i];\n data[i] = data[j];\n data[j] = vi;\n };\n /**\n * Preprocess data, which can be an Array or DenseMatrix with nested Arrays and\n * Matrices. Replaces all nested Matrices with Arrays\n * @memberof DenseMatrix\n * @param {Array} data\n * @return {Array} data\n */\n\n\n function preprocess(data) {\n for (var i = 0, ii = data.length; i < ii; i++) {\n var elem = data[i];\n\n if (isArray(elem)) {\n data[i] = preprocess(elem);\n } else if (elem && elem.isMatrix === true) {\n data[i] = preprocess(elem.valueOf());\n }\n }\n\n return data;\n }\n\n return DenseMatrix;\n}, {\n isClass: true\n});","/**\n * Create a typed-function which checks the types of the arguments and\n * can match them against multiple provided signatures. The typed-function\n * automatically converts inputs in order to find a matching signature.\n * Typed functions throw informative errors in case of wrong input arguments.\n *\n * See the library [typed-function](https://github.com/josdejong/typed-function)\n * for detailed documentation.\n *\n * Syntax:\n *\n * math.typed(name, signatures) : function\n * math.typed(signatures) : function\n *\n * Examples:\n *\n * // create a typed function with multiple types per argument (type union)\n * const fn2 = typed({\n * 'number | boolean': function (b) {\n * return 'b is a number or boolean'\n * },\n * 'string, number | boolean': function (a, b) {\n * return 'a is a string, b is a number or boolean'\n * }\n * })\n *\n * // create a typed function with an any type argument\n * const log = typed({\n * 'string, any': function (event, data) {\n * console.log('event: ' + event + ', data: ' + JSON.stringify(data))\n * }\n * })\n *\n * @param {string} [name] Optional name for the typed-function\n * @param {Object} signatures Object with one or multiple function signatures\n * @returns {function} The created typed-function.\n */\nimport { isAccessorNode, isArray, isArrayNode, isAssignmentNode, isBigNumber, isBlockNode, isBoolean, isChain, isComplex, isConditionalNode, isConstantNode, isDate, isDenseMatrix, isFraction, isFunction, isFunctionAssignmentNode, isFunctionNode, isHelp, isIndex, isIndexNode, isMatrix, isNode, isNull, isNumber, isObject, isObjectNode, isOperatorNode, isParenthesisNode, isRange, isRangeNode, isRegExp, isResultSet, isSparseMatrix, isString, isSymbolNode, isUndefined, isUnit } from '../../utils/is.js';\nimport typedFunction from 'typed-function';\nimport { digits } from '../../utils/number.js';\nimport { factory } from '../../utils/factory.js'; // returns a new instance of typed-function\n\nvar _createTyped2 = function _createTyped() {\n // initially, return the original instance of typed-function\n // consecutively, return a new instance from typed.create.\n _createTyped2 = typedFunction.create;\n return typedFunction;\n};\n\nvar dependencies = ['?BigNumber', '?Complex', '?DenseMatrix', '?Fraction'];\n/**\n * Factory function for creating a new typed instance\n * @param {Object} dependencies Object with data types like Complex and BigNumber\n * @returns {Function}\n */\n\nexport var createTyped = /* #__PURE__ */factory('typed', dependencies, function createTyped(_ref) {\n var {\n BigNumber,\n Complex,\n DenseMatrix,\n Fraction\n } = _ref;\n\n // TODO: typed-function must be able to silently ignore signatures with unknown data types\n // get a new instance of typed-function\n var typed = _createTyped2(); // define all types. The order of the types determines in which order function\n // arguments are type-checked (so for performance it's important to put the\n // most used types first).\n\n\n typed.types = [{\n name: 'number',\n test: isNumber\n }, {\n name: 'Complex',\n test: isComplex\n }, {\n name: 'BigNumber',\n test: isBigNumber\n }, {\n name: 'Fraction',\n test: isFraction\n }, {\n name: 'Unit',\n test: isUnit\n }, {\n name: 'string',\n test: isString\n }, {\n name: 'Chain',\n test: isChain\n }, {\n name: 'Array',\n test: isArray\n }, {\n name: 'Matrix',\n test: isMatrix\n }, {\n name: 'DenseMatrix',\n test: isDenseMatrix\n }, {\n name: 'SparseMatrix',\n test: isSparseMatrix\n }, {\n name: 'Range',\n test: isRange\n }, {\n name: 'Index',\n test: isIndex\n }, {\n name: 'boolean',\n test: isBoolean\n }, {\n name: 'ResultSet',\n test: isResultSet\n }, {\n name: 'Help',\n test: isHelp\n }, {\n name: 'function',\n test: isFunction\n }, {\n name: 'Date',\n test: isDate\n }, {\n name: 'RegExp',\n test: isRegExp\n }, {\n name: 'null',\n test: isNull\n }, {\n name: 'undefined',\n test: isUndefined\n }, {\n name: 'AccessorNode',\n test: isAccessorNode\n }, {\n name: 'ArrayNode',\n test: isArrayNode\n }, {\n name: 'AssignmentNode',\n test: isAssignmentNode\n }, {\n name: 'BlockNode',\n test: isBlockNode\n }, {\n name: 'ConditionalNode',\n test: isConditionalNode\n }, {\n name: 'ConstantNode',\n test: isConstantNode\n }, {\n name: 'FunctionNode',\n test: isFunctionNode\n }, {\n name: 'FunctionAssignmentNode',\n test: isFunctionAssignmentNode\n }, {\n name: 'IndexNode',\n test: isIndexNode\n }, {\n name: 'Node',\n test: isNode\n }, {\n name: 'ObjectNode',\n test: isObjectNode\n }, {\n name: 'OperatorNode',\n test: isOperatorNode\n }, {\n name: 'ParenthesisNode',\n test: isParenthesisNode\n }, {\n name: 'RangeNode',\n test: isRangeNode\n }, {\n name: 'SymbolNode',\n test: isSymbolNode\n }, {\n name: 'Object',\n test: isObject\n } // order 'Object' last, it matches on other classes too\n ];\n typed.conversions = [{\n from: 'number',\n to: 'BigNumber',\n convert: function convert(x) {\n if (!BigNumber) {\n throwNoBignumber(x);\n } // note: conversion from number to BigNumber can fail if x has >15 digits\n\n\n if (digits(x) > 15) {\n throw new TypeError('Cannot implicitly convert a number with >15 significant digits to BigNumber ' + '(value: ' + x + '). ' + 'Use function bignumber(x) to convert to BigNumber.');\n }\n\n return new BigNumber(x);\n }\n }, {\n from: 'number',\n to: 'Complex',\n convert: function convert(x) {\n if (!Complex) {\n throwNoComplex(x);\n }\n\n return new Complex(x, 0);\n }\n }, {\n from: 'number',\n to: 'string',\n convert: function convert(x) {\n return x + '';\n }\n }, {\n from: 'BigNumber',\n to: 'Complex',\n convert: function convert(x) {\n if (!Complex) {\n throwNoComplex(x);\n }\n\n return new Complex(x.toNumber(), 0);\n }\n }, {\n from: 'Fraction',\n to: 'BigNumber',\n convert: function convert(x) {\n throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' + 'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');\n }\n }, {\n from: 'Fraction',\n to: 'Complex',\n convert: function convert(x) {\n if (!Complex) {\n throwNoComplex(x);\n }\n\n return new Complex(x.valueOf(), 0);\n }\n }, {\n from: 'number',\n to: 'Fraction',\n convert: function convert(x) {\n if (!Fraction) {\n throwNoFraction(x);\n }\n\n var f = new Fraction(x);\n\n if (f.valueOf() !== x) {\n throw new TypeError('Cannot implicitly convert a number to a Fraction when there will be a loss of precision ' + '(value: ' + x + '). ' + 'Use function fraction(x) to convert to Fraction.');\n }\n\n return f;\n }\n }, {\n // FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))`\n // from: 'Fraction',\n // to: 'number',\n // convert: function (x) {\n // return x.valueOf()\n // }\n // }, {\n from: 'string',\n to: 'number',\n convert: function convert(x) {\n var n = Number(x);\n\n if (isNaN(n)) {\n throw new Error('Cannot convert \"' + x + '\" to a number');\n }\n\n return n;\n }\n }, {\n from: 'string',\n to: 'BigNumber',\n convert: function convert(x) {\n if (!BigNumber) {\n throwNoBignumber(x);\n }\n\n try {\n return new BigNumber(x);\n } catch (err) {\n throw new Error('Cannot convert \"' + x + '\" to BigNumber');\n }\n }\n }, {\n from: 'string',\n to: 'Fraction',\n convert: function convert(x) {\n if (!Fraction) {\n throwNoFraction(x);\n }\n\n try {\n return new Fraction(x);\n } catch (err) {\n throw new Error('Cannot convert \"' + x + '\" to Fraction');\n }\n }\n }, {\n from: 'string',\n to: 'Complex',\n convert: function convert(x) {\n if (!Complex) {\n throwNoComplex(x);\n }\n\n try {\n return new Complex(x);\n } catch (err) {\n throw new Error('Cannot convert \"' + x + '\" to Complex');\n }\n }\n }, {\n from: 'boolean',\n to: 'number',\n convert: function convert(x) {\n return +x;\n }\n }, {\n from: 'boolean',\n to: 'BigNumber',\n convert: function convert(x) {\n if (!BigNumber) {\n throwNoBignumber(x);\n }\n\n return new BigNumber(+x);\n }\n }, {\n from: 'boolean',\n to: 'Fraction',\n convert: function convert(x) {\n if (!Fraction) {\n throwNoFraction(x);\n }\n\n return new Fraction(+x);\n }\n }, {\n from: 'boolean',\n to: 'string',\n convert: function convert(x) {\n return String(x);\n }\n }, {\n from: 'Array',\n to: 'Matrix',\n convert: function convert(array) {\n if (!DenseMatrix) {\n throwNoMatrix();\n }\n\n return new DenseMatrix(array);\n }\n }, {\n from: 'Matrix',\n to: 'Array',\n convert: function convert(matrix) {\n return matrix.valueOf();\n }\n }];\n return typed;\n});\n\nfunction throwNoBignumber(x) {\n throw new Error(\"Cannot convert value \".concat(x, \" into a BigNumber: no class 'BigNumber' provided\"));\n}\n\nfunction throwNoComplex(x) {\n throw new Error(\"Cannot convert value \".concat(x, \" into a Complex number: no class 'Complex' provided\"));\n}\n\nfunction throwNoMatrix() {\n throw new Error('Cannot convert array into a Matrix: no class \\'DenseMatrix\\' provided');\n}\n\nfunction throwNoFraction(x) {\n throw new Error(\"Cannot convert value \".concat(x, \" into a Fraction, no class 'Fraction' provided.\"));\n}","import { isCollection, isMatrix } from './is.js';\nimport { IndexError } from '../error/IndexError.js';\nimport { arraySize } from './array.js';\n/**\n * Test whether an array contains collections\n * @param {Array} array\n * @returns {boolean} Returns true when the array contains one or multiple\n * collections (Arrays or Matrices). Returns false otherwise.\n */\n\nexport function containsCollections(array) {\n for (var i = 0; i < array.length; i++) {\n if (isCollection(array[i])) {\n return true;\n }\n }\n\n return false;\n}\n/**\n * Recursively loop over all elements in a given multi dimensional array\n * and invoke the callback on each of the elements.\n * @param {Array | Matrix} array\n * @param {Function} callback The callback method is invoked with one\n * parameter: the current element in the array\n */\n\nexport function deepForEach(array, callback) {\n if (isMatrix(array)) {\n array = array.valueOf();\n }\n\n for (var i = 0, ii = array.length; i < ii; i++) {\n var value = array[i];\n\n if (Array.isArray(value)) {\n deepForEach(value, callback);\n } else {\n callback(value);\n }\n }\n}\n/**\n * Execute the callback function element wise for each element in array and any\n * nested array\n * Returns an array with the results\n * @param {Array | Matrix} array\n * @param {Function} callback The callback is called with two parameters:\n * value1 and value2, which contain the current\n * element of both arrays.\n * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.\n *\n * @return {Array | Matrix} res\n */\n\nexport function deepMap(array, callback, skipZeros) {\n if (array && typeof array.map === 'function') {\n // TODO: replace array.map with a for loop to improve performance\n return array.map(function (x) {\n return deepMap(x, callback, skipZeros);\n });\n } else {\n return callback(array);\n }\n}\n/**\n * Reduce a given matrix or array to a new matrix or\n * array with one less dimension, applying the given\n * callback in the selected dimension.\n * @param {Array | Matrix} mat\n * @param {number} dim\n * @param {Function} callback\n * @return {Array | Matrix} res\n */\n\nexport function reduce(mat, dim, callback) {\n var size = Array.isArray(mat) ? arraySize(mat) : mat.size();\n\n if (dim < 0 || dim >= size.length) {\n // TODO: would be more clear when throwing a DimensionError here\n throw new IndexError(dim, size.length);\n }\n\n if (isMatrix(mat)) {\n return mat.create(_reduce(mat.valueOf(), dim, callback));\n } else {\n return _reduce(mat, dim, callback);\n }\n}\n/**\n * Recursively reduce a matrix\n * @param {Array} mat\n * @param {number} dim\n * @param {Function} callback\n * @returns {Array} ret\n * @private\n */\n\nfunction _reduce(mat, dim, callback) {\n var i, ret, val, tran;\n\n if (dim <= 0) {\n if (!Array.isArray(mat[0])) {\n val = mat[0];\n\n for (i = 1; i < mat.length; i++) {\n val = callback(val, mat[i]);\n }\n\n return val;\n } else {\n tran = _switch(mat);\n ret = [];\n\n for (i = 0; i < tran.length; i++) {\n ret[i] = _reduce(tran[i], dim - 1, callback);\n }\n\n return ret;\n }\n } else {\n ret = [];\n\n for (i = 0; i < mat.length; i++) {\n ret[i] = _reduce(mat[i], dim - 1, callback);\n }\n\n return ret;\n }\n}\n/**\n * Transpose a matrix\n * @param {Array} mat\n * @returns {Array} ret\n * @private\n */\n\n\nfunction _switch(mat) {\n var I = mat.length;\n var J = mat[0].length;\n var i, j;\n var ret = [];\n\n for (j = 0; j < J; j++) {\n var tmp = [];\n\n for (i = 0; i < I; i++) {\n tmp.push(mat[i][j]);\n }\n\n ret.push(tmp);\n }\n\n return ret;\n} // TODO: document function scatter\n\n\nexport function scatter(a, j, w, x, u, mark, cindex, f, inverse, update, value) {\n // a arrays\n var avalues = a._values;\n var aindex = a._index;\n var aptr = a._ptr; // vars\n\n var k, k0, k1, i; // check we need to process values (pattern matrix)\n\n if (x) {\n // values in j\n for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {\n // row\n i = aindex[k]; // check value exists in current j\n\n if (w[i] !== mark) {\n // i is new entry in j\n w[i] = mark; // add i to pattern of C\n\n cindex.push(i); // x(i) = A, check we need to call function this time\n\n if (update) {\n // copy value to workspace calling callback function\n x[i] = inverse ? f(avalues[k], value) : f(value, avalues[k]); // function was called on current row\n\n u[i] = mark;\n } else {\n // copy value to workspace\n x[i] = avalues[k];\n }\n } else {\n // i exists in C already\n x[i] = inverse ? f(avalues[k], x[i]) : f(x[i], avalues[k]); // function was called on current row\n\n u[i] = mark;\n }\n }\n } else {\n // values in j\n for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {\n // row\n i = aindex[k]; // check value exists in current j\n\n if (w[i] !== mark) {\n // i is new entry in j\n w[i] = mark; // add i to pattern of C\n\n cindex.push(i);\n } else {\n // indicate function was called on current row\n u[i] = mark;\n }\n }\n }\n}","import { deepMap } from '../../utils/collection.js';\nimport { isInteger as isIntegerNumber } from '../../utils/number.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'isInteger';\nvar dependencies = ['typed'];\nexport var createIsInteger = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Test whether a value is an integer number.\n * The function supports `number`, `BigNumber`, and `Fraction`.\n *\n * The function is evaluated element-wise in case of Array or Matrix input.\n *\n * Syntax:\n *\n * math.isInteger(x)\n *\n * Examples:\n *\n * math.isInteger(2) // returns true\n * math.isInteger(0) // returns true\n * math.isInteger(0.5) // returns false\n * math.isInteger(math.bignumber(500)) // returns true\n * math.isInteger(math.fraction(4)) // returns true\n * math.isInteger('3') // returns true\n * math.isInteger([3, 0.5, -2]) // returns [true, false, true]\n * math.isInteger(math.complex('2-4i') // throws an error\n *\n * See also:\n *\n * isNumeric, isPositive, isNegative, isZero\n *\n * @param {number | BigNumber | Fraction | Array | Matrix} x Value to be tested\n * @return {boolean} Returns true when `x` contains a numeric, integer value.\n * Throws an error in case of an unknown data type.\n */\n return typed(name, {\n number: isIntegerNumber,\n // TODO: what to do with isInteger(add(0.1, 0.2)) ?\n BigNumber: function BigNumber(x) {\n return x.isInt();\n },\n Fraction: function Fraction(x) {\n return x.d === 1 && isFinite(x.n);\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n return deepMap(x, this);\n }\n });\n});","import { deepMap } from '../../utils/collection.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'isNumeric';\nvar dependencies = ['typed'];\nexport var createIsNumeric = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Test whether a value is an numeric value.\n *\n * The function is evaluated element-wise in case of Array or Matrix input.\n *\n * Syntax:\n *\n * math.isNumeric(x)\n *\n * Examples:\n *\n * math.isNumeric(2) // returns true\n * math.isNumeric('2') // returns false\n * math.hasNumericValue('2') // returns true\n * math.isNumeric(0) // returns true\n * math.isNumeric(math.bignumber(500)) // returns true\n * math.isNumeric(math.fraction(4)) // returns true\n * math.isNumeric(math.complex('2-4i') // returns false\n * math.isNumeric([2.3, 'foo', false]) // returns [true, false, true]\n *\n * See also:\n *\n * isZero, isPositive, isNegative, isInteger, hasNumericValue\n *\n * @param {*} x Value to be tested\n * @return {boolean} Returns true when `x` is a `number`, `BigNumber`,\n * `Fraction`, or `boolean`. Returns false for other types.\n * Throws an error in case of unknown types.\n */\n return typed(name, {\n 'number | BigNumber | Fraction | boolean': function numberBigNumberFractionBoolean() {\n return true;\n },\n 'Complex | Unit | string | null | undefined | Node': function ComplexUnitStringNullUndefinedNode() {\n return false;\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n return deepMap(x, this);\n }\n });\n});","import { isInteger } from '../../utils/number.js';\nvar n1 = 'number';\nexport function isIntegerNumber(x) {\n return isInteger(x);\n}\nisIntegerNumber.signature = n1;\nexport function isNegativeNumber(x) {\n return x < 0;\n}\nisNegativeNumber.signature = n1;\nexport function isPositiveNumber(x) {\n return x > 0;\n}\nisPositiveNumber.signature = n1;\nexport function isZeroNumber(x) {\n return x === 0;\n}\nisZeroNumber.signature = n1;\nexport function isNaNNumber(x) {\n return Number.isNaN(x);\n}\nisNaNNumber.signature = n1;","/**\n * Compares two BigNumbers.\n * @param {BigNumber} x First value to compare\n * @param {BigNumber} y Second value to compare\n * @param {number} [epsilon] The maximum relative difference between x and y\n * If epsilon is undefined or null, the function will\n * test whether x and y are exactly equal.\n * @return {boolean} whether the two numbers are nearly equal\n */\nexport function nearlyEqual(x, y, epsilon) {\n // if epsilon is null or undefined, test whether x and y are exactly equal\n if (epsilon === null || epsilon === undefined) {\n return x.eq(y);\n } // use \"==\" operator, handles infinities\n\n\n if (x.eq(y)) {\n return true;\n } // NaN\n\n\n if (x.isNaN() || y.isNaN()) {\n return false;\n } // at this point x and y should be finite\n\n\n if (x.isFinite() && y.isFinite()) {\n // check numbers are very close, needed when comparing numbers near zero\n var diff = x.minus(y).abs();\n\n if (diff.isZero()) {\n return true;\n } else {\n // use relative error\n var max = x.constructor.max(x.abs(), y.abs());\n return diff.lte(max.times(epsilon));\n }\n } // Infinite and Number or negative Infinite and positive Infinite cases\n\n\n return false;\n}","import { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js';\nimport { nearlyEqual } from '../../utils/number.js';\nimport { factory } from '../../utils/factory.js';\nimport { complexEquals } from '../../utils/complex.js';\nvar name = 'equalScalar';\nvar dependencies = ['typed', 'config'];\nexport var createEqualScalar = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config\n } = _ref;\n\n /**\n * Test whether two scalar values are nearly equal.\n *\n * @param {number | BigNumber | Fraction | boolean | Complex | Unit} x First value to compare\n * @param {number | BigNumber | Fraction | boolean | Complex} y Second value to compare\n * @return {boolean} Returns true when the compared values are equal, else returns false\n * @private\n */\n return typed(name, {\n 'boolean, boolean': function booleanBoolean(x, y) {\n return x === y;\n },\n 'number, number': function numberNumber(x, y) {\n return nearlyEqual(x, y, config.epsilon);\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {\n return x.eq(y) || bigNearlyEqual(x, y, config.epsilon);\n },\n 'Fraction, Fraction': function FractionFraction(x, y) {\n return x.equals(y);\n },\n 'Complex, Complex': function ComplexComplex(x, y) {\n return complexEquals(x, y, config.epsilon);\n },\n 'Unit, Unit': function UnitUnit(x, y) {\n if (!x.equalBase(y)) {\n throw new Error('Cannot compare units with different base');\n }\n\n return this(x.value, y.value);\n }\n });\n});\nexport var createEqualScalarNumber = factory(name, ['typed', 'config'], (_ref2) => {\n var {\n typed,\n config\n } = _ref2;\n return typed(name, {\n 'number, number': function numberNumber(x, y) {\n return nearlyEqual(x, y, config.epsilon);\n }\n });\n});","import { nearlyEqual } from './number.js';\n/**\n * Test whether two complex values are equal provided a given epsilon.\n * Does not use or change the global Complex.EPSILON setting\n * @param {Complex} x\n * @param {Complex} y\n * @param {number} epsilon\n * @returns {boolean}\n */\n\nexport function complexEquals(x, y, epsilon) {\n return nearlyEqual(x.re, y.re, epsilon) && nearlyEqual(x.im, y.im, epsilon);\n}","import { factory } from '../utils/factory.js';\nimport { deepMap } from '../utils/collection.js';\nvar name = 'number';\nvar dependencies = ['typed'];\nexport var createNumber = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Create a number or convert a string, boolean, or unit to a number.\n * When value is a matrix, all elements will be converted to number.\n *\n * Syntax:\n *\n * math.number(value)\n * math.number(unit, valuelessUnit)\n *\n * Examples:\n *\n * math.number(2) // returns number 2\n * math.number('7.2') // returns number 7.2\n * math.number(true) // returns number 1\n * math.number([true, false, true, true]) // returns [1, 0, 1, 1]\n * math.number(math.unit('52cm'), 'm') // returns 0.52\n *\n * See also:\n *\n * bignumber, boolean, complex, index, matrix, string, unit\n *\n * @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted\n * @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number\n * @return {number | Array | Matrix} The created number\n */\n var number = typed('number', {\n '': function _() {\n return 0;\n },\n number: function number(x) {\n return x;\n },\n string: function string(x) {\n if (x === 'NaN') return NaN;\n var size = 0;\n var boxMatch = x.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);\n\n if (boxMatch) {\n // x includes a size suffix like 0xffffi32, so we extract\n // the suffix and remove it from x\n size = Number(boxMatch[2]);\n x = boxMatch[1];\n }\n\n var num = Number(x);\n\n if (isNaN(num)) {\n throw new SyntaxError('String \"' + x + '\" is no valid number');\n }\n\n if (boxMatch) {\n // x is a signed bin, oct, or hex literal\n // num is the value of string x if x is interpreted as unsigned\n if (num > 2 ** size - 1) {\n // literal is too large for size suffix\n throw new SyntaxError(\"String \\\"\".concat(x, \"\\\" is out of range\"));\n } // check if the bit at index size - 1 is set and if so do the twos complement\n\n\n if (num >= 2 ** (size - 1)) {\n num = num - 2 ** size;\n }\n }\n\n return num;\n },\n BigNumber: function BigNumber(x) {\n return x.toNumber();\n },\n Fraction: function Fraction(x) {\n return x.valueOf();\n },\n Unit: function Unit(x) {\n throw new Error('Second argument with valueless unit expected');\n },\n null: function _null(x) {\n return 0;\n },\n 'Unit, string | Unit': function UnitStringUnit(unit, valuelessUnit) {\n return unit.toNumber(valuelessUnit);\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n return deepMap(x, this);\n }\n }); // reviver function to parse a JSON object like:\n //\n // {\"mathjs\":\"number\",\"value\":\"2.3\"}\n //\n // into a number 2.3\n\n number.fromJSON = function (json) {\n return parseFloat(json.value);\n };\n\n return number;\n});","import { isInteger, log2, log10, cbrt, expm1, sign, toFixed, log1p } from '../../utils/number.js';\nvar n1 = 'number';\nvar n2 = 'number, number';\nexport function absNumber(a) {\n return Math.abs(a);\n}\nabsNumber.signature = n1;\nexport function addNumber(a, b) {\n return a + b;\n}\naddNumber.signature = n2;\nexport function subtractNumber(a, b) {\n return a - b;\n}\nsubtractNumber.signature = n2;\nexport function multiplyNumber(a, b) {\n return a * b;\n}\nmultiplyNumber.signature = n2;\nexport function divideNumber(a, b) {\n return a / b;\n}\ndivideNumber.signature = n2;\nexport function unaryMinusNumber(x) {\n return -x;\n}\nunaryMinusNumber.signature = n1;\nexport function unaryPlusNumber(x) {\n return x;\n}\nunaryPlusNumber.signature = n1;\nexport function cbrtNumber(x) {\n return cbrt(x);\n}\ncbrtNumber.signature = n1;\nexport function ceilNumber(x) {\n return Math.ceil(x);\n}\nceilNumber.signature = n1;\nexport function cubeNumber(x) {\n return x * x * x;\n}\ncubeNumber.signature = n1;\nexport function expNumber(x) {\n return Math.exp(x);\n}\nexpNumber.signature = n1;\nexport function expm1Number(x) {\n return expm1(x);\n}\nexpm1Number.signature = n1;\nexport function fixNumber(x) {\n return x > 0 ? Math.floor(x) : Math.ceil(x);\n}\nfixNumber.signature = n1;\nexport function floorNumber(x) {\n return Math.floor(x);\n}\nfloorNumber.signature = n1;\n/**\n * Calculate gcd for numbers\n * @param {number} a\n * @param {number} b\n * @returns {number} Returns the greatest common denominator of a and b\n */\n\nexport function gcdNumber(a, b) {\n if (!isInteger(a) || !isInteger(b)) {\n throw new Error('Parameters in function gcd must be integer numbers');\n } // https://en.wikipedia.org/wiki/Euclidean_algorithm\n\n\n var r;\n\n while (b !== 0) {\n r = a % b;\n a = b;\n b = r;\n }\n\n return a < 0 ? -a : a;\n}\ngcdNumber.signature = n2;\n/**\n * Calculate lcm for two numbers\n * @param {number} a\n * @param {number} b\n * @returns {number} Returns the least common multiple of a and b\n */\n\nexport function lcmNumber(a, b) {\n if (!isInteger(a) || !isInteger(b)) {\n throw new Error('Parameters in function lcm must be integer numbers');\n }\n\n if (a === 0 || b === 0) {\n return 0;\n } // https://en.wikipedia.org/wiki/Euclidean_algorithm\n // evaluate lcm here inline to reduce overhead\n\n\n var t;\n var prod = a * b;\n\n while (b !== 0) {\n t = b;\n b = a % t;\n a = t;\n }\n\n return Math.abs(prod / a);\n}\nlcmNumber.signature = n2;\n/**\n * Calculate the logarithm of a value.\n * @param {number} x\n * @return {number}\n */\n\nexport function logNumber(x) {\n return Math.log(x);\n}\nlogNumber.signature = n1;\n/**\n * Calculate the 10-base logarithm of a number\n * @param {number} x\n * @return {number}\n */\n\nexport function log10Number(x) {\n return log10(x);\n}\nlog10Number.signature = n1;\n/**\n * Calculate the 2-base logarithm of a number\n * @param {number} x\n * @return {number}\n */\n\nexport function log2Number(x) {\n return log2(x);\n}\nlog2Number.signature = n1;\n/**\n * Calculate the natural logarithm of a `number+1`\n * @param {number} x\n * @returns {number}\n */\n\nexport function log1pNumber(x) {\n return log1p(x);\n}\nlog1pNumber.signature = n1;\n/**\n * Calculate the modulus of two numbers\n * @param {number} x\n * @param {number} y\n * @returns {number} res\n * @private\n */\n\nexport function modNumber(x, y) {\n if (y > 0) {\n // We don't use JavaScript's % operator here as this doesn't work\n // correctly for x < 0 and x === 0\n // see https://en.wikipedia.org/wiki/Modulo_operation\n return x - y * Math.floor(x / y);\n } else if (y === 0) {\n return x;\n } else {\n // y < 0\n // TODO: implement mod for a negative divisor\n throw new Error('Cannot calculate mod for a negative divisor');\n }\n}\nmodNumber.signature = n2;\n/**\n * Calculate the nth root of a, solve x^root == a\n * http://rosettacode.org/wiki/Nth_root#JavaScript\n * @param {number} a\n * @param {number} root\n * @private\n */\n\nexport function nthRootNumber(a, root) {\n var inv = root < 0;\n\n if (inv) {\n root = -root;\n }\n\n if (root === 0) {\n throw new Error('Root must be non-zero');\n }\n\n if (a < 0 && Math.abs(root) % 2 !== 1) {\n throw new Error('Root must be odd when a is negative.');\n } // edge cases zero and infinity\n\n\n if (a === 0) {\n return inv ? Infinity : 0;\n }\n\n if (!isFinite(a)) {\n return inv ? 0 : a;\n }\n\n var x = Math.pow(Math.abs(a), 1 / root); // If a < 0, we require that root is an odd integer,\n // so (-1) ^ (1/root) = -1\n\n x = a < 0 ? -x : x;\n return inv ? 1 / x : x; // Very nice algorithm, but fails with nthRoot(-2, 3).\n // Newton's method has some well-known problems at times:\n // https://en.wikipedia.org/wiki/Newton%27s_method#Failure_analysis\n\n /*\n let x = 1 // Initial guess\n let xPrev = 1\n let i = 0\n const iMax = 10000\n do {\n const delta = (a / Math.pow(x, root - 1) - x) / root\n xPrev = x\n x = x + delta\n i++\n }\n while (xPrev !== x && i < iMax)\n if (xPrev !== x) {\n throw new Error('Function nthRoot failed to converge')\n }\n return inv ? 1 / x : x\n */\n}\nnthRootNumber.signature = n2;\nexport function signNumber(x) {\n return sign(x);\n}\nsignNumber.signature = n1;\nexport function sqrtNumber(x) {\n return Math.sqrt(x);\n}\nsqrtNumber.signature = n1;\nexport function squareNumber(x) {\n return x * x;\n}\nsquareNumber.signature = n1;\n/**\n * Calculate xgcd for two numbers\n * @param {number} a\n * @param {number} b\n * @return {number} result\n * @private\n */\n\nexport function xgcdNumber(a, b) {\n // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm\n var t; // used to swap two variables\n\n var q; // quotient\n\n var r; // remainder\n\n var x = 0;\n var lastx = 1;\n var y = 1;\n var lasty = 0;\n\n if (!isInteger(a) || !isInteger(b)) {\n throw new Error('Parameters in function xgcd must be integer numbers');\n }\n\n while (b) {\n q = Math.floor(a / b);\n r = a - q * b;\n t = x;\n x = lastx - q * x;\n lastx = t;\n t = y;\n y = lasty - q * y;\n lasty = t;\n a = b;\n b = r;\n }\n\n var res;\n\n if (a < 0) {\n res = [-a, -lastx, -lasty];\n } else {\n res = [a, a ? lastx : 0, lasty];\n }\n\n return res;\n}\nxgcdNumber.signature = n2;\n/**\n * Calculates the power of x to y, x^y, for two numbers.\n * @param {number} x\n * @param {number} y\n * @return {number} res\n */\n\nexport function powNumber(x, y) {\n // x^Infinity === 0 if -1 < x < 1\n // A real number 0 is returned instead of complex(0)\n if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) {\n return 0;\n }\n\n return Math.pow(x, y);\n}\npowNumber.signature = n2;\n/**\n * round a number to the given number of decimals, or to zero if decimals is\n * not provided\n * @param {number} value\n * @param {number} decimals number of decimals, between 0 and 15 (0 by default)\n * @return {number} roundedValue\n */\n\nexport function roundNumber(value) {\n var decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n return parseFloat(toFixed(value, decimals));\n}\nroundNumber.signature = n2;\n/**\n * Calculate the norm of a number, the absolute value.\n * @param {number} x\n * @return {number}\n */\n\nexport function normNumber(x) {\n return Math.abs(x);\n}\nnormNumber.signature = n1;","import { factory } from '../../utils/factory.js';\nimport { deepMap } from '../../utils/collection.js';\nimport { cubeNumber } from '../../plain/number/index.js';\nvar name = 'cube';\nvar dependencies = ['typed'];\nexport var createCube = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Compute the cube of a value, `x * x * x`.\n * For matrices, the function is evaluated element wise.\n *\n * Syntax:\n *\n * math.cube(x)\n *\n * Examples:\n *\n * math.cube(2) // returns number 8\n * math.pow(2, 3) // returns number 8\n * math.cube(4) // returns number 64\n * 4 * 4 * 4 // returns number 64\n *\n * math.cube([1, 2, 3, 4]) // returns Array [1, 8, 27, 64]\n *\n * See also:\n *\n * multiply, square, pow, cbrt\n *\n * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x Number for which to calculate the cube\n * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} Cube of x\n */\n return typed(name, {\n number: cubeNumber,\n Complex: function Complex(x) {\n return x.mul(x).mul(x); // Is faster than pow(x, 3)\n },\n BigNumber: function BigNumber(x) {\n return x.times(x).times(x);\n },\n Fraction: function Fraction(x) {\n return x.pow(3); // Is faster than mul()mul()mul()\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n // deep map collection, skip zeros since cube(0) = 0\n return deepMap(x, this, true);\n },\n Unit: function Unit(x) {\n return x.pow(3);\n }\n });\n});","import { factory } from '../../utils/factory.js';\nimport { multiplyNumber } from '../../plain/number/index.js';\nvar name = 'multiplyScalar';\nvar dependencies = ['typed'];\nexport var createMultiplyScalar = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Multiply two scalar values, `x * y`.\n * This function is meant for internal use: it is used by the public function\n * `multiply`\n *\n * This function does not support collections (Array or Matrix).\n *\n * @param {number | BigNumber | Fraction | Complex | Unit} x First value to multiply\n * @param {number | BigNumber | Fraction | Complex} y Second value to multiply\n * @return {number | BigNumber | Fraction | Complex | Unit} Multiplication of `x` and `y`\n * @private\n */\n return typed('multiplyScalar', {\n 'number, number': multiplyNumber,\n 'Complex, Complex': function ComplexComplex(x, y) {\n return x.mul(y);\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {\n return x.times(y);\n },\n 'Fraction, Fraction': function FractionFraction(x, y) {\n return x.mul(y);\n },\n 'number | Fraction | BigNumber | Complex, Unit': function numberFractionBigNumberComplexUnit(x, y) {\n var res = y.clone();\n res.value = res.value === null ? res._normalize(x) : this(res.value, x);\n return res;\n },\n 'Unit, number | Fraction | BigNumber | Complex': function UnitNumberFractionBigNumberComplex(x, y) {\n var res = x.clone();\n res.value = res.value === null ? res._normalize(y) : this(res.value, y);\n return res;\n },\n 'Unit, Unit': function UnitUnit(x, y) {\n return x.multiply(y);\n }\n });\n});","import { isInteger } from '../../utils/number.js';\nvar n1 = 'number';\nvar n2 = 'number, number';\nexport function bitAndNumber(x, y) {\n if (!isInteger(x) || !isInteger(y)) {\n throw new Error('Integers expected in function bitAnd');\n }\n\n return x & y;\n}\nbitAndNumber.signature = n2;\nexport function bitNotNumber(x) {\n if (!isInteger(x)) {\n throw new Error('Integer expected in function bitNot');\n }\n\n return ~x;\n}\nbitNotNumber.signature = n1;\nexport function bitOrNumber(x, y) {\n if (!isInteger(x) || !isInteger(y)) {\n throw new Error('Integers expected in function bitOr');\n }\n\n return x | y;\n}\nbitOrNumber.signature = n2;\nexport function bitXorNumber(x, y) {\n if (!isInteger(x) || !isInteger(y)) {\n throw new Error('Integers expected in function bitXor');\n }\n\n return x ^ y;\n}\nbitXorNumber.signature = n2;\nexport function leftShiftNumber(x, y) {\n if (!isInteger(x) || !isInteger(y)) {\n throw new Error('Integers expected in function leftShift');\n }\n\n return x << y;\n}\nleftShiftNumber.signature = n2;\nexport function rightArithShiftNumber(x, y) {\n if (!isInteger(x) || !isInteger(y)) {\n throw new Error('Integers expected in function rightArithShift');\n }\n\n return x >> y;\n}\nrightArithShiftNumber.signature = n2;\nexport function rightLogShiftNumber(x, y) {\n if (!isInteger(x) || !isInteger(y)) {\n throw new Error('Integers expected in function rightLogShift');\n }\n\n return x >>> y;\n}\nrightLogShiftNumber.signature = n2;","var n1 = 'number';\nvar n2 = 'number, number';\nexport function notNumber(x) {\n return !x;\n}\nnotNumber.signature = n1;\nexport function orNumber(x, y) {\n return !!(x || y);\n}\norNumber.signature = n2;\nexport function xorNumber(x, y) {\n return !!x !== !!y;\n}\nxorNumber.signature = n2;\nexport function andNumber(x, y) {\n return !!(x && y);\n}\nandNumber.signature = n2;","/* eslint-disable no-loss-of-precision */\nimport { deepMap } from '../../utils/collection.js';\nimport { sign } from '../../utils/number.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'erf';\nvar dependencies = ['typed'];\nexport var createErf = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Compute the erf function of a value using a rational Chebyshev\n * approximations for different intervals of x.\n *\n * This is a translation of W. J. Cody's Fortran implementation from 1987\n * ( https://www.netlib.org/specfun/erf ). See the AMS publication\n * \"Rational Chebyshev Approximations for the Error Function\" by W. J. Cody\n * for an explanation of this process.\n *\n * For matrices, the function is evaluated element wise.\n *\n * Syntax:\n *\n * math.erf(x)\n *\n * Examples:\n *\n * math.erf(0.2) // returns 0.22270258921047847\n * math.erf(-0.5) // returns -0.5204998778130465\n * math.erf(4) // returns 0.9999999845827421\n *\n * @param {number | Array | Matrix} x A real number\n * @return {number | Array | Matrix} The erf of `x`\n */\n return typed('name', {\n number: function number(x) {\n var y = Math.abs(x);\n\n if (y >= MAX_NUM) {\n return sign(x);\n }\n\n if (y <= THRESH) {\n return sign(x) * erf1(y);\n }\n\n if (y <= 4.0) {\n return sign(x) * (1 - erfc2(y));\n }\n\n return sign(x) * (1 - erfc3(y));\n },\n 'Array | Matrix': function ArrayMatrix(n) {\n return deepMap(n, this);\n } // TODO: For complex numbers, use the approximation for the Faddeeva function\n // from \"More Efficient Computation of the Complex Error Function\" (AMS)\n\n });\n /**\n * Approximates the error function erf() for x <= 0.46875 using this function:\n * n\n * erf(x) = x * sum (p_j * x^(2j)) / (q_j * x^(2j))\n * j=0\n */\n\n function erf1(y) {\n var ysq = y * y;\n var xnum = P[0][4] * ysq;\n var xden = ysq;\n var i;\n\n for (i = 0; i < 3; i += 1) {\n xnum = (xnum + P[0][i]) * ysq;\n xden = (xden + Q[0][i]) * ysq;\n }\n\n return y * (xnum + P[0][3]) / (xden + Q[0][3]);\n }\n /**\n * Approximates the complement of the error function erfc() for\n * 0.46875 <= x <= 4.0 using this function:\n * n\n * erfc(x) = e^(-x^2) * sum (p_j * x^j) / (q_j * x^j)\n * j=0\n */\n\n\n function erfc2(y) {\n var xnum = P[1][8] * y;\n var xden = y;\n var i;\n\n for (i = 0; i < 7; i += 1) {\n xnum = (xnum + P[1][i]) * y;\n xden = (xden + Q[1][i]) * y;\n }\n\n var result = (xnum + P[1][7]) / (xden + Q[1][7]);\n var ysq = parseInt(y * 16) / 16;\n var del = (y - ysq) * (y + ysq);\n return Math.exp(-ysq * ysq) * Math.exp(-del) * result;\n }\n /**\n * Approximates the complement of the error function erfc() for x > 4.0 using\n * this function:\n *\n * erfc(x) = (e^(-x^2) / x) * [ 1/sqrt(pi) +\n * n\n * 1/(x^2) * sum (p_j * x^(-2j)) / (q_j * x^(-2j)) ]\n * j=0\n */\n\n\n function erfc3(y) {\n var ysq = 1 / (y * y);\n var xnum = P[2][5] * ysq;\n var xden = ysq;\n var i;\n\n for (i = 0; i < 4; i += 1) {\n xnum = (xnum + P[2][i]) * ysq;\n xden = (xden + Q[2][i]) * ysq;\n }\n\n var result = ysq * (xnum + P[2][4]) / (xden + Q[2][4]);\n result = (SQRPI - result) / y;\n ysq = parseInt(y * 16) / 16;\n var del = (y - ysq) * (y + ysq);\n return Math.exp(-ysq * ysq) * Math.exp(-del) * result;\n }\n});\n/**\n * Upper bound for the first approximation interval, 0 <= x <= THRESH\n * @constant\n */\n\nvar THRESH = 0.46875;\n/**\n * Constant used by W. J. Cody's Fortran77 implementation to denote sqrt(pi)\n * @constant\n */\n\nvar SQRPI = 5.6418958354775628695e-1;\n/**\n * Coefficients for each term of the numerator sum (p_j) for each approximation\n * interval (see W. J. Cody's paper for more details)\n * @constant\n */\n\nvar P = [[3.16112374387056560e00, 1.13864154151050156e02, 3.77485237685302021e02, 3.20937758913846947e03, 1.85777706184603153e-1], [5.64188496988670089e-1, 8.88314979438837594e00, 6.61191906371416295e01, 2.98635138197400131e02, 8.81952221241769090e02, 1.71204761263407058e03, 2.05107837782607147e03, 1.23033935479799725e03, 2.15311535474403846e-8], [3.05326634961232344e-1, 3.60344899949804439e-1, 1.25781726111229246e-1, 1.60837851487422766e-2, 6.58749161529837803e-4, 1.63153871373020978e-2]];\n/**\n * Coefficients for each term of the denominator sum (q_j) for each approximation\n * interval (see W. J. Cody's paper for more details)\n * @constant\n */\n\nvar Q = [[2.36012909523441209e01, 2.44024637934444173e02, 1.28261652607737228e03, 2.84423683343917062e03], [1.57449261107098347e01, 1.17693950891312499e02, 5.37181101862009858e02, 1.62138957456669019e03, 3.29079923573345963e03, 4.36261909014324716e03, 3.43936767414372164e03, 1.23033935480374942e03], [2.56852019228982242e00, 1.87295284992346047e00, 5.27905102951428412e-1, 6.05183413124413191e-2, 2.33520497626869185e-3]];\n/**\n * Maximum/minimum safe numbers to input to erf() (in ES6+, this number is\n * Number.[MAX|MIN]_SAFE_INTEGER). erf() for all numbers beyond this limit will\n * return 1\n */\n\nvar MAX_NUM = Math.pow(2, 53);","import { format as formatString } from '../../utils/string.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'format';\nvar dependencies = ['typed'];\nexport var createFormat = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Format a value of any type into a string.\n *\n * Syntax:\n *\n * math.format(value)\n * math.format(value, options)\n * math.format(value, precision)\n * math.format(value, callback)\n *\n * Where:\n *\n * - `value: *`\n * The value to be formatted\n * - `options: Object`\n * An object with formatting options. Available options:\n * - `notation: string`\n * Number notation. Choose from:\n * - 'fixed'\n * Always use regular number notation.\n * For example '123.40' and '14000000'\n * - 'exponential'\n * Always use exponential notation.\n * For example '1.234e+2' and '1.4e+7'\n * - 'engineering'\n * Always use engineering notation: always have exponential notation,\n * and select the exponent to be a multiple of 3.\n * For example '123.4e+0' and '14.0e+6'\n * - 'auto' (default)\n * Regular number notation for numbers having an absolute value between\n * `lower` and `upper` bounds, and uses exponential notation elsewhere.\n * Lower bound is included, upper bound is excluded.\n * For example '123.4' and '1.4e7'.\n * - 'bin', 'oct, or 'hex'\n * Format the number using binary, octal, or hexadecimal notation.\n * For example '0b1101' and '0x10fe'.\n * - `wordSize: number`\n * The word size in bits to use for formatting in binary, octal, or\n * hexadecimal notation. To be used only with 'bin', 'oct', or 'hex'\n * values for 'notation' option. When this option is defined the value\n * is formatted as a signed twos complement integer of the given word\n * size and the size suffix is appended to the output.\n * For example format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'.\n * Default value is undefined.\n * - `precision: number`\n * A number between 0 and 16 to round the digits of the number. In case\n * of notations 'exponential', 'engineering', and 'auto', `precision`\n * defines the total number of significant digits returned.\n * In case of notation 'fixed', `precision` defines the number of\n * significant digits after the decimal point.\n * `precision` is undefined by default.\n * - `lowerExp: number`\n * Exponent determining the lower boundary for formatting a value with\n * an exponent when `notation='auto`. Default value is `-3`.\n * - `upperExp: number`\n * Exponent determining the upper boundary for formatting a value with\n * an exponent when `notation='auto`. Default value is `5`.\n * - `fraction: string`. Available values: 'ratio' (default) or 'decimal'.\n * For example `format(fraction(1, 3))` will output '1/3' when 'ratio' is\n * configured, and will output `0.(3)` when 'decimal' is configured.\n * - `callback: function`\n * A custom formatting function, invoked for all numeric elements in `value`,\n * for example all elements of a matrix, or the real and imaginary\n * parts of a complex number. This callback can be used to override the\n * built-in numeric notation with any type of formatting. Function `callback`\n * is called with `value` as parameter and must return a string.\n *\n * When `value` is an Object:\n *\n * - When the object contains a property `format` being a function, this function\n * is invoked as `value.format(options)` and the result is returned.\n * - When the object has its own `toString` method, this method is invoked\n * and the result is returned.\n * - In other cases the function will loop over all object properties and\n * return JSON object notation like '{\"a\": 2, \"b\": 3}'.\n *\n * When value is a function:\n *\n * - When the function has a property `syntax`, it returns this\n * syntax description.\n * - In other cases, a string `'function'` is returned.\n *\n * Examples:\n *\n * math.format(6.4) // returns '6.4'\n * math.format(1240000) // returns '1.24e6'\n * math.format(1/3) // returns '0.3333333333333333'\n * math.format(1/3, 3) // returns '0.333'\n * math.format(21385, 2) // returns '21000'\n * math.format(12e8, {notation: 'fixed'}) // returns '1200000000'\n * math.format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000'\n * math.format(52.8, {notation: 'exponential'}) // returns '5.28e+1'\n * math.format(12400,{notation: 'engineering'}) // returns '12.400e+3'\n * math.format(2000, {lowerExp: -2, upperExp: 2}) // returns '2e+3'\n *\n * function formatCurrency(value) {\n * // return currency notation with two digits:\n * return '$' + value.toFixed(2)\n *\n * // you could also use math.format inside the callback:\n * // return '$' + math.format(value, {notation: 'fixed', precision: 2})\n * }\n * math.format([2.1, 3, 0.016], formatCurrency} // returns '[$2.10, $3.00, $0.02]'\n *\n * See also:\n *\n * print\n *\n * @param {*} value Value to be stringified\n * @param {Object | Function | number} [options] Formatting options\n * @return {string} The formatted value\n */\n return typed(name, {\n any: formatString,\n 'any, Object | function | number': formatString\n });\n});","import { factory } from '../../utils/factory.js';\nvar name = 'oct';\nvar dependencies = ['typed', 'format'];\n/**\n * Format a number as octal.\n *\n * Syntax:\n *\n * math.oct(value)\n *\n * Examples:\n *\n * //the following outputs \"0o70\"\n * math.oct(56)\n *\n * See also:\n *\n * bin\n * hex\n *\n * @param {number} value Value to be stringified\n * @param {number} wordSize Optional word size (see `format`)\n * @return {string} The formatted value\n */\n\nexport var createOct = factory(name, dependencies, (_ref) => {\n var {\n typed,\n format\n } = _ref;\n return typed(name, {\n 'number | BigNumber': function numberBigNumber(n) {\n return format(n, {\n notation: 'oct'\n });\n },\n 'number | BigNumber, number': function numberBigNumberNumber(n, wordSize) {\n return format(n, {\n notation: 'oct',\n wordSize: wordSize\n });\n }\n });\n});","import { acosh, asinh, atanh, cosh, sign, sinh, tanh } from '../../utils/number.js';\nvar n1 = 'number';\nvar n2 = 'number, number';\nexport function acosNumber(x) {\n return Math.acos(x);\n}\nacosNumber.signature = n1;\nexport function acoshNumber(x) {\n return acosh(x);\n}\nacoshNumber.signature = n1;\nexport function acotNumber(x) {\n return Math.atan(1 / x);\n}\nacotNumber.signature = n1;\nexport function acothNumber(x) {\n return isFinite(x) ? (Math.log((x + 1) / x) + Math.log(x / (x - 1))) / 2 : 0;\n}\nacothNumber.signature = n1;\nexport function acscNumber(x) {\n return Math.asin(1 / x);\n}\nacscNumber.signature = n1;\nexport function acschNumber(x) {\n var xInv = 1 / x;\n return Math.log(xInv + Math.sqrt(xInv * xInv + 1));\n}\nacschNumber.signature = n1;\nexport function asecNumber(x) {\n return Math.acos(1 / x);\n}\nasecNumber.signature = n1;\nexport function asechNumber(x) {\n var xInv = 1 / x;\n var ret = Math.sqrt(xInv * xInv - 1);\n return Math.log(ret + xInv);\n}\nasechNumber.signature = n1;\nexport function asinNumber(x) {\n return Math.asin(x);\n}\nasinNumber.signature = n1;\nexport function asinhNumber(x) {\n return asinh(x);\n}\nasinhNumber.signature = n1;\nexport function atanNumber(x) {\n return Math.atan(x);\n}\natanNumber.signature = n1;\nexport function atan2Number(y, x) {\n return Math.atan2(y, x);\n}\natan2Number.signature = n2;\nexport function atanhNumber(x) {\n return atanh(x);\n}\natanhNumber.signature = n1;\nexport function cosNumber(x) {\n return Math.cos(x);\n}\ncosNumber.signature = n1;\nexport function coshNumber(x) {\n return cosh(x);\n}\ncoshNumber.signature = n1;\nexport function cotNumber(x) {\n return 1 / Math.tan(x);\n}\ncotNumber.signature = n1;\nexport function cothNumber(x) {\n var e = Math.exp(2 * x);\n return (e + 1) / (e - 1);\n}\ncothNumber.signature = n1;\nexport function cscNumber(x) {\n return 1 / Math.sin(x);\n}\ncscNumber.signature = n1;\nexport function cschNumber(x) {\n // consider values close to zero (+/-)\n if (x === 0) {\n return Number.POSITIVE_INFINITY;\n } else {\n return Math.abs(2 / (Math.exp(x) - Math.exp(-x))) * sign(x);\n }\n}\ncschNumber.signature = n1;\nexport function secNumber(x) {\n return 1 / Math.cos(x);\n}\nsecNumber.signature = n1;\nexport function sechNumber(x) {\n return 2 / (Math.exp(x) + Math.exp(-x));\n}\nsechNumber.signature = n1;\nexport function sinNumber(x) {\n return Math.sin(x);\n}\nsinNumber.signature = n1;\nexport function sinhNumber(x) {\n return sinh(x);\n}\nsinhNumber.signature = n1;\nexport function tanNumber(x) {\n return Math.tan(x);\n}\ntanNumber.signature = n1;\nexport function tanhNumber(x) {\n return tanh(x);\n}\ntanhNumber.signature = n1;","/** @param {number} i\n * @param {number} n\n * @returns {number} product of i to n\n */\nexport function product(i, n) {\n if (n < i) {\n return 1;\n }\n\n if (n === i) {\n return n;\n }\n\n var half = n + i >> 1; // divide (n + i) by 2 and truncate to integer\n\n return product(i, half) * product(half + 1, n);\n}","import { isInteger } from '../../utils/number.js';\nimport { product } from '../../utils/product.js';\nexport function combinationsNumber(n, k) {\n if (!isInteger(n) || n < 0) {\n throw new TypeError('Positive integer value expected in function combinations');\n }\n\n if (!isInteger(k) || k < 0) {\n throw new TypeError('Positive integer value expected in function combinations');\n }\n\n if (k > n) {\n throw new TypeError('k must be less than or equal to n');\n }\n\n var nMinusk = n - k;\n var prodrange;\n\n if (k < nMinusk) {\n prodrange = product(nMinusk + 1, n);\n return prodrange / product(1, k);\n }\n\n prodrange = product(k + 1, n);\n return prodrange / product(1, nMinusk);\n}\ncombinationsNumber.signature = 'number, number';","import seedrandom from 'seedrandom';\nvar singletonRandom = /* #__PURE__ */seedrandom(Date.now());\nexport function createRng(randomSeed) {\n var random; // create a new random generator with given seed\n\n function setSeed(seed) {\n random = seed === null ? singletonRandom : seedrandom(String(seed));\n } // initialize a seeded pseudo random number generator with config's random seed\n\n\n setSeed(randomSeed); // wrapper function so the rng can be updated via generator\n\n function rng() {\n return random();\n }\n\n return rng;\n}","import { factory } from '../../utils/factory.js';\nimport { randomMatrix } from './util/randomMatrix.js';\nimport { createRng } from './util/seededRNG.js';\nimport { isMatrix } from '../../utils/is.js';\nvar name = 'randomInt';\nvar dependencies = ['typed', 'config', '?on'];\nexport var createRandomInt = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n on\n } = _ref;\n // seeded pseudo random number generator\n var rng = createRng(config.randomSeed);\n\n if (on) {\n on('config', function (curr, prev) {\n if (curr.randomSeed !== prev.randomSeed) {\n rng = createRng(curr.randomSeed);\n }\n });\n }\n /**\n * Return a random integer number larger or equal to `min` and smaller than `max`\n * using a uniform distribution.\n *\n * Syntax:\n *\n * math.randomInt() // generate a random integer between 0 and 1\n * math.randomInt(max) // generate a random integer between 0 and max\n * math.randomInt(min, max) // generate a random integer between min and max\n * math.randomInt(size) // generate a matrix with random integer between 0 and 1\n * math.randomInt(size, max) // generate a matrix with random integer between 0 and max\n * math.randomInt(size, min, max) // generate a matrix with random integer between min and max\n *\n * Examples:\n *\n * math.randomInt(100) // returns a random integer between 0 and 100\n * math.randomInt(30, 40) // returns a random integer between 30 and 40\n * math.randomInt([2, 3]) // returns a 2x3 matrix with random integers between 0 and 1\n *\n * See also:\n *\n * random, pickRandom\n *\n * @param {Array | Matrix} [size] If provided, an array or matrix with given\n * size and filled with random values is returned\n * @param {number} [min] Minimum boundary for the random value, included\n * @param {number} [max] Maximum boundary for the random value, excluded\n * @return {number | Array | Matrix} A random integer value\n */\n\n\n return typed(name, {\n '': () => _randomInt(0, 1),\n number: max => _randomInt(0, max),\n 'number, number': (min, max) => _randomInt(min, max),\n 'Array | Matrix': size => _randomIntMatrix(size, 0, 1),\n 'Array | Matrix, number': (size, max) => _randomIntMatrix(size, 0, max),\n 'Array | Matrix, number, number': (size, min, max) => _randomIntMatrix(size, min, max)\n });\n\n function _randomIntMatrix(size, min, max) {\n var res = randomMatrix(size.valueOf(), () => _randomInt(min, max));\n return isMatrix(size) ? size.create(res) : res;\n }\n\n function _randomInt(min, max) {\n return Math.floor(min + rng() * (max - min));\n }\n});","import { factory } from '../../../utils/factory.js';\nimport { deepMap } from '../../../utils/collection.js';\nvar name = 'fraction';\nvar dependencies = ['typed', 'Fraction'];\nexport var createFraction = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n Fraction\n } = _ref;\n\n /**\n * Create a fraction convert a value to a fraction.\n *\n * Syntax:\n * math.fraction(numerator, denominator)\n * math.fraction({n: numerator, d: denominator})\n * math.fraction(matrix: Array | Matrix) Turn all matrix entries\n * into fractions\n *\n * Examples:\n *\n * math.fraction(1, 3)\n * math.fraction('2/3')\n * math.fraction({n: 2, d: 3})\n * math.fraction([0.2, 0.25, 1.25])\n *\n * See also:\n *\n * bignumber, number, string, unit\n *\n * @param {number | string | Fraction | BigNumber | Array | Matrix} [args]\n * Arguments specifying the numerator and denominator of\n * the fraction\n * @return {Fraction | Array | Matrix} Returns a fraction\n */\n return typed('fraction', {\n number: function number(x) {\n if (!isFinite(x) || isNaN(x)) {\n throw new Error(x + ' cannot be represented as a fraction');\n }\n\n return new Fraction(x);\n },\n string: function string(x) {\n return new Fraction(x);\n },\n 'number, number': function numberNumber(numerator, denominator) {\n return new Fraction(numerator, denominator);\n },\n null: function _null(x) {\n return new Fraction(0);\n },\n BigNumber: function BigNumber(x) {\n return new Fraction(x.toString());\n },\n Fraction: function Fraction(x) {\n return x; // fractions are immutable\n },\n Object: function Object(x) {\n return new Fraction(x);\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n return deepMap(x, this);\n }\n });\n});","import { factory } from '../../utils/factory.js';\nimport { deepMap } from '../../utils/collection.js';\nimport { unaryMinusNumber } from '../../plain/number/index.js';\nvar name = 'unaryMinus';\nvar dependencies = ['typed'];\nexport var createUnaryMinus = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Inverse the sign of a value, apply a unary minus operation.\n *\n * For matrices, the function is evaluated element wise. Boolean values and\n * strings will be converted to a number. For complex numbers, both real and\n * complex value are inverted.\n *\n * Syntax:\n *\n * math.unaryMinus(x)\n *\n * Examples:\n *\n * math.unaryMinus(3.5) // returns -3.5\n * math.unaryMinus(-4.2) // returns 4.2\n *\n * See also:\n *\n * add, subtract, unaryPlus\n *\n * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Number to be inverted.\n * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Returns the value with inverted sign.\n */\n return typed(name, {\n number: unaryMinusNumber,\n Complex: function Complex(x) {\n return x.neg();\n },\n BigNumber: function BigNumber(x) {\n return x.neg();\n },\n Fraction: function Fraction(x) {\n return x.neg();\n },\n Unit: function Unit(x) {\n var res = x.clone();\n res.value = this(x.value);\n return res;\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n // deep map collection, skip zeros since unaryMinus(0) = 0\n return deepMap(x, this, true);\n } // TODO: add support for string\n\n });\n});","import { factory } from '../../utils/factory.js';\nimport { addNumber } from '../../plain/number/index.js';\nvar name = 'addScalar';\nvar dependencies = ['typed'];\nexport var createAddScalar = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Add two scalar values, `x + y`.\n * This function is meant for internal use: it is used by the public function\n * `add`\n *\n * This function does not support collections (Array or Matrix).\n *\n * @param {number | BigNumber | Fraction | Complex | Unit} x First value to add\n * @param {number | BigNumber | Fraction | Complex} y Second value to add\n * @return {number | BigNumber | Fraction | Complex | Unit} Sum of `x` and `y`\n * @private\n */\n return typed(name, {\n 'number, number': addNumber,\n 'Complex, Complex': function ComplexComplex(x, y) {\n return x.add(y);\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {\n return x.plus(y);\n },\n 'Fraction, Fraction': function FractionFraction(x, y) {\n return x.add(y);\n },\n 'Unit, Unit': function UnitUnit(x, y) {\n if (x.value === null || x.value === undefined) throw new Error('Parameter x contains a unit with undefined value');\n if (y.value === null || y.value === undefined) throw new Error('Parameter y contains a unit with undefined value');\n if (!x.equalBase(y)) throw new Error('Units do not match');\n var res = x.clone();\n res.value = this(res.value, y.value);\n res.fixPrefix = false;\n return res;\n }\n });\n});","import { factory } from '../../utils/factory.js';\nimport { deepMap } from '../../utils/collection.js';\nvar name = 'conj';\nvar dependencies = ['typed'];\nexport var createConj = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Compute the complex conjugate of a complex value.\n * If `x = a+bi`, the complex conjugate of `x` is `a - bi`.\n *\n * For matrices, the function is evaluated element wise.\n *\n * Syntax:\n *\n * math.conj(x)\n *\n * Examples:\n *\n * math.conj(math.complex('2 + 3i')) // returns Complex 2 - 3i\n * math.conj(math.complex('2 - 3i')) // returns Complex 2 + 3i\n * math.conj(math.complex('-5.2i')) // returns Complex 5.2i\n *\n * See also:\n *\n * re, im, arg, abs\n *\n * @param {number | BigNumber | Complex | Array | Matrix} x\n * A complex number or array with complex numbers\n * @return {number | BigNumber | Complex | Array | Matrix}\n * The complex conjugate of x\n */\n return typed(name, {\n number: function number(x) {\n return x;\n },\n BigNumber: function BigNumber(x) {\n return x;\n },\n Complex: function Complex(x) {\n return x.conjugate();\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n return deepMap(x, this);\n }\n });\n});","import { factory } from '../../utils/factory.js';\nvar name = 'bin';\nvar dependencies = ['typed', 'format'];\n/**\n * Format a number as binary.\n *\n * Syntax:\n *\n * math.bin(value)\n *\n * Examples:\n *\n * //the following outputs \"0b10\"\n * math.bin(2)\n *\n * See also:\n *\n * oct\n * hex\n *\n * @param {number} value Value to be stringified\n * @param {number} wordSize Optional word size (see `format`)\n * @return {string} The formatted value\n */\n\nexport var createBin = factory(name, dependencies, (_ref) => {\n var {\n typed,\n format\n } = _ref;\n return typed(name, {\n 'number | BigNumber': function numberBigNumber(n) {\n return format(n, {\n notation: 'bin'\n });\n },\n 'number | BigNumber, number': function numberBigNumberNumber(n, wordSize) {\n return format(n, {\n notation: 'bin',\n wordSize: wordSize\n });\n }\n });\n});","import { factory } from '../../utils/factory.js';\nimport { isMatrix } from '../../utils/is.js';\nimport { createRng } from './util/seededRNG.js';\nimport { randomMatrix } from './util/randomMatrix.js';\nvar name = 'random';\nvar dependencies = ['typed', 'config', '?on'];\nexport var createRandom = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n on\n } = _ref;\n // seeded pseudo random number generator\n var rng = createRng(config.randomSeed);\n\n if (on) {\n on('config', function (curr, prev) {\n if (curr.randomSeed !== prev.randomSeed) {\n rng = createRng(curr.randomSeed);\n }\n });\n }\n /**\n * Return a random number larger or equal to `min` and smaller than `max`\n * using a uniform distribution.\n *\n * Syntax:\n *\n * math.random() // generate a random number between 0 and 1\n * math.random(max) // generate a random number between 0 and max\n * math.random(min, max) // generate a random number between min and max\n * math.random(size) // generate a matrix with random numbers between 0 and 1\n * math.random(size, max) // generate a matrix with random numbers between 0 and max\n * math.random(size, min, max) // generate a matrix with random numbers between min and max\n *\n * Examples:\n *\n * math.random() // returns a random number between 0 and 1\n * math.random(100) // returns a random number between 0 and 100\n * math.random(30, 40) // returns a random number between 30 and 40\n * math.random([2, 3]) // returns a 2x3 matrix with random numbers between 0 and 1\n *\n * See also:\n *\n * randomInt, pickRandom\n *\n * @param {Array | Matrix} [size] If provided, an array or matrix with given\n * size and filled with random values is returned\n * @param {number} [min] Minimum boundary for the random value, included\n * @param {number} [max] Maximum boundary for the random value, excluded\n * @return {number | Array | Matrix} A random number\n */\n\n\n return typed(name, {\n '': () => _random(0, 1),\n number: max => _random(0, max),\n 'number, number': (min, max) => _random(min, max),\n 'Array | Matrix': size => _randomMatrix(size, 0, 1),\n 'Array | Matrix, number': (size, max) => _randomMatrix(size, 0, max),\n 'Array | Matrix, number, number': (size, min, max) => _randomMatrix(size, min, max)\n });\n\n function _randomMatrix(size, min, max) {\n var res = randomMatrix(size.valueOf(), () => _random(min, max));\n return isMatrix(size) ? size.create(res) : res;\n }\n\n function _random(min, max) {\n return min + rng() * (max - min);\n }\n}); // number only implementation of random, no matrix support\n// TODO: there is quite some duplicate code in both createRandom and createRandomNumber, can we improve that?\n\nexport var createRandomNumber = /* #__PURE__ */factory(name, ['typed', 'config', '?on'], (_ref2) => {\n var {\n typed,\n config,\n on,\n matrix\n } = _ref2;\n // seeded pseudo random number generator1\n var rng = createRng(config.randomSeed);\n\n if (on) {\n on('config', function (curr, prev) {\n if (curr.randomSeed !== prev.randomSeed) {\n rng = createRng(curr.randomSeed);\n }\n });\n }\n\n return typed(name, {\n '': () => _random(0, 1),\n number: max => _random(0, max),\n 'number, number': (min, max) => _random(min, max)\n });\n\n function _random(min, max) {\n return min + rng() * (max - min);\n }\n});","import { isArray, isBigNumber, isCollection, isIndex, isMatrix, isNumber, isString, typeOf } from '../../utils/is.js';\nimport { isInteger } from '../../utils/number.js';\nimport { format } from '../../utils/string.js';\nimport { clone, deepStrictEqual } from '../../utils/object.js';\nimport { arraySize, getArrayDataType, processSizesWildcard, unsqueeze, validateIndex } from '../../utils/array.js';\nimport { factory } from '../../utils/factory.js';\nimport { DimensionError } from '../../error/DimensionError.js';\nvar name = 'SparseMatrix';\nvar dependencies = ['typed', 'equalScalar', 'Matrix'];\nexport var createSparseMatrixClass = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n equalScalar,\n Matrix\n } = _ref;\n\n /**\n * Sparse Matrix implementation. This type implements a Compressed Column Storage format\n * for sparse matrices.\n * @class SparseMatrix\n */\n function SparseMatrix(data, datatype) {\n if (!(this instanceof SparseMatrix)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n }\n\n if (datatype && !isString(datatype)) {\n throw new Error('Invalid datatype: ' + datatype);\n }\n\n if (isMatrix(data)) {\n // create from matrix\n _createFromMatrix(this, data, datatype);\n } else if (data && isArray(data.index) && isArray(data.ptr) && isArray(data.size)) {\n // initialize fields\n this._values = data.values;\n this._index = data.index;\n this._ptr = data.ptr;\n this._size = data.size;\n this._datatype = datatype || data.datatype;\n } else if (isArray(data)) {\n // create from array\n _createFromArray(this, data, datatype);\n } else if (data) {\n // unsupported type\n throw new TypeError('Unsupported type of data (' + typeOf(data) + ')');\n } else {\n // nothing provided\n this._values = [];\n this._index = [];\n this._ptr = [0];\n this._size = [0, 0];\n this._datatype = datatype;\n }\n }\n\n function _createFromMatrix(matrix, source, datatype) {\n // check matrix type\n if (source.type === 'SparseMatrix') {\n // clone arrays\n matrix._values = source._values ? clone(source._values) : undefined;\n matrix._index = clone(source._index);\n matrix._ptr = clone(source._ptr);\n matrix._size = clone(source._size);\n matrix._datatype = datatype || source._datatype;\n } else {\n // build from matrix data\n _createFromArray(matrix, source.valueOf(), datatype || source._datatype);\n }\n }\n\n function _createFromArray(matrix, data, datatype) {\n // initialize fields\n matrix._values = [];\n matrix._index = [];\n matrix._ptr = [];\n matrix._datatype = datatype; // discover rows & columns, do not use math.size() to avoid looping array twice\n\n var rows = data.length;\n var columns = 0; // equal signature to use\n\n var eq = equalScalar; // zero value\n\n var zero = 0;\n\n if (isString(datatype)) {\n // find signature that matches (datatype, datatype)\n eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype\n\n zero = typed.convert(0, datatype);\n } // check we have rows (empty array)\n\n\n if (rows > 0) {\n // column index\n var j = 0;\n\n do {\n // store pointer to values index\n matrix._ptr.push(matrix._index.length); // loop rows\n\n\n for (var i = 0; i < rows; i++) {\n // current row\n var row = data[i]; // check row is an array\n\n if (isArray(row)) {\n // update columns if needed (only on first column)\n if (j === 0 && columns < row.length) {\n columns = row.length;\n } // check row has column\n\n\n if (j < row.length) {\n // value\n var v = row[j]; // check value != 0\n\n if (!eq(v, zero)) {\n // store value\n matrix._values.push(v); // index\n\n\n matrix._index.push(i);\n }\n }\n } else {\n // update columns if needed (only on first column)\n if (j === 0 && columns < 1) {\n columns = 1;\n } // check value != 0 (row is a scalar)\n\n\n if (!eq(row, zero)) {\n // store value\n matrix._values.push(row); // index\n\n\n matrix._index.push(i);\n }\n }\n } // increment index\n\n\n j++;\n } while (j < columns);\n } // store number of values in ptr\n\n\n matrix._ptr.push(matrix._index.length); // size\n\n\n matrix._size = [rows, columns];\n }\n\n SparseMatrix.prototype = new Matrix();\n /**\n * Create a new SparseMatrix\n */\n\n SparseMatrix.prototype.createSparseMatrix = function (data, datatype) {\n return new SparseMatrix(data, datatype);\n };\n /**\n * Attach type information\n */\n\n\n SparseMatrix.prototype.type = 'SparseMatrix';\n SparseMatrix.prototype.isSparseMatrix = true;\n /**\n * Get the matrix type\n *\n * Usage:\n * const matrixType = matrix.getDataType() // retrieves the matrix type\n *\n * @memberOf SparseMatrix\n * @return {string} type information; if multiple types are found from the Matrix, it will return \"mixed\"\n */\n\n SparseMatrix.prototype.getDataType = function () {\n return getArrayDataType(this._values, typeOf);\n };\n /**\n * Get the storage format used by the matrix.\n *\n * Usage:\n * const format = matrix.storage() // retrieve storage format\n *\n * @memberof SparseMatrix\n * @return {string} The storage format.\n */\n\n\n SparseMatrix.prototype.storage = function () {\n return 'sparse';\n };\n /**\n * Get the datatype of the data stored in the matrix.\n *\n * Usage:\n * const format = matrix.datatype() // retrieve matrix datatype\n *\n * @memberof SparseMatrix\n * @return {string} The datatype.\n */\n\n\n SparseMatrix.prototype.datatype = function () {\n return this._datatype;\n };\n /**\n * Create a new SparseMatrix\n * @memberof SparseMatrix\n * @param {Array} data\n * @param {string} [datatype]\n */\n\n\n SparseMatrix.prototype.create = function (data, datatype) {\n return new SparseMatrix(data, datatype);\n };\n /**\n * Get the matrix density.\n *\n * Usage:\n * const density = matrix.density() // retrieve matrix density\n *\n * @memberof SparseMatrix\n * @return {number} The matrix density.\n */\n\n\n SparseMatrix.prototype.density = function () {\n // rows & columns\n var rows = this._size[0];\n var columns = this._size[1]; // calculate density\n\n return rows !== 0 && columns !== 0 ? this._index.length / (rows * columns) : 0;\n };\n /**\n * Get a subset of the matrix, or replace a subset of the matrix.\n *\n * Usage:\n * const subset = matrix.subset(index) // retrieve subset\n * const value = matrix.subset(index, replacement) // replace subset\n *\n * @memberof SparseMatrix\n * @param {Index} index\n * @param {Array | Matrix | *} [replacement]\n * @param {*} [defaultValue=0] Default value, filled in on new entries when\n * the matrix is resized. If not provided,\n * new matrix elements will be filled with zeros.\n */\n\n\n SparseMatrix.prototype.subset = function (index, replacement, defaultValue) {\n // check it is a pattern matrix\n if (!this._values) {\n throw new Error('Cannot invoke subset on a Pattern only matrix');\n } // check arguments\n\n\n switch (arguments.length) {\n case 1:\n return _getsubset(this, index);\n // intentional fall through\n\n case 2:\n case 3:\n return _setsubset(this, index, replacement, defaultValue);\n\n default:\n throw new SyntaxError('Wrong number of arguments');\n }\n };\n\n function _getsubset(matrix, idx) {\n // check idx\n if (!isIndex(idx)) {\n throw new TypeError('Invalid index');\n }\n\n var isScalar = idx.isScalar();\n\n if (isScalar) {\n // return a scalar\n return matrix.get(idx.min());\n } // validate dimensions\n\n\n var size = idx.size();\n\n if (size.length !== matrix._size.length) {\n throw new DimensionError(size.length, matrix._size.length);\n } // vars\n\n\n var i, ii, k, kk; // validate if any of the ranges in the index is out of range\n\n var min = idx.min();\n var max = idx.max();\n\n for (i = 0, ii = matrix._size.length; i < ii; i++) {\n validateIndex(min[i], matrix._size[i]);\n validateIndex(max[i], matrix._size[i]);\n } // matrix arrays\n\n\n var mvalues = matrix._values;\n var mindex = matrix._index;\n var mptr = matrix._ptr; // rows & columns dimensions for result matrix\n\n var rows = idx.dimension(0);\n var columns = idx.dimension(1); // workspace & permutation vector\n\n var w = [];\n var pv = []; // loop rows in resulting matrix\n\n rows.forEach(function (i, r) {\n // update permutation vector\n pv[i] = r[0]; // mark i in workspace\n\n w[i] = true;\n }); // result matrix arrays\n\n var values = mvalues ? [] : undefined;\n var index = [];\n var ptr = []; // loop columns in result matrix\n\n columns.forEach(function (j) {\n // update ptr\n ptr.push(index.length); // loop values in column j\n\n for (k = mptr[j], kk = mptr[j + 1]; k < kk; k++) {\n // row\n i = mindex[k]; // check row is in result matrix\n\n if (w[i] === true) {\n // push index\n index.push(pv[i]); // check we need to process values\n\n if (values) {\n values.push(mvalues[k]);\n }\n }\n }\n }); // update ptr\n\n ptr.push(index.length); // return matrix\n\n return new SparseMatrix({\n values: values,\n index: index,\n ptr: ptr,\n size: size,\n datatype: matrix._datatype\n });\n }\n\n function _setsubset(matrix, index, submatrix, defaultValue) {\n // check index\n if (!index || index.isIndex !== true) {\n throw new TypeError('Invalid index');\n } // get index size and check whether the index contains a single value\n\n\n var iSize = index.size();\n var isScalar = index.isScalar(); // calculate the size of the submatrix, and convert it into an Array if needed\n\n var sSize;\n\n if (isMatrix(submatrix)) {\n // submatrix size\n sSize = submatrix.size(); // use array representation\n\n submatrix = submatrix.toArray();\n } else {\n // get submatrix size (array, scalar)\n sSize = arraySize(submatrix);\n } // check index is a scalar\n\n\n if (isScalar) {\n // verify submatrix is a scalar\n if (sSize.length !== 0) {\n throw new TypeError('Scalar expected');\n } // set value\n\n\n matrix.set(index.min(), submatrix, defaultValue);\n } else {\n // validate dimensions, index size must be one or two dimensions\n if (iSize.length !== 1 && iSize.length !== 2) {\n throw new DimensionError(iSize.length, matrix._size.length, '<');\n } // check submatrix and index have the same dimensions\n\n\n if (sSize.length < iSize.length) {\n // calculate number of missing outer dimensions\n var i = 0;\n var outer = 0;\n\n while (iSize[i] === 1 && sSize[i] === 1) {\n i++;\n }\n\n while (iSize[i] === 1) {\n outer++;\n i++;\n } // unsqueeze both outer and inner dimensions\n\n\n submatrix = unsqueeze(submatrix, iSize.length, outer, sSize);\n } // check whether the size of the submatrix matches the index size\n\n\n if (!deepStrictEqual(iSize, sSize)) {\n throw new DimensionError(iSize, sSize, '>');\n } // offsets\n\n\n var x0 = index.min()[0];\n var y0 = index.min()[1]; // submatrix rows and columns\n\n var m = sSize[0];\n var n = sSize[1]; // loop submatrix\n\n for (var x = 0; x < m; x++) {\n // loop columns\n for (var y = 0; y < n; y++) {\n // value at i, j\n var v = submatrix[x][y]; // invoke set (zero value will remove entry from matrix)\n\n matrix.set([x + x0, y + y0], v, defaultValue);\n }\n }\n }\n\n return matrix;\n }\n /**\n * Get a single element from the matrix.\n * @memberof SparseMatrix\n * @param {number[]} index Zero-based index\n * @return {*} value\n */\n\n\n SparseMatrix.prototype.get = function (index) {\n if (!isArray(index)) {\n throw new TypeError('Array expected');\n }\n\n if (index.length !== this._size.length) {\n throw new DimensionError(index.length, this._size.length);\n } // check it is a pattern matrix\n\n\n if (!this._values) {\n throw new Error('Cannot invoke get on a Pattern only matrix');\n } // row and column\n\n\n var i = index[0];\n var j = index[1]; // check i, j are valid\n\n validateIndex(i, this._size[0]);\n validateIndex(j, this._size[1]); // find value index\n\n var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row\n\n\n if (k < this._ptr[j + 1] && this._index[k] === i) {\n return this._values[k];\n }\n\n return 0;\n };\n /**\n * Replace a single element in the matrix.\n * @memberof SparseMatrix\n * @param {number[]} index Zero-based index\n * @param {*} v\n * @param {*} [defaultValue] Default value, filled in on new entries when\n * the matrix is resized. If not provided,\n * new matrix elements will be set to zero.\n * @return {SparseMatrix} self\n */\n\n\n SparseMatrix.prototype.set = function (index, v, defaultValue) {\n if (!isArray(index)) {\n throw new TypeError('Array expected');\n }\n\n if (index.length !== this._size.length) {\n throw new DimensionError(index.length, this._size.length);\n } // check it is a pattern matrix\n\n\n if (!this._values) {\n throw new Error('Cannot invoke set on a Pattern only matrix');\n } // row and column\n\n\n var i = index[0];\n var j = index[1]; // rows & columns\n\n var rows = this._size[0];\n var columns = this._size[1]; // equal signature to use\n\n var eq = equalScalar; // zero value\n\n var zero = 0;\n\n if (isString(this._datatype)) {\n // find signature that matches (datatype, datatype)\n eq = typed.find(equalScalar, [this._datatype, this._datatype]) || equalScalar; // convert 0 to the same datatype\n\n zero = typed.convert(0, this._datatype);\n } // check we need to resize matrix\n\n\n if (i > rows - 1 || j > columns - 1) {\n // resize matrix\n _resize(this, Math.max(i + 1, rows), Math.max(j + 1, columns), defaultValue); // update rows & columns\n\n\n rows = this._size[0];\n columns = this._size[1];\n } // check i, j are valid\n\n\n validateIndex(i, rows);\n validateIndex(j, columns); // find value index\n\n var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row\n\n\n if (k < this._ptr[j + 1] && this._index[k] === i) {\n // check value != 0\n if (!eq(v, zero)) {\n // update value\n this._values[k] = v;\n } else {\n // remove value from matrix\n _remove(k, j, this._values, this._index, this._ptr);\n }\n } else {\n // insert value @ (i, j)\n _insert(k, i, j, v, this._values, this._index, this._ptr);\n }\n\n return this;\n };\n\n function _getValueIndex(i, top, bottom, index) {\n // check row is on the bottom side\n if (bottom - top === 0) {\n return bottom;\n } // loop rows [top, bottom[\n\n\n for (var r = top; r < bottom; r++) {\n // check we found value index\n if (index[r] === i) {\n return r;\n }\n } // we did not find row\n\n\n return top;\n }\n\n function _remove(k, j, values, index, ptr) {\n // remove value @ k\n values.splice(k, 1);\n index.splice(k, 1); // update pointers\n\n for (var x = j + 1; x < ptr.length; x++) {\n ptr[x]--;\n }\n }\n\n function _insert(k, i, j, v, values, index, ptr) {\n // insert value\n values.splice(k, 0, v); // update row for k\n\n index.splice(k, 0, i); // update column pointers\n\n for (var x = j + 1; x < ptr.length; x++) {\n ptr[x]++;\n }\n }\n /**\n * Resize the matrix to the given size. Returns a copy of the matrix when\n * `copy=true`, otherwise return the matrix itself (resize in place).\n *\n * @memberof SparseMatrix\n * @param {number[] | Matrix} size The new size the matrix should have.\n * @param {*} [defaultValue=0] Default value, filled in on new entries.\n * If not provided, the matrix elements will\n * be filled with zeros.\n * @param {boolean} [copy] Return a resized copy of the matrix\n *\n * @return {Matrix} The resized matrix\n */\n\n\n SparseMatrix.prototype.resize = function (size, defaultValue, copy) {\n // validate arguments\n if (!isCollection(size)) {\n throw new TypeError('Array or Matrix expected');\n } // SparseMatrix input is always 2d, flatten this into 1d if it's indeed a vector\n\n\n var sizeArray = size.valueOf().map(value => {\n return Array.isArray(value) && value.length === 1 ? value[0] : value;\n });\n\n if (sizeArray.length !== 2) {\n throw new Error('Only two dimensions matrix are supported');\n } // check sizes\n\n\n sizeArray.forEach(function (value) {\n if (!isNumber(value) || !isInteger(value) || value < 0) {\n throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + format(sizeArray) + ')');\n }\n }); // matrix to resize\n\n var m = copy ? this.clone() : this; // resize matrix\n\n return _resize(m, sizeArray[0], sizeArray[1], defaultValue);\n };\n\n function _resize(matrix, rows, columns, defaultValue) {\n // value to insert at the time of growing matrix\n var value = defaultValue || 0; // equal signature to use\n\n var eq = equalScalar; // zero value\n\n var zero = 0;\n\n if (isString(matrix._datatype)) {\n // find signature that matches (datatype, datatype)\n eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype\n\n zero = typed.convert(0, matrix._datatype); // convert value to the same datatype\n\n value = typed.convert(value, matrix._datatype);\n } // should we insert the value?\n\n\n var ins = !eq(value, zero); // old columns and rows\n\n var r = matrix._size[0];\n var c = matrix._size[1];\n var i, j, k; // check we need to increase columns\n\n if (columns > c) {\n // loop new columns\n for (j = c; j < columns; j++) {\n // update matrix._ptr for current column\n matrix._ptr[j] = matrix._values.length; // check we need to insert matrix._values\n\n if (ins) {\n // loop rows\n for (i = 0; i < r; i++) {\n // add new matrix._values\n matrix._values.push(value); // update matrix._index\n\n\n matrix._index.push(i);\n }\n }\n } // store number of matrix._values in matrix._ptr\n\n\n matrix._ptr[columns] = matrix._values.length;\n } else if (columns < c) {\n // truncate matrix._ptr\n matrix._ptr.splice(columns + 1, c - columns); // truncate matrix._values and matrix._index\n\n\n matrix._values.splice(matrix._ptr[columns], matrix._values.length);\n\n matrix._index.splice(matrix._ptr[columns], matrix._index.length);\n } // update columns\n\n\n c = columns; // check we need to increase rows\n\n if (rows > r) {\n // check we have to insert values\n if (ins) {\n // inserts\n var n = 0; // loop columns\n\n for (j = 0; j < c; j++) {\n // update matrix._ptr for current column\n matrix._ptr[j] = matrix._ptr[j] + n; // where to insert matrix._values\n\n k = matrix._ptr[j + 1] + n; // pointer\n\n var p = 0; // loop new rows, initialize pointer\n\n for (i = r; i < rows; i++, p++) {\n // add value\n matrix._values.splice(k + p, 0, value); // update matrix._index\n\n\n matrix._index.splice(k + p, 0, i); // increment inserts\n\n\n n++;\n }\n } // store number of matrix._values in matrix._ptr\n\n\n matrix._ptr[c] = matrix._values.length;\n }\n } else if (rows < r) {\n // deletes\n var d = 0; // loop columns\n\n for (j = 0; j < c; j++) {\n // update matrix._ptr for current column\n matrix._ptr[j] = matrix._ptr[j] - d; // where matrix._values start for next column\n\n var k0 = matrix._ptr[j];\n var k1 = matrix._ptr[j + 1] - d; // loop matrix._index\n\n for (k = k0; k < k1; k++) {\n // row\n i = matrix._index[k]; // check we need to delete value and matrix._index\n\n if (i > rows - 1) {\n // remove value\n matrix._values.splice(k, 1); // remove item from matrix._index\n\n\n matrix._index.splice(k, 1); // increase deletes\n\n\n d++;\n }\n }\n } // update matrix._ptr for current column\n\n\n matrix._ptr[j] = matrix._values.length;\n } // update matrix._size\n\n\n matrix._size[0] = rows;\n matrix._size[1] = columns; // return matrix\n\n return matrix;\n }\n /**\n * Reshape the matrix to the given size. Returns a copy of the matrix when\n * `copy=true`, otherwise return the matrix itself (reshape in place).\n *\n * NOTE: This might be better suited to copy by default, instead of modifying\n * in place. For now, it operates in place to remain consistent with\n * resize().\n *\n * @memberof SparseMatrix\n * @param {number[]} sizes The new size the matrix should have.\n * @param {boolean} [copy] Return a reshaped copy of the matrix\n *\n * @return {Matrix} The reshaped matrix\n */\n\n\n SparseMatrix.prototype.reshape = function (sizes, copy) {\n // validate arguments\n if (!isArray(sizes)) {\n throw new TypeError('Array expected');\n }\n\n if (sizes.length !== 2) {\n throw new Error('Sparse matrices can only be reshaped in two dimensions');\n } // check sizes\n\n\n sizes.forEach(function (value) {\n if (!isNumber(value) || !isInteger(value) || value <= -2 || value === 0) {\n throw new TypeError('Invalid size, must contain positive integers or -1 ' + '(size: ' + format(sizes) + ')');\n }\n });\n var currentLength = this._size[0] * this._size[1];\n sizes = processSizesWildcard(sizes, currentLength);\n var newLength = sizes[0] * sizes[1]; // m * n must not change\n\n if (currentLength !== newLength) {\n throw new Error('Reshaping sparse matrix will result in the wrong number of elements');\n } // matrix to reshape\n\n\n var m = copy ? this.clone() : this; // return unchanged if the same shape\n\n if (this._size[0] === sizes[0] && this._size[1] === sizes[1]) {\n return m;\n } // Convert to COO format (generate a column index)\n\n\n var colIndex = [];\n\n for (var i = 0; i < m._ptr.length; i++) {\n for (var j = 0; j < m._ptr[i + 1] - m._ptr[i]; j++) {\n colIndex.push(i);\n }\n } // Clone the values array\n\n\n var values = m._values.slice(); // Clone the row index array\n\n\n var rowIndex = m._index.slice(); // Transform the (row, column) indices\n\n\n for (var _i = 0; _i < m._index.length; _i++) {\n var r1 = rowIndex[_i];\n var c1 = colIndex[_i];\n var flat = r1 * m._size[1] + c1;\n colIndex[_i] = flat % sizes[1];\n rowIndex[_i] = Math.floor(flat / sizes[1]);\n } // Now reshaping is supposed to preserve the row-major order, BUT these sparse matrices are stored\n // in column-major order, so we have to reorder the value array now. One option is to use a multisort,\n // sorting several arrays based on some other array.\n // OR, we could easily just:\n // 1. Remove all values from the matrix\n\n\n m._values.length = 0;\n m._index.length = 0;\n m._ptr.length = sizes[1] + 1;\n m._size = sizes.slice();\n\n for (var _i2 = 0; _i2 < m._ptr.length; _i2++) {\n m._ptr[_i2] = 0;\n } // 2. Re-insert all elements in the proper order (simplified code from SparseMatrix.prototype.set)\n // This step is probably the most time-consuming\n\n\n for (var h = 0; h < values.length; h++) {\n var _i3 = rowIndex[h];\n var _j = colIndex[h];\n var v = values[h];\n\n var k = _getValueIndex(_i3, m._ptr[_j], m._ptr[_j + 1], m._index);\n\n _insert(k, _i3, _j, v, m._values, m._index, m._ptr);\n } // The value indices are inserted out of order, but apparently that's... still OK?\n\n\n return m;\n };\n /**\n * Create a clone of the matrix\n * @memberof SparseMatrix\n * @return {SparseMatrix} clone\n */\n\n\n SparseMatrix.prototype.clone = function () {\n var m = new SparseMatrix({\n values: this._values ? clone(this._values) : undefined,\n index: clone(this._index),\n ptr: clone(this._ptr),\n size: clone(this._size),\n datatype: this._datatype\n });\n return m;\n };\n /**\n * Retrieve the size of the matrix.\n * @memberof SparseMatrix\n * @returns {number[]} size\n */\n\n\n SparseMatrix.prototype.size = function () {\n return this._size.slice(0); // copy the Array\n };\n /**\n * Create a new matrix with the results of the callback function executed on\n * each entry of the matrix.\n * @memberof SparseMatrix\n * @param {Function} callback The callback function is invoked with three\n * parameters: the value of the element, the index\n * of the element, and the Matrix being traversed.\n * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.\n *\n * @return {SparseMatrix} matrix\n */\n\n\n SparseMatrix.prototype.map = function (callback, skipZeros) {\n // check it is a pattern matrix\n if (!this._values) {\n throw new Error('Cannot invoke map on a Pattern only matrix');\n } // matrix instance\n\n\n var me = this; // rows and columns\n\n var rows = this._size[0];\n var columns = this._size[1]; // invoke callback\n\n var invoke = function invoke(v, i, j) {\n // invoke callback\n return callback(v, [i, j], me);\n }; // invoke _map\n\n\n return _map(this, 0, rows - 1, 0, columns - 1, invoke, skipZeros);\n };\n /**\n * Create a new matrix with the results of the callback function executed on the interval\n * [minRow..maxRow, minColumn..maxColumn].\n */\n\n\n function _map(matrix, minRow, maxRow, minColumn, maxColumn, callback, skipZeros) {\n // result arrays\n var values = [];\n var index = [];\n var ptr = []; // equal signature to use\n\n var eq = equalScalar; // zero value\n\n var zero = 0;\n\n if (isString(matrix._datatype)) {\n // find signature that matches (datatype, datatype)\n eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype\n\n zero = typed.convert(0, matrix._datatype);\n } // invoke callback\n\n\n var invoke = function invoke(v, x, y) {\n // invoke callback\n v = callback(v, x, y); // check value != 0\n\n if (!eq(v, zero)) {\n // store value\n values.push(v); // index\n\n index.push(x);\n }\n }; // loop columns\n\n\n for (var j = minColumn; j <= maxColumn; j++) {\n // store pointer to values index\n ptr.push(values.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]\n\n var k0 = matrix._ptr[j];\n var k1 = matrix._ptr[j + 1];\n\n if (skipZeros) {\n // loop k within [k0, k1[\n for (var k = k0; k < k1; k++) {\n // row index\n var i = matrix._index[k]; // check i is in range\n\n if (i >= minRow && i <= maxRow) {\n // value @ k\n invoke(matrix._values[k], i - minRow, j - minColumn);\n }\n }\n } else {\n // create a cache holding all defined values\n var _values = {};\n\n for (var _k = k0; _k < k1; _k++) {\n var _i4 = matrix._index[_k];\n _values[_i4] = matrix._values[_k];\n } // loop over all rows (indexes can be unordered so we can't use that),\n // and either read the value or zero\n\n\n for (var _i5 = minRow; _i5 <= maxRow; _i5++) {\n var value = _i5 in _values ? _values[_i5] : 0;\n invoke(value, _i5 - minRow, j - minColumn);\n }\n }\n } // store number of values in ptr\n\n\n ptr.push(values.length); // return sparse matrix\n\n return new SparseMatrix({\n values: values,\n index: index,\n ptr: ptr,\n size: [maxRow - minRow + 1, maxColumn - minColumn + 1]\n });\n }\n /**\n * Execute a callback function on each entry of the matrix.\n * @memberof SparseMatrix\n * @param {Function} callback The callback function is invoked with three\n * parameters: the value of the element, the index\n * of the element, and the Matrix being traversed.\n * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.\n */\n\n\n SparseMatrix.prototype.forEach = function (callback, skipZeros) {\n // check it is a pattern matrix\n if (!this._values) {\n throw new Error('Cannot invoke forEach on a Pattern only matrix');\n } // matrix instance\n\n\n var me = this; // rows and columns\n\n var rows = this._size[0];\n var columns = this._size[1]; // loop columns\n\n for (var j = 0; j < columns; j++) {\n // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]\n var k0 = this._ptr[j];\n var k1 = this._ptr[j + 1];\n\n if (skipZeros) {\n // loop k within [k0, k1[\n for (var k = k0; k < k1; k++) {\n // row index\n var i = this._index[k]; // value @ k\n\n callback(this._values[k], [i, j], me);\n }\n } else {\n // create a cache holding all defined values\n var values = {};\n\n for (var _k2 = k0; _k2 < k1; _k2++) {\n var _i6 = this._index[_k2];\n values[_i6] = this._values[_k2];\n } // loop over all rows (indexes can be unordered so we can't use that),\n // and either read the value or zero\n\n\n for (var _i7 = 0; _i7 < rows; _i7++) {\n var value = _i7 in values ? values[_i7] : 0;\n callback(value, [_i7, j], me);\n }\n }\n }\n };\n /**\n * Create an Array with a copy of the data of the SparseMatrix\n * @memberof SparseMatrix\n * @returns {Array} array\n */\n\n\n SparseMatrix.prototype.toArray = function () {\n return _toArray(this._values, this._index, this._ptr, this._size, true);\n };\n /**\n * Get the primitive value of the SparseMatrix: a two dimensions array\n * @memberof SparseMatrix\n * @returns {Array} array\n */\n\n\n SparseMatrix.prototype.valueOf = function () {\n return _toArray(this._values, this._index, this._ptr, this._size, false);\n };\n\n function _toArray(values, index, ptr, size, copy) {\n // rows and columns\n var rows = size[0];\n var columns = size[1]; // result\n\n var a = []; // vars\n\n var i, j; // initialize array\n\n for (i = 0; i < rows; i++) {\n a[i] = [];\n\n for (j = 0; j < columns; j++) {\n a[i][j] = 0;\n }\n } // loop columns\n\n\n for (j = 0; j < columns; j++) {\n // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]\n var k0 = ptr[j];\n var k1 = ptr[j + 1]; // loop k within [k0, k1[\n\n for (var k = k0; k < k1; k++) {\n // row index\n i = index[k]; // set value (use one for pattern matrix)\n\n a[i][j] = values ? copy ? clone(values[k]) : values[k] : 1;\n }\n }\n\n return a;\n }\n /**\n * Get a string representation of the matrix, with optional formatting options.\n * @memberof SparseMatrix\n * @param {Object | number | Function} [options] Formatting options. See\n * lib/utils/number:format for a\n * description of the available\n * options.\n * @returns {string} str\n */\n\n\n SparseMatrix.prototype.format = function (options) {\n // rows and columns\n var rows = this._size[0];\n var columns = this._size[1]; // density\n\n var density = this.density(); // rows & columns\n\n var str = 'Sparse Matrix [' + format(rows, options) + ' x ' + format(columns, options) + '] density: ' + format(density, options) + '\\n'; // loop columns\n\n for (var j = 0; j < columns; j++) {\n // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]\n var k0 = this._ptr[j];\n var k1 = this._ptr[j + 1]; // loop k within [k0, k1[\n\n for (var k = k0; k < k1; k++) {\n // row index\n var i = this._index[k]; // append value\n\n str += '\\n (' + format(i, options) + ', ' + format(j, options) + ') ==> ' + (this._values ? format(this._values[k], options) : 'X');\n }\n }\n\n return str;\n };\n /**\n * Get a string representation of the matrix\n * @memberof SparseMatrix\n * @returns {string} str\n */\n\n\n SparseMatrix.prototype.toString = function () {\n return format(this.toArray());\n };\n /**\n * Get a JSON representation of the matrix\n * @memberof SparseMatrix\n * @returns {Object}\n */\n\n\n SparseMatrix.prototype.toJSON = function () {\n return {\n mathjs: 'SparseMatrix',\n values: this._values,\n index: this._index,\n ptr: this._ptr,\n size: this._size,\n datatype: this._datatype\n };\n };\n /**\n * Get the kth Matrix diagonal.\n *\n * @memberof SparseMatrix\n * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved.\n *\n * @returns {Matrix} The matrix vector with the diagonal values.\n */\n\n\n SparseMatrix.prototype.diagonal = function (k) {\n // validate k if any\n if (k) {\n // convert BigNumber to a number\n if (isBigNumber(k)) {\n k = k.toNumber();\n } // is must be an integer\n\n\n if (!isNumber(k) || !isInteger(k)) {\n throw new TypeError('The parameter k must be an integer number');\n }\n } else {\n // default value\n k = 0;\n }\n\n var kSuper = k > 0 ? k : 0;\n var kSub = k < 0 ? -k : 0; // rows & columns\n\n var rows = this._size[0];\n var columns = this._size[1]; // number diagonal values\n\n var n = Math.min(rows - kSub, columns - kSuper); // diagonal arrays\n\n var values = [];\n var index = [];\n var ptr = []; // initial ptr value\n\n ptr[0] = 0; // loop columns\n\n for (var j = kSuper; j < columns && values.length < n; j++) {\n // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]\n var k0 = this._ptr[j];\n var k1 = this._ptr[j + 1]; // loop x within [k0, k1[\n\n for (var x = k0; x < k1; x++) {\n // row index\n var i = this._index[x]; // check row\n\n if (i === j - kSuper + kSub) {\n // value on this column\n values.push(this._values[x]); // store row\n\n index[values.length - 1] = i - kSub; // exit loop\n\n break;\n }\n }\n } // close ptr\n\n\n ptr.push(values.length); // return matrix\n\n return new SparseMatrix({\n values: values,\n index: index,\n ptr: ptr,\n size: [n, 1]\n });\n };\n /**\n * Generate a matrix from a JSON object\n * @memberof SparseMatrix\n * @param {Object} json An object structured like\n * `{\"mathjs\": \"SparseMatrix\", \"values\": [], \"index\": [], \"ptr\": [], \"size\": []}`,\n * where mathjs is optional\n * @returns {SparseMatrix}\n */\n\n\n SparseMatrix.fromJSON = function (json) {\n return new SparseMatrix(json);\n };\n /**\n * Create a diagonal matrix.\n *\n * @memberof SparseMatrix\n * @param {Array} size The matrix size.\n * @param {number | Array | Matrix } value The values for the diagonal.\n * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in.\n * @param {number} [defaultValue] The default value for non-diagonal\n * @param {string} [datatype] The Matrix datatype, values must be of this datatype.\n *\n * @returns {SparseMatrix}\n */\n\n\n SparseMatrix.diagonal = function (size, value, k, defaultValue, datatype) {\n if (!isArray(size)) {\n throw new TypeError('Array expected, size parameter');\n }\n\n if (size.length !== 2) {\n throw new Error('Only two dimensions matrix are supported');\n } // map size & validate\n\n\n size = size.map(function (s) {\n // check it is a big number\n if (isBigNumber(s)) {\n // convert it\n s = s.toNumber();\n } // validate arguments\n\n\n if (!isNumber(s) || !isInteger(s) || s < 1) {\n throw new Error('Size values must be positive integers');\n }\n\n return s;\n }); // validate k if any\n\n if (k) {\n // convert BigNumber to a number\n if (isBigNumber(k)) {\n k = k.toNumber();\n } // is must be an integer\n\n\n if (!isNumber(k) || !isInteger(k)) {\n throw new TypeError('The parameter k must be an integer number');\n }\n } else {\n // default value\n k = 0;\n } // equal signature to use\n\n\n var eq = equalScalar; // zero value\n\n var zero = 0;\n\n if (isString(datatype)) {\n // find signature that matches (datatype, datatype)\n eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype\n\n zero = typed.convert(0, datatype);\n }\n\n var kSuper = k > 0 ? k : 0;\n var kSub = k < 0 ? -k : 0; // rows and columns\n\n var rows = size[0];\n var columns = size[1]; // number of non-zero items\n\n var n = Math.min(rows - kSub, columns - kSuper); // value extraction function\n\n var _value; // check value\n\n\n if (isArray(value)) {\n // validate array\n if (value.length !== n) {\n // number of values in array must be n\n throw new Error('Invalid value array length');\n } // define function\n\n\n _value = function _value(i) {\n // return value @ i\n return value[i];\n };\n } else if (isMatrix(value)) {\n // matrix size\n var ms = value.size(); // validate matrix\n\n if (ms.length !== 1 || ms[0] !== n) {\n // number of values in array must be n\n throw new Error('Invalid matrix length');\n } // define function\n\n\n _value = function _value(i) {\n // return value @ i\n return value.get([i]);\n };\n } else {\n // define function\n _value = function _value() {\n // return value\n return value;\n };\n } // create arrays\n\n\n var values = [];\n var index = [];\n var ptr = []; // loop items\n\n for (var j = 0; j < columns; j++) {\n // number of rows with value\n ptr.push(values.length); // diagonal index\n\n var i = j - kSuper; // check we need to set diagonal value\n\n if (i >= 0 && i < n) {\n // get value @ i\n var v = _value(i); // check for zero\n\n\n if (!eq(v, zero)) {\n // column\n index.push(i + kSub); // add value\n\n values.push(v);\n }\n }\n } // last value should be number of values\n\n\n ptr.push(values.length); // create SparseMatrix\n\n return new SparseMatrix({\n values: values,\n index: index,\n ptr: ptr,\n size: [rows, columns]\n });\n };\n /**\n * Swap rows i and j in Matrix.\n *\n * @memberof SparseMatrix\n * @param {number} i Matrix row index 1\n * @param {number} j Matrix row index 2\n *\n * @return {Matrix} The matrix reference\n */\n\n\n SparseMatrix.prototype.swapRows = function (i, j) {\n // check index\n if (!isNumber(i) || !isInteger(i) || !isNumber(j) || !isInteger(j)) {\n throw new Error('Row index must be positive integers');\n } // check dimensions\n\n\n if (this._size.length !== 2) {\n throw new Error('Only two dimensional matrix is supported');\n } // validate index\n\n\n validateIndex(i, this._size[0]);\n validateIndex(j, this._size[0]); // swap rows\n\n SparseMatrix._swapRows(i, j, this._size[1], this._values, this._index, this._ptr); // return current instance\n\n\n return this;\n };\n /**\n * Loop rows with data in column j.\n *\n * @param {number} j Column\n * @param {Array} values Matrix values\n * @param {Array} index Matrix row indeces\n * @param {Array} ptr Matrix column pointers\n * @param {Function} callback Callback function invoked for every row in column j\n */\n\n\n SparseMatrix._forEachRow = function (j, values, index, ptr, callback) {\n // indeces for column j\n var k0 = ptr[j];\n var k1 = ptr[j + 1]; // loop\n\n for (var k = k0; k < k1; k++) {\n // invoke callback\n callback(index[k], values[k]);\n }\n };\n /**\n * Swap rows x and y in Sparse Matrix data structures.\n *\n * @param {number} x Matrix row index 1\n * @param {number} y Matrix row index 2\n * @param {number} columns Number of columns in matrix\n * @param {Array} values Matrix values\n * @param {Array} index Matrix row indeces\n * @param {Array} ptr Matrix column pointers\n */\n\n\n SparseMatrix._swapRows = function (x, y, columns, values, index, ptr) {\n // loop columns\n for (var j = 0; j < columns; j++) {\n // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]\n var k0 = ptr[j];\n var k1 = ptr[j + 1]; // find value index @ x\n\n var kx = _getValueIndex(x, k0, k1, index); // find value index @ x\n\n\n var ky = _getValueIndex(y, k0, k1, index); // check both rows exist in matrix\n\n\n if (kx < k1 && ky < k1 && index[kx] === x && index[ky] === y) {\n // swap values (check for pattern matrix)\n if (values) {\n var v = values[kx];\n values[kx] = values[ky];\n values[ky] = v;\n } // next column\n\n\n continue;\n } // check x row exist & no y row\n\n\n if (kx < k1 && index[kx] === x && (ky >= k1 || index[ky] !== y)) {\n // value @ x (check for pattern matrix)\n var vx = values ? values[kx] : undefined; // insert value @ y\n\n index.splice(ky, 0, y);\n\n if (values) {\n values.splice(ky, 0, vx);\n } // remove value @ x (adjust array index if needed)\n\n\n index.splice(ky <= kx ? kx + 1 : kx, 1);\n\n if (values) {\n values.splice(ky <= kx ? kx + 1 : kx, 1);\n } // next column\n\n\n continue;\n } // check y row exist & no x row\n\n\n if (ky < k1 && index[ky] === y && (kx >= k1 || index[kx] !== x)) {\n // value @ y (check for pattern matrix)\n var vy = values ? values[ky] : undefined; // insert value @ x\n\n index.splice(kx, 0, x);\n\n if (values) {\n values.splice(kx, 0, vy);\n } // remove value @ y (adjust array index if needed)\n\n\n index.splice(kx <= ky ? ky + 1 : ky, 1);\n\n if (values) {\n values.splice(kx <= ky ? ky + 1 : ky, 1);\n }\n }\n }\n };\n\n return SparseMatrix;\n}, {\n isClass: true\n});","import { factory } from '../../../utils/factory.js';\nvar name = 'matrix';\nvar dependencies = ['typed', 'Matrix', 'DenseMatrix', 'SparseMatrix'];\nexport var createMatrix = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n Matrix,\n DenseMatrix,\n SparseMatrix\n } = _ref;\n\n /**\n * Create a Matrix. The function creates a new `math.Matrix` object from\n * an `Array`. A Matrix has utility functions to manipulate the data in the\n * matrix, like getting the size and getting or setting values in the matrix.\n * Supported storage formats are 'dense' and 'sparse'.\n *\n * Syntax:\n *\n * math.matrix() // creates an empty matrix using default storage format (dense).\n * math.matrix(data) // creates a matrix with initial data using default storage format (dense).\n * math.matrix('dense') // creates an empty matrix using the given storage format.\n * math.matrix(data, 'dense') // creates a matrix with initial data using the given storage format.\n * math.matrix(data, 'sparse') // creates a sparse matrix with initial data.\n * math.matrix(data, 'sparse', 'number') // creates a sparse matrix with initial data, number data type.\n *\n * Examples:\n *\n * let m = math.matrix([[1, 2], [3, 4]])\n * m.size() // Array [2, 2]\n * m.resize([3, 2], 5)\n * m.valueOf() // Array [[1, 2], [3, 4], [5, 5]]\n * m.get([1, 0]) // number 3\n *\n * See also:\n *\n * bignumber, boolean, complex, index, number, string, unit, sparse\n *\n * @param {Array | Matrix} [data] A multi dimensional array\n * @param {string} [format] The Matrix storage format\n *\n * @return {Matrix} The created matrix\n */\n return typed(name, {\n '': function _() {\n return _create([]);\n },\n string: function string(format) {\n return _create([], format);\n },\n 'string, string': function stringString(format, datatype) {\n return _create([], format, datatype);\n },\n Array: function Array(data) {\n return _create(data);\n },\n Matrix: function Matrix(data) {\n return _create(data, data.storage());\n },\n 'Array | Matrix, string': _create,\n 'Array | Matrix, string, string': _create\n });\n /**\n * Create a new Matrix with given storage format\n * @param {Array} data\n * @param {string} [format]\n * @param {string} [datatype]\n * @returns {Matrix} Returns a new Matrix\n * @private\n */\n\n function _create(data, format, datatype) {\n // get storage format constructor\n if (format === 'dense' || format === 'default' || format === undefined) {\n return new DenseMatrix(data, datatype);\n }\n\n if (format === 'sparse') {\n return new SparseMatrix(data, datatype);\n }\n\n throw new TypeError('Unknown matrix type ' + JSON.stringify(format) + '.');\n }\n});","import { factory } from '../../../utils/factory.js';\nimport { DimensionError } from '../../../error/DimensionError.js';\nvar name = 'algorithm01';\nvar dependencies = ['typed'];\nexport var createAlgorithm01 = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij).\n * Callback function invoked NNZ times (number of nonzero items in SparseMatrix).\n *\n *\n * ┌ f(Dij, Sij) ; S(i,j) !== 0\n * C(i,j) = ┤\n * └ Dij ; otherwise\n *\n *\n * @param {Matrix} denseMatrix The DenseMatrix instance (D)\n * @param {Matrix} sparseMatrix The SparseMatrix instance (S)\n * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)\n * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij)\n *\n * @return {Matrix} DenseMatrix (C)\n *\n * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571\n */\n return function algorithm1(denseMatrix, sparseMatrix, callback, inverse) {\n // dense matrix arrays\n var adata = denseMatrix._data;\n var asize = denseMatrix._size;\n var adt = denseMatrix._datatype; // sparse matrix arrays\n\n var bvalues = sparseMatrix._values;\n var bindex = sparseMatrix._index;\n var bptr = sparseMatrix._ptr;\n var bsize = sparseMatrix._size;\n var bdt = sparseMatrix._datatype; // validate dimensions\n\n if (asize.length !== bsize.length) {\n throw new DimensionError(asize.length, bsize.length);\n } // check rows & columns\n\n\n if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {\n throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');\n } // sparse matrix cannot be a Pattern matrix\n\n\n if (!bvalues) {\n throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');\n } // rows & columns\n\n\n var rows = asize[0];\n var columns = asize[1]; // process data types\n\n var dt = typeof adt === 'string' && adt === bdt ? adt : undefined; // callback function\n\n var cf = dt ? typed.find(callback, [dt, dt]) : callback; // vars\n\n var i, j; // result (DenseMatrix)\n\n var cdata = []; // initialize c\n\n for (i = 0; i < rows; i++) {\n cdata[i] = [];\n } // workspace\n\n\n var x = []; // marks indicating we have a value in x for a given column\n\n var w = []; // loop columns in b\n\n for (j = 0; j < columns; j++) {\n // column mark\n var mark = j + 1; // values in column j\n\n for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {\n // row\n i = bindex[k]; // update workspace\n\n x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]); // mark i as updated\n\n w[i] = mark;\n } // loop rows\n\n\n for (i = 0; i < rows; i++) {\n // check row is in workspace\n if (w[i] === mark) {\n // c[i][j] was already calculated\n cdata[i][j] = x[i];\n } else {\n // item does not exist in S\n cdata[i][j] = adata[i][j];\n }\n }\n } // return dense matrix\n\n\n return denseMatrix.createDenseMatrix({\n data: cdata,\n size: [rows, columns],\n datatype: dt\n });\n };\n});","import { factory } from '../../../utils/factory.js';\nvar name = 'algorithm10';\nvar dependencies = ['typed', 'DenseMatrix'];\nexport var createAlgorithm10 = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n DenseMatrix\n } = _ref;\n\n /**\n * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).\n * Callback function invoked NZ times (number of nonzero items in S).\n *\n *\n * ┌ f(Sij, b) ; S(i,j) !== 0\n * C(i,j) = ┤\n * └ b ; otherwise\n *\n *\n * @param {Matrix} s The SparseMatrix instance (S)\n * @param {Scalar} b The Scalar value\n * @param {Function} callback The f(Aij,b) operation to invoke\n * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij)\n *\n * @return {Matrix} DenseMatrix (C)\n *\n * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813\n */\n return function algorithm10(s, b, callback, inverse) {\n // sparse matrix arrays\n var avalues = s._values;\n var aindex = s._index;\n var aptr = s._ptr;\n var asize = s._size;\n var adt = s._datatype; // sparse matrix cannot be a Pattern matrix\n\n if (!avalues) {\n throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');\n } // rows & columns\n\n\n var rows = asize[0];\n var columns = asize[1]; // datatype\n\n var dt; // callback signature to use\n\n var cf = callback; // process data types\n\n if (typeof adt === 'string') {\n // datatype\n dt = adt; // convert b to the same datatype\n\n b = typed.convert(b, dt); // callback\n\n cf = typed.find(callback, [dt, dt]);\n } // result arrays\n\n\n var cdata = []; // workspaces\n\n var x = []; // marks indicating we have a value in x for a given column\n\n var w = []; // loop columns\n\n for (var j = 0; j < columns; j++) {\n // columns mark\n var mark = j + 1; // values in j\n\n for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {\n // row\n var r = aindex[k]; // update workspace\n\n x[r] = avalues[k];\n w[r] = mark;\n } // loop rows\n\n\n for (var i = 0; i < rows; i++) {\n // initialize C on first column\n if (j === 0) {\n // create row array\n cdata[i] = [];\n } // check sparse matrix has a value @ i,j\n\n\n if (w[i] === mark) {\n // invoke callback, update C\n cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b);\n } else {\n // dense matrix value @ i, j\n cdata[i][j] = b;\n }\n }\n } // return dense matrix\n\n\n return new DenseMatrix({\n data: cdata,\n size: [rows, columns],\n datatype: dt\n });\n };\n});","import { factory } from '../../../utils/factory.js';\nimport { DimensionError } from '../../../error/DimensionError.js';\nvar name = 'algorithm13';\nvar dependencies = ['typed'];\nexport var createAlgorithm13 = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z).\n * Callback function invoked MxN times.\n *\n * C(i,j,...z) = f(Aij..z, Bij..z)\n *\n * @param {Matrix} a The DenseMatrix instance (A)\n * @param {Matrix} b The DenseMatrix instance (B)\n * @param {Function} callback The f(Aij..z,Bij..z) operation to invoke\n *\n * @return {Matrix} DenseMatrix (C)\n *\n * https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658\n */\n return function algorithm13(a, b, callback) {\n // a arrays\n var adata = a._data;\n var asize = a._size;\n var adt = a._datatype; // b arrays\n\n var bdata = b._data;\n var bsize = b._size;\n var bdt = b._datatype; // c arrays\n\n var csize = []; // validate dimensions\n\n if (asize.length !== bsize.length) {\n throw new DimensionError(asize.length, bsize.length);\n } // validate each one of the dimension sizes\n\n\n for (var s = 0; s < asize.length; s++) {\n // must match\n if (asize[s] !== bsize[s]) {\n throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');\n } // update dimension in c\n\n\n csize[s] = asize[s];\n } // datatype\n\n\n var dt; // callback signature to use\n\n var cf = callback; // process data types\n\n if (typeof adt === 'string' && adt === bdt) {\n // datatype\n dt = adt; // callback\n\n cf = typed.find(callback, [dt, dt]);\n } // populate cdata, iterate through dimensions\n\n\n var cdata = csize.length > 0 ? _iterate(cf, 0, csize, csize[0], adata, bdata) : []; // c matrix\n\n return a.createDenseMatrix({\n data: cdata,\n size: csize,\n datatype: dt\n });\n }; // recursive function\n\n function _iterate(f, level, s, n, av, bv) {\n // initialize array for this level\n var cv = []; // check we reach the last level\n\n if (level === s.length - 1) {\n // loop arrays in last level\n for (var i = 0; i < n; i++) {\n // invoke callback and store value\n cv[i] = f(av[i], bv[i]);\n }\n } else {\n // iterate current level\n for (var j = 0; j < n; j++) {\n // iterate next level\n cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv[j]);\n }\n }\n\n return cv;\n }\n});","import { factory } from '../../../utils/factory.js';\nimport { clone } from '../../../utils/object.js';\nvar name = 'algorithm14';\nvar dependencies = ['typed'];\nexport var createAlgorithm14 = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, b).\n * Callback function invoked MxN times.\n *\n * C(i,j,...z) = f(Aij..z, b)\n *\n * @param {Matrix} a The DenseMatrix instance (A)\n * @param {Scalar} b The Scalar value\n * @param {Function} callback The f(Aij..z,b) operation to invoke\n * @param {boolean} inverse A true value indicates callback should be invoked f(b,Aij..z)\n *\n * @return {Matrix} DenseMatrix (C)\n *\n * https://github.com/josdejong/mathjs/pull/346#issuecomment-97659042\n */\n return function algorithm14(a, b, callback, inverse) {\n // a arrays\n var adata = a._data;\n var asize = a._size;\n var adt = a._datatype; // datatype\n\n var dt; // callback signature to use\n\n var cf = callback; // process data types\n\n if (typeof adt === 'string') {\n // datatype\n dt = adt; // convert b to the same datatype\n\n b = typed.convert(b, dt); // callback\n\n cf = typed.find(callback, [dt, dt]);\n } // populate cdata, iterate through dimensions\n\n\n var cdata = asize.length > 0 ? _iterate(cf, 0, asize, asize[0], adata, b, inverse) : []; // c matrix\n\n return a.createDenseMatrix({\n data: cdata,\n size: clone(asize),\n datatype: dt\n });\n }; // recursive function\n\n function _iterate(f, level, s, n, av, bv, inverse) {\n // initialize array for this level\n var cv = []; // check we reach the last level\n\n if (level === s.length - 1) {\n // loop arrays in last level\n for (var i = 0; i < n; i++) {\n // invoke callback and store value\n cv[i] = inverse ? f(bv, av[i]) : f(av[i], bv);\n }\n } else {\n // iterate current level\n for (var j = 0; j < n; j++) {\n // iterate next level\n cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv, inverse);\n }\n }\n\n return cv;\n }\n});","import { factory } from '../../../utils/factory.js';\nimport { DimensionError } from '../../../error/DimensionError.js';\nvar name = 'algorithm03';\nvar dependencies = ['typed'];\nexport var createAlgorithm03 = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Iterates over SparseMatrix items and invokes the callback function f(Dij, Sij).\n * Callback function invoked M*N times.\n *\n *\n * ┌ f(Dij, Sij) ; S(i,j) !== 0\n * C(i,j) = ┤\n * └ f(Dij, 0) ; otherwise\n *\n *\n * @param {Matrix} denseMatrix The DenseMatrix instance (D)\n * @param {Matrix} sparseMatrix The SparseMatrix instance (C)\n * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)\n * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij)\n *\n * @return {Matrix} DenseMatrix (C)\n *\n * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571\n */\n return function algorithm03(denseMatrix, sparseMatrix, callback, inverse) {\n // dense matrix arrays\n var adata = denseMatrix._data;\n var asize = denseMatrix._size;\n var adt = denseMatrix._datatype; // sparse matrix arrays\n\n var bvalues = sparseMatrix._values;\n var bindex = sparseMatrix._index;\n var bptr = sparseMatrix._ptr;\n var bsize = sparseMatrix._size;\n var bdt = sparseMatrix._datatype; // validate dimensions\n\n if (asize.length !== bsize.length) {\n throw new DimensionError(asize.length, bsize.length);\n } // check rows & columns\n\n\n if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {\n throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');\n } // sparse matrix cannot be a Pattern matrix\n\n\n if (!bvalues) {\n throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');\n } // rows & columns\n\n\n var rows = asize[0];\n var columns = asize[1]; // datatype\n\n var dt; // zero value\n\n var zero = 0; // callback signature to use\n\n var cf = callback; // process data types\n\n if (typeof adt === 'string' && adt === bdt) {\n // datatype\n dt = adt; // convert 0 to the same datatype\n\n zero = typed.convert(0, dt); // callback\n\n cf = typed.find(callback, [dt, dt]);\n } // result (DenseMatrix)\n\n\n var cdata = []; // initialize dense matrix\n\n for (var z = 0; z < rows; z++) {\n // initialize row\n cdata[z] = [];\n } // workspace\n\n\n var x = []; // marks indicating we have a value in x for a given column\n\n var w = []; // loop columns in b\n\n for (var j = 0; j < columns; j++) {\n // column mark\n var mark = j + 1; // values in column j\n\n for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {\n // row\n var i = bindex[k]; // update workspace\n\n x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]);\n w[i] = mark;\n } // process workspace\n\n\n for (var y = 0; y < rows; y++) {\n // check we have a calculated value for current row\n if (w[y] === mark) {\n // use calculated value\n cdata[y][j] = x[y];\n } else {\n // calculate value\n cdata[y][j] = inverse ? cf(zero, adata[y][j]) : cf(adata[y][j], zero);\n }\n }\n } // return dense matrix\n\n\n return denseMatrix.createDenseMatrix({\n data: cdata,\n size: [rows, columns],\n datatype: dt\n });\n };\n});","import { factory } from '../../../utils/factory.js';\nimport { DimensionError } from '../../../error/DimensionError.js';\nvar name = 'algorithm05';\nvar dependencies = ['typed', 'equalScalar'];\nexport var createAlgorithm05 = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n equalScalar\n } = _ref;\n\n /**\n * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).\n * Callback function invoked MAX(NNZA, NNZB) times\n *\n *\n * ┌ f(Aij, Bij) ; A(i,j) !== 0 || B(i,j) !== 0\n * C(i,j) = ┤\n * └ 0 ; otherwise\n *\n *\n * @param {Matrix} a The SparseMatrix instance (A)\n * @param {Matrix} b The SparseMatrix instance (B)\n * @param {Function} callback The f(Aij,Bij) operation to invoke\n *\n * @return {Matrix} SparseMatrix (C)\n *\n * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294\n */\n return function algorithm05(a, b, callback) {\n // sparse matrix arrays\n var avalues = a._values;\n var aindex = a._index;\n var aptr = a._ptr;\n var asize = a._size;\n var adt = a._datatype; // sparse matrix arrays\n\n var bvalues = b._values;\n var bindex = b._index;\n var bptr = b._ptr;\n var bsize = b._size;\n var bdt = b._datatype; // validate dimensions\n\n if (asize.length !== bsize.length) {\n throw new DimensionError(asize.length, bsize.length);\n } // check rows & columns\n\n\n if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {\n throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');\n } // rows & columns\n\n\n var rows = asize[0];\n var columns = asize[1]; // datatype\n\n var dt; // equal signature to use\n\n var eq = equalScalar; // zero value\n\n var zero = 0; // callback signature to use\n\n var cf = callback; // process data types\n\n if (typeof adt === 'string' && adt === bdt) {\n // datatype\n dt = adt; // find signature that matches (dt, dt)\n\n eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype\n\n zero = typed.convert(0, dt); // callback\n\n cf = typed.find(callback, [dt, dt]);\n } // result arrays\n\n\n var cvalues = avalues && bvalues ? [] : undefined;\n var cindex = [];\n var cptr = []; // workspaces\n\n var xa = cvalues ? [] : undefined;\n var xb = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column\n\n var wa = [];\n var wb = []; // vars\n\n var i, j, k, k1; // loop columns\n\n for (j = 0; j < columns; j++) {\n // update cptr\n cptr[j] = cindex.length; // columns mark\n\n var mark = j + 1; // loop values A(:,j)\n\n for (k = aptr[j], k1 = aptr[j + 1]; k < k1; k++) {\n // row\n i = aindex[k]; // push index\n\n cindex.push(i); // update workspace\n\n wa[i] = mark; // check we need to process values\n\n if (xa) {\n xa[i] = avalues[k];\n }\n } // loop values B(:,j)\n\n\n for (k = bptr[j], k1 = bptr[j + 1]; k < k1; k++) {\n // row\n i = bindex[k]; // check row existed in A\n\n if (wa[i] !== mark) {\n // push index\n cindex.push(i);\n } // update workspace\n\n\n wb[i] = mark; // check we need to process values\n\n if (xb) {\n xb[i] = bvalues[k];\n }\n } // check we need to process values (non pattern matrix)\n\n\n if (cvalues) {\n // initialize first index in j\n k = cptr[j]; // loop index in j\n\n while (k < cindex.length) {\n // row\n i = cindex[k]; // marks\n\n var wai = wa[i];\n var wbi = wb[i]; // check Aij or Bij are nonzero\n\n if (wai === mark || wbi === mark) {\n // matrix values @ i,j\n var va = wai === mark ? xa[i] : zero;\n var vb = wbi === mark ? xb[i] : zero; // Cij\n\n var vc = cf(va, vb); // check for zero\n\n if (!eq(vc, zero)) {\n // push value\n cvalues.push(vc); // increment pointer\n\n k++;\n } else {\n // remove value @ i, do not increment pointer\n cindex.splice(k, 1);\n }\n }\n }\n }\n } // update cptr\n\n\n cptr[columns] = cindex.length; // return sparse matrix\n\n return a.createSparseMatrix({\n values: cvalues,\n index: cindex,\n ptr: cptr,\n size: [rows, columns],\n datatype: dt\n });\n };\n});","import { factory } from '../../../utils/factory.js';\nvar name = 'algorithm11';\nvar dependencies = ['typed', 'equalScalar'];\nexport var createAlgorithm11 = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n equalScalar\n } = _ref;\n\n /**\n * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).\n * Callback function invoked NZ times (number of nonzero items in S).\n *\n *\n * ┌ f(Sij, b) ; S(i,j) !== 0\n * C(i,j) = ┤\n * └ 0 ; otherwise\n *\n *\n * @param {Matrix} s The SparseMatrix instance (S)\n * @param {Scalar} b The Scalar value\n * @param {Function} callback The f(Aij,b) operation to invoke\n * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij)\n *\n * @return {Matrix} SparseMatrix (C)\n *\n * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813\n */\n return function algorithm11(s, b, callback, inverse) {\n // sparse matrix arrays\n var avalues = s._values;\n var aindex = s._index;\n var aptr = s._ptr;\n var asize = s._size;\n var adt = s._datatype; // sparse matrix cannot be a Pattern matrix\n\n if (!avalues) {\n throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');\n } // rows & columns\n\n\n var rows = asize[0];\n var columns = asize[1]; // datatype\n\n var dt; // equal signature to use\n\n var eq = equalScalar; // zero value\n\n var zero = 0; // callback signature to use\n\n var cf = callback; // process data types\n\n if (typeof adt === 'string') {\n // datatype\n dt = adt; // find signature that matches (dt, dt)\n\n eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype\n\n zero = typed.convert(0, dt); // convert b to the same datatype\n\n b = typed.convert(b, dt); // callback\n\n cf = typed.find(callback, [dt, dt]);\n } // result arrays\n\n\n var cvalues = [];\n var cindex = [];\n var cptr = []; // loop columns\n\n for (var j = 0; j < columns; j++) {\n // initialize ptr\n cptr[j] = cindex.length; // values in j\n\n for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {\n // row\n var i = aindex[k]; // invoke callback\n\n var v = inverse ? cf(b, avalues[k]) : cf(avalues[k], b); // check value is zero\n\n if (!eq(v, zero)) {\n // push index & value\n cindex.push(i);\n cvalues.push(v);\n }\n }\n } // update ptr\n\n\n cptr[columns] = cindex.length; // return sparse matrix\n\n return s.createSparseMatrix({\n values: cvalues,\n index: cindex,\n ptr: cptr,\n size: [rows, columns],\n datatype: dt\n });\n };\n});","import { factory } from '../../../utils/factory.js';\nvar name = 'algorithm12';\nvar dependencies = ['typed', 'DenseMatrix'];\nexport var createAlgorithm12 = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n DenseMatrix\n } = _ref;\n\n /**\n * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).\n * Callback function invoked MxN times.\n *\n *\n * ┌ f(Sij, b) ; S(i,j) !== 0\n * C(i,j) = ┤\n * └ f(0, b) ; otherwise\n *\n *\n * @param {Matrix} s The SparseMatrix instance (S)\n * @param {Scalar} b The Scalar value\n * @param {Function} callback The f(Aij,b) operation to invoke\n * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij)\n *\n * @return {Matrix} DenseMatrix (C)\n *\n * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813\n */\n return function algorithm12(s, b, callback, inverse) {\n // sparse matrix arrays\n var avalues = s._values;\n var aindex = s._index;\n var aptr = s._ptr;\n var asize = s._size;\n var adt = s._datatype; // sparse matrix cannot be a Pattern matrix\n\n if (!avalues) {\n throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');\n } // rows & columns\n\n\n var rows = asize[0];\n var columns = asize[1]; // datatype\n\n var dt; // callback signature to use\n\n var cf = callback; // process data types\n\n if (typeof adt === 'string') {\n // datatype\n dt = adt; // convert b to the same datatype\n\n b = typed.convert(b, dt); // callback\n\n cf = typed.find(callback, [dt, dt]);\n } // result arrays\n\n\n var cdata = []; // workspaces\n\n var x = []; // marks indicating we have a value in x for a given column\n\n var w = []; // loop columns\n\n for (var j = 0; j < columns; j++) {\n // columns mark\n var mark = j + 1; // values in j\n\n for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {\n // row\n var r = aindex[k]; // update workspace\n\n x[r] = avalues[k];\n w[r] = mark;\n } // loop rows\n\n\n for (var i = 0; i < rows; i++) {\n // initialize C on first column\n if (j === 0) {\n // create row array\n cdata[i] = [];\n } // check sparse matrix has a value @ i,j\n\n\n if (w[i] === mark) {\n // invoke callback, update C\n cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b);\n } else {\n // dense matrix value @ i, j\n cdata[i][j] = inverse ? cf(b, 0) : cf(0, b);\n }\n }\n } // return dense matrix\n\n\n return new DenseMatrix({\n data: cdata,\n size: [rows, columns],\n datatype: dt\n });\n };\n});","import { factory } from '../../../utils/factory.js';\nimport { DimensionError } from '../../../error/DimensionError.js';\nvar name = 'algorithm07';\nvar dependencies = ['typed', 'DenseMatrix'];\nexport var createAlgorithm07 = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n DenseMatrix\n } = _ref;\n\n /**\n * Iterates over SparseMatrix A and SparseMatrix B items (zero and nonzero) and invokes the callback function f(Aij, Bij).\n * Callback function invoked MxN times.\n *\n * C(i,j) = f(Aij, Bij)\n *\n * @param {Matrix} a The SparseMatrix instance (A)\n * @param {Matrix} b The SparseMatrix instance (B)\n * @param {Function} callback The f(Aij,Bij) operation to invoke\n *\n * @return {Matrix} DenseMatrix (C)\n *\n * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294\n */\n return function algorithm07(a, b, callback) {\n // sparse matrix arrays\n var asize = a._size;\n var adt = a._datatype; // sparse matrix arrays\n\n var bsize = b._size;\n var bdt = b._datatype; // validate dimensions\n\n if (asize.length !== bsize.length) {\n throw new DimensionError(asize.length, bsize.length);\n } // check rows & columns\n\n\n if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {\n throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');\n } // rows & columns\n\n\n var rows = asize[0];\n var columns = asize[1]; // datatype\n\n var dt; // zero value\n\n var zero = 0; // callback signature to use\n\n var cf = callback; // process data types\n\n if (typeof adt === 'string' && adt === bdt) {\n // datatype\n dt = adt; // convert 0 to the same datatype\n\n zero = typed.convert(0, dt); // callback\n\n cf = typed.find(callback, [dt, dt]);\n } // vars\n\n\n var i, j; // result arrays\n\n var cdata = []; // initialize c\n\n for (i = 0; i < rows; i++) {\n cdata[i] = [];\n } // workspaces\n\n\n var xa = [];\n var xb = []; // marks indicating we have a value in x for a given column\n\n var wa = [];\n var wb = []; // loop columns\n\n for (j = 0; j < columns; j++) {\n // columns mark\n var mark = j + 1; // scatter the values of A(:,j) into workspace\n\n _scatter(a, j, wa, xa, mark); // scatter the values of B(:,j) into workspace\n\n\n _scatter(b, j, wb, xb, mark); // loop rows\n\n\n for (i = 0; i < rows; i++) {\n // matrix values @ i,j\n var va = wa[i] === mark ? xa[i] : zero;\n var vb = wb[i] === mark ? xb[i] : zero; // invoke callback\n\n cdata[i][j] = cf(va, vb);\n }\n } // return dense matrix\n\n\n return new DenseMatrix({\n data: cdata,\n size: [rows, columns],\n datatype: dt\n });\n };\n\n function _scatter(m, j, w, x, mark) {\n // a arrays\n var values = m._values;\n var index = m._index;\n var ptr = m._ptr; // loop values in column j\n\n for (var k = ptr[j], k1 = ptr[j + 1]; k < k1; k++) {\n // row\n var i = index[k]; // update workspace\n\n w[i] = mark;\n x[i] = values[k];\n }\n }\n});","import { isMatrix } from '../../utils/is.js';\nimport { arraySize } from '../../utils/array.js';\nimport { isInteger } from '../../utils/number.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'diag';\nvar dependencies = ['typed', 'matrix', 'DenseMatrix', 'SparseMatrix'];\nexport var createDiag = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n DenseMatrix,\n SparseMatrix\n } = _ref;\n\n /**\n * Create a diagonal matrix or retrieve the diagonal of a matrix\n *\n * When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.\n * When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.\n * When k is positive, the values are placed on the super diagonal.\n * When k is negative, the values are placed on the sub diagonal.\n *\n * Syntax:\n *\n * math.diag(X)\n * math.diag(X, format)\n * math.diag(X, k)\n * math.diag(X, k, format)\n *\n * Examples:\n *\n * // create a diagonal matrix\n * math.diag([1, 2, 3]) // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]\n * math.diag([1, 2, 3], 1) // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]\n * math.diag([1, 2, 3], -1) // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]]\n *\n * // retrieve the diagonal from a matrix\n * const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n * math.diag(a) // returns [1, 5, 9]\n *\n * See also:\n *\n * ones, zeros, identity\n *\n * @param {Matrix | Array} x A two dimensional matrix or a vector\n * @param {number | BigNumber} [k=0] The diagonal where the vector will be filled\n * in or retrieved.\n * @param {string} [format='dense'] The matrix storage format.\n *\n * @returns {Matrix | Array} Diagonal matrix from input vector, or diagonal from input matrix.\n */\n return typed(name, {\n // FIXME: simplify this huge amount of signatures as soon as typed-function supports optional arguments\n Array: function Array(x) {\n return _diag(x, 0, arraySize(x), null);\n },\n 'Array, number': function ArrayNumber(x, k) {\n return _diag(x, k, arraySize(x), null);\n },\n 'Array, BigNumber': function ArrayBigNumber(x, k) {\n return _diag(x, k.toNumber(), arraySize(x), null);\n },\n 'Array, string': function ArrayString(x, format) {\n return _diag(x, 0, arraySize(x), format);\n },\n 'Array, number, string': function ArrayNumberString(x, k, format) {\n return _diag(x, k, arraySize(x), format);\n },\n 'Array, BigNumber, string': function ArrayBigNumberString(x, k, format) {\n return _diag(x, k.toNumber(), arraySize(x), format);\n },\n Matrix: function Matrix(x) {\n return _diag(x, 0, x.size(), x.storage());\n },\n 'Matrix, number': function MatrixNumber(x, k) {\n return _diag(x, k, x.size(), x.storage());\n },\n 'Matrix, BigNumber': function MatrixBigNumber(x, k) {\n return _diag(x, k.toNumber(), x.size(), x.storage());\n },\n 'Matrix, string': function MatrixString(x, format) {\n return _diag(x, 0, x.size(), format);\n },\n 'Matrix, number, string': function MatrixNumberString(x, k, format) {\n return _diag(x, k, x.size(), format);\n },\n 'Matrix, BigNumber, string': function MatrixBigNumberString(x, k, format) {\n return _diag(x, k.toNumber(), x.size(), format);\n }\n });\n /**\n * Creeate diagonal matrix from a vector or vice versa\n * @param {Array | Matrix} x\n * @param {number} k\n * @param {string} format Storage format for matrix. If null,\n * an Array is returned\n * @returns {Array | Matrix}\n * @private\n */\n\n function _diag(x, k, size, format) {\n if (!isInteger(k)) {\n throw new TypeError('Second parameter in function diag must be an integer');\n }\n\n var kSuper = k > 0 ? k : 0;\n var kSub = k < 0 ? -k : 0; // check dimensions\n\n switch (size.length) {\n case 1:\n return _createDiagonalMatrix(x, k, format, size[0], kSub, kSuper);\n\n case 2:\n return _getDiagonal(x, k, format, size, kSub, kSuper);\n }\n\n throw new RangeError('Matrix for function diag must be 2 dimensional');\n }\n\n function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {\n // matrix size\n var ms = [l + kSub, l + kSuper];\n\n if (format && format !== 'sparse' && format !== 'dense') {\n throw new TypeError(\"Unknown matrix type \".concat(format, \"\\\"\"));\n } // create diagonal matrix\n\n\n var m = format === 'sparse' ? SparseMatrix.diagonal(ms, x, k) : DenseMatrix.diagonal(ms, x, k); // check we need to return a matrix\n\n return format !== null ? m : m.valueOf();\n }\n\n function _getDiagonal(x, k, format, s, kSub, kSuper) {\n // check x is a Matrix\n if (isMatrix(x)) {\n // get diagonal matrix\n var dm = x.diagonal(k); // check we need to return a matrix\n\n if (format !== null) {\n // check we need to change matrix format\n if (format !== dm.storage()) {\n return matrix(dm, format);\n }\n\n return dm;\n }\n\n return dm.valueOf();\n } // vector size\n\n\n var n = Math.min(s[0] - kSub, s[1] - kSuper); // diagonal values\n\n var vector = []; // loop diagonal\n\n for (var i = 0; i < n; i++) {\n vector[i] = x[i + kSub][i + kSuper];\n } // check we need to return a matrix\n\n\n return format !== null ? matrix(vector) : vector;\n }\n});","import { isBigNumber } from '../../utils/is.js';\nimport { resize } from '../../utils/array.js';\nimport { isInteger } from '../../utils/number.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'identity';\nvar dependencies = ['typed', 'config', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix'];\nexport var createIdentity = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n matrix,\n BigNumber,\n DenseMatrix,\n SparseMatrix\n } = _ref;\n\n /**\n * Create a 2-dimensional identity matrix with size m x n or n x n.\n * The matrix has ones on the diagonal and zeros elsewhere.\n *\n * Syntax:\n *\n * math.identity(n)\n * math.identity(n, format)\n * math.identity(m, n)\n * math.identity(m, n, format)\n * math.identity([m, n])\n * math.identity([m, n], format)\n *\n * Examples:\n *\n * math.identity(3) // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n * math.identity(3, 2) // returns [[1, 0], [0, 1], [0, 0]]\n *\n * const A = [[1, 2, 3], [4, 5, 6]]\n * math.identity(math.size(A)) // returns [[1, 0, 0], [0, 1, 0]]\n *\n * See also:\n *\n * diag, ones, zeros, size, range\n *\n * @param {...number | Matrix | Array} size The size for the matrix\n * @param {string} [format] The Matrix storage format\n *\n * @return {Matrix | Array | number} A matrix with ones on the diagonal.\n */\n return typed(name, {\n '': function _() {\n return config.matrix === 'Matrix' ? matrix([]) : [];\n },\n string: function string(format) {\n return matrix(format);\n },\n 'number | BigNumber': function numberBigNumber(rows) {\n return _identity(rows, rows, config.matrix === 'Matrix' ? 'dense' : undefined);\n },\n 'number | BigNumber, string': function numberBigNumberString(rows, format) {\n return _identity(rows, rows, format);\n },\n 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(rows, cols) {\n return _identity(rows, cols, config.matrix === 'Matrix' ? 'dense' : undefined);\n },\n 'number | BigNumber, number | BigNumber, string': function numberBigNumberNumberBigNumberString(rows, cols, format) {\n return _identity(rows, cols, format);\n },\n Array: function Array(size) {\n return _identityVector(size);\n },\n 'Array, string': function ArrayString(size, format) {\n return _identityVector(size, format);\n },\n Matrix: function Matrix(size) {\n return _identityVector(size.valueOf(), size.storage());\n },\n 'Matrix, string': function MatrixString(size, format) {\n return _identityVector(size.valueOf(), format);\n }\n });\n\n function _identityVector(size, format) {\n switch (size.length) {\n case 0:\n return format ? matrix(format) : [];\n\n case 1:\n return _identity(size[0], size[0], format);\n\n case 2:\n return _identity(size[0], size[1], format);\n\n default:\n throw new Error('Vector containing two values expected');\n }\n }\n /**\n * Create an identity matrix\n * @param {number | BigNumber} rows\n * @param {number | BigNumber} cols\n * @param {string} [format]\n * @returns {Matrix}\n * @private\n */\n\n\n function _identity(rows, cols, format) {\n // BigNumber constructor with the right precision\n var Big = isBigNumber(rows) || isBigNumber(cols) ? BigNumber : null;\n if (isBigNumber(rows)) rows = rows.toNumber();\n if (isBigNumber(cols)) cols = cols.toNumber();\n\n if (!isInteger(rows) || rows < 1) {\n throw new Error('Parameters in function identity must be positive integers');\n }\n\n if (!isInteger(cols) || cols < 1) {\n throw new Error('Parameters in function identity must be positive integers');\n }\n\n var one = Big ? new BigNumber(1) : 1;\n var defaultValue = Big ? new Big(0) : 0;\n var size = [rows, cols]; // check we need to return a matrix\n\n if (format) {\n // create diagonal matrix (use optimized implementation for storage format)\n if (format === 'sparse') {\n return SparseMatrix.diagonal(size, one, 0, defaultValue);\n }\n\n if (format === 'dense') {\n return DenseMatrix.diagonal(size, one, 0, defaultValue);\n }\n\n throw new TypeError(\"Unknown matrix type \\\"\".concat(format, \"\\\"\"));\n } // create and resize array\n\n\n var res = resize([], size, defaultValue); // fill in ones on the diagonal\n\n var minimum = rows < cols ? rows : cols; // fill diagonal\n\n for (var d = 0; d < minimum; d++) {\n res[d][d] = one;\n }\n\n return res;\n }\n});","export function noBignumber() {\n throw new Error('No \"bignumber\" implementation available');\n}\nexport function noFraction() {\n throw new Error('No \"fraction\" implementation available');\n}\nexport function noMatrix() {\n throw new Error('No \"matrix\" implementation available');\n}\nexport function noIndex() {\n throw new Error('No \"index\" implementation available');\n}\nexport function noSubset() {\n throw new Error('No \"matrix\" implementation available');\n}","import { arraySize } from '../../utils/array.js';\nimport { factory } from '../../utils/factory.js';\nimport { noMatrix } from '../../utils/noop.js';\nvar name = 'size';\nvar dependencies = ['typed', 'config', '?matrix'];\nexport var createSize = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n matrix\n } = _ref;\n\n /**\n * Calculate the size of a matrix or scalar.\n *\n * Syntax:\n *\n * math.size(x)\n *\n * Examples:\n *\n * math.size(2.3) // returns []\n * math.size('hello world') // returns [11]\n *\n * const A = [[1, 2, 3], [4, 5, 6]]\n * math.size(A) // returns [2, 3]\n * math.size(math.range(1,6)) // returns [5]\n *\n * See also:\n *\n * count, resize, squeeze, subset\n *\n * @param {boolean | number | Complex | Unit | string | Array | Matrix} x A matrix\n * @return {Array | Matrix} A vector with size of `x`.\n */\n return typed(name, {\n Matrix: function Matrix(x) {\n return x.create(x.size());\n },\n Array: arraySize,\n string: function string(x) {\n return config.matrix === 'Array' ? [x.length] : matrix([x.length]);\n },\n 'number | Complex | BigNumber | Unit | boolean | null': function numberComplexBigNumberUnitBooleanNull(x) {\n // scalar\n return config.matrix === 'Array' ? [] : matrix ? matrix([]) : noMatrix();\n }\n });\n});","import { isBigNumber } from '../../utils/is.js';\nimport { isInteger } from '../../utils/number.js';\nimport { resize } from '../../utils/array.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'zeros';\nvar dependencies = ['typed', 'config', 'matrix', 'BigNumber'];\nexport var createZeros = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n matrix,\n BigNumber\n } = _ref;\n\n /**\n * Create a matrix filled with zeros. The created matrix can have one or\n * multiple dimensions.\n *\n * Syntax:\n *\n * math.zeros(m)\n * math.zeros(m, format)\n * math.zeros(m, n)\n * math.zeros(m, n, format)\n * math.zeros([m, n])\n * math.zeros([m, n], format)\n *\n * Examples:\n *\n * math.zeros(3) // returns [0, 0, 0]\n * math.zeros(3, 2) // returns [[0, 0], [0, 0], [0, 0]]\n * math.zeros(3, 'dense') // returns [0, 0, 0]\n *\n * const A = [[1, 2, 3], [4, 5, 6]]\n * math.zeros(math.size(A)) // returns [[0, 0, 0], [0, 0, 0]]\n *\n * See also:\n *\n * ones, identity, size, range\n *\n * @param {...number | Array} size The size of each dimension of the matrix\n * @param {string} [format] The Matrix storage format\n *\n * @return {Array | Matrix} A matrix filled with zeros\n */\n return typed(name, {\n '': function _() {\n return config.matrix === 'Array' ? _zeros([]) : _zeros([], 'default');\n },\n // math.zeros(m, n, p, ..., format)\n // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this\n '...number | BigNumber | string': function numberBigNumberString(size) {\n var last = size[size.length - 1];\n\n if (typeof last === 'string') {\n var format = size.pop();\n return _zeros(size, format);\n } else if (config.matrix === 'Array') {\n return _zeros(size);\n } else {\n return _zeros(size, 'default');\n }\n },\n Array: _zeros,\n Matrix: function Matrix(size) {\n var format = size.storage();\n return _zeros(size.valueOf(), format);\n },\n 'Array | Matrix, string': function ArrayMatrixString(size, format) {\n return _zeros(size.valueOf(), format);\n }\n });\n /**\n * Create an Array or Matrix with zeros\n * @param {Array} size\n * @param {string} [format='default']\n * @return {Array | Matrix}\n * @private\n */\n\n function _zeros(size, format) {\n var hasBigNumbers = _normalize(size);\n\n var defaultValue = hasBigNumbers ? new BigNumber(0) : 0;\n\n _validate(size);\n\n if (format) {\n // return a matrix\n var m = matrix(format);\n\n if (size.length > 0) {\n return m.resize(size, defaultValue);\n }\n\n return m;\n } else {\n // return an Array\n var arr = [];\n\n if (size.length > 0) {\n return resize(arr, size, defaultValue);\n }\n\n return arr;\n }\n } // replace BigNumbers with numbers, returns true if size contained BigNumbers\n\n\n function _normalize(size) {\n var hasBigNumbers = false;\n size.forEach(function (value, index, arr) {\n if (isBigNumber(value)) {\n hasBigNumbers = true;\n arr[index] = value.toNumber();\n }\n });\n return hasBigNumbers;\n } // validate arguments\n\n\n function _validate(size) {\n size.forEach(function (value) {\n if (typeof value !== 'number' || !isInteger(value) || value < 0) {\n throw new Error('Parameters in function zeros must be positive integers');\n }\n });\n }\n}); // TODO: zeros contains almost the same code as ones. Reuse this?","import { factory } from '../../utils/factory.js';\nvar name = 'hex';\nvar dependencies = ['typed', 'format'];\n/**\n * Format a number as hexadecimal.\n *\n * Syntax:\n *\n * math.hex(value)\n *\n * Examples:\n *\n * //the following outputs \"0xF0\"\n * math.hex(240)\n *\n * See also:\n *\n * oct\n * bin\n *\n * @param {number} value Value to be stringified\n * @param {number} wordSize Optional word size (see `format`)\n * @return {string} The formatted value\n */\n\nexport var createHex = factory(name, dependencies, (_ref) => {\n var {\n typed,\n format\n } = _ref;\n return typed(name, {\n 'number | BigNumber': function numberBigNumber(n) {\n return format(n, {\n notation: 'hex'\n });\n },\n 'number | BigNumber, number': function numberBigNumberNumber(n, wordSize) {\n return format(n, {\n notation: 'hex',\n wordSize: wordSize\n });\n }\n });\n});","function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nimport { factory } from '../../utils/factory.js';\nimport { deepMap } from '../../utils/collection.js';\nimport { isInteger } from '../../utils/number.js';\nimport { createAlgorithm11 } from '../../type/matrix/utils/algorithm11.js';\nimport { createAlgorithm12 } from '../../type/matrix/utils/algorithm12.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nimport { roundNumber } from '../../plain/number/index.js';\nvar NO_INT = 'Number of decimals in function round must be an integer';\nvar name = 'round';\nvar dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'BigNumber', 'DenseMatrix'];\nexport var createRound = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n equalScalar,\n zeros,\n BigNumber,\n DenseMatrix\n } = _ref;\n var algorithm11 = createAlgorithm11({\n typed,\n equalScalar\n });\n var algorithm12 = createAlgorithm12({\n typed,\n DenseMatrix\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Round a value towards the nearest integer.\n * For matrices, the function is evaluated element wise.\n *\n * Syntax:\n *\n * math.round(x)\n * math.round(x, n)\n *\n * Examples:\n *\n * math.round(3.22) // returns number 3\n * math.round(3.82) // returns number 4\n * math.round(-4.2) // returns number -4\n * math.round(-4.7) // returns number -5\n * math.round(3.22, 1) // returns number 3.2\n * math.round(3.88, 1) // returns number 3.9\n * math.round(-4.21, 1) // returns number -4.2\n * math.round(-4.71, 1) // returns number -4.7\n * math.round(math.pi, 3) // returns number 3.142\n * math.round(123.45678, 2) // returns number 123.46\n *\n * const c = math.complex(3.2, -2.7)\n * math.round(c) // returns Complex 3 - 3i\n *\n * math.round([3.2, 3.8, -4.7]) // returns Array [3, 4, -5]\n *\n * See also:\n *\n * ceil, fix, floor\n *\n * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded\n * @param {number | BigNumber | Array} [n=0] Number of decimals\n * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value\n */\n\n return typed(name, _objectSpread(_objectSpread({}, roundNumberSignatures), {}, {\n Complex: function Complex(x) {\n return x.round();\n },\n 'Complex, number': function ComplexNumber(x, n) {\n if (n % 1) {\n throw new TypeError(NO_INT);\n }\n\n return x.round(n);\n },\n 'Complex, BigNumber': function ComplexBigNumber(x, n) {\n if (!n.isInteger()) {\n throw new TypeError(NO_INT);\n }\n\n var _n = n.toNumber();\n\n return x.round(_n);\n },\n 'number, BigNumber': function numberBigNumber(x, n) {\n if (!n.isInteger()) {\n throw new TypeError(NO_INT);\n }\n\n return new BigNumber(x).toDecimalPlaces(n.toNumber());\n },\n BigNumber: function BigNumber(x) {\n return x.toDecimalPlaces(0);\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, n) {\n if (!n.isInteger()) {\n throw new TypeError(NO_INT);\n }\n\n return x.toDecimalPlaces(n.toNumber());\n },\n Fraction: function Fraction(x) {\n return x.round();\n },\n 'Fraction, number': function FractionNumber(x, n) {\n if (n % 1) {\n throw new TypeError(NO_INT);\n }\n\n return x.round(n);\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n // deep map collection, skip zeros since round(0) = 0\n return deepMap(x, this, true);\n },\n 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {\n return algorithm11(x, y, this, false);\n },\n 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {\n return algorithm14(x, y, this, false);\n },\n 'number | Complex | BigNumber, SparseMatrix': function numberComplexBigNumberSparseMatrix(x, y) {\n // check scalar is zero\n if (equalScalar(x, 0)) {\n // do not execute algorithm, result will be a zero matrix\n return zeros(y.size(), y.storage());\n }\n\n return algorithm12(y, x, this, true);\n },\n 'number | Complex | BigNumber, DenseMatrix': function numberComplexBigNumberDenseMatrix(x, y) {\n // check scalar is zero\n if (equalScalar(x, 0)) {\n // do not execute algorithm, result will be a zero matrix\n return zeros(y.size(), y.storage());\n }\n\n return algorithm14(y, x, this, true);\n },\n 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) {\n // use matrix implementation\n return algorithm14(matrix(x), y, this, false).valueOf();\n },\n 'number | Complex | BigNumber, Array': function numberComplexBigNumberArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, this, true).valueOf();\n }\n }));\n});\nvar roundNumberSignatures = {\n number: roundNumber,\n 'number, number': function numberNumber(x, n) {\n if (!isInteger(n)) {\n throw new TypeError(NO_INT);\n }\n\n if (n < 0 || n > 15) {\n throw new Error('Number of decimals in function round must be in te range of 0-15');\n }\n\n return roundNumber(x, n);\n }\n};\nexport var createRoundNumber = /* #__PURE__ */factory(name, ['typed'], (_ref2) => {\n var {\n typed\n } = _ref2;\n return typed(name, roundNumberSignatures);\n});","import { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js';\nimport { nearlyEqual } from '../../utils/number.js';\nimport { factory } from '../../utils/factory.js';\nimport { createAlgorithm03 } from '../../type/matrix/utils/algorithm03.js';\nimport { createAlgorithm12 } from '../../type/matrix/utils/algorithm12.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nimport { createAlgorithm13 } from '../../type/matrix/utils/algorithm13.js';\nimport { createAlgorithm05 } from '../../type/matrix/utils/algorithm05.js';\nvar name = 'compare';\nvar dependencies = ['typed', 'config', 'matrix', 'equalScalar', 'BigNumber', 'Fraction', 'DenseMatrix'];\nexport var createCompare = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n equalScalar,\n matrix,\n BigNumber,\n Fraction,\n DenseMatrix\n } = _ref;\n var algorithm03 = createAlgorithm03({\n typed\n });\n var algorithm05 = createAlgorithm05({\n typed,\n equalScalar\n });\n var algorithm12 = createAlgorithm12({\n typed,\n DenseMatrix\n });\n var algorithm13 = createAlgorithm13({\n typed\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.\n *\n * x and y are considered equal when the relative difference between x and y\n * is smaller than the configured epsilon. The function cannot be used to\n * compare values smaller than approximately 2.22e-16.\n *\n * For matrices, the function is evaluated element wise.\n * Strings are compared by their numerical value.\n *\n * Syntax:\n *\n * math.compare(x, y)\n *\n * Examples:\n *\n * math.compare(6, 1) // returns 1\n * math.compare(2, 3) // returns -1\n * math.compare(7, 7) // returns 0\n * math.compare('10', '2') // returns 1\n * math.compare('1000', '1e3') // returns 0\n *\n * const a = math.unit('5 cm')\n * const b = math.unit('40 mm')\n * math.compare(a, b) // returns 1\n *\n * math.compare(2, [1, 2, 3]) // returns [1, 0, -1]\n *\n * See also:\n *\n * equal, unequal, smaller, smallerEq, larger, largerEq, compareNatural, compareText\n *\n * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} x First value to compare\n * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} y Second value to compare\n * @return {number | BigNumber | Fraction | Array | Matrix} Returns the result of the comparison:\n * 1 when x > y, -1 when x < y, and 0 when x == y.\n */\n\n return typed(name, {\n 'boolean, boolean': function booleanBoolean(x, y) {\n return x === y ? 0 : x > y ? 1 : -1;\n },\n 'number, number': function numberNumber(x, y) {\n return nearlyEqual(x, y, config.epsilon) ? 0 : x > y ? 1 : -1;\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {\n return bigNearlyEqual(x, y, config.epsilon) ? new BigNumber(0) : new BigNumber(x.cmp(y));\n },\n 'Fraction, Fraction': function FractionFraction(x, y) {\n return new Fraction(x.compare(y));\n },\n 'Complex, Complex': function ComplexComplex() {\n throw new TypeError('No ordering relation is defined for complex numbers');\n },\n 'Unit, Unit': function UnitUnit(x, y) {\n if (!x.equalBase(y)) {\n throw new Error('Cannot compare units with different base');\n }\n\n return this(x.value, y.value);\n },\n 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {\n return algorithm05(x, y, this);\n },\n 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {\n return algorithm03(y, x, this, true);\n },\n 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {\n return algorithm03(x, y, this, false);\n },\n 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {\n return algorithm13(x, y, this);\n },\n 'Array, Array': function ArrayArray(x, y) {\n // use matrix implementation\n return this(matrix(x), matrix(y)).valueOf();\n },\n 'Array, Matrix': function ArrayMatrix(x, y) {\n // use matrix implementation\n return this(matrix(x), y);\n },\n 'Matrix, Array': function MatrixArray(x, y) {\n // use matrix implementation\n return this(x, matrix(y));\n },\n 'SparseMatrix, any': function SparseMatrixAny(x, y) {\n return algorithm12(x, y, this, false);\n },\n 'DenseMatrix, any': function DenseMatrixAny(x, y) {\n return algorithm14(x, y, this, false);\n },\n 'any, SparseMatrix': function anySparseMatrix(x, y) {\n return algorithm12(y, x, this, true);\n },\n 'any, DenseMatrix': function anyDenseMatrix(x, y) {\n return algorithm14(y, x, this, true);\n },\n 'Array, any': function ArrayAny(x, y) {\n // use matrix implementation\n return algorithm14(matrix(x), y, this, false).valueOf();\n },\n 'any, Array': function anyArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, this, true).valueOf();\n }\n });\n});\nexport var createCompareNumber = /* #__PURE__ */factory(name, ['typed', 'config'], (_ref2) => {\n var {\n typed,\n config\n } = _ref2;\n return typed(name, {\n 'number, number': function numberNumber(x, y) {\n return nearlyEqual(x, y, config.epsilon) ? 0 : x > y ? 1 : -1;\n }\n });\n});","import { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js';\nimport { nearlyEqual } from '../../utils/number.js';\nimport { factory } from '../../utils/factory.js';\nimport { createAlgorithm03 } from '../../type/matrix/utils/algorithm03.js';\nimport { createAlgorithm07 } from '../../type/matrix/utils/algorithm07.js';\nimport { createAlgorithm12 } from '../../type/matrix/utils/algorithm12.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nimport { createAlgorithm13 } from '../../type/matrix/utils/algorithm13.js';\nvar name = 'smaller';\nvar dependencies = ['typed', 'config', 'matrix', 'DenseMatrix'];\nexport var createSmaller = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n matrix,\n DenseMatrix\n } = _ref;\n var algorithm03 = createAlgorithm03({\n typed\n });\n var algorithm07 = createAlgorithm07({\n typed,\n DenseMatrix\n });\n var algorithm12 = createAlgorithm12({\n typed,\n DenseMatrix\n });\n var algorithm13 = createAlgorithm13({\n typed\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Test whether value x is smaller than y.\n *\n * The function returns true when x is smaller than y and the relative\n * difference between x and y is smaller than the configured epsilon. The\n * function cannot be used to compare values smaller than approximately 2.22e-16.\n *\n * For matrices, the function is evaluated element wise.\n * Strings are compared by their numerical value.\n *\n * Syntax:\n *\n * math.smaller(x, y)\n *\n * Examples:\n *\n * math.smaller(2, 3) // returns true\n * math.smaller(5, 2 * 2) // returns false\n *\n * const a = math.unit('5 cm')\n * const b = math.unit('2 inch')\n * math.smaller(a, b) // returns true\n *\n * See also:\n *\n * equal, unequal, smallerEq, smaller, smallerEq, compare\n *\n * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare\n * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare\n * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false\n */\n\n return typed(name, {\n 'boolean, boolean': function booleanBoolean(x, y) {\n return x < y;\n },\n 'number, number': function numberNumber(x, y) {\n return x < y && !nearlyEqual(x, y, config.epsilon);\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {\n return x.lt(y) && !bigNearlyEqual(x, y, config.epsilon);\n },\n 'Fraction, Fraction': function FractionFraction(x, y) {\n return x.compare(y) === -1;\n },\n 'Complex, Complex': function ComplexComplex(x, y) {\n throw new TypeError('No ordering relation is defined for complex numbers');\n },\n 'Unit, Unit': function UnitUnit(x, y) {\n if (!x.equalBase(y)) {\n throw new Error('Cannot compare units with different base');\n }\n\n return this(x.value, y.value);\n },\n 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {\n return algorithm07(x, y, this);\n },\n 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {\n return algorithm03(y, x, this, true);\n },\n 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {\n return algorithm03(x, y, this, false);\n },\n 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {\n return algorithm13(x, y, this);\n },\n 'Array, Array': function ArrayArray(x, y) {\n // use matrix implementation\n return this(matrix(x), matrix(y)).valueOf();\n },\n 'Array, Matrix': function ArrayMatrix(x, y) {\n // use matrix implementation\n return this(matrix(x), y);\n },\n 'Matrix, Array': function MatrixArray(x, y) {\n // use matrix implementation\n return this(x, matrix(y));\n },\n 'SparseMatrix, any': function SparseMatrixAny(x, y) {\n return algorithm12(x, y, this, false);\n },\n 'DenseMatrix, any': function DenseMatrixAny(x, y) {\n return algorithm14(x, y, this, false);\n },\n 'any, SparseMatrix': function anySparseMatrix(x, y) {\n return algorithm12(y, x, this, true);\n },\n 'any, DenseMatrix': function anyDenseMatrix(x, y) {\n return algorithm14(y, x, this, true);\n },\n 'Array, any': function ArrayAny(x, y) {\n // use matrix implementation\n return algorithm14(matrix(x), y, this, false).valueOf();\n },\n 'any, Array': function anyArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, this, true).valueOf();\n }\n });\n});\nexport var createSmallerNumber = /* #__PURE__ */factory(name, ['typed', 'config'], (_ref2) => {\n var {\n typed,\n config\n } = _ref2;\n return typed(name, {\n 'number, number': function numberNumber(x, y) {\n return x < y && !nearlyEqual(x, y, config.epsilon);\n }\n });\n});","import { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js';\nimport { nearlyEqual } from '../../utils/number.js';\nimport { factory } from '../../utils/factory.js';\nimport { createAlgorithm03 } from '../../type/matrix/utils/algorithm03.js';\nimport { createAlgorithm07 } from '../../type/matrix/utils/algorithm07.js';\nimport { createAlgorithm12 } from '../../type/matrix/utils/algorithm12.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nimport { createAlgorithm13 } from '../../type/matrix/utils/algorithm13.js';\nvar name = 'larger';\nvar dependencies = ['typed', 'config', 'matrix', 'DenseMatrix'];\nexport var createLarger = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n matrix,\n DenseMatrix\n } = _ref;\n var algorithm03 = createAlgorithm03({\n typed\n });\n var algorithm07 = createAlgorithm07({\n typed,\n DenseMatrix\n });\n var algorithm12 = createAlgorithm12({\n typed,\n DenseMatrix\n });\n var algorithm13 = createAlgorithm13({\n typed\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Test whether value x is larger than y.\n *\n * The function returns true when x is larger than y and the relative\n * difference between x and y is larger than the configured epsilon. The\n * function cannot be used to compare values smaller than approximately 2.22e-16.\n *\n * For matrices, the function is evaluated element wise.\n * Strings are compared by their numerical value.\n *\n * Syntax:\n *\n * math.larger(x, y)\n *\n * Examples:\n *\n * math.larger(2, 3) // returns false\n * math.larger(5, 2 + 2) // returns true\n *\n * const a = math.unit('5 cm')\n * const b = math.unit('2 inch')\n * math.larger(a, b) // returns false\n *\n * See also:\n *\n * equal, unequal, smaller, smallerEq, largerEq, compare\n *\n * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare\n * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare\n * @return {boolean | Array | Matrix} Returns true when the x is larger than y, else returns false\n */\n\n return typed(name, {\n 'boolean, boolean': function booleanBoolean(x, y) {\n return x > y;\n },\n 'number, number': function numberNumber(x, y) {\n return x > y && !nearlyEqual(x, y, config.epsilon);\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {\n return x.gt(y) && !bigNearlyEqual(x, y, config.epsilon);\n },\n 'Fraction, Fraction': function FractionFraction(x, y) {\n return x.compare(y) === 1;\n },\n 'Complex, Complex': function ComplexComplex() {\n throw new TypeError('No ordering relation is defined for complex numbers');\n },\n 'Unit, Unit': function UnitUnit(x, y) {\n if (!x.equalBase(y)) {\n throw new Error('Cannot compare units with different base');\n }\n\n return this(x.value, y.value);\n },\n 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {\n return algorithm07(x, y, this);\n },\n 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {\n return algorithm03(y, x, this, true);\n },\n 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {\n return algorithm03(x, y, this, false);\n },\n 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {\n return algorithm13(x, y, this);\n },\n 'Array, Array': function ArrayArray(x, y) {\n // use matrix implementation\n return this(matrix(x), matrix(y)).valueOf();\n },\n 'Array, Matrix': function ArrayMatrix(x, y) {\n // use matrix implementation\n return this(matrix(x), y);\n },\n 'Matrix, Array': function MatrixArray(x, y) {\n // use matrix implementation\n return this(x, matrix(y));\n },\n 'SparseMatrix, any': function SparseMatrixAny(x, y) {\n return algorithm12(x, y, this, false);\n },\n 'DenseMatrix, any': function DenseMatrixAny(x, y) {\n return algorithm14(x, y, this, false);\n },\n 'any, SparseMatrix': function anySparseMatrix(x, y) {\n return algorithm12(y, x, this, true);\n },\n 'any, DenseMatrix': function anyDenseMatrix(x, y) {\n return algorithm14(y, x, this, true);\n },\n 'Array, any': function ArrayAny(x, y) {\n // use matrix implementation\n return algorithm14(matrix(x), y, this, false).valueOf();\n },\n 'any, Array': function anyArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, this, true).valueOf();\n }\n });\n});\nexport var createLargerNumber = /* #__PURE__ */factory(name, ['typed', 'config'], (_ref2) => {\n var {\n typed,\n config\n } = _ref2;\n return typed(name, {\n 'number, number': function numberNumber(x, y) {\n return x > y && !nearlyEqual(x, y, config.epsilon);\n }\n });\n});","import { factory } from '../../utils/factory.js';\nvar name = 'FibonacciHeap';\nvar dependencies = ['smaller', 'larger'];\nexport var createFibonacciHeapClass = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n smaller,\n larger\n } = _ref;\n var oneOverLogPhi = 1.0 / Math.log((1.0 + Math.sqrt(5.0)) / 2.0);\n /**\n * Fibonacci Heap implementation, used interally for Matrix math.\n * @class FibonacciHeap\n * @constructor FibonacciHeap\n */\n\n function FibonacciHeap() {\n if (!(this instanceof FibonacciHeap)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n } // initialize fields\n\n\n this._minimum = null;\n this._size = 0;\n }\n /**\n * Attach type information\n */\n\n\n FibonacciHeap.prototype.type = 'FibonacciHeap';\n FibonacciHeap.prototype.isFibonacciHeap = true;\n /**\n * Inserts a new data element into the heap. No heap consolidation is\n * performed at this time, the new node is simply inserted into the root\n * list of this heap. Running time: O(1) actual.\n * @memberof FibonacciHeap\n */\n\n FibonacciHeap.prototype.insert = function (key, value) {\n // create node\n var node = {\n key: key,\n value: value,\n degree: 0\n }; // check we have a node in the minimum\n\n if (this._minimum) {\n // minimum node\n var minimum = this._minimum; // update left & right of node\n\n node.left = minimum;\n node.right = minimum.right;\n minimum.right = node;\n node.right.left = node; // update minimum node in heap if needed\n\n if (smaller(key, minimum.key)) {\n // node has a smaller key, use it as minimum\n this._minimum = node;\n }\n } else {\n // set left & right\n node.left = node;\n node.right = node; // this is the first node\n\n this._minimum = node;\n } // increment number of nodes in heap\n\n\n this._size++; // return node\n\n return node;\n };\n /**\n * Returns the number of nodes in heap. Running time: O(1) actual.\n * @memberof FibonacciHeap\n */\n\n\n FibonacciHeap.prototype.size = function () {\n return this._size;\n };\n /**\n * Removes all elements from this heap.\n * @memberof FibonacciHeap\n */\n\n\n FibonacciHeap.prototype.clear = function () {\n this._minimum = null;\n this._size = 0;\n };\n /**\n * Returns true if the heap is empty, otherwise false.\n * @memberof FibonacciHeap\n */\n\n\n FibonacciHeap.prototype.isEmpty = function () {\n return this._size === 0;\n };\n /**\n * Extracts the node with minimum key from heap. Amortized running\n * time: O(log n).\n * @memberof FibonacciHeap\n */\n\n\n FibonacciHeap.prototype.extractMinimum = function () {\n // node to remove\n var node = this._minimum; // check we have a minimum\n\n if (node === null) {\n return node;\n } // current minimum\n\n\n var minimum = this._minimum; // get number of children\n\n var numberOfChildren = node.degree; // pointer to the first child\n\n var x = node.child; // for each child of node do...\n\n while (numberOfChildren > 0) {\n // store node in right side\n var tempRight = x.right; // remove x from child list\n\n x.left.right = x.right;\n x.right.left = x.left; // add x to root list of heap\n\n x.left = minimum;\n x.right = minimum.right;\n minimum.right = x;\n x.right.left = x; // set Parent[x] to null\n\n x.parent = null;\n x = tempRight;\n numberOfChildren--;\n } // remove node from root list of heap\n\n\n node.left.right = node.right;\n node.right.left = node.left; // update minimum\n\n if (node === node.right) {\n // empty\n minimum = null;\n } else {\n // update minimum\n minimum = node.right; // we need to update the pointer to the root with minimum key\n\n minimum = _findMinimumNode(minimum, this._size);\n } // decrement size of heap\n\n\n this._size--; // update minimum\n\n this._minimum = minimum; // return node\n\n return node;\n };\n /**\n * Removes a node from the heap given the reference to the node. The trees\n * in the heap will be consolidated, if necessary. This operation may fail\n * to remove the correct element if there are nodes with key value -Infinity.\n * Running time: O(log n) amortized.\n * @memberof FibonacciHeap\n */\n\n\n FibonacciHeap.prototype.remove = function (node) {\n // decrease key value\n this._minimum = _decreaseKey(this._minimum, node, -1); // remove the smallest\n\n this.extractMinimum();\n };\n /**\n * Decreases the key value for a heap node, given the new value to take on.\n * The structure of the heap may be changed and will not be consolidated.\n * Running time: O(1) amortized.\n * @memberof FibonacciHeap\n */\n\n\n function _decreaseKey(minimum, node, key) {\n // set node key\n node.key = key; // get parent node\n\n var parent = node.parent;\n\n if (parent && smaller(node.key, parent.key)) {\n // remove node from parent\n _cut(minimum, node, parent); // remove all nodes from parent to the root parent\n\n\n _cascadingCut(minimum, parent);\n } // update minimum node if needed\n\n\n if (smaller(node.key, minimum.key)) {\n minimum = node;\n } // return minimum\n\n\n return minimum;\n }\n /**\n * The reverse of the link operation: removes node from the child list of parent.\n * This method assumes that min is non-null. Running time: O(1).\n * @memberof FibonacciHeap\n */\n\n\n function _cut(minimum, node, parent) {\n // remove node from parent children and decrement Degree[parent]\n node.left.right = node.right;\n node.right.left = node.left;\n parent.degree--; // reset y.child if necessary\n\n if (parent.child === node) {\n parent.child = node.right;\n } // remove child if degree is 0\n\n\n if (parent.degree === 0) {\n parent.child = null;\n } // add node to root list of heap\n\n\n node.left = minimum;\n node.right = minimum.right;\n minimum.right = node;\n node.right.left = node; // set parent[node] to null\n\n node.parent = null; // set mark[node] to false\n\n node.mark = false;\n }\n /**\n * Performs a cascading cut operation. This cuts node from its parent and then\n * does the same for its parent, and so on up the tree.\n * Running time: O(log n); O(1) excluding the recursion.\n * @memberof FibonacciHeap\n */\n\n\n function _cascadingCut(minimum, node) {\n // store parent node\n var parent = node.parent; // if there's a parent...\n\n if (!parent) {\n return;\n } // if node is unmarked, set it marked\n\n\n if (!node.mark) {\n node.mark = true;\n } else {\n // it's marked, cut it from parent\n _cut(minimum, node, parent); // cut its parent as well\n\n\n _cascadingCut(parent);\n }\n }\n /**\n * Make the first node a child of the second one. Running time: O(1) actual.\n * @memberof FibonacciHeap\n */\n\n\n var _linkNodes = function _linkNodes(node, parent) {\n // remove node from root list of heap\n node.left.right = node.right;\n node.right.left = node.left; // make node a Child of parent\n\n node.parent = parent;\n\n if (!parent.child) {\n parent.child = node;\n node.right = node;\n node.left = node;\n } else {\n node.left = parent.child;\n node.right = parent.child.right;\n parent.child.right = node;\n node.right.left = node;\n } // increase degree[parent]\n\n\n parent.degree++; // set mark[node] false\n\n node.mark = false;\n };\n\n function _findMinimumNode(minimum, size) {\n // to find trees of the same degree efficiently we use an array of length O(log n) in which we keep a pointer to one root of each degree\n var arraySize = Math.floor(Math.log(size) * oneOverLogPhi) + 1; // create list with initial capacity\n\n var array = new Array(arraySize); // find the number of root nodes.\n\n var numRoots = 0;\n var x = minimum;\n\n if (x) {\n numRoots++;\n x = x.right;\n\n while (x !== minimum) {\n numRoots++;\n x = x.right;\n }\n } // vars\n\n\n var y; // For each node in root list do...\n\n while (numRoots > 0) {\n // access this node's degree..\n var d = x.degree; // get next node\n\n var next = x.right; // check if there is a node already in array with the same degree\n\n while (true) {\n // get node with the same degree is any\n y = array[d];\n\n if (!y) {\n break;\n } // make one node with the same degree a child of the other, do this based on the key value.\n\n\n if (larger(x.key, y.key)) {\n var temp = y;\n y = x;\n x = temp;\n } // make y a child of x\n\n\n _linkNodes(y, x); // we have handled this degree, go to next one.\n\n\n array[d] = null;\n d++;\n } // save this node for later when we might encounter another of the same degree.\n\n\n array[d] = x; // move forward through list.\n\n x = next;\n numRoots--;\n } // Set min to null (effectively losing the root list) and reconstruct the root list from the array entries in array[].\n\n\n minimum = null; // loop nodes in array\n\n for (var i = 0; i < arraySize; i++) {\n // get current node\n y = array[i];\n\n if (!y) {\n continue;\n } // check if we have a linked list\n\n\n if (minimum) {\n // First remove node from root list.\n y.left.right = y.right;\n y.right.left = y.left; // now add to root list, again.\n\n y.left = minimum;\n y.right = minimum.right;\n minimum.right = y;\n y.right.left = y; // check if this is a new min.\n\n if (smaller(y.key, minimum.key)) {\n minimum = y;\n }\n } else {\n minimum = y;\n }\n }\n\n return minimum;\n }\n\n return FibonacciHeap;\n}, {\n isClass: true\n});","import { factory } from '../../utils/factory.js';\nimport { createAlgorithm03 } from '../../type/matrix/utils/algorithm03.js';\nimport { createAlgorithm07 } from '../../type/matrix/utils/algorithm07.js';\nimport { createAlgorithm12 } from '../../type/matrix/utils/algorithm12.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nimport { createAlgorithm13 } from '../../type/matrix/utils/algorithm13.js';\nvar name = 'unequal';\nvar dependencies = ['typed', 'config', 'equalScalar', 'matrix', 'DenseMatrix'];\nexport var createUnequal = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n equalScalar,\n matrix,\n DenseMatrix\n } = _ref;\n var algorithm03 = createAlgorithm03({\n typed\n });\n var algorithm07 = createAlgorithm07({\n typed,\n DenseMatrix\n });\n var algorithm12 = createAlgorithm12({\n typed,\n DenseMatrix\n });\n var algorithm13 = createAlgorithm13({\n typed\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Test whether two values are unequal.\n *\n * The function tests whether the relative difference between x and y is\n * larger than the configured epsilon. The function cannot be used to compare\n * values smaller than approximately 2.22e-16.\n *\n * For matrices, the function is evaluated element wise.\n * In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im.\n * Strings are compared by their numerical value.\n *\n * Values `null` and `undefined` are compared strictly, thus `null` is unequal\n * with everything except `null`, and `undefined` is unequal with everything\n * except `undefined`.\n *\n * Syntax:\n *\n * math.unequal(x, y)\n *\n * Examples:\n *\n * math.unequal(2 + 2, 3) // returns true\n * math.unequal(2 + 2, 4) // returns false\n *\n * const a = math.unit('50 cm')\n * const b = math.unit('5 m')\n * math.unequal(a, b) // returns false\n *\n * const c = [2, 5, 1]\n * const d = [2, 7, 1]\n *\n * math.unequal(c, d) // returns [false, true, false]\n * math.deepEqual(c, d) // returns false\n *\n * math.unequal(0, null) // returns true\n * See also:\n *\n * equal, deepEqual, smaller, smallerEq, larger, largerEq, compare\n *\n * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} x First value to compare\n * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} y Second value to compare\n * @return {boolean | Array | Matrix} Returns true when the compared values are unequal, else returns false\n */\n\n return typed('unequal', {\n 'any, any': function anyAny(x, y) {\n // strict equality for null and undefined?\n if (x === null) {\n return y !== null;\n }\n\n if (y === null) {\n return x !== null;\n }\n\n if (x === undefined) {\n return y !== undefined;\n }\n\n if (y === undefined) {\n return x !== undefined;\n }\n\n return _unequal(x, y);\n },\n 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {\n return algorithm07(x, y, _unequal);\n },\n 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {\n return algorithm03(y, x, _unequal, true);\n },\n 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {\n return algorithm03(x, y, _unequal, false);\n },\n 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {\n return algorithm13(x, y, _unequal);\n },\n 'Array, Array': function ArrayArray(x, y) {\n // use matrix implementation\n return this(matrix(x), matrix(y)).valueOf();\n },\n 'Array, Matrix': function ArrayMatrix(x, y) {\n // use matrix implementation\n return this(matrix(x), y);\n },\n 'Matrix, Array': function MatrixArray(x, y) {\n // use matrix implementation\n return this(x, matrix(y));\n },\n 'SparseMatrix, any': function SparseMatrixAny(x, y) {\n return algorithm12(x, y, _unequal, false);\n },\n 'DenseMatrix, any': function DenseMatrixAny(x, y) {\n return algorithm14(x, y, _unequal, false);\n },\n 'any, SparseMatrix': function anySparseMatrix(x, y) {\n return algorithm12(y, x, _unequal, true);\n },\n 'any, DenseMatrix': function anyDenseMatrix(x, y) {\n return algorithm14(y, x, _unequal, true);\n },\n 'Array, any': function ArrayAny(x, y) {\n // use matrix implementation\n return algorithm14(matrix(x), y, _unequal, false).valueOf();\n },\n 'any, Array': function anyArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, _unequal, true).valueOf();\n }\n });\n\n function _unequal(x, y) {\n return !equalScalar(x, y);\n }\n});\nexport var createUnequalNumber = factory(name, ['typed', 'equalScalar'], (_ref2) => {\n var {\n typed,\n equalScalar\n } = _ref2;\n return typed(name, {\n 'any, any': function anyAny(x, y) {\n // strict equality for null and undefined?\n if (x === null) {\n return y !== null;\n }\n\n if (y === null) {\n return x !== null;\n }\n\n if (x === undefined) {\n return y !== undefined;\n }\n\n if (y === undefined) {\n return x !== undefined;\n }\n\n return !equalScalar(x, y);\n }\n });\n});","import { factory } from '../../utils/factory.js';\nimport { isMatrix } from '../../utils/is.js';\nvar name = 'dot';\nvar dependencies = ['typed', 'addScalar', 'multiplyScalar', 'conj', 'size'];\nexport var createDot = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n addScalar,\n multiplyScalar,\n conj,\n size\n } = _ref;\n\n /**\n * Calculate the dot product of two vectors. The dot product of\n * `A = [a1, a2, ..., an]` and `B = [b1, b2, ..., bn]` is defined as:\n *\n * dot(A, B) = conj(a1) * b1 + conj(a2) * b2 + ... + conj(an) * bn\n *\n * Syntax:\n *\n * math.dot(x, y)\n *\n * Examples:\n *\n * math.dot([2, 4, 1], [2, 2, 3]) // returns number 15\n * math.multiply([2, 4, 1], [2, 2, 3]) // returns number 15\n *\n * See also:\n *\n * multiply, cross\n *\n * @param {Array | Matrix} x First vector\n * @param {Array | Matrix} y Second vector\n * @return {number} Returns the dot product of `x` and `y`\n */\n return typed(name, {\n 'Array | DenseMatrix, Array | DenseMatrix': _denseDot,\n 'SparseMatrix, SparseMatrix': _sparseDot\n });\n\n function _validateDim(x, y) {\n var xSize = _size(x);\n\n var ySize = _size(y);\n\n var xLen, yLen;\n\n if (xSize.length === 1) {\n xLen = xSize[0];\n } else if (xSize.length === 2 && xSize[1] === 1) {\n xLen = xSize[0];\n } else {\n throw new RangeError('Expected a column vector, instead got a matrix of size (' + xSize.join(', ') + ')');\n }\n\n if (ySize.length === 1) {\n yLen = ySize[0];\n } else if (ySize.length === 2 && ySize[1] === 1) {\n yLen = ySize[0];\n } else {\n throw new RangeError('Expected a column vector, instead got a matrix of size (' + ySize.join(', ') + ')');\n }\n\n if (xLen !== yLen) throw new RangeError('Vectors must have equal length (' + xLen + ' != ' + yLen + ')');\n if (xLen === 0) throw new RangeError('Cannot calculate the dot product of empty vectors');\n return xLen;\n }\n\n function _denseDot(a, b) {\n var N = _validateDim(a, b);\n\n var adata = isMatrix(a) ? a._data : a;\n var adt = isMatrix(a) ? a._datatype : undefined;\n var bdata = isMatrix(b) ? b._data : b;\n var bdt = isMatrix(b) ? b._datatype : undefined; // are these 2-dimensional column vectors? (as opposed to 1-dimensional vectors)\n\n var aIsColumn = _size(a).length === 2;\n var bIsColumn = _size(b).length === 2;\n var add = addScalar;\n var mul = multiplyScalar; // process data types\n\n if (adt && bdt && adt === bdt && typeof adt === 'string') {\n var dt = adt; // find signatures that matches (dt, dt)\n\n add = typed.find(addScalar, [dt, dt]);\n mul = typed.find(multiplyScalar, [dt, dt]);\n } // both vectors 1-dimensional\n\n\n if (!aIsColumn && !bIsColumn) {\n var c = mul(conj(adata[0]), bdata[0]);\n\n for (var i = 1; i < N; i++) {\n c = add(c, mul(conj(adata[i]), bdata[i]));\n }\n\n return c;\n } // a is 1-dim, b is column\n\n\n if (!aIsColumn && bIsColumn) {\n var _c = mul(conj(adata[0]), bdata[0][0]);\n\n for (var _i = 1; _i < N; _i++) {\n _c = add(_c, mul(conj(adata[_i]), bdata[_i][0]));\n }\n\n return _c;\n } // a is column, b is 1-dim\n\n\n if (aIsColumn && !bIsColumn) {\n var _c2 = mul(conj(adata[0][0]), bdata[0]);\n\n for (var _i2 = 1; _i2 < N; _i2++) {\n _c2 = add(_c2, mul(conj(adata[_i2][0]), bdata[_i2]));\n }\n\n return _c2;\n } // both vectors are column\n\n\n if (aIsColumn && bIsColumn) {\n var _c3 = mul(conj(adata[0][0]), bdata[0][0]);\n\n for (var _i3 = 1; _i3 < N; _i3++) {\n _c3 = add(_c3, mul(conj(adata[_i3][0]), bdata[_i3][0]));\n }\n\n return _c3;\n }\n }\n\n function _sparseDot(x, y) {\n _validateDim(x, y);\n\n var xindex = x._index;\n var xvalues = x._values;\n var yindex = y._index;\n var yvalues = y._values; // TODO optimize add & mul using datatype\n\n var c = 0;\n var add = addScalar;\n var mul = multiplyScalar;\n var i = 0;\n var j = 0;\n\n while (i < xindex.length && j < yindex.length) {\n var I = xindex[i];\n var J = yindex[j];\n\n if (I < J) {\n i++;\n continue;\n }\n\n if (I > J) {\n j++;\n continue;\n }\n\n if (I === J) {\n c = add(c, mul(xvalues[i], yvalues[j]));\n i++;\n j++;\n }\n }\n\n return c;\n } // TODO remove this once #1771 is fixed\n\n\n function _size(x) {\n return isMatrix(x) ? x.size() : size(x);\n }\n});","import { factory } from '../../utils/factory.js';\nimport { deepMap } from '../../utils/collection.js';\nimport { absNumber } from '../../plain/number/index.js';\nvar name = 'abs';\nvar dependencies = ['typed'];\nexport var createAbs = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed\n } = _ref;\n\n /**\n * Calculate the absolute value of a number. For matrices, the function is\n * evaluated element wise.\n *\n * Syntax:\n *\n * math.abs(x)\n *\n * Examples:\n *\n * math.abs(3.5) // returns number 3.5\n * math.abs(-4.2) // returns number 4.2\n *\n * math.abs([3, -5, -1, 0, 2]) // returns Array [3, 5, 1, 0, 2]\n *\n * See also:\n *\n * sign\n *\n * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x\n * A number or matrix for which to get the absolute value\n * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}\n * Absolute value of `x`\n */\n return typed(name, {\n number: absNumber,\n Complex: function Complex(x) {\n return x.abs();\n },\n BigNumber: function BigNumber(x) {\n return x.abs();\n },\n Fraction: function Fraction(x) {\n return x.abs();\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n // deep map collection, skip zeros since abs(0) = 0\n return deepMap(x, this, true);\n },\n Unit: function Unit(x) {\n return x.abs();\n }\n });\n});","import Decimal from 'decimal.js';\nimport { factory } from '../../utils/factory.js';\nimport { deepMap } from '../../utils/collection.js';\nimport { nearlyEqual } from '../../utils/number.js';\nimport { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js';\nimport { createAlgorithm11 } from '../../type/matrix/utils/algorithm11.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nvar name = 'floor';\nvar dependencies = ['typed', 'config', 'round', 'matrix', 'equalScalar'];\nexport var createFloor = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n round,\n matrix,\n equalScalar\n } = _ref;\n var algorithm11 = createAlgorithm11({\n typed,\n equalScalar\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Round a value towards minus infinity.\n * For matrices, the function is evaluated element wise.\n *\n * Syntax:\n *\n * math.floor(x)\n * math.floor(x, n)\n *\n * Examples:\n *\n * math.floor(3.2) // returns number 3\n * math.floor(3.8) // returns number 3\n * math.floor(-4.2) // returns number -5\n * math.floor(-4.7) // returns number -5\n *\n * math.floor(3.212, 2) // returns number 3.21\n * math.floor(3.288, 2) // returns number 3.28\n * math.floor(-4.212, 2) // returns number -4.22\n * math.floor(-4.782, 2) // returns number -4.79\n *\n * const c = math.complex(3.24, -2.71)\n * math.floor(c) // returns Complex 3 - 3i\n * math.floor(c, 1) // returns Complex 3.2 - 2.8i\n *\n * math.floor([3.2, 3.8, -4.7]) // returns Array [3, 3, -5]\n * math.floor([3.21, 3.82, -4.71], 1) // returns Array [3.2, 3.8, -4.8]\n *\n * See also:\n *\n * ceil, fix, round\n *\n * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded\n * @param {number | BigNumber | Array} [n=0] Number of decimals\n * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value\n */\n\n return typed('floor', {\n number: function number(x) {\n if (nearlyEqual(x, round(x), config.epsilon)) {\n return round(x);\n } else {\n return Math.floor(x);\n }\n },\n 'number, number': function numberNumber(x, n) {\n if (nearlyEqual(x, round(x, n), config.epsilon)) {\n return round(x, n);\n } else {\n var [number, exponent] = \"\".concat(x, \"e\").split('e');\n var result = Math.floor(Number(\"\".concat(number, \"e\").concat(Number(exponent) + n)));\n [number, exponent] = \"\".concat(result, \"e\").split('e');\n return Number(\"\".concat(number, \"e\").concat(Number(exponent) - n));\n }\n },\n Complex: function Complex(x) {\n return x.floor();\n },\n 'Complex, number': function ComplexNumber(x, n) {\n return x.floor(n);\n },\n BigNumber: function BigNumber(x) {\n if (bigNearlyEqual(x, round(x), config.epsilon)) {\n return round(x);\n } else {\n return x.floor();\n }\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, n) {\n if (bigNearlyEqual(x, round(x, n), config.epsilon)) {\n return round(x, n);\n } else {\n return x.toDecimalPlaces(n.toNumber(), Decimal.ROUND_FLOOR);\n }\n },\n Fraction: function Fraction(x) {\n return x.floor();\n },\n 'Fraction, number': function FractionNumber(x, n) {\n return x.floor(n);\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n // deep map collection, skip zeros since floor(0) = 0\n return deepMap(x, this, true);\n },\n 'Array | Matrix, number': function ArrayMatrixNumber(x, n) {\n // deep map collection, skip zeros since ceil(0) = 0\n return deepMap(x, i => this(i, n), true);\n },\n 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {\n return algorithm11(x, y, this, false);\n },\n 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {\n return algorithm14(x, y, this, false);\n },\n 'number | Complex | BigNumber, Array': function numberComplexBigNumberArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, this, true).valueOf();\n }\n });\n});","import { factory } from '../../utils/factory.js';\nimport { isMatrix } from '../../utils/is.js';\nimport { extend } from '../../utils/object.js';\nimport { arraySize } from '../../utils/array.js';\nimport { createAlgorithm11 } from '../../type/matrix/utils/algorithm11.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nvar name = 'multiply';\nvar dependencies = ['typed', 'matrix', 'addScalar', 'multiplyScalar', 'equalScalar', 'dot'];\nexport var createMultiply = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n addScalar,\n multiplyScalar,\n equalScalar,\n dot\n } = _ref;\n var algorithm11 = createAlgorithm11({\n typed,\n equalScalar\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n\n function _validateMatrixDimensions(size1, size2) {\n // check left operand dimensions\n switch (size1.length) {\n case 1:\n // check size2\n switch (size2.length) {\n case 1:\n // Vector x Vector\n if (size1[0] !== size2[0]) {\n // throw error\n throw new RangeError('Dimension mismatch in multiplication. Vectors must have the same length');\n }\n\n break;\n\n case 2:\n // Vector x Matrix\n if (size1[0] !== size2[0]) {\n // throw error\n throw new RangeError('Dimension mismatch in multiplication. Vector length (' + size1[0] + ') must match Matrix rows (' + size2[0] + ')');\n }\n\n break;\n\n default:\n throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');\n }\n\n break;\n\n case 2:\n // check size2\n switch (size2.length) {\n case 1:\n // Matrix x Vector\n if (size1[1] !== size2[0]) {\n // throw error\n throw new RangeError('Dimension mismatch in multiplication. Matrix columns (' + size1[1] + ') must match Vector length (' + size2[0] + ')');\n }\n\n break;\n\n case 2:\n // Matrix x Matrix\n if (size1[1] !== size2[0]) {\n // throw error\n throw new RangeError('Dimension mismatch in multiplication. Matrix A columns (' + size1[1] + ') must match Matrix B rows (' + size2[0] + ')');\n }\n\n break;\n\n default:\n throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');\n }\n\n break;\n\n default:\n throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix A has ' + size1.length + ' dimensions)');\n }\n }\n /**\n * C = A * B\n *\n * @param {Matrix} a Dense Vector (N)\n * @param {Matrix} b Dense Vector (N)\n *\n * @return {number} Scalar value\n */\n\n\n function _multiplyVectorVector(a, b, n) {\n // check empty vector\n if (n === 0) {\n throw new Error('Cannot multiply two empty vectors');\n }\n\n return dot(a, b);\n }\n /**\n * C = A * B\n *\n * @param {Matrix} a Dense Vector (M)\n * @param {Matrix} b Matrix (MxN)\n *\n * @return {Matrix} Dense Vector (N)\n */\n\n\n function _multiplyVectorMatrix(a, b) {\n // process storage\n if (b.storage() !== 'dense') {\n throw new Error('Support for SparseMatrix not implemented');\n }\n\n return _multiplyVectorDenseMatrix(a, b);\n }\n /**\n * C = A * B\n *\n * @param {Matrix} a Dense Vector (M)\n * @param {Matrix} b Dense Matrix (MxN)\n *\n * @return {Matrix} Dense Vector (N)\n */\n\n\n function _multiplyVectorDenseMatrix(a, b) {\n // a dense\n var adata = a._data;\n var asize = a._size;\n var adt = a._datatype; // b dense\n\n var bdata = b._data;\n var bsize = b._size;\n var bdt = b._datatype; // rows & columns\n\n var alength = asize[0];\n var bcolumns = bsize[1]; // datatype\n\n var dt; // addScalar signature to use\n\n var af = addScalar; // multiplyScalar signature to use\n\n var mf = multiplyScalar; // process data types\n\n if (adt && bdt && adt === bdt && typeof adt === 'string') {\n // datatype\n dt = adt; // find signatures that matches (dt, dt)\n\n af = typed.find(addScalar, [dt, dt]);\n mf = typed.find(multiplyScalar, [dt, dt]);\n } // result\n\n\n var c = []; // loop matrix columns\n\n for (var j = 0; j < bcolumns; j++) {\n // sum (do not initialize it with zero)\n var sum = mf(adata[0], bdata[0][j]); // loop vector\n\n for (var i = 1; i < alength; i++) {\n // multiply & accumulate\n sum = af(sum, mf(adata[i], bdata[i][j]));\n }\n\n c[j] = sum;\n } // return matrix\n\n\n return a.createDenseMatrix({\n data: c,\n size: [bcolumns],\n datatype: dt\n });\n }\n /**\n * C = A * B\n *\n * @param {Matrix} a Matrix (MxN)\n * @param {Matrix} b Dense Vector (N)\n *\n * @return {Matrix} Dense Vector (M)\n */\n\n\n var _multiplyMatrixVector = typed('_multiplyMatrixVector', {\n 'DenseMatrix, any': _multiplyDenseMatrixVector,\n 'SparseMatrix, any': _multiplySparseMatrixVector\n });\n /**\n * C = A * B\n *\n * @param {Matrix} a Matrix (MxN)\n * @param {Matrix} b Matrix (NxC)\n *\n * @return {Matrix} Matrix (MxC)\n */\n\n\n var _multiplyMatrixMatrix = typed('_multiplyMatrixMatrix', {\n 'DenseMatrix, DenseMatrix': _multiplyDenseMatrixDenseMatrix,\n 'DenseMatrix, SparseMatrix': _multiplyDenseMatrixSparseMatrix,\n 'SparseMatrix, DenseMatrix': _multiplySparseMatrixDenseMatrix,\n 'SparseMatrix, SparseMatrix': _multiplySparseMatrixSparseMatrix\n });\n /**\n * C = A * B\n *\n * @param {Matrix} a DenseMatrix (MxN)\n * @param {Matrix} b Dense Vector (N)\n *\n * @return {Matrix} Dense Vector (M)\n */\n\n\n function _multiplyDenseMatrixVector(a, b) {\n // a dense\n var adata = a._data;\n var asize = a._size;\n var adt = a._datatype; // b dense\n\n var bdata = b._data;\n var bdt = b._datatype; // rows & columns\n\n var arows = asize[0];\n var acolumns = asize[1]; // datatype\n\n var dt; // addScalar signature to use\n\n var af = addScalar; // multiplyScalar signature to use\n\n var mf = multiplyScalar; // process data types\n\n if (adt && bdt && adt === bdt && typeof adt === 'string') {\n // datatype\n dt = adt; // find signatures that matches (dt, dt)\n\n af = typed.find(addScalar, [dt, dt]);\n mf = typed.find(multiplyScalar, [dt, dt]);\n } // result\n\n\n var c = []; // loop matrix a rows\n\n for (var i = 0; i < arows; i++) {\n // current row\n var row = adata[i]; // sum (do not initialize it with zero)\n\n var sum = mf(row[0], bdata[0]); // loop matrix a columns\n\n for (var j = 1; j < acolumns; j++) {\n // multiply & accumulate\n sum = af(sum, mf(row[j], bdata[j]));\n }\n\n c[i] = sum;\n } // return matrix\n\n\n return a.createDenseMatrix({\n data: c,\n size: [arows],\n datatype: dt\n });\n }\n /**\n * C = A * B\n *\n * @param {Matrix} a DenseMatrix (MxN)\n * @param {Matrix} b DenseMatrix (NxC)\n *\n * @return {Matrix} DenseMatrix (MxC)\n */\n\n\n function _multiplyDenseMatrixDenseMatrix(a, b) {\n // a dense\n var adata = a._data;\n var asize = a._size;\n var adt = a._datatype; // b dense\n\n var bdata = b._data;\n var bsize = b._size;\n var bdt = b._datatype; // rows & columns\n\n var arows = asize[0];\n var acolumns = asize[1];\n var bcolumns = bsize[1]; // datatype\n\n var dt; // addScalar signature to use\n\n var af = addScalar; // multiplyScalar signature to use\n\n var mf = multiplyScalar; // process data types\n\n if (adt && bdt && adt === bdt && typeof adt === 'string') {\n // datatype\n dt = adt; // find signatures that matches (dt, dt)\n\n af = typed.find(addScalar, [dt, dt]);\n mf = typed.find(multiplyScalar, [dt, dt]);\n } // result\n\n\n var c = []; // loop matrix a rows\n\n for (var i = 0; i < arows; i++) {\n // current row\n var row = adata[i]; // initialize row array\n\n c[i] = []; // loop matrix b columns\n\n for (var j = 0; j < bcolumns; j++) {\n // sum (avoid initializing sum to zero)\n var sum = mf(row[0], bdata[0][j]); // loop matrix a columns\n\n for (var x = 1; x < acolumns; x++) {\n // multiply & accumulate\n sum = af(sum, mf(row[x], bdata[x][j]));\n }\n\n c[i][j] = sum;\n }\n } // return matrix\n\n\n return a.createDenseMatrix({\n data: c,\n size: [arows, bcolumns],\n datatype: dt\n });\n }\n /**\n * C = A * B\n *\n * @param {Matrix} a DenseMatrix (MxN)\n * @param {Matrix} b SparseMatrix (NxC)\n *\n * @return {Matrix} SparseMatrix (MxC)\n */\n\n\n function _multiplyDenseMatrixSparseMatrix(a, b) {\n // a dense\n var adata = a._data;\n var asize = a._size;\n var adt = a._datatype; // b sparse\n\n var bvalues = b._values;\n var bindex = b._index;\n var bptr = b._ptr;\n var bsize = b._size;\n var bdt = b._datatype; // validate b matrix\n\n if (!bvalues) {\n throw new Error('Cannot multiply Dense Matrix times Pattern only Matrix');\n } // rows & columns\n\n\n var arows = asize[0];\n var bcolumns = bsize[1]; // datatype\n\n var dt; // addScalar signature to use\n\n var af = addScalar; // multiplyScalar signature to use\n\n var mf = multiplyScalar; // equalScalar signature to use\n\n var eq = equalScalar; // zero value\n\n var zero = 0; // process data types\n\n if (adt && bdt && adt === bdt && typeof adt === 'string') {\n // datatype\n dt = adt; // find signatures that matches (dt, dt)\n\n af = typed.find(addScalar, [dt, dt]);\n mf = typed.find(multiplyScalar, [dt, dt]);\n eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype\n\n zero = typed.convert(0, dt);\n } // result\n\n\n var cvalues = [];\n var cindex = [];\n var cptr = []; // c matrix\n\n var c = b.createSparseMatrix({\n values: cvalues,\n index: cindex,\n ptr: cptr,\n size: [arows, bcolumns],\n datatype: dt\n }); // loop b columns\n\n for (var jb = 0; jb < bcolumns; jb++) {\n // update ptr\n cptr[jb] = cindex.length; // indeces in column jb\n\n var kb0 = bptr[jb];\n var kb1 = bptr[jb + 1]; // do not process column jb if no data exists\n\n if (kb1 > kb0) {\n // last row mark processed\n var last = 0; // loop a rows\n\n for (var i = 0; i < arows; i++) {\n // column mark\n var mark = i + 1; // C[i, jb]\n\n var cij = void 0; // values in b column j\n\n for (var kb = kb0; kb < kb1; kb++) {\n // row\n var ib = bindex[kb]; // check value has been initialized\n\n if (last !== mark) {\n // first value in column jb\n cij = mf(adata[i][ib], bvalues[kb]); // update mark\n\n last = mark;\n } else {\n // accumulate value\n cij = af(cij, mf(adata[i][ib], bvalues[kb]));\n }\n } // check column has been processed and value != 0\n\n\n if (last === mark && !eq(cij, zero)) {\n // push row & value\n cindex.push(i);\n cvalues.push(cij);\n }\n }\n }\n } // update ptr\n\n\n cptr[bcolumns] = cindex.length; // return sparse matrix\n\n return c;\n }\n /**\n * C = A * B\n *\n * @param {Matrix} a SparseMatrix (MxN)\n * @param {Matrix} b Dense Vector (N)\n *\n * @return {Matrix} SparseMatrix (M, 1)\n */\n\n\n function _multiplySparseMatrixVector(a, b) {\n // a sparse\n var avalues = a._values;\n var aindex = a._index;\n var aptr = a._ptr;\n var adt = a._datatype; // validate a matrix\n\n if (!avalues) {\n throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');\n } // b dense\n\n\n var bdata = b._data;\n var bdt = b._datatype; // rows & columns\n\n var arows = a._size[0];\n var brows = b._size[0]; // result\n\n var cvalues = [];\n var cindex = [];\n var cptr = []; // datatype\n\n var dt; // addScalar signature to use\n\n var af = addScalar; // multiplyScalar signature to use\n\n var mf = multiplyScalar; // equalScalar signature to use\n\n var eq = equalScalar; // zero value\n\n var zero = 0; // process data types\n\n if (adt && bdt && adt === bdt && typeof adt === 'string') {\n // datatype\n dt = adt; // find signatures that matches (dt, dt)\n\n af = typed.find(addScalar, [dt, dt]);\n mf = typed.find(multiplyScalar, [dt, dt]);\n eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype\n\n zero = typed.convert(0, dt);\n } // workspace\n\n\n var x = []; // vector with marks indicating a value x[i] exists in a given column\n\n var w = []; // update ptr\n\n cptr[0] = 0; // rows in b\n\n for (var ib = 0; ib < brows; ib++) {\n // b[ib]\n var vbi = bdata[ib]; // check b[ib] != 0, avoid loops\n\n if (!eq(vbi, zero)) {\n // A values & index in ib column\n for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {\n // a row\n var ia = aindex[ka]; // check value exists in current j\n\n if (!w[ia]) {\n // ia is new entry in j\n w[ia] = true; // add i to pattern of C\n\n cindex.push(ia); // x(ia) = A\n\n x[ia] = mf(vbi, avalues[ka]);\n } else {\n // i exists in C already\n x[ia] = af(x[ia], mf(vbi, avalues[ka]));\n }\n }\n }\n } // copy values from x to column jb of c\n\n\n for (var p1 = cindex.length, p = 0; p < p1; p++) {\n // row\n var ic = cindex[p]; // copy value\n\n cvalues[p] = x[ic];\n } // update ptr\n\n\n cptr[1] = cindex.length; // return sparse matrix\n\n return a.createSparseMatrix({\n values: cvalues,\n index: cindex,\n ptr: cptr,\n size: [arows, 1],\n datatype: dt\n });\n }\n /**\n * C = A * B\n *\n * @param {Matrix} a SparseMatrix (MxN)\n * @param {Matrix} b DenseMatrix (NxC)\n *\n * @return {Matrix} SparseMatrix (MxC)\n */\n\n\n function _multiplySparseMatrixDenseMatrix(a, b) {\n // a sparse\n var avalues = a._values;\n var aindex = a._index;\n var aptr = a._ptr;\n var adt = a._datatype; // validate a matrix\n\n if (!avalues) {\n throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');\n } // b dense\n\n\n var bdata = b._data;\n var bdt = b._datatype; // rows & columns\n\n var arows = a._size[0];\n var brows = b._size[0];\n var bcolumns = b._size[1]; // datatype\n\n var dt; // addScalar signature to use\n\n var af = addScalar; // multiplyScalar signature to use\n\n var mf = multiplyScalar; // equalScalar signature to use\n\n var eq = equalScalar; // zero value\n\n var zero = 0; // process data types\n\n if (adt && bdt && adt === bdt && typeof adt === 'string') {\n // datatype\n dt = adt; // find signatures that matches (dt, dt)\n\n af = typed.find(addScalar, [dt, dt]);\n mf = typed.find(multiplyScalar, [dt, dt]);\n eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype\n\n zero = typed.convert(0, dt);\n } // result\n\n\n var cvalues = [];\n var cindex = [];\n var cptr = []; // c matrix\n\n var c = a.createSparseMatrix({\n values: cvalues,\n index: cindex,\n ptr: cptr,\n size: [arows, bcolumns],\n datatype: dt\n }); // workspace\n\n var x = []; // vector with marks indicating a value x[i] exists in a given column\n\n var w = []; // loop b columns\n\n for (var jb = 0; jb < bcolumns; jb++) {\n // update ptr\n cptr[jb] = cindex.length; // mark in workspace for current column\n\n var mark = jb + 1; // rows in jb\n\n for (var ib = 0; ib < brows; ib++) {\n // b[ib, jb]\n var vbij = bdata[ib][jb]; // check b[ib, jb] != 0, avoid loops\n\n if (!eq(vbij, zero)) {\n // A values & index in ib column\n for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {\n // a row\n var ia = aindex[ka]; // check value exists in current j\n\n if (w[ia] !== mark) {\n // ia is new entry in j\n w[ia] = mark; // add i to pattern of C\n\n cindex.push(ia); // x(ia) = A\n\n x[ia] = mf(vbij, avalues[ka]);\n } else {\n // i exists in C already\n x[ia] = af(x[ia], mf(vbij, avalues[ka]));\n }\n }\n }\n } // copy values from x to column jb of c\n\n\n for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {\n // row\n var ic = cindex[p]; // copy value\n\n cvalues[p] = x[ic];\n }\n } // update ptr\n\n\n cptr[bcolumns] = cindex.length; // return sparse matrix\n\n return c;\n }\n /**\n * C = A * B\n *\n * @param {Matrix} a SparseMatrix (MxN)\n * @param {Matrix} b SparseMatrix (NxC)\n *\n * @return {Matrix} SparseMatrix (MxC)\n */\n\n\n function _multiplySparseMatrixSparseMatrix(a, b) {\n // a sparse\n var avalues = a._values;\n var aindex = a._index;\n var aptr = a._ptr;\n var adt = a._datatype; // b sparse\n\n var bvalues = b._values;\n var bindex = b._index;\n var bptr = b._ptr;\n var bdt = b._datatype; // rows & columns\n\n var arows = a._size[0];\n var bcolumns = b._size[1]; // flag indicating both matrices (a & b) contain data\n\n var values = avalues && bvalues; // datatype\n\n var dt; // addScalar signature to use\n\n var af = addScalar; // multiplyScalar signature to use\n\n var mf = multiplyScalar; // process data types\n\n if (adt && bdt && adt === bdt && typeof adt === 'string') {\n // datatype\n dt = adt; // find signatures that matches (dt, dt)\n\n af = typed.find(addScalar, [dt, dt]);\n mf = typed.find(multiplyScalar, [dt, dt]);\n } // result\n\n\n var cvalues = values ? [] : undefined;\n var cindex = [];\n var cptr = []; // c matrix\n\n var c = a.createSparseMatrix({\n values: cvalues,\n index: cindex,\n ptr: cptr,\n size: [arows, bcolumns],\n datatype: dt\n }); // workspace\n\n var x = values ? [] : undefined; // vector with marks indicating a value x[i] exists in a given column\n\n var w = []; // variables\n\n var ka, ka0, ka1, kb, kb0, kb1, ia, ib; // loop b columns\n\n for (var jb = 0; jb < bcolumns; jb++) {\n // update ptr\n cptr[jb] = cindex.length; // mark in workspace for current column\n\n var mark = jb + 1; // B values & index in j\n\n for (kb0 = bptr[jb], kb1 = bptr[jb + 1], kb = kb0; kb < kb1; kb++) {\n // b row\n ib = bindex[kb]; // check we need to process values\n\n if (values) {\n // loop values in a[:,ib]\n for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {\n // row\n ia = aindex[ka]; // check value exists in current j\n\n if (w[ia] !== mark) {\n // ia is new entry in j\n w[ia] = mark; // add i to pattern of C\n\n cindex.push(ia); // x(ia) = A\n\n x[ia] = mf(bvalues[kb], avalues[ka]);\n } else {\n // i exists in C already\n x[ia] = af(x[ia], mf(bvalues[kb], avalues[ka]));\n }\n }\n } else {\n // loop values in a[:,ib]\n for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {\n // row\n ia = aindex[ka]; // check value exists in current j\n\n if (w[ia] !== mark) {\n // ia is new entry in j\n w[ia] = mark; // add i to pattern of C\n\n cindex.push(ia);\n }\n }\n }\n } // check we need to process matrix values (pattern matrix)\n\n\n if (values) {\n // copy values from x to column jb of c\n for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {\n // row\n var ic = cindex[p]; // copy value\n\n cvalues[p] = x[ic];\n }\n }\n } // update ptr\n\n\n cptr[bcolumns] = cindex.length; // return sparse matrix\n\n return c;\n }\n /**\n * Multiply two or more values, `x * y`.\n * For matrices, the matrix product is calculated.\n *\n * Syntax:\n *\n * math.multiply(x, y)\n * math.multiply(x, y, z, ...)\n *\n * Examples:\n *\n * math.multiply(4, 5.2) // returns number 20.8\n * math.multiply(2, 3, 4) // returns number 24\n *\n * const a = math.complex(2, 3)\n * const b = math.complex(4, 1)\n * math.multiply(a, b) // returns Complex 5 + 14i\n *\n * const c = [[1, 2], [4, 3]]\n * const d = [[1, 2, 3], [3, -4, 7]]\n * math.multiply(c, d) // returns Array [[7, -6, 17], [13, -4, 33]]\n *\n * const e = math.unit('2.1 km')\n * math.multiply(3, e) // returns Unit 6.3 km\n *\n * See also:\n *\n * divide, prod, cross, dot\n *\n * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to multiply\n * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to multiply\n * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`\n */\n\n\n return typed(name, extend({\n // we extend the signatures of multiplyScalar with signatures dealing with matrices\n 'Array, Array': function ArrayArray(x, y) {\n // check dimensions\n _validateMatrixDimensions(arraySize(x), arraySize(y)); // use dense matrix implementation\n\n\n var m = this(matrix(x), matrix(y)); // return array or scalar\n\n return isMatrix(m) ? m.valueOf() : m;\n },\n 'Matrix, Matrix': function MatrixMatrix(x, y) {\n // dimensions\n var xsize = x.size();\n var ysize = y.size(); // check dimensions\n\n _validateMatrixDimensions(xsize, ysize); // process dimensions\n\n\n if (xsize.length === 1) {\n // process y dimensions\n if (ysize.length === 1) {\n // Vector * Vector\n return _multiplyVectorVector(x, y, xsize[0]);\n } // Vector * Matrix\n\n\n return _multiplyVectorMatrix(x, y);\n } // process y dimensions\n\n\n if (ysize.length === 1) {\n // Matrix * Vector\n return _multiplyMatrixVector(x, y);\n } // Matrix * Matrix\n\n\n return _multiplyMatrixMatrix(x, y);\n },\n 'Matrix, Array': function MatrixArray(x, y) {\n // use Matrix * Matrix implementation\n return this(x, matrix(y));\n },\n 'Array, Matrix': function ArrayMatrix(x, y) {\n // use Matrix * Matrix implementation\n return this(matrix(x, y.storage()), y);\n },\n 'SparseMatrix, any': function SparseMatrixAny(x, y) {\n return algorithm11(x, y, multiplyScalar, false);\n },\n 'DenseMatrix, any': function DenseMatrixAny(x, y) {\n return algorithm14(x, y, multiplyScalar, false);\n },\n 'any, SparseMatrix': function anySparseMatrix(x, y) {\n return algorithm11(y, x, multiplyScalar, true);\n },\n 'any, DenseMatrix': function anyDenseMatrix(x, y) {\n return algorithm14(y, x, multiplyScalar, true);\n },\n 'Array, any': function ArrayAny(x, y) {\n // use matrix implementation\n return algorithm14(matrix(x), y, multiplyScalar, false).valueOf();\n },\n 'any, Array': function anyArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, multiplyScalar, true).valueOf();\n },\n 'any, any': multiplyScalar,\n 'any, any, ...any': function anyAnyAny(x, y, rest) {\n var result = this(x, y);\n\n for (var i = 0; i < rest.length; i++) {\n result = this(result, rest[i]);\n }\n\n return result;\n }\n }, multiplyScalar.signatures));\n});","/**\n * Create a syntax error with the message:\n * 'Wrong number of arguments in function ( provided, - expected)'\n * @param {string} fn Function name\n * @param {number} count Actual argument count\n * @param {number} min Minimum required argument count\n * @param {number} [max] Maximum required argument count\n * @extends Error\n */\nexport function ArgumentsError(fn, count, min, max) {\n if (!(this instanceof ArgumentsError)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n }\n\n this.fn = fn;\n this.count = count;\n this.min = min;\n this.max = max;\n this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + (max !== undefined && max !== null ? '-' + max : '') + ' expected)';\n this.stack = new Error().stack;\n}\nArgumentsError.prototype = new Error();\nArgumentsError.prototype.constructor = Error;\nArgumentsError.prototype.name = 'ArgumentsError';\nArgumentsError.prototype.isArgumentsError = true;","import { isBigNumber, isMatrix } from '../../utils/is.js';\nimport { DimensionError } from '../../error/DimensionError.js';\nimport { ArgumentsError } from '../../error/ArgumentsError.js';\nimport { isInteger } from '../../utils/number.js';\nimport { format } from '../../utils/string.js';\nimport { clone } from '../../utils/object.js';\nimport { resize as arrayResize } from '../../utils/array.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'resize';\nvar dependencies = ['config', 'matrix'];\nexport var createResize = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n config,\n matrix\n } = _ref;\n\n /**\n * Resize a matrix\n *\n * Syntax:\n *\n * math.resize(x, size)\n * math.resize(x, size, defaultValue)\n *\n * Examples:\n *\n * math.resize([1, 2, 3, 4, 5], [3]) // returns Array [1, 2, 3]\n * math.resize([1, 2, 3], [5], 0) // returns Array [1, 2, 3, 0, 0]\n * math.resize(2, [2, 3], 0) // returns Matrix [[2, 0, 0], [0, 0, 0]]\n * math.resize(\"hello\", [8], \"!\") // returns string 'hello!!!'\n *\n * See also:\n *\n * size, squeeze, subset, reshape\n *\n * @param {Array | Matrix | *} x Matrix to be resized\n * @param {Array | Matrix} size One dimensional array with numbers\n * @param {number | string} [defaultValue=0] Zero by default, except in\n * case of a string, in that case\n * defaultValue = ' '\n * @return {* | Array | Matrix} A resized clone of matrix `x`\n */\n // TODO: rework resize to a typed-function\n return function resize(x, size, defaultValue) {\n if (arguments.length !== 2 && arguments.length !== 3) {\n throw new ArgumentsError('resize', arguments.length, 2, 3);\n }\n\n if (isMatrix(size)) {\n size = size.valueOf(); // get Array\n }\n\n if (isBigNumber(size[0])) {\n // convert bignumbers to numbers\n size = size.map(function (value) {\n return !isBigNumber(value) ? value : value.toNumber();\n });\n } // check x is a Matrix\n\n\n if (isMatrix(x)) {\n // use optimized matrix implementation, return copy\n return x.resize(size, defaultValue, true);\n }\n\n if (typeof x === 'string') {\n // resize string\n return _resizeString(x, size, defaultValue);\n } // check result should be a matrix\n\n\n var asMatrix = Array.isArray(x) ? false : config.matrix !== 'Array';\n\n if (size.length === 0) {\n // output a scalar\n while (Array.isArray(x)) {\n x = x[0];\n }\n\n return clone(x);\n } else {\n // output an array/matrix\n if (!Array.isArray(x)) {\n x = [x];\n }\n\n x = clone(x);\n var res = arrayResize(x, size, defaultValue);\n return asMatrix ? matrix(res) : res;\n }\n };\n /**\n * Resize a string\n * @param {string} str\n * @param {number[]} size\n * @param {string} [defaultChar=' ']\n * @private\n */\n\n function _resizeString(str, size, defaultChar) {\n if (defaultChar !== undefined) {\n if (typeof defaultChar !== 'string' || defaultChar.length !== 1) {\n throw new TypeError('Single character expected as defaultValue');\n }\n } else {\n defaultChar = ' ';\n }\n\n if (size.length !== 1) {\n throw new DimensionError(size.length, 1);\n }\n\n var len = size[0];\n\n if (typeof len !== 'number' || !isInteger(len)) {\n throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + format(size) + ')');\n }\n\n if (str.length > len) {\n return str.substring(0, len);\n } else if (str.length < len) {\n var res = str;\n\n for (var i = 0, ii = len - str.length; i < ii; i++) {\n res += defaultChar;\n }\n\n return res;\n } else {\n return str;\n }\n }\n});","import { factory } from '../../utils/factory.js';\nimport { isInteger } from '../../utils/number.js';\nimport { arraySize as size } from '../../utils/array.js';\nimport { powNumber } from '../../plain/number/index.js';\nvar name = 'pow';\nvar dependencies = ['typed', 'config', 'identity', 'multiply', 'matrix', 'fraction', 'number', 'Complex'];\nexport var createPow = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n identity,\n multiply,\n matrix,\n number,\n fraction,\n Complex\n } = _ref;\n\n /**\n * Calculates the power of x to y, `x ^ y`.\n * Matrix exponentiation is supported for square matrices `x`, and positive\n * integer exponents `y`.\n *\n * For cubic roots of negative numbers, the function returns the principal\n * root by default. In order to let the function return the real root,\n * math.js can be configured with `math.config({predictable: true})`.\n * To retrieve all cubic roots of a value, use `math.cbrt(x, true)`.\n *\n * Syntax:\n *\n * math.pow(x, y)\n *\n * Examples:\n *\n * math.pow(2, 3) // returns number 8\n *\n * const a = math.complex(2, 3)\n * math.pow(a, 2) // returns Complex -5 + 12i\n *\n * const b = [[1, 2], [4, 3]]\n * math.pow(b, 2) // returns Array [[9, 8], [16, 17]]\n *\n * See also:\n *\n * multiply, sqrt, cbrt, nthRoot\n *\n * @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base\n * @param {number | BigNumber | Complex} y The exponent\n * @return {number | BigNumber | Complex | Array | Matrix} The value of `x` to the power `y`\n */\n return typed(name, {\n 'number, number': _pow,\n 'Complex, Complex': function ComplexComplex(x, y) {\n return x.pow(y);\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {\n if (y.isInteger() || x >= 0 || config.predictable) {\n return x.pow(y);\n } else {\n return new Complex(x.toNumber(), 0).pow(y.toNumber(), 0);\n }\n },\n 'Fraction, Fraction': function FractionFraction(x, y) {\n if (y.d !== 1) {\n if (config.predictable) {\n throw new Error('Function pow does not support non-integer exponents for fractions.');\n } else {\n return _pow(x.valueOf(), y.valueOf());\n }\n } else {\n return x.pow(y);\n }\n },\n 'Array, number': _powArray,\n 'Array, BigNumber': function ArrayBigNumber(x, y) {\n return _powArray(x, y.toNumber());\n },\n 'Matrix, number': _powMatrix,\n 'Matrix, BigNumber': function MatrixBigNumber(x, y) {\n return _powMatrix(x, y.toNumber());\n },\n 'Unit, number | BigNumber': function UnitNumberBigNumber(x, y) {\n return x.pow(y);\n }\n });\n /**\n * Calculates the power of x to y, x^y, for two numbers.\n * @param {number} x\n * @param {number} y\n * @return {number | Complex} res\n * @private\n */\n\n function _pow(x, y) {\n // Alternatively could define a 'realmode' config option or something, but\n // 'predictable' will work for now\n if (config.predictable && !isInteger(y) && x < 0) {\n // Check to see if y can be represented as a fraction\n try {\n var yFrac = fraction(y);\n var yNum = number(yFrac);\n\n if (y === yNum || Math.abs((y - yNum) / y) < 1e-14) {\n if (yFrac.d % 2 === 1) {\n return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y);\n }\n }\n } catch (ex) {// fraction() throws an error if y is Infinity, etc.\n } // Unable to express y as a fraction, so continue on\n\n } // **for predictable mode** x^Infinity === NaN if x < -1\n // N.B. this behavour is different from `Math.pow` which gives\n // (-2)^Infinity === Infinity\n\n\n if (config.predictable && (x < -1 && y === Infinity || x > -1 && x < 0 && y === -Infinity)) {\n return NaN;\n }\n\n if (isInteger(y) || x >= 0 || config.predictable) {\n return powNumber(x, y);\n } else {\n // TODO: the following infinity checks are duplicated from powNumber. Deduplicate this somehow\n // x^Infinity === 0 if -1 < x < 1\n // A real number 0 is returned instead of complex(0)\n if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) {\n return 0;\n }\n\n return new Complex(x, 0).pow(y, 0);\n }\n }\n /**\n * Calculate the power of a 2d array\n * @param {Array} x must be a 2 dimensional, square matrix\n * @param {number} y a positive, integer value\n * @returns {Array}\n * @private\n */\n\n\n function _powArray(x, y) {\n if (!isInteger(y) || y < 0) {\n throw new TypeError('For A^b, b must be a positive integer (value is ' + y + ')');\n } // verify that A is a 2 dimensional square matrix\n\n\n var s = size(x);\n\n if (s.length !== 2) {\n throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimensions)');\n }\n\n if (s[0] !== s[1]) {\n throw new Error('For A^b, A must be square (size is ' + s[0] + 'x' + s[1] + ')');\n }\n\n var res = identity(s[0]).valueOf();\n var px = x;\n\n while (y >= 1) {\n if ((y & 1) === 1) {\n res = multiply(px, res);\n }\n\n y >>= 1;\n px = multiply(px, px);\n }\n\n return res;\n }\n /**\n * Calculate the power of a 2d matrix\n * @param {Matrix} x must be a 2 dimensional, square matrix\n * @param {number} y a positive, integer value\n * @returns {Matrix}\n * @private\n */\n\n\n function _powMatrix(x, y) {\n return matrix(_powArray(x.valueOf(), y));\n }\n});","/* eslint-disable no-loss-of-precision */\nimport { isInteger } from '../../utils/number.js';\nimport { product } from '../../utils/product.js';\nexport function gammaNumber(n) {\n var x;\n\n if (isInteger(n)) {\n if (n <= 0) {\n return isFinite(n) ? Infinity : NaN;\n }\n\n if (n > 171) {\n return Infinity; // Will overflow\n }\n\n return product(1, n - 1);\n }\n\n if (n < 0.5) {\n return Math.PI / (Math.sin(Math.PI * n) * gammaNumber(1 - n));\n }\n\n if (n >= 171.35) {\n return Infinity; // will overflow\n }\n\n if (n > 85.0) {\n // Extended Stirling Approx\n var twoN = n * n;\n var threeN = twoN * n;\n var fourN = threeN * n;\n var fiveN = fourN * n;\n return Math.sqrt(2 * Math.PI / n) * Math.pow(n / Math.E, n) * (1 + 1 / (12 * n) + 1 / (288 * twoN) - 139 / (51840 * threeN) - 571 / (2488320 * fourN) + 163879 / (209018880 * fiveN) + 5246819 / (75246796800 * fiveN * n));\n }\n\n --n;\n x = gammaP[0];\n\n for (var i = 1; i < gammaP.length; ++i) {\n x += gammaP[i] / (n + i);\n }\n\n var t = n + gammaG + 0.5;\n return Math.sqrt(2 * Math.PI) * Math.pow(t, n + 0.5) * Math.exp(-t) * x;\n}\ngammaNumber.signature = 'number'; // TODO: comment on the variables g and p\n\nexport var gammaG = 4.7421875;\nexport var gammaP = [0.99999999999999709182, 57.156235665862923517, -59.597960355475491248, 14.136097974741747174, -0.49191381609762019978, 0.33994649984811888699e-4, 0.46523628927048575665e-4, -0.98374475304879564677e-4, 0.15808870322491248884e-3, -0.21026444172410488319e-3, 0.21743961811521264320e-3, -0.16431810653676389022e-3, 0.84418223983852743293e-4, -0.26190838401581408670e-4, 0.36899182659531622704e-5];","import { factory } from '../../../utils/factory.js';\nimport { deepMap } from '../../../utils/collection.js';\nvar name = 'bignumber';\nvar dependencies = ['typed', 'BigNumber'];\nexport var createBignumber = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n BigNumber\n } = _ref;\n\n /**\n * Create a BigNumber, which can store numbers with arbitrary precision.\n * When a matrix is provided, all elements will be converted to BigNumber.\n *\n * Syntax:\n *\n * math.bignumber(x)\n *\n * Examples:\n *\n * 0.1 + 0.2 // returns number 0.30000000000000004\n * math.bignumber(0.1) + math.bignumber(0.2) // returns BigNumber 0.3\n *\n *\n * 7.2e500 // returns number Infinity\n * math.bignumber('7.2e500') // returns BigNumber 7.2e500\n *\n * See also:\n *\n * boolean, complex, index, matrix, string, unit\n *\n * @param {number | string | Fraction | BigNumber | Array | Matrix | boolean | null} [value] Value for the big number,\n * 0 by default.\n * @returns {BigNumber} The created bignumber\n */\n return typed('bignumber', {\n '': function _() {\n return new BigNumber(0);\n },\n number: function number(x) {\n // convert to string to prevent errors in case of >15 digits\n return new BigNumber(x + '');\n },\n string: function string(x) {\n var match = x.match(/(0[box][0-9a-fA-F]*)i([0-9]*)/);\n\n if (match) {\n // x has a word size suffix\n var size = match[2];\n var n = BigNumber(match[1]);\n var twoPowSize = new BigNumber(2).pow(Number(size));\n\n if (n.gt(twoPowSize.sub(1))) {\n throw new SyntaxError(\"String \\\"\".concat(x, \"\\\" is out of range\"));\n }\n\n var twoPowSizeSubOne = new BigNumber(2).pow(Number(size) - 1);\n\n if (n.gte(twoPowSizeSubOne)) {\n return n.sub(twoPowSize);\n } else {\n return n;\n }\n }\n\n return new BigNumber(x);\n },\n BigNumber: function BigNumber(x) {\n // we assume a BigNumber is immutable\n return x;\n },\n Fraction: function Fraction(x) {\n return new BigNumber(x.n).div(x.d).times(x.s);\n },\n null: function _null(x) {\n return new BigNumber(0);\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n return deepMap(x, this);\n }\n });\n});","import { typeOf } from '../../utils/is.js';\nimport { factory } from '../../utils/factory.js';\nimport { noBignumber, noFraction } from '../../utils/noop.js';\nvar name = 'numeric';\nvar dependencies = ['number', '?bignumber', '?fraction'];\nexport var createNumeric = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n number: _number,\n bignumber,\n fraction\n } = _ref;\n var validInputTypes = {\n string: true,\n number: true,\n BigNumber: true,\n Fraction: true\n }; // Load the conversion functions for each output type\n\n var validOutputTypes = {\n number: x => _number(x),\n BigNumber: bignumber ? x => bignumber(x) : noBignumber,\n Fraction: fraction ? x => fraction(x) : noFraction\n };\n /**\n * Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.\n *\n * Syntax:\n *\n * math.numeric(x)\n *\n * Examples:\n *\n * math.numeric('4') // returns number 4\n * math.numeric('4', 'number') // returns number 4\n * math.numeric('4', 'BigNumber') // returns BigNumber 4\n * math.numeric('4', 'Fraction') // returns Fraction 4\n * math.numeric(4, 'Fraction') // returns Fraction 4\n * math.numeric(math.fraction(2, 5), 'number') // returns number 0.4\n *\n * See also:\n *\n * number, fraction, bignumber, string, format\n *\n * @param {string | number | BigNumber | Fraction } value\n * A numeric value or a string containing a numeric value\n * @param {string} outputType\n * Desired numeric output type.\n * Available values: 'number', 'BigNumber', or 'Fraction'\n * @return {number | BigNumber | Fraction}\n * Returns an instance of the numeric in the requested type\n */\n\n return function numeric(value, outputType) {\n var inputType = typeOf(value);\n\n if (!(inputType in validInputTypes)) {\n throw new TypeError('Cannot convert ' + value + ' of type \"' + inputType + '\"; valid input types are ' + Object.keys(validInputTypes).join(', '));\n }\n\n if (!(outputType in validOutputTypes)) {\n throw new TypeError('Cannot convert ' + value + ' to type \"' + outputType + '\"; valid output types are ' + Object.keys(validOutputTypes).join(', '));\n }\n\n if (outputType === inputType) {\n return value;\n } else {\n return validOutputTypes[outputType](value);\n }\n };\n});","import Decimal from 'decimal.js';\nimport { factory } from '../../utils/factory.js';\nimport { deepMap } from '../../utils/collection.js';\nimport { nearlyEqual } from '../../utils/number.js';\nimport { nearlyEqual as bigNearlyEqual } from '../../utils/bignumber/nearlyEqual.js';\nimport { ceilNumber } from '../../plain/number/index.js';\nimport { createAlgorithm11 } from '../../type/matrix/utils/algorithm11.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nvar name = 'ceil';\nvar dependencies = ['typed', 'config', 'round', 'matrix', 'equalScalar'];\nexport var createCeil = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n config,\n round,\n matrix,\n equalScalar\n } = _ref;\n var algorithm11 = createAlgorithm11({\n typed,\n equalScalar\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Round a value towards plus infinity\n * If `x` is complex, both real and imaginary part are rounded towards plus infinity.\n * For matrices, the function is evaluated element wise.\n *\n * Syntax:\n *\n * math.ceil(x)\n * math.ceil(x, n)\n *\n * Examples:\n *\n * math.ceil(3.2) // returns number 4\n * math.ceil(3.8) // returns number 4\n * math.ceil(-4.2) // returns number -4\n * math.ceil(-4.7) // returns number -4\n *\n * math.ceil(3.212, 2) // returns number 3.22\n * math.ceil(3.288, 2) // returns number 3.29\n * math.ceil(-4.212, 2) // returns number -4.21\n * math.ceil(-4.782, 2) // returns number -4.78\n *\n * const c = math.complex(3.24, -2.71)\n * math.ceil(c) // returns Complex 4 - 2i\n * math.ceil(c, 1) // returns Complex 3.3 - 2.7i\n *\n * math.ceil([3.2, 3.8, -4.7]) // returns Array [4, 4, -4]\n * math.ceil([3.21, 3.82, -4.71], 1) // returns Array [3.3, 3.9, -4.7]\n *\n * See also:\n *\n * floor, fix, round\n *\n * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded\n * @param {number | BigNumber | Array} [n=0] Number of decimals\n * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value\n */\n\n return typed('ceil', {\n number: function number(x) {\n if (nearlyEqual(x, round(x), config.epsilon)) {\n return round(x);\n } else {\n return ceilNumber(x);\n }\n },\n 'number, number': function numberNumber(x, n) {\n if (nearlyEqual(x, round(x, n), config.epsilon)) {\n return round(x, n);\n } else {\n var [number, exponent] = \"\".concat(x, \"e\").split('e');\n var result = Math.ceil(Number(\"\".concat(number, \"e\").concat(Number(exponent) + n)));\n [number, exponent] = \"\".concat(result, \"e\").split('e');\n return Number(\"\".concat(number, \"e\").concat(Number(exponent) - n));\n }\n },\n Complex: function Complex(x) {\n return x.ceil();\n },\n 'Complex, number': function ComplexNumber(x, n) {\n return x.ceil(n);\n },\n BigNumber: function BigNumber(x) {\n if (bigNearlyEqual(x, round(x), config.epsilon)) {\n return round(x);\n } else {\n return x.ceil();\n }\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, n) {\n if (bigNearlyEqual(x, round(x, n), config.epsilon)) {\n return round(x, n);\n } else {\n return x.toDecimalPlaces(n.toNumber(), Decimal.ROUND_CEIL);\n }\n },\n Fraction: function Fraction(x) {\n return x.ceil();\n },\n 'Fraction, number': function FractionNumber(x, n) {\n return x.ceil(n);\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n // deep map collection, skip zeros since ceil(0) = 0\n return deepMap(x, this, true);\n },\n 'Array | Matrix, number': function ArrayMatrixNumber(x, n) {\n // deep map collection, skip zeros since ceil(0) = 0\n return deepMap(x, i => this(i, n), true);\n },\n 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {\n return algorithm11(x, y, this, false);\n },\n 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {\n return algorithm14(x, y, this, false);\n },\n 'number | Complex | BigNumber, Array': function numberComplexBigNumberArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, this, true).valueOf();\n }\n });\n});","import { factory } from '../../utils/factory.js';\nimport { DimensionError } from '../../error/DimensionError.js';\nimport { createAlgorithm01 } from '../../type/matrix/utils/algorithm01.js';\nimport { createAlgorithm03 } from '../../type/matrix/utils/algorithm03.js';\nimport { createAlgorithm05 } from '../../type/matrix/utils/algorithm05.js';\nimport { createAlgorithm10 } from '../../type/matrix/utils/algorithm10.js';\nimport { createAlgorithm13 } from '../../type/matrix/utils/algorithm13.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nvar name = 'subtract';\nvar dependencies = ['typed', 'matrix', 'equalScalar', 'addScalar', 'unaryMinus', 'DenseMatrix'];\nexport var createSubtract = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n equalScalar,\n addScalar,\n unaryMinus,\n DenseMatrix\n } = _ref;\n // TODO: split function subtract in two: subtract and subtractScalar\n var algorithm01 = createAlgorithm01({\n typed\n });\n var algorithm03 = createAlgorithm03({\n typed\n });\n var algorithm05 = createAlgorithm05({\n typed,\n equalScalar\n });\n var algorithm10 = createAlgorithm10({\n typed,\n DenseMatrix\n });\n var algorithm13 = createAlgorithm13({\n typed\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Subtract two values, `x - y`.\n * For matrices, the function is evaluated element wise.\n *\n * Syntax:\n *\n * math.subtract(x, y)\n *\n * Examples:\n *\n * math.subtract(5.3, 2) // returns number 3.3\n *\n * const a = math.complex(2, 3)\n * const b = math.complex(4, 1)\n * math.subtract(a, b) // returns Complex -2 + 2i\n *\n * math.subtract([5, 7, 4], 4) // returns Array [1, 3, 0]\n *\n * const c = math.unit('2.1 km')\n * const d = math.unit('500m')\n * math.subtract(c, d) // returns Unit 1.6 km\n *\n * See also:\n *\n * add\n *\n * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x\n * Initial value\n * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y\n * Value to subtract from `x`\n * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}\n * Subtraction of `x` and `y`\n */\n\n return typed(name, {\n 'number, number': function numberNumber(x, y) {\n return x - y;\n },\n 'Complex, Complex': function ComplexComplex(x, y) {\n return x.sub(y);\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {\n return x.minus(y);\n },\n 'Fraction, Fraction': function FractionFraction(x, y) {\n return x.sub(y);\n },\n 'Unit, Unit': function UnitUnit(x, y) {\n if (x.value === null) {\n throw new Error('Parameter x contains a unit with undefined value');\n }\n\n if (y.value === null) {\n throw new Error('Parameter y contains a unit with undefined value');\n }\n\n if (!x.equalBase(y)) {\n throw new Error('Units do not match');\n }\n\n var res = x.clone();\n res.value = this(res.value, y.value);\n res.fixPrefix = false;\n return res;\n },\n 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {\n checkEqualDimensions(x, y);\n return algorithm05(x, y, this);\n },\n 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {\n checkEqualDimensions(x, y);\n return algorithm03(y, x, this, true);\n },\n 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {\n checkEqualDimensions(x, y);\n return algorithm01(x, y, this, false);\n },\n 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {\n checkEqualDimensions(x, y);\n return algorithm13(x, y, this);\n },\n 'Array, Array': function ArrayArray(x, y) {\n // use matrix implementation\n return this(matrix(x), matrix(y)).valueOf();\n },\n 'Array, Matrix': function ArrayMatrix(x, y) {\n // use matrix implementation\n return this(matrix(x), y);\n },\n 'Matrix, Array': function MatrixArray(x, y) {\n // use matrix implementation\n return this(x, matrix(y));\n },\n 'SparseMatrix, any': function SparseMatrixAny(x, y) {\n return algorithm10(x, unaryMinus(y), addScalar);\n },\n 'DenseMatrix, any': function DenseMatrixAny(x, y) {\n return algorithm14(x, y, this);\n },\n 'any, SparseMatrix': function anySparseMatrix(x, y) {\n return algorithm10(y, x, this, true);\n },\n 'any, DenseMatrix': function anyDenseMatrix(x, y) {\n return algorithm14(y, x, this, true);\n },\n 'Array, any': function ArrayAny(x, y) {\n // use matrix implementation\n return algorithm14(matrix(x), y, this, false).valueOf();\n },\n 'any, Array': function anyArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, this, true).valueOf();\n }\n });\n});\n/**\n * Check whether matrix x and y have the same number of dimensions.\n * Throws a DimensionError when dimensions are not equal\n * @param {Matrix} x\n * @param {Matrix} y\n */\n\nfunction checkEqualDimensions(x, y) {\n var xsize = x.size();\n var ysize = y.size();\n\n if (xsize.length !== ysize.length) {\n throw new DimensionError(xsize.length, ysize.length);\n }\n}","import { arraySize, squeeze } from '../../utils/array.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'cross';\nvar dependencies = ['typed', 'matrix', 'subtract', 'multiply'];\nexport var createCross = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n subtract,\n multiply\n } = _ref;\n\n /**\n * Calculate the cross product for two vectors in three dimensional space.\n * The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined\n * as:\n *\n * cross(A, B) = [\n * a2 * b3 - a3 * b2,\n * a3 * b1 - a1 * b3,\n * a1 * b2 - a2 * b1\n * ]\n *\n * If one of the input vectors has a dimension greater than 1, the output\n * vector will be a 1x3 (2-dimensional) matrix.\n *\n * Syntax:\n *\n * math.cross(x, y)\n *\n * Examples:\n *\n * math.cross([1, 1, 0], [0, 1, 1]) // Returns [1, -1, 1]\n * math.cross([3, -3, 1], [4, 9, 2]) // Returns [-15, -2, 39]\n * math.cross([2, 3, 4], [5, 6, 7]) // Returns [-3, 6, -3]\n * math.cross([[1, 2, 3]], [[4], [5], [6]]) // Returns [[-3, 6, -3]]\n *\n * See also:\n *\n * dot, multiply\n *\n * @param {Array | Matrix} x First vector\n * @param {Array | Matrix} y Second vector\n * @return {Array | Matrix} Returns the cross product of `x` and `y`\n */\n return typed(name, {\n 'Matrix, Matrix': function MatrixMatrix(x, y) {\n return matrix(_cross(x.toArray(), y.toArray()));\n },\n 'Matrix, Array': function MatrixArray(x, y) {\n return matrix(_cross(x.toArray(), y));\n },\n 'Array, Matrix': function ArrayMatrix(x, y) {\n return matrix(_cross(x, y.toArray()));\n },\n 'Array, Array': _cross\n });\n /**\n * Calculate the cross product for two arrays\n * @param {Array} x First vector\n * @param {Array} y Second vector\n * @returns {Array} Returns the cross product of x and y\n * @private\n */\n\n function _cross(x, y) {\n var highestDimension = Math.max(arraySize(x).length, arraySize(y).length);\n x = squeeze(x);\n y = squeeze(y);\n var xSize = arraySize(x);\n var ySize = arraySize(y);\n\n if (xSize.length !== 1 || ySize.length !== 1 || xSize[0] !== 3 || ySize[0] !== 3) {\n throw new RangeError('Vectors with length 3 expected ' + '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])');\n }\n\n var product = [subtract(multiply(x[1], y[2]), multiply(x[2], y[1])), subtract(multiply(x[2], y[0]), multiply(x[0], y[2])), subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))];\n\n if (highestDimension > 1) {\n return [product];\n } else {\n return product;\n }\n }\n});","import { factory } from '../../utils/factory.js';\nimport { createAlgorithm03 } from '../../type/matrix/utils/algorithm03.js';\nimport { createAlgorithm07 } from '../../type/matrix/utils/algorithm07.js';\nimport { createAlgorithm12 } from '../../type/matrix/utils/algorithm12.js';\nimport { createAlgorithm13 } from '../../type/matrix/utils/algorithm13.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nvar name = 'equal';\nvar dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix'];\nexport var createEqual = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n equalScalar,\n DenseMatrix\n } = _ref;\n var algorithm03 = createAlgorithm03({\n typed\n });\n var algorithm07 = createAlgorithm07({\n typed,\n DenseMatrix\n });\n var algorithm12 = createAlgorithm12({\n typed,\n DenseMatrix\n });\n var algorithm13 = createAlgorithm13({\n typed\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Test whether two values are equal.\n *\n * The function tests whether the relative difference between x and y is\n * smaller than the configured epsilon. The function cannot be used to\n * compare values smaller than approximately 2.22e-16.\n *\n * For matrices, the function is evaluated element wise.\n * In case of complex numbers, x.re must equal y.re, and x.im must equal y.im.\n *\n * Values `null` and `undefined` are compared strictly, thus `null` is only\n * equal to `null` and nothing else, and `undefined` is only equal to\n * `undefined` and nothing else. Strings are compared by their numerical value.\n *\n * Syntax:\n *\n * math.equal(x, y)\n *\n * Examples:\n *\n * math.equal(2 + 2, 3) // returns false\n * math.equal(2 + 2, 4) // returns true\n *\n * const a = math.unit('50 cm')\n * const b = math.unit('5 m')\n * math.equal(a, b) // returns true\n *\n * const c = [2, 5, 1]\n * const d = [2, 7, 1]\n *\n * math.equal(c, d) // returns [true, false, true]\n * math.deepEqual(c, d) // returns false\n *\n * math.equal(\"1000\", \"1e3\") // returns true\n * math.equal(0, null) // returns false\n *\n * See also:\n *\n * unequal, smaller, smallerEq, larger, largerEq, compare, deepEqual, equalText\n *\n * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} x First value to compare\n * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} y Second value to compare\n * @return {boolean | Array | Matrix} Returns true when the compared values are equal, else returns false\n */\n\n return typed(name, {\n 'any, any': function anyAny(x, y) {\n // strict equality for null and undefined?\n if (x === null) {\n return y === null;\n }\n\n if (y === null) {\n return x === null;\n }\n\n if (x === undefined) {\n return y === undefined;\n }\n\n if (y === undefined) {\n return x === undefined;\n }\n\n return equalScalar(x, y);\n },\n 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {\n return algorithm07(x, y, equalScalar);\n },\n 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {\n return algorithm03(y, x, equalScalar, true);\n },\n 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {\n return algorithm03(x, y, equalScalar, false);\n },\n 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {\n return algorithm13(x, y, equalScalar);\n },\n 'Array, Array': function ArrayArray(x, y) {\n // use matrix implementation\n return this(matrix(x), matrix(y)).valueOf();\n },\n 'Array, Matrix': function ArrayMatrix(x, y) {\n // use matrix implementation\n return this(matrix(x), y);\n },\n 'Matrix, Array': function MatrixArray(x, y) {\n // use matrix implementation\n return this(x, matrix(y));\n },\n 'SparseMatrix, any': function SparseMatrixAny(x, y) {\n return algorithm12(x, y, equalScalar, false);\n },\n 'DenseMatrix, any': function DenseMatrixAny(x, y) {\n return algorithm14(x, y, equalScalar, false);\n },\n 'any, SparseMatrix': function anySparseMatrix(x, y) {\n return algorithm12(y, x, equalScalar, true);\n },\n 'any, DenseMatrix': function anyDenseMatrix(x, y) {\n return algorithm14(y, x, equalScalar, true);\n },\n 'Array, any': function ArrayAny(x, y) {\n // use matrix implementation\n return algorithm14(matrix(x), y, equalScalar, false).valueOf();\n },\n 'any, Array': function anyArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, equalScalar, true).valueOf();\n }\n });\n});\nexport var createEqualNumber = factory(name, ['typed', 'equalScalar'], (_ref2) => {\n var {\n typed,\n equalScalar\n } = _ref2;\n return typed(name, {\n 'any, any': function anyAny(x, y) {\n // strict equality for null and undefined?\n if (x === null) {\n return y === null;\n }\n\n if (y === null) {\n return x === null;\n }\n\n if (x === undefined) {\n return y === undefined;\n }\n\n if (y === undefined) {\n return x === undefined;\n }\n\n return equalScalar(x, y);\n }\n });\n});","import { factory } from '../../utils/factory.js';\nimport { deepMap } from '../../utils/collection.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nvar name = 'fix';\nvar dependencies = ['typed', 'Complex', 'matrix', 'ceil', 'floor'];\nexport var createFix = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n Complex: _Complex,\n matrix,\n ceil,\n floor\n } = _ref;\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Round a value towards zero.\n * For matrices, the function is evaluated element wise.\n *\n * Syntax:\n *\n * math.fix(x)\n *\n * Examples:\n *\n * math.fix(3.2) // returns number 3\n * math.fix(3.8) // returns number 3\n * math.fix(-4.2) // returns number -4\n * math.fix(-4.7) // returns number -4\n *\n * math.fix(3.12, 1) // returns number 3.1\n * math.fix(3.18, 1) // returns number 3.1\n * math.fix(-4.12, 1) // returns number -4.1\n * math.fix(-4.17, 1) // returns number -4.1\n *\n * const c = math.complex(3.22, -2.78)\n * math.fix(c) // returns Complex 3 - 2i\n * math.fix(c, 1) // returns Complex 3.2 - 2.7i\n *\n * math.fix([3.2, 3.8, -4.7]) // returns Array [3, 3, -4]\n * math.fix([3.2, 3.8, -4.7], 1) // returns Array [3.2, 3.8, -4.7]\n *\n * See also:\n *\n * ceil, floor, round\n *\n * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded\n * @param {number | BigNumber | Array} [n=0] Number of decimals\n * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value\n */\n\n return typed('fix', {\n number: function number(x) {\n return x > 0 ? floor(x) : ceil(x);\n },\n 'number, number | BigNumber': function numberNumberBigNumber(x, n) {\n return x > 0 ? floor(x, n) : ceil(x, n);\n },\n Complex: function Complex(x) {\n return new _Complex(x.re > 0 ? Math.floor(x.re) : Math.ceil(x.re), x.im > 0 ? Math.floor(x.im) : Math.ceil(x.im));\n },\n 'Complex, number | BigNumber': function ComplexNumberBigNumber(x, n) {\n return new _Complex(x.re > 0 ? floor(x.re, n) : ceil(x.re, n), x.im > 0 ? floor(x.im, n) : ceil(x.im, n));\n },\n BigNumber: function BigNumber(x) {\n return x.isNegative() ? ceil(x) : floor(x);\n },\n 'BigNumber, number | BigNumber': function BigNumberNumberBigNumber(x, n) {\n return x.isNegative() ? ceil(x, n) : floor(x, n);\n },\n Fraction: function Fraction(x) {\n return x.s < 0 ? x.ceil() : x.floor();\n },\n 'Fraction, number | BigNumber': function FractionNumberBigNumber(x, n) {\n return x.s < 0 ? x.ceil(n) : x.floor(n);\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n // deep map collection, skip zeros since fix(0) = 0\n return deepMap(x, this, true);\n },\n 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(x, n) {\n // deep map collection, skip zeros since fix(0) = 0\n return deepMap(x, i => this(i, n), true);\n },\n 'number | Complex | BigNumber, Array': function numberComplexBigNumberArray(x, y) {\n // use matrix implementation\n return algorithm14(matrix(y), x, this, true).valueOf();\n }\n });\n});","import { factory } from '../../utils/factory.js';\nimport { typeOf } from '../../utils/is.js';\nvar name = 'divideScalar';\nvar dependencies = ['typed', 'numeric'];\nexport var createDivideScalar = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n numeric\n } = _ref;\n\n /**\n * Divide two scalar values, `x / y`.\n * This function is meant for internal use: it is used by the public functions\n * `divide` and `inv`.\n *\n * This function does not support collections (Array or Matrix).\n *\n * @param {number | BigNumber | Fraction | Complex | Unit} x Numerator\n * @param {number | BigNumber | Fraction | Complex} y Denominator\n * @return {number | BigNumber | Fraction | Complex | Unit} Quotient, `x / y`\n * @private\n */\n return typed(name, {\n 'number, number': function numberNumber(x, y) {\n return x / y;\n },\n 'Complex, Complex': function ComplexComplex(x, y) {\n return x.div(y);\n },\n 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {\n return x.div(y);\n },\n 'Fraction, Fraction': function FractionFraction(x, y) {\n return x.div(y);\n },\n 'Unit, number | Fraction | BigNumber': function UnitNumberFractionBigNumber(x, y) {\n var res = x.clone(); // TODO: move the divide function to Unit.js, it uses internals of Unit\n\n var one = numeric(1, typeOf(y));\n res.value = this(res.value === null ? res._normalize(one) : res.value, y);\n return res;\n },\n 'number | Fraction | BigNumber, Unit': function numberFractionBigNumberUnit(x, y) {\n var res = y.clone();\n res = res.pow(-1); // TODO: move the divide function to Unit.js, it uses internals of Unit\n\n var one = numeric(1, typeOf(x));\n res.value = this(x, y.value === null ? y._normalize(one) : y.value);\n return res;\n },\n 'Unit, Unit': function UnitUnit(x, y) {\n return x.divide(y);\n }\n });\n});","import { factory } from '../../../utils/factory.js';\nimport { createSolveValidation } from './utils/solveValidation.js';\nvar name = 'lsolve';\nvar dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtract', 'equalScalar', 'DenseMatrix'];\nexport var createLsolve = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n divideScalar,\n multiplyScalar,\n subtract,\n equalScalar,\n DenseMatrix\n } = _ref;\n var solveValidation = createSolveValidation({\n DenseMatrix\n });\n /**\n * Finds one solution of a linear equation system by forwards substitution. Matrix must be a lower triangular matrix. Throws an error if there's no solution.\n *\n * `L * x = b`\n *\n * Syntax:\n *\n * math.lsolve(L, b)\n *\n * Examples:\n *\n * const a = [[-2, 3], [2, 1]]\n * const b = [11, 9]\n * const x = lsolve(a, b) // [[-5.5], [20]]\n *\n * See also:\n *\n * lsolveAll, lup, slu, usolve, lusolve\n *\n * @param {Matrix, Array} L A N x N matrix or array (L)\n * @param {Matrix, Array} b A column vector with the b values\n *\n * @return {DenseMatrix | Array} A column vector with the linear system solution (x)\n */\n\n return typed(name, {\n 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) {\n return _sparseForwardSubstitution(m, b);\n },\n 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) {\n return _denseForwardSubstitution(m, b);\n },\n 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {\n var m = matrix(a);\n\n var r = _denseForwardSubstitution(m, b);\n\n return r.valueOf();\n }\n });\n\n function _denseForwardSubstitution(m, b) {\n // validate matrix and vector, return copy of column vector b\n b = solveValidation(m, b, true);\n var bdata = b._data;\n var rows = m._size[0];\n var columns = m._size[1]; // result\n\n var x = [];\n var mdata = m._data; // loop columns\n\n for (var j = 0; j < columns; j++) {\n var bj = bdata[j][0] || 0;\n var xj = void 0;\n\n if (!equalScalar(bj, 0)) {\n // non-degenerate row, find solution\n var vjj = mdata[j][j];\n\n if (equalScalar(vjj, 0)) {\n throw new Error('Linear system cannot be solved since matrix is singular');\n }\n\n xj = divideScalar(bj, vjj); // loop rows\n\n for (var i = j + 1; i < rows; i++) {\n bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, mdata[i][j]))];\n }\n } else {\n // degenerate row, we can choose any value\n xj = 0;\n }\n\n x[j] = [xj];\n }\n\n return new DenseMatrix({\n data: x,\n size: [rows, 1]\n });\n }\n\n function _sparseForwardSubstitution(m, b) {\n // validate matrix and vector, return copy of column vector b\n b = solveValidation(m, b, true);\n var bdata = b._data;\n var rows = m._size[0];\n var columns = m._size[1];\n var values = m._values;\n var index = m._index;\n var ptr = m._ptr; // result\n\n var x = []; // loop columns\n\n for (var j = 0; j < columns; j++) {\n var bj = bdata[j][0] || 0;\n\n if (!equalScalar(bj, 0)) {\n // non-degenerate row, find solution\n var vjj = 0; // matrix values & indices (column j)\n\n var jValues = [];\n var jIndices = []; // first and last index in the column\n\n var firstIndex = ptr[j];\n var lastIndex = ptr[j + 1]; // values in column, find value at [j, j]\n\n for (var k = firstIndex; k < lastIndex; k++) {\n var i = index[k]; // check row (rows are not sorted!)\n\n if (i === j) {\n vjj = values[k];\n } else if (i > j) {\n // store lower triangular\n jValues.push(values[k]);\n jIndices.push(i);\n }\n } // at this point we must have a value in vjj\n\n\n if (equalScalar(vjj, 0)) {\n throw new Error('Linear system cannot be solved since matrix is singular');\n }\n\n var xj = divideScalar(bj, vjj);\n\n for (var _k = 0, l = jIndices.length; _k < l; _k++) {\n var _i = jIndices[_k];\n bdata[_i] = [subtract(bdata[_i][0] || 0, multiplyScalar(xj, jValues[_k]))];\n }\n\n x[j] = [xj];\n } else {\n // degenerate row, we can choose any value\n x[j] = [0];\n }\n }\n\n return new DenseMatrix({\n data: x,\n size: [rows, 1]\n });\n }\n});","import { factory } from '../../utils/factory.js';\nvar name = 'Spa';\nvar dependencies = ['addScalar', 'equalScalar', 'FibonacciHeap'];\nexport var createSpaClass = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n addScalar,\n equalScalar,\n FibonacciHeap\n } = _ref;\n\n /**\n * An ordered Sparse Accumulator is a representation for a sparse vector that includes a dense array\n * of the vector elements and an ordered list of non-zero elements.\n */\n function Spa() {\n if (!(this instanceof Spa)) {\n throw new SyntaxError('Constructor must be called with the new operator');\n } // allocate vector, TODO use typed arrays\n\n\n this._values = [];\n this._heap = new FibonacciHeap();\n }\n /**\n * Attach type information\n */\n\n\n Spa.prototype.type = 'Spa';\n Spa.prototype.isSpa = true;\n /**\n * Set the value for index i.\n *\n * @param {number} i The index\n * @param {number | BigNumber | Complex} The value at index i\n */\n\n Spa.prototype.set = function (i, v) {\n // check we have a value @ i\n if (!this._values[i]) {\n // insert in heap\n var node = this._heap.insert(i, v); // set the value @ i\n\n\n this._values[i] = node;\n } else {\n // update the value @ i\n this._values[i].value = v;\n }\n };\n\n Spa.prototype.get = function (i) {\n var node = this._values[i];\n\n if (node) {\n return node.value;\n }\n\n return 0;\n };\n\n Spa.prototype.accumulate = function (i, v) {\n // node @ i\n var node = this._values[i];\n\n if (!node) {\n // insert in heap\n node = this._heap.insert(i, v); // initialize value\n\n this._values[i] = node;\n } else {\n // accumulate value\n node.value = addScalar(node.value, v);\n }\n };\n\n Spa.prototype.forEach = function (from, to, callback) {\n // references\n var heap = this._heap;\n var values = this._values; // nodes\n\n var nodes = []; // node with minimum key, save it\n\n var node = heap.extractMinimum();\n\n if (node) {\n nodes.push(node);\n } // extract nodes from heap (ordered)\n\n\n while (node && node.key <= to) {\n // check it is in range\n if (node.key >= from) {\n // check value is not zero\n if (!equalScalar(node.value, 0)) {\n // invoke callback\n callback(node.key, node.value, this);\n }\n } // extract next node, save it\n\n\n node = heap.extractMinimum();\n\n if (node) {\n nodes.push(node);\n }\n } // reinsert all nodes in heap\n\n\n for (var i = 0; i < nodes.length; i++) {\n // current node\n var n = nodes[i]; // insert node in heap\n\n node = heap.insert(n.key, n.value); // update values\n\n values[node.key] = node;\n }\n };\n\n Spa.prototype.swap = function (i, j) {\n // node @ i and j\n var nodei = this._values[i];\n var nodej = this._values[j]; // check we need to insert indeces\n\n if (!nodei && nodej) {\n // insert in heap\n nodei = this._heap.insert(i, nodej.value); // remove from heap\n\n this._heap.remove(nodej); // set values\n\n\n this._values[i] = nodei;\n this._values[j] = undefined;\n } else if (nodei && !nodej) {\n // insert in heap\n nodej = this._heap.insert(j, nodei.value); // remove from heap\n\n this._heap.remove(nodei); // set values\n\n\n this._values[j] = nodej;\n this._values[i] = undefined;\n } else if (nodei && nodej) {\n // swap values\n var v = nodei.value;\n nodei.value = nodej.value;\n nodej.value = v;\n }\n };\n\n return Spa;\n}, {\n isClass: true\n});","import { clone } from '../../../utils/object.js';\nimport { factory } from '../../../utils/factory.js';\nvar name = 'lup';\nvar dependencies = ['typed', 'matrix', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtract', 'larger', 'equalScalar', 'unaryMinus', 'DenseMatrix', 'SparseMatrix', 'Spa'];\nexport var createLup = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n abs,\n addScalar,\n divideScalar,\n multiplyScalar,\n subtract,\n larger,\n equalScalar,\n unaryMinus,\n DenseMatrix,\n SparseMatrix,\n Spa\n } = _ref;\n\n /**\n * Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a\n * row permutation vector `p` where `A[p,:] = L * U`\n *\n * Syntax:\n *\n * math.lup(A)\n *\n * Example:\n *\n * const m = [[2, 1], [1, 4]]\n * const r = math.lup(m)\n * // r = {\n * // L: [[1, 0], [0.5, 1]],\n * // U: [[2, 1], [0, 3.5]],\n * // P: [0, 1]\n * // }\n *\n * See also:\n *\n * slu, lsolve, lusolve, usolve\n *\n * @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition.\n *\n * @return {{L: Array | Matrix, U: Array | Matrix, P: Array.}} The lower triangular matrix, the upper triangular matrix and the permutation matrix.\n */\n return typed(name, {\n DenseMatrix: function DenseMatrix(m) {\n return _denseLUP(m);\n },\n SparseMatrix: function SparseMatrix(m) {\n return _sparseLUP(m);\n },\n Array: function Array(a) {\n // create dense matrix from array\n var m = matrix(a); // lup, use matrix implementation\n\n var r = _denseLUP(m); // result\n\n\n return {\n L: r.L.valueOf(),\n U: r.U.valueOf(),\n p: r.p\n };\n }\n });\n\n function _denseLUP(m) {\n // rows & columns\n var rows = m._size[0];\n var columns = m._size[1]; // minimum rows and columns\n\n var n = Math.min(rows, columns); // matrix array, clone original data\n\n var data = clone(m._data); // l matrix arrays\n\n var ldata = [];\n var lsize = [rows, n]; // u matrix arrays\n\n var udata = [];\n var usize = [n, columns]; // vars\n\n var i, j, k; // permutation vector\n\n var p = [];\n\n for (i = 0; i < rows; i++) {\n p[i] = i;\n } // loop columns\n\n\n for (j = 0; j < columns; j++) {\n // skip first column in upper triangular matrix\n if (j > 0) {\n // loop rows\n for (i = 0; i < rows; i++) {\n // min i,j\n var min = Math.min(i, j); // v[i, j]\n\n var s = 0; // loop up to min\n\n for (k = 0; k < min; k++) {\n // s = l[i, k] - data[k, j]\n s = addScalar(s, multiplyScalar(data[i][k], data[k][j]));\n }\n\n data[i][j] = subtract(data[i][j], s);\n }\n } // row with larger value in cvector, row >= j\n\n\n var pi = j;\n var pabsv = 0;\n var vjj = 0; // loop rows\n\n for (i = j; i < rows; i++) {\n // data @ i, j\n var v = data[i][j]; // absolute value\n\n var absv = abs(v); // value is greater than pivote value\n\n if (larger(absv, pabsv)) {\n // store row\n pi = i; // update max value\n\n pabsv = absv; // value @ [j, j]\n\n vjj = v;\n }\n } // swap rows (j <-> pi)\n\n\n if (j !== pi) {\n // swap values j <-> pi in p\n p[j] = [p[pi], p[pi] = p[j]][0]; // swap j <-> pi in data\n\n DenseMatrix._swapRows(j, pi, data);\n } // check column is in lower triangular matrix\n\n\n if (j < rows) {\n // loop rows (lower triangular matrix)\n for (i = j + 1; i < rows; i++) {\n // value @ i, j\n var vij = data[i][j];\n\n if (!equalScalar(vij, 0)) {\n // update data\n data[i][j] = divideScalar(data[i][j], vjj);\n }\n }\n }\n } // loop columns\n\n\n for (j = 0; j < columns; j++) {\n // loop rows\n for (i = 0; i < rows; i++) {\n // initialize row in arrays\n if (j === 0) {\n // check row exists in upper triangular matrix\n if (i < columns) {\n // U\n udata[i] = [];\n } // L\n\n\n ldata[i] = [];\n } // check we are in the upper triangular matrix\n\n\n if (i < j) {\n // check row exists in upper triangular matrix\n if (i < columns) {\n // U\n udata[i][j] = data[i][j];\n } // check column exists in lower triangular matrix\n\n\n if (j < rows) {\n // L\n ldata[i][j] = 0;\n }\n\n continue;\n } // diagonal value\n\n\n if (i === j) {\n // check row exists in upper triangular matrix\n if (i < columns) {\n // U\n udata[i][j] = data[i][j];\n } // check column exists in lower triangular matrix\n\n\n if (j < rows) {\n // L\n ldata[i][j] = 1;\n }\n\n continue;\n } // check row exists in upper triangular matrix\n\n\n if (i < columns) {\n // U\n udata[i][j] = 0;\n } // check column exists in lower triangular matrix\n\n\n if (j < rows) {\n // L\n ldata[i][j] = data[i][j];\n }\n }\n } // l matrix\n\n\n var l = new DenseMatrix({\n data: ldata,\n size: lsize\n }); // u matrix\n\n var u = new DenseMatrix({\n data: udata,\n size: usize\n }); // p vector\n\n var pv = [];\n\n for (i = 0, n = p.length; i < n; i++) {\n pv[p[i]] = i;\n } // return matrices\n\n\n return {\n L: l,\n U: u,\n p: pv,\n toString: function toString() {\n return 'L: ' + this.L.toString() + '\\nU: ' + this.U.toString() + '\\nP: ' + this.p;\n }\n };\n }\n\n function _sparseLUP(m) {\n // rows & columns\n var rows = m._size[0];\n var columns = m._size[1]; // minimum rows and columns\n\n var n = Math.min(rows, columns); // matrix arrays (will not be modified, thanks to permutation vector)\n\n var values = m._values;\n var index = m._index;\n var ptr = m._ptr; // l matrix arrays\n\n var lvalues = [];\n var lindex = [];\n var lptr = [];\n var lsize = [rows, n]; // u matrix arrays\n\n var uvalues = [];\n var uindex = [];\n var uptr = [];\n var usize = [n, columns]; // vars\n\n var i, j, k; // permutation vectors, (current index -> original index) and (original index -> current index)\n\n var pvCo = [];\n var pvOc = [];\n\n for (i = 0; i < rows; i++) {\n pvCo[i] = i;\n pvOc[i] = i;\n } // swap indices in permutation vectors (condition x < y)!\n\n\n var swapIndeces = function swapIndeces(x, y) {\n // find pv indeces getting data from x and y\n var kx = pvOc[x];\n var ky = pvOc[y]; // update permutation vector current -> original\n\n pvCo[kx] = y;\n pvCo[ky] = x; // update permutation vector original -> current\n\n pvOc[x] = ky;\n pvOc[y] = kx;\n }; // loop columns\n\n\n var _loop = function _loop() {\n // sparse accumulator\n var spa = new Spa(); // check lower triangular matrix has a value @ column j\n\n if (j < rows) {\n // update ptr\n lptr.push(lvalues.length); // first value in j column for lower triangular matrix\n\n lvalues.push(1);\n lindex.push(j);\n } // update ptr\n\n\n uptr.push(uvalues.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]\n\n var k0 = ptr[j];\n var k1 = ptr[j + 1]; // copy column j into sparse accumulator\n\n for (k = k0; k < k1; k++) {\n // row\n i = index[k]; // copy column values into sparse accumulator (use permutation vector)\n\n spa.set(pvCo[i], values[k]);\n } // skip first column in upper triangular matrix\n\n\n if (j > 0) {\n // loop rows in column j (above diagonal)\n spa.forEach(0, j - 1, function (k, vkj) {\n // loop rows in column k (L)\n SparseMatrix._forEachRow(k, lvalues, lindex, lptr, function (i, vik) {\n // check row is below k\n if (i > k) {\n // update spa value\n spa.accumulate(i, unaryMinus(multiplyScalar(vik, vkj)));\n }\n });\n });\n } // row with larger value in spa, row >= j\n\n\n var pi = j;\n var vjj = spa.get(j);\n var pabsv = abs(vjj); // loop values in spa (order by row, below diagonal)\n\n spa.forEach(j + 1, rows - 1, function (x, v) {\n // absolute value\n var absv = abs(v); // value is greater than pivote value\n\n if (larger(absv, pabsv)) {\n // store row\n pi = x; // update max value\n\n pabsv = absv; // value @ [j, j]\n\n vjj = v;\n }\n }); // swap rows (j <-> pi)\n\n if (j !== pi) {\n // swap values j <-> pi in L\n SparseMatrix._swapRows(j, pi, lsize[1], lvalues, lindex, lptr); // swap values j <-> pi in U\n\n\n SparseMatrix._swapRows(j, pi, usize[1], uvalues, uindex, uptr); // swap values in spa\n\n\n spa.swap(j, pi); // update permutation vector (swap values @ j, pi)\n\n swapIndeces(j, pi);\n } // loop values in spa (order by row)\n\n\n spa.forEach(0, rows - 1, function (x, v) {\n // check we are above diagonal\n if (x <= j) {\n // update upper triangular matrix\n uvalues.push(v);\n uindex.push(x);\n } else {\n // update value\n v = divideScalar(v, vjj); // check value is non zero\n\n if (!equalScalar(v, 0)) {\n // update lower triangular matrix\n lvalues.push(v);\n lindex.push(x);\n }\n }\n });\n };\n\n for (j = 0; j < columns; j++) {\n _loop();\n } // update ptrs\n\n\n uptr.push(uvalues.length);\n lptr.push(lvalues.length); // return matrices\n\n return {\n L: new SparseMatrix({\n values: lvalues,\n index: lindex,\n ptr: lptr,\n size: lsize\n }),\n U: new SparseMatrix({\n values: uvalues,\n index: uindex,\n ptr: uptr,\n size: usize\n }),\n p: pvCo,\n toString: function toString() {\n return 'L: ' + this.L.toString() + '\\nU: ' + this.U.toString() + '\\nP: ' + this.p;\n }\n };\n }\n});","import { csReach } from './csReach.js';\nimport { factory } from '../../../utils/factory.js';\nvar name = 'csSpsolve';\nvar dependencies = ['divideScalar', 'multiply', 'subtract'];\nexport var createCsSpsolve = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n divideScalar,\n multiply,\n subtract\n } = _ref;\n\n /**\n * The function csSpsolve() computes the solution to G * x = bk, where bk is the\n * kth column of B. When lo is true, the function assumes G = L is lower triangular with the\n * diagonal entry as the first entry in each column. When lo is true, the function assumes G = U\n * is upper triangular with the diagonal entry as the last entry in each column.\n *\n * @param {Matrix} g The G matrix\n * @param {Matrix} b The B matrix\n * @param {Number} k The kth column in B\n * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n\n * The first n entries is the nonzero pattern, the last n entries is the stack\n * @param {Array} x The soluton to the linear system G * x = b\n * @param {Array} pinv The inverse row permutation vector, must be null for L * x = b\n * @param {boolean} lo The lower (true) upper triangular (false) flag\n *\n * @return {Number} The index for the nonzero pattern\n *\n * Reference: http://faculty.cse.tamu.edu/davis/publications.html\n */\n return function csSpsolve(g, b, k, xi, x, pinv, lo) {\n // g arrays\n var gvalues = g._values;\n var gindex = g._index;\n var gptr = g._ptr;\n var gsize = g._size; // columns\n\n var n = gsize[1]; // b arrays\n\n var bvalues = b._values;\n var bindex = b._index;\n var bptr = b._ptr; // vars\n\n var p, p0, p1, q; // xi[top..n-1] = csReach(B(:,k))\n\n var top = csReach(g, b, k, xi, pinv); // clear x\n\n for (p = top; p < n; p++) {\n x[xi[p]] = 0;\n } // scatter b\n\n\n for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) {\n x[bindex[p]] = bvalues[p];\n } // loop columns\n\n\n for (var px = top; px < n; px++) {\n // x array index for px\n var j = xi[px]; // apply permutation vector (U x = b), j maps to column J of G\n\n var J = pinv ? pinv[j] : j; // check column J is empty\n\n if (J < 0) {\n continue;\n } // column value indeces in G, p0 <= p < p1\n\n\n p0 = gptr[J];\n p1 = gptr[J + 1]; // x(j) /= G(j,j)\n\n x[j] = divideScalar(x[j], gvalues[lo ? p0 : p1 - 1]); // first entry L(j,j)\n\n p = lo ? p0 + 1 : p0;\n q = lo ? p1 : p1 - 1; // loop\n\n for (; p < q; p++) {\n // row\n var i = gindex[p]; // x(i) -= G(i,j) * x(j)\n\n x[i] = subtract(x[i], multiply(gvalues[p], x[j]));\n }\n } // return top of stack\n\n\n return top;\n };\n});","import { isMatrix } from '../../utils/is.js';\nimport { clone } from '../../utils/object.js';\nimport { format } from '../../utils/string.js';\nimport { factory } from '../../utils/factory.js';\nvar name = 'det';\nvar dependencies = ['typed', 'matrix', 'subtract', 'multiply', 'unaryMinus', 'lup'];\nexport var createDet = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n subtract,\n multiply,\n unaryMinus,\n lup\n } = _ref;\n\n /**\n * Calculate the determinant of a matrix.\n *\n * Syntax:\n *\n * math.det(x)\n *\n * Examples:\n *\n * math.det([[1, 2], [3, 4]]) // returns -2\n *\n * const A = [\n * [-2, 2, 3],\n * [-1, 1, 3],\n * [2, 0, -1]\n * ]\n * math.det(A) // returns 6\n *\n * See also:\n *\n * inv\n *\n * @param {Array | Matrix} x A matrix\n * @return {number} The determinant of `x`\n */\n return typed(name, {\n any: function any(x) {\n return clone(x);\n },\n 'Array | Matrix': function det(x) {\n var size;\n\n if (isMatrix(x)) {\n size = x.size();\n } else if (Array.isArray(x)) {\n x = matrix(x);\n size = x.size();\n } else {\n // a scalar\n size = [];\n }\n\n switch (size.length) {\n case 0:\n // scalar\n return clone(x);\n\n case 1:\n // vector\n if (size[0] === 1) {\n return clone(x.valueOf()[0]);\n } else {\n throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');\n }\n\n case 2:\n {\n // two dimensional array\n var rows = size[0];\n var cols = size[1];\n\n if (rows === cols) {\n return _det(x.clone().valueOf(), rows, cols);\n } else {\n throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');\n }\n }\n\n default:\n // multi dimensional array\n throw new RangeError('Matrix must be two dimensional ' + '(size: ' + format(size) + ')');\n }\n }\n });\n /**\n * Calculate the determinant of a matrix\n * @param {Array[]} matrix A square, two dimensional matrix\n * @param {number} rows Number of rows of the matrix (zero-based)\n * @param {number} cols Number of columns of the matrix (zero-based)\n * @returns {number} det\n * @private\n */\n\n function _det(matrix, rows, cols) {\n if (rows === 1) {\n // this is a 1 x 1 matrix\n return clone(matrix[0][0]);\n } else if (rows === 2) {\n // this is a 2 x 2 matrix\n // the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12\n return subtract(multiply(matrix[0][0], matrix[1][1]), multiply(matrix[1][0], matrix[0][1]));\n } else {\n // Compute the LU decomposition\n var decomp = lup(matrix); // The determinant is the product of the diagonal entries of U (and those of L, but they are all 1)\n\n var det = decomp.U[0][0];\n\n for (var _i = 1; _i < rows; _i++) {\n det = multiply(det, decomp.U[_i][_i]);\n } // The determinant will be multiplied by 1 or -1 depending on the parity of the permutation matrix.\n // This can be determined by counting the cycles. This is roughly a linear time algorithm.\n\n\n var evenCycles = 0;\n var i = 0;\n var visited = [];\n\n while (true) {\n while (visited[i]) {\n i++;\n }\n\n if (i >= rows) break;\n var j = i;\n var cycleLen = 0;\n\n while (!visited[decomp.p[j]]) {\n visited[decomp.p[j]] = true;\n j = decomp.p[j];\n cycleLen++;\n }\n\n if (cycleLen % 2 === 0) {\n evenCycles++;\n }\n }\n\n return evenCycles % 2 === 0 ? det : unaryMinus(det);\n }\n }\n});","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nimport { factory } from '../../../utils/factory.js';\nvar name = 'qr';\nvar dependencies = ['typed', 'matrix', 'zeros', 'identity', 'isZero', 'equal', 'sign', 'sqrt', 'conj', 'unaryMinus', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtract', 'complex'];\nexport var createQr = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n zeros,\n identity,\n isZero,\n equal,\n sign,\n sqrt,\n conj,\n unaryMinus,\n addScalar,\n divideScalar,\n multiplyScalar,\n subtract,\n complex\n } = _ref;\n\n /**\n * Calculate the Matrix QR decomposition. Matrix `A` is decomposed in\n * two matrices (`Q`, `R`) where `Q` is an\n * orthogonal matrix and `R` is an upper triangular matrix.\n *\n * Syntax:\n *\n * math.qr(A)\n *\n * Example:\n *\n * const m = [\n * [1, -1, 4],\n * [1, 4, -2],\n * [1, 4, 2],\n * [1, -1, 0]\n * ]\n * const result = math.qr(m)\n * // r = {\n * // Q: [\n * // [0.5, -0.5, 0.5],\n * // [0.5, 0.5, -0.5],\n * // [0.5, 0.5, 0.5],\n * // [0.5, -0.5, -0.5],\n * // ],\n * // R: [\n * // [2, 3, 2],\n * // [0, 5, -2],\n * // [0, 0, 4],\n * // [0, 0, 0]\n * // ]\n * // }\n *\n * See also:\n *\n * lup, lusolve\n *\n * @param {Matrix | Array} A A two dimensional matrix or array\n * for which to get the QR decomposition.\n *\n * @return {{Q: Array | Matrix, R: Array | Matrix}} Q: the orthogonal\n * matrix and R: the upper triangular matrix\n */\n return _extends(typed(name, {\n DenseMatrix: function DenseMatrix(m) {\n return _denseQR(m);\n },\n SparseMatrix: function SparseMatrix(m) {\n return _sparseQR(m);\n },\n Array: function Array(a) {\n // create dense matrix from array\n var m = matrix(a); // lup, use matrix implementation\n\n var r = _denseQR(m); // result\n\n\n return {\n Q: r.Q.valueOf(),\n R: r.R.valueOf()\n };\n }\n }), {\n _denseQRimpl\n });\n\n function _denseQRimpl(m) {\n // rows & columns (m x n)\n var rows = m._size[0]; // m\n\n var cols = m._size[1]; // n\n\n var Q = identity([rows], 'dense');\n var Qdata = Q._data;\n var R = m.clone();\n var Rdata = R._data; // vars\n\n var i, j, k;\n var w = zeros([rows], '');\n\n for (k = 0; k < Math.min(cols, rows); ++k) {\n /*\n * **k-th Household matrix**\n *\n * The matrix I - 2*v*transpose(v)\n * x = first column of A\n * x1 = first element of x\n * alpha = x1 / |x1| * |x|\n * e1 = tranpose([1, 0, 0, ...])\n * u = x - alpha * e1\n * v = u / |u|\n *\n * Household matrix = I - 2 * v * tranpose(v)\n *\n * * Initially Q = I and R = A.\n * * Household matrix is a reflection in a plane normal to v which\n * will zero out all but the top right element in R.\n * * Appplying reflection to both Q and R will not change product.\n * * Repeat this process on the (1,1) minor to get R as an upper\n * triangular matrix.\n * * Reflections leave the magnitude of the columns of Q unchanged\n * so Q remains othoganal.\n *\n */\n var pivot = Rdata[k][k];\n var sgn = unaryMinus(equal(pivot, 0) ? 1 : sign(pivot));\n var conjSgn = conj(sgn);\n var alphaSquared = 0;\n\n for (i = k; i < rows; i++) {\n alphaSquared = addScalar(alphaSquared, multiplyScalar(Rdata[i][k], conj(Rdata[i][k])));\n }\n\n var alpha = multiplyScalar(sgn, sqrt(alphaSquared));\n\n if (!isZero(alpha)) {\n // first element in vector u\n var u1 = subtract(pivot, alpha); // w = v * u1 / |u| (only elements k to (rows-1) are used)\n\n w[k] = 1;\n\n for (i = k + 1; i < rows; i++) {\n w[i] = divideScalar(Rdata[i][k], u1);\n } // tau = - conj(u1 / alpha)\n\n\n var tau = unaryMinus(conj(divideScalar(u1, alpha)));\n var s = void 0;\n /*\n * tau and w have been choosen so that\n *\n * 2 * v * tranpose(v) = tau * w * tranpose(w)\n */\n\n /*\n * -- calculate R = R - tau * w * tranpose(w) * R --\n * Only do calculation with rows k to (rows-1)\n * Additionally columns 0 to (k-1) will not be changed by this\n * multiplication so do not bother recalculating them\n */\n\n for (j = k; j < cols; j++) {\n s = 0.0; // calculate jth element of [tranpose(w) * R]\n\n for (i = k; i < rows; i++) {\n s = addScalar(s, multiplyScalar(conj(w[i]), Rdata[i][j]));\n } // calculate the jth element of [tau * transpose(w) * R]\n\n\n s = multiplyScalar(s, tau);\n\n for (i = k; i < rows; i++) {\n Rdata[i][j] = multiplyScalar(subtract(Rdata[i][j], multiplyScalar(w[i], s)), conjSgn);\n }\n }\n /*\n * -- calculate Q = Q - tau * Q * w * transpose(w) --\n * Q is a square matrix (rows x rows)\n * Only do calculation with columns k to (rows-1)\n * Additionally rows 0 to (k-1) will not be changed by this\n * multiplication so do not bother recalculating them\n */\n\n\n for (i = 0; i < rows; i++) {\n s = 0.0; // calculate ith element of [Q * w]\n\n for (j = k; j < rows; j++) {\n s = addScalar(s, multiplyScalar(Qdata[i][j], w[j]));\n } // calculate the ith element of [tau * Q * w]\n\n\n s = multiplyScalar(s, tau);\n\n for (j = k; j < rows; ++j) {\n Qdata[i][j] = divideScalar(subtract(Qdata[i][j], multiplyScalar(s, conj(w[j]))), conjSgn);\n }\n }\n }\n } // return matrices\n\n\n return {\n Q: Q,\n R: R,\n toString: function toString() {\n return 'Q: ' + this.Q.toString() + '\\nR: ' + this.R.toString();\n }\n };\n }\n\n function _denseQR(m) {\n var ret = _denseQRimpl(m);\n\n var Rdata = ret.R._data;\n\n if (m._data.length > 0) {\n var zero = Rdata[0][0].type === 'Complex' ? complex(0) : 0;\n\n for (var i = 0; i < Rdata.length; ++i) {\n for (var j = 0; j < i && j < (Rdata[0] || []).length; ++j) {\n Rdata[i][j] = zero;\n }\n }\n }\n\n return ret;\n }\n\n function _sparseQR(m) {\n throw new Error('qr not implemented for sparse matrices yet');\n }\n});","import { isMatrix } from '../../utils/is.js';\nimport { arraySize } from '../../utils/array.js';\nimport { factory } from '../../utils/factory.js';\nimport { format } from '../../utils/string.js';\nvar name = 'inv';\nvar dependencies = ['typed', 'matrix', 'divideScalar', 'addScalar', 'multiply', 'unaryMinus', 'det', 'identity', 'abs'];\nexport var createInv = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n divideScalar,\n addScalar,\n multiply,\n unaryMinus,\n det,\n identity,\n abs\n } = _ref;\n\n /**\n * Calculate the inverse of a square matrix.\n *\n * Syntax:\n *\n * math.inv(x)\n *\n * Examples:\n *\n * math.inv([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]]\n * math.inv(4) // returns 0.25\n * 1 / 4 // returns 0.25\n *\n * See also:\n *\n * det, transpose\n *\n * @param {number | Complex | Array | Matrix} x Matrix to be inversed\n * @return {number | Complex | Array | Matrix} The inverse of `x`.\n */\n return typed(name, {\n 'Array | Matrix': function ArrayMatrix(x) {\n var size = isMatrix(x) ? x.size() : arraySize(x);\n\n switch (size.length) {\n case 1:\n // vector\n if (size[0] === 1) {\n if (isMatrix(x)) {\n return matrix([divideScalar(1, x.valueOf()[0])]);\n } else {\n return [divideScalar(1, x[0])];\n }\n } else {\n throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');\n }\n\n case 2:\n // two dimensional array\n {\n var rows = size[0];\n var cols = size[1];\n\n if (rows === cols) {\n if (isMatrix(x)) {\n return matrix(_inv(x.valueOf(), rows, cols), x.storage());\n } else {\n // return an Array\n return _inv(x, rows, cols);\n }\n } else {\n throw new RangeError('Matrix must be square ' + '(size: ' + format(size) + ')');\n }\n }\n\n default:\n // multi dimensional array\n throw new RangeError('Matrix must be two dimensional ' + '(size: ' + format(size) + ')');\n }\n },\n any: function any(x) {\n // scalar\n return divideScalar(1, x); // FIXME: create a BigNumber one when configured for bignumbers\n }\n });\n /**\n * Calculate the inverse of a square matrix\n * @param {Array[]} mat A square matrix\n * @param {number} rows Number of rows\n * @param {number} cols Number of columns, must equal rows\n * @return {Array[]} inv Inverse matrix\n * @private\n */\n\n function _inv(mat, rows, cols) {\n var r, s, f, value, temp;\n\n if (rows === 1) {\n // this is a 1 x 1 matrix\n value = mat[0][0];\n\n if (value === 0) {\n throw Error('Cannot calculate inverse, determinant is zero');\n }\n\n return [[divideScalar(1, value)]];\n } else if (rows === 2) {\n // this is a 2 x 2 matrix\n var d = det(mat);\n\n if (d === 0) {\n throw Error('Cannot calculate inverse, determinant is zero');\n }\n\n return [[divideScalar(mat[1][1], d), divideScalar(unaryMinus(mat[0][1]), d)], [divideScalar(unaryMinus(mat[1][0]), d), divideScalar(mat[0][0], d)]];\n } else {\n // this is a matrix of 3 x 3 or larger\n // calculate inverse using gauss-jordan elimination\n // https://en.wikipedia.org/wiki/Gaussian_elimination\n // http://mathworld.wolfram.com/MatrixInverse.html\n // http://math.uww.edu/~mcfarlat/inverse.htm\n // make a copy of the matrix (only the arrays, not of the elements)\n var A = mat.concat();\n\n for (r = 0; r < rows; r++) {\n A[r] = A[r].concat();\n } // create an identity matrix which in the end will contain the\n // matrix inverse\n\n\n var B = identity(rows).valueOf(); // loop over all columns, and perform row reductions\n\n for (var c = 0; c < cols; c++) {\n // Pivoting: Swap row c with row r, where row r contains the largest element A[r][c]\n var ABig = abs(A[c][c]);\n var rBig = c;\n r = c + 1;\n\n while (r < rows) {\n if (abs(A[r][c]) > ABig) {\n ABig = abs(A[r][c]);\n rBig = r;\n }\n\n r++;\n }\n\n if (ABig === 0) {\n throw Error('Cannot calculate inverse, determinant is zero');\n }\n\n r = rBig;\n\n if (r !== c) {\n temp = A[c];\n A[c] = A[r];\n A[r] = temp;\n temp = B[c];\n B[c] = B[r];\n B[r] = temp;\n } // eliminate non-zero values on the other rows at column c\n\n\n var Ac = A[c];\n var Bc = B[c];\n\n for (r = 0; r < rows; r++) {\n var Ar = A[r];\n var Br = B[r];\n\n if (r !== c) {\n // eliminate value at column c and row r\n if (Ar[c] !== 0) {\n f = divideScalar(unaryMinus(Ar[c]), Ac[c]); // add (f * row c) to row r to eliminate the value\n // at column c\n\n for (s = c; s < cols; s++) {\n Ar[s] = addScalar(Ar[s], multiply(f, Ac[s]));\n }\n\n for (s = 0; s < cols; s++) {\n Br[s] = addScalar(Br[s], multiply(f, Bc[s]));\n }\n }\n } else {\n // normalize value at Acc to 1,\n // divide each value on row r with the value at Acc\n f = Ac[c];\n\n for (s = c; s < cols; s++) {\n Ar[s] = divideScalar(Ar[s], f);\n }\n\n for (s = 0; s < cols; s++) {\n Br[s] = divideScalar(Br[s], f);\n }\n }\n }\n }\n\n return B;\n }\n }\n});","import { factory } from '../../utils/factory.js';\nimport { extend } from '../../utils/object.js';\nimport { createAlgorithm11 } from '../../type/matrix/utils/algorithm11.js';\nimport { createAlgorithm14 } from '../../type/matrix/utils/algorithm14.js';\nvar name = 'divide';\nvar dependencies = ['typed', 'matrix', 'multiply', 'equalScalar', 'divideScalar', 'inv'];\nexport var createDivide = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n multiply,\n equalScalar,\n divideScalar,\n inv\n } = _ref;\n var algorithm11 = createAlgorithm11({\n typed,\n equalScalar\n });\n var algorithm14 = createAlgorithm14({\n typed\n });\n /**\n * Divide two values, `x / y`.\n * To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.\n *\n * Syntax:\n *\n * math.divide(x, y)\n *\n * Examples:\n *\n * math.divide(2, 3) // returns number 0.6666666666666666\n *\n * const a = math.complex(5, 14)\n * const b = math.complex(4, 1)\n * math.divide(a, b) // returns Complex 2 + 3i\n *\n * const c = [[7, -6], [13, -4]]\n * const d = [[1, 2], [4, 3]]\n * math.divide(c, d) // returns Array [[-9, 4], [-11, 6]]\n *\n * const e = math.unit('18 km')\n * math.divide(e, 4.5) // returns Unit 4 km\n *\n * See also:\n *\n * multiply\n *\n * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator\n * @param {number | BigNumber | Fraction | Complex | Array | Matrix} y Denominator\n * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x / y`\n */\n\n return typed('divide', extend({\n // we extend the signatures of divideScalar with signatures dealing with matrices\n 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(x, y) {\n // TODO: implement matrix right division using pseudo inverse\n // https://www.mathworks.nl/help/matlab/ref/mrdivide.html\n // https://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html\n // https://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour\n return multiply(x, inv(y));\n },\n 'DenseMatrix, any': function DenseMatrixAny(x, y) {\n return algorithm14(x, y, divideScalar, false);\n },\n 'SparseMatrix, any': function SparseMatrixAny(x, y) {\n return algorithm11(x, y, divideScalar, false);\n },\n 'Array, any': function ArrayAny(x, y) {\n // use matrix implementation\n return algorithm14(matrix(x), y, divideScalar, false).valueOf();\n },\n 'any, Array | Matrix': function anyArrayMatrix(x, y) {\n return multiply(x, inv(y));\n }\n }, divideScalar.signatures));\n});","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nimport { isComplex, isUnit, typeOf } from '../../utils/is.js';\nimport { factory } from '../../utils/factory.js';\nimport { memoize } from '../../utils/function.js';\nimport { endsWith } from '../../utils/string.js';\nimport { clone, hasOwnProperty } from '../../utils/object.js';\nimport { createBigNumberPi as createPi } from '../../utils/bignumber/constants.js';\nvar name = 'Unit';\nvar dependencies = ['?on', 'config', 'addScalar', 'subtract', 'multiplyScalar', 'divideScalar', 'pow', 'abs', 'fix', 'round', 'equal', 'isNumeric', 'format', 'number', 'Complex', 'BigNumber', 'Fraction'];\nexport var createUnitClass = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n on,\n config,\n addScalar,\n subtract,\n multiplyScalar,\n divideScalar,\n pow,\n abs,\n fix,\n round,\n equal,\n isNumeric,\n format,\n number,\n Complex,\n BigNumber: _BigNumber,\n Fraction: _Fraction\n } = _ref;\n var toNumber = number;\n /**\n * A unit can be constructed in the following ways:\n *\n * const a = new Unit(value, name)\n * const b = new Unit(null, name)\n * const c = Unit.parse(str)\n *\n * Example usage:\n *\n * const a = new Unit(5, 'cm') // 50 mm\n * const b = Unit.parse('23 kg') // 23 kg\n * const c = math.in(a, new Unit(null, 'm') // 0.05 m\n * const d = new Unit(9.81, \"m/s^2\") // 9.81 m/s^2\n *\n * @class Unit\n * @constructor Unit\n * @param {number | BigNumber | Fraction | Complex | boolean} [value] A value like 5.2\n * @param {string} [name] A unit name like \"cm\" or \"inch\", or a derived unit of the form: \"u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3] [u4[^ex4]]]\", such as \"kg m^2/s^2\", where each unit appearing after the forward slash is taken to be in the denominator. \"kg m^2 s^-2\" is a synonym and is also acceptable. Any of the units can include a prefix.\n */\n\n function Unit(value, name) {\n if (!(this instanceof Unit)) {\n throw new Error('Constructor must be called with the new operator');\n }\n\n if (!(value === null || value === undefined || isNumeric(value) || isComplex(value))) {\n throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined');\n }\n\n if (name !== undefined && (typeof name !== 'string' || name === '')) {\n throw new TypeError('Second parameter in Unit constructor must be a string');\n }\n\n if (name !== undefined) {\n var u = Unit.parse(name);\n this.units = u.units;\n this.dimensions = u.dimensions;\n } else {\n this.units = [{\n unit: UNIT_NONE,\n prefix: PREFIXES.NONE,\n // link to a list with supported prefixes\n power: 0\n }];\n this.dimensions = [];\n\n for (var i = 0; i < BASE_DIMENSIONS.length; i++) {\n this.dimensions[i] = 0;\n }\n }\n\n this.value = value !== undefined && value !== null ? this._normalize(value) : null;\n this.fixPrefix = false; // if true, function format will not search for the\n // best prefix but leave it as initially provided.\n // fixPrefix is set true by the method Unit.to\n // The justification behind this is that if the constructor is explicitly called,\n // the caller wishes the units to be returned exactly as he supplied.\n\n this.skipAutomaticSimplification = true;\n }\n /**\n * Attach type information\n */\n\n\n Unit.prototype.type = 'Unit';\n Unit.prototype.isUnit = true; // private variables and functions for the Unit parser\n\n var text, index, c;\n\n function skipWhitespace() {\n while (c === ' ' || c === '\\t') {\n next();\n }\n }\n\n function isDigitDot(c) {\n return c >= '0' && c <= '9' || c === '.';\n }\n\n function isDigit(c) {\n return c >= '0' && c <= '9';\n }\n\n function next() {\n index++;\n c = text.charAt(index);\n }\n\n function revert(oldIndex) {\n index = oldIndex;\n c = text.charAt(index);\n }\n\n function parseNumber() {\n var number = '';\n var oldIndex = index;\n\n if (c === '+') {\n next();\n } else if (c === '-') {\n number += c;\n next();\n }\n\n if (!isDigitDot(c)) {\n // a + or - must be followed by a digit\n revert(oldIndex);\n return null;\n } // get number, can have a single dot\n\n\n if (c === '.') {\n number += c;\n next();\n\n if (!isDigit(c)) {\n // this is no legal number, it is just a dot\n revert(oldIndex);\n return null;\n }\n } else {\n while (isDigit(c)) {\n number += c;\n next();\n }\n\n if (c === '.') {\n number += c;\n next();\n }\n }\n\n while (isDigit(c)) {\n number += c;\n next();\n } // check for exponential notation like \"2.3e-4\" or \"1.23e50\"\n\n\n if (c === 'E' || c === 'e') {\n // The grammar branches here. This could either be part of an exponent or the start of a unit that begins with the letter e, such as \"4exabytes\"\n var tentativeNumber = '';\n var tentativeIndex = index;\n tentativeNumber += c;\n next();\n\n if (c === '+' || c === '-') {\n tentativeNumber += c;\n next();\n } // Scientific notation MUST be followed by an exponent (otherwise we assume it is not scientific notation)\n\n\n if (!isDigit(c)) {\n // The e or E must belong to something else, so return the number without the e or E.\n revert(tentativeIndex);\n return number;\n } // We can now safely say that this is scientific notation.\n\n\n number = number + tentativeNumber;\n\n while (isDigit(c)) {\n number += c;\n next();\n }\n }\n\n return number;\n }\n\n function parseUnit() {\n var unitName = ''; // Alphanumeric characters only; matches [a-zA-Z0-9]\n\n while (isDigit(c) || Unit.isValidAlpha(c)) {\n unitName += c;\n next();\n } // Must begin with [a-zA-Z]\n\n\n var firstC = unitName.charAt(0);\n\n if (Unit.isValidAlpha(firstC)) {\n return unitName;\n } else {\n return null;\n }\n }\n\n function parseCharacter(toFind) {\n if (c === toFind) {\n next();\n return toFind;\n } else {\n return null;\n }\n }\n /**\n * Parse a string into a unit. The value of the unit is parsed as number,\n * BigNumber, or Fraction depending on the math.js config setting `number`.\n *\n * Throws an exception if the provided string does not contain a valid unit or\n * cannot be parsed.\n * @memberof Unit\n * @param {string} str A string like \"5.2 inch\", \"4e2 cm/s^2\"\n * @return {Unit} unit\n */\n\n\n Unit.parse = function (str, options) {\n options = options || {};\n text = str;\n index = -1;\n c = '';\n\n if (typeof text !== 'string') {\n throw new TypeError('Invalid argument in Unit.parse, string expected');\n }\n\n var unit = new Unit();\n unit.units = [];\n var powerMultiplierCurrent = 1;\n var expectingUnit = false; // A unit should follow this pattern:\n // [number] ...[ [*/] unit[^number] ]\n // unit[^number] ... [ [*/] unit[^number] ]\n // Rules:\n // number is any floating point number.\n // unit is any alphanumeric string beginning with an alpha. Units with names like e3 should be avoided because they look like the exponent of a floating point number!\n // The string may optionally begin with a number.\n // Each unit may optionally be followed by ^number.\n // Whitespace or a forward slash is recommended between consecutive units, although the following technically is parseable:\n // 2m^2kg/s^2\n // it is not good form. If a unit starts with e, then it could be confused as a floating point number:\n // 4erg\n\n next();\n skipWhitespace(); // Optional number at the start of the string\n\n var valueStr = parseNumber();\n var value = null;\n\n if (valueStr) {\n if (config.number === 'BigNumber') {\n value = new _BigNumber(valueStr);\n } else if (config.number === 'Fraction') {\n try {\n // not all numbers can be turned in Fractions, for example very small numbers not\n value = new _Fraction(valueStr);\n } catch (err) {\n value = parseFloat(valueStr);\n }\n } else {\n // number\n value = parseFloat(valueStr);\n }\n\n skipWhitespace(); // Whitespace is not required here\n // handle multiplication or division right after the value, like '1/s'\n\n if (parseCharacter('*')) {\n powerMultiplierCurrent = 1;\n expectingUnit = true;\n } else if (parseCharacter('/')) {\n powerMultiplierCurrent = -1;\n expectingUnit = true;\n }\n } // Stack to keep track of powerMultipliers applied to each parentheses group\n\n\n var powerMultiplierStack = []; // Running product of all elements in powerMultiplierStack\n\n var powerMultiplierStackProduct = 1;\n\n while (true) {\n skipWhitespace(); // Check for and consume opening parentheses, pushing powerMultiplierCurrent to the stack\n // A '(' will always appear directly before a unit.\n\n while (c === '(') {\n powerMultiplierStack.push(powerMultiplierCurrent);\n powerMultiplierStackProduct *= powerMultiplierCurrent;\n powerMultiplierCurrent = 1;\n next();\n skipWhitespace();\n } // Is there something here?\n\n\n var uStr = void 0;\n\n if (c) {\n var oldC = c;\n uStr = parseUnit();\n\n if (uStr === null) {\n throw new SyntaxError('Unexpected \"' + oldC + '\" in \"' + text + '\" at index ' + index.toString());\n }\n } else {\n // End of input.\n break;\n } // Verify the unit exists and get the prefix (if any)\n\n\n var res = _findUnit(uStr);\n\n if (res === null) {\n // Unit not found.\n throw new SyntaxError('Unit \"' + uStr + '\" not found.');\n }\n\n var power = powerMultiplierCurrent * powerMultiplierStackProduct; // Is there a \"^ number\"?\n\n skipWhitespace();\n\n if (parseCharacter('^')) {\n skipWhitespace();\n var p = parseNumber();\n\n if (p === null) {\n // No valid number found for the power!\n throw new SyntaxError('In \"' + str + '\", \"^\" must be followed by a floating-point number');\n }\n\n power *= p;\n } // Add the unit to the list\n\n\n unit.units.push({\n unit: res.unit,\n prefix: res.prefix,\n power: power\n });\n\n for (var i = 0; i < BASE_DIMENSIONS.length; i++) {\n unit.dimensions[i] += (res.unit.dimensions[i] || 0) * power;\n } // Check for and consume closing parentheses, popping from the stack.\n // A ')' will always follow a unit.\n\n\n skipWhitespace();\n\n while (c === ')') {\n if (powerMultiplierStack.length === 0) {\n throw new SyntaxError('Unmatched \")\" in \"' + text + '\" at index ' + index.toString());\n }\n\n powerMultiplierStackProduct /= powerMultiplierStack.pop();\n next();\n skipWhitespace();\n } // \"*\" and \"/\" should mean we are expecting something to come next.\n // Is there a forward slash? If so, negate powerMultiplierCurrent. The next unit or paren group is in the denominator.\n\n\n expectingUnit = false;\n\n if (parseCharacter('*')) {\n // explicit multiplication\n powerMultiplierCurrent = 1;\n expectingUnit = true;\n } else if (parseCharacter('/')) {\n // division\n powerMultiplierCurrent = -1;\n expectingUnit = true;\n } else {\n // implicit multiplication\n powerMultiplierCurrent = 1;\n } // Replace the unit into the auto unit system\n\n\n if (res.unit.base) {\n var baseDim = res.unit.base.key;\n UNIT_SYSTEMS.auto[baseDim] = {\n unit: res.unit,\n prefix: res.prefix\n };\n }\n } // Has the string been entirely consumed?\n\n\n skipWhitespace();\n\n if (c) {\n throw new SyntaxError('Could not parse: \"' + str + '\"');\n } // Is there a trailing slash?\n\n\n if (expectingUnit) {\n throw new SyntaxError('Trailing characters: \"' + str + '\"');\n } // Is the parentheses stack empty?\n\n\n if (powerMultiplierStack.length !== 0) {\n throw new SyntaxError('Unmatched \"(\" in \"' + text + '\"');\n } // Are there any units at all?\n\n\n if (unit.units.length === 0 && !options.allowNoUnits) {\n throw new SyntaxError('\"' + str + '\" contains no units');\n }\n\n unit.value = value !== undefined ? unit._normalize(value) : null;\n return unit;\n };\n /**\n * create a copy of this unit\n * @memberof Unit\n * @return {Unit} Returns a cloned version of the unit\n */\n\n\n Unit.prototype.clone = function () {\n var unit = new Unit();\n unit.fixPrefix = this.fixPrefix;\n unit.skipAutomaticSimplification = this.skipAutomaticSimplification;\n unit.value = clone(this.value);\n unit.dimensions = this.dimensions.slice(0);\n unit.units = [];\n\n for (var i = 0; i < this.units.length; i++) {\n unit.units[i] = {};\n\n for (var p in this.units[i]) {\n if (hasOwnProperty(this.units[i], p)) {\n unit.units[i][p] = this.units[i][p];\n }\n }\n }\n\n return unit;\n };\n /**\n * Return whether the unit is derived (such as m/s, or cm^2, but not N)\n * @memberof Unit\n * @return {boolean} True if the unit is derived\n */\n\n\n Unit.prototype._isDerived = function () {\n if (this.units.length === 0) {\n return false;\n }\n\n return this.units.length > 1 || Math.abs(this.units[0].power - 1.0) > 1e-15;\n };\n /**\n * Normalize a value, based on its currently set unit(s)\n * @memberof Unit\n * @param {number | BigNumber | Fraction | boolean} value\n * @return {number | BigNumber | Fraction | boolean} normalized value\n * @private\n */\n\n\n Unit.prototype._normalize = function (value) {\n var unitValue, unitOffset, unitPower, unitPrefixValue;\n var convert;\n\n if (value === null || value === undefined || this.units.length === 0) {\n return value;\n } else if (this._isDerived()) {\n // This is a derived unit, so do not apply offsets.\n // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.\n var res = value;\n convert = Unit._getNumberConverter(typeOf(value)); // convert to Fraction or BigNumber if needed\n\n for (var i = 0; i < this.units.length; i++) {\n unitValue = convert(this.units[i].unit.value);\n unitPrefixValue = convert(this.units[i].prefix.value);\n unitPower = convert(this.units[i].power);\n res = multiplyScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower));\n }\n\n return res;\n } else {\n // This is a single unit of power 1, like kg or degC\n convert = Unit._getNumberConverter(typeOf(value)); // convert to Fraction or BigNumber if needed\n\n unitValue = convert(this.units[0].unit.value);\n unitOffset = convert(this.units[0].unit.offset);\n unitPrefixValue = convert(this.units[0].prefix.value);\n return multiplyScalar(addScalar(value, unitOffset), multiplyScalar(unitValue, unitPrefixValue));\n }\n };\n /**\n * Denormalize a value, based on its currently set unit(s)\n * @memberof Unit\n * @param {number} value\n * @param {number} [prefixValue] Optional prefix value to be used (ignored if this is a derived unit)\n * @return {number} denormalized value\n * @private\n */\n\n\n Unit.prototype._denormalize = function (value, prefixValue) {\n var unitValue, unitOffset, unitPower, unitPrefixValue;\n var convert;\n\n if (value === null || value === undefined || this.units.length === 0) {\n return value;\n } else if (this._isDerived()) {\n // This is a derived unit, so do not apply offsets.\n // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.\n // Also, prefixValue is ignored--but we will still use the prefix value stored in each unit, since kg is usually preferable to g unless the user decides otherwise.\n var res = value;\n convert = Unit._getNumberConverter(typeOf(value)); // convert to Fraction or BigNumber if needed\n\n for (var i = 0; i < this.units.length; i++) {\n unitValue = convert(this.units[i].unit.value);\n unitPrefixValue = convert(this.units[i].prefix.value);\n unitPower = convert(this.units[i].power);\n res = divideScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower));\n }\n\n return res;\n } else {\n // This is a single unit of power 1, like kg or degC\n convert = Unit._getNumberConverter(typeOf(value)); // convert to Fraction or BigNumber if needed\n\n unitValue = convert(this.units[0].unit.value);\n unitPrefixValue = convert(this.units[0].prefix.value);\n unitOffset = convert(this.units[0].unit.offset);\n\n if (prefixValue === undefined || prefixValue === null) {\n return subtract(divideScalar(divideScalar(value, unitValue), unitPrefixValue), unitOffset);\n } else {\n return subtract(divideScalar(divideScalar(value, unitValue), prefixValue), unitOffset);\n }\n }\n };\n /**\n * Find a unit from a string\n * @memberof Unit\n * @param {string} str A string like 'cm' or 'inch'\n * @returns {Object | null} result When found, an object with fields unit and\n * prefix is returned. Else, null is returned.\n * @private\n */\n\n\n var _findUnit = memoize(str => {\n // First, match units names exactly. For example, a user could define 'mm' as 10^-4 m, which is silly, but then we would want 'mm' to match the user-defined unit.\n if (hasOwnProperty(UNITS, str)) {\n var unit = UNITS[str];\n var prefix = unit.prefixes[''];\n return {\n unit,\n prefix\n };\n }\n\n for (var _name in UNITS) {\n if (hasOwnProperty(UNITS, _name)) {\n if (endsWith(str, _name)) {\n var _unit = UNITS[_name];\n var prefixLen = str.length - _name.length;\n var prefixName = str.substring(0, prefixLen);\n\n var _prefix = hasOwnProperty(_unit.prefixes, prefixName) ? _unit.prefixes[prefixName] : undefined;\n\n if (_prefix !== undefined) {\n // store unit, prefix, and value\n return {\n unit: _unit,\n prefix: _prefix\n };\n }\n }\n }\n }\n\n return null;\n }, {\n hasher: args => args[0],\n limit: 100\n });\n /**\n * Test if the given expression is a unit.\n * The unit can have a prefix but cannot have a value.\n * @memberof Unit\n * @param {string} name A string to be tested whether it is a value less unit.\n * The unit can have prefix, like \"cm\"\n * @return {boolean} true if the given string is a unit\n */\n\n\n Unit.isValuelessUnit = function (name) {\n return _findUnit(name) !== null;\n };\n /**\n * check if this unit has given base unit\n * If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived.\n * @memberof Unit\n * @param {BASE_UNITS | string | undefined} base\n */\n\n\n Unit.prototype.hasBase = function (base) {\n if (typeof base === 'string') {\n base = BASE_UNITS[base];\n }\n\n if (!base) {\n return false;\n } // All dimensions must be the same\n\n\n for (var i = 0; i < BASE_DIMENSIONS.length; i++) {\n if (Math.abs((this.dimensions[i] || 0) - (base.dimensions[i] || 0)) > 1e-12) {\n return false;\n }\n }\n\n return true;\n };\n /**\n * Check if this unit has a base or bases equal to another base or bases\n * For derived units, the exponent on each base also must match\n * @memberof Unit\n * @param {Unit} other\n * @return {boolean} true if equal base\n */\n\n\n Unit.prototype.equalBase = function (other) {\n // All dimensions must be the same\n for (var i = 0; i < BASE_DIMENSIONS.length; i++) {\n if (Math.abs((this.dimensions[i] || 0) - (other.dimensions[i] || 0)) > 1e-12) {\n return false;\n }\n }\n\n return true;\n };\n /**\n * Check if this unit equals another unit\n * @memberof Unit\n * @param {Unit} other\n * @return {boolean} true if both units are equal\n */\n\n\n Unit.prototype.equals = function (other) {\n return this.equalBase(other) && equal(this.value, other.value);\n };\n /**\n * Multiply this unit with another one\n * @memberof Unit\n * @param {Unit} other\n * @return {Unit} product of this unit and the other unit\n */\n\n\n Unit.prototype.multiply = function (other) {\n var res = this.clone();\n\n for (var i = 0; i < BASE_DIMENSIONS.length; i++) {\n // Dimensions arrays may be of different lengths. Default to 0.\n res.dimensions[i] = (this.dimensions[i] || 0) + (other.dimensions[i] || 0);\n } // Append other's units list onto res\n\n\n for (var _i = 0; _i < other.units.length; _i++) {\n // Make a shallow copy of every unit\n var inverted = _objectSpread({}, other.units[_i]);\n\n res.units.push(inverted);\n } // If at least one operand has a value, then the result should also have a value\n\n\n if (this.value !== null || other.value !== null) {\n var valThis = this.value === null ? this._normalize(1) : this.value;\n var valOther = other.value === null ? other._normalize(1) : other.value;\n res.value = multiplyScalar(valThis, valOther);\n } else {\n res.value = null;\n }\n\n res.skipAutomaticSimplification = false;\n return getNumericIfUnitless(res);\n };\n /**\n * Divide this unit by another one\n * @memberof Unit\n * @param {Unit} other\n * @return {Unit} result of dividing this unit by the other unit\n */\n\n\n Unit.prototype.divide = function (other) {\n var res = this.clone();\n\n for (var i = 0; i < BASE_DIMENSIONS.length; i++) {\n // Dimensions arrays may be of different lengths. Default to 0.\n res.dimensions[i] = (this.dimensions[i] || 0) - (other.dimensions[i] || 0);\n } // Invert and append other's units list onto res\n\n\n for (var _i2 = 0; _i2 < other.units.length; _i2++) {\n // Make a shallow copy of every unit\n var inverted = _objectSpread(_objectSpread({}, other.units[_i2]), {}, {\n power: -other.units[_i2].power\n });\n\n res.units.push(inverted);\n } // If at least one operand has a value, the result should have a value\n\n\n if (this.value !== null || other.value !== null) {\n var valThis = this.value === null ? this._normalize(1) : this.value;\n var valOther = other.value === null ? other._normalize(1) : other.value;\n res.value = divideScalar(valThis, valOther);\n } else {\n res.value = null;\n }\n\n res.skipAutomaticSimplification = false;\n return getNumericIfUnitless(res);\n };\n /**\n * Calculate the power of a unit\n * @memberof Unit\n * @param {number | Fraction | BigNumber} p\n * @returns {Unit} The result: this^p\n */\n\n\n Unit.prototype.pow = function (p) {\n var res = this.clone();\n\n for (var i = 0; i < BASE_DIMENSIONS.length; i++) {\n // Dimensions arrays may be of different lengths. Default to 0.\n res.dimensions[i] = (this.dimensions[i] || 0) * p;\n } // Adjust the power of each unit in the list\n\n\n for (var _i3 = 0; _i3 < res.units.length; _i3++) {\n res.units[_i3].power *= p;\n }\n\n if (res.value !== null) {\n res.value = pow(res.value, p); // only allow numeric output, we don't want to return a Complex number\n // if (!isNumeric(res.value)) {\n // res.value = NaN\n // }\n // Update: Complex supported now\n } else {\n res.value = null;\n }\n\n res.skipAutomaticSimplification = false;\n return getNumericIfUnitless(res);\n };\n /**\n * Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise\n * @param {Unit} unit\n * @returns {number | Fraction | BigNumber | Unit} The numeric value of the unit if conditions are met, or the original unit otherwise\n */\n\n\n function getNumericIfUnitless(unit) {\n if (unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) {\n return unit.value;\n } else {\n return unit;\n }\n }\n /**\n * Calculate the absolute value of a unit\n * @memberof Unit\n * @param {number | Fraction | BigNumber} x\n * @returns {Unit} The result: |x|, absolute value of x\n */\n\n\n Unit.prototype.abs = function () {\n // This gives correct, but unexpected, results for units with an offset.\n // For example, abs(-283.15 degC) = -263.15 degC !!!\n var ret = this.clone();\n ret.value = ret.value !== null ? abs(ret.value) : null;\n\n for (var i in ret.units) {\n if (ret.units[i].unit.name === 'VA' || ret.units[i].unit.name === 'VAR') {\n ret.units[i].unit = UNITS.W;\n }\n }\n\n return ret;\n };\n /**\n * Convert the unit to a specific unit name.\n * @memberof Unit\n * @param {string | Unit} valuelessUnit A unit without value. Can have prefix, like \"cm\"\n * @returns {Unit} Returns a clone of the unit with a fixed prefix and unit.\n */\n\n\n Unit.prototype.to = function (valuelessUnit) {\n var other;\n var value = this.value === null ? this._normalize(1) : this.value;\n\n if (typeof valuelessUnit === 'string') {\n // other = new Unit(null, valuelessUnit)\n other = Unit.parse(valuelessUnit);\n\n if (!this.equalBase(other)) {\n throw new Error(\"Units do not match ('\".concat(other.toString(), \"' != '\").concat(this.toString(), \"')\"));\n }\n\n if (other.value !== null) {\n throw new Error('Cannot convert to a unit with a value');\n }\n\n other.value = clone(value);\n other.fixPrefix = true;\n other.skipAutomaticSimplification = true;\n return other;\n } else if (isUnit(valuelessUnit)) {\n if (!this.equalBase(valuelessUnit)) {\n throw new Error(\"Units do not match ('\".concat(valuelessUnit.toString(), \"' != '\").concat(this.toString(), \"')\"));\n }\n\n if (valuelessUnit.value !== null) {\n throw new Error('Cannot convert to a unit with a value');\n }\n\n other = valuelessUnit.clone();\n other.value = clone(value);\n other.fixPrefix = true;\n other.skipAutomaticSimplification = true;\n return other;\n } else {\n throw new Error('String or Unit expected as parameter');\n }\n };\n /**\n * Return the value of the unit when represented with given valueless unit\n * @memberof Unit\n * @param {string | Unit} valuelessUnit For example 'cm' or 'inch'\n * @return {number} Returns the unit value as number.\n */\n // TODO: deprecate Unit.toNumber? It's always better to use toNumeric\n\n\n Unit.prototype.toNumber = function (valuelessUnit) {\n return toNumber(this.toNumeric(valuelessUnit));\n };\n /**\n * Return the value of the unit in the original numeric type\n * @memberof Unit\n * @param {string | Unit} valuelessUnit For example 'cm' or 'inch'\n * @return {number | BigNumber | Fraction} Returns the unit value\n */\n\n\n Unit.prototype.toNumeric = function (valuelessUnit) {\n var other;\n\n if (valuelessUnit) {\n // Allow getting the numeric value without converting to a different unit\n other = this.to(valuelessUnit);\n } else {\n other = this.clone();\n }\n\n if (other._isDerived() || other.units.length === 0) {\n return other._denormalize(other.value);\n } else {\n return other._denormalize(other.value, other.units[0].prefix.value);\n }\n };\n /**\n * Get a string representation of the unit.\n * @memberof Unit\n * @return {string}\n */\n\n\n Unit.prototype.toString = function () {\n return this.format();\n };\n /**\n * Get a JSON representation of the unit\n * @memberof Unit\n * @returns {Object} Returns a JSON object structured as:\n * `{\"mathjs\": \"Unit\", \"value\": 2, \"unit\": \"cm\", \"fixPrefix\": false}`\n */\n\n\n Unit.prototype.toJSON = function () {\n return {\n mathjs: 'Unit',\n value: this._denormalize(this.value),\n unit: this.formatUnits(),\n fixPrefix: this.fixPrefix\n };\n };\n /**\n * Instantiate a Unit from a JSON object\n * @memberof Unit\n * @param {Object} json A JSON object structured as:\n * `{\"mathjs\": \"Unit\", \"value\": 2, \"unit\": \"cm\", \"fixPrefix\": false}`\n * @return {Unit}\n */\n\n\n Unit.fromJSON = function (json) {\n var unit = new Unit(json.value, json.unit);\n unit.fixPrefix = json.fixPrefix || false;\n return unit;\n };\n /**\n * Returns the string representation of the unit.\n * @memberof Unit\n * @return {string}\n */\n\n\n Unit.prototype.valueOf = Unit.prototype.toString;\n /**\n * Simplify this Unit's unit list and return a new Unit with the simplified list.\n * The returned Unit will contain a list of the \"best\" units for formatting.\n */\n\n Unit.prototype.simplify = function () {\n var ret = this.clone();\n var proposedUnitList = []; // Search for a matching base\n\n var matchingBase;\n\n for (var key in currentUnitSystem) {\n if (hasOwnProperty(currentUnitSystem, key)) {\n if (ret.hasBase(BASE_UNITS[key])) {\n matchingBase = key;\n break;\n }\n }\n }\n\n if (matchingBase === 'NONE') {\n ret.units = [];\n } else {\n var matchingUnit;\n\n if (matchingBase) {\n // Does the unit system have a matching unit?\n if (hasOwnProperty(currentUnitSystem, matchingBase)) {\n matchingUnit = currentUnitSystem[matchingBase];\n }\n }\n\n if (matchingUnit) {\n ret.units = [{\n unit: matchingUnit.unit,\n prefix: matchingUnit.prefix,\n power: 1.0\n }];\n } else {\n // Multiple units or units with powers are formatted like this:\n // 5 (kg m^2) / (s^3 mol)\n // Build an representation from the base units of the current unit system\n var missingBaseDim = false;\n\n for (var i = 0; i < BASE_DIMENSIONS.length; i++) {\n var baseDim = BASE_DIMENSIONS[i];\n\n if (Math.abs(ret.dimensions[i] || 0) > 1e-12) {\n if (hasOwnProperty(currentUnitSystem, baseDim)) {\n proposedUnitList.push({\n unit: currentUnitSystem[baseDim].unit,\n prefix: currentUnitSystem[baseDim].prefix,\n power: ret.dimensions[i] || 0\n });\n } else {\n missingBaseDim = true;\n }\n }\n } // Is the proposed unit list \"simpler\" than the existing one?\n\n\n if (proposedUnitList.length < ret.units.length && !missingBaseDim) {\n // Replace this unit list with the proposed list\n ret.units = proposedUnitList;\n }\n }\n }\n\n return ret;\n };\n /**\n * Returns a new Unit in the SI system with the same value as this one\n */\n\n\n Unit.prototype.toSI = function () {\n var ret = this.clone();\n var proposedUnitList = []; // Multiple units or units with powers are formatted like this:\n // 5 (kg m^2) / (s^3 mol)\n // Build an representation from the base units of the SI unit system\n\n for (var i = 0; i < BASE_DIMENSIONS.length; i++) {\n var baseDim = BASE_DIMENSIONS[i];\n\n if (Math.abs(ret.dimensions[i] || 0) > 1e-12) {\n if (hasOwnProperty(UNIT_SYSTEMS.si, baseDim)) {\n proposedUnitList.push({\n unit: UNIT_SYSTEMS.si[baseDim].unit,\n prefix: UNIT_SYSTEMS.si[baseDim].prefix,\n power: ret.dimensions[i] || 0\n });\n } else {\n throw new Error('Cannot express custom unit ' + baseDim + ' in SI units');\n }\n }\n } // Replace this unit list with the proposed list\n\n\n ret.units = proposedUnitList;\n ret.fixPrefix = true;\n ret.skipAutomaticSimplification = true;\n return ret;\n };\n /**\n * Get a string representation of the units of this Unit, without the value. The unit list is formatted as-is without first being simplified.\n * @memberof Unit\n * @return {string}\n */\n\n\n Unit.prototype.formatUnits = function () {\n var strNum = '';\n var strDen = '';\n var nNum = 0;\n var nDen = 0;\n\n for (var i = 0; i < this.units.length; i++) {\n if (this.units[i].power > 0) {\n nNum++;\n strNum += ' ' + this.units[i].prefix.name + this.units[i].unit.name;\n\n if (Math.abs(this.units[i].power - 1.0) > 1e-15) {\n strNum += '^' + this.units[i].power;\n }\n } else if (this.units[i].power < 0) {\n nDen++;\n }\n }\n\n if (nDen > 0) {\n for (var _i4 = 0; _i4 < this.units.length; _i4++) {\n if (this.units[_i4].power < 0) {\n if (nNum > 0) {\n strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name;\n\n if (Math.abs(this.units[_i4].power + 1.0) > 1e-15) {\n strDen += '^' + -this.units[_i4].power;\n }\n } else {\n strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name;\n strDen += '^' + this.units[_i4].power;\n }\n }\n }\n } // Remove leading \" \"\n\n\n strNum = strNum.substr(1);\n strDen = strDen.substr(1); // Add parans for better copy/paste back into evaluate, for example, or for better pretty print formatting\n\n if (nNum > 1 && nDen > 0) {\n strNum = '(' + strNum + ')';\n }\n\n if (nDen > 1 && nNum > 0) {\n strDen = '(' + strDen + ')';\n }\n\n var str = strNum;\n\n if (nNum > 0 && nDen > 0) {\n str += ' / ';\n }\n\n str += strDen;\n return str;\n };\n /**\n * Get a string representation of the Unit, with optional formatting options.\n * @memberof Unit\n * @param {Object | number | Function} [options] Formatting options. See\n * lib/utils/number:format for a\n * description of the available\n * options.\n * @return {string}\n */\n\n\n Unit.prototype.format = function (options) {\n // Simplfy the unit list, unless it is valueless or was created directly in the\n // constructor or as the result of to or toSI\n var simp = this.skipAutomaticSimplification || this.value === null ? this.clone() : this.simplify(); // Apply some custom logic for handling VA and VAR. The goal is to express the value of the unit as a real value, if possible. Otherwise, use a real-valued unit instead of a complex-valued one.\n\n var isImaginary = false;\n\n if (typeof simp.value !== 'undefined' && simp.value !== null && isComplex(simp.value)) {\n // TODO: Make this better, for example, use relative magnitude of re and im rather than absolute\n isImaginary = Math.abs(simp.value.re) < 1e-14;\n }\n\n for (var i in simp.units) {\n if (hasOwnProperty(simp.units, i)) {\n if (simp.units[i].unit) {\n if (simp.units[i].unit.name === 'VA' && isImaginary) {\n simp.units[i].unit = UNITS.VAR;\n } else if (simp.units[i].unit.name === 'VAR' && !isImaginary) {\n simp.units[i].unit = UNITS.VA;\n }\n }\n }\n } // Now apply the best prefix\n // Units must have only one unit and not have the fixPrefix flag set\n\n\n if (simp.units.length === 1 && !simp.fixPrefix) {\n // Units must have integer powers, otherwise the prefix will change the\n // outputted value by not-an-integer-power-of-ten\n if (Math.abs(simp.units[0].power - Math.round(simp.units[0].power)) < 1e-14) {\n // Apply the best prefix\n simp.units[0].prefix = simp._bestPrefix();\n }\n }\n\n var value = simp._denormalize(simp.value);\n\n var str = simp.value !== null ? format(value, options || {}) : '';\n var unitStr = simp.formatUnits();\n\n if (simp.value && isComplex(simp.value)) {\n str = '(' + str + ')'; // Surround complex values with ( ) to enable better parsing\n }\n\n if (unitStr.length > 0 && str.length > 0) {\n str += ' ';\n }\n\n str += unitStr;\n return str;\n };\n /**\n * Calculate the best prefix using current value.\n * @memberof Unit\n * @returns {Object} prefix\n * @private\n */\n\n\n Unit.prototype._bestPrefix = function () {\n if (this.units.length !== 1) {\n throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!');\n }\n\n if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) >= 1e-14) {\n throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!');\n } // find the best prefix value (resulting in the value of which\n // the absolute value of the log10 is closest to zero,\n // though with a little offset of 1.2 for nicer values: you get a\n // sequence 1mm 100mm 500mm 0.6m 1m 10m 100m 500m 0.6km 1km ...\n // Note: the units value can be any numeric type, but to find the best\n // prefix it's enough to work with limited precision of a regular number\n // Update: using mathjs abs since we also allow complex numbers\n\n\n var absValue = this.value !== null ? abs(this.value) : 0;\n var absUnitValue = abs(this.units[0].unit.value);\n var bestPrefix = this.units[0].prefix;\n\n if (absValue === 0) {\n return bestPrefix;\n }\n\n var power = this.units[0].power;\n var bestDiff = Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - 1.2;\n if (bestDiff > -2.200001 && bestDiff < 1.800001) return bestPrefix; // Allow the original prefix\n\n bestDiff = Math.abs(bestDiff);\n var prefixes = this.units[0].unit.prefixes;\n\n for (var p in prefixes) {\n if (hasOwnProperty(prefixes, p)) {\n var prefix = prefixes[p];\n\n if (prefix.scientific) {\n var diff = Math.abs(Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - 1.2);\n\n if (diff < bestDiff || diff === bestDiff && prefix.name.length < bestPrefix.name.length) {\n // choose the prefix with the smallest diff, or if equal, choose the one\n // with the shortest name (can happen with SHORTLONG for example)\n bestPrefix = prefix;\n bestDiff = diff;\n }\n }\n }\n }\n\n return bestPrefix;\n };\n /**\n * Returns an array of units whose sum is equal to this unit\n * @memberof Unit\n * @param {Array} [parts] An array of strings or valueless units.\n *\n * Example:\n *\n * const u = new Unit(1, 'm')\n * u.splitUnit(['feet', 'inch'])\n * [ 3 feet, 3.3700787401575 inch ]\n *\n * @return {Array} An array of units.\n */\n\n\n Unit.prototype.splitUnit = function (parts) {\n var x = this.clone();\n var ret = [];\n\n for (var i = 0; i < parts.length; i++) {\n // Convert x to the requested unit\n x = x.to(parts[i]);\n if (i === parts.length - 1) break; // Get the numeric value of this unit\n\n var xNumeric = x.toNumeric(); // Check to see if xNumeric is nearly equal to an integer,\n // since fix can incorrectly round down if there is round-off error\n\n var xRounded = round(xNumeric);\n var xFixed = void 0;\n var isNearlyEqual = equal(xRounded, xNumeric);\n\n if (isNearlyEqual) {\n xFixed = xRounded;\n } else {\n xFixed = fix(x.toNumeric());\n }\n\n var y = new Unit(xFixed, parts[i].toString());\n ret.push(y);\n x = subtract(x, y);\n } // This little bit fixes a bug where the remainder should be 0 but is a little bit off.\n // But instead of comparing x, the remainder, with zero--we will compare the sum of\n // all the parts so far with the original value. If they are nearly equal,\n // we set the remainder to 0.\n\n\n var testSum = 0;\n\n for (var _i5 = 0; _i5 < ret.length; _i5++) {\n testSum = addScalar(testSum, ret[_i5].value);\n }\n\n if (equal(testSum, this.value)) {\n x.value = 0;\n }\n\n ret.push(x);\n return ret;\n };\n\n var PREFIXES = {\n NONE: {\n '': {\n name: '',\n value: 1,\n scientific: true\n }\n },\n SHORT: {\n '': {\n name: '',\n value: 1,\n scientific: true\n },\n da: {\n name: 'da',\n value: 1e1,\n scientific: false\n },\n h: {\n name: 'h',\n value: 1e2,\n scientific: false\n },\n k: {\n name: 'k',\n value: 1e3,\n scientific: true\n },\n M: {\n name: 'M',\n value: 1e6,\n scientific: true\n },\n G: {\n name: 'G',\n value: 1e9,\n scientific: true\n },\n T: {\n name: 'T',\n value: 1e12,\n scientific: true\n },\n P: {\n name: 'P',\n value: 1e15,\n scientific: true\n },\n E: {\n name: 'E',\n value: 1e18,\n scientific: true\n },\n Z: {\n name: 'Z',\n value: 1e21,\n scientific: true\n },\n Y: {\n name: 'Y',\n value: 1e24,\n scientific: true\n },\n d: {\n name: 'd',\n value: 1e-1,\n scientific: false\n },\n c: {\n name: 'c',\n value: 1e-2,\n scientific: false\n },\n m: {\n name: 'm',\n value: 1e-3,\n scientific: true\n },\n u: {\n name: 'u',\n value: 1e-6,\n scientific: true\n },\n n: {\n name: 'n',\n value: 1e-9,\n scientific: true\n },\n p: {\n name: 'p',\n value: 1e-12,\n scientific: true\n },\n f: {\n name: 'f',\n value: 1e-15,\n scientific: true\n },\n a: {\n name: 'a',\n value: 1e-18,\n scientific: true\n },\n z: {\n name: 'z',\n value: 1e-21,\n scientific: true\n },\n y: {\n name: 'y',\n value: 1e-24,\n scientific: true\n }\n },\n LONG: {\n '': {\n name: '',\n value: 1,\n scientific: true\n },\n deca: {\n name: 'deca',\n value: 1e1,\n scientific: false\n },\n hecto: {\n name: 'hecto',\n value: 1e2,\n scientific: false\n },\n kilo: {\n name: 'kilo',\n value: 1e3,\n scientific: true\n },\n mega: {\n name: 'mega',\n value: 1e6,\n scientific: true\n },\n giga: {\n name: 'giga',\n value: 1e9,\n scientific: true\n },\n tera: {\n name: 'tera',\n value: 1e12,\n scientific: true\n },\n peta: {\n name: 'peta',\n value: 1e15,\n scientific: true\n },\n exa: {\n name: 'exa',\n value: 1e18,\n scientific: true\n },\n zetta: {\n name: 'zetta',\n value: 1e21,\n scientific: true\n },\n yotta: {\n name: 'yotta',\n value: 1e24,\n scientific: true\n },\n deci: {\n name: 'deci',\n value: 1e-1,\n scientific: false\n },\n centi: {\n name: 'centi',\n value: 1e-2,\n scientific: false\n },\n milli: {\n name: 'milli',\n value: 1e-3,\n scientific: true\n },\n micro: {\n name: 'micro',\n value: 1e-6,\n scientific: true\n },\n nano: {\n name: 'nano',\n value: 1e-9,\n scientific: true\n },\n pico: {\n name: 'pico',\n value: 1e-12,\n scientific: true\n },\n femto: {\n name: 'femto',\n value: 1e-15,\n scientific: true\n },\n atto: {\n name: 'atto',\n value: 1e-18,\n scientific: true\n },\n zepto: {\n name: 'zepto',\n value: 1e-21,\n scientific: true\n },\n yocto: {\n name: 'yocto',\n value: 1e-24,\n scientific: true\n }\n },\n SQUARED: {\n '': {\n name: '',\n value: 1,\n scientific: true\n },\n da: {\n name: 'da',\n value: 1e2,\n scientific: false\n },\n h: {\n name: 'h',\n value: 1e4,\n scientific: false\n },\n k: {\n name: 'k',\n value: 1e6,\n scientific: true\n },\n M: {\n name: 'M',\n value: 1e12,\n scientific: true\n },\n G: {\n name: 'G',\n value: 1e18,\n scientific: true\n },\n T: {\n name: 'T',\n value: 1e24,\n scientific: true\n },\n P: {\n name: 'P',\n value: 1e30,\n scientific: true\n },\n E: {\n name: 'E',\n value: 1e36,\n scientific: true\n },\n Z: {\n name: 'Z',\n value: 1e42,\n scientific: true\n },\n Y: {\n name: 'Y',\n value: 1e48,\n scientific: true\n },\n d: {\n name: 'd',\n value: 1e-2,\n scientific: false\n },\n c: {\n name: 'c',\n value: 1e-4,\n scientific: false\n },\n m: {\n name: 'm',\n value: 1e-6,\n scientific: true\n },\n u: {\n name: 'u',\n value: 1e-12,\n scientific: true\n },\n n: {\n name: 'n',\n value: 1e-18,\n scientific: true\n },\n p: {\n name: 'p',\n value: 1e-24,\n scientific: true\n },\n f: {\n name: 'f',\n value: 1e-30,\n scientific: true\n },\n a: {\n name: 'a',\n value: 1e-36,\n scientific: true\n },\n z: {\n name: 'z',\n value: 1e-42,\n scientific: true\n },\n y: {\n name: 'y',\n value: 1e-48,\n scientific: true\n }\n },\n CUBIC: {\n '': {\n name: '',\n value: 1,\n scientific: true\n },\n da: {\n name: 'da',\n value: 1e3,\n scientific: false\n },\n h: {\n name: 'h',\n value: 1e6,\n scientific: false\n },\n k: {\n name: 'k',\n value: 1e9,\n scientific: true\n },\n M: {\n name: 'M',\n value: 1e18,\n scientific: true\n },\n G: {\n name: 'G',\n value: 1e27,\n scientific: true\n },\n T: {\n name: 'T',\n value: 1e36,\n scientific: true\n },\n P: {\n name: 'P',\n value: 1e45,\n scientific: true\n },\n E: {\n name: 'E',\n value: 1e54,\n scientific: true\n },\n Z: {\n name: 'Z',\n value: 1e63,\n scientific: true\n },\n Y: {\n name: 'Y',\n value: 1e72,\n scientific: true\n },\n d: {\n name: 'd',\n value: 1e-3,\n scientific: false\n },\n c: {\n name: 'c',\n value: 1e-6,\n scientific: false\n },\n m: {\n name: 'm',\n value: 1e-9,\n scientific: true\n },\n u: {\n name: 'u',\n value: 1e-18,\n scientific: true\n },\n n: {\n name: 'n',\n value: 1e-27,\n scientific: true\n },\n p: {\n name: 'p',\n value: 1e-36,\n scientific: true\n },\n f: {\n name: 'f',\n value: 1e-45,\n scientific: true\n },\n a: {\n name: 'a',\n value: 1e-54,\n scientific: true\n },\n z: {\n name: 'z',\n value: 1e-63,\n scientific: true\n },\n y: {\n name: 'y',\n value: 1e-72,\n scientific: true\n }\n },\n BINARY_SHORT_SI: {\n '': {\n name: '',\n value: 1,\n scientific: true\n },\n k: {\n name: 'k',\n value: 1e3,\n scientific: true\n },\n M: {\n name: 'M',\n value: 1e6,\n scientific: true\n },\n G: {\n name: 'G',\n value: 1e9,\n scientific: true\n },\n T: {\n name: 'T',\n value: 1e12,\n scientific: true\n },\n P: {\n name: 'P',\n value: 1e15,\n scientific: true\n },\n E: {\n name: 'E',\n value: 1e18,\n scientific: true\n },\n Z: {\n name: 'Z',\n value: 1e21,\n scientific: true\n },\n Y: {\n name: 'Y',\n value: 1e24,\n scientific: true\n }\n },\n BINARY_SHORT_IEC: {\n '': {\n name: '',\n value: 1,\n scientific: true\n },\n Ki: {\n name: 'Ki',\n value: 1024,\n scientific: true\n },\n Mi: {\n name: 'Mi',\n value: Math.pow(1024, 2),\n scientific: true\n },\n Gi: {\n name: 'Gi',\n value: Math.pow(1024, 3),\n scientific: true\n },\n Ti: {\n name: 'Ti',\n value: Math.pow(1024, 4),\n scientific: true\n },\n Pi: {\n name: 'Pi',\n value: Math.pow(1024, 5),\n scientific: true\n },\n Ei: {\n name: 'Ei',\n value: Math.pow(1024, 6),\n scientific: true\n },\n Zi: {\n name: 'Zi',\n value: Math.pow(1024, 7),\n scientific: true\n },\n Yi: {\n name: 'Yi',\n value: Math.pow(1024, 8),\n scientific: true\n }\n },\n BINARY_LONG_SI: {\n '': {\n name: '',\n value: 1,\n scientific: true\n },\n kilo: {\n name: 'kilo',\n value: 1e3,\n scientific: true\n },\n mega: {\n name: 'mega',\n value: 1e6,\n scientific: true\n },\n giga: {\n name: 'giga',\n value: 1e9,\n scientific: true\n },\n tera: {\n name: 'tera',\n value: 1e12,\n scientific: true\n },\n peta: {\n name: 'peta',\n value: 1e15,\n scientific: true\n },\n exa: {\n name: 'exa',\n value: 1e18,\n scientific: true\n },\n zetta: {\n name: 'zetta',\n value: 1e21,\n scientific: true\n },\n yotta: {\n name: 'yotta',\n value: 1e24,\n scientific: true\n }\n },\n BINARY_LONG_IEC: {\n '': {\n name: '',\n value: 1,\n scientific: true\n },\n kibi: {\n name: 'kibi',\n value: 1024,\n scientific: true\n },\n mebi: {\n name: 'mebi',\n value: Math.pow(1024, 2),\n scientific: true\n },\n gibi: {\n name: 'gibi',\n value: Math.pow(1024, 3),\n scientific: true\n },\n tebi: {\n name: 'tebi',\n value: Math.pow(1024, 4),\n scientific: true\n },\n pebi: {\n name: 'pebi',\n value: Math.pow(1024, 5),\n scientific: true\n },\n exi: {\n name: 'exi',\n value: Math.pow(1024, 6),\n scientific: true\n },\n zebi: {\n name: 'zebi',\n value: Math.pow(1024, 7),\n scientific: true\n },\n yobi: {\n name: 'yobi',\n value: Math.pow(1024, 8),\n scientific: true\n }\n },\n BTU: {\n '': {\n name: '',\n value: 1,\n scientific: true\n },\n MM: {\n name: 'MM',\n value: 1e6,\n scientific: true\n }\n }\n };\n PREFIXES.SHORTLONG = _extends({}, PREFIXES.SHORT, PREFIXES.LONG);\n PREFIXES.BINARY_SHORT = _extends({}, PREFIXES.BINARY_SHORT_SI, PREFIXES.BINARY_SHORT_IEC);\n PREFIXES.BINARY_LONG = _extends({}, PREFIXES.BINARY_LONG_SI, PREFIXES.BINARY_LONG_IEC);\n /* Internally, each unit is represented by a value and a dimension array. The elements of the dimensions array have the following meaning:\n * Index Dimension\n * ----- ---------\n * 0 Length\n * 1 Mass\n * 2 Time\n * 3 Current\n * 4 Temperature\n * 5 Luminous intensity\n * 6 Amount of substance\n * 7 Angle\n * 8 Bit (digital)\n * For example, the unit \"298.15 K\" is a pure temperature and would have a value of 298.15 and a dimension array of [0, 0, 0, 0, 1, 0, 0, 0, 0]. The unit \"1 cal / (gm °C)\" can be written in terms of the 9 fundamental dimensions as [length^2] / ([time^2] * [temperature]), and would a value of (after conversion to SI) 4184.0 and a dimensions array of [2, 0, -2, 0, -1, 0, 0, 0, 0].\n *\n */\n\n var BASE_DIMENSIONS = ['MASS', 'LENGTH', 'TIME', 'CURRENT', 'TEMPERATURE', 'LUMINOUS_INTENSITY', 'AMOUNT_OF_SUBSTANCE', 'ANGLE', 'BIT'];\n var BASE_UNITS = {\n NONE: {\n dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 0]\n },\n MASS: {\n dimensions: [1, 0, 0, 0, 0, 0, 0, 0, 0]\n },\n LENGTH: {\n dimensions: [0, 1, 0, 0, 0, 0, 0, 0, 0]\n },\n TIME: {\n dimensions: [0, 0, 1, 0, 0, 0, 0, 0, 0]\n },\n CURRENT: {\n dimensions: [0, 0, 0, 1, 0, 0, 0, 0, 0]\n },\n TEMPERATURE: {\n dimensions: [0, 0, 0, 0, 1, 0, 0, 0, 0]\n },\n LUMINOUS_INTENSITY: {\n dimensions: [0, 0, 0, 0, 0, 1, 0, 0, 0]\n },\n AMOUNT_OF_SUBSTANCE: {\n dimensions: [0, 0, 0, 0, 0, 0, 1, 0, 0]\n },\n FORCE: {\n dimensions: [1, 1, -2, 0, 0, 0, 0, 0, 0]\n },\n SURFACE: {\n dimensions: [0, 2, 0, 0, 0, 0, 0, 0, 0]\n },\n VOLUME: {\n dimensions: [0, 3, 0, 0, 0, 0, 0, 0, 0]\n },\n ENERGY: {\n dimensions: [1, 2, -2, 0, 0, 0, 0, 0, 0]\n },\n POWER: {\n dimensions: [1, 2, -3, 0, 0, 0, 0, 0, 0]\n },\n PRESSURE: {\n dimensions: [1, -1, -2, 0, 0, 0, 0, 0, 0]\n },\n ELECTRIC_CHARGE: {\n dimensions: [0, 0, 1, 1, 0, 0, 0, 0, 0]\n },\n ELECTRIC_CAPACITANCE: {\n dimensions: [-1, -2, 4, 2, 0, 0, 0, 0, 0]\n },\n ELECTRIC_POTENTIAL: {\n dimensions: [1, 2, -3, -1, 0, 0, 0, 0, 0]\n },\n ELECTRIC_RESISTANCE: {\n dimensions: [1, 2, -3, -2, 0, 0, 0, 0, 0]\n },\n ELECTRIC_INDUCTANCE: {\n dimensions: [1, 2, -2, -2, 0, 0, 0, 0, 0]\n },\n ELECTRIC_CONDUCTANCE: {\n dimensions: [-1, -2, 3, 2, 0, 0, 0, 0, 0]\n },\n MAGNETIC_FLUX: {\n dimensions: [1, 2, -2, -1, 0, 0, 0, 0, 0]\n },\n MAGNETIC_FLUX_DENSITY: {\n dimensions: [1, 0, -2, -1, 0, 0, 0, 0, 0]\n },\n FREQUENCY: {\n dimensions: [0, 0, -1, 0, 0, 0, 0, 0, 0]\n },\n ANGLE: {\n dimensions: [0, 0, 0, 0, 0, 0, 0, 1, 0]\n },\n BIT: {\n dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 1]\n }\n };\n\n for (var key in BASE_UNITS) {\n if (hasOwnProperty(BASE_UNITS, key)) {\n BASE_UNITS[key].key = key;\n }\n }\n\n var BASE_UNIT_NONE = {};\n var UNIT_NONE = {\n name: '',\n base: BASE_UNIT_NONE,\n value: 1,\n offset: 0,\n dimensions: BASE_DIMENSIONS.map(x => 0)\n };\n var UNITS = {\n // length\n meter: {\n name: 'meter',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n inch: {\n name: 'inch',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 0.0254,\n offset: 0\n },\n foot: {\n name: 'foot',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 0.3048,\n offset: 0\n },\n yard: {\n name: 'yard',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 0.9144,\n offset: 0\n },\n mile: {\n name: 'mile',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 1609.344,\n offset: 0\n },\n link: {\n name: 'link',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 0.201168,\n offset: 0\n },\n rod: {\n name: 'rod',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 5.0292,\n offset: 0\n },\n chain: {\n name: 'chain',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 20.1168,\n offset: 0\n },\n angstrom: {\n name: 'angstrom',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 1e-10,\n offset: 0\n },\n m: {\n name: 'm',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n in: {\n name: 'in',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 0.0254,\n offset: 0\n },\n ft: {\n name: 'ft',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 0.3048,\n offset: 0\n },\n yd: {\n name: 'yd',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 0.9144,\n offset: 0\n },\n mi: {\n name: 'mi',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 1609.344,\n offset: 0\n },\n li: {\n name: 'li',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 0.201168,\n offset: 0\n },\n rd: {\n name: 'rd',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 5.029210,\n offset: 0\n },\n ch: {\n name: 'ch',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 20.1168,\n offset: 0\n },\n mil: {\n name: 'mil',\n base: BASE_UNITS.LENGTH,\n prefixes: PREFIXES.NONE,\n value: 0.0000254,\n offset: 0\n },\n // 1/1000 inch\n // Surface\n m2: {\n name: 'm2',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.SQUARED,\n value: 1,\n offset: 0\n },\n sqin: {\n name: 'sqin',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.NONE,\n value: 0.00064516,\n offset: 0\n },\n // 645.16 mm2\n sqft: {\n name: 'sqft',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.NONE,\n value: 0.09290304,\n offset: 0\n },\n // 0.09290304 m2\n sqyd: {\n name: 'sqyd',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.NONE,\n value: 0.83612736,\n offset: 0\n },\n // 0.83612736 m2\n sqmi: {\n name: 'sqmi',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.NONE,\n value: 2589988.110336,\n offset: 0\n },\n // 2.589988110336 km2\n sqrd: {\n name: 'sqrd',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.NONE,\n value: 25.29295,\n offset: 0\n },\n // 25.29295 m2\n sqch: {\n name: 'sqch',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.NONE,\n value: 404.6873,\n offset: 0\n },\n // 404.6873 m2\n sqmil: {\n name: 'sqmil',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.NONE,\n value: 6.4516e-10,\n offset: 0\n },\n // 6.4516 * 10^-10 m2\n acre: {\n name: 'acre',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.NONE,\n value: 4046.86,\n offset: 0\n },\n // 4046.86 m2\n hectare: {\n name: 'hectare',\n base: BASE_UNITS.SURFACE,\n prefixes: PREFIXES.NONE,\n value: 10000,\n offset: 0\n },\n // 10000 m2\n // Volume\n m3: {\n name: 'm3',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.CUBIC,\n value: 1,\n offset: 0\n },\n L: {\n name: 'L',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.SHORT,\n value: 0.001,\n offset: 0\n },\n // litre\n l: {\n name: 'l',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.SHORT,\n value: 0.001,\n offset: 0\n },\n // litre\n litre: {\n name: 'litre',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.LONG,\n value: 0.001,\n offset: 0\n },\n cuin: {\n name: 'cuin',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 1.6387064e-5,\n offset: 0\n },\n // 1.6387064e-5 m3\n cuft: {\n name: 'cuft',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.028316846592,\n offset: 0\n },\n // 28.316 846 592 L\n cuyd: {\n name: 'cuyd',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.764554857984,\n offset: 0\n },\n // 764.554 857 984 L\n teaspoon: {\n name: 'teaspoon',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.000005,\n offset: 0\n },\n // 5 mL\n tablespoon: {\n name: 'tablespoon',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.000015,\n offset: 0\n },\n // 15 mL\n // {name: 'cup', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.000240, offset: 0}, // 240 mL // not possible, we have already another cup\n drop: {\n name: 'drop',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 5e-8,\n offset: 0\n },\n // 0.05 mL = 5e-8 m3\n gtt: {\n name: 'gtt',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 5e-8,\n offset: 0\n },\n // 0.05 mL = 5e-8 m3\n // Liquid volume\n minim: {\n name: 'minim',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.00000006161152,\n offset: 0\n },\n // 0.06161152 mL\n fluiddram: {\n name: 'fluiddram',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0000036966911,\n offset: 0\n },\n // 3.696691 mL\n fluidounce: {\n name: 'fluidounce',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.00002957353,\n offset: 0\n },\n // 29.57353 mL\n gill: {\n name: 'gill',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0001182941,\n offset: 0\n },\n // 118.2941 mL\n cc: {\n name: 'cc',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 1e-6,\n offset: 0\n },\n // 1e-6 L\n cup: {\n name: 'cup',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0002365882,\n offset: 0\n },\n // 236.5882 mL\n pint: {\n name: 'pint',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0004731765,\n offset: 0\n },\n // 473.1765 mL\n quart: {\n name: 'quart',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0009463529,\n offset: 0\n },\n // 946.3529 mL\n gallon: {\n name: 'gallon',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.003785412,\n offset: 0\n },\n // 3.785412 L\n beerbarrel: {\n name: 'beerbarrel',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.1173478,\n offset: 0\n },\n // 117.3478 L\n oilbarrel: {\n name: 'oilbarrel',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.1589873,\n offset: 0\n },\n // 158.9873 L\n hogshead: {\n name: 'hogshead',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.2384810,\n offset: 0\n },\n // 238.4810 L\n // {name: 'min', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00000006161152, offset: 0}, // 0.06161152 mL // min is already in use as minute\n fldr: {\n name: 'fldr',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0000036966911,\n offset: 0\n },\n // 3.696691 mL\n floz: {\n name: 'floz',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.00002957353,\n offset: 0\n },\n // 29.57353 mL\n gi: {\n name: 'gi',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0001182941,\n offset: 0\n },\n // 118.2941 mL\n cp: {\n name: 'cp',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0002365882,\n offset: 0\n },\n // 236.5882 mL\n pt: {\n name: 'pt',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0004731765,\n offset: 0\n },\n // 473.1765 mL\n qt: {\n name: 'qt',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.0009463529,\n offset: 0\n },\n // 946.3529 mL\n gal: {\n name: 'gal',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.003785412,\n offset: 0\n },\n // 3.785412 L\n bbl: {\n name: 'bbl',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.1173478,\n offset: 0\n },\n // 117.3478 L\n obl: {\n name: 'obl',\n base: BASE_UNITS.VOLUME,\n prefixes: PREFIXES.NONE,\n value: 0.1589873,\n offset: 0\n },\n // 158.9873 L\n // {name: 'hogshead', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.2384810, offset: 0}, // 238.4810 L // TODO: hh?\n // Mass\n g: {\n name: 'g',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.SHORT,\n value: 0.001,\n offset: 0\n },\n gram: {\n name: 'gram',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.LONG,\n value: 0.001,\n offset: 0\n },\n ton: {\n name: 'ton',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.SHORT,\n value: 907.18474,\n offset: 0\n },\n t: {\n name: 't',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.SHORT,\n value: 1000,\n offset: 0\n },\n tonne: {\n name: 'tonne',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.LONG,\n value: 1000,\n offset: 0\n },\n grain: {\n name: 'grain',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 64.79891e-6,\n offset: 0\n },\n dram: {\n name: 'dram',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 1.7718451953125e-3,\n offset: 0\n },\n ounce: {\n name: 'ounce',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 28.349523125e-3,\n offset: 0\n },\n poundmass: {\n name: 'poundmass',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 453.59237e-3,\n offset: 0\n },\n hundredweight: {\n name: 'hundredweight',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 45.359237,\n offset: 0\n },\n stick: {\n name: 'stick',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 115e-3,\n offset: 0\n },\n stone: {\n name: 'stone',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 6.35029318,\n offset: 0\n },\n gr: {\n name: 'gr',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 64.79891e-6,\n offset: 0\n },\n dr: {\n name: 'dr',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 1.7718451953125e-3,\n offset: 0\n },\n oz: {\n name: 'oz',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 28.349523125e-3,\n offset: 0\n },\n lbm: {\n name: 'lbm',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 453.59237e-3,\n offset: 0\n },\n cwt: {\n name: 'cwt',\n base: BASE_UNITS.MASS,\n prefixes: PREFIXES.NONE,\n value: 45.359237,\n offset: 0\n },\n // Time\n s: {\n name: 's',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n min: {\n name: 'min',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 60,\n offset: 0\n },\n h: {\n name: 'h',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 3600,\n offset: 0\n },\n second: {\n name: 'second',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n sec: {\n name: 'sec',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n minute: {\n name: 'minute',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 60,\n offset: 0\n },\n hour: {\n name: 'hour',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 3600,\n offset: 0\n },\n day: {\n name: 'day',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 86400,\n offset: 0\n },\n week: {\n name: 'week',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 7 * 86400,\n offset: 0\n },\n month: {\n name: 'month',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 2629800,\n // 1/12th of Julian year\n offset: 0\n },\n year: {\n name: 'year',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 31557600,\n // Julian year\n offset: 0\n },\n decade: {\n name: 'decade',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 315576000,\n // Julian decade\n offset: 0\n },\n century: {\n name: 'century',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 3155760000,\n // Julian century\n offset: 0\n },\n millennium: {\n name: 'millennium',\n base: BASE_UNITS.TIME,\n prefixes: PREFIXES.NONE,\n value: 31557600000,\n // Julian millennium\n offset: 0\n },\n // Frequency\n hertz: {\n name: 'Hertz',\n base: BASE_UNITS.FREQUENCY,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0,\n reciprocal: true\n },\n Hz: {\n name: 'Hz',\n base: BASE_UNITS.FREQUENCY,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0,\n reciprocal: true\n },\n // Angle\n rad: {\n name: 'rad',\n base: BASE_UNITS.ANGLE,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n radian: {\n name: 'radian',\n base: BASE_UNITS.ANGLE,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n // deg = rad / (2*pi) * 360 = rad / 0.017453292519943295769236907684888\n deg: {\n name: 'deg',\n base: BASE_UNITS.ANGLE,\n prefixes: PREFIXES.SHORT,\n value: null,\n // will be filled in by calculateAngleValues()\n offset: 0\n },\n degree: {\n name: 'degree',\n base: BASE_UNITS.ANGLE,\n prefixes: PREFIXES.LONG,\n value: null,\n // will be filled in by calculateAngleValues()\n offset: 0\n },\n // grad = rad / (2*pi) * 400 = rad / 0.015707963267948966192313216916399\n grad: {\n name: 'grad',\n base: BASE_UNITS.ANGLE,\n prefixes: PREFIXES.SHORT,\n value: null,\n // will be filled in by calculateAngleValues()\n offset: 0\n },\n gradian: {\n name: 'gradian',\n base: BASE_UNITS.ANGLE,\n prefixes: PREFIXES.LONG,\n value: null,\n // will be filled in by calculateAngleValues()\n offset: 0\n },\n // cycle = rad / (2*pi) = rad / 6.2831853071795864769252867665793\n cycle: {\n name: 'cycle',\n base: BASE_UNITS.ANGLE,\n prefixes: PREFIXES.NONE,\n value: null,\n // will be filled in by calculateAngleValues()\n offset: 0\n },\n // arcsec = rad / (3600 * (360 / 2 * pi)) = rad / 0.0000048481368110953599358991410235795\n arcsec: {\n name: 'arcsec',\n base: BASE_UNITS.ANGLE,\n prefixes: PREFIXES.NONE,\n value: null,\n // will be filled in by calculateAngleValues()\n offset: 0\n },\n // arcmin = rad / (60 * (360 / 2 * pi)) = rad / 0.00029088820866572159615394846141477\n arcmin: {\n name: 'arcmin',\n base: BASE_UNITS.ANGLE,\n prefixes: PREFIXES.NONE,\n value: null,\n // will be filled in by calculateAngleValues()\n offset: 0\n },\n // Electric current\n A: {\n name: 'A',\n base: BASE_UNITS.CURRENT,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n ampere: {\n name: 'ampere',\n base: BASE_UNITS.CURRENT,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n // Temperature\n // K(C) = °C + 273.15\n // K(F) = (°F + 459.67) / 1.8\n // K(R) = °R / 1.8\n K: {\n name: 'K',\n base: BASE_UNITS.TEMPERATURE,\n prefixes: PREFIXES.NONE,\n value: 1,\n offset: 0\n },\n degC: {\n name: 'degC',\n base: BASE_UNITS.TEMPERATURE,\n prefixes: PREFIXES.NONE,\n value: 1,\n offset: 273.15\n },\n degF: {\n name: 'degF',\n base: BASE_UNITS.TEMPERATURE,\n prefixes: PREFIXES.NONE,\n value: 1 / 1.8,\n offset: 459.67\n },\n degR: {\n name: 'degR',\n base: BASE_UNITS.TEMPERATURE,\n prefixes: PREFIXES.NONE,\n value: 1 / 1.8,\n offset: 0\n },\n kelvin: {\n name: 'kelvin',\n base: BASE_UNITS.TEMPERATURE,\n prefixes: PREFIXES.NONE,\n value: 1,\n offset: 0\n },\n celsius: {\n name: 'celsius',\n base: BASE_UNITS.TEMPERATURE,\n prefixes: PREFIXES.NONE,\n value: 1,\n offset: 273.15\n },\n fahrenheit: {\n name: 'fahrenheit',\n base: BASE_UNITS.TEMPERATURE,\n prefixes: PREFIXES.NONE,\n value: 1 / 1.8,\n offset: 459.67\n },\n rankine: {\n name: 'rankine',\n base: BASE_UNITS.TEMPERATURE,\n prefixes: PREFIXES.NONE,\n value: 1 / 1.8,\n offset: 0\n },\n // amount of substance\n mol: {\n name: 'mol',\n base: BASE_UNITS.AMOUNT_OF_SUBSTANCE,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n mole: {\n name: 'mole',\n base: BASE_UNITS.AMOUNT_OF_SUBSTANCE,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n // luminous intensity\n cd: {\n name: 'cd',\n base: BASE_UNITS.LUMINOUS_INTENSITY,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n candela: {\n name: 'candela',\n base: BASE_UNITS.LUMINOUS_INTENSITY,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n // TODO: units STERADIAN\n // {name: 'sr', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0},\n // {name: 'steradian', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0},\n // Force\n N: {\n name: 'N',\n base: BASE_UNITS.FORCE,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n newton: {\n name: 'newton',\n base: BASE_UNITS.FORCE,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n dyn: {\n name: 'dyn',\n base: BASE_UNITS.FORCE,\n prefixes: PREFIXES.SHORT,\n value: 0.00001,\n offset: 0\n },\n dyne: {\n name: 'dyne',\n base: BASE_UNITS.FORCE,\n prefixes: PREFIXES.LONG,\n value: 0.00001,\n offset: 0\n },\n lbf: {\n name: 'lbf',\n base: BASE_UNITS.FORCE,\n prefixes: PREFIXES.NONE,\n value: 4.4482216152605,\n offset: 0\n },\n poundforce: {\n name: 'poundforce',\n base: BASE_UNITS.FORCE,\n prefixes: PREFIXES.NONE,\n value: 4.4482216152605,\n offset: 0\n },\n kip: {\n name: 'kip',\n base: BASE_UNITS.FORCE,\n prefixes: PREFIXES.LONG,\n value: 4448.2216,\n offset: 0\n },\n kilogramforce: {\n name: 'kilogramforce',\n base: BASE_UNITS.FORCE,\n prefixes: PREFIXES.NONE,\n value: 9.80665,\n offset: 0\n },\n // Energy\n J: {\n name: 'J',\n base: BASE_UNITS.ENERGY,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n joule: {\n name: 'joule',\n base: BASE_UNITS.ENERGY,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n erg: {\n name: 'erg',\n base: BASE_UNITS.ENERGY,\n prefixes: PREFIXES.NONE,\n value: 1e-7,\n offset: 0\n },\n Wh: {\n name: 'Wh',\n base: BASE_UNITS.ENERGY,\n prefixes: PREFIXES.SHORT,\n value: 3600,\n offset: 0\n },\n BTU: {\n name: 'BTU',\n base: BASE_UNITS.ENERGY,\n prefixes: PREFIXES.BTU,\n value: 1055.05585262,\n offset: 0\n },\n eV: {\n name: 'eV',\n base: BASE_UNITS.ENERGY,\n prefixes: PREFIXES.SHORT,\n value: 1.602176565e-19,\n offset: 0\n },\n electronvolt: {\n name: 'electronvolt',\n base: BASE_UNITS.ENERGY,\n prefixes: PREFIXES.LONG,\n value: 1.602176565e-19,\n offset: 0\n },\n // Power\n W: {\n name: 'W',\n base: BASE_UNITS.POWER,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n watt: {\n name: 'watt',\n base: BASE_UNITS.POWER,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n hp: {\n name: 'hp',\n base: BASE_UNITS.POWER,\n prefixes: PREFIXES.NONE,\n value: 745.6998715386,\n offset: 0\n },\n // Electrical power units\n VAR: {\n name: 'VAR',\n base: BASE_UNITS.POWER,\n prefixes: PREFIXES.SHORT,\n value: Complex.I,\n offset: 0\n },\n VA: {\n name: 'VA',\n base: BASE_UNITS.POWER,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n // Pressure\n Pa: {\n name: 'Pa',\n base: BASE_UNITS.PRESSURE,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n psi: {\n name: 'psi',\n base: BASE_UNITS.PRESSURE,\n prefixes: PREFIXES.NONE,\n value: 6894.75729276459,\n offset: 0\n },\n atm: {\n name: 'atm',\n base: BASE_UNITS.PRESSURE,\n prefixes: PREFIXES.NONE,\n value: 101325,\n offset: 0\n },\n bar: {\n name: 'bar',\n base: BASE_UNITS.PRESSURE,\n prefixes: PREFIXES.SHORTLONG,\n value: 100000,\n offset: 0\n },\n torr: {\n name: 'torr',\n base: BASE_UNITS.PRESSURE,\n prefixes: PREFIXES.NONE,\n value: 133.322,\n offset: 0\n },\n mmHg: {\n name: 'mmHg',\n base: BASE_UNITS.PRESSURE,\n prefixes: PREFIXES.NONE,\n value: 133.322,\n offset: 0\n },\n mmH2O: {\n name: 'mmH2O',\n base: BASE_UNITS.PRESSURE,\n prefixes: PREFIXES.NONE,\n value: 9.80665,\n offset: 0\n },\n cmH2O: {\n name: 'cmH2O',\n base: BASE_UNITS.PRESSURE,\n prefixes: PREFIXES.NONE,\n value: 98.0665,\n offset: 0\n },\n // Electric charge\n coulomb: {\n name: 'coulomb',\n base: BASE_UNITS.ELECTRIC_CHARGE,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n C: {\n name: 'C',\n base: BASE_UNITS.ELECTRIC_CHARGE,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n // Electric capacitance\n farad: {\n name: 'farad',\n base: BASE_UNITS.ELECTRIC_CAPACITANCE,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n F: {\n name: 'F',\n base: BASE_UNITS.ELECTRIC_CAPACITANCE,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n // Electric potential\n volt: {\n name: 'volt',\n base: BASE_UNITS.ELECTRIC_POTENTIAL,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n V: {\n name: 'V',\n base: BASE_UNITS.ELECTRIC_POTENTIAL,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n // Electric resistance\n ohm: {\n name: 'ohm',\n base: BASE_UNITS.ELECTRIC_RESISTANCE,\n prefixes: PREFIXES.SHORTLONG,\n // Both Mohm and megaohm are acceptable\n value: 1,\n offset: 0\n },\n\n /*\n * Unicode breaks in browsers if charset is not specified\n Ω: {\n name: 'Ω',\n base: BASE_UNITS.ELECTRIC_RESISTANCE,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n */\n // Electric inductance\n henry: {\n name: 'henry',\n base: BASE_UNITS.ELECTRIC_INDUCTANCE,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n H: {\n name: 'H',\n base: BASE_UNITS.ELECTRIC_INDUCTANCE,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n // Electric conductance\n siemens: {\n name: 'siemens',\n base: BASE_UNITS.ELECTRIC_CONDUCTANCE,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n S: {\n name: 'S',\n base: BASE_UNITS.ELECTRIC_CONDUCTANCE,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n // Magnetic flux\n weber: {\n name: 'weber',\n base: BASE_UNITS.MAGNETIC_FLUX,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n Wb: {\n name: 'Wb',\n base: BASE_UNITS.MAGNETIC_FLUX,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n // Magnetic flux density\n tesla: {\n name: 'tesla',\n base: BASE_UNITS.MAGNETIC_FLUX_DENSITY,\n prefixes: PREFIXES.LONG,\n value: 1,\n offset: 0\n },\n T: {\n name: 'T',\n base: BASE_UNITS.MAGNETIC_FLUX_DENSITY,\n prefixes: PREFIXES.SHORT,\n value: 1,\n offset: 0\n },\n // Binary\n b: {\n name: 'b',\n base: BASE_UNITS.BIT,\n prefixes: PREFIXES.BINARY_SHORT,\n value: 1,\n offset: 0\n },\n bits: {\n name: 'bits',\n base: BASE_UNITS.BIT,\n prefixes: PREFIXES.BINARY_LONG,\n value: 1,\n offset: 0\n },\n B: {\n name: 'B',\n base: BASE_UNITS.BIT,\n prefixes: PREFIXES.BINARY_SHORT,\n value: 8,\n offset: 0\n },\n bytes: {\n name: 'bytes',\n base: BASE_UNITS.BIT,\n prefixes: PREFIXES.BINARY_LONG,\n value: 8,\n offset: 0\n }\n }; // aliases (formerly plurals)\n\n var ALIASES = {\n meters: 'meter',\n inches: 'inch',\n feet: 'foot',\n yards: 'yard',\n miles: 'mile',\n links: 'link',\n rods: 'rod',\n chains: 'chain',\n angstroms: 'angstrom',\n lt: 'l',\n litres: 'litre',\n liter: 'litre',\n liters: 'litre',\n teaspoons: 'teaspoon',\n tablespoons: 'tablespoon',\n minims: 'minim',\n fluiddrams: 'fluiddram',\n fluidounces: 'fluidounce',\n gills: 'gill',\n cups: 'cup',\n pints: 'pint',\n quarts: 'quart',\n gallons: 'gallon',\n beerbarrels: 'beerbarrel',\n oilbarrels: 'oilbarrel',\n hogsheads: 'hogshead',\n gtts: 'gtt',\n grams: 'gram',\n tons: 'ton',\n tonnes: 'tonne',\n grains: 'grain',\n drams: 'dram',\n ounces: 'ounce',\n poundmasses: 'poundmass',\n hundredweights: 'hundredweight',\n sticks: 'stick',\n lb: 'lbm',\n lbs: 'lbm',\n kips: 'kip',\n kgf: 'kilogramforce',\n acres: 'acre',\n hectares: 'hectare',\n sqfeet: 'sqft',\n sqyard: 'sqyd',\n sqmile: 'sqmi',\n sqmiles: 'sqmi',\n mmhg: 'mmHg',\n mmh2o: 'mmH2O',\n cmh2o: 'cmH2O',\n seconds: 'second',\n secs: 'second',\n minutes: 'minute',\n mins: 'minute',\n hours: 'hour',\n hr: 'hour',\n hrs: 'hour',\n days: 'day',\n weeks: 'week',\n months: 'month',\n years: 'year',\n decades: 'decade',\n centuries: 'century',\n millennia: 'millennium',\n hertz: 'hertz',\n radians: 'radian',\n degrees: 'degree',\n gradians: 'gradian',\n cycles: 'cycle',\n arcsecond: 'arcsec',\n arcseconds: 'arcsec',\n arcminute: 'arcmin',\n arcminutes: 'arcmin',\n BTUs: 'BTU',\n watts: 'watt',\n joules: 'joule',\n amperes: 'ampere',\n coulombs: 'coulomb',\n volts: 'volt',\n ohms: 'ohm',\n farads: 'farad',\n webers: 'weber',\n teslas: 'tesla',\n electronvolts: 'electronvolt',\n moles: 'mole',\n bit: 'bits',\n byte: 'bytes'\n };\n /**\n * Calculate the values for the angle units.\n * Value is calculated as number or BigNumber depending on the configuration\n * @param {{number: 'number' | 'BigNumber'}} config\n */\n\n function calculateAngleValues(config) {\n if (config.number === 'BigNumber') {\n var pi = createPi(_BigNumber);\n UNITS.rad.value = new _BigNumber(1);\n UNITS.deg.value = pi.div(180); // 2 * pi / 360\n\n UNITS.grad.value = pi.div(200); // 2 * pi / 400\n\n UNITS.cycle.value = pi.times(2); // 2 * pi\n\n UNITS.arcsec.value = pi.div(648000); // 2 * pi / 360 / 3600\n\n UNITS.arcmin.value = pi.div(10800); // 2 * pi / 360 / 60\n } else {\n // number\n UNITS.rad.value = 1;\n UNITS.deg.value = Math.PI / 180; // 2 * pi / 360\n\n UNITS.grad.value = Math.PI / 200; // 2 * pi / 400\n\n UNITS.cycle.value = Math.PI * 2; // 2 * pi\n\n UNITS.arcsec.value = Math.PI / 648000; // 2 * pi / 360 / 3600\n\n UNITS.arcmin.value = Math.PI / 10800; // 2 * pi / 360 / 60\n } // copy to the full names of the angles\n\n\n UNITS.radian.value = UNITS.rad.value;\n UNITS.degree.value = UNITS.deg.value;\n UNITS.gradian.value = UNITS.grad.value;\n } // apply the angle values now\n\n\n calculateAngleValues(config);\n\n if (on) {\n // recalculate the values on change of configuration\n on('config', function (curr, prev) {\n if (curr.number !== prev.number) {\n calculateAngleValues(curr);\n }\n });\n }\n /**\n * A unit system is a set of dimensionally independent base units plus a set of derived units, formed by multiplication and division of the base units, that are by convention used with the unit system.\n * A user perhaps could issue a command to select a preferred unit system, or use the default (see below).\n * Auto unit system: The default unit system is updated on the fly anytime a unit is parsed. The corresponding unit in the default unit system is updated, so that answers are given in the same units the user supplies.\n */\n\n\n var UNIT_SYSTEMS = {\n si: {\n // Base units\n NONE: {\n unit: UNIT_NONE,\n prefix: PREFIXES.NONE['']\n },\n LENGTH: {\n unit: UNITS.m,\n prefix: PREFIXES.SHORT['']\n },\n MASS: {\n unit: UNITS.g,\n prefix: PREFIXES.SHORT.k\n },\n TIME: {\n unit: UNITS.s,\n prefix: PREFIXES.SHORT['']\n },\n CURRENT: {\n unit: UNITS.A,\n prefix: PREFIXES.SHORT['']\n },\n TEMPERATURE: {\n unit: UNITS.K,\n prefix: PREFIXES.SHORT['']\n },\n LUMINOUS_INTENSITY: {\n unit: UNITS.cd,\n prefix: PREFIXES.SHORT['']\n },\n AMOUNT_OF_SUBSTANCE: {\n unit: UNITS.mol,\n prefix: PREFIXES.SHORT['']\n },\n ANGLE: {\n unit: UNITS.rad,\n prefix: PREFIXES.SHORT['']\n },\n BIT: {\n unit: UNITS.bits,\n prefix: PREFIXES.SHORT['']\n },\n // Derived units\n FORCE: {\n unit: UNITS.N,\n prefix: PREFIXES.SHORT['']\n },\n ENERGY: {\n unit: UNITS.J,\n prefix: PREFIXES.SHORT['']\n },\n POWER: {\n unit: UNITS.W,\n prefix: PREFIXES.SHORT['']\n },\n PRESSURE: {\n unit: UNITS.Pa,\n prefix: PREFIXES.SHORT['']\n },\n ELECTRIC_CHARGE: {\n unit: UNITS.C,\n prefix: PREFIXES.SHORT['']\n },\n ELECTRIC_CAPACITANCE: {\n unit: UNITS.F,\n prefix: PREFIXES.SHORT['']\n },\n ELECTRIC_POTENTIAL: {\n unit: UNITS.V,\n prefix: PREFIXES.SHORT['']\n },\n ELECTRIC_RESISTANCE: {\n unit: UNITS.ohm,\n prefix: PREFIXES.SHORT['']\n },\n ELECTRIC_INDUCTANCE: {\n unit: UNITS.H,\n prefix: PREFIXES.SHORT['']\n },\n ELECTRIC_CONDUCTANCE: {\n unit: UNITS.S,\n prefix: PREFIXES.SHORT['']\n },\n MAGNETIC_FLUX: {\n unit: UNITS.Wb,\n prefix: PREFIXES.SHORT['']\n },\n MAGNETIC_FLUX_DENSITY: {\n unit: UNITS.T,\n prefix: PREFIXES.SHORT['']\n },\n FREQUENCY: {\n unit: UNITS.Hz,\n prefix: PREFIXES.SHORT['']\n }\n }\n }; // Clone to create the other unit systems\n\n UNIT_SYSTEMS.cgs = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));\n UNIT_SYSTEMS.cgs.LENGTH = {\n unit: UNITS.m,\n prefix: PREFIXES.SHORT.c\n };\n UNIT_SYSTEMS.cgs.MASS = {\n unit: UNITS.g,\n prefix: PREFIXES.SHORT['']\n };\n UNIT_SYSTEMS.cgs.FORCE = {\n unit: UNITS.dyn,\n prefix: PREFIXES.SHORT['']\n };\n UNIT_SYSTEMS.cgs.ENERGY = {\n unit: UNITS.erg,\n prefix: PREFIXES.NONE['']\n }; // there are wholly 4 unique cgs systems for electricity and magnetism,\n // so let's not worry about it unless somebody complains\n\n UNIT_SYSTEMS.us = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));\n UNIT_SYSTEMS.us.LENGTH = {\n unit: UNITS.ft,\n prefix: PREFIXES.NONE['']\n };\n UNIT_SYSTEMS.us.MASS = {\n unit: UNITS.lbm,\n prefix: PREFIXES.NONE['']\n };\n UNIT_SYSTEMS.us.TEMPERATURE = {\n unit: UNITS.degF,\n prefix: PREFIXES.NONE['']\n };\n UNIT_SYSTEMS.us.FORCE = {\n unit: UNITS.lbf,\n prefix: PREFIXES.NONE['']\n };\n UNIT_SYSTEMS.us.ENERGY = {\n unit: UNITS.BTU,\n prefix: PREFIXES.BTU['']\n };\n UNIT_SYSTEMS.us.POWER = {\n unit: UNITS.hp,\n prefix: PREFIXES.NONE['']\n };\n UNIT_SYSTEMS.us.PRESSURE = {\n unit: UNITS.psi,\n prefix: PREFIXES.NONE['']\n }; // Add additional unit systems here.\n // Choose a unit system to seed the auto unit system.\n\n UNIT_SYSTEMS.auto = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); // Set the current unit system\n\n var currentUnitSystem = UNIT_SYSTEMS.auto;\n /**\n * Set a unit system for formatting derived units.\n * @param {string} [name] The name of the unit system.\n */\n\n Unit.setUnitSystem = function (name) {\n if (hasOwnProperty(UNIT_SYSTEMS, name)) {\n currentUnitSystem = UNIT_SYSTEMS[name];\n } else {\n throw new Error('Unit system ' + name + ' does not exist. Choices are: ' + Object.keys(UNIT_SYSTEMS).join(', '));\n }\n };\n /**\n * Return the current unit system.\n * @return {string} The current unit system.\n */\n\n\n Unit.getUnitSystem = function () {\n for (var _key in UNIT_SYSTEMS) {\n if (hasOwnProperty(UNIT_SYSTEMS, _key)) {\n if (UNIT_SYSTEMS[_key] === currentUnitSystem) {\n return _key;\n }\n }\n }\n };\n /**\n * Converters to convert from number to an other numeric type like BigNumber\n * or Fraction\n */\n\n\n Unit.typeConverters = {\n BigNumber: function BigNumber(x) {\n return new _BigNumber(x + ''); // stringify to prevent constructor error\n },\n Fraction: function Fraction(x) {\n return new _Fraction(x);\n },\n Complex: function Complex(x) {\n return x;\n },\n number: function number(x) {\n return x;\n }\n };\n /**\n * Retrieve the right convertor function corresponding with the type\n * of provided exampleValue.\n *\n * @param {string} type A string 'number', 'BigNumber', or 'Fraction'\n * In case of an unknown type,\n * @return {Function}\n */\n\n Unit._getNumberConverter = function (type) {\n if (!Unit.typeConverters[type]) {\n throw new TypeError('Unsupported type \"' + type + '\"');\n }\n\n return Unit.typeConverters[type];\n }; // Add dimensions to each built-in unit\n\n\n for (var _key2 in UNITS) {\n if (hasOwnProperty(UNITS, _key2)) {\n var unit = UNITS[_key2];\n unit.dimensions = unit.base.dimensions;\n }\n } // Create aliases\n\n\n for (var _name2 in ALIASES) {\n if (hasOwnProperty(ALIASES, _name2)) {\n var _unit2 = UNITS[ALIASES[_name2]];\n var alias = {};\n\n for (var _key3 in _unit2) {\n if (hasOwnProperty(_unit2, _key3)) {\n alias[_key3] = _unit2[_key3];\n }\n }\n\n alias.name = _name2;\n UNITS[_name2] = alias;\n }\n }\n /**\n * Checks if a character is a valid latin letter (upper or lower case).\n * Note that this function can be overridden, for example to allow support of other alphabets.\n * @param {string} c Tested character\n */\n\n\n Unit.isValidAlpha = function isValidAlpha(c) {\n return /^[a-zA-Z]$/.test(c);\n };\n\n function assertUnitNameIsValid(name) {\n for (var i = 0; i < name.length; i++) {\n c = name.charAt(i);\n\n if (i === 0 && !Unit.isValidAlpha(c)) {\n throw new Error('Invalid unit name (must begin with alpha character): \"' + name + '\"');\n }\n\n if (i > 0 && !(Unit.isValidAlpha(c) || isDigit(c))) {\n throw new Error('Invalid unit name (only alphanumeric characters are allowed): \"' + name + '\"');\n }\n }\n }\n /**\n * Wrapper around createUnitSingle.\n * Example:\n * createUnit({\n * foo: { },\n * bar: {\n * definition: 'kg/foo',\n * aliases: ['ba', 'barr', 'bars'],\n * offset: 200\n * },\n * baz: '4 bar'\n * },\n * {\n * override: true\n * })\n * @param {object} obj Object map. Each key becomes a unit which is defined by its value.\n * @param {object} options\n */\n\n\n Unit.createUnit = function (obj, options) {\n if (typeof obj !== 'object') {\n throw new TypeError(\"createUnit expects first parameter to be of type 'Object'\");\n } // Remove all units and aliases we are overriding\n\n\n if (options && options.override) {\n for (var _key4 in obj) {\n if (hasOwnProperty(obj, _key4)) {\n Unit.deleteUnit(_key4);\n }\n\n if (obj[_key4].aliases) {\n for (var i = 0; i < obj[_key4].aliases.length; i++) {\n Unit.deleteUnit(obj[_key4].aliases[i]);\n }\n }\n }\n } // TODO: traverse multiple times until all units have been added\n\n\n var lastUnit;\n\n for (var _key5 in obj) {\n if (hasOwnProperty(obj, _key5)) {\n lastUnit = Unit.createUnitSingle(_key5, obj[_key5]);\n }\n }\n\n return lastUnit;\n };\n /**\n * Create a user-defined unit and register it with the Unit type.\n * Example:\n * createUnitSingle('knot', '0.514444444 m/s')\n * createUnitSingle('acre', new Unit(43560, 'ft^2'))\n *\n * @param {string} name The name of the new unit. Must be unique. Example: 'knot'\n * @param {string, Unit, Object} definition Definition of the unit in terms\n * of existing units. For example, '0.514444444 m / s'. Can be a Unit, a string,\n * or an Object. If an Object, may have the following properties:\n * - definition {string|Unit} The definition of this unit.\n * - prefixes {string} \"none\", \"short\", \"long\", \"binary_short\", or \"binary_long\".\n * The default is \"none\".\n * - aliases {Array} Array of strings. Example: ['knots', 'kt', 'kts']\n * - offset {Numeric} An offset to apply when converting from the unit. For\n * example, the offset for celsius is 273.15 and the offset for farhenheit\n * is 459.67. Default is 0.\n * - baseName {string} If the unit's dimension does not match that of any other\n * base unit, the name of the newly create base unit. Otherwise, this property\n * has no effect.\n *\n * @param {Object} options (optional) An object containing any of the following\n * properties:\n * - override {boolean} Whether this unit should be allowed to override existing\n * units.\n *\n * @return {Unit}\n */\n\n\n Unit.createUnitSingle = function (name, obj, options) {\n if (typeof obj === 'undefined' || obj === null) {\n obj = {};\n }\n\n if (typeof name !== 'string') {\n throw new TypeError(\"createUnitSingle expects first parameter to be of type 'string'\");\n } // Check collisions with existing units\n\n\n if (hasOwnProperty(UNITS, name)) {\n throw new Error('Cannot create unit \"' + name + '\": a unit with that name already exists');\n } // TODO: Validate name for collisions with other built-in functions (like abs or cos, for example), and for acceptable variable names. For example, '42' is probably not a valid unit. Nor is '%', since it is also an operator.\n\n\n assertUnitNameIsValid(name);\n var defUnit = null; // The Unit from which the new unit will be created.\n\n var aliases = [];\n var offset = 0;\n var definition;\n var prefixes;\n var baseName;\n\n if (obj && obj.type === 'Unit') {\n defUnit = obj.clone();\n } else if (typeof obj === 'string') {\n if (obj !== '') {\n definition = obj;\n }\n } else if (typeof obj === 'object') {\n definition = obj.definition;\n prefixes = obj.prefixes;\n offset = obj.offset;\n baseName = obj.baseName;\n\n if (obj.aliases) {\n aliases = obj.aliases.valueOf(); // aliases could be a Matrix, so convert to Array\n }\n } else {\n throw new TypeError('Cannot create unit \"' + name + '\" from \"' + obj.toString() + '\": expecting \"string\" or \"Unit\" or \"Object\"');\n }\n\n if (aliases) {\n for (var i = 0; i < aliases.length; i++) {\n if (hasOwnProperty(UNITS, aliases[i])) {\n throw new Error('Cannot create alias \"' + aliases[i] + '\": a unit with that name already exists');\n }\n }\n }\n\n if (definition && typeof definition === 'string' && !defUnit) {\n try {\n defUnit = Unit.parse(definition, {\n allowNoUnits: true\n });\n } catch (ex) {\n ex.message = 'Could not create unit \"' + name + '\" from \"' + definition + '\": ' + ex.message;\n throw ex;\n }\n } else if (definition && definition.type === 'Unit') {\n defUnit = definition.clone();\n }\n\n aliases = aliases || [];\n offset = offset || 0;\n\n if (prefixes && prefixes.toUpperCase) {\n prefixes = PREFIXES[prefixes.toUpperCase()] || PREFIXES.NONE;\n } else {\n prefixes = PREFIXES.NONE;\n } // If defUnit is null, it is because the user did not\n // specify a defintion. So create a new base dimension.\n\n\n var newUnit = {};\n\n if (!defUnit) {\n // Add a new base dimension\n baseName = baseName || name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo\n\n if (BASE_DIMENSIONS.indexOf(baseName) >= 0) {\n throw new Error('Cannot create new base unit \"' + name + '\": a base unit with that name already exists (and cannot be overridden)');\n }\n\n BASE_DIMENSIONS.push(baseName); // Push 0 onto existing base units\n\n for (var b in BASE_UNITS) {\n if (hasOwnProperty(BASE_UNITS, b)) {\n BASE_UNITS[b].dimensions[BASE_DIMENSIONS.length - 1] = 0;\n }\n } // Add the new base unit\n\n\n var newBaseUnit = {\n dimensions: []\n };\n\n for (var _i6 = 0; _i6 < BASE_DIMENSIONS.length; _i6++) {\n newBaseUnit.dimensions[_i6] = 0;\n }\n\n newBaseUnit.dimensions[BASE_DIMENSIONS.length - 1] = 1;\n newBaseUnit.key = baseName;\n BASE_UNITS[baseName] = newBaseUnit;\n newUnit = {\n name: name,\n value: 1,\n dimensions: BASE_UNITS[baseName].dimensions.slice(0),\n prefixes: prefixes,\n offset: offset,\n base: BASE_UNITS[baseName]\n };\n currentUnitSystem[baseName] = {\n unit: newUnit,\n prefix: PREFIXES.NONE['']\n };\n } else {\n newUnit = {\n name: name,\n value: defUnit.value,\n dimensions: defUnit.dimensions.slice(0),\n prefixes: prefixes,\n offset: offset\n }; // Create a new base if no matching base exists\n\n var anyMatch = false;\n\n for (var _i7 in BASE_UNITS) {\n if (hasOwnProperty(BASE_UNITS, _i7)) {\n var match = true;\n\n for (var j = 0; j < BASE_DIMENSIONS.length; j++) {\n if (Math.abs((newUnit.dimensions[j] || 0) - (BASE_UNITS[_i7].dimensions[j] || 0)) > 1e-12) {\n match = false;\n break;\n }\n }\n\n if (match) {\n anyMatch = true;\n newUnit.base = BASE_UNITS[_i7];\n break;\n }\n }\n }\n\n if (!anyMatch) {\n baseName = baseName || name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo\n // Add the new base unit\n\n var _newBaseUnit = {\n dimensions: defUnit.dimensions.slice(0)\n };\n _newBaseUnit.key = baseName;\n BASE_UNITS[baseName] = _newBaseUnit;\n currentUnitSystem[baseName] = {\n unit: newUnit,\n prefix: PREFIXES.NONE['']\n };\n newUnit.base = BASE_UNITS[baseName];\n }\n }\n\n Unit.UNITS[name] = newUnit;\n\n for (var _i8 = 0; _i8 < aliases.length; _i8++) {\n var aliasName = aliases[_i8];\n var _alias = {};\n\n for (var _key6 in newUnit) {\n if (hasOwnProperty(newUnit, _key6)) {\n _alias[_key6] = newUnit[_key6];\n }\n }\n\n _alias.name = aliasName;\n Unit.UNITS[aliasName] = _alias;\n } // delete the memoization cache, since adding a new unit to the array\n // invalidates all old results\n\n\n delete _findUnit.cache;\n return new Unit(null, name);\n };\n\n Unit.deleteUnit = function (name) {\n delete Unit.UNITS[name];\n }; // expose arrays with prefixes, dimensions, units, systems\n\n\n Unit.PREFIXES = PREFIXES;\n Unit.BASE_DIMENSIONS = BASE_DIMENSIONS;\n Unit.BASE_UNITS = BASE_UNITS;\n Unit.UNIT_SYSTEMS = UNIT_SYSTEMS;\n Unit.UNITS = UNITS;\n return Unit;\n}, {\n isClass: true\n});","import { isArray, isMatrix } from '../../../utils/is.js';\nimport { factory } from '../../../utils/factory.js';\nimport { createSolveValidation } from './utils/solveValidation.js';\nimport { csIpvec } from '../sparse/csIpvec.js';\nvar name = 'lusolve';\nvar dependencies = ['typed', 'matrix', 'lup', 'slu', 'usolve', 'lsolve', 'DenseMatrix'];\nexport var createLusolve = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n matrix,\n lup,\n slu,\n usolve,\n lsolve,\n DenseMatrix\n } = _ref;\n var solveValidation = createSolveValidation({\n DenseMatrix\n });\n /**\n * Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector.\n *\n * Syntax:\n *\n * math.lusolve(A, b) // returns column vector with the solution to the linear system A * x = b\n * math.lusolve(lup, b) // returns column vector with the solution to the linear system A * x = b, lup = math.lup(A)\n *\n * Examples:\n *\n * const m = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]\n *\n * const x = math.lusolve(m, [-1, -1, -1, -1]) // x = [[-1], [-0.5], [-1/3], [-0.25]]\n *\n * const f = math.lup(m)\n * const x1 = math.lusolve(f, [-1, -1, -1, -1]) // x1 = [[-1], [-0.5], [-1/3], [-0.25]]\n * const x2 = math.lusolve(f, [1, 2, 1, -1]) // x2 = [[1], [1], [1/3], [-0.25]]\n *\n * const a = [[-2, 3], [2, 1]]\n * const b = [11, 9]\n * const x = math.lusolve(a, b) // [[2], [5]]\n *\n * See also:\n *\n * lup, slu, lsolve, usolve\n *\n * @param {Matrix | Array | Object} A Invertible Matrix or the Matrix LU decomposition\n * @param {Matrix | Array} b Column Vector\n * @param {number} [order] The Symbolic Ordering and Analysis order, see slu for details. Matrix must be a SparseMatrix\n * @param {Number} [threshold] Partial pivoting threshold (1 for partial pivoting), see slu for details. Matrix must be a SparseMatrix.\n *\n * @return {DenseMatrix | Array} Column vector with the solution to the linear system A * x = b\n */\n\n return typed(name, {\n 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {\n a = matrix(a);\n var d = lup(a);\n\n var x = _lusolve(d.L, d.U, d.p, null, b);\n\n return x.valueOf();\n },\n 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(a, b) {\n var d = lup(a);\n return _lusolve(d.L, d.U, d.p, null, b);\n },\n 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(a, b) {\n var d = lup(a);\n return _lusolve(d.L, d.U, d.p, null, b);\n },\n 'SparseMatrix, Array | Matrix, number, number': function SparseMatrixArrayMatrixNumberNumber(a, b, order, threshold) {\n var d = slu(a, order, threshold);\n return _lusolve(d.L, d.U, d.p, d.q, b);\n },\n 'Object, Array | Matrix': function ObjectArrayMatrix(d, b) {\n return _lusolve(d.L, d.U, d.p, d.q, b);\n }\n });\n\n function _toMatrix(a) {\n if (isMatrix(a)) {\n return a;\n }\n\n if (isArray(a)) {\n return matrix(a);\n }\n\n throw new TypeError('Invalid Matrix LU decomposition');\n }\n\n function _lusolve(l, u, p, q, b) {\n // verify decomposition\n l = _toMatrix(l);\n u = _toMatrix(u); // apply row permutations if needed (b is a DenseMatrix)\n\n if (p) {\n b = solveValidation(l, b, true);\n b._data = csIpvec(p, b._data);\n } // use forward substitution to resolve L * y = b\n\n\n var y = lsolve(l, b); // use backward substitution to resolve U * x = y\n\n var x = usolve(u, y); // apply column permutations if needed (x is a DenseMatrix)\n\n if (q) {\n x._data = csIpvec(q, x._data);\n }\n\n return x;\n }\n});","import { factory } from '../../../utils/factory.js';\nimport { deepMap } from '../../../utils/collection.js';\nvar name = 'unit';\nvar dependencies = ['typed', 'Unit']; // This function is named createUnitFunction to prevent a naming conflict with createUnit\n\nexport var createUnitFunction = /* #__PURE__ */factory(name, dependencies, (_ref) => {\n var {\n typed,\n Unit\n } = _ref;\n\n /**\n * Create a unit. Depending on the passed arguments, the function\n * will create and return a new math.Unit object.\n * When a matrix is provided, all elements will be converted to units.\n *\n * Syntax:\n *\n * math.unit(unit : string)\n * math.unit(value : number, unit : string)\n *\n * Examples:\n *\n * const a = math.unit(5, 'cm') // returns Unit 50 mm\n * const b = math.unit('23 kg') // returns Unit 23 kg\n * a.to('m') // returns Unit 0.05 m\n *\n * See also:\n *\n * bignumber, boolean, complex, index, matrix, number, string, createUnit\n *\n * @param {* | Array | Matrix} args A number and unit.\n * @return {Unit | Array | Matrix} The created unit\n */\n return typed(name, {\n Unit: function Unit(x) {\n return x.clone();\n },\n string: function string(x) {\n if (Unit.isValuelessUnit(x)) {\n return new Unit(null, x); // a pure unit\n }\n\n return Unit.parse(x, {\n allowNoUnits: true\n }); // a unit with value, like '5cm'\n },\n 'number | BigNumber | Fraction | Complex, string': function numberBigNumberFractionComplexString(value, unit) {\n return new Unit(value, unit);\n },\n 'Array | Matrix': function ArrayMatrix(x) {\n return deepMap(x, this);\n }\n });\n});","/**\n * THIS FILE IS AUTO-GENERATED\n * DON'T MAKE CHANGES HERE\n */\nimport { config } from './configReadonly.js';\nimport { createResultSet, createComplexClass, createRangeClass, createFalse, createNull, createTrue, createBigNumberClass, createMatrixClass, createReplacer, createI, createLN10, createLOG10E, createNaN, createPi, createSQRT1_2 // eslint-disable-line camelcase\n, createTau, createEfimovFactor, createFineStructure, createSackurTetrode, createWeakMixingAngle, createFractionClass, createE, createInfinity, createLOG2E, createVersion, createDenseMatrixClass, createPhi, createTyped, createIsInteger, createIsNumeric, createIsPositive, createIsNaN, createEqualScalar, createNumber, createBoolean, createComplex, createSplitUnit, createUnaryPlus, createApply, createCube, createExpm1, createLog10, createMultiplyScalar, createSign, createSquare, createBitNot, createArg, createIm, createNot, createFilter, createForEach, createMap, createErf, createFormat, createOct, createPrint, createIsPrime, createAcos, createAcot, createAcsc, createAsec, createAsin, createAtan, createAtanh, createCosh, createCoth, createCsch, createSech, createSinh, createTanh, createCombinations, createPickRandom, createRandomInt, createLN2, createClone, createHasNumericValue, createTypeOf, createString, createFraction, createUnaryMinus, createAddScalar, createExp, createLog2, createSqrt, createConj, createGetMatrixDataType, createMode, createBin, createAcosh, createAcsch, createAsinh, createCos, createCsc, createSin, createCombinationsWithRep, createRandom, createSQRT2, createIsNegative, createSparseMatrixClass, createMatrix, createCbrt, createGcd, createMod, createNthRoot, createXgcd, createBitAnd, createBitXor, createOr, createConcat, createDiag, createIdentity, createOnes, createReshape, createSize, createSubset, createZeros, createHex, createRound, createLeftShift, createRightLogShift, createCompare, createCompareText, createSmaller, createLarger, createUnequal, createImmutableDenseMatrixClass, createFibonacciHeapClass, createSparse, createAcoth, createAtan2, createSec, createAdd, createDot, createComposition, createIsZero, createAbs, createFloor, createMultiply, createDotMultiply, createRe, createFlatten, createResize, createSqueeze, createTo, createPow, createDotPow, createRightArithShift, createCompareNatural, createEqualText, createLargerEq, createPartitionSelect, createIndexClass, createAsech, createTan, createSetDifference, createSetIntersect, createSetMultiplicity, createSetSize, createTrace, createQuantileSeq, createGamma, createBignumber, createLcm, createBitOr, createKron, createTranspose, createNumeric, createAnd, createSmallerEq, createSort, createMin, createCot, createSetDistinct, createSetPowerset, createIndex, createSum, createFactorial, createPermutations, createCeil, createSubtract, createCross, createRange, createRow, createProd, createEqual, createMax, createSetCartesian, createSetSymDifference, createFix, createColumn, createDiff, createCtranspose, createDeepEqual, createSetIsSubset, createXor, createDivideScalar, createNthRoots, createLsolve, createLsolveAll, createSpaClass, createSetUnion, createLup, createSlu, createDet, createDistance, createStirlingS2, createCatalan, createCount, createLog, createDotDivide, createUsolveAll, createHypot, createQr, createInv, createExpm, createDivide, createMean, createVariance, createKldivergence, createBellNumbers, createLog1p, createUnitClass, createCreateUnit, createEigs, createIntersect, createStd, createAtomicMass, createBohrMagneton, createBoltzmann, createConductanceQuantum, createDeuteronMass, createElectronMass, createFaraday, createFirstRadiation, createGravitationConstant, createHartreeEnergy, createKlitzing, createMagneticConstant, createMolarMass, createMolarPlanckConstant, createNeutronMass, createPlanckCharge, createPlanckLength, createPlanckTemperature, createProtonMass, createReducedPlanckConstant, createSecondRadiation, createStefanBoltzmann, createVacuumImpedance, createUsolve, createNorm, createLusolve, createSqrtm, createMultinomial, createAvogadro, createClassicalElectronRadius, createElectricConstant, createFermiCoupling, createGravity, createLoschmidt, createMolarMassC12, createNuclearMagneton, createPlanckMass, createQuantumOfCirculation, createSpeedOfLight, createWienDisplacement, createRotationMatrix, createMedian, createBohrRadius, createElementaryCharge, createInverseConductanceQuantum, createMolarVolume, createPlanckTime, createThomsonCrossSection, createRotate, createMad, createCoulomb, createMagneticFluxQuantum, createRydberg, createUnitFunction, createGasConstant, createPlanckConstant } from '../factoriesAny.js';\nexport var ResultSet = /* #__PURE__ */createResultSet({});\nexport var Complex = /* #__PURE__ */createComplexClass({});\nexport var Range = /* #__PURE__ */createRangeClass({});\nexport var _false = /* #__PURE__ */createFalse({});\nexport var _null = /* #__PURE__ */createNull({});\nexport var _true = /* #__PURE__ */createTrue({});\nexport var BigNumber = /* #__PURE__ */createBigNumberClass({\n config\n});\nexport var Matrix = /* #__PURE__ */createMatrixClass({});\nexport var replacer = /* #__PURE__ */createReplacer({});\nexport var i = /* #__PURE__ */createI({\n Complex\n});\nexport var LN10 = /* #__PURE__ */createLN10({\n BigNumber,\n config\n});\nexport var LOG10E = /* #__PURE__ */createLOG10E({\n BigNumber,\n config\n});\nexport var _NaN = /* #__PURE__ */createNaN({\n BigNumber,\n config\n});\nexport var pi = /* #__PURE__ */createPi({\n BigNumber,\n config\n});\nexport var SQRT1_2 = /* #__PURE__ */createSQRT1_2({\n BigNumber,\n config\n});\nexport var tau = /* #__PURE__ */createTau({\n BigNumber,\n config\n});\nexport var efimovFactor = /* #__PURE__ */createEfimovFactor({\n BigNumber,\n config\n});\nexport var fineStructure = /* #__PURE__ */createFineStructure({\n BigNumber,\n config\n});\nexport var sackurTetrode = /* #__PURE__ */createSackurTetrode({\n BigNumber,\n config\n});\nexport var weakMixingAngle = /* #__PURE__ */createWeakMixingAngle({\n BigNumber,\n config\n});\nexport var Fraction = /* #__PURE__ */createFractionClass({});\nexport var e = /* #__PURE__ */createE({\n BigNumber,\n config\n});\nexport var _Infinity = /* #__PURE__ */createInfinity({\n BigNumber,\n config\n});\nexport var LOG2E = /* #__PURE__ */createLOG2E({\n BigNumber,\n config\n});\nexport var version = /* #__PURE__ */createVersion({});\nexport var DenseMatrix = /* #__PURE__ */createDenseMatrixClass({\n Matrix\n});\nexport var phi = /* #__PURE__ */createPhi({\n BigNumber,\n config\n});\nexport var typed = /* #__PURE__ */createTyped({\n BigNumber,\n Complex,\n DenseMatrix,\n Fraction\n});\nexport var isInteger = /* #__PURE__ */createIsInteger({\n typed\n});\nexport var isNumeric = /* #__PURE__ */createIsNumeric({\n typed\n});\nexport var isPositive = /* #__PURE__ */createIsPositive({\n typed\n});\nexport var isNaN = /* #__PURE__ */createIsNaN({\n typed\n});\nexport var equalScalar = /* #__PURE__ */createEqualScalar({\n config,\n typed\n});\nexport var number = /* #__PURE__ */createNumber({\n typed\n});\nexport var boolean = /* #__PURE__ */createBoolean({\n typed\n});\nexport var complex = /* #__PURE__ */createComplex({\n Complex,\n typed\n});\nexport var splitUnit = /* #__PURE__ */createSplitUnit({\n typed\n});\nexport var unaryPlus = /* #__PURE__ */createUnaryPlus({\n BigNumber,\n config,\n typed\n});\nexport var apply = /* #__PURE__ */createApply({\n isInteger,\n typed\n});\nexport var cube = /* #__PURE__ */createCube({\n typed\n});\nexport var expm1 = /* #__PURE__ */createExpm1({\n Complex,\n typed\n});\nexport var log10 = /* #__PURE__ */createLog10({\n Complex,\n config,\n typed\n});\nexport var multiplyScalar = /* #__PURE__ */createMultiplyScalar({\n typed\n});\nexport var sign = /* #__PURE__ */createSign({\n BigNumber,\n Fraction,\n complex,\n typed\n});\nexport var square = /* #__PURE__ */createSquare({\n typed\n});\nexport var bitNot = /* #__PURE__ */createBitNot({\n typed\n});\nexport var arg = /* #__PURE__ */createArg({\n typed\n});\nexport var im = /* #__PURE__ */createIm({\n typed\n});\nexport var not = /* #__PURE__ */createNot({\n typed\n});\nexport var filter = /* #__PURE__ */createFilter({\n typed\n});\nexport var forEach = /* #__PURE__ */createForEach({\n typed\n});\nexport var map = /* #__PURE__ */createMap({\n typed\n});\nexport var erf = /* #__PURE__ */createErf({\n typed\n});\nexport var format = /* #__PURE__ */createFormat({\n typed\n});\nexport var oct = /* #__PURE__ */createOct({\n format,\n typed\n});\nexport var print = /* #__PURE__ */createPrint({\n typed\n});\nexport var isPrime = /* #__PURE__ */createIsPrime({\n typed\n});\nexport var acos = /* #__PURE__ */createAcos({\n Complex,\n config,\n typed\n});\nexport var acot = /* #__PURE__ */createAcot({\n BigNumber,\n typed\n});\nexport var acsc = /* #__PURE__ */createAcsc({\n BigNumber,\n Complex,\n config,\n typed\n});\nexport var asec = /* #__PURE__ */createAsec({\n BigNumber,\n Complex,\n config,\n typed\n});\nexport var asin = /* #__PURE__ */createAsin({\n Complex,\n config,\n typed\n});\nexport var atan = /* #__PURE__ */createAtan({\n typed\n});\nexport var atanh = /* #__PURE__ */createAtanh({\n Complex,\n config,\n typed\n});\nexport var cosh = /* #__PURE__ */createCosh({\n typed\n});\nexport var coth = /* #__PURE__ */createCoth({\n BigNumber,\n typed\n});\nexport var csch = /* #__PURE__ */createCsch({\n BigNumber,\n typed\n});\nexport var sech = /* #__PURE__ */createSech({\n BigNumber,\n typed\n});\nexport var sinh = /* #__PURE__ */createSinh({\n typed\n});\nexport var tanh = /* #__PURE__ */createTanh({\n typed\n});\nexport var combinations = /* #__PURE__ */createCombinations({\n typed\n});\nexport var pickRandom = /* #__PURE__ */createPickRandom({\n config,\n typed\n});\nexport var randomInt = /* #__PURE__ */createRandomInt({\n config,\n typed\n});\nexport var LN2 = /* #__PURE__ */createLN2({\n BigNumber,\n config\n});\nexport var clone = /* #__PURE__ */createClone({\n typed\n});\nexport var hasNumericValue = /* #__PURE__ */createHasNumericValue({\n isNumeric,\n typed\n});\nexport var typeOf = /* #__PURE__ */createTypeOf({\n typed\n});\nexport var string = /* #__PURE__ */createString({\n typed\n});\nexport var fraction = /* #__PURE__ */createFraction({\n Fraction,\n typed\n});\nexport var unaryMinus = /* #__PURE__ */createUnaryMinus({\n typed\n});\nexport var addScalar = /* #__PURE__ */createAddScalar({\n typed\n});\nexport var exp = /* #__PURE__ */createExp({\n typed\n});\nexport var log2 = /* #__PURE__ */createLog2({\n Complex,\n config,\n typed\n});\nexport var sqrt = /* #__PURE__ */createSqrt({\n Complex,\n config,\n typed\n});\nexport var conj = /* #__PURE__ */createConj({\n typed\n});\nexport var getMatrixDataType = /* #__PURE__ */createGetMatrixDataType({\n typed\n});\nexport var mode = /* #__PURE__ */createMode({\n isNaN,\n isNumeric,\n typed\n});\nexport var bin = /* #__PURE__ */createBin({\n format,\n typed\n});\nexport var acosh = /* #__PURE__ */createAcosh({\n Complex,\n config,\n typed\n});\nexport var acsch = /* #__PURE__ */createAcsch({\n BigNumber,\n typed\n});\nexport var asinh = /* #__PURE__ */createAsinh({\n typed\n});\nexport var cos = /* #__PURE__ */createCos({\n typed\n});\nexport var csc = /* #__PURE__ */createCsc({\n BigNumber,\n typed\n});\nexport var sin = /* #__PURE__ */createSin({\n typed\n});\nexport var combinationsWithRep = /* #__PURE__ */createCombinationsWithRep({\n typed\n});\nexport var random = /* #__PURE__ */createRandom({\n config,\n typed\n});\nexport var SQRT2 = /* #__PURE__ */createSQRT2({\n BigNumber,\n config\n});\nexport var isNegative = /* #__PURE__ */createIsNegative({\n typed\n});\nexport var SparseMatrix = /* #__PURE__ */createSparseMatrixClass({\n Matrix,\n equalScalar,\n typed\n});\nexport var matrix = /* #__PURE__ */createMatrix({\n DenseMatrix,\n Matrix,\n SparseMatrix,\n typed\n});\nexport var cbrt = /* #__PURE__ */createCbrt({\n BigNumber,\n Complex,\n Fraction,\n config,\n isNegative,\n matrix,\n typed,\n unaryMinus\n});\nexport var gcd = /* #__PURE__ */createGcd({\n BigNumber,\n DenseMatrix,\n equalScalar,\n matrix,\n typed\n});\nexport var mod = /* #__PURE__ */createMod({\n DenseMatrix,\n equalScalar,\n matrix,\n typed\n});\nexport var nthRoot = /* #__PURE__ */createNthRoot({\n BigNumber,\n equalScalar,\n matrix,\n typed\n});\nexport var xgcd = /* #__PURE__ */createXgcd({\n BigNumber,\n config,\n matrix,\n typed\n});\nexport var bitAnd = /* #__PURE__ */createBitAnd({\n equalScalar,\n matrix,\n typed\n});\nexport var bitXor = /* #__PURE__ */createBitXor({\n DenseMatrix,\n matrix,\n typed\n});\nexport var or = /* #__PURE__ */createOr({\n DenseMatrix,\n equalScalar,\n matrix,\n typed\n});\nexport var concat = /* #__PURE__ */createConcat({\n isInteger,\n matrix,\n typed\n});\nexport var diag = /* #__PURE__ */createDiag({\n DenseMatrix,\n SparseMatrix,\n matrix,\n typed\n});\nexport var identity = /* #__PURE__ */createIdentity({\n BigNumber,\n DenseMatrix,\n SparseMatrix,\n config,\n matrix,\n typed\n});\nexport var ones = /* #__PURE__ */createOnes({\n BigNumber,\n config,\n matrix,\n typed\n});\nexport var reshape = /* #__PURE__ */createReshape({\n isInteger,\n matrix,\n typed\n});\nexport var size = /* #__PURE__ */createSize({\n matrix,\n config,\n typed\n});\nexport var subset = /* #__PURE__ */createSubset({\n matrix,\n typed\n});\nexport var zeros = /* #__PURE__ */createZeros({\n BigNumber,\n config,\n matrix,\n typed\n});\nexport var hex = /* #__PURE__ */createHex({\n format,\n typed\n});\nexport var round = /* #__PURE__ */createRound({\n BigNumber,\n DenseMatrix,\n equalScalar,\n matrix,\n typed,\n zeros\n});\nexport var leftShift = /* #__PURE__ */createLeftShift({\n DenseMatrix,\n equalScalar,\n matrix,\n typed,\n zeros\n});\nexport var rightLogShift = /* #__PURE__ */createRightLogShift({\n DenseMatrix,\n equalScalar,\n matrix,\n typed,\n zeros\n});\nexport var compare = /* #__PURE__ */createCompare({\n BigNumber,\n DenseMatrix,\n Fraction,\n config,\n equalScalar,\n matrix,\n typed\n});\nexport var compareText = /* #__PURE__ */createCompareText({\n matrix,\n typed\n});\nexport var smaller = /* #__PURE__ */createSmaller({\n DenseMatrix,\n config,\n matrix,\n typed\n});\nexport var larger = /* #__PURE__ */createLarger({\n DenseMatrix,\n config,\n matrix,\n typed\n});\nexport var unequal = /* #__PURE__ */createUnequal({\n DenseMatrix,\n config,\n equalScalar,\n matrix,\n typed\n});\nexport var ImmutableDenseMatrix = /* #__PURE__ */createImmutableDenseMatrixClass({\n DenseMatrix,\n smaller\n});\nexport var FibonacciHeap = /* #__PURE__ */createFibonacciHeapClass({\n larger,\n smaller\n});\nexport var sparse = /* #__PURE__ */createSparse({\n SparseMatrix,\n typed\n});\nexport var acoth = /* #__PURE__ */createAcoth({\n BigNumber,\n Complex,\n config,\n typed\n});\nexport var atan2 = /* #__PURE__ */createAtan2({\n BigNumber,\n DenseMatrix,\n equalScalar,\n matrix,\n typed\n});\nexport var sec = /* #__PURE__ */createSec({\n BigNumber,\n typed\n});\nexport var add = /* #__PURE__ */createAdd({\n DenseMatrix,\n SparseMatrix,\n addScalar,\n equalScalar,\n matrix,\n typed\n});\nexport var dot = /* #__PURE__ */createDot({\n addScalar,\n conj,\n multiplyScalar,\n size,\n typed\n});\nexport var composition = /* #__PURE__ */createComposition({\n addScalar,\n combinations,\n isInteger,\n isNegative,\n isPositive,\n larger,\n typed\n});\nexport var isZero = /* #__PURE__ */createIsZero({\n typed\n});\nexport var abs = /* #__PURE__ */createAbs({\n typed\n});\nexport var floor = /* #__PURE__ */createFloor({\n config,\n equalScalar,\n matrix,\n round,\n typed\n});\nexport var multiply = /* #__PURE__ */createMultiply({\n addScalar,\n dot,\n equalScalar,\n matrix,\n multiplyScalar,\n typed\n});\nexport var dotMultiply = /* #__PURE__ */createDotMultiply({\n equalScalar,\n matrix,\n multiplyScalar,\n typed\n});\nexport var re = /* #__PURE__ */createRe({\n typed\n});\nexport var flatten = /* #__PURE__ */createFlatten({\n matrix,\n typed\n});\nexport var resize = /* #__PURE__ */createResize({\n config,\n matrix\n});\nexport var squeeze = /* #__PURE__ */createSqueeze({\n matrix,\n typed\n});\nexport var to = /* #__PURE__ */createTo({\n matrix,\n typed\n});\nexport var pow = /* #__PURE__ */createPow({\n Complex,\n config,\n fraction,\n identity,\n matrix,\n multiply,\n number,\n typed\n});\nexport var dotPow = /* #__PURE__ */createDotPow({\n DenseMatrix,\n equalScalar,\n matrix,\n pow,\n typed\n});\nexport var rightArithShift = /* #__PURE__ */createRightArithShift({\n DenseMatrix,\n equalScalar,\n matrix,\n typed,\n zeros\n});\nexport var compareNatural = /* #__PURE__ */createCompareNatural({\n compare,\n typed\n});\nexport var equalText = /* #__PURE__ */createEqualText({\n compareText,\n isZero,\n typed\n});\nexport var largerEq = /* #__PURE__ */createLargerEq({\n DenseMatrix,\n config,\n matrix,\n typed\n});\nexport var partitionSelect = /* #__PURE__ */createPartitionSelect({\n compare,\n isNaN,\n isNumeric,\n typed\n});\nexport var Index = /* #__PURE__ */createIndexClass({\n ImmutableDenseMatrix\n});\nexport var asech = /* #__PURE__ */createAsech({\n BigNumber,\n Complex,\n config,\n typed\n});\nexport var tan = /* #__PURE__ */createTan({\n typed\n});\nexport var setDifference = /* #__PURE__ */createSetDifference({\n DenseMatrix,\n Index,\n compareNatural,\n size,\n subset,\n typed\n});\nexport var setIntersect = /* #__PURE__ */createSetIntersect({\n DenseMatrix,\n Index,\n compareNatural,\n size,\n subset,\n typed\n});\nexport var setMultiplicity = /* #__PURE__ */createSetMultiplicity({\n Index,\n compareNatural,\n size,\n subset,\n typed\n});\nexport var setSize = /* #__PURE__ */createSetSize({\n compareNatural,\n typed\n});\nexport var trace = /* #__PURE__ */createTrace({\n add,\n matrix,\n typed\n});\nexport var quantileSeq = /* #__PURE__ */createQuantileSeq({\n add,\n compare,\n multiply,\n partitionSelect,\n typed\n});\nexport var gamma = /* #__PURE__ */createGamma({\n BigNumber,\n Complex,\n config,\n multiplyScalar,\n pow,\n typed\n});\nexport var bignumber = /* #__PURE__ */createBignumber({\n BigNumber,\n typed\n});\nexport var lcm = /* #__PURE__ */createLcm({\n equalScalar,\n matrix,\n typed\n});\nexport var bitOr = /* #__PURE__ */createBitOr({\n DenseMatrix,\n equalScalar,\n matrix,\n typed\n});\nexport var kron = /* #__PURE__ */createKron({\n matrix,\n multiplyScalar,\n typed\n});\nexport var transpose = /* #__PURE__ */createTranspose({\n matrix,\n typed\n});\nexport var numeric = /* #__PURE__ */createNumeric({\n bignumber,\n fraction,\n number\n});\nexport var and = /* #__PURE__ */createAnd({\n equalScalar,\n matrix,\n not,\n typed,\n zeros\n});\nexport var smallerEq = /* #__PURE__ */createSmallerEq({\n DenseMatrix,\n config,\n matrix,\n typed\n});\nexport var sort = /* #__PURE__ */createSort({\n compare,\n compareNatural,\n matrix,\n typed\n});\nexport var min = /* #__PURE__ */createMin({\n config,\n numeric,\n smaller,\n typed\n});\nexport var cot = /* #__PURE__ */createCot({\n BigNumber,\n typed\n});\nexport var setDistinct = /* #__PURE__ */createSetDistinct({\n DenseMatrix,\n Index,\n compareNatural,\n size,\n subset,\n typed\n});\nexport var setPowerset = /* #__PURE__ */createSetPowerset({\n Index,\n compareNatural,\n size,\n subset,\n typed\n});\nexport var index = /* #__PURE__ */createIndex({\n Index,\n typed\n});\nexport var sum = /* #__PURE__ */createSum({\n add,\n config,\n numeric,\n typed\n});\nexport var factorial = /* #__PURE__ */createFactorial({\n gamma,\n typed\n});\nexport var permutations = /* #__PURE__ */createPermutations({\n factorial,\n typed\n});\nexport var ceil = /* #__PURE__ */createCeil({\n config,\n equalScalar,\n matrix,\n round,\n typed\n});\nexport var subtract = /* #__PURE__ */createSubtract({\n DenseMatrix,\n addScalar,\n equalScalar,\n matrix,\n typed,\n unaryMinus\n});\nexport var cross = /* #__PURE__ */createCross({\n matrix,\n multiply,\n subtract,\n typed\n});\nexport var range = /* #__PURE__ */createRange({\n bignumber,\n matrix,\n config,\n larger,\n largerEq,\n smaller,\n smallerEq,\n typed\n});\nexport var row = /* #__PURE__ */createRow({\n Index,\n matrix,\n range,\n typed\n});\nexport var prod = /* #__PURE__ */createProd({\n config,\n multiplyScalar,\n numeric,\n typed\n});\nexport var equal = /* #__PURE__ */createEqual({\n DenseMatrix,\n equalScalar,\n matrix,\n typed\n});\nexport var max = /* #__PURE__ */createMax({\n config,\n larger,\n numeric,\n typed\n});\nexport var setCartesian = /* #__PURE__ */createSetCartesian({\n DenseMatrix,\n Index,\n compareNatural,\n size,\n subset,\n typed\n});\nexport var setSymDifference = /* #__PURE__ */createSetSymDifference({\n Index,\n concat,\n setDifference,\n size,\n subset,\n typed\n});\nexport var fix = /* #__PURE__ */createFix({\n Complex,\n ceil,\n floor,\n matrix,\n typed\n});\nexport var column = /* #__PURE__ */createColumn({\n Index,\n matrix,\n range,\n typed\n});\nexport var diff = /* #__PURE__ */createDiff({\n matrix,\n number,\n subtract,\n typed\n});\nexport var ctranspose = /* #__PURE__ */createCtranspose({\n conj,\n transpose,\n typed\n});\nexport var deepEqual = /* #__PURE__ */createDeepEqual({\n equal,\n typed\n});\nexport var setIsSubset = /* #__PURE__ */createSetIsSubset({\n Index,\n compareNatural,\n size,\n subset,\n typed\n});\nexport var xor = /* #__PURE__ */createXor({\n DenseMatrix,\n matrix,\n typed\n});\nexport var divideScalar = /* #__PURE__ */createDivideScalar({\n numeric,\n typed\n});\nexport var nthRoots = /* #__PURE__ */createNthRoots({\n Complex,\n config,\n divideScalar,\n typed\n});\nexport var lsolve = /* #__PURE__ */createLsolve({\n DenseMatrix,\n divideScalar,\n equalScalar,\n matrix,\n multiplyScalar,\n subtract,\n typed\n});\nexport var lsolveAll = /* #__PURE__ */createLsolveAll({\n DenseMatrix,\n divideScalar,\n equalScalar,\n matrix,\n multiplyScalar,\n subtract,\n typed\n});\nexport var Spa = /* #__PURE__ */createSpaClass({\n FibonacciHeap,\n addScalar,\n equalScalar\n});\nexport var setUnion = /* #__PURE__ */createSetUnion({\n Index,\n concat,\n setIntersect,\n setSymDifference,\n size,\n subset,\n typed\n});\nexport var lup = /* #__PURE__ */createLup({\n DenseMatrix,\n Spa,\n SparseMatrix,\n abs,\n addScalar,\n divideScalar,\n equalScalar,\n larger,\n matrix,\n multiplyScalar,\n subtract,\n typed,\n unaryMinus\n});\nexport var slu = /* #__PURE__ */createSlu({\n SparseMatrix,\n abs,\n add,\n divideScalar,\n larger,\n largerEq,\n multiply,\n subtract,\n transpose,\n typed\n});\nexport var det = /* #__PURE__ */createDet({\n lup,\n matrix,\n multiply,\n subtract,\n typed,\n unaryMinus\n});\nexport var distance = /* #__PURE__ */createDistance({\n abs,\n addScalar,\n divideScalar,\n multiplyScalar,\n sqrt,\n subtract,\n typed,\n unaryMinus\n});\nexport var stirlingS2 = /* #__PURE__ */createStirlingS2({\n addScalar,\n combinations,\n divideScalar,\n factorial,\n isInteger,\n isNegative,\n larger,\n multiplyScalar,\n pow,\n subtract,\n typed\n});\nexport var catalan = /* #__PURE__ */createCatalan({\n addScalar,\n combinations,\n divideScalar,\n isInteger,\n isNegative,\n multiplyScalar,\n typed\n});\nexport var count = /* #__PURE__ */createCount({\n prod,\n size,\n typed\n});\nexport var log = /* #__PURE__ */createLog({\n Complex,\n config,\n divideScalar,\n typed\n});\nexport var dotDivide = /* #__PURE__ */createDotDivide({\n DenseMatrix,\n divideScalar,\n equalScalar,\n matrix,\n typed\n});\nexport var usolveAll = /* #__PURE__ */createUsolveAll({\n DenseMatrix,\n divideScalar,\n equalScalar,\n matrix,\n multiplyScalar,\n subtract,\n typed\n});\nexport var hypot = /* #__PURE__ */createHypot({\n abs,\n addScalar,\n divideScalar,\n isPositive,\n multiplyScalar,\n smaller,\n sqrt,\n typed\n});\nexport var qr = /* #__PURE__ */createQr({\n addScalar,\n complex,\n conj,\n divideScalar,\n equal,\n identity,\n isZero,\n matrix,\n multiplyScalar,\n sign,\n sqrt,\n subtract,\n typed,\n unaryMinus,\n zeros\n});\nexport var inv = /* #__PURE__ */createInv({\n abs,\n addScalar,\n det,\n divideScalar,\n identity,\n matrix,\n multiply,\n typed,\n unaryMinus\n});\nexport var expm = /* #__PURE__ */createExpm({\n abs,\n add,\n identity,\n inv,\n multiply,\n typed\n});\nexport var divide = /* #__PURE__ */createDivide({\n divideScalar,\n equalScalar,\n inv,\n matrix,\n multiply,\n typed\n});\nexport var mean = /* #__PURE__ */createMean({\n add,\n divide,\n typed\n});\nexport var variance = /* #__PURE__ */createVariance({\n add,\n apply,\n divide,\n isNaN,\n multiply,\n subtract,\n typed\n});\nexport var kldivergence = /* #__PURE__ */createKldivergence({\n divide,\n dotDivide,\n isNumeric,\n log,\n matrix,\n multiply,\n sum,\n typed\n});\nexport var bellNumbers = /* #__PURE__ */createBellNumbers({\n addScalar,\n isInteger,\n isNegative,\n stirlingS2,\n typed\n});\nexport var log1p = /* #__PURE__ */createLog1p({\n Complex,\n config,\n divideScalar,\n log,\n typed\n});\nexport var Unit = /* #__PURE__ */createUnitClass({\n BigNumber,\n Complex,\n Fraction,\n abs,\n addScalar,\n config,\n divideScalar,\n equal,\n fix,\n format,\n isNumeric,\n multiplyScalar,\n number,\n pow,\n round,\n subtract\n});\nexport var createUnit = /* #__PURE__ */createCreateUnit({\n Unit,\n typed\n});\nexport var eigs = /* #__PURE__ */createEigs({\n abs,\n add,\n addScalar,\n atan,\n bignumber,\n config,\n cos,\n equal,\n inv,\n matrix,\n multiply,\n multiplyScalar,\n sin,\n subtract,\n typed\n});\nexport var intersect = /* #__PURE__ */createIntersect({\n abs,\n add,\n addScalar,\n config,\n divideScalar,\n equalScalar,\n matrix,\n multiply,\n multiplyScalar,\n smaller,\n subtract,\n typed\n});\nexport var std = /* #__PURE__ */createStd({\n sqrt,\n typed,\n variance\n});\nexport var atomicMass = /* #__PURE__ */createAtomicMass({\n BigNumber,\n Unit,\n config\n});\nexport var bohrMagneton = /* #__PURE__ */createBohrMagneton({\n BigNumber,\n Unit,\n config\n});\nexport var boltzmann = /* #__PURE__ */createBoltzmann({\n BigNumber,\n Unit,\n config\n});\nexport var conductanceQuantum = /* #__PURE__ */createConductanceQuantum({\n BigNumber,\n Unit,\n config\n});\nexport var deuteronMass = /* #__PURE__ */createDeuteronMass({\n BigNumber,\n Unit,\n config\n});\nexport var electronMass = /* #__PURE__ */createElectronMass({\n BigNumber,\n Unit,\n config\n});\nexport var faraday = /* #__PURE__ */createFaraday({\n BigNumber,\n Unit,\n config\n});\nexport var firstRadiation = /* #__PURE__ */createFirstRadiation({\n BigNumber,\n Unit,\n config\n});\nexport var gravitationConstant = /* #__PURE__ */createGravitationConstant({\n BigNumber,\n Unit,\n config\n});\nexport var hartreeEnergy = /* #__PURE__ */createHartreeEnergy({\n BigNumber,\n Unit,\n config\n});\nexport var klitzing = /* #__PURE__ */createKlitzing({\n BigNumber,\n Unit,\n config\n});\nexport var magneticConstant = /* #__PURE__ */createMagneticConstant({\n BigNumber,\n Unit,\n config\n});\nexport var molarMass = /* #__PURE__ */createMolarMass({\n BigNumber,\n Unit,\n config\n});\nexport var molarPlanckConstant = /* #__PURE__ */createMolarPlanckConstant({\n BigNumber,\n Unit,\n config\n});\nexport var neutronMass = /* #__PURE__ */createNeutronMass({\n BigNumber,\n Unit,\n config\n});\nexport var planckCharge = /* #__PURE__ */createPlanckCharge({\n BigNumber,\n Unit,\n config\n});\nexport var planckLength = /* #__PURE__ */createPlanckLength({\n BigNumber,\n Unit,\n config\n});\nexport var planckTemperature = /* #__PURE__ */createPlanckTemperature({\n BigNumber,\n Unit,\n config\n});\nexport var protonMass = /* #__PURE__ */createProtonMass({\n BigNumber,\n Unit,\n config\n});\nexport var reducedPlanckConstant = /* #__PURE__ */createReducedPlanckConstant({\n BigNumber,\n Unit,\n config\n});\nexport var secondRadiation = /* #__PURE__ */createSecondRadiation({\n BigNumber,\n Unit,\n config\n});\nexport var stefanBoltzmann = /* #__PURE__ */createStefanBoltzmann({\n BigNumber,\n Unit,\n config\n});\nexport var vacuumImpedance = /* #__PURE__ */createVacuumImpedance({\n BigNumber,\n Unit,\n config\n});\nexport var usolve = /* #__PURE__ */createUsolve({\n DenseMatrix,\n divideScalar,\n equalScalar,\n matrix,\n multiplyScalar,\n subtract,\n typed\n});\nexport var norm = /* #__PURE__ */createNorm({\n abs,\n add,\n conj,\n ctranspose,\n eigs,\n equalScalar,\n larger,\n matrix,\n multiply,\n pow,\n smaller,\n sqrt,\n typed\n});\nexport var lusolve = /* #__PURE__ */createLusolve({\n DenseMatrix,\n lsolve,\n lup,\n matrix,\n slu,\n typed,\n usolve\n});\nexport var sqrtm = /* #__PURE__ */createSqrtm({\n abs,\n add,\n identity,\n inv,\n max,\n multiply,\n size,\n sqrt,\n subtract,\n typed\n});\nexport var multinomial = /* #__PURE__ */createMultinomial({\n add,\n divide,\n factorial,\n isInteger,\n isPositive,\n multiply,\n typed\n});\nexport var avogadro = /* #__PURE__ */createAvogadro({\n BigNumber,\n Unit,\n config\n});\nexport var classicalElectronRadius = /* #__PURE__ */createClassicalElectronRadius({\n BigNumber,\n Unit,\n config\n});\nexport var electricConstant = /* #__PURE__ */createElectricConstant({\n BigNumber,\n Unit,\n config\n});\nexport var fermiCoupling = /* #__PURE__ */createFermiCoupling({\n BigNumber,\n Unit,\n config\n});\nexport var gravity = /* #__PURE__ */createGravity({\n BigNumber,\n Unit,\n config\n});\nexport var loschmidt = /* #__PURE__ */createLoschmidt({\n BigNumber,\n Unit,\n config\n});\nexport var molarMassC12 = /* #__PURE__ */createMolarMassC12({\n BigNumber,\n Unit,\n config\n});\nexport var nuclearMagneton = /* #__PURE__ */createNuclearMagneton({\n BigNumber,\n Unit,\n config\n});\nexport var planckMass = /* #__PURE__ */createPlanckMass({\n BigNumber,\n Unit,\n config\n});\nexport var quantumOfCirculation = /* #__PURE__ */createQuantumOfCirculation({\n BigNumber,\n Unit,\n config\n});\nexport var speedOfLight = /* #__PURE__ */createSpeedOfLight({\n BigNumber,\n Unit,\n config\n});\nexport var wienDisplacement = /* #__PURE__ */createWienDisplacement({\n BigNumber,\n Unit,\n config\n});\nexport var rotationMatrix = /* #__PURE__ */createRotationMatrix({\n BigNumber,\n DenseMatrix,\n SparseMatrix,\n addScalar,\n config,\n cos,\n matrix,\n multiplyScalar,\n norm,\n sin,\n typed,\n unaryMinus\n});\nexport var median = /* #__PURE__ */createMedian({\n add,\n compare,\n divide,\n partitionSelect,\n typed\n});\nexport var bohrRadius = /* #__PURE__ */createBohrRadius({\n BigNumber,\n Unit,\n config\n});\nexport var elementaryCharge = /* #__PURE__ */createElementaryCharge({\n BigNumber,\n Unit,\n config\n});\nexport var inverseConductanceQuantum = /* #__PURE__ */createInverseConductanceQuantum({\n BigNumber,\n Unit,\n config\n});\nexport var molarVolume = /* #__PURE__ */createMolarVolume({\n BigNumber,\n Unit,\n config\n});\nexport var planckTime = /* #__PURE__ */createPlanckTime({\n BigNumber,\n Unit,\n config\n});\nexport var thomsonCrossSection = /* #__PURE__ */createThomsonCrossSection({\n BigNumber,\n Unit,\n config\n});\nexport var rotate = /* #__PURE__ */createRotate({\n multiply,\n rotationMatrix,\n typed\n});\nexport var mad = /* #__PURE__ */createMad({\n abs,\n map,\n median,\n subtract,\n typed\n});\nexport var coulomb = /* #__PURE__ */createCoulomb({\n BigNumber,\n Unit,\n config\n});\nexport var magneticFluxQuantum = /* #__PURE__ */createMagneticFluxQuantum({\n BigNumber,\n Unit,\n config\n});\nexport var rydberg = /* #__PURE__ */createRydberg({\n BigNumber,\n Unit,\n config\n});\nexport var unit = /* #__PURE__ */createUnitFunction({\n Unit,\n typed\n});\nexport var gasConstant = /* #__PURE__ */createGasConstant({\n BigNumber,\n Unit,\n config\n});\nexport var planckConstant = /* #__PURE__ */createPlanckConstant({\n BigNumber,\n Unit,\n config\n});","import _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport getScrollbarSize from '../utils/getScrollbarSize';\nimport ownerDocument from '../utils/ownerDocument';\nimport ownerWindow from '../utils/ownerWindow'; // Is a vertical scrollbar displayed?\n\nfunction isOverflowing(container) {\n var doc = ownerDocument(container);\n\n if (doc.body === container) {\n return ownerWindow(doc).innerWidth > doc.documentElement.clientWidth;\n }\n\n return container.scrollHeight > container.clientHeight;\n}\n\nexport function ariaHidden(node, show) {\n if (show) {\n node.setAttribute('aria-hidden', 'true');\n } else {\n node.removeAttribute('aria-hidden');\n }\n}\n\nfunction getPaddingRight(node) {\n return parseInt(window.getComputedStyle(node)['padding-right'], 10) || 0;\n}\n\nfunction ariaHiddenSiblings(container, mountNode, currentNode) {\n var nodesToExclude = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];\n var show = arguments.length > 4 ? arguments[4] : undefined;\n var blacklist = [mountNode, currentNode].concat(_toConsumableArray(nodesToExclude));\n var blacklistTagNames = ['TEMPLATE', 'SCRIPT', 'STYLE'];\n [].forEach.call(container.children, function (node) {\n if (node.nodeType === 1 && blacklist.indexOf(node) === -1 && blacklistTagNames.indexOf(node.tagName) === -1) {\n ariaHidden(node, show);\n }\n });\n}\n\nfunction findIndexOf(containerInfo, callback) {\n var idx = -1;\n containerInfo.some(function (item, index) {\n if (callback(item)) {\n idx = index;\n return true;\n }\n\n return false;\n });\n return idx;\n}\n\nfunction handleContainer(containerInfo, props) {\n var restoreStyle = [];\n var restorePaddings = [];\n var container = containerInfo.container;\n var fixedNodes;\n\n if (!props.disableScrollLock) {\n if (isOverflowing(container)) {\n // Compute the size before applying overflow hidden to avoid any scroll jumps.\n var scrollbarSize = getScrollbarSize();\n restoreStyle.push({\n value: container.style.paddingRight,\n key: 'padding-right',\n el: container\n }); // Use computed style, here to get the real padding to add our scrollbar width.\n\n container.style['padding-right'] = \"\".concat(getPaddingRight(container) + scrollbarSize, \"px\"); // .mui-fixed is a global helper.\n\n fixedNodes = ownerDocument(container).querySelectorAll('.mui-fixed');\n [].forEach.call(fixedNodes, function (node) {\n restorePaddings.push(node.style.paddingRight);\n node.style.paddingRight = \"\".concat(getPaddingRight(node) + scrollbarSize, \"px\");\n });\n } // Improve Gatsby support\n // https://css-tricks.com/snippets/css/force-vertical-scrollbar/\n\n\n var parent = container.parentElement;\n var scrollContainer = parent.nodeName === 'HTML' && window.getComputedStyle(parent)['overflow-y'] === 'scroll' ? parent : container; // Block the scroll even if no scrollbar is visible to account for mobile keyboard\n // screensize shrink.\n\n restoreStyle.push({\n value: scrollContainer.style.overflow,\n key: 'overflow',\n el: scrollContainer\n });\n scrollContainer.style.overflow = 'hidden';\n }\n\n var restore = function restore() {\n if (fixedNodes) {\n [].forEach.call(fixedNodes, function (node, i) {\n if (restorePaddings[i]) {\n node.style.paddingRight = restorePaddings[i];\n } else {\n node.style.removeProperty('padding-right');\n }\n });\n }\n\n restoreStyle.forEach(function (_ref) {\n var value = _ref.value,\n el = _ref.el,\n key = _ref.key;\n\n if (value) {\n el.style.setProperty(key, value);\n } else {\n el.style.removeProperty(key);\n }\n });\n };\n\n return restore;\n}\n\nfunction getHiddenSiblings(container) {\n var hiddenSiblings = [];\n [].forEach.call(container.children, function (node) {\n if (node.getAttribute && node.getAttribute('aria-hidden') === 'true') {\n hiddenSiblings.push(node);\n }\n });\n return hiddenSiblings;\n}\n/**\n * @ignore - do not document.\n *\n * Proper state management for containers and the modals in those containers.\n * Simplified, but inspired by react-overlay's ModalManager class.\n * Used by the Modal to ensure proper styling of containers.\n */\n\n\nvar ModalManager = /*#__PURE__*/function () {\n function ModalManager() {\n _classCallCheck(this, ModalManager);\n\n // this.modals[modalIndex] = modal\n this.modals = []; // this.containers[containerIndex] = {\n // modals: [],\n // container,\n // restore: null,\n // }\n\n this.containers = [];\n }\n\n _createClass(ModalManager, [{\n key: \"add\",\n value: function add(modal, container) {\n var modalIndex = this.modals.indexOf(modal);\n\n if (modalIndex !== -1) {\n return modalIndex;\n }\n\n modalIndex = this.modals.length;\n this.modals.push(modal); // If the modal we are adding is already in the DOM.\n\n if (modal.modalRef) {\n ariaHidden(modal.modalRef, false);\n }\n\n var hiddenSiblingNodes = getHiddenSiblings(container);\n ariaHiddenSiblings(container, modal.mountNode, modal.modalRef, hiddenSiblingNodes, true);\n var containerIndex = findIndexOf(this.containers, function (item) {\n return item.container === container;\n });\n\n if (containerIndex !== -1) {\n this.containers[containerIndex].modals.push(modal);\n return modalIndex;\n }\n\n this.containers.push({\n modals: [modal],\n container: container,\n restore: null,\n hiddenSiblingNodes: hiddenSiblingNodes\n });\n return modalIndex;\n }\n }, {\n key: \"mount\",\n value: function mount(modal, props) {\n var containerIndex = findIndexOf(this.containers, function (item) {\n return item.modals.indexOf(modal) !== -1;\n });\n var containerInfo = this.containers[containerIndex];\n\n if (!containerInfo.restore) {\n containerInfo.restore = handleContainer(containerInfo, props);\n }\n }\n }, {\n key: \"remove\",\n value: function remove(modal) {\n var modalIndex = this.modals.indexOf(modal);\n\n if (modalIndex === -1) {\n return modalIndex;\n }\n\n var containerIndex = findIndexOf(this.containers, function (item) {\n return item.modals.indexOf(modal) !== -1;\n });\n var containerInfo = this.containers[containerIndex];\n containerInfo.modals.splice(containerInfo.modals.indexOf(modal), 1);\n this.modals.splice(modalIndex, 1); // If that was the last modal in a container, clean up the container.\n\n if (containerInfo.modals.length === 0) {\n // The modal might be closed before it had the chance to be mounted in the DOM.\n if (containerInfo.restore) {\n containerInfo.restore();\n }\n\n if (modal.modalRef) {\n // In case the modal wasn't in the DOM yet.\n ariaHidden(modal.modalRef, true);\n }\n\n ariaHiddenSiblings(containerInfo.container, modal.mountNode, modal.modalRef, containerInfo.hiddenSiblingNodes, false);\n this.containers.splice(containerIndex, 1);\n } else {\n // Otherwise make sure the next top modal is visible to a screen reader.\n var nextTop = containerInfo.modals[containerInfo.modals.length - 1]; // as soon as a modal is adding its modalRef is undefined. it can't set\n // aria-hidden because the dom element doesn't exist either\n // when modal was unmounted before modalRef gets null\n\n if (nextTop.modalRef) {\n ariaHidden(nextTop.modalRef, false);\n }\n }\n\n return modalIndex;\n }\n }, {\n key: \"isTopModal\",\n value: function isTopModal(modal) {\n return this.modals.length > 0 && this.modals[this.modals.length - 1] === modal;\n }\n }]);\n\n return ModalManager;\n}();\n\nexport { ModalManager as default };","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}","/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex, camelcase */\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport PropTypes from 'prop-types';\nimport ownerDocument from '../utils/ownerDocument';\nimport useForkRef from '../utils/useForkRef';\nimport { exactProp } from '@material-ui/utils';\n/**\n * Utility component that locks focus inside the component.\n */\n\nfunction Unstable_TrapFocus(props) {\n var children = props.children,\n _props$disableAutoFoc = props.disableAutoFocus,\n disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,\n _props$disableEnforce = props.disableEnforceFocus,\n disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce,\n _props$disableRestore = props.disableRestoreFocus,\n disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore,\n getDoc = props.getDoc,\n isEnabled = props.isEnabled,\n open = props.open;\n var ignoreNextEnforceFocus = React.useRef();\n var sentinelStart = React.useRef(null);\n var sentinelEnd = React.useRef(null);\n var nodeToRestore = React.useRef();\n var rootRef = React.useRef(null); // can be removed once we drop support for non ref forwarding class components\n\n var handleOwnRef = React.useCallback(function (instance) {\n // #StrictMode ready\n rootRef.current = ReactDOM.findDOMNode(instance);\n }, []);\n var handleRef = useForkRef(children.ref, handleOwnRef);\n var prevOpenRef = React.useRef();\n React.useEffect(function () {\n prevOpenRef.current = open;\n }, [open]);\n\n if (!prevOpenRef.current && open && typeof window !== 'undefined') {\n // WARNING: Potentially unsafe in concurrent mode.\n // The way the read on `nodeToRestore` is setup could make this actually safe.\n // Say we render `open={false}` -> `open={true}` but never commit.\n // We have now written a state that wasn't committed. But no committed effect\n // will read this wrong value. We only read from `nodeToRestore` in effects\n // that were committed on `open={true}`\n // WARNING: Prevents the instance from being garbage collected. Should only\n // hold a weak ref.\n nodeToRestore.current = getDoc().activeElement;\n }\n\n React.useEffect(function () {\n if (!open) {\n return;\n }\n\n var doc = ownerDocument(rootRef.current); // We might render an empty child.\n\n if (!disableAutoFocus && rootRef.current && !rootRef.current.contains(doc.activeElement)) {\n if (!rootRef.current.hasAttribute('tabIndex')) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(['Material-UI: The modal content node does not accept focus.', 'For the benefit of assistive technologies, ' + 'the tabIndex of the node is being set to \"-1\".'].join('\\n'));\n }\n\n rootRef.current.setAttribute('tabIndex', -1);\n }\n\n rootRef.current.focus();\n }\n\n var contain = function contain() {\n var rootElement = rootRef.current; // Cleanup functions are executed lazily in React 17.\n // Contain can be called between the component being unmounted and its cleanup function being run.\n\n if (rootElement === null) {\n return;\n }\n\n if (!doc.hasFocus() || disableEnforceFocus || !isEnabled() || ignoreNextEnforceFocus.current) {\n ignoreNextEnforceFocus.current = false;\n return;\n }\n\n if (rootRef.current && !rootRef.current.contains(doc.activeElement)) {\n rootRef.current.focus();\n }\n };\n\n var loopFocus = function loopFocus(event) {\n // 9 = Tab\n if (disableEnforceFocus || !isEnabled() || event.keyCode !== 9) {\n return;\n } // Make sure the next tab starts from the right place.\n\n\n if (doc.activeElement === rootRef.current) {\n // We need to ignore the next contain as\n // it will try to move the focus back to the rootRef element.\n ignoreNextEnforceFocus.current = true;\n\n if (event.shiftKey) {\n sentinelEnd.current.focus();\n } else {\n sentinelStart.current.focus();\n }\n }\n };\n\n doc.addEventListener('focus', contain, true);\n doc.addEventListener('keydown', loopFocus, true); // With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area\n // e.g. https://bugzilla.mozilla.org/show_bug.cgi?id=559561.\n //\n // The whatwg spec defines how the browser should behave but does not explicitly mention any events:\n // https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule.\n\n var interval = setInterval(function () {\n contain();\n }, 50);\n return function () {\n clearInterval(interval);\n doc.removeEventListener('focus', contain, true);\n doc.removeEventListener('keydown', loopFocus, true); // restoreLastFocus()\n\n if (!disableRestoreFocus) {\n // In IE 11 it is possible for document.activeElement to be null resulting\n // in nodeToRestore.current being null.\n // Not all elements in IE 11 have a focus method.\n // Once IE 11 support is dropped the focus() call can be unconditional.\n if (nodeToRestore.current && nodeToRestore.current.focus) {\n nodeToRestore.current.focus();\n }\n\n nodeToRestore.current = null;\n }\n };\n }, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open]);\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"div\", {\n tabIndex: 0,\n ref: sentinelStart,\n \"data-test\": \"sentinelStart\"\n }), /*#__PURE__*/React.cloneElement(children, {\n ref: handleRef\n }), /*#__PURE__*/React.createElement(\"div\", {\n tabIndex: 0,\n ref: sentinelEnd,\n \"data-test\": \"sentinelEnd\"\n }));\n}\n\nprocess.env.NODE_ENV !== \"production\" ? Unstable_TrapFocus.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A single child content element.\n */\n children: PropTypes.node,\n\n /**\n * If `true`, the trap focus will not automatically shift focus to itself when it opens, and\n * replace it to the last focused element when it closes.\n * This also works correctly with any trap focus children that have the `disableAutoFocus` prop.\n *\n * Generally this should never be set to `true` as it makes the trap focus less\n * accessible to assistive technologies, like screen readers.\n */\n disableAutoFocus: PropTypes.bool,\n\n /**\n * If `true`, the trap focus will not prevent focus from leaving the trap focus while open.\n *\n * Generally this should never be set to `true` as it makes the trap focus less\n * accessible to assistive technologies, like screen readers.\n */\n disableEnforceFocus: PropTypes.bool,\n\n /**\n * If `true`, the trap focus will not restore focus to previously focused element once\n * trap focus is hidden.\n */\n disableRestoreFocus: PropTypes.bool,\n\n /**\n * Return the document to consider.\n * We use it to implement the restore focus between different browser documents.\n */\n getDoc: PropTypes.func.isRequired,\n\n /**\n * Do we still want to enforce the focus?\n * This prop helps nesting TrapFocus elements.\n */\n isEnabled: PropTypes.func.isRequired,\n\n /**\n * If `true`, focus will be locked.\n */\n open: PropTypes.bool.isRequired\n} : void 0;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line\n Unstable_TrapFocus['propTypes' + ''] = exactProp(Unstable_TrapFocus.propTypes);\n}\n\nexport default Unstable_TrapFocus;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n zIndex: -1,\n position: 'fixed',\n right: 0,\n bottom: 0,\n top: 0,\n left: 0,\n backgroundColor: 'rgba(0, 0, 0, 0.5)',\n WebkitTapHighlightColor: 'transparent'\n },\n\n /* Styles applied to the root element if `invisible={true}`. */\n invisible: {\n backgroundColor: 'transparent'\n }\n};\n/**\n * @ignore - internal component.\n */\n\nvar SimpleBackdrop = /*#__PURE__*/React.forwardRef(function SimpleBackdrop(props, ref) {\n var _props$invisible = props.invisible,\n invisible = _props$invisible === void 0 ? false : _props$invisible,\n open = props.open,\n other = _objectWithoutProperties(props, [\"invisible\", \"open\"]);\n\n return open ? /*#__PURE__*/React.createElement(\"div\", _extends({\n \"aria-hidden\": true,\n ref: ref\n }, other, {\n style: _extends({}, styles.root, invisible ? styles.invisible : {}, other.style)\n })) : null;\n});\nprocess.env.NODE_ENV !== \"production\" ? SimpleBackdrop.propTypes = {\n /**\n * If `true`, the backdrop is invisible.\n * It can be used when rendering a popover or a custom select component.\n */\n invisible: PropTypes.bool,\n\n /**\n * If `true`, the backdrop is open.\n */\n open: PropTypes.bool.isRequired\n} : void 0;\nexport default SimpleBackdrop;","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport PropTypes from 'prop-types';\nimport { getThemeProps, useTheme } from '@material-ui/styles';\nimport { elementAcceptingRef, HTMLElementType } from '@material-ui/utils';\nimport deprecatedPropType from '../utils/deprecatedPropType';\nimport ownerDocument from '../utils/ownerDocument';\nimport Portal from '../Portal';\nimport createChainedFunction from '../utils/createChainedFunction';\nimport useForkRef from '../utils/useForkRef';\nimport useEventCallback from '../utils/useEventCallback';\nimport zIndex from '../styles/zIndex';\nimport ModalManager, { ariaHidden } from './ModalManager';\nimport TrapFocus from '../Unstable_TrapFocus';\nimport SimpleBackdrop from './SimpleBackdrop';\n\nfunction getContainer(container) {\n container = typeof container === 'function' ? container() : container;\n return ReactDOM.findDOMNode(container);\n}\n\nfunction getHasTransition(props) {\n return props.children ? props.children.props.hasOwnProperty('in') : false;\n} // A modal manager used to track and manage the state of open Modals.\n// Modals don't open on the server so this won't conflict with concurrent requests.\n\n\nvar defaultManager = new ModalManager();\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n position: 'fixed',\n zIndex: theme.zIndex.modal,\n right: 0,\n bottom: 0,\n top: 0,\n left: 0\n },\n\n /* Styles applied to the root element if the `Modal` has exited. */\n hidden: {\n visibility: 'hidden'\n }\n };\n};\n/**\n * Modal is a lower-level construct that is leveraged by the following components:\n *\n * - [Dialog](/api/dialog/)\n * - [Drawer](/api/drawer/)\n * - [Menu](/api/menu/)\n * - [Popover](/api/popover/)\n *\n * If you are creating a modal dialog, you probably want to use the [Dialog](/api/dialog/) component\n * rather than directly using Modal.\n *\n * This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).\n */\n\nvar Modal = /*#__PURE__*/React.forwardRef(function Modal(inProps, ref) {\n var theme = useTheme();\n var props = getThemeProps({\n name: 'MuiModal',\n props: _extends({}, inProps),\n theme: theme\n });\n\n var _props$BackdropCompon = props.BackdropComponent,\n BackdropComponent = _props$BackdropCompon === void 0 ? SimpleBackdrop : _props$BackdropCompon,\n BackdropProps = props.BackdropProps,\n children = props.children,\n _props$closeAfterTran = props.closeAfterTransition,\n closeAfterTransition = _props$closeAfterTran === void 0 ? false : _props$closeAfterTran,\n container = props.container,\n _props$disableAutoFoc = props.disableAutoFocus,\n disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,\n _props$disableBackdro = props.disableBackdropClick,\n disableBackdropClick = _props$disableBackdro === void 0 ? false : _props$disableBackdro,\n _props$disableEnforce = props.disableEnforceFocus,\n disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce,\n _props$disableEscapeK = props.disableEscapeKeyDown,\n disableEscapeKeyDown = _props$disableEscapeK === void 0 ? false : _props$disableEscapeK,\n _props$disablePortal = props.disablePortal,\n disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal,\n _props$disableRestore = props.disableRestoreFocus,\n disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore,\n _props$disableScrollL = props.disableScrollLock,\n disableScrollLock = _props$disableScrollL === void 0 ? false : _props$disableScrollL,\n _props$hideBackdrop = props.hideBackdrop,\n hideBackdrop = _props$hideBackdrop === void 0 ? false : _props$hideBackdrop,\n _props$keepMounted = props.keepMounted,\n keepMounted = _props$keepMounted === void 0 ? false : _props$keepMounted,\n _props$manager = props.manager,\n manager = _props$manager === void 0 ? defaultManager : _props$manager,\n onBackdropClick = props.onBackdropClick,\n onClose = props.onClose,\n onEscapeKeyDown = props.onEscapeKeyDown,\n onRendered = props.onRendered,\n open = props.open,\n other = _objectWithoutProperties(props, [\"BackdropComponent\", \"BackdropProps\", \"children\", \"closeAfterTransition\", \"container\", \"disableAutoFocus\", \"disableBackdropClick\", \"disableEnforceFocus\", \"disableEscapeKeyDown\", \"disablePortal\", \"disableRestoreFocus\", \"disableScrollLock\", \"hideBackdrop\", \"keepMounted\", \"manager\", \"onBackdropClick\", \"onClose\", \"onEscapeKeyDown\", \"onRendered\", \"open\"]);\n\n var _React$useState = React.useState(true),\n exited = _React$useState[0],\n setExited = _React$useState[1];\n\n var modal = React.useRef({});\n var mountNodeRef = React.useRef(null);\n var modalRef = React.useRef(null);\n var handleRef = useForkRef(modalRef, ref);\n var hasTransition = getHasTransition(props);\n\n var getDoc = function getDoc() {\n return ownerDocument(mountNodeRef.current);\n };\n\n var getModal = function getModal() {\n modal.current.modalRef = modalRef.current;\n modal.current.mountNode = mountNodeRef.current;\n return modal.current;\n };\n\n var handleMounted = function handleMounted() {\n manager.mount(getModal(), {\n disableScrollLock: disableScrollLock\n }); // Fix a bug on Chrome where the scroll isn't initially 0.\n\n modalRef.current.scrollTop = 0;\n };\n\n var handleOpen = useEventCallback(function () {\n var resolvedContainer = getContainer(container) || getDoc().body;\n manager.add(getModal(), resolvedContainer); // The element was already mounted.\n\n if (modalRef.current) {\n handleMounted();\n }\n });\n var isTopModal = React.useCallback(function () {\n return manager.isTopModal(getModal());\n }, [manager]);\n var handlePortalRef = useEventCallback(function (node) {\n mountNodeRef.current = node;\n\n if (!node) {\n return;\n }\n\n if (onRendered) {\n onRendered();\n }\n\n if (open && isTopModal()) {\n handleMounted();\n } else {\n ariaHidden(modalRef.current, true);\n }\n });\n var handleClose = React.useCallback(function () {\n manager.remove(getModal());\n }, [manager]);\n React.useEffect(function () {\n return function () {\n handleClose();\n };\n }, [handleClose]);\n React.useEffect(function () {\n if (open) {\n handleOpen();\n } else if (!hasTransition || !closeAfterTransition) {\n handleClose();\n }\n }, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);\n\n if (!keepMounted && !open && (!hasTransition || exited)) {\n return null;\n }\n\n var handleEnter = function handleEnter() {\n setExited(false);\n };\n\n var handleExited = function handleExited() {\n setExited(true);\n\n if (closeAfterTransition) {\n handleClose();\n }\n };\n\n var handleBackdropClick = function handleBackdropClick(event) {\n if (event.target !== event.currentTarget) {\n return;\n }\n\n if (onBackdropClick) {\n onBackdropClick(event);\n }\n\n if (!disableBackdropClick && onClose) {\n onClose(event, 'backdropClick');\n }\n };\n\n var handleKeyDown = function handleKeyDown(event) {\n // The handler doesn't take event.defaultPrevented into account:\n //\n // event.preventDefault() is meant to stop default behaviours like\n // clicking a checkbox to check it, hitting a button to submit a form,\n // and hitting left arrow to move the cursor in a text input etc.\n // Only special HTML elements have these default behaviors.\n if (event.key !== 'Escape' || !isTopModal()) {\n return;\n }\n\n if (onEscapeKeyDown) {\n onEscapeKeyDown(event);\n }\n\n if (!disableEscapeKeyDown) {\n // Swallow the event, in case someone is listening for the escape key on the body.\n event.stopPropagation();\n\n if (onClose) {\n onClose(event, 'escapeKeyDown');\n }\n }\n };\n\n var inlineStyle = styles(theme || {\n zIndex: zIndex\n });\n var childProps = {};\n\n if (children.props.tabIndex === undefined) {\n childProps.tabIndex = children.props.tabIndex || '-1';\n } // It's a Transition like component\n\n\n if (hasTransition) {\n childProps.onEnter = createChainedFunction(handleEnter, children.props.onEnter);\n childProps.onExited = createChainedFunction(handleExited, children.props.onExited);\n }\n\n return /*#__PURE__*/React.createElement(Portal, {\n ref: handlePortalRef,\n container: container,\n disablePortal: disablePortal\n }, /*#__PURE__*/React.createElement(\"div\", _extends({\n ref: handleRef,\n onKeyDown: handleKeyDown,\n role: \"presentation\"\n }, other, {\n style: _extends({}, inlineStyle.root, !open && exited ? inlineStyle.hidden : {}, other.style)\n }), hideBackdrop ? null : /*#__PURE__*/React.createElement(BackdropComponent, _extends({\n open: open,\n onClick: handleBackdropClick\n }, BackdropProps)), /*#__PURE__*/React.createElement(TrapFocus, {\n disableEnforceFocus: disableEnforceFocus,\n disableAutoFocus: disableAutoFocus,\n disableRestoreFocus: disableRestoreFocus,\n getDoc: getDoc,\n isEnabled: isTopModal,\n open: open\n }, /*#__PURE__*/React.cloneElement(children, childProps))));\n});\nprocess.env.NODE_ENV !== \"production\" ? Modal.propTypes = {\n /**\n * A backdrop component. This prop enables custom backdrop rendering.\n */\n BackdropComponent: PropTypes.elementType,\n\n /**\n * Props applied to the [`Backdrop`](/api/backdrop/) element.\n */\n BackdropProps: PropTypes.object,\n\n /**\n * A single child content element.\n */\n children: elementAcceptingRef.isRequired,\n\n /**\n * When set to true the Modal waits until a nested Transition is completed before closing.\n */\n closeAfterTransition: PropTypes.bool,\n\n /**\n * A HTML element, component instance, or function that returns either.\n * The `container` will have the portal children appended to it.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes\n /* @typescript-to-proptypes-ignore */\n .oneOfType([HTMLElementType, PropTypes.instanceOf(React.Component), PropTypes.func]),\n\n /**\n * If `true`, the modal will not automatically shift focus to itself when it opens, and\n * replace it to the last focused element when it closes.\n * This also works correctly with any modal children that have the `disableAutoFocus` prop.\n *\n * Generally this should never be set to `true` as it makes the modal less\n * accessible to assistive technologies, like screen readers.\n */\n disableAutoFocus: PropTypes.bool,\n\n /**\n * If `true`, clicking the backdrop will not fire `onClose`.\n */\n disableBackdropClick: deprecatedPropType(PropTypes.bool, 'Use the onClose prop with the `reason` argument to filter the `backdropClick` events.'),\n\n /**\n * If `true`, the modal will not prevent focus from leaving the modal while open.\n *\n * Generally this should never be set to `true` as it makes the modal less\n * accessible to assistive technologies, like screen readers.\n */\n disableEnforceFocus: PropTypes.bool,\n\n /**\n * If `true`, hitting escape will not fire `onClose`.\n */\n disableEscapeKeyDown: PropTypes.bool,\n\n /**\n * Disable the portal behavior.\n * The children stay within it's parent DOM hierarchy.\n */\n disablePortal: PropTypes.bool,\n\n /**\n * If `true`, the modal will not restore focus to previously focused element once\n * modal is hidden.\n */\n disableRestoreFocus: PropTypes.bool,\n\n /**\n * Disable the scroll lock behavior.\n */\n disableScrollLock: PropTypes.bool,\n\n /**\n * If `true`, the backdrop is not rendered.\n */\n hideBackdrop: PropTypes.bool,\n\n /**\n * Always keep the children in the DOM.\n * This prop can be useful in SEO situation or\n * when you want to maximize the responsiveness of the Modal.\n */\n keepMounted: PropTypes.bool,\n\n /**\n * @ignore\n */\n manager: PropTypes.object,\n\n /**\n * Callback fired when the backdrop is clicked.\n */\n onBackdropClick: deprecatedPropType(PropTypes.func, 'Use the onClose prop with the `reason` argument to handle the `backdropClick` events.'),\n\n /**\n * Callback fired when the component requests to be closed.\n * The `reason` parameter can optionally be used to control the response to `onClose`.\n *\n * @param {object} event The event source of the callback.\n * @param {string} reason Can be: `\"escapeKeyDown\"`, `\"backdropClick\"`.\n */\n onClose: PropTypes.func,\n\n /**\n * Callback fired when the escape key is pressed,\n * `disableEscapeKeyDown` is false and the modal is in focus.\n */\n onEscapeKeyDown: deprecatedPropType(PropTypes.func, 'Use the onClose prop with the `reason` argument to handle the `escapeKeyDown` events.'),\n\n /**\n * Callback fired once the children has been mounted into the `container`.\n * It signals that the `open={true}` prop took effect.\n *\n * This prop will be removed in v5, the ref can be used instead.\n */\n onRendered: deprecatedPropType(PropTypes.func, 'Use the ref instead.'),\n\n /**\n * If `true`, the modal is open.\n */\n open: PropTypes.bool.isRequired\n} : void 0;\nexport default Modal;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { Transition } from 'react-transition-group';\nimport useTheme from '../styles/useTheme';\nimport { reflow, getTransitionProps } from '../transitions/utils';\nimport useForkRef from '../utils/useForkRef';\n\nfunction getScale(value) {\n return \"scale(\".concat(value, \", \").concat(Math.pow(value, 2), \")\");\n}\n\nvar styles = {\n entering: {\n opacity: 1,\n transform: getScale(1)\n },\n entered: {\n opacity: 1,\n transform: 'none'\n }\n};\n/**\n * The Grow transition is used by the [Tooltip](/components/tooltips/) and\n * [Popover](/components/popover/) components.\n * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.\n */\n\nvar Grow = /*#__PURE__*/React.forwardRef(function Grow(props, ref) {\n var children = props.children,\n _props$disableStrictM = props.disableStrictModeCompat,\n disableStrictModeCompat = _props$disableStrictM === void 0 ? false : _props$disableStrictM,\n inProp = props.in,\n onEnter = props.onEnter,\n onEntered = props.onEntered,\n onEntering = props.onEntering,\n onExit = props.onExit,\n onExited = props.onExited,\n onExiting = props.onExiting,\n style = props.style,\n _props$timeout = props.timeout,\n timeout = _props$timeout === void 0 ? 'auto' : _props$timeout,\n _props$TransitionComp = props.TransitionComponent,\n TransitionComponent = _props$TransitionComp === void 0 ? Transition : _props$TransitionComp,\n other = _objectWithoutProperties(props, [\"children\", \"disableStrictModeCompat\", \"in\", \"onEnter\", \"onEntered\", \"onEntering\", \"onExit\", \"onExited\", \"onExiting\", \"style\", \"timeout\", \"TransitionComponent\"]);\n\n var timer = React.useRef();\n var autoTimeout = React.useRef();\n var theme = useTheme();\n var enableStrictModeCompat = theme.unstable_strictMode && !disableStrictModeCompat;\n var nodeRef = React.useRef(null);\n var foreignRef = useForkRef(children.ref, ref);\n var handleRef = useForkRef(enableStrictModeCompat ? nodeRef : undefined, foreignRef);\n\n var normalizedTransitionCallback = function normalizedTransitionCallback(callback) {\n return function (nodeOrAppearing, maybeAppearing) {\n if (callback) {\n var _ref = enableStrictModeCompat ? [nodeRef.current, nodeOrAppearing] : [nodeOrAppearing, maybeAppearing],\n _ref2 = _slicedToArray(_ref, 2),\n node = _ref2[0],\n isAppearing = _ref2[1]; // onEnterXxx and onExitXxx callbacks have a different arguments.length value.\n\n\n if (isAppearing === undefined) {\n callback(node);\n } else {\n callback(node, isAppearing);\n }\n }\n };\n };\n\n var handleEntering = normalizedTransitionCallback(onEntering);\n var handleEnter = normalizedTransitionCallback(function (node, isAppearing) {\n reflow(node); // So the animation always start from the start.\n\n var _getTransitionProps = getTransitionProps({\n style: style,\n timeout: timeout\n }, {\n mode: 'enter'\n }),\n transitionDuration = _getTransitionProps.duration,\n delay = _getTransitionProps.delay;\n\n var duration;\n\n if (timeout === 'auto') {\n duration = theme.transitions.getAutoHeightDuration(node.clientHeight);\n autoTimeout.current = duration;\n } else {\n duration = transitionDuration;\n }\n\n node.style.transition = [theme.transitions.create('opacity', {\n duration: duration,\n delay: delay\n }), theme.transitions.create('transform', {\n duration: duration * 0.666,\n delay: delay\n })].join(',');\n\n if (onEnter) {\n onEnter(node, isAppearing);\n }\n });\n var handleEntered = normalizedTransitionCallback(onEntered);\n var handleExiting = normalizedTransitionCallback(onExiting);\n var handleExit = normalizedTransitionCallback(function (node) {\n var _getTransitionProps2 = getTransitionProps({\n style: style,\n timeout: timeout\n }, {\n mode: 'exit'\n }),\n transitionDuration = _getTransitionProps2.duration,\n delay = _getTransitionProps2.delay;\n\n var duration;\n\n if (timeout === 'auto') {\n duration = theme.transitions.getAutoHeightDuration(node.clientHeight);\n autoTimeout.current = duration;\n } else {\n duration = transitionDuration;\n }\n\n node.style.transition = [theme.transitions.create('opacity', {\n duration: duration,\n delay: delay\n }), theme.transitions.create('transform', {\n duration: duration * 0.666,\n delay: delay || duration * 0.333\n })].join(',');\n node.style.opacity = '0';\n node.style.transform = getScale(0.75);\n\n if (onExit) {\n onExit(node);\n }\n });\n var handleExited = normalizedTransitionCallback(onExited);\n\n var addEndListener = function addEndListener(nodeOrNext, maybeNext) {\n var next = enableStrictModeCompat ? nodeOrNext : maybeNext;\n\n if (timeout === 'auto') {\n timer.current = setTimeout(next, autoTimeout.current || 0);\n }\n };\n\n React.useEffect(function () {\n return function () {\n clearTimeout(timer.current);\n };\n }, []);\n return /*#__PURE__*/React.createElement(TransitionComponent, _extends({\n appear: true,\n in: inProp,\n nodeRef: enableStrictModeCompat ? nodeRef : undefined,\n onEnter: handleEnter,\n onEntered: handleEntered,\n onEntering: handleEntering,\n onExit: handleExit,\n onExited: handleExited,\n onExiting: handleExiting,\n addEndListener: addEndListener,\n timeout: timeout === 'auto' ? null : timeout\n }, other), function (state, childProps) {\n return /*#__PURE__*/React.cloneElement(children, _extends({\n style: _extends({\n opacity: 0,\n transform: getScale(0.75),\n visibility: state === 'exited' && !inProp ? 'hidden' : undefined\n }, styles[state], style, children.props.style),\n ref: handleRef\n }, childProps));\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Grow.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A single child content element.\n */\n children: PropTypes.element,\n\n /**\n * Enable this prop if you encounter 'Function components cannot be given refs',\n * use `unstable_createStrictModeTheme`,\n * and can't forward the ref in the child component.\n */\n disableStrictModeCompat: PropTypes.bool,\n\n /**\n * If `true`, show the component; triggers the enter or exit animation.\n */\n in: PropTypes.bool,\n\n /**\n * @ignore\n */\n onEnter: PropTypes.func,\n\n /**\n * @ignore\n */\n onEntered: PropTypes.func,\n\n /**\n * @ignore\n */\n onEntering: PropTypes.func,\n\n /**\n * @ignore\n */\n onExit: PropTypes.func,\n\n /**\n * @ignore\n */\n onExited: PropTypes.func,\n\n /**\n * @ignore\n */\n onExiting: PropTypes.func,\n\n /**\n * @ignore\n */\n style: PropTypes.object,\n\n /**\n * The duration for the transition, in milliseconds.\n * You may specify a single timeout for all transitions, or individually with an object.\n *\n * Set to 'auto' to automatically calculate transition time based on height.\n */\n timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })])\n} : void 0;\nGrow.muiSupportAuto = true;\nexport default Grow;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport * as ReactDOM from 'react-dom';\nimport { chainPropTypes, elementTypeAcceptingRef, refType, HTMLElementType } from '@material-ui/utils';\nimport debounce from '../utils/debounce';\nimport clsx from 'clsx';\nimport ownerDocument from '../utils/ownerDocument';\nimport ownerWindow from '../utils/ownerWindow';\nimport createChainedFunction from '../utils/createChainedFunction';\nimport deprecatedPropType from '../utils/deprecatedPropType';\nimport withStyles from '../styles/withStyles';\nimport Modal from '../Modal';\nimport Grow from '../Grow';\nimport Paper from '../Paper';\nexport function getOffsetTop(rect, vertical) {\n var offset = 0;\n\n if (typeof vertical === 'number') {\n offset = vertical;\n } else if (vertical === 'center') {\n offset = rect.height / 2;\n } else if (vertical === 'bottom') {\n offset = rect.height;\n }\n\n return offset;\n}\nexport function getOffsetLeft(rect, horizontal) {\n var offset = 0;\n\n if (typeof horizontal === 'number') {\n offset = horizontal;\n } else if (horizontal === 'center') {\n offset = rect.width / 2;\n } else if (horizontal === 'right') {\n offset = rect.width;\n }\n\n return offset;\n}\n\nfunction getTransformOriginValue(transformOrigin) {\n return [transformOrigin.horizontal, transformOrigin.vertical].map(function (n) {\n return typeof n === 'number' ? \"\".concat(n, \"px\") : n;\n }).join(' ');\n} // Sum the scrollTop between two elements.\n\n\nfunction getScrollParent(parent, child) {\n var element = child;\n var scrollTop = 0;\n\n while (element && element !== parent) {\n element = element.parentElement;\n scrollTop += element.scrollTop;\n }\n\n return scrollTop;\n}\n\nfunction getAnchorEl(anchorEl) {\n return typeof anchorEl === 'function' ? anchorEl() : anchorEl;\n}\n\nexport var styles = {\n /* Styles applied to the root element. */\n root: {},\n\n /* Styles applied to the `Paper` component. */\n paper: {\n position: 'absolute',\n overflowY: 'auto',\n overflowX: 'hidden',\n // So we see the popover when it's empty.\n // It's most likely on issue on userland.\n minWidth: 16,\n minHeight: 16,\n maxWidth: 'calc(100% - 32px)',\n maxHeight: 'calc(100% - 32px)',\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0\n }\n};\nvar Popover = /*#__PURE__*/React.forwardRef(function Popover(props, ref) {\n var action = props.action,\n anchorEl = props.anchorEl,\n _props$anchorOrigin = props.anchorOrigin,\n anchorOrigin = _props$anchorOrigin === void 0 ? {\n vertical: 'top',\n horizontal: 'left'\n } : _props$anchorOrigin,\n anchorPosition = props.anchorPosition,\n _props$anchorReferenc = props.anchorReference,\n anchorReference = _props$anchorReferenc === void 0 ? 'anchorEl' : _props$anchorReferenc,\n children = props.children,\n classes = props.classes,\n className = props.className,\n containerProp = props.container,\n _props$elevation = props.elevation,\n elevation = _props$elevation === void 0 ? 8 : _props$elevation,\n getContentAnchorEl = props.getContentAnchorEl,\n _props$marginThreshol = props.marginThreshold,\n marginThreshold = _props$marginThreshol === void 0 ? 16 : _props$marginThreshol,\n onEnter = props.onEnter,\n onEntered = props.onEntered,\n onEntering = props.onEntering,\n onExit = props.onExit,\n onExited = props.onExited,\n onExiting = props.onExiting,\n open = props.open,\n _props$PaperProps = props.PaperProps,\n PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps,\n _props$transformOrigi = props.transformOrigin,\n transformOrigin = _props$transformOrigi === void 0 ? {\n vertical: 'top',\n horizontal: 'left'\n } : _props$transformOrigi,\n _props$TransitionComp = props.TransitionComponent,\n TransitionComponent = _props$TransitionComp === void 0 ? Grow : _props$TransitionComp,\n _props$transitionDura = props.transitionDuration,\n transitionDurationProp = _props$transitionDura === void 0 ? 'auto' : _props$transitionDura,\n _props$TransitionProp = props.TransitionProps,\n TransitionProps = _props$TransitionProp === void 0 ? {} : _props$TransitionProp,\n other = _objectWithoutProperties(props, [\"action\", \"anchorEl\", \"anchorOrigin\", \"anchorPosition\", \"anchorReference\", \"children\", \"classes\", \"className\", \"container\", \"elevation\", \"getContentAnchorEl\", \"marginThreshold\", \"onEnter\", \"onEntered\", \"onEntering\", \"onExit\", \"onExited\", \"onExiting\", \"open\", \"PaperProps\", \"transformOrigin\", \"TransitionComponent\", \"transitionDuration\", \"TransitionProps\"]);\n\n var paperRef = React.useRef(); // Returns the top/left offset of the position\n // to attach to on the anchor element (or body if none is provided)\n\n var getAnchorOffset = React.useCallback(function (contentAnchorOffset) {\n if (anchorReference === 'anchorPosition') {\n if (process.env.NODE_ENV !== 'production') {\n if (!anchorPosition) {\n console.error('Material-UI: You need to provide a `anchorPosition` prop when using ' + '.');\n }\n }\n\n return anchorPosition;\n }\n\n var resolvedAnchorEl = getAnchorEl(anchorEl); // If an anchor element wasn't provided, just use the parent body element of this Popover\n\n var anchorElement = resolvedAnchorEl && resolvedAnchorEl.nodeType === 1 ? resolvedAnchorEl : ownerDocument(paperRef.current).body;\n var anchorRect = anchorElement.getBoundingClientRect();\n\n if (process.env.NODE_ENV !== 'production') {\n var box = anchorElement.getBoundingClientRect();\n\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n console.warn(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n }\n\n var anchorVertical = contentAnchorOffset === 0 ? anchorOrigin.vertical : 'center';\n return {\n top: anchorRect.top + getOffsetTop(anchorRect, anchorVertical),\n left: anchorRect.left + getOffsetLeft(anchorRect, anchorOrigin.horizontal)\n };\n }, [anchorEl, anchorOrigin.horizontal, anchorOrigin.vertical, anchorPosition, anchorReference]); // Returns the vertical offset of inner content to anchor the transform on if provided\n\n var getContentAnchorOffset = React.useCallback(function (element) {\n var contentAnchorOffset = 0;\n\n if (getContentAnchorEl && anchorReference === 'anchorEl') {\n var contentAnchorEl = getContentAnchorEl(element);\n\n if (contentAnchorEl && element.contains(contentAnchorEl)) {\n var scrollTop = getScrollParent(element, contentAnchorEl);\n contentAnchorOffset = contentAnchorEl.offsetTop + contentAnchorEl.clientHeight / 2 - scrollTop || 0;\n } // != the default value\n\n\n if (process.env.NODE_ENV !== 'production') {\n if (anchorOrigin.vertical !== 'top') {\n console.error(['Material-UI: You can not change the default `anchorOrigin.vertical` value ', 'when also providing the `getContentAnchorEl` prop to the popover component.', 'Only use one of the two props.', 'Set `getContentAnchorEl` to `null | undefined`' + ' or leave `anchorOrigin.vertical` unchanged.'].join('\\n'));\n }\n }\n }\n\n return contentAnchorOffset;\n }, [anchorOrigin.vertical, anchorReference, getContentAnchorEl]); // Return the base transform origin using the element\n // and taking the content anchor offset into account if in use\n\n var getTransformOrigin = React.useCallback(function (elemRect) {\n var contentAnchorOffset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n return {\n vertical: getOffsetTop(elemRect, transformOrigin.vertical) + contentAnchorOffset,\n horizontal: getOffsetLeft(elemRect, transformOrigin.horizontal)\n };\n }, [transformOrigin.horizontal, transformOrigin.vertical]);\n var getPositioningStyle = React.useCallback(function (element) {\n // Check if the parent has requested anchoring on an inner content node\n var contentAnchorOffset = getContentAnchorOffset(element);\n var elemRect = {\n width: element.offsetWidth,\n height: element.offsetHeight\n }; // Get the transform origin point on the element itself\n\n var elemTransformOrigin = getTransformOrigin(elemRect, contentAnchorOffset);\n\n if (anchorReference === 'none') {\n return {\n top: null,\n left: null,\n transformOrigin: getTransformOriginValue(elemTransformOrigin)\n };\n } // Get the offset of of the anchoring element\n\n\n var anchorOffset = getAnchorOffset(contentAnchorOffset); // Calculate element positioning\n\n var top = anchorOffset.top - elemTransformOrigin.vertical;\n var left = anchorOffset.left - elemTransformOrigin.horizontal;\n var bottom = top + elemRect.height;\n var right = left + elemRect.width; // Use the parent window of the anchorEl if provided\n\n var containerWindow = ownerWindow(getAnchorEl(anchorEl)); // Window thresholds taking required margin into account\n\n var heightThreshold = containerWindow.innerHeight - marginThreshold;\n var widthThreshold = containerWindow.innerWidth - marginThreshold; // Check if the vertical axis needs shifting\n\n if (top < marginThreshold) {\n var diff = top - marginThreshold;\n top -= diff;\n elemTransformOrigin.vertical += diff;\n } else if (bottom > heightThreshold) {\n var _diff = bottom - heightThreshold;\n\n top -= _diff;\n elemTransformOrigin.vertical += _diff;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (elemRect.height > heightThreshold && elemRect.height && heightThreshold) {\n console.error(['Material-UI: The popover component is too tall.', \"Some part of it can not be seen on the screen (\".concat(elemRect.height - heightThreshold, \"px).\"), 'Please consider adding a `max-height` to improve the user-experience.'].join('\\n'));\n }\n } // Check if the horizontal axis needs shifting\n\n\n if (left < marginThreshold) {\n var _diff2 = left - marginThreshold;\n\n left -= _diff2;\n elemTransformOrigin.horizontal += _diff2;\n } else if (right > widthThreshold) {\n var _diff3 = right - widthThreshold;\n\n left -= _diff3;\n elemTransformOrigin.horizontal += _diff3;\n }\n\n return {\n top: \"\".concat(Math.round(top), \"px\"),\n left: \"\".concat(Math.round(left), \"px\"),\n transformOrigin: getTransformOriginValue(elemTransformOrigin)\n };\n }, [anchorEl, anchorReference, getAnchorOffset, getContentAnchorOffset, getTransformOrigin, marginThreshold]);\n var setPositioningStyles = React.useCallback(function () {\n var element = paperRef.current;\n\n if (!element) {\n return;\n }\n\n var positioning = getPositioningStyle(element);\n\n if (positioning.top !== null) {\n element.style.top = positioning.top;\n }\n\n if (positioning.left !== null) {\n element.style.left = positioning.left;\n }\n\n element.style.transformOrigin = positioning.transformOrigin;\n }, [getPositioningStyle]);\n\n var handleEntering = function handleEntering(element, isAppearing) {\n if (onEntering) {\n onEntering(element, isAppearing);\n }\n\n setPositioningStyles();\n };\n\n var handlePaperRef = React.useCallback(function (instance) {\n // #StrictMode ready\n paperRef.current = ReactDOM.findDOMNode(instance);\n }, []);\n React.useEffect(function () {\n if (open) {\n setPositioningStyles();\n }\n });\n React.useImperativeHandle(action, function () {\n return open ? {\n updatePosition: function updatePosition() {\n setPositioningStyles();\n }\n } : null;\n }, [open, setPositioningStyles]);\n React.useEffect(function () {\n if (!open) {\n return undefined;\n }\n\n var handleResize = debounce(function () {\n setPositioningStyles();\n });\n window.addEventListener('resize', handleResize);\n return function () {\n handleResize.clear();\n window.removeEventListener('resize', handleResize);\n };\n }, [open, setPositioningStyles]);\n var transitionDuration = transitionDurationProp;\n\n if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) {\n transitionDuration = undefined;\n } // If the container prop is provided, use that\n // If the anchorEl prop is provided, use its parent body element as the container\n // If neither are provided let the Modal take care of choosing the container\n\n\n var container = containerProp || (anchorEl ? ownerDocument(getAnchorEl(anchorEl)).body : undefined);\n return /*#__PURE__*/React.createElement(Modal, _extends({\n container: container,\n open: open,\n ref: ref,\n BackdropProps: {\n invisible: true\n },\n className: clsx(classes.root, className)\n }, other), /*#__PURE__*/React.createElement(TransitionComponent, _extends({\n appear: true,\n in: open,\n onEnter: onEnter,\n onEntered: onEntered,\n onExit: onExit,\n onExited: onExited,\n onExiting: onExiting,\n timeout: transitionDuration\n }, TransitionProps, {\n onEntering: createChainedFunction(handleEntering, TransitionProps.onEntering)\n }), /*#__PURE__*/React.createElement(Paper, _extends({\n elevation: elevation,\n ref: handlePaperRef\n }, PaperProps, {\n className: clsx(classes.paper, PaperProps.className)\n }), children)));\n});\nprocess.env.NODE_ENV !== \"production\" ? Popover.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A ref for imperative actions.\n * It currently only supports updatePosition() action.\n */\n action: refType,\n\n /**\n * A HTML element, or a function that returns it.\n * It's used to set the position of the popover.\n */\n anchorEl: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.func]), function (props) {\n if (props.open && (!props.anchorReference || props.anchorReference === 'anchorEl')) {\n var resolvedAnchorEl = getAnchorEl(props.anchorEl);\n\n if (resolvedAnchorEl && resolvedAnchorEl.nodeType === 1) {\n var box = resolvedAnchorEl.getBoundingClientRect();\n\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n return new Error(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n } else {\n return new Error(['Material-UI: The `anchorEl` prop provided to the component is invalid.', \"It should be an Element instance but it's `\".concat(resolvedAnchorEl, \"` instead.\")].join('\\n'));\n }\n }\n\n return null;\n }),\n\n /**\n * This is the point on the anchor where the popover's\n * `anchorEl` will attach to. This is not used when the\n * anchorReference is 'anchorPosition'.\n *\n * Options:\n * vertical: [top, center, bottom];\n * horizontal: [left, center, right].\n */\n anchorOrigin: PropTypes.shape({\n horizontal: PropTypes.oneOfType([PropTypes.oneOf(['center', 'left', 'right']), PropTypes.number]).isRequired,\n vertical: PropTypes.oneOfType([PropTypes.oneOf(['bottom', 'center', 'top']), PropTypes.number]).isRequired\n }),\n\n /**\n * This is the position that may be used\n * to set the position of the popover.\n * The coordinates are relative to\n * the application's client area.\n */\n anchorPosition: PropTypes.shape({\n left: PropTypes.number.isRequired,\n top: PropTypes.number.isRequired\n }),\n\n /**\n * This determines which anchor prop to refer to to set\n * the position of the popover.\n */\n anchorReference: PropTypes.oneOf(['anchorEl', 'anchorPosition', 'none']),\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * A HTML element, component instance, or function that returns either.\n * The `container` will passed to the Modal component.\n *\n * By default, it uses the body of the anchorEl's top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes\n /* @typescript-to-proptypes-ignore */\n .oneOfType([HTMLElementType, PropTypes.instanceOf(React.Component), PropTypes.func]),\n\n /**\n * The elevation of the popover.\n */\n elevation: PropTypes.number,\n\n /**\n * This function is called in order to retrieve the content anchor element.\n * It's the opposite of the `anchorEl` prop.\n * The content anchor element should be an element inside the popover.\n * It's used to correctly scroll and set the position of the popover.\n * The positioning strategy tries to make the content anchor element just above the\n * anchor element.\n */\n getContentAnchorEl: PropTypes.func,\n\n /**\n * Specifies how close to the edge of the window the popover can appear.\n */\n marginThreshold: PropTypes.number,\n\n /**\n * Callback fired when the component requests to be closed.\n */\n onClose: PropTypes.func,\n\n /**\n * Callback fired before the component is entering.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onEnter: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired when the component has entered.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onEntered: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired when the component is entering.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onEntering: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired before the component is exiting.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onExit: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired when the component has exited.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onExited: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired when the component is exiting.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onExiting: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * If `true`, the popover is visible.\n */\n open: PropTypes.bool.isRequired,\n\n /**\n * Props applied to the [`Paper`](/api/paper/) element.\n */\n PaperProps: PropTypes\n /* @typescript-to-proptypes-ignore */\n .shape({\n component: elementTypeAcceptingRef\n }),\n\n /**\n * This is the point on the popover which\n * will attach to the anchor's origin.\n *\n * Options:\n * vertical: [top, center, bottom, x(px)];\n * horizontal: [left, center, right, x(px)].\n */\n transformOrigin: PropTypes.shape({\n horizontal: PropTypes.oneOfType([PropTypes.oneOf(['center', 'left', 'right']), PropTypes.number]).isRequired,\n vertical: PropTypes.oneOfType([PropTypes.oneOf(['bottom', 'center', 'top']), PropTypes.number]).isRequired\n }),\n\n /**\n * The component used for the transition.\n * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.\n */\n TransitionComponent: PropTypes.elementType,\n\n /**\n * Set to 'auto' to automatically calculate transition time based on height.\n */\n transitionDuration: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })]),\n\n /**\n * Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element.\n */\n TransitionProps: PropTypes.object\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiPopover'\n})(Popover);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport { isFragment } from 'react-is';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { HTMLElementType } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nimport Popover from '../Popover';\nimport MenuList from '../MenuList';\nimport * as ReactDOM from 'react-dom';\nimport setRef from '../utils/setRef';\nimport useTheme from '../styles/useTheme';\nimport deprecatedPropType from '../utils/deprecatedPropType';\nvar RTL_ORIGIN = {\n vertical: 'top',\n horizontal: 'right'\n};\nvar LTR_ORIGIN = {\n vertical: 'top',\n horizontal: 'left'\n};\nexport var styles = {\n /* Styles applied to the `Paper` component. */\n paper: {\n // specZ: The maximum height of a simple menu should be one or more rows less than the view\n // height. This ensures a tapable area outside of the simple menu with which to dismiss\n // the menu.\n maxHeight: 'calc(100% - 96px)',\n // Add iOS momentum scrolling.\n WebkitOverflowScrolling: 'touch'\n },\n\n /* Styles applied to the `List` component via `MenuList`. */\n list: {\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0\n }\n};\nvar Menu = /*#__PURE__*/React.forwardRef(function Menu(props, ref) {\n var _props$autoFocus = props.autoFocus,\n autoFocus = _props$autoFocus === void 0 ? true : _props$autoFocus,\n children = props.children,\n classes = props.classes,\n _props$disableAutoFoc = props.disableAutoFocusItem,\n disableAutoFocusItem = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,\n _props$MenuListProps = props.MenuListProps,\n MenuListProps = _props$MenuListProps === void 0 ? {} : _props$MenuListProps,\n onClose = props.onClose,\n onEnteringProp = props.onEntering,\n open = props.open,\n _props$PaperProps = props.PaperProps,\n PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps,\n PopoverClasses = props.PopoverClasses,\n _props$transitionDura = props.transitionDuration,\n transitionDuration = _props$transitionDura === void 0 ? 'auto' : _props$transitionDura,\n _props$TransitionProp = props.TransitionProps;\n _props$TransitionProp = _props$TransitionProp === void 0 ? {} : _props$TransitionProp;\n\n var onEntering = _props$TransitionProp.onEntering,\n TransitionProps = _objectWithoutProperties(_props$TransitionProp, [\"onEntering\"]),\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'selectedMenu' : _props$variant,\n other = _objectWithoutProperties(props, [\"autoFocus\", \"children\", \"classes\", \"disableAutoFocusItem\", \"MenuListProps\", \"onClose\", \"onEntering\", \"open\", \"PaperProps\", \"PopoverClasses\", \"transitionDuration\", \"TransitionProps\", \"variant\"]);\n\n var theme = useTheme();\n var autoFocusItem = autoFocus && !disableAutoFocusItem && open;\n var menuListActionsRef = React.useRef(null);\n var contentAnchorRef = React.useRef(null);\n\n var getContentAnchorEl = function getContentAnchorEl() {\n return contentAnchorRef.current;\n };\n\n var handleEntering = function handleEntering(element, isAppearing) {\n if (menuListActionsRef.current) {\n menuListActionsRef.current.adjustStyleForScrollbar(element, theme);\n }\n\n if (onEnteringProp) {\n onEnteringProp(element, isAppearing);\n }\n\n if (onEntering) {\n onEntering(element, isAppearing);\n }\n };\n\n var handleListKeyDown = function handleListKeyDown(event) {\n if (event.key === 'Tab') {\n event.preventDefault();\n\n if (onClose) {\n onClose(event, 'tabKeyDown');\n }\n }\n };\n /**\n * the index of the item should receive focus\n * in a `variant=\"selectedMenu\"` it's the first `selected` item\n * otherwise it's the very first item.\n */\n\n\n var activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead\n // to check if there is a `selected` item. We're looking for the last `selected`\n // item and use the first valid item as a fallback\n\n React.Children.map(children, function (child, index) {\n if (! /*#__PURE__*/React.isValidElement(child)) {\n return;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (isFragment(child)) {\n console.error([\"Material-UI: The Menu component doesn't accept a Fragment as a child.\", 'Consider providing an array instead.'].join('\\n'));\n }\n }\n\n if (!child.props.disabled) {\n if (variant !== \"menu\" && child.props.selected) {\n activeItemIndex = index;\n } else if (activeItemIndex === -1) {\n activeItemIndex = index;\n }\n }\n });\n var items = React.Children.map(children, function (child, index) {\n if (index === activeItemIndex) {\n return /*#__PURE__*/React.cloneElement(child, {\n ref: function ref(instance) {\n // #StrictMode ready\n contentAnchorRef.current = ReactDOM.findDOMNode(instance);\n setRef(child.ref, instance);\n }\n });\n }\n\n return child;\n });\n return /*#__PURE__*/React.createElement(Popover, _extends({\n getContentAnchorEl: getContentAnchorEl,\n classes: PopoverClasses,\n onClose: onClose,\n TransitionProps: _extends({\n onEntering: handleEntering\n }, TransitionProps),\n anchorOrigin: theme.direction === 'rtl' ? RTL_ORIGIN : LTR_ORIGIN,\n transformOrigin: theme.direction === 'rtl' ? RTL_ORIGIN : LTR_ORIGIN,\n PaperProps: _extends({}, PaperProps, {\n classes: _extends({}, PaperProps.classes, {\n root: classes.paper\n })\n }),\n open: open,\n ref: ref,\n transitionDuration: transitionDuration\n }, other), /*#__PURE__*/React.createElement(MenuList, _extends({\n onKeyDown: handleListKeyDown,\n actions: menuListActionsRef,\n autoFocus: autoFocus && (activeItemIndex === -1 || disableAutoFocusItem),\n autoFocusItem: autoFocusItem,\n variant: variant\n }, MenuListProps, {\n className: clsx(classes.list, MenuListProps.className)\n }), items));\n});\nprocess.env.NODE_ENV !== \"production\" ? Menu.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A HTML element, or a function that returns it.\n * It's used to set the position of the menu.\n */\n anchorEl: PropTypes\n /* @typescript-to-proptypes-ignore */\n .oneOfType([HTMLElementType, PropTypes.func]),\n\n /**\n * If `true` (Default) will focus the `[role=\"menu\"]` if no focusable child is found. Disabled\n * children are not focusable. If you set this prop to `false` focus will be placed\n * on the parent modal container. This has severe accessibility implications\n * and should only be considered if you manage focus otherwise.\n */\n autoFocus: PropTypes.bool,\n\n /**\n * Menu contents, normally `MenuItem`s.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * When opening the menu will not focus the active item but the `[role=\"menu\"]`\n * unless `autoFocus` is also set to `false`. Not using the default means not\n * following WAI-ARIA authoring practices. Please be considerate about possible\n * accessibility implications.\n */\n disableAutoFocusItem: PropTypes.bool,\n\n /**\n * Props applied to the [`MenuList`](/api/menu-list/) element.\n */\n MenuListProps: PropTypes.object,\n\n /**\n * Callback fired when the component requests to be closed.\n *\n * @param {object} event The event source of the callback.\n * @param {string} reason Can be: `\"escapeKeyDown\"`, `\"backdropClick\"`, `\"tabKeyDown\"`.\n */\n onClose: PropTypes.func,\n\n /**\n * Callback fired before the Menu enters.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onEnter: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired when the Menu has entered.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onEntered: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired when the Menu is entering.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onEntering: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired before the Menu exits.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onExit: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired when the Menu has exited.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onExited: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * Callback fired when the Menu is exiting.\n * @deprecated Use the `TransitionProps` prop instead.\n */\n onExiting: deprecatedPropType(PropTypes.func, 'Use the `TransitionProps` prop instead.'),\n\n /**\n * If `true`, the menu is visible.\n */\n open: PropTypes.bool.isRequired,\n\n /**\n * @ignore\n */\n PaperProps: PropTypes.object,\n\n /**\n * `classes` prop applied to the [`Popover`](/api/popover/) element.\n */\n PopoverClasses: PropTypes.object,\n\n /**\n * The length of the transition in `ms`, or 'auto'\n */\n transitionDuration: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })]),\n\n /**\n * Props applied to the transition element.\n * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition) component.\n */\n TransitionProps: PropTypes.object,\n\n /**\n * The variant to use. Use `menu` to prevent selected items from impacting the initial focus\n * and the vertical alignment relative to the anchor element.\n */\n variant: PropTypes.oneOf(['menu', 'selectedMenu'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiMenu'\n})(Menu);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport { formatMuiErrorMessage as _formatMuiErrorMessage } from \"@material-ui/utils\";\nimport * as React from 'react';\nimport { isFragment } from 'react-is';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport ownerDocument from '../utils/ownerDocument';\nimport capitalize from '../utils/capitalize';\nimport { refType } from '@material-ui/utils';\nimport Menu from '../Menu/Menu';\nimport { isFilled } from '../InputBase/utils';\nimport useForkRef from '../utils/useForkRef';\nimport useControlled from '../utils/useControlled';\n\nfunction areEqualValues(a, b) {\n if (_typeof(b) === 'object' && b !== null) {\n return a === b;\n }\n\n return String(a) === String(b);\n}\n\nfunction isEmpty(display) {\n return display == null || typeof display === 'string' && !display.trim();\n}\n/**\n * @ignore - internal component.\n */\n\n\nvar SelectInput = /*#__PURE__*/React.forwardRef(function SelectInput(props, ref) {\n var ariaLabel = props['aria-label'],\n autoFocus = props.autoFocus,\n autoWidth = props.autoWidth,\n children = props.children,\n classes = props.classes,\n className = props.className,\n defaultValue = props.defaultValue,\n disabled = props.disabled,\n displayEmpty = props.displayEmpty,\n IconComponent = props.IconComponent,\n inputRefProp = props.inputRef,\n labelId = props.labelId,\n _props$MenuProps = props.MenuProps,\n MenuProps = _props$MenuProps === void 0 ? {} : _props$MenuProps,\n multiple = props.multiple,\n name = props.name,\n onBlur = props.onBlur,\n onChange = props.onChange,\n onClose = props.onClose,\n onFocus = props.onFocus,\n onOpen = props.onOpen,\n openProp = props.open,\n readOnly = props.readOnly,\n renderValue = props.renderValue,\n _props$SelectDisplayP = props.SelectDisplayProps,\n SelectDisplayProps = _props$SelectDisplayP === void 0 ? {} : _props$SelectDisplayP,\n tabIndexProp = props.tabIndex,\n type = props.type,\n valueProp = props.value,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'standard' : _props$variant,\n other = _objectWithoutProperties(props, [\"aria-label\", \"autoFocus\", \"autoWidth\", \"children\", \"classes\", \"className\", \"defaultValue\", \"disabled\", \"displayEmpty\", \"IconComponent\", \"inputRef\", \"labelId\", \"MenuProps\", \"multiple\", \"name\", \"onBlur\", \"onChange\", \"onClose\", \"onFocus\", \"onOpen\", \"open\", \"readOnly\", \"renderValue\", \"SelectDisplayProps\", \"tabIndex\", \"type\", \"value\", \"variant\"]);\n\n var _useControlled = useControlled({\n controlled: valueProp,\n default: defaultValue,\n name: 'Select'\n }),\n _useControlled2 = _slicedToArray(_useControlled, 2),\n value = _useControlled2[0],\n setValue = _useControlled2[1];\n\n var inputRef = React.useRef(null);\n\n var _React$useState = React.useState(null),\n displayNode = _React$useState[0],\n setDisplayNode = _React$useState[1];\n\n var _React$useRef = React.useRef(openProp != null),\n isOpenControlled = _React$useRef.current;\n\n var _React$useState2 = React.useState(),\n menuMinWidthState = _React$useState2[0],\n setMenuMinWidthState = _React$useState2[1];\n\n var _React$useState3 = React.useState(false),\n openState = _React$useState3[0],\n setOpenState = _React$useState3[1];\n\n var handleRef = useForkRef(ref, inputRefProp);\n React.useImperativeHandle(handleRef, function () {\n return {\n focus: function focus() {\n displayNode.focus();\n },\n node: inputRef.current,\n value: value\n };\n }, [displayNode, value]);\n React.useEffect(function () {\n if (autoFocus && displayNode) {\n displayNode.focus();\n }\n }, [autoFocus, displayNode]);\n React.useEffect(function () {\n if (displayNode) {\n var label = ownerDocument(displayNode).getElementById(labelId);\n\n if (label) {\n var handler = function handler() {\n if (getSelection().isCollapsed) {\n displayNode.focus();\n }\n };\n\n label.addEventListener('click', handler);\n return function () {\n label.removeEventListener('click', handler);\n };\n }\n }\n\n return undefined;\n }, [labelId, displayNode]);\n\n var update = function update(open, event) {\n if (open) {\n if (onOpen) {\n onOpen(event);\n }\n } else if (onClose) {\n onClose(event);\n }\n\n if (!isOpenControlled) {\n setMenuMinWidthState(autoWidth ? null : displayNode.clientWidth);\n setOpenState(open);\n }\n };\n\n var handleMouseDown = function handleMouseDown(event) {\n // Ignore everything but left-click\n if (event.button !== 0) {\n return;\n } // Hijack the default focus behavior.\n\n\n event.preventDefault();\n displayNode.focus();\n update(true, event);\n };\n\n var handleClose = function handleClose(event) {\n update(false, event);\n };\n\n var childrenArray = React.Children.toArray(children); // Support autofill.\n\n var handleChange = function handleChange(event) {\n var index = childrenArray.map(function (child) {\n return child.props.value;\n }).indexOf(event.target.value);\n\n if (index === -1) {\n return;\n }\n\n var child = childrenArray[index];\n setValue(child.props.value);\n\n if (onChange) {\n onChange(event, child);\n }\n };\n\n var handleItemClick = function handleItemClick(child) {\n return function (event) {\n if (!multiple) {\n update(false, event);\n }\n\n var newValue;\n\n if (multiple) {\n newValue = Array.isArray(value) ? value.slice() : [];\n var itemIndex = value.indexOf(child.props.value);\n\n if (itemIndex === -1) {\n newValue.push(child.props.value);\n } else {\n newValue.splice(itemIndex, 1);\n }\n } else {\n newValue = child.props.value;\n }\n\n if (child.props.onClick) {\n child.props.onClick(event);\n }\n\n if (value === newValue) {\n return;\n }\n\n setValue(newValue);\n\n if (onChange) {\n event.persist(); // Preact support, target is read only property on a native event.\n\n Object.defineProperty(event, 'target', {\n writable: true,\n value: {\n value: newValue,\n name: name\n }\n });\n onChange(event, child);\n }\n };\n };\n\n var handleKeyDown = function handleKeyDown(event) {\n if (!readOnly) {\n var validKeys = [' ', 'ArrowUp', 'ArrowDown', // The native select doesn't respond to enter on MacOS, but it's recommended by\n // https://www.w3.org/TR/wai-aria-practices/examples/listbox/listbox-collapsible.html\n 'Enter'];\n\n if (validKeys.indexOf(event.key) !== -1) {\n event.preventDefault();\n update(true, event);\n }\n }\n };\n\n var open = displayNode !== null && (isOpenControlled ? openProp : openState);\n\n var handleBlur = function handleBlur(event) {\n // if open event.stopImmediatePropagation\n if (!open && onBlur) {\n event.persist(); // Preact support, target is read only property on a native event.\n\n Object.defineProperty(event, 'target', {\n writable: true,\n value: {\n value: value,\n name: name\n }\n });\n onBlur(event);\n }\n };\n\n delete other['aria-invalid'];\n var display;\n var displaySingle;\n var displayMultiple = [];\n var computeDisplay = false;\n var foundMatch = false; // No need to display any value if the field is empty.\n\n if (isFilled({\n value: value\n }) || displayEmpty) {\n if (renderValue) {\n display = renderValue(value);\n } else {\n computeDisplay = true;\n }\n }\n\n var items = childrenArray.map(function (child) {\n if (! /*#__PURE__*/React.isValidElement(child)) {\n return null;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (isFragment(child)) {\n console.error([\"Material-UI: The Select component doesn't accept a Fragment as a child.\", 'Consider providing an array instead.'].join('\\n'));\n }\n }\n\n var selected;\n\n if (multiple) {\n if (!Array.isArray(value)) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: The `value` prop must be an array when using the `Select` component with `multiple`.\" : _formatMuiErrorMessage(2));\n }\n\n selected = value.some(function (v) {\n return areEqualValues(v, child.props.value);\n });\n\n if (selected && computeDisplay) {\n displayMultiple.push(child.props.children);\n }\n } else {\n selected = areEqualValues(value, child.props.value);\n\n if (selected && computeDisplay) {\n displaySingle = child.props.children;\n }\n }\n\n if (selected) {\n foundMatch = true;\n }\n\n return /*#__PURE__*/React.cloneElement(child, {\n 'aria-selected': selected ? 'true' : undefined,\n onClick: handleItemClick(child),\n onKeyUp: function onKeyUp(event) {\n if (event.key === ' ') {\n // otherwise our MenuItems dispatches a click event\n // it's not behavior of the native \n );\n}\n","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nimport * as React from \"react\";\n\nvar _ref2 = /*#__PURE__*/React.createElement(\"path\", {\n d: \"M12 18c1.657 0 3 1.343 3 3s-1.343 3-3 3-3-1.343-3-3 1.343-3 3-3zm0-9c1.657 0 3 1.343 3 3s-1.343 3-3 3-3-1.343-3-3 1.343-3 3-3zm0-9c1.657 0 3 1.343 3 3s-1.343 3-3 3-3-1.343-3-3 1.343-3 3-3z\"\n});\n\nfunction SvgMenu(_ref) {\n var svgRef = _ref.svgRef,\n title = _ref.title,\n titleId = _ref.titleId,\n props = _objectWithoutProperties(_ref, [\"svgRef\", \"title\", \"titleId\"]);\n\n return /*#__PURE__*/React.createElement(\"svg\", _extends({\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, _ref2);\n}\n\nvar ForwardRef = React.forwardRef(function (props, ref) {\n return /*#__PURE__*/React.createElement(SvgMenu, _extends({\n svgRef: ref\n }, props));\n});\nexport default __webpack_public_path__ + \"static/media/menu.bc56e94a.svg\";\nexport { ForwardRef as ReactComponent };","import React, { useState } from 'react';\nimport clsx from 'clsx';\nimport { TreeNode as RcTreeNode } from 'rc-tree';\nimport { getDataAndAria } from 'rc-tree/es/util';\nimport classNames from 'classnames';\nimport range from 'lodash/range';\nimport isEqual from 'lodash/isEqual';\nimport PopoverMenu from './PopoverMenu';\nimport HelpTooltip from './HelpTooltip';\nimport { callbackOnKeyPress, colorArrayToString, getLevelTooltipText } from './utils';\nimport { ReactComponent as MenuSVG } from '../../assets/menu.svg';\nimport { getDefaultColor } from '../utils';\n\n\n/**\n * Construct a `menuConfig` array for the PopoverMenu component.\n * @param {object} props The props for the TreeNode component.\n * @returns {object[]} An array of menu items to pass to PopoverMenu.\n */\nfunction makeNodeViewMenuConfig(props) {\n const {\n path,\n level,\n height,\n onCheckNode,\n onNodeRemove,\n onNodeSetIsEditing,\n onExportLevelZeroNodeJSON,\n onExportLevelZeroNodeTabular,\n onExportSetJSON,\n checkable,\n editable,\n exportable,\n checked,\n } = props;\n\n return [\n ...(editable ? [\n {\n title: 'Rename',\n handler: () => { onNodeSetIsEditing(path, true); },\n handlerKey: 'r',\n },\n {\n title: 'Delete',\n confirm: true,\n handler: () => { onNodeRemove(path); },\n handlerKey: 'd',\n },\n ] : []),\n ...(level === 0 && exportable ? [\n {\n title: 'Export hierarchy',\n subtitle: '(to JSON file)',\n handler: () => { onExportLevelZeroNodeJSON(path); },\n handlerKey: 'j',\n },\n ...(height <= 1 ? [\n {\n title: 'Export hierarchy',\n subtitle: '(to CSV file)',\n handler: () => { onExportLevelZeroNodeTabular(path); },\n handlerKey: 't',\n },\n ] : []),\n ] : []),\n ...(level > 0 ? [\n ...(checkable ? [\n {\n title: (checked ? 'Uncheck' : 'Check'),\n handler: () => { onCheckNode(path, !checked); },\n handlerKey: 's',\n },\n ] : []),\n ...(exportable ? [\n {\n title: 'Export set',\n subtitle: '(to JSON file)',\n handler: () => { onExportSetJSON(path); },\n handlerKey: 'e',\n },\n ] : []),\n ] : []),\n ];\n}\n\n/**\n * The \"static\" node component to render when the user is not renaming.\n * @param {object} props The props for the TreeNode component.\n */\nfunction NamedSetNodeStatic(props) {\n const {\n title,\n path,\n nodeKey,\n level,\n height,\n color,\n checkbox,\n isChecking,\n isLeaf,\n onNodeSetColor,\n onNodeView,\n expanded,\n onCheckLevel,\n checkedLevelPath,\n checkedLevelIndex,\n disableTooltip,\n size,\n datatype,\n editable,\n theme,\n } = props;\n const shouldCheckNextLevel = (level === 0 && !expanded);\n const nextLevelToCheck = (\n (checkedLevelIndex && isEqual(path, checkedLevelPath) && checkedLevelIndex < height)\n ? checkedLevelIndex + 1\n : 1\n );\n const numberFormatter = new Intl.NumberFormat('en-US');\n const niceSize = numberFormatter.format(size);\n let tooltipText;\n if (shouldCheckNextLevel) {\n tooltipText = getLevelTooltipText(nextLevelToCheck);\n } else if (isLeaf || !expanded) {\n tooltipText = `Color individual set (${niceSize} ${datatype}${(size === 1 ? '' : 's')})`;\n } else {\n tooltipText = 'Color by expanded descendants';\n }\n // If this is a level zero node and is _not_ expanded, then upon click,\n // the behavior should be to color by the first or next cluster level.\n // If this is a level zero node and _is_ expanded, or if any other node,\n // click should trigger onNodeView.\n const onClick = (level === 0 && !expanded\n ? () => onCheckLevel(nodeKey, nextLevelToCheck)\n : () => onNodeView(path)\n );\n const tooltipProps = (disableTooltip ? { visible: false } : {});\n const popoverMenuConfig = makeNodeViewMenuConfig(props);\n return (\n \n \n callbackOnKeyPress(e, 'v', () => onNodeView(path))}\n className=\"title-button\"\n >\n {title}\n \n \n {popoverMenuConfig.length > 0 ? (\n 0 && editable ? (color || getDefaultColor(theme)) : null}\n setColor={c => onNodeSetColor(path, c)}\n >\n \n \n ) : null}\n {level > 0 && isChecking ? checkbox : null}\n {level > 0 && ({niceSize})}\n \n );\n}\n\n/**\n * The \"editing\" node component to render when the user is renaming,\n * containing a text input field and a save button.\n * @param {object} props The props for the TreeNode component.\n */\nfunction NamedSetNodeEditing(props) {\n const {\n title,\n path,\n onNodeSetName,\n onNodeCheckNewName,\n } = props;\n const [currentTitle, setCurrentTitle] = useState(title);\n\n // Do not allow the user to save a potential name if it conflicts with\n // another name in the hierarchy.\n const hasConflicts = onNodeCheckNewName(path, currentTitle);\n function trySetName() {\n if (!hasConflicts) {\n onNodeSetName(path, currentTitle, true);\n }\n }\n return (\n \n { setCurrentTitle(e.target.value); }}\n onKeyPress={e => callbackOnKeyPress(\n e,\n 'Enter',\n trySetName,\n )}\n onFocus={e => e.target.select()}\n />\n {!hasConflicts && (\n \n Save\n \n )}\n \n );\n}\n\n/**\n * A \"delegation\" component, to decide whether to render\n * an \"editing\" vs. \"static\" node component.\n * @param {object} props The props for the TreeNode component.\n */\nfunction NamedSetNode(props) {\n const {\n isEditing,\n isCurrentSet,\n } = props;\n return (\n (isEditing || isCurrentSet)\n ? ()\n : ()\n );\n}\n\n/**\n * Buttons for viewing each hierarchy level,\n * rendered below collapsed level zero nodes.\n * @param {object} props The props for the (level zero) TreeNode component.\n */\nfunction LevelsButtons(props) {\n const {\n nodeKey,\n path,\n height,\n onCheckLevel,\n checkedLevelPath,\n checkedLevelIndex,\n hasColorEncoding,\n } = props;\n function onCheck(event) {\n if (event.target.checked) {\n const newLevel = parseInt(event.target.value, 10);\n onCheckLevel(nodeKey, newLevel);\n }\n }\n return (\n
\n {range(1, height + 1).map((i) => {\n const isChecked = isEqual(path, checkedLevelPath) && i === checkedLevelIndex;\n return (\n
\n \n \n \n
\n );\n })}\n
\n );\n}\n\n/**\n * Render the \"switcher\" icon.\n * Arrow for collapsed/expanded non-leaf nodes,\n * or square for leaf nodes.\n * @param {object} props The props for the TreeNode component.\n */\nfunction SwitcherIcon(props) {\n const {\n isLeaf, isOpen, color,\n } = props;\n const hexColor = (color ? colorArrayToString(color) : undefined);\n if (isLeaf) {\n return (\n \n \n \n \n \n );\n }\n return (\n \n \n \n \n \n );\n}\n\n/**\n * A custom TreeNode component.\n * @extends {RcTreeNode} TreeNode from the rc-tree library.\n */\nexport default class TreeNode extends RcTreeNode {\n /**\n * Override the main node text elements.\n */\n renderSelector = () => {\n const {\n title,\n isCurrentSet,\n isSelected,\n isEditing,\n onDragStart: onDragStartProp,\n } = this.props;\n const {\n rcTree: {\n prefixCls: prefixClass,\n draggable,\n },\n } = this.context;\n\n const onDragStart = (e) => {\n onDragStartProp();\n this.onDragStart(e);\n };\n\n const wrapClass = `${prefixClass}-node-content-wrapper`;\n const isDraggable = (!isCurrentSet && !isEditing && draggable);\n return (\n \n \n {this.renderLevels()}\n \n );\n };\n\n /**\n * Render the LevelsButtons component if this node\n * is a collapsed level zero node.\n */\n renderLevels = () => {\n const { level, expanded } = this.props;\n if (level !== 0 || expanded) {\n return null;\n }\n return (\n \n );\n }\n\n /**\n * Override the switcher element.\n */\n renderSwitcher = () => {\n const { expanded, isLeaf, color } = this.props;\n const {\n rcTree: {\n prefixCls: prefixClass,\n onNodeExpand,\n },\n } = this.context;\n\n const onNodeExpandWrapper = (e) => {\n // Do not call onNodeExpand if the node is a leaf node.\n if (!isLeaf) {\n onNodeExpand(e, this);\n }\n };\n\n const switcherClass = classNames(\n `${prefixClass}-switcher`,\n { [`${prefixClass}-switcher_${(expanded ? 'open' : 'close')}`]: !isLeaf },\n );\n return (\n callbackOnKeyPress(e, 'd', onNodeExpandWrapper)}\n role=\"button\"\n tabIndex=\"0\"\n >\n \n \n );\n };\n\n /**\n * Override main render function,\n * to enable overriding the sub-render functions\n * for switcher, selector, etc.\n */\n render() {\n const {\n style, loading, level,\n dragOver, dragOverGapTop, dragOverGapBottom,\n isLeaf,\n expanded, selected, checked, halfChecked,\n onDragEnd: onDragEndProp,\n expandable,\n ...otherProps\n } = this.props;\n const {\n rcTree: {\n prefixCls: prefixClass,\n filterTreeNode,\n draggable,\n },\n } = this.context;\n const disabled = this.isDisabled();\n const dataAndAriaAttributeProps = getDataAndAria(otherProps);\n\n const onDragEnd = (e) => {\n onDragEndProp();\n this.onDragEnd(e);\n };\n\n return (\n \n {expandable ? this.renderSwitcher() : null}\n {this.renderSelector()}\n {this.renderChildren()}\n \n );\n }\n}\n","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nimport * as React from \"react\";\n\nfunction SvgUnion(_ref) {\n var svgRef = _ref.svgRef,\n title = _ref.title,\n titleId = _ref.titleId,\n props = _objectWithoutProperties(_ref, [\"svgRef\", \"title\", \"titleId\"]);\n\n return /*#__PURE__*/React.createElement(\"svg\", _extends({\n viewBox: \"0 0 16.433999 10.234\",\n height: 12,\n width: 18,\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, /*#__PURE__*/React.createElement(\"g\", {\n transform: \"translate(0.117,-2.883)\"\n }, /*#__PURE__*/React.createElement(\"path\", {\n d: \"m 11.467471,11.811278 c 0.198237,-0.322177 0.508,-1.011333 0.653661,-1.454255 0.659343,-2.0049141 0.44323,-4.2620847 -0.577734,-6.0340822 l -0.168844,-0.2930481 0.105744,0.017887 c 0.759902,0.1285441 1.368762,0.3699553 1.856675,0.7361658 1.988296,1.4923476 2.192477,4.3353549 0.434717,6.0529895 -0.641216,0.626581 -1.299647,0.94683 -2.294136,1.115833 l -0.108488,0.01844 z M 4.3162122,11.919169 C 1.9278944,11.487872 0.46692382,9.0323123 1.234873,6.7401372 1.5621727,5.763213 2.2610593,4.9489746 3.1840041,4.4693005 3.5978035,4.2542401 3.9427842,4.145371 4.5197023,4.0477802 L 4.6254464,4.0298927 4.4571836,4.3223069 C 3.4332707,6.1017061 3.2180432,8.3476022 3.878868,10.357023 c 0.1458466,0.443487 0.4554716,1.132155 0.6542959,1.455285 0.054471,0.08853 0.087814,0.159599 0.074096,0.157937 -0.013718,-0.0017 -0.1446898,-0.02465 -0.2910477,-0.05108 z M 5.0000001,3 C 2.2,3 0,5.2 0,8 c 0,2.8 2.2,5 5.0000001,5 0.6,0 1.1,-0.1 1.6,-0.3 C 5.3000001,11.6 4.5,9.7999998 4.5,8 4.5,6.2 5.3000001,4.5 6.6000001,3.3 c -0.5,-0.2 -1,-0.3 -1.6,-0.3 z M 4.65,4.02 C 3.92,5.17 3.51,6.54 3.51,8 c 0,1.4599998 0.42,2.83 1.14,3.98 C 2.61,11.8 1.01,10.08 1.01,8 1.01,5.92 2.61,4.2 4.65,4.02 Z M 8,4 C 6.8,4.9 6,6.4 6,8 6,9.6 6.8,11.1 8,12 9.2,11.1 10,9.7 10,8 10,6.3 9.2,4.9 8,4 Z m 3,-1 c 2.8,0 5,2.2 5,5 0,2.8 -2.2,5 -5,5 C 10.4,13 9.9,12.9 9.4,12.7 10.7,11.6 11.5,9.8 11.5,8 11.5,6.2 10.7,4.5 9.4,3.3 9.9,3.1 10.4,3 11,3 Z m 0.35,1.02 c 0.73,1.15 1.14,2.52 1.14,3.98 0,1.46 -0.42,2.83 -1.14,3.98 2.04,-0.18 3.64,-1.9 3.64,-3.98 0,-2.08 -1.6,-3.8 -3.64,-3.98 z\",\n style: {\n strokeWidth: 0.234,\n strokeMiterlimit: 4,\n strokeDasharray: \"none\",\n strokeOpacity: 1\n }\n })));\n}\n\nvar ForwardRef = React.forwardRef(function (props, ref) {\n return /*#__PURE__*/React.createElement(SvgUnion, _extends({\n svgRef: ref\n }, props));\n});\nexport default __webpack_public_path__ + \"static/media/union.de5168c6.svg\";\nexport { ForwardRef as ReactComponent };","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nimport * as React from \"react\";\n\nfunction SvgIntersection(_ref) {\n var svgRef = _ref.svgRef,\n title = _ref.title,\n titleId = _ref.titleId,\n props = _objectWithoutProperties(_ref, [\"svgRef\", \"title\", \"titleId\"]);\n\n return /*#__PURE__*/React.createElement(\"svg\", _extends({\n width: 18,\n height: 12,\n viewBox: \"0 0 16 10\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, /*#__PURE__*/React.createElement(\"g\", {\n transform: \"translate(0,-3)\"\n }, /*#__PURE__*/React.createElement(\"path\", {\n d: \"M 5.0000001,3 C 2.2,3 0,5.2 0,8 c 0,2.8 2.2,5 5.0000001,5 0.6,0 1.1,-0.1 1.6,-0.3 C 5.3000001,11.6 4.5,9.7999998 4.5,8 4.5,6.2 5.3000001,4.5 6.6000001,3.3 c -0.5,-0.2 -1,-0.3 -1.6,-0.3 z M 4.65,4.02 C 3.92,5.17 3.51,6.54 3.51,8 c 0,1.4599998 0.42,2.83 1.14,3.98 C 2.61,11.8 1.01,10.08 1.01,8 1.01,5.92 2.61,4.2 4.65,4.02 Z M 8,4 C 6.8,4.9 6,6.4 6,8 6,9.6 6.8,11.1 8,12 9.2,11.1 10,9.7 10,8 10,6.3 9.2,4.9 8,4 Z m 3,-1 c 2.8,0 5,2.2 5,5 0,2.8 -2.2,5 -5,5 C 10.4,13 9.9,12.9 9.4,12.7 10.7,11.6 11.5,9.8 11.5,8 11.5,6.2 10.7,4.5 9.4,3.3 9.9,3.1 10.4,3 11,3 Z m 0.35,1.02 c 0.73,1.15 1.14,2.52 1.14,3.98 0,1.46 -0.42,2.83 -1.14,3.98 2.04,-0.18 3.64,-1.9 3.64,-3.98 0,-2.08 -1.6,-3.8 -3.64,-3.98 z\",\n style: {\n strokeWidth: 0.234,\n strokeMiterlimit: 4,\n strokeDasharray: \"none\",\n strokeOpacity: 1\n }\n })));\n}\n\nvar ForwardRef = React.forwardRef(function (props, ref) {\n return /*#__PURE__*/React.createElement(SvgIntersection, _extends({\n svgRef: ref\n }, props));\n});\nexport default __webpack_public_path__ + \"static/media/intersection.b0003109.svg\";\nexport { ForwardRef as ReactComponent };","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nimport * as React from \"react\";\n\nvar _ref2 = /*#__PURE__*/React.createElement(\"rect\", {\n x: \"5%\",\n width: \"90%\",\n height: \"100%\",\n fill: \"white\"\n});\n\nvar _ref3 = /*#__PURE__*/React.createElement(\"g\", null, /*#__PURE__*/React.createElement(\"rect\", {\n x: 0,\n y: 0,\n width: 25.3804963846,\n height: 16,\n mask: \"url(#union-mask)\"\n}));\n\nfunction SvgComplement(_ref) {\n var svgRef = _ref.svgRef,\n title = _ref.title,\n titleId = _ref.titleId,\n props = _objectWithoutProperties(_ref, [\"svgRef\", \"title\", \"titleId\"]);\n\n return /*#__PURE__*/React.createElement(\"svg\", _extends({\n id: \"svg14\",\n viewBox: \"0 0 25.3804963846 16\",\n height: 16,\n width: 25.3804963846,\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, /*#__PURE__*/React.createElement(\"defs\", null, /*#__PURE__*/React.createElement(\"mask\", {\n id: \"union-mask\",\n x: 0,\n y: 0,\n width: 25.3804963846,\n height: 16\n }, _ref2, /*#__PURE__*/React.createElement(\"g\", {\n transform: \"translate(4.69,0)\"\n }, /*#__PURE__*/React.createElement(\"path\", {\n d: \"m 11.467471,11.811278 c 0.198237,-0.322177 0.508,-1.011333 0.653661,-1.454255 0.659343,-2.0049141 0.44323,-4.2620847 -0.577734,-6.0340822 l -0.168844,-0.2930481 0.105744,0.017887 c 0.759902,0.1285441 1.368762,0.3699553 1.856675,0.7361658 1.988296,1.4923476 2.192477,4.3353549 0.434717,6.0529895 -0.641216,0.626581 -1.299647,0.94683 -2.294136,1.115833 l -0.108488,0.01844 z M 4.3162122,11.919169 C 1.9278944,11.487872 0.46692382,9.0323123 1.234873,6.7401372 1.5621727,5.763213 2.2610593,4.9489746 3.1840041,4.4693005 3.5978035,4.2542401 3.9427842,4.145371 4.5197023,4.0477802 L 4.6254464,4.0298927 4.4571836,4.3223069 C 3.4332707,6.1017061 3.2180432,8.3476022 3.878868,10.357023 c 0.1458466,0.443487 0.4554716,1.132155 0.6542959,1.455285 0.054471,0.08853 0.087814,0.159599 0.074096,0.157937 -0.013718,-0.0017 -0.1446898,-0.02465 -0.2910477,-0.05108 z M 5.0000001,3 C 2.2,3 0,5.2 0,8 c 0,2.8 2.2,5 5.0000001,5 0.6,0 1.1,-0.1 1.6,-0.3 C 5.3000001,11.6 4.5,9.7999998 4.5,8 4.5,6.2 5.3000001,4.5 6.6000001,3.3 c -0.5,-0.2 -1,-0.3 -1.6,-0.3 z M 4.65,4.02 C 3.92,5.17 3.51,6.54 3.51,8 c 0,1.4599998 0.42,2.83 1.14,3.98 C 2.61,11.8 1.01,10.08 1.01,8 1.01,5.92 2.61,4.2 4.65,4.02 Z M 8,4 C 6.8,4.9 6,6.4 6,8 6,9.6 6.8,11.1 8,12 9.2,11.1 10,9.7 10,8 10,6.3 9.2,4.9 8,4 Z m 3,-1 c 2.8,0 5,2.2 5,5 0,2.8 -2.2,5 -5,5 C 10.4,13 9.9,12.9 9.4,12.7 10.7,11.6 11.5,9.8 11.5,8 11.5,6.2 10.7,4.5 9.4,3.3 9.9,3.1 10.4,3 11,3 Z m 0.35,1.02 c 0.73,1.15 1.14,2.52 1.14,3.98 0,1.46 -0.42,2.83 -1.14,3.98 2.04,-0.18 3.64,-1.9 3.64,-3.98 0,-2.08 -1.6,-3.8 -3.64,-3.98 z\",\n style: {\n strokeWidth: 0.234,\n strokeMiterlimit: 4,\n strokeDasharray: \"none\",\n strokeOpacity: 1\n },\n fill: \"black\"\n })))), _ref3);\n}\n\nvar ForwardRef = React.forwardRef(function (props, ref) {\n return /*#__PURE__*/React.createElement(SvgComplement, _extends({\n svgRef: ref\n }, props));\n});\nexport default __webpack_public_path__ + \"static/media/complement.c220ca8c.svg\";\nexport { ForwardRef as ReactComponent };","import React, { useCallback } from 'react';\nimport PopoverMenu from './PopoverMenu';\nimport {\n handleImportJSON,\n handleImportTabular,\n} from './io';\nimport {\n MIME_TYPE_JSON,\n MIME_TYPE_TABULAR,\n} from './constants';\n\nimport { ReactComponent as SetUnionSVG } from '../../assets/sets/union.svg';\nimport { ReactComponent as SetIntersectionSVG } from '../../assets/sets/intersection.svg';\nimport { ReactComponent as SetComplementSVG } from '../../assets/sets/complement.svg';\n\n/**\n * A plus button for creating or importing set hierarchies.\n * @param {object} props\n * @param {string} props.datatype The data type to validate imported hierarchies against.\n * @param {function} props.onError A callback to pass error message strings.\n * @param {function} props.onImportTree A callback to pass successfully-validated tree objects.\n * @param {function} props.onCreateLevelZeroNode A callback to create a new empty\n * level zero node.\n * @param {boolean} props.importable Is importing allowed?\n * If not, the import button will not be rendered.\n * @param {boolean} props.editable Is editing allowed?\n * If not, the create button will not be rendered.\n */\nexport function PlusButton(props) {\n const {\n datatype, onError, onImportTree, onCreateLevelZeroNode,\n importable, editable,\n } = props;\n\n /**\n * Import a file, then process the imported data via the supplied handler function.\n * @param {Function} importHandler The function to process the imported data.\n * @param {string} mimeType The accepted mime type for the file upload input.\n * @returns {Function} An import function corresponding to the supplied parameters.\n */\n const onImport = useCallback((importHandler, mimeType) => () => {\n const uploadInputNode = document.createElement('input');\n uploadInputNode.setAttribute('type', 'file');\n uploadInputNode.setAttribute('accept', mimeType);\n document.body.appendChild(uploadInputNode); // required for firefox\n uploadInputNode.click();\n uploadInputNode.addEventListener('change', (event) => {\n if (!(window.File && window.FileReader && window.FileList && window.Blob)) {\n onError('Local file reading APIs are not fully supported in this browser.');\n return;\n }\n const { files } = event.target;\n if (!files || files.length !== 1) {\n onError('Incorrect number of files selected.');\n return;\n }\n const reader = new FileReader();\n reader.addEventListener('load', () => {\n const { result } = reader;\n try {\n const treeToImport = importHandler(result, datatype);\n onError(false); // Clear any previous import error.\n onImportTree(treeToImport);\n } catch (e) {\n onError(e.message);\n }\n }, false);\n reader.readAsText(files[0]);\n });\n uploadInputNode.remove();\n }, [datatype, onError, onImportTree]);\n\n const menuConfig = [\n ...(editable ? [\n {\n title: 'Create hierarchy',\n handler: onCreateLevelZeroNode,\n handlerKey: 'n',\n },\n ] : []),\n ...(importable ? [\n {\n title: 'Import hierarchy',\n subtitle: '(from CSV file)',\n handler: onImport(handleImportTabular, MIME_TYPE_TABULAR),\n handlerKey: 'c',\n },\n {\n title: 'Import hierarchy',\n subtitle: '(from JSON file)',\n handler: onImport(handleImportJSON, MIME_TYPE_JSON),\n handlerKey: 'j',\n },\n ] : []),\n ];\n\n return (menuConfig.length > 0 ? (\n \n \n \n ) : null);\n}\n\n/**\n * Set operations buttons (union, intersection, complement)\n * and a view checked sets button.\n * @param {object} props\n * @param {function} props.onUnion A callback for the union button.\n * @param {function} props.onIntersection A callback for the intersection button.\n * @param {function} props.onComplement A callback for the complement button.\n * @param {boolean} props.operatable Are set operations allowed?\n * If not, the union, intersection, and complement buttons will not be rendered.\n */\nexport function SetOperationButtons(props) {\n const {\n onUnion,\n onIntersection,\n onComplement,\n operatable,\n hasCheckedSetsToUnion,\n hasCheckedSetsToIntersect,\n hasCheckedSetsToComplement,\n } = props;\n\n return (\n <>\n {operatable && (\n <>\n \n \n \n \n \n \n \n \n \n \n )}\n \n );\n}\n","/* eslint-disable no-underscore-dangle */\nimport React, { useState, useMemo } from 'react';\nimport isEqual from 'lodash/isEqual';\nimport Tree from './Tree';\nimport TreeNode from './TreeNode';\nimport { PlusButton, SetOperationButtons } from './SetsManagerButtons';\nimport { nodeToRenderProps } from './cell-set-utils';\nimport { getDefaultColor } from '../utils';\nimport { pathToKey } from './utils';\n\nfunction processNode(node, prevPath, setColor, theme) {\n const nodePath = [...prevPath, node.name];\n return {\n ...node,\n ...(node.children ? ({\n children: node.children\n .map(c => processNode(c, nodePath, setColor)),\n }) : {}),\n color: setColor?.find(d => isEqual(d.path, nodePath))?.color || getDefaultColor(theme),\n };\n}\n\nfunction processSets(sets, setColor, theme) {\n return {\n ...sets,\n tree: sets ? sets.tree.map(lzn => processNode(lzn, [], setColor, theme)) : [],\n };\n}\n\nfunction getAllKeys(node, path = []) {\n if (!node) {\n return null;\n }\n const newPath = [...path, node.name];\n if (node.children) {\n return [pathToKey(newPath), ...node.children.flatMap(v => getAllKeys(v, newPath))];\n }\n return pathToKey(newPath);\n}\n\n/**\n * A generic hierarchical set manager component.\n * @prop {object} tree An object representing set hierarchies.\n * @prop {string} datatype The data type for sets (e.g. \"cell\")\n * @prop {function} clearPleaseWait A callback to signal that loading is complete.\n * @prop {boolean} draggable Whether tree nodes can be rearranged via drag-and-drop.\n * By default, true.\n * @prop {boolean} checkable Whether to show the \"Check\" menu button\n * and checkboxes for selecting multiple sets. By default, true.\n * @prop {boolean} editable Whether to show rename, delete, color, or create options.\n * By default, true.\n * @prop {boolean} expandable Whether to allow hierarchies to be expanded\n * to show the list or tree of sets contained. By default, true.\n * @prop {boolean} operatable Whether to enable union, intersection,\n * and complement operations on checked sets. By default, true.\n * @prop {boolean} exportable Whether to enable exporting hierarchies and sets to files.\n * By default, true.\n * @prop {boolean} importable Whether to enable importing hierarchies from files.\n * By default, true.\n * @prop {function} onError Function to call with error messages (failed import validation, etc).\n * @prop {function} onCheckNode Function to call when a single node has been checked or un-checked.\n * @prop {function} onExpandNode Function to call when a node has been expanded.\n * @prop {function} onDropNode Function to call when a node has been dragged-and-dropped.\n * @prop {function} onCheckLevel Function to call when an entire hierarchy level has been selected,\n * via the \"Color by cluster\" and \"Color by subcluster\" buttons below collapsed level zero nodes.\n * @prop {function} onNodeSetColor Function to call when a new node color has been selected.\n * @prop {function} onNodeSetName Function to call when a node has been renamed.\n * @prop {function} onNodeRemove Function to call when the user clicks the \"Delete\" menu button\n * to remove a node.\n * @prop {function} onNodeView Function to call when the user wants to view the set associated\n * with a particular node.\n * @prop {function} onImportTree Function to call when a tree has been imported\n * using the \"plus\" button.\n * @prop {function} onCreateLevelZeroNode Function to call when a user clicks the \"Create hierarchy\"\n * menu option using the \"plus\" button.\n * @prop {function} onExportLevelZeroNode Function to call when a user wants to\n * export an entire hierarchy via the \"Export hierarchy\" menu button for a\n * particular level zero node.\n * @prop {function} onExportSet Function to call when a user wants to export a set associated with\n * a particular node via the \"Export set\" menu button.\n * @prop {function} onUnion Function to call when a user wants to create a new set from the union\n * of the sets associated with the currently-checked nodes.\n * @prop {function} onIntersection Function to call when a user wants to create a new set from the\n * intersection of the sets associated with the currently-checked nodes.\n * @prop {function} onComplement Function to call when a user wants to create a new set from the\n * complement of the (union of the) sets associated with the currently-checked nodes.\n * @prop {function} onView Function to call when a user wants to view the sets\n * associated with the currently-checked nodes.\n * @prop {string} theme \"light\" or \"dark\" for the vitessce theme\n */\nexport default function SetsManager(props) {\n const {\n theme,\n sets,\n additionalSets,\n setColor, // TODO: use this\n levelSelection: checkedLevel,\n setSelection,\n setExpansion,\n hasColorEncoding,\n datatype,\n draggable = true,\n checkable = true,\n editable = true,\n expandable = true,\n operatable = true,\n exportable = true,\n importable = true,\n onError,\n onCheckNode,\n onExpandNode,\n onDropNode,\n onCheckLevel,\n onNodeSetColor,\n onNodeSetName,\n onNodeCheckNewName,\n onNodeRemove,\n onNodeView,\n onImportTree,\n onCreateLevelZeroNode,\n onExportLevelZeroNodeJSON,\n onExportLevelZeroNodeTabular,\n onExportSetJSON,\n onUnion,\n onIntersection,\n onComplement,\n hasCheckedSetsToUnion,\n hasCheckedSetsToIntersect,\n hasCheckedSetsToComplement,\n } = props;\n\n const isChecking = true;\n const autoExpandParent = true;\n const [isDragging, setIsDragging] = useState(false);\n const [isEditingNodeName, setIsEditingNodeName] = useState(null);\n\n const processedSets = useMemo(() => processSets(\n sets, setColor, theme,\n ), [sets, setColor, theme]);\n const processedAdditionalSets = useMemo(() => processSets(\n additionalSets, setColor, theme,\n ), [additionalSets, setColor, theme]);\n\n const additionalSetKeys = (processedAdditionalSets\n ? processedAdditionalSets.tree.flatMap(v => getAllKeys(v, []))\n : []\n );\n\n const allSetSelectionKeys = (setSelection || []).map(pathToKey);\n const allSetExpansionKeys = (setExpansion || []).map(pathToKey);\n\n const setSelectionKeys = allSetSelectionKeys.filter(k => !additionalSetKeys.includes(k));\n const setExpansionKeys = allSetExpansionKeys.filter(k => !additionalSetKeys.includes(k));\n\n const additionalSetSelectionKeys = allSetSelectionKeys.filter(k => additionalSetKeys.includes(k));\n const additionalSetExpansionKeys = allSetExpansionKeys.filter(k => additionalSetKeys.includes(k));\n\n /**\n * Recursively render TreeNode components.\n * @param {object[]} nodes An array of node objects.\n * @returns {TreeNode[]|null} Array of TreeNode components or null.\n */\n function renderTreeNodes(nodes, readOnly, currPath) {\n if (!nodes) {\n return null;\n }\n return nodes.map((node) => {\n const newPath = [...currPath, node.name];\n return (\n {\n onNodeSetName(targetPath, name);\n setIsEditingNodeName(null);\n }}\n onNodeCheckNewName={onNodeCheckNewName}\n onNodeSetIsEditing={setIsEditingNodeName}\n onNodeRemove={onNodeRemove}\n onExportLevelZeroNodeJSON={onExportLevelZeroNodeJSON}\n onExportLevelZeroNodeTabular={onExportLevelZeroNodeTabular}\n onExportSetJSON={onExportSetJSON}\n\n disableTooltip={isDragging}\n onDragStart={() => setIsDragging(true)}\n onDragEnd={() => setIsDragging(false)}\n >\n {renderTreeNodes(node.children, readOnly, newPath, theme)}\n \n );\n });\n }\n\n return (\n
\n
\n onCheckNode(\n info.node.props.nodeKey,\n info.checked,\n )}\n onExpand={(expandedKeys, info) => onExpandNode(\n expandedKeys,\n info.node.props.nodeKey,\n info.expanded,\n )}\n >\n {renderTreeNodes(processedSets.tree, true, [], theme)}\n \n onCheckNode(\n info.node.props.nodeKey,\n info.checked,\n )}\n onExpand={(expandedKeys, info) => onExpandNode(\n expandedKeys,\n info.node.props.nodeKey,\n info.expanded,\n )}\n onDrop={(info) => {\n const { eventKey: dropKey } = info.node.props;\n const { eventKey: dragKey } = info.dragNode.props;\n const { dropToGap, dropPosition } = info;\n onDropNode(dropKey, dragKey, dropPosition, dropToGap);\n }}\n >\n {renderTreeNodes(processedAdditionalSets.tree, false, [], theme)}\n \n\n \n
\n {isChecking ? (\n
\n \n
\n ) : null}\n
\n );\n}\n","import React, {\n useEffect,\n useState,\n useMemo,\n} from 'react';\nimport isEqual from 'lodash/isEqual';\nimport packageJson from '../../../package.json';\nimport {\n useCoordination,\n useLoaders,\n useSetWarning,\n} from '../../app/state/hooks';\nimport { COMPONENT_COORDINATION_TYPES } from '../../app/state/coordination';\nimport SetsManager from './SetsManager';\nimport TitleInfo from '../TitleInfo';\nimport {\n treeExportLevelZeroNode,\n treeExportSet,\n treeToExpectedCheckedLevel,\n nodeToLevelDescendantNamePaths,\n treeToIntersection,\n treeToUnion,\n treeToComplement,\n treeFindNodeByNamePath,\n treesConflict,\n nodeTransform,\n nodeAppendChild,\n nodePrependChild,\n nodeInsertChild,\n filterNode,\n treeInitialize,\n initializeCellSetColor,\n} from './cell-set-utils';\nimport {\n isEqualOrPrefix,\n tryRenamePath,\n PATH_SEP,\n} from './utils';\nimport {\n downloadForUser,\n handleExportJSON,\n handleExportTabular,\n tryUpgradeTreeToLatestSchema,\n} from './io';\nimport {\n FILE_EXTENSION_JSON,\n FILE_EXTENSION_TABULAR,\n SETS_DATATYPE_CELL,\n} from './constants';\nimport { useUrls, useReady } from '../hooks';\nimport {\n setCellSelection,\n mergeCellSets,\n getNextNumberedNodeName,\n} from '../utils';\nimport { useCellsData, useCellSetsData } from '../data-hooks';\n\nconst CELL_SETS_DATA_TYPES = ['cells', 'cell-sets'];\n\n/**\n * A subscriber wrapper around the SetsManager component\n * for the 'cell' datatype.\n * @param {object} props\n * @param {string} props.theme The current theme name.\n * @param {object} props.coordinationScopes The mapping from coordination types to coordination\n * scopes.\n * @param {function} props.removeGridComponent The callback function to pass to TitleInfo,\n * to call when the component has been removed from the grid.\n * @param {string} props.title The component title.\n */\nexport default function CellSetsManagerSubscriber(props) {\n const {\n coordinationScopes,\n removeGridComponent,\n theme,\n title = 'Cell Sets',\n } = props;\n\n const loaders = useLoaders();\n const setWarning = useSetWarning();\n\n // Get \"props\" from the coordination space.\n const [{\n dataset,\n cellSetSelection,\n cellSetColor,\n additionalCellSets,\n cellColorEncoding,\n }, {\n setCellSetSelection,\n setCellColorEncoding,\n setCellSetColor,\n setAdditionalCellSets,\n }] = useCoordination(COMPONENT_COORDINATION_TYPES.cellSets, coordinationScopes);\n\n const [urls, addUrl, resetUrls] = useUrls();\n const [\n isReady,\n setItemIsReady,\n setItemIsNotReady, // eslint-disable-line no-unused-vars\n resetReadyItems,\n ] = useReady(\n CELL_SETS_DATA_TYPES,\n );\n\n const [cellSetExpansion, setCellSetExpansion] = useState([]);\n\n // Reset file URLs and loader progress when the dataset has changed.\n useEffect(() => {\n resetUrls();\n resetReadyItems();\n setCellSetExpansion([]);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loaders, dataset]);\n\n // Get data from loaders using the data hooks.\n const [cells] = useCellsData(loaders, dataset, setItemIsReady, addUrl, true);\n const [cellSets] = useCellSetsData(\n loaders, dataset, setItemIsReady, addUrl, true,\n { setCellSetSelection, setCellSetColor },\n { cellSetSelection, cellSetColor },\n );\n\n // Validate and upgrade the additionalCellSets.\n useEffect(() => {\n if (additionalCellSets) {\n let upgradedCellSets;\n try {\n upgradedCellSets = tryUpgradeTreeToLatestSchema(additionalCellSets, SETS_DATATYPE_CELL);\n } catch (e) {\n setWarning(e.message);\n return;\n }\n setAdditionalCellSets(upgradedCellSets);\n }\n }, [additionalCellSets, setAdditionalCellSets, setWarning]);\n\n // Get an array of all cell IDs to use for set complement operations.\n const allCellIds = useMemo(() => (cells ? Object.keys(cells) : []), [cells]);\n\n // A helper function for updating the encoding for cell colors,\n // which may have previously been set to 'geneSelection'.\n function setCellSetColorEncoding() {\n setCellColorEncoding('cellSetSelection');\n }\n\n // Merged cell sets are only to be used for convenience when reading\n // (if writing: update either `cellSets` _or_ `additionalCellSets`).\n const mergedCellSets = useMemo(\n () => mergeCellSets(cellSets, additionalCellSets),\n [cellSets, additionalCellSets],\n );\n\n // Infer the state of the \"checked level\" radio button based on the selected cell sets.\n const checkedLevel = useMemo(() => {\n if (cellSetSelection && cellSetSelection.length > 0\n && mergedCellSets && mergedCellSets.tree.length > 0) {\n return treeToExpectedCheckedLevel(mergedCellSets, cellSetSelection);\n }\n return null;\n }, [cellSetSelection, mergedCellSets]);\n\n // Callback functions\n\n // The user wants to select all nodes at a particular hierarchy level.\n function onCheckLevel(levelZeroName, levelIndex) {\n const lzn = mergedCellSets.tree.find(n => n.name === levelZeroName);\n if (lzn) {\n const newCellSetSelection = nodeToLevelDescendantNamePaths(lzn, levelIndex, [], true);\n setCellSetSelection(newCellSetSelection);\n setCellSetColorEncoding();\n }\n }\n\n // The user wants to check or uncheck a cell set node.\n function onCheckNode(targetKey, checked) {\n const targetPath = (Array.isArray(targetKey) ? targetKey : targetKey.split(PATH_SEP));\n if (!targetKey) {\n return;\n }\n if (checked) {\n setCellSetSelection([...cellSetSelection, targetPath]);\n } else {\n setCellSetSelection(cellSetSelection.filter(d => !isEqual(d, targetPath)));\n }\n setCellSetColorEncoding();\n }\n\n // The user wants to expand or collapse a node in the tree.\n function onExpandNode(expandedKeys, targetKey, expanded) {\n if (expanded) {\n setCellSetExpansion(prev => ([...prev, targetKey.split(PATH_SEP)]));\n } else {\n setCellSetExpansion(prev => prev.filter(d => !isEqual(d, targetKey.split(PATH_SEP))));\n }\n }\n\n // The user dragged a tree node and dropped it somewhere else in the tree\n // to re-arrange or re-order the nodes.\n // We need to verify that their drop target is valid, and if so, complete\n // the tree re-arrangement.\n function onDropNode(dropKey, dragKey, dropPosition, dropToGap) {\n const dropPath = dropKey.split(PATH_SEP);\n const dropNode = treeFindNodeByNamePath(additionalCellSets, dropPath);\n if (!dropNode.children && !dropToGap) {\n // Do not allow a node with a set (i.e. leaf) to become a child of another node with a set,\n // as this will result in an internal node having a set, which we do not allow.\n return;\n }\n const dropNodeLevel = dropPath.length - 1;\n const dropNodeIsLevelZero = dropNodeLevel === 0;\n\n // Get drag node.\n const dragPath = dragKey.split(PATH_SEP);\n const dragNode = treeFindNodeByNamePath(additionalCellSets, dragPath);\n\n if (dropNodeIsLevelZero && dropToGap && !dragNode.children) {\n // Do not allow a leaf node to become a level zero node.\n return;\n }\n\n let dropParentNode;\n let dropParentPath;\n let dropNodeCurrIndex;\n if (!dropNodeIsLevelZero) {\n dropParentPath = dropPath.slice(0, -1);\n dropParentNode = treeFindNodeByNamePath(additionalCellSets, dropParentPath);\n dropNodeCurrIndex = dropParentNode.children.findIndex(c => c.name === dropNode.name);\n } else {\n dropNodeCurrIndex = additionalCellSets.tree.findIndex(\n lzn => lzn.name === dropNode.name,\n );\n }\n // Further, only allow dragging if the dragged node will have a unique\n // name among its new siblings.\n let hasSiblingNameConflict;\n const dragNodeName = dragNode.name;\n if (!dropNodeIsLevelZero && dropToGap) {\n hasSiblingNameConflict = dropParentNode.children\n .find(c => c !== dragNode && c.name === dragNodeName);\n } else if (!dropToGap) {\n hasSiblingNameConflict = dropNode.children\n .find(c => c !== dragNode && c.name === dragNodeName);\n } else {\n hasSiblingNameConflict = additionalCellSets.tree\n .find(lzn => lzn !== dragNode && lzn.name === dragNodeName);\n }\n\n if (hasSiblingNameConflict) {\n return;\n }\n\n // Remove the dragged object from its current position.\n // Recursively check whether each node path\n // matches the path of the node to delete.\n // If so, return null, and then always use\n // .filter(Boolean) to eliminate any null array elements.\n const nextAdditionalCellSets = {\n ...additionalCellSets,\n tree: additionalCellSets.tree.map(lzn => filterNode(lzn, [], dragPath)).filter(Boolean),\n };\n\n // Update index values after temporarily removing the dragged node.\n // Names are unique as children of their parents.\n if (!dropNodeIsLevelZero) {\n dropNodeCurrIndex = dropParentNode.children.findIndex(c => c.name === dropNode.name);\n } else {\n dropNodeCurrIndex = nextAdditionalCellSets.tree.findIndex(\n lzn => lzn.name === dropNode.name,\n );\n }\n let newDragPath = [];\n if (!dropToGap || !dropNodeIsLevelZero) {\n let addChildFunction;\n let checkPathFunction;\n const newPath = [];\n if (!dropToGap) {\n // Append the dragNode to dropNode's children if dropping _onto_ the dropNode.\n // Set dragNode as the last child of dropNode.\n addChildFunction = n => nodeAppendChild(n, dragNode);\n checkPathFunction = path => isEqual(path, dropPath);\n } else if (!dropNodeIsLevelZero) {\n // Prepend or insert the dragNode if dropping _between_ (above or below dropNode).\n // The dropNode is at a level greater than zero,\n // so it has a parent.\n checkPathFunction = path => isEqual(path, dropParentPath);\n if (dropPosition === -1) {\n // Set dragNode as first child of dropParentNode.\n addChildFunction = n => nodePrependChild(n, dragNode);\n } else {\n // Set dragNode before or after dropNode.\n const insertIndex = dropNodeCurrIndex + (dropPosition > dropNodeCurrIndex ? 1 : 0);\n addChildFunction = n => nodeInsertChild(n, dragNode, insertIndex);\n }\n }\n nextAdditionalCellSets.tree = nextAdditionalCellSets.tree.map(\n node => nodeTransform(\n node,\n (n, path) => checkPathFunction(path),\n (n) => {\n const newNode = addChildFunction(n);\n return newNode;\n },\n newPath,\n ),\n );\n // Done\n setAdditionalCellSets(nextAdditionalCellSets);\n newDragPath = [...newPath[0], dragNode.name];\n setCellSetSelection([newDragPath]);\n } else if (dropPosition === -1) {\n // We need to drop the dragNode to level zero,\n // and level zero nodes do not have parents.\n // Set dragNode as first level zero node of the tree.\n nextAdditionalCellSets.tree.unshift(dragNode);\n setAdditionalCellSets(nextAdditionalCellSets);\n newDragPath = [dragNode.name];\n setCellSetSelection([newDragPath]);\n } else {\n // Set dragNode before or after dropNode in level zero.\n const insertIndex = dropNodeCurrIndex + (dropPosition > dropNodeCurrIndex ? 1 : 0);\n const newLevelZero = Array.from(nextAdditionalCellSets.tree);\n newLevelZero.splice(insertIndex, 0, dragNode);\n nextAdditionalCellSets.tree = newLevelZero;\n setAdditionalCellSets(nextAdditionalCellSets);\n newDragPath = [dragNode.name];\n setCellSetSelection([newDragPath]);\n }\n const oldColors = cellSetColor.filter(\n i => isEqualOrPrefix(dragPath, i.path),\n );\n const newColors = oldColors.map(\n i => (\n {\n ...i,\n path: !isEqual(i.path, dragPath)\n ? newDragPath.concat(i.path.slice(dragPath.length))\n : newDragPath,\n }\n ),\n );\n const newCellSetColor = cellSetColor.filter(\n i => !isEqualOrPrefix(dragPath, i.path),\n );\n newCellSetColor.push(...newColors);\n setCellSetColor(newCellSetColor);\n }\n\n // The user wants to change the color of a cell set node.\n function onNodeSetColor(targetPath, color) {\n // Replace the color if an array element for this path already exists.\n const prevNodeColor = cellSetColor?.find(d => isEqual(d.path, targetPath));\n if (!prevNodeColor) {\n setCellSetColor([\n ...(cellSetColor || []),\n {\n path: targetPath,\n color,\n },\n ]);\n } else {\n setCellSetColor([\n ...cellSetColor.filter(d => !isEqual(d.path, targetPath)),\n {\n path: targetPath,\n color,\n },\n ]);\n }\n }\n\n // The user wants to change the name of a cell set node.\n function onNodeSetName(targetPath, name) {\n const nextNamePath = [...targetPath];\n nextNamePath.pop();\n nextNamePath.push(name);\n\n // Recursively check whether each node path\n // matches the path or a prefix of the path of the node to rename.\n // If so, rename the node using the new path.\n function renameNode(node, prevPath) {\n if (isEqual([...prevPath, node.name], targetPath)) {\n return {\n ...node,\n name,\n };\n }\n if (!node.children) {\n return node;\n }\n return {\n ...node,\n children: node.children.map(c => renameNode(c, [...prevPath, node.name])),\n };\n }\n const nextAdditionalCellSets = {\n ...additionalCellSets,\n tree: additionalCellSets.tree.map(lzn => renameNode(lzn, [])),\n };\n // Change all paths that have this node as a prefix (i.e. descendants).\n const nextCellSetColor = cellSetColor.map(d => ({\n path: tryRenamePath(targetPath, d.path, nextNamePath),\n color: d.color,\n }));\n const nextCellSetSelection = cellSetSelection.map(d => (\n tryRenamePath(targetPath, d, nextNamePath)\n ));\n const nextCellSetExpansion = cellSetExpansion.map(d => (\n tryRenamePath(targetPath, d, nextNamePath)\n ));\n // Need to update the node path everywhere it may be present.\n setAdditionalCellSets(nextAdditionalCellSets);\n setCellSetColor(nextCellSetColor);\n setCellSetSelection(nextCellSetSelection);\n setCellSetExpansion(nextCellSetExpansion);\n }\n\n // Each time the user types while renaming a cell set node,\n // we need to check whether the potential new name conflicts\n // with any existing cell set node names.\n // If there are conflicts, we want to disable the \"Save\" button.\n function onNodeCheckNewName(targetPath, name) {\n const nextNamePath = [...targetPath];\n nextNamePath.pop();\n nextNamePath.push(name);\n const hasConflicts = (\n !isEqual(targetPath, nextNamePath)\n && treeFindNodeByNamePath(additionalCellSets, nextNamePath)\n );\n return hasConflicts;\n }\n\n // The user wants to delete a cell set node, and has confirmed their choice.\n function onNodeRemove(targetPath) {\n // Recursively check whether each node path\n // matches the path of the node to delete.\n // If so, return null, and then always use\n // .filter(Boolean) to eliminate any null array elements.\n const nextAdditionalCellSets = {\n ...additionalCellSets,\n tree: additionalCellSets.tree.map(lzn => filterNode(lzn, [], targetPath)).filter(Boolean),\n };\n // Delete state for all paths that have this node\n // path as a prefix (i.e. delete all descendents).\n const nextCellSetColor = cellSetColor.filter(d => !isEqualOrPrefix(targetPath, d.path));\n const nextCellSetSelection = cellSetSelection.filter(d => !isEqualOrPrefix(targetPath, d));\n const nextCellSetExpansion = cellSetExpansion.filter(d => !isEqualOrPrefix(targetPath, d));\n setAdditionalCellSets(nextAdditionalCellSets);\n setCellSetColor(nextCellSetColor);\n setCellSetSelection(nextCellSetSelection);\n setCellSetExpansion(nextCellSetExpansion);\n }\n\n // The user wants to view (i.e. select) a particular node,\n // or its expanded descendents.\n function onNodeView(targetPath) {\n // If parent node is clicked, and if it is expanded,\n // then select the expanded descendent nodes.\n const setsToView = [];\n // Recursively determine which descendent nodes are currently expanded.\n function viewNode(node, nodePath) {\n if (cellSetExpansion.find(expandedPath => isEqual(nodePath, expandedPath))) {\n if (node.children) {\n node.children.forEach((c) => {\n viewNode(c, [...nodePath, c.name]);\n });\n } else {\n setsToView.push(nodePath);\n }\n } else {\n setsToView.push(nodePath);\n }\n }\n const targetNode = treeFindNodeByNamePath(mergedCellSets, targetPath);\n viewNode(targetNode, targetPath);\n setCellSetSelection(setsToView);\n setCellSetColorEncoding();\n }\n\n // The user wants to create a new level zero node.\n function onCreateLevelZeroNode() {\n const nextName = getNextNumberedNodeName(additionalCellSets?.tree, 'My hierarchy ');\n setAdditionalCellSets({\n ...(additionalCellSets || treeInitialize(SETS_DATATYPE_CELL)),\n tree: [\n ...(additionalCellSets ? additionalCellSets.tree : []),\n {\n name: nextName,\n children: [],\n },\n ],\n });\n }\n\n // The user wants to create a new node corresponding to\n // the union of the selected sets.\n function onUnion() {\n const newSet = treeToUnion(mergedCellSets, cellSetSelection);\n setCellSelection(\n newSet, additionalCellSets, cellSetColor,\n setCellSetSelection, setAdditionalCellSets, setCellSetColor,\n setCellColorEncoding,\n 'Union ',\n );\n }\n\n // The user wants to create a new node corresponding to\n // the intersection of the selected sets.\n function onIntersection() {\n const newSet = treeToIntersection(mergedCellSets, cellSetSelection);\n setCellSelection(\n newSet, additionalCellSets, cellSetColor,\n setCellSetSelection, setAdditionalCellSets, setCellSetColor,\n setCellColorEncoding,\n 'Intersection ',\n );\n }\n\n // The user wants to create a new node corresponding to\n // the complement of the selected sets.\n function onComplement() {\n const newSet = treeToComplement(mergedCellSets, cellSetSelection, allCellIds);\n setCellSelection(\n newSet, additionalCellSets, cellSetColor,\n setCellSetSelection, setAdditionalCellSets, setCellSetColor,\n setCellColorEncoding,\n 'Complement ',\n );\n }\n\n // The user wants to import a cell set hierarchy,\n // probably from a CSV or JSON file.\n function onImportTree(treeToImport) {\n // Check for any naming conflicts with the current sets\n // (both user-defined and dataset-defined) before importing.\n const hasConflict = treesConflict(mergedCellSets, treeToImport);\n if (!hasConflict) {\n setAdditionalCellSets({\n ...(additionalCellSets || treeInitialize(SETS_DATATYPE_CELL)),\n tree: [\n ...(additionalCellSets ? additionalCellSets.tree : []),\n ...treeToImport.tree,\n ],\n });\n // Automatically initialize set colors for the imported sets.\n const importAutoSetColors = initializeCellSetColor(treeToImport, cellSetColor);\n setCellSetColor([\n ...cellSetColor,\n ...importAutoSetColors,\n ]);\n }\n }\n\n // The user wants to download a particular hierarchy to a JSON file.\n function onExportLevelZeroNodeJSON(nodePath) {\n const {\n treeToExport, nodeName,\n } = treeExportLevelZeroNode(mergedCellSets, nodePath, SETS_DATATYPE_CELL, cellSetColor, theme);\n downloadForUser(\n handleExportJSON(treeToExport),\n `${nodeName}_${packageJson.name}-${SETS_DATATYPE_CELL}-hierarchy.${FILE_EXTENSION_JSON}`,\n );\n }\n\n // The user wants to download a particular hierarchy to a CSV file.\n function onExportLevelZeroNodeTabular(nodePath) {\n const {\n treeToExport, nodeName,\n } = treeExportLevelZeroNode(mergedCellSets, nodePath, SETS_DATATYPE_CELL, cellSetColor, theme);\n downloadForUser(\n handleExportTabular(treeToExport),\n `${nodeName}_${packageJson.name}-${SETS_DATATYPE_CELL}-hierarchy.${FILE_EXTENSION_TABULAR}`,\n );\n }\n\n // The user wants to download a particular set to a JSON file.\n function onExportSetJSON(nodePath) {\n const { setToExport, nodeName } = treeExportSet(mergedCellSets, nodePath);\n downloadForUser(\n handleExportJSON(setToExport),\n `${nodeName}_${packageJson.name}-${SETS_DATATYPE_CELL}-set.${FILE_EXTENSION_JSON}`,\n FILE_EXTENSION_JSON,\n );\n }\n return (\n \n 1}\n hasCheckedSetsToIntersect={cellSetSelection?.length > 1}\n hasCheckedSetsToComplement={cellSetSelection?.length > 0}\n theme={theme}\n />\n \n );\n}\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-param-reassign */\nimport { treeToCellColorsBySetNames } from './sets/cell-set-utils';\n\n// The functions defined here have been adapted from d3-interpolate,\n// d3-color, and d3-scale-chromatic.\n// Color string \"rgb(r,g,b)\" representations are replaced by color array [r, g, b]\n// representations, to allow them to work nicely with deck.gl,\n// without the need to converting back and forth between string and array formats.\n\n// Reference: https://github.com/d3/d3-scale-chromatic/blob/431d21da776f97c632f53a855bd822edfbbcd56e/src/diverging/RdBu.js\n// eslint-disable-next-line max-len\nconst schemeRdBu = [[103, 0, 31], [178, 24, 43], [214, 96, 77], [244, 165, 130], [253, 219, 199], [247, 247, 247], [209, 229, 240], [146, 197, 222], [67, 147, 195], [33, 102, 172], [5, 48, 97]];\n// eslint-disable-next-line max-len\nconst schemePlasma = [[13, 8, 135], [16, 7, 136], [19, 7, 137], [22, 7, 138], [25, 6, 140], [27, 6, 141], [29, 6, 142], [32, 6, 143], [34, 6, 144], [36, 6, 145], [38, 5, 145], [40, 5, 146], [42, 5, 147], [44, 5, 148], [46, 5, 149], [47, 5, 150], [49, 5, 151], [51, 5, 151], [53, 4, 152], [55, 4, 153], [56, 4, 154], [58, 4, 154], [60, 4, 155], [62, 4, 156], [63, 4, 156], [65, 4, 157], [67, 3, 158], [68, 3, 158], [70, 3, 159], [72, 3, 159], [73, 3, 160], [75, 3, 161], [76, 2, 161], [78, 2, 162], [80, 2, 162], [81, 2, 163], [83, 2, 163], [85, 2, 164], [86, 1, 164], [88, 1, 164], [89, 1, 165], [91, 1, 165], [92, 1, 166], [94, 1, 166], [96, 1, 166], [97, 0, 167], [99, 0, 167], [100, 0, 167], [102, 0, 167], [103, 0, 168], [105, 0, 168], [106, 0, 168], [108, 0, 168], [110, 0, 168], [111, 0, 168], [113, 0, 168], [114, 1, 168], [116, 1, 168], [117, 1, 168], [119, 1, 168], [120, 1, 168], [122, 2, 168], [123, 2, 168], [125, 3, 168], [126, 3, 168], [128, 4, 168], [129, 4, 167], [131, 5, 167], [132, 5, 167], [134, 6, 166], [135, 7, 166], [136, 8, 166], [138, 9, 165], [139, 10, 165], [141, 11, 165], [142, 12, 164], [143, 13, 164], [145, 14, 163], [146, 15, 163], [148, 16, 162], [149, 17, 161], [150, 19, 161], [152, 20, 160], [153, 21, 159], [154, 22, 159], [156, 23, 158], [157, 24, 157], [158, 25, 157], [160, 26, 156], [161, 27, 155], [162, 29, 154], [163, 30, 154], [165, 31, 153], [166, 32, 152], [167, 33, 151], [168, 34, 150], [170, 35, 149], [171, 36, 148], [172, 38, 148], [173, 39, 147], [174, 40, 146], [176, 41, 145], [177, 42, 144], [178, 43, 143], [179, 44, 142], [180, 46, 141], [181, 47, 140], [182, 48, 139], [183, 49, 138], [184, 50, 137], [186, 51, 136], [187, 52, 136], [188, 53, 135], [189, 55, 134], [190, 56, 133], [191, 57, 132], [192, 58, 131], [193, 59, 130], [194, 60, 129], [195, 61, 128], [196, 62, 127], [197, 64, 126], [198, 65, 125], [199, 66, 124], [200, 67, 123], [201, 68, 122], [202, 69, 122], [203, 70, 121], [204, 71, 120], [204, 73, 119], [205, 74, 118], [206, 75, 117], [207, 76, 116], [208, 77, 115], [209, 78, 114], [210, 79, 113], [211, 81, 113], [212, 82, 112], [213, 83, 111], [213, 84, 110], [214, 85, 109], [215, 86, 108], [216, 87, 107], [217, 88, 106], [218, 90, 106], [218, 91, 105], [219, 92, 104], [220, 93, 103], [221, 94, 102], [222, 95, 101], [222, 97, 100], [223, 98, 99], [224, 99, 99], [225, 100, 98], [226, 101, 97], [226, 102, 96], [227, 104, 95], [228, 105, 94], [229, 106, 93], [229, 107, 93], [230, 108, 92], [231, 110, 91], [231, 111, 90], [232, 112, 89], [233, 113, 88], [233, 114, 87], [234, 116, 87], [235, 117, 86], [235, 118, 85], [236, 119, 84], [237, 121, 83], [237, 122, 82], [238, 123, 81], [239, 124, 81], [239, 126, 80], [240, 127, 79], [240, 128, 78], [241, 129, 77], [241, 131, 76], [242, 132, 75], [243, 133, 75], [243, 135, 74], [244, 136, 73], [244, 137, 72], [245, 139, 71], [245, 140, 70], [246, 141, 69], [246, 143, 68], [247, 144, 68], [247, 145, 67], [247, 147, 66], [248, 148, 65], [248, 149, 64], [249, 151, 63], [249, 152, 62], [249, 154, 62], [250, 155, 61], [250, 156, 60], [250, 158, 59], [251, 159, 58], [251, 161, 57], [251, 162, 56], [252, 163, 56], [252, 165, 55], [252, 166, 54], [252, 168, 53], [252, 169, 52], [253, 171, 51], [253, 172, 51], [253, 174, 50], [253, 175, 49], [253, 177, 48], [253, 178, 47], [253, 180, 47], [253, 181, 46], [254, 183, 45], [254, 184, 44], [254, 186, 44], [254, 187, 43], [254, 189, 42], [254, 190, 42], [254, 192, 41], [253, 194, 41], [253, 195, 40], [253, 197, 39], [253, 198, 39], [253, 200, 39], [253, 202, 38], [253, 203, 38], [252, 205, 37], [252, 206, 37], [252, 208, 37], [252, 210, 37], [251, 211, 36], [251, 213, 36], [251, 215, 36], [250, 216, 36], [250, 218, 36], [249, 220, 36], [249, 221, 37], [248, 223, 37], [248, 225, 37], [247, 226, 37], [247, 228, 37], [246, 230, 38], [246, 232, 38], [245, 233, 38], [245, 235, 39], [244, 237, 39], [243, 238, 39], [243, 240, 39], [242, 242, 39], [241, 244, 38], [241, 245, 37], [240, 247, 36], [240, 249, 33]];\n\n// Reference: https://github.com/d3/d3-interpolate/blob/96d54051d1c2fec55f240edd0ec5401715b10390/src/rgb.js\nfunction rgbSpline(spline) {\n return (colors) => {\n const n = colors.length;\n let r = new Array(n);\n let g = new Array(n);\n let b = new Array(n);\n let i; let\n color;\n // eslint-disable-next-line no-plusplus\n for (i = 0; i < n; ++i) {\n color = [colors[i][0], colors[i][1], colors[i][2]];\n r[i] = color[0] || 0;\n g[i] = color[1] || 0;\n b[i] = color[2] || 0;\n }\n r = spline(r);\n g = spline(g);\n b = spline(b);\n return t => [r(t), g(t), b(t)];\n };\n}\n\n// Reference: https://github.com/d3/d3-interpolate/blob/594a32af1fe1118812b439012c2cb742e907c0c0/src/basis.js\nfunction basis(values) {\n function innerBasis(t1, v0, v1, v2, v3) {\n const t2 = t1 * t1; const\n t3 = t2 * t1;\n return ((1 - 3 * t1 + 3 * t2 - t3) * v0\n + (4 - 6 * t2 + 3 * t3) * v1\n + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2\n + t3 * v3) / 6;\n }\n\n const n = values.length - 1;\n return (t) => {\n const i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n);\n const v1 = values[i];\n const v2 = values[i + 1];\n const v0 = i > 0 ? values[i - 1] : 2 * v1 - v2;\n const v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;\n return innerBasis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n\n\n// Reference: https://github.com/d3/d3-scale-chromatic/blob/ade54c13e8dfdb9807801a794eaec1a37f926b8a/src/ramp.js\nconst interpolateRgbBasis = rgbSpline(basis);\n\nfunction interpolateSequentialMulti(range) {\n const n = range.length;\n return t => range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];\n}\n\nexport const interpolateRdBu = interpolateRgbBasis(schemeRdBu);\nexport const interpolatePlasma = interpolateSequentialMulti(schemePlasma);\n\n\n/**\n * Get a mapping of cell IDs to cell colors based on\n * gene / cell set selection coordination state.\n * @param {object} params\n * @param {object} params.expressionMatrix { rows, cols, matrix }\n * @param {array} params.geneSelection Array of selected gene IDs.\n * @param {object} params.cellSets The cell sets tree.\n * @param {object} params.cellSetSelection Selected cell sets.\n * @param {string} params.cellColorEncoding Which to use for\n * coloring: gene expression or cell sets?\n * @returns {Map} Mapping from cell IDs to [r, g, b] color arrays.\n */\nexport function getCellColors(params) {\n const {\n cellColorEncoding,\n expressionData,\n cellSets, cellSetSelection,\n cellSetColor,\n expressionDataAttrs,\n theme,\n } = params;\n if (cellColorEncoding === 'geneSelection' && expressionData && expressionDataAttrs) {\n // TODO: allow other color maps.\n const geneExpColormap = interpolatePlasma;\n const colors = new Map();\n for (let i = 0; i < expressionData.length; i += 1) {\n const value = expressionData[i];\n const cellColor = geneExpColormap(value / 255);\n colors.set(expressionDataAttrs.rows[i], cellColor);\n }\n return colors;\n } if (cellColorEncoding === 'cellSetSelection' && cellSetSelection && cellSets) {\n // Cell sets can potentially lack set colors since the color property\n // is not a required part of the schema.\n // The `initializeSets` function fills in any empty colors\n // with defaults and returns the processed tree object.\n return treeToCellColorsBySetNames(cellSets, cellSetSelection, cellSetColor, theme);\n }\n return new Map();\n}\n","/* eslint-disable import/no-extraneous-dependencies */\n/* eslint-disable no-underscore-dangle */\n// File adopted from nebula.gl's SelectionLayer\n// https://github.com/uber/nebula.gl/blob/8e9c2ec8d7cf4ca7050909ed826eb847d5e2cd9c/modules/layers/src/layers/selection-layer.js\nimport { CompositeLayer } from 'deck.gl';\nimport { polygon as turfPolygon, point as turfPoint } from '@turf/helpers';\nimport booleanWithin from '@turf/boolean-within';\nimport booleanContains from '@turf/boolean-contains';\nimport booleanOverlap from '@turf/boolean-overlap';\nimport booleanPointInPolygon from '@turf/boolean-point-in-polygon';\nimport { ScatterplotLayer } from '@deck.gl/layers';\nimport { SELECTION_TYPE } from 'nebula.gl';\nimport { EditableGeoJsonLayer } from '@nebula.gl/layers';\nimport { DrawRectangleMode, DrawPolygonByDraggingMode, ViewMode } from '@nebula.gl/edit-modes';\n\nconst EDIT_TYPE_ADD = 'addFeature';\nconst EDIT_TYPE_CLEAR = 'clearFeatures';\n\n// Customize the click handlers for the rectangle and polygon tools,\n// so that clicking triggers the `onEdit` callback.\nclass ClickableDrawRectangleMode extends DrawRectangleMode {\n // eslint-disable-next-line class-methods-use-this\n handleClick(event, props) {\n props.onEdit({ editType: EDIT_TYPE_CLEAR });\n }\n}\n\nclass ClickableDrawPolygonByDraggingMode extends DrawPolygonByDraggingMode {\n // eslint-disable-next-line class-methods-use-this\n handleClick(event, props) {\n props.onEdit({ editType: EDIT_TYPE_CLEAR });\n }\n}\n\nconst MODE_MAP = {\n [SELECTION_TYPE.RECTANGLE]: ClickableDrawRectangleMode,\n [SELECTION_TYPE.POLYGON]: ClickableDrawPolygonByDraggingMode,\n};\n\nconst defaultProps = {\n selectionType: SELECTION_TYPE.RECTANGLE,\n layerIds: [],\n onSelect: () => {},\n};\n\nconst EMPTY_DATA = {\n type: 'FeatureCollection',\n features: [],\n};\n\nconst LAYER_ID_GEOJSON = 'selection-geojson';\n\nconst PASS_THROUGH_PROPS = [\n 'lineWidthScale',\n 'lineWidthMinPixels',\n 'lineWidthMaxPixels',\n 'lineWidthUnits',\n 'lineJointRounded',\n 'lineMiterLimit',\n 'pointRadiusScale',\n 'pointRadiusMinPixels',\n 'pointRadiusMaxPixels',\n 'lineDashJustified',\n 'getLineColor',\n 'getFillColor',\n 'getRadius',\n 'getLineWidth',\n 'getLineDashArray',\n 'getTentativeLineDashArray',\n 'getTentativeLineColor',\n 'getTentativeFillColor',\n 'getTentativeLineWidth',\n 'editHandlePointRadiusScale',\n 'editHandlePointRadiusMinPixels',\n 'editHandlePointRadiusMaxPixels',\n 'getEditHandlePointColor',\n 'getEditHandlePointRadius',\n 'modeHandlers',\n];\n\nexport default class SelectionLayer extends CompositeLayer {\n _selectPolygonObjects(coordinates) {\n const {\n onSelect,\n getCellCoords,\n cellsQuadTree,\n flipY,\n } = this.props;\n\n const flippedCoordinates = (flipY\n ? coordinates.map(poly => poly.map(p => ([p[0], -p[1]])))\n : coordinates);\n\n // Convert the selection to a turf polygon object.\n const selectedPolygon = turfPolygon(flippedCoordinates);\n\n // Create an array to store the results.\n const pickingInfos = [];\n\n // quadtree.visit() takes a callback that returns a boolean:\n // If true returned, then the children of the node are _not_ visited.\n // If false returned, then the children of the node are visited.\n // Reference: https://github.com/d3/d3-quadtree#quadtree_visit\n cellsQuadTree.visit((node, x0, y0, x1, y1) => {\n const nodePoints = [[[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]]];\n const nodePolygon = turfPolygon(nodePoints);\n\n const nodePolygonContainsSelectedPolygon = booleanContains(nodePolygon, selectedPolygon);\n const nodePolygonWithinSelectedPolygon = booleanWithin(nodePolygon, selectedPolygon);\n const nodePolygonOverlapsSelectedPolgyon = booleanOverlap(nodePolygon, selectedPolygon);\n\n if (!nodePolygonContainsSelectedPolygon\n && !nodePolygonWithinSelectedPolygon\n && !nodePolygonOverlapsSelectedPolgyon) {\n // We are not interested in anything below this node,\n // so return true because we are done with this node.\n return true;\n }\n\n // This node made it past the above return statement, so it must either\n // contain, be within, or overlap with the selected polygon.\n\n // Check if this is a leaf node.\n if (node.data\n && booleanPointInPolygon(\n turfPoint([].slice.call(getCellCoords(node.data[1]))), selectedPolygon,\n )\n ) {\n // This node has data, so it is a leaf node representing one data point,\n // and we have verified that the point is in the selected polygon.\n pickingInfos.push(node.data);\n }\n\n // Return false because we are not done.\n // We want to visit the children of this node.\n return false;\n });\n\n onSelect({ pickingInfos });\n }\n\n renderLayers() {\n const { onSelect } = this.props;\n const mode = MODE_MAP[this.props.selectionType] || ViewMode;\n\n const inheritedProps = {};\n PASS_THROUGH_PROPS.forEach((p) => {\n if (this.props[p] !== undefined) inheritedProps[p] = this.props[p];\n });\n const layers = [\n new EditableGeoJsonLayer(\n this.getSubLayerProps({\n id: LAYER_ID_GEOJSON,\n pickable: true,\n mode,\n modeConfig: {\n dragToDraw: true,\n },\n selectedFeatureIndexes: [],\n data: EMPTY_DATA,\n onEdit: ({ updatedData, editType }) => {\n if (editType === EDIT_TYPE_ADD) {\n const { coordinates } = updatedData.features[0].geometry;\n this._selectPolygonObjects(coordinates);\n } else if (editType === EDIT_TYPE_CLEAR) {\n // We want to select an empty array to clear any previous selection.\n onSelect({ pickingInfos: [] });\n }\n },\n _subLayerProps: {\n guides: {\n pointType: 'circle',\n _subLayerProps: {\n 'points-circle': {\n // Styling for editHandles goes here.\n // Reference: https://github.com/uber/nebula.gl/issues/618#issuecomment-898466319\n type: ScatterplotLayer,\n radiusScale: 1,\n stroked: true,\n getLineWidth: 1,\n radiusMinPixels: 1,\n radiusMaxPixels: 3,\n getRadius: 2,\n },\n },\n },\n },\n ...inheritedProps,\n }),\n ),\n ];\n\n return layers;\n }\n}\n\nSelectionLayer.layerName = 'SelectionLayer';\nSelectionLayer.defaultProps = defaultProps;\n","import { COORDINATE_SYSTEM } from '@deck.gl/core'; // eslint-disable-line import/no-extraneous-dependencies\nimport { DataFilterExtension } from '@deck.gl/extensions'; // eslint-disable-line import/no-extraneous-dependencies\nimport SelectionLayer from './SelectionLayer';\n\n/**\n * Convert a DeckGL layer ID to a \"base\" layer ID for selection.\n * @param {string} layerId The layer ID to convert.\n * @returns {string} The base layer ID.\n */\nfunction getBaseLayerId(layerId) {\n return `base-${layerId}`;\n}\n\n/**\n * Convert a DeckGL layer ID to a \"selected\" layer ID for selection.\n * @param {string} layerId The layer ID to convert.\n * @returns {string} The base layer ID.\n */\nfunction getSelectedLayerId(layerId) {\n return `selected-${layerId}`;\n}\n\n/**\n * Construct DeckGL selection layers.\n * @param {string} tool\n * @param {number} zoom\n * @param {string} cellBaseLayerId\n * @param {function} getCellCoords\n * @param {function} updateCellsSelection\n * @returns {object[]} The array of DeckGL selection layers.\n */\nexport function getSelectionLayers(\n tool,\n zoom,\n layerId,\n getCellCoords,\n updateCellsSelection,\n cellsQuadTree,\n flipY = false,\n) {\n if (!tool) {\n return [];\n }\n\n const cellBaseLayerId = getBaseLayerId(layerId);\n const editHandlePointRadius = 5 / (zoom + 16);\n\n return [new SelectionLayer({\n id: 'selection',\n flipY,\n cellsQuadTree,\n getCellCoords,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n selectionType: tool,\n onSelect: ({ pickingInfos }) => {\n const cellIds = pickingInfos.map(cellObj => cellObj[0]);\n if (updateCellsSelection) {\n updateCellsSelection(cellIds);\n }\n },\n layerIds: [cellBaseLayerId],\n getTentativeFillColor: () => [255, 255, 255, 95],\n getTentativeLineColor: () => [143, 143, 143, 255],\n getTentativeLineDashArray: () => [7, 4],\n lineWidthMinPixels: 2,\n lineWidthMaxPixels: 2,\n getEditHandlePointColor: () => [0xff, 0xff, 0xff, 0xff],\n getEditHandlePointRadius: () => editHandlePointRadius,\n editHandlePointRadiusScale: 1,\n editHandlePointRadiusMinPixels: editHandlePointRadius,\n editHandlePointRadiusMaxPixels: 2 * editHandlePointRadius,\n })];\n}\n\n/**\n * Get deck.gl layer props for selection overlays.\n * @param {object} props\n * @returns {object} Object with two properties,\n * overlay: overlayProps, base: baseProps,\n * where the values are deck.gl layer props.\n */\nexport function overlayBaseProps(props) {\n const {\n id, getColor, data, isSelected, ...rest\n } = props;\n return {\n overlay: {\n id: getSelectedLayerId(id),\n getFillColor: getColor,\n getLineColor: getColor,\n data,\n getFilterValue: isSelected,\n extensions: [new DataFilterExtension({ filterSize: 1 })],\n filterRange: [1, 1],\n ...rest,\n },\n base: {\n id: getBaseLayerId(id),\n getLineColor: getColor,\n getFillColor: getColor,\n // Alternatively: contrast outlines with solids:\n // getLineColor: getColor,\n // getFillColor: [255, 255, 255],\n data: data.slice(),\n ...rest,\n },\n };\n}\n","import GL from '@luma.gl/constants'; // eslint-disable-line import/no-extraneous-dependencies\n\nexport const TILE_SIZE = 2048;\nexport const MIN_ROW_AGG = 1;\nexport const MAX_ROW_AGG = 16;\n\nexport const COLOR_BAR_SIZE = 20;\nexport const AXIS_LABEL_TEXT_SIZE = 9;\nexport const AXIS_TITLE_TEXT_SIZE = 15;\nexport const AXIS_MIN_SIZE = 10;\nexport const AXIS_MAX_SIZE = 90;\nexport const AXIS_MARGIN = 3;\nexport const THEME_TO_TEXT_COLOR = {\n dark: [224, 224, 224],\n light: [64, 64, 64],\n};\nexport const AXIS_FONT_FAMILY = \"-apple-system, 'Helvetica Neue', Arial, sans-serif\";\n\nexport const PIXELATED_TEXTURE_PARAMETERS = {\n // NEAREST for integer data to prevent interpolation.\n [GL.TEXTURE_MIN_FILTER]: GL.NEAREST,\n [GL.TEXTURE_MAG_FILTER]: GL.NEAREST,\n // CLAMP_TO_EDGE to remove tile artifacts.\n [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE,\n [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE,\n};\n","import glsl from 'glslify';\n\n/**\n * No change to the vertex shader from the base BitmapLayer.\n * Reference: https://github.com/visgl/deck.gl/blob/8.2-release/modules/layers/src/bitmap-layer/bitmap-layer-vertex.js\n */\nexport const vertexShader = glsl`\n#define SHADER_NAME heatmap-bitmap-layer-vertex-shader\n\nattribute vec2 texCoords;\nattribute vec3 positions;\nattribute vec3 positions64Low;\n\nvarying vec2 vTexCoord;\n\nconst vec3 pickingColor = vec3(1.0, 0.0, 0.0);\n\nvoid main(void) {\n geometry.worldPosition = positions;\n geometry.uv = texCoords;\n geometry.pickingColor = pickingColor;\n\n gl_Position = project_position_to_clipspace(positions, positions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n vTexCoord = texCoords;\n\n vec4 color = vec4(0.0);\n DECKGL_FILTER_COLOR(color, geometry);\n}\n`;\n\n/**\n * Fragment shader adapted to perform aggregation and\n * take color scale functions + sliders into account.\n * Reference: https://github.com/visgl/deck.gl/blob/8.2-release/modules/layers/src/bitmap-layer/bitmap-layer-fragment.js\n * Reference: https://github.com/hms-dbmi/viv/blob/06231ae02cac1ff57ba458c71e9bc59ed2fc4f8b/src/layers/XRLayer/xr-layer-fragment-colormap.webgl1.glsl\n */\nexport const fragmentShader = glsl`\n#define SHADER_NAME heatmap-bitmap-layer-fragment-shader\n\n#ifdef GL_ES\nprecision mediump float;\n#endif\n\n#pragma glslify: rdbu = require(\"glsl-colormap/rdbu\")\n#pragma glslify: plasma = require(\"glsl-colormap/plasma\")\n#pragma glslify: viridis = require(\"glsl-colormap/viridis\")\n#pragma glslify: greys = require(\"glsl-colormap/greys\")\n#pragma glslify: magma = require(\"glsl-colormap/magma\")\n#pragma glslify: jet = require(\"glsl-colormap/jet\")\n#pragma glslify: bone = require(\"glsl-colormap/bone\")\n#pragma glslify: copper = require(\"glsl-colormap/copper\")\n#pragma glslify: density = require(\"glsl-colormap/density\")\n#pragma glslify: inferno = require(\"glsl-colormap/inferno\")\n#pragma glslify: cool = require(\"glsl-colormap/cool\")\n#pragma glslify: hot = require(\"glsl-colormap/hot\")\n#pragma glslify: spring = require(\"glsl-colormap/spring\")\n#pragma glslify: summer = require(\"glsl-colormap/summer\")\n#pragma glslify: autumn = require(\"glsl-colormap/autumn\")\n#pragma glslify: winter = require(\"glsl-colormap/winter\")\n\n// The texture (GL.LUMINANCE & Uint8Array).\nuniform sampler2D uBitmapTexture;\n\n// What are the dimensions of the texture (width, height)?\nuniform vec2 uTextureSize;\n\n// How many consecutive pixels should be aggregated together along each axis?\nuniform vec2 uAggSize;\n\n// What are the values of the color scale sliders?\nuniform vec2 uColorScaleRange;\n\n// The texture coordinate, varying (interpolated between values set by the vertex shader).\nvarying vec2 vTexCoord;\n\nvoid main(void) {\n // Compute 1 pixel in texture coordinates\n vec2 onePixel = vec2(1.0, 1.0) / uTextureSize;\n \n vec2 viewCoord = vec2(floor(vTexCoord.x * uTextureSize.x), floor(vTexCoord.y * uTextureSize.y));\n\n // Compute (x % aggSizeX, y % aggSizeY).\n // These values will be the number of values to the left / above the current position to consider.\n vec2 modAggSize = vec2(-1.0 * mod(viewCoord.x, uAggSize.x), -1.0 * mod(viewCoord.y, uAggSize.y));\n\n // Take the sum of values along each axis.\n float intensitySum = 0.0;\n vec2 offsetPixels = vec2(0.0, 0.0);\n\n for(int i = 0; i < 16; i++) {\n // Check to break outer loop early.\n // Uniforms cannot be used as conditions in GLSL for loops.\n if(float(i) >= uAggSize.y) {\n // Done in the y direction.\n break;\n }\n\n offsetPixels = vec2(offsetPixels.x, (modAggSize.y + float(i)) * onePixel.y);\n\n for(int j = 0; j < 16; j++) {\n // Check to break inner loop early.\n // Uniforms cannot be used as conditions in GLSL for loops.\n if(float(j) >= uAggSize.x) {\n // Done in the x direction.\n break;\n }\n\n offsetPixels = vec2((modAggSize.x + float(j)) * onePixel.x, offsetPixels.y);\n intensitySum += texture2D(uBitmapTexture, vTexCoord + offsetPixels).r;\n }\n }\n \n // Compute the mean value.\n float intensityMean = intensitySum / (uAggSize.x * uAggSize.y);\n \n // Re-scale using the color scale slider values.\n float scaledIntensityMean = (intensityMean - uColorScaleRange[0]) / max(0.005, (uColorScaleRange[1] - uColorScaleRange[0]));\n\n gl_FragColor = COLORMAP_FUNC(clamp(scaledIntensityMean, 0.0, 1.0));\n\n geometry.uv = vTexCoord;\n DECKGL_FILTER_COLOR(gl_FragColor, geometry);\n}\n`;\n","/* eslint-disable no-underscore-dangle */\nimport GL from '@luma.gl/constants'; // eslint-disable-line import/no-extraneous-dependencies\nimport { _mergeShaders, project32, picking } from '@deck.gl/core'; // eslint-disable-line import/no-extraneous-dependencies\nimport { BitmapLayer } from '@deck.gl/layers'; // eslint-disable-line import/no-extraneous-dependencies\nimport { Texture2D } from '@luma.gl/core';\nimport { PIXELATED_TEXTURE_PARAMETERS, TILE_SIZE } from './heatmap-constants';\nimport { GLSL_COLORMAPS, GLSL_COLORMAP_DEFAULT, COLORMAP_SHADER_PLACEHOLDER } from './constants';\nimport { vertexShader, fragmentShader } from './heatmap-bitmap-layer-shaders';\n\nconst defaultProps = {\n image: { type: 'object', value: null, async: true },\n colormap: { type: 'string', value: GLSL_COLORMAP_DEFAULT, compare: true },\n bounds: { type: 'array', value: [1, 0, 0, 1], compare: true },\n aggSizeX: { type: 'number', value: 8.0, compare: true },\n aggSizeY: { type: 'number', value: 8.0, compare: true },\n colorScaleLo: { type: 'number', value: 0.0, compare: true },\n colorScaleHi: { type: 'number', value: 1.0, compare: true },\n};\n\n/**\n * A BitmapLayer that performs aggregation in the fragment shader,\n * and renders its texture from a Uint8Array rather than an ImageData.\n */\nexport default class HeatmapBitmapLayer extends BitmapLayer {\n /**\n * Copy of getShaders from Layer (grandparent, parent of BitmapLayer).\n * Reference: https://github.com/visgl/deck.gl/blob/0afd4e99a6199aeec979989e0c361c97e6c17a16/modules/core/src/lib/layer.js#L302\n * @param {object} shaders\n * @returns {object} Merged shaders.\n */\n _getShaders(shaders) {\n this.props.extensions.forEach((extension) => {\n // eslint-disable-next-line no-param-reassign\n shaders = _mergeShaders(shaders, extension.getShaders.call(this, extension));\n });\n return shaders;\n }\n\n /**\n * Need to override to provide custom shaders.\n */\n getShaders() {\n const { colormap } = this.props;\n const fragmentShaderWithColormap = (GLSL_COLORMAPS.includes(colormap)\n ? fragmentShader.replace(COLORMAP_SHADER_PLACEHOLDER, colormap)\n : fragmentShader.replace(COLORMAP_SHADER_PLACEHOLDER, GLSL_COLORMAP_DEFAULT)\n );\n return this._getShaders({\n vs: vertexShader,\n fs: fragmentShaderWithColormap,\n modules: [project32, picking],\n });\n }\n\n updateState(args) {\n super.updateState(args);\n this.loadTexture(this.props.image);\n const { props, oldProps } = args;\n if (props.colormap !== oldProps.colormap) {\n const { gl } = this.context;\n // eslint-disable-next-line no-unused-expressions\n this.state.model?.delete();\n this.state.model = this._getModel(gl);\n this.getAttributeManager().invalidateAll();\n }\n }\n\n /**\n * Need to override to provide additional uniform values.\n * Simplified by removing video-related code.\n * Reference: https://github.com/visgl/deck.gl/blob/0afd4e99a6199aeec979989e0c361c97e6c17a16/modules/layers/src/bitmap-layer/bitmap-layer.js#L173\n * @param {*} opts\n */\n draw(opts) {\n const { uniforms } = opts;\n const { bitmapTexture, model } = this.state;\n const {\n aggSizeX,\n aggSizeY,\n colorScaleLo,\n colorScaleHi,\n } = this.props;\n\n // Render the image\n if (bitmapTexture && model) {\n model\n .setUniforms(\n Object.assign({}, uniforms, {\n uBitmapTexture: bitmapTexture,\n uTextureSize: [TILE_SIZE, TILE_SIZE],\n uAggSize: [aggSizeX, aggSizeY],\n uColorScaleRange: [colorScaleLo, colorScaleHi],\n }),\n )\n .draw();\n }\n }\n\n /**\n * Need to override to provide the custom DEFAULT_TEXTURE_PARAMETERS\n * object.\n * Simplified by removing video-related code.\n * Reference: https://github.com/visgl/deck.gl/blob/0afd4e99a6199aeec979989e0c361c97e6c17a16/modules/layers/src/bitmap-layer/bitmap-layer.js#L218\n * @param {Uint8Array} image\n */\n loadTexture(image) {\n const { gl } = this.context;\n\n if (this.state.bitmapTexture) {\n this.state.bitmapTexture.delete();\n }\n\n if (image instanceof Texture2D) {\n this.setState({\n bitmapTexture: image,\n });\n } else if (image) {\n this.setState({\n bitmapTexture: new Texture2D(gl, {\n data: image,\n mipmaps: false,\n parameters: PIXELATED_TEXTURE_PARAMETERS,\n // Each color contains a single luminance value.\n // When sampled, rgb are all set to this luminance, alpha is 1.0.\n // Reference: https://luma.gl/docs/api-reference/webgl/texture#texture-formats\n format: GL.LUMINANCE,\n dataFormat: GL.LUMINANCE,\n type: GL.UNSIGNED_BYTE,\n width: TILE_SIZE,\n height: TILE_SIZE,\n }),\n });\n }\n }\n}\nHeatmapBitmapLayer.layerName = 'HeatmapBitmapLayer';\nHeatmapBitmapLayer.defaultProps = defaultProps;\n","import { BitmapLayer } from '@deck.gl/layers'; // eslint-disable-line import/no-extraneous-dependencies\nimport { CompositeLayer } from '@deck.gl/core'; // eslint-disable-line import/no-extraneous-dependencies\nimport { PIXELATED_TEXTURE_PARAMETERS } from './heatmap-constants';\n\n\n// These are the same defaultProps as for BitmapLayer.\nconst defaultProps = {\n ...BitmapLayer.defaultProps,\n image: { type: 'object', value: null, async: true },\n bounds: { type: 'array', value: [1, 0, 0, 1], compare: true },\n desaturate: {\n type: 'number', min: 0, max: 1, value: 0,\n },\n transparentColor: { type: 'color', value: [0, 0, 0, 0] },\n tintColor: { type: 'color', value: [255, 255, 255] },\n};\n\nexport default class PixelatedBitmapLayer extends CompositeLayer {\n renderLayers() {\n const { image } = this.props;\n return new BitmapLayer(this.props, {\n id: `${this.props.id}-wrapped`,\n image,\n textureParameters: PIXELATED_TEXTURE_PARAMETERS,\n });\n }\n}\n\nPixelatedBitmapLayer.layerName = 'PixelatedBitmapLayer';\nPixelatedBitmapLayer.defaultProps = defaultProps;\n","/* eslint-disable no-underscore-dangle */\nimport { COORDINATE_SYSTEM, CompositeLayer } from '@deck.gl/core'; // eslint-disable-line import/no-extraneous-dependencies\nimport { TextLayer } from '@deck.gl/layers'; // eslint-disable-line import/no-extraneous-dependencies\nimport {\n AXIS_LABEL_TEXT_SIZE,\n AXIS_TITLE_TEXT_SIZE,\n AXIS_MARGIN,\n THEME_TO_TEXT_COLOR,\n AXIS_FONT_FAMILY,\n} from './heatmap-constants';\n\nexport default class HeatmapCompositeTextLayer extends CompositeLayer {\n _renderAxisTopLayers() {\n const {\n axisTopLabelData, matrixLeft, width, matrixWidth, viewWidth, theme,\n targetX, targetY, axisTopTitle, cellWidth, axisOffsetTop, scaleFactor,\n } = this.props;\n const showAxisTopLabels = cellWidth >= AXIS_LABEL_TEXT_SIZE;\n const axisLabelTop = targetY + (axisOffsetTop - AXIS_MARGIN) / 2 / scaleFactor;\n return [\n new TextLayer({\n id: 'axisTopLabels',\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: axisTopLabelData,\n getText: d => d[1],\n getPosition: d => [matrixLeft + ((d[0] + 0.5) / width) * matrixWidth, axisLabelTop],\n getTextAnchor: 'start',\n getColor: () => THEME_TO_TEXT_COLOR[theme],\n getSize: (showAxisTopLabels ? AXIS_LABEL_TEXT_SIZE : 0),\n getAngle: 75,\n fontFamily: AXIS_FONT_FAMILY,\n updateTriggers: {\n getPosition: [axisLabelTop, matrixLeft, matrixWidth, viewWidth],\n getSize: [showAxisTopLabels],\n getColor: [theme],\n },\n }),\n new TextLayer({\n id: 'axisTopTitle',\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [{ title: axisTopTitle }],\n getText: d => d.title,\n getPosition: [targetX, targetY],\n getTextAnchor: 'middle',\n getColor: () => THEME_TO_TEXT_COLOR[theme],\n getSize: (!showAxisTopLabels ? AXIS_TITLE_TEXT_SIZE : 0),\n getAngle: 0,\n fontFamily: AXIS_FONT_FAMILY,\n updateTriggers: {\n getSize: [showAxisTopLabels],\n getColor: [theme],\n },\n }),\n ];\n }\n\n _renderAxisLeftLayers() {\n const {\n axisLeftLabelData, matrixTop, height, matrixHeight,\n viewHeight, theme, axisLeftTitle, targetX, targetY, cellHeight, axisOffsetLeft,\n scaleFactor,\n } = this.props;\n const showAxisLeftLabels = cellHeight >= AXIS_LABEL_TEXT_SIZE;\n const axisLabelLeft = targetX + (axisOffsetLeft - AXIS_MARGIN) / 2 / scaleFactor;\n return [\n new TextLayer({\n id: 'axisLeftLabels',\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: axisLeftLabelData,\n getText: d => d[1],\n getPosition: d => [axisLabelLeft, matrixTop + ((d[0] + 0.5) / height) * matrixHeight],\n getTextAnchor: 'end',\n getColor: () => THEME_TO_TEXT_COLOR[theme],\n getSize: (showAxisLeftLabels ? AXIS_LABEL_TEXT_SIZE : 0),\n getAngle: 0,\n fontFamily: AXIS_FONT_FAMILY,\n updateTriggers: {\n getPosition: [axisLabelLeft, matrixTop, matrixHeight, viewHeight],\n getSize: [showAxisLeftLabels],\n getColor: [theme],\n },\n }),\n new TextLayer({\n id: 'axisLeftTitle',\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: [{ title: axisLeftTitle }],\n getText: d => d.title,\n getPosition: [targetX, targetY],\n getTextAnchor: 'middle',\n getColor: () => THEME_TO_TEXT_COLOR[theme],\n getSize: (!showAxisLeftLabels ? AXIS_TITLE_TEXT_SIZE : 0),\n getAngle: 90,\n fontFamily: AXIS_FONT_FAMILY,\n updateTriggers: {\n getSize: [showAxisLeftLabels],\n getColor: [theme],\n },\n }),\n ];\n }\n\n renderLayers() {\n return [\n this._renderAxisTopLayers(),\n this._renderAxisLeftLayers(),\n ];\n }\n}\n\nHeatmapCompositeTextLayer.layerName = 'HeatmapCompositeTextLayer';\n","import { quadtree } from 'd3-quadtree';\n\n/**\n * Create a d3-quadtree object for cells data points.\n * @param {array} cellsEntries Array of [cellId, cell] tuples,\n * resulting from running Object.entries on the cells object.\n * @param {function} getCellCoords Given a cell object, return the\n * spatial/scatterplot coordinates [x, y].\n * @returns {object} Quadtree instance.\n */\nexport function createCellsQuadTree(cellsEntries, getCellCoords) {\n // Use the cellsEntries variable since it is already\n // an array, converted by Object.entries().\n // Only use cellsEntries in quadtree calculation if there is\n // centroid data in the cells (i.e not just ids).\n // eslint-disable-next-line no-unused-vars\n if (!cellsEntries || !cellsEntries.length || !getCellCoords(cellsEntries[0][1])) {\n // Abort if the cells data is not yet available.\n return null;\n }\n const tree = quadtree()\n .x(d => getCellCoords(d[1])[0])\n .y(d => getCellCoords(d[1])[1])\n .addAll(cellsEntries);\n return tree;\n}\n","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nimport * as React from \"react\";\n\nvar _ref2 = /*#__PURE__*/React.createElement(\"path\", {\n fill: \"none\",\n d: \"M0 0h24v24H0V0z\"\n});\n\nvar _ref3 = /*#__PURE__*/React.createElement(\"path\", {\n d: \"M21 3L3 10.53v.98l6.84 2.65L12.48 21h.98L21 3z\"\n});\n\nfunction SvgNearMe(_ref) {\n var svgRef = _ref.svgRef,\n title = _ref.title,\n titleId = _ref.titleId,\n props = _objectWithoutProperties(_ref, [\"svgRef\", \"title\", \"titleId\"]);\n\n return /*#__PURE__*/React.createElement(\"svg\", _extends({\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, _ref2, _ref3);\n}\n\nvar ForwardRef = React.forwardRef(function (props, ref) {\n return /*#__PURE__*/React.createElement(SvgNearMe, _extends({\n svgRef: ref\n }, props));\n});\nexport default __webpack_public_path__ + \"static/media/near_me.2a308adc.svg\";\nexport { ForwardRef as ReactComponent };","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nimport * as React from \"react\";\n\nvar _ref2 = /*#__PURE__*/React.createElement(\"path\", {\n d: \" M19 19h2v2h-2v-2zm0-2h2v-2h-2v2z M3 13h2v-2H3v2zm0 4h2v-2H3v2z m0-8h2V7H3v2zm0-4h2V3H3v2z m4 0h2V3H7v2zm8 16h2v-2h-2v2z m-4 0h2v-2h-2v2z m4 0h2v-2h-2v2z m-8 0h2v-2H7v2z m-4 0h2v-2H3v2z M11 5h2v-2h-2v2z M15 5h2v-2h-2v2z M19 5h2v-2h-2v2z M19 9h2v-2h-2v2z M19 13h2v-2h-2v2z \"\n});\n\nfunction SvgSelectionRectangle(_ref) {\n var svgRef = _ref.svgRef,\n title = _ref.title,\n titleId = _ref.titleId,\n props = _objectWithoutProperties(_ref, [\"svgRef\", \"title\", \"titleId\"]);\n\n return /*#__PURE__*/React.createElement(\"svg\", _extends({\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, _ref2);\n}\n\nvar ForwardRef = React.forwardRef(function (props, ref) {\n return /*#__PURE__*/React.createElement(SvgSelectionRectangle, _extends({\n svgRef: ref\n }, props));\n});\nexport default __webpack_public_path__ + \"static/media/selection_rectangle.aa477261.svg\";\nexport { ForwardRef as ReactComponent };","function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nimport * as React from \"react\";\n\nfunction SvgSelectionLasso(_ref) {\n var svgRef = _ref.svgRef,\n title = _ref.title,\n titleId = _ref.titleId,\n props = _objectWithoutProperties(_ref, [\"svgRef\", \"title\", \"titleId\"]);\n\n return /*#__PURE__*/React.createElement(\"svg\", _extends({\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n ref: svgRef,\n \"aria-labelledby\": titleId\n }, props), title ? /*#__PURE__*/React.createElement(\"title\", {\n id: titleId\n }, title) : null, /*#__PURE__*/React.createElement(\"g\", {\n transform: \"translate(0,3)\"\n }, /*#__PURE__*/React.createElement(\"path\", {\n style: {\n strokeWidth: 0.343565\n },\n d: \"M 23.942314,4.6958443 C 23.446206,1.8868581 19.727461,0 14.687364,0 13.437819,0 12.150138,0.11543779 10.859708,0.34287772 4.1629423,1.5250844 -0.58168816,5.2884937 0.05768601,8.911385 c 0.25355086,1.439193 1.35605049,2.63583 3.04638949,3.461072 -0.2569865,0.387198 -0.4074679,0.826617 -0.4074679,1.29524 0,1.337498 1.1863293,2.457176 2.7639791,2.728248 l -1.3615475,2.333149 c -0.1576963,0.271073 -0.066308,0.61876 0.2047647,0.776457 0.090014,0.05291 0.1886171,0.07799 0.2858459,0.07799 0.1951448,0 0.3851362,-0.100665 0.4912977,-0.281723 l 1.6803757,-2.88148 C 8.41868,16.20561 9.6895264,15.063601 9.6998333,13.683844 c 6.872e-4,-0.0055 0.00137,-0.01065 0.00137,-0.01615 0,-0.02336 -0.00344,-0.04569 -0.00481,-0.06837 1.1292977,-0.0213 2.2847067,-0.130211 3.4435507,-0.334975 6.69711,-1.181863 11.44174,-4.9456164 10.802366,-8.5685077 z M 3.83312,13.667353 c 0,-0.30749 0.1281497,-0.59849 0.3470005,-0.848261 0.1219655,0.04295 0.2456489,0.08383 0.3717372,0.123339 l 1.2234344,2.352045 C 4.6865351,15.149835 3.83312,14.46408 3.83312,13.667353 Z M 7.0141869,15.216144 6.0223152,13.309702 5.4008064,12.114097 c 0.121622,-0.03161 0.2477103,-0.05634 0.3772342,-0.07387 0.1367388,-0.0189 0.2772568,-0.02886 0.420867,-0.02886 0.5067581,0 0.980534,0.11956 1.3701366,0.317454 0.5696305,0.289968 0.9554538,0.750345 0.9904974,1.262944 0.00137,0.02542 0.0055,0.05016 0.0055,0.07593 0,0.698124 -0.6562089,1.310356 -1.5508518,1.548447 z m 5.9185921,-3.126441 c -1.217251,0.214728 -2.429691,0.323982 -3.6060571,0.324669 -0.5765018,-0.911821 -1.7614569,-1.53917 -3.1278143,-1.53917 -0.4717146,0 -0.921441,0.07593 -1.332001,0.211292 -0.3061162,0.100665 -0.5878394,0.237403 -0.8427645,0.39991 C 2.4598914,10.828133 1.4360682,9.8579062 1.2319907,8.7035283 0.72660678,5.8381974 5.2307418,2.5475333 11.067221,1.5175259 c 1.222061,-0.2161023 2.439998,-0.3246688 3.620143,-0.3246688 4.371863,0 7.694479,1.5250844 8.080645,3.7101568 0.505041,2.8653309 -3.998751,6.1566821 -9.83523,7.1866891 z\",\n id: \"path10\"\n })));\n}\n\nvar ForwardRef = React.forwardRef(function (props, ref) {\n return /*#__PURE__*/React.createElement(SvgSelectionLasso, _extends({\n svgRef: ref\n }, props));\n});\nexport default __webpack_public_path__ + \"static/media/selection_lasso.00e80a33.svg\";\nexport { ForwardRef as ReactComponent };","import React from 'react';\nimport { SELECTION_TYPE } from 'nebula.gl';\nimport { ReactComponent as PointerIconSVG } from '../../assets/tools/near_me.svg';\nimport { ReactComponent as SelectRectangleIconSVG } from '../../assets/tools/selection_rectangle.svg';\nimport { ReactComponent as SelectLassoIconSVG } from '../../assets/tools/selection_lasso.svg';\n\nexport function IconButton(props) {\n const {\n alt, onClick, isActive, children,\n } = props;\n const inactive = 'btn btn-outline-secondary mr-2 icon';\n const active = `${inactive} active`;\n return (\n \n {children}\n \n );\n}\n\nexport default function ToolMenu(props) {\n const {\n setActiveTool,\n activeTool,\n visibleTools = { pan: true, selectRectangle: true, selectLasso: true },\n } = props;\n return (\n
\n {visibleTools.pan && (\n setActiveTool(null)}\n isActive={activeTool === null}\n >\n \n )}\n {visibleTools.selectRectangle ? (\n setActiveTool(SELECTION_TYPE.RECTANGLE)}\n isActive={activeTool === SELECTION_TYPE.RECTANGLE}\n >\n \n ) : null}\n {visibleTools.selectLasso ? (\n setActiveTool(SELECTION_TYPE.POLYGON)}\n isActive={activeTool === SELECTION_TYPE.POLYGON}\n >\n \n ) : null}\n
\n );\n}\n","export const getCursorWithTool = () => 'crosshair';\nexport const getCursor = interactionState => (interactionState.isDragging\n ? 'grabbing' : 'default'\n);\n","import React, { PureComponent } from 'react';\nimport DeckGL, { OrthographicView, OrbitView } from 'deck.gl';\nimport ToolMenu from './ToolMenu';\nimport { DEFAULT_GL_OPTIONS } from '../utils';\nimport { getCursor, getCursorWithTool } from './cursor';\n\n/**\n * Abstract class component intended to be inherited by\n * the Spatial and Scatterplot class components.\n * Contains a common constructor, common DeckGL callbacks,\n * and common render function.\n */\nexport default class AbstractSpatialOrScatterplot extends PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n gl: null,\n tool: null,\n };\n\n this.viewport = null;\n\n this.onViewStateChange = this.onViewStateChange.bind(this);\n this.onInitializeViewInfo = this.onInitializeViewInfo.bind(this);\n this.onWebGLInitialized = this.onWebGLInitialized.bind(this);\n this.onToolChange = this.onToolChange.bind(this);\n this.onHover = this.onHover.bind(this);\n }\n\n /**\n * Called by DeckGL upon a viewState change,\n * for example zoom or pan interaction.\n * Emit the new viewState to the `setViewState`\n * handler prop.\n * @param {object} params\n * @param {object} params.viewState The next deck.gl viewState.\n */\n onViewStateChange({ viewState: nextViewState }) {\n const {\n setViewState, viewState, layers, spatialAxisFixed,\n } = this.props;\n const use3d = layers?.some(l => l.use3d);\n setViewState({\n ...nextViewState,\n // If the axis is fixed, just use the current target in state i.e don't change target.\n target: spatialAxisFixed && use3d ? viewState.target : nextViewState.target,\n });\n }\n\n /**\n * Called by DeckGL upon viewport\n * initialization.\n * @param {object} viewState\n * @param {object} viewState.viewport\n */\n onInitializeViewInfo({ viewport }) {\n this.viewport = viewport;\n }\n\n /**\n * Called by DeckGL upon initialization,\n * helps to understand when to pass layers\n * to the DeckGL component.\n * @param {object} gl The WebGL context object.\n */\n onWebGLInitialized(gl) {\n this.setState({ gl });\n }\n\n /**\n * Called by the ToolMenu buttons.\n * Emits the new tool value to the\n * `onToolChange` prop.\n * @param {string} tool Name of tool.\n */\n onToolChange(tool) {\n const { onToolChange: onToolChangeProp } = this.props;\n this.setState({ tool });\n if (onToolChangeProp) {\n onToolChangeProp(tool);\n }\n }\n\n /**\n * Create the DeckGL layers.\n * @returns {object[]} Array of\n * DeckGL layer objects.\n * Intended to be overriden by descendants.\n */\n // eslint-disable-next-line class-methods-use-this\n getLayers() {\n return [];\n }\n\n // eslint-disable-next-line consistent-return\n onHover(info) {\n const {\n coordinate, sourceLayer: layer, tile,\n } = info;\n const {\n setCellHighlight, cellHighlight, setComponentHover, layers,\n } = this.props;\n const hasBitmask = (layers || []).some(l => l.type === 'bitmask');\n if (!setCellHighlight || !tile) {\n return null;\n }\n if (!layer || !coordinate) {\n if (cellHighlight && hasBitmask) {\n setCellHighlight(null);\n }\n return null;\n }\n const { content, bbox, z } = tile;\n if (!content) {\n if (cellHighlight && hasBitmask) {\n setCellHighlight(null);\n }\n return null;\n }\n const { data, width, height } = content;\n const {\n left, right, top, bottom,\n } = bbox;\n const bounds = [\n left,\n data.height < layer.tileSize ? height : bottom,\n data.width < layer.tileSize ? width : right,\n top,\n ];\n if (!data) {\n if (cellHighlight && hasBitmask) {\n setCellHighlight(null);\n }\n return null;\n }\n // Tiled layer needs a custom layerZoomScale.\n if (layer.id.includes('bitmask')) {\n // The zoomed out layer needs to use the fixed zoom at which it is rendered.\n const layerZoomScale = Math.max(\n 1,\n 2 ** Math.round(-z),\n );\n const dataCoords = [\n Math.floor((coordinate[0] - bounds[0]) / layerZoomScale),\n Math.floor((coordinate[1] - bounds[3]) / layerZoomScale),\n ];\n const coords = dataCoords[1] * width + dataCoords[0];\n const hoverData = data.map(d => d[coords]);\n const cellId = hoverData.find(i => i > 0);\n if (cellId !== Number(cellHighlight)) {\n if (setComponentHover) {\n setComponentHover();\n }\n // eslint-disable-next-line no-unused-expressions\n setCellHighlight(cellId ? String(cellId) : null);\n }\n }\n }\n\n /**\n * Emits a function to project from the\n * cell ID space to the scatterplot or\n * spatial coordinate space, via the\n * `updateViewInfo` prop.\n */\n viewInfoDidUpdate(getCellCoords) {\n const { updateViewInfo, cells, uuid } = this.props;\n const { viewport } = this;\n if (updateViewInfo && viewport) {\n updateViewInfo({\n uuid,\n project: (cellId) => {\n const cell = cells[cellId];\n try {\n const [positionX, positionY] = getCellCoords(cell);\n return viewport.project([positionX, positionY]);\n } catch (e) {\n return [null, null];\n }\n },\n });\n }\n }\n\n /**\n * Intended to be overriden by descendants.\n */\n componentDidUpdate() {\n\n }\n\n /**\n * A common render function for both Spatial\n * and Scatterplot components.\n */\n render() {\n const {\n deckRef, viewState, uuid, layers: layerProps,\n } = this.props;\n const { gl, tool } = this.state;\n const layers = this.getLayers();\n const use3d = (layerProps || []).some(l => l.use3d);\n\n const showCellSelectionTools = this.cellsLayer !== null\n || (this.cellsEntries.length && this.cellsEntries[0][1].xy);\n const showPanTool = this.cellsLayer !== null || layerProps.findIndex(l => l.type === 'bitmask' || l.type === 'raster') >= 0;\n // For large datasets or ray casting, the visual quality takes only a small\n // hit in exchange for much better performance by setting this to false:\n // https://deck.gl/docs/api-reference/core/deck#usedevicepixels\n const useDevicePixels = this.cellsEntries.length < 100000 && !use3d;\n\n return (\n <>\n \n typeof i === 'number')\n ? layers\n : []\n }\n glOptions={DEFAULT_GL_OPTIONS}\n onWebGLInitialized={this.onWebGLInitialized}\n onViewStateChange={this.onViewStateChange}\n viewState={viewState}\n useDevicePixels={useDevicePixels}\n controller={tool ? { dragPan: false } : true}\n getCursor={tool ? getCursorWithTool : getCursor}\n onHover={this.onHover}\n >\n {this.onInitializeViewInfo}\n \n \n );\n }\n}\n","/* eslint-disable no-plusplus */\n/* eslint-disable no-param-reassign */\nimport { quadtree } from 'd3-quadtree';\n\n/**\n * Returns a closure that returns a constant value.\n */\nfunction constant(v) {\n return (() => v);\n}\n\n/**\n * Adds a tiny bit of randomness to a number.\n */\nfunction jiggle(v) {\n return v + (Math.random() - 0.5) * 1e-6;\n}\n\n/**\n * A force function to be used with d3.forceSimulation.\n * This has been adapted for use here, with comments explaining each part.\n * Reference: https://bl.ocks.org/cmgiven/547658968d365bcc324f3e62e175709b\n */\nexport function forceCollideRects() {\n // D3 implements things with function prototypes rather than classes.\n // Pretend these variables are the \"instance members\" of a class.\n // Note that this function actually returns the internal force() function,\n // but that the force() function is a closure with access to these instance members.\n\n let nodes;\n let masses;\n let strength = 1;\n let iterations = 1;\n\n let sizes;\n let size = constant([0, 0]);\n\n // Given a node, return the center point along the x-axis.\n function xCenter(d) {\n return d.x + d.vx + sizes[d.index][0] / 2;\n }\n\n // Given a node, return the center point along the y-axis.\n function yCenter(d) {\n return d.y + d.vy + sizes[d.index][1] / 2;\n }\n\n // Given a quadtree node, initialize its .size property.\n function prepare(quad) {\n if (quad.data) {\n // This is a leaf node, so we set quad.size to the node's size.\n // (No need to compute the max of internal nodes,\n // since leaf nodes do not have any internal nodes).\n quad.size = sizes[quad.data.index];\n } else {\n quad.size = [0, 0];\n // Internal nodes of the quadtree are represented\n // as four-element arrays in left-to-right, top-to-bottom order.\n // Here, we are setting quad.size to [maxWidth, maxHeight]\n // among the internal nodes of this current `quad` node.\n for (let i = 0; i < 4; i++) {\n if (quad[i] && quad[i].size) {\n quad.size[0] = Math.max(quad.size[0], quad[i].size[0]);\n quad.size[1] = Math.max(quad.size[1], quad[i].size[1]);\n }\n }\n }\n }\n\n function force() {\n let node;\n let nodeSize;\n let nodeMass;\n let xi;\n let yi;\n\n // Create a quadtree based on node center points.\n // Initialize each quadtree node's .size property by calling\n // the prepare() function on each quadtree node.\n const tree = quadtree(nodes, xCenter, yCenter).visitAfter(prepare);\n\n // Update the .vx and .vy properties of both `node` and `data`\n // (the current node pair).\n function apply(quad, x0, y0, x1, y1) {\n // `quad` is a quadtree node.\n const { data } = quad;\n const xSize = (nodeSize[0] + quad.size[0]) / 2;\n const ySize = (nodeSize[1] + quad.size[1]) / 2;\n\n if (data && data.index > node.index) {\n // This is a leaf node because `data` is defined.\n // `x` is the difference in x centers between `node` and `data`.\n // `y` is the difference in y centers between `node` and `data`.\n let x = jiggle(xi - xCenter(data));\n let y = jiggle(yi - yCenter(data));\n const xd = Math.abs(x) - xSize;\n const yd = Math.abs(y) - ySize;\n\n // If `xd` and `yd` is less than zero,\n // then there is an overlap between the two nodes.\n if (xd < 0 && yd < 0) {\n const l = Math.sqrt(x * x + y * y);\n const m = masses[data.index] / (nodeMass + masses[data.index]);\n\n // We move the nodes either in the x or y direction.\n // Nodes are moved proportionally to:\n // their distance apart (`l`), their amount of overlap (`xd` or `yd`), their masses (`m`),\n // and the strength parameter (`strength`).\n if (Math.abs(xd) < Math.abs(yd)) {\n node.vx -= (x *= xd / l * strength) * m;\n data.vx += x * (1 - m);\n } else {\n node.vy -= (y *= yd / l * strength) * m;\n data.vy += y * (1 - m);\n }\n }\n // When the quadtree.visit callback returns _true_ for a node,\n // then the node's children will _not_ be visited.\n return x0 > xi + xSize || x1 < xi - xSize || y0 > yi + ySize || y1 < yi - ySize;\n }\n return false;\n }\n\n function iterate() {\n // On every iteration, use the `apply` function to visit every node\n // which has an index greater than the current node's index,\n // (visiting every node pair).\n for (let j = 0; j < nodes.length; j++) {\n node = nodes[j];\n nodeSize = sizes[j];\n nodeMass = masses[j];\n xi = xCenter(node);\n yi = yCenter(node);\n\n tree.visit(apply);\n }\n }\n\n // Do the specified number of iterations.\n for (let i = 0; i < iterations; i++) {\n iterate();\n }\n }\n\n // The \"constructor\".\n // Takes a list of nodes as input.\n force.initialize = (v) => {\n nodes = v;\n // Get the size [w, h] of each node using the size getter function.\n sizes = nodes.map(size);\n // Get the mass of each node,\n // which is the sum of its horizontal and vertical edge lengths.\n masses = sizes.map(d => d[0] + d[1]);\n };\n\n // Set the number of iterations.\n // If no value is provided as a parameter, this acts as a getter function.\n force.iterations = (...v) => {\n if (v.length) {\n iterations = +v[0];\n return force;\n }\n return iterations;\n };\n\n // Set the strength value.\n // If no value is provided as a parameter, this acts as a getter function.\n force.strength = (...v) => {\n if (v.length) {\n strength = +v[0];\n return force;\n }\n return strength;\n };\n\n // Set the size function.\n // The size function takes a node as a parameter and returns its size.\n // If no size function is provided as a parameter, this acts as a getter function.\n force.size = (...v) => {\n if (v.length) {\n size = (typeof v[0] === 'function' ? v[0] : constant(v[0]));\n return force;\n }\n return size;\n };\n\n // Returns the force closure.\n return force;\n}\n","import glsl from 'glslify';\n\n/**\n *\n * Reference: https://github.com/visgl/deck.gl/blob/8.4-release/modules/layers/src/scatterplot-layer/scatterplot-layer-vertex.glsl.js\n * Reference: https://observablehq.com/@rreusser/selecting-the-right-opacity-for-2d-point-clouds\n * Reference: https://github.com/flekschas/regl-scatterplot/blob/5e3b03e/src/point.vs\n */\nconst vs = glsl`\n#pragma glslify: plasma = require(\"glsl-colormap/plasma\")\n#pragma glslify: viridis = require(\"glsl-colormap/viridis\")\n#pragma glslify: greys = require(\"glsl-colormap/greys\")\n#pragma glslify: magma = require(\"glsl-colormap/magma\")\n#pragma glslify: jet = require(\"glsl-colormap/jet\")\n#pragma glslify: bone = require(\"glsl-colormap/bone\")\n#pragma glslify: copper = require(\"glsl-colormap/copper\")\n#pragma glslify: density = require(\"glsl-colormap/density\")\n#pragma glslify: inferno = require(\"glsl-colormap/inferno\")\n#pragma glslify: cool = require(\"glsl-colormap/cool\")\n#pragma glslify: hot = require(\"glsl-colormap/hot\")\n#pragma glslify: spring = require(\"glsl-colormap/spring\")\n#pragma glslify: summer = require(\"glsl-colormap/summer\")\n#pragma glslify: autumn = require(\"glsl-colormap/autumn\")\n#pragma glslify: winter = require(\"glsl-colormap/winter\")\n\n// Custom attributes for Vitessce:\nattribute float expressionValue;\n\n// Custom uniforms for Vitessce:\nuniform vec2 uColorScaleRange;\nuniform bool uIsExpressionMode;\n\n`;\n\nconst inject = {\n 'vs:DECKGL_FILTER_COLOR': `\n if(uIsExpressionMode) {\n float normalizedExpressionValue = expressionValue / 255.0;\n float scaledExpressionValue = (normalizedExpressionValue - uColorScaleRange[0]) / max(0.005, (uColorScaleRange[1] - uColorScaleRange[0]));\n color.rgb = COLORMAP_FUNC(clamp(scaledExpressionValue, 0.0, 1.0)).rgb;\n }\n `,\n};\n\nexport default {\n name: 'scaled-expression',\n vs,\n inject,\n};\n","/* eslint-disable no-underscore-dangle */\n/* eslint-disable import/no-extraneous-dependencies */\nimport GL from '@luma.gl/constants';\nimport { LayerExtension } from '@deck.gl/core';\nimport { GLSL_COLORMAPS, GLSL_COLORMAP_DEFAULT, COLORMAP_SHADER_PLACEHOLDER } from '../../layers/constants';\nimport module from './shader-module';\n\nconst defaultProps = {\n colormap: { type: 'string', value: GLSL_COLORMAP_DEFAULT, compare: true },\n colorScaleLo: { type: 'number', value: 0.0, compare: true },\n colorScaleHi: { type: 'number', value: 1.0, compare: true },\n isExpressionMode: false,\n getExpressionValue: { type: 'accessor', value: 0 },\n getSelectionState: { type: 'accessor', value: 0.0 },\n};\n\nexport default class ScaledExpressionExtension extends LayerExtension {\n getShaders() {\n const { colormap } = this.props;\n return {\n modules: [module],\n defines: {\n [COLORMAP_SHADER_PLACEHOLDER]: GLSL_COLORMAPS.includes(colormap)\n ? colormap\n : GLSL_COLORMAP_DEFAULT,\n },\n };\n }\n\n updateState({ props, oldProps }) {\n if (props.colormap !== oldProps.colormap) {\n const { gl } = this.context;\n // Normal single model layers, like ScatterplotLayer\n if (this.state.model) {\n // eslint-disable-next-line no-unused-expressions\n this.state.model?.delete();\n this.state.model = this._getModel(gl);\n } else {\n // Special handling for PolygonLayer sublayer models.\n if (this.state.models) {\n // eslint-disable-next-line no-unused-expressions\n this.state.models?.forEach(model => model?.delete());\n }\n if (this.state.topModel) {\n // eslint-disable-next-line no-unused-expressions\n this.state.topModel?.delete();\n }\n if (this.state.sideModel) {\n // eslint-disable-next-line no-unused-expressions\n this.state.sideModel?.delete();\n }\n if (this._getModels) {\n this.setState(this._getModels(this.context.gl));\n }\n }\n const attributeManager = this.getAttributeManager();\n if (attributeManager) {\n this.getAttributeManager().invalidateAll();\n }\n }\n }\n\n initializeState() {\n const layer = this.getCurrentLayer();\n // No need to run this on layers that don't have a `draw` call.\n if (layer.isComposite) {\n return;\n }\n const attributeManager = this.getAttributeManager();\n if (attributeManager) {\n // This attributes is the array of expression data needed for\n // coloring cells against the colormap.\n attributeManager.add({\n expressionValue: {\n type: GL.FLOAT,\n size: 1,\n transition: true,\n accessor: 'getExpressionValue',\n defaultValue: 1,\n // PolygonLayer fill needs not-intsanced attribute but\n // ScatterplotLayer and the PolygonLayer stroke needs instanced.\n // So use another attribute's divisor property as a proxy for this divisor.\n divisor: Object.values(attributeManager.attributes)[0].settings.divisor,\n },\n });\n }\n }\n\n draw() {\n const {\n colorScaleLo,\n colorScaleHi,\n isExpressionMode,\n } = this.props;\n const {\n topModel, sideModel, models, model,\n } = this.state;\n const uniforms = {\n uColorScaleRange: [colorScaleLo, colorScaleHi],\n uIsExpressionMode: isExpressionMode,\n };\n // ScatterplotLayer model\n // eslint-disable-next-line no-unused-expressions\n model?.setUniforms(uniforms);\n\n // PolygonLayer models from sublayers\n // eslint-disable-next-line no-unused-expressions\n models?.forEach(m => m.setUniforms(uniforms));\n // eslint-disable-next-line no-unused-expressions\n topModel?.setUniforms(uniforms);\n // eslint-disable-next-line no-unused-expressions\n sideModel?.setUniforms(uniforms);\n }\n}\n\nScaledExpressionExtension.extensionName = 'ScaledExpressionExtension';\nScaledExpressionExtension.defaultProps = defaultProps;\n","import ScaledExpressionExtension from './ScaledExpressionExtension';\n\nexport default ScaledExpressionExtension;\n","import glsl from 'glslify';\n\nconst vs = glsl`\nattribute float isSelected;\n`;\n\nconst inject = {\n 'vs:DECKGL_FILTER_GL_POSITION': `\n position.z += (1. - isSelected) * .00005; // Add a small z offset for unselected points in the positive direction i.e into the screen.\n `,\n 'fs:#main-start': ` // Gets rid of bad border effects (active after deck.gl 8.5): https://github.com/visgl/deck.gl/pull/6081\n float distToCenterNew = length(unitPosition) * outerRadiusPixels;\n float inCircleNew = step(distToCenterNew, outerRadiusPixels);\n if (inCircleNew == 0.0) {\n discard;\n }\n `,\n};\n\nexport default {\n name: 'selection',\n vs,\n inject,\n};\n","/* eslint-disable no-underscore-dangle */\n/* eslint-disable import/no-extraneous-dependencies */\nimport GL from '@luma.gl/constants';\nimport { LayerExtension } from '@deck.gl/core';\nimport module from './shader-module';\n\nexport default class SelectionExtension extends LayerExtension {\n // eslint-disable-next-line class-methods-use-this\n getShaders() {\n return {\n modules: [module],\n };\n }\n\n initializeState(context, extension) {\n const attributeManager = this.getAttributeManager();\n if (attributeManager) {\n attributeManager.add({\n isSelected: {\n type: GL.FLOAT,\n size: 1,\n transition: true,\n accessor: 'getCellIsSelected',\n defaultValue: 1,\n // PolygonLayer needs not-intsanced attribute but\n // ScatterplotLayer needs instanced.\n divisor: Number(extension.opts.instanced),\n },\n });\n }\n }\n}\n\nSelectionExtension.extensionName = 'SelectionExtension';\n","import SelectionExtension from './SelectionExtension';\n\nexport default SelectionExtension;\n","import React, { forwardRef } from 'react';\nimport { PolygonLayer, TextLayer, ScatterplotLayer } from '@deck.gl/layers'; // eslint-disable-line import/no-extraneous-dependencies\nimport { forceSimulation } from 'd3-force';\nimport { getSelectionLayers } from '../../layers';\nimport { cellLayerDefaultProps, getDefaultColor } from '../utils';\nimport {\n createCellsQuadTree,\n} from '../shared-spatial-scatterplot/quadtree';\nimport AbstractSpatialOrScatterplot from '../shared-spatial-scatterplot/AbstractSpatialOrScatterplot';\nimport { forceCollideRects } from '../shared-spatial-scatterplot/force-collide-rects';\nimport { ScaledExpressionExtension, SelectionExtension } from '../../layer-extensions';\n\nconst CELLS_LAYER_ID = 'scatterplot';\nconst LABEL_FONT_FAMILY = \"-apple-system, 'Helvetica Neue', Arial, sans-serif\";\nconst NUM_FORCE_SIMULATION_TICKS = 100;\nconst LABEL_UPDATE_ZOOM_DELTA = 0.25;\n\n// Default getter function props.\nconst makeDefaultGetCellPosition = mapping => (cellEntry) => {\n const { mappings } = cellEntry[1];\n if (!(mapping in mappings)) {\n const available = Object.keys(mappings).map(s => `\"${s}\"`).join(', ');\n throw new Error(`Expected to find \"${mapping}\", but available mappings are: ${available}`);\n }\n const mappedCell = mappings[mapping];\n // The negative applied to the y-axis is because\n // graphics rendering has the y-axis positive going south.\n return [mappedCell[0], -mappedCell[1], 0];\n};\nconst makeDefaultGetCellCoords = mapping => cell => cell.mappings[mapping];\nconst makeDefaultGetCellColors = (cellColors, theme) => (cellEntry) => {\n const [r, g, b, a] = (cellColors && cellColors.get(cellEntry[0])) || getDefaultColor(theme);\n return [r, g, b, 255 * (a || 1)];\n};\n\n/**\n * React component which renders a scatterplot from cell data, typically tSNE or PCA.\n * @param {object} props\n * @param {string} props.uuid A unique identifier for this component.\n * @param {string} props.theme The current vitessce theme.\n * @param {object} props.viewState The deck.gl view state.\n * @param {function} props.setViewState Function to call to update the deck.gl view state.\n * @param {object} props.cells\n * @param {string} props.mapping The name of the coordinate mapping field,\n * for each cell, for example \"PCA\" or \"t-SNE\".\n * @param {Map} props.cellColors Mapping of cell IDs to colors.\n * @param {array} props.cellSelection Array of selected cell IDs.\n * @param {array} props.cellFilter Array of filtered cell IDs. By default, null.\n * @param {number} props.cellRadius The value for `radiusScale` to pass\n * to the deck.gl cells ScatterplotLayer.\n * @param {number} props.cellOpacity The value for `opacity` to pass\n * to the deck.gl cells ScatterplotLayer.\n * @param {function} props.getCellCoords Getter function for cell coordinates\n * (used by the selection layer).\n * @param {function} props.getCellPosition Getter function for cell [x, y, z] position.\n * @param {function} props.getCellColor Getter function for cell color as [r, g, b] array.\n * @param {function} props.getCellIsSelected Getter function for cell layer isSelected.\n * @param {function} props.setCellSelection\n * @param {function} props.setCellHighlight\n * @param {function} props.updateViewInfo\n * @param {function} props.onToolChange Callback for tool changes\n * (lasso/pan/rectangle selection tools).\n * @param {function} props.onCellClick Getter function for cell layer onClick.\n */\nclass Scatterplot extends AbstractSpatialOrScatterplot {\n constructor(props) {\n super(props);\n\n // To avoid storing large arrays/objects\n // in React state, this component\n // uses instance variables.\n // All instance variables used in this class:\n this.cellsEntries = [];\n this.cellsQuadTree = null;\n this.cellsLayer = null;\n this.cellSetsForceSimulation = forceCollideRects();\n this.cellSetsLabelPrevZoom = null;\n this.cellSetsLayers = [];\n\n // Initialize data and layers.\n this.onUpdateCellsData();\n this.onUpdateCellsLayer();\n this.onUpdateCellSetsLayers();\n }\n\n createCellsLayer() {\n const { cellsEntries } = this;\n const {\n theme,\n mapping,\n getCellPosition = makeDefaultGetCellPosition(mapping),\n cellRadius = 1.0,\n cellOpacity = 1.0,\n cellFilter,\n cellSelection,\n setCellHighlight,\n setComponentHover,\n getCellIsSelected,\n cellColors,\n getCellColor = makeDefaultGetCellColors(cellColors, theme),\n getExpressionValue,\n onCellClick,\n geneExpressionColormap,\n geneExpressionColormapRange = [0.0, 1.0],\n cellColorEncoding,\n } = this.props;\n const filteredCellsEntries = (cellFilter\n ? cellsEntries.filter(cellEntry => cellFilter.includes(cellEntry[0]))\n : cellsEntries);\n return new ScatterplotLayer({\n id: CELLS_LAYER_ID,\n backgroundColor: (theme === 'dark' ? [0, 0, 0] : [241, 241, 241]),\n getCellIsSelected,\n opacity: cellOpacity,\n radiusScale: cellRadius,\n radiusMinPixels: 1,\n radiusMaxPixels: 30,\n // Our radius pixel setters measure in pixels.\n radiusUnits: 'pixels',\n lineWidthUnits: 'pixels',\n getPosition: getCellPosition,\n getFillColor: getCellColor,\n getLineColor: getCellColor,\n getRadius: 1,\n getExpressionValue,\n getLineWidth: 0,\n extensions: [\n new ScaledExpressionExtension(),\n new SelectionExtension({ instanced: true }),\n ],\n colorScaleLo: geneExpressionColormapRange[0],\n colorScaleHi: geneExpressionColormapRange[1],\n isExpressionMode: (cellColorEncoding === 'geneSelection'),\n colormap: geneExpressionColormap,\n onClick: (info) => {\n if (onCellClick) {\n onCellClick(info);\n }\n },\n updateTriggers: {\n getExpressionValue,\n getFillColor: [cellColorEncoding, cellSelection, cellColors],\n getLineColor: [cellColorEncoding, cellSelection, cellColors],\n getCellIsSelected,\n },\n ...cellLayerDefaultProps(\n filteredCellsEntries, undefined, setCellHighlight, setComponentHover,\n ),\n stroked: 0,\n });\n }\n\n createCellSetsLayers() {\n const {\n theme,\n cellSetPolygons,\n viewState,\n cellSetPolygonsVisible,\n cellSetLabelsVisible,\n cellSetLabelSize,\n } = this.props;\n\n const result = [];\n\n if (cellSetPolygonsVisible) {\n result.push(new PolygonLayer({\n id: 'cell-sets-polygon-layer',\n data: cellSetPolygons,\n stroked: true,\n filled: false,\n wireframe: true,\n lineWidthMaxPixels: 1,\n getPolygon: d => d.hull,\n getLineColor: d => d.color,\n getLineWidth: 1,\n }));\n }\n\n if (cellSetLabelsVisible) {\n const { zoom } = viewState;\n const nodes = cellSetPolygons.map(p => ({\n x: p.centroid[0],\n y: p.centroid[1],\n label: p.name,\n }));\n\n const collisionForce = this.cellSetsForceSimulation\n .size(d => ([\n cellSetLabelSize * 1 / (2 ** zoom) * 4 * d.label.length,\n cellSetLabelSize * 1 / (2 ** zoom) * 1.5,\n ]));\n\n forceSimulation()\n .nodes(nodes)\n .force('collision', collisionForce)\n .tick(NUM_FORCE_SIMULATION_TICKS);\n\n result.push(new TextLayer({\n id: 'cell-sets-text-layer',\n data: nodes,\n getPosition: d => ([d.x, d.y]),\n getText: d => d.label,\n getColor: (theme === 'dark' ? [255, 255, 255] : [0, 0, 0]),\n getSize: cellSetLabelSize,\n getAngle: 0,\n getTextAnchor: 'middle',\n getAlignmentBaseline: 'center',\n fontFamily: LABEL_FONT_FAMILY,\n fontWeight: 'normal',\n }));\n }\n\n return result;\n }\n\n createSelectionLayers() {\n const {\n viewState,\n mapping,\n getCellCoords = makeDefaultGetCellCoords(mapping),\n setCellSelection,\n } = this.props;\n const { tool } = this.state;\n const { cellsQuadTree } = this;\n const flipYTooltip = true;\n return getSelectionLayers(\n tool,\n viewState.zoom,\n CELLS_LAYER_ID,\n getCellCoords,\n setCellSelection,\n cellsQuadTree,\n flipYTooltip,\n );\n }\n\n getLayers() {\n const {\n cellsLayer,\n cellSetsLayers,\n } = this;\n return [\n cellsLayer,\n ...cellSetsLayers,\n ...this.createSelectionLayers(),\n ];\n }\n\n onUpdateCellsData() {\n const {\n cells = {},\n mapping,\n getCellCoords = makeDefaultGetCellCoords(mapping),\n } = this.props;\n const cellsEntries = Object.entries(cells);\n this.cellsEntries = cellsEntries;\n this.cellsQuadTree = createCellsQuadTree(cellsEntries, getCellCoords);\n }\n\n onUpdateCellsLayer() {\n this.cellsLayer = this.createCellsLayer();\n }\n\n onUpdateCellSetsLayers(onlyViewStateChange) {\n // Because the label sizes for the force simulation depend on the zoom level,\n // we _could_ run the simulation every time the zoom level changes.\n // However, this has a performance impact in firefox.\n if (onlyViewStateChange) {\n const { viewState, cellSetLabelsVisible } = this.props;\n const { zoom } = viewState;\n const { cellSetsLabelPrevZoom } = this;\n // Instead, we can just check if the zoom level has changed\n // by some relatively large delta, to be more conservative\n // about re-running the force simulation.\n if (cellSetLabelsVisible\n && (\n cellSetsLabelPrevZoom === null\n || Math.abs(cellSetsLabelPrevZoom - zoom) > LABEL_UPDATE_ZOOM_DELTA\n )\n ) {\n this.cellSetsLayers = this.createCellSetsLayers();\n this.cellSetsLabelPrevZoom = zoom;\n }\n } else {\n // Otherwise, something more substantial than just\n // the viewState has changed, such as the label array\n // itself, so we always want to update the layer\n // in this case.\n this.cellSetsLayers = this.createCellSetsLayers();\n }\n }\n\n viewInfoDidUpdate() {\n const {\n mapping,\n getCellPosition = makeDefaultGetCellPosition(mapping),\n } = this.props;\n super.viewInfoDidUpdate(cell => getCellPosition([null, cell]));\n }\n\n /**\n * Here, asynchronously check whether props have\n * updated which require re-computing memoized variables,\n * followed by a re-render.\n * This function does not follow React conventions or paradigms,\n * it is only implemented this way to try to squeeze out\n * performance.\n * @param {object} prevProps The previous props to diff against.\n */\n componentDidUpdate(prevProps) {\n this.viewInfoDidUpdate();\n\n const shallowDiff = propName => (prevProps[propName] !== this.props[propName]);\n if (['cells'].some(shallowDiff)) {\n // Cells data changed.\n this.onUpdateCellsData();\n this.forceUpdate();\n }\n\n if ([\n 'cells', 'cellFilter', 'cellSelection', 'cellColors',\n 'cellRadius', 'cellOpacity', 'cellRadiusMode', 'geneExpressionColormap',\n 'geneExpressionColormapRange', 'geneSelection', 'cellColorEncoding',\n ].some(shallowDiff)) {\n // Cells layer props changed.\n this.onUpdateCellsLayer();\n this.forceUpdate();\n }\n if ([\n 'cellSetPolygons', 'cellSetPolygonsVisible',\n 'cellSetLabelsVisible', 'cellSetLabelSize',\n ].some(shallowDiff)) {\n // Cell sets layer props changed.\n this.onUpdateCellSetsLayers(false);\n this.forceUpdate();\n }\n if (shallowDiff('viewState')) {\n // The viewState prop has changed (due to zoom or pan).\n this.onUpdateCellSetsLayers(true);\n this.forceUpdate();\n }\n }\n\n // render() is implemented in the abstract parent class.\n}\n\n/**\n * Need this wrapper function here,\n * since we want to pass a forwardRef\n * so that outer components can\n * access the grandchild DeckGL ref,\n * but we are using a class component.\n */\nconst ScatterplotWrapper = forwardRef((props, deckRef) => (\n \n));\nexport default ScatterplotWrapper;\n","import { makeStyles } from '@material-ui/core/styles';\n\nexport const styles = makeStyles(() => ({\n tooltipAnchor: {\n position: 'relative',\n width: '0px',\n height: '0px',\n pointerEvents: 'none',\n userSelect: 'none',\n },\n tooltipContent: {\n opacity: 0.9,\n padding: '5px',\n pointerEvents: 'none',\n '& table > tbody > tr > th, & table > tbody > tr > td': {\n fontSize: '80%',\n opacity: 0.8,\n outline: 0,\n padding: '0 2px',\n },\n '& table': {\n borderCollapse: 'collapse',\n },\n },\n}));\n","import React, { useEffect, useRef, useState } from 'react';\nimport Paper from '@material-ui/core/Paper';\nimport Popper from '@material-ui/core/Popper';\nimport { useVitessceContainer } from '../hooks';\nimport { styles } from './styles';\n\nexport default function Tooltip(props) {\n const {\n x,\n y,\n parentWidth,\n parentHeight,\n children,\n } = props;\n const ref = useRef();\n const classes = styles();\n const [placementX, setPlacementX] = useState('start');\n const [placementY, setPlacementY] = useState('bottom');\n\n const getTooltipContainer = useVitessceContainer(ref);\n\n // Do collision detection based on the bounds of the tooltip ancestor element.\n useEffect(() => {\n if (ref && ref.current) {\n const flipX = (x > parentWidth / 2);\n const flipY = (y > parentHeight / 2);\n setPlacementX(flipX ? 'end' : 'start');\n setPlacementY(flipY ? 'top' : 'bottom');\n ref.current.style.left = `${x + (flipX ? -20 : 5)}px`;\n ref.current.style.top = `${y + (flipY ? -20 : 5)}px`;\n }\n }, [x, y, parentWidth, parentHeight]);\n\n return (\n \n {ref && ref.current ? (\n \n \n {children}\n \n \n ) : null}\n \n );\n}\n","import React from 'react';\nimport Tooltip from './Tooltip';\n\n/**\n * A tooltip component that also incorporates a crosshair element.\n * @param {object} props\n * @param {string} props.parentUuid A unique identifier corresponding to the plot\n * with which this scatterplot is associated.\n * @param {string} props.sourceUuid A unique identifier corresponding to the plot\n * from which this tooltip originated.\n * @param {number} props.x The x coordinate for the tooltip.\n * @param {number} props.y The y coordinate for the tooltip.\n * @param {number} props.parentWidth The width of the parent plot container element.\n * @param {number} props.parentHeight The height of the parent plot container element.\n * @param {React.Component} props.children The tooltip contents as a react component.\n */\nexport default function Tooltip2D(props) {\n const {\n parentUuid,\n sourceUuid,\n x,\n y,\n parentWidth,\n parentHeight,\n children,\n } = props;\n // Check if out of bounds.\n if (x < 0 || x > parentWidth || y < 0 || y > parentHeight) {\n return null;\n }\n // Show tooltip or crosshair?\n const isTooltipVisible = (parentUuid === sourceUuid);\n const crosshairWidth = 1;\n return (\n <>\n {isTooltipVisible ? (\n \n {children}\n \n ) : (\n <>\n {x !== null ? (\n \n ) : null}\n {y !== null ? (\n \n ) : null}\n \n )}\n \n );\n}\n","import React from 'react';\n\nexport default function TooltipContent(props) {\n const {\n info,\n } = props;\n\n return (\n \n \n {Object.entries(info).map(([key, value]) => (\n \n \n \n \n ))}\n \n
{key}{value}
\n );\n}\n","import React from 'react';\nimport Tooltip2D from '../tooltip/Tooltip2D';\nimport TooltipContent from '../tooltip/TooltipContent';\nimport { useComponentHover, useComponentViewInfo } from '../../app/state/hooks';\n\nexport default function ScatterplotTooltipSubscriber(props) {\n const {\n parentUuid,\n cellHighlight,\n width,\n height,\n getCellInfo,\n } = props;\n\n const sourceUuid = useComponentHover();\n const viewInfo = useComponentViewInfo(parentUuid);\n\n const [cellInfo, x, y] = (cellHighlight && getCellInfo ? (\n [\n getCellInfo(cellHighlight),\n ...(viewInfo && viewInfo.project ? viewInfo.project(cellHighlight) : [null, null]),\n ]\n ) : ([null, null, null]));\n\n return (\n (cellInfo ? (\n \n \n \n ) : null)\n );\n}\n","import { makeStyles } from '@material-ui/core/styles';\n\nexport const useStyles = makeStyles(theme => ({\n box: {\n boxSizing: 'border-box',\n },\n checkbox: {\n padding: '3px',\n color: theme.palette.primaryForeground,\n '&:checked': {\n color: theme.palette.primaryForeground,\n },\n '& input': {\n height: '100%',\n },\n },\n slider: {\n color: theme.palette.primaryForeground,\n minWidth: '60px',\n padding: '10px 0 10px 0',\n },\n sliderValueLabel: {\n '& span': {\n '& span': {\n color: theme.palette.primaryBackground,\n },\n },\n },\n tableContainer: {\n overflow: 'hidden',\n overflowX: 'hidden !important',\n },\n labelCell: {\n padding: '2px 8px 2px 16px',\n },\n inputCell: {\n padding: '2px 16px 2px 8px',\n overflow: 'visible',\n },\n select: {\n '& select': {\n fontSize: '.875rem',\n },\n },\n selectRoot: {\n padding: 0,\n height: 'auto',\n },\n}));\n","import React from 'react';\nimport Box from '@material-ui/core/Box';\nimport Table from '@material-ui/core/Table';\nimport TableBody from '@material-ui/core/TableBody';\nimport TableContainer from '@material-ui/core/TableContainer';\nimport { useStyles } from './styles';\n\nexport default function OptionsContainer(props) {\n const {\n children,\n } = props;\n\n const classes = useStyles();\n\n return (\n \n \n \n \n {children}\n \n
\n
\n
\n );\n}\n","import React from 'react';\nimport Select from '@material-ui/core/Select';\nimport { useStyles } from './styles';\n\nexport default function OptionSelect(props) {\n const { classes: classesProp = {} } = props;\n const classes = useStyles();\n return (\n \n );\n}\n","import React from 'react';\nimport TableCell from '@material-ui/core/TableCell';\nimport TableRow from '@material-ui/core/TableRow';\nimport { capitalize } from '../../utils';\nimport OptionSelect from './OptionSelect';\nimport { useStyles } from './styles';\n\nexport default function CellColorEncodingOption(props) {\n const {\n observationsLabel,\n cellColorEncoding,\n setCellColorEncoding,\n } = props;\n\n const classes = useStyles();\n\n const observationsLabelNice = capitalize(observationsLabel);\n\n function handleColorEncodingChange(event) {\n setCellColorEncoding(event.target.value);\n }\n\n return (\n \n \n {observationsLabelNice} Color Encoding\n \n \n \n \n \n \n \n \n );\n}\n","import React, { useCallback } from 'react';\nimport debounce from 'lodash/debounce';\nimport Checkbox from '@material-ui/core/Checkbox';\nimport Slider from '@material-ui/core/Slider';\nimport TableCell from '@material-ui/core/TableCell';\nimport TableRow from '@material-ui/core/TableRow';\nimport { capitalize } from '../../utils';\nimport { useStyles } from '../shared-plot-options/styles';\nimport OptionsContainer from '../shared-plot-options/OptionsContainer';\nimport OptionSelect from '../shared-plot-options/OptionSelect';\nimport CellColorEncodingOption from '../shared-plot-options/CellColorEncodingOption';\nimport { GLSL_COLORMAPS } from '../../layers/constants';\n\nexport default function ScatterplotOptions(props) {\n const {\n observationsLabel,\n cellRadius,\n setCellRadius,\n cellRadiusMode,\n setCellRadiusMode,\n cellOpacity,\n setCellOpacity,\n cellOpacityMode,\n setCellOpacityMode,\n cellSetLabelsVisible,\n setCellSetLabelsVisible,\n cellSetLabelSize,\n setCellSetLabelSize,\n cellSetPolygonsVisible,\n setCellSetPolygonsVisible,\n cellColorEncoding,\n setCellColorEncoding,\n geneExpressionColormap,\n setGeneExpressionColormap,\n geneExpressionColormapRange,\n setGeneExpressionColormapRange,\n } = props;\n\n const observationsLabelNice = capitalize(observationsLabel);\n\n const classes = useStyles();\n\n function handleCellRadiusModeChange(event) {\n setCellRadiusMode(event.target.value);\n }\n\n function handleCellOpacityModeChange(event) {\n setCellOpacityMode(event.target.value);\n }\n\n function handleRadiusChange(event, value) {\n setCellRadius(value);\n }\n\n function handleOpacityChange(event, value) {\n setCellOpacity(value);\n }\n\n function handleLabelVisibilityChange(event) {\n setCellSetLabelsVisible(event.target.checked);\n }\n\n function handleLabelSizeChange(event, value) {\n setCellSetLabelSize(value);\n }\n\n function handlePolygonVisibilityChange(event) {\n setCellSetPolygonsVisible(event.target.checked);\n }\n\n function handleGeneExpressionColormapChange(event) {\n setGeneExpressionColormap(event.target.value);\n }\n\n function handleColormapRangeChange(event, value) {\n setGeneExpressionColormapRange(value);\n }\n const handleColormapRangeChangeDebounced = useCallback(\n debounce(handleColormapRangeChange, 5, { trailing: true }),\n [handleColormapRangeChange],\n );\n\n return (\n \n \n \n \n {observationsLabelNice} Set Labels Visible\n \n \n \n \n \n \n \n {observationsLabelNice} Set Label Size\n \n \n \n \n \n \n \n {observationsLabelNice} Set Polygons Visible\n \n \n \n \n \n \n \n {observationsLabelNice} Radius Mode\n \n \n \n \n \n \n \n \n \n \n {observationsLabelNice} Radius\n \n \n \n \n \n \n \n {observationsLabelNice} Opacity Mode\n \n \n \n \n \n \n \n \n \n \n {observationsLabelNice} Opacity\n \n \n \n \n \n \n \n Gene Expression Colormap\n \n \n \n {GLSL_COLORMAPS.map(cmap => (\n \n ))}\n \n \n \n \n \n Gene Expression Colormap Range\n \n \n \n \n \n \n );\n}\n","import React, {\n useState, useEffect, useCallback, useMemo,\n} from 'react';\nimport { extent } from 'd3-array';\nimport isEqual from 'lodash/isEqual';\nimport TitleInfo from '../TitleInfo';\nimport { pluralize, capitalize } from '../../utils';\nimport {\n useDeckCanvasSize, useReady, useUrls, useExpressionValueGetter,\n} from '../hooks';\nimport { setCellSelection, mergeCellSets } from '../utils';\nimport { getCellSetPolygons } from '../sets/cell-set-utils';\nimport {\n useCellsData,\n useCellSetsData,\n useGeneSelection,\n useExpressionAttrs,\n} from '../data-hooks';\nimport { getCellColors } from '../interpolate-colors';\nimport Scatterplot from './Scatterplot';\nimport ScatterplotTooltipSubscriber from './ScatterplotTooltipSubscriber';\nimport ScatterplotOptions from './ScatterplotOptions';\nimport {\n useCoordination,\n useLoaders,\n useSetComponentHover,\n useSetComponentViewInfo,\n} from '../../app/state/hooks';\nimport {\n getPointSizeDevicePixels,\n getPointOpacity,\n} from '../shared-spatial-scatterplot/dynamic-opacity';\nimport { COMPONENT_COORDINATION_TYPES } from '../../app/state/coordination';\n\nconst SCATTERPLOT_DATA_TYPES = ['cells', 'expression-matrix', 'cell-sets'];\n\n/**\n * A subscriber component for the scatterplot.\n * @param {object} props\n * @param {number} props.uuid The unique identifier for this component.\n * @param {string} props.theme The current theme name.\n * @param {object} props.coordinationScopes The mapping from coordination types to coordination\n * scopes.\n * @param {boolean} props.disableTooltip Should the tooltip be disabled?\n * @param {function} props.removeGridComponent The callback function to pass to TitleInfo,\n * to call when the component has been removed from the grid.\n * @param {string} props.title An override value for the component title.\n * @param {number} props.averageFillDensity Override the average fill density calculation\n * when using dynamic opacity mode.\n */\nexport default function ScatterplotSubscriber(props) {\n const {\n uuid,\n coordinationScopes,\n removeGridComponent,\n theme,\n disableTooltip = false,\n observationsLabelOverride: observationsLabel = 'cell',\n observationsPluralLabelOverride: observationsPluralLabel = `${observationsLabel}s`,\n title: titleOverride,\n // Average fill density for dynamic opacity calculation.\n averageFillDensity,\n } = props;\n\n const loaders = useLoaders();\n const setComponentHover = useSetComponentHover();\n const setComponentViewInfo = useSetComponentViewInfo(uuid);\n\n // Get \"props\" from the coordination space.\n const [{\n dataset,\n embeddingZoom: zoom,\n embeddingTargetX: targetX,\n embeddingTargetY: targetY,\n embeddingTargetZ: targetZ,\n embeddingType: mapping,\n cellFilter,\n cellHighlight,\n geneSelection,\n cellSetSelection,\n cellSetColor,\n cellColorEncoding,\n additionalCellSets,\n embeddingCellSetPolygonsVisible: cellSetPolygonsVisible,\n embeddingCellSetLabelsVisible: cellSetLabelsVisible,\n embeddingCellSetLabelSize: cellSetLabelSize,\n embeddingCellRadius: cellRadiusFixed,\n embeddingCellRadiusMode: cellRadiusMode,\n embeddingCellOpacity: cellOpacityFixed,\n embeddingCellOpacityMode: cellOpacityMode,\n geneExpressionColormap,\n geneExpressionColormapRange,\n }, {\n setEmbeddingZoom: setZoom,\n setEmbeddingTargetX: setTargetX,\n setEmbeddingTargetY: setTargetY,\n setEmbeddingTargetZ: setTargetZ,\n setCellFilter,\n setCellSetSelection,\n setCellHighlight,\n setCellSetColor,\n setCellColorEncoding,\n setAdditionalCellSets,\n setEmbeddingCellSetPolygonsVisible: setCellSetPolygonsVisible,\n setEmbeddingCellSetLabelsVisible: setCellSetLabelsVisible,\n setEmbeddingCellSetLabelSize: setCellSetLabelSize,\n setEmbeddingCellRadius: setCellRadiusFixed,\n setEmbeddingCellRadiusMode: setCellRadiusMode,\n setEmbeddingCellOpacity: setCellOpacityFixed,\n setEmbeddingCellOpacityMode: setCellOpacityMode,\n setGeneExpressionColormap,\n setGeneExpressionColormapRange,\n }] = useCoordination(COMPONENT_COORDINATION_TYPES.scatterplot, coordinationScopes);\n\n const [urls, addUrl, resetUrls] = useUrls();\n const [width, height, deckRef] = useDeckCanvasSize();\n const [\n isReady,\n setItemIsReady,\n setItemIsNotReady, // eslint-disable-line no-unused-vars\n resetReadyItems,\n ] = useReady(\n SCATTERPLOT_DATA_TYPES,\n );\n\n const title = titleOverride || `Scatterplot (${mapping})`;\n\n // Reset file URLs and loader progress when the dataset has changed.\n useEffect(() => {\n resetUrls();\n resetReadyItems();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loaders, dataset]);\n\n // Get data from loaders using the data hooks.\n const [cells, cellsCount] = useCellsData(loaders, dataset, setItemIsReady, addUrl, true);\n const [cellSets] = useCellSetsData(\n loaders,\n dataset,\n setItemIsReady,\n addUrl,\n false,\n { setCellSetSelection, setCellSetColor },\n { cellSetSelection, cellSetColor },\n );\n const [expressionData] = useGeneSelection(\n loaders, dataset, setItemIsReady, false, geneSelection, setItemIsNotReady,\n );\n const [attrs] = useExpressionAttrs(\n loaders, dataset, setItemIsReady, addUrl, false,\n );\n\n const [dynamicCellRadius, setDynamicCellRadius] = useState(cellRadiusFixed);\n const [dynamicCellOpacity, setDynamicCellOpacity] = useState(cellOpacityFixed);\n\n const mergedCellSets = useMemo(() => mergeCellSets(\n cellSets, additionalCellSets,\n ), [cellSets, additionalCellSets]);\n\n const setCellSelectionProp = useCallback((v) => {\n setCellSelection(\n v, additionalCellSets, cellSetColor,\n setCellSetSelection, setAdditionalCellSets, setCellSetColor,\n setCellColorEncoding,\n );\n }, [additionalCellSets, cellSetColor, setCellColorEncoding,\n setAdditionalCellSets, setCellSetColor, setCellSetSelection]);\n\n const cellColors = useMemo(() => getCellColors({\n cellColorEncoding,\n expressionData: expressionData && expressionData[0],\n geneSelection,\n cellSets: mergedCellSets,\n cellSetSelection,\n cellSetColor,\n expressionDataAttrs: attrs,\n theme,\n }), [cellColorEncoding, geneSelection, mergedCellSets, theme,\n cellSetSelection, cellSetColor, expressionData, attrs]);\n\n // cellSetPolygonCache is an array of tuples like [(key0, val0), (key1, val1), ...],\n // where the keys are cellSetSelection arrays.\n const [cellSetPolygonCache, setCellSetPolygonCache] = useState([]);\n const cacheHas = (cache, key) => cache.findIndex(el => isEqual(el[0], key)) !== -1;\n const cacheGet = (cache, key) => cache.find(el => isEqual(el[0], key))?.[1];\n const cellSetPolygons = useMemo(() => {\n if ((cellSetLabelsVisible || cellSetPolygonsVisible)\n && !cacheHas(cellSetPolygonCache, cellSetSelection)\n && mergedCellSets?.tree?.length\n && Object.values(cells).length\n && cellSetColor?.length) {\n const newCellSetPolygons = getCellSetPolygons({\n cells,\n mapping,\n cellSets: mergedCellSets,\n cellSetSelection,\n cellSetColor,\n theme,\n });\n setCellSetPolygonCache(cache => [...cache, [cellSetSelection, newCellSetPolygons]]);\n return newCellSetPolygons;\n }\n return cacheGet(cellSetPolygonCache, cellSetSelection) || [];\n }, [cellSetPolygonsVisible, cellSetPolygonCache, cellSetLabelsVisible, theme,\n cells, mapping, mergedCellSets, cellSetSelection, cellSetColor]);\n\n\n const cellSelection = useMemo(() => Array.from(cellColors.keys()), [cellColors]);\n\n const [xRange, yRange, xExtent, yExtent, numCells] = useMemo(() => {\n const cellValues = cells && Object.values(cells);\n if (cellValues?.length) {\n const cellCoordinates = Object.values(cells)\n .map(c => c.mappings[mapping]);\n const xE = extent(cellCoordinates, c => c[0]);\n const yE = extent(cellCoordinates, c => c[1]);\n const xR = xE[1] - xE[0];\n const yR = yE[1] - yE[0];\n return [xR, yR, xE, yE, cellValues.length];\n }\n return [null, null, null, null, null];\n }, [cells, mapping]);\n\n // After cells have loaded or changed,\n // compute the cell radius scale based on the\n // extents of the cell coordinates on the x/y axes.\n useEffect(() => {\n if (xRange && yRange) {\n const pointSizeDevicePixels = getPointSizeDevicePixels(\n window.devicePixelRatio, zoom, xRange, yRange, width, height,\n );\n setDynamicCellRadius(pointSizeDevicePixels);\n\n const nextCellOpacityScale = getPointOpacity(\n zoom, xRange, yRange, width, height, numCells, averageFillDensity,\n );\n setDynamicCellOpacity(nextCellOpacityScale);\n\n if (typeof targetX !== 'number' || typeof targetY !== 'number') {\n const newTargetX = xExtent[0] + xRange / 2;\n const newTargetY = yExtent[0] + yRange / 2;\n const newZoom = Math.log2(Math.min(width / xRange, height / yRange));\n setTargetX(newTargetX);\n // Graphics rendering has the y-axis going south so we need to multiply by negative one.\n setTargetY(-newTargetY);\n setZoom(newZoom);\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [xRange, yRange, xExtent, yExtent, numCells, cells, mapping,\n width, height, zoom, averageFillDensity]);\n\n const getCellInfo = useCallback((cellId) => {\n const cellInfo = cells[cellId];\n return {\n [`${capitalize(observationsLabel)} ID`]: cellId,\n ...(cellInfo ? cellInfo.factors : {}),\n };\n }, [cells, observationsLabel]);\n\n const cellSelectionSet = useMemo(() => new Set(cellSelection), [cellSelection]);\n const getCellIsSelected = useCallback(cellEntry => (\n (cellSelectionSet || new Set([])).has(cellEntry[0]) ? 1.0 : 0.0), [cellSelectionSet]);\n\n const cellRadius = (cellRadiusMode === 'manual' ? cellRadiusFixed : dynamicCellRadius);\n const cellOpacity = (cellOpacityMode === 'manual' ? cellOpacityFixed : dynamicCellOpacity);\n\n // Set up a getter function for gene expression values, to be used\n // by the DeckGL layer to obtain values for instanced attributes.\n const getExpressionValue = useExpressionValueGetter({ attrs, expressionData });\n\n return (\n \n )}\n >\n {\n setZoom(newZoom);\n setTargetX(target[0]);\n setTargetY(target[1]);\n setTargetZ(target[2] || 0);\n }}\n cells={cells}\n mapping={mapping}\n cellFilter={cellFilter}\n cellSelection={cellSelection}\n cellHighlight={cellHighlight}\n cellColors={cellColors}\n cellSetPolygons={cellSetPolygons}\n cellSetLabelSize={cellSetLabelSize}\n cellSetLabelsVisible={cellSetLabelsVisible}\n cellSetPolygonsVisible={cellSetPolygonsVisible}\n setCellFilter={setCellFilter}\n setCellSelection={setCellSelectionProp}\n setCellHighlight={setCellHighlight}\n cellRadius={cellRadius}\n cellOpacity={cellOpacity}\n cellColorEncoding={cellColorEncoding}\n geneExpressionColormap={geneExpressionColormap}\n geneExpressionColormapRange={geneExpressionColormapRange}\n setComponentHover={() => {\n setComponentHover(uuid);\n }}\n updateViewInfo={setComponentViewInfo}\n getExpressionValue={getExpressionValue}\n getCellIsSelected={getCellIsSelected}\n\n />\n {!disableTooltip && (\n \n )}\n \n );\n}\n","import React, { forwardRef } from 'react';\nimport isEqual from 'lodash/isEqual';\nimport { COORDINATE_SYSTEM } from '@deck.gl/core'; // eslint-disable-line import/no-extraneous-dependencies\nimport { PolygonLayer, ScatterplotLayer } from '@deck.gl/layers'; // eslint-disable-line import/no-extraneous-dependencies\nimport { Matrix4 } from 'math.gl';\nimport {\n ScaleBarLayer,\n MultiscaleImageLayer,\n AdditiveColormapExtension,\n ColorPaletteExtension,\n} from '@hms-dbmi/viv';\nimport { getSelectionLayers } from '../../layers';\nimport { cellLayerDefaultProps, PALETTE, getDefaultColor } from '../utils';\nimport { getSourceFromLoader } from '../../utils';\nimport { square, getLayerLoaderTuple, renderSubBitmaskLayers } from './utils';\nimport AbstractSpatialOrScatterplot from '../shared-spatial-scatterplot/AbstractSpatialOrScatterplot';\nimport { createCellsQuadTree } from '../shared-spatial-scatterplot/quadtree';\nimport { ScaledExpressionExtension } from '../../layer-extensions';\n\nconst CELLS_LAYER_ID = 'cells-layer';\nconst MOLECULES_LAYER_ID = 'molecules-layer';\nconst NEIGHBORHOODS_LAYER_ID = 'neighborhoods-layer';\n\n// Default getter function props.\nconst defaultGetCellCoords = cell => cell.xy;\nconst makeDefaultGetCellPolygon = radius => (cellEntry) => {\n const cell = cellEntry[1];\n return cell.poly?.length ? cell.poly : square(cell.xy[0], cell.xy[1], radius);\n};\nconst makeDefaultGetCellColors = (cellColors, theme) => (cellEntry) => {\n const [r, g, b, a] = (cellColors && cellColors.get(cellEntry[0])) || getDefaultColor(theme);\n return [r, g, b, 255 * (a || 1)];\n};\nconst makeDefaultGetCellIsSelected = (cellSelection) => {\n if (cellSelection) {\n // For performance, convert the Array to a Set instance.\n // Set.has() is faster than Array.includes().\n const cellSelectionSet = new Set(cellSelection);\n return cellEntry => (cellSelectionSet.has(cellEntry[0]) ? 1.0 : 0.0);\n }\n return () => 0.0;\n};\n\n/**\n * React component which expresses the spatial relationships between cells and molecules.\n * @param {object} props\n * @param {string} props.uuid A unique identifier for this component,\n * used to determine when to show tooltips vs. crosshairs.\n * @param {number} props.height Height of the DeckGL canvas, used when\n * rendering the scale bar layer.\n * @param {number} props.width Width of the DeckGL canvas, used when\n * rendering the scale bar layer.\n * @param {object} props.viewState The DeckGL viewState object.\n * @param {function} props.setViewState A handler for updating the DeckGL\n * viewState object.\n * @param {object} props.molecules Molecules data.\n * @param {object} props.cells Cells data.\n * @param {object} props.neighborhoods Neighborhoods data.\n * @param {number} props.lineWidthScale Width of cell border in view space (deck.gl).\n * @param {number} props.lineWidthMaxPixels Max width of the cell border in pixels (deck.gl).\n * @param {object} props.imageLayerLoaders An object mapping raster layer index to Viv loader\n * instances.\n * @param {object} props.cellColors Map from cell IDs to colors [r, g, b].\n * @param {function} props.getCellCoords Getter function for cell coordinates\n * (used by the selection layer).\n * @param {function} props.getCellColor Getter function for cell color as [r, g, b] array.\n * @param {function} props.getCellPolygon Getter function for cell polygons.\n * @param {function} props.getCellIsSelected Getter function for cell layer isSelected.\n * @param {function} props.getMoleculeColor\n * @param {function} props.getMoleculePosition\n * @param {function} props.getNeighborhoodPolygon\n * @param {function} props.updateViewInfo Handler for DeckGL viewport updates,\n * used when rendering tooltips and crosshairs.\n * @param {function} props.onCellClick Getter function for cell layer onClick.\n * @param {string} props.theme \"light\" or \"dark\" for the vitessce theme\n */\nclass Spatial extends AbstractSpatialOrScatterplot {\n constructor(props) {\n super(props);\n\n // To avoid storing large arrays/objects\n // in React state, this component\n // uses instance variables.\n // All instance variables used in this class:\n this.cellsEntries = [];\n this.moleculesEntries = [];\n this.cellsQuadTree = null;\n this.cellsLayer = null;\n this.moleculesLayer = null;\n this.neighborhoodsLayer = null;\n this.imageLayers = [];\n this.layerLoaderSelections = {};\n // Better for the bitmask layer when there is no color data to use this.\n // 2048 is best for performance and for stability (4096 texture size is not always supported).\n this.randomColorData = {\n data: new Uint8Array(2048 * 2048 * 3)\n .map((_, j) => (j < 4 ? 0 : Math.round(255 * Math.random()))),\n // This buffer should be able to hold colors for 2048 x 2048 ~ 4 million cells.\n height: 2048,\n width: 2048,\n };\n this.color = { ...this.randomColorData };\n this.expression = {\n data: new Uint8Array(2048 * 2048),\n // This buffer should be able to hold colors for 2048 x 2048 ~ 4 million cells.\n height: 2048,\n width: 2048,\n };\n\n // Initialize data and layers.\n this.onUpdateCellsData();\n this.onUpdateCellsLayer();\n this.onUpdateMoleculesData();\n this.onUpdateMoleculesLayer();\n this.onUpdateNeighborhoodsData();\n this.onUpdateNeighborhoodsLayer();\n this.onUpdateImages();\n }\n\n createCellsLayer(layerDef) {\n const {\n radius, stroked, visible, opacity,\n } = layerDef;\n const { cellsEntries } = this;\n const {\n theme,\n cellFilter,\n cellSelection,\n setCellHighlight,\n setComponentHover,\n getCellIsSelected = makeDefaultGetCellIsSelected(\n cellsEntries.length === cellSelection.length ? null : cellSelection,\n ),\n cellColors,\n getCellColor = makeDefaultGetCellColors(cellColors, theme),\n getCellPolygon = makeDefaultGetCellPolygon(radius),\n onCellClick,\n lineWidthScale = 10,\n lineWidthMaxPixels = 2,\n geneExpressionColormapRange,\n cellColorEncoding,\n getExpressionValue,\n geneExpressionColormap,\n } = this.props;\n const filteredCellsEntries = cellFilter\n ? cellsEntries.filter(cellEntry => cellFilter.includes(cellEntry[0]))\n : cellsEntries;\n\n // Graphics rendering has the y-axis positive going south,\n // so we need to flip it for rendering tooltips.\n const flipYTooltip = true;\n\n return new PolygonLayer({\n id: CELLS_LAYER_ID,\n backgroundColor: [0, 0, 0],\n isSelected: getCellIsSelected,\n getPolygon: getCellPolygon,\n updateTriggers: {\n getLineWidth: [stroked],\n isSelected: cellSelection,\n getExpressionValue,\n getFillColor: [opacity, cellColorEncoding, cellSelection, cellColors],\n getLineColor: [cellColorEncoding, cellSelection, cellColors],\n },\n getFillColor: (cellEntry) => {\n const color = getCellColor(cellEntry);\n color[3] = opacity * 255;\n return color;\n },\n getLineColor: (cellEntry) => {\n const color = getCellColor(cellEntry);\n color[3] = 255;\n return color;\n },\n onClick: (info) => {\n if (onCellClick) {\n onCellClick(info);\n }\n },\n visible,\n getLineWidth: stroked ? 1 : 0,\n lineWidthScale,\n lineWidthMaxPixels,\n getExpressionValue,\n extensions: [new ScaledExpressionExtension()],\n colorScaleLo: geneExpressionColormapRange[0],\n colorScaleHi: geneExpressionColormapRange[1],\n isExpressionMode: cellColorEncoding === 'geneSelection',\n colormap: geneExpressionColormap,\n ...cellLayerDefaultProps(\n filteredCellsEntries,\n undefined,\n setCellHighlight,\n setComponentHover,\n flipYTooltip,\n ),\n });\n }\n\n createMoleculesLayer(layerDef) {\n const {\n setMoleculeHighlight,\n getMoleculeColor = d => PALETTE[d[2] % PALETTE.length],\n getMoleculePosition = d => [d[0], d[1], 0],\n } = this.props;\n const { moleculesEntries } = this;\n\n return new ScatterplotLayer({\n id: MOLECULES_LAYER_ID,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: moleculesEntries,\n pickable: true,\n autoHighlight: true,\n radiusMaxPixels: 3,\n opacity: layerDef.opacity,\n visible: layerDef.visible,\n getRadius: layerDef.radius,\n getPosition: getMoleculePosition,\n getLineColor: getMoleculeColor,\n getFillColor: getMoleculeColor,\n onHover: (info) => {\n if (setMoleculeHighlight) {\n if (info.object) {\n setMoleculeHighlight(info.object[3]);\n } else {\n setMoleculeHighlight(null);\n }\n }\n },\n });\n }\n\n createNeighborhoodsLayer(layerDef) {\n const {\n getNeighborhoodPolygon = (neighborhoodsEntry) => {\n const neighborhood = neighborhoodsEntry[1];\n return neighborhood.poly;\n },\n } = this.props;\n const { neighborhoodsEntries } = this;\n\n return new PolygonLayer({\n id: NEIGHBORHOODS_LAYER_ID,\n getPolygon: getNeighborhoodPolygon,\n coordinateSystem: COORDINATE_SYSTEM.CARTESIAN,\n data: neighborhoodsEntries,\n pickable: true,\n autoHighlight: true,\n stroked: true,\n filled: false,\n getElevation: 0,\n getLineWidth: 10,\n visible: layerDef.visible,\n });\n }\n\n createSelectionLayers() {\n const {\n viewState,\n getCellCoords = defaultGetCellCoords,\n setCellSelection,\n } = this.props;\n const { tool } = this.state;\n const { cellsQuadTree } = this;\n return getSelectionLayers(\n tool,\n viewState.zoom,\n CELLS_LAYER_ID,\n getCellCoords,\n setCellSelection,\n cellsQuadTree,\n );\n }\n\n createScaleBarLayer() {\n const {\n viewState,\n width,\n height,\n imageLayerLoaders = {},\n layers,\n } = this.props;\n const use3d = (layers || []).some(i => i.use3d);\n // Just get the first layer/loader since they should all be spatially\n // resolved and therefore have the same unit size scale.\n const loaders = Object.values(imageLayerLoaders);\n if (!viewState || !width || !height || loaders.length < 1) return null;\n const loader = loaders[0];\n if (!loader) return null;\n const source = getSourceFromLoader(loader);\n if (!source.meta) return null;\n const { physicalSizes } = source.meta;\n if (physicalSizes && !use3d) {\n const { x } = physicalSizes;\n const { unit, size } = x;\n if (unit && size) {\n return new ScaleBarLayer({\n id: 'scalebar-layer',\n unit,\n size,\n viewState: { ...viewState, width, height },\n });\n }\n return null;\n }\n return null;\n }\n\n createImageLayer(rawLayerDef, loader, i) {\n const layerDef = {\n ...rawLayerDef,\n channels: rawLayerDef.channels.filter(\n channel => channel.selection && channel.color && channel.slider,\n ),\n };\n\n // We need to keep the same selections array reference,\n // otherwise the Viv layer will not be re-used as we want it to,\n // since selections is one of its `updateTriggers`.\n // Reference: https://github.com/hms-dbmi/viv/blob/ad86d0f/src/layers/MultiscaleImageLayer/MultiscaleImageLayer.js#L127\n let selections;\n const nextLoaderSelection = layerDef.channels.map(c => c.selection);\n const prevLoaderSelection = this.layerLoaderSelections[layerDef.index];\n if (isEqual(prevLoaderSelection, nextLoaderSelection)) {\n selections = prevLoaderSelection;\n } else {\n selections = nextLoaderSelection;\n this.layerLoaderSelections[layerDef.index] = nextLoaderSelection;\n }\n const useTransparentColor = (!layerDef.visible\n && typeof layerDef.visible === 'boolean')\n || Boolean(layerDef.transparentColor);\n const transparentColor = useTransparentColor ? [0, 0, 0] : null;\n const layerProps = {\n colormap: layerDef.colormap,\n opacity: layerDef.opacity,\n useTransparentColor,\n transparentColor,\n colors: layerDef.channels.map(c => c.color),\n sliders: layerDef.channels.map(c => c.slider),\n resolution: layerDef.resolution,\n renderingMode: layerDef.renderingMode,\n xSlice: layerDef.xSlice,\n ySlice: layerDef.ySlice,\n zSlice: layerDef.zSlice,\n callback: layerDef.callback,\n visibilities: layerDef.channels.map(c => (!layerDef.visible && typeof layerDef.visible === 'boolean'\n ? false\n : c.visible)),\n };\n\n if (!loader || !layerProps) return null;\n const {\n metadata: { transform },\n data,\n } = loader;\n let modelMatrix;\n if (transform) {\n const { scale, translate } = transform;\n modelMatrix = new Matrix4()\n .translate([translate.x, translate.y, 0])\n .scale(scale);\n } else if (layerDef.modelMatrix) {\n // eslint-disable-next-line prefer-destructuring\n modelMatrix = new Matrix4(layerDef.modelMatrix);\n }\n if (rawLayerDef.type === 'bitmask') {\n const {\n geneExpressionColormap,\n geneExpressionColormapRange = [0.0, 1.0],\n cellColorEncoding,\n } = this.props;\n return new MultiscaleImageLayer({\n // `bitmask` is used by the AbstractSpatialOrScatterplot\n // https://github.com/vitessce/vitessce/pull/927/files#diff-9cab35a2ca0c5b6d9754b177810d25079a30ca91efa062d5795181360bc3ff2cR111\n id: `bitmask-layer-${layerDef.index}-${i}`,\n channelsVisible: layerProps.visibilities,\n opacity: layerProps.opacity,\n modelMatrix,\n hoveredCell: Number(this.props.cellHighlight),\n renderSubLayers: renderSubBitmaskLayers,\n loader: data,\n selections,\n // For some reason, deck.gl doesn't recognize the prop diffing\n // unless these are separated out. I don't think it's a bug, just\n // has to do with the fact that we don't have it in the `defaultProps`,\n // could be wrong though.\n cellColorData: this.color.data,\n cellTexHeight: this.color.height,\n cellTexWidth: this.color.width,\n excludeBackground: true,\n onViewportLoad: layerProps.callback,\n colorScaleLo: geneExpressionColormapRange[0],\n colorScaleHi: geneExpressionColormapRange[1],\n isExpressionMode: cellColorEncoding === 'geneSelection',\n colormap: geneExpressionColormap,\n expressionData: this.expression.data,\n });\n }\n const [Layer, layerLoader] = getLayerLoaderTuple(data, layerDef.use3d);\n\n const extensions = (layerDef.use3d ? [] : [\n ...(layerProps.colormap ? [\n new AdditiveColormapExtension(),\n ] : [\n new ColorPaletteExtension(),\n ]),\n ]);\n\n return new Layer({\n loader: layerLoader,\n id: `${layerDef.use3d ? 'volume' : 'image'}-layer-${layerDef.index}-${i}`,\n colors: layerProps.colors,\n contrastLimits: layerProps.sliders,\n selections,\n channelsVisible: layerProps.visibilities,\n opacity: layerProps.opacity,\n colormap: layerProps.colormap,\n modelMatrix,\n transparentColor: layerProps.transparentColor,\n useTransparentColor: layerProps.useTransparentColor,\n resolution: layerProps.resolution,\n renderingMode: layerProps.renderingMode,\n pickable: false,\n xSlice: layerProps.xSlice,\n ySlice: layerProps.ySlice,\n zSlice: layerProps.zSlice,\n onViewportLoad: layerProps.callback,\n extensions,\n });\n }\n\n createImageLayers() {\n const {\n layers,\n imageLayerLoaders = {},\n rasterLayersCallbacks = [],\n } = this.props;\n const use3d = (layers || []).some(i => i.use3d);\n const use3dIndex = (layers || []).findIndex(i => i.use3d);\n return (layers || [])\n .filter(layer => layer.type === 'raster' || layer.type === 'bitmask')\n .filter(layer => (use3d ? layer.use3d === use3d : true))\n .map((layer, i) => this.createImageLayer(\n { ...layer, callback: rasterLayersCallbacks[use3d ? use3dIndex : i] },\n imageLayerLoaders[layer.index],\n i,\n ));\n }\n\n getLayers() {\n const {\n imageLayers, cellsLayer, neighborhoodsLayer, moleculesLayer,\n } = this;\n return [\n ...imageLayers,\n cellsLayer,\n neighborhoodsLayer,\n moleculesLayer,\n this.createScaleBarLayer(),\n ...this.createSelectionLayers(),\n ];\n }\n\n onUpdateCellsData() {\n const { cells = {}, getCellCoords = defaultGetCellCoords } = this.props;\n const cellsEntries = Object.entries(cells);\n this.cellsEntries = cellsEntries;\n this.cellsQuadTree = createCellsQuadTree(cellsEntries, getCellCoords);\n }\n\n onUpdateCellsLayer() {\n const { layers } = this.props;\n const layerDef = (layers || []).find(layer => layer.type === 'cells');\n if (layerDef) {\n this.cellsLayer = this.createCellsLayer(layerDef);\n } else {\n this.cellsLayer = null;\n }\n }\n\n onUpdateCellColors() {\n const color = this.randomColorData;\n const { size } = this.props.cellColors;\n if (typeof size === 'number') {\n const cellIds = this.props.cellColors.keys();\n color.data = new Uint8Array(color.height * color.width * 3).fill(\n getDefaultColor(this.props.theme)[0],\n );\n // 0th cell id is the empty space of the image i.e black color.\n color.data[0] = 0;\n color.data[1] = 0;\n color.data[2] = 0;\n // eslint-disable-next-line no-restricted-syntax\n for (const id of cellIds) {\n if (id > 0) {\n const cellColor = this.props.cellColors.get(id);\n if (cellColor) {\n color.data.set(cellColor.slice(0, 3), Number(id) * 3);\n }\n }\n }\n }\n this.color = color;\n }\n\n onUpdateExpressionData() {\n const { expressionData } = this.props;\n if (expressionData[0]?.length) {\n this.expression.data = new Uint8Array(\n this.expression.height * this.expression.width,\n );\n this.expression.data.set(expressionData[0]);\n }\n }\n\n onUpdateMoleculesData() {\n const { molecules = {} } = this.props;\n const moleculesEntries = Object.entries(molecules).flatMap(\n ([molecule, coords], index) => coords.map(([x, y]) => [x, y, index, molecule]),\n );\n this.moleculesEntries = moleculesEntries;\n }\n\n onUpdateMoleculesLayer() {\n const { layers } = this.props;\n const layerDef = (layers || []).find(layer => layer.type === 'molecules');\n if (layerDef) {\n this.moleculesLayer = this.createMoleculesLayer(layerDef);\n } else {\n this.moleculesLayer = null;\n }\n }\n\n onUpdateNeighborhoodsData() {\n const { neighborhoods = {} } = this.props;\n const neighborhoodsEntries = Object.entries(neighborhoods);\n this.neighborhoodsEntries = neighborhoodsEntries;\n }\n\n onUpdateNeighborhoodsLayer() {\n const { layers } = this.props;\n const layerDef = (layers || []).find(\n layer => layer.type === 'neighborhoods',\n );\n if (layerDef) {\n this.neighborhoodsLayer = this.createNeighborhoodsLayer(layerDef);\n } else {\n this.neighborhoodsLayer = null;\n }\n }\n\n onUpdateImages() {\n this.imageLayers = this.createImageLayers();\n }\n\n viewInfoDidUpdate() {\n const { getCellCoords = defaultGetCellCoords } = this.props;\n super.viewInfoDidUpdate(getCellCoords);\n }\n\n /**\n * Here, asynchronously check whether props have\n * updated which require re-computing memoized variables,\n * followed by a re-render.\n * This function does not follow React conventions or paradigms,\n * it is only implemented this way to try to squeeze out\n * performance.\n * @param {object} prevProps The previous props to diff against.\n */\n componentDidUpdate(prevProps) {\n this.viewInfoDidUpdate();\n\n const shallowDiff = propName => prevProps[propName] !== this.props[propName];\n if (['cells'].some(shallowDiff)) {\n // Cells data changed.\n this.onUpdateCellsData();\n this.forceUpdate();\n }\n\n if (\n [\n 'layers',\n 'cells',\n 'cellFilter',\n 'cellSelection',\n 'cellColors',\n 'geneExpressionColormapRange',\n 'cellColorEncoding',\n 'geneExpressionColormap',\n ].some(shallowDiff)\n ) {\n // Cells layer props changed.\n this.onUpdateCellsLayer();\n this.forceUpdate();\n }\n\n if (['cellColors'].some(shallowDiff)) {\n // Cells Color layer props changed.\n this.onUpdateCellColors();\n this.forceUpdate();\n }\n\n if (['expressionData'].some(shallowDiff)) {\n // Expression data prop changed.\n this.onUpdateExpressionData();\n this.forceUpdate();\n }\n\n if (['molecules'].some(shallowDiff)) {\n // Molecules data changed.\n this.onUpdateMoleculesData();\n this.forceUpdate();\n }\n\n if (['layers', 'molecules'].some(shallowDiff)) {\n // Molecules layer props changed.\n this.onUpdateMoleculesLayer();\n this.forceUpdate();\n }\n\n if (['neighborhoods'].some(shallowDiff)) {\n // Neighborhoods data changed.\n this.onUpdateNeighborhoodsData();\n this.forceUpdate();\n }\n\n if (['layers', 'neighborhoods'].some(shallowDiff)) {\n // Neighborhoods layer props changed.\n this.onUpdateNeighborhoodsLayer();\n this.forceUpdate();\n }\n\n if (\n [\n 'layers',\n 'imageLayerLoaders',\n 'cellColors',\n 'cellHighlight',\n 'geneExpressionColormapRange',\n 'expressionData',\n 'rasterLayersCallbacks',\n 'geneExpressionColormap',\n ].some(shallowDiff)\n ) {\n // Image layers changed.\n this.onUpdateImages();\n this.forceUpdate();\n }\n }\n\n // render() is implemented in the abstract parent class.\n}\n\n/**\n * Need this wrapper function here,\n * since we want to pass a forwardRef\n * so that outer components can\n * access the grandchild DeckGL ref,\n * but we are using a class component.\n */\nconst SpatialWrapper = forwardRef((props, deckRef) => (\n \n));\nexport default SpatialWrapper;\n","import React, { useCallback } from 'react';\nimport debounce from 'lodash/debounce';\n\nimport Checkbox from '@material-ui/core/Checkbox';\nimport TableCell from '@material-ui/core/TableCell';\nimport TableRow from '@material-ui/core/TableRow';\nimport Slider from '@material-ui/core/Slider';\nimport { makeStyles, createStyles } from '@material-ui/core/styles';\nimport { useStyles } from '../shared-plot-options/styles';\nimport OptionsContainer from '../shared-plot-options/OptionsContainer';\nimport CellColorEncodingOption from '../shared-plot-options/CellColorEncodingOption';\nimport OptionSelect from '../shared-plot-options/OptionSelect';\nimport { GLSL_COLORMAPS } from '../../layers/constants';\n\nconst useToggleStyles = makeStyles(() => createStyles({\n cameraLabel: {\n padding: '0px 0px 0px 16px',\n },\n box: {\n padding: '0px',\n },\n button: {\n padding: '0px 0px 0px 8px',\n },\n}));\n\nconst ToggleFixedAxisButton = ({\n setSpatialAxisFixed,\n spatialAxisFixed,\n use3d,\n}) => {\n const classes = useToggleStyles();\n return (\n \n \n Fix Camera Axis\n \n \n setSpatialAxisFixed(!spatialAxisFixed)}\n disabled={!use3d}\n checked={Boolean(spatialAxisFixed)}\n />\n \n \n );\n};\n\nexport default function SpatialOptions(props) {\n const {\n observationsLabel,\n cellColorEncoding,\n setCellColorEncoding,\n setSpatialAxisFixed,\n spatialAxisFixed,\n use3d,\n geneExpressionColormap,\n setGeneExpressionColormap,\n geneExpressionColormapRange,\n setGeneExpressionColormapRange,\n canShowExpressionOptions,\n canShowColorEncodingOption,\n canShow3DOptions,\n } = props;\n\n function handleGeneExpressionColormapChange(event) {\n setGeneExpressionColormap(event.target.value);\n }\n\n function handleColormapRangeChange(event, value) {\n setGeneExpressionColormapRange(value);\n }\n const handleColormapRangeChangeDebounced = useCallback(\n debounce(handleColormapRangeChange, 5, { trailing: true }),\n [handleColormapRangeChange],\n );\n\n const classes = useStyles();\n\n return (\n \n {canShowColorEncodingOption ? (\n \n ) : null}\n {canShow3DOptions ? (\n \n ) : null}\n {canShowExpressionOptions ? (\n <>\n \n \n Gene Expression Colormap\n \n \n \n {GLSL_COLORMAPS.map(cmap => (\n \n ))}\n \n \n \n \n \n Gene Expression Colormap Range\n \n \n \n \n \n \n ) : null}\n \n );\n}\n","import React from 'react';\nimport Tooltip2D from '../tooltip/Tooltip2D';\nimport TooltipContent from '../tooltip/TooltipContent';\nimport { useComponentHover, useComponentViewInfo } from '../../app/state/hooks';\n\nexport default function SpatialTooltipSubscriber(props) {\n const {\n parentUuid,\n cellHighlight,\n width,\n height,\n getCellInfo,\n } = props;\n\n const sourceUuid = useComponentHover();\n const viewInfo = useComponentViewInfo(parentUuid);\n\n const [cellInfo, x, y] = (cellHighlight && getCellInfo ? (\n [\n getCellInfo(cellHighlight),\n ...(viewInfo && viewInfo.project ? viewInfo.project(cellHighlight) : [null, null]),\n ]\n ) : ([null, null, null]));\n\n return (\n (cellInfo ? (\n \n \n \n ) : null)\n );\n}\n","import React, { useEffect, useMemo, useCallback } from 'react';\nimport TitleInfo from '../TitleInfo';\nimport { capitalize } from '../../utils';\nimport {\n useDeckCanvasSize, useReady, useUrls, useExpressionValueGetter,\n} from '../hooks';\nimport { setCellSelection, mergeCellSets, canLoadResolution } from '../utils';\nimport {\n useCellsData,\n useCellSetsData,\n useGeneSelection,\n useMoleculesData,\n useNeighborhoodsData,\n useRasterData,\n useExpressionAttrs,\n} from '../data-hooks';\nimport { getCellColors } from '../interpolate-colors';\nimport Spatial from './Spatial';\nimport SpatialOptions from './SpatialOptions';\nimport SpatialTooltipSubscriber from './SpatialTooltipSubscriber';\nimport { makeSpatialSubtitle, getInitialSpatialTargets } from './utils';\nimport {\n useCoordination,\n useLoaders,\n useSetComponentHover,\n useSetComponentViewInfo,\n useAuxiliaryCoordination,\n} from '../../app/state/hooks';\nimport { COMPONENT_COORDINATION_TYPES } from '../../app/state/coordination';\n\nconst SPATIAL_DATA_TYPES = [\n 'cells', 'molecules', 'raster', 'cell-sets', 'expression-matrix',\n];\n\n/**\n * A subscriber component for the spatial plot.\n * @param {object} props\n * @param {string} props.theme The current theme name.\n * @param {object} props.coordinationScopes The mapping from coordination types to coordination\n * scopes.\n * @param {function} props.removeGridComponent The callback function to pass to TitleInfo,\n * to call when the component has been removed from the grid.\n * @param {string} props.title The component title.\n */\nexport default function SpatialSubscriber(props) {\n const {\n uuid,\n coordinationScopes,\n removeGridComponent,\n observationsLabelOverride: observationsLabel = 'cell',\n observationsPluralLabelOverride: observationsPluralLabel = `${observationsLabel}s`,\n subobservationsLabelOverride: subobservationsLabel = 'molecule',\n subobservationsPluralLabelOverride: subobservationsPluralLabel = `${subobservationsLabel}s`,\n theme,\n disableTooltip = false,\n title = 'Spatial',\n disable3d,\n globalDisable3d,\n } = props;\n\n const loaders = useLoaders();\n const setComponentHover = useSetComponentHover();\n const setComponentViewInfo = useSetComponentViewInfo(uuid);\n\n // Get \"props\" from the coordination space.\n const [{\n dataset,\n spatialZoom: zoom,\n spatialTargetX: targetX,\n spatialTargetY: targetY,\n spatialTargetZ: targetZ,\n spatialRotationX: rotationX,\n spatialRotationY: rotationY,\n spatialRotationZ: rotationZ,\n spatialRotationOrbit: rotationOrbit,\n spatialOrbitAxis: orbitAxis,\n spatialRasterLayers: rasterLayers,\n spatialCellsLayer: cellsLayer,\n spatialMoleculesLayer: moleculesLayer,\n spatialNeighborhoodsLayer: neighborhoodsLayer,\n cellFilter,\n cellHighlight,\n geneSelection,\n cellSetSelection,\n cellSetColor,\n cellColorEncoding,\n additionalCellSets,\n spatialAxisFixed,\n geneExpressionColormap,\n geneExpressionColormapRange,\n }, {\n setSpatialZoom: setZoom,\n setSpatialTargetX: setTargetX,\n setSpatialTargetY: setTargetY,\n setSpatialTargetZ: setTargetZ,\n setSpatialRotationX: setRotationX,\n setSpatialRotationOrbit: setRotationOrbit,\n setSpatialOrbitAxis: setOrbitAxis,\n setSpatialRasterLayers: setRasterLayers,\n setSpatialCellsLayer: setCellsLayer,\n setSpatialMoleculesLayer: setMoleculesLayer,\n setSpatialNeighborhoodsLayer: setNeighborhoodsLayer,\n setCellFilter,\n setCellSetSelection,\n setCellHighlight,\n setCellSetColor,\n setCellColorEncoding,\n setAdditionalCellSets,\n setMoleculeHighlight,\n setSpatialAxisFixed,\n setGeneExpressionColormap,\n setGeneExpressionColormapRange,\n }] = useCoordination(COMPONENT_COORDINATION_TYPES.spatial, coordinationScopes);\n\n const [\n {\n rasterLayersCallbacks,\n },\n ] = useAuxiliaryCoordination(\n COMPONENT_COORDINATION_TYPES.layerController,\n coordinationScopes,\n );\n\n const use3d = rasterLayers?.some(l => l.use3d);\n\n const [urls, addUrl, resetUrls] = useUrls();\n const [\n isReady,\n setItemIsReady,\n setItemIsNotReady,\n resetReadyItems,\n ] = useReady(\n SPATIAL_DATA_TYPES,\n );\n const [width, height, deckRef] = useDeckCanvasSize();\n\n // Reset file URLs and loader progress when the dataset has changed.\n // Also clear the array of automatically-initialized layers.\n useEffect(() => {\n resetUrls();\n resetReadyItems();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loaders, dataset]);\n\n // Get data from loaders using the data hooks.\n const [cells, cellsCount] = useCellsData(\n loaders, dataset, setItemIsReady, addUrl, false,\n { setSpatialCellsLayer: setCellsLayer },\n { spatialCellsLayer: cellsLayer },\n );\n const [molecules, moleculesCount, locationsCount] = useMoleculesData(\n loaders, dataset, setItemIsReady, addUrl, false,\n { setSpatialMoleculesLayer: setMoleculesLayer },\n { spatialMoleculesLayer: moleculesLayer },\n );\n const [neighborhoods] = useNeighborhoodsData(\n loaders, dataset, setItemIsReady, addUrl, false,\n { setSpatialNeighborhoodsLayer: setNeighborhoodsLayer },\n { spatialNeighborhoodsLayer: neighborhoodsLayer },\n );\n const [cellSets] = useCellSetsData(\n loaders, dataset, setItemIsReady, addUrl, false,\n { setCellSetSelection, setCellSetColor },\n { cellSetSelection, cellSetColor },\n );\n const [expressionData] = useGeneSelection(\n loaders, dataset, setItemIsReady, false, geneSelection, setItemIsNotReady,\n );\n const [attrs] = useExpressionAttrs(\n loaders, dataset, setItemIsReady, addUrl, false,\n );\n // eslint-disable-next-line no-unused-vars\n const [raster, imageLayerLoaders, imageLayerMeta] = useRasterData(\n loaders, dataset, setItemIsReady, addUrl, false,\n { setSpatialRasterLayers: setRasterLayers },\n { spatialRasterLayers: rasterLayers },\n );\n\n const layers = useMemo(() => {\n // Only want to pass in cells layer once if there is not `bitmask`.\n // We pass in the cells data regardless because it is needed for selection,\n // but the rendering layer itself is not needed.\n const canPassInCellsLayer = !imageLayerMeta.some(l => l?.metadata?.isBitmask);\n return [\n ...(moleculesLayer ? [{ ...moleculesLayer, type: 'molecules' }] : []),\n ...((cellsLayer && canPassInCellsLayer) ? [{ ...cellsLayer, type: 'cells' }] : []),\n ...(neighborhoodsLayer ? [{ ...neighborhoodsLayer, type: 'neighborhoods' }] : []),\n ...(rasterLayers ? rasterLayers.map(l => ({ ...l, type: (l.type && ['raster', 'bitmask'].includes(l.type) ? l.type : 'raster') })) : []),\n ];\n }, [cellsLayer, moleculesLayer, neighborhoodsLayer, rasterLayers, imageLayerMeta]);\n\n useEffect(() => {\n if ((typeof targetX !== 'number' || typeof targetY !== 'number')) {\n const {\n initialTargetX, initialTargetY, initialTargetZ, initialZoom,\n } = getInitialSpatialTargets({\n width,\n height,\n cells,\n imageLayerLoaders,\n useRaster: Boolean(loaders[dataset].loaders.raster),\n use3d,\n });\n setTargetX(initialTargetX);\n setTargetY(initialTargetY);\n setTargetZ(initialTargetZ);\n setZoom(initialZoom);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [imageLayerLoaders, cells, targetX, targetY, setTargetX, setTargetY, setZoom, use3d]);\n\n const mergedCellSets = useMemo(() => mergeCellSets(\n cellSets, additionalCellSets,\n ), [cellSets, additionalCellSets]);\n\n const setCellSelectionProp = useCallback((v) => {\n setCellSelection(\n v, additionalCellSets, cellSetColor,\n setCellSetSelection, setAdditionalCellSets, setCellSetColor,\n setCellColorEncoding,\n );\n }, [additionalCellSets, cellSetColor, setCellColorEncoding,\n setAdditionalCellSets, setCellSetColor, setCellSetSelection]);\n\n const cellColors = useMemo(() => getCellColors({\n cellColorEncoding,\n expressionData: expressionData && expressionData[0],\n geneSelection,\n cellSets: mergedCellSets,\n cellSetSelection,\n cellSetColor,\n expressionDataAttrs: attrs,\n theme,\n }), [cellColorEncoding, geneSelection, mergedCellSets, theme,\n cellSetColor, cellSetSelection, expressionData, attrs]);\n\n // The bitmask layer needs access to a array (i.e a texture) lookup of cell -> expression value\n // where each cell id indexes into the array.\n // Cell ids in `attrs.rows` do not necessaryily correspond to indices in that array, though,\n // so we create a \"shifted\" array where this is the case.\n const shiftedExpressionDataForBitmask = useMemo(() => {\n const hasBitmask = imageLayerMeta.some(l => l?.metadata?.isBitmask);\n if (attrs?.rows && expressionData && hasBitmask) {\n const maxId = attrs.rows.reduce((max, curr) => Math.max(max, Number(curr)));\n const result = new Uint8Array(maxId + 1);\n // eslint-disable-next-line no-plusplus\n for (let i = 0; i < attrs.rows.length; i++) {\n const id = attrs.rows[i];\n result.set(expressionData[0].slice(i, i + 1), Number(id));\n }\n return [result];\n } return [new Uint8Array()];\n }, [attrs, expressionData, imageLayerMeta]);\n\n const cellSelection = useMemo(() => Array.from(cellColors.keys()), [cellColors]);\n\n const getCellInfo = (cellId) => {\n const cell = cells[cellId];\n if (cell) {\n return {\n [`${capitalize(observationsLabel)} ID`]: cellId,\n ...cell.factors,\n };\n }\n return null;\n };\n\n const setViewState = ({\n zoom: newZoom,\n target,\n rotationX: newRotationX,\n rotationOrbit: newRotationOrbit,\n orbitAxis: newOrbitAxis,\n }) => {\n setZoom(newZoom);\n setTargetX(target[0]);\n setTargetY(target[1]);\n setTargetZ(target[2] || null);\n setRotationX(newRotationX);\n setRotationOrbit(newRotationOrbit);\n setOrbitAxis(newOrbitAxis || null);\n };\n\n const subtitle = makeSpatialSubtitle({\n observationsCount: cellsCount,\n observationsLabel,\n observationsPluralLabel,\n subobservationsCount: moleculesCount,\n subobservationsLabel,\n subobservationsPluralLabel,\n locationsCount,\n });\n\n // Set up a getter function for gene expression values, to be used\n // by the DeckGL layer to obtain values for instanced attributes.\n const getExpressionValue = useExpressionValueGetter({ attrs, expressionData });\n const hasExpressionData = loaders[dataset].loaders['expression-matrix'];\n const hasCellsData = loaders[dataset].loaders.cells\n || imageLayerMeta.some(l => l?.metadata?.isBitmask);\n const canLoad3DLayers = imageLayerLoaders.some(loader => Boolean(\n Array.from({\n length: loader.data.length,\n }).filter((_, res) => canLoadResolution(loader.data, res)).length,\n ));\n // Only show 3D options if we can theoretically load the data and it is allowed to be loaded.\n const canShow3DOptions = canLoad3DLayers\n && !(disable3d?.length === imageLayerLoaders.length) && !globalDisable3d;\n\n return (\n \n ) : null\n }\n >\n {\n setComponentHover(uuid);\n }}\n updateViewInfo={setComponentViewInfo}\n rasterLayersCallbacks={rasterLayersCallbacks}\n spatialAxisFixed={spatialAxisFixed}\n geneExpressionColormap={geneExpressionColormap}\n geneExpressionColormapRange={geneExpressionColormapRange}\n expressionData={shiftedExpressionDataForBitmask}\n cellColorEncoding={cellColorEncoding}\n getExpressionValue={getExpressionValue}\n theme={theme}\n />\n {!disableTooltip && (\n \n )}\n \n );\n}\n","import clamp from 'lodash/clamp';\nimport range from 'lodash/range';\n\nimport {\n AXIS_LABEL_TEXT_SIZE,\n AXIS_MIN_SIZE,\n AXIS_MAX_SIZE,\n} from '../../layers/heatmap-constants';\n\nexport function getGeneByCellTile(view, {\n tileSize, tileI, tileJ, numCells, numGenes, cellOrdering, cells,\n}) {\n const tileData = new Uint8Array(tileSize * tileSize);\n let offset;\n let value;\n let cellI;\n let geneI;\n let sortedCellI;\n\n const tileSizeRange = range(tileSize);\n\n tileSizeRange.forEach((j) => {\n // Need to iterate over cells in the outer loop.\n cellI = (tileJ * tileSize) + j;\n if (cellI < numCells) {\n sortedCellI = cells.indexOf(cellOrdering[cellI]);\n if (sortedCellI >= -1) {\n tileSizeRange.forEach((i) => {\n geneI = (tileI * tileSize) + i;\n value = view[sortedCellI * numGenes + geneI];\n offset = ((tileSize - i - 1) * tileSize + j);\n tileData[offset] = value;\n });\n }\n }\n });\n return tileData;\n}\n\nexport function getCellByGeneTile(view, {\n tileSize, tileI, tileJ, numCells, numGenes, cellOrdering, cells,\n}) {\n const tileData = new Uint8Array(tileSize * tileSize);\n let offset;\n let value;\n let cellI;\n let geneI;\n let sortedCellI;\n\n const tileSizeRange = range(tileSize);\n\n tileSizeRange.forEach((i) => {\n // Need to iterate over cells in the outer loop.\n cellI = (tileI * tileSize) + i;\n if (cellI < numCells) {\n sortedCellI = cells.indexOf(cellOrdering[cellI]);\n if (sortedCellI >= -1) {\n tileSizeRange.forEach((j) => {\n geneI = (tileJ * tileSize) + j;\n if (geneI < numGenes) {\n value = view[sortedCellI * numGenes + geneI];\n } else {\n value = 0;\n }\n offset = ((tileSize - i - 1) * tileSize + j);\n tileData[offset] = value;\n });\n }\n }\n });\n\n return tileData;\n}\n\n/**\n * Called before a layer is drawn to determine whether it should be rendered.\n * Reference: https://deck.gl/docs/api-reference/core/deck#layerfilter\n * @param {object} params A viewport, layer pair.\n * @param {object} params.layer The layer to check.\n * @param {object} params.viewport The viewport to check.\n * @returns {boolean} Should this layer be rendered in this viewport?\n */\nexport function layerFilter({ layer, viewport }) {\n if (viewport.id === 'axisLeft') {\n return layer.id.startsWith('axisLeft');\n } if (viewport.id === 'axisTop') {\n return layer.id.startsWith('axisTop');\n } if (viewport.id === 'heatmap') {\n return layer.id.startsWith('heatmap');\n } if (viewport.id === 'colorsLeft') {\n return layer.id.startsWith('colorsLeft');\n } if (viewport.id === 'colorsTop') {\n return layer.id.startsWith('colorsTop');\n }\n return false;\n}\n\n/**\n * Get the size of the left and top heatmap axes,\n * taking into account the maximum label string lengths.\n * @param {boolean} transpose Is the heatmap transposed?\n * @param {number} geneLabelMaxLength What is the maximum length gene label?\n * @param {number} cellLabelMaxLength What is the maximum length cell label?\n * @returns {number[]} [axisOffsetLeft, axisOffsetTop]\n */\nexport function getAxisSizes(transpose, geneLabelMaxLength, cellLabelMaxLength) {\n const axisOffsetLeft = clamp(\n (transpose ? geneLabelMaxLength : cellLabelMaxLength) * AXIS_LABEL_TEXT_SIZE,\n AXIS_MIN_SIZE,\n AXIS_MAX_SIZE,\n );\n const axisOffsetTop = clamp(\n (transpose ? cellLabelMaxLength : geneLabelMaxLength) * AXIS_LABEL_TEXT_SIZE,\n AXIS_MIN_SIZE,\n AXIS_MAX_SIZE,\n );\n return [axisOffsetLeft, axisOffsetTop];\n}\n\n/**\n * Convert a mouse coordinate (x, y) to a heatmap coordinate (col index, row index).\n * @param {number} mouseX The mouse X of interest.\n * @param {number} mouseY The mouse Y of interest.\n * @param {object} param2 An object containing current sizes and scale factors.\n * @returns {number[]} [colI, rowI]\n */\nexport function mouseToHeatmapPosition(mouseX, mouseY, {\n offsetLeft, offsetTop, targetX, targetY, scaleFactor, matrixWidth, matrixHeight, numRows, numCols,\n}) {\n // TODO: use linear algebra\n const viewMouseX = mouseX - offsetLeft;\n const viewMouseY = mouseY - offsetTop;\n\n if (viewMouseX < 0 || viewMouseY < 0) {\n // The mouse is outside the heatmap.\n return [null, null];\n }\n\n // Determine the rowI and colI values based on the current viewState.\n const bboxTargetX = targetX * scaleFactor + matrixWidth * scaleFactor / 2;\n const bboxTargetY = targetY * scaleFactor + matrixHeight * scaleFactor / 2;\n\n const bboxLeft = bboxTargetX - matrixWidth / 2;\n const bboxTop = bboxTargetY - matrixHeight / 2;\n\n const zoomedOffsetLeft = bboxLeft / (matrixWidth * scaleFactor);\n const zoomedOffsetTop = bboxTop / (matrixHeight * scaleFactor);\n\n const zoomedViewMouseX = viewMouseX / (matrixWidth * scaleFactor);\n const zoomedViewMouseY = viewMouseY / (matrixHeight * scaleFactor);\n\n const zoomedMouseX = zoomedOffsetLeft + zoomedViewMouseX;\n const zoomedMouseY = zoomedOffsetTop + zoomedViewMouseY;\n\n const rowI = Math.floor(zoomedMouseY * numRows);\n const colI = Math.floor(zoomedMouseX * numCols);\n return [colI, rowI];\n}\n\n/**\n * Convert a heatmap coordinate (col index, row index) to a mouse coordinate (x, y).\n * @param {number} colI The column index of interest.\n * @param {number} rowI The row index of interest.\n * @param {object} param2 An object containing current sizes and scale factors.\n * @returns {number[]} [x, y]\n */\nexport function heatmapToMousePosition(colI, rowI, {\n offsetLeft, offsetTop, targetX, targetY, scaleFactor, matrixWidth, matrixHeight, numRows, numCols,\n}) {\n // TODO: use linear algebra\n let zoomedMouseY = null;\n let zoomedMouseX = null;\n\n if (rowI !== null) {\n const minY = -matrixHeight * scaleFactor / 2;\n const maxY = matrixHeight * scaleFactor / 2;\n const totalHeight = maxY - minY;\n\n const minInViewY = (targetY * scaleFactor) - (matrixHeight / 2);\n const maxInViewY = (targetY * scaleFactor) + (matrixHeight / 2);\n const inViewHeight = maxInViewY - minInViewY;\n\n const normalizedRowY = (rowI + 0.5) / numRows;\n const globalRowY = minY + (normalizedRowY * totalHeight);\n\n if (minInViewY <= globalRowY && globalRowY <= maxInViewY) {\n zoomedMouseY = offsetTop + ((globalRowY - minInViewY) / inViewHeight) * matrixHeight;\n }\n }\n if (colI !== null) {\n const minX = -matrixWidth * scaleFactor / 2;\n const maxX = matrixWidth * scaleFactor / 2;\n const totalWidth = maxX - minX;\n\n const minInViewX = (targetX * scaleFactor) - (matrixWidth / 2);\n const maxInViewX = (targetX * scaleFactor) + (matrixWidth / 2);\n const inViewWidth = maxInViewX - minInViewX;\n\n const normalizedRowX = (colI + 0.5) / numCols;\n const globalRowX = minX + (normalizedRowX * totalWidth);\n\n if (minInViewX <= globalRowX && globalRowX <= maxInViewX) {\n zoomedMouseX = offsetLeft + ((globalRowX - minInViewX) / inViewWidth) * matrixWidth;\n }\n }\n return [zoomedMouseX, zoomedMouseY];\n}\n","// https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency\n// We need to give a different way of getting this for safari, so 4 is probably a safe bet\n// for parallel processing in the meantime. More can't really hurt since they'll just block\n// each other and not the UI thread, which is the real benefit.\nconst defaultPoolSize = typeof navigator !== 'undefined' ? navigator.hardwareConcurrency || 4 : null;\n\n/**\n * Pool for workers to decode chunks of the images.\n * This is a line-for-line copy of GeoTIFFs old implementation: https://github.com/geotiffjs/geotiff.js/blob/v1.0.0-beta.6/src/pool.js\n */\nexport default class Pool {\n /**\n * @constructor\n * @param {object} Worker The worker class to be used for processing.\n */\n constructor(Worker) {\n this.workers = [];\n this.idleWorkers = [];\n this.waitQueue = [];\n this.decoder = null;\n\n // eslint-disable-next-line no-plusplus\n for (let i = 0; i < defaultPoolSize; ++i) {\n const w = new Worker();\n this.workers.push(w);\n this.idleWorkers.push(w);\n }\n }\n\n // eslint-disable-next-line class-methods-use-this\n async process() {\n throw new Error('Pool needs to implement \"process\" method');\n }\n\n async waitForWorker() {\n const idleWorker = this.idleWorkers.pop();\n if (idleWorker) {\n return idleWorker;\n }\n const waiter = {};\n const promise = new Promise((resolve) => {\n waiter.resolve = resolve;\n });\n\n this.waitQueue.push(waiter);\n return promise;\n }\n\n async finishTask(currentWorker) {\n const waiter = this.waitQueue.pop();\n if (waiter) {\n waiter.resolve(currentWorker);\n } else {\n this.idleWorkers.push(currentWorker);\n }\n }\n\n destroy() {\n // eslint-disable-next-line no-plusplus\n for (let i = 0; i < this.workers.length; ++i) {\n this.workers[i].terminate();\n }\n }\n}\n","import Worker from './heatmap.worker'; // eslint-disable-line import/no-unresolved\nimport Pool from '../../Pool';\n\n/**\n * Pool for workers to decode chunks of the images.\n * This is a line-for-line copy of GeoTIFFs old implementation: https://github.com/geotiffjs/geotiff.js/blob/v1.0.0-beta.6/src/pool.js\n */\nexport default class HeatmapPool extends Pool {\n constructor() {\n super(Worker);\n }\n\n /**\n * Process each heatmap tile\n * @param {object} params The arguments passed to the heatmap worker.\n * @param {string} params.curr The current task uuid.\n * @param {number} params.xTiles How many tiles required in the x direction?\n * @param {number} params.yTiles How many tiles required in the y direction?\n * @param {number} params.tileSize How many entries along each tile axis?\n * @param {string[]} params.cellOrdering The current ordering of cells.\n * @param {string[]} params.rows The name of each row (cell ID).\n * Does not take transpose into account (always cells).\n * @param {string[]} params.cols The name of each column (gene ID).\n * Does not take transpose into account (always genes).\n * @param {ArrayBuffer} params.data The array buffer.\n * Need to transfer back to main thread when done.\n * @param {boolean} params.transpose Is the heatmap transposed?\n * @returns {array} [message, transfers]\n * @returns {Promise.} the decoded result as a `Promise`\n */\n async process(args) {\n const currentWorker = await this.waitForWorker();\n return new Promise((resolve, reject) => {\n currentWorker.onmessage = (event) => {\n // this.workers.push(currentWorker);\n this.finishTask(currentWorker);\n resolve(event.data);\n };\n currentWorker.onerror = (error) => {\n // this.workers.push(currentWorker);\n this.finishTask(currentWorker);\n reject(error);\n };\n currentWorker.postMessage(['getTile', args], [args.data]);\n });\n }\n}\n","import React, {\n useRef, useState, useCallback, useMemo, useEffect, useReducer, forwardRef,\n} from 'react';\nimport uuidv4 from 'uuid/v4';\nimport DeckGL from 'deck.gl';\nimport { OrthographicView } from '@deck.gl/core'; // eslint-disable-line import/no-extraneous-dependencies\nimport range from 'lodash/range';\nimport clamp from 'lodash/clamp';\nimport isEqual from 'lodash/isEqual';\nimport { max } from 'd3-array';\nimport HeatmapCompositeTextLayer from '../../layers/HeatmapCompositeTextLayer';\nimport PixelatedBitmapLayer from '../../layers/PixelatedBitmapLayer';\nimport HeatmapBitmapLayer from '../../layers/HeatmapBitmapLayer';\nimport {\n DEFAULT_GL_OPTIONS,\n createDefaultUpdateCellsHover,\n createDefaultUpdateGenesHover,\n createDefaultUpdateViewInfo,\n copyUint8Array,\n} from '../utils';\nimport {\n layerFilter,\n getAxisSizes,\n mouseToHeatmapPosition,\n heatmapToMousePosition,\n} from './utils';\nimport {\n TILE_SIZE, MAX_ROW_AGG, MIN_ROW_AGG,\n COLOR_BAR_SIZE,\n AXIS_MARGIN,\n} from '../../layers/heatmap-constants';\nimport HeatmapWorkerPool from './HeatmapWorkerPool';\n/**\n * A heatmap component for cell x gene matrices.\n * @param {object} props\n * @param {string} props.uuid The uuid of this component,\n * used by tooltips to determine whether to render a tooltip or\n * a crosshair.\n * @param {string} props.theme The current theme name.\n * @param {object} props.initialViewState The initial viewState for\n * DeckGL.\n * @param {number} props.width The width of the canvas.\n * @param {number} props.height The height of the canvas.\n * @param {object} props.expressionMatrix An object { rows, cols, matrix },\n * where matrix is a flat Uint8Array, rows is a list of cell ID strings,\n * and cols is a list of gene ID strings.\n * @param {Map} props.cellColors Map of cell ID to color. Optional.\n * If defined, the key ordering is used to order the cell axis of the heatmap.\n * @param {function} props.clearPleaseWait The clear please wait callback,\n * called when the expression matrix has loaded (is not null).\n * @param {function} props.setCellHighlight Callback function called on\n * hover with the cell ID. Optional.\n * @param {function} props.setGeneHighlight Callback function called on\n * hover with the gene ID. Optional.\n * @param {function} props.updateViewInfo Callback function that gets called with an\n * object { uuid, project() } where project is a function that maps (cellId, geneId)\n * to canvas (x,y) coordinates. Used to show tooltips. Optional.\n * @param {boolean} props.transpose By default, false.\n * @param {string} props.variablesTitle By default, 'Genes'.\n * @param {string} props.observationsTitle By default, 'Cells'.\n * @param {string} props.colormap The name of the colormap function to use.\n * @param {array} props.colormapRange A tuple [lower, upper] to adjust the color scale.\n * @param {function} props.setColormapRange The setter function for colormapRange.\n */\nconst Heatmap = forwardRef((props, deckRef) => {\n const {\n uuid,\n theme,\n viewState: rawViewState,\n setViewState,\n width: viewWidth,\n height: viewHeight,\n expressionMatrix: expression,\n cellColors,\n colormap,\n colormapRange,\n clearPleaseWait,\n setComponentHover,\n setCellHighlight = createDefaultUpdateCellsHover('Heatmap'),\n setGeneHighlight = createDefaultUpdateGenesHover('Heatmap'),\n updateViewInfo = createDefaultUpdateViewInfo('Heatmap'),\n setIsRendering = () => {},\n transpose = false,\n variablesTitle = 'Genes',\n observationsTitle = 'Cells',\n } = props;\n\n const viewState = {\n ...rawViewState,\n target: (transpose ? [rawViewState.target[1], rawViewState.target[0]] : rawViewState.target),\n minZoom: 0,\n };\n\n const axisLeftTitle = (transpose ? variablesTitle : observationsTitle);\n const axisTopTitle = (transpose ? observationsTitle : variablesTitle);\n\n const workerPool = useMemo(() => new HeatmapWorkerPool(), []);\n\n useEffect(() => {\n if (clearPleaseWait && expression) {\n clearPleaseWait('expression-matrix');\n }\n }, [clearPleaseWait, expression]);\n\n const tilesRef = useRef();\n const dataRef = useRef();\n const [axisLeftLabels, setAxisLeftLabels] = useState([]);\n const [axisTopLabels, setAxisTopLabels] = useState([]);\n\n\n // Since we are storing the tile data in a ref,\n // and updating it asynchronously when the worker finishes,\n // we need to tie it to a piece of state through this iteration value.\n const [tileIteration, incTileIteration] = useReducer(i => i + 1, 0);\n\n // We need to keep a backlog of the tasks for the worker thread,\n // since the array buffer can only be held by one thread at a time.\n const [backlog, setBacklog] = useState([]);\n\n // Store a reference to the matrix Uint8Array in the dataRef,\n // since we need to access its array buffer to transfer\n // it back and forth from the worker thread.\n useEffect(() => {\n // Store the expression matrix Uint8Array in the dataRef.\n if (expression && expression.matrix) {\n dataRef.current = copyUint8Array(expression.matrix);\n }\n }, [dataRef, expression]);\n\n // Check if the ordering of axis labels needs to be changed,\n // for example if the cells \"selected\" (technically just colored)\n // have changed.\n useEffect(() => {\n if (!expression) {\n return;\n }\n const newCellOrdering = (!cellColors || cellColors.size === 0\n ? expression.rows\n : Array.from(cellColors.keys())\n );\n const oldCellOrdering = (transpose ? axisTopLabels : axisLeftLabels);\n\n if (!isEqual(oldCellOrdering, newCellOrdering)) {\n if (transpose) {\n setAxisTopLabels(newCellOrdering);\n } else {\n setAxisLeftLabels(newCellOrdering);\n }\n }\n }, [expression, cellColors, axisTopLabels, axisLeftLabels, transpose]);\n\n // Set the genes ordering.\n useEffect(() => {\n if (!expression) {\n return;\n }\n if (transpose) {\n setAxisLeftLabels(expression.cols);\n } else {\n setAxisTopLabels(expression.cols);\n }\n }, [expression, transpose]);\n\n const [cellLabelMaxLength, geneLabelMaxLength] = useMemo(() => {\n if (!expression) {\n return [0, 0];\n }\n return [\n max(expression.rows.map(cellId => cellId.length)),\n max(expression.cols.map(geneId => geneId.length)),\n ];\n }, [expression]);\n\n const width = axisTopLabels.length;\n const height = axisLeftLabels.length;\n\n const [axisOffsetLeft, axisOffsetTop] = getAxisSizes(\n transpose, geneLabelMaxLength, cellLabelMaxLength,\n );\n\n const offsetTop = axisOffsetTop + COLOR_BAR_SIZE;\n const offsetLeft = axisOffsetLeft + COLOR_BAR_SIZE;\n\n const matrixWidth = viewWidth - offsetLeft;\n const matrixHeight = viewHeight - offsetTop;\n\n const matrixLeft = -matrixWidth / 2;\n const matrixRight = matrixWidth / 2;\n const matrixTop = -matrixHeight / 2;\n const matrixBottom = matrixHeight / 2;\n\n const xTiles = Math.ceil(width / TILE_SIZE);\n const yTiles = Math.ceil(height / TILE_SIZE);\n\n const widthRatio = 1 - (TILE_SIZE - (width % TILE_SIZE)) / (xTiles * TILE_SIZE);\n const heightRatio = 1 - (TILE_SIZE - (height % TILE_SIZE)) / (yTiles * TILE_SIZE);\n\n const tileWidth = (matrixWidth / widthRatio) / (xTiles);\n const tileHeight = (matrixHeight / heightRatio) / (yTiles);\n\n const scaleFactor = 2 ** viewState.zoom;\n const cellHeight = (matrixHeight * scaleFactor) / height;\n const cellWidth = (matrixWidth * scaleFactor) / width;\n\n // Get power of 2 between 1 and 16,\n // for number of cells to aggregate together in each direction.\n const aggSizeX = clamp(2 ** Math.ceil(Math.log2(1 / cellWidth)), MIN_ROW_AGG, MAX_ROW_AGG);\n const aggSizeY = clamp(2 ** Math.ceil(Math.log2(1 / cellHeight)), MIN_ROW_AGG, MAX_ROW_AGG);\n\n const [targetX, targetY] = viewState.target;\n\n // Emit the viewInfo object on viewState updates\n // (used by tooltips / crosshair elements).\n useEffect(() => {\n updateViewInfo({\n uuid,\n project: (cellId, geneId) => {\n const colI = transpose ? axisTopLabels.indexOf(cellId) : axisTopLabels.indexOf(geneId);\n const rowI = transpose ? axisLeftLabels.indexOf(geneId) : axisLeftLabels.indexOf(cellId);\n return heatmapToMousePosition(\n colI, rowI, {\n offsetLeft,\n offsetTop,\n targetX: viewState.target[0],\n targetY: viewState.target[1],\n scaleFactor,\n matrixWidth,\n matrixHeight,\n numRows: height,\n numCols: width,\n },\n );\n },\n });\n }, [uuid, updateViewInfo, transpose, axisTopLabels, axisLeftLabels, offsetLeft,\n offsetTop, viewState, scaleFactor, matrixWidth, matrixHeight, height, width]);\n\n\n // Listen for viewState changes.\n // Do not allow the user to zoom and pan outside of the initial window.\n const onViewStateChange = useCallback(({ viewState: nextViewState }) => {\n const { zoom: nextZoom } = nextViewState;\n const nextScaleFactor = 2 ** nextZoom;\n\n const minTargetX = nextZoom === 0 ? 0 : -(matrixRight - (matrixRight / nextScaleFactor));\n const maxTargetX = -1 * minTargetX;\n\n const minTargetY = nextZoom === 0 ? 0 : -(matrixBottom - (matrixBottom / nextScaleFactor));\n const maxTargetY = -1 * minTargetY;\n\n // Manipulate view state if necessary to keep the user in the window.\n const nextTarget = [\n clamp(nextViewState.target[0], minTargetX, maxTargetX),\n clamp(nextViewState.target[1], minTargetY, maxTargetY),\n ];\n\n setViewState({\n zoom: nextZoom,\n target: (transpose ? [nextTarget[1], nextTarget[0]] : nextTarget),\n });\n }, [matrixRight, matrixBottom, transpose, setViewState]);\n\n // If `expression` or `cellOrdering` have changed,\n // then new tiles need to be generated,\n // so add a new task to the backlog.\n useEffect(() => {\n if (!expression) {\n return;\n }\n // Use a uuid to give the task a unique ID,\n // to help identify where in the list it is located\n // after the worker thread asynchronously sends the data back\n // to this thread.\n if (\n axisTopLabels && axisLeftLabels && xTiles && yTiles\n ) {\n setBacklog(prev => [...prev, uuidv4()]);\n }\n }, [dataRef, expression, axisTopLabels, axisLeftLabels, xTiles, yTiles]);\n\n // When the backlog has updated, a new worker job can be submitted if:\n // - the backlog has length >= 1 (at least one job is waiting), and\n // - buffer.byteLength is not zero, so the worker does not currently \"own\" the buffer.\n useEffect(() => {\n if (backlog.length < 1) {\n return;\n }\n const curr = backlog[backlog.length - 1];\n if (dataRef.current && dataRef.current.buffer.byteLength) {\n const { rows, cols, matrix } = expression;\n const promises = range(yTiles).map(i => range(xTiles).map(async j => workerPool.process({\n curr,\n tileI: i,\n tileJ: j,\n tileSize: TILE_SIZE,\n cellOrdering: transpose ? axisTopLabels : axisLeftLabels,\n rows,\n cols,\n transpose,\n data: matrix.buffer.slice(),\n })));\n const process = async () => {\n const tiles = await Promise.all(promises.flat());\n tilesRef.current = tiles.map(i => i.tile);\n incTileIteration();\n dataRef.current = new Uint8Array(tiles[0].buffer);\n const { curr: currWork } = tiles[0];\n setBacklog((prev) => {\n const currIndex = prev.indexOf(currWork);\n return prev.slice(currIndex + 1, prev.length);\n });\n };\n process();\n }\n }, [axisLeftLabels, axisTopLabels, backlog, expression, transpose, xTiles, yTiles, workerPool]);\n\n useEffect(() => {\n setIsRendering(backlog.length > 0);\n }, [backlog, setIsRendering]);\n\n // Update the heatmap tiles if:\n // - new tiles are available (`tileIteration` has changed), or\n // - the matrix bounds have changed, or\n // - the `aggSizeX` or `aggSizeY` have changed, or\n // - the cell ordering has changed.\n const heatmapLayers = useMemo(() => {\n if (!tilesRef.current || backlog.length) {\n return [];\n }\n function getLayer(i, j, tile) {\n return new HeatmapBitmapLayer({\n id: `heatmapLayer-${tileIteration}-${i}-${j}`,\n image: tile,\n bounds: [\n matrixLeft + j * tileWidth,\n matrixTop + i * tileHeight,\n matrixLeft + (j + 1) * tileWidth,\n matrixTop + (i + 1) * tileHeight,\n ],\n aggSizeX,\n aggSizeY,\n colormap,\n colorScaleLo: colormapRange[0],\n colorScaleHi: colormapRange[1],\n updateTriggers: {\n image: [axisLeftLabels, axisTopLabels],\n bounds: [tileHeight, tileWidth],\n },\n });\n }\n const layers = tilesRef\n .current.map((tile, index) => getLayer(Math.floor(index / xTiles), index % xTiles, tile));\n return layers;\n }, [backlog, tileIteration, matrixLeft, tileWidth, matrixTop, tileHeight,\n aggSizeX, aggSizeY, colormap, colormapRange,\n axisLeftLabels, axisTopLabels, xTiles]);\n\n\n // Map cell and gene names to arrays with indices,\n // to prepare to render the names in TextLayers.\n const axisTopLabelData = useMemo(() => axisTopLabels.map((d, i) => [i, d]), [axisTopLabels]);\n const axisLeftLabelData = useMemo(() => axisLeftLabels.map((d, i) => [i, d]), [axisLeftLabels]);\n\n // Generate the axis label, axis title, and loading indicator text layers.\n const textLayers = [\n new HeatmapCompositeTextLayer({\n targetX,\n targetY,\n scaleFactor,\n axisLeftLabelData,\n matrixTop,\n height,\n matrixHeight,\n cellHeight,\n cellWidth,\n axisTopLabelData,\n matrixLeft,\n width,\n matrixWidth,\n viewHeight,\n viewWidth,\n theme,\n axisLeftTitle,\n axisTopTitle,\n axisOffsetLeft,\n axisOffsetTop,\n }),\n ];\n\n // Create the left color bar with a BitmapLayer.\n // TODO: find a way to do aggregation for this as well.\n const cellColorsTiles = useMemo(() => {\n if (!cellColors) {\n return null;\n }\n\n let cellId;\n let offset;\n let color;\n let rowI;\n\n const cellOrdering = (transpose ? axisTopLabels : axisLeftLabels);\n const colorBarTileWidthPx = (transpose ? TILE_SIZE : 1);\n const colorBarTileHeightPx = (transpose ? 1 : TILE_SIZE);\n\n const result = range((transpose ? xTiles : yTiles)).map((i) => {\n const tileData = new Uint8ClampedArray(TILE_SIZE * 1 * 4);\n\n range(TILE_SIZE).forEach((tileY) => {\n rowI = (i * TILE_SIZE) + tileY; // the row / cell index\n if (rowI < cellOrdering.length) {\n cellId = cellOrdering[rowI];\n color = cellColors.get(cellId);\n offset = (transpose ? tileY : (TILE_SIZE - tileY - 1)) * 4;\n if (color) {\n const [rValue, gValue, bValue] = color;\n tileData[offset + 0] = rValue;\n tileData[offset + 1] = gValue;\n tileData[offset + 2] = bValue;\n tileData[offset + 3] = 255;\n }\n }\n });\n\n return new ImageData(tileData, colorBarTileWidthPx, colorBarTileHeightPx);\n });\n\n return result;\n }, [cellColors, transpose, axisTopLabels, axisLeftLabels, xTiles, yTiles]);\n\n const cellColorsLayers = useMemo(() => (cellColorsTiles\n ? cellColorsTiles\n .map((tile, i) => new PixelatedBitmapLayer({\n id: `${(transpose ? 'colorsTopLayer' : 'colorsLeftLayer')}-${i}-${uuidv4()}`,\n image: tile,\n bounds: (transpose ? [\n matrixLeft + i * tileWidth,\n -matrixHeight / 2,\n matrixLeft + (i + 1) * tileWidth,\n matrixHeight / 2,\n ] : [\n -matrixWidth / 2,\n matrixTop + i * tileHeight,\n matrixWidth / 2,\n matrixTop + (i + 1) * tileHeight,\n ]),\n }))\n : []), [cellColorsTiles, matrixTop, matrixLeft, matrixHeight,\n matrixWidth, tileWidth, tileHeight, transpose]);\n\n const layers = heatmapLayers\n .concat(textLayers)\n .concat(cellColorsLayers);\n\n // Set up the onHover function.\n function onHover(info, event) {\n if (!expression) {\n return;\n }\n const { x: mouseX, y: mouseY } = event.offsetCenter;\n const [colI, rowI] = mouseToHeatmapPosition(mouseX, mouseY, {\n offsetLeft,\n offsetTop,\n targetX,\n targetY,\n scaleFactor,\n matrixWidth,\n matrixHeight,\n numRows: height,\n numCols: width,\n });\n\n if (colI === null) {\n if (transpose) {\n setCellHighlight(null);\n } else {\n setGeneHighlight(null);\n }\n }\n\n if (rowI === null) {\n if (transpose) {\n setGeneHighlight(null);\n } else {\n setCellHighlight(null);\n }\n }\n\n const obsI = expression.rows.indexOf(transpose\n ? axisTopLabels[colI]\n : axisLeftLabels[rowI]);\n const varI = expression.cols.indexOf(transpose\n ? axisLeftLabels[rowI]\n : axisTopLabels[colI]);\n\n const obsId = expression.rows[obsI];\n const varId = expression.cols[varI];\n if (setComponentHover) {\n setComponentHover();\n }\n setCellHighlight(obsId || null);\n setGeneHighlight(varId || null);\n }\n\n return (\n (interactionState.isDragging ? 'grabbing' : 'default')}\n glOptions={DEFAULT_GL_OPTIONS}\n onViewStateChange={onViewStateChange}\n viewState={viewState}\n onHover={onHover}\n />\n );\n});\n\nexport default Heatmap;\n","import React from 'react';\nimport Tooltip2D from '../tooltip/Tooltip2D';\nimport TooltipContent from '../tooltip/TooltipContent';\nimport { useComponentHover, useComponentViewInfo } from '../../app/state/hooks';\n\nexport default function HeatmapTooltipSubscriber(props) {\n const {\n parentUuid,\n width, height, transpose,\n getCellInfo, getGeneInfo,\n cellHighlight, geneHighlight,\n } = props;\n\n const sourceUuid = useComponentHover();\n const viewInfo = useComponentViewInfo(parentUuid);\n\n const [cellInfo, cellCoord] = (cellHighlight && getCellInfo ? (\n [\n getCellInfo(cellHighlight),\n (viewInfo && viewInfo.project\n ? viewInfo.project(cellHighlight, null)[(transpose ? 0 : 1)]\n : null),\n ]\n ) : ([null, null]));\n\n const [geneInfo, geneCoord] = (geneHighlight && getGeneInfo ? (\n [\n getGeneInfo(geneHighlight),\n (viewInfo && viewInfo.project\n ? viewInfo.project(null, geneHighlight)[(transpose ? 1 : 0)]\n : null),\n ]\n ) : ([null, null]));\n\n const x = (transpose ? cellCoord : geneCoord);\n const y = (transpose ? geneCoord : cellCoord);\n\n return (\n (cellInfo || geneInfo ? (\n \n \n \n ) : null)\n );\n}\n","import React, { useCallback } from 'react';\nimport debounce from 'lodash/debounce';\nimport Slider from '@material-ui/core/Slider';\nimport TableCell from '@material-ui/core/TableCell';\nimport TableRow from '@material-ui/core/TableRow';\nimport { useStyles } from '../shared-plot-options/styles';\nimport OptionsContainer from '../shared-plot-options/OptionsContainer';\nimport OptionSelect from '../shared-plot-options/OptionSelect';\nimport { GLSL_COLORMAPS } from '../../layers/constants';\n\nexport default function HeatmapOptions(props) {\n const {\n geneExpressionColormap,\n setGeneExpressionColormap,\n geneExpressionColormapRange,\n setGeneExpressionColormapRange,\n } = props;\n\n const classes = useStyles();\n\n function handleGeneExpressionColormapChange(event) {\n setGeneExpressionColormap(event.target.value);\n }\n\n function handleColormapRangeChange(event, value) {\n setGeneExpressionColormapRange(value);\n }\n const handleColormapRangeChangeDebounced = useCallback(\n debounce(handleColormapRangeChange, 5, { trailing: true }),\n [handleColormapRangeChange],\n );\n\n return (\n \n \n \n Gene Expression Colormap\n \n \n \n {GLSL_COLORMAPS.map(cmap => (\n \n ))}\n \n \n \n \n \n Gene Expression Colormap Range\n \n \n \n \n \n \n );\n}\n","import React, {\n useEffect, useState, useCallback, useMemo,\n} from 'react';\nimport TitleInfo from '../TitleInfo';\nimport { pluralize, capitalize } from '../../utils';\nimport { useDeckCanvasSize, useReady, useUrls } from '../hooks';\nimport { mergeCellSets } from '../utils';\nimport {\n useCellsData,\n useCellSetsData,\n useExpressionMatrixData,\n} from '../data-hooks';\nimport { getCellColors } from '../interpolate-colors';\nimport {\n useCoordination, useLoaders,\n useSetComponentHover, useSetComponentViewInfo,\n} from '../../app/state/hooks';\nimport {\n COMPONENT_COORDINATION_TYPES,\n} from '../../app/state/coordination';\nimport Heatmap from './Heatmap';\nimport HeatmapTooltipSubscriber from './HeatmapTooltipSubscriber';\nimport HeatmapOptions from './HeatmapOptions';\n\nconst HEATMAP_DATA_TYPES = ['cells', 'cell-sets', 'expression-matrix'];\n\n/**\n * @param {object} props\n * @param {number} props.uuid The unique identifier for this component.\n * @param {object} props.coordinationScopes The mapping from coordination types to coordination\n * scopes.\n * @param {function} props.removeGridComponent The callback function to pass to TitleInfo,\n * to call when the component has been removed from the grid.\n * @param {string} props.title The component title.\n * @param {boolean} props.transpose Whether to\n * render as cell-by-gene or gene-by-cell.\n * @param {string} props.observationsLabelOverride The singular\n * form of the name of the observation.\n * @param {string} props.observationsPluralLabelOverride The\n * plural form of the name of the observation.\n * @param {string} props.variablesLabelOverride The singular\n * form of the name of the variable.\n * @param {string} props.variablesPluralLabelOverride The plural\n * form of the name of the variable.\n * @param {boolean} props.disableTooltip Whether to disable the\n * tooltip on mouse hover.\n */\nexport default function HeatmapSubscriber(props) {\n const {\n uuid,\n coordinationScopes,\n removeGridComponent, theme, transpose,\n observationsLabelOverride: observationsLabel = 'cell',\n observationsPluralLabelOverride: observationsPluralLabel = `${observationsLabel}s`,\n variablesLabelOverride: variablesLabel = 'gene',\n variablesPluralLabelOverride: variablesPluralLabel = `${variablesLabel}s`,\n disableTooltip = false,\n title = 'Heatmap',\n } = props;\n\n const loaders = useLoaders();\n const setComponentHover = useSetComponentHover();\n const setComponentViewInfo = useSetComponentViewInfo(uuid);\n\n // Get \"props\" from the coordination space.\n const [{\n dataset,\n heatmapZoomX: zoomX,\n heatmapTargetX: targetX,\n heatmapTargetY: targetY,\n geneSelection,\n cellHighlight,\n geneHighlight,\n cellSetSelection,\n cellSetColor,\n additionalCellSets,\n geneExpressionColormap,\n geneExpressionColormapRange,\n }, {\n setHeatmapZoomX: setZoomX,\n setHeatmapZoomY: setZoomY,\n setHeatmapTargetX: setTargetX,\n setHeatmapTargetY: setTargetY,\n setCellHighlight,\n setGeneHighlight,\n setCellSetSelection,\n setCellSetColor,\n setGeneExpressionColormapRange,\n setGeneExpressionColormap,\n }] = useCoordination(COMPONENT_COORDINATION_TYPES.heatmap, coordinationScopes);\n\n const observationsTitle = capitalize(observationsPluralLabel);\n const variablesTitle = capitalize(variablesPluralLabel);\n\n const [isRendering, setIsRendering] = useState(false);\n const [\n isReady,\n setItemIsReady,\n setItemIsNotReady, // eslint-disable-line no-unused-vars\n resetReadyItems,\n ] = useReady(\n HEATMAP_DATA_TYPES,\n );\n const [urls, addUrl, resetUrls] = useUrls();\n const [width, height, deckRef] = useDeckCanvasSize();\n\n // Reset file URLs and loader progress when the dataset has changed.\n useEffect(() => {\n resetUrls();\n resetReadyItems();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loaders, dataset]);\n\n // Get data from loaders using the data hooks.\n const [cells] = useCellsData(loaders, dataset, setItemIsReady, addUrl, true);\n const [expressionMatrix] = useExpressionMatrixData(\n loaders, dataset, setItemIsReady, addUrl, true,\n );\n const [cellSets] = useCellSetsData(\n loaders, dataset, setItemIsReady, addUrl, false,\n { setCellSetSelection, setCellSetColor },\n { cellSetSelection, cellSetColor },\n );\n\n const mergedCellSets = useMemo(() => mergeCellSets(\n cellSets, additionalCellSets,\n ), [cellSets, additionalCellSets]);\n\n const cellColors = useMemo(() => getCellColors({\n // Only show cell set selection on heatmap labels.\n cellColorEncoding: 'cellSetSelection',\n geneSelection,\n cellSets: mergedCellSets,\n cellSetSelection,\n cellSetColor,\n expressionDataAttrs: expressionMatrix,\n theme,\n }), [mergedCellSets, geneSelection, theme,\n cellSetColor, cellSetSelection, expressionMatrix]);\n\n const getCellInfo = useCallback((cellId) => {\n if (cellId) {\n const cellInfo = cells[cellId];\n return {\n [`${capitalize(observationsLabel)} ID`]: cellId,\n ...(cellInfo ? cellInfo.factors : {}),\n };\n }\n return null;\n }, [cells, observationsLabel]);\n\n const getGeneInfo = useCallback((geneId) => {\n if (geneId) {\n return { [`${capitalize(variablesLabel)} ID`]: geneId };\n }\n return null;\n }, [variablesLabel]);\n\n const cellsCount = expressionMatrix && expressionMatrix.rows\n ? expressionMatrix.rows.length : 0;\n const genesCount = expressionMatrix && expressionMatrix.cols\n ? expressionMatrix.cols.length : 0;\n const selectedCount = cellColors.size;\n return (\n \n )}\n >\n {\n setZoomX(zoom);\n setZoomY(zoom);\n setTargetX(target[0]);\n setTargetY(target[1]);\n }}\n colormapRange={geneExpressionColormapRange}\n setColormapRange={setGeneExpressionColormapRange}\n height={height}\n width={width}\n theme={theme}\n uuid={uuid}\n expressionMatrix={expressionMatrix}\n cellColors={cellColors}\n colormap={geneExpressionColormap}\n setIsRendering={setIsRendering}\n setCellHighlight={setCellHighlight}\n setGeneHighlight={setGeneHighlight}\n setComponentHover={() => {\n setComponentHover(uuid);\n }}\n updateViewInfo={setComponentViewInfo}\n observationsTitle={observationsTitle}\n variablesTitle={variablesTitle}\n />\n {!disableTooltip && (\n \n )}\n \n );\n}\n","import React from 'react';\nimport IconButton from '@material-ui/core/IconButton';\nimport LensIcon from '@material-ui/icons/Lens';\nimport { makeStyles } from '@material-ui/core/styles';\n\n\nimport { VIEWER_PALETTE } from '../utils';\n\nconst useStyles = makeStyles(theme => ({\n container: {\n width: '70px',\n height: '40px',\n display: 'flex',\n justifyContent: 'space-between',\n alignItems: 'center',\n flexWrap: 'wrap',\n },\n button: {\n padding: '3px',\n width: '16px',\n },\n icon: {\n width: '17px',\n height: '17px',\n stroke: theme.palette.action.selected,\n 'stroke-width': '1px',\n },\n}));\n\nconst ColorPalette = ({ handleChange }) => {\n const classes = useStyles();\n return (\n
\n {VIEWER_PALETTE.map(color => (\n handleChange(color)}\n >\n \n \n ))}\n
\n );\n};\n\nexport default ColorPalette;\n","import React, { useState } from 'react';\nimport { makeStyles } from '@material-ui/core/styles';\nimport MoreVertIcon from '@material-ui/icons/MoreVert';\nimport MenuItem from '@material-ui/core/MenuItem';\nimport { PopperMenu, MuiSpan } from '../shared-mui/components';\n\nimport ColorPalette from './ColorPalette';\n\nconst useStyles = makeStyles(() => ({\n menuButton: {\n backgroundColor: 'transparent',\n },\n colors: {\n '&:hover': {\n backgroundColor: 'transparent',\n },\n paddingLeft: '2px',\n paddingRight: '2px',\n },\n}));\n\n/**\n * Dropdown for options for a channel on the three dots button.\n * @prop {function} handlePropertyChange Callback for changing property (color, IQR of sliders).\n * @prop {function} handleChannelRemove Callback for channel removal.\n * @prop {function} handleIQRUpdate Callback for IQR slider update.\n */\nfunction ChannelOptions({ handlePropertyChange, handleChannelRemove, handleIQRUpdate }) {\n const [open, setOpen] = useState(false);\n\n const classes = useStyles();\n\n const handleColorSelect = (color) => {\n handlePropertyChange('color', color);\n };\n\n const handleRemove = () => {\n setOpen(false);\n handleChannelRemove();\n };\n\n return (\n }\n buttonClassName={classes.menuButton}\n >\n \n Remove\n \n \n Use IQR\n \n \n \n \n \n );\n}\n\nexport default ChannelOptions;\n","import { DTYPE_VALUES } from '@hms-dbmi/viv';\n\nfunction getDomains() {\n const domains = {};\n const needMin = ['Int8', 'Int16', 'Int32'];\n Object.keys(DTYPE_VALUES).forEach((dtype) => {\n const { max } = DTYPE_VALUES[dtype];\n const min = needMin.includes(dtype) ? -(max + 1) : 0;\n domains[dtype] = [min, max];\n });\n return domains;\n}\n\nexport const DOMAINS = getDomains();\n","import { makeStyles, withStyles } from '@material-ui/core/styles';\nimport AccordionSummary from '@material-ui/core/AccordionSummary';\nimport AccordionDetails from '@material-ui/core/AccordionDetails';\nimport InputLabel from '@material-ui/core/InputLabel';\nimport Slider from '@material-ui/core/Slider';\nimport Grid from '@material-ui/core/Grid';\n\nexport const useSelectStyles = makeStyles(() => ({\n selectRoot: {\n padding: 0,\n height: 'auto',\n margin: '4px 0',\n },\n}));\n\nexport const useOptionStyles = withStyles(theme => ({\n paper: {\n backgroundColor: theme.palette.background.paper,\n },\n span: {\n width: '70px',\n textAlign: 'center',\n paddingLeft: '2px',\n paddingRight: '2px',\n },\n colors: {\n '&:hover': {\n backgroundColor: 'transparent',\n },\n paddingLeft: '2px',\n paddingRight: '2px',\n },\n popper: {\n zIndex: 4,\n },\n}));\n\nconst sharedControllerStyles = {\n width: '100%',\n flexDirection: 'column',\n};\n\nexport const useControllerSectionStyles = makeStyles(() => ({\n root: {\n ...sharedControllerStyles,\n padding: '0px 8px',\n },\n}));\n\nexport const StyledAccordionDetails = withStyles(() => ({\n root: {\n ...sharedControllerStyles,\n padding: '8px 8px 24px 8px',\n },\n}))(AccordionDetails);\n\nexport const StyledAccordionSummary = withStyles(theme => ({\n root: {\n padding: '0px 8px',\n },\n content: {\n margin: '4px 0px',\n minWidth: '0px',\n },\n expanded: {\n marginBottom: theme.spacing(-3),\n top: theme.spacing(-1),\n },\n expandIcon: {\n '&$expanded': {\n top: theme.spacing(-1.3),\n },\n },\n}))(AccordionSummary);\n\nexport const StyledInputLabel = withStyles(() => ({\n root: {\n fontSize: '14px',\n },\n}))(InputLabel);\n\nexport const OverflowEllipsisGrid = withStyles(() => ({\n item: {\n width: '100%',\n overflow: 'hidden',\n whiteSpace: 'nowrap',\n textOverflow: 'ellipsis',\n },\n}))(Grid);\n\nexport const StyledSelectionSlider = withStyles(() => ({\n root: {\n marginTop: '7px',\n },\n markActive: {\n backgroundColor: 'rgba(128, 128, 128, 0.7)',\n },\n}))(Slider);\n","import React from 'react';\n\nimport Checkbox from '@material-ui/core/Checkbox';\nimport Select from '@material-ui/core/Select';\nimport { useSelectStyles } from './styles';\n\n/**\n * Dropdown for selecting a channel.\n * @prop {function} handleChange Callback for each new selection.\n * @prop {array} channelOptions List of available selections, like ['DAPI', 'FITC', ...].\n * @prop {boolean} disabled Whether or not the component is disabled.\n * @prop {number} selectionIndex Current numeric index of a selection.\n */\nexport function ChannelSelectionDropdown({\n handleChange,\n disabled,\n channelOptions,\n selectionIndex,\n}) {\n const classes = useSelectStyles();\n return (\n handleChange(Number(e.target.value))}\n >\n {channelOptions.map((opt, i) => (\n \n ))}\n \n );\n}\n\n/**\n * Checkbox for toggling on/off of a channel.\n * @prop {string} color Current color for this channel.\n * @prop {boolean} checked Whether or not this channel is \"on\".\n * @prop {boolean} disabled Whether or not the component is disabled.\n * @prop {function} toggle Callback for toggling on/off.\n */\nexport function ChannelVisibilityCheckbox({\n color, checked, toggle, disabled,\n}) {\n return (\n \n );\n}\n","import React, { useCallback, useState, useEffect } from 'react';\n\nimport Grid from '@material-ui/core/Grid';\nimport Slider from '@material-ui/core/Slider';\nimport debounce from 'lodash/debounce';\nimport isEqual from 'lodash/isEqual';\n\nimport ChannelOptions from './ChannelOptions';\nimport { DOMAINS } from './constants';\nimport { getSourceFromLoader } from '../../utils';\nimport { getMultiSelectionStats } from './utils';\nimport {\n ChannelSelectionDropdown,\n ChannelVisibilityCheckbox,\n} from './shared-channel-controls';\n\n// Returns an rgb string for display, and changes the color (arr)\n// to use a grey for light theme + white color or if the colormap is on.\nexport const toRgbUIString = (on, arr, theme) => {\n const color = on || (theme === 'light' && arr.every(i => i === 255))\n ? [220, 220, 220]\n : arr;\n return `rgb(${color})`;\n};\n\nfunction abbreviateNumber(value) {\n // Return an abbreviated representation of value, in 5 characters or less.\n\n const maxLength = 5;\n let maxNaiveDigits = maxLength;\n\n /* eslint-disable no-plusplus */\n if (!Number.isInteger(value)) {\n --maxNaiveDigits;\n } // Wasted on \".\"\n if (value < 1) {\n --maxNaiveDigits;\n } // Wasted on \"0.\"\n /* eslint-disable no-plusplus */\n\n const naive = Intl.NumberFormat('en-US', {\n maximumSignificantDigits: maxNaiveDigits,\n useGrouping: false,\n }).format(value);\n if (naive.length <= maxLength) return naive;\n\n // \"e+9\" consumes 3 characters, so if we even had two significant digits,\n // it would take take us to six characters, including the decimal point.\n return value.toExponential(0);\n}\n\n/**\n * Slider for controlling current colormap.\n * @prop {string} color Current color for this channel.\n * @prop {arry} slider Current value of the slider.\n * @prop {function} handleChange Callback for each slider change.\n * @prop {array} domain Current max/min allowable slider values.\n */\nfunction ChannelSlider({\n color,\n slider = [0, 0],\n handleChange,\n domain = [0, 0],\n dtype,\n disabled,\n}) {\n const [min, max] = domain;\n const handleChangeDebounced = useCallback(\n debounce(handleChange, 3, { trailing: true }),\n [handleChange],\n );\n const step = max - min < 500 && dtype === 'Float32' ? (max - min) / 500 : 1;\n return (\n handleChangeDebounced(v)}\n valueLabelDisplay=\"auto\"\n getAriaLabel={() => `${color}-${slider}`}\n min={min}\n max={max}\n step={step}\n orientation=\"horizontal\"\n style={{ color, marginTop: '7px' }}\n disabled={disabled}\n />\n );\n}\n\n/**\n * Controller for the handling the colormapping sliders.\n * @prop {boolean} visibility Whether or not this channel is \"on\"\n * @prop {array} slider Current slider range.\n * @prop {array} color Current color for this channel.\n * @prop {array} domain Current max/min for this channel.\n * @prop {string} dimName Name of the dimensions this slider controls (usually \"channel\").\n * @prop {boolean} colormapOn Whether or not the colormap (viridis, magma etc.) is on.\n * @prop {object} channelOptions All available options for this dimension (i.e channel names).\n * @prop {function} handlePropertyChange Callback for when a property (color, slider etc.) changes.\n * @prop {function} handleChannelRemove When a channel is removed, this is called.\n * @prop {function} handleIQRUpdate When the IQR button is clicked, this is called.\n * @prop {number} selectionIndex The current numeric index of the selection.\n */\nfunction RasterChannelController({\n visibility = false,\n slider,\n color,\n channels,\n channelId,\n domainType: newDomainType,\n dimName,\n theme,\n loader,\n colormapOn,\n channelOptions,\n handlePropertyChange,\n handleChannelRemove,\n handleIQRUpdate,\n selectionIndex,\n isLoading,\n use3d: newUse3d,\n}) {\n const { dtype } = getSourceFromLoader(loader);\n const [domain, setDomain] = useState(null);\n const [domainType, setDomainType] = useState(null);\n const [use3d, setUse3d] = useState(null);\n const [selection, setSelection] = useState([\n { ...channels[channelId].selection },\n ]);\n const rgbColor = toRgbUIString(colormapOn, color, theme);\n\n useEffect(() => {\n // Use mounted to prevent state updates/re-renders after the component has been unmounted.\n // All state updates should happen within the mounted check.\n let mounted = true;\n if (dtype && loader && channels) {\n const selections = [{ ...channels[channelId].selection }];\n let domains;\n const hasDomainChanged = newDomainType !== domainType;\n const has3dChanged = use3d !== newUse3d;\n const hasSelectionChanged = !isEqual(selections, selection);\n if (hasDomainChanged || hasSelectionChanged || has3dChanged) {\n if (newDomainType === 'Full') {\n domains = [DOMAINS[dtype]];\n const [newDomain] = domains;\n if (mounted) {\n setDomain(newDomain);\n setDomainType(newDomainType);\n if (hasSelectionChanged) {\n setSelection(selections);\n }\n if (has3dChanged) {\n setUse3d(newUse3d);\n }\n }\n } else {\n getMultiSelectionStats({\n loader: loader.data,\n selections,\n use3d: newUse3d,\n }).then((stats) => {\n // eslint-disable-next-line prefer-destructuring\n domains = stats.domains;\n const [newDomain] = domains;\n if (mounted) {\n setDomain(newDomain);\n setDomainType(newDomainType);\n if (hasSelectionChanged) {\n setSelection(selections);\n }\n if (has3dChanged) {\n setUse3d(newUse3d);\n }\n }\n });\n }\n }\n }\n return () => {\n mounted = false;\n };\n }, [\n domainType,\n channels,\n channelId,\n loader,\n dtype,\n newDomainType,\n selection,\n newUse3d,\n use3d,\n ]);\n /* A valid selection is defined by an object where the keys are\n * the name of a dimension of the data, and the values are the\n * index of the image along that particular dimension.\n *\n * Since we currently only support making a selection along one\n * addtional dimension (i.e. the dropdown just has channels or mz)\n * we have a helper function to create the selection.\n *\n * e.g { channel: 2 } // channel dimension, third channel\n */\n const createSelection = index => ({ [dimName]: index });\n return (\n \n \n \n handlePropertyChange('selection', createSelection(v))\n }\n selectionIndex={selectionIndex}\n channelOptions={channelOptions}\n disabled={isLoading}\n />\n \n \n \n \n \n \n \n handlePropertyChange('visible', !visibility)}\n disabled={isLoading}\n />\n \n \n handlePropertyChange('slider', v)}\n disabled={isLoading}\n />\n \n \n \n );\n}\n\nexport default RasterChannelController;\n","import React from 'react';\n\nimport RemoveCircleIcon from '@material-ui/icons/RemoveCircle';\nimport IconButton from '@material-ui/core/IconButton';\n\nimport Grid from '@material-ui/core/Grid';\n\nimport { ChannelSelectionDropdown, ChannelVisibilityCheckbox } from './shared-channel-controls';\n\n/**\n * Controller for the handling the bitmask channels.\n * @prop {boolean} visibility Whether or not this channel is \"on\"\n * @prop {string} dimName Name of the dimensions this slider controls (usually \"channel\").\n * @prop {object} channelOptions All available options for this dimension (i.e channel names).\n * @prop {function} handlePropertyChange Callback for when a property (color, slider etc.) changes.\n * @prop {function} handleChannelRemove When a channel is removed, this is called.\n * @prop {number} selectionIndex The current numeric index of the selection.\n * @prop {boolean} disableOptions Whether or not channel options are be disabled (default: false).\n */\nfunction BitmaskChannelController({\n visibility = false,\n dimName,\n channelOptions,\n handlePropertyChange,\n handleChannelRemove,\n selectionIndex,\n disableOptions = false,\n}) {\n /* A valid selection is defined by an object where the keys are\n * the name of a dimension of the data, and the values are the\n * index of the image along that particular dimension.\n *\n * Since we currently only support making a selection along one\n * addtional dimension (i.e. the dropdown just has channels or mz)\n * we have a helper function to create the selection.\n *\n * e.g { channel: 2 } // channel dimension, third channel\n */\n const createSelection = index => ({ [dimName]: index });\n return (\n \n \n handlePropertyChange('visible', !visibility)}\n />\n \n \n handlePropertyChange('selection', createSelection(v))}\n selectionIndex={selectionIndex}\n disableOptions={disableOptions}\n channelOptions={channelOptions}\n />\n \n \n \n \n \n \n \n );\n}\n\nexport default BitmaskChannelController;\n","import React from 'react';\n\nimport Grid from '@material-ui/core/Grid';\nimport Checkbox from '@material-ui/core/Checkbox';\nimport Paper from '@material-ui/core/Paper';\nimport Typography from '@material-ui/core/Typography';\nimport Slider from '@material-ui/core/Slider';\nimport { useControllerSectionStyles } from './styles';\n\nexport default function VectorLayerController(props) {\n const {\n label,\n layer,\n layerType,\n handleLayerChange,\n } = props;\n\n const slider = layer.opacity;\n const isOn = layer.visible;\n\n function handleSliderChange(v) {\n if (layerType === 'cells') {\n const stroked = v < 0.7;\n handleLayerChange({ ...layer, opacity: v, stroked });\n } else {\n handleLayerChange({ ...layer, opacity: v });\n }\n }\n\n function handleCheckBoxChange(v) {\n handleLayerChange({ ...layer, visible: v });\n }\n\n const classes = useControllerSectionStyles();\n return (\n \n \n \n {label}\n \n \n \n handleCheckBoxChange(v)} />\n \n \n handleSliderChange(v)}\n style={{ marginTop: '7px' }}\n orientation=\"horizontal\"\n />\n \n \n \n \n );\n}\n","import React from 'react';\nimport range from 'lodash/range';\nimport { Matrix4 } from 'math.gl';\nimport Grid from '@material-ui/core/Grid';\nimport Slider from '@material-ui/core/Slider';\nimport InputLabel from '@material-ui/core/InputLabel';\nimport Select from '@material-ui/core/Select';\nimport Checkbox from '@material-ui/core/Checkbox';\nimport { getDefaultInitialViewState } from '@hms-dbmi/viv';\n\nimport {\n getBoundingCube, getMultiSelectionStats,\n} from './utils';\nimport {\n COLORMAP_OPTIONS,\n canLoadResolution,\n formatBytes,\n getStatsForResolution,\n} from '../utils';\nimport { DEFAULT_RASTER_DOMAIN_TYPE } from '../spatial/constants';\nimport { StyledSelectionSlider, useSelectStyles } from './styles';\n\nconst DOMAIN_OPTIONS = ['Full', 'Min/Max'];\n\n/**\n * Wrapper for the dropdown that selects a colormap (None, viridis, magma, etc.).\n * @prop {Object} loader Loader object with metadata.\n * @prop {function} handleMultiPropertyChange Function to propgate multiple layer changes at once.\n * This prevents updates from overridding each other.\n * @prop {number} resolution Current 3D resolution.\n * @prop {boolean} disable3d Whether or not to enable 3D selection\n * @prop {function} setRasterLayerCallback Setter for callbacks that fire after raster/volume loads.\n * @prop {function} setAreAllChannelsLoading Setter for whether or not a given channel is loading.\n * @prop {Object} setViewState Setter for the current view state.\n * @prop {number} spatialHeight Height of the spatial component.\n * @prop {number} spatialWidth Width of the spatial component.\n * @prop {object} channels Channels object.\n * @prop {boolean} use3d Whether or not 3D is enabled for this layer.\n */\nfunction VolumeDropdown({\n loader: loaderWithMeta,\n handleMultiPropertyChange,\n resolution: currResolution,\n disable3d,\n setRasterLayerCallback,\n setAreAllChannelsLoading,\n setViewState,\n spatialHeight,\n spatialWidth,\n channels,\n use3d,\n modelMatrix,\n}) {\n const classes = useSelectStyles();\n const selections = channels.map(i => i.selection);\n const { data: loader } = loaderWithMeta;\n const handleChange = async (val) => {\n // val is the resolution - null indicates 2D\n const shouldUse3D = typeof val === 'number';\n setAreAllChannelsLoading(true);\n setRasterLayerCallback(() => {\n setAreAllChannelsLoading(false);\n setRasterLayerCallback(null);\n });\n if (shouldUse3D) {\n const [xSlice, ySlice, zSlice] = getBoundingCube(loader);\n const propertiesChanged = {\n resolution: val,\n xSlice,\n ySlice,\n zSlice,\n use3d: shouldUse3D,\n };\n // Only make the fetch if needed i.e if the 3d was just being turned on.\n if (!use3d) {\n const { sliders } = await getMultiSelectionStats({\n loader,\n selections,\n use3d: shouldUse3D,\n });\n propertiesChanged.channels = [...channels];\n propertiesChanged.channels.forEach((ch, i) => {\n // eslint-disable-next-line no-param-reassign\n ch.slider = sliders[i];\n });\n }\n // Update all properties at once to avoid overriding calls.\n handleMultiPropertyChange(propertiesChanged);\n const defaultViewState = getDefaultInitialViewState(loader,\n { height: spatialHeight, width: spatialWidth }, 1.5, true, new Matrix4(modelMatrix));\n setViewState({\n ...defaultViewState,\n rotationX: 0,\n rotationOrbit: 0,\n });\n } else {\n const { sliders } = await getMultiSelectionStats({\n loader, selections, use3d: shouldUse3D,\n });\n const newChannels = [...channels];\n newChannels.forEach((ch, i) => {\n // eslint-disable-next-line no-param-reassign\n ch.slider = sliders[i];\n });\n // Update all properties at once to avoid overriding calls.\n handleMultiPropertyChange({\n resolution: val,\n use3d: shouldUse3D,\n spatialAxisFixed: false,\n channels: newChannels,\n });\n const defaultViewState = getDefaultInitialViewState(loader,\n { height: spatialHeight, width: spatialWidth }, 0.5, false, new Matrix4(modelMatrix));\n setViewState({\n ...defaultViewState,\n rotationX: null,\n rotationOrbit: null,\n orbitAxis: null,\n });\n }\n };\n const { labels, shape } = Array.isArray(loader) ? loader[0] : loader;\n const hasZStack = shape[labels.indexOf('z')] > 1;\n return (\n <>\n handleChange(\n e.target.value === '2D' ? e.target.value : Number(e.target.value),\n )\n }\n classes={{ root: classes.selectRoot }}\n >\n {\n \n }\n {Array.from({ length: loader.length })\n .fill(0)\n // eslint-disable-next-line no-unused-vars\n .map((_, resolution) => {\n if (loader) {\n if (canLoadResolution(loader, resolution)) {\n const {\n height,\n width,\n depthDownsampled,\n totalBytes,\n } = getStatsForResolution(loader, resolution);\n return (\n \n {`3D: ${resolution}x Downsampled, ~${formatBytes(\n totalBytes,\n )} per channel, (${height}, ${width}, ${depthDownsampled})`}\n \n );\n }\n }\n return null;\n })}\n \n \n );\n}\n\n\n/**\n * Wrapper for the dropdown that selects a colormap (None, viridis, magma, etc.).\n * @prop {string} value Currently selected value for the colormap.\n * @prop {string} inputId Css id.\n * @prop {function} handleChange Callback for every change in colormap.\n */\nfunction ColormapSelect({ value, inputId, handleChange }) {\n const classes = useSelectStyles();\n return (\n handleChange(e.target.value === '' ? null : e.target.value)}\n value={value}\n inputProps={{ name: 'colormap', id: inputId }}\n style={{ width: '100%' }}\n classes={{ root: classes.selectRoot }}\n >\n \n {COLORMAP_OPTIONS.map(name => (\n \n ))}\n \n );\n}\n\nfunction TransparentColorCheckbox({ value, handleChange }) {\n return (\n {\n if (value) {\n handleChange(null);\n } else {\n handleChange([0, 0, 0]);\n }\n }}\n checked={Boolean(value)}\n />\n );\n}\n\n/**\n * Wrapper for the slider that updates opacity.\n * @prop {string} value Currently selected value between 0 and 1.\n * @prop {function} handleChange Callback for every change in opacity.\n */\nfunction OpacitySlider({ value, handleChange }) {\n return (\n handleChange(v)}\n valueLabelDisplay=\"auto\"\n getAriaLabel={() => 'opacity slider'}\n min={0}\n max={1}\n step={0.01}\n orientation=\"horizontal\"\n style={{ marginTop: '7px' }}\n />\n );\n}\n\n/**\n * Wrapper for the dropdown that chooses the domain type.\n * @prop {string} value Currently selected value (i.e 'Max/Min').\n * @prop {string} inputId Css id.\n * @prop {function} handleChange Callback for every change in domain.\n */\nfunction SliderDomainSelector({ value, inputId, handleChange }) {\n const classes = useSelectStyles();\n return (\n handleChange(e.target.value)}\n value={value}\n inputProps={{ name: 'domain-selector', id: inputId }}\n style={{ width: '100%' }}\n classes={{ root: classes.selectRoot }}\n >\n {DOMAIN_OPTIONS.map(name => (\n \n ))}\n \n );\n}\n\n/**\n * Wrapper for the slider that chooses global selections (z, t etc.).\n * @prop {string} field The dimension this selects for (z, t etc.).\n * @prop {number} value Currently selected index (1, 4, etc.).\n * @prop {function} handleChange Callback for every change in selection.\n * @prop {function} possibleValues All available values for the field.\n */\nfunction GlobalSelectionSlider({\n field,\n value,\n handleChange,\n possibleValues,\n}) {\n return (\n {\n handleChange({ selection: { [field]: newValue }, event });\n }\n }\n onChangeCommitted={\n (event, newValue) => {\n handleChange({ selection: { [field]: newValue }, event });\n }\n }\n valueLabelDisplay=\"auto\"\n getAriaLabel={() => `${field} slider`}\n marks={possibleValues.map(val => ({ value: val }))}\n min={Number(possibleValues[0])}\n max={Number(possibleValues.slice(-1))}\n orientation=\"horizontal\"\n step={null}\n />\n );\n}\n\n/**\n * Wrapper for each of the options to show its name and then its UI component.\n * @prop {string} name Display name for option.\n * @prop {number} opacity Current opacity value.\n * @prop {string} inputId An id for css.\n * @prop {object} children Components to be rendered next to the name (slider, dropdown etc.).\n */\nfunction LayerOption({ name, inputId, children }) {\n return (\n \n \n {name}:\n \n \n {children}\n \n \n );\n}\n\n/**\n * Gloabl options for all channels (opacity, colormap, etc.).\n * @prop {string} colormap What colormap is currently selected (None, viridis etc.).\n * @prop {number} opacity Current opacity value.\n * @prop {function} handleColormapChange Callback for when colormap changes.\n * @prop {function} handleOpacityChange Callback for when opacity changes.\n * @prop {object} globalControlLabels All available options for global control (z and t).\n * @prop {function} handleGlobalChannelsSelectionChange Callback for global selection changes.\n * @prop {function} handleDomainChange Callback for domain type changes (full or min/max).\n * @prop {array} channels Current channel object for inferring the current global selection.\n * @prop {array} dimensions Currently available dimensions (channel, z, t etc.).\n * @prop {string} domainType One of Max/Min or Full (soon presets as well).\n * @prop {boolean} disableChannelsIfRgbDetected Whether or not we need colormap controllers if RGB.\n */\nfunction LayerOptions({\n colormap,\n opacity,\n handleColormapChange,\n handleOpacityChange,\n handleTransparentColorChange,\n globalControlLabels,\n globalLabelValues,\n handleGlobalChannelsSelectionChange,\n handleSliderChange,\n handleDomainChange,\n transparentColor,\n channels,\n domainType,\n disableChannelsIfRgbDetected,\n shouldShowTransparentColor,\n shouldShowDomain,\n shouldShowColormap,\n use3d,\n loader,\n handleMultiPropertyChange,\n resolution,\n disable3d,\n setRasterLayerCallback,\n setAreAllChannelsLoading,\n setViewState,\n spatialHeight,\n spatialWidth,\n modelMatrix,\n}) {\n const { labels, shape } = Array.isArray(loader.data) ? loader.data[0] : loader.data;\n const hasDimensionsAndChannels = labels.length > 0 && channels.length > 0;\n const hasZStack = shape[labels.indexOf('z')] > 1;\n // Only show volume button if we can actually view resolutions.\n const hasViewableResolutions = Boolean(Array.from({\n length: loader.data.length,\n }).filter((_, res) => canLoadResolution(loader.data, res)).length);\n return (\n \n {hasZStack\n && !disable3d\n && hasViewableResolutions\n && (\n \n )\n }\n {hasDimensionsAndChannels\n && !use3d\n && globalControlLabels.map(\n field => shape[labels.indexOf(field)] > 1 && (\n \n \n \n ),\n )}\n {!disableChannelsIfRgbDetected ? (\n <>\n {shouldShowColormap && (\n \n \n \n \n \n )}\n {shouldShowDomain && (\n \n \n {\n handleDomainChange(value);\n }}\n />\n \n \n )}\n \n ) : null}\n {!use3d && (\n \n \n \n \n \n )}\n {shouldShowTransparentColor && !use3d && (\n \n \n \n \n \n )}\n \n );\n}\n\nexport default LayerOptions;\n","import React from 'react';\nimport { Matrix4 } from 'math.gl';\nimport Grid from '@material-ui/core/Grid';\nimport Typography from '@material-ui/core/Typography';\nimport Button from '@material-ui/core/Button';\nimport { makeStyles, createStyles } from '@material-ui/core/styles';\nimport FormControl from '@material-ui/core/FormControl';\nimport Select from '@material-ui/core/Select';\nimport InputLabel from '@material-ui/core/InputLabel';\nimport Slider from '@material-ui/core/Slider';\nimport { RENDERING_MODES, getDefaultInitialViewState } from '@hms-dbmi/viv';\nimport { abbreviateNumber, getBoundingCube } from './utils';\nimport { useSelectStyles } from './styles';\n\nconst useSlicerStyles = makeStyles(theme => createStyles({\n enabled: {},\n disabled: {\n color: theme.palette.text.disabled,\n // Because of the .5 opacity of the disabled color in the theme, and the fact\n // that there are multiple overlaid parts to the slider,\n // this needs to be set manually for the desired effect.\n '& .MuiSlider-thumb': {\n color: 'rgb(100, 100, 100, 1.0)',\n },\n '& .MuiSlider-track': {\n color: 'rgb(100, 100, 100, 1.0)',\n },\n },\n}));\n\nconst Slicer = ({\n xSlice,\n ySlice,\n zSlice,\n handleSlicerSetting,\n loader,\n use3d,\n}) => {\n const [xSliceInit, ySliceInit, zSliceInit] = getBoundingCube(loader.data);\n const sliceValuesAndSetSliceFunctions = [\n [\n xSlice,\n xSliceNew => handleSlicerSetting('x', xSliceNew),\n 'x',\n xSliceInit,\n ],\n [\n ySlice,\n ySliceNew => handleSlicerSetting('y', ySliceNew),\n 'y',\n ySliceInit,\n ],\n [\n zSlice,\n zSliceNew => handleSlicerSetting('z', zSliceNew),\n 'z',\n zSliceInit,\n ],\n ];\n const classes = useSlicerStyles();\n const Slicers = sliceValuesAndSetSliceFunctions.map(\n ([val, setVal, label, [min, max]]) => (\n \n \n \n {label}:\n \n \n \n setVal(v)}\n valueLabelDisplay=\"auto\"\n valueLabelFormat={v => abbreviateNumber(v)}\n getAriaLabel={() => `${label} slider`}\n min={min}\n max={max}\n step={0.005}\n orientation=\"horizontal\"\n />\n \n \n ),\n );\n return (\n <>\n \n Clipping Planes:{' '}\n {' '}\n {Slicers}\n \n );\n};\n\nconst renderingOptions = Object.values(RENDERING_MODES);\n\nfunction RenderingModeSelect({\n handleRenderingModeChange,\n renderingMode,\n use3d,\n}) {\n const classes = useSelectStyles();\n // Empty option allows for displaying the title of the dropdown fully in the UI.\n const options = !use3d ? [...renderingOptions, ''] : renderingOptions;\n return (\n \n Rendering Mode\n handleRenderingModeChange(e.target.value)}\n value={use3d ? renderingMode : ''}\n inputProps={{\n name: 'rendering-mode',\n id: 'rendering-mode-select',\n }}\n disabled={!use3d}\n classes={{ root: classes.selectRoot }}\n >\n {options.map(name => (\n \n ))}\n \n \n );\n}\n\nconst ReCenterButton = ({\n setViewState,\n use3d,\n spatialHeight,\n spatialWidth,\n loader,\n modelMatrix,\n}) => (\n \n {\n const defaultViewState = getDefaultInitialViewState(\n loader.data,\n { height: spatialHeight, width: spatialWidth },\n 1.5,\n use3d,\n new Matrix4(modelMatrix),\n );\n setViewState({\n ...defaultViewState,\n rotationX: 0,\n rotationOrbit: 0,\n });\n }\n }\n disabled={!use3d}\n style={{\n padding: 0,\n marginBottom: 6,\n }}\n >\n Re-Center\n \n \n);\n\nconst VolumeOptions = ({\n handleSlicerSetting,\n handleRenderingModeChange,\n renderingMode,\n xSlice,\n ySlice,\n zSlice,\n use3d,\n loader,\n setViewState,\n spatialHeight,\n spatialWidth,\n modelMatrix,\n}) => (\n <>\n \n \n \n \n);\n\nexport default VolumeOptions;\n","import React, { useState, useRef, useEffect } from 'react';\nimport { MAX_CHANNELS, getChannelStats } from '@hms-dbmi/viv';\n\nimport Grid from '@material-ui/core/Grid';\nimport Button from '@material-ui/core/Button';\nimport AddIcon from '@material-ui/icons/Add';\nimport Slider from '@material-ui/core/Slider';\nimport Tabs from '@material-ui/core/Tabs';\nimport Tab from '@material-ui/core/Tab';\n\nimport Accordion from '@material-ui/core/Accordion';\nimport ExpandMoreIcon from '@material-ui/icons/ExpandMore';\nimport VisibilityIcon from '@material-ui/icons/Visibility';\nimport VisibilityOffIcon from '@material-ui/icons/VisibilityOff';\n\nimport LayerOptions from './LayerOptions';\nimport VolumeOptions from './VolumeOptions';\nimport {\n useControllerSectionStyles,\n StyledAccordionDetails,\n StyledAccordionSummary,\n StyledInputLabel,\n OverflowEllipsisGrid,\n} from './styles';\nimport { getMultiSelectionStats } from './utils';\n\nimport { GLOBAL_LABELS } from '../spatial/constants';\nimport { getSourceFromLoader, isRgb } from '../../utils';\nimport { canLoadResolution } from '../utils';\nimport { DOMAINS } from './constants';\n\nfunction TabPanel(props) {\n const {\n children, value, index, ...other\n } = props;\n\n return (\n